language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
|---|---|
C
|
#ifndef NTRU_RAND_H
#define NTRU_RAND_H
#include "types.h"
#ifdef WIN32
/**
* @brief CryptGenRandom-based RNG
*
* Fills an array with random data from CryptGenRandom().
*
* @param rand_data output parameter; the random data is written to this array
* @param len the number of elements to write to rand_data
* @param rand_ctx ignored
* @return 0 for error, 1 otherwise
*/
uint8_t ntru_rand_wincrypt(uint8_t rand_data[], uint16_t len, NtruRandContext *rand_ctx);
#else
/**
* @brief /dev/random-based RNG
*
* Fills an array with random data from /dev/random.
*
* @param rand_data output parameter; the random data is written to this array
* @param len the number of elements to write to rand_data
* @param rand_ctx ignored
* @return 0 for error, 1 otherwise
*/
uint8_t ntru_rand_devrandom(uint8_t rand_data[], uint16_t len, NtruRandContext *rand_ctx);
/**
* @brief /dev/urandom-based RNG
*
* Fills an array with random data from /dev/urandom.
*
* @param rand_data output parameter; the random data is written to this array
* @param len the number of elements to write to rand_data
* @param rand_ctx ignored
* @return 0 for error, 1 otherwise
*/
uint8_t ntru_rand_devurandom(uint8_t rand_data[], uint16_t len, NtruRandContext *rand_ctx);
#endif // WIN32
/**
* @brief default RNG
*
* Fills an array with random data from CryptGenRandom() (on Windows) or
* /dev/urandom (on *nix).
*
* @param rand_data output parameter; the random data is written to this array
* @param len the number of elements to write to rand_data
* @param rand_ctx ignored
* @return 0 for error, 1 otherwise
*/
uint8_t ntru_rand_default(uint8_t rand_data[], uint16_t len, NtruRandContext *rand_ctx);
/**
* @brief deterministic RNG based on IGF-2
*
* Fills an array with random data from ntru_IGF_next()
*
* @param rand_data output parameter; the random data is written to this array
* @param len the number of elements to write to rand_data
* @param rand_ctx pointer to a NtruRandContext struct
* @return 0 for error, 1 otherwise
*/
uint8_t ntru_rand_igf2(uint8_t rand_data[], uint16_t len, NtruRandContext *rand_ctx);
#endif /* NTRU_RAND_H */
|
C
|
/*
* +++ NAME +++
*
* DASIN Double precision arc sine
*
* +++ INDEX +++
*
* DASIN
* machine independent routines
* trigonometric functions
* math libraries
*
* +++ DESCRIPTION +++
*
* Returns double precision arc sine of double precision
* floating point argument.
*
* +++ USAGE +++
*
* double dasin(x)
* double x;
*
* +++ REFERENCES +++
*
* Fortran IV-plus user's guide, Digital Equipment Corp. pp B-2.
*
* +++ RESTRICTIONS +++
*
* For precision information refer to documentation of the floating
* point library primatives called.
*
* +++ PROGRAMMER +++
*
* Fred Fish
* Goodyear Aerospace Corp, Arizona Div.
* (602) 932-7000 work
* (602) 894-6881 home
*
* +++ INTERNALS +++
*
* Computes arcsine(X) from:
*
* (1) If X = 0.0 then DASIN(X) = 0.0
*
* (2) If X = 1.0 then DASIN(X) = PI/2.
*
* (3) If X = -1.0 then DASIN(X) = -PI/2
*
* (4) If -1.0 < X < 1.0 then
* DASIN(X) = DATAN(Y)
* Y = X / DSQRT[1-(X**2)]
*
* ---
*/
/*)LIBRARY
*/
#include <stdio.h>
#include "pmluse.h"
#include "pml.h"
double dasin(x)
double x;
{
double datan(), dsqrt();
if ( x > 1.0 || x < -1.0) {
pmlerr(DASIN_BADARG);
return(0.0);
} else if (x == 0.0)
return (0.0);
else if (x == 1.0)
return (HALFPI);
else if (x == -1.0)
return (-HALFPI);
else
return datan(x / dsqrt(1.0 - x * x));
}
|
C
|
#include<stdio.h>
#include<math.h>
int main (void)
{
double deposit=0.0;
double rate=0;
double interest=0;
double percent=0;
int years=0;
int totalMonths=0;
double balance=0;
printf("Please enter the amount of your savings account deposit: ");
scanf(" %lf",&deposit);
printf("You entered a deposit of $%.2f\n",deposit);
printf("Please enter the interest rate as a percentage %%: ");
scanf(" %lf",&percent);
rate=percent/100;
printf("You entered an interest rate of %.2f%%\n",percent);
printf("It will be calculated as %.4f\n",rate);
printf("Please enter the number of years for this deposit: ");
scanf(" %i",&years);
balance=deposit;
totalMonths=years*12;
interest=rate/12;
balance=deposit* (pow( 1+interest, totalMonths));
printf("After %i number of years, the deposit in the savings account is now $%.2f", years, balance);
return 0;
}
|
C
|
#include <stdio.h>
int main()
{
FILE *zrodlo;
FILE *cel;
if((zrodlo=fopen("zadanie5zrodlo.txt","w"))==NULL) //zrodlo > stworz + napisz tekst > zamknij
{
printf("Blad pliku ZRODLO (W)");
return -1;
}
fprintf(zrodlo,"%s","ciekawe\njak\nduzo\nczasu\nmi\nzostalo");
fclose(zrodlo);
if((cel=fopen("zadanie5cel.txt","w"))==NULL) //OTWORZ, ZAPISZ do cel
{
printf("Blad pliku CEL (W)");
return -1;
}
if((zrodlo=fopen("zadanie5zrodlo.txt","r"))==NULL) //odczyt ZRODLO
{
printf("Blad pliku ZRODLO (r)");
return -1;
}
char ch;
int i;
int rozmiarZ;
fseek(zrodlo,0,SEEK_END);
rozmiarZ=ftell(zrodlo);
rozmiarZ--; // rzeczywista wartosc zrodla ( - '\0' )
printf("rozmiar = %i\n", rozmiarZ);
fseek(zrodlo,0,SEEK_SET);
for(;rozmiarZ>=0;rozmiarZ--)
{
ch=fgetc(zrodlo);
if(feof(zrodlo)) break;
// printf("%c",ch);
fprintf(cel,"%c", ch);
}
fclose(zrodlo);
fclose(cel);
return 0;
}
|
C
|
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
typedef struct TYPE_2__ TYPE_1__ ;
/* Type definitions */
typedef int /*<<< orphan*/ wchar_t ;
struct qstr {unsigned int len; char const* name; } ;
struct nls_table {int (* char2uni ) (char const*,unsigned int,int /*<<< orphan*/ *) ;} ;
struct dentry {int /*<<< orphan*/ d_sb; } ;
struct TYPE_2__ {struct nls_table* local_nls; } ;
/* Variables and functions */
TYPE_1__* CIFS_SB (int /*<<< orphan*/ ) ;
scalar_t__ cifs_toupper (int /*<<< orphan*/ ) ;
int stub1 (char const*,unsigned int,int /*<<< orphan*/ *) ;
int stub2 (char const*,int,int /*<<< orphan*/ *) ;
scalar_t__ unlikely (int) ;
__attribute__((used)) static int cifs_ci_compare(const struct dentry *dentry,
unsigned int len, const char *str, const struct qstr *name)
{
struct nls_table *codepage = CIFS_SB(dentry->d_sb)->local_nls;
wchar_t c1, c2;
int i, l1, l2;
/*
* We make the assumption here that uppercase characters in the local
* codepage are always the same length as their lowercase counterparts.
*
* If that's ever not the case, then this will fail to match it.
*/
if (name->len != len)
return 1;
for (i = 0; i < len; i += l1) {
/* Convert characters in both strings to UTF-16. */
l1 = codepage->char2uni(&str[i], len - i, &c1);
l2 = codepage->char2uni(&name->name[i], name->len - i, &c2);
/*
* If we can't convert either character, just declare it to
* be 1 byte long and compare the original byte.
*/
if (unlikely(l1 < 0 && l2 < 0)) {
if (str[i] != name->name[i])
return 1;
l1 = 1;
continue;
}
/*
* Here, we again ass|u|me that upper/lowercase versions of
* a character are the same length in the local NLS.
*/
if (l1 != l2)
return 1;
/* Now compare uppercase versions of these characters */
if (cifs_toupper(c1) != cifs_toupper(c2))
return 1;
}
return 0;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
typedef struct node *treePointer;
typedef struct node {
char data;
treePointer leftChild, rightChild;
} node;
treePointer createNode(char newData) //ο node
{
treePointer newNode = (treePointer)malloc(sizeof(node));
newNode->leftChild = NULL;
newNode->rightChild = NULL;
newNode->data = newData;
return newNode;
}
void preorder(treePointer ptr) //preorder traversal
{
if (ptr) {
printf("%c", (*ptr).data);
preorder(ptr->leftChild);
preorder(ptr->rightChild);
}
}
int main()
{
char Data;
char relation;
char Child;
while (1) {
printf(">>");
scanf_s("%c%c%c", &Data, &relation, &Child); // data Է ޱ
treePointer nodeData = createNode(Data); // Է¹ data ο root node
if (relation == 'F') { //谡 F(father)
treePointer nodeFather = createNode(Child);
(*nodeData).leftChild = nodeFather;
printf(">>");
preorder(nodeData);
}
if (relation == 'M') { //谡 M(mother)
treePointer nodeMother = createNode(Child);
(*nodeData).rightChild = nodeMother;
printf(">>");
preorder(nodeData);
}
if (relation =='?') { //踦
preorder(nodeData);
if (Child == nodeData->leftChild) { //Է¹ Child preorder traversal ã data ٷ ̸ F
printf(">>F");
}
else(Child == nodeData->rightChild) { //Է¹ Child preorder traversal ã data tree treversal ϴ ù° ̸ M
printf(">>M");
}
}
system("pause");
}
return 0;
}
|
C
|
#include <stdio.h>
int main() {
char n;
printf("\nEnter any character: ");
scanf("%c", &n);
printf("\nascii value of %c = %d\n", n, n);
return 0;
}
|
C
|
#include<stdio.h>
int main()
{
int a,*p;
printf("Enter a value = ");
scanf("%d",&a);
p = &a;
if(*p % 2 == 0)
printf("\neven");
else
printf("\nodd");
}
|
C
|
#include <inttypes.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include "dlfn.h"
#include "float.h"
#include "functor.h"
#include "hash.h"
#include "rdtsc.h"
#include "stats.h"
#define MAX_FUNC 128
static size_t result[MAX_SYMBOLS];
static uint64_t hash_result[MAX_FUNC];
static Functor_t apply_func[MAX_FUNC];
static size_t used_apply_func;
static Functor_t result_func[MAX_FUNC];
static size_t used_result_func;
size_t
increment(size_t *val)
{
*val += 1;
return 1;
}
size_t
left_shift(size_t *val)
{
*val <<= 1;
return 1;
}
size_t
decrement(size_t *val)
{
*val -= 1;
return 1;
}
size_t
copy(const size_t *src, size_t *dst)
{
*dst = *src;
return 1;
}
size_t
print_result(const Symbol_t *sym, size_t r)
{
printf("0x%zX %s 0x%zX 0x%zX 0x%zX\n", r, sym->name, sym->fnctor.param[0].i,
sym->fnctor.param[1].i, sym->fnctor.param[2].i);
return 0;
}
int
tokenize(size_t len, char *input, size_t token_count,
char *token[token_count])
{
char *iter = input;
char *end = input + len;
token[0] = input;
int tc = 1;
for (; iter < end && tc < token_count; ++iter) {
if (*iter == ' ') {
*iter = 0;
token[tc++] = iter + 1;
}
}
return tc;
}
bool
add_apply_func(Functor_t fnctor)
{
if (used_apply_func >= MAX_FUNC)
return false;
apply_func[used_apply_func] = fnctor;
++used_apply_func;
return true;
}
bool
add_result_func(Functor_t fnctor)
{
if (used_result_func >= MAX_FUNC)
return false;
result_func[used_result_func] = fnctor;
++used_result_func;
return true;
}
void
apply_param(const char *pstr, Param_t *p)
{
uint64_t val = strtol(pstr, 0, 0);
if (val) {
printf("pstr %s val %" PRIu64 "\n", pstr, val);
p->i = val;
} else if (pstr[0] == '+') {
printf("pstr %s increment\n", pstr);
Functor_t fnctor = { .call = increment, .param[0].p = &p->i };
add_apply_func(fnctor);
} else if (pstr[0] == '-') {
printf("pstr %s decrement\n", pstr);
Functor_t fnctor = { .call = decrement, .param[0].p = &p->i };
add_apply_func(fnctor);
} else if (pstr[0] == '<') {
printf("pstr %s left_shift\n", pstr);
Functor_t fnctor = { .call = left_shift, .param[0].p = &p->i };
add_apply_func(fnctor);
} else if (pstr[0] == '@') {
const Symbol_t *sym = dlfn_get_symbol(&pstr[1]);
if (sym) {
uint32_t sym_offset = (sym - dlfn_symbols);
Functor_t fnctor = { .call = copy,
.param[0].p = &result[sym_offset],
.param[1].p = &p->i };
add_result_func(fnctor);
printf("pstr result of %s [offset %u]\n", &pstr[1], sym_offset);
} else {
printf("sym not found %s\n", &pstr[1]);
}
} else { // TODO
printf("parameter unhandled %s\n", pstr);
}
}
void
execute_benchmark()
{
Stats_t aggregate;
stats_init(&aggregate);
const int magnitudes = 10;
int calls = 1;
for (int h = 0; h < magnitudes; ++h) {
Stats_t perfStats[MAX_SYMBOLS];
for (int i = 0; i < MAX_SYMBOLS; ++i) {
stats_init(&perfStats[i]);
}
for (int i = 0; i < dlfn_used_symbols; ++i) {
double sum = 0;
for (int j = 0; j < calls; ++j) {
uint64_t startCall = rdtsc();
functor_invoke(dlfn_symbols[i].fnctor);
uint64_t endCall = rdtsc();
double duration = to_double(endCall - startCall);
stats_sample_add(&perfStats[i], duration);
sum += duration;
}
stats_sample_add(&aggregate, sum);
}
printf("--per 10e%d\n", h);
for (int i = 0; i < dlfn_used_symbols; ++i) {
printf("%-20s\t(%5.2e, %5.2e) range\t%5.2e mean ± %4.02f%%\t\n",
dlfn_symbols[i].name, stats_min(&perfStats[i]),
stats_max(&perfStats[i]), stats_mean(&perfStats[i]),
100.0 * stats_rs_dev(&perfStats[i]));
}
puts("");
if (aggregate.max > 10000000.0)
break;
calls *= 10;
}
puts("benchmark threshold reached.");
}
// simulation <until frame>
#define SIMULATION_MAX UINT32_MAX
uint32_t
execute_simulation(size_t len, char *input)
{
const unsigned TOKEN_COUNT = 2;
char *token[TOKEN_COUNT];
int tc = tokenize(len, input, TOKEN_COUNT, token);
if (tc == 1)
return SIMULATION_MAX;
uint64_t val = strtol(token[1], 0, 0);
return val;
}
// apply <fn> <p1> <p2> <p3> <...>
void
execute_apply(size_t len, char *input)
{
const unsigned TOKEN_COUNT = 6;
char *token[TOKEN_COUNT];
int tc = tokenize(len, input, TOKEN_COUNT, token);
if (tc < 2) {
puts("Usage: apply <func> <param1> <param2> <param3>");
return;
}
int matched = 0;
for (int fi = 0; fi < dlfn_used_symbols; ++fi) {
const char *filter =
token[1][0] == '*' ? dlfn_symbols[fi].name : token[1];
if (strcmp(filter, dlfn_symbols[fi].name))
continue;
++matched;
for (int pi = 0; pi < PARAM_COUNT; ++pi) {
int ti = 2 + pi;
if (ti >= tc)
break;
apply_param(token[ti], &dlfn_symbols[fi].fnctor.param[pi]);
}
}
if (!matched) {
printf("Failure to apply: function not found (%s).\n", token[1]);
return;
}
}
void
execute_object(size_t len, char *input)
{
const unsigned TOKEN_COUNT = 2;
char *token[TOKEN_COUNT];
int tc = tokenize(len, input, TOKEN_COUNT, token);
if (tc < 2) {
puts("Usage: object <name>");
return;
}
Object_t *obj = dlfn_get_object(token[1]);
if (!obj->address) {
printf("%s not found.\n", token[1]);
return;
}
if (obj->bytes == 8) {
long *lp = obj->address;
printf("%s: %p long %ld\n", token[1], obj->address, *lp);
} else if (obj->bytes == 4) {
signed *p = obj->address;
printf("%s: %p signed %d\n", token[1], obj->address, *p);
}
}
void
execute_hash(size_t len, char *input)
{
memset(hash_result, 0, sizeof(hash_result));
uint64_t hash_seed = memhash(0, 0);
for (int i = 0; i < dlfn_used_objects; ++i) {
hash_seed =
memhash_cont(hash_seed, dlfn_objects[i].address, dlfn_objects[i].bytes);
hash_result[i] = hash_seed;
printf("Hashval %s: %lu\n", dlfn_objects[i].name, hash_seed);
}
}
|
C
|
#ifndef VARIABLE_H
#define VARIABLE_H
#include "std_lib_facilities.h"
struct Variable
{
string name;
double value;
Variable(string name, double val)
: name{name}, value{val} {}
};
struct Table_variables
{
vector<Variable> variables{};
Table_variables() {}
double define_variable(string variable_name, double variable_value);
double get_value(string variable_name);
void set_value(string variable_name, double new_value);
bool is_defined(string variable_name);
};
#endif
|
C
|
#include <stdio.h>
#include <fcntl.h>
#include <termios.h>
#include <unistd.h>
#include <errno.h>
#include "time_utils.h"
const char* device_name = "/dev/balmerSDIO0";
int main(void)
{
int fd;/*File Descriptor*/
printf("SDIO Port Read\n");
fd = open(device_name,O_RDWR);
if(fd == -1)
printf(" Error! in Opening %s\n", device_name);
else
printf(" %s Opened Successfully\n", device_name);
static uint8_t read_buffer[4096];
int bytes_read = 0;
int i = 0;
//msleep(100);
uint64_t start_usec = TimeUsec();
bytes_read = read(fd, read_buffer, sizeof(read_buffer));
uint64_t end_usec = TimeUsec();
printf(" Delta tume %i usec\n", (int)(end_usec-start_usec));
printf(" Bytes received %d\n", bytes_read);
//for(i=0;i<bytes_read;i++)
// printf("%x,", (int)read_buffer[i]);
printf("\n");
close(fd);
return 0;
}
|
C
|
#include "monitor/watchpoint.h"
#include "monitor/expr.h"
#include<stdlib.h>
#define NR_WP 32
static WP wp_pool[NR_WP] = {};
static WP *head = NULL, *free_ = NULL;
void init_wp_pool() {
int i;
for (i = 0; i < NR_WP; i ++) {
wp_pool[i].NO = i;
wp_pool[i].next = &wp_pool[i + 1];
}
wp_pool[NR_WP - 1].next = NULL;
head = NULL;
free_ = wp_pool;
}
/* TODO: Implement the functionality of watchpoint */
WP* new_wp()
{
if(free_==NULL)
{
printf("Too many watchpoints!!\n");
assert(0);
}
WP* temp=free_;
free_=free_->next;
temp->next=head;
head=temp;
return temp;
}
void free_wp(WP *wp)
{
WP *temp=head;
if(head==wp)
{
head=head->next;
wp->next=free_;
free_=wp;
}
else
{
while(temp->next!=NULL&&temp->next!=wp)temp=temp->next;
if(temp->next==NULL)return;
else if(temp->next==wp)
{
temp->next=wp->next;
wp->next=free_;
free_=wp;
}
}
return;
}
void info_w()
{
WP* temp=head;
printf("Num\tAddress\tExprssion\tValue\n");
while(temp!=NULL)
{
printf("%d\t%u\t%s\t\t%u\n", temp->NO, temp->vaddr, temp->buf, temp->seq_val);
temp=temp->next;
}
}
void wp_d(int Number)
{
WP* temp=head;
while(temp!=NULL&&temp->NO!=Number)temp=temp->next;
if(temp!=NULL)free_wp(temp);
}
void wp_d_all()
{
while(head!=NULL)
{
free_wp(head);
}
}
void wp_new(char *args, uint32_t val)
{
WP* temp=new_wp();
temp->seq_val=val;
temp->ori_val=val;
temp->vaddr=0;
temp->buf[0]='\0';
strcat(temp->buf,args);
}
bool wp_check()
{
bool Flag=false;
bool *Success=malloc(sizeof(bool));
WP* temp=head;
while(temp!=NULL)
{
temp->ori_val=temp->seq_val;
temp->seq_val=expr(temp->buf, Success);
if(temp->ori_val!=temp->seq_val)
{
printf("Watchpoint %d: %s\nOld value: %u\nNew value: %u\n", temp->NO, temp->buf, temp->ori_val, temp->seq_val);
Flag=true;
}
temp=temp->next;
}
return Flag;
}
|
C
|
#include <stdio.h>
#include <string.h>
#include "pass_list.h"
#include "pragma.h"
/******************************************************************************/
/**
* Handles a pragma of 'instrumente' plugin which can be:
* - #pragma instrumente foo
* - #pragma instrumente (fct_0, fct_1, fct_2, ...)
* It stores all functions well indicated in a chain-list structure to be used
* by the pragma_pass.
* @param arg Not used
* @TODO Print a warning if a pragma is not well-defined.
*/
static void
handle_instrument_pragma (
cpp_reader * arg)
{
tree message = 0;
enum cpp_ttype token; // Lexer token
/* Get the lexer token */
token = pragma_lex (&message);
/* If it is an open parenthesis */
if (token == CPP_OPEN_PAREN)
{
/* Get the next token */
token = pragma_lex (&message);
/* Loop for all tokens if they are legal (name or comma) */
while (token == CPP_NAME || token == CPP_COMMA)
{
/* If it is a name, add it to the list */
if (token == CPP_NAME)
{
func_to_inst_list = add_function_to_list (
func_to_inst_list,
IDENTIFIER_POINTER (message),
EXPR_FILENAME (message) );
}
token = pragma_lex (&message);
}
/* If the token is not a close parenthesis */
if (token != CPP_CLOSE_PAREN)
{
printf ("The pragma is not allowed\n");
}
}
/* If it is an only name, add it to the list */
else if (token == CPP_NAME)
{
func_to_inst_list = add_function_to_list (
func_to_inst_list,
IDENTIFIER_POINTER (message),
EXPR_FILENAME (message) );
update_function_list (func_to_inst_list);
}
}
/**
* Registers the pragma usage.
* @param event_data Not used
* @param user_data Not used
*/
void
instrument_pragma (
void * event_data,
void * user_data)
{
c_register_pragma (NULL, "instrument", handle_instrument_pragma);
}
|
C
|
#include "tommath_private.h"
#ifdef S_MP_GET_BIT_C
/* LibTomMath, multiple-precision integer library -- Tom St Denis */
/* SPDX-License-Identifier: Unlicense */
/* Get bit at position b and return true if the bit is 1, false if it is 0 */
bool s_mp_get_bit(const mp_int *a, int b)
{
mp_digit bit;
int limb = b / MP_DIGIT_BIT;
if (limb < 0 || limb >= a->used) {
return false;
}
bit = (mp_digit)1 << (b % MP_DIGIT_BIT);
return ((a->dp[limb] & bit) != 0u);
}
#endif
|
C
|
#include "sort.h"
#include "deck.h"
#include <stdio.h>
/**
* co - function to order some cards
* @c: The deck
*
* Return: int
*/
int co(char c)
{
int idc;
idc = (int)c;
if (c == 'A')
idc = idc - 16;
if (c == '1')
idc = idc + 9;
if (c == 'K')
idc = idc + 10;
return (idc);
}
/**
* sort_deck - function that use the insertion sort
* Description: A function that implements the
* insertion sort algoritm to organize a deck of
* cards.
* @deck: The deck
*
* Return: void
*/
void sort_deck(deck_node_t **deck)
{
deck_node_t *tmp0, *tmp1;
if (deck == NULL || *deck == NULL)
return;
for (tmp0 = *deck; tmp0 != NULL; tmp0 = tmp0->next)
{
while (tmp0->prev != NULL &&
co(tmp0->card->value[0]) <
co(tmp0->prev->card->value[0]))
{
tmp0->prev->next = tmp0->next;
if (tmp0->next != NULL)
tmp0->next->prev = tmp0->prev;
tmp0->next = tmp0->prev;
tmp0->prev = tmp0->next->prev;
tmp0->next->prev = tmp0;
if (tmp0->prev == NULL)
*deck = tmp0;
else
tmp0->prev->next = tmp0;
}
}
for (tmp1 = *deck; tmp1 != NULL; tmp1 = tmp1->next)
{
while (tmp1->prev != NULL &&
tmp1->card->kind <
tmp1->prev->card->kind)
{
tmp1->prev->next = tmp1->next;
if (tmp1->next != NULL)
tmp1->next->prev = tmp1->prev;
tmp1->next = tmp1->prev;
tmp1->prev = tmp1->next->prev;
tmp1->next->prev = tmp1;
if (tmp1->prev == NULL)
*deck = tmp1;
else
tmp1->prev->next = tmp1;
}
}
}
|
C
|
/*
* App utility functions:
*
* Platform: Neutral
*
* Version: 3.35 2002/12/23 First release.
* Version: 3.36 2002/12/30 Fixed crash if key does not exist.
* Version: 3.41 2003/03/18 Fixed a typo.
* Version: 3.43 2003/04/25 Now deletes all cursors when deinitialised.
* Version: 3.50 2004/01/11 Uses const keyword for some param strings.
* Version: 3.56 2005/08/09 Silenced some size_t conversion warnings.
*/
/* Copyright (c) L. Patrick
This file is part of the App cross-platform programming package.
You may redistribute it and/or modify it under the terms of the
App Software License. See the file LICENSE.TXT for details.
*/
#include "apputils.h"
/*
* Complete initialising the App structure.
*/
void app_app_initialise(App *app)
{
app->string_table = app_new_string_table();
app_set_string(app, "Yes", "Yes");
app_set_string(app, "No", "No");
app_set_string(app, "Cancel", "Cancel");
app_set_string(app, "OK", "OK");
app_set_string(app, "Quit", "Quit");
app_set_string(app, "Create", "Create");
app_set_string(app, "Overwrite","Overwrite");
app_set_string(app, "Error", "Error");
app_set_string(app, "File:", "File:");
app_set_string(app, "Files:", "Files:");
app_set_string(app, "Path:", "Path:");
app_set_string(app, "Folder:", "Folder:");
app_set_string(app, "Folders:", "Folders:");
app_set_string(app, "Create File", "Create File");
app_set_string(app, "Error: Create File", "Error: Create File");
app_set_string(app, "Create file?",
"That file does not exist. Create the file?");
app_set_string(app, "Already a folder!",
"That file name is already in use as a folder.");
app_set_string(app, "Overwrite File", "Overwrite File");
app_set_string(app, "Error: Save File", "Error: Save File");
app_set_string(app, "Overwrite file?",
"That file already exists. Overwrite the file?");
}
/*
* Delete whatever was initialised above, and whatever can be
* portably deleted.
*/
void app_app_deinitialise(App *app)
{
int i;
app_hide_all_windows(app);
app_del_all_windows(app);
for (i = app->num_cursors - 1; i >= 0; i--)
app_del_cursor(app->cursors[i]);
for (i = app->num_fonts - 1; i >= 0; i--)
app_del_font(app->fonts[i]);
while (app->num_timers)
app_del_timer(app->timers[0]);
app_free(app->program_name);
app_free(app->open_folder);
app_free(app->save_folder);
app_del_string_table(app->string_table);
app->string_table = NULL;
}
/*
* We just define two functions here, for using strings
* stored with the App structure. These functions are used
* by the dialogs, amongst others, to find the appropriate
* string to display.
*/
void app_set_string(App *app, const char *key, char *value)
{
StringNode *n;
n = app_insert_node(app->string_table, key, (int) strlen(key));
n->value = value;
}
char * app_get_string(App *app, const char *key)
{
StringNode *n;
n = app_locate_node(app->string_table, key, (int) strlen(key));
if (n == NULL)
return NULL;
return n->value;
}
|
C
|
// Assuming you have been able to compile, run and understand the Hello World program
// we will now introduce some of the basic features of the C++ language
//***************************************************
// Conor Henderson, Univ of Alabama, August 2011
//***************************************************
#include <iostream>
using namespace std;
// again we need a 'main' program
int main()
{
// the basic data types for numbers in C++ are integers, and doubles (or floats)
int A = 2;
// this statement creates a variable A of type integer, and assigns it the value of 2
// for non-integer numbers, we use the type 'double'
double B = 3.1415927;
// you could also use a float, but a double is better and the standard these days
// (the difference is related to how much internal memory the computer uses to store the number - doubles use twice as much as floats, which is why they're better
// there are also variables which can be true or false
// we represent these by 'booleans'
// true=1 and false=0
bool C = true;
// here is a single character
char D = 'D';
// we will see how to represent 'strings' of characters later...
// let's check these assignments by printing the values of the variables to the screen for display
cout << "A = " << A <<endl;
cout << "B = " << B <<endl;
cout << "C = " << C <<endl;
cout << "D = " << D <<endl;
// now for some operations
// let's say we want to add 4 to the value of variable A
// and store it in a new variable
// then we would do
int E = A+4;
//lets check that worked:
cout << "E = " << E <<endl;
// we can do other operations as well
// this time we'll just print them, but not bother to save them
// to new variables ...
cout << "A minus 10 = " << A-10 <<endl;
cout << "A multipled by 10 = " << A*10 <<endl;
cout << "A divided by 2 = " << A/2 <<endl;
// note that none of these operations changed the value of A itself
// if we wanted to do that, we could do:
A = A+2;
// now let's see what value A has:
cout << "Now A = " <<A <<endl;
// we often find that we want to increase the value of an integer
// by one unit, eg if we are using it as a counter
// we could do this by: A=A+1
// but since we use this often, C++ provides a shortcut:
A++;
// this literally means A=A+1, but its shorter
// let's check the value:
cout << "After A++, A = " << A <<endl;
// there is an equivalent if we want to decrease by one: A--;
// see how we were able to change the value of A?
// well, now look at variable B above
// its value is (pretty close to) pi
// but we could change that value easily, eg by B = B+1
// but if we were trying to really use it to represent pi
// then we would not want to be able to change the value at all, in case we sometimes did it by accident ...
// so instead, we can create a variable with a CONSTANT value
// we can do this by:
const double pi = 3.1415927;
// now we can use this in normal expressions, such as
cout << "Pi + 1 =" << pi+1 <<endl;
// but if we were to try to change the value, the compiler would generate an error
// you can see that yourself by editing this program and uncommenting the line below
// pi = pi+1;
// you should see the compiler give you an error like:
// error: assignment of read-only variable `pi'
// and the program will fail to compile
// failing to compile is how the computer tries to help you make sure you dont accidentally run broken programs that might do bad things.
// if you see errors when you go to compile the program, then you need to fix them
// an output program will not be generated if the compiler finds errors in the source code
// to correct the above error, just comment out the line again, and recompile
//now that we've seen the basic data types and arithmetical operations,
// let's look at the basic control functions: if/else, for, etc...
// often in a program, we will want to do one thing under some conditions
// and a different thing under other conditions
// we can accomplish this by if/else statements
// an if statement basically works like:
// if (some condition) { do a bunch of stuff }
// here's an example
if(A==5) {
cout <<" We have just checked if A equals 5" <<endl;
cout << "And if it is, we will double it" <<endl;
A = A*2;
}
// note that the condition we check for is inside ()
// if this is true, we execute all the code that is contained inside the curly brackets {}
// if the condition is not true, we do not execute that code, and we move on through the program
// also note that we use '==' to check if A equals 5
// == is different from just =
// a single = means an *assignment operation*
// if we wrote if(A=5) then we would actually *assign* the value 5 to A
// thats not what we want
// so to check what the value of A is, we need to use ==
// (it's a common beginner mistake to write = when you mean == ...)
// if we want to check for more than one condition at a time, we can use if/else if / else statements
if(A==9) {
cout << "We have checked that A ==9" <<endl;
cout << "Now we add 3 to it" <<endl;
A = A+3;
}
else if(A==10) {
cout << "We have checked that A ==10" <<endl;
cout << "Now we add 7 to it" <<endl;
A = A+7;
}
else {
// if none of the above are true, then we default to else
// i.e. in every other case....
cout << "We have checked that A is not 9 or 10 ..." <<endl;
cout << "This time we won't change it" <<endl;
}
// depending on what condition was chosen, we can see what the value of A is now
cout << "After that choice, the value of A is now: A = " << A << endl;
// the other common control structures are loops
// there are both for-loops and while-loops in C++
for(int i=0;i<10;i++) {
// this is a very common loop example
// we create a counter i
// each time through the loop, we increment i by one (i++)
// we continue this loop as long as it is true that i<10
// i.e. we do the loop ten times, then stop and move on
//each time through the loop, let's add one to our variable A
A++;
}
// now we can see what the value of A is after this loop:
cout << "After the for loop, A = " << A <<endl;
//there is also a while loop
// and sometimes you can use statements like break or continue
// to modify control flow in programs
// you can look all these up at
// http://www.cplusplus.com/doc/tutorial/control/
// note that technically C++ has a goto function like in classic BASIC programs
// but these days, we basically never use goto in real programs...
// and we're done for this exercise, so we return:
return 0;
}
|
C
|
#ifndef FNV_H
#define FNV_H
#include <stdlib.h>
#include <stdio.h>
typedef unsigned long long u64;
#define FNVP64 ((u64)0x00000100000001b3)
#define FNVO64 ((u64)0xcbf29ce484222325)
u64 fnv64c(u64 input) {
unsigned int i;
u64 hash = FNVO64;
for(i = 0; i < 8; i++) {
hash ^= input & 0xff;
hash *= FNVP64;
input >>= 8;
}
return hash;
}
extern u64 fnv64(u64 input);
int main() {
u64 i;
for(i = 0; i < 1000; i++) {
u64 code = fnv64c(i);
u64 ass = fnv64(i);
if(code != ass) {
printf("code %#.16llx != assembly %#.16llx for input %#.16llx\n",
code, ass, i);
}
}
return 0;
}
#endif
|
C
|
/*
Authors: Jani Heinikoski, Vili Huusko
Last modified (date): 22.04.2021
Sources:
*/
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
FILE* open_file(char* file_name) {
FILE* f = fopen(file_name, "rb");
if (!f) {
fprintf(stderr, "my-zip: couldn't open file\n");
exit(1);
}
return f;
}
void unzip(char* file_name) {
FILE* fptr = open_file(file_name);
uint32_t repeated_count;
uint8_t ascii;
size_t read_count;
int i;
/* fread guaranteed to return zero in case of error or EOF in this case because nmemb is exactly one */
/* otherwise always returns 1. In other cases use while (fread != nmemb). */
while ((read_count = fread(&repeated_count, 4, 1, fptr))) {
read_count = fread(&ascii, 1, 1, fptr);
if (!read_count) break;
for (i = 0; i < repeated_count; i++) {
fprintf(stdout, "%c", ascii);
}
}
if (ferror(fptr) != 0) {
perror("my-unzip");
exit(1);
}
fclose(fptr);
}
int main (int argc, char** argv) {
if (argc < 2) {
fprintf(stderr, "my-unzip: file1 [file2 ...]\n");
exit(1);
}
/* Loop the file names */
for (argv++; *argv != NULL; argv++) {
unzip(*argv);
}
return 0;
}
|
C
|
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
/* Type definitions */
typedef int /*<<< orphan*/ FILE ;
/* Variables and functions */
int /*<<< orphan*/ SIGALRM ;
scalar_t__ SIG_IGN ;
int /*<<< orphan*/ _PATH_TTY ;
int /*<<< orphan*/ alarm (int /*<<< orphan*/ ) ;
int /*<<< orphan*/ alarmcatch (int /*<<< orphan*/ ) ;
char const* attnmessage ;
int /*<<< orphan*/ clearerr (int /*<<< orphan*/ *) ;
int /*<<< orphan*/ errno ;
int /*<<< orphan*/ fclose (int /*<<< orphan*/ *) ;
int /*<<< orphan*/ * fgets (char*,int,int /*<<< orphan*/ *) ;
int /*<<< orphan*/ * fopen (int /*<<< orphan*/ ,char*) ;
int /*<<< orphan*/ fprintf (int /*<<< orphan*/ ,char*,...) ;
int /*<<< orphan*/ quit (char*,...) ;
scalar_t__ sig ;
scalar_t__ signal (int /*<<< orphan*/ ,scalar_t__) ;
int /*<<< orphan*/ stderr ;
int /*<<< orphan*/ strerror (int /*<<< orphan*/ ) ;
scalar_t__ timeout ;
int
query(const char *question)
{
char replybuffer[64];
int back, errcount;
FILE *mytty;
if ((mytty = fopen(_PATH_TTY, "r")) == NULL)
quit("fopen on %s fails: %s\n", _PATH_TTY, strerror(errno));
attnmessage = question;
timeout = 0;
alarmcatch(0);
back = -1;
errcount = 0;
do {
if (fgets(replybuffer, 63, mytty) == NULL) {
clearerr(mytty);
if (++errcount > 30) /* XXX ugly */
quit("excessive operator query failures\n");
} else if (replybuffer[0] == 'y' || replybuffer[0] == 'Y') {
back = 1;
} else if (replybuffer[0] == 'n' || replybuffer[0] == 'N') {
back = 0;
} else {
(void) fprintf(stderr,
" DUMP: \"Yes\" or \"No\"?\n");
(void) fprintf(stderr,
" DUMP: %s: (\"yes\" or \"no\") ", question);
}
} while (back < 0);
/*
* Turn off the alarm, and reset the signal to trap out..
*/
(void) alarm(0);
if (signal(SIGALRM, sig) == SIG_IGN)
signal(SIGALRM, SIG_IGN);
(void) fclose(mytty);
return(back);
}
|
C
|
#include "OMminimum.h"
#include "OMerrordef.h"
#include "PWminimum.h"
#include "PWerror.h"
#include "PWapi/clsid.h"
/*
ABSTRACT
This function outputs the active classid given the objid and it's
object space number. If the objid is invalid, PW_K_NullClass is returned.
*/
PWclassid omClassidFromObjid
(
PWobjid objid,
PWosnum osnum
)
{
PWclassid classid=PW_K_NullClass;
som_get_classid (osnum, (char *) NULL, objid, (OM_p_OBJECTHDR) NULL,
&classid);
return (classid);
}
/*
ABSTRACT
This function finds the classname given the classid of an object. The
object space in which this classname is defined is also input.
The size of the string to hold the classname must be PW_K_MaxStringLen long.
If successful, the pointer to the input string that contains the classname
will be returned. On failure, a NULL pointer is returned.
*/
char *omClassNameFromClassid
(
PWclassid classid,
PWosnum osnum,
char *classname
)
{
PWresult result=PW_K_Success;
result = som_get_classname (osnum, classid, NULL_OBJID,
(OM_p_OBJECTHDR) NULL, classname);
if (IsError (result))
return (char *) NULL;
else
return classname;
}
/*
ABSTRACT
This function returns the active classid given the classname and the
relevant object space. If the classname is invalid, PW_K_NullClass is
returned.
*/
PWclassid omClassidFromName
(
char *classname,
PWosnum osnum
)
{
PWclassid classid=PW_K_NullClass;
som_get_classid (osnum, classname, NULL_OBJID, (OM_p_OBJECTHDR) NULL,
&classid);
return (classid);
}
/*
ABSTRACT
Tests whether or not a super class is in the ancestry of a subclass. The
inputs are the classids of the super class and the subclass. If the subclass
is in the ancestry, this function will return TRUE. If not (or if the
classids are invalid), this function will return FALSE.
*/
PWboolean omIsAncestryValid
(
PWclassid subclassid,
PWclassid superclassid
)
{
return (som_is_ancestry_valid (subclassid, superclassid,
(char *) NULL, (char *) NULL) == OM_S_SUCCESS);
}
|
C
|
/*****************************************
* File Name : main.C
* Purpose :
* Creation Date : 23-10-2014 20-12-2008
* Last Modified : Tue 04 Nov 2014 04:02:15 PM CET
* Created By : Mihai Constantin constant.mihai@googlemail.com
******************************************/
/*
*http://stackoverflow.com/questions/57483/what-are-the-differences-between-a-pointer-variable-and-a-reference-variable-in
* Just messing around with references.
*/
#include <cassert>
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
using namespace std;
/*
* A pointer can be reassigned
*/
void pointer_reasignment()
{
int x = 5;
int y = 6;
int *p;
p = &x;
p = &y;
*p = 10;
assert(x == 5);
assert(y == 10);
}
/*
* A refference cannot be reassigned
* Must be assigned at init.
*/
void reference_initialization()
{
int x = 5;
int &r = x;
assert(r == 5);
}
/*
* TODO read standard for qoute here
*/
void memory_addresses()
{
int x = 0;
int &r = x;
int *p = &x;
int *p2 = &r;
assert(p == p2);
}
void indirection_level()
{
int x = 0;
int y = 0;
int *p = &x;
int *q = &y;
int **pp = &p;
pp = &q;//*pp = q
**pp = 4;
assert(y == 4);
assert(x == 0);
}
void null_assignment()
{
int *p = NULL;
// int &r = NULL; <--- compiling error
(void)p;
}
void pointer_arithmetic()
{
int a[3] = {1, 2, 3};
int &r = *a;
assert(&r == a);
assert(r == 1);
assert(*(a+1) == 2);
assert((&r)+1 /*Hop 4 bytes further. as in: over the value at a+0*/ == a+1);
}
void dereferencing()
{
int n = 3;
int &r = n;
int *p = &n;
assert(*p == r);
}
void pointer_array()
{
int a[3] = {1, 2, 3};
int *p1 = a+0, *p2 = a+1, *p3 = a+2;
int &r1 = *(a+0), &r2 = *(a+1), &r3 = *(a+2);
int *ap[3] = {p1, p2, p3};
int *ar[3] = {&r1, &r2, &r3};
for (int i=0;i<3;i++) assert(*(ap[i]) == a[i]);
for (int i=0;i<3;i++) assert(ar[i] == &(a[i]));
}
void tmp_dereferencing()
{
const int &x = int(12); //legal C++
// int *y = &int(12); //illegal to dereference a temporary.
(void)x;
}
/* Printing a constant string */
void print(const string& s)
{
cout << s << "\n";
}
int main(int argc, char** argv)
{
string s("const_string");
print(s);
char buf[50];
sprintf(buf,"%ld", 0);
printf("buf len %d\n",strlen(buf));
pointer_reasignment();
reference_initialization();
memory_addresses();
indirection_level();
null_assignment();
pointer_arithmetic();
dereferencing();
pointer_array();
tmp_dereferencing();
return 1;
}
|
C
|
/*
* DIO.c
*
* Created: 09/09/2018 10:21:18 PM
* Author: Ramy Badr
*/
#include "DIO.h"
//////////////////////////////////////////////////////////////////////////////////
// Port Direction
//////////////////////////////////////////////////////////////////////////////////
U8 DIO_PortDir(U8 portBase, U8 dir){
U8 changed_pins = 0 ;
if(IS_DIR(dir)&&IS_PORT(portBase)){
DDR(portBase) = (dir==INPUT) ? 0x00 : 0xff ;
changed_pins = 0x08;
}
return changed_pins;
}
U8 DIO_PinDir(U8 portBase, U8 pin, U8 dir){
U8 changed_pins = 0;
if (IS_DIR(dir)&&IS_PORT(portBase)&&IS_PIN(pin)){
if (dir==INPUT){
CLR_BIT(DDR(portBase),pin);
changed_pins = 1;
}else{
SET_BIT(DDR(portBase),pin);
changed_pins = 0x01;
}
}
return changed_pins;
}
U8 DIO_PortRangeDir(U8 portBase, U8 startPin, U8 endPin, U8 dir){
U8 changed_pins = 0 , i ;
if(IS_PIN(startPin)&&IS_PIN(endPin)&&
IS_PORT(portBase)&&IS_DIR(dir)){
if (startPin > endPin){
startPin += endPin;
endPin = startPin - endPin ;
startPin -= endPin ;
}
if(dir==INPUT){
for (i=startPin;i<=endPin;i++){
CLR_BIT(DDR(portBase),i);
changed_pins++ ;
}
}else{
for (i=startPin;i<=endPin;i++){
SET_BIT(DDR(portBase),i);
changed_pins ++;
}
}
}
return changed_pins;
}
U8 DIO_PortMaskDir(U8 portBase, U8 mask, U8 pinsDir){
U8 changedPins = 0, pin;
if(IS_PORT(portBase)&&mask>0){
//using logic:
//DDR(portBase) = ((mask&pinsDir)|(~(mask)&DDR(portBase)));
//return 0x8 ;
//using loop:
for( pin= 0 ; pin< 8 ; pin++ ) {
if(READ_BIT(mask,pin)){
if(READ_BIT(pinsDir,pin)) {
SET_BIT(DDR(portBase),pin) ;
changedPins++ ;
}
else{
CLR_BIT(DDR(portBase),pin) ;
changedPins++ ;
}
}
}
}
return changedPins;
}
//////////////////////////////////////////////////////////////////////////////////
// Writing to Port
//////////////////////////////////////////////////////////////////////////////////
U8 DIO_PortWrite(U8 portBase, U8 val ){
U8 changed_pins = 0 ;
if(IS_PORT(portBase)&&val<=0xff){
PORT(portBase) = val ;
changed_pins = 0x08;
}
return changed_pins;
}
U8 DIO_PinWrite(U8 portBase, U8 pin, U8 val){
U8 changed_pins = 0;
if(IS_PORT(portBase)&&IS_PIN(pin)&&(val==0||val==1)){
if(val==1){
SET_BIT(PORT(portBase),pin);
changed_pins++;
}else{
CLR_BIT(PORT(portBase),pin);
changed_pins++;
}
}
return changed_pins;
}
U8 DIO_PortRangeWrite(U8 portBase, U8 startPin, U8 endPin, U8 val){
U8 changed_pins = 0 , i , shift_val = 0x01;
if(IS_PIN(startPin)&&IS_PIN(endPin)&&
IS_PORT(portBase)){
if (startPin > endPin){
startPin += endPin;
endPin = startPin - endPin ;
startPin -= endPin ;
}
for (i=startPin;i<=endPin;i++,shift_val<<=1){
if(val&shift_val){
SET_BIT(PORT(portBase),i);
}else{
CLR_BIT(PORT(portBase),i);
}
changed_pins++ ;
}
}
return changed_pins;
}
U8 DIO_PortMaskWrite(U8 portBase, U8 mask, U8 val){
U8 changedPins = 0, pin;
if(IS_PORT(portBase)&&mask>=0){
//using logic:
//
//
//using loop:
for( pin= 0 ; pin< 8 ; pin++ ) {
if(READ_BIT(mask,pin)){
if(READ_BIT(val,pin)) {
SET_BIT(PORT(portBase),pin) ;
changedPins++ ;
}
else {
CLR_BIT(PORT(portBase),pin) ;
changedPins++ ;
}
}
}
}
return changedPins;
}
//////////////////////////////////////////////////////////////////////////////////
// Reading Port value
//////////////////////////////////////////////////////////////////////////////////
U8 DIO_PortRead(U8 portBase, U8 *portVal ){
U8 changed_pins = 0 ;
if(IS_PORT(portBase)){
*portVal = PIN(portBase);
changed_pins = 0x08;
}
return changed_pins;
}
U8 DIO_PinRead(U8 portBase, U8 pin, U8 *pinVal){
U8 changed_pin = 0 ;
if(IS_PORT(portBase)&&IS_PIN(pin)){
*pinVal = READ_BIT(PIN(portBase),pin);
changed_pin =1;
}
return pinVal ;
}
U8 DIO_PortRangeRead(U8 portBase, U8 startPin, U8 endPin, U8 *rangeReadVal){
int changed_pins =0 , i ;
if(IS_PORT(portBase)&&IS_PIN(startPin)&&IS_PIN(endPin)){
if (startPin > endPin){
startPin += endPin;
endPin = startPin - endPin ;
startPin -= endPin ;
}
*rangeReadVal = 0x00;
for(i=startPin;i<=endPin;i++){
*rangeReadVal|= PIN(portBase)&(1<<i) ;
changed_pins++;
}
(*rangeReadVal)>>=startPin;
}
return changed_pins ;
}
U8 DIO_PortMaskRead(U8 portBase, U8 mask, U8 *binaryIndividuals_readVal){
U8 changedPins= 0, pin ;
if( IS_PORT(portBase) && mask > 0x00 ) {
*binaryIndividuals_readVal= 0x00;
for( pin= 0 ; pin< 8 ; pin++ ) {
if( READ_BIT(mask,pin) ) {
*binaryIndividuals_readVal|= PIN(portBase)&(1<<pin) ;
changedPins++ ;
}
}
}
return changedPins;
}
//////////////////////////////////////////////////////////////////////////////////
// Toggle Port Value
//////////////////////////////////////////////////////////////////////////////////
U8 DIO_PortToggle(U8 portBase){
U8 changed_pins = 0 ;
if(IS_PORT(portBase)){
PORT(portBase) ^= 0xff ;
changed_pins = 0x08;
}
return changed_pins;
}
U8 DIO_PinToggle(U8 portBase, U8 pin){
U8 changed_pins = 0;
if(changed_pins = IS_PORT(portBase)&&IS_PIN(pin)){
TOGGLE_BIT(PORT(portBase),pin);
}
return changed_pins;
}
U8 DIO_PortRangeToggle(U8 portBase, U8 startPin, U8 endPin){
U8 changed_pins = 0 , i ;
if(IS_PIN(startPin)&&IS_PIN(endPin)&&
IS_PORT(portBase)){
if (startPin > endPin){
startPin += endPin;
endPin = startPin - endPin ;
startPin -= endPin ;
}
for (i=startPin;i<=endPin;i++){
TOGGLE_BIT(PORT(portBase),i);
changed_pins++ ;
}
}
return changed_pins;
}
U8 DIO_PortMaskToggle(U8 portBase, U8 mask){
U8 changedPins= 0, pin ;
if(IS_PORT(portBase)&& mask> 0x00 ) {
for( pin= 0 ; pin< 8 ; pin++ ) {
if( READ_BIT(mask,pin) ) {
TOGGLE_BIT(PORT(portBase),pin) ;
changedPins++ ;
}
}
}
return changedPins;
}
|
C
|
/**
* History:
* ================================================================
* 2017-5-2 qing.zou created
*
*/
#ifndef VPK_QUEUES_H
#define VPK_QUEUES_H
#include "vpk_typedef.h"
TIMA_BEGIN_DELS
struct vpk_tqueue;
typedef struct vpk_tqueue vpk_tqueue;
/**
* Initializes a TQueue object.
*
* @param queue The TQueue object.
* @param s_size The data size of 'structure'.
* @param nr The max number of TQueue's element.
*
* @return NULL: error.
*/
VPKAPI vpk_tqueue* vpk_tqueue_create(int s_size, int nr);
/**
* Write data to TQueue.
*
* @param queue The TQueue object.
* @param data The target data to write.
*
* @return -1: error; 0: successful.
*/
VPKAPI int vpk_tqueue_write(vpk_tqueue *queue, void *data);
/**
* Read data from TQueue.
*
* @queue The TQueue object.
* @data Read data to this pointer.
* @timout > 0:
* = 0:
* < 0:
*
* @return -1: error; 0: successful.
*/
VPKAPI int vpk_tqueue_read(vpk_tqueue *queue, void *data, int timout);
/**
* Destroy the TQueue.
*
* @queue The TQueue object.
*
*/
VPKAPI void vpk_tqueue_destroy(vpk_tqueue *queue);
#if 0
/** message queue by use of 'system call' **/
struct vpk_mqueue;
typedef struct vpk_mqueue vpk_mqueue;
/**
* Initializes a message queue object.
*
* @param fname The .
* @param id The msg queue...
* @param s_size The ....
*
* @return NULL: error.
*/
vpk_mqueue* vpk_mqueue_create(const char* fname, int id, int s_size);
int vpk_mqueue_send(vpk_mqueue *msg_queue, void *data);
int vpk_mqueue_recv(vpk_mqueue *msg_queue, void *data, int msgflg);
void vpk_mqueue_destroy(vpk_mqueue *msg_queue);
#endif
TIMA_END_DELS
#endif //VPK_QUEUES_H
|
C
|
#include <stdio.h>
#include <string.h>
#include <dlfcn.h>
__attribute__((constructor())) void do_pre() {
printf("main constructor\n");
}
int main(int argc, char **argv)
{
void (*print)();
int (*add)(int, int);
void *handle;
printf("i am in\n");
if (argc < 2)
return -1;
handle = dlopen(argv[1], RTLD_LAZY);
if (!handle) {
printf("dlopen failed: %s\n", dlerror());
return -1;
}
print = dlsym(handle, "print");
if (!print) {
printf("dlsym failed: %s\n", dlerror());
return -1;
}
print();
add = dlsym(handle, "add");
if (!add) {
printf("dlsym failed: %s\n", dlerror());
return -1;
}
add(1, 2);
dlclose(handle);
return 0;
}
|
C
|
//
// affichage.c
// Vocabulle 2.0
//
// Created by Lulu on 13/07/2018.
// Copyright © 2018 Lulu. All rights reserved.
//
#include "affichage.h"
void premierMessage(void)
{
char *V [HAUTEUR_LETTRE] =
{
"* * ",
" * * ",
" * * ",
" * * ",
" * "
};
char *O [HAUTEUR_LETTRE] =
{
" ***** ",
"* * ",
"* * ",
"* * ",
" ***** "
};
char *C [HAUTEUR_LETTRE] =
{
" ***** ",
"* ",
"* ",
"* ",
" ***** "
};
char *A [HAUTEUR_LETTRE] =
{
" * ",
" * * ",
" ***** ",
" * * ",
"* * "
};
char *B [HAUTEUR_LETTRE] =
{
"*** ",
"* * ",
"**** ",
"* * ",
"**** "
};
char *U [HAUTEUR_LETTRE] =
{
"* * ",
"* * ",
"* * ",
"* * ",
" **** "
};
char *L [HAUTEUR_LETTRE] =
{
"* ",
"* ",
"* ",
"* ",
"***** "
};
char *E [HAUTEUR_LETTRE] =
{
"***** ",
"* ",
"*** ",
"* ",
"***** ",
};
for (int i = 0 ; i < HAUTEUR_LETTRE ; i++)
{
printf("\n%s %s %s %s %s %s %s %s %s", V[i], O[i], C[i], A[i], B[i], U[i], L[i], L[i], E[i]);
}
printf("\n\n");
}
char MenuPrincipal()
{
char menu;
do {
printf("\nMenu principal: \n-> e : Entrer des mots \n-> a : Apprendre des mots \n-> v : Voir les mots\n-> s : Supprimer un mot\n-> q : Quitter\n");
menu = getchar();
while (getchar() != '\n');
} while (menu != 'e' && menu != 'a' && menu != 'v' && menu != 's' && menu != 'q');
return menu;
}
void PresentationEntrer (void)
{
printf("\nENTRER : \nEntrez un nouveau mot de vocabulaire avec le symbole << & >> entre deux synonymes, le symbole << > >> entre deux mots de la même famille, le symbole << = >> entre le mot francais et sa traduction et le mot francais en premier.\nEnrez le symbole << ! >> pour arreter.\n");
}
void EntrerMot(char mot[])
{
printf("\nNouveau mot:\n");
fgets(mot, TAILLEMOT, stdin);
}
void presentationApprendre(void)
{
printf("\nAPPRENDRE : \nQuand un mot français est affiché, entrez n'importe quel caractère pour afficher sa traduction.\nEnsuite, entrez :\n-> o : oui, si vous connaissiez la traduction\n-> n : non, si vous ne connaissiez pas la traduction\n-> q : quitter, pour retourner au menu principal\n");
}
void afficherMot (char mot[])
{
int i;
printf("\n|");
for (i = 0 ; LETTRE != '=' ; i++) {
if (LETTRE == '&')
printf("\n|");
else printf("%c", LETTRE);
}
getchar();
while (getchar() != '\n');
for (; LETTRE != '\n' ; i++) {
if (LETTRE == '&' || LETTRE == '=')
printf("\n|");
else
printf("%c", LETTRE);
}
printf("\n");
}
char menuApprendre(void)
{
char c;
do
{
c = getchar();
while (getchar() != '\n');
} while (c != 'o' && c != 'n' && 'c' != 'q');
return c;
}
int menuVoir(void)
{
char choix;
do {
printf("Choisissez quelle classe afficher.\nMenu Voir:\n-> 1 : Classe 1\n-> 2 : Classe 2\n-> 3 : Classe 3\n-> 4 : Classe 4\n-> 5 : Classe 5\n-> 6 : Classe 6\n-> 7 : Classe 7\n-> t : Toutes les classes\n");
choix = getchar();
while (getchar() != '\n');
} while (choix != '1' && choix != '2' && choix != '3' && choix != '4' && choix != '5' && choix != '6' && choix != '7' && choix != 't');
switch (choix)
{
case '1':
return 0;
break;
case '2':
return 1;
break;
case '3':
return 2;
break;
case '4':
return 3;
break;
case '5':
return 4;
break;
case '6':
return 5;
break;
case '7':
return 6;
break;
case 't':
return 666;
break;
default:
return (-1);
break;
}
}
void afficherClasse(FILE* classe)
{
char ligne[TAILLEMOT] = "";
char *mot = NULL;
int i = 1;
long curseur = ftell(classe);
fseek(classe, 0, SEEK_SET);
printf("\n");
while (fgets(ligne, TAILLEMOT, classe)) {
strtol(ligne, &mot, 0);
printf("%d.%s", i, mot);
i++;
}
printf("\n");
fseek(classe, curseur, SEEK_SET);
}
void menuSupprimer(int* classe, int* ligne, FILE** tableauFichier)
{
int numClasse = 0;
int numLigne = 0;
*classe = 0;
*ligne = 0;
while (numClasse == 0 || numClasse > NOMBRECLASSES)
{
printf("Entrez le numéro de classe du mot à supprimer : ");
scanf("%d", &numClasse);
while(getchar() != '\n');
}
numClasse--;
*classe = numClasse;
afficherClasse(tableauFichier[numClasse]);
while (numLigne <= 0)
{
printf("Entrez le numéro du mot à supprimer : ");
scanf("%d", &numLigne);
while(getchar() != '\n');
}
*ligne = numLigne;
}
long afficherLigne(FILE* classe, int ligne)
{
char lecture[TAILLEMOT] = "";
char *mot = NULL;
fseek(classe, 0, SEEK_SET);
for (int i = 0 ; i < ligne ; i++) {
curDebutLigne = ftell(classe);
fgets(lecture, TAILLEMOT, classe);
}
strtol(lecture, &mot, 0);
printf("%s", mot);
return curDebutLigne;
}
char menuValiderSuppression(void)
{
char choix = ' ';
do {
printf("\nConfirmez vous la suppression de ce mot?\n-> o : oui\n-> n : non\n");
choix = getc(stdin);
while (getchar() != '\n');
} while (choix != 'o' && choix != 'n');
return choix;
}
|
C
|
//======================================================================
// e01_aux.c / JAS
// To be executed with e01.c
//----------------------------------------------------------------------
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
int i, n;
n = atoi(argv[1]);
for (i=1; i<=n; i++)
{
printf("CHILD (%d - %d): Hello father ...%d!\n",getpid(),getppid(),i);
}
return 10;
}
|
C
|
#include <stdio.h>
int main()
{
//Exercicio 6
//r == 1 (SIM) repete a operacao
//r == 0 (NAO) finaliza a operacao
int r=1;
//enquanto r e 1, repete a operacao
while(r == 1)
{
int n;
int f=1;
//pergunta o numero
printf("Digite un numero: ");
scanf("%d",&n);
//calcula o fatorial
int i=0;
for(i=1; i<=n; ++i)
{
f *= i; // f = f*i;
}
//imprime factorial
printf("\nFatorial: %d",f);
//pergunta pra repetir
printf ("\nRepetir?: ");
scanf("%d", &r);
}
return 0;
}
|
C
|
#include <stdio.h>
int ex5() {
int ent;
int ent2;
int ent3;
scanf("%d %d %d",&ent,&ent2,&ent3);
if(ent<=ent2 && ent2<=ent3){
printf("%d %d %d\n",ent,ent2,ent3);
} else if(ent<=ent3 && ent3<=ent2){
printf("%d %d %d\n",ent,ent3,ent2);
} else if(ent2<=ent && ent<=ent3){
printf("%d %d %d\n",ent2,ent,ent3);
} else if(ent2<=ent3 && ent3<=ent){
printf("%d %d %d\n",ent2,ent3,ent);
} else if(ent3<=ent2 && ent2<=ent){
printf("%d %d %d\n",ent3,ent2,ent);
} else {
printf("%d %d %d\n",ent3,ent,ent2);
}
return 0;
}
|
C
|
/*
* vm.c
* part of Atto :: https://github.com/deveah/atto
*/
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "vm.h"
struct atto_vm_state *atto_allocate_vm_state(void)
{
struct atto_vm_state *vm = (struct atto_vm_state *)malloc(sizeof(struct atto_vm_state));
assert(vm != NULL);
vm->data_stack_size = 0;
vm->data_stack = (struct atto_object **)malloc(sizeof(struct atto_object *) * ATTO_VM_MAX_DATA_STACK_SIZE);
assert(vm->data_stack != NULL);
vm->heap_size = 0;
vm->heap = (struct atto_object *)malloc(sizeof(struct atto_object) * ATTO_VM_MAX_HEAP_OBJECTS);
assert(vm->heap != NULL);
vm->call_stack_size = 0;
vm->call_stack = (struct atto_vm_call_stack_entry *)malloc(sizeof(struct atto_vm_call_stack_entry) * ATTO_VM_MAX_CALL_STACK_SIZE);
assert(vm->call_stack != NULL);
vm->number_of_instruction_streams = 0;
vm->number_of_allocated_instruction_streams = ATTO_VM_MIN_NUMBER_OF_INSTRUCTION_STREAMS;
vm->instruction_streams = (struct atto_instruction_stream **)malloc(sizeof(struct atto_instruction_stream *) * ATTO_VM_MIN_NUMBER_OF_INSTRUCTION_STREAMS);
vm->current_instruction_stream_index = 0;
vm->current_instruction_stream_index = 0;
return vm;
}
void atto_destroy_vm_state(struct atto_vm_state *vm)
{
free(vm->data_stack);
free(vm->call_stack);
free(vm->instruction_streams);
free(vm);
}
void atto_vm_perform_step(struct atto_vm_state *vm)
{
struct atto_instruction_stream *current_instruction_stream = vm->instruction_streams[vm->current_instruction_stream_index];
uint8_t opcode = current_instruction_stream->stream[vm->current_instruction_offset];
switch (opcode) {
case ATTO_VM_OP_NOP: {
printf("vm: nop\n");
vm->current_instruction_offset += 1;
break;
}
case ATTO_VM_OP_CALL: {
size_t target_instruction_stream;
if (vm->data_stack[vm->data_stack_size - 1]->kind != ATTO_OBJECT_KIND_LAMBDA) {
printf("fatal: attempting to call non-lambda object\n");
vm->flags &= ~(ATTO_VM_FLAG_RUNNING);
return;
}
vm->data_stack_size--;
target_instruction_stream = vm->data_stack[vm->data_stack_size]->container.instruction_stream_index;
printf("vm: call\n");
vm->call_stack[vm->call_stack_size].instruction_stream_index = vm->current_instruction_stream_index;
vm->call_stack[vm->call_stack_size].instruction_offset = vm->current_instruction_offset + 1;
vm->call_stack[vm->call_stack_size].stack_offset_at_entrypoint = vm->data_stack_size;
vm->call_stack_size++;
vm->current_instruction_stream_index = target_instruction_stream;
vm->current_instruction_offset = 0;
break;
}
case ATTO_VM_OP_RET: {
printf("vm: ret\n");
vm->call_stack_size -= 1;
vm->current_instruction_stream_index = vm->call_stack[vm->call_stack_size].instruction_stream_index;
vm->current_instruction_offset = vm->call_stack[vm->call_stack_size].instruction_offset;
break;
}
case ATTO_VM_OP_B:
break;
case ATTO_VM_OP_BT:
break;
case ATTO_VM_OP_BF:
break;
case ATTO_VM_OP_CLOSE: {
size_t count;
memcpy(&count, current_instruction_stream->stream + vm->current_instruction_offset + 1, sizeof(size_t));
printf("vm: close %lu\n", count);
vm->data_stack[vm->call_stack[vm->call_stack_size - 1].stack_offset_at_entrypoint - count] = vm->data_stack[vm->data_stack_size - 1];
vm->data_stack_size = vm->call_stack[vm->call_stack_size - 1].stack_offset_at_entrypoint - count + 1;
vm->current_instruction_offset += 1 + sizeof(size_t);
break;
}
case ATTO_VM_OP_ADD: {
struct atto_object *a = vm->data_stack[vm->data_stack_size - 1];
struct atto_object *b = vm->data_stack[vm->data_stack_size - 2];
struct atto_object *c = &vm->heap[vm->heap_size++];
printf("vm: add\n");
if (a->kind == ATTO_OBJECT_KIND_THUNK) {
evaluate_thunk(vm, a);
}
if (b->kind == ATTO_OBJECT_KIND_THUNK) {
evaluate_thunk(vm, b);
}
if ((a->kind != ATTO_OBJECT_KIND_NUMBER) ||
(b->kind != ATTO_OBJECT_KIND_NUMBER)) {
printf("fatal: attempting to perform `add' on non-numeric arguments\n");
vm->flags &= ~(ATTO_VM_FLAG_RUNNING);
return;
}
vm->data_stack_size -= 1;
c->kind = ATTO_OBJECT_KIND_NUMBER;
c->container.number = a->container.number + b->container.number;
vm->data_stack[vm->data_stack_size - 1] = c;
vm->current_instruction_offset += 1;
break;
}
case ATTO_VM_OP_SUB:
break;
case ATTO_VM_OP_MUL:
break;
case ATTO_VM_OP_DIV:
break;
case ATTO_VM_OP_ISEQ:
break;
case ATTO_VM_OP_ISLT:
break;
case ATTO_VM_OP_ISLET:
break;
case ATTO_VM_OP_ISGT:
break;
case ATTO_VM_OP_ISGET:
break;
case ATTO_VM_OP_ISSEQ:
break;
case ATTO_VM_OP_NOT:
break;
case ATTO_VM_OP_OR:
break;
case ATTO_VM_OP_AND:
break;
case ATTO_VM_OP_CAR:
break;
case ATTO_VM_OP_CDR:
break;
case ATTO_VM_OP_CONS:
break;
case ATTO_VM_OP_PUSHN: {
double number;
memcpy(&number, current_instruction_stream->stream + vm->current_instruction_offset + 1, sizeof(double));
printf("vm: push_number %lf\n", number);
vm->heap[vm->heap_size].kind = ATTO_OBJECT_KIND_NUMBER;
vm->heap[vm->heap_size].container.number = number;
vm->heap_size++;
vm->data_stack[vm->data_stack_size] = &vm->heap[vm->heap_size - 1];
vm->data_stack_size++;
vm->current_instruction_offset += 1 + sizeof(double);
break;
}
case ATTO_VM_OP_PUSHS:
break;
case ATTO_VM_OP_PUSHZ:
break;
case ATTO_VM_OP_DUP:
break;
case ATTO_VM_OP_DROP:
break;
case ATTO_VM_OP_SWAP:
break;
case ATTO_VM_OP_GETGL: {
size_t index;
memcpy(&index, current_instruction_stream->stream + vm->current_instruction_offset + 1, sizeof(size_t));
printf("vm: getgl %lu\n", index);
vm->data_stack[vm->data_stack_size] = vm->data_stack[index];
vm->data_stack_size++;
vm->current_instruction_offset += 1 + sizeof(size_t);
break;
}
case ATTO_VM_OP_GETLC: {
size_t index;
memcpy(&index, current_instruction_stream->stream + vm->current_instruction_offset + 1, sizeof(size_t));
printf("vm: getlc %lu\n", index);
vm->data_stack[vm->data_stack_size] = vm->data_stack[vm->call_stack[vm->call_stack_size - 1].stack_offset_at_entrypoint + index];
vm->data_stack_size++;
vm->current_instruction_offset += 1 + sizeof(size_t);
break;
}
case ATTO_VM_OP_GETAG: {
size_t index;
memcpy(&index, current_instruction_stream->stream + vm->current_instruction_offset + 1, sizeof(size_t));
printf("vm: getag %lu\n", index);
vm->data_stack[vm->data_stack_size] = vm->data_stack[vm->call_stack[vm->call_stack_size - 1].stack_offset_at_entrypoint - index - 1];
vm->data_stack_size++;
vm->current_instruction_offset += 1 + sizeof(size_t);
break;
}
default:
printf("fatal: unknown opcode (0x%02x)\n", opcode);
exit(1);
}
}
void atto_run_vm(struct atto_vm_state *vm)
{
vm->flags |= ATTO_VM_FLAG_RUNNING;
printf("vm: run is=%lu, o=%lu\n", vm->current_instruction_stream_index, vm->current_instruction_offset);
while (vm->flags & ATTO_VM_FLAG_RUNNING) {
atto_vm_perform_step(vm);
pretty_print_stack(vm);
if (vm->current_instruction_offset >= vm->instruction_streams[vm->current_instruction_stream_index]->length) {
vm->flags &= ~(ATTO_VM_FLAG_RUNNING);
printf("vm: stop\n");
}
}
}
void pretty_print_stack(struct atto_vm_state *vm)
{
size_t i;
printf("stack: ");
for (i = 0; i < vm->data_stack_size; i++) {
if (i == vm->call_stack[vm->call_stack_size - 1].stack_offset_at_entrypoint) {
printf("| ");
}
switch (vm->data_stack[i]->kind) {
case ATTO_OBJECT_KIND_NULL:
printf("() ");
break;
case ATTO_OBJECT_KIND_NUMBER:
printf("num(%lf) ", vm->data_stack[i]->container.number);
break;
case ATTO_OBJECT_KIND_SYMBOL:
printf("sym(%lu) ", vm->data_stack[i]->container.symbol);
break;
case ATTO_OBJECT_KIND_LIST:
printf("list() ");
break;
case ATTO_OBJECT_KIND_LAMBDA:
printf("lambda() ");
break;
case ATTO_OBJECT_KIND_THUNK:
printf("thunk(%lu) ", vm->data_stack[i]->container.instruction_stream_index);
break;
default:
printf("bug ");
}
}
printf("\n");
}
void evaluate_thunk(struct atto_vm_state *vm, struct atto_object *o)
{
if (o->kind != ATTO_OBJECT_KIND_THUNK) {
return;
}
/*vm->call_stack[vm->call_stack_size].instruction_stream_index = vm->current_instruction_stream_index;
vm->call_stack[vm->call_stack_size].instruction_offset = vm->current_instruction_offset;
vm->call_stack[vm->call_stack_size].stack_offset_at_entrypoint = vm->data_stack_size;
vm->call_stack_size++;*/
size_t saved_instruction_stream_index = vm->current_instruction_stream_index;
size_t saved_instruction_offset = vm->current_instruction_offset;
vm->current_instruction_stream_index = o->container.instruction_stream_index;
vm->current_instruction_offset = 0;
printf("EXECUTING THUNK\n");
atto_run_vm(vm);
printf("FINISHED EXECUTING THUNK\n");
vm->current_instruction_stream_index = saved_instruction_stream_index;
vm->current_instruction_offset = saved_instruction_offset;
/* TODO: free linked instruction stream */
printf("o->kind = %i\n", o->kind);
o->kind = vm->data_stack[vm->data_stack_size - 1]->kind;
o->container = vm->data_stack[vm->data_stack_size - 1]->container;
}
|
C
|
/*
* Filename: testcreateMask.c
* Author: Huize Shi
* Userid: cs30xapo
* Description: This function test the createMask function
* Date: May 1st, 2016
* Source of help: none
*/
#include "test.h" /* For TEST() macro and stdio.h */
#include <stdlib.h> /* For rand() function prototype */
#include <limits.h> /* For LONG_MIN and LONG_MAX */
#include "pa2.h" /* For rotate() function prototype */
// Function prototypes
void createMask( unsigned long keys[], unsigned char passphrase[],
unsigned long mask[] );
void refillPassphrase( unsigned char * passphrase );
void zeroFillPassphrase( unsigned char * passphrase );
// Testing function
void testcreateMask() {
// Initialize variables
unsigned long mask[2];
unsigned long key[2];
printf("Testing createMask()\n" );
// Checking when 2 bytes are xored
unsigned char passphrase[8] = { 'h','e', 'l', 'l', 'o', 'c', 's', 'e' };
key[0] = 0x4F;
key[1] = 0x34;
createMask( key, passphrase, mask );
TEST( mask[0] == 0x68656C23 && mask[1] == 0x6F637351 );
// Checking when no bytes are xored
refillPassphrase( passphrase );
key[0] = 0;
key[1] = 0;
createMask( key, passphrase, mask );
TEST( mask[0] == 0x68656C6C && mask[1] == 0x6F637365);
// Checking when all nibbles are xored
refillPassphrase( passphrase );
key[0] = 0x243F4A9A;
key[1] = 0x1B4C9D8E;
createMask( key, passphrase, mask );
TEST( mask[0] == 0x4C5A26F6 && mask[1] == 0x742FEEEB );
// Checking when all bits are xored
refillPassphrase( passphrase );
key[0] = 0xFFFFFFFF;
key[1] = 0xFFFFFFFF;
createMask( key, passphrase, mask );
TEST( mask[0] == 0x979A9393 && mask[1] == 0x909C8C9A );
// Checking when 0 xoring with data
zeroFillPassphrase( passphrase );
key[0] = 0xABCDEF98;
key[1] = 0x89FEDCBA;
createMask( key, passphrase, mask );
TEST( mask[0] == 0xABCDEF98 && mask[1] == 0x89FEDCBA );
printf( "Finished running tests on createMask()\n" );
}
/*
* Helper method that fill the passphrase with unsigned values of "hellocse"
*/
void refillPassphrase( unsigned char * passphrase ) {
*passphrase = 0x68;
++passphrase;
*passphrase = 0x65;
++passphrase;
*passphrase = 0x6C;
++passphrase;
*passphrase = 0x6C;
++passphrase;
*passphrase = 0x6F;
++passphrase;
*passphrase = 0x63;
++passphrase;
*passphrase = 0x73;
++passphrase;
*passphrase = 0x65;
}
/*
* Helper method that fill the passphrase with all 0s
*/
void zeroFillPassphrase( unsigned char * passphrase ) {
*passphrase = 0;
++passphrase;
*passphrase = 0;
++passphrase;
*passphrase = 0;
++passphrase;
*passphrase = 0;
++passphrase;
*passphrase = 0;
++passphrase;
*passphrase = 0;
++passphrase;
*passphrase = 0;
++passphrase;
*passphrase = 0;
}
int main() {
testcreateMask();
return 0;
}
|
C
|
#include<iostream>
#include<memory>
#include<stdlib.h>
using namespace std;
struct Node
{
int data;
Node *left;
Node *right;
};
Node *allocateNode(int data)
{
Node *temp = new Node;
temp->data = data;
temp->left = NULL;
temp->right = NULL;
return temp;
}
int height(Node *root)
{
if(root == NULL)
return 0;
int lh = height(root->left);
int rh = height(root->right);
return (lh > rh) ? (lh+1) : (rh+1);
}
bool isHeightBalanced(Node *root)
{
if(root == NULL)
return true;
int lheight = height(root->left);
int rheight = height(root->right);
if( (abs(lheight - rheight) <= 1) &&
isHeightBalanced(root->left) &&
isHeightBalanced(root->right) )
return true;
else
return false;
}
bool isHeightBalancedOpt(Node *root, int &height)
{
if(root == NULL)
{
height = 0;
return true;
}
bool lbalanced = false;
bool rbalanced = false;
int lh = 0, rh = 0;
lbalanced = isHeightBalancedOpt(root->left, lh);
rbalanced = isHeightBalancedOpt(root->right, rh);
height = ( lh > rh ) ? (lh + 1) : ( rh + 1);
if( abs(lh - rh) > 1 )
return false;
else
return (lbalanced && rbalanced);
}
int main()
{
Node *root = allocateNode(1);
root->left = allocateNode(2);
root->right = allocateNode(3);
root->left->left = allocateNode(4);
root->left->right = allocateNode(5);
root->left->left->left = allocateNode(8);
if(isHeightBalanced(root))
cout << "Tree is balanced" << endl;
else
cout << "Tree is not balanced" << endl;
return 0;
}
|
C
|
#include <string.h>
#include <stdlib.h>
#include <math.h>
// Only used for debug mode
#include "../gbRenderer/gbRenderer_sys.h"
#include "../gbUtils/gbUtils.h"
#include "Collision_sys.h"
#include "CollisionDynamicRect_type.h"
#include "CollisionStaticRect_type.h"
#include "../global_state.h"
static Position *dynamicColliderPositions[COLLISION_MAX_DYNAMIC_COLLIDERS];
static CollisionDynamicRect *dynamicColliders[COLLISION_MAX_DYNAMIC_COLLIDERS];
static unsigned int dynamicColliderCursor;
static CollisionStaticRect *staticColliders[COLLISION_MAX_STATIC_COLLIDERS];
static unsigned int staticColliderCursor;
static CollisionStaticRect *passiveColliders[COLLISION_MAX_PASSIVE_COLLIDERS];
static unsigned int passiveColliderCursor;
void collisionInit() {
dynamicColliderCursor = 0;
staticColliderCursor = 0;
passiveColliderCursor = 0;
for (unsigned int i = 0; i < COLLISION_MAX_DYNAMIC_COLLIDERS; i++) {
dynamicColliders[i] = 0;
dynamicColliderPositions[i] = 0;
}
for (unsigned int i = 0; i < COLLISION_MAX_STATIC_COLLIDERS; i++) {
staticColliders[i] = 0;
}
for (unsigned int i = 0; i < COLLISION_MAX_PASSIVE_COLLIDERS; i++) {
passiveColliders[i] = 0;
}
}
void collisionDynamicTeardown() {
for (unsigned i = 0; i < dynamicColliderCursor; i++) {
dynamicColliders[i] = 0;
}
dynamicColliderCursor = 0;
}
void collisionStaticTeardown() {
for (unsigned i = 0; i < staticColliderCursor; i++) {
staticColliders[i] = 0;
}
staticColliderCursor = 0;
}
void collisionTeardown() {
collisionDynamicTeardown();
collisionStaticTeardown();
for (unsigned i = 0; i < passiveColliderCursor; i++) {
passiveColliders[i] = 0;
}
passiveColliderCursor = 0;
}
void collisionDynamicRectSet(
CollisionDynamicRect *rect,
unsigned int entityId,
int offsetX,
int offsetY,
unsigned int width,
unsigned int height,
uint8_t solid
) {
rect->entityId = entityId;
rect->active = 1;
rect->solid = solid;
rect->offsetX = offsetX;
rect->offsetY = offsetY;
rect->width = width;
rect->height = height;
}
void collisionDynamicRectRegister(CollisionDynamicRect *rect, Position *pos) {
if (dynamicColliderCursor >= COLLISION_MAX_DYNAMIC_COLLIDERS)
return;
rect->index = dynamicColliderCursor;
dynamicColliders[dynamicColliderCursor] = rect;
dynamicColliderPositions[dynamicColliderCursor] = pos;
dynamicColliderCursor++;
}
void collisionDynamicRectUnregister(CollisionDynamicRect *rect) {
unsigned int index = rect->index;
dynamicColliderPositions[index] = 0;
dynamicColliders[index] = 0;
if (--dynamicColliderCursor > 0 && dynamicColliderCursor != index) {
dynamicColliders[index] = dynamicColliders[dynamicColliderCursor];
dynamicColliderPositions[index] = dynamicColliderPositions[dynamicColliderCursor];
dynamicColliders[index]->index = index;
}
dynamicColliders[dynamicColliderCursor] = 0;
dynamicColliderPositions[dynamicColliderCursor] = 0;
}
void collisionStaticRectSet(CollisionStaticRect * rect, int x1, int y1, int x2, int y2, uint8_t active) {
rect->active = active;
rect->x1 = x1;
rect->y1 = y1;
rect->x2 = x2;
rect->y2 = y2;
}
void collisionStaticRectRegister(CollisionStaticRect *rect) {
if (staticColliderCursor >= COLLISION_MAX_STATIC_COLLIDERS)
return;
staticColliders[staticColliderCursor++] = rect;
}
void collisionStaticRectUnregister(CollisionStaticRect *rect) {
unsigned int index = 0;
for (; index < staticColliderCursor; index++) {
if (staticColliders[index] == rect) break;
}
if (index == staticColliderCursor)
return;
staticColliders[index] = 0;
if (--staticColliderCursor > 0 && staticColliderCursor != index) {
staticColliders[index] = staticColliders[staticColliderCursor];
}
staticColliders[staticColliderCursor] = 0;
}
void collisionStaticRectPassiveRegister(CollisionStaticRect *rect) {
if (passiveColliderCursor >= COLLISION_MAX_PASSIVE_COLLIDERS)
return;
passiveColliders[passiveColliderCursor++] = rect;
}
void collisionStaticRectPassiveUnregister(CollisionStaticRect *rect) {
unsigned int index = 0;
for (; index < passiveColliderCursor; index++) {
if (passiveColliders[index] == rect) break;
}
if (index == passiveColliderCursor)
return;
passiveColliders[index] = 0;
if (--passiveColliderCursor > 0 && passiveColliderCursor != index) {
passiveColliders[index] = passiveColliders[passiveColliderCursor];
}
passiveColliders[passiveColliderCursor] = 0;
}
// Check collisions between A and B and return flags
// Collision detection is performed from A's perspective
uint8_t detectCollision(
double x1A,
double y1A,
double x2A,
double y2A,
double x1B,
double y1B,
double x2B,
double y2B,
double dx,
double dy,
double *xOverlap,
double *yOverlap
) {
uint8_t collData = 0;
// Check x axis
if ((x1A >= x1B && x2A <= x2B) ||
(x1A <= x1B && x2A >= x2B) ||
(x1A < x2B && x2A > x2B) ||
(x1A < x1B && x2A > x1B)) {
collData |= COLLISION_X;
if (x1A < x2B && x2A > x2B)
collData |= COLLISION_RIGHT;
else if (x1A < x1B && x2A > x1B)
collData |= COLLISION_LEFT;
}
// If there is no overlap on the x axis, there is no collision.
if ((y1A >= y1B && y2A <= y2B) ||
(y1A <= y1B && y2A >= y2B) ||
(y1A < y2B && y2A > y2B) ||
(y1A < y1B && y2A > y1B)) {
collData |= COLLISION_Y;
if ((y1A < y2B && y2A > y2B))
collData |= COLLISION_BOTTOM;
else if ((y1A < y1B && y2A > y1B))
collData |= COLLISION_TOP;
}
if ((collData & (COLLISION_X | COLLISION_Y)) == (COLLISION_X | COLLISION_Y)) {
int xOverlap1 = x2B - x1A;
int xOverlap2 = x1B - x2A;
*xOverlap = abs(xOverlap1) < abs(xOverlap2) ? xOverlap1 : xOverlap2;
int yOverlap1 = y1B - y2A;
int yOverlap2 = y2B - y1A;
*yOverlap = abs(yOverlap1) < abs(yOverlap2) ? yOverlap1 : yOverlap2;
if ((abs(*xOverlap) <= abs(*yOverlap)))
collData |= COLLISION_X_MARKED;
if ((abs(*yOverlap) <= abs(*xOverlap)))
collData |= COLLISION_Y_MARKED;
}
return collData;
}
unsigned int collisionResolveStaticCollisions(unsigned int index, CollisionDynamicRect *dynamicCollider, double dx, double dy, uint8_t *collData) {
Position *dynamicPosition = dynamicColliderPositions[dynamicCollider->index];
for (;index < staticColliderCursor; index++) {
double x1A = dynamicPosition->x + dynamicCollider->offsetX;
double y1A = dynamicPosition->y + dynamicCollider->offsetY;
double x2A = x1A + dynamicCollider->width;
double y2A = y1A + dynamicCollider->height;
double xOverlap = 0;
double yOverlap = 0;
CollisionStaticRect *rect = staticColliders[index];
if (!rect->active) continue;
uint8_t data = detectCollision(
x1A, y1A, x2A, y2A,
rect->x1, rect->y1, rect->x2, rect->y2,
dx, dy,
&xOverlap, &yOverlap
);
if ((data & COLLISION_X) && (data & COLLISION_Y)) {
if (data & COLLISION_X_MARKED) {
dynamicPosition->x += xOverlap;
}
if (data & COLLISION_Y_MARKED) {
dynamicPosition->y += yOverlap;
}
*collData = data;
return index + 1;
}
}
*collData = 0;
return 0;
}
unsigned int collisionResolveDynamicCollisions(unsigned int index, CollisionDynamicRect *dynamicCollider, double dx, double dy, unsigned int *entityId, uint8_t *collData) {
Position *dynamicPosition = dynamicColliderPositions[dynamicCollider->index];
for (;index < dynamicColliderCursor; index++) {
double x1A = dynamicPosition->x + dynamicCollider->offsetX;
double y1A = dynamicPosition->y + dynamicCollider->offsetY;
double x2A = x1A + dynamicCollider->width;
double y2A = y1A + dynamicCollider->height;
CollisionDynamicRect *rect = dynamicColliders[index];
if (rect->entityId == dynamicCollider->entityId) continue;
Position *rectPos = dynamicColliderPositions[index];
if (!rect->active) continue;
double x1B = rectPos->x + rect->offsetX;
double y1B = rectPos->y + rect->offsetY;
double x2B = x1B + rect->width;
double y2B = y1B + rect->height;
double xOverlap = 0;
double yOverlap = 0;
uint8_t data = detectCollision(
x1A, y1A, x2A, y2A,
x1B, y1B, x2B, y2B,
dx, dy,
&xOverlap, &yOverlap
);
if ((data & COLLISION_X) && (data & COLLISION_Y)) {
if (((xOverlap && dx) || (yOverlap && dy)) && dynamicCollider->solid && rect->solid) {
if (data & COLLISION_X_MARKED) {
dynamicPosition->x += xOverlap;
}
if (data & COLLISION_Y_MARKED) {
dynamicPosition->y += yOverlap;
}
}
*collData = data;
*entityId = rect->entityId;
return index + 1;
}
}
*collData = 0;
return 0;
}
CollisionStaticRect *collisionDetectPointCollisionStatic(int x, int y) {
for (unsigned int i = 0; i < staticColliderCursor; i++) {
if (!staticColliders[i]->active) continue;
if (x > staticColliders[i]->x1 && x < staticColliders[i]->x2 &&
y > staticColliders[i]->y1 && y < staticColliders[i]->y2) {
return staticColliders[i];
}
}
return 0;
}
CollisionStaticRect *collisionDetectPointCollisionPassive(int x, int y) {
for (unsigned int i = 0; i < passiveColliderCursor; i++) {
if (!passiveColliders[i]->active) continue;
if (x > passiveColliders[i]->x1 && x < passiveColliders[i]->x2 &&
y > passiveColliders[i]->y1 && y < passiveColliders[i]->y2) {
return passiveColliders[i];
}
}
return 0;
}
uint8_t collisionCheckPlayer(DynamicEntity *other) {
int index = 0;
unsigned int id = 0;
uint8_t collData;
while(index = collisionResolveDynamicCollisions(index, &other->boundingBox, 0, 0, &id, &collData)) {
if (id == mainPlayer->id) break;
}
return index != 0;
}
void collisionDebugDraw() {
SDL_SetRenderDrawColor(gbMainRenderer, 0x00, 0xff, 0xff, 0xff);
SDL_Rect rect;
for (unsigned int i = 0; i < staticColliderCursor; i++) {
rect.x = staticColliders[i]->x1;
rect.y = staticColliders[i]->y1;
rect.w = staticColliders[i]->x2 - staticColliders[i]->x1;
rect.h = staticColliders[i]->y2 - staticColliders[i]->y1;
SDL_RenderDrawRect(gbMainRenderer, &rect);
}
gbRendererResetDrawColor();
}
void serializeStaticCollisionRects(CollisionStaticRect **rects, unsigned int numRects, SDL_RWops *file) {
if (!numRects) {
SDL_WriteBE16(file, 0);
return;
}
// Write number of colliders
SDL_WriteBE16(file, numRects);
// Write each collider info
CollisionStaticRect *rect;
for (int i = 0; i < numRects; i++) {
rect = rects[i];
SDL_WriteU8(file, rect->active);
SDL_WriteBE64(file, rect->x1);
SDL_WriteBE64(file, rect->y1);
SDL_WriteBE64(file, rect->x2);
SDL_WriteBE64(file, rect->y2);
}
}
CollisionStaticRect *deserializeStaticCollisionRect(SDL_RWops *file) {
CollisionStaticRect *rect = (CollisionStaticRect *)malloc(sizeof(CollisionStaticRect));
rect->active = SDL_ReadU8(file);
rect->x1 = SDL_ReadBE64(file);
rect->y1 = SDL_ReadBE64(file);
rect->x2 = SDL_ReadBE64(file);
rect->y2 = SDL_ReadBE64(file);
return rect;
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <ctype.h>
void interschimbaLitere(char* sir) {
if (strlen(sir) % 2) return; // daca nu are numar par de litere nu face interschimbarile(ar ramane o litera ce nu are cu ce sa se schimbe)
for (int i = 0; i < strlen(sir); i += 2) {
char temp = sir[i];
sir[i] = sir[i + 1];
sir[i + 1] = temp;
}
}
void main () {
char cuvant[25];
printf("Introdu un cuvant: ");
scanf("%[^\n]s", cuvant);
printf("%s\n", cuvant);
interschimbaLitere(cuvant);
printf("%s\n", cuvant);
}
|
C
|
#include <check.h>
#include "num_dcmp.h"
START_TEST(decompose)
{
struct num_dcmp nd;
nd = nd_decompose(0U);
ck_assert(nd.head == NULL);
nd = nd_decompose(1U);
ck_assert(nd.head == NULL);
nd = nd_decompose(2U);
ck_assert(nd.head != NULL);
ck_assert(nd.head->power == 1);
ck_assert(nd.head->next == NULL);
nd_destroy(&nd);
nd = nd_decompose(2U * 25U * 1331U);
ck_assert(nd.head != NULL);
ck_assert(nd.head->power == 1); // 2
ck_assert(nd.head->next != NULL);
ck_assert(nd.head->next->power == 0);
ck_assert(nd.head->next->next != NULL);
ck_assert(nd.head->next->next->power == 2); // 5 * 5 = 25
ck_assert(nd.head->next->next->next != NULL);
ck_assert(nd.head->next->next->next->power == 0);
ck_assert(nd.head->next->next->next->next != NULL);
ck_assert(nd.head->next->next->next->next->power == 3); // 11 ^ 3 = 1331
ck_assert(nd.head->next->next->next->next->next == NULL);
nd_destroy(&nd);
}
END_TEST
START_TEST(multiply)
{
struct num_dcmp nd_1 = nd_decompose(18U);
struct num_dcmp nd_2 = nd_decompose(25U);
struct num_dcmp res = nd_multiply(&nd_1, &nd_2);
ck_assert(res.head != NULL);
ck_assert(res.head->power == 1);
ck_assert(res.head->next != NULL);
ck_assert(res.head->next->power == 2);
ck_assert(res.head->next->next != NULL);
ck_assert(res.head->next->next->power == 2);
ck_assert(res.head->next->next->next == NULL);
nd_destroy(&nd_1);
nd_destroy(&nd_2);
nd_destroy(&res);
}
END_TEST
START_TEST(divide)
{
struct num_dcmp nd_1 = nd_decompose(135000U);
struct num_dcmp nd_2 = nd_decompose(300U);
struct num_dcmp res = nd_divide(&nd_1, &nd_2);
ck_assert(res.head != NULL);
ck_assert(res.head->power == 1);
ck_assert(res.head->next != NULL);
ck_assert(res.head->next->power == 2);
ck_assert(res.head->next->next != NULL);
ck_assert(res.head->next->next->power == 2);
ck_assert(res.head->next->next->next == NULL);
nd_destroy(&nd_1);
nd_destroy(&nd_2);
nd_destroy(&res);
}
END_TEST
START_TEST(square)
{
struct num_dcmp nd = nd_decompose(450U);
struct num_dcmp res = nd_square(&nd);
ck_assert(res.head != NULL);
ck_assert(res.head->power == 2);
ck_assert(res.head->next != NULL);
ck_assert(res.head->next->power == 4);
ck_assert(res.head->next->next != NULL);
ck_assert(res.head->next->next->power == 4);
ck_assert(res.head->next->next->next == NULL);
nd_destroy(&nd);
nd_destroy(&res);
}
Suite *num_dcmp_suite(void)
{
Suite *suite = suite_create("num decompose");
TCase *tcase = tcase_create("core");
tcase_add_test(tcase, decompose);
tcase_add_test(tcase, multiply);
tcase_add_test(tcase, divide);
tcase_add_test(tcase, square);
suite_add_tcase(suite, tcase);
return suite;
}
|
C
|
#include "internal_dgraph.h"
#include <errno.h>
#include <stdlib.h>
void **dgraph_retrive_node(dgraph_t graph, int n, int *is_new) {
size_t old_size = graph->nodes;
dgraph_node_t node = dgraph_internal_place_node(graph, n, NULL, 1);
if (is_new)
*is_new = graph->nodes - old_size;
if (node)
return &node->content;
else
return NULL;
}
int dgraph_set(dgraph_t graph, int a, int b) {
return dgraph_internal_insert_to_node(graph, a, 1, &b);
}
int dgraph_set_list(dgraph_t graph, int n, size_t size, const int list[]) {
return dgraph_internal_insert_to_node(graph, n, size, list);
}
int dgraph_remove(dgraph_t graph, int a, int b) {
return dgraph_internal_remove_from_node(graph, a, 1, &b);
}
int dgraph_rm_list(dgraph_t graph, int n, size_t size, const int list[]) {
return dgraph_internal_remove_from_node(graph, n, size, list);
}
int dgraph_rm_node(dgraph_t graph, int n) {
return dgraph_internal_destroy_node(graph, n);
}
int dgraph_init(dgraph_t graph, size_t size, const int *const *data) {
size_t i;
int result = 0;
int *buff = malloc(size*sizeof(int));
for (i = 0; i < size; i++) {
size_t j;
size_t amount = 0;
const int *list = data[i];
for (j = 0; j < size; j++) {
if (list[j])
buff[amount++] = j;
}
if (amount) {
if (dgraph_internal_insert_to_node(graph, i, amount, buff))
result = 1;
else if (errno == ENOMEM) {
free(buff);
errno = ENOMEM;
return 0;
}
}
}
free(buff);
return result;
}
void dgraph_clear(dgraph_t graph) {
size_t i;
dgraph_allocator alloc = graph->alloc;
void *ud_alloc = graph->ud_alloc;
size_t nodes = graph->nodes;
dgraph_node_t *data = graph->data;
for (i = 0; i < nodes; i++)
alloc(ud_alloc, data[i], 0);
alloc(ud_alloc, data, 0);
graph->data = NULL;
graph->nodes = 0;
}
|
C
|
/*
** EPITECH PROJECT, 2020
** NWP_myteams_2019
** File description:
** broadcast
*/
#include "response.h"
#include "logging_client.h"
#include "libparse.h"
int broadcast_log(client_t *client)
{
char **array;
const char *end_ptr;
if (strstr(client->receive_command, "LOGGEDIN")) {
array = parse_args(client->receive_command + 4, &end_ptr, PARSE_COMMA);
if (array != NULL) {
client_event_loggedin(array[2], array[3]);
free_array(array);
}
return 1;
}
if (strstr(client->receive_command, "LOGGEDOUT")) {
array = parse_args(client->receive_command + 4, &end_ptr, PARSE_COMMA);
if (array != NULL) {
client_event_loggedout(array[2], array[3]);
free_array(array);
}
return 1;
}
return 0;
}
int broadcast_message(client_t *client)
{
char **array;
const char *end_ptr;
if (strstr(client->receive_command, "MP")) {
array = parse_args(client->receive_command + 4, &end_ptr, PARSE_COMMA);
if (array != NULL) {
client_event_private_message_received(array[2], array[3]);
free_array(array);
}
return 1;
}
if (strstr(client->receive_command, "COMMENT")) {
array = parse_args(client->receive_command + 4, &end_ptr, PARSE_COMMA);
if (array != NULL) {
client_event_thread_message_received(array[2], array[3], array[4],
array[5]);
free_array(array);
}
return 1;
}
return 0;
}
void broadcast_create2(char **array)
{
if (array != NULL) {
client_event_thread_created(array[2], array[3], atoi(array[4]),
array[5], array[6]);
free_array(array);
}
}
int broadcast_create(client_t *client)
{
const char *end_ptr;
char **array = parse_args(client->receive_command + 4, &end_ptr,
PARSE_COMMA);
if (strstr(client->receive_command, "TEAM")) {
if (array != NULL) {
client_event_team_created(array[2], array[3], array[4]);
free_array(array);
} return 1;
} if (strstr(client->receive_command, "CHANNEL")) {
if (array != NULL) {
client_event_channel_created(array[2], array[3], array[4]);
free_array(array);
} return 1;
}
if (strstr(client->receive_command, "THREAD")) {
broadcast_create2(array);
return 1;
}
free_array(array);
return 0;
}
void broadcast(client_t *client)
{
if (broadcast_log(client))
return;
if (broadcast_message(client))
return;
broadcast_create(client);
}
|
C
|
#include <stdio.h>
int main()
{
int year, month, days;
while (1) {
printf("请输入一个年份和月份:\n");
scanf("%d%d", &year, &month);
switch (month)
{
case 1: days = 31; break;
case 2: if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0))
days = 29;
else
days = 28;
break;
case 3: days = 31; break;
case 4: days = 30; break;
case 5: days = 31; break;
case 6: days = 30; break;
case 7: days = 31; break;
case 8: days = 31; break;
case 9: days = 30; break;
case 10: days = 31; break;
case 11: days = 30; break;
case 12: days = 31; break;
default:
break;
}
printf("该月有%d天\n", days);
}
return 0;
}
|
C
|
#ifndef JOUEUR_H_INCLUDED
#define JOUEUR_H_INCLUDED
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include "piece/piece.h"
#include "toolbox/tools.h"
#include "mainHeader.h"
#include "coup.h"
/*
Ce fichier contiendra la structure et les dfinitions des fonctions ncessaires au fonctionnement d'un joueur.
*/
//0 Constantes
#define JOUEUR_HUMAIN 0
#define JOUEUR_ALEATOIRE 1
#define JOUEUR_HEURISTIQUE 2
#define LOG_ALEA_NAME "data/logs/aleatoie.txt"
//1 Dfinition de la structure
typedef struct Joueur
{
// Pointeur vers la liste chane de pices destines au joueur
t_Piece * ancre;
// Liste chane de coin.
// A chaque maillon de cette liste s'accroche une liste chane de coups possibles depuis ce coin
t_Coin * possibilites;
// Variable pour dfinir le type de joueur (AI, alatoire, joueur humain)
char type;
// Variable qui dfinit la couleur des pices d'un joueur.
// Les constantes dfinissant les couleurs windows sont dans mainHeader.h
char couleur;
// Variables qui contiennent la position du curseur du joueur
// Le curseur correspond la case centrale de la pice
int curs_lig;
int curs_col;
// Variable qui indique si le joueur est encore capable de jouer o si toutes
// ses options sont bloques, auquel cas il faut passer son tour
char bloque;
// Variables qui indique la position de dpart du joueur
int start_lig;
int start_col;
// Score du joueur
int score;
}t_Joueur;
//2 Prototypes des fonctions
//Fonction qui initalise une structure de joueur avec sa liste chane de pices
// Recoit en entre :
// la structure d'un joueur
// un string contenant le nom du fichier o se trouve la liste des fichiers contenant les pices disponibles au joueur
void joueurInitialisation(t_Joueur * self, char pieceFile[TAILLE_FILE_NAME]);
// Fonction de desinitialisation d'un joueur (on parcourt la liste chaine de pices et on efface tout)
void joueurDesinit(t_Joueur * self);
// Fonction permettant de jouer la piece selectionne par l'ancre
// Renvoit la grille de la piece, et retire la piece de la liste chainee.
void playAncre(t_Joueur * self, char grid[I_TAB_PIECE][J_TAB_PIECE]);
// Fonction renvoyant un pointeur sur coup qui permet de jouer un coup alatoire
t_Coup * getAleaCoup(t_Joueur * self);
/// Fonctions elementaires
// Fonction permettant d'ajouter une piece vide dans la chaine juste apres l'ancre et de faire pointer l'ancre dessus
void addPieceAfter(t_Joueur * self, t_Piece * newPiece);
// Fonction permettant de n'effacer qu'un seule piece
void scrapAncre(t_Joueur * self);
// Fonction permettant d'avancer sur la liste chaine
void scrollToSuivant(t_Joueur * self);
// Fonction permettant de reculer sur la liste chaine
void scrollToPrecedent(t_Joueur * self);
// Fonction qui teste si le joueur est bloqu
char testBloc(t_Joueur * self);
// Fonction pour dsallouer la mmoire d'un coin
void scrapCoin(t_Joueur * self, int pos_i, int pos_j);
// Fonction pour ajouter un coin la liste chainee
void addCoin(t_Joueur * self, int pos_i, int pos_j);
// Fonction qui teste si un joueur peut encore jouer
// Renvoit 1 s'il est bloqu, 0 sinon
char isBloque(t_Joueur * self);
// Fonction charge de parcourir les coins du joueur afin de vider les coins vides
void clearEmptyCoins(t_Joueur * self);
int get_n_PossiblePlays(t_Joueur * self);
// Renvoit un pointeur vers la pice de numro n
t_Piece * get_piece_n(t_Joueur * self, int n);
#endif // JOUEUR_H_INCLUDED
|
C
|
#include <stdio.h>
int main()
{
printf("in linux ...\n");
int l_char=sizeof(char);
printf("char ----> %d\n",l_char);
int l_int=sizeof(int);
printf("int ----> %d\n",l_int);
int l_short=sizeof(short);
printf("short ----> %d\n",l_short);
int l_long=sizeof(long);
printf("long ----> %d\n",l_long);
int l_long_long_int=sizeof(long long int);
printf("long long int----> %d\n",l_long_long_int);
int l_long_long=sizeof(long long);
printf("long long ----> %d\n",l_long_long);
int l_float=sizeof(float);
printf("float ----> %d\n",l_float);
int l_double=sizeof(double);
printf("double ----> %d\n",l_double);
int l_ldouble=sizeof(long double);
printf("long double ----> %d\n",l_ldouble);
return 0;
}
|
C
|
/*
server is up and running because of my rookieness on C.
all the structures are well thought 'in my opinion'
my code needed to checked manually.
my server and clients are compiling however I couldn't manage to receive starting parameters from user I think
which is caused by my client_handler() function. If I had manage to do that it would run smoothly
*/
#include <ctype.h>
#include <signal.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <pthread.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <semaphore.h> // library includes
#define roomcapacity 4
#define chatroom_count 10
#define SERVERPORT 3205
#define SOCKETERROR (-1)
#define USERNAMELENGHT 20
#define RECEIVEINGMESGLENGHT 111
#define SENDINGMESGLENGHT 222 //defines to use
int totalconnnectedclient =0;
int createdroomcount =0;
int maxconnectedclient = 40;
// Global variables
int server_sockfd = 0, client_sockfd = 0;
int connectedusercount = 0;
typedef struct ClientNode {//client node which hold socket id as data ip address and nick name
int data;
char ip[16];
char name[31];
} ClientList;
ClientList *newNode(int sockfd, char* ip) {
ClientList *np = (ClientList *)malloc( sizeof(ClientList) );
np->data = sockfd;
strncpy(np->ip, ip, 16);
strncpy(np->name, "NULL", 5);
return np; // client list which all clients gets recorded when connecting
}
struct rooms // rooms get maximum 4 clients and they are in kind of client list so I can add them to the room to talk to each other.
{
int roomid;
ClientList *person1;
ClientList *person2;
ClientList *person3;
ClientList *person4;
};
struct rooms room[chatroom_count]; // creating 10 rooms which is defined
void clientdisplay(void *p_client) // client display test if they are noded correctly
{ClientList *np = (ClientList *)p_client;
printf("username:%s IPadress(%s)(%d)", np->name, np->ip, np->data);
printf("\n");
}
int check (int exp, const char *msg){ //socket error check function to reuse when needed
if(exp = SOCKETERROR)
perror(msg);
exit(1);
return exp;
}
//static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
//static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void list(void *p_client){ // room lister
char send_buffer[SENDINGMESGLENGHT] = {};
ClientList *np = (ClientList *)p_client;
int k;
for (k = 0; k < chatroom_count; k++)
{
if(room[k].roomid != NULL){
sprintf(send_buffer,"There is a room %x",room[k].roomid);
send_to_one_client(np,send_buffer);
}
}
}
void lobby(void *p_client){ //sending lobby text to client upon connection
char send_buffer[SENDINGMESGLENGHT] = {};
ClientList *np = (ClientList *)p_client;
sprintf(send_buffer,"1.)List All Rooms \n");
send_to_one_client(np,send_buffer);
sprintf(send_buffer,"2.)Create a room (without name or password) \n");
send_to_one_client(np,send_buffer);
sprintf(send_buffer,"3.)Enter a room from listed rooms \n");
send_to_one_client(np,send_buffer);
sprintf(send_buffer,"4.)quit to the main lobby (when in a room) \n");
send_to_one_client(np,send_buffer);
sprintf(send_buffer,"5.)WHO AM I?\n");
send_to_one_client(np,send_buffer);
sprintf(send_buffer,"6.)Quit\n");
send_to_one_client(np,send_buffer);
}
void enterRoom(int roomnumber,void *p_client){
int roomcountxd;
int leave_flag = 0;
char nickname[USERNAMELENGHT] = {};
char recv_buffer[RECEIVEINGMESGLENGHT] = {};
char send_buffer[SENDINGMESGLENGHT] = {};
ClientList *np = (ClientList *)p_client;
// Naming
if (recv(np->data, nickname, USERNAMELENGHT, 0) <= 0 || strlen(nickname) < 2 || strlen(nickname) >= USERNAMELENGHT-1) {
printf("%s didn't input name.\n", np->ip);
leave_flag = 1;
} else {
strncpy(np->name, nickname, USERNAMELENGHT);
printf("%s(%s)(%d) join the chatroom.\n", np->name, np->ip, np->data);
sprintf(send_buffer, "%s(%s) join the chatroom.", np->name, np->ip);
roomcountxd =1;
send_to_all_clients(roomcountxd,np, send_buffer);
}
// Conversation
while (1) { // talking in the room establishment
if (leave_flag) {
break;
}
int receive = recv(np->data, recv_buffer, RECEIVEINGMESGLENGHT, 0);
if (receive > 0) {
if (strlen(recv_buffer) == 0) {
continue;
}
sprintf(send_buffer, "%s:%s from %s", np->name, recv_buffer, np->ip);
} else if (receive == 0 || strcmp(recv_buffer, "exit") == 0) {
printf("%s(%s)(%d) leave the chatroom.\n", np->name, np->ip, np->data);
sprintf(send_buffer, "%s(%s) leave the chatroom.", np->name, np->ip);
leave_flag = 1;
} else {
printf("Fatal Error: -1\n");
leave_flag = 1;
}
roomcountxd =1;
send_to_all_clients(roomcountxd,np, send_buffer);
}
}
void quitRoom(void *p_client){ //quit room is to exit to maini lobby when doing that we compare and find exiting client and we null its place on room with client list *null pointer
ClientList *np = (ClientList *)p_client;
ClientList *null = newNode(-1, -1);
int i;
for (i = 0; i < chatroom_count; ++i)
{
ClientList *ax =(ClientList *)room[i].person1;
ClientList *bx =(ClientList *)room[i].person2;
ClientList *cx =(ClientList *)room[i].person3;
ClientList *dx =(ClientList *)room[i].person4;
if(np->data == ax->data){
room[i].person1 = null;
}
if(np->data == bx->data){
room[i].person2 = null;
}
if(np->data == cx->data){
room[i].person3 = null;
}
if(np->data == dx->data){
room[i].person4 = null;
}
}
client_handler(np);
}
void createRoom(void *p_client){ // create room which creates room if room count not exceeding limit and redirecting user to enterRoom
char send_buffer[SENDINGMESGLENGHT] = {};
ClientList *np = (ClientList *)p_client;
if(createdroomcount!=9)
{
ClientList *c = newNode(-1, -1);
room[createdroomcount].roomid = createdroomcount;
room[createdroomcount].person1 =(ClientList *) np;
room[createdroomcount].person2 =(ClientList *)c;
room[createdroomcount].person3 =(ClientList *) c;
room[createdroomcount].person4 =(ClientList *) c;
createdroomcount++;
}
else{
sprintf(send_buffer,"MAXIMUM ROOM COUNT REACHED CANNOT CREATE ROOM");
send_to_one_client(np,send_buffer);
}
enterRoom(createdroomcount,(void *)np);
}
void exitProgram(void *p_client){ //exiter with ctrlc
char send_buffer[SENDINGMESGLENGHT] = {};
ClientList *np = (ClientList *)p_client;
sprintf(send_buffer,"OUCH, did you hit Ctrl-C?\n");
send_to_one_client(np,send_buffer);
exit(0);
}
void whoamI(void *p_client){ //user credential function
char send_buffer[SENDINGMESGLENGHT] = {};
ClientList *np = (ClientList *)p_client;
sprintf(send_buffer,"You are %s(%s)(%d) .\n", np->name, np->ip, np->data);
send_to_one_client(np,send_buffer);
}
void send_to_all_clients(int roomid,void *p_client, char tmp_buffer[]) { //sending all the clients in the room when in a room and sending everyone but itself of client
ClientList *np = (ClientList *)p_client;
char send_buffer[SENDINGMESGLENGHT] = {};
ClientList *a =(ClientList *)room[roomid].person1;
ClientList *b =(ClientList *)room[roomid].person2;
ClientList *c =(ClientList *)room[roomid].person3;
ClientList *d =(ClientList *)room[roomid].person4;
if(np->data != a->data){
printf("Send to sockfd %d: \"%s\" \n", a->data, tmp_buffer);
send(a->data, tmp_buffer, SENDINGMESGLENGHT, 0);
}
if(np->data != b->data){
printf("Send to sockfd %d: \"%s\" \n", b->data, tmp_buffer);
send(b->data, tmp_buffer, SENDINGMESGLENGHT, 0);
}
if(np->data != c->data){
printf("Send to sockfd %d: \"%s\" \n", c->data, tmp_buffer);
send(c->data, tmp_buffer, SENDINGMESGLENGHT, 0);
}
if(np->data != d->data){
printf("Send to sockfd %d: \"%s\" \n", d->data, tmp_buffer);
send(d->data, tmp_buffer, SENDINGMESGLENGHT, 0);
}
}
void send_to_one_client(ClientList *np, char tmp_buffer[]) { // sending feedback from server to one client
char send_buffer[SENDINGMESGLENGHT] = {};
ClientList *xdad = (ClientList *)np;
printf("Send to sockfd %d: \"%s\" \n", xdad->data, tmp_buffer);
send(xdad->data, tmp_buffer, SENDINGMESGLENGHT, 0);
}
void client_handler(void *p_client) {
ClientList *np = (ClientList *)p_client;
listen(server_sockfd, 5);
char nickname[USERNAMELENGHT] = {};
char recv_buffer[RECEIVEINGMESGLENGHT] = {};
char send_buffer[SENDINGMESGLENGHT] = {};
lobby(np);
createRoom(np); // tring the manual creationg
int number =0;
int roomselect =-1;
sprintf(send_buffer,"Welcome to the chat server \n");
send_to_one_client(np,send_buffer);
int receive = recv(np->data, recv_buffer, RECEIVEINGMESGLENGHT, 0);
while(1){ //while loop to choose category of case switch
if (receive > 0) {
if (strlen(recv_buffer) == 0) {
continue;
}
}
else if (receive == 0 || strcmp(recv_buffer, "1") == 0) {
number =1;
break;
}
else if (receive == 0 || strcmp(recv_buffer, "2") == 0) {
number =2;
break;
}
else if (receive == 0 || strcmp(recv_buffer, "3") == 0) {
number =3;
break;
}else if (receive == 0 || strcmp(recv_buffer, "4") == 0) {
number =4;
break;
}else if (receive == 0 || strcmp(recv_buffer, "5") == 0) {
number =5;
break;
}else if (receive == 0 || strcmp(recv_buffer, "6") == 0) {
number =6;
break;
}
else{
sprintf(send_buffer,"try again please");
send_to_one_client(np,send_buffer);
}
}
while(1) // while to go to the functions and sending client infos to communicate back while in there
{
switch (number) {
case 1:
list(np);
break;
case 2:
createRoom(np);
break;
case 3:
enterRoom(roomselect, np);
break;
case 4:
quitRoom(np);
break;
case 5:
whoamI(np);
break;
case 6:
exitProgram(np);
break;
default:
sprintf(send_buffer,"Command not listed on up");
send_to_one_client(np,send_buffer);
break;
}
break;
}
}
int main()
{
// Create socket
server_sockfd = socket(AF_INET , SOCK_STREAM , 0);
if (server_sockfd == -1) {
printf("Fail to create a socket.");
exit(EXIT_FAILURE);
}
// Socket information
struct sockaddr_in server_info, client_info;
int s_addrlen = sizeof(server_info);
int c_addrlen = sizeof(client_info);
memset(&server_info, 0, s_addrlen);
memset(&client_info, 0, c_addrlen);
server_info.sin_family = PF_INET;
server_info.sin_addr.s_addr = INADDR_ANY;
server_info.sin_port = htons(SERVERPORT);// default connections and server port fix to 3205
// Bind and Listen
bind(server_sockfd, (struct sockaddr *)&server_info, s_addrlen);
listen(server_sockfd, 5);
// Print Server IP
getsockname(server_sockfd, (struct sockaddr*) &server_info, (socklen_t*) &s_addrlen);
printf("Start Server on: %s:%d\n", inet_ntoa(server_info.sin_addr), ntohs(server_info.sin_port));
while (1) {
client_sockfd = accept(server_sockfd, (struct sockaddr*) &client_info, (socklen_t*) &c_addrlen);
// Print Client IP
getpeername(client_sockfd, (struct sockaddr*) &client_info, (socklen_t*) &c_addrlen);
printf("Client %s:%d come in.\n", inet_ntoa(client_info.sin_addr), ntohs(client_info.sin_port));
// Append linked list for clients
ClientList *c = newNode(client_sockfd, inet_ntoa(client_info.sin_addr));
clientdisplay(c);
pthread_t id;
if (pthread_create(&id, NULL, (void *)client_handler, (void *)c) != 0) {
perror("Create pthread error!\n");
exit(EXIT_FAILURE);
}
}
return 0;
}
|
C
|
#include <stdio.h>
#include <conio.h>
int main()
{
float s;
float c;
printf("enter total amount of sales:");
scanf("%f", &s);
if (s < 5000)
{
c = s * 1 / 100;
printf("total commission amount is %f", c);
}
else if (s > 5000 && s < 8000)
{
c = s * 3 / 100;
printf("total commission amount is %f", c);
}
else if (s > 8000 && s < 11000)
{
c = s * 5 / 100;
printf("total commission amount is %f", c);
}
else
{ c = s * 10 / 100;
printf("total commission amount is %f", c);}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "LinkedList.h"
static Node* getNode(LinkedList* this, int nodeIndex);//consigue la dir de memoria del nodo. recibe la dir de memoria del primer elemento y el indice, devuelve la dir de memoria del indice
static int addNode(LinkedList* this, int nodeIndex,void* pElement);//carga un nodo con una direccion de memoria
/** \brief Crea un nuevo LinkedList en memoria de manera dinamica
*
* \param void
* \return LinkedList* Retorna (NULL) en el caso de no conseguir espacio en memoria
* o el puntero al espacio reservado
*/
LinkedList* ll_newLinkedList(void)
{
LinkedList* this;
this = (LinkedList*) malloc(sizeof(LinkedList));
if(this!=NULL)
{
this->size = 0;
this->pFirstNode = NULL;
}
return this;
}
/** \brief Retorna la cantidad de elementos de la lista
*
* \param this LinkedList* Puntero a la lista
* \return int Retorna (-1) si el puntero es NULL o la cantidad de elementos de la lista
*
*/
int ll_len(LinkedList* this)//es como si fuese un getter que accede al valor del campo
{
// int size;
int returnAux = -1;
if(this!=NULL)
{
returnAux = this->size;
}
return returnAux;
}
/** \brief Obtiene un nodo de la lista
*
* \param this LinkedList* Puntero a la lista
* \param index int Indice del nodo a obtener
* \return Node* Retorna (NULL) Error: si el puntero a la lista es NULL o (si el indice es menor a 0 o mayor al len de la lista)
(pElement) Si funciono correctamente
*
*/
static Node* getNode(LinkedList* this, int nodeIndex)
{
Node* pNode = NULL;
int contador=0;
if(this!=NULL && nodeIndex>=0 && nodeIndex<ll_len(this))//menor a ll_l(this) tiene que estar entre 0 y el tamao total que tiene
{
pNode=this->pFirstNode;//aca copio la dir de memoria del elemento 0 en pNode (primero vagon)
while(contador<nodeIndex)//si el index es cero, no se entra aca y devuelve 0, caso contrario entra aca y devuelve el ultimo antes del 0
{
pNode=pNode->pNextNode;//aca copio el dir de memoria del elemento que sigue (el vagon que sigue y sigue y asi)
contador++;
}
/*
for(pNode=this->pFirstNode;contador<nodeIndex;contador++)
{
pNode=pNode->pNextNode;
}*/
}
return pNode;
}
/** \brief Permite realizar el test de la funcion getNode la cual es privada
*
* \param this LinkedList* Puntero a la lista
* \param index int Indice del nodo a obtener
* \return Node* Retorna (NULL) Error: si el puntero a la lista es NULL o (si el indice es menor a 0 o mayor al len de la lista)
(pElement) Si funciono correctamente
*
*/
Node* test_getNode(LinkedList* this, int nodeIndex)
{
return getNode(this, nodeIndex);
}
/** \brief Agrega y enlaza un nuevo nodo a la lista
*
* \param this LinkedList* Puntero a la lista
* \param nodeIndex int Ubicacion donde se agregara el nuevo nodo
* \param pElement void* Puntero al elemento a ser contenido por el nuevo nodo
* \return int Retorna (-1) Error: si el puntero a la lista es NULL o (si el indice es menor a 0 o mayor al len de la lista)
( 0) Si funciono correctamente
*
*/
static int addNode(LinkedList* this, int nodeIndex,void* pElement)
{//recibe una locomotora, lista y una carga
//lo vagones se crean con un malloc
int returnAux = -1;
// Node* prev;
//Node* next;
Node* nuevoNodo= NULL;
Node* nodoAuxiliar=NULL;//esto es una dir de memoria, cuando la cargamos
if(this!=NULL && nodeIndex>=0 && nodeIndex<= ll_len(this))
{
nuevoNodo= (Node*) malloc(sizeof (Node));
if(nuevoNodo !=NULL)
{
nuevoNodo->pElement=pElement;//aca se carga el vagon con la direccion de memori de la informacion a la que apunta (se lo cargar)
if(nodeIndex==0)
{
//aca el nuevo nodo se engancha de la locomotora
nuevoNodo->pNextNode=this->pFirstNode;
this->pFirstNode= nuevoNodo;
}
else
{
//aca el nuevo nodo se engancha de un vagon
//el nuevo nodo apunta a el vagon donde se va a insertar
nodoAuxiliar=getNode(this,nodeIndex-1);
nuevoNodo->pNextNode=nodoAuxiliar->pNextNode;
nodoAuxiliar->pNextNode=nuevoNodo;
}
this->size++;
returnAux=0;
}
}
return returnAux;
}
/** \brief Permite realizar el test de la funcion addNode la cual es privada
*
* \param this LinkedList* Puntero a la lista
* \param nodeIndex int Ubicacion donde se agregara el nuevo nodo
* \param pElement void* Puntero al elemento a ser contenido por el nuevo nodo
* \return int Retorna (-1) Error: si el puntero a la lista es NULL o (si el indice es menor a 0 o mayor al len de la lista)
( 0) Si funciono correctamente
*
*/
int test_addNode(LinkedList* this, int nodeIndex,void* pElement)
{
return addNode(this,nodeIndex,pElement);
}
/** \brief Agrega un elemento a la lista
* \param pList LinkedList* Puntero a la lista
* \param pElement void* Puntero al elemento a ser agregado
* \return int Retorna (-1) Error: si el puntero a la lista es NULL
( 0) Si funciono correctamente
*
*/
//esta no sabe la ubicacion
int ll_add(LinkedList* this, void* pElement)
{//crea un nuevo vagon y el campo apunta al vago que creamos, y este nuevo vagon hay que agregarlo al tren
int returnAux = -1;
//int indice = 0;
//Node* actual;
if(this!=NULL)
{
if(addNode(this,ll_len(this),pElement)==0)
{
returnAux=0;
}
}
return returnAux;
}
// ******* OJO CORREGIR *******************
/** \brief Permite realizar el test de la funcion addNode la cual es privada
*
* \param this LinkedList* Puntero a la lista
* \param nodeIndex int Ubicacion del elemento a obtener
* \return void* Retorna (NULL) Error: si el puntero a la lista es NULL o (si el indice es menor a 0 o mayor al len de la lista)
(pElement) Si funciono correctamente
*
*/
//ll_get trae la ubicacion de la carga,
void* ll_get(LinkedList* this, int index)
{
void* returnAux = NULL;
Node* auxNode=NULL;
if(this!=NULL && index>=0 && index <ll_len(this))
{
auxNode=getNode(this,index);//si lo que trae es algo, ahi le asigno la carga
if(auxNode!=NULL)
{
returnAux=auxNode->pElement;
}
}
return returnAux;
}
/** \brief Modifica un elemento de la lista
*
* \param this LinkedList* Puntero a la lista
* \param nodeIndex int Ubicacion del elemento a modificar
* \param pElement void* Puntero al nuevo elemento
* \return int Retorna (-1) Error: si el puntero a la lista es NULL o (si el indice es menor a 0 o mayor al len de la lista)
( 0) Si funciono correctamente
*
*/
int ll_set(LinkedList* this, int index,void* pElement)
{
int returnAux = -1;
Node* actual;
//int cantidad;
if(this!=NULL && index >=0 && index < ll_len(this))
{
actual=getNode(this,index);
if(actual!=NULL)
{
actual->pElement=pElement;
returnAux=0;
}
}
return returnAux;
}
/** \brief Elimina un elemento de la lista
*
* \param this LinkedList* Puntero a la lista
* \param nodeIndex int Ubicacion del elemento a eliminar
* \return int Retorna (-1) Error: si el puntero a la lista es NULL o (si el indice es menor a 0 o mayor al len de la lista)
( 0) Si funciono correctamente
*
*/
int ll_remove(LinkedList* this,int index)
{
int returnAux = -1;
Node* actual;
//Node* next;
if(this!=NULL && index>=0 && index <ll_len(this))
{
actual=getNode(this,index);
if(index==0)
{
this->pFirstNode=actual->pNextNode;
}
else
{
getNode(this,index-1)->pNextNode=actual->pNextNode;
}
free(actual);
this->size--;
returnAux=0;
}
return returnAux;
}
/** \brief Elimina todos los elementos de la lista
*
* \param this LinkedList* Puntero a la lista
* \return int Retorna (-1) Error: si el puntero a la lista es NULL
( 0) Si funciono correctamente
*
*/
int ll_clear(LinkedList* this)
{
int returnAux = -1;
//Node* nodo;
if(this != NULL)
{
while(ll_len(this) != 0)//va actualizando el tamao hasta que vale cero, ahi rompe el bucle y sale
{
ll_remove(this,ll_len(this));//va borrando y actualizanado los indices
this->size--;
}
if(ll_len(this) == 0)
{
returnAux = 0;
}
}
return returnAux;
}
/** \brief Elimina todos los elementos de la lista y la lista
*
* \param this LinkedList* Puntero a la lista
* \return int Retorna (-1) Error: si el puntero a la lista es NULL
( 0) Si funciono correctamente
*
*/
int ll_deleteLinkedList(LinkedList* this)
{
int returnAux = -1;
if(this!=NULL)
{
if(!ll_clear(this))//si devuelve algo distinto de cero es falso y no entra
{
free(this);
returnAux=0;
}
}
return returnAux;
}
/** \brief Busca el indice de la primer ocurrencia del elemento pasado como parametro
*
* \param this LinkedList* Puntero a la lista
* \param pElement void* Puntero al elemento
* \return int Retorna (-1) Error: si el puntero a la lista es NULL
(indice del elemento) Si funciono correctamente
*
*/
int ll_indexOf(LinkedList* this, void* pElement)
{
int returnAux = -1;
if(this!=NULL)
{
int tam=ll_len(this);//asi se llama una sola vez a ll_len, genera mejor eficiencia
for(int i=0;i<tam;i++)
{
if(ll_get(this,i)==pElement)//aca devuelve el p element en la posicion i
{
returnAux=i;//la posicion del "vagon"
break;
}
}
}
return returnAux;
}
/** \brief Indica si la lista esta o no vacia
*
* \param this LinkedList* Puntero a la lista
* \return int Retorna (-1) Error: si el puntero a la lista es NULL
( 0) Si la lista NO esta vacia
( 1) Si la lista esta vacia
*
*/
int ll_isEmpty(LinkedList* this)
{
int returnAux = -1;
if(this != NULL)
{
returnAux = 1;//asi le hago la pre carga asi me ahorro el else
if( ll_len(this))
{
returnAux = 0;
}
//returnAux=ll_len(this)==0? 1: 0 ;
//variable=condicion ? valor en caso de la condicion sea verdadera: valor en caso de que sea falsa;
}
return returnAux;
}
/** \brief Inserta un nuevo elemento en la lista en la posicion indicada
*
* \param this LinkedList* Puntero a la lista
* \param nodeIndex int Ubicacion donde se agregara el nuevo elemento
* \param pElement void* Puntero al nuevo elemento
* \return int Retorna (-1) Error: si el puntero a la lista es NULL o (si el indice es menor a 0 o mayor al len de la lista)
( 0) Si funciono correctamente
*
*/
int ll_push(LinkedList* this, int index, void* pElement)
{
//int returnAux = -1;
return addNode(this,index,pElement);
//return returnAux;
}
/** \brief Elimina el elemento de la posicion indicada y retorna su puntero
*
* \param this LinkedList* Puntero a la lista
* \param nodeIndex int Ubicacion del elemento eliminar
* \return void* Retorna (NULL) Error: si el puntero a la lista es NULL o (si el indice es menor a 0 o mayor al len de la lista)
(pElement) Si funciono correctamente
*
*/
//aca te da el elemento pero tambien lo saca de la lista
void* ll_pop(LinkedList* this,int index)
{
void* returnAux = NULL;
if(this !=NULL && index>=0 && index < ll_len(this))
{
returnAux=ll_get(this,index);
if(ll_remove(this,index))
{
returnAux=NULL;
}
}
return returnAux;
}
/** \brief Determina si la lista contiene o no el elemento pasado como parametro
*
* \param this LinkedList* Puntero a la lista
* \param pElement void* Puntero del elemento a verificar
* \return int Retorna (-1) Error: si el puntero a la lista es NULL
( 1) Si contiene el elemento
( 0) si No contiene el elemento
*/
int ll_contains(LinkedList* this, void* pElement)
{
int returnAux = -1;
if(this!=NULL)
{
returnAux=0;
if(ll_indexOf(this,pElement)!=-1)
{
returnAux=1;
}
}
return returnAux;
}
/** \brief Determina si todos los elementos de la lista (this2)
estan contenidos en la lista (this)
*
* \param this LinkedList* Puntero a la lista
* \param this2 LinkedList* Puntero a la lista
* \return int Retorna (-1) Error: si alguno de los punteros a las listas son NULL
( 1) Si los elementos de (this2) estan contenidos en la lista (this)
( 0) si los elementos de (this2) NO estan contenidos en la lista (this)
*/
int ll_containsAll(LinkedList* this,LinkedList* this2)
{
int returnAux = -1;
int len;
void* aux;
if(this!=NULL && this2 !=NULL)
{
returnAux=1;
len=ll_len(this2);
for(int i=0;i<len;i++)
{
aux=ll_get(this2,i);
if(!ll_contains(this,aux))
{
returnAux=0;
break;
}
}
}
return returnAux;
}
/** \brief Crea y retorna una nueva lista con los elementos indicados
*
* \param pList LinkedList* Puntero a la lista
* \param from int Indice desde el cual se copian los elementos en la nueva lista
* \param to int Indice hasta el cual se copian los elementos en la nueva lista (no incluido)
* \return LinkedList* Retorna (NULL) Error: si el puntero a la listas es NULL
o (si el indice from es menor a 0 o mayor al len de la lista)
o (si el indice to es menor o igual a from o mayor al len de la lista)
(puntero a la nueva lista) Si ok
*/
LinkedList* ll_subList(LinkedList* this,int from,int to)
{
LinkedList* cloneArray = NULL;
if(this!=NULL && from>=0 && from<to && to<=ll_len(this) && to>from && from <ll_len(this))
{
cloneArray=ll_newLinkedList();
for( ;from<to;from++)
{
ll_add(cloneArray,ll_get(this,from));
}
}
return cloneArray;
}
/** \brief Crea y retorna una nueva lista con los elementos de la lista pasada como parametro
*
* \param pList LinkedList* Puntero a la lista
* \return LinkedList* Retorna (NULL) Error: si el puntero a la listas es NULL
(puntero a la nueva lista) Si ok
*/
LinkedList* ll_clone(LinkedList* this)
{
LinkedList* cloneArray = NULL;
if(this!=NULL)
{
return cloneArray=ll_subList(this,0,ll_len(this));
}
return cloneArray;
}
/** \brief Ordena los elementos de la lista utilizando la funcion criterio recibida como parametro
* \param pList LinkedList* Puntero a la lista
* \param pFunc (*pFunc) Puntero a la funcion criterio
* \param order int [1] Indica orden ascendente - [0] Indica orden descendente
* \return int Retorna (-1) Error: si el puntero a la listas es NULL
( 0) Si ok
*/
int ll_sort(LinkedList* this, int (*pFunc)(void*,void*), int order)
{
int returnAux =-1;
int tamanio;
void* pElementI;
void* pElementJ;
void* pElementAuxiliar;
if(this!= NULL && pFunc != NULL &&( order == 0 || order == 1))
{
tamanio = ll_len(this);
for(int i = 0; i<tamanio-1;i++)
{
for(int j = i+1; j<tamanio;j++)
{
pElementI = ll_get(this,i);
pElementJ = ll_get(this,j);
if(order == 1)
{
if(pFunc(pElementI,pElementJ))
{
pElementAuxiliar = pElementI;
pElementI = pElementJ;
pElementJ = pElementAuxiliar;
pElementI = ll_get(this,i);
}
}else
{
if(pFunc(pElementI,pElementJ)== -1)
{
pElementAuxiliar = ll_get(this,i);
ll_set(this,i,pElementJ);
ll_set(this,j,pElementAuxiliar);
}
}
}
returnAux = 0;
}
}
return returnAux;
}
|
C
|
#include "include/Vector2.h"
float Vec2Magnitude(Vector2* vector2){
return sqrt((vector2->x * vector2->x) + (vector2->y * vector2->y));
}
Vector2 Vec2Create(float x, float y){
Vector2 ret;
ret.x = x;
ret.y = y;
return ret;
}
Vector2* Vec2Allocate(float x, float y){
Vector2* ret = (Vector2*) malloc(sizeof(Vector2));
ret->x = x;
ret->y = y;
return ret;
}
void Vec2Free(Vector2* mem){
free(mem);
}
Vector2 Vec2Sub( Vector2* Lop, Vector2* Rop){
return Vec2Create(Lop->x - Rop->x, Lop->y - Rop->y);
}
Vector2 Vec2Add( Vector2* Lop, Vector2* Rop){
return Vec2Create(Lop->x + Rop->x, Lop->y + Rop->y);
}
Vector2 Vec2Mul( Vector2* Lop, Vector2* Rop){
return Vec2Create(Lop->x * Rop->x, Lop->y * Rop->y);
}
Vector2 Vec2Div( Vector2* Lop, Vector2* Rop){
return Vec2Create(Lop->x / Rop->x, Lop->y / Rop->y);
}
Vector2 Vec2Scale( Vector2* Lop, float scale){
return Vec2Create(Lop->x * scale, Lop->y * scale);
}
float Vec2Distance( Vector2* one, Vector2* two){
Vector2 relativePos = Vec2Sub(one, two);
return Vec2Magnitude(&relativePos);
}
float Vec2Dot( Vector2* one, Vector2* two){
return ((one->x * two->x) + (one->y * two->y));
}
void Vec2Normalize(Vector2* vec){
float mag = Vec2Magnitude(vec);
vec->x /= mag;
vec->y /= mag;
}
Vector2 Vec2GetNormalized( Vector2* vec){
Vector2 cpy = Vec2Copy(vec);
Vec2Normalize(&cpy);
return cpy;
}
Vector2 Vec2Copy( Vector2* vector){
Vector2 ret;
ret.x = vector->x;
ret.y = vector->y;
return ret;
}
|
C
|
#include <stdio.h>
#include <math.h>
#include "vector.h"
#include "constants.h"
#include "orientation.h"
// EulerOrientation creation
void euler_set(EulerOrientation * eo, double a, double b, double c) {
eo->alpha = a;
eo->beta = b;
eo->gamma = c;
}
EulerOrientation euler_make(double a, double b, double c) {
return (EulerOrientation){a, b, c};
}
EulerOrientation euler_make_from_quater(Quaternion const * q) {
double cosa = 1.0;
double cosb = (q->w * q->w + q->z * q->z - q->x * q->x - q->y * q->y) / (q->w * q->w + q->z * q->z + q->x * q->x + q->y * q->y);
if(cosb < -1.0) cosb = -1.0;
if(cosb > 1.0) cosb = 1.0;
double beta = acos(cosb);
double cosg = 1.0;
if(fabs(sin(beta)) > EPS) {
cosg = -2.0 * (q->z * q->x - q->y * q->w) / (q->w * q->w + q->z * q->z + q->x * q->x + q->y * q->y) / sin(beta);
cosa = 2.0 * (q->y * q->w + q->z * q->x) / (q->w * q->w + q->z * q->z + q->x * q->x + q->y * q->y) / sin(beta);
} else {
cosa = (q->w * q->w - q->x * q->x + q->y * q->y - q->z * q->z) / (q->w * q->w + q->z * q->z + q->x * q->x + q->y * q->y);
}
if(cosa < -1.0) cosa = -1.0;
if(cosg < -1.0) cosg = -1.0;
if(cosa > 1.0) cosa = 1.0;
if(cosg > 1.0) cosg = 1.0;
return euler_make(acos(cosa), acos(cosb), acos(cosg));
}
// EulerOrientation functions
void euler_print(EulerOrientation const * eo) {
printf("Euler angels: alpha = %lf beta = %lf gamma = %lf\n",
eo->alpha, eo->beta, eo->gamma);
}
// Quaternion creation
void quater_set(Quaternion * q, double w, double x, double y, double z) {
q->w = w;
q->x = x;
q->y = y;
q->z = z;
}
Quaternion quater_make(double w, double x, double y, double z) {
return (Quaternion) {w, x, y, z};
}
Quaternion quater_make_from_pair(double theta, Vector const * v) {
return (Quaternion) {cos(theta / 2.0),
sin(theta / 2.0) * v->x,
sin(theta / 2.0) * v->y,
sin(theta / 2.0) * v->z};
}
Quaternion quater_make_from_euler(EulerOrientation const * eo) {
Vector pz = {0.0, 0.0, 1.0};
Vector py = {0.0, 1.0, 0.0};
Quaternion qa = quater_make_from_pair(eo->alpha, &pz);
Quaternion qb = quater_make_from_pair(eo->beta, &py);
Quaternion qg = quater_make_from_pair(eo->gamma, &pz);
Quaternion q = quater_composition(&qa, &qb);
return quater_composition(&q, &qg);
}
// Quaternion functions
Quaternion quater_composition(Quaternion const * q1, Quaternion const * q2) {
return quater_make(q1->w * q2->w - q1->x * q2->x - q1->y * q2->y - q1->z * q2->z,
q1->w * q2->x + q2->w * q1->x + q1->y * q2->z - q2->y * q1->z,
q1->w * q2->y + q2->w * q1->y + q1->z * q2->x - q2->z * q1->x,
q1->w * q2->z + q2->w * q1->z + q1->x * q2->y - q1->y * q2->x);
}
void quater_print(Quaternion const * q) {
printf("Quaternion: w = %lf x = %lf y = %lf z = %lf\n", q->w, q->x, q->y, q->z);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "buyer.h"
// ---------------------------------------- Lista circular simplemente enlazada de compras
// inicializar lista circular de compras
BuyersList* initBuyersList(int count, int cartCount) {
BuyersList* list = (BuyersList*)malloc(sizeof(BuyersList));
list->root = NULL;
list->count = 0;
for(int i = cartCount; i < count + cartCount; i++) {
insertAfter(list, i, i);
}
return list;
}
// Crear nuevo nodo
BuyersNode* createBuyersNode(Client client, Cart cart) {
BuyersNode* tmp = (BuyersNode*)malloc(sizeof(BuyersNode));
tmp->client = client;
tmp->cart = cart;
tmp->next = NULL;
return tmp;
}
// Insertar nodo al final de la lista
void insertAfter(BuyersList* list, Client client, Cart cart) {
BuyersNode* tmp = createBuyersNode(client, cart);
if(!list->root) {
list->root = tmp;
tmp->next = tmp;
} else {
BuyersNode* node = list->root;
while(node->next != list->root) {
node = node->next;
}
node->next = tmp;
tmp->next = list->root;
}
list->count++;
}
// Eliminar cliente de la lista segun id
BuyersNode* removeBuyer(BuyersList* list, Client client) {
if(list->root) {
BuyersNode* node = list->root;
if(node->client == client) {
if(node->next != list->root) {
BuyersNode* tmp = node;
while(tmp->next != list->root) {
tmp = tmp->next;
}
list->root = node->next;
tmp->next = list->root;
node->next = NULL;
} else {
list->root = NULL;
node->next = NULL;
}
list->count--;
return node;
} else {
while(node->next != list->root) {
if(node->next->client == client) {
BuyersNode* tmp = node->next;
node->next = tmp->next;
tmp->next = NULL;
list->count--;
return tmp;
}
node = node->next;
}
//printf("Cliente %d, no encontrado.\n", client);
}
} else {
//printf("Listado vacio\n");
}
return NULL;
}
// Imprimir informacion de compradores en archivo .dot
void printBuyersListInDot(FILE* file, BuyersList* list) {
fprintf(file, "subgraph cluster_3 {\n");
fprintf(file, "label = \"Compradores\";\n\n");
if(list->root) {
BuyersNode* node = list->root;
do {
fprintf(file, "comprador%d[label=\"Cliente %d\\nCarrito %d\"];\n", node->client, node->client, node->cart);
node = node->next;
} while(node != list->root);
fprintf(file, "\n");
node = list->root;
do {
if(node->next != list->root) {
fprintf(file, "comprador%d -> comprador%d;\n", node->client, node->next->client);
} else {
fprintf(file, "comprador%d -> comprador%d;\n", node->client, node->next->client);
}
node = node->next;
} while(node != list->root);
} else {
fprintf(file, "comprador[label=\"Lista Vacia\"];\n");
}
fprintf(file, "}\n\n");
}
// Imprimir listado de compradores
void printBuyersList(BuyersList* list) {
if(!list->root) {
printf("Listado vacio\n");
} else{
BuyersNode* node = list->root;
printf("Listado de clientes:\n");
do {
printf("Cliente -> %d, Carrito -> %d\n", node->client, node->cart);
node = node->next;
}while(node != list->root);
//printf("Cliente -> %d, Carrito -> %d\n", node->client, node->cart);
}
printf("\n");
}
// ---------------------------------------- Cola de pagos
// Inicializar cola de pagos
PaymentQueue* initPaymentQueue(int count) {
PaymentQueue* queue = (PaymentQueue*)malloc(sizeof(PaymentQueue));
queue->top = NULL;
queue->bottom = NULL;
queue->count = 0;
for(int i = 0; i < count; i++) {
BuyersNode* node = createBuyersNode(i, i);
enqueuePaymentQueue(queue, node);
}
return queue;
}
// Encolar nuevo comprador a la cola de pagos
void enqueuePaymentQueue(PaymentQueue* queue, BuyersNode* node) {
if(!queue->top) {
queue->top = node;
queue->bottom = node;
} else {
queue->bottom->next = node;
queue->bottom = node;
}
queue->count++;
}
// Desencolar nodo de PaymentQueue
BuyersNode* dequeuePaymentQueue(PaymentQueue* queue) {
if(queue->top) {
BuyersNode* first = queue->top;
queue->top = first->next;
queue->count--;
if(!queue->top) {
queue->bottom = NULL;
}
return first;
}
return NULL;
}
// Imprimir cola de pagadores en archivo .dot
void printPaymentQueueInDot(FILE* file, PaymentQueue* queue) {
fprintf(file, "subgraph cluster_4 {\n");
fprintf(file, "label = \"Cola de Pagos\";\n\n");
if(queue->top) {
BuyersNode* node = queue->top;
do {
fprintf(file, "pago%d[label=\"Cliente %d\\nCarrito %d\"];\n", node->client, node->client, node->cart);
node = node->next;
} while(node);
fprintf(file, "\n");
node = queue->top;
while(node->next) {
fprintf(file, "pago%d -> pago%d;\n", node->client, node->next->client);
node = node->next;
}
} else {
fprintf(file, "pago[label=\"Cola Vacia\"];\n");
}
fprintf(file, "}\n\n");
}
// Imprimir cola de pagos
void printPaymentQueue(PaymentQueue* queue) {
if(queue->top) {
BuyersNode* node = queue->top;
printf("Compradores en cola de pago\n");
do {
printf("Comprador -> %d, Carrito -> %d\n", node->client, node->cart);
node = node->next;
}while(node);
}else {
printf("La cola de pagos esta vacia\n");
}
printf("\n");
}
|
C
|
#include <math.h>
float toradiansf(float x) {
return (float) x * (M_PI / 180.0);
}
#ifdef BUILD_TEST
int main() {
toradiansf(12.5);
return 0;
}
#endif
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strsplit_with.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jolabour <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/04/10 06:05:42 by jolabour #+# #+# */
/* Updated: 2019/04/12 08:55:05 by jolabour ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static size_t ft_word_len(const char *s, char c)
{
size_t i;
i = 1;
while (s[i] && s[i] != c)
++i;
return (i);
}
static size_t ft_word_count(const char *s, char c)
{
size_t words;
words = 0;
while (*s)
{
while (*s != c && *s)
++s;
++words;
while (*s == c && *s)
++s;
}
return (words - 1);
}
char **ft_strsplit_with(char const *s, char c)
{
char **split;
size_t i;
size_t j;
size_t words;
if (!s || !(split = (char **)ft_malloc_exit(sizeof(*split)
* ((words = ft_word_count(s, c)) + 1))))
return (NULL);
split[words] = NULL;
i = 0;
j = 0;
while (j < words)
{
while (s[i] && s[i + 1] == c)
i++;
split[j++] = ft_strsub(s, i, ft_word_len(s + i, c));
if (s[i])
i++;
while (s[i] && s[i] != c)
i++;
}
return (split);
}
|
C
|
/*
* rc_servo.c
*
* Created: 05/02/2017 17:32:18
* Author: Emile
*/
#include "rc_servo.h"
#include <asf.h>
#define RC_SERVO_TIMER TCD0
#define RC_SERVO_PORT PORTC
#define PERIOD (500 * 30)
#define MINIMUM (500 * 0.9)
#define RANGE (125 * 2.5)
typedef enum
{
STATE_LOW,
STATE_HIGH,
STATE_POS
} tState;
static uint8_t m_outputs;
static uint8_t m_pos[8];
static uint8_t m_timingArray[256];
static uint8_t m_arrayPos = 0;
static tState m_state = LOW;
static void timer_callback()
{
if( m_state == STATE_POS) // This must be very very fast
{
//Clear any outputs set in our array
RC_SERVO_PORT.OUTCLR = m_timingArray[m_arrayPos];
m_arrayPos++;
if( m_arrayPos == 0)
{
m_state = STATE_LOW; // Set to low state
RC_SERVO_PORT.OUTCLR = m_outputs;
// Setup timer to trigger in 20ms (low time)
tc_write_clock_source(&RC_SERVO_TIMER, TC_CLKSEL_DIV64_gc );
tc_write_period(&RC_SERVO_TIMER, PERIOD ); // ((32000000/1000)*20) / 64 = 10000
tc_write_count(&RC_SERVO_TIMER, 0);
tc_clear_overflow(&RC_SERVO_TIMER);
}
}
else if( m_state == STATE_LOW) // Low, go to High for 1ms state
{
RC_SERVO_PORT.OUTSET = m_outputs;
m_state = STATE_HIGH;
tc_write_period(&RC_SERVO_TIMER, MINIMUM ); // Minimum position
tc_write_count(&RC_SERVO_TIMER, 0);
tc_clear_overflow(&RC_SERVO_TIMER);
}
else if( m_state == STATE_HIGH) // Now go to the position state
{
m_state = STATE_POS;
tc_write_period(&RC_SERVO_TIMER, RANGE );
tc_write_clock_source(&RC_SERVO_TIMER, TC_CLKSEL_DIV1_gc);
tc_write_count(&RC_SERVO_TIMER, 0);
tc_clear_overflow(&RC_SERVO_TIMER);
}
}
#define DEFAULT 100
void rc_servo_init( uint8_t output )
{
m_outputs = output;
for( int n = 0; n < 256; n++ )
{
m_timingArray[n] = 0;
}
//Put all in the middle
m_timingArray[DEFAULT] = m_outputs;
for( int n = 0; n < 8; n++ )
{
m_pos[n] = DEFAULT;
}
tc_enable(&RC_SERVO_TIMER);
tc_set_overflow_interrupt_callback(&RC_SERVO_TIMER, timer_callback);
tc_set_wgm(&RC_SERVO_TIMER, TC_WG_NORMAL);
tc_set_overflow_interrupt_level(&RC_SERVO_TIMER, TC_INT_LVL_HI);
tc_write_clock_source(&RC_SERVO_TIMER, TC_CLKSEL_DIV64_gc );
tc_write_period(&RC_SERVO_TIMER, 10000 ); // ((32000000/1000)*20) / 64 = 10000
// Set outputs
RC_SERVO_PORT.DIRSET = m_outputs;
}
void rc_servo_setPos( uint8_t servo, uint8_t pos )
{
// Clear old position
m_timingArray[ m_pos[servo] ] &= ~(1<<servo);
//Set new position
m_timingArray[ pos ] |= (1<<servo);
//Save new position
m_pos[servo] = pos;
}
|
C
|
#include <stdio.h>
int max(int a, int b);
int main(int argc, char const *argv[])
{
int a = 3;
int b = 5;
printf("the max number is: %d\n", max(a, b));
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
#include <math.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
struct Student{
char Ime[100];
int OcjA;
int OcjB;
int OcjC;
int OcjD;
};
int q = 0;
int main() {
struct Student Studenti[4];
FILE *fp;
char c;
int n = 0; int brojac = 0; int flag = 0; int brocj = 0; int abc = 0;
char ime[100];
fp = fopen("c:\\temp\\ocjene.txt", "r");
if (fp == NULL) {
perror("Error in opening file");
return 0;
} do {
//printf("%s",Studenti[0].Ime);
c = fgetc(fp);
if (feof(fp)) {
break;
}
if(c != ','){
if(flag == 0){
if(c != '0' && c != '1' && c != '2' && c != '3' && c != '4' && c != '5'){
ime[brojac] = c;
brojac++;
}else {
strcpy(Studenti[brocj].Ime,ime);
brojac = 0;
int i = 0;
flag = 1;
int BRUpis = c-'0';
if(abc == 0){
Studenti[brocj].OcjA = BRUpis;
}
else if(abc == 1){
Studenti[brocj].OcjB = BRUpis;
}
else if(abc == 2){
Studenti[brocj].OcjC = BRUpis;
}
else {
Studenti[brocj].OcjD = BRUpis;
}
abc++;
}
}else{
if(c == '0' || c == '1' || c == '2' || c == '3' || c == '4' || c == '5'){
int BRUpis = c-'0';
if(abc == 0){
Studenti[brocj].OcjA = BRUpis;
}
else if(abc == 1){
Studenti[brocj].OcjB = BRUpis;
}
else if(abc == 2){
Studenti[brocj].OcjC = BRUpis;
}
else {
Studenti[brocj].OcjD = BRUpis;
}
abc++;
}else{
brocj++;
flag = 0;
ime[brojac] = c;
brojac++;
}
}
}
} while (1);
fclose(fp);
int Ocj[4] = {0};
int i = 0;
for(i = 0; i < 4; i++){
Ocj[i] += Studenti[i].OcjC;
printf("%d %d %d %d\n",Studenti[i].OcjA,Studenti[i].OcjB , Studenti[i].OcjC , Studenti[i].OcjD);
}
int max = 100;
for(i = 0; i < 4; i++){
if(max > Ocj[i])
max = Ocj[i];
}
for(i = 0; i < 4; i++){
if(max == Ocj[i])
printf("%s",Studenti[i].Ime);
}
getch();
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
int getal = 0;
printf("Verkoop van 28 april 2010\n");
printf("Geef het aantal bonnetjes: ");
scanf("%d", &getal);
double tmp = 0;
double som = 0;
for (int i = 0; i < getal; ++i) {
printf("Geef het bedrag van bon %d: ", i+1);
scanf("%lf",&tmp);
som+=tmp;
}
printf("\nDe totale omzet voor vandaag is %.2lf", som);
}
|
C
|
#ifndef DICO_INSTRUCT_H
#define DICO_INSTRUCT_H
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "Utils.h"
typedef struct
{
unsigned int func:6,
sa:5,
rd:5,
rt:5,
rs:5,
opcode:6;
} R;
typedef struct
{
unsigned int immediate:16,
rt:5,
rs:5,
opcode:6;
} I;
typedef struct
{
unsigned int target:26,
opcode:6;
} J;
typedef union
{
R rInst;
I iInst;
J jInst;
unsigned int intInst;
char code[4];
} BIT_FIELD;
typedef struct
{
char order[5];
char modificable[5];
char type;
} DETAILS_INSTRUCT;
typedef struct
{
char id[30];
char operands[3];
int hasPseudoInstruction;
int typeNumber;
BIT_FIELD bitField;
DETAILS_INSTRUCT details;
} INSTRUCTION;
/**
* @brief Contain the size of the instruction dictionary.
*
*/
extern int sizeDico;
/**
* @param file FILE* who contain the pointeur on the file that you want to us to construction the dictionary
* @param sizeDico int* to receive the size of the dictionary.
* @brief Allocate the instruction's dictionary.
* @return The allocated dictionary.
*
*/
INSTRUCTION* AllocateDico(FILE *file, int* sizeDico);
/**
* @param nameDicoFile char* which correspond to the file you want to open to initialize the dictionary.
* @brief Initialiaze the instruction's dictionary.
* @return The initialized dictionary.
*
*/
INSTRUCTION* InitializeDicoInstruct(char* nameDicoFile);
/**
* @param dictionary INSTRUCTION* which is a instructions' dictionary.
* @param instructionName char* which the instruction to find in the dictionary.
* @brief Find an instruction in the dictionary.
* @return The index of the instructionName in the dictionary or -1 if is not inside.
*
*/
int IndexInstruction(INSTRUCTION* dictionary, char *instructionName);
#endif
|
C
|
#ifndef __KERN_PROC_H__
#define __KERN_PROC_H__
#include <types.h>
#include <spinlock.h>
#include <frame.h>
#include <arch/context.h>
#include <arch/local.h>
/* == SCHEDULE CLASS INTERFACE ============================== */
typedef struct sched_node_s *sched_node_t;
typedef struct sched_node_s
{
struct sched_class_s *class;
struct
{
sched_node_t prev, next;
} rr;
} sched_node_s;
typedef struct runqueue_s *runqueue_t;
typedef struct runqueue_s
{
spinlock_s lock;
struct
{
sched_node_t node;
} idle;
struct
{
sched_node_t first;
} rr;
} runqueue_s;
/* Func in sched_class can be called only with rq->lock acquired */
typedef struct sched_class_s *sched_class_t;
typedef struct sched_class_s
{
void (*init)(runqueue_t rq);
void (*enqueue)(runqueue_t rq, sched_node_t node);
void (*dequeue)(runqueue_t rq, sched_node_t node);
sched_node_t (*pick)(runqueue_t rq);
} sched_class_s;
#define SCHED_CLASS_COUNT 2
#define SCHED_CLASS_IDLE 0
#define SCHED_CLASS_RR 1
sched_class_t sched_class[SCHED_CLASS_COUNT];
/* == PROC STRUCTURE ======================================== */
#define PROC_NAME_MAX 16
typedef struct proc_s *proc_t;
typedef struct proc_s
{
/* INIT DATA */
char name[PROC_NAME_MAX];
void (*entry)(void *arg);
void *priv;
/* KERNEL LEVEL SCHEDULER DATA */
spinlock_s lock;
int status;
int irq;
context_s ctx;
sched_node_s sched_node;
int type;
proc_t sched_prev_usr;
proc_t sched_prev;
} proc_s;
#define PROC_TYPE_FREE 0
#define PROC_TYPE_KERN 1
#define PROC_TYPE_USER_INIT 2
#define PROC_TYPE_USER 3
#define PROC_STATUS_RUNNABLE_WEAK 0
#define PROC_STATUS_RUNNABLE_STRONG 1
#define PROC_STATUS_WAITING 2
#define PROC_STATUS_ZOMBIE 3
PLS_PTR_DECLARE(proc_s, __current);
#define current (PLS(__current))
/* The initial value of __current */
extern proc_s __current_init;
int proc_init(proc_t proc, const char *name, int class, void (*entry)(void *arg), void *arg, void *stack_base, size_t stack_size);
void proc_wait_pretend(void);
void proc_wait_try(void);
void proc_notify(proc_t proc);
/* == SCHEDULER ============================================= */
int sched_sys_init(void);
int sched_sys_init_mp(void);
void schedule(void);
void yield();
#endif
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* read_flags.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mbraslav <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/03/06 18:38:31 by mbraslav #+# #+# */
/* Updated: 2017/03/06 18:38:33 by mbraslav ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_ls.h"
static int set_flag(t_opt *conf, char c)
{
if (c == 'R')
conf->rb = 1;
else if (c == 'a')
conf->a = 1;
else if (c == 'l')
conf->l = 1;
else if (c == 'r')
conf->r = 1;
else if (c == 't')
conf->t = 1;
else if (c == 'S')
conf->sb = 1;
else
return (0);
return (1);
}
t_opt *read_options(int argc, char **argv)
{
t_opt *conf;
int i;
int j;
if ((conf = (t_opt *)malloc(sizeof(t_opt))) == NULL)
return (NULL);
ft_memset(conf, 0, sizeof(t_opt));
i = 0;
while (++i <= argc - 1 && argv[i][0] == '-')
{
j = 0;
while (argv[i][++j])
{
if (!set_flag(conf, argv[i][j]))
{
ft_printf("ft_ls: illegal option -- %c\nusage: ft_ls [-Ralrt] \
[file ...]\n", argv[i][j]);
exit(1);
}
}
}
return (conf);
}
|
C
|
/* functions for manipulating the environment */
/* written by Eric R. Smith and placed in the public domain */
#include <stddef.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
int
putenv(const char *strng)
{
size_t idx;
const char **var;
const char *name;
size_t len = strlen(strng);
char **environ_ptr = _get_environ_ptr();
if (!environ_ptr) {
name = 0;
var = 0;
} else {
for (var = environ_ptr; (name = *var) != 0; var++) {
if (!strncmp(name, strng, len) && name[len] == '=')
break;
}
}
if (name) {
// replace old value
*var = strng;
return 0;
}
idx = (var - environ_ptr);
var = realloc( environ_ptr, (idx+2) * sizeof(char *) );
if (!var) {
return _seterror(ENOMEM);
}
var[idx] = strng;
var[idx+1] = 0;
_put_environ_ptr(var);
return 0;
}
|
C
|
#include "hw4.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
//#include "hw4.tab.h"
extern int courseLine;
extern int classLine;
extern int meetingLine;
char* copy(char* string){
char* cloned;
cloned = (char*)malloc(sizeof(char)*strlen(string));
return strcpy(cloned, string);}
void printTree ( TreeNode * tree_root) {
//printf("%d",tree_root != NULL);
if ( tree_root !=NULL) {
if( tree_root->thisNodeType==PROG)
{
printTree( tree_root->exprNodePtr->prog.firstChild);
}
else if( tree_root->thisNodeType==ELEMENTLIST1)
{
printTree(tree_root->exprNodePtr->elementlist1.firstChild);
}
else if( tree_root->thisNodeType==ELEMENTLIST2)
{
if(tree_root->exprNodePtr->elementlist2.firstChild->exprNodePtr->elm.thirdChild->thisNodeType == ENDCONSTRAINTNODE)
{
printTree( tree_root->exprNodePtr->elementlist2.secondChild);
printTree( tree_root->exprNodePtr->elementlist2.firstChild);
}
else {
printTree( tree_root->exprNodePtr->elementlist2.firstChild);
printTree( tree_root->exprNodePtr->elementlist2.secondChild);
}
}
else if( tree_root->thisNodeType==ELM)
{
printTree( tree_root->exprNodePtr->elm.firstChild);
printTree( tree_root->exprNodePtr->elm.secondChild);
printTree( tree_root->exprNodePtr->elm.thirdChild);
}
else if( tree_root->thisNodeType==BEGINCOURSE)
{
//if(tree_root->exprNodePtr->begincourse.thirdChild->exprNodePtr->courseattrlist_1.name==1)
//printf("%s",tree_root->exprNodePtr->begincourse.thirdChild->exprNodePtr->courseattrlist_1.code);
//printf("%s",tree_root->exprNodePtr->begincourse.thirdChild->exprNodePtr->courseattrlist_1.name);
//printf("%s",tree_root->exprNodePtr->begincourse.thirdChild->exprNodePtr->courseattrlist_1.type);
printf("%s", tree_root->exprNodePtr->begincourse.t1);
printf("%s", tree_root->exprNodePtr->begincourse.t2);
printTree( tree_root->exprNodePtr->begincourse.thirdChild);
printf("%s\n", tree_root->exprNodePtr->begincourse.t4);
}
else if( tree_root->thisNodeType==ENDCOURSE)
{
printf("%s", tree_root->exprNodePtr->endcourse.t1);
printf("%s", tree_root->exprNodePtr->endcourse.t2);
printf( "%s\n", tree_root->exprNodePtr->endcourse.t3);
}
else if( tree_root->thisNodeType==COURSEATTRLIST_1)
{
printTree( tree_root->exprNodePtr->courseattrlist_1.firstChild);
}
else if( tree_root->thisNodeType==COURSEATTRLIST_2)
{
printTree( tree_root->exprNodePtr->courseattrlist_2.firstChild);
printTree( tree_root->exprNodePtr->courseattrlist_2.secondChild);
}
else if( tree_root->thisNodeType==COURSEATTR)
{
printf(" %s", tree_root->exprNodePtr->courseattr.token);
printf("%s", tree_root->exprNodePtr->courseattr.code);
printf("%s",tree_root->exprNodePtr->courseattr.name);
printf("%s",tree_root->exprNodePtr->courseattr.type);
}
else if( tree_root->thisNodeType==CLASSLIST1)
{
printTree( tree_root->exprNodePtr->classlist1.firstChild);
}
else if( tree_root->thisNodeType==CLASSLIST2)
{
printTree( tree_root->exprNodePtr->classlist2.firstChild);
printTree( tree_root->exprNodePtr->classlist2.secondChild);
}
else if( tree_root->thisNodeType==CLASSNODE)
{
printTree( tree_root->exprNodePtr->classnode.firstChild);
printTree( tree_root->exprNodePtr->classnode.secondChild);
printTree( tree_root->exprNodePtr->classnode.thirdChild);
printTree( tree_root->exprNodePtr->classnode.forthChild);
printTree( tree_root->exprNodePtr->classnode.fiftChild);
}
else if( tree_root->thisNodeType==BEGINCLASSNODE)
{
printf("\t%s", tree_root->exprNodePtr->beginclassnode.t1);
printf("%s", tree_root->exprNodePtr->beginclassnode.t2);
}
else if( tree_root->thisNodeType==ENDCLASSNODE)
{
printf("%s\n", tree_root->exprNodePtr->endclassnode.t1);
}
else if( tree_root->thisNodeType==CLOSECLASSNODE)
{
printf("\t%s", tree_root->exprNodePtr->closeclassnode.t1);
printf("%s", tree_root->exprNodePtr->closeclassnode.t2);
printf("%s\n", tree_root->exprNodePtr->closeclassnode.t3);
}
else if( tree_root->thisNodeType==CLASSATTRLISTNODE1)
{
printTree( tree_root->exprNodePtr->classattrlistnode1.firstChild);
}
else if( tree_root->thisNodeType==CLASSATTRLISTNODE2)
{
printTree( tree_root->exprNodePtr->classattrlistnode2.firstChild);
printTree( tree_root->exprNodePtr->classattrlistnode2.secondChild);
}
else if( tree_root->thisNodeType==CLASSATTRNODE)
{
printf(" %s", tree_root->exprNodePtr->classattrnode.token);
printf("%s", tree_root->exprNodePtr->classattrnode.section);
printf("%s", tree_root->exprNodePtr->classattrnode.instructor);
printf("%s", tree_root->exprNodePtr->classattrnode.crn);
printf("%s", tree_root->exprNodePtr->classattrnode.capacity);
}
else if( tree_root->thisNodeType==MEETINGLISTNODE1)
{
printTree( tree_root->exprNodePtr->meetinglistnode1.firstChild);
}
else if( tree_root->thisNodeType==MEETINGLISTNODE2)
{
printTree( tree_root->exprNodePtr->meetinglistnode2.firstChild);
printTree( tree_root->exprNodePtr->meetinglistnode2.secondChild);
}
else if( tree_root->thisNodeType==MEETINGNODE)
{
printTree( tree_root->exprNodePtr->meetingnode.firstChild);
printTree( tree_root->exprNodePtr->meetingnode.secondChild);
printTree( tree_root->exprNodePtr->meetingnode.thirdChild);
//printTree( tree_root->exprNodePtr->meetingnode.forthChild);
}
else if( tree_root->thisNodeType==BEGINMEETINGNODE)
{
printf("\t\t%s", tree_root->exprNodePtr->beginmeetingnode.t1);
printf("%s", tree_root->exprNodePtr->beginmeetingnode.t2);
}
else if( tree_root->thisNodeType==ENDMEETINGNODE)
{
printf("%s\n", tree_root->exprNodePtr->endmeetingnode.t1);
}
else if( tree_root->thisNodeType==MEETINGATTRLISTNODE1)
{
printTree( tree_root->exprNodePtr->meetingattrlistnode1.firstChild);
}
else if( tree_root->thisNodeType==MEETINGATTRLISTNODE2)
{
printTree( tree_root->exprNodePtr->meetingattrlistnode2.firstChild);
printTree( tree_root->exprNodePtr->meetingattrlistnode2.secondChild);
}
/*else if( tree_root->thisNodeType==MEETINGNODE)
{
printTree( tree_root->exprNodePtr->meetingnode.firstChild);
printTree( tree_root->exprNodePtr->meetingnode.secondChild);
printTree( tree_root->exprNodePtr->meetingnode.thirdChild);
printTree( tree_root->exprNodePtr->meetingnode.forthChild);
}*/
/*
else if( tree_root->thisNodeType==BEGINMEETINGNODE)
{
printf( "%s", tree_root->exprNodePtr->beginmeetingnode.t1);
printf("%s", tree_root->exprNodePtr->beginmeetingnode.t2);
}*/
/*
else if( tree_root->thisNodeType==ENDMEETINGNODE)
{
printf( tree_root->exprNodePtr->endmeetingnode.t1);
}*/
/*
else if( tree_root->thisNodeType==MEETINGATTRLISTNODE1)
{
printTree( tree_root->exprNodePtr->meetingattrlistnode1.firstChild);
}*/
/*
else if( tree_root->thisNodeType==MEETINGATTRLISTNODE2)
{
printTree( tree_root->exprNodePtr->meetingattrlistnode2.firstChild);
printTree( tree_root->exprNodePtr->meetingattrlistnode2.secondChild);
}*/
else if( tree_root->thisNodeType==MEETINGATTRNODE)
{
printf(" %s", tree_root->exprNodePtr->meetingattrnode.tday);
printTree(tree_root->exprNodePtr->meetingattrnode.day);
printf("%s", tree_root->exprNodePtr->meetingattrnode.time);
printf("%s", tree_root->exprNodePtr->meetingattrnode.end_time);
}
else if( tree_root->thisNodeType==DAYNODE)
{
printf("%s", tree_root->exprNodePtr->daynode.day);
}
else if( tree_root->thisNodeType==BEGINCONSTRAINTNODE)
{
printf("%s", tree_root->exprNodePtr->beginconstraintnode.t1);
printf("%s", tree_root->exprNodePtr->beginconstraintnode.t2);
printf("%s\n", tree_root->exprNodePtr->beginconstraintnode.t3);
}
else if( tree_root->thisNodeType==ENDCONSTRAINTNODE)
{
printf("%s", tree_root->exprNodePtr->endconstraintnode.t1);
printf("%s", tree_root->exprNodePtr->endconstraintnode.t2);
printf("%s\n", tree_root->exprNodePtr->endconstraintnode.t3);
}
else if( tree_root->thisNodeType==ITEMLISTNODE1)
{
printTree( tree_root->exprNodePtr->itemlistnode1.firstChild);
}
else if( tree_root->thisNodeType==ITEMLISTNODE2)
{
printTree( tree_root->exprNodePtr->itemlistnode2.firstChild);
printTree( tree_root->exprNodePtr->itemlistnode2.secondChild);
}
else if( tree_root->thisNodeType==ITEMNODE)
{
printTree( tree_root->exprNodePtr->itemnode.firstChild);
printTree( tree_root->exprNodePtr->itemnode.secondChild);
printTree( tree_root->exprNodePtr->itemnode.thirdChild);
}
else if( tree_root->thisNodeType==BEGINITEMNODE)
{
printf("\t%s", tree_root->exprNodePtr->beginitemnode.t1);
printf("%s", tree_root->exprNodePtr->beginitemnode.t2);
}
else if( tree_root->thisNodeType==ENDITEMNODE)
{
printf("%s\n", tree_root->exprNodePtr->enditemnode.t1);
}
else if( tree_root->thisNodeType==ITEMATTRNODE)
{
printf(" %s", tree_root->exprNodePtr->itemattrnode.token);
printf("%s", tree_root->exprNodePtr->itemattrnode.code);
printf("%s", tree_root->exprNodePtr->itemattrnode.crn);
}
}
}
TreeNode * mkprogNode ( TreeNode *first) {
TreeNode * ret = (TreeNode *)malloc (sizeof(TreeNode));
ret->thisNodeType = PROG;
ret->exprNodePtr = (ExprNode *)malloc (sizeof(ExprNode));
ret->exprNodePtr->prog.firstChild = first;
return (ret);
}
TreeNode * mkelementlistNode_c ( TreeNode *first) {
TreeNode * ret = (TreeNode *)malloc (sizeof(TreeNode));
ret->thisNodeType = ELEMENTLIST1;
ret->exprNodePtr = (ExprNode *)malloc (sizeof(ExprNode));
ret->exprNodePtr->elementlist1.firstChild = first;
return (ret);
}
TreeNode * mkelementlistNode_cc ( TreeNode *first,TreeNode *second) {
TreeNode * ret = (TreeNode *)malloc (sizeof(TreeNode));
ret->thisNodeType = ELEMENTLIST2;
ret->exprNodePtr = (ExprNode *)malloc (sizeof(ExprNode));
ret->exprNodePtr->elementlist2.firstChild = first;
ret->exprNodePtr->elementlist2.secondChild = second;
return (ret);
}
TreeNode * mkelementNode( TreeNode *first,TreeNode *second,TreeNode* third) {
TreeNode * ret = (TreeNode *)malloc (sizeof(TreeNode));
ret->thisNodeType = ELM;
ret->exprNodePtr = (ExprNode *)malloc (sizeof(ExprNode));
ret->exprNodePtr->elm.firstChild = first;
ret->exprNodePtr->elm.secondChild = second;
ret->exprNodePtr->elm.thirdChild = third;
return (ret);
}
TreeNode * mkbegincourseNode( char *t1,char *t2,TreeNode* third ,char * t4) {
TreeNode * ret = (TreeNode *)malloc (sizeof(TreeNode));
ret->thisNodeType = BEGINCOURSE;
ret->exprNodePtr = (ExprNode *)malloc (sizeof(ExprNode));
ret->exprNodePtr->begincourse.t1 = t1;
ret->exprNodePtr->begincourse.t2 = t2;
ret->exprNodePtr->begincourse.thirdChild = third;
ret->exprNodePtr->begincourse.t4 = t4;
if(third->exprNodePtr->courseattrlist_1.code >= 1){
printf("ERROR: course element at line %d has %d occurrences of code\n", courseLine,third->exprNodePtr->courseattrlist_1.code);
}
if(third->exprNodePtr->courseattrlist_1.name >= 1){
printf("ERROR: course element at line %d has %d occurrences of name\n", courseLine,third->exprNodePtr->courseattrlist_1.name);
}
if(third->exprNodePtr->courseattrlist_1.type >=1){
printf("ERROR: course element at line %d has %d occurrences of type\n", courseLine,third->exprNodePtr->courseattrlist_1.type);
}
return (ret);
}
TreeNode * mkendcourseNode( char * t1,char *t2,char * t3 ) {
TreeNode * ret = (TreeNode *)malloc (sizeof(TreeNode));
ret->thisNodeType = ENDCOURSE;
ret->exprNodePtr = (ExprNode *)malloc (sizeof(ExprNode));
ret->exprNodePtr->endcourse.t1 = t1;
ret->exprNodePtr->endcourse.t2 = t2;
ret->exprNodePtr->endcourse.t3 = t3;
return (ret);
}
TreeNode * mkcourseattrlistNode_1( TreeNode *first) {
TreeNode * ret = (TreeNode *)malloc (sizeof(TreeNode));
ret->thisNodeType = COURSEATTRLIST_1;
ret->exprNodePtr = (ExprNode *)malloc (sizeof(ExprNode));
ret->exprNodePtr->courseattrlist_1.firstChild = first;
ret->exprNodePtr->courseattrlist_1.code=0+ret->exprNodePtr->courseattrlist_1.firstChild->exprNodePtr->courseattr.code_num;
ret->exprNodePtr->courseattrlist_1.name=0+ret->exprNodePtr->courseattrlist_1.firstChild->exprNodePtr->courseattr.name_num;
ret->exprNodePtr->courseattrlist_1.type=0+ret->exprNodePtr->courseattrlist_1.firstChild->exprNodePtr->courseattr.type_num;
//ok
return (ret);
}
TreeNode * mkcourseattrlistNode_2 ( TreeNode *first,TreeNode *second) {
TreeNode * ret = (TreeNode *)malloc (sizeof(TreeNode));
ret->thisNodeType = COURSEATTRLIST_2;
ret->exprNodePtr = (ExprNode *)malloc (sizeof(ExprNode));
ret->exprNodePtr->courseattrlist_2.firstChild = first;
ret->exprNodePtr->courseattrlist_2.secondChild = second;
ret->exprNodePtr->courseattrlist_2.code=ret->exprNodePtr->courseattrlist_2.firstChild->exprNodePtr->courseattrlist_1.code + ret->exprNodePtr->courseattrlist_2.secondChild->exprNodePtr->courseattrlist_2.code;
ret->exprNodePtr->courseattrlist_2.name=ret->exprNodePtr->courseattrlist_2.firstChild->exprNodePtr->courseattrlist_1.name + ret->exprNodePtr->courseattrlist_2.secondChild->exprNodePtr->courseattrlist_2.name;
ret->exprNodePtr->courseattrlist_2.type=ret->exprNodePtr->courseattrlist_2.firstChild->exprNodePtr->courseattrlist_1.type + ret->exprNodePtr->courseattrlist_2.secondChild->exprNodePtr->courseattrlist_2.type;
//ret->exprNodePtr->courseattrlist_2.name=ret->exprNodePtr->courseattrlist_2.firstChild->exprNodePtr->courseattrlist_1.name + ret->exprNodePtr->courseattrlist_2.name;
//ret->exprNodePtr->courseattrlist_2.type=ret->exprNodePtr->courseattrlist_2.firstChild->exprNodePtr->courseattrlist_1.type + ret->exprNodePtr->courseattrlist_2.type;
//printf("%s",ret->exprNodePtr->courseattrlist_2.code);
//printf("%s",ret->exprNodePtr->courseattrlist_2.name);
return (ret);
}
TreeNode * mkcourseAttrNode ( char* token,char *c ,char*n, char*t) {
TreeNode * ret = (TreeNode *)malloc (sizeof(TreeNode));
ret->thisNodeType = COURSEATTR;
ret->exprNodePtr = (ExprNode *)malloc (sizeof(ExprNode));
ret->exprNodePtr->courseattr.token = token;
ret->exprNodePtr->courseattr.code = c;
ret->exprNodePtr->courseattr.name = n;
ret->exprNodePtr->courseattr.type = t;
if(c!=""){
ret->exprNodePtr->courseattr.code_num =1;
ret->exprNodePtr->courseattr.name_num =0;
ret->exprNodePtr->courseattr.type_num =0;
}
else if(n!=""){
ret->exprNodePtr->courseattr.code_num =0;
ret->exprNodePtr->courseattr.name_num =1;
ret->exprNodePtr->courseattr.type_num =0;
}
else if(t!=""){
ret->exprNodePtr->courseattr.code_num =0;
ret->exprNodePtr->courseattr.name_num =0;
ret->exprNodePtr->courseattr.type_num =1;
}
//printf("%s",ret->exprNodePtr->courseattr.code_num );
//printf("%s",ret->exprNodePtr->courseattr.name_num );
//printf("%s",ret->exprNodePtr->courseattr.type_num );
return (ret);
}
TreeNode * mkclassListNode1( TreeNode *first) {
TreeNode * ret = (TreeNode *)malloc (sizeof(TreeNode));
ret->thisNodeType = CLASSLIST1;
ret->exprNodePtr = (ExprNode *)malloc (sizeof(ExprNode));
ret->exprNodePtr->classlist1.firstChild = first;
return (ret);
}
TreeNode * mkclassListNode2 ( TreeNode *first,TreeNode *second) {
TreeNode * ret = (TreeNode *)malloc (sizeof(TreeNode));
ret->thisNodeType = CLASSLIST2;
ret->exprNodePtr = (ExprNode *)malloc (sizeof(ExprNode));
ret->exprNodePtr->classlist2.firstChild = first;
ret->exprNodePtr->classlist2.secondChild = second;
return (ret);
}
TreeNode * mkclassNode( TreeNode *first,TreeNode *second,TreeNode* third ,TreeNode*forth , TreeNode*fift) {
TreeNode * ret = (TreeNode *)malloc (sizeof(TreeNode));
ret->thisNodeType = CLASSNODE;
ret->exprNodePtr = (ExprNode *)malloc (sizeof(ExprNode));
ret->exprNodePtr->classnode.firstChild = first;
ret->exprNodePtr->classnode.secondChild = second;
ret->exprNodePtr->classnode.thirdChild = third;
ret->exprNodePtr->classnode.forthChild = forth;
ret->exprNodePtr->classnode.fiftChild = fift;
if(second->exprNodePtr->classattrlistnode1.section != 1){
printf("ERROR: course element at line %d has %d occurrences of printf("ERROR: course element at line %d has %d occurrences of code\n", classLine,second->exprNodePtr->classattrlistnode1.section);
\n", classLine,second->exprNodePtr->classattrlistnode1.section);
}
if(second->exprNodePtr->classattrlistnode1.instructor != 1){
printf("ERROR: course element at line %d has %d occurrences of instructor\n", classLine,second->exprNodePtr->classattrlistnode1.instructor);
}
if(second->exprNodePtr->classattrlistnode1.crn !=1){
printf("ERROR: course element at line %d has %d occurrences of crn\n", classLine,second->exprNodePtr->classattrlistnode1.crn);
}
if(second->exprNodePtr->classattrlistnode1.capacity !=1){
printf("ERROR: course element at line %d has %d occurrences of capacity\n", classLine,second->exprNodePtr->classattrlistnode1.capacity);
}
return (ret);
}
TreeNode * mkbeginclassNode( char *t1,char * t2) {
TreeNode * ret = (TreeNode *)malloc (sizeof(TreeNode));
ret->thisNodeType = BEGINCLASSNODE;
ret->exprNodePtr = (ExprNode *)malloc (sizeof(ExprNode));
ret->exprNodePtr->beginclassnode.t1 = t1;
ret->exprNodePtr->beginclassnode.t2 = t2;
return (ret);
}
TreeNode * mkendclassNode( char *t1) {
TreeNode * ret = (TreeNode *)malloc (sizeof(TreeNode));
ret->thisNodeType = ENDCLASSNODE;
ret->exprNodePtr = (ExprNode *)malloc (sizeof(ExprNode));
ret->exprNodePtr->endclassnode.t1 = t1;
return (ret);
}
TreeNode * mkcloseclassNode( char * t1,char * t2, char * t3) {
TreeNode * ret = (TreeNode *)malloc (sizeof(TreeNode));
ret->thisNodeType = CLOSECLASSNODE;
ret->exprNodePtr = (ExprNode *)malloc (sizeof(ExprNode));
ret->exprNodePtr->closeclassnode.t1 = t1;
ret->exprNodePtr->closeclassnode.t2 = t2;
ret->exprNodePtr->closeclassnode.t3 = t3;
return (ret);
}
TreeNode * mkclassattrlistNode1( TreeNode *first) {
TreeNode * ret = (TreeNode *)malloc (sizeof(TreeNode));
ret->thisNodeType = CLASSATTRLISTNODE1;
ret->exprNodePtr = (ExprNode *)malloc (sizeof(ExprNode));
ret->exprNodePtr->classattrlistnode1.firstChild = first;
ret->exprNodePtr->classattrlistnode1.section=0+ret->exprNodePtr->classattrlistnode1.firstChild->exprNodePtr->classattrnode.section_num;
ret->exprNodePtr->classattrlistnode1.instructor=0+ret->exprNodePtr->classattrlistnode1.firstChild->exprNodePtr->classattrnode.instructor_num;
ret->exprNodePtr->classattrlistnode1.crn=0+ret->exprNodePtr->classattrlistnode1.firstChild->exprNodePtr->classattrnode.crn_num;
ret->exprNodePtr->classattrlistnode1.capacity=0+ret->exprNodePtr->classattrlistnode1.firstChild->exprNodePtr->classattrnode.capacity_num;
return (ret);
}
TreeNode * mkclassattrlistNode2( TreeNode *first,TreeNode * second) {
TreeNode * ret = (TreeNode *)malloc (sizeof(TreeNode));
ret->thisNodeType = CLASSATTRLISTNODE2;
ret->exprNodePtr = (ExprNode *)malloc (sizeof(ExprNode));
ret->exprNodePtr->classattrlistnode2.firstChild = first;
ret->exprNodePtr->classattrlistnode2.secondChild =second;
ret->exprNodePtr->classattrlistnode2.section=ret->exprNodePtr->classattrlistnode2.firstChild->exprNodePtr->classattrlistnode1.section + ret->exprNodePtr->classattrlistnode2.secondChild->exprNodePtr->classattrlistnode2.section;
ret->exprNodePtr->classattrlistnode2.instructor=ret->exprNodePtr->classattrlistnode2.firstChild->exprNodePtr->classattrlistnode1.instructor + ret->exprNodePtr->classattrlistnode2.secondChild->exprNodePtr->classattrlistnode2.instructor;
ret->exprNodePtr->classattrlistnode2.crn=ret->exprNodePtr->classattrlistnode2.firstChild->exprNodePtr->classattrlistnode1.crn + ret->exprNodePtr->classattrlistnode2.secondChild->exprNodePtr->classattrlistnode2.crn;
ret->exprNodePtr->classattrlistnode2.capacity=ret->exprNodePtr->classattrlistnode2.firstChild->exprNodePtr->classattrlistnode1.capacity + ret->exprNodePtr->classattrlistnode2.secondChild->exprNodePtr->classattrlistnode2.capacity;
return (ret);
}
TreeNode * mkclassattrNode ( char* token, char *sec ,char* inst,char*crn,char*cap) {
TreeNode * ret = (TreeNode *)malloc (sizeof(TreeNode));
ret->thisNodeType = CLASSATTRNODE;
ret->exprNodePtr = (ExprNode *)malloc (sizeof(ExprNode));
ret->exprNodePtr->classattrnode.token = token;
ret->exprNodePtr->classattrnode.section = sec;
ret->exprNodePtr->classattrnode.instructor = inst;
ret->exprNodePtr->classattrnode.crn = crn;
ret->exprNodePtr->classattrnode.capacity = cap;
if(sec!=""){
ret->exprNodePtr->classattrnode.section_num =1;
ret->exprNodePtr->classattrnode.instructor_num =0;
ret->exprNodePtr->classattrnode.crn_num =0;
ret->exprNodePtr->classattrnode.capacity_num =0;
}
else if(inst!=""){
ret->exprNodePtr->classattrnode.section_num =0;
ret->exprNodePtr->classattrnode.instructor_num =1;
ret->exprNodePtr->classattrnode.crn_num =0;
ret->exprNodePtr->classattrnode.capacity_num =0;
}
else if(crn!=""){
ret->exprNodePtr->classattrnode.section_num =0;
ret->exprNodePtr->classattrnode.instructor_num =0;
ret->exprNodePtr->classattrnode.crn_num =1;
ret->exprNodePtr->classattrnode.capacity_num =0;
}
else if(cap!=""){
ret->exprNodePtr->classattrnode.section_num =0;
ret->exprNodePtr->classattrnode.instructor_num =0;
ret->exprNodePtr->classattrnode.crn_num =0;
ret->exprNodePtr->classattrnode.capacity_num =1;
}
return (ret);
}
TreeNode * mkmeetinglistNode1( TreeNode *first) {
TreeNode * ret = (TreeNode *)malloc (sizeof(TreeNode));
ret->thisNodeType = MEETINGLISTNODE1;
ret->exprNodePtr = (ExprNode *)malloc (sizeof(ExprNode));
ret->exprNodePtr->meetinglistnode1.firstChild = first;
return (ret);
}
TreeNode * mkmeetinglistNode2( TreeNode *first,TreeNode * second) {
TreeNode * ret = (TreeNode *)malloc (sizeof(TreeNode));
ret->thisNodeType = MEETINGATTRLISTNODE2;
ret->exprNodePtr = (ExprNode *)malloc (sizeof(ExprNode));
ret->exprNodePtr->meetinglistnode2.firstChild = first;
ret->exprNodePtr->meetinglistnode2.secondChild = second;
return (ret);
}
TreeNode * mkmeetingNode( TreeNode *first,TreeNode *second,TreeNode* third ) {
TreeNode * ret = (TreeNode *)malloc (sizeof(TreeNode));
ret->thisNodeType = MEETINGNODE;
ret->exprNodePtr = (ExprNode *)malloc (sizeof(ExprNode));
ret->exprNodePtr->meetingnode.firstChild = first;
ret->exprNodePtr->meetingnode.secondChild = second;
ret->exprNodePtr->meetingnode.thirdChild = third;
return (ret);
}
TreeNode * mkbeginmeetingNode( char * t1,char * t2) {
TreeNode * ret = (TreeNode *)malloc (sizeof(TreeNode));
ret->thisNodeType = BEGINMEETINGNODE;
ret->exprNodePtr = (ExprNode *)malloc (sizeof(ExprNode));
ret->exprNodePtr->beginmeetingnode.t1 = t1;
ret->exprNodePtr->beginmeetingnode.t2 = t2;
return (ret);
}
TreeNode * mkendmeetingNode( char *t1) {
TreeNode * ret = (TreeNode *)malloc (sizeof(TreeNode));
ret->thisNodeType = ENDMEETINGNODE;
ret->exprNodePtr = (ExprNode *)malloc (sizeof(ExprNode));
ret->exprNodePtr->endmeetingnode.t1 = t1;
return (ret);
}
TreeNode * mkmeetingattrlistNode1( TreeNode *first) {
TreeNode * ret = (TreeNode *)malloc (sizeof(TreeNode));
ret->thisNodeType = MEETINGATTRLISTNODE1;
ret->exprNodePtr = (ExprNode *)malloc (sizeof(ExprNode));
ret->exprNodePtr->meetingattrlistnode1.firstChild = first;
return (ret);
}
TreeNode * mkmeetingattrlistNode2( TreeNode *first,TreeNode * second) {
TreeNode * ret = (TreeNode *)malloc (sizeof(TreeNode));
ret->thisNodeType = MEETINGATTRLISTNODE2;
ret->exprNodePtr = (ExprNode *)malloc (sizeof(ExprNode));
ret->exprNodePtr->meetingattrlistnode2.firstChild = first;
ret->exprNodePtr->meetingattrlistnode2.secondChild = second;
return (ret);
}
TreeNode * mkmeetingattrNode ( char* tday, TreeNode* day ,char* time,char*end_time) {
TreeNode * ret = (TreeNode *)malloc (sizeof(TreeNode));
ret->thisNodeType = MEETINGATTRNODE;
ret->exprNodePtr = (ExprNode *)malloc (sizeof(ExprNode));
ret->exprNodePtr->meetingattrnode.tday = tday;
ret->exprNodePtr->meetingattrnode.day = day;
ret->exprNodePtr->meetingattrnode.time = time;
ret->exprNodePtr->meetingattrnode.end_time = end_time;
return (ret);
}
TreeNode * mkdayNode ( char *day ) {
TreeNode * ret = (TreeNode *)malloc (sizeof(TreeNode));
ret->thisNodeType = DAYNODE;
ret->exprNodePtr = (ExprNode *)malloc (sizeof(ExprNode));
ret->exprNodePtr->daynode.day = day;
return (ret);
}
TreeNode * mkbeginconstraintNode( char *t1,char *t2,char* t3 ) {
TreeNode * ret = (TreeNode *)malloc (sizeof(TreeNode));
ret->thisNodeType = BEGINCONSTRAINTNODE;
ret->exprNodePtr = (ExprNode *)malloc (sizeof(ExprNode));
ret->exprNodePtr->beginconstraintnode.t1 = t1;
ret->exprNodePtr->beginconstraintnode.t2 = t2;
ret->exprNodePtr->beginconstraintnode.t3 = t3;
return (ret);
}
TreeNode * mkendconstraintNode( char * t1,char *t2,char * t3 ) {
TreeNode * ret = (TreeNode *)malloc (sizeof(TreeNode));
ret->thisNodeType = ENDCONSTRAINTNODE;
ret->exprNodePtr = (ExprNode *)malloc (sizeof(ExprNode));
ret->exprNodePtr->endconstraintnode.t1 = t1;
ret->exprNodePtr->endconstraintnode.t2 = t2;
ret->exprNodePtr->endconstraintnode.t3 = t3;
return (ret);
}
TreeNode * mkitemlistNode1( TreeNode *first) {
TreeNode * ret = (TreeNode *)malloc (sizeof(TreeNode));
ret->thisNodeType = ITEMLISTNODE1;
ret->exprNodePtr = (ExprNode *)malloc (sizeof(ExprNode));
ret->exprNodePtr->itemlistnode1.firstChild = first;
return (ret);
}
TreeNode * mkitemlistNode2( TreeNode *first,TreeNode * second) {
TreeNode * ret = (TreeNode *)malloc (sizeof(TreeNode));
ret->thisNodeType = ITEMLISTNODE2;
ret->exprNodePtr = (ExprNode *)malloc (sizeof(ExprNode));
ret->exprNodePtr->itemlistnode2.firstChild = first;
ret->exprNodePtr->itemlistnode2.secondChild = second;
return (ret);
}
TreeNode * mkitemNode( TreeNode *first,TreeNode *second,TreeNode* third ) {
TreeNode * ret = (TreeNode *)malloc (sizeof(TreeNode));
ret->thisNodeType = ITEMNODE;
ret->exprNodePtr = (ExprNode *)malloc (sizeof(ExprNode));
ret->exprNodePtr->itemnode.firstChild = first;
ret->exprNodePtr->itemnode.secondChild = second;
ret->exprNodePtr->itemnode.thirdChild = third;
return (ret);
}
TreeNode * mkbeginitemNode( char *t1,char * t2) {
TreeNode * ret = (TreeNode *)malloc (sizeof(TreeNode));
ret->thisNodeType = BEGINITEMNODE;
ret->exprNodePtr = (ExprNode *)malloc (sizeof(ExprNode));
ret->exprNodePtr->beginitemnode.t1 = t1;
ret->exprNodePtr->beginitemnode.t2 = t2;
return (ret);
}
TreeNode * mkenditemNode( char *t1) {
TreeNode * ret = (TreeNode *)malloc (sizeof(TreeNode));
ret->thisNodeType = ENDITEMNODE;
ret->exprNodePtr = (ExprNode *)malloc (sizeof(ExprNode));
ret->exprNodePtr->enditemnode.t1 = t1;
return (ret);
}
TreeNode * mkitemattrNode ( char* token,char *code ,char* crn) {
TreeNode * ret = (TreeNode *)malloc (sizeof(TreeNode));
ret->thisNodeType = ITEMATTRNODE;
ret->exprNodePtr = (ExprNode *)malloc (sizeof(ExprNode));
ret->exprNodePtr->itemattrnode.token = token;
ret->exprNodePtr->itemattrnode.code = code;
ret->exprNodePtr->itemattrnode.crn = crn;
return (ret);
}
|
C
|
/**
* Copyright (c) 2020 Raspberry Pi (Trading) Ltd.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
// Sweep through all 7-bit I2C addresses, to see if any slaves are present on
// the I2C bus. Print out a table that looks like this:
//
// I2C Bus Scan
// 0 1 2 3 4 5 6 7 8 9 A B C D E F
// 0
// 1 @
// 2
// 3 @
// 4
// 5
// 6
// 7
//
// E.g. if slave addresses 0x12 and 0x34 were acknowledged.
#include <stdio.h>
#include "pico/stdlib.h"
#include "pico/binary_info.h"
#include "hardware/i2c.h"
// I2C reserves some addresses for special purposes. We exclude these from the scan.
// These are any addresses of the form 000 0xxx or 111 1xxx
bool reserved_addr(uint8_t addr) {
return (addr & 0x78) == 0 || (addr & 0x78) == 0x78;
}
int main() {
// Enable UART so we can print status output
stdio_init_all();
#if !defined(i2c_default) || !defined(PICO_DEFAULT_I2C_SDA_PIN) || !defined(PICO_DEFAULT_I2C_SCL_PIN)
#warning i2c/bus_scan example requires a board with I2C pins
puts("Default I2C pins were not defined");
#else
// This example will use I2C0 on the default SDA and SCL pins (GP4, GP5 on a Pico)
i2c_init(i2c_default, 100 * 1000);
gpio_set_function(PICO_DEFAULT_I2C_SDA_PIN, GPIO_FUNC_I2C);
gpio_set_function(PICO_DEFAULT_I2C_SCL_PIN, GPIO_FUNC_I2C);
gpio_pull_up(PICO_DEFAULT_I2C_SDA_PIN);
gpio_pull_up(PICO_DEFAULT_I2C_SCL_PIN);
// Make the I2C pins available to picotool
bi_decl(bi_2pins_with_func(PICO_DEFAULT_I2C_SDA_PIN, PICO_DEFAULT_I2C_SCL_PIN, GPIO_FUNC_I2C));
printf("\nI2C Bus Scan\n");
printf(" 0 1 2 3 4 5 6 7 8 9 A B C D E F\n");
for (int addr = 0; addr < (1 << 7); ++addr) {
if (addr % 16 == 0) {
printf("%02x ", addr);
}
// Perform a 1-byte dummy read from the probe address. If a slave
// acknowledges this address, the function returns the number of bytes
// transferred. If the address byte is ignored, the function returns
// -1.
// Skip over any reserved addresses.
int ret;
uint8_t rxdata;
if (reserved_addr(addr))
ret = PICO_ERROR_GENERIC;
else
ret = i2c_read_blocking(i2c_default, addr, &rxdata, 1, false);
printf(ret < 0 ? "." : "@");
printf(addr % 16 == 15 ? "\n" : " ");
}
printf("Done.\n");
return 0;
#endif
}
|
C
|
//number 3
//but 9
//3,6,12,15,21...
#include<stdio.h>
void main()
{
int n;
printf("Enter a number : ");
scanf("%d",&n);
//18==>18%3==>0, 18%9==>0
if(n%3 == 0)
{
if(n%9!=0)
{
printf("%d is a mutiple of 3 but not multiple of 9",n);
}
else
{
printf("%d is a multiple of 9",n);
}
}
else
{
printf("%d is not a multiple of 3",n);
}
}
1000-9999 ==> valid year
1-12 ==>
1-30 ==>
|
C
|
#include "prefix.h"
#include <stdio.h>
#include <stdlib.h>
// Cycles through prefixes until opcode is found, returns opcode index
int find_opcode(struct x86_instr * inst){
if(inst == NULL){
printf("%s: %s\n", __func__, "inst == NULL");
return -1;
}
int i = 0;
int opcode_flag = 0; // turn on when prefix not found
unsigned char * bytes = inst-> byte_code;
if(bytes == NULL){
printf("%s: %s\n", __func__, "byte_code is NULL");
return -1;
}
while(opcode_flag == 0 && i < MAX_INSTR_LEN){
switch(bytes[i]){
case(prefix_lock):
case(prefix_repn): // Must also include bnd
case(prefix_rep):
case(prefix_cs): // Must include branchn
case(prefix_ss):
case(prefix_ds): // Must include branch
case(prefix_es):
case(prefix_fs):
case(prefix_gs):
case(prefix_op_size_override):
case(prefix_addr_size_override):
inst->prefix_ptr = 0; // Instruction contains prefix
goto append;
}
// Check for REX prefix
if(prefix_rex <= bytes[i] && bytes[i] <= prefix_rex + 0xf){
inst->rex_ptr = i;
inst->rex = bytes[i];
i++; // REX must come before opcode
}
inst->opcode[0] = bytes[i];
inst->opcode_ptr = i;
opcode_flag = 1;
goto out;
append:
printf("append needed");
out:
if(opcode_flag == 1)
break;
i++;
}
return i;
}
// Returns 16, 32, 64
// TODO should this go in instruction.c?
int check_bit_mode(struct x86_instr * inst){
if (inst->rex != 0x0 && inst->rex & REX_W){
return 64;
}
return DEFAULT_BIT_MODE;
}
int get_rex_w(struct x86_instr * inst){
unsigned char rex = inst->rex;
if(rex & REX_prefix != REX_prefix)
return 0;
return (rex & REX_W) >> 3;
}
int get_rex_r(struct x86_instr * inst){
unsigned char rex = inst->rex;
if(rex & REX_prefix != REX_prefix)
return 0;
return (rex & REX_R) >> 2;
}
int get_rex_x(struct x86_instr * inst){
unsigned char rex = inst->rex;
if(rex & REX_prefix != REX_prefix)
return 0;
return (rex & REX_X) >> 1;
}
int get_rex_b(struct x86_instr * inst){
unsigned char rex = inst->rex;
if(rex & REX_prefix != REX_prefix)
return 0;
return (rex & REX_B) >> 0;
}
// Group 1:
// FO - LOCK prefix - exclusive use of shared memory in multiprocessor environ
// F2 - REPNE/REPNZ (repeat not equal/zero) - repeat for each element of string or sometimes mandatory for instructions
// F3 - REP/REPE/REPZ - repeat (equal/zero) - mandatory for POPCNT, LZCNT, ADOX
// F2 - BND prefix iff:
// CPUID.(EAX=07, ECX=0):EBX.MPX[bit 14] is set
// BNDCFGU.EN and/or IA32_BNDCFGS.EN is set
// When F2 precedes a near CALL, near RET, near JMP, short Jcc, or near Jcc instruction
// Group 2:
// 2E - CS segment override prefix
// 36 - SS segment override prefix
// 3E - DS segment override prefix
// 26 - ES segment override prefix
// 64 - FS segment override prefix
// 65 - GS segment override prefix
// 2E - Branch not taken (only Jcc instructions)
// 3E - Branch taken (only Jcc instructions)
// Group 3:
// 66 - operand size override prefix (switch between 16 and 32 bit operands; use to select non-default) or mandatory
// Group 4:
// 67 - address size override prefix (switch between 16 and 32 bit addressing)
|
C
|
#include<stdio.h>
#include<conio.h>
void main()
{
int n1,n2,add,sub,mul,div;
clrscr();
printf("Enter number 1:\n");
scanf("%d",&n1);
printf("Enter number 2:\n");
scanf("%d",&n2);
add=n1+n2;
printf("Add = %d",add);
sub=n1-n2;
printf("Sub = %d",sub);
mul=n1*n2;
printf("Mul = %d",mul);
div=n1/n2;
printf("Div = %d",div);
getch();
}
|
C
|
int factorial(int n){
int f = 1;
int i;
for(i = 0 ; i < n ; i++){
f = f * i;
}
return f;
}
|
C
|
//
// HW5_Functions.h
// HW5
//
// Created by morgan mcmahon on 11/25/16.
// Copyright © 2016 morgan mcmahon. All rights reserved.
//
#ifndef HW5_Functions_h
#define HW5_Functions_h
#define stringLength 30
/* ---------- Enum Gate Primitive Methods ---------- */
// These the enumeated verilog primitives
enum gateType {
// Gate Primatives
and,
nand,
or,
nor,
xor,
xnor,
// Transmission Gate Primitives
not,
buf
};
// returns the string name of the gateType enum
const char* getGateType(enum gateType type){
switch (type)
{
case and: return "and";
case nand: return "nand";
case or: return "or";
case nor: return "nor";
case xor: return "xor";
case xnor: return "xnor";
case not: return "not";
case buf: return "buffer";
}
}
// given a string representation of a gate type the enum representation is returned
enum gateType getEnum(char* string){
if (strcmp(string, "and") == 0)
return and;
if (strcmp(string, "nand") == 0)
return nand;
if (strcmp(string, "or") == 0)
return or;
if (strcmp(string, "nor") == 0)
return nor;
if (strcmp(string, "xor") == 0)
return xor;
if (strcmp(string, "xnor") == 0)
return xnor;
if (strcmp(string, "not") == 0)
return not;
if (strcmp(string, "buf") == 0)
return buf;
return 0;
}
/* ---------- Type defines ----------- */
// Gate DataStructure
typedef struct Gate {
char name[10]; // names 5 characters and shorter are supported
enum gateType type; // types given by the verilog primitive gate types
struct Fan* fanin; // pointers to fanin gates
struct Fan* fanout; // pointers to fanout gates
struct Gate* next_gate; // pointer to next gate in the list
} Gate;
typedef struct GateList {
Gate* first;
Gate* last;
int length;
} GateList;
// GateList is used to store the list of gates for the fanin and fanouts
typedef struct Fan {
struct Gate* gate;
struct Fan* next_fan;
} Fan;
void addFan(struct Fan* list, struct Gate* gate) {
struct Fan* temp = list;
while(temp->next_fan != NULL){ //while next gate exists
temp = temp->next_fan; //move to the next gate
}
//temp->next_gate = gate;
}
void addGate(struct GateList* list, struct Gate* gate){
if (list->first == NULL) { //sets the first gate as head of the list
list->first = gate;
list->last = gate;
} else {
list->last->next_gate = gate; //sets the point of the last gate in GateList to the new element
list->last = gate; //sets the last element of GateList to the new element
list->length = list->length + 1; //adds one to length
}
gate->next_gate = NULL; //sets the next gate pointer of the new last gate to null
}
/* ---------- Print Methods ----------- */
//prints out the list of gates
void printGateList (struct GateList* list) {
void printGate (Gate* gate);
struct Gate* gate;
gate = list->first;
while (gate->next_gate != NULL){ // while the next gate pointer is != null
printGate(gate); // print the gate
gate = gate->next_gate; // move to next gate in list
}
printGate(gate);
}
//prints out the gate to the terminal
void printGate (struct Gate* gate) {
void printFan (struct Fan* gate);
printf("\nName: ");
printf("%s", gate->name);
printf("\nType: ");
printf("%s", getGateType(gate->type));
printf("\nFanin: ");
printFan(gate->fanin);
printf("\nFanout: ");
printFan(gate->fanout);
printf("\nNext Gate: ");
printf("%s", gate->next_gate->name);
printf("\n");
}
void printFan (struct Fan* list) {
Fan* f = list;
while (f != NULL) {
if (f->gate != NULL)
printf("%s", f->gate->name);
printf("%s", ", ");
f = f->next_fan;
}
}
/* ---------- Constructors ---------- */
// Gate constructor
Gate* newGate(char name[], enum gateType type, struct Fan* fin, struct Fan* fout, struct Gate* next_gate){
Gate* p = malloc(sizeof(*p));
strcpy(p->name, name);
p->type = type;
p->fanin = fin;
p->fanout = fout;
p->next_gate = next_gate;
return p;
}
// Fan constructor
Fan* newFan(struct Gate* gate, struct Fan* next_fan) {
Fan* p = malloc(sizeof(*p));
p->gate = gate;
p->next_fan = next_fan;
return p;
}
/* ---------- Parser Methods ---------- */
//returns a 1 if the string is a gate
int tagCheck(char string[stringLength]){
if (strcmp(string, "and") == 0)
return 1;
if (strcmp(string, "nand") == 0)
return 1;
if (strcmp(string, "or") == 0)
return 1;
if (strcmp(string, "nor") == 0)
return 1;
if (strcmp(string, "xor") == 0)
return 1;
if (strcmp(string, "xnor") == 0)
return 1;
if (strcmp(string, "not") == 0)
return 1;
if (strcmp(string, "buf") == 0)
return 1;
return 0;
}
/* ---------- Preprocessor ---------- */
/*
* Reads in file input.v in working directory
* Processes the file and writes the result in a temporary file
* -The goal is to get rid of variations between files like white space and comments
*/
void preProcessFile(){
FILE *in;
FILE *temp;
in = fopen("/Users/mlm/Google Drive/CASE/Fall 2016/EECS 318/HW5/HW5/input.v", "r");
temp = fopen("/Users/mlm/Google Drive/CASE/Fall 2016/EECS 318/HW5/HW5/temp.v", "w");
// flags used for parsing
int open_paren = 0;
int comment = 0;
int block_comment = 0;
int semicolon = 0;
char last = 0;
char car = fgetc(in); // temporary variable for each caracter read
int print = 0; // blooean to decide if car should be printed
while (car != EOF ){
/*
* Gets rid of:
* - all tabs in the file
* - all spaces inside and new lines characters inside parethesis
* - all blank lines
*/
print = 1;
//deals with semicolons
if (car == ';'){
semicolon = 1;
fputc(';', temp);
}
if ( (car < 123) && (car > 64) && semicolon ){
semicolon = 0;
fputc('\n', temp);
}
if (car=='\t') // deletes all tabs
print = 0;
else if (open_paren && ((car ==' ') || (car=='\n'))) // deletes all all seperators inside parenthesis
print = 0;
else if (comment || block_comment) // deletes all comments
print = 0;
else if (semicolon) // deletes everthing between ______
print = 0;
else if ( (last == ' ') && (car == ' ') )
print = 0;
else if ( (last == ',') && (car == ' ') )
print = 0;
if (print)
fputc(car, temp);
//reset flags if needed
if (car == ')')
open_paren = 0; // flag is reset
//set flags based on current character
if (car == '(')
open_paren = 1; // flag is set
//checks for comments blocks and sets flags
if ( (last == '/') && (car == '/') ) {
comment = 1; // entering comment text
} else if ( (last == '/') && (car == '*') ) {
block_comment = 1; // entering block comment
}
//resets block comment flags
if (car == '\n') // comment end with line end
comment = 0;
if ( (last == '*') && (car == '/') )
block_comment = 0; // end of block comment reached
last = car; // store car value
car = fgetc(in); // get next character from file
}
// closes both files
fclose(in);
fclose(temp);
}
#endif /* HW5_Functions_h */
|
C
|
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
int main(void)
{
sigset_t set;
sigemptyset(&set);
sigaddset(&set, SIGINT);
sigaddset(&set, SIGQUIT);
if (sigprocmask(SIG_BLOCK, &set, NULL) < 0) {
perror("sigprocmask");
return 1;
}
puts("Blocking signal");
if (sigwaitinfo(&set, NULL) < 0)
{
perror("sigwaitinfo");
return 1;
}
puts("nsigwaitinfo return");
return 0;
}
|
C
|
/*
Copyright (C) 2016 Thomas Kaulen
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
char decodeIntertechno(char symbol, long value, char protocolID)
{
if (symbol == '4')
{
resetBuffersAndSetState(1);
return 0;
}
switch (getState())
{
case 0:
break;
case 1:
if (symbol == 'v' || symbol == 'w' || symbol == 'x')
{
if (symbol == 'v') writeBuffer('0');
if (symbol == 'w') writeBuffer('1');
if (symbol == 'x') writeBuffer('f');
if (getTickCounter() == 4) writeBuffer(' ');
if (getTickCounter() == 8) writeBuffer(' ');
if (getTickCounter() == 10) writeBuffer(' ');
if ( getTickCounter() == 11)
{
if (symbol == 'x' || symbol == 'v') setState(2); else resetBuffersAndSetState(0); /// error
}
} else resetBuffersAndSetState(0); //error
return 0;
break;
case 2:
if (symbol == 'x' || symbol == 'v')
{
if (symbol == 'v') writeBuffer('0');
if (symbol == 'x') writeBuffer('f');
setState(3);
}
else resetBuffersAndSetState(0); //error
break;
case 3: ///Sync Bit
if (symbol == '2') flushDecodeBuffer('4'); //accept if nextSymbol = 4
resetState(0);
break;
}
}
char encodeIntertechno(char symbol, char protocolID)
{
if (symbol == '0') writeEncode('v'); // send symbol A (from set sequence) 300 ys High 1000 ys Low
if (symbol == '1') writeEncode('w');
if (symbol == 'f') writeEncode('x');
if (symbol == '{') writeEncode('4'); // start condition
if (symbol == '}') // end conbdition
{
writeEncode('2'); writeEncode('4');
}
return 0;
}
|
C
|
#include "../h/const.h"
#include "../h/types.h"
#include "../e/initial.e"
#include "../e/pcb.e"
#include "/usr/local/include/umps2/umps/libumps.e"
/***********************************************************************
* This module implements Kaya's process scheduler and deadlock
* detector
*
* It also is the primary location for maintaining processor cpu usage.
*
* scheduler maintains the following variables
* int procCount;
* int sftBlkCount;
* pcb_PTR currProc;
* pcb_PTR readyQueue;
***********************************************************************/
/* global vars for maintaining cpu time usage */
cpu_t TODStarted;
cpu_t currentTOD;
/* external globals scheduler uses */
extern int procCount;
extern int sftBlkCount;
extern pcb_PTR currProc;
extern pcb_PTR readyQueue;
/*extern int semD[MAGICNUM];*/
/***********************************************************************
* Scheduler function
*
* Implements a simple Round-Robin scheduling algorithm
* Primary maintainer for cpu time usage
*
* After all processes are terminated the scheduler will halt the system
*
* In the event of deadlock (procCount > 0, sftBlk == 0) the system will
* PANIC()
*
*
*
***********************************************************************/
void scheduler() {
/* was someone just running? */
/* this means a process was running and was then blocked
* or returned to readyQ for some reason */
if(currProc != NULL){
/* save how much time current process used on CPU */
/* subtract current time from global start time to get this ^ */
STCK(currentTOD);
currProc->cpu_time = (currProc->cpu_time)
+ (currentTOD - TODStarted);
}
if(!emptyProcQ(readyQueue)) {
/* start next process in queue */
currProc = removeProcQ(&readyQueue);
/* get start time */
STCK(TODStarted);
/* load QUANTUM into process timer */
setTIMER(QUANTUM);
LDST(&(currProc -> p_s));
} else {
/* nothing was in readyQueue */
currProc = NULL; /* no running process */
/* finished all processes properly */
if(procCount == 0) {
HALT();
}
/* deadlock */
if(procCount > 0 && sftBlkCount == 0) {
PANIC();
}
/* now it's just a waiting game */
if(procCount > 0 && sftBlkCount > 0) {
setSTATUS((getSTATUS() | ALLOFF | IEON | IECON | IMON));
WAIT(); /* run silent run deep */
}
}
}
/** end scheduler **/
|
C
|
/*
** my_putstr_err.c for my_putstr_err.c in /home/cheval_8/rendu/PSU_2015_minishell2/lib/src
**
** Made by Chevalier Nicolas
** Login <cheval_8@epitech.net>
**
** Started on Sun Apr 10 03:43:45 2016 Chevalier Nicolas
** Last update Sun Apr 10 03:47:09 2016 Chevalier Nicolas
*/
#include "lib.h"
void my_putstr_err(char *str)
{
if (write(2, str, my_strlen(str)) == -1)
exit (1);
}
|
C
|
/* Esimerkki VIRHEELLISEST srand-funktion kytst. */
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
int i;
for (i = 1; i < 50; ++i) {
srand(time(0));
printf("%i\n", rand());
}
return 0;
}
|
C
|
/*
** right_op.c for 42sh in /home/toozs-_c/Prog_tests/fourty_two_tests/sources
**
** Made by cristopher toozs-hobson
** Login <toozs-_c@epitech.net>
**
** Started on Sat Apr 25 16:09:43 2015 cristopher toozs-hobson
** Last update Sun May 17 12:38:53 2015 cristopher toozs-hobson
*/
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <fcntl.h>
#include "minishell.h"
#include "my.h"
int right_op_check(t_tree *root, t_main *m)
{
int ret;
ret = 1;
if (root->op == '>')
ret = right_op(root, 1, m);
else if (root->op == '1')
ret = right_op(root, 2, m);
return (ret);
}
char **right_errors(t_tree *root)
{
char **tab;
if (root->right->exp)
{
if ((tab = set_file_word(root)) == NULL)
return (NULL);
}
else
{
my_putstr_err("Invalid syntax\n");
return (NULL);
}
if (!tab[0])
{
my_putstr_err("Missing file operand\n");
return (NULL);
}
else
return (tab);
}
int right_prep(t_tree *root, int type)
{
int fd;
char **tab;
if ((tab = right_errors(root)) == NULL)
return (1);
if (type == 1)
fd = open(tab[0], O_CREAT | O_WRONLY | O_TRUNC,
S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
else if (type == 2)
fd = open(tab[0], O_WRONLY | O_CREAT | O_APPEND,
S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if (fd == -1)
{
my_putstr_err("Invalid open\n");
return (1);
}
if (dup2(fd, 1) == -1)
return (1);
return (0);
}
int execute_right(t_tree *root, t_main *m, char **check, int out)
{
int ret;
if ((!root->left->exp && root->left->op)
|| (root->left->exp && check && !check[0]))
{
free_tab(check);
if (!root->left->op)
ret = execute_function(root->right->exp, m);
else
ret = launch_tree(root->left, m);
if (dup2(out, 1) == -1)
return (1);
return (ret);
}
else
{
ret = execute_function(root->left->exp, m);
if (dup2(out, 1) == -1)
return (1);
return (ret);
}
return (0);
}
int right_op(t_tree *root, int type, t_main *m)
{
int stdout_cpy;
char **check;
check = NULL;
if ((stdout_cpy = dup(1)) == -1)
return (1);
if (right_prep(root, type) == 1)
return (1);
if (root->left->exp != NULL)
check = my_str_tab(root->left->exp);
return (execute_right(root, m, check, stdout_cpy));
}
|
C
|
#ifndef DOCUMENT_H
#define DOCUMENT_H
#include <stdbool.h>
#include <X11/Xft/Xft.h>
#define MAX_UTF8_CHAR_LENGTH 6
typedef struct {
short x;
short width;
char utf8[MAX_UTF8_CHAR_LENGTH + 1];
size_t length;
} Character;
typedef struct {
short x;
short width;
Character *chars;
size_t nchars;
} Token;
typedef struct {
Token *tokens;
size_t ntokens;
} VisualLine;
typedef struct {
short width, height;
short margin_top, margin_right, margin_bottom, margin_left;
} PageInfo;
typedef struct {
VisualLine *lines;
size_t nlines;
PageInfo *page;
} Document;
#include "cursor_path.h"
Character **ExtractCharacters(Document *doc, size_t *nchars_return);
void CharacterInitialize(Character *ch, short x, const char *utf8, size_t bytes);
bool CharacterIsEOF(Character *ch);
Token *CharactersToTokens(Character text[], size_t nchars, size_t *ntokens_return);
Document *CreateDocument(const char *text, const PageInfo *page);
void DocumentSetPageInfo(Document *doc, PageInfo *page);
Token *ExtractTokens(Document *doc, size_t *ntokens_return);
Token *FillLine(VisualLine **line_return, Token *input, const PageInfo *page);
VisualLine *GetLine(Document *doc, size_t line);
Token *GetToken(Document *doc, size_t line, size_t token);
void InspectLine(VisualLine *line);
void JustifyLine(VisualLine *line, const PageInfo *page);
short PageInfoGetVisibleWidth(const PageInfo *page);
void ResetCharacterWidth(Character *ch);
Character *StringToCharacters(const char *text, size_t length, size_t *nchars_return);
void TokenAddCharacter(Token *tok, Character *ch);
Token *TokenCreate(void);
short TokenEOF(Token *tok, short x);
void TokenInitialize(Token *tok);
bool TokenIsEOF(Token *tok);
bool TokenIsNewline(Token *tok);
bool TokenIsSpace(Token *tok);
void UpdateTokenPositions(VisualLine *line);
void VisualLineAddToken(VisualLine *line, Token *tok);
VisualLine *VisualLineCreate(void);
short VisualLineGetWidth(VisualLine *line);
#endif
|
C
|
/*
* main.c
*/
#include "../fonctionsC.h"
#include <stdio.h>
int Liste_Choix[3] = {0,0,0};
unsigned int TabIntNoS[2] = {0,0};
signed int TabIntS[2] = {0,0};
int TabInt[2] = {0,0};
float TabFloat[2] = {0,0};
double TabDouble[2] = {0,0};
unsigned long TabLongNoS[2] = {0,0};
int TabDonnees[8] = {0,0,0,0,0,0,0,0};
short TabShortS[2] = {0, 0}; // un short dfini une variable de 16 bit.
double extensionSigne(int entier);
float exempleF;
#pragma DATA_ALIGN(TabDonnees, 32);
int main(void) {
ObtenirType(Liste_Choix);
ObtenirFormat(Liste_Choix+1);
ObtenirOperation(Liste_Choix+2);
//test = ConvertirListe(Liste_Choix) ;
AnalyserListe(Liste_Choix, TabIntNoS, TabIntS, TabInt, TabFloat, TabDouble, TabLongNoS, TabDonnees);
//AnalyserListe();
return 0;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
//Tipos de barramento do emulador
typedef unsigned char b_1bit;
typedef unsigned char b_8bits;
typedef unsigned int b_32bits;
typedef unsigned long int b_64bits;
//Numero de variaveis do programa que está sendo executado
static int numvar = 0;
//ALU
typedef struct alu
{
b_32bits saida;
b_1bit N;
b_1bit Z;
} alu;
//Processador
typedef struct processador
{
alu ALU;
b_32bits MAR;
b_32bits MDR;
b_32bits PC;
b_8bits MBR;
b_32bits SP;
b_32bits LV;
b_32bits CPP;
b_32bits TOS;
b_32bits OPC;
b_32bits H;
b_32bits A;
b_32bits B;
b_32bits C;
b_32bits MPC;
b_64bits MIR;
b_64bits microprograma[512];
b_8bits *memoria;
} processador;
//Cria um novo processador com o tamanho de memoria especificado
processador *newproc(b_8bits *mem)
{
processador *p = (processador*)malloc(sizeof(processador));
if(p != NULL && mem != NULL)
{
p->MAR = 0;
p->MDR = 0;
p->PC = 0;
p->MBR = 0;
p->SP = 0;
p->LV = 0;
p->CPP = 0;
p->TOS = 0;
p->OPC = 0;
p->H = 0;
p->A = 0;
p->B = 0;
p->C = 0;
p->MPC = 0;
p->MIR = 0;
p->ALU.saida = 0;
p->ALU.N = 0;
p->ALU.Z = 0;
p->memoria = mem;
return p;
}
return NULL;
}
//Libera da memoria um processador criado
void freeproc(processador *p)
{
if(p != NULL)
{
free(p->memoria);
free(p);
}
}
//Define qual registrador será usado no barramento B
void setbus(processador *p, b_8bits B)
{
if(p != NULL)
{
p->A = p->H;
switch(B)
{
case 0: p->B = p->MDR;
break;
case 1: p->B = p->PC;
break;
case 2: p->B = (signed int)p->MBR;
break;
case 3: p->B = p->MBR;
break;
case 4: p->B = p->SP;
break;
case 5: p->B = p->LV;
break;
case 6: p->B = p->CPP;
break;
case 7: p->B = p->TOS;
break;
case 8: p->B = p->OPC;
break;
default: break;
}
}
}
/* Opera a ALU, define o seu ultimo estado (N ou Z)
e coloca o resultado no barramento C */
void opalu(processador *p, b_8bits controle)
{
if(p != NULL)
{
switch(controle)
{
case 0b00011000: p->ALU.saida = p->A;
break;
case 0b00010100: p->ALU.saida = p->B;
break;
case 0b01010100: p->ALU.saida = p->B << 8;
break;
case 0b10010100: p->ALU.saida = p->B >> 8;
break;
case 0b11010100: p->ALU.saida = (p->B << 7) >> 1;
break;
case 0b00011010: p->ALU.saida = ~(p->A);
break;
case 0b00101100: p->ALU.saida = ~(p->B);
break;
case 0b00111100: p->ALU.saida = p->A + p->B;
break;
case 0b00111101: p->ALU.saida = p->A + p->B + 1;
break;
case 0b00111001: p->ALU.saida = p->A + 1;
break;
case 0b00110101: p->ALU.saida = p->B + 1;
break;
case 0b00111111: p->ALU.saida = p->B - p->A;
break;
case 0b00110110: p->ALU.saida = p->B - 1;
break;
case 0b00111011: p->ALU.saida = -(p->A);
break;
case 0b00001100: p->ALU.saida = p->A & p->B;
break;
case 0b00011100: p->ALU.saida = p->A | p->B;
break;
case 0b00010000: p->ALU.saida = 0;
break;
case 0b00110001: p->ALU.saida = 1;
break;
case 0b00110010: p->ALU.saida = -1;
break;
default: break;
}
if(p->ALU.saida == 0)
{
p->ALU.N = 0;
p->ALU.Z = 1;
}
else
{
p->ALU.N = 1;
p->ALU.Z = 0;
}
p->C = p->ALU.saida;
}
}
//Escolhe quais registradores receberao o valor do barramento C
void setreg(processador *p, b_32bits C)
{
if(p != NULL)
{
if(C & 0x001)
p->MAR = p->C;
if(C & 0x002)
p->MDR = p->C;
if(C & 0x004)
p->PC = p->C;
if(C & 0x008)
p->SP = p->C;
if(C & 0x010)
p->LV = p->C;
if(C & 0x020)
p->CPP = p->C;
if(C & 0x040)
p->TOS = p->C;
if(C & 0x080)
p->OPC = p->C;
if(C & 0x100)
p->H = p->C;
}
}
/* Define o valor de MPC:
1 - Salto incodicional: JAM-000
2 - Salto se Z: JAM-001
3 - Salto se N: JAM-010
4 - Salto incondicional para posicao de MBR: JAM-100 */
void setMPC(processador *p, b_8bits JAM, b_32bits NEXT_ADDR)
{
if(p != NULL)
{
p->MPC = NEXT_ADDR;
if((JAM & 1) && p->ALU.Z)
p->MPC = NEXT_ADDR | 0x100;
if((JAM & 2) && p->ALU.N)
p->MPC = NEXT_ADDR | 0x100;
if(JAM & 4)
p->MPC = p->MBR;
}
}
/* Opera a memoria:
1 - Fetch: MEM-001
2 - Read: MEM-010
3 - Write: MEM-100 */
void opmem(processador *p, b_8bits MEM)
{
if(p != NULL)
{
if(MEM & 1)
p->MBR = p->memoria[p->PC];
if(MEM & 2)
memcpy(&p->MDR, &p->memoria[p->MAR * 4], 4);
if(MEM & 4)
memcpy(&p->memoria[p->MAR * 4], &p->MDR, 4);
}
}
/* Imprime na tela:
1 - Registradores
2 - Pilha de execucao
3 - Variaveis do programa */
void console(processador *p)
{
if(p != NULL)
{
int base = p->LV + numvar, var, elem;
system("clear");
printf("\t\tESTADO DO EMULADOR\t\t");
printf("\nRegistradores:");
printf("\n\tMAR: 0x%x", p->MAR);
printf("\n\tMDR: 0x%x", p->MDR);
printf("\n\t PC: 0x%x", p->PC);
printf("\n\tMBR: 0x%x", p->MBR);
printf("\n\t SP: 0x%x", p->SP);
printf("\n\t LV: 0x%x", p->LV);
printf("\n\tCPP: 0x%x", p->CPP);
printf("\n\tTOS: 0x%x", p->TOS);
printf("\n\tOPC: 0x%x", p->OPC);
printf("\n\t H: 0x%x\n", p->H);
printf("\nMemoria:");
printf("\nPilha:");
for(int i = p->SP; i >= base; i--)
{
memcpy(&elem, &p->memoria[i * 4], 4);
printf("\n\t0x%x: %d", i, elem);
}
printf("\nVariaveis Locais(0x%x):", p->LV);
for(int i = 0; i < numvar; i++)
{
memcpy(&var, &p->memoria[(p->LV + i) * 4], 4);
printf("\n\t%d: %d", i, var);
}
printf("\n");
}
}
/* Realiza um ciclo de clock no processador:
1 - Coloca em MIR a microinstrucao na posicao de MPC
2 - Divide a microinstrucao em suas partes
3 - escolhe o registrador para o barramento B
4 - Opera a ALU
5 - Coloca o resultado da ALU nos registradores que recebem o valor do barramento C
6 - Opera a Memoria
7 - Define o novo valor de MPC */
void clock(processador *p)
{
if(p != NULL)
{
p->MIR = p->microprograma[p->MPC];
b_32bits NEXT_ADDR = p->MIR >> 27;
b_8bits JAM = (p->MIR << 37) >> 61;
b_8bits ALU = (p->MIR << 40) >> 56;
b_32bits C = (p->MIR << 48) >> 55;
b_8bits MEM = (p->MIR << 57) >> 61;
b_8bits B = (p->MIR << 60) >> 60;
setbus(p, B);
opalu(p, ALU);
setreg(p, C);
opmem(p, MEM);
setMPC(p, JAM, NEXT_ADDR);
}
}
//Carrega o microprograma de microprog.rom para p->microprograma
void loadmicroprog(processador *p, char *microprog)
{
FILE *mp = fopen(microprog, "r");
if(mp != NULL)
{
fread(p->microprograma, 8, 512, mp);
fclose(mp);
}
}
/* Calcula o numero de variaveis do programa executado.
OBS: O calculo e feito de acordo com o valor maximo entre
as variaveis encontradas apos instrucoes ILOAD ou ISTORE, pois
essas instrucoes admitem uma variavel x para colocar
ou remover no topo da pilha de execucao. */
int calcvar(char *prog, int tam)
{
int counter = 0;
int max = -1;
for(int i = 0; i < tam; i++)
{
if((((int)prog[i] == 0x1C) || (int)prog[i] == 0x22) && (i < tam - 1))
if((int)prog[i + 1] > max)
{
max = (int)prog[i + 1];
counter++;
}
}
return counter;
}
/* Carrega o programa de prog.exe para p->memoria.
OBS: Esse metodo carrega na memoria os 20 bytes de init
caso prog.exe nao possua esses 20 bytes. */
void loadprog(processador *p, char *prog)
{
FILE *pr = fopen(prog, "r");
if(pr != NULL)
{
int numBytes = 0;
char *init = (char*)calloc(20, 1);
fseek(pr, 0, SEEK_END);
numBytes = ftell(pr) - 24;
char *exe = (char*)calloc(numBytes, 1);
fseek(pr, 4, SEEK_SET);
fread(init, 1, 20, pr);
fread(exe, 1, numBytes, pr);
numvar = calcvar(exe, numBytes);
if(strcmp(init, "") == 0)
{
p->memoria[1] = 0x73;
p->memoria[4] = 0x0006;
b_32bits tmp = 0x1001;
memcpy(&p->memoria[8], &tmp, 4);
tmp = 0x0400;
memcpy(&p->memoria[12], &tmp, 4);
tmp = 0x1001 + numvar;
memcpy(&p->memoria[16], &tmp, 4);
}
else
memcpy(&p->memoria[0], init, 20);
memcpy(&p->memoria[0x0401], exe, numBytes);
free(init);
free(exe);
fclose(pr);
}
}
//Mantem o estado de execucao do processador e so para se digitado 'e'
void executar(processador *p)
{
if(p != NULL)
{
int i = 1;
char c;
while(i)
{
console(p);
clock(p);
c = getchar();
if(c == 'e' || p->PC == p->LV)
i = 0;
}
}
}
/* Logica principal do emulador:
1 - Cria a memoria do processador
2 - Cria o processador
3 - Analisa os argumentos da linha de comando para conferir se
os arquivos sao microprog.rom e prog.exe, independentemente da ordem
4 - carrega microprog.rom e prog.exe
5 - Inicia a execucao do programa.
6 - Libera o processador da memoria */
int main(int argc, char *argv[])
{
if(argc == 3 && argv[1] != argv[2])
{
b_8bits *memoria = (b_8bits*)calloc(8192, sizeof(b_8bits));
processador *p = newproc(memoria);
if(strstr(argv[1], ".rom") != NULL && strstr(argv[2], ".exe") != NULL)
{
loadmicroprog(p, argv[1]);
loadprog(p, argv[2]);
executar(p);
}
if(strstr(argv[1], ".exe") != NULL && strstr(argv[2], ".rom") != NULL)
{
loadmicroprog(p, argv[2]);
loadprog(p, argv[1]);
executar(p);
}
freeproc(p);
}
return 0;
}
|
C
|
#ifndef GLOBAL_H
#define GLOBAL_H
//ͷļҪõֽṹ
typedef struct table//ӽṹ
{
int id;//ӱ
int capacity;//
int state;//״ֵ̬Ϊ0ʾУ1ʾˣorder.cchangetablestate_infilecalculate.cĽβֱֻļֵ
struct table *next;//ıһָһڵָ
} Table;
typedef Table *tableptr;//ο˿αTable* typedefһ£ʹ
typedef struct menu//˵ṹ
{
int id;//˵ı
char name[22];//˵֣ԣ22ijԴ10֣ʲôֵķ
int times;//˱Ĵ
float money;//˵ļ۸floatӦþˣλλСDzᷢģһ㲻λ۸IJ˰
struct menu *next;//
} Menu;
typedef Menu *menuptr;//Dzοαtypedefʹ
typedef struct order//ṹ壬ÿһorder͵ֻһ
{
int tid;//
int id;//Ʒ
char name[22];//Ʒ
float money;//Ʒ
int times;//ڱĴ
struct order *next;//
} Order;
typedef Order *orderptr;//ȻDzοαtypedefʹ
#endif
|
C
|
#include<stdio.h>
#include<stdlib.h>
#define ull unsigned long long int
#define MOD 1000000007
ull fpow(int a,int n)
{
if(n==0)
return 1;
if(n==1)
return a;
else
{
ull temp=fpow(a,n/2);
if(n%2)
return (((temp*temp)%MOD)*a)%MOD;
else
return (temp*temp)%MOD;
}
}
int main()
{
int t,n,m,k,i;
ull val=0;
ull inverse[100001],factorial[300001];
factorial[0]=1;
for(i=1;i<=300000;i++)
{
factorial[i]=factorial[i-1]*i;
if(factorial[i]>MOD)
factorial[i]%=MOD;
}
inverse[0]=0;
inverse[1]=1;
for(i=2;i<=100000;i++)
{
inverse[i]=inverse[i-1]*fpow(i,MOD-2);
if(inverse[i]>MOD)
inverse[i]%=MOD;
}
scanf("%d",&t);
while(t--)
{
scanf("%d%d%d",&n,&m,&k);
val=factorial[n+m+k];
val*=inverse[n];
if(val>=MOD)
val%=MOD;
val*=inverse[m];
if(val>=MOD)
val%=MOD;
val*=inverse[k];
if(val>=MOD)
val%=MOD;
printf("%lld\n",val);
}
return 0;
}
|
C
|
/* Pingpong sends a message back and forth between two tasks.
* Pingpong requires a working subscription scheme, which we
* don't have yet. Pingpong also requires support for
* multiple instances of tasks, which we don't have either.
* IOW, we need to do some work before pingpong is up and running.
*/
#include <stdio.h>
#include <unistd.h>
#include <metal.h>
#define MM_MY_MESSAGE (MM_USER_BASE + 1)
void pingpongfn(void)
{
tid_t sender;
msgid_t msg;
msgarg_t arg1, arg2;
static int i;
unsigned long n = 0;
while (message_get(&sender, &msg, &arg1, &arg2) == success) {
switch (msg) {
case MM_MY_MESSAGE:
n++;
//usleep(1);
if (!publish(msg, arg1 + 1, arg2)) {
puts("Could not publish message");
break; // Do nothing ATM
}
break;
case MM_EXIT:
goto end;
}
}
end: // Not much to do here.
printf("Got %ld messages. Good bye\n", n);
return;
}
int main(void)
{
tid_t tid1, tid2;
size_t i, n;
if (!metal_init(0))
return 1;
if (!metal_task_new(&tid1, "pingpong", 0, pingpongfn)
|| !metal_task_new(&tid2, "pingpong", 1, pingpongfn))
die("Could not create tasks.\n");
// Set them up to subscribe to each other
if (!metal_subscribe(tid1, tid2)
|| !metal_subscribe(tid2, tid1))
die("Could not subscribe.");
if (!metal_task_start(tid1) || !metal_task_start(tid2))
die("Could not start tasks\n");
if (!message_send(0, tid1, MM_MY_MESSAGE, 1, 0))
die("Could not send message to task\n");
// Wait a long time.
usleep(5 * 1000 * 1000);
// Stop the tasks in a civilized way
if (!metal_task_stop(tid1) || !metal_task_stop(tid2))
die("Could not stop tasks");
usleep(1100);
if (!metal_exit())
return 1;
return 0;
}
|
C
|
#include "open_n_create_fs_file.h"
//----------------------------------------------------------------------------//
void*
create_fs_file(int* ret_fd,
char* path,
size_t inodes_cnt,
size_t blocks_cnt)
{
int fd = open(path, O_RDWR | O_CREAT, 0666);
if (fd == -1)
{
return NULL;
}
size_t file_size = BLOCKS_INFO_SECTION_SIZE * BYTES_BLOCK_SIZE +
inodes_cnt * sizeof(struct inode) +
blocks_cnt * BYTES_BLOCK_SIZE;
ftruncate(fd, file_size);
void* mapped_file =
mmap(NULL, file_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
struct fs_data filesys_data = {.blocks_cnt = blocks_cnt,
.blocks_stack_beginning = blocks_cnt,
.blocks_tail_beginning = 0,
.inodes_cnt = inodes_cnt,
.inodes_stack_beginning = inodes_cnt,
.inodes_tail_beginning = 0};
if (mapped_file != MAP_FAILED)
{
set_filesys_data(&filesys_data, mapped_file);
*ret_fd = fd;
return mapped_file;
}
// Failed at mmap
close(fd);
return NULL;
}
//----------------------------------------------------------------------------//
void*
open_fs_file(int* ret_fd,
char* path)
{
int fd = open(path, O_RDWR, 0666);
if (fd == -1)
{ // Failed while opening
return NULL;
}
struct stat st;
fstat(fd, &st);
void* mapped_ptr =
mmap(NULL, st.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (mapped_ptr != MAP_FAILED)
{ // Filed at mmap
*ret_fd = fd;
return mapped_ptr;
}
close(fd);
return NULL;
}
|
C
|
#include <sys/types.h>
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <time.h>
#include <fcntl.h>
#include <unistd.h>
#include <syslog.h>
#define BUF_SIZE 1024
void copy(const char *fromPath, const char *toPath){
syslog(LOG_INFO, "Zaczeto kopiowanie z %s do %s", fromPath, toPath);
int file;
int fileToSave;
char buf[BUF_SIZE];
file = open(fromPath, O_RDONLY,0);
if(file < 0){
syslog(LOG_ERR, "Blad otwarcia pliku %s!!!", fromPath);
syslog(LOG_INFO, "Koniec programu");
return;
}
fileToSave = open(toPath, O_WRONLY | O_CREAT, 00700);
if(fileToSave < 0){
syslog(LOG_ERR, "Blad otwarcia pliku %s!!!", toPath);
syslog(LOG_INFO, "Koniec programu");
return;
}
int ssize;
while((ssize=read(file, buf, BUF_SIZE)) != 0){
if(ssize < BUF_SIZE)
buf[ssize] = '\0';
if(write(fileToSave, buf, ssize) < 0){
syslog(LOG_ERR, "Blad zapisu!!!");
syslog(LOG_INFO, "Koniec programu");
close(file);
close(fileToSave);
return;
}
}
close(file);
close(fileToSave);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line_utils.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: albgarci <albgarci@student.42madrid> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/09/28 19:30:47 by albgarci #+# #+# */
/* Updated: 2021/10/20 13:29:43 by albgarci ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
char *ft_strjoin(char const *s1, char const *s2)
{
char *s3;
if (!s1 || !s2)
return (NULL);
s3 = malloc(sizeof(char) * (ft_strlen(s1) + ft_strlen(s2) + 1));
if (!s3)
return (NULL);
ft_memmove(s3, (char *)s1, ft_strlen(s1));
ft_memmove(s3 + ft_strlen(s1), (char *)s2, ft_strlen(s2));
s3[ft_strlen(s1) + ft_strlen(s2)] = '\0';
return (s3);
}
void *ft_memmove(void *dst, const void *src, size_t len)
{
size_t i;
char *d;
char *s;
s = (char *) src;
d = (char *) dst;
i = 0;
if (!s && !d && len > 0)
return (dst);
if (d > s)
{
while (len > 0)
{
len--;
d[len] = s[len];
}
return (dst);
}
while (i < len)
{
d[i] = s[i];
i++;
}
return (dst);
}
void ft_bzero(void *s, unsigned long n)
{
unsigned long i;
char *str;
str = (char *) s;
i = 0;
while (i < n)
{
str[i] = '\0';
i++;
}
}
|
C
|
/*
** EPITECH PROJECT, 2020
** 42sh
** File description:
** double quot file
*/
#include "parsing/input/double_quote.h"
char *double_quote(char *separators, char **arr, int i)
{
char *str = NULL;
str = malloc(sizeof(char) * (strlen(arr[i])));
str = cpy_dquote(str, arr[i]);
str = re_modify_str(str, separators);
if (arr[index_darr(arr)][strlen(arr[index_darr(arr)]) - 1] == '"')
arr[index_darr(arr)][strlen(arr[index_darr(arr)]) - 1] = '\0';
arr[i] = strcpy(arr[i], str);
return (arr[i]);
}
|
C
|
# include<stdio.h>
# include<stdlib.h>
# include"matrixmath.h"
# include"helper.h"
# include"image.h"
# include"ppm.h"
image imgcreate(int m, int n) {
image temp = (image)malloc(sizeof(struct Image));
temp->red = matcreate(m, n);
temp->green = matcreate(m, n);
temp->blue = matcreate(m, n);
return temp;
}
image PPMImage2Image(PPMImage *img) {
int i;
if(img){
image res = imgcreate(img->y, img->x);
i = 0;
for (int a=0; a<img->y; a++) {
for (int b=0; b<img->x; b++) {
res->red->M[a][b] = img->data[i].red;
res->green->M[a][b] = img->data[i].green;
res->blue->M[a][b] = img->data[i].blue;
i++;
}
}
return res;
}
else {
print_exit("Not a proper image");
}
}
PPMImage *Image2PPMImage(image img) {
PPMImage *ppm = (PPMImage *)malloc(sizeof(PPMImage));
int m = img->red->m;
int n = img->red->n;
ppm->x = n;
ppm->y = m;
int c = 0;
ppm->data = (PPMPixel*)malloc(n * m * sizeof(PPMPixel));
for (int i=0;i<m;i++) {
for (int j=0;j<n; j++) {
ppm->data[c].red = (char)img->red->M[i][j];
ppm->data[c].green = (char)img->green->M[i][j];
ppm->data[c].blue = (char)img->blue->M[i][j];
c++;
}
}
return ppm;
}
void blur(matrix X) { // T1 - Gaussian Blur
matrix kernel = matcreate(3, 3);
float arr[3][3] = {
{(float)1/16, (float)1/8, (float)1/16},
{(float)1/8, (float)1/4, (float)1/8},
{(float)1/16, (float)1/8, (float)1/16}
};
for (int i=0; i<3; i++) {
for (int j=0; j<3; j++) {
kernel->M[i][j] = arr[i][j];
}
}
X->m = X->m-2;
X->n = X->n-2;
for (int i=1; i<X->m-1; i++) {
for (int j=1; j<X->n-1; j++) {
matrix temp = slice(X, i-1, i+2, j-1, j+2);
matrix prod = matcreate(kernel->m, kernel->n);
multiply(prod, temp, kernel);
X->M[i][j] = sum(prod);
}
}
}
matrix bgr2grey(image img) { // T2
matrix R = img->red;
matrix B = img->blue;
matrix G = img->green;
matrix kernel = matcreate(1, 3);
valassign(kernel, (float)1/3);
if (R->n == G->n && G->n == B->n && R->m == G->m && G->m == B->m) {
int n = R->n;
int m = R->m;
matrix ans = matcreate(m, n);
for (int i=0;i<m;i++) {
for (int j=0;j<n;j++) {
matrix temp = matcreate(1, 3);
temp->M[0][0] = R->M[i][j];
temp->M[0][1] = B->M[i][j];
temp->M[0][2] = G->M[i][j];
matrix prod = matcreate(kernel->m, kernel->n);
multiply(prod, temp, kernel);
ans->M[i][j] = sum(prod);
}
}
return ans;
}
else {
print_exit("Diminsion of RGB doesn't match!");
}
}
void edgedetect(matrix X) { // T3 - Canny Edge Detection
matrix Gx = matcreate(3, 3);
matrix Gy = matcreate(3, 3);
float total;
float arr1[3][3] = {
{-1, 0, 1},
{-2, 0, 2},
{-1, 0, 1}
};
float arr2[3][3] = {
{1, 2, 1},
{0, 0, 0},
{-1, -2, -1}
};
for (int i=0; i<3; i++) {
for (int j=0; j<3; j++) {
Gx->M[i][j] = arr1[i][j];
Gy->M[i][j] = arr2[i][j];
}
}
X->m = X->m-2;
X->n = X->n-2;
for (int i=1; i<X->m-1; i++) {
for (int j=1; j<X->n-1; j++) {
matrix temp = slice(X, i-1, i+2, j-1, j+2);
matrix prod1 = matcreate(Gx->m, Gx->n);
matrix prod2 = matcreate(Gy->m, Gy->n);
multiply(prod1, temp, Gx);
multiply(prod2, temp, Gy);
total = abs(sum(prod1)) + abs(sum(prod2));
if(total > 255)
total = 255;
X->M[i][j] = 255 - (unsigned char)total;
free(prod1);
free(prod2);
}
}
free(Gx);
free(Gy);
}
void imgblur(image X) { // All channels blur
blur(X->red);
blur(X->green);
blur(X->blue);
}
void ppmgrey(image img, matrix grey) {
img->red = grey;
img->green = grey;
img->blue = grey;
}
void gausblur(image X, int n){
for (int i=0; i<n; i++) {
imgblur(X);
}
}
void imgedgedetect(image X) {
edgedetect(X->red);
edgedetect(X->green);
edgedetect(X->blue);
}
|
C
|
/*++
Copyright (c) 1997 Microsoft Corporation
Module Name:
parsearg.c
Abstract:
Argument Handling
Author:
MikeTs
Environment:
Any
Revision History:
--*/
#include "pch.h"
VOID
ParseProgramInfo(
PUCHAR ProgramName,
PPROGINFO ProgramInfo
)
/*++
Routine Description:
This routine parses program path and module name
Arguments:
ProgramName - The Argv[0] from main()
ProgramInfo - Program Information structure
Return Value:
None
--*/
{
PUCHAR ptr;
ProgramInfo->ProgPath = _strlwr(ProgramName);
ptr = strrchr( ProgramName, '\\' );
if (ptr != NULL) {
*ptr = '\0';
ProgramInfo->ProgName = ptr + 1;
} else {
ProgramInfo->ProgName = ProgramName;
}
ptr = strchr(ProgramInfo->ProgName, '.');
if (ptr != NULL) {
*ptr = '\0';
}
}
ULONG
ParseSwitches(
PULONG ArgumentCount,
PUCHAR **ArgumentList,
PARGTYPE ArgumentArray,
PPROGINFO ProgramInfo
)
/*++
Routine Description:
Parse command line switches
Arguments:
ArgumentCount - Pointer to the number of arguments
ArgumentList - Pointer to the pointer to the list of arguments
ArgumentArray - How to parse the arguments
ProgramInfo - Program Specific structure
Return Value:
ULONG - Success = ARGERR_NONE
--*/
{
PUCHAR argument;
ULONG status = ARGERR_NONE;
if (ProgramInfo->SwitchChars == NULL) {
ProgramInfo->SwitchChars = DEF_SWITCHCHARS;
}
if (ProgramInfo->Separators == NULL) {
ProgramInfo->Separators = DEF_SEPARATORS;
}
for (; *ArgumentCount; (*ArgumentCount)--, (*ArgumentList)++)
{
argument = **ArgumentList;
if (strchr(ProgramInfo->SwitchChars, *argument)) {
argument++;
status = ParseArgSwitch(
&argument,
ArgumentArray,
ProgramInfo
);
if (status != ARGERR_NONE) {
PrintError( status, argument, ProgramInfo );
break;
}
} else {
break;
}
}
return status;
}
ULONG
ParseArgSwitch(
PUCHAR *Argument,
PARGTYPE ArgumentArray,
PPROGINFO ProgramInfo
)
/*++
Routine Description:
Parse a command line switch
Arguments
Argument - Pointer to argument
ArgumentArray - How to handle the argument
ProgramInfo - Program Information Structure
Return Value:
ULONG
--*/
{
BOOL found = FALSE;
PARGTYPE tableEntry;
PUCHAR argumentEnd;
ULONG length = 0;
ULONG status = ARGERR_NONE;
tableEntry = ArgumentArray;
while (tableEntry->ArgID[0]) {
length = strlen(tableEntry->ArgID);
if (tableEntry->ParseFlags & PF_NOI) {
found = (strncmp(tableEntry->ArgID, *Argument, length) == 0);
} else {
found = (_strnicmp(tableEntry->ArgID, *Argument, length) == 0);
}
if (found) {
break;
}
tableEntry++;
}
if (found) {
*Argument += length;
switch (tableEntry->ArgType) {
case AT_STRING:
case AT_NUM:
if (tableEntry->ParseFlags & PF_SEPARATOR)
{
if (**Argument &&
strchr(ProgramInfo->Separators, **Argument)) {
(*Argument)++;
} else {
status = ARGERR_NO_SEPARATOR;
break;
}
}
if (tableEntry->ArgType == AT_STRING) {
*(UCHAR **)tableEntry->ArgData = *Argument;
} else {
*(ULONG *)tableEntry->ArgData = (ULONG)
strtoul(*Argument, &argumentEnd, tableEntry->ArgParam);
if (*Argument == argumentEnd) {
status = ARGERR_INVALID_NUM;
break;
}
*Argument = argumentEnd;
}
if (tableEntry->ArgVerify) {
status = (*tableEntry->ArgVerify)(Argument, tableEntry);
}
break;
case AT_ENABLE:
case AT_DISABLE:
if (tableEntry->ArgType == AT_ENABLE) {
*(ULONG *)tableEntry->ArgData |= tableEntry->ArgParam;
} else {
*(ULONG *)tableEntry->ArgData &= ~tableEntry->ArgParam;
}
if ( tableEntry->ArgVerify) {
status = (*tableEntry->ArgVerify)(Argument, tableEntry);
if (status == ARGERR_NONE) {
break;
}
}
if (**Argument) {
if (strchr(ProgramInfo->SwitchChars, **Argument)) {
(*Argument)++;
}
status = ParseArgSwitch(
Argument,
ArgumentArray,
ProgramInfo
);
}
break;
case AT_ACTION:
if (tableEntry->ParseFlags & PF_SEPARATOR)
{
if (**Argument &&
strchr(ProgramInfo->Separators, **Argument)) {
(*Argument)++;
} else {
status = ARGERR_NO_SEPARATOR;
break;
}
}
#pragma warning(disable: 4055)
status = (*(PFNARG)tableEntry->ArgData)(Argument, tableEntry);
#pragma warning(default: 4055)
break;
}
} else {
status = ARGERR_UNKNOWN_SWITCH;
}
return status;
}
VOID
PrintError(
ULONG ErrorCode,
PUCHAR Argument,
PPROGINFO ProgramInfo
)
/*++
Routine Description:
Print Appropriate Error Message according to error code
Arguments:
ErrorCode - The error which occured
Argument - Argument in Error
ProgramInfo - Program info structure
Return Value:
VOID
--*/
{
switch (ErrorCode) {
case ARGERR_UNKNOWN_SWITCH:
fprintf(
stderr,
"%s: unknown switch \"%s\"\n",
ProgramInfo->ProgName,
Argument
);
break;
case ARGERR_NO_SEPARATOR:
fprintf(
stderr,
"%s: separator missing after the switch char '%c'\n",
ProgramInfo->ProgName,
*(Argument-1)
);
break;
case ARGERR_INVALID_NUM:
fprintf(
stderr,
"%s: invalid numeric switch \"%s\"\n",
ProgramInfo->ProgName,
Argument
);
break;
case ARGERR_INVALID_TAIL:
fprintf(
stderr,
"%s: invalid argument tail \"%s\"\n",
ProgramInfo->ProgName,
Argument
);
}
}
|
C
|
// Answers within 10^-5 of the true value will be accepted as correct.
// if it's 10^-5, it should use double !!!!!!!
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
double* sampleStats(int* count, int countSize, int* returnSize)
{
long sum = 0;
int num = 0;
int min_value = 0;
int max_value = 0;
int max_num = 0;
int max_num_value = 0;
double* r = malloc(sizeof(double) * 5);
for (int i = 0; i < 256; i ++)
{
sum += i * count[i];
num += count[i];
if (count[i])
{
if (!min_value)
min_value = i + 1;
max_value = i + 1;
if (max_num < count[i])
{
max_num = count[i];
max_num_value = i;
}
}
}
int median = 0;
int need = (num % 2) ? (num + 1) / 2 : (num / 2);
int i = 0;
for (i = 0; i < 256; i ++)
{
if (need <= count[i])
{
median = i;
break;
}
need -= count[i];
}
r[3] = median;
if (!(num % 2))
{
need += 1;
for (; i < 256; i ++)
{
if (need <= count[i])
{
median += i;
break;
}
need -= count[i];
}
r[3] = median / 2.0;
}
r[0] = min_value - 1;
r[1] = max_value - 1;
r[2] = sum / ((double) num);
r[4] = max_num_value;
*returnSize = 5;
return r;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_move.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: amorfan <amorfan@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2014/01/18 19:07:14 by amorfan #+# #+# */
/* Updated: 2014/01/18 19:57:33 by amorfan ### ########.fr */
/* */
/* ************************************************************************** */
#include "wolf.h"
void ft_dash_right(t_data *e)
{
e->pos.Py -= sin(ft_get_radian(e->pos.a - 90)) * 5;
e->pos.Px += cos(ft_get_radian(e->pos.a - 90)) * 5;
if (e->map[(int)(e->pos.Py / 64)][(int)(e->pos.Px / 64)] == 1)
ft_dash_left(e);
}
void ft_dash_left(t_data *e)
{
e->pos.Py -= sin(ft_get_radian(e->pos.a + 90)) * 5;
e->pos.Px += cos(ft_get_radian(e->pos.a + 90)) * 5;
if (e->map[(int)(e->pos.Py / 64)][(int)(e->pos.Px / 64)] == 1)
ft_dash_right(e);
}
void ft_move_up(t_data *e)
{
e->pos.Py -= sin(ft_get_radian(e->pos.a)) * 5;
e->pos.Px += cos(ft_get_radian(e->pos.a)) * 5;
if (e->map[(int)(e->pos.Py / 64)][(int)(e->pos.Px / 64)] == 1)
ft_move_down(e);
}
void ft_move_down(t_data *e)
{
e->pos.Py += sin(ft_get_radian(e->pos.a)) * 5;
e->pos.Px -= cos(ft_get_radian(e->pos.a)) * 5;
if (e->map[(int)(e->pos.Py / 64)][(int)(e->pos.Px / 64)] == 1)
ft_move_up(e);
}
void ft_move_left(t_data *e)
{
e->pos.a += 5;
if (e->pos.a > 359)
e->pos.a -= 359;
}
|
C
|
#include <stdio.h>
#include <conio.h>
int reverse() {
int n,rem,rvrno=0;
printf("Enter a number with 3 or more digits ");
scanf("%d",&n);
while(n!=0){
rem=n%10;
rvrno=rvrno*10+rem;
n/=10;
}
return(rvrno);
}
void main() {
int reverse(void);
int rev;
rev=reverse();
printf("Reversed Number is %d",rev);
getch();
}
|
C
|
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
int main() {
int number = 0;
int numberToFind = 101;
bool foundNumber = false;
while (true) {
if (foundNumber) return printf("Found it");
if (number == 100 && !foundNumber) {
printf("Number not found");
break;
};
if (number == numberToFind) foundNumber = true;
number++;
};
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mboivin <mboivin@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/10/01 13:30:41 by mboivin #+# #+# */
/* Updated: 2021/01/02 16:12:31 by mboivin ### ########.fr */
/* */
/* ************************************************************************** */
#include "minishell.h"
int main(int argc, char **argv, char **envp)
{
t_shctrl ft_sh;
(void)argv;
/* Si argc != 1, on affiche le message d'usage car minishell ne prend aucun arg */
if (argc != NO_ARGS)
print_usage();
/* On récupère l'env et on set quelques variables */
start_shell(envp);
/* cf. commentaire ci-dessous */
create_shell(&ft_sh);
/* Boucle qui attend l'input utilisateur */
return (shell_loop(&ft_sh));
}
/*
** Fichier src/subsystems/sh_ctrl.c
**
** On init les éléments du shell à NULL
**
** void create_shell(t_shctrl *ft_sh)
** {
** ft_sh->lexer = NULL;
** ft_sh->ast = NULL;
** ft_sh->cmd = NULL;
** }
*/
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define tam 25
int campo[10][10], op[10][10], countbombas[100];
pthread_mutex_t mutex_bomba[25];
pthread_t gerando[25];
int verificaBomba(int linha, int coluna, int comparado)
{
int z;
for(z=0; z<tam; z++)
{
if(op[linha][coluna] == comparado)
{
return 1;
}
}
return 0;
}
void imprime_inicio() //ESSA FUN��O SERVE PRA IMPRIMIR O ESTADO INICIAL DO CAMPO MINADO
{
int i, j, z=0;
system("clear");
for(i=0; i<10; i++)
{
for(j=0; j<10; j++)//imprime e seta o campo ao mesmo tempo
{
campo[i][j] = z;
z++;
if(z<10)
{
printf("| %d ", campo[i][j]);
}
else
printf("| %d ", campo[i][j]);
}
printf("\n");
}
}
//FUN��ES PARA GERAR AS BOMBAS PARALELAMENTE UTILIZANDO THREADS
void gerando(int * bomba)//AQUI � BLOQUEADO O ACESSO QUE EST� SENDO UTILIZADO
{
pthread_mutex_lock(&(mutex_bomba[*bomba]));
}
void acabou_gerar(int * bomba)//AQUI � LIBERADO O ACESSO AP�S O USO
{
pthread_mutex_unlock(&(mutex_bomba[*bomba]));
}
void * gera_bombas(void *var)//FUN��O PARA GERAR AS BOMBAS
{
int * bomba = (int *) (var);
srand(time(NULL));
int tempo = rand() % 10;
int aux,contador;
sleep(tempo);//� DEFINIDO UM TEMPO ALEAT�RIO PARA AS THREADS N�O ACESSAREM AO MESMO TEMPO
gerando(bomba);//BLOQUEIA O ACESSO
do
{
int linha = rand() % 10;
int coluna = rand() % 10;
}while(verificaBomba(linha, coluna, op[linha][coluna]));
op[linha][coluna] = -1; //-1 � O VALOR ATRIBUIDO �S BOMBAS
acabou_gerar(bomba);//LIBERA O ACESSO A FUN��O
pthread_exit(NULL);
}
void gera_dicas(void){
int i,j,aux,k=0;
for(i=0;i<10;i++){
for(j=0;j<10;j++){
if(op[i--][j--]==-1 && i>0 && j>0)
aux++;
else if(op[i--][j]==-1 && i>0)
aux++;
else if(op[i--][j++]==-1 && i>0 && j<10)
aux++;
else if(op[i][j++]==-1 && j<10)
aux++;
else if(op[i][j--]==-1 && j>0)
aux++;
else if(op[i++][j--]==-1 && i<10 && j>0)
aux++;
else if(op[i++][j]==-1 && i<10)
aux++;
else if(op[i++][j++]==-1 && i<10 && j<10)
aux++;
countbombas[k]=aux;
aux=0;
k++;
}
}
}
void atualiza_op(void){//pega agora o vetor countbombas e atualiza a matriz op para colocar as dicas
int i,j,k=0;
for(i=0;i<9;i++){
for(j=0;j<9;j++){
if(op[i][j] != -1)
op[i][j]=countbombas[k];
k++;
}
}
}
|
C
|
#include <p18cxxx.h>
#include <delays.h>
#define HIGH 1
#define LOW 0
#define CS PORTBbits.RB5
#define DATA_bit PORTBbits.RB6
#define SERCLK PORTBbits.RB7
#define delay_us Delay10TCYx
// function declarations
void ssrOut(unsigned char);
void pulseCS(void);
void init_MAX7219(void);
void writeMAX7219(char, char);
void delay_ms(int);
void init_18F2250(void);
// See c018i.c in your C18 compiler dir
extern void _startup( void );
#pragma code _RESET_INTERRUPT_VECTOR = 0x000800
void _reset( void )
{
_asm goto _startup _endasm
}
#pragma code
int i, j, digit, count;
void main()
{
init_18F2550();
init_MAX7219();
count = 9999;
// convert to BCD send to MAXMAX7219
for (i=0; i<=count; i++) {
j = i;
// get 1st digit of j
digit = j % 10; // MOD J
writeMAX7219(1, digit);
// get 2nd digit of j
j = j / 10;
digit = j % 10; // MOD j
writeMAX7219(2, digit);
// get 3rd digit of j
j = j / 10;
digit = j % 10; // MOD j
writeMAX7219(3, digit);
// get 4th digit of j
j = j / 10;
digit = j % 10; // MOD j
writeMAX7219(4, digit);
delay_ms(200);
} // end for
} //end main
// shift data to MAX7219
// Rb7 -> SERCLK, Rb6 -> DATA_bit, Rb5 -> CS not
void ssrOut(unsigned char val) {
int j;
for(j=1; j<=8; j++) { // shift out MSB first
unsigned char temp = val & 0x80; // MSB out first
if (temp == 0x80) DATA_bit = HIGH; // Rb6 DATA
else DATA_bit = LOW;
SERCLK = HIGH;
delay_us(20);
SERCLK = LOW;
val = val << 1; // shift one place left
} // next j
}
void writeMAX7219(char address, char data) {
if ((address < 1) || (address > 8)) return;
ssrOut(address); // valid numbers 1-8
ssrOut(data);
pulseCS();
}
void pulseCS(void)
{
CS = HIGH;
delay_ms(1);
CS = LOW;
}
void init_MAX7219(void)
{
CS = LOW; // CS NOT
// set decode mode
ssrOut(0x09); // address
// ssrOut(0x00); // no decode
ssrOut(0xFF); // 4-bit BCD decode eight digits
pulseCS();
// set intensity
ssrOut(0x0A); // address
ssrOut(0x0D); // 5/32s
pulseCS();
// set scan limit 0-7
ssrOut(0x0B); // address
// ssrOut(0x07); // 8 digits
ssrOut(0x03); // 4 digits
pulseCS();
// clear MAX7219 all zeros
// BCD mode all off otherwise
for(i=1; i<=8; i++)
{
ssrOut(i);
ssrOut(0x00);
pulseCS();
}
// set for normal operation
ssrOut(0x0C); // address
// ssrOut(0x00); // Off
ssrOut(0x01); // On
pulseCS();
}
void delay_ms(int i)
{
long int j;
for(j=0;j<i;j++)
{
Delay1KTCYx(12); //48 MHZ, DELAY OF 1 MS APPROX.
}
}
//Ports initialized etc.
void init_18F2250(void) {
// disables converters A/D
ADCON1=0x0F;
// comparators off
CMCON=7;
//PORTB are outputs
TRISB=0;
// off LEDs
PORTB=0;
//Ra4,Ra5 are inputs Ra0,Ra1,Ra2,Ra3 outputs
TRISA=0X30;
//Rc0,Rc1 are inputs (MICRO SWITCHES)
TRISC=0X0F;
//select pull-up resistors on port B (Rb4...Rb7).
INTCON2bits.RBPU=0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main_de_test.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: fgiverna <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/08/10 15:01:28 by fgiverna #+# #+# */
/* Updated: 2017/08/10 15:18:37 by fgiverna ### ########.fr */
/* */
/* ************************************************************************** */
#include <stdio.h>
int ft_str_is_printable(char *str);
int main(void)
{
char str[] = "dbhwkbek12782175AAUDMKS:S!@#$^&*)*(+-<>?[]{ }";
char str1[] = "";
char str2[] = "hello\n\t\r";
char str3[] = "jdjkZANANjdewkl";
char str4[] = "\vaA";
int ret;
ret = ft_str_is_printable(str);
printf("Testinig %s : %d, expected 1\n", str, ret);
ret = ft_str_is_printable(str1);
printf("Testing %s : %d, expected 1\n", str1, ret);
ret = ft_str_is_printable(str2);
printf("Testing %s : %d, expected 0\n", str2, ret);
ret = ft_str_is_printable(str3);
printf("Testing %s : %d, expected 1\n", str3, ret);
ret = ft_str_is_printable(str4);
printf("Testing %s : %d, expected 0\n", str4, ret);
return (0);
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
void anagram(char *arr){
char *ptr = arr;
int length = 0;
char save = *ptr;
while(save != '\0'){
save = *(++ptr);
length++;
}
if(length%2 == 1){
printf("-1\n");
return;
}
ptr = arr;
char *ptr2 = arr;
ptr2+=length/2;
int dist = 0;
int map1[27];
int map2[27];
int i;
for(i=0;i<27;i++){
map1[i]=0;
map2[i]=0;
}
while(*ptr2 != '\0'){
map1[(int)(*ptr-'a')]++;
map2[(int)(*ptr2-'a')]++;
ptr++;
ptr2++;
}
for(i=0;i<27;i++){
int temp = map1[i] - map2[i];
if(temp < 0){
temp*=-1;
}
dist+=temp;
}
dist/=2;
printf("%d\n",dist);
}
int main() {
int loops;
scanf("%d",&loops);
while(loops-->0){
//char arr[33721];
char *arr = malloc(sizeof(char)*100000);
scanf("%s",arr);
anagram(arr);
free(arr);
}
//makePalind(argv[1]);
return 0;
}
|
C
|
#include "monty.h"
/**
* free_stack - Free stack
* @head: stack to free
*/
void free_stack(stack_t *head)
{
stack_t *save;
while (head != NULL)
{
save = head;
head = head->next;
free(save);
}
}
/**
* add_stack - add to stack
* @head: stack
* @n: line
* Return: 1 if ok
*/
int add_stack(stack_t **head, int n)
{
stack_t *save;
save = malloc(sizeof(stack_t));
if (save == NULL)
{
printf("Error: malloc falided\n");
return (-1);
}
save->n = n;
save->prev = NULL;
if (*head == NULL)
{
save->next = NULL;
*head = save;
}
else
{
save->next = *head;
(*head)->prev = save;
*head = save;
}
return (1);
}
/**
* print_stack - Print all stack
* @head: stack
* Return: 0 if is ok
*/
int print_stack(stack_t **head)
{
stack_t *temp;
temp = (*head);
if (temp == NULL)
{
return (-1);
}
while (temp != NULL)
{
printf("%d\n", temp->n);
temp = temp->next;
}
return (0);
}
/**
* dhead_stack - delete in head of stack
* @head: stack
* Return: 1 if ok
*/
int dhead_stack(stack_t **head)
{
stack_t *save;
if (*head == NULL)
{
return (-1);
}
save = (*head);
if (save->next == NULL)
{
free(save);
(*head) = NULL;
return (1);
}
(*head) = (*head)->next;
(*head)->prev = NULL;
free(save);
return (1);
}
|
C
|
#include "PCF8574.h" // Required for PCF8574
PCF8574 pcf4;
String buttonColor[5] = {"red", "green", "blue", "pink", "none"};
bool eventButton[5] = {false, false, false, false, false};
void initButtonPanel(){
pcf4.begin(0x24);
for(byte i = 0; i < 4; i++){
pcf4.pinMode(i, INPUT_PULLUP);
}
pcf4.pinMode(4, INPUT);
pcf4.digitalWrite(4, HIGH);
for(byte i = 0; i < 4; i ++){
pcf4.pinMode(i+5, OUTPUT);
pcf4.digitalWrite(i+5, HIGH);
}
}
void setColorButton(String color){
if( color == "red"){
pcf4.digitalWrite(5, LOW);
pcf4.digitalWrite(6, HIGH);
pcf4.digitalWrite(7, HIGH);
}
else if(color == "blue"){
pcf4.digitalWrite(5, HIGH);
pcf4.digitalWrite(6, HIGH);
pcf4.digitalWrite(7, LOW);
}
else if(color == "green"){
pcf4.digitalWrite(5, HIGH);
pcf4.digitalWrite(6, LOW);
pcf4.digitalWrite(7, HIGH);
}
else if(color == "pink"){
pcf4.digitalWrite(5, LOW);
pcf4.digitalWrite(6, HIGH);
pcf4.digitalWrite(7, LOW);
}
else if(color == "none"){
pcf4.digitalWrite(5, HIGH);
pcf4.digitalWrite(6, HIGH);
pcf4.digitalWrite(7, HIGH);
}
}
void readEventButtons(){
for(byte i = 0; i < 5; i++){
if(pcf4.digitalRead(i) == LOW){
eventButton[i] = true;
}
else eventButton[i] = false;
}
}
|
C
|
#include <stdlib.h>
#include <string.h>
#include "lists.h"
/**
* sum_listint - check the code .
* @head: list
* Return: Always .
*/
int sum_listint(listint_t *head)
{
listint_t *tmp;
int sum = 0;
if (!head)
return (0);
tmp = head;
while (tmp)
{
sum += tmp->n;
tmp = tmp->next;
}
return (sum);
}
|
C
|
/*
Escriba un programa que lea dos enteros y que determine
e imprima si el primero es mltiplo del segundo. [Pista:
Utilice el operador mdulo.]
*/
#include<stdio.h>
int main(){
int p, s;
printf("Escriba 2 numeros: ");
scanf("%d%d", &p, &s);
if (p%s==0){
printf("%d es multiplo de %d", p, s);
}
if (p%s==1){
printf("%d no es multiplo de %d", p, s);
}
return 0;
}
|
C
|
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<stdio.h>
int main(void)
{
int fd, len;
char buf[20];
if ((fd = open("tempfile", O_RDWR | O_CREAT | O_TRUNC, 0666)) == -1)
{
printf("open error\n");
return 1;
}
unlink("tempfile");
if(write(fd, "How are you?", 12) != 12)
{
printf("write error\n");
return 1;
}
lseek(fd, 0L, SEEK_SET);
if((len = read(fd, buf, sizeof(buf))) <=0){
printf("read error\n");
return 1;
}
else buf[len] = '\0';
printf("%s\n", buf);
close(fd);
if ((fd = open("tempfile", O_RDWR)) < 0)
{
printf("Second open error\n");
return 1;
}
close(fd);
return 0;
}
|
C
|
/*This is a function for sorting an array useing merge.c
*
*Author: Eric
*Time: 2011.01.08
*/
#include <stdio.h>
#include "main.h"
#include "merge.h"
/*Sort array a, from a[begin] to a[upend-1]*/
void sort(int *a, int begin, int upend)
{
int n = upend - begin; /*the number to be sorted*/
/*The first array is a[idxa] to a[idxb-1]. The second is a[idxb] to a[idxc-1]*/
int idxa = begin,
idxb = ((begin+upend)%2 == 0) ? (begin+upend)/2 : (begin+upend+1)/2,
idxc = upend;
if(n < 2)
{
printf("The array elements are less than two. No need to sort\n");
return;
}
else if(n == 2)
merge(a, idxa, idxb, idxc);
else
{
if(idxb-idxa > 1)
sort(a, idxa, idxb);
if(idxc-idxb > 1)
sort(a, idxb, idxc);
merge(a, idxa, idxb, idxc);
}
}
#ifndef MAIN
#define MAIN
/*For test*/
int main()
{
int a[10] = {1, 4, 8, 5, 10, 25, 54, 15, 12, 2};
int i = 0;
sort(a, 0, 10);
printf("The sorted array is:");
for(i = 0; i < 10; i++)
printf(" %d", a[i]);
printf("\n");
return 0;
}
#endif
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/select.h>
#include <fcntl.h>
#include <errno.h>
#include "potato.h"
void make_fifos(char *fifos_name[], int index) {
if ((mkfifo(fifos_name[index], FILE_MODE) < 0) && (errno != EEXIST)) {
perror("mkfifo() error");
exit(1);
}
}
void build_left_fifos(char *fifos_name[], int player_id, int total_players) {
if (player_id == 0) {
int left_neighbor = total_players - 1;
sprintf(fifos_name[2], "/tmp/p%d_p%d", left_neighbor, player_id);
sprintf(fifos_name[3], "/tmp/p%d_p%d", player_id, left_neighbor);
}
else {
int left_neighbor = player_id - 1;
sprintf(fifos_name[2], "/tmp/p%d_p%d", left_neighbor, player_id);
sprintf(fifos_name[3], "/tmp/p%d_p%d", player_id, left_neighbor);
}
make_fifos(fifos_name, 2);
make_fifos(fifos_name, 3);
}
void build_right_fifos(char *fifos_name[], int player_id, int total_players) {
if (player_id == total_players - 1) {
int right_neighbor = 0;
sprintf(fifos_name[4], "/tmp/p%d_p%d", right_neighbor, player_id);
sprintf(fifos_name[5], "/tmp/p%d_p%d", player_id, right_neighbor);
}
else {
int right_neighbor = player_id + 1;
sprintf(fifos_name[4], "/tmp/p%d_p%d", right_neighbor, player_id);
sprintf(fifos_name[5], "/tmp/p%d_p%d", player_id, right_neighbor);
}
make_fifos(fifos_name, 4);
make_fifos(fifos_name, 5);
}
int main(int argc, char *argv[]) {
//check command line argument
if (argc != 2) {
printf("wrong input, should be: ./player <player_id>\n");
return EXIT_FAILURE;
}
int player_id = atoi(argv[1]);
//printf("player:%d\n", player_id);
//initilize the game
int total_players;
int fifos[6];
char *fifos_name[6];
int m;
for (m = 0; m < 6; m++) {
fifos_name[m] = malloc(20 * sizeof(char));
}
POTATO_T potato;
sprintf(fifos_name[0], "/tmp/master_p%d", player_id); //make fifos with master: 0 from, 1 to master
make_fifos(fifos_name, 0);
fifos[0] = open(fifos_name[0], O_RDWR);
if (fifos[0] < 0) {
printf("player open1 %s failed\n", fifos_name[0]);
perror("player open1");
return EXIT_FAILURE;
}
sprintf(fifos_name[1], "/tmp/p%d_master", player_id);
make_fifos(fifos_name, 1);
fifos[1] = open(fifos_name[1], O_RDWR);
if (fifos[1] < 0) {
printf("open1 %s failed\n", fifos_name[1]);
perror("open1");
return EXIT_FAILURE;
}
//give init message to ringmaster
potato.msg_type = PLAYER_INIT;
potato.hop_trace[0] = player_id;
write(fifos[1], &potato, sizeof(struct potato));
//read from ring master
for (;;) {
fd_set fds;
int fd = fifos[0];
FD_ZERO(&fds);
FD_SET(fd, &fds);
select(fd + 1, &fds, NULL, NULL, NULL);
if (FD_ISSET(fd, &fds)) {
read(fifos[0], &potato, sizeof(struct potato));
if (potato.msg_type == RING_MASTER_INIT) {
total_players = potato.total_players;
if (player_id >= total_players) {
printf("player_id should be less than %d\n", total_players);
return EXIT_FAILURE;
}
printf("Connected as player %d out of %d total players\n", player_id, total_players);
close(fifos[0]);
close(fifos[1]);
//build fifos with left neighbor
build_left_fifos(fifos_name, player_id, total_players);
//build fifos with right neighbor
build_right_fifos(fifos_name, player_id, total_players);
goto open;
}
}
}
open: ;
/* int x;
for (x = 0; x < 6; x++) {
printf("%s\n", fifos_name[x]);
}*/
int i;
for (i = 0; i < 3; i++) {
fifos[2 * i] = open(fifos_name[2 * i], O_RDWR);
if (fifos[2 * i] < 0) {
printf("open2 %s failed\n", fifos_name[2 * i]);
perror("open2");
return EXIT_FAILURE;
}
//printf("player %d try to open %s\n", player_id, fifos_name[2 * i]);
fifos[2 * i + 1] = open(fifos_name[2 * i + 1], O_RDWR);
if (fifos[2 * i + 1] < 0) {
printf("open3 %s failed\n", fifos_name[2 * i + 1]);
perror("open3");
return EXIT_FAILURE;
}
//printf("player %d try to open %s\n", player_id, fifos_name[2 * i + 1]);
}
//printf("open finish\n");
//receive potato
for (;;) {
int k;
for(k = 0; k < 3; k++) {
fd_set fds;
int fd = fifos[2 * k];
FD_ZERO(&fds);
FD_SET(fd, &fds);
struct timeval tv;
tv.tv_sec = 0.1;
tv.tv_usec = 0;
select(fd + 1, &fds, NULL, NULL, &tv);
POTATO_T hot_potato;
if (FD_ISSET(fd, &fds)) {
read(fd, &hot_potato, sizeof(struct potato));
if (hot_potato.msg_type == GAME_STARTED) {
//printf("player %d receive potato\n", player_id);
--hot_potato.total_hops;
if (hot_potato.total_hops < 0) {
write(fifos[1], &hot_potato, sizeof(struct potato));
}
else {
hot_potato.hop_trace[hot_potato.hop_count++] = player_id;
//hot_potato.hop_count++;
if (hot_potato.total_hops == 0) {
printf("I'm it\n");
write(fifos[1], &hot_potato, sizeof(struct potato));
}
if (hot_potato.total_hops > 0) {
srand(hot_potato.total_hops);
int random = rand() % 2;
//printf("random is %d\n", random);
if (random == 1) { //send to left neighbor
if (player_id == 0) {
printf("Sending potato to %d\n", total_players -1);
}
else {
printf("Sending potato to %d\n", player_id - 1);
}
write(fifos[3], &hot_potato, sizeof(struct potato));
}
else { //send to right neighbor
if (player_id == total_players - 1) {
printf("Sending potato to %d\n", 0);
}
else {
printf("Sending potato to %d\n", player_id + 1);
}
write(fifos[5], &hot_potato, sizeof(struct potato));
}
//printf("send potato finish\n");
}
}
}
if (hot_potato.msg_type == GAME_OVER) {
goto over;
}
}
}
}
over:;
int j;
//printf("after open\n");
//close(fifos[0]);
//close(fifos[1]);
for(j = 0 ; j < 6; j++) {
//printf("players fifos: %s\n", fifos_name[j]);
close(fifos[j]);
unlink(fifos_name[j]);
free(fifos_name[j]);
}
//printf("player %d exit\n", player_id);
return EXIT_SUCCESS;
}
|
C
|
#include <hidef.h> /* common defines and macros */
#include "derivative.h" /* derivative-specific definitions */
#include <stdio.h>
#include <termio.h>
#include <stdlib.h>
//float asciiToFloat(byte* line);
#define FreqClockA 2000000 // Value on Reset (PWMPRCLK = 0x00)
//assigns values to the PWM registers
//and returns the actual frequency of the signal generated by those values.
float setPWM(float frequency, float duty_cycle)
{
float actualFrequency;
int quotent=(1000000/frequency);
int s,p;
int freq;
for(s=1; s<254; s++)
{
for(p=1; p<254; p++)
{
if(s*p==quotent)
{
printf("s=%d, p=%d\r\n",s,p);
//actualFrequency = 2000000 / (2 * ((float)PWMPER5 * (float)PWMSCLA));
actualFrequency = 2000000 / (2 * ((float)p * (float)s));
freq=1000000/(s*p);
PWMSCLA = s; //PWMSCLA;
PWMDTY5 = (duty_cycle*p)/100;
PWMPER5 = (PWMDTY5/duty_cycle)*100;//1/freq;///255;//p; //1000000/p;
return actualFrequency;
}
}
}
}
float asciiToFloat(char line [])
{
//unsigned num = 0, digit;
//unsigned i=0;
//while(line[i]!=0x00 && line[i]<0x3A)
//{
// digit=line[i]-0x30;
// num=num*10+digit;
// i++;
//}
return atof(line);
}
byte getChar()
{
char input;
while( SCISR1_RDRF == 0 ) {};
input = (char) SCIDRL;
return input;
}
byte* getLine()
{
byte line [80];
char input;
int i=0;
while(1)
{
input = getChar();
if(input =='\r' || input =='\n')
return line;
line[i]=input;
i++;
}
}
void delay(word d)
{
int constant=350;
int i;
while(d>0)
{
i = constant;
while(i>0)
i--;
d--;
}
}
void initializePorts()
{
///////////// Serial port ///////////////////////////
SCIBD = 52; // 2400 baud if SCI clock is 2 MHz
SCICR2 = 0x0C; // Enable receiver and transmitter
/////// PWM module ///////////////////////////////////
PWMCLK_PCLK5 = 1; // Select Clock SA for channel 5
PWMPRCLK = 0x00; // Set Clock A = BusClock = 2 MHz
PWMSCLA = 10; // Set Clock SA = Clock A / (2 * 10)
PWMPER5 = 200; // Set period of channel 5; output freq = freq of ClkA / period
PWMDTY5 = 150; // Set Duty Cycle of channel 5
PWMPOL_PPOL5 = 1; // Make first part of period high; switch to low when
// count = duty. This means motor speed will be low for
// small values of duty and high for large values of duty.
PWME_PWME5 = 1; // Enable PWM channel 5 (connect PWM output to PP5)
;
}
void main(void)
{
float actualFrequency;
float actualDutyCycle;
float frequency;
float duty_cycle;
byte line[80];
byte * freq_input;
byte * duty_input;
int test=1000;
initializePorts();
printf("\r\n\r\nDay 19 Demo\r\n");
actualFrequency = 2000000 / (2 * ((float)PWMPER5 * (float)PWMSCLA));
sprintf(line, "Actual Frequency = %.2f\r\n", actualFrequency);
printf(line);
actualDutyCycle = 100.0 * PWMDTY5 / PWMPER5;
sprintf(line, "Actual Duty Cycle = %.2f\r\n", actualDutyCycle);
printf(line);
while (1)
{
printf("\r\nEnter Frequency");
freq_input=getLine(); //Hz
frequency=asciiToFloat(freq_input);
sprintf(line, "=%f\r\n", frequency);
printf(line);
printf("Enter Duty Mode");
duty_input=getLine(); // %
duty_cycle=asciiToFloat(duty_input);
printf("=%f\r\n", duty_cycle);
actualFrequency=setPWM(frequency, duty_cycle);
printf("PWMPER5=%d\r\n", PWMPER5);
printf("PWMDTY5=%d\r\n", PWMDTY5);
printf("PWMSCLA=%d\r\n", PWMSCLA);
sprintf(line, "Actual Frequency = %.2f\r\n", actualFrequency);
printf(line);
actualDutyCycle = (float)((float)PWMDTY5/(float)PWMPER5) * 100;
sprintf(line, "Actual Duty Cycle = %.2f\r\n", actualDutyCycle);
printf(line);
}// End while
} // End main
|
C
|
#include <stdio.h>
int main(void)
{
freopen("/var/log/kern.log", "r", stdin);
freopen("user.out", "w", stdout);
char s[100];
while (gets(s) != EOF)
{
printf("%s", s);
}
return 0;
}
|
C
|
#include "holberton.h"
/**
* _getenv - retrieves env variable that matches input string
* @input: input string
* @environ: local environmental variables
* Return: string of env variable
*/
char *_getenv(char *input, char **environ)
{
register int i = 0;
char *tok, *right;
while (environ[i])
{
tok = strtok(environ[i], "=");
if (_strcmp(tok, input) == 0)
{
right = strtok(NULL, "=");
return (right);
}
i++;
}
return (NULL);
}
/**
* generateLinkedList - generates a linked list of environ
* variables
* @array: input array of strings
* Return: head of linked list
*/
linked_l *generateLinkedList(char **array)
{
register int i = 0;
linked_l *head;
head = NULL;
while (array[i])
{
addNodeEnd(&head, array[i]);
i++;
}
return (head);
}
/**
* addNodeEnd - adds a new node at the end of a linked_l list;
* @head: reference to head of list
* @str: string to be added to linked list
* Return: address of new node
*/
linked_l *addNodeEnd(linked_l **head, char *str)
{
linked_l *newNode;
linked_l *last = *head;
char *newStr;
if (!str)
return (NULL);
newNode = malloc(sizeof(linked_l));
if (!newNode)
{
perror("Malloc failed\n");
exit(errno);
}
newStr = _strdup(str);
if (!newStr)
{
free(newNode);
perror("Malloc failed\n");
exit(errno);
}
newNode->string = newStr;
newNode->next = NULL;
if (!*head)
{
*head = newNode;
return (newNode);
}
while (last->next)
last = last->next;
last->next = newNode;
return (last);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.