language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C
|
#include <stdio.h>
void reverse(char *str, int start, int end);
int main()
{
char str[80] = "teri maa ki saaree";
int i, start = 0;
for (i=0 ; str[i]!= '\0'; i++)
{
if (str[i] == ' ')
{
reverse(str, start, i);
start = i+1;
}
}
reverse(str, start, i);
printf("\nReversed: %s", str);
}
void reverse(char *str, int start, int end)
{
int j,k, mid;
mid = start + ((end-start)/2);
char temp;
for (j =start, k=end-1; j <= mid; j++, k--)
{
temp = str[j];
str[j] = str[k];
str[k] = temp;
}
}
|
C
|
#ifndef _linkedlist_h_
#define _linkedlist_h_
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define OK (0)
#define ERROR (-1)
typedef void* Type;
struct _List_Node{
Type *data;
struct _List_Node *next;
struct _List_Node *prior;
};
typedef struct _List_Node List_Node;
struct _Linkedlist{
int size;
List_Node *head;
};
typedef struct _Linkedlist Linkedlist;
Linkedlist *linkedlist_create();
void linkedlist_free(Linkedlist *list);
int linkedlist_add(Linkedlist *list,Type add_data);
int linkedlist_add_at_index(Linkedlist *list,int index,Type add_data);
int linkedlist_remove_at_index(Linkedlist *list,int index);
int linkedlist_remove_element(Linkedlist *list,Type remove_item);
Type linkedlist_get_element(Linkedlist *list,int index);
List_Node *linkedlist_create_list_node(Type data);
int linkedlist_remove_node(Linkedlist *list,List_Node *p);
#endif
|
C
|
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <string.h>
main()
{
int aux, somadig=0, dig1, dig2, dig3, dig4, dig5, cc, dv, dv2, somad;
printf("Informe a conta conrrente:");
scanf("%d", &cc);
dig5 = cc%10;
aux = cc/10;
dig4 = aux%10;
aux = aux/10;
dig3 = aux%10;
aux = aux/10;
dig2 = aux%10;
dig1 = aux/10;
somadig = dig1 + dig2 + dig3 + dig4 + dig5;
if (somadig >= 10)
{
dig1 = somadig%10;
dig2 = somadig/10;
somadig = dig1 + dig2;
if (somadig >= 10){
dig1 = somadig%10;
dig2 = somadig/10;
somadig = dig1 + dig2;
}
}
printf("O digito verificador: %d", &somadig);
}
|
C
|
/**
* Judge Online: Caribbean Online Judge.
* URL: http://coj.uci.cu/24h/problem.xhtml?pid=2422
* Problem: 2422 - Betty and the Modular Exponentiation
* Description
*
* Betty likes integer–number mathematics, and knows that calculating something like a^b
* can produce rather large results when a and b are sufficiently big. Furthermore, Betty is
* only interested in knowing the last 9 digits from a^b. For this reason, she has hired you,
* a member of the Union for Tremendous Powers (UTP), to tell her the 9 least significant digits
* from the exponentiation.
**/
#include <stdio.h>
#define mod 1000000000
long long power(long long x, long long y){
long long int res = 1; // Initialize result
x = x % mod; // Update x if it is more than or
while (y > 0){
if (y & 1)
res = ((res%mod)*(x%mod)) % mod;
y = y>>1; // y = y/2
x = ((x%mod)*(x%mod)) % mod;
}
return res;
}
int main(void){
int t;
long long a, b;
scanf("%d", &t);
while(t--){
scanf("%ld %ld", &a, &b);
printf("%lld\n", power(a,b));
}
return 0;
}
|
C
|
#include <stdio.h> //Standar inputs and outputs, has the main functions in c
#include <stdlib.h> //Standar library, it contains functions and manage processes
#include <string.h> //It contains macro definitions, constants and declarations of functions
#include <math.h> //Defines various mathematical functions and one macro
///////////////////////////////////////////////////////////////////////////////////
///////// Classroom exercises with addition, FizzBuzz test, hypotenuse. //////////
/////////////////////////////////////////////////////////////////////////////////
//Addition
int add_two_int(int x,int y) //Function add of two arguments called x and y
{
return x+y; // The operation (addition)
// Put "return" because the function is going to return the value of the operation
}
int main()
{
int n1 = 4, n2 = 6; //Declaration of the variables
printf("The sum of the number is: %d",add_two_int(n1,n2)); //Prints the result using the
//function (10)
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
struct PunchCard {
int *r1;
int *r2;
int *r3;
};
/* LOL punchcard lol lol lol whoops */
void radixIsort(struct PunchCard p, int col, int len) {
int *ptr;
switch(col) {
case 2:
ptr = p.r3;
break;
case 1:
ptr = p.r2;
break;
case 0:
ptr = p.r1;
break;
}
int i, x, y, z;
for (int j = 1; j < len; j++) {
x=ptr[j];
if (col == 2) {
y=p.r2[j];
z=p.r1[j];
}
if (col == 1) {
y=p.r3[j];
z=p.r1[j];
}
if (col == 0) {
y=p.r3[j];
z=p.r2[j];
}
i = j-1;
while ( i > 0 && ptr[i] > x ) {
ptr[i+1] = ptr[i];
if (col == 2) {
p.r2[i+1] = p.r2[i];
p.r1[i+1] = p.r1[i];
}
if (col == 1) {
p.r3[i+1] = p.r3[i];
p.r1[i+1] = p.r1[i];
}
if (col == 0) {
p.r3[i+1] = p.r3[i];
p.r2[i+1] = p.r2[i];
}
i = i - 1;
}
ptr[i+1] = x;
if (col == 2) {
p.r2[i+1] = y;
p.r1[i+1] = z;
}
if (col == 1) {
p.r3[i+1] = y;
p.r1[i+1] = z;
}
if (col == 0) {
p.r3[i+1] = y;
p.r2[i+1] = z;
}
}
}
void radixSort(int *r1, int *r2, int *r3, int len) {
struct PunchCard punch;
punch.r1 = r1;
punch.r2 = r2;
punch.r3 = r3;
radixIsort(punch,2,len);
radixIsort(punch,1,len);
radixIsort(punch,0,len);
}
int main(void) {
// my punch card split in three rows
int *r1 = malloc(sizeof(int)*10);
int *r2 = malloc(sizeof(int)*10);
int *r3 = malloc(sizeof(int)*10);
r1[0] = 0; r2[0] = 9; r3[0] = 7;
r1[1] = 1; r2[1] = 2; r3[1] = 3;
r1[2] = 8; r2[2] = 2; r3[2] = 7;
r1[3] = 3; r2[3] = 1; r3[3] = 3;
r1[4] = 2; r2[4] = 2; r3[4] = 3;
r1[5] = 5; r2[5] = 2; r3[5] = 1;
r1[6] = 2; r2[6] = 1; r3[6] = 5;
r1[7] = 5; r2[7] = 0; r3[7] = 8;
r1[8] = 6; r2[8] = 4; r3[8] = 2;
r1[9] = 1; r2[9] = 5; r3[9] = 1;
for (int i = 0; i < 10; i++) {
printf("%d%d%d, ", r1[i],r2[i],r3[i]);
}
printf("\n");
radixSort(r1,r2,r3, 10);
for (int i = 0; i < 10; i++) {
printf("%d%d%d, ", r1[i],r2[i],r3[i]);
}
printf("\n");
}
|
C
|
// RLG20141229
// analogue.c = read an analogue voltage and vary the brightness of an LED
#include <avr/io.h>
#include <util/delay.h>
int main(void)
{
// volatile unsigned int val, val2;
volatile unsigned int val;
DDRB |= 0xff;
PORTC |= 0x01;
//ADMUX |= (1 << ADLAR); // left-adjust result
ADMUX |= (1 << REFS0);
ADCSRA |= (1 << ADPS1) | (1 << ADPS0); // prescale of 8 (1MHz >> 125KHz)
ADCSRA |= (1 << ADEN);
for(;;) {
ADCSRA |= (1 << ADSC);
while (ADCSRA & (1 << ADSC))
;
val = ADCL;
val = (ADCH << 8) | val;
// val = ADCH;
PORTB |= 0b00100000;
_delay_loop_2(val << 6);
_delay_loop_2(val << 6);
_delay_loop_2(val << 6);
_delay_loop_2(val << 6);
PORTB &= ~0b00100000;
_delay_loop_2(val << 6);
_delay_loop_2(val << 6);
_delay_loop_2(val << 6);
_delay_loop_2(val << 6);
if (val > 1000) {
PORTB |= 0b00000100;
} else {
PORTB &= 0b11111011;
}
}
return(0);
}
|
C
|
//Encontrar o numero de elementos pares, numero de elementos impares e numero de elementos primos de um vetor aleatorio
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include<math.h>
#include<time.h>
#include"timer.h"
long int dim; //dimensao do vetor de entrada
int nthreads; //numero de threads
long int verificaGlobal=0; //verifica se todos os elementos dos vetores ja foram processados dentro da tarefa
pthread_mutex_t espera; //controla o uso do verificaGlobal
int *vetor; //vetor de valores a serem comparados
//fluxo executado pelas threads
void * tarefa(void * arg){
int *parLocal; //variavel local de par, impar e primo
int primoLocal=0; //auxilia na identificacao dos primos
long int verificaLocal=0; //controla internamente o while
//guarda o numero de pares, impares e primos do bloco atual parLocal = par, parLocal+1 = impar, parLocal+2 = primo
parLocal = (int*) malloc(sizeof(int)*3);
if (parLocal == NULL){
fprintf(stderr, "ERRO-- malloc\n"); exit(1);
}
//primeira execucao
pthread_mutex_lock(&espera);
verificaLocal = verificaGlobal;
verificaGlobal++;
pthread_mutex_unlock(&espera);
//verifica os elementos impares, pares e primos de determinado bloco
while(verificaLocal < dim){
if(vetor[verificaLocal]%2 == 0){ //verificacao par
*parLocal +=1;
if(vetor[verificaLocal]==2) //verificacao 2
*(parLocal+2) +=1;
}
else{
*(parLocal+1) +=1; //impar local
for(int j=2; j<=sqrt(vetor[verificaLocal]); j++){ //verificacao primo
if(vetor[verificaLocal]%j==0)
primoLocal = 2;
}
if(primoLocal!=2)
*(parLocal+2) +=1;
primoLocal=0;
}
//controle do total de execucoes
pthread_mutex_lock(&espera);
verificaLocal = verificaGlobal;
verificaGlobal++;
pthread_mutex_unlock(&espera);
}
//retorna os numeros de pares, impares e primos locais
pthread_exit((void *) parLocal);
}
//fluxo principal
int main(int argc, char *argv[]){
int parSeq=0, imparSeq=0, primoSeq=0; //elementos a serem retornados pela forma sequencial
int parConc=0, imparConc=0, primoConc=0; //elementos a serem retornados pela forma concorrente
int *retorno; //valor de retorno das threads
pthread_t *tid; //identificadores das threads
//recebe e valida os parametros de entrada (dimensao do vetor, numero de threads)
if(argc < 3){
printf("Digite: %s <dimensao do vetor> <numero de threads>\n", argv[0]);
return 1;
}
dim = atoi(argv[1]);
nthreads = atoi(argv[2]);
//aloca o vetor de entrada
vetor = (int*) malloc(sizeof(int) * dim);
if(vetor == NULL){
printf("ERRO--malloc\n");
return 2;
}
//preenche o vetor de entrada com valores inteiros aleatorios
srand(time(NULL));
for(long int i=0; i<dim; i++)
vetor[i] = rand();
//verificacao impar, par e primo sequencial dos elementos
int primo=0;
for(int i=0; i<dim; i++){
if(vetor[i]%2 == 0){
parSeq +=1;
if(vetor[i]==2)
primoSeq += 1;
}
else{
imparSeq +=1;
//verificacao primo
for(int j=2; j<=sqrt(vetor[i]); j++){
if(vetor[i]%j==0)
primo = 2;
}
if(primo!=2)
primoSeq +=1;
primo=0;
}
}
//verificacao impar, par e primo concorrente
tid = (pthread_t *) malloc(sizeof(pthread_t) * nthreads); //aloca espaco para as threads
if(tid == NULL){
printf("ERRO--malloc\n");
return 2;
}
//criar as threads
for(long int i=0; i<nthreads; i++){
if(pthread_create(tid+i, NULL, tarefa, NULL)){
printf("ERRO--pthread_create\n");
return 3;
}
}
//aguardar o termino e retorno das threads
for(long int i=0; i<nthreads; i++){
if(pthread_join(*(tid+i), (void**) &retorno)){
printf("ERRO--pthread_join\n");
return 3;
}
parConc += *retorno;
imparConc += *(retorno+1);
primoConc += *(retorno+2);
free(retorno); //libera o parLocal da funcao executada pela thread
}
//verificar corretude
if(parSeq == parConc && imparSeq == imparConc && primoSeq == primoConc){
printf("--Execucao bem sucedida\n");
printf("Pares: %d\n", parSeq);
printf("Impares: %d\n", imparSeq);
printf("Primos: %d\n", primoSeq);
}
else{
printf("--Problema na execucao\n");
printf("Pares Seq: %d\n", parSeq);
printf("Impares Seq: %d\n", imparSeq);
printf("Primos Seq: %d\n", primoSeq);
printf("Pares Conc: %d\n", parConc);
printf("Impares Conc: %d\n", imparConc);
printf("Primos Conc: %d\n", primoConc);
}
//libera as areas de memoria alocadas
free(vetor);
free(tid);
return 0;
}
|
C
|
#define _XOPEN_SOURCE 700
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>
#include <sys/types.h>
#include <signal.h>
#include <sys/wait.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include "mom.h"
#include "philo_general.h"
#include "libs/argv_parser.h"
/* Producer-consumer philosophers problem: We have PHILO_AMOUNT philosophers
sitting on a round table, trying to acquire two chopsticks, one at their
left and one at their right. Once a philosopher have two chopsticks, they
can either produce or consume an item. This behaviour is defined by the
philosopher's id: odd philosophers will produce for the philosopher after
them, and even philosophers will consume from the philospher before them
(i.e. 0 will produce for 1 and 1 will consume from 0 and so on). Philosophers
ids go from 0 to PHILO_AMOUNT-1 in clockwise sense. Once a philosopher do
their consumption or production, they release the chopsticks. The cycle is
repeated ITEMS times.
Implementation: Each philospher will be a process with id ranging from
0 to PHILO_AMOUNT-1. Each chopstick will be a 1-initialized semaphore,
with name "SEMSTICK_x" with x ranging from 0 to PHILO_AMOUNT-1. As such,
each philosopher with id "i" must wait for both sems "SEMSTICK_i" and
"SEMSTICK_((i-1)%PHILO_AMOUNT)". Each buffer for storing items will be
a shared memory with name "SHMBUFFER_x" with x being the id of the PRODUCER
philosopher (i.e. philosopher 0 will produce to "SHMBUFFER_0" and philosopher
1 will consume from the same buffer). Note we need no extra semaphore for
locking the buffer (chopsticks' semaphores already accomplish that).
*/
void launch_philo(ap_t* ap, int id) {
ap_t* ap_philo = ap_clone(ap);
if(!ap_philo) {
printf("%d: Error creating argv_parser for philo %d: %d\n", getpid(), id, errno);
exit(-1);
}
ap_set_int(ap_philo, "id", id);
pid_t pid = fork();
if (pid < 0) {
printf("%d: Error forkig philo %d: %d\n", getpid(), id, errno);
return;
}
if (pid == 0) {
// Philosopher
ap_exec(ap_philo);
printf("SHOULDNT BE HERE %d\n", id);
exit(-1);
}
ap_destroy(ap_philo);
}
int main(int argc, char* argv[]) {
mom_t* mom = mom_create();
if(!mom) {
printf("%d: Error creating mom on main: %d\n", getpid(), errno);
return -1;
}
ap_t* ap = ap_create("./philosopher");
if(!ap) {
printf("%d: Error creating argv_parser: %d\n", getpid(), errno);
mom_destroy(mom);
return -1;
}
subscribe_to_coordinator(mom, 1);
// Create chopsticks' semaphores
char sem_name[20] = {0};
for(int i = 0; i < PHILO_AMOUNT; i++) {
sprintf(sem_name, "SEMSTICK_%d", i);
dsem_init(mom, sem_name, 1);
}
// Create buffers
char shm_name[20] = {0};
for(int i = 0; i < PHILO_AMOUNT; i+=2) {
sprintf(shm_name, "SHMBUFFER_%d", i);
dshm_init(mom, shm_name, 0);
}
printf("%d: ------------- Starting simulation -------------\n", getpid());
// Launch all philosophers
for(int i = 0; i < PHILO_AMOUNT; i++)
launch_philo(ap, i);
// Wait all philosophers
for(int i = 0; i < PHILO_AMOUNT; i++)
wait(NULL);
// Destroy shared resources
for(int i = 0; i < PHILO_AMOUNT; i++) {
sprintf(sem_name, "SEMSTICK_%d", i);
dsem_destroy(mom, sem_name);
}
for(int i = 0; i < PHILO_AMOUNT; i+=2) {
sprintf(shm_name, "SHMBUFFER_%d", i);
dshm_destroy(mom, shm_name);
}
ap_destroy(ap);
mom_destroy(mom);
printf("%d: ------------- Simulation finished -------------\n", getpid());
return 0;
}
|
C
|
#include<stdio.h>
void swap(int*,int*);
int main()
{
int a=10,b=20;
swap(&a,&b);
printf("a=%d\tb=%d",a,b);
}
void swap(int*x,int*y)
{
int temp;
temp=*x;
*x=*y;
*y=*x;
printf("x=%d\ty=%d\n",*x,*y);
}
|
C
|
#ifndef GAME_H
#define GAME_H
#include <stdbool.h>
typedef struct game_s {
int n; // number of rows
int m; // number of columns
double **player1; // payoffs for player 1
double **player2; // payoffs for player 2
int orig_n; // do not change after initialized
int orig_m; // do not change after initialized
} *game_t;
/* mk_game: load a game from the specified directory */
game_t mk_game(char *dirname);
/* free_game: free the memory associated with the specified game */
void free_game(game_t g);
/* print_game: print the contents of the specified game to the screen */
void print_game(game_t g);
/* remove_row_game: remove the specified row from the specified game.
* The rows following the specified row are shifted to fill the gap.
*/
void remove_row_game(game_t g, int row_num);
/* remove_col_game: remove the specified column from the specified
* game. The columns following the specified column are shifted to fill
* the gap.
*/
void remove_col_game(game_t g, int col_num);
/* are_equal_game: returns true if g0 and g1 have the same shape and payoffs for each
* player and false otherwise. Used only by test code.
*/
bool are_equal_game(game_t g0, game_t g1);
#endif
|
C
|
/**
* CSC 335 - Analysis of Algorithms
* Programming Assignment 1
* Jan-Lucas Fitzanthony Ott, Anthony Fitznathan Pompili, David Quadragesimus Shull
* March 28, 2017
*/
#include <stdio.h>
#include "read_array.c"
void heapify(int* heap, int i, int size) {
int left = i * 2 + 1;
int right = left + 1;
int child = left;
if (left >= size) return; // base case - hit a leaf
if (right < size) { // has right child
if (heap[left] > heap[right]) {
child = right; // take smaller child
}
}
if (heap[child] < heap[i]) { // if child is smaller than parent
int temp = heap[i]; // swap the child up, parent down
heap[i] = heap[child];
heap[child] = temp;
heapify(heap, child, size); // recursive call
}
}
int main(void) {
int size;
int* heap = read_array(&size);
int count;
// for each parent node
for (count = size / 2; count >= 0; count--) {
heapify(heap, count, size);
}
int i;
for (i = 0; i < size; i++) {
printf("%d\n", heap[i]);
}
free(heap);
}
|
C
|
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
printf("\n enter the numbers:");
scanf("%d %d",&a,&b);
if(a==b)
printf("\n a and b are equal");
else
printf("\n a and b are not equal");
getch();
}
|
C
|
// list.c
#include <stdio.h>
#include <stdlib.h>
#include "list.h"
struct list_node *list_create(int val) {
struct list_node* head = (struct list_node*)malloc(sizeof(struct list_node));
head->val = val;
head->next = NULL;
return head;
}
int list_insert_after_recursive(struct list_node **list, int node_val, int val) {
if (*list == NULL) {
return 0;
}
if ((*list)->val == node_val) {
struct list_node *newNode = (struct list_node*)malloc(sizeof(struct list_node));
newNode->next = (*list)->next;
newNode->val = val;
(*list)->next = newNode;
return 1;
}
return list_insert_after_recursive(&(*list)->next, node_val, val);
}
int list_prepend(struct list_node **list, int val) {
if (*list == NULL) {
return 0;
}
struct list_node *newNode = (struct list_node*)malloc(sizeof(struct list_node));
newNode->val = val;
newNode->next = *list;
*list = newNode;
return 1;
}
int list_append(struct list_node *list, int val) {
if (list == NULL) {
return 0;
}
struct list_node *newNode = (struct list_node*)malloc(sizeof(struct list_node));
newNode->val = val;
newNode->next = NULL;
struct list_node *currNode = list;
int len = 1;
while(currNode->next != NULL) {
len++;
currNode = currNode->next;
}
currNode->next = newNode;
return ++len;
}
int list_remove_at(struct list_node **list, int index) {
if (*list == NULL || index < 0) {
return 0;
}
struct list_node *curr = *list;
if (index == 0) {
*list = (*list)->next;
free(curr);
} else {
for (int n = 0; n < index - 1; n++) {
if (curr->next == NULL) {
return 0;
}
curr = curr->next;
}
struct list_node *tmp = curr->next;
curr->next = tmp->next;
free(tmp);
}
return 1;
}
void list_free(struct list_node **list) {
struct list_node *curr = *list;
struct list_node *next = NULL;
while(curr != NULL) {
printf("Deallocating node with value %d\n", curr->val);
next = curr->next;
free(curr);
curr = next;
}
*list = NULL;
}
int list_size(struct list_node *list) {
if (list == NULL) {
return 0;
}
struct list_node *currNode = list;
int len = 1;
while(currNode->next != NULL) {
len++;
currNode = currNode->next;
}
return len;
}
int list_size_recursive(struct list_node *list) {
return(list == NULL ? 0 : 1 + list_size_recursive(list->next));
}
int list_contains(struct list_node *list, int searchVal) {
struct list_node *curr = list;
while (curr != NULL) {
if (curr->val == searchVal) {
return 1;
}
curr = curr->next;
}
return 0;
}
void list_print(struct list_node *list) {
if (list == NULL) {
printf("Empty list.\n");
} else {
struct list_node *currNode = list;
do {
printf("%d ", currNode->val);
currNode = currNode->next;
} while(currNode != NULL);
printf("\n");
}
}
|
C
|
#include<stdio.h>
void main()
{
int n,sqr=0;
printf("\n\t ENTER THE NO.:= ");
scanf("%d",&n);
sqr=n*n;
printf("\n\t SQUARE OF %d is %d .",n,sqr);
}
|
C
|
#include "ApproxSeg.h"
void ClassiSegProba(double *sequence, int *lgSeq, int *nStep, double *res1, int *res2, int *nbClasse,
double *moyennes, double *logP, double *variance_){
/* Compteurs et autres */
int i, k, l, indice;
double variance = variance_[0];
/* Variable temporaires */
double * vTmp;
vTmp = (double *) malloc( *nbClasse * sizeof(double));
for(i =0; i < *nbClasse; i++) vTmp[i]= logP[i];
int * whichCome;
whichCome = (int *) malloc( *nbClasse * sizeof(int));
for(i =0; i < *nbClasse; i++) whichCome[i]=-1;
double min;
int whichMin;
for(i = 0; i < *lgSeq; i++)
for(k= 0; k < *nStep; k++)
res1[(*lgSeq)*k+i] = A_POSINF;
/* intialisation */
for(i =0; i < *lgSeq; i++)
{
min=A_POSINF;
for(l =0; l < *nbClasse; l++)
{
vTmp[l] = vTmp[l] + (sequence[i] - moyennes[l])*(sequence[i] - moyennes[l]) / variance;
if(min > vTmp[l]) min = vTmp[l];
}
res1[i] = min;
res2[i] = 0;
}
/* main loop */
for(k =1; k < *nStep; k++)
{
for(l =0; l < *nbClasse; l++) vTmp[l]= A_POSINF;
for(l =0; l < *nbClasse; l++) whichCome[l]=0;
for(i=k; i < *lgSeq; i++)
{
min=A_POSINF;
for(l =0; l < *nbClasse; l++)
{
indice = (*lgSeq)*(k-1)+i-1;
if( vTmp[l] > res1[indice] + logP[l] ) /* on change de segment */
{
vTmp[l] = res1[indice] + (sequence[i] - moyennes[l])*(sequence[i] - moyennes[l]) / variance +
logP[l];
whichCome[l]=i;
} else /* pas de changement de segment */
{
vTmp[l] = vTmp[l] + (sequence[i] - moyennes[l])*(sequence[i] - moyennes[l]) / variance;
}
if(vTmp[l] < min)
{
min=vTmp[l];
whichMin=l;
}
}
indice = (*lgSeq)*k+i;
res1[indice] = min;
res2[indice] = whichCome[whichMin];
}
}
free(vTmp);
free(whichCome);
}
|
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 */
/* Variables and functions */
int /*<<< orphan*/ exit (int) ;
int /*<<< orphan*/ free (char*) ;
int /*<<< orphan*/ pg_log_error (char*,...) ;
char* pg_strdup (char*) ;
char* setlocale (int,char const*) ;
__attribute__((used)) static void
check_locale_name(int category, const char *locale, char **canonname)
{
char *save;
char *res;
if (canonname)
*canonname = NULL; /* in case of failure */
save = setlocale(category, NULL);
if (!save)
{
pg_log_error("setlocale() failed");
exit(1);
}
/* save may be pointing at a modifiable scratch variable, so copy it. */
save = pg_strdup(save);
/* for setlocale() call */
if (!locale)
locale = "";
/* set the locale with setlocale, to see if it accepts it. */
res = setlocale(category, locale);
/* save canonical name if requested. */
if (res && canonname)
*canonname = pg_strdup(res);
/* restore old value. */
if (!setlocale(category, save))
{
pg_log_error("failed to restore old locale \"%s\"", save);
exit(1);
}
free(save);
/* complain if locale wasn't valid */
if (res == NULL)
{
if (*locale)
pg_log_error("invalid locale name \"%s\"", locale);
else
{
/*
* If no relevant switch was given on command line, locale is an
* empty string, which is not too helpful to report. Presumably
* setlocale() found something it did not like in the environment.
* Ideally we'd report the bad environment variable, but since
* setlocale's behavior is implementation-specific, it's hard to
* be sure what it didn't like. Print a safe generic message.
*/
pg_log_error("invalid locale settings; check LANG and LC_* environment variables");
}
exit(1);
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
char c;
printf("Introduza o caracter\n");
scanf("%c",&c);
c=toupper(c);
if(c!='S' && c!='C' && c!='D' && c!='V'){
printf("Carcter introduzido = \'%c\' ERRO-Carcter invlido!",c);
}else if(c=='C'){
printf("Carcter introduzido = \'%c\': CASADO",c);
}else if(c=='S'){
printf("Carcter introduzido = \'%c\': Solteiro",c);
}else if(c=='D'){
printf("Carcter introduzido = \'%c\': Divorciado",c);
}else if(c=='V'){
printf("Carcter introduzido = \'%c\': Viuvo",c);
}
}
|
C
|
/*palindrom olup olmadigini bulma*/
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main(void)
{
char x[10];
int a,b,durum=1;
printf("kelime yaz:");
scanf("%s",&x);
for(a=0,b=strlen(x)-1;a<=(strlen(x)/2);a++,b--)
{
if(x[a]==x[b])
{
durum*=1;
}
else
{
durum*=0;
}
}
if(durum==1)
printf("palindromdur: %d",durum);
else
printf("palindrom degildir: %d",durum);
getch();
return 0;
}
|
C
|
#include <stdio.h>
#include <math.h>
void Forward(int n){
int i,j;
float ax[10],ay[10],x,y=0,h,p,diff[20][20],y1,y2,y3,y4;
for(i=0; i<n; i++) {
printf("x%d: ",i+1);
scanf("%f",&ax[i]);
}
for(i=0; i<n; i++) {
printf("y%d: ",i+1);
scanf("%f",&ay[i]);
}
printf("\n F(x) x = ?");
printf("\n x: ");
scanf("%f",&x);
h=ax[1]-ax[0];
for(i=0; i<n-1; i++) {
diff[i][1]=ay[i+1]-ay[i];
}
for(j=2; j<=4; j++) {
for(i=0; i<n-j; i++) {
diff[i][j]=diff[i+1][j-1]-diff[i][j-1];
}
}
i=0;
do {
i++;
}
while(ax[i]<x);
i--;
p=(x-ax[i])/h;
y1=p*diff[i][1];
y2=p*(p-1)*diff[i-1][2]/2;
y3=(p+1)*p*(p-1)*diff[i-2][3]/6;
y4=(p+1)*p*(p-1)*(p-2)*diff[i-3][4]/24;
y=ay[i]+y1+y2+y3+y4;
printf("\n\n\n x = %6.4f , y = %6.8f\n",x,y);
}
void Backward(int n){
int i,j;
float ax[10],ay[10],x,y=0,h,p,diff[20][20],y1,y2,y3,y4;
for(i=0; i<n; i++) {
printf("\n x%d: ",i+1);
scanf("%f",&ax[i]);
}
for(i=0; i<n; i++) {
printf("\ny%d: ",i+1);
scanf("%f",&ay[i]);
}
printf("\n F(x) x = ?");
printf("\n x: ");
scanf("%f",&x);
h=ax[1]-ax[0];
for(i=0; i<n-1; i++) {
diff[i][1]=ay[i+1]-ay[i];
}
for(j=2; j<=4; j++) {
for(i=0; i<n-j; i++) {
diff[i][j]=diff[i+1][j-1]-diff[i][j-1];
}
}
i=0;
do {
i++;
}
while(ax[i]<x);
i--;
p=(x-ax[i])/h;
y1=p*diff[i-1][1];
y2=p*(p+1)*diff[i-1][2]/2;
y3=(p+1)*p*(p-1)*diff[i-2][3]/6;
y4=(p+2)*(p+1)*p*(p-1)*diff[i-3][4]/24;
y=ay[i]+y1+y2+y3+y4;
printf("\n x = %6.4f , y = %6.4f",x,y);
}
int main()
{
int n,choose;
printf("\n Sems Mustafa Turgut - 130106106054");
printf("\n Hüseyin Atmaca - 131106106001");
printf("\n Bilal Demir - 130106106009");
printf("\n Taner Güden - 130106106057");
printf("\n Numeric Analysis Homework-V ");
printf("\n Enter how many values: ");
scanf("%d",&n);
printf("\n 1)Gauss Forward\n 2)Gauss Backward");
scanf("%d",&choose );
if (choose==1) {
Forward(n);
}
else if (choose==2) {
Backward(n);
}
return 0;
}
|
C
|
/* Find How many times a word appears in another sentence */
/* Notice : 5Geeks didn't carried out the promise of announcing the winners , They are liars */
#include<stdio.h>
#include<string.h>
main()
{
char string [20] , sentence[2000];
int x ,i ,j , result , l ,t;
gets(string);
gets(sentence);
x = strlen(string);
i=0;
l=0;
result = 0;
for (i=0;sentence[i]!='\0';i++) /* check every character in the sentence */
{
if ( sentence [i] == string[0]) /* if a character in the sentence mathcs the first letter in the word */
{
l=0; /* reset l */
t=0; /* reset t */
for (j=i ; j<(i+x) ; j++) /* check if the all word in the sentence sequentially */
{
if ( sentence[j] == string[t])
{
l++; /* how many characters are matched in a row ,if l=length of the word then we have the first duplicate*/
}
t++; /* to check the next character */
}
if ( l == x) /* if l = length of the word then we have a Duplicate */
{
result++; /* Number of Duplicates */
i+=x-1; /* to jump to the character after the match in the Main loop not to the next character */
}
}
}
printf("The Result is %d",result); /* Print The Result */
}
|
C
|
/* 1부터 100 까지 3의 배수는 fizz 5의 배수는 buzz 둘 다 해당하는 경우 fizz buzz를 출력하는 프로그램을 작성 */
#include <stdio.h>
int main() {
int i;
for(i=1; i<=100; i++) {
if((i % 15) == 0) {
printf("fizz buzz ");
}
else if((i % 3) == 0) {
printf("fizz ");
} else if((i % 5) == 0) {
printf("buzz ");
} else {
printf("%d ", i);
}
}
return 0;
}
|
C
|
#include <msp430.h>
#include "DS18B20.h"
// Drivers to access DS1822 Temperature Sensor over a 1-wire comm bus from:
// https://www.maximintegrated.com/en/design/technical-documents/app-notes/1/162.html
//////////////////////////////////////////////////////////////////////////////
// OW_RESET - performs a reset on the one-wire bus and
// returns the presence detect. Reset is 480us
//
unsigned char ow_reset(void)
{
unsigned char presence;
// pull DQ low to start timeslot
DS_PxDIR |= DS_DQ_BIT; // Set DQ as Output
DS_PxOUT &= ~DS_DQ_BIT; //pull DQ line low
__delay_cycles(490*US_MULTIPLIER); // leave it low for atleast 480us
// allow line to return high by external pullup
DS_PxDIR &= ~DS_DQ_BIT; // Release DQ line to allow pull up or READ
__delay_cycles(100*US_MULTIPLIER); // wait for presence 70us
presence = DS_PxIN & DS_DQ_BIT; // get presence signal
__delay_cycles(380*US_MULTIPLIER); // wait for end of timeslot
return(presence); // presence signal returned
} // 0=presence, 1 = no part
//////////////////////////////////////////////////////////////////////////////
// WRITE_BIT - writes a bit to the one-wire bus, passed in bitval.
//
void write_bit(char bitval)
{
// pull DQ low to start timeslot
DS_PxDIR |= DS_DQ_BIT; // Set DQ as Output
DS_PxOUT &= ~DS_DQ_BIT; //pull DQ line low to initiate start condition
__delay_cycles(US_MULTIPLIER); // hold write condition for 1us
if(bitval==1){
//return DQ high if write 1
DS_PxDIR &= ~DS_DQ_BIT; // Release DQ line to allow pull up or READ
}
__delay_cycles(104*US_MULTIPLIER); // hold value for remainder of timeslot
DS_PxDIR &= ~DS_DQ_BIT; // Release DQ line to allow pull up or READ
}//
//////////////////////////////////////////////////////////////////////////////
// WRITE_BYTE - writes a byte to the one-wire bus.
//
void write_byte(char val)
{
unsigned char i;
unsigned char temp;
for (i=0; i<8; i++) // writes byte, one bit at a time
{
temp = val>>i; // shifts val right 'i' spaces
temp &= 0x01; // copy that bit to temp
write_bit(temp); // write bit in temp into
}
__delay_cycles(104*US_MULTIPLIER);
}
//////////////////////////////////////////////////////////////////////////////
// READ_BIT - reads a bit from the one-wire bus. The delay
// required for a read is 15us, so the DELAY routine won't work.
// We put our own delay function in this routine in the form of a
// for() loop.
//
unsigned char read_bit(void)
{
unsigned char readBit;
DS_PxDIR |= DS_DQ_BIT; // Set DQ as Output
DS_PxOUT &= ~DS_DQ_BIT; //pull DQ line low to initiate READ condition
__delay_cycles(US_MULTIPLIER); // hold write condition for 1us
DS_PxDIR &= ~DS_DQ_BIT; // Release DQ line to allow pull up or READ
__delay_cycles(14*US_MULTIPLIER); // delay 14us from start of timeslot
readBit = DS_PxIN & DS_DQ_BIT;
return(readBit); // return value of DQ line
}
//////////////////////////////////////////////////////////////////////////////
// READ_BYTE - reads a byte from the one-wire bus.
//
unsigned char read_byte(void)
{
unsigned char i;
unsigned char value = 0;
for (i=0;i<8;i++)
{
if(read_bit()) value|=0x01<<i; // reads byte in, one byte at a time and then
// shifts it left
__delay_cycles(120*US_MULTIPLIER); // wait for rest of timeslot
}
return(value);
}
unsigned int Read_Temperature(void)
{
char get[9];
char temp_lsb,temp_msb;
unsigned int tempOut = 0;
volatile int k, intC = 0;
ow_reset();
write_byte(0xCC); // Skip ROM
write_byte(0x44); // Start Conversion
__delay_cycles(750*US_MULTIPLIER);
ow_reset();
write_byte(0xCC); // Skip ROM
write_byte(0xBE); // Read Scratch Pad
for (k=0;k<9;k++){get[k]=read_byte();}
temp_msb = get[1]; // Sign byte + lsbit
temp_lsb = get[0]; // Temp data plus lsb
intC = ((temp_msb<<4) & 0x70) + ((temp_lsb>>4) & 0x0F);
// Temp out Format: 2^[S S S S S 6 5 4 3 2 1 0 -1 -2 -3 -4]
tempOut = (temp_msb<<8) + temp_lsb;
return tempOut;
}
|
C
|
#include "header.h"
int bikeIndexMax = 0;
void main() {
system("mode con cols=75 lines=40");
system("color b");
bool mLoop = true;
char strBuffer[256];
char select[10];
char loginId[30];
char loginPwd[30];
char *id = loginId;
char *pwd = loginPwd;
FILE* f;
if (fopen_s(&f, LNAME, "a")) {
system("cls");
printf(" Ͽϴ.");
exit(1);
}
fclose(f);
if (fopen_s(&f, FNAME, "a")) {
system("cls");
printf(" Ͽϴ.");
exit(1);
}
fclose(f);
while (mLoop) {
if (fopen_s(&f, LNAME, "r") != 0) {
printf(" ߽ϴ.\n");
exit(1);
}
Login l;
fgets(strBuffer, sizeof(strBuffer), f);
sscanf_s(strBuffer, "%s %s", l.id, sizeof(l.id), l.pwd, sizeof(l.pwd));
fclose(f);
loginDisplay(id, pwd);
if (!strcmp(l.id, loginId) && !strcmp(l.pwd, loginPwd)) {
system("cls");
while (true) {
FILE *f;
char strBuffer[256];
Bike b[50] = { NULL };
bikeIndexMax = 0;
if (fopen_s(&f, FNAME, "r") != 0) {
system("cls");
printf(" Ͽϴ.");
exit(1);
}
while (!feof(f)) {
fgets(strBuffer, sizeof(strBuffer), f);
sscanf_s(strBuffer, "%d %s %s %s",
&b[bikeIndexMax].index,
b[bikeIndexMax].model, sizeof(b[bikeIndexMax].model),
b[bikeIndexMax].manufacture, sizeof(b[bikeIndexMax].manufacture),
b[bikeIndexMax].insertDate, sizeof(b[bikeIndexMax].insertDate)
);
bikeIndexMax++;
}
fclose(f);
displayMenu(loginId);
gets_s(select, sizeof(select));
if (!strcmp(select, "1")) {
system("cls");
addBike(b);
}
else if (!strcmp(select, "2")) {
system("cls");
modifyBike(b);
}
else if (!strcmp(select, "3")) {
system("cls");
deleteBike(b);
}
else if (!strcmp(select, "q")) {
system("cls");
break;
}
else {
system("cls");
printf("\t\t<Է¿!>\n");
}
}
}
else {
system("cls");
printf("------------------------------------------------------------------\n");
printf("\t\t\t<Է¿>\t\t\n\n");
}
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
struct number1{
int odd;
struct odd *next;
};
struct number2{
int even;
struct even *next;
};
struct number1 *start1;
struct number2 *start2;
struct number1 *temp1;
struct number2 *temp2;
struct number1 *last1;
struct number2 *last2;
int n;
void insert1(){
int a;
printf("Insert : ");
scanf("%d",&a);
last1 = start1;
temp1=malloc(sizeof(struct number1));
temp1->odd = a;
temp1->next=NULL;
if(start1==NULL){
start1 = temp1;
}
else{
while(last1->next!=NULL){
last1 = last1->next;
}
last1->next =temp1;
}
}
void insert2(){
int a;
printf("Insert : ");
scanf("%d",&a);
last2 = start2;
temp2=malloc(sizeof(struct number2));
temp2->even = a;
temp2->next=NULL;
if(start2==NULL){
start2 = temp2;
}
else{
while(last2->next!=NULL){
last2 = last2->next;
}
last2->next =temp2;
}
}
void printLinkedList1(){
struct number1 * printVariable;
printVariable=start1;
printf("\nThe list is : ");
while(printVariable!=NULL){
printf("%d ",printVariable->odd);
printVariable = printVariable->next;
}
}
void printLinkedList2(){
struct number2 * printVariable;
printVariable=start2;
printf("\nThe list is : ");
while(printVariable!=NULL){
printf("%d ",printVariable->even);
printVariable = printVariable->next;
}
}
void addLinkedList(){
struct number1 * searchVariable1;
struct number2 * searchVariable2;
while(last1->next!=NULL){
last1 = last1->next;
}
last1->next=start2;
printLinkedList1();
}
int main(){
printf("Insert In The First Link List : \n");
while(1){
printf("\nPress 1 To Insert\nPress 0 To Exit\n");
scanf("%d",&n);
if(n!=0){
insert1();
}
else{
break;
}
}
printf("Insert In The Second Link List : \n");
while(1){
printf("\nPress 1 To Insert\nPress 0 To Exit\n");
scanf("%d",&n);
if(n!=0){
insert2();
}
else{
break;
}
}
printf("\n\n");
printLinkedList1();
printLinkedList2();
addLinkedList();
printf("\n\n");
return 0;
}
|
C
|
#include <stdio.h>
#include <sys/select.h>
#include <sys/time.h>
#include <unistd.h>
int main(void)
{
struct timeval timer;
fd_set readfds;
timer.tv_sec=2;
timer.tv_usec=500000;
FD_ZERO(&readfds);
FD_SET(STDIN_FILENO,&readfds);
select(STDIN_FILENO+1,&readfds,NULL,NULL,&timer);
if(FD_ISSET(STDIN_FILENO,&readfds))
printf("one key was pressed.\n");
else
printf("Time out.\n");
return 0;
}
|
C
|
week6 Pointers & Dynamic memory allocation
segmentation fault
การพยายามเข้าถึงหน่วยความจำที่เราไม่ได้จองไว้หรือหน่วยความจำที่นอกเหนือจากตัวเเปรที่เราประกาศไว้ มีโอกาสที่จะถูกระบบปฏิบัติการจะหยุด
การทำงานของโปรเเกรม
#include <stdio.h>
// void addTen(int number[][n]], int n) //คอลลัมต้องใส่ค่าด้วย
void addTen(int *number, int n){
for(int i = 0; i< n; i++){
// printf("[%d] = %d" , i, number[i]);
printf("addTen [%p] = %d\n" , number + i, *(number + i));
*(number + i) += 10;
}
}
int addTwenty(int *n){
*n += 20;
return 1;
}
int main(){
int number[] = {1,2,3,4,5};
int n = 5;
addTen(&number[0], n);
for (int i = 0; i < n; i++)
{
// printf("[%d] = %d" , i, number[i]);
printf("main [%p] = %d\n" , number + i, *(number + i));
}
addTwenty(&n); //ส่งค่า address ไปฟังก์ชัน Twenty
addTwenty(&number[4]);
printf("n = %d\n", n);
printf("number[4] = %d", number[4]);
}
|
C
|
/* Module: list_handler.c
*
* Purpose: The main purpose of this module is provide functions to deal with and maintain the
* list data structures.
*
* Written by Jesse Costales, Ismael Flores, Julian Escontrias, and Mike Marez.
*
*/
#include "project_manager.h"
extern list attribute_names;
extern list relation_names;
extern list undeclared;
extern ot_tree object_types;
extern rd_tree relation_defs;
extern object Object_Table[];
extern relationship Relation_Table[];
int list_insert_name(list *head, char *name)
{
list_node *temp;
int i;
if (*head)
{
if ((i = strcmp(name, (*head)->name)) == 0)
return FALSE;
else if (i > 0)
return list_insert_name(&((*head)->next), name);
}
temp = (*head);
(*head) = (list) malloc((size_t) sizeof(list_node));
if (*head)
{
strcpy((*head)->name, name);
(*head)->text = NULL;
(*head)->next = temp;
return TRUE;
}
else
{
printf("FATAL ERROR - UNABLE TO ALLOCATE MEMORY\n");
return FALSE;
}
}
int list_insert_text(list *head, char *name, char *text)
{
list_node *temp;
int i;
if (*head)
{
if ((i = strcmp(name, (*head)->name)) == 0)
return FALSE;
else if (i > 0)
return list_insert_text(&((*head)->next), name, text);
}
temp = (*head);
(*head) = (list) malloc((size_t) sizeof(list_node));
if ((*head) && ((*head)->text = (char *) malloc((size_t) (strlen(text) + 1))))
{
strcpy((*head)->name, name);
strcpy((*head)->text, text);
(*head)->next = temp;
}
else
{
printf("FATAL ERROR - UNABLE TO ALLOCATE MEMORY\n");
return FALSE;
}
return FALSE;
}
char *list_get_name(list head, int n)
{
int i;
for (i = 0; i < n; i++)
head = head->next;
return head->name;
}
char *list_get_text(list head, char *name)
{
while (head)
{
if (!strcmp(head->name, name))
return head->text;
head = head->next;
}
return NULL;
}
void list_delete(list *head, char *name)
{
list_node *temp;
if (*head)
{
if (strcmp(name, (*head)->name) == 0)
{
temp = (*head)->next;
free((*head)->name);
free((*head)->text);
free(*head);
(*head) = temp;
}
else
list_delete(&((*head)->next), name);
}
}
list list_locate(list head, char *name)
{
if (head)
{
if (strcmp(name, head->name) == 0)
return head;
else
return list_locate(head->next, name);
}
return NULL;
}
int list_index(list head, char *name)
{
int i;
for (i = 0; head; i++)
{
if (!strcmp(head->name, name))
return i;
head = head->next;
}
return -1;
}
void list_dispose(list *head)
{
if (*head)
{
list_dispose(&((*head)->next));
if ((*head)->name)
free((*head)->name);
if ((*head)->text)
free((*head)->text);
free(*head);
(*head) = NULL;
}
}
int list_length(list head)
{
int i;
for (i = 0; head; i++)
head = head->next;
return i;
}
int obj_type_insert(ot_tree *root, char *type)
{
int i;
if (*root)
{
#ifdef DEBUG
printf("finding\n");
#endif
if (!(i = strcmp(type, (*root)->type)))
return FALSE;
else if (i < 0)
return obj_type_insert(&((*root)->left), type);
else if (i > 0)
return obj_type_insert(&((*root)->right), type);
}
else
{
(*root) = (ot_tree) malloc((size_t) sizeof(obj_type_node));
if (*root)
{
strcpy((*root)->type, type);
(*root)->att_list = NULL;
(*root)->rel_list = NULL;
(*root)->right = NULL;
(*root)->left = NULL;
#ifdef DEBUG
printf("adding\n");
#endif
return TRUE;
}
else
{
printf("FATAL ERROR - UNABLE TO ALLOCATE MEMORY\n");
return FALSE;
}
}
return FALSE;
}
ot_tree obj_type_locate(ot_tree root, char *type)
{
int i;
if (root)
{
if (!(i = strcmp(type, root->type)))
return root;
else if (i < 0)
return obj_type_locate(root->left, type);
else if (i > 0)
return obj_type_locate(root->right, type);
}
return NULL;
}
void obj_type_dispose(ot_tree *root)
{
if (*root)
{
if ((*root)->left)
obj_type_dispose(&((*root)->left));
if ((*root)->right)
obj_type_dispose(&((*root)->right));
list_dispose(&((*root)->att_list));
list_dispose(&((*root)->rel_list));
free(*root);
(*root) = NULL;
}
}
int rel_def_insert(rd_tree *root, char *domain, char *relation, char *range, char *inverse)
{
int i;
if (*root)
{
if (!(i = strcmp(domain, (*root)->domain)))
if (!(i = strcmp(relation, (*root)->relation)))
if (!(i = strcmp(range, (*root)->range)))
return FALSE;
if (i < 0)
return rel_def_insert(&((*root)->left), domain, relation, range, inverse);
if (i > 0)
return rel_def_insert(&((*root)->right), domain, relation, range, inverse);
}
else
{
(*root) = (rd_tree) malloc((size_t) sizeof(rel_def_node));
if (*root)
{
strcpy((*root)->domain, domain);
strcpy((*root)->relation, relation);
strcpy((*root)->range, range);
strcpy((*root)->inverse, inverse);
(*root)->right = NULL;
(*root)->left = NULL;
return TRUE;
}
else
{
printf("FATAL ERROR - UNABLE TO ALLOCATE MEMORY\n");
return FALSE;
}
}
return FALSE;
}
rd_tree rel_def_locate(rd_tree root, char *domain, char *relation, char *range)
{
int i;
if (root)
{
if (!(i = strcmp(domain, root->domain)))
if (!(i = strcmp(relation, root->relation)))
if (!(i = strcmp(range, root->range)))
return root;
if (i < 0)
return rel_def_locate(root->left, domain, relation, range);
if (i > 0)
return rel_def_locate(root->right, domain, relation, range);
}
return NULL;
}
void rel_def_dispose(rd_tree *root)
{
if (*root)
{
if ((*root)->left)
rel_def_dispose(&((*root)->left));
if ((*root)->right)
rel_def_dispose(&((*root)->right));
free(*root);
(*root) = NULL;
}
}
|
C
|
/***************************************************************************//**
* @file : cox_types.h
* @brief : Contains the COX typedefs for C standard types.
* @version : V1.0
* @date : 26. May. 2010
* @author : CooCox
*******************************************************************************/
#ifndef __COX_TYPES_H
#define __COX_TYPES_H
#include "stdint.h"
/** Status type definition */
typedef enum {
COX_SUCCESS = 0,
COX_ERROR = 1,
} COX_Status;
#define COX_NULL ((void *)0)
#define COX_PIN_Dev uint16_t
/** Define a PIO device using port number and pin number */
#define COX_PIN(port_num, pin_num) ((((uint16_t)(port_num) & 0xFF) << 8) | ((pin_num) & 0xFF))
#define COX_PORT_NUM(pin) ((pin >> 8) & 0xFF)
#define COX_PIN_NUM(pin) ((pin >> 0) & 0xFF)
/** Invalid PIN */
#define COX_PIN_NC COX_PIN(0xFF, 0xFF)
#endif
|
C
|
#include "ft_printf.h"
static int ft_count_len(long c)
{
int len;
len = 0;
if (c < 0)
{
len++;
c = c * (-1);
}
while (c > 0)
{
len++;
c /= 10;
}
return (len);
}
static char *ft_convert_char(char *str, long num, int len, int minus)
{
if (num != 0)
str = (char *)malloc(sizeof(char) * (len + 1));
else
return (str = ft_strdup("0"));
if (!str)
return (0);
if (num < 0)
num = num * (-1);
str[len] = '\0';
while (--len > 0)
{
str[len] = (num % 10) + '0';
num /= 10;
}
if (minus == 1)
str[0] = '-';
else
str[0] = (num % 10) + '0';
return (str);
}
char *ft_uint_itoa(unsigned int c)
{
int len;
char *put;
long num;
int min;
num = c;
put = 0;
min = 0;
if (num < 0)
min++;
len = ft_count_len(c);
put = ft_convert_char(put, num, len, min);
if (!put)
return (0);
return (put);
}
|
C
|
#include "fcounter.h"
const char *get_filename_ext(const char *filename) {
const char *dot = strrchr(filename, '.');
if(!dot || dot == filename) return "";
return dot + 1;
}
int collect_children_file_count() {
int file_count, status;
file_count = 0;
while(wait(&status)>0) {
/* increase the count if child terminated normally(return exit, or _exit) */
if(WIFEXITED(status) && WEXITSTATUS(status) != 1){
file_count += WEXITSTATUS(status);
}
}
return file_count;
}
void execute_child_process(char *path, char **argv) {
int exec_result;
pid_t process_id;
setenv("PATH_TO_BROWSE", path, 1);
process_id = fork();
if(process_id == 0) {
/* int execvp(const char *file, char *const argv[]); */
exec_result = execvp(argv[0], argv);
if(exec_result < 0) {
printf("Error in execvp function\n");
exit(EXIT_FAILURE);
}
fprintf(stderr, "exec error\n");
_exit(0);
} else if(process_id < 0) {
fprintf(stderr, "fork error\n");
}
}
void insert_argv_path(int argc, char **argv, char *dir) {
int i;
if(argc > 1 && argv[1][0] == '-') {
argv[argc+1] = NULL;
for(i=1; i<argc; i+=1) {
argv[i+1] = argv[i];
}
}
argv[1] = dir;
}
void run(char* dir_path, int argc, char **argv, char *ext, int wait_flag, int display_flag) {
int file_count, children_file_count, sprintf_result;
DIR *dir;
dirent_t *dirent_file;
char *file_path;
file_count = 0;
dir = opendir(dir_path);
if(dir == NULL) {
printf("Error while opening the directory\n");
exit(EXIT_FAILURE);
}
while((dirent_file = readdir(dir)) != NULL) {
if(strcmp(dirent_file->d_name, "." )!=0 && strcmp(dirent_file->d_name, "..")!= 0) {
if(dirent_file->d_type == DT_DIR) {
file_path = malloc(strlen(dir_path) + strlen(dirent_file->d_name) + 2);
if(file_path == NULL) {
printf("Error in malloc function \n");
exit(EXIT_FAILURE);
}
/* copy path + dirent_file->d_nme to entry_path string */
sprintf_result = sprintf(file_path, "%s/%s", dir_path, dirent_file->d_name);
if(sprintf_result < 0) {
printf("Error in sprintf function \n");
exit(EXIT_FAILURE);
}
insert_argv_path(argc, argv, file_path);
execute_child_process(file_path, argv);
free(file_path);
}
else if(dirent_file->d_type == DT_REG) {
if(ext==NULL || strcmp(get_filename_ext(dirent_file->d_name), ext) == 0) {
file_count += 1;
}
}
}
}
if(wait_flag) sleep(15);
children_file_count = collect_children_file_count();
if(display_flag) {
printf("Directory %s \n File count %d \n Children file count %d \n ------- \n",
dir_path, file_count, children_file_count);
}
closedir(dir);
exit(file_count+children_file_count);
}
int main(int argc, char **argv) {
char *dir, *ext;
int opt;
int wait_flag = 0;
int display_flag = 0;
int path_browse_flag = 0;
dir = NULL;
/* argv[1] exists and is not an option e.g -w -v */
if(argc > 1 && argv[1][0] != '-') {
dir = argv[1];
}
ext = getenv("EXT_TO_BROWSE");
while ((opt = getopt(argc, argv, "wvp")) != -1) {
switch(opt) {
case 'p': path_browse_flag=1; break;
case 'w': wait_flag=1; break;
case 'v': display_flag=1; break;
}
}
/* default option -> without flag p */
if(path_browse_flag== 0 && (dir == NULL || strlen(dir) == 0)) {
dir = ".";
}
if(path_browse_flag == 1) {
dir = getenv("PATH_TO_BROWSE");
}
run(dir, argc, argv, ext, wait_flag, display_flag);
return 0;
}
|
C
|
// #include <time.h>
// #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "chip8.h"
// #define STACK_SIZE 16
// #define STACK_MASK 0x0F
#define MEMORY_SIZE 4096
extern unsigned short chip8_get_compatibility_flags();
extern UBYTE *mem; // Memory
// Stops playing at zero.
static unsigned short compat_flags; // Compatibility flags
void chip8_disassemble(int pc, unsigned short opcode, char *disstr) {
UBYTE c, x, y, n, nn;
unsigned short nnn, tmp;
compat_flags = chip8_get_compatibility_flags();
c = (opcode >> 12) & 0x0F;
x = (opcode >> 8) & 0x0F;
y = (opcode >> 4) & 0x0F;
n = opcode & 0x0F;
nn = opcode & 0xFF;
nnn = opcode & 0x0FFF;
// SCROLU n : XO-Chip command. Scroll up n pixels.
if((opcode & 0xFFF0) == 0x00D0) {
sprintf(disstr, "SCROLU %d\n", n);
// CLS : Clear display
} else if(opcode == 0x00E0) {
sprintf(disstr,"CLS");
// RET : Return from subroutine
} else if(opcode == 0x00EE) {
sprintf(disstr, "RET");
// LORES : Superchip command
} else if(opcode == 0x00FE) {
sprintf(disstr, "LORES 64x32");
// HIRES : Superchip_command
} else if(opcode == 0x00FF) {
sprintf(disstr, "HIRES 128x64");
// SCROLD n : Superchip command. Scroll down n lines (n = 0-15).
} else if((opcode & 0xFFF0) == 0x00C0) {
sprintf(disstr, "SCROLD %02d", n);
// SCROLR : Superchip command. Scroll right by 4 pixels.
}else if(opcode == 0x00FB) {
sprintf(disstr, "SCROLR 4");
// SCROLL : Superchip command. Scroll left by 4 pixels.
} else if(opcode == 0x00FC) {
sprintf(disstr, "SCROLL 4");
// JP nnn : Jump to adress nnn
} else if(c == 0x01) {
sprintf(disstr, "JUMP 0x%03X", nnn);
if(nnn & 0x01) strcat(disstr, " <- Jump to uneven adress");
// CALL nnn : Call subroutine at adress nnn
} else if(c == 0x02) {
sprintf(disstr, "CALL 0x%03X", nnn);
if(nnn & 0x01) strcat(disstr, " <- Call to uneven adress");
// SE Vx, nn : Skip next instruction if Vx == nn
} else if(c == 0x03) {
sprintf(disstr, "SE V%X, 0x%02X", x, nn);
// SNE Vx, nn : Skip next instruction if Vx != nn
} else if(c == 0x04) {
sprintf(disstr, "SNE V%X, 0x%02X", x, nn);
} else if(c == 0x05) {
// SE Vx, Vy : Skip next instruction if Vx == Vy
if(n == 0x00) {
sprintf(disstr, "SE V%X, V%X", x, y);
// SAVE I,Vx-Vy : XO-Chip command. Save Vx - Vy to I. I is unchanged.
} else if(n == 0x02) {
sprintf(disstr, "SAVE I, V%1X-V%1X", x, y);
// LOAD Vx-Vy,I : XO-Chip command. Load Vx-Vy from I. I is unchanged.
} else if(n == 0x03) {
sprintf(disstr, "LOAD V%1X-V%1X, I", x, y);
}
// LD Vx, nn : Set Vx = nn
} else if(c == 0x06) {
sprintf(disstr, "LD V%X, 0x%02X", x, nn);
// ADD Vx, nn : Set Vx = Vx + nn
} else if(c == 0x07) {
sprintf(disstr, "ADD V%X, 0x%02X", x, nn);
// Group instructions with c = 0x08 together for optimization
} else if(c == 0x08) {
// LD Vx, Vy : Set Vx = Vy
if(n == 0x0) {
sprintf(disstr, "LD V%X, V%X", x, y);
// OR Vx, Vy : Set Vx = Vx OR Vy
} else if(n == 0x01) {
sprintf(disstr, "OR V%X, V%X", x, y);
// AND Vx, Vy : Set Vx = Vx AND Vy
} else if(n == 0x02) {
sprintf(disstr, "AND V%X, V%X", x, y);
// XOR Vx, Vy : Set Vx = Vx XOR Vy
} else if(n == 0x03) {
sprintf(disstr, "XOR V%X, V%X", x, y);
// ADD Vx, Vy : Set Vx = Vx + Vy, set VF = carry
} else if(n == 0x04) {
sprintf(disstr, "ADDC V%X, V%X", x, y);
// SUB Vx, Vy : Set Vx = Vx - Vy, set VF = NOT borrow
} else if(n == 0x05) {
sprintf(disstr, "SUB V%X, V%X", x, y);
// SHR Vx : Set Vx = Vx >> 1 and shift out least significant bit to VF
} else if(n == 0x06) {
if(compat_flags & (1 << COMPAT_SHIFT_QUIRK)) {
sprintf(disstr, "SHR V%X", x);
} else {
sprintf(disstr, "SHR V%X, V%X", x, y);
}
// SUBN Vx, Vy : Set Vx = Vy - Vx, set VF = NOT borrow (if Vy > Vx, VF = 1)
} else if(n == 0x07) {
sprintf(disstr, "SUBN V%X, V%X", x, y);
// SHL Vx : Set Vx = Vx << 1 and shift out most significant bit to VF
} else if(n == 0x0E) {
if(compat_flags & (1 << COMPAT_SHIFT_QUIRK)) {
sprintf(disstr, "SHL V%X", x);
} else {
sprintf(disstr, "SHL V%X, V%X", x, y);
}
}
// SNE Vx, Vy : Skip next instruction if Vx != Vy
} else if(c == 0x09 && n == 0x00) {
sprintf(disstr, "SNE V%X, V%X", x, y);
// LD I, nnn : Set I = nnn
} else if(c == 0x0A) {
sprintf(disstr, "LD I, 0x%03X", nnn);
// JP V0, nnn : Jump to location nnn + V0
} else if(c == 0x0B) {
sprintf(disstr, "JP V0, 0x%03X", nnn);
// RND Vx, nn : Set Vx = random byte & nn
} else if(c == 0x0C) {
sprintf(disstr, "RND V%X, 0x%02X", x, nn);
// DXYN, DRW Vx, Vy, n, Draws sprite at coordinate x,y. n = height, width = 8 pixels.
// Sprite data is fetched from memory location I.
} else if(c == 0x0D) {
if(n) {
sprintf(disstr, "DRW V%X, V%X, 0x%1X", x, y, n);
} else {
// Superchip command. Draw 16x16 size sprite.
sprintf(disstr, "DRW16 V%X, V%X, 16", x, y);
}
// SKP Vx : Skip next instruction if key with the value of Vx IS pressed
} else if(c == 0x0E && nn ==0x9E) {
sprintf(disstr, "SKP V%X", x);
// SKNP Vx : Skip next instruction if key with the value of Vx is NOT pressed
} else if(c == 0x0E && nn == 0xA1) {
sprintf(disstr, "SKNP V%X", x);
// Group instruction with c == 0x0F
} else if(c == 0x0F) {
// AUDIO : XO-Chip command.
if(nnn == 0x002) {
sprintf(disstr, "AUDIO");
// LD I,#16bit : XO-Chip command. Load I with 16 bit immediate value
} else if(nnn == 0x0000) {
tmp = (mem[pc+2] << 8) | mem[pc+3];
sprintf(disstr, "LD I,#%04X", tmp);
// PLANE x : XO-Chip command. Set drawing plane.
} else if(nn == 0x01) {
sprintf(disstr, "PLANE %d", x);
// LD Vx, DT : Set Vx = delay_timer value
} else if(nn == 0x07) {
sprintf(disstr, "LD V%X, DelayTimer", x);
// LD Vx, K : Wait for keypress, store the value of key in Vx
} else if(nn == 0x0A) {
sprintf(disstr, "LD V%X, Keypressed", x);
// LD DT, Vx : Set delay timer = Vx
} else if(nn == 0x15) {
sprintf(disstr, "LD DelayTimer, V%X", x);
// LD ST, Vx : Set sound timer 0 Vx
} else if(nn == 0x18) {
sprintf(disstr, "LD SoundTimer, V%X", x);
// ADD I, Vx : Set I = I + Vx
} else if(nn == 0x1E) {
sprintf(disstr, "ADD I, V%X", x);
// LD F, Vx : Set I = location of sprite for hexdigit Vx
// Since we have loaded the charset to 0x00 - 0x50
// and each character is 5 bytes, we multiply Vx with 5
// and store result in I.
} else if(nn == 0x29) {
sprintf(disstr, "LD F, V%X", x);
// LD B, Vx : Store BCD representation of Vx in memory locations I, I+1, I+2
} else if(nn == 0x33) {
sprintf(disstr, "LD B, V%X", x);
// LD [I], Vx : Store registers V0 through Vx in memory starting at location I
} else if(nn == 0x55) {
sprintf(disstr, "LD [I], V0-V%X", x);
// LD Vx, [I] : Read registers V0 through Vx from memory starting at location I
} else if(nn == 0x65) {
sprintf(disstr, "LD V0-V%X, [I]", x);
// LD I, HEX16 : Superchip command. Load I with pointer to hexdigits.
} else if(nn == 0x30) {
sprintf(disstr, "LD I, HEX16[V%X]", x);
// LD [R], Vx : Superchip command. Store registers V0 - VX in R memory.
} else if(nn == 0x75) {
sprintf(disstr, "LD [R], V0-V%X", x);
// LD Vx, [R] : Superchip command. Load register V0 - VX from R memory.
} else if(nn == 0x85) {
sprintf(disstr, "LD V0-V%X, [R]", x);
}
} else {
sprintf(disstr, "D.W 0x%04X", opcode);
}
}
|
C
|
#include <windows.h>
#include <stdio.h>
#include <math.h>
// К заданию 1
enum org_name{
ZAO,
OOO,
IP,
};
// К заданию 2
struct trinagle {
float x1,y1,x2,y2,x3,y3,x4,y4;
};
// К задание 3
union cond{
struct{
unsigned int on_off : 1;
unsigned int SDcard : 1;
unsigned int CompactFlash : 1;
unsigned int MemoryStick : 1;
}bitfield;
int x16;
};
int main(){
SetConsoleOutputCP(CP_UTF8); // Изменение пкодировки на UTF8 для локализации русского(CLion, GCC)
//Задание 1
enum org_name x;
x = OOO;
printf("Значение целого числа для OOO: %d\n\n", x);
// Задание 2
float a,s;
struct trinagle ABC;
ABC.x1 = 1;
ABC.y1 = -1;
ABC.x2 = 3;
ABC.y2 = -1;
ABC.x3 = 3;
ABC.y3 = 3;
ABC.x4 = 1;
ABC.y4 = 3;
a = sqrtf(pow((ABC.x2 - ABC.x1), 2) + pow((ABC.y2 - ABC.y1), 2));
s = pow(a,2);
printf("Площадь квадрата равна: %f\n\n", s);
// Задание 3
union cond y;
printf("Введите 16-ричное число:");
scanf("%x\n", &y);
printf(" Card Reader: %d\n SD card: %d\n Compact Flash: %d\n Memory Stick: %d\n", y.bitfield.on_off,y.bitfield.SDcard,y.bitfield.CompactFlash,y.bitfield.MemoryStick);
return 0;
}
|
C
|
//指针运算中的优先级
// order.c
// C programming
//
// Created by bhjml on 2020/4/22.
// Copyright © 2020 bhjml. All rights reserved.
//
#include <stdio.h>
int data[2]={100,200};
int moredata[2]={300,400};
int main()
{
int *p1, *p2, *p3;
p1 = p2 = data;
p3 = moredata;
printf(" *p1 = %d, *p2 = %d, *p3 = %d\n",*p1 ,*p2, *p3);
printf(" *p1++ = %d, *++p2 = %d, (*p3)++ = %d\n",*p1++,*++p2,(*p3)++);
printf(" *p1 = %d, *p2 = %d, *p3 = %d\n",*p1 ,*p2, *p3);
return 0;
}
|
C
|
#include "lib.h"
#include <stdio.h>
void main(){
list lst = create_lst();
node* n1 = create_node_by_value(8);
node* n2 = create_node_by_value(2);
node* n3 = create_node_by_value(5);
node* n4 = create_node_by_value(4);
add_node(&lst, n1); add_node(&lst, n2); add_node(&lst, n3); add_node(&lst, n4);
delete_node(&lst, n3);
printf("%f\n", get_list_avg(lst));
printf("%d\n", get_node_data(get_first_node(lst)));
destroy_lst(lst);
queue q = create_queue();
add_queue(&q, 2); add_queue(&q, 5); add_queue(&q, 7); add_queue(&q, 6);
printf("%d\n", get_queue_first(q));
printf("%d\n", pop(&q));
printf("currrent length is: %d\n", get_queue_length(q));
add_queue(&q, 1000);
while (get_queue_length(q) > 0){
printf("now poping %d\n", pop(&q));
}
system("PAUSE");
}
|
C
|
#include "holberton.h"
int main(void) {
int len;
int len2;
len = _printf("Let's try to printf a simple sentence.\n");
_printf("Length:[%d, %i]\n", len, len);
_printf("Negative:[%d]\n", -762534);
_printf("Character:[%c]\n", 'H');
_printf("String:[%s]\n", "I am a string !");
len = _printf("Percent:[%%]\n");
len2 = printf("Percent:[%%]\n");
_printf("Len:[%d]\n", len);
printf("Len:[%d]\n", len2);
_printf("Unknown:[%r]\n");
printf("Unknown:[%r]\n");
_printf("There is %d bytes in %d KB\n", 1024, 1);
return 0;
}
|
C
|
/******************************************************************************
* Copyright (C) 2017 by Alex Fosdick - University of Colorado
*
* Redistribution, modification or use of this software in source or binary
* forms is permitted as long as the files maintain this copyright. Users are
* permitted to modify this and use it to learn about the field of embedded
* software. Alex Fosdick and the University of Colorado are not liable for any
* misuse of this material.
*
*****************************************************************************/
/*****************************************************************************
* Copyright 2019 Varun Mohan<[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction,including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*****************************************************************************/
/**
* @file stats.c
* @brief Program calculates statistics on an array of elements.
*
* This program contains various functions to calculate and print
* different staistics like mean, median, maximum and minimum of a
* set of elemnts in an array.
*
* @author Varun Mohan
* @date 10/08/2019
*
*/
#include <stdio.h>
#include "stats.h"
#include "platform.h"
/* Size of the Data Set */
/*#define SIZE (40)
unsigned char test[SIZE] = { 34, 201, 190, 154, 8, 194, 2, 6,
114, 88, 45, 76, 123, 87, 25, 23,
200, 122, 150, 90, 92, 87, 177, 244,
201, 6, 12, 60, 8, 2, 5, 67,
7, 87, 250, 230, 99, 3, 100, 90};
void main() {
unsigned char test[SIZE] = { 34, 201, 190, 154, 8, 194, 2, 6,
114, 88, 45, 76, 123, 87, 25, 23,
200, 122, 150, 90, 92, 87, 177, 244,
201, 6, 12, 60, 8, 2, 5, 67,
7, 87, 250, 230, 99, 3, 100, 90};
printf("\nThe array is : ");
print_array(test,SIZE);
printf("\n");
sort_array(test,SIZE);
printf("The sorted(descending order) array is : ");
print_array(test,SIZE);
printf("\n");
print_statistics(test,SIZE);
}*/
void print_statistics(unsigned char *array, unsigned int size)
{
printf("\n********************* Data Statistics ************************");
printf("\nMean : %u, Median : %u, Maximum : %u, Minimum : %u\n\n",find_mean(array,size),find_median(array,size),find_maximum(array,size),find_minimum(array,size));
}
void print_array(unsigned char *array, unsigned int size)
{
#ifdef VERBOSE
unsigned int i;
for(i=0;i<size;i++)
{
PRINTF("%d ", array[i]);
}
PRINTF("\n");
#endif
}
unsigned char find_median(unsigned char * array, unsigned int size)
{
sort_array(array,size);
if((size%2)!=0)
return array[(size/2)-1];
else
{
unsigned char mid1=array[(size/2)-1];
unsigned char mid2=array[(size/2)];
return (mid1+mid2)/2;
}
}
unsigned char find_mean(unsigned char * array, unsigned int size)
{
unsigned int i;
unsigned int sum=0;
for(i=0;i<size;i++)
sum=sum+array[i];
return sum/size;
}
unsigned char find_maximum(unsigned char * array, unsigned int size)
{
unsigned int i;
unsigned char max=array[0];
for(i=1;i<size;i++)
if(array[i]>max)
max=array[i];
return max;
}
unsigned char find_minimum(unsigned char * array, unsigned int size)
{
unsigned int i;
unsigned char min=array[0];
for(i=1;i<size;i++)
if(array[i]<min)
min=array[i];
return min;
}
void sort_array(unsigned char * array, unsigned int size)
{
unsigned int i,j;
for(i=0;i<size-1;i++)
for(j=0;j<size-1;j++)
if(array[j]<array[j+1])
swap(&array[j],&array[j+1]);
}
void swap(unsigned char *a,unsigned char *b)
{
unsigned char temp;
temp=*a;
*a=*b;
*b=temp;
}
|
C
|
//Write a C program to check two given integers, and return true if one of them is 30 or if their sum is 30
#include <stdio.h>
int main(){
int int1, int2, sum;
printf("Enter int1: ");
scanf("%d", &int1);
printf("Enter int2: ");
scanf("%d", &int2);
sum = int1 + int2;
if ((sum == 30) || (int1 == 30) || (int2 == 30)){
puts("True.");
}else {
puts("False.");
}
return 0;
}
|
C
|
/**
* @file server.c (IPK projekt 2)
*
* @brief SFTP - RFC-913 implementation
* @date 2021-04-23
* @author F3lda
* @update 2021-04-24
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>
#include <stdarg.h>
#include <fcntl.h>
#include <errno.h>
#include <ifaddrs.h>
#include <linux/if_link.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <time.h>
#include <dirent.h>
#include "../libs/processes.h"
#define MACHINE_NAME "IPK-SFTP-SERVER"
#define STDIN 0
#define STATIC_STRING_SIZE 512
#define MESSAGE_NULL_CHAR 1
struct client_info {
int socket;
char ip_address[STATIC_STRING_SIZE];
int port;
char pass_file[STATIC_STRING_SIZE];
};
#define INET64_ADDRSTRLEN 64
struct address_info_INET64 {
int count;
int current;
int family;
char address[INET64_ADDRSTRLEN];
union {
struct sockaddr_in v4;
struct sockaddr_in6 v6;
} addr;
};
int client_process(pid_t processID, void *userData);
int lookup_host(const char *host, struct address_info_INET64 *addr_info);
int get_interfaces(char * interface_name, char * interface_ip, int max_interface_ip_length, char * list, int max_list_length);
void trim(char * str);
int get_user_line(char * filename, char * user_line, int user_line_size);
int main(int argc, char *argv[])
{
// READ ARGS
// -------------------------
char arg_interface[STATIC_STRING_SIZE] = {0};
int arg_port = 0;
char arg_pass_file_path[STATIC_STRING_SIZE] = {0};
char usage_str[] = "usage: %s {-i <interface>} {-p <port>} -u <passwords file>\n";
int arg_check_sum = 0; // for mandatory arguments only
int i = 0;
while(++i < argc)
{
char *value1 = i+1 < argc ? argv[i+1] : NULL;
if (strlen(argv[i]) == 2 && argv[i][0] == '-') {
int option = argv[i][1];
switch(option)
{
case 'i':
case 'p':
case 'u':
{
if (value1 == NULL) {
fprintf(stderr,"ERROR - arguments: option %c - mmissing value\n%s", option, usage_str);
exit(EXIT_FAILURE);
} else if (option == 'i') {
if (arg_interface[0] == '\0') {
if (strlen(value1) < sizeof(arg_interface)) {
memcpy(arg_interface, value1, sizeof(arg_interface));
} else {
fprintf(stderr,"ERROR - arguments: option %c - value is too long (max size: %d chars)\n%s", sizeof(arg_interface)-1, option, usage_str);
exit(EXIT_FAILURE);
}
} else {
fprintf(stderr,"ERROR - arguments: option %c - duplicate\n%s", option, usage_str);
exit(EXIT_FAILURE);
}
} else if (option == 'p') {
if (arg_port == 0) {
arg_port = atoi(value1);
if (arg_port == 0) {
fprintf(stderr,"ERROR - arguments: option %c - invalid value\n%s", option, usage_str);
exit(EXIT_FAILURE);
}
} else {
fprintf(stderr,"ERROR - arguments: option %c - duplicate\n%s", option, usage_str);
exit(EXIT_FAILURE);
}
} else if (option == 'u') {
if (arg_pass_file_path[0] == '\0') {
if (strlen(value1) < sizeof(arg_pass_file_path)) {
memcpy(arg_pass_file_path, value1, sizeof(arg_pass_file_path));
} else {
fprintf(stderr,"ERROR - arguments: option %c - value is too long (max size: %d chars)\n%s", sizeof(arg_pass_file_path)-1, option, usage_str);
exit(EXIT_FAILURE);
}
} else {
fprintf(stderr,"ERROR - arguments: option %c - duplicate\n%s", option, usage_str);
exit(EXIT_FAILURE);
}
arg_check_sum++; // mandatory argument
}
break;
}
default:
{
fprintf(stderr,"ERROR - arguments: option %c - unknown\n%s", option, usage_str);
exit(EXIT_FAILURE);
}
}
}
}
if (arg_check_sum != 1) {// number of mandatory arguments
fprintf(stderr,"ERROR - arguments: missing arguments\n%s", usage_str);
exit(EXIT_FAILURE);
}
if (arg_port == 0) {arg_port = 115;}
// CHECK ARGS
// -------------------------
// check file
FILE *file;
if ((file = fopen(arg_pass_file_path, "r")) == NULL) {
perror("ERROR - password file doesn't exist");
exit(EXIT_FAILURE);
}
fclose(file);
// check interface
char interface_ip[STATIC_STRING_SIZE] = {0};
char interface_list[1024] = {0};
get_interfaces(arg_interface, interface_ip, STATIC_STRING_SIZE-1, interface_list, 1023);
printf("%s\n", interface_list);
if (arg_interface[0] != '\0' && interface_ip[0] == '\0') {
perror("ERROR - interface ip not found");
exit(EXIT_FAILURE);
} else if (interface_ip[0] == '\0') {
strcpy(interface_ip, "::"); // = INADDR6_ANY -> eqivalent for 0.0.0.0
// AF_INET6 -> for both IPv4 and IPv6 (for only IPv6 -> socket option - IPV6_V6ONLY) -> https://www.ibm.com/docs/en/i/7.4?topic=sscaaiic-example-accepting-connections-from-both-ipv6-ipv4-clients
}
printf("SELECTED INTERFACE IP: %s (:: = all interfaces)\n\n", interface_ip);
printf("----------------------------\n\n");
// CREATE SERVER
// -------------------------
// prepare socket
int welcome_socket;
struct address_info_INET64 addr_info;
memset(&addr_info, 0, sizeof(addr_info));
// set local ip and family
lookup_host(interface_ip, &addr_info);
// set local port
if (addr_info.family == AF_INET) {
//printf("IPv4\n");
//addr_info.addr.v4.sin_family = AF_INET;
addr_info.addr.v4.sin_port = htons(arg_port);
// bind socket to specific interface (selects the first interface with the name equal to the name inserted by user -> maybe TODO option '-6' -> for the first ipv6 interface)
//inet_pton(AF_INET, addr_info.address, (void *)&addr_info.addr.v4.sin_addr.s_addr);
} else if (addr_info.family == AF_INET6) { // PF_INET6 -> https://stackoverflow.com/questions/6729366/what-is-the-difference-between-af-inet-and-pf-inet-in-socket-programming
//printf("IPv6\n");
//addr_info.addr.v6.sin6_family = AF_INET6;
addr_info.addr.v6.sin6_port = htons(arg_port);
// bind socket to specific interface (selects the first interface with the name equal to the name inserted by user -> maybe TODO option '-6' -> for the first ipv6 interface)
//inet_pton(AF_INET6, addr_info.address, (void *)&addr_info.addr.v6.sin6_addr.s6_addr);
//addr_info.addr.v6.sin6_scope_id = if_nametoindex(arg_interface);
}
// create server main socket
if ((welcome_socket = socket(addr_info.family, SOCK_STREAM, 0)) < 0) {
perror("ERROR - socket");
exit(EXIT_FAILURE);
}
// enable immediate address reuse
int enable = 1;
if (setsockopt(welcome_socket, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable)) < 0) {
perror("ERROR - SO_REUSEADDR");
exit(EXIT_FAILURE);
}
// bind socket to the port
if (bind(welcome_socket, (struct sockaddr*)&addr_info.addr, sizeof(addr_info.addr)) < 0) {
perror("ERROR - bind port");
exit(EXIT_FAILURE);
}
if ((listen(welcome_socket, 16)) < 0) {
perror("ERROR - listen");
exit(EXIT_FAILURE);
}
// set non-blocking socket
int flags = fcntl(welcome_socket, F_GETFL, 0);
if (fcntl(welcome_socket, F_SETFL, flags | O_NONBLOCK) < 0) {
perror("ERROR - non-blocking");
exit(EXIT_FAILURE);
}
// socket blocking timeout
struct timeval timeoutStruct = {0, 0}; // socket blocking timeout (seconds, nanoseconds)
fd_set fd_welcome_socket; // socket file descriptors
// SERVER SOCKET LOOP
// -------------------------
printf("\n\nSERVER STARTED SUCCESSFULLY!\n");
printf("--------------------------------------------------------\n");
struct sockaddr_in6 sa_client;
socklen_t sa_client_len = sizeof(sa_client);
char ip_buffer[INET6_ADDRSTRLEN];
struct client_info clinfo;
memset(&clinfo, 0, sizeof(clinfo));
fd_set fds_stdin;
while(1)
{
// check a new client
FD_ZERO(&fd_welcome_socket);
FD_SET(welcome_socket, &fd_welcome_socket);
if (select(FD_SETSIZE, &fd_welcome_socket, NULL, NULL, &timeoutStruct) == 1) {
// accept new client
int new_client_socket = accept(welcome_socket, (struct sockaddr*)&sa_client, &sa_client_len);
if (new_client_socket >= 0) {
// create info struct for the new client and process
memset(&clinfo, 0, sizeof(clinfo));
clinfo.socket = new_client_socket;
if(inet_ntop(AF_INET6, &sa_client.sin6_addr, ip_buffer, sizeof(ip_buffer))) {
memcpy(clinfo.ip_address, ip_buffer, sizeof(clinfo.ip_address));
clinfo.port = ntohs(sa_client.sin6_port);
}
memcpy(clinfo.pass_file, arg_pass_file_path, sizeof(clinfo.pass_file));
// create the new process for the new client
ProcessCreate(client_process, &clinfo, false);
} else {
// error
break;
}
}
// check an input on STDIN
FD_ZERO(&fds_stdin);
FD_SET(STDIN, &fds_stdin);
if (select(1, &fds_stdin, NULL, NULL, &timeoutStruct) > 0) {
// read line from STDIN
char stdin_str[STATIC_STRING_SIZE] = {0};
fgets(stdin_str, sizeof(stdin_str), stdin);
trim(stdin_str);
if (strcmp(stdin_str, "DONE") == 0) {
while(ProcessCheckIfAnyChildProcessFinished() > 0){} // read all finished processes
// check if any clients are still connected
if (ProcessCheckIfAnyChildProcessFinished() == 0) {
printf("SOME CLIENTS STILL CONNECTED!\nKILLING ALL PROCESSES...\n");
close(welcome_socket);
kill(0, SIGKILL);
}
errno = 0;
break;
}
// write line to STDOUT
if (stdin_str[0] != '\0') {
printf("> %s\n", stdin_str);
}
}
// short delay
usleep(1000000/30);
}
// -------------------------
// FREE SOCKET
// close server socket
close(welcome_socket);
printf("SERVER FINISHED OK: %s\n", strerror(errno));
return 0;
}
int client_process(pid_t processID, void *userData)
{
// read client info struct
struct client_info clinfo;
memset(&clinfo, 0, sizeof(clinfo));
clinfo = *((struct client_info *)userData);
printf("NEW CLIENT CONNECTED: [%s]:%d\n", clinfo.ip_address, clinfo.port);
printf("PASS FILE: %s\n", clinfo.pass_file);
int client_socket = clinfo.socket;
// send welcome message
send(client_socket, "+", 1, 0);
send(client_socket, MACHINE_NAME, strlen(MACHINE_NAME), 0);
send(client_socket, " SFTP Service", strlen(" SFTP Service")+MESSAGE_NULL_CHAR, 0);
// vars
int LOGGED_IN = 0;
char LAST_CMD[5] = {0};
char user_line[STATIC_STRING_SIZE] = {0};
char STREAM_TYPE = 'B';
int DIR_COUNT = 0;
char RENAME_FILE[STATIC_STRING_SIZE] = {0};
char DOWNLOAD_FILE[STATIC_STRING_SIZE] = {0};
char message_buffer[STATIC_STRING_SIZE] = {0};
int receivedBytes = 0;
while(1)
{
receivedBytes = recv(client_socket, message_buffer, sizeof(message_buffer),0);
if (receivedBytes <= 0)
break;
printf("MESSAGE ([%s]:%d): <%s>(%d)\n", clinfo.ip_address, clinfo.port, message_buffer, receivedBytes);
// handle message and send response
//-------------------------------------------------
// check if file bytes are not in MESSAGE
if (strcmp(LAST_CMD, "SIZE") != 0) { // strcmp(LAST_CMD, "SEND") != 0 &&
// handle current CMD
// DONE
if (strncmp(message_buffer, "DONE", 4) == 0) {
memcpy(message_buffer, "+DONE - close the connection", strlen("+DONE - close the connection")+1);
// USER id - ACCT account
} else if (strncmp(message_buffer, "USER", 4) == 0 || strncmp(message_buffer, "ACCT", 4) == 0) {
// username received
if (receivedBytes > 6) {
char *username = message_buffer+5;
printf("USERNAME: %s\n", username);
// already logged in
if (LOGGED_IN == 1 && strstr(user_line, username) == user_line) {
if (strncmp(message_buffer, "USER", 4) == 0) {// USER
char str_temp[STATIC_STRING_SIZE] = {0};
snprintf(str_temp, sizeof(str_temp), "!%s logged in", username);
memcpy(message_buffer, str_temp, strlen(str_temp)+1);
} else {// ACCT
memcpy(message_buffer, "! Account valid, logged-in", strlen("! Account valid, logged-in")+1);
}
// new user
} else {
LOGGED_IN = 0;
memset(user_line, '\0', sizeof(user_line));
memcpy(user_line, username, sizeof(user_line));
int userNeeded = get_user_line(clinfo.pass_file, user_line, sizeof(user_line));
// invalid user id
if (userNeeded == 1 && user_line[0] == '\0') {
if (strncmp(message_buffer, "USER", 4) == 0) {// USER
memcpy(message_buffer, "-Invalid user-id, try again", strlen("-Invalid user-id, try again")+1);
} else {// ACCT
memcpy(message_buffer, "-Invalid account, try again", strlen("-Invalid account, try again")+1);
}
// valid user id - need password
} else if (userNeeded == 1 && user_line[0] != '\0' && (strchr(user_line, ':')+1)[0] != '\0') {
if (strncmp(message_buffer, "USER", 4) == 0) {// USER
memcpy(message_buffer, "+User-id valid, send account and password", strlen("+User-id valid, send account and password")+1);
} else {// ACCT
memcpy(message_buffer, "+Account valid, send password", strlen("+Account valid, send password")+1);
}
// user id or password not needed
} else {
// add user id to user_line
snprintf(user_line, sizeof(user_line), "%s:", username);
if (strncmp(message_buffer, "USER", 4) == 0) {// USER
char str_temp[STATIC_STRING_SIZE] = {0};
snprintf(str_temp, sizeof(str_temp), "!%s logged in", username);
memcpy(message_buffer, str_temp, strlen(str_temp)+1);
} else {// ACCT
memcpy(message_buffer, "! Account valid, logged-in", strlen("! Account valid, logged-in")+1);
}
LOGGED_IN = 1;
}
printf("USER: needed: %d - found: %s\n", userNeeded, user_line);
}
// no username received
} else {
if (strncmp(message_buffer, "USER", 4) == 0) {// USER
memcpy(message_buffer, "-Invalid user-id, try again", strlen("-Invalid user-id, try again")+1);
} else {// ACCT
memcpy(message_buffer, "-Invalid account, try again", strlen("-Invalid account, try again")+1);
}
}
// PASS password
} else if (strncmp(message_buffer, "PASS", 4) == 0) {
// password received
if (receivedBytes > 6) {
char *password = message_buffer+5;
printf("PASSWORD: %s\n", password);
// no username or already logged in
if (user_line[0] == '\0' || LOGGED_IN == 1) {
memcpy(message_buffer, "+Send account", strlen("+Send account")+1);
// password ok
} else if (strcmp((strstr(user_line, ":")+1), password) == 0) {
LOGGED_IN = 1;
memcpy(message_buffer, "! Logged in", strlen("! Logged in")+1);
// invalid password
} else {
memcpy(message_buffer, "-Wrong password, try again", strlen("-Wrong password, try again")+1);
}
// no password received
} else {
memcpy(message_buffer, "-Wrong password, try again", strlen("-Wrong password, try again")+1);
}
// CMDS AFTER LOGIN
} else if (LOGGED_IN == 1) {
// TYPE {A, B, C}
if (strncmp(message_buffer, "TYPE", 4) == 0) {
if (receivedBytes == 7) {
// ACII
if (message_buffer[5] == 'A') {
STREAM_TYPE = message_buffer[5];
memcpy(message_buffer, "+Using Ascii mode", strlen("+Using Ascii mode")+1);
// BINARY
} else if(message_buffer[5] == 'B') {
STREAM_TYPE = message_buffer[5];
memcpy(message_buffer, "+Using Binary mode", strlen("+Using Binary mode")+1);
// CONTINUOUS
} else if(message_buffer[5] == 'C') {
STREAM_TYPE = message_buffer[5];
memcpy(message_buffer, "+Using Continuous mode", strlen("+Using Continuous mode")+1);
// invalid type
} else {
memcpy(message_buffer, "-Type not valid", strlen("-Type not valid")+1);
}
// invalid type
} else {
memcpy(message_buffer, "-Type not valid", strlen("-Type not valid")+1);
}
// LIST {F, V} directory-path
} else if (strncmp(message_buffer, "LIST", 4) == 0 && (receivedBytes == 7 || (receivedBytes > 8 && message_buffer[6] == ' '))) {
if (message_buffer[5] == 'F' || message_buffer[5] == 'V') {
char curdir[2] = ".";
char *path = curdir;
if (receivedBytes > 8) {
path = message_buffer+7;
}
if (strstr(path, "..") == NULL) { // path can't go up
char tempBuffer[STATIC_STRING_SIZE] = {0};
strcpy(tempBuffer, "+");
strcat(tempBuffer, path);
strcat(tempBuffer, "\r\n");
send(client_socket, tempBuffer, strlen(tempBuffer), 0);
printf("path: %s\n", path);
DIR *directory;
struct dirent *dir;
directory = opendir(path);
if (directory) {
while ((dir = readdir(directory)) != NULL) {
if (strcmp(dir->d_name, ".") != 0 && strcmp(dir->d_name, "..") != 0) {
if (message_buffer[5] == 'F') { // F format
snprintf(tempBuffer, sizeof(tempBuffer), "%s\r\n", dir->d_name);
} else { // V format
char filePath[STATIC_STRING_SIZE] = {0};
snprintf(filePath, sizeof(filePath), "%s/%s", path, dir->d_name);
struct stat sb;
if (stat(filePath, &sb) == -1) {
snprintf(tempBuffer, sizeof(tempBuffer), "%s - no info\r\n", dir->d_name);
} else {
snprintf(tempBuffer, sizeof(tempBuffer), "%s\t\t%lld bytes\tUID=%ld GID=%ld\t%s\r\n", dir->d_name, (long long) sb.st_size, (long) sb.st_uid, (long) sb.st_gid, ctime(&sb.st_mtime));
}
}
//printf("%s\n", tempBuffer);
send(client_socket, tempBuffer, strlen(tempBuffer), 0);
}
}
closedir(directory);
memset(message_buffer, 0, sizeof(message_buffer)); // send MESSAGE_NULL_CHAR
} else {
memcpy(message_buffer, "-List path not valid", strlen("-List path not valid")+1);
}
} else {
memcpy(message_buffer, "-List path can't go up", strlen("-List path can't go up")+1);
}
// invalid
} else {
memcpy(message_buffer, "-List format not valid", strlen("-List format not valid")+1);
}
// CDIR new-directory
} else if (strncmp(message_buffer, "CDIR", 4) == 0 && receivedBytes > 6) {
char *path = message_buffer+5;
printf("DIR: %s\n", path);
printf("DIR COUNT: %d\n", DIR_COUNT);
if (strcmp(path, "..") != 0 || DIR_COUNT > 0) { // check top dir
if (strchr(path, '\\') == NULL && strchr(path, '/') == NULL) { // only one dir
DIR* dir = opendir(path);
if (dir) {
closedir(dir);
if (chdir(path) == 0) {
if (strcmp(path, "..") == 0) { // add/sub dir depth
DIR_COUNT--;
} else {
DIR_COUNT++;
}
char str_temp[STATIC_STRING_SIZE] = {0};
snprintf(str_temp, sizeof(str_temp), "!Changed working dir to %s", path);
memcpy(message_buffer, str_temp, strlen(str_temp)+1);
} else {
memcpy(message_buffer, "-Can't connect to directory because: unable to open directory", strlen("-Can't connect to directory because: unable to open directory")+1);
}
} else if (ENOENT == errno) {
memcpy(message_buffer, "-Can't connect to directory because: directory does not exist", strlen("-Can't connect to directory because: directory does not exist")+1);
} else {
memcpy(message_buffer, "-Can't connect to directory because: unable to open directory", strlen("-Can't connect to directory because: unable to open directory")+1);
}
} else {
memcpy(message_buffer, "-Can't connect to directory because: only one directory can be changed", strlen("-Can't connect to directory because: only one directory can be changed")+1);
}
} else {
memcpy(message_buffer, "-Can't connect to directory because: current directory is top directory", strlen("-Can't connect to directory because: current directory is top directory")+1);
}
// KILL file-name
} else if (strncmp(message_buffer, "KILL", 4) == 0 && receivedBytes > 6) {
char *filename = message_buffer+5;
printf("FILE: %s\n", filename);
if (strstr(filename, "..") == NULL) { // path can't go up
if(remove(filename) == 0) { // remove file
char str_temp[STATIC_STRING_SIZE] = {0};
snprintf(str_temp, sizeof(str_temp), "+%s deleted", filename);
memcpy(message_buffer, str_temp, strlen(str_temp)+1);
} else {
memcpy(message_buffer, "-Not deleted because unable to delete the file", strlen("-Not deleted because unable to delete the file")+1);
}
} else {
memcpy(message_buffer, "-Not deleted because path can't go up", strlen("-Not deleted because path can't go up")+1);
}
// NAME file-name
} else if (strncmp(message_buffer, "NAME", 4) == 0 && receivedBytes > 6) {
char *filename = message_buffer+5;
printf("FILE: %s\n", filename);
if (strstr(filename, "..") == NULL) { // path can't go up
FILE *file;
if ((file = fopen(filename, "r")) != NULL) { // file exists?
fclose(file);
snprintf(RENAME_FILE, sizeof(RENAME_FILE), "%s", filename); // save file name
memcpy(message_buffer, "+File exists", strlen("+File exists")+1);
} else {
char str_temp[STATIC_STRING_SIZE] = {0};
snprintf(str_temp, sizeof(str_temp), "-Can't find %s", filename);
memcpy(message_buffer, str_temp, strlen(str_temp)+1);
}
} else {
char str_temp[STATIC_STRING_SIZE] = {0};
snprintf(str_temp, sizeof(str_temp), "-Can't find %s because path can't go up", filename);
memcpy(message_buffer, str_temp, strlen(str_temp)+1);
}
// TOBE new-name
} else if (strncmp(message_buffer, "TOBE", 4) == 0 && receivedBytes > 6) {
char *filename = message_buffer+5;
printf("FILE OLD: %s\n", RENAME_FILE);
printf("FILE NEW: %s\n", filename);
if (strstr(filename, "..") == NULL) { // path can't go up
if(rename(RENAME_FILE, filename) == 0) { // rename file
char str_temp[STATIC_STRING_SIZE] = {0};
snprintf(str_temp, sizeof(str_temp), "+%s renamed to %s", RENAME_FILE, filename);
memcpy(message_buffer, str_temp, strlen(str_temp)+1);
memset(RENAME_FILE, 0, sizeof(RENAME_FILE));
} else {
memcpy(message_buffer, "-File wasn't renamed because unable to rename the file", strlen("-File wasn't renamed because unable to rename the file")+1);
}
} else {
memcpy(message_buffer, "-File wasn't renamed because path can't go up", strlen("-File wasn't renamed because path can't go up")+1);
}
// RETR file-name
} else if (strncmp(message_buffer, "RETR", 4) == 0 && receivedBytes > 6) {
char *filename = message_buffer+5;
printf("FILE: %s\n", filename);
if (strstr(filename, "..") == NULL) { // path can't go up
FILE *file;
if ((file = fopen(filename, "r")) != NULL) { // file exists?
fclose(file);
printf("FILE eXISTS\n");
struct stat sb;
if (stat(filename, &sb) != -1) { // get file size
snprintf(DOWNLOAD_FILE, sizeof(DOWNLOAD_FILE), "%s", filename); // save file name
char str_temp[STATIC_STRING_SIZE] = {0};
snprintf(str_temp, sizeof(str_temp), " %lld", (long long) sb.st_size);
memcpy(message_buffer, str_temp, strlen(str_temp)+1);
} else {
memcpy(message_buffer, "-File doesn't exist", strlen("-File doesn't exist")+1);
}
} else {
memcpy(message_buffer, "-File doesn't exist", strlen("-File doesn't exist")+1);
}
} else {
memcpy(message_buffer, "-File doesn't exist because path can't go up", strlen("-File doesn't exist because path can't go up")+1);
}
// SEND
} else if (strncmp(message_buffer, "SEND", 4) == 0) {
FILE *download_file = fopen(DOWNLOAD_FILE, "r");
if(download_file == NULL){
printf("File doesn't exist\n");
memcpy(message_buffer, "-File doesn't exist", strlen("-File doesn't exist")+1);
} else {
char buffer[STATIC_STRING_SIZE] = {0};
while(fread(buffer, 1, sizeof(buffer)-1, download_file) > 0) {
send(client_socket, buffer, strlen(buffer), 0); // send data
memset(buffer, 0, sizeof(buffer)); // clear buffer
}
fclose(download_file);
printf("FILE DOWNLOADED\n");
memset(message_buffer, 0, sizeof(message_buffer)); // send MESSAGE_NULL_CHAR
}
// STOP
} else if (strncmp(message_buffer, "STOP", 4) == 0) {
memset(DOWNLOAD_FILE, 0, sizeof(DOWNLOAD_FILE)); // clear download file path
memcpy(message_buffer, "+ok, RETR aborted", strlen("+ok, RETR aborted")+1);
// Invalid command
} else {
memcpy(message_buffer, "-Invalid command", strlen("-Invalid command")+1);
}
// NOT LOGGED IN or Invalid command
} else {
memcpy(message_buffer, "-NOT Logged in or Invalid command", strlen("-NOT Logged in or Invalid command")+1);
}
// save current CMD
strncpy(LAST_CMD, message_buffer, 4);
}
//-------------------------------------------------
// handle message and send response - END
send(client_socket, message_buffer, strlen(message_buffer)+MESSAGE_NULL_CHAR, 0);
memset(message_buffer, 0, sizeof(message_buffer));
}
// FREE SOCKET
close(client_socket);
printf("CLIENT DISCONNECTED: [%s]:%d\n", clinfo.ip_address, clinfo.port);
return 0;
}
int get_user_line(char * filename, char * user_line, int user_line_size)
{ // returns true/false if user is needed (file is emtpy)
FILE *passfile = fopen(filename, "r");
if(passfile == NULL){
fprintf(stderr, "ERROR - OPEN FILE: %s\n", filename);
return 0;
}
int user_found = 0;
int line_count = 0;
char buffer[STATIC_STRING_SIZE] = {0};
while(fgets(buffer, STATIC_STRING_SIZE-1, passfile)) {
if (strchr(buffer, '\n') != NULL) {line_count++;}
trim(buffer);
if (buffer[0] != '\0') {
if (strstr(buffer, user_line) == buffer && (buffer+strlen(user_line))[0] == ':') { // line starts with username and ':'
user_found = 1;
memcpy(user_line, buffer, user_line_size); // return line from file with password
break;
}
//printf("<%s>\n", buffer);
}
}
fclose(passfile);
if (user_found == 0) {
memset(user_line, '\0', user_line_size);
}
return (line_count > 0);
}
void trim(char * str)
{
char * front = str-1;
while(isspace(*++front));
char * back = front+strlen(front);
if(front[0] != 0){
while(isspace(*--back));
*(++back) = '\0';}
if(front != str){memcpy(str, front, back-front+1);}
}
int lookup_host(const char *host, struct address_info_INET64 *addr_info)
{// https://gist.github.com/jirihnidek/bf7a2363e480491da72301b228b35d5d
struct addrinfo hints, *result, *info;
int exit_code = 0;
memset(&hints, 0, sizeof (hints));
hints.ai_family = PF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags |= AI_CANONNAME | AI_PASSIVE;
if (getaddrinfo(host, NULL, &hints, &result) != 0) {
perror("ERROR - getaddrinfo");
return -1;
}
info = result;
while(info != NULL)
{
if (addr_info->current == addr_info->count) {
char addr_buffer[INET64_ADDRSTRLEN] = {0};
if (info->ai_family == AF_INET) {
addr_info->family = info->ai_family;
if (inet_ntop(info->ai_family, &((struct sockaddr_in *)info->ai_addr)->sin_addr, addr_buffer, sizeof(addr_buffer)) == NULL) {
exit_code = -2;
break;
}
memcpy(addr_info->address, addr_buffer, sizeof(addr_buffer));
memcpy(&addr_info->addr.v4, info->ai_addr, info->ai_addrlen);
} else if (info->ai_family == AF_INET6) {
addr_info->family = info->ai_family;
if (inet_ntop(info->ai_family, &((struct sockaddr_in6 *)info->ai_addr)->sin6_addr, addr_buffer, sizeof(addr_buffer)) == NULL) {
exit_code = -3;
break;
}
memcpy(addr_info->address, addr_buffer, sizeof(addr_buffer));
memcpy(&addr_info->addr.v6, info->ai_addr, info->ai_addrlen);
}
//printf("IPv%d address: %s (%s)\n", info->ai_family == PF_INET6 ? 6 : 4, addr_buffer, info->ai_canonname);
}
addr_info->count++;
info = info->ai_next;
}
freeaddrinfo(result);
return exit_code;
}
int get_interfaces(char * interface_name, char * interface_ip, int max_interface_ip_length, char * interface_list, int max_list_length)
{// https://man7.org/linux/man-pages/man3/getifaddrs.3.html
struct ifaddrs *ifaddr, *ifa;
int family = -1, exit_code = 0;
char host[NI_MAXHOST];
if (getifaddrs(&ifaddr) == -1) {
perror("ERROR - getifaddrs");
return -1;
}
snprintf(interface_list+strlen(interface_list), max_list_length-strlen(interface_list), "\nLIST OF ETHERNET INTERFACES\n");
snprintf(interface_list+strlen(interface_list), max_list_length-strlen(interface_list), "----------------------------\n");
for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
if (ifa->ifa_addr != NULL) {
if (family == AF_PACKET && ifa->ifa_addr->sa_family != AF_PACKET) {
snprintf(interface_list+strlen(interface_list), max_list_length-strlen(interface_list), "----------------------------\n");
}
family = ifa->ifa_addr->sa_family;
if (family == AF_INET || family == AF_INET6) {
if (getnameinfo(ifa->ifa_addr, (family == AF_INET) ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6), host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST) != 0) {
perror("ERROR - getnameinfo");
exit_code = 0;
break;
}
snprintf(interface_list+strlen(interface_list), max_list_length-strlen(interface_list), "%-8s %s \t(%d) \taddress: <%s>\n", ifa->ifa_name, (family == AF_PACKET) ? "AF_PACKET" : (family == AF_INET) ? "AF_INET" : (family == AF_INET6) ? "AF_INET6" : "???", family, host);
if (strcmp(ifa->ifa_name, interface_name) == 0 && interface_ip[0] == '\0') {
memcpy(interface_ip, host, max_interface_ip_length);
}
} else if (family == AF_PACKET && ifa->ifa_data != NULL) {
snprintf(interface_list+strlen(interface_list), max_list_length-strlen(interface_list), "%-8s\n", ifa->ifa_name);
}
}
}
snprintf(interface_list+strlen(interface_list), max_list_length-strlen(interface_list), "----------------------------\n");
freeifaddrs(ifaddr);
return exit_code;
}
|
C
|
#include <stdlib.h>
#include "lerror.h"
#include "circularBuffer.h"
void pushNode(circularBuffer* this, char* value) {
circularNode* node;
if ((node = malloc(sizeof(circularNode))) == NULL)
lerror(MEMORY_ERROR(sizeof(circularNode)));
node->next = NULL;
if (!this->endQueue)
this->endQueue = node;
else
this->endQueue->next = node;
if (!this->queue)
this->queue = node;
this->endQueue = node;
node->value = value;
this->size += 1;
}
char* popNode(circularBuffer* this) {
circularNode* node;
char* txt;
if (!this->queue)
return (NULL);
txt = this->queue->value;
node = this->queue;
if (node == this->endQueue)
this->endQueue = NULL;
this->queue = this->queue->next;
free(node);
this->size -= 1;
return (txt);
}
void destroyBuffer(circularBuffer* this, bool freeNodeVal) {
char* k;
while (this->size > 0) {
k = popNode(this);
if (freeNodeVal)
free(k);
}
free(this);
}
circularBuffer* createBuffer(){
circularBuffer* this;
if ((this = malloc(sizeof(circularBuffer))) == NULL)
lerror(MEMORY_ERROR(sizeof(circularBuffer)));
this->queue = this->endQueue = NULL;
this->size = 0;
return (this);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "stdbool.h"
struct stack {
int val;
struct stack* next;
}stack;
struct stack* head = NULL;
void push(int x) {
struct stack* new = (struct stack*)
malloc(sizeof(struct stack*));
new->val = x;
new->next = head;
head = new;
printf("Element pushed: %d\n", x);
}
bool isEmpty() {
if (head == NULL) {
return true;
}
return false;
}
int pop() {
struct stack* temp;
int x;
if (isEmpty()) {
perror("Stack is empty");
return -1;
}
temp = head;
x = temp->val;
head = head->next;
free(temp);
return x;
}
int peek() {
if (isEmpty()) {
perror("Stack is empty");
return -1;
}
int x = head->val;
return x;
}
void print() {
struct stack* temp;
temp = head;
if (isEmpty()) {
perror("Stack is empty");
}
while (temp != NULL) {
printf("%d ", temp->val);
temp = temp->next;
}
printf("\n");
}
int main() {
push(2); push(3); push(1); push(7);
print();
printf("%d\n", peek());
return 0;
}
|
C
|
/*! \file JmsMapMessage.h
\brief Describes a JmsMapMessage handle
This file describes the functions that can be performed on a JmsMapMessage handle
A JmsMapMessage handle corresponds to javax.jms.MapMessage
\author Copyright (c) 2002, BEA Systems, Inc.
*/
#ifndef _JMS_MAP_MESSAGE_H
#define _JMS_MAP_MESSAGE_H 1
#include <JmsCommon.h>
#include <JmsSession.h>
#include <JmsMessage.h>
#include <JmsEnumeration.h>
#include <JmsTypes.h>
/*!
A map message handle that represents the class javax.jms.MapMessage
*/
typedef JmsMessage JmsMapMessage;
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
/*!
Gets a map message handle from the given session handle
\param session Must be a valid session handle. May not be NULL
\param message May not be NULL. On success, *message will contain
a valid map message handle
\param flags Reserved for future use. Must be zero
\return
- JMS_NO_ERROR
- JMS_GOT_EXCEPTION
- JMS_INPUT_PARAM_ERROR
- JMS_MALLOC_ERROR
- JMS_JVM_ERROR
*/
extern int JMSENTRY JmsSessionMapMessageCreate(
JmsSession * session,
JmsMapMessage ** message,
JMS64I flags
);
/*!
Gets a boolean value of the given tag name from a map message handle
\param message Must be a valid map message handle. May not be NULL
\param name The tag name to retrieve
\param value May not be NULL. On success, *value will contain the
boolean value with the given tag name
\param flags Reserved for future use. Must be zero
\return
- JMS_NO_ERROR
- JMS_GOT_EXCEPTION
- JMS_INPUT_PARAM_ERROR
- JMS_MALLOC_ERROR
- JMS_JVM_ERROR
*/
extern int JMSENTRY JmsMapMessageGetBoolean(
JmsMapMessage * message,
JmsString * name,
int * value,
JMS64I flags
);
/*!
Gets a byte value of the given tag name from a map message handle
\param message Must be a valid map message handle. May not be NULL
\param name The tag name to retrieve
\param value May not be NULL. On success, *value will contain the
byte value with the given tag name
\param flags Reserved for future use. Must be zero
\return
- JMS_NO_ERROR
- JMS_GOT_EXCEPTION
- JMS_INPUT_PARAM_ERROR
- JMS_MALLOC_ERROR
- JMS_JVM_ERROR
*/
extern int JMSENTRY JmsMapMessageGetByte(
JmsMapMessage * message,
JmsString * name,
unsigned char * value,
JMS64I flags
);
/*!
Gets a two byte java character value of the given tag name from a map
message handle
\param message Must be a valid map message handle. May not be NULL
\param name The tag name to retrieve
\param value May not be NULL. On success, *value will contain the
two byte java character value with the given tag name
\param flags Reserved for future use. Must be zero
\return
- JMS_NO_ERROR
- JMS_GOT_EXCEPTION
- JMS_INPUT_PARAM_ERROR
- JMS_MALLOC_ERROR
- JMS_JVM_ERROR
*/
extern int JMSENTRY JmsMapMessageGetChar(
JmsMapMessage * message,
JmsString * name,
short * value,
JMS64I flags
);
/*!
Gets a short value of the given tag name from a map message handle
\param message Must be a valid map message handle. May not be NULL
\param name The tag name to retrieve
\param value May not be NULL. On success, *value will contain the
short value with the given tag name
\param flags Reserved for future use. Must be zero
\return
- JMS_NO_ERROR
- JMS_GOT_EXCEPTION
- JMS_INPUT_PARAM_ERROR
- JMS_MALLOC_ERROR
- JMS_JVM_ERROR
*/
extern int JMSENTRY JmsMapMessageGetShort(
JmsMapMessage * message,
JmsString * name,
short * value,
JMS64I flags
);
/*!
Gets an integer value of the given tag name from a map message handle
\param message Must be a valid map message handle. May not be NULL
\param name The tag name to retrieve
\param value May not be NULL. On success, *value will contain the
integer value with the given tag name
\param flags Reserved for future use. Must be zero
\return
- JMS_NO_ERROR
- JMS_GOT_EXCEPTION
- JMS_INPUT_PARAM_ERROR
- JMS_MALLOC_ERROR
- JMS_JVM_ERROR
*/
extern int JMSENTRY JmsMapMessageGetInt(
JmsMapMessage * message,
JmsString * name,
JMS32I * value,
JMS64I flags
);
/*!
Gets a long value of the given tag name from a map message handle
\param message Must be a valid map message handle. May not be NULL
\param name The tag name to retrieve
\param value May not be NULL. On success, *value will contain the
long value with the given tag name
\param flags Reserved for future use. Must be zero
\return
- JMS_NO_ERROR
- JMS_GOT_EXCEPTION
- JMS_INPUT_PARAM_ERROR
- JMS_MALLOC_ERROR
- JMS_JVM_ERROR
*/
extern int JMSENTRY JmsMapMessageGetLong(
JmsMapMessage * message,
JmsString * name,
JMS64I * value,
JMS64I flags
);
/*!
Gets a float value of the given tag name from a map message handle
\param message Must be a valid map message handle. May not be NULL
\param name The tag name to retrieve
\param value May not be NULL. On success, *value will contain the
float value with the given tag name
\param flags Reserved for future use. Must be zero
\return
- JMS_NO_ERROR
- JMS_GOT_EXCEPTION
- JMS_INPUT_PARAM_ERROR
- JMS_MALLOC_ERROR
- JMS_JVM_ERROR
*/
extern int JMSENTRY JmsMapMessageGetFloat(
JmsMapMessage * message,
JmsString * name,
float * value,
JMS64I flags
);
/*!
Gets a double value of the given tag name from a map message handle
\param message Must be a valid map message handle. May not be NULL
\param name The tag name to retrieve
\param value May not be NULL. On success, *value will contain the
double value with the given tag name
\param flags Reserved for future use. Must be zero
\return
- JMS_NO_ERROR
- JMS_GOT_EXCEPTION
- JMS_INPUT_PARAM_ERROR
- JMS_MALLOC_ERROR
- JMS_JVM_ERROR
*/
extern int JMSENTRY JmsMapMessageGetDouble(
JmsMapMessage * message,
JmsString * name,
double * value,
JMS64I flags
);
/*!
Gets a string value of the given tag name from a map message handle
\param message Must be a valid map message handle. May not be NULL
\param name The tag name to retrieve
\param value May not be NULL. On success, will contain the
string value with the given tag name
\param flags Reserved for future use. Must be zero
\return
- JMS_NO_ERROR
- JMS_GOT_EXCEPTION
- JMS_INPUT_PARAM_ERROR
- JMS_MALLOC_ERROR
- JMS_JVM_ERROR
- JMS_NEED_SPACE
*/
extern int JMSENTRY JmsMapMessageGetString(
JmsMapMessage * message,
JmsString * name,
JmsString * value,
JMS64I flags
);
/*!
Gets a byte array value of the given tag name from a map message handle
\param message Must be a valid map message handle. May not be NULL
\param name The tag name to retrieve
\param bytes May not be NULL. Must have at least *length bytes to be
written into. On success this array will be filled in up to *length bytes
\param length May not be NULL. On input, *length must contain the number
of bytes that can be written to bytes. If the return is JMS_NEED_SPACE
then *length will contain the number of bytes necessary to get the
complete byte array and bytes will have been filled in as much as possible.
On success, *length will contain the actual number of bytes written to
bytes
\param flags Reserved for future use. Must be zero
\return
- JMS_NO_ERROR
- JMS_GOT_EXCEPTION
- JMS_INPUT_PARAM_ERROR
- JMS_MALLOC_ERROR
- JMS_JVM_ERROR
- JMS_NEED_SPACE
*/
extern int JMSENTRY JmsMapMessageGetBytes(
JmsMapMessage * message,
JmsString * name,
void * bytes,
JMS32I * length,
JMS64I flags
);
/*!
Gets an enumeration handle containing the names of all the tags in this
map message handle
\param message Must be a valid map message handle. May not be NULL
\param enumeration May not be NULL. On success, *enumeration will
contain a valid enumeration handle. The value parameter of
JmsEnumerationNextElement should be a JmsString ** with this enumeration.
\param flags Reserved for future use. Must be zero
\return
- JMS_NO_ERROR
- JMS_GOT_EXCEPTION
- JMS_INPUT_PARAM_ERROR
- JMS_MALLOC_ERROR
- JMS_JVM_ERROR
- JMS_NEED_SPACE
*/
extern int JMSENTRY JmsMapMessageGetNames(
JmsMapMessage * message,
JmsEnumeration ** enumeration,
JMS64I flags
);
/*!
Sets a boolean value with the given tag name on a map message
\param message Must be a valid map message handle. May not be NULL
\param name The tag name to set
\param value The boolean value to set on the map message handle
\param flags Reserved for future use. Must be zero
\return
- JMS_NO_ERROR
- JMS_GOT_EXCEPTION
- JMS_INPUT_PARAM_ERROR
- JMS_MALLOC_ERROR
- JMS_JVM_ERROR
*/
extern int JMSENTRY JmsMapMessageSetBoolean(
JmsMapMessage * message,
JmsString * name,
int value,
JMS64I flags
);
/*!
Sets a byte value with the given tag name on a map message
\param message Must be a valid map message handle. May not be NULL
\param name The tag name to set
\param value The byte value to set on the map message handle
\param flags Reserved for future use. Must be zero
\return
- JMS_NO_ERROR
- JMS_GOT_EXCEPTION
- JMS_INPUT_PARAM_ERROR
- JMS_MALLOC_ERROR
- JMS_JVM_ERROR
*/
extern int JMSENTRY JmsMapMessageSetByte(
JmsMapMessage * message,
JmsString * name,
unsigned char value,
JMS64I flags
);
/*!
Sets a short value with the given tag name on a map message
\param message Must be a valid map message handle. May not be NULL
\param name The tag name to set
\param value The short value to set on the map message handle
\param flags Reserved for future use. Must be zero
\return
- JMS_NO_ERROR
- JMS_GOT_EXCEPTION
- JMS_INPUT_PARAM_ERROR
- JMS_MALLOC_ERROR
- JMS_JVM_ERROR
*/
extern int JMSENTRY JmsMapMessageSetShort(
JmsMapMessage * message,
JmsString * name,
short value,
JMS64I flags
);
/*!
Sets a two byte java character value with the given tag name on a
map message
\param message Must be a valid map message handle. May not be NULL
\param name The tag name to set
\param value The two byte java character value to set on the map
message handle
\param flags Reserved for future use. Must be zero
\return
- JMS_NO_ERROR
- JMS_GOT_EXCEPTION
- JMS_INPUT_PARAM_ERROR
- JMS_MALLOC_ERROR
- JMS_JVM_ERROR
*/
extern int JMSENTRY JmsMapMessageSetChar(
JmsMapMessage * message,
JmsString * name,
short value,
JMS64I flags
);
/*!
Sets an integer value with the given tag name on a map message
\param message Must be a valid map message handle. May not be NULL
\param name The tag name to set
\param value The integer value to set on the map message handle
\param flags Reserved for future use. Must be zero
\return
- JMS_NO_ERROR
- JMS_GOT_EXCEPTION
- JMS_INPUT_PARAM_ERROR
- JMS_MALLOC_ERROR
- JMS_JVM_ERROR
*/
extern int JMSENTRY JmsMapMessageSetInt(
JmsMapMessage * message,
JmsString * name,
JMS32I value,
JMS64I flags
);
/*!
Sets a long value with the given tag name on a map message
\param message Must be a valid map message handle. May not be NULL
\param name The tag name to set
\param value The long value to set on the map message handle
\param flags Reserved for future use. Must be zero
\return
- JMS_NO_ERROR
- JMS_GOT_EXCEPTION
- JMS_INPUT_PARAM_ERROR
- JMS_MALLOC_ERROR
- JMS_JVM_ERROR
*/
extern int JMSENTRY JmsMapMessageSetLong(
JmsMapMessage * message,
JmsString * name,
JMS64I value,
JMS64I flags
);
/*!
Sets a float value with the given tag name on a map message
\param message Must be a valid map message handle. May not be NULL
\param name The tag name to set
\param value The float value to set on the map message handle
\param flags Reserved for future use. Must be zero
\return
- JMS_NO_ERROR
- JMS_GOT_EXCEPTION
- JMS_INPUT_PARAM_ERROR
- JMS_MALLOC_ERROR
- JMS_JVM_ERROR
*/
extern int JMSENTRY JmsMapMessageSetFloat(
JmsMapMessage * message,
JmsString * name,
float value,
JMS64I flags
);
/*!
Sets a double value with the given tag name on a map message
\param message Must be a valid map message handle. May not be NULL
\param name The tag name to set
\param value The double value to set on the map message handle
\param flags Reserved for future use. Must be zero
\return
- JMS_NO_ERROR
- JMS_GOT_EXCEPTION
- JMS_INPUT_PARAM_ERROR
- JMS_MALLOC_ERROR
- JMS_JVM_ERROR
*/
extern int JMSENTRY JmsMapMessageSetDouble(
JmsMapMessage * message,
JmsString * name,
double value,
JMS64I flags
);
/*!
Sets a string value with the given tag name on a map message
\param message Must be a valid map message handle. May not be NULL
\param name The tag name to set
\param value The string value to set on the map message handle
\param flags Reserved for future use. Must be zero
\return
- JMS_NO_ERROR
- JMS_GOT_EXCEPTION
- JMS_INPUT_PARAM_ERROR
- JMS_MALLOC_ERROR
- JMS_JVM_ERROR
*/
extern int JMSENTRY JmsMapMessageSetString(
JmsMapMessage * message,
JmsString * name,
JmsString * value,
JMS64I flags
);
/*!
Sets a byte array value with the given tag name on a map message
\param message Must be a valid map message handle. May not be NULL
\param name The tag name to set
\param value The byte array to set on the map message handle
\param length The number of bytes to write from bytes
\param flags Reserved for future use. Must be zero
\return
- JMS_NO_ERROR
- JMS_GOT_EXCEPTION
- JMS_INPUT_PARAM_ERROR
- JMS_MALLOC_ERROR
- JMS_JVM_ERROR
*/
extern int JMSENTRY JmsMapMessageSetBytes(
JmsMapMessage * message,
JmsString * name,
void * value,
JMS32I length,
JMS64I flags
);
/*!
Tells whether or not a given tag name exists on the map message handles
\param message Must be a valid map message handle. May not be NULL
\param name The tag name to query
\param boolean May not be NULL. On success, *boolean will be zero if the tag
name does not exist on the message and will be non-zero if the tag name
does exist
\param flags Reserved for future use. Must be zero
\return
- JMS_NO_ERROR
- JMS_GOT_EXCEPTION
- JMS_INPUT_PARAM_ERROR
- JMS_MALLOC_ERROR
- JMS_JVM_ERROR
*/
extern int JMSENTRY JmsMapMessageItemExists(
JmsMapMessage * message,
JmsString * name,
int * boolean,
JMS64I flags
);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* _JMS_MAP_MESSAGE_H */
|
C
|
#include "list.h"
/*
* Generic doubly linked list.
* head,tail: pointers to first,last element
* len : number of nodes
* data_size: size of element data in bytes
* free_fn: function for deleting data
*/
struct list
{
list_node_t *head;
list_node_t *tail;
unsigned int len;
unsigned int data_size;
free_func free_fn;
};
/*
* Iterator for the list.
* prev,next: pointers to adjacent nodes at current position
* direction: movement type
*/
struct list_iterator
{
list_node_t *prev;
list_node_t *next;
iter_direction direction;
};
/* Create and initialize list */
void list_create(list_t **_list,unsigned int data_size, free_func free_fn)
{
if (((*_list) = (list_t*)malloc(sizeof(list_t))) == NULL) {
fprintf(stderr, "Failed to allocate linked list\n");
exit(EXIT_FAILURE);
};
(*_list)->head = NULL;
(*_list)->tail = NULL;
(*_list)->len = 0;
(*_list)->data_size = data_size;
(*_list)->free_fn = free_fn;
}
/* Delete list node */
static void list_delete(list_t *_list,list_node_t **node)
{
if ((!_list->len) || node == NULL) return;
list_node_t *next_node,*prev_node;
next_node = list_node_get_next(*node);
prev_node = list_node_get_prev(*node);
list_node_delete(node, _list->free_fn);
// Adjust previous and next node
if (prev_node != NULL) list_node_set_next(prev_node,next_node);
else _list->head = next_node;
if (next_node != NULL) list_node_set_prev(next_node,prev_node);
else _list->tail = prev_node;
_list->len--;
}
/* Delete list and all of its nodes */
void list_destroy(list_t **_list)
{
while ((*_list)->len) {
list_delete(*_list,&(*_list)->head);
}
free(*_list);
*_list = NULL;
}
/* Insert element after node 'prev_node'*/
static void list_insert_after(list_t *_list, list_node_t * prev_node, void *element)
{
list_node_t *new_node, *next_node;
list_node_create(&new_node,element);
list_node_set_prev(new_node, prev_node);
// Adjust previous and new node
if (prev_node != NULL) {
list_node_set_next(new_node,list_node_get_next(prev_node));
list_node_set_next(prev_node,new_node);
} else {
list_node_set_next(new_node,_list->head);
_list->head = new_node;
}
// Adjust next node too
next_node = list_node_get_next(new_node);
if (next_node != NULL) list_node_set_prev(next_node,new_node);
else _list->tail = new_node;
_list->len++;
}
// Specific insertions
void list_insert_after_iter(list_t *_list, list_iter_t * prev_iter, void *element)
{
list_insert_after(_list, prev_iter->prev, element);
}
void list_push(list_t *_list, void *element)
{
list_insert_after(_list, NULL, element);
}
void list_enqueue(list_t *_list, void *element)
{
list_insert_after(_list, _list->tail, element);
}
/* Insert to a sorted list keeping the list sorted */
void list_insert_sorted(list_t *_list, void *element, comp_func comp_fn)
{
list_node_t *cur = _list->head;
if (cur == NULL || comp_fn(list_node_get_data(cur),element) >= 0 ) {
list_push(_list,element);
} else {
// Find correct position to insert
while(cur!=NULL && comp_fn(list_node_get_data(cur),element)<0) {
cur = list_node_get_next(cur);
}
if (cur != NULL)list_insert_after(_list,list_node_get_prev(cur),element);
else list_enqueue(_list,element);
}
}
/* Specific deletion operations*/
void list_delete_at_iter(list_t *_list,list_iter_t *iter)
{
list_delete(_list,&iter->prev);
}
/* Remove first/last node and return their data*/
void list_pop(list_t *_list,void *front_data)
{
if (!_list->len) return;
memcpy(front_data,list_node_get_data(_list->head),_list->data_size);
list_delete(_list,&_list->head);
}
void list_dequeue(list_t *_list,void *tail_data)
{
if (!_list->len) return;
memcpy(tail_data,list_node_get_data(_list->tail),_list->data_size);
list_delete(_list,&_list->tail);
}
unsigned int list_get_len(list_t *_list)
{
return _list->len;
}
/* Create an iterator used to visit and operate on nodes */
void list_iter_create(list_iter_t **iter)
{
if (((*iter) = (list_iter_t*)malloc(sizeof(list_iter_t))) == NULL) {
fprintf(stderr, "Failed to allocate list iterator\n");
exit(EXIT_FAILURE);
};
}
/* Position iterator correctly depenging on the direction */
void list_iter_init(list_iter_t *iter, list_t *_list,iter_direction dir)
{
iter->direction = dir;
iter->prev = NULL;
if (_list != NULL) iter->next = dir == FORWARD ? _list->head : _list->tail;
else iter->next = NULL;
}
void list_iter_destroy (list_iter_t **iter)
{
free (*iter);
*iter = NULL;
}
/* Move to the next/previous node depending on direction*/
void * list_iter_next(list_iter_t *iter)
{
iter->prev = iter->next;
if (iter->next != NULL) iter->next = iter->direction == FORWARD
? list_node_get_next(iter->next)
: list_node_get_prev(iter->next);
return iter->prev != NULL ? list_node_get_data(iter->prev): NULL;
}
/* Sort list in descending order using selection sort */
void list_sort(list_t *_list, comp_func comp_fn)
{
if (_list->len < 2) return;
list_node_t *head = _list->head, *i, *j;
for (j=head;list_node_get_next(j)!=NULL;j=list_node_get_next(j)) {
// Find the maximum element in the unsorted sublist of indexes j..n-1
list_node_t *iMax = j;
for (i = list_node_get_next(j);i!=NULL;i=list_node_get_next(i)) {
if (comp_fn(list_node_get_data(i),list_node_get_data(iMax))>0) iMax = i;
}
if (iMax != j) {
void *tmp = list_node_get_data(j);
list_node_set_data(j,list_node_get_data(iMax));
list_node_set_data(iMax,tmp);
}
}
}
|
C
|
//
// main.c
// lista 02-9
//
// Created by Marco Antonio Zambeli on 09/07/13.
// Copyright (c) 2013 Marco Antonio Zambeli. All rights reserved.
//
#include <stdio.h>
#include <stdlib.h>
int vetneg (float vetor[],int tam)
{
int i,neg=0;
for(i=0;i<=tam;i++)
{
if(vetor[i]<0)
neg++;
}
return neg;
}
int main(int argc, const char * argv[])
{
int i,negativos;
float vet[10];
printf("criacao de um vetor de tamanho 10");
for(i=0;i<10;i++)
{
printf("\ndigite o valos do vetor na %d posicao:\n",i);
scanf("%f",&vet[i]);
}
negativos=vetneg(vet,10);
printf("existem %d numero(s) negativo(s) nesse vetor",negativos);
return 0;
}
|
C
|
#ifndef BITPRACTICE_H
#define BITPRACTICE_H
/*
The above preprocessor directives are what is called an "include guard".
They prevent compilation errors due to the same header file being included
multiple times.
*/
/*
This macro contains the number of bits in an int for the current implementation.
The sizeof() operator returns the number of bytes required to store its
argument. We then multiply that by 8 (8 bits = 1 byte).
*/
#define INT_BITS sizeof(int) * 8
/*
Uses bitwise operations to determine whether or not a number is even.
args : num (unsigned integer)
returns : 1 if num is even
0 if num is odd
*/
unsigned int isEven(unsigned int num);
/*
Uses bitwise operations to return one eighth of an unsigned integer.
(note that result will be integer division result)
args : num (unsigned integer)
returns : one eighth of num with fractional part of value discarded
*/
unsigned int eighth(unsigned int num);
/*
Uses bitwise operations to determine whether or not the nth bit is on (1).
args : num (unsigned integer)
: n (index of bit to check)
returns : 1 if nth bit in num has a value of 1
0 if nth bit in num has a value of 0
*/
unsigned int isNthBitOn(unsigned int num, unsigned int n);
/*
Flips all leading 0s in input number.
args : num (unsigned integer)
returns : num with all leading 0s flipped to 1
*/
unsigned int flipLeading0s (unsigned int num);
#endif
|
C
|
#include "../includes/rtv1.h"
t_object *ft_disk_new(void)
{
t_object *new;
if ((new = (t_object *)malloc(sizeof(*new))))
{
new->type = DISK;
new->name = "DISK";
new->pos = (t_vector){0.0, 0.0, 0.0};
new->translate = (t_vector){0.0, -1.01, 0.0};
new->rotate = (t_vector){0.0, 0.0, 0.0};
new->scale = (t_vector){1.0f, 1.0f, 1.0f};
new->normal = (t_vector){0.0, 0.0, 1.0};
new->material = (t_material){{ft_rand48(), ft_rand48(), ft_rand48()},
{ft_rand48(), ft_rand48(), ft_rand48()}, 60.0, 0, 0, 0};
new->radius = 10.0;
new->angle = new->radius * new->radius;
new->next = NULL;
}
else
ft_print_error("malloc error");
return (new);
}
t_vector ft_normal_disk(t_object *disk, int ret)
{
t_vector p;
if (ret == 1)
p = disk->normal;
else
p = ft_vector_kmult(-1.0, disk->normal);
return (p);
}
int ft_disk_compute(t_object *p, t_intersect *in)
{
t_ray r;
int ret;
r = in->ray;
r.start = ft_scale_vec3(r.start, p->scale, -1);
r.start = ft_rotate_vec3(r.start, p->rotate, -1);
r.start = ft_translate_vec3(r.start, p->translate, -1);
r.dir = ft_scale_vec3(r.dir, p->scale, -1);
r.dir = ft_rotate_vec3(r.dir, p->rotate, -1);
ret = ft_disk_intersect(p, &r, &in->t);
if (!ret)
return (0);
in->current = p;
in->p = ft_vector_sum(r.start, ft_vector_kmult(in->t, r.dir));
in->n = ft_normal_disk(p, ret);
in->p = ft_translate_vec3(in->p, p->translate, 0);
in->p = ft_rotate_vec3(in->p, p->rotate, 0);
in->p = ft_scale_vec3(in->p, p->scale, 0);
in->n = ft_rotate_vec3(in->n, p->rotate, 0);
in->n = ft_scale_vec3(in->n, p->scale, -1);
in->n = ft_vector_normalized(in->n);
return (1);
}
int ft_disk_intersect(t_object *d, t_ray *r, float *t)
{
float ddn;
t_vector v;
t_vector dist;
float t1;
ddn = ft_vector_dot(r->dir, d->normal);
if (ddn == 0.000001)
return (0);
dist = ft_vector_sub(d->pos, r->start);
t1 = (ft_vector_dot(dist, d->normal)) / ddn;
v = ft_vector_sum(r->start, ft_vector_kmult(t1, r->dir));
if (t1 < *t && t1 > 0.001 && (ft_vector_dot(v, v) <= d->angle))
{
*t = t1;
if (ddn > 0)
return (2);
return (1);
}
return (0);
}
|
C
|
/*
* SurgeScript
* A scripting language for games
* Copyright 2016-2023 Alexandre Martins <alemartf(at)gmail(dot)com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* runtime/vm_time.c
* SurgeScript Virtual Machine Time - this is used to count time
*/
#include "vm_time.h"
#include "../util/util.h"
/* VM time */
struct surgescript_vmtime_t {
uint64_t time; /* in ms */
uint64_t ticks_at_last_update;
bool is_paused;
};
/*
* surgescript_vmtime_create()
* Create a VM time object
*/
surgescript_vmtime_t* surgescript_vmtime_create()
{
surgescript_vmtime_t* vmtime = ssmalloc(sizeof *vmtime);
vmtime->time = 0;
vmtime->ticks_at_last_update = surgescript_util_gettickcount();
vmtime->is_paused = false;
return vmtime;
}
/*
* surgescript_vmtime_destroy()
* Destroy a VM time object
*/
surgescript_vmtime_t* surgescript_vmtime_destroy(surgescript_vmtime_t* vmtime)
{
ssfree(vmtime);
return NULL;
}
/*
* surgescript_vmtime_update()
* Update the VM time object
*/
void surgescript_vmtime_update(surgescript_vmtime_t* vmtime)
{
uint64_t now = surgescript_util_gettickcount();
uint64_t delta_time = now > vmtime->ticks_at_last_update ? now - vmtime->ticks_at_last_update : 0;
vmtime->time += vmtime->is_paused ? 0 : delta_time;
vmtime->ticks_at_last_update = now;
}
/*
* surgescript_vmtime_pause()
* Pause the VM time
*/
void surgescript_vmtime_pause(surgescript_vmtime_t* vmtime)
{
/* nothing to do */
if(vmtime->is_paused)
return;
/* pause the time */
vmtime->is_paused = true;
}
/*
* surgescript_vmtime_resume()
* Resume the VM time
*/
void surgescript_vmtime_resume(surgescript_vmtime_t* vmtime)
{
/* nothing to do */
if(!vmtime->is_paused)
return;
/* resume the time */
vmtime->ticks_at_last_update = surgescript_util_gettickcount();
vmtime->is_paused = false;
}
/*
* surgescript_vmtime_time()
* Get the time, in milliseconds, at the beginning of the current update cycle
*/
uint64_t surgescript_vmtime_time(const surgescript_vmtime_t* vmtime)
{
return vmtime->time;
}
/*
* surgescript_vmtime_is_paused()
* Is the VM time paused?
*/
bool surgescript_vmtime_is_paused(const surgescript_vmtime_t* vmtime)
{
return vmtime->is_paused;
}
|
C
|
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#pragma warning(disable : 4996)
typedef struct _RESULT { // ans struct
int ans_count;
char words[100];
}_RESULT;
char* eliminateSpecial(char* str);
void bubbleSort(char* string[], int size);
void swap(char* arr[], int front, int back);
int main()
{
FILE* fp = fopen("pride_and_prejudice.txt", "r");
char buffer[10000];
char* str[10000];
char* target_arr[1000];
char tempBuffer[10000];
char* tempArr[1000];
char* strArr[10000];
int diff_flag = 1;
int nullCount = 0;
int idx = 0;
int number = 0;
int res_idx = 0;
int count = 0;
struct _RESULT result[1000];
while (fgets(buffer, 10000, fp)) {
if (strcmp(buffer, "\n") == 0) {
continue;
}
for (int i = 0; i < 10000; i++) { // minimalize
if (buffer[i] >= 'A' && buffer[i] <= 'Z') {
buffer[i] = buffer[i] + 32;
}
}
char* ptr = strtok(buffer, " ");
while (ptr != NULL) {
char* afterProcess = eliminateSpecial(ptr);
if (strcmp(afterProcess, " ") == 0) {
ptr = strtok(NULL, " ");
continue;
}
str[idx] = strdup(afterProcess);
idx++;
ptr = strtok(NULL, " ");
}
}
for (int i = 0; i < idx; i++) {
int sliceFlg = 0;
strcpy(tempBuffer, str[i]);
for (int j = 0; j < strlen(tempBuffer); j++) {
if (tempBuffer[j] == '-') {
if (tempBuffer[j + 1] == '-') {
sliceFlg = 1;
break;
}
}
}
if (sliceFlg == 1) {
char* pptr = strtok(tempBuffer, "-");
while (pptr != NULL) {
char* string = eliminateSpecial(pptr);
if (strcmp(string, " ") == 0) {
pptr = strtok(NULL, "-");
continue;
}
tempArr[number] = strdup(string);
number++;
pptr = strtok(NULL, "-");
}
str[i] = NULL;
}
}
for (int i = 0; i < idx; i++) { // special character
int sliceFlg = 0;
if (str[i] == NULL) {
continue;
}
strcpy(tempBuffer, str[i]);
for (int j = 0; j < strlen(tempBuffer); j++) {
if (tempBuffer[j] != '\'' && tempBuffer[j] != '-') {
if (tempBuffer[j] >= 'a' && tempBuffer[j] <= 'z') {
continue;
}
else {
sliceFlg = 1;
tempBuffer[i] = ' ';
}
}
}
if (sliceFlg == 1) {
char* ppptr = strtok(tempBuffer, " ");
while (ppptr != NULL) {
char* string = eliminateSpecial(ppptr);
if (strcmp(string, " ") == 0) {
ppptr = strtok(NULL, " ");
continue;
}
tempArr[number] = strdup(string);
number++;
ppptr = strtok(NULL, " ");
}
str[i] = NULL;
}
}
int temp_idx = 0;
int str_idx = 0;
while (temp_idx < number) {
str[idx] = tempArr[temp_idx];
idx++;
temp_idx++;
}
for (int i = 0; i < idx; i++) {
if (str[i] != NULL) {
strArr[str_idx] = str[i];
str_idx++;
}
}
bubbleSort(strArr, str_idx);
for (int i = 0; i < str_idx; i++) {
if (strlen(strArr[i]) >= 7) {
for (int j = 0; j < i; j++) {
if (strcmp(strArr[i], strArr[j]) == 0) {
diff_flag = 0;
break;
}
diff_flag = 1;
}
if (diff_flag == 0) {
continue;
}
strcpy(result[res_idx].words, strArr[i]);
for (int j = i; j < str_idx; j++) {
if (strcmp(strArr[i], strArr[j]) == 0) {
count++;
}
}
result[res_idx].ans_count = count;
res_idx++;
}
count = 0;
diff_flag = 1;
}
for (int i = 0; i < res_idx; i += 10) {
printf("%s %d\n", result[i].words, result[i].ans_count);
}
for (int i = 0; i < idx + number; i++) {
free(str[i]);
}
fclose(fp);
}
char* eliminateSpecial(char* str) {
char* afterStr = NULL;
char tempBuf[10000];
strcpy(tempBuf, str);
for (int i = 0; i <= strlen(str); i++) {
if (tempBuf[i] >= 'a' && tempBuf[i] <= 'z') { // 배열의 처음에서부터 진행하여 첫 알파벳을 만날 시 정지
while (1) { // tempBuf[0]이 공백이 아닐때까지 앞으로 끌어당기기
if (tempBuf[0] != ' ') {
break;
}
else {
for (int j = 1; j <= strlen(str); j++) {
tempBuf[j - 1] = tempBuf[j];
}
}
}
break;
}
else {
tempBuf[i] = ' '; // 유니코드 공백치환
}
}
for (int i = strlen(str) - 1; i >= 0; i--) {
if (tempBuf[i] >= 'a' && tempBuf[i] <= 'z') { // 배열의 끝에서부터 진행하여 첫 알파벳을 만날 때 까지 널 문자로 치환
break;
}
else {
tempBuf[i] = '\0';
}
}
afterStr = strdup(tempBuf);
return afterStr;
}
void bubbleSort(char* string[], int size) {
for (int i = 0; i < size - 1; i++) {
for (int j = 0; j < size - 1; j++) {
if (strcmp(string[j], string[j + 1]) > 0) {
swap(string, j, j + 1);
}
}
}
}
void swap(char* arr[], int front, int back) {
char* temp = arr[front];
arr[front] = arr[back];
arr[back] = temp;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int sumFibs(max)
{
int fibs[512] = {0};
fibs[0] = fibs[1] = 1;
int x=1;
do {
x++;
fibs[x] = fibs[x-1] + fibs[x-2]; //add prev 2
} while (fibs[x] <= max);
int tot=0;
for(int y=x-1; y>=0; y--)
tot += (fibs[y] & 1) ? fibs[y] : 0;
return tot;
}
int main(int argc, char *argv[])
{
if(argc != 2)
{
printf("Need 2 args\n");
return 0;
}
int numMax = atoi(argv[1]);
int tot = sumFibs(numMax);
printf("%i\n", tot);
return tot;
}
/* JS code:
function sumFibs(numMax) {
var fibs = [1,1];
var x=1;
do {
x++;
fibs.push(fibs[x-1] + fibs[x-2]);
} while (fibs[x] <= numMax);
var tot=0;
for(y=x-1; y>=0; y--)
tot += (fibs[y] & 1) ? fibs[y] : 0;
return tot;
}
sumFibs(4);
*/
|
C
|
#include <stdio.h>
void main (void)
{
int num1, num2,result;
while(1){
printf("please enter first number ");
scanf("%d",&num1);
printf("please enter second number ");
scanf("%d",&num2);
result = num1 + num2;
printf("the result is %d \n \n",result);
}
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include "common.h"
#include "../qrinput.h"
#include "../qrencode_inner.h"
#include "../split.h"
#include "decoder.h"
int encodeAndCheckBStream(int mqr, int version, QRecLevel level, QRencodeMode mode, char *data, char *correct)
{
QRinput *input;
BitStream *bstream;
int ret;
if(mqr) {
input = QRinput_newMQR(version, level);
} else {
input = QRinput_new2(version, level);
}
QRinput_append(input, mode, strlen(data), (unsigned char *)data);
bstream = QRinput_getBitStream(input);
ret = cmpBin(correct, bstream);
if(ret) {
printf("result : ");
printBstream(bstream);
printf("correct: %s\n", correct);
}
QRinput_free(input);
BitStream_free(bstream);
return ret;
}
int mergeAndCheckBStream(int mqr, QRencodeMode mode, char *data, char *correct)
{
QRinput *input;
BitStream *bstream;
int ret;
if(mqr) {
input = QRinput_newMQR(1, QR_ECLEVEL_L);
} else {
input = QRinput_new();
}
QRinput_append(input, mode, strlen(data), (unsigned char *)data);
bstream = QRinput_mergeBitStream(input);
ret = cmpBin(correct, bstream);
QRinput_free(input);
BitStream_free(bstream);
return ret;
}
void test_encodeKanji(void)
{
char str[5]= {0x93, 0x5f,0xe4, 0xaa, 0x00};
char *correct = "10000000001001101100111111101010101010";
testStart("Encoding kanji stream.");
testEnd(mergeAndCheckBStream(0, QR_MODE_KANJI, str, correct));
}
void test_encode8(void)
{
char str[] = "AC-42";
char correct[] = "0100000001010100000101000011001011010011010000110010";
testStart("Encoding 8bit stream.");
testEnd(mergeAndCheckBStream(0, QR_MODE_8, str, correct));
}
void test_encode8_versionup(void)
{
QRinput *stream;
BitStream *bstream;
char *str;
int version;
testStart("Encoding 8bit stream. (auto-version up test)");
str = (char *)malloc(2900);
memset(str, 0xff, 2900);
stream = QRinput_new();
QRinput_append(stream, QR_MODE_8, 2900, (unsigned char *)str);
bstream = QRinput_mergeBitStream(stream);
version = QRinput_getVersion(stream);
assert_equal(version, 40, "Version is %d (40 expected).\n", version);
testFinish();
QRinput_free(stream);
BitStream_free(bstream);
free(str);
}
void test_encodeAn(void)
{
char *str = "AC-42";
char correct[] = "00100000001010011100111011100111001000010";
testStart("Encoding alphabet-numeric stream.");
testEnd(mergeAndCheckBStream(0, QR_MODE_AN, str, correct));
}
void test_encodeAn2(void)
{
QRinput *stream;
char str[] = "!,;$%";
int ret;
testStart("Encoding INVALID alphabet-numeric stream.");
stream = QRinput_new();
ret = QRinput_append(stream, QR_MODE_AN, 5, (unsigned char *)str);
testEnd(!ret);
QRinput_free(stream);
}
void test_encodeNumeric(void)
{
char *str = "01234567";
char correct[] = "00010000001000000000110001010110011000011";
testStart("Encoding numeric stream. (8 digits)");
testEnd(mergeAndCheckBStream(0, QR_MODE_NUM, str, correct));
}
void test_encodeNumeric_versionup(void)
{
QRinput *stream;
BitStream *bstream;
char *str;
int version;
testStart("Encoding numeric stream. (auto-version up test)");
str = (char *)malloc(1050);
memset(str, '1', 1050);
stream = QRinput_new2(0, QR_ECLEVEL_L);
QRinput_append(stream, QR_MODE_NUM, 1050, (unsigned char *)str);
bstream = QRinput_mergeBitStream(stream);
version = QRinput_getVersion(stream);
assert_equal(version, 14, "Version is %d (14 expected).", version);
testFinish();
QRinput_free(stream);
BitStream_free(bstream);
free(str);
}
void test_encodeNumericPadded(void)
{
char *str = "01234567";
char *correct;
char *correctHead = "000100000010000000001100010101100110000110000000";
int i, ret;
testStart("Encoding numeric stream. (8 digits)(padded)");
correct = (char *)malloc(19 * 8 + 1);
correct[0] = '\0';
strcat(correct, correctHead);
for(i=0; i<13; i++) {
strcat(correct, (i&1)?"00010001":"11101100");
}
ret = encodeAndCheckBStream(0, 0, QR_ECLEVEL_L, QR_MODE_NUM, str, correct);
testEnd(ret);
free(correct);
}
void test_encodeNumericPadded2(void)
{
char *str = "0123456";
char *correct;
char *correctHead = "000100000001110000001100010101100101100000000000";
int i, ret;
testStart("Encoding numeric stream. (7 digits)(padded)");
correct = (char *)malloc(19 * 8 + 1);
correct[0] = '\0';
strcat(correct, correctHead);
for(i=0; i<13; i++) {
strcat(correct, (i&1)?"00010001":"11101100");
}
ret = encodeAndCheckBStream(0, 0, QR_ECLEVEL_L, QR_MODE_NUM, str, correct);
testEnd(ret);
free(correct);
}
void test_padding(void)
{
QRinput *input;
BitStream *bstream;
int i, size;
char data[] = "0123456789ABCDeFG";
unsigned char c;
testStart("Padding bit check. (less than 5 bits)");
input = QRinput_new2(1, QR_ECLEVEL_L);
QRinput_append(input, QR_MODE_8, 17, (unsigned char *)data);
bstream = QRinput_getBitStream(input);
size = BitStream_size(bstream);
assert_equal(size, 152, "# of bit is incorrect (%d != 152).\n", size);
c = 0;
for(i=0; i<4; i++) {
c += bstream->data[size - i - 1];
}
assert_zero(c, "Padding bits are not zero.");
testFinish();
QRinput_free(input);
BitStream_free(bstream);
}
void test_padding2(void)
{
QRinput *input;
BitStream *bstream;
int i, size, ret;
char data[] = "0123456789ABCDeF";
char correct[153];
unsigned char c;
testStart("Padding bit check. (1 or 2 padding bytes)");
/* 16 byte data (4 bit terminator and 1 byte padding) */
memset(correct, 0, 153);
memcpy(correct, "010000010000", 12);
for(size=0; size<16; size++) {
c = 0x80;
for(i=0; i<8; i++) {
correct[size * 8 + i + 12] = (data[size]&c)?'1':'0';
c = c >> 1;
}
}
memcpy(correct + 140, "000011101100", 12);
input = QRinput_new2(1, QR_ECLEVEL_L);
QRinput_append(input, QR_MODE_8, 16, (unsigned char *)data);
bstream = QRinput_getBitStream(input);
size = BitStream_size(bstream);
assert_equal(size, 152, "16byte: # of bit is incorrect (%d != 152).\n", size);
ret = ncmpBin(correct, bstream, 152);
assert_zero(ret, "Padding bits incorrect.\n");
printBstream(bstream);
QRinput_free(input);
BitStream_free(bstream);
/* 15 byte data (4 bit terminator and 2 byte paddings) */
memcpy(correct, "010000001111", 12);
memcpy(correct + 132, "00001110110000010001", 20);
input = QRinput_new2(1, QR_ECLEVEL_L);
QRinput_append(input, QR_MODE_8, 15, (unsigned char *)data);
bstream = QRinput_getBitStream(input);
size = BitStream_size(bstream);
assert_equal(size, 152, "15byte: # of bit is incorrect (%d != 152).\n", size);
ret = ncmpBin(correct, bstream, 152);
assert_zero(ret, "Padding bits incorrect.\n");
printBstream(bstream);
testFinish();
QRinput_free(input);
BitStream_free(bstream);
}
void test_encodeNumeric2(void)
{
char *str = "0123456789012345";
char *correct = "00010000010000000000110001010110011010100110111000010100111010100101";
testStart("Encoding numeric stream. (16 digits)");
testEnd(mergeAndCheckBStream(0, QR_MODE_NUM, str, correct));
}
void test_encodeNumeric3(void)
{
char *str = "0123456";
char *correct = "0001 0000000111 0000001100 0101011001 0110";
testStart("Encoding numeric stream. (7 digits)");
testEnd(mergeAndCheckBStream(0, QR_MODE_NUM, str, correct));
}
void test_encodeTooLong(void)
{
QRinput *stream;
unsigned char *data;
BitStream *bstream;
data = (unsigned char *)malloc(4297);
memset(data, 'A', 4297);
testStart("Encoding long string. (4297 bytes of alphanumeric)");
stream = QRinput_new();
QRinput_append(stream, QR_MODE_AN, 4297, data);
bstream = QRinput_mergeBitStream(stream);
testEndExp(bstream == NULL);
QRinput_free(stream);
if(bstream != NULL) {
BitStream_free(bstream);
}
free(data);
}
void test_encodeAnNum(void)
{
QRinput *input;
BitStream *bstream;
testStart("Bit length check of alpha-numeric stream. (11 + 12)");
input = QRinput_new();
QRinput_append(input, QR_MODE_AN, 11, (unsigned char *)"ABCDEFGHIJK");
QRinput_append(input, QR_MODE_NUM, 12, (unsigned char *)"123456789012");
bstream = QRinput_mergeBitStream(input);
testEndExp(BitStream_size(bstream) == 128);
QRinput_free(input);
BitStream_free(bstream);
testStart("Bit length check of alphabet stream. (23)");
input = QRinput_new();
QRinput_append(input, QR_MODE_AN, 23, (unsigned char *)"ABCDEFGHIJK123456789012");
bstream = QRinput_mergeBitStream(input);
testEndExp(BitStream_size(bstream) == 140);
QRinput_free(input);
BitStream_free(bstream);
}
void test_struct_listop(void)
{
QRinput_Struct *s;
QRinput *inputs[5];
QRinput_InputList *l;
int i, ret;
testStart("QRinput_Struct list operation test.");
s = QRinput_Struct_new();
QRinput_Struct_setParity(s, 10);
assert_nonnull(s, "QRinput_Struct_new() failed.");
assert_equal(s->parity, 10, "QRinput_Struct_setParity() failed.");
for(i=0; i<5; i++) {
inputs[i] = QRinput_new();
QRinput_append(inputs[i], QR_MODE_AN, 5, (unsigned char *)"ABCDE");
ret = QRinput_Struct_appendInput(s, inputs[i]);
}
assert_equal(ret, 5, "QRinput_Struct_appendInput() returns wrong num?");
assert_equal(s->size, 5, "QRiput_Struct.size counts wrong number.");
l = s->head;
i = 0;
while(l != NULL) {
assert_equal(l->input, inputs[i], "QRinput_Struct input list order would be wrong?");
l = l->next;
i++;
}
QRinput_Struct_free(s);
testFinish();
}
void test_insertStructuredAppendHeader(void)
{
QRinput *stream;
char correct[] = "0011000011111010010101000000000101000001";
BitStream *bstream;
int ret;
testStart("Insert a structured-append header");
stream = QRinput_new();
QRinput_append(stream, QR_MODE_8, 1, (unsigned char *)"A");
ret = QRinput_insertStructuredAppendHeader(stream, 16, 1, 0xa5);
assert_zero(ret, "QRinput_insertStructuredAppendHeader() returns nonzero.\n");
bstream = QRinput_mergeBitStream(stream);
assert_nonnull(bstream->data, "Bstream->data is null.");
assert_zero(cmpBin(correct, bstream), "bitstream is wrong.");
testFinish();
QRinput_free(stream);
BitStream_free(bstream);
}
void test_insertStructuredAppendHeader_error(void)
{
QRinput *stream;
int ret;
testStart("Insert a structured-append header (errors expected)");
stream = QRinput_new();
QRinput_append(stream, QR_MODE_8, 1, (unsigned char *)"A");
ret = QRinput_insertStructuredAppendHeader(stream, 17, 1, 0xa5);
assert_equal(-1, ret, "QRinput_insertStructuredAppendHeader() returns 0.");
assert_equal(EINVAL, errno, "errno is not set correctly (%d returned).", errno);
ret = QRinput_insertStructuredAppendHeader(stream, 16, 17, 0xa5);
assert_equal(-1, ret, "QRinput_insertStructuredAppendHeader() returns 0.");
assert_equal(EINVAL, errno, "errno is not set correctly (%d returned).", errno);
ret = QRinput_insertStructuredAppendHeader(stream, 16, 0, 0xa5);
assert_equal(-1, ret, "QRinput_insertStructuredAppendHeader() returns 0.");
assert_equal(EINVAL, errno, "errno is not set correctly (%d returned).", errno);
testFinish();
QRinput_free(stream);
}
void test_struct_insertStructuredAppendHeaders(void)
{
QRinput *input;
QRinput_Struct *s;
QRinput_InputList *p;
int i;
testStart("Insert structured-append headers to a QRinput_Struct.");
s = QRinput_Struct_new();
for(i=0; i<10; i++) {
input = QRinput_new();
QRinput_append(input, QR_MODE_8, 1, (unsigned char *)"A");
QRinput_Struct_appendInput(s, input);
}
QRinput_Struct_insertStructuredAppendHeaders(s);
p = s->head;
i = 1;
while(p != NULL) {
assert_equal(p->input->head->mode, QR_MODE_STRUCTURE, "a structured-append header is not inserted.");
assert_equal(p->input->head->data[0], 10, "size of the structured-header is wrong: #%d, %d should be %d\n", i, p->input->head->data[0], 10);
assert_equal(p->input->head->data[1], i, "index of the structured-header is wrong: #%d, %d should be %d\n", i, p->input->head->data[1], i);
assert_equal(p->input->head->data[2], 0, "parity of the structured-header is wrong: #%d\n", i);
p = p->next;
i++;
}
testFinish();
QRinput_Struct_free(s);
}
static int check_lengthOfCode(QRencodeMode mode, char *data, int size, int version)
{
QRinput *input;
BitStream *b;
int bits;
int bytes;
input = QRinput_new();
QRinput_setVersion(input, version);
QRinput_append(input, mode, size, (unsigned char *)data);
b = QRinput_mergeBitStream(input);
bits = BitStream_size(b);
bytes = QRinput_lengthOfCode(mode, version, bits);
QRinput_free(input);
BitStream_free(b);
return bytes;
}
void test_lengthOfCode_num(void)
{
int i, bytes;
char *data;
data = (char *)malloc(8000);
for(i=0; i<8000; i++) {
data[i] = '0' + i % 10;
}
testStart("Checking length of code (numeric)");
for(i=1; i<=9; i++) {
bytes = check_lengthOfCode(QR_MODE_NUM, data, i, 1);
assert_equal(i, bytes, "lengthOfCode failed. (QR_MODE_NUM, version:1, size:%d)\n", i);
}
for(i=1023; i<=1025; i++) {
bytes = check_lengthOfCode(QR_MODE_NUM, data, i, 1);
assert_equal(1023, bytes, "lengthOfCode failed. (QR_MODE_NUM, version:1, size:%d)\n", i);
}
testFinish();
free(data);
}
void test_lengthOfCode_kanji(void)
{
int i, bytes;
unsigned char str[4]= {0x93, 0x5f,0xe4, 0xaa};
testStart("Checking length of code (kanji)");
for(i=2; i<=4; i+=2) {
bytes = check_lengthOfCode(QR_MODE_KANJI, (char *)str, i, 1);
assert_equal(i, bytes, "lengthOfCode failed. (QR_MODE_KANJI, version:1, size:%d)\n", i);
}
testFinish();
}
void test_struct_split_example(void)
{
QRinput *input;
QRinput_Struct *s;
QRinput_InputList *e;
QRinput_List *l;
const char *str[4] = { "an example ", "of four Str", "uctured Appe", "nd symbols,"};
int i;
BitStream *bstream;
testStart("Testing the example of structured-append symbols");
s = QRinput_Struct_new();
for(i=0; i<4; i++) {
input = QRinput_new2(1, QR_ECLEVEL_M);
QRinput_append(input, QR_MODE_8, strlen(str[i]), (unsigned char *)str[i]);
QRinput_Struct_appendInput(s, input);
}
QRinput_Struct_insertStructuredAppendHeaders(s);
e = s->head;
i = 0;
while(e != NULL) {
bstream = QRinput_mergeBitStream(e->input);
BitStream_free(bstream);
l = e->input->head->next;
assert_equal(l->mode, QR_MODE_8, "#%d: wrong mode (%d).\n", i, l->mode);
assert_equal(e->input->level, QR_ECLEVEL_M, "#%d: wrong level (%d).\n", i, e->input->level);
e = e->next;
i++;
}
testFinish();
QRinput_Struct_free(s);
}
void test_struct_split_tooLarge(void)
{
QRinput *input;
QRinput_Struct *s;
char *str;
int errsv;
testStart("Testing structured-append symbols. (too large data)");
str = (char *)malloc(128);
memset(str, 'a', 128);
input = QRinput_new2(1, QR_ECLEVEL_H);
QRinput_append(input, QR_MODE_8, 128, (unsigned char *)str);
s = QRinput_splitQRinputToStruct(input);
errsv = errno;
assert_null(s, "returns non-null.");
assert_equal(errsv, ERANGE, "did not return ERANGE.");
testFinish();
if(s != NULL) QRinput_Struct_free(s);
QRinput_free(input);
free(str);
}
void test_struct_split_invalidVersion(void)
{
QRinput *input;
QRinput_Struct *s;
char *str;
int errsv;
testStart("Testing structured-append symbols. (invalid version 0)");
str = (char *)malloc(128);
memset(str, 'a', 128);
input = QRinput_new2(0, QR_ECLEVEL_H);
QRinput_append(input, QR_MODE_8, 128, (unsigned char *)str);
s = QRinput_splitQRinputToStruct(input);
errsv = errno;
assert_null(s, "returns non-null.");
assert_equal(errsv, ERANGE, "did not return ERANGE.");
testFinish();
if(s != NULL) QRinput_Struct_free(s);
QRinput_free(input);
free(str);
}
void test_struct_singlestructure(void)
{
QRinput *input;
QRinput_Struct *s;
char *str = "TEST";
testStart("Testing structured-append symbols. (single structure)");
input = QRinput_new2(10, QR_ECLEVEL_H);
QRinput_append(input, QR_MODE_AN, strlen(str), (unsigned char *)str);
s = QRinput_splitQRinputToStruct(input);
assert_nonnull(s, "must return a code.");
assert_equal(s->size, 1, "size must be 1, but %d returned.", s->size);
if(s->size != 1) {
printQRinputStruct(s);
}
testFinish();
if(s != NULL) QRinput_Struct_free(s);
QRinput_free(input);
}
void test_splitentry(void)
{
QRinput *i1, *i2;
QRinput_List *e;
const char *str = "abcdefghij";
int size1, size2, i;
unsigned char *d1, *d2;
testStart("Testing QRinput_splitEntry. (next == NULL)");
i1 = QRinput_new();
QRinput_append(i1, QR_MODE_8, strlen(str), (unsigned char *)str);
i2 = QRinput_dup(i1);
e = i2->head;
e = i2->head;
QRinput_splitEntry(e, 4);
size1 = size2 = 0;
e = i1->head;
while(e != NULL) {
size1 += e->size;
e = e->next;
}
e = i2->head;
while(e != NULL) {
size2 += e->size;
e = e->next;
}
d1 = (unsigned char *)malloc(size1);
e = i1->head;
i = 0;
while(e != NULL) {
memcpy(&d1[i], e->data, e->size);
i += e->size;
e = e->next;
}
d2 = (unsigned char *)malloc(size2);
e = i2->head;
i = 0;
while(e != NULL) {
memcpy(&d2[i], e->data, e->size);
i += e->size;
e = e->next;
}
assert_equal(size1, size2, "sizes are different. (%d:%d)\n", size1, size2);
assert_equal(i2->head->size, 4, "split failed (first half)");
assert_equal(i2->head->next->size, 6, "split failed(second half)");
assert_zero(memcmp(d1, d2, size1), "strings are different.");
QRinput_free(i1);
QRinput_free(i2);
free(d1);
free(d2);
testFinish();
}
void test_splitentry2(void)
{
QRinput *i1, *i2;
QRinput_List *e;
const char *str = "abcdefghij";
int size1, size2, i;
unsigned char *d1, *d2;
testStart("Testing QRinput_splitEntry. (next != NULL)");
i1 = QRinput_new();
QRinput_append(i1, QR_MODE_8, strlen(str), (unsigned char *)str);
QRinput_append(i1, QR_MODE_8, strlen(str), (unsigned char *)str);
i2 = QRinput_dup(i1);
e = i2->head;
e = i2->head;
QRinput_splitEntry(e, 4);
size1 = size2 = 0;
e = i1->head;
while(e != NULL) {
size1 += e->size;
e = e->next;
}
e = i2->head;
while(e != NULL) {
size2 += e->size;
e = e->next;
}
d1 = (unsigned char *)malloc(size1);
e = i1->head;
i = 0;
while(e != NULL) {
memcpy(&d1[i], e->data, e->size);
i += e->size;
e = e->next;
}
d2 = (unsigned char *)malloc(size2);
e = i2->head;
i = 0;
while(e != NULL) {
memcpy(&d2[i], e->data, e->size);
i += e->size;
e = e->next;
}
assert_equal(size1, size2, "sizes are different. (%d:%d)\n", size1, size2);
assert_equal(i2->head->size, 4, "split failed (first half)");
assert_equal(i2->head->next->size, 6, "split failed(second half)");
assert_zero(memcmp(d1, d2, size1), "strings are different.");
QRinput_free(i1);
QRinput_free(i2);
free(d1);
free(d2);
testFinish();
}
void test_splitentry3(void)
{
QRinput *input;
QRinput_Struct *s;
QRinput_List *e00, *e01, *e10, *e11;
QRinput_InputList *list;
const char *str = "abcdefghijklmno";
testStart("Testing QRinput_splitEntry. (does not split an entry)");
/* version 1 symbol contains 152 bit (19 byte) data.
* 20 bits for a structured-append header, so 132 bits can be used.
* 15 bytes of 8-bit data is suitable for the symbol.
* (mode(4) + length(8) + data(120) == 132.)
*/
input = QRinput_new2(1, QR_ECLEVEL_L);
QRinput_append(input, QR_MODE_8, strlen(str), (unsigned char *)str);
QRinput_append(input, QR_MODE_8, strlen(str), (unsigned char *)str);
s = QRinput_splitQRinputToStruct(input);
list = s->head;
e00 = list->input->head;
e01 = e00->next;
list = list->next;
e10 = list->input->head;
e11 = e10->next;
assert_equal(e00->mode, QR_MODE_STRUCTURE, "Structure header is missing?");
assert_equal(e01->mode, QR_MODE_8, "no data?!");
assert_null(e01->next, "Input list is not terminated!\n");
assert_equal(e10->mode, QR_MODE_STRUCTURE, "Structure header is missing?");
assert_equal(e11->mode, QR_MODE_8, "no data?!");
assert_null(e11->next, "Input list is not terminated!\n");
QRinput_free(input);
QRinput_Struct_free(s);
testFinish();
}
void test_parity(void)
{
QRinput *input;
QRinput_Struct *s;
const char *text = "an example of four Structured Append symbols,";
const char *str[4] = {
"an example ",
"of four Str",
"uctured Appe",
"nd symbols,"};
unsigned char p1, p2;
int i, len;
testStart("Testing parity calc.");
s = QRinput_Struct_new();
for(i=0; i<4; i++) {
input = QRinput_new2(1, QR_ECLEVEL_M);
QRinput_append(input, QR_MODE_8, strlen(str[i]), (unsigned char *)str[i]);
QRinput_Struct_appendInput(s, input);
}
QRinput_Struct_insertStructuredAppendHeaders(s);
p1 = s->parity;
p2 = 0;
len = strlen(text);
for(i=0; i<len; i++) {
p2 ^= text[i];
}
assert_equal(p1, p2, "Parity numbers didn't match. (%02x should be %02x).\n", p1, p2);
testFinish();
QRinput_Struct_free(s);
}
void test_parity2(void)
{
QRinput *input;
QRinput_Struct *s;
const char *text = "an example of four Structured Append symbols,";
unsigned char p1, p2;
int i, len;
testStart("Testing parity calc.(split)");
input = QRinput_new2(1, QR_ECLEVEL_L);
QRinput_append(input, QR_MODE_8, strlen(text), (unsigned char *)text);
s = QRinput_splitQRinputToStruct(input);
p1 = s->parity;
p2 = 0;
len = strlen(text);
for(i=0; i<len; i++) {
p2 ^= text[i];
}
assert_equal(p1, p2, "Parity numbers didn't match. (%02x should be %02x).\n", p1, p2);
testFinish();
QRinput_free(input);
QRinput_Struct_free(s);
}
void test_null_free(void)
{
testStart("Testing free NULL pointers");
assert_nothing(QRinput_free(NULL), "Check QRinput_free(NULL).\n");
assert_nothing(QRinput_Struct_free(NULL), "Check QRinput_Struct_free(NULL).\n");
testFinish();
}
void test_mqr_new(void)
{
QRinput *input;
testStart("Testing QRinput_newMQR().");
input = QRinput_newMQR(0, QR_ECLEVEL_L);
assert_null(input, "Version 0 passed.\n");
QRinput_free(input);
input = QRinput_newMQR(5, QR_ECLEVEL_L);
assert_null(input, "Version 5 passed.\n");
QRinput_free(input);
input = QRinput_newMQR(1, QR_ECLEVEL_M);
assert_null(input, "Invalid ECLEVEL passed.\n");
QRinput_free(input);
input = QRinput_newMQR(1, QR_ECLEVEL_L);
assert_equal(input->version, 1, "QRinput.version was not as expected.\n");
assert_equal(input->level, QR_ECLEVEL_L, "QRinput.version was not as expected.\n");
QRinput_free(input);
testFinish();
}
void test_mqr_setversion(void)
{
QRinput *input;
int ret;
testStart("Testing QRinput_setVersion() for MQR.");
input = QRinput_newMQR(1, QR_ECLEVEL_L);
ret = QRinput_setVersion(input, 2);
assert_exp((ret < 0), "QRinput_setVersion should be denied.\n");
QRinput_free(input);
testFinish();
}
void test_mqr_setlevel(void)
{
QRinput *input;
int ret;
testStart("Testing QRinput_setErrorCorrectionLevel() for MQR.");
input = QRinput_newMQR(1, QR_ECLEVEL_L);
ret = QRinput_setErrorCorrectionLevel(input, QR_ECLEVEL_M);
assert_exp((ret < 0), "QRinput_setErrorCorrectionLevel should be denied.\n");
QRinput_free(input);
testFinish();
}
void test_paddingMQR(void)
{
char *dataM1[] = {"65", "513", "5139", "51365"};
char *correctM1[] = {"01010000010000000000",
"01110000000010000000",
"10010000000011001000",
"10110000000011000001"};
char *dataM2[] = {"513513", "51351365"};
char *correctM2[] = {"0 0110 1000000001 1000000001 0000000",
"0 1000 1000000001 1000000001 1000001"};
int i, ret;
testStart("Padding bit check of MQR. (only 0 padding)");
for(i=0; i<4; i++) {
ret = encodeAndCheckBStream(1, 1, QR_ECLEVEL_L, QR_MODE_NUM, dataM1[i], correctM1[i]);
assert_zero(ret, "Number %s incorrectly encoded.\n", dataM1[i]);
}
for(i=0; i<2; i++) {
ret = encodeAndCheckBStream(1, 2, QR_ECLEVEL_M, QR_MODE_NUM, dataM2[i], correctM2[i]);
assert_zero(ret, "Number %s incorrectly encoded.\n", dataM2[i]);
}
testFinish();
}
void test_padding2MQR(void)
{
char *data[] = {"9", "513513", "513", "513"};
int ver[] = {1, 2, 2, 3};
char *correct[] = {"00110010 00000000 0000",
"0 0110 1000000001 1000000001 0000000 11101100",
"0 0011 1000000001 000000000 11101100 00010001",
"00 00011 1000000001 0000000 11101100 00010001 11101100 00010001 11101100 00010001 11101100 0000"
};
int i, ret;
testStart("Padding bit check. (1 or 2 padding bytes)");
for(i=0; i<4; i++) {
ret = encodeAndCheckBStream(1, ver[i], QR_ECLEVEL_L, QR_MODE_NUM, data[i], correct[i]);
assert_zero(ret, "Number %s incorrectly encoded.\n", data[i]);
}
testFinish();
}
void test_textMQR(void)
{
int version = 3;
QRecLevel level = QR_ECLEVEL_M;
char *str = "MICROQR";
char *correct = {"01 0111 01111110000 01000110111 10001010010 011011 0000000 0000 11101100 0000"};
int ret;
testStart("Text encoding (Micro QR)");
ret = encodeAndCheckBStream(1, version, level, QR_MODE_AN, str, correct);
assert_zero(ret, "AlphaNumeric string '%s' incorrectly encoded.\n", str);
testFinish();
}
void test_ECIinvalid(void)
{
QRinput *stream;
int ret;
testStart("Appending invalid ECI header");
stream = QRinput_new();
ret = QRinput_appendECIheader(stream, 999999);
assert_zero(ret, "Valid ECI header rejected.");
ret = QRinput_appendECIheader(stream, 1000000);
assert_nonzero(ret, "Invalid ECI header accepted.");
QRinput_free(stream);
testFinish();
}
void test_encodeECI(void)
{
QRinput *input;
BitStream *bstream;
unsigned char str[] = {0xa1, 0xa2, 0xa3, 0xa4, 0xa5};
char *correct = "0111 00001001 0100 00000101 10100001 10100010 10100011 10100100 10100101";
int ret;
testStart("Encoding characters with ECI header.");
input = QRinput_new();
ret = QRinput_appendECIheader(input, 9);
assert_zero(ret, "Valid ECI header rejected.\n");
ret = QRinput_append(input, QR_MODE_8, 5, str);
assert_zero(ret, "Failed to append characters.\n");
bstream = QRinput_mergeBitStream(input);
assert_nonnull(bstream, "Failed to merge.\n");
if(bstream != NULL) {
ret = ncmpBin(correct, bstream, 64);
assert_zero(ret, "Encodation of ECI header was invalid.\n");
BitStream_free(bstream);
}
QRinput_free(input);
testFinish();
}
int main(void)
{
test_encodeNumeric();
test_encodeNumeric2();
test_encodeNumeric3();
test_encodeNumeric_versionup();
test_encode8();
test_encode8_versionup();
test_encodeTooLong();
test_encodeAn();
test_encodeAn2();
test_encodeKanji();
test_encodeNumericPadded();
test_encodeNumericPadded2();
test_encodeAnNum();
test_padding();
test_padding2();
test_struct_listop();
test_insertStructuredAppendHeader();
test_insertStructuredAppendHeader_error();
test_struct_insertStructuredAppendHeaders();
test_lengthOfCode_num();
test_splitentry();
test_splitentry2();
test_splitentry3();
test_struct_split_example();
test_struct_split_tooLarge();
test_struct_split_invalidVersion();
test_struct_singlestructure();
test_parity();
test_parity2();
test_null_free();
test_mqr_new();
test_mqr_setversion();
test_mqr_setlevel();
test_paddingMQR();
test_padding2MQR();
test_textMQR();
test_ECIinvalid();
test_encodeECI();
report();
return 0;
}
|
C
|
#include <stdio.h>
#define x 100
#define y 200
int main(void) {
printf("常數 x = %d, y = %d \n", x, y);
printf("Pree any key to continue... \n");
getchar();
return 0;
}
|
C
|
//**********************************************************************
// Date: 01/26/2018
// Program to calculate the time for a System call and context switch
//
//**********************************************************************
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <sys/time.h>
#include <unistd.h>
#include <sys/types.h>
#include <pthread.h>
#include <sched.h>
#include <time.h>
//Return system time
double calctime()
{
double timeinsec = 0.0;
struct timeval ctime;
gettimeofday(&ctime, (struct timezone *)0);
timeinsec = (double)(ctime.tv_sec + ctime.tv_usec * 1.0e-3);
return(timeinsec);
}
int main(int argc, const char * argv[])
{
double beginning ;
double end;
//Set thread to one processor
cpu_set_t affin;
CPU_ZERO(&affin);
unsigned int length = sizeof(affin);
CPU_SET(0, &affin);
double sysStart, sysStop, sysCallDur, dur, funcCallDur;
int i,p;
long k;
int n;
printf("Start Running \n");
long itr_a = 1000000;
//calculate system call cost
sysStart = calctime();
for (k = 0; k < itr_a; k++)
{
i = getpid();
}
//record the time in which the system call operations ends
sysStop = calctime();
//system call time
dur = sysStop - sysStart;
//estimated system call time
sysCallDur = (sysStop - sysStart) / itr_a;
printf("Average system call time is %0.10f\n", sysCallDur);
return(0);
}
|
C
|
/******************************************************************************
calcura area e perimetro de um hexagono
*******************************************************************************/
#include<stdio.h>
#include<math.h>
void calc_hexa(float l, float *area, float *per) {
*per = 6 * l;
*area = (3 * pow(l,2) * sqrt(3))/2;
}
int main(){
float lado, area, perimetro;
printf("\n\nDigite o lado do hexagono:");
scanf("%f", &lado);
while (lado > 0) {
calc_hexa(lado, &area, &perimetro);
printf("\n\na area e o perímetro do hexagono regular de lado %f e igual a %f e %f", lado, area, perimetro);
printf("\n\nDigite o lado do hexagono:");
scanf("%f", &lado);
}
}
|
C
|
#include<stdio.h>
#include<conio.h>
main()
{
int day;
printf("Enter the day:");
Scanf("%d",&day);
switch(day)
{
case Monday:
printf("True");
break;
case tuesday:
printf("True");
break;
case Wednesday:
printf("True");
break;
case Thursday:
printf("True");
break;
case Friday:
printf("True");
break;
case Saturday:
printf("False");
break;
case Sunday:
printf("False");
break;
default:
printf("Invalid Entry");
}
getch();
}
|
C
|
#include "internal.h"
/// <summary>
/// Build the gradient and rotation pyramids
/// NOTE: Size of Pyramids = octave_count * gaussian_count with empty entries!
/// </summary>
/// <param name="gaussians"> IN: The octaves of the input image. </param>
/// <param name="gaussian_count"> IN: Number of octaves. </param>
/// <param name="gradients"> OUT: Struct of gradients to compute.
/// <param name="rotations"> OUT: Struct of rotations to compute.
/// <param name="layers"> IN: Number of layers in the gradients and rotation pyramids.
/// <param name="octave_count"> IN: Number of octaves. </param>
/// <param name="gaussian_count"> IN: Number of gaussian blurred images per layer. </param>
/// <returns> 1 IF generation was successful, ELSE 0. </returns>
int ethsift_generate_gradient_pyramid(struct ethsift_image gaussians[],
uint32_t gaussian_count,
struct ethsift_image gradients[],
struct ethsift_image rotations[],
uint32_t layers,
uint32_t octave_count){
int width, height;
int idx;
int col_upper_offset = 8, col_lower_offset = 1;
int row_upper_offset = 1, row_lower_offset = 1;
float d_row, d_column;
float d_row1, d_column1;
float d_row2, d_column2;
__m256 d_row_m256, d_column_m256;
__m256 d_row1_m256, d_column1_m256;
__m256 d_row2_m256, d_column2_m256;
float * in_gaussian;
float * out_grads;
float * out_rots;
float * in_gaussian1;
float * out_grads1;
float * out_rots1;
float * in_gaussian2;
float * out_grads2;
float * out_rots2;
for(int i = 0; i < octave_count; i++){
width = (int) gaussians[i * gaussian_count].width;
height = (int) gaussians[i * gaussian_count].height;
inc_read(2, int32_t);
idx = i * gaussian_count + 1;
in_gaussian = gaussians[idx].pixels;
out_grads = gradients[idx].pixels;
out_rots = rotations[idx].pixels;
in_gaussian1 = gaussians[idx + 1].pixels;
out_grads1 = gradients[idx + 1].pixels;
out_rots1 = rotations[idx + 1].pixels;
in_gaussian2 = gaussians[idx + 2].pixels;
out_grads2 = gradients[idx + 2].pixels;
out_rots2 = rotations[idx + 2].pixels;
// DO THE MIDDLE OF THE IMAGE WITH AVX
__m256 gaussian_rpo_cols, gaussian_rmo_cols;
__m256 gaussian1_rpo_cols, gaussian1_rmo_cols;
__m256 gaussian2_rpo_cols, gaussian2_rmo_cols;
__m256 gaussian_cpo_cols, gaussian_cmo_cols;
__m256 gaussian1_cpo_cols, gaussian1_cmo_cols;
__m256 gaussian2_cpo_cols, gaussian2_cmo_cols;
__m256 sqrt_input, sqrt_input1, sqrt_input2;
__m256 grad, grad1, grad2;
__m256 rot, rot1, rot2;
int col_counter = 0;
for(int row = row_lower_offset; row < height-row_upper_offset; ++row){
int row_plus_one = row + 1;
int row_minus_one = row - 1;
int row_width = row*width;
int column = col_lower_offset;
for(; column < width-col_upper_offset; column+=8){
int write_index = row_width + column;
int col_plus_one = column + 1;
int col_minus_one = column - 1;
int rpo_ind = row_plus_one * width + column;
int rmo_ind = row_minus_one * width + column;
int cpo_ind = row * width + col_plus_one;
int cmo_ind = row * width + col_minus_one;
gaussian_rpo_cols = _mm256_loadu_ps(in_gaussian + rpo_ind);
gaussian_rmo_cols = _mm256_loadu_ps(in_gaussian + rmo_ind);
gaussian1_rpo_cols = _mm256_loadu_ps(in_gaussian1 + rpo_ind);
gaussian1_rmo_cols = _mm256_loadu_ps(in_gaussian1 + rmo_ind);
gaussian2_rpo_cols = _mm256_loadu_ps(in_gaussian2 + rpo_ind);
gaussian2_rmo_cols = _mm256_loadu_ps(in_gaussian2 + rmo_ind);
gaussian_cpo_cols = _mm256_loadu_ps(in_gaussian + cpo_ind);
gaussian_cmo_cols = _mm256_loadu_ps(in_gaussian + cmo_ind);
gaussian1_cpo_cols = _mm256_loadu_ps(in_gaussian1 + cpo_ind);
gaussian1_cmo_cols = _mm256_loadu_ps(in_gaussian1 + cmo_ind);
gaussian2_cpo_cols = _mm256_loadu_ps(in_gaussian2 + cpo_ind);
gaussian2_cmo_cols = _mm256_loadu_ps(in_gaussian2 + cmo_ind);
inc_read(2*3*2*8, float);
d_row_m256 = _mm256_sub_ps(gaussian_rpo_cols, gaussian_rmo_cols);
d_column_m256 = _mm256_sub_ps(gaussian_cpo_cols, gaussian_cmo_cols);
d_row1_m256 = _mm256_sub_ps(gaussian1_rpo_cols, gaussian1_rmo_cols);
d_column1_m256 = _mm256_sub_ps(gaussian1_cpo_cols, gaussian1_cmo_cols);
d_row2_m256 = _mm256_sub_ps(gaussian2_rpo_cols, gaussian2_rmo_cols);
d_column2_m256 = _mm256_sub_ps(gaussian2_cpo_cols, gaussian2_cmo_cols);
inc_adds(48); // 2 Subtractions
sqrt_input = _mm256_mul_ps(d_row_m256, d_row_m256);
sqrt_input1 = _mm256_mul_ps(d_row1_m256, d_row1_m256);
sqrt_input2 = _mm256_mul_ps(d_row2_m256, d_row2_m256);
sqrt_input = _mm256_fmadd_ps(d_column_m256, d_column_m256, sqrt_input);
sqrt_input1 = _mm256_fmadd_ps(d_column1_m256, d_column1_m256, sqrt_input1);
sqrt_input2 = _mm256_fmadd_ps(d_column2_m256, d_column2_m256, sqrt_input2);
grad = _mm256_sqrt_ps(sqrt_input);
grad1 = _mm256_sqrt_ps(sqrt_input1);
grad2 = _mm256_sqrt_ps(sqrt_input2);
eth_mm256_atan2_ps(&d_row_m256, &d_column_m256, &rot);
eth_mm256_atan2_ps(&d_row1_m256, &d_column1_m256, &rot1);
eth_mm256_atan2_ps(&d_row2_m256, &d_column2_m256, &rot2);
_mm256_storeu_ps(out_grads + write_index, grad);
_mm256_storeu_ps(out_rots + write_index, rot);
_mm256_storeu_ps(out_grads1 + write_index, grad1);
_mm256_storeu_ps(out_rots1 + write_index, rot1);
_mm256_storeu_ps(out_grads2 + write_index, grad2);
_mm256_storeu_ps(out_rots2 + write_index, rot2);
inc_write(3*2*8, float);
}
//DO THE REST UP UNTIL TO THE BORDERS
for(; column < width-1; ++column){
int col_plus_one = column + 1;
int col_minus_one = column - 1;
d_row = in_gaussian[row_plus_one * width + column] - in_gaussian[row_minus_one * width + column];
d_column = in_gaussian[row * width + col_plus_one] - in_gaussian[row * width + col_minus_one];
d_row1 = in_gaussian1[row_plus_one * width + column] - in_gaussian1[row_minus_one * width + column];
d_column1 = in_gaussian1[row * width + col_plus_one] - in_gaussian1[row * width + col_minus_one];
d_row2 = in_gaussian2[row_plus_one * width + column] - in_gaussian2[row_minus_one * width + column];
d_column2 = in_gaussian2[row * width + col_plus_one] - in_gaussian2[row * width + col_minus_one];
inc_read(3*2*2, float);
inc_adds(6); // 2 Subtractions
out_grads[row * width + column] = sqrtf(d_row * d_row + d_column * d_column);
out_rots[row * width + column] = fast_atan2_f(d_row, d_column);
out_grads1[row * width + column] = sqrtf(d_row1 * d_row1 + d_column1 * d_column1);
out_rots1[row * width + column] = fast_atan2_f(d_row1, d_column1);
out_grads2[row * width + column] = sqrtf(d_row2 * d_row2 + d_column2 * d_column2);
out_rots2[row * width + column] = fast_atan2_f(d_row2, d_column2);
inc_write(3*2, float);
}
}
// DO THE THE BORDER OF THE IMAGE AS WE HAVE DONE BEFORE.
int row_plus_one1 = 1;
int row1 = 0;
int row2 = height-1;
int row_minus_one2 = height-2;
for(int column = 0; column < width; ++column){
// UPPER ROW BORDER
int col_plus_one = internal_min(internal_max(column + 1, 0), width - 1);
int col_minus_one = internal_min(internal_max(column - 1, 0), width - 1);
d_row = in_gaussian[row_plus_one1 * width + column] - in_gaussian[row1 * width + column];
d_column = in_gaussian[row1 * width + col_plus_one] - in_gaussian[row1 * width + col_minus_one];
d_row1 = in_gaussian1[row_plus_one1 * width + column] - in_gaussian1[row1 * width + column];
d_column1 = in_gaussian1[row1 * width + col_plus_one] - in_gaussian1[row1 * width + col_minus_one];
d_row2 = in_gaussian2[row_plus_one1 * width + column] - in_gaussian2[row1 * width + column];
d_column2 = in_gaussian2[row1 * width + col_plus_one] - in_gaussian2[row1 * width + col_minus_one];
inc_adds(6); // 2 Subtractions
inc_read(3*2*2, float);
out_grads[row1 * width + column] = sqrtf(d_row * d_row + d_column * d_column);
out_rots[row1 * width + column] = fast_atan2_f(d_row, d_column);
out_grads1[row1 * width + column] = sqrtf(d_row1 * d_row1 + d_column1 * d_column1);
out_rots1[row1 * width + column] = fast_atan2_f(d_row1, d_column1);
out_grads2[row1 * width + column] = sqrtf(d_row2 * d_row2 + d_column2 * d_column2);
out_rots2[row1 * width + column] = fast_atan2_f(d_row2, d_column2);
inc_write(3*2, float);
// LOWER ROW BORDER
d_row = in_gaussian[row2 * width + column] - in_gaussian[row_minus_one2 * width + column];
d_column = in_gaussian[row2 * width + col_plus_one] - in_gaussian[row2 * width + col_minus_one];
d_row1 = in_gaussian1[row2 * width + column] - in_gaussian1[row_minus_one2 * width + column];
d_column1 = in_gaussian1[row2 * width + col_plus_one] - in_gaussian1[row2 * width + col_minus_one];
d_row2 = in_gaussian2[row2 * width + column] - in_gaussian2[row_minus_one2 * width + column];
d_column2 = in_gaussian2[row2 * width + col_plus_one] - in_gaussian2[row2 * width + col_minus_one];
inc_adds(6); // 2 Subtractions
inc_read(3*2*2, float);
out_grads[row2 * width + column] = sqrtf(d_row * d_row + d_column * d_column);
out_rots[row2 * width + column] = fast_atan2_f(d_row, d_column);
out_grads1[row2 * width + column] = sqrtf(d_row1 * d_row1 + d_column1 * d_column1);
out_rots1[row2 * width + column] = fast_atan2_f(d_row1, d_column1);
out_grads2[row2 * width + column] = sqrtf(d_row2 * d_row2 + d_column2 * d_column2);
out_rots2[row2 * width + column] = fast_atan2_f(d_row2, d_column2);
inc_write(3*2, float);
}
//DO COLUMN BORDERS
for(int row = 1; row < height-1; ++row){
int row_plus_one = row+1;
int row_minus_one = row-1;
//LEFTHAND SIDE COLUMN BORDER
int col_plus_one = 1;
d_row = in_gaussian[row_plus_one * width] - in_gaussian[row_minus_one * width];
d_column = in_gaussian[row * width + col_plus_one] - in_gaussian[row * width];
d_row1 = in_gaussian1[row_plus_one * width] - in_gaussian1[row_minus_one * width];
d_column1 = in_gaussian1[row * width + col_plus_one] - in_gaussian1[row * width];
d_row2 = in_gaussian2[row_plus_one * width] - in_gaussian2[row_minus_one * width];
d_column2 = in_gaussian2[row * width + col_plus_one] - in_gaussian2[row * width];
inc_adds(6); // 2 Subtractions
inc_read(3*2*2, float);
out_grads[row * width] = sqrtf(d_row * d_row + d_column * d_column);
out_rots[row * width] = fast_atan2_f(d_row, d_column);
out_grads1[row * width] = sqrtf(d_row1 * d_row1 + d_column1 * d_column1);
out_rots1[row * width] = fast_atan2_f(d_row1, d_column1);
out_grads2[row * width] = sqrtf(d_row2 * d_row2 + d_column2 * d_column2);
out_rots2[row * width] = fast_atan2_f(d_row2, d_column2);
inc_write(3*2, float);
//RIGHTHAND SIDE COLUMN BORDER
col_plus_one = width-1;
int col_minus_one = width-2;
d_row = in_gaussian[row_plus_one * width + col_plus_one] - in_gaussian[row_minus_one * width + col_plus_one];
d_column = in_gaussian[row * width + col_plus_one] - in_gaussian[row * width + col_minus_one];
d_row1 = in_gaussian1[row_plus_one * width + col_plus_one] - in_gaussian1[row_minus_one * width + col_plus_one];
d_column1 = in_gaussian1[row * width + col_plus_one] - in_gaussian1[row * width + col_minus_one];
d_row2 = in_gaussian2[row_plus_one * width + col_plus_one] - in_gaussian2[row_minus_one * width + col_plus_one];
d_column2 = in_gaussian2[row * width + col_plus_one] - in_gaussian2[row * width + col_minus_one];
inc_adds(6); // 2 Subtractions
inc_read(3*2*2, float);
out_grads[row * width + col_plus_one] = sqrtf(d_row * d_row + d_column * d_column);
out_rots[row * width + col_plus_one] = fast_atan2_f(d_row, d_column);
out_grads1[row * width + col_plus_one] = sqrtf(d_row1 * d_row1 + d_column1 * d_column1);
out_rots1[row * width + col_plus_one] = fast_atan2_f(d_row1, d_column1);
out_grads2[row * width + col_plus_one] = sqrtf(d_row2 * d_row2 + d_column2 * d_column2);
out_rots2[row * width + col_plus_one] = fast_atan2_f(d_row2, d_column2);
inc_write(3*2, float);
}
}
return 1;
}
int ethsift_generate_gradient_pyramid_janleu(struct ethsift_image gaussians[],
uint32_t gaussian_count,
struct ethsift_image gradients[],
struct ethsift_image rotations[],
uint32_t layers,
uint32_t octave_count){
int width, height;
int idx;
float *in_gaussian;
float *out_grads;
float *out_rots;
for(int i = 0; i < octave_count; i++){
width = (int) gaussians[i * gaussian_count].width;
height = (int) gaussians[i * gaussian_count].height;
inc_read(2, int32_t);
__m256 d_cp1;
__m256 d_cm1;
__m256 d_rp1;
__m256 d_rm1;
__m256 d_row;
__m256 d_col;
__m256 d_input_sqrt;
__m256 d_sqrt;
__m256 d_atan;
int w_lim = width - 8;
for (int l = 1; l <= layers; ++l) {
idx = i * gaussian_count + l;
in_gaussian = gaussians[idx].pixels;
out_grads = gradients[idx].pixels;
out_rots = rotations[idx].pixels;
int c;
for (int r = 1; r < height - 1; ++r) {
for (c = 1; c < w_lim; c += 8) {
int c_m1 = c - 1;
int c_p1 = c + 1;
int r_m1 = r - 1;
int r_p1 = r + 1;
int pos = r * width + c;
d_cp1 = _mm256_loadu_ps(in_gaussian + r * width + c_p1);
d_cm1 = _mm256_loadu_ps(in_gaussian + r * width + c_m1);
d_rm1 = _mm256_loadu_ps(in_gaussian + r_m1 * width + c);
d_rp1 = _mm256_loadu_ps(in_gaussian + r_p1 * width + c);
inc_read(4*8, float);
d_row = _mm256_sub_ps(d_rp1, d_rm1);
d_col = _mm256_sub_ps(d_cp1, d_cm1);
d_input_sqrt = _mm256_mul_ps(d_col, d_col);
d_input_sqrt = _mm256_fmadd_ps(d_row, d_row, d_input_sqrt);
d_sqrt = _mm256_sqrt_ps(d_input_sqrt);
eth_mm256_atan2_ps(&d_row, &d_col, &d_atan);
_mm256_storeu_ps(out_grads + pos, d_sqrt);
_mm256_storeu_ps(out_rots + pos, d_atan);
inc_write(2*8, float);
}
for (; c < width; ++c) {
int r_p1 = r + 1;
int r_m1 = r - 1;
int c_m1 = internal_min(internal_max(c - 1, 0), width - 1);
int c_p1 = internal_min(internal_max(c + 1, 0), width - 1);
float row = in_gaussian[r_p1 * width + c] - in_gaussian[r_m1 * width + c];
float col = in_gaussian[r * width + c_p1] - in_gaussian[r * width + c_m1];
inc_read(2*2, float);
out_grads[r * width + c] = sqrtf(row * row + col * col);
out_rots[r * width + c] = fast_atan2_f(row, col);
inc_write(2, float);
}
}
for (int i = 0; i < width; ++ i) {
int c_p1 = internal_min(internal_max(i + 1, 0), width - 1);
int c_m1 = internal_min(internal_max(i - 1, 0), width - 1);
float row1 = in_gaussian[width + i] - in_gaussian[i];
float col1 = in_gaussian[c_p1] - in_gaussian[c_m1];
inc_read(2*2, float);
float row2 = in_gaussian[(height - 1) * width + i] - in_gaussian[(height - 2) * width + i];
float col2 = in_gaussian[(height - 1) * width + c_p1] - in_gaussian[(height - 1) * width + c_m1];
inc_read(2*2, float);
out_grads[i] = sqrtf(row1 * row1 + col1 * col1);
out_rots[i] = fast_atan2_f(row1, col1);
out_grads[(height - 1) * width + i] = sqrtf(row2 * row2 + col2 * col2);
out_rots[(height - 1) * width + i] = fast_atan2_f(row2, col2);
inc_write(2, float);
}
for (int i = 0; i < height; ++i) {
int c_m1 = 0;
int c_p1 = 1;
int r_p1 = internal_min(internal_max(i + 1, 0), height - 1);
int r_m1 = internal_min(internal_max(i - 1, 0), height - 1);
float row1 = in_gaussian[r_p1 * width] - in_gaussian[r_m1 * width];
float col1 = in_gaussian[i * width + c_p1] - in_gaussian[i * width + c_m1];
inc_read(2*2, float);
out_grads[i * width] = sqrtf(row1 * row1 + col1 * col1);
out_rots[i * width] = fast_atan2_f(row1, col1);
inc_write(2, float);
}
}
}
return 1;
}
|
C
|
//*********************************************
// ntpproxy.c - NTP Proxy
//
// Program runs as proxy between NTP time source
// and another NTP client which in turn acts as
// a server for other NTP clients.
// NTP Proxy modifies time stamps and
// sets leap-indicator flag on the flow
// from NTP time source to client.
//
// 03.05.2013 R. Karbowski - Initial version
// 20.01.2014 R. Karbowski - Unbuffer stdout for logging
// 24.01.2014 R. Karbowski - print() with timestamp instead of printf()
// - logging facility displays client/server IP@-es
// - dump NTP packet in hex mode
// - allow only mode 03 client's queries
//
//*********************************************
#include <time.h>
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <strings.h>
#include <libnet.h>
#include <stdbool.h>
#define JAN_1970 2208988800U // 1970 - 1900 in seconds - shifts system time to NTP one
// Default values
time_t bmidnight=600; // Number of seconds before midnight (leap second action)
int ls=1; // 1: insert, -1: deduct leap second
bool verbose=false; // Print additional information
char ntpserverip[25]; // IP of NTP source time server
void printNtp();
void pparam();
void usage();
void print(const char *format,...);
// Number of days per month
int dpm[]={31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int main(argc, argv)
int argc;
char *argv[];
{
unsigned char buf[1024], mode;
int csd; // Client socket descriptor
int ssd; // Server socket descriptor
int i, srin_tmp_len, year, days;
bool WasLsApplied=false; // Divide time befor leap second and after
bool leapyear=false;
time_t now, t2midnight, timeoffset, lswindow;
long len, n;
struct sockaddr_in srin, srin_tmp, clin;
struct libnet_ntp_hdr ntp_hdr;
struct tm *ts;
// Unbuffer stdout
setbuf(stdout, NULL);
// Parse parameters
pparam(argc, argv);
// Calculate time offset to be added to current
// time to reach end of Jun or Dec 23:50
now=time(NULL);
// Number of seconds to midnight
t2midnight=((now/86400)*86400 + 86400) - now;
ts=gmtime(&now);
year=1900+ts->tm_year;
// Is it leap year?
if((year%4 == 0) && ((year%100 != 0) || (year%400 == 0)))
leapyear=true;
// Number of days to the next leap second window (end of Jun or Dec)
days=0;
if(ts->tm_mon < 6)
{
for(i=ts->tm_mon; i<6; i++)
if(dpm[i] == 1 && leapyear)
days+=29;
else
days+=dpm[i];
}
else
for(i=ts->tm_mon; i<12; i++)
days+=dpm[i];
timeoffset=(days - ts->tm_mday)*86400 + t2midnight - bmidnight;
// Time (in sec and NTP format) when leap second will be applied
lswindow=now + timeoffset + bmidnight + JAN_1970;
if(verbose)
print("days=%d, tm_mday=%d, t2midnight=%lld, now=%d, timeoffset=%d, lswindow=%lld\n", days, ts->tm_mday, t2midnight, now, timeoffset, lswindow);
now+=timeoffset;
ts=gmtime(&now);
if(verbose)
print("now + timeoffset=%ld\n", now);
if(verbose)
print("%02d:%02d:%02d Day=%d, Month=%d, Year=%d\n", ts->tm_hour, ts->tm_min, ts->tm_sec, ts->tm_mday, ts->tm_mon, ts->tm_year);
//exit(0);
// We play as client and connect to NTP time source server
print("Connecting NTP source time server: %s\n", ntpserverip);
if ((csd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
{
perror("csd = socket(AF_INET, SOCK_DGRAM, 0)");
exit(2);
}
bzero(&clin,sizeof(clin));
clin.sin_family=AF_INET;
clin.sin_addr.s_addr=inet_addr(ntpserverip);
clin.sin_port=htons(123);
if(connect(csd, (struct sockaddr *) &clin, sizeof(clin)) == -1)
{
perror("connect(csd, (struct sockaddr *) &clin, sizeof(clin))");
exit(1);
}
// Listener part
if ((ssd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
{
perror("ssd = socket(AF_INET, SOCK_DGRAM, 0)");
exit(2);
}
bzero(&srin,sizeof(srin));
srin.sin_family=AF_INET;
srin.sin_addr.s_addr=INADDR_ANY;
srin.sin_port=htons(123);
if(bind(ssd,(struct sockaddr *)&srin,sizeof(srin)) < 0)
{
perror("bind(ssd,(struct sockaddr *)&srin,sizeof(srin))");
exit(2);
}
print("Ready for NTP client query\n\n");
len=sizeof(ntp_hdr);
while(1)
{
// Client's query
srin_tmp_len=sizeof(srin_tmp);
if((n=recvfrom(ssd,&ntp_hdr,len,0,(struct sockaddr *) &srin_tmp,&srin_tmp_len)) < 0)
{
perror("recvfrom(ssd)");
exit(2);
}
print("Received %i B from client %s\n", n, inet_ntoa(srin_tmp.sin_addr));
if(verbose)
printNtp(&ntp_hdr);
// Accept only Clinet's mode requests (3)
mode=ntp_hdr.ntp_li_vn_mode & 0x7;
if(mode != 3)
{
print("Packet's mode (%02hi) is not supported. Ignoring request\n\n", mode);
continue;
}
// Client's query forwarded to server
if((n=write(csd,&ntp_hdr,n)) < 0)
{
perror("write(csd)");
exit(2);
}
print("Client's query forwarded to server\n");
// Server's response
if((n=read(csd,&ntp_hdr,len)) < 0)
{
perror("read(csd)");
exit(2);
}
print("Received %i B from server %s\n", n, ntpserverip);
if(verbose)
printNtp(&ntp_hdr);
// Modification of server's response
if(!WasLsApplied)
{ // Part before leap second window
if((ntohl(ntp_hdr.ntp_xmt_ts.integer) + timeoffset) >= lswindow)
{
WasLsApplied=true;
goto afterLS;
}
// Add leap second indicator
if(ls == 1)
ntp_hdr.ntp_li_vn_mode+=64; // Add LS
else
ntp_hdr.ntp_li_vn_mode+=128; // Subtract LS
ntp_hdr.ntp_ref_ts.integer=htonl(ntohl(ntp_hdr.ntp_ref_ts.integer) + timeoffset);
ntp_hdr.ntp_rec_ts.integer=htonl(ntohl(ntp_hdr.ntp_rec_ts.integer) + timeoffset);
ntp_hdr.ntp_xmt_ts.integer=htonl(ntohl(ntp_hdr.ntp_xmt_ts.integer) + timeoffset);
}
else // After leap second window subtract 1 second
afterLS:
{
ntp_hdr.ntp_ref_ts.integer=htonl(ntohl(ntp_hdr.ntp_ref_ts.integer) + timeoffset - ls);
ntp_hdr.ntp_rec_ts.integer=htonl(ntohl(ntp_hdr.ntp_rec_ts.integer) + timeoffset - ls);
ntp_hdr.ntp_xmt_ts.integer=htonl(ntohl(ntp_hdr.ntp_xmt_ts.integer) + timeoffset - ls);
}
// Modified server's response forwarded to client
if((n=sendto(ssd,&ntp_hdr,n,0,(struct sockaddr *) &srin_tmp,srin_tmp_len)) < 0)
{
perror("sendto(ssd)");
exit(2);
}
print("Modified response (%i B) sent to client %s\n", n, inet_ntoa(srin_tmp.sin_addr));
if(verbose)
printNtp(&ntp_hdr);
printf("\n");
}
close(ssd);
close(csd);
}
//*************************
// Parse parameters
//*************************
void pparam(argc, argv)
int argc;
char *argv[];
{
int opt, len;
if(argc < 3)
{
usage();
exit(1);
}
while((opt=getopt(argc, argv, "s:d:l:vh")) != -1)
{
switch(opt)
{
case 's': // NTP server IP
len=strlen(optarg);
if(len > 15 || len < 7) // IP size -> XXX.XXX.XXX.XXX - X.X.X.X
{
printf("Wrong argument for option \'-s\'\n");
usage();
exit(1);
}
strncpy(ntpserverip,optarg,len);
print("ntpserverip=%s\n", ntpserverip);
break;
case 'd': // Set delay in seconds
bmidnight=atoi(optarg);
break;
case 'l': // Insert/delete leap second
if(strncmp(optarg, "add", 3) == 0)
{
ls=1;
break;
}
if(strncmp(optarg, "del", 3) == 0)
{
ls=-1;
break;
}
printf("Wrong argument for option \'-l\'\n");
usage();
exit(1);
break;
case 'v': // Verbose
verbose=true;
break;
case 'h':
default:
usage();
exit(1);
}
}
}
//*************************
// Print usage message
//*************************
void usage()
{
printf("Usage: ntpproxy -s server_ip [-d seconds] [-l add|del] [-v] [-h]\n");
printf("-s\tIP of NTP source time server\n");
printf("-d\tdelay before leap second accomplishment. Default 600 seconds\n");
printf("-l\tadd: insert leap second, del: delete leap second. Default add\n");
printf("-v\tdebug information\n");
printf("-h\thelp\n");
}
//***************************
// Parse NTP header and
// print values
//***************************
void printNtp(ntp_hdr)
struct libnet_ntp_hdr *ntp_hdr;
{
unsigned char li, version, mode;
register int f;
register float ff;
register u_int32_t luf;
register u_int32_t lf;
register float lff;
FILE *pfd;
// leap second
li=ntp_hdr->ntp_li_vn_mode >> 6;
// version
version=(ntp_hdr->ntp_li_vn_mode >> 3) & 0x7;
// mode
mode=ntp_hdr->ntp_li_vn_mode & 0x7;
print("Leap=%02hi, Ver=%02hi, Mode=%02hi, Stratum=%02hi, ", li, version, mode, ntp_hdr->ntp_stratum);
printf("Poll=%03hi, Precision=%#02hx, ", ntp_hdr->ntp_poll, ntp_hdr->ntp_precision);
f=ntohs(ntp_hdr->ntp_delay.fraction);
ff=f / 65536.0;
f=ff * 1000000.0;
printf("Delay=%d.%06d, ", ntohs(ntp_hdr->ntp_delay.integer), f);
f=ntohs(ntp_hdr->ntp_dispersion.fraction);
ff=f / 65536.0;
f=ff * 1000000.0;
printf("Dispersion=%d.%06d, ", ntohs(ntp_hdr->ntp_dispersion.integer), f);
printf("ReferenceID=%#lx, ", ntp_hdr->ntp_reference_id);
luf=ntohl(ntp_hdr->ntp_ref_ts.fraction);
lff=luf;
lff=lff/4294967296.0;
lf=lff*1000000000.0;
printf("ReferenceTS=%u.%09d, ", ntohl(ntp_hdr->ntp_ref_ts.integer), lf);
luf=ntohl(ntp_hdr->ntp_orig_ts.fraction);
lff=luf;
lff=lff/4294967296.0;
lf=lff*1000000000.0;
printf("OriginateTS=%u.%09d, ", ntohl(ntp_hdr->ntp_orig_ts.integer), lf);
luf=ntohl(ntp_hdr->ntp_rec_ts.fraction);
lff=luf;
lff=lff/4294967296.0;
lf=lff*1000000000.0;
printf("ReceiveTS=%u.%09d, ", ntohl(ntp_hdr->ntp_rec_ts.integer), lf);
luf=ntohl(ntp_hdr->ntp_xmt_ts.fraction);
lff=luf;
lff=lff/4294967296.0;
lf=lff*1000000000.0;
printf("TransmitTS=%u.%09d\n", ntohl(ntp_hdr->ntp_xmt_ts.integer), lf);
// Dump hexadecimally NTP packet
if((pfd=popen("hexdump -Cv","w")) == NULL)
{
perror("popen(hexdump -Cv)");
exit(1);
}
fwrite(ntp_hdr, 1, sizeof(struct libnet_ntp_hdr), pfd);
pclose(pfd);
}
//***************************
// Print info string with
// timestamp
//***************************
void print(const char *format,...)
{
struct timeval tv;
struct tm *tm;
va_list arg;
if(gettimeofday(&tv, NULL) == -1)
{
perror("gettimeofday()");
exit(1);
}
if((tm=localtime(&tv.tv_sec)) == NULL)
{
perror("localtime()");
exit(1);
}
printf("%02d.%02d.%02d %02d:%02d:%02d.%06d ", tm->tm_mday, tm->tm_mon+1, tm->tm_year-100, tm->tm_hour, tm->tm_min, tm->tm_sec, tv.tv_usec);
va_start(arg, format);
vprintf(format, arg);
va_end(arg);
}
|
C
|
#include<stdio.h>
void main()
{int count=0;
int a[5]={1,2,3,4,5};
for(int i=0;i<sizeof(a/4);i++)
{
count++;
}
printf("%d",count);
}
|
C
|
#include<stdio.h>
#include<Windows.h>
void main(int argc,char* argv[])
{
int check1 = 0,check2=0;
STARTUPINFO sui1;
STARTUPINFO sui2;
PROCESS_INFORMATION pi1;
PROCESS_INFORMATION pi2;
ZeroMemory(&sui1, sizeof(sui1));
ZeroMemory(&pi1, sizeof(pi1));
sui1.cb = sizeof(sui1);
ZeroMemory(&sui2, sizeof(sui2));
ZeroMemory(&pi2, sizeof(pi2));
sui2.cb = sizeof(sui2);
HANDLE han1,han2;
check1 = CreateProcess(TEXT("C://Windows/notepad.exe"), NULL, NULL, NULL, FALSE, NORMAL_PRIORITY_CLASS, NULL,NULL , &sui1, &pi1);
if (check1 == 0)
{
printf("process1 not created:%d\n",GetLastError());
exit(0);
}
else
{
printf("process created");
printf("%ld\n", pi1.hProcess);
han1 = pi1.hProcess;
printf("%ld\n", pi1.hThread);
}
check2 = CreateProcessA((LPSTR)argv[1], NULL,NULL, NULL, FALSE, NORMAL_PRIORITY_CLASS, NULL,NULL, &sui2, &pi2);
if(check2==0)
{
printf("process2 not created:%d\n", GetLastError());
exit(0);
}
else
{
printf("process created");
printf("%ld\n", pi2.hProcess);
han2 = pi2.hProcess;
printf("%ld\n", pi2.hThread);
}
CloseHandle(han1);
CloseHandle(han2);
}
|
C
|
#include "remote_controller.h"
#include "stream_controller.h"
//#include "graphics.h"
static inline void textColor(int32_t attr, int32_t fg, int32_t bg)
{
char command[13];
/* command is the control command to the terminal */
sprintf(command, "%c[%d;%d;%dm", 0x1B, attr, fg + 30, bg + 40);
printf("%s", command);
}
/* macro function for error checking */
#define ERRORCHECK(x) \
{ \
if (x != 0) \
{ \
textColor(1,1,0); \
printf(" Error!\n File: %s \t Line: <%d>\n", __FILE__, __LINE__); \
textColor(0,7,0); \
return -1; \
} \
}
static void remoteControllerCallback(uint16_t code, uint16_t type, uint32_t value);
static pthread_cond_t deinitCond = PTHREAD_COND_INITIALIZER;
static pthread_mutex_t deinitMutex = PTHREAD_MUTEX_INITIALIZER;
static ChannelInfo channelInfo;
int8_t currChannel=0;
void readConf(FILE *);
input_struct* inputData;
int main(int argc, char *argv[])
{
FILE *fptr;
//creating a string for a config fiole name
int v = strlen(argv[1]); // for allocating memroy
char *str = (char *)malloc(v);
strcat(str, argv[1]);
//openning a config file
fptr = fopen(str,"r");
inputData = (input_struct*) malloc(sizeof(input_struct));
readConf(fptr);
currChannel=inputData->programNumber;
/* initialize remote controller module */
ERRORCHECK(remoteControllerInit());
/* register remote controller callback */
ERRORCHECK(registerRemoteControllerCallback(remoteControllerCallback));
/* initialize stream controller module */
ERRORCHECK(streamControllerInit(inputData));
/* wait for a EXIT remote controller key press event */
pthread_mutex_lock(&deinitMutex);
if (ETIMEDOUT == pthread_cond_wait(&deinitCond, &deinitMutex))
{
printf("\n%s : ERROR Lock timeout exceeded!\n", __FUNCTION__);
}
pthread_mutex_unlock(&deinitMutex);
/* unregister remote controller callback */
ERRORCHECK(unregisterRemoteControllerCallback(remoteControllerCallback));
/* deinitialize remote controller module */
ERRORCHECK(remoteControllerDeinit());
/* deinitialize stream controller module */
ERRORCHECK(streamControllerDeinit());
free(inputData);
free(str);
fclose(fptr);
return 0;
}
void remoteControllerCallback(uint16_t code, uint16_t type, uint32_t value)
{
switch(code)
{
case KEYCODE_INFO:
printf("\nInfo pressed\n");
if (getChannelInfo(&channelInfo) == SC_NO_ERROR)
{
printf("\n********************* Channel info *********************\n");
printf("Program number: %d\n", channelInfo.programNumber);
printf("Audio pid: %d\n", channelInfo.audioPid);
printf("Video pid: %d\n", channelInfo.videoPid);
printf("**********************************************************\n");
}
onInfoPressed();
break;
case KEYCODE_P_PLUS:
printf("\nCH+ pressed\n");
channelUp();
currChannel++;
break;
case KEYCODE_P_MINUS:
printf("\nCH- pressed\n");
channelDown();
currChannel--;
break;
case KEYCODE_EXIT:
printf("\nExit pressed\n");
pthread_mutex_lock(&deinitMutex);
pthread_cond_signal(&deinitCond);
pthread_mutex_unlock(&deinitMutex);
break;
//channel number pressed
case 2:
printf("Changing to Channel 1!\n");
if(currChannel!=1)
{
switchChannel(1);
}
currChannel=1;
break;
case 3:
printf("Changing to Channel 2!\n");
if(currChannel!=2)
{
switchChannel(2);
}
currChannel=2;
break;
case 4:
printf("Changing to Channel 3!\n");
if(currChannel!=3)
{
switchChannel(3);
}
currChannel=3;
break;
case 5:
printf("Changing to Channel 4!\n");
if(currChannel!=4)
{
switchChannel(4);
}
printf("current Channel: %d\n",currChannel);
currChannel=4;
break;
case 6:
printf("Changing to Channel 5!\n");
if(currChannel!=5)
{
switchChannel(5);
}
currChannel=5;
break;
case 7:
printf("Changing to Channel 6!\n");
if(currChannel!=6)
{
switchChannel(6);
}
currChannel=6;
break;
case 8:
printf("Changing to Channel 7!\n");
if(currChannel!=7)
{
switchChannel(7);
}
currChannel=7;
break;
case VOLUME_UP:
printf("Volume up!\n");
volumeUp();
onVolumePressed();
break;
case VOLUME_DOWN:
printf("Volume down!\n");
volumeDown();
onVolumePressed();
break;
case MUTE:
printf("Muted!\n");
muteVolume();
onVolumePressed();
break;
default: /*No defined key pressed*/
printf("\nPress P+, P-, info or exit! \n\n");
}
}
void readConf(FILE *fp)
{
//char ch = getc(fp);
fscanf(fp,"%d %d %s %d %d %d %d %d",&inputData->freq,&inputData->bandwith,inputData->module,&inputData->audioPID,&inputData->videoPID,&inputData->audioType,&inputData->videoType,&inputData->programNumber);
}
|
C
|
#define RESP_EOL "\n"
int hex2bin(const char *in, unsigned char *out);
unsigned char *hex2bin_m(const char *in, long *plen);
int do_hex2bn(BIGNUM **pr, const char *in);
int do_bn_print(FILE *out, const BIGNUM *bn);
int do_bn_print_name(FILE *out, const char *name, const BIGNUM *bn);
int parse_line(char **pkw, char **pval, char *linebuf, char *olinebuf);
int parse_line2(char **pkw, char **pval, char *linebuf, char *olinebuf, int eol);
BIGNUM *hex2bn(const char *in);
int tidy_line(char *linebuf, char *olinebuf);
int copy_line(const char *in, FILE *ofp);
int bint2bin(const char *in, int len, unsigned char *out);
int bin2bint(const unsigned char *in,int len,char *out);
void PrintValue(char *tag, unsigned char *val, int len);
void OutputValue(char *tag, unsigned char *val, int len, FILE *rfp,int bitmode);
void fips_algtest_init(void);
void do_entropy_stick(void);
int fips_strncasecmp(const char *str1, const char *str2, size_t n);
int fips_strcasecmp(const char *str1, const char *str2);
static int no_err;
static void put_err_cb(int lib, int func,int reason,const char *file,int line)
{
if (no_err)
return;
fprintf(stderr, "ERROR:%08lX:lib=%d,func=%d,reason=%d"
":file=%s:line=%d\n",
ERR_PACK(lib, func, reason),
lib, func, reason, file, line);
}
static void add_err_cb(int num, va_list args)
{
int i;
char *str;
if (no_err)
return;
fputs("\t", stderr);
for (i = 0; i < num; i++)
{
str = va_arg(args, char *);
if (str)
fputs(str, stderr);
}
fputs("\n", stderr);
}
int hex2bin(const char *in, unsigned char *out)
{
int n1, n2, isodd = 0;
unsigned char ch;
n1 = strlen(in);
if (in[n1 - 1] == '\n')
n1--;
if (n1 & 1)
isodd = 1;
for (n1=0,n2=0 ; in[n1] && in[n1] != '\n' ; )
{ /* first byte */
if ((in[n1] >= '0') && (in[n1] <= '9'))
ch = in[n1++] - '0';
else if ((in[n1] >= 'A') && (in[n1] <= 'F'))
ch = in[n1++] - 'A' + 10;
else if ((in[n1] >= 'a') && (in[n1] <= 'f'))
ch = in[n1++] - 'a' + 10;
else
return -1;
if(!in[n1])
{
out[n2++]=ch;
break;
}
/* If input is odd length first digit is least significant: assumes
* all digits valid hex and null terminated which is true for the
* strings we pass.
*/
if (n1 == 1 && isodd)
{
out[n2++] = ch;
continue;
}
out[n2] = ch << 4;
/* second byte */
if ((in[n1] >= '0') && (in[n1] <= '9'))
ch = in[n1++] - '0';
else if ((in[n1] >= 'A') && (in[n1] <= 'F'))
ch = in[n1++] - 'A' + 10;
else if ((in[n1] >= 'a') && (in[n1] <= 'f'))
ch = in[n1++] - 'a' + 10;
else
return -1;
out[n2++] |= ch;
}
return n2;
}
unsigned char *hex2bin_m(const char *in, long *plen)
{
unsigned char *p;
if (strlen(in) == 0)
{
*plen = 0;
return OPENSSL_malloc(1);
}
p = OPENSSL_malloc((strlen(in) + 1)/2);
*plen = hex2bin(in, p);
return p;
}
int do_hex2bn(BIGNUM **pr, const char *in)
{
unsigned char *p;
long plen;
int r = 0;
p = hex2bin_m(in, &plen);
if (!p)
return 0;
if (!*pr)
*pr = BN_new();
if (!*pr)
return 0;
if (BN_bin2bn(p, plen, *pr))
r = 1;
OPENSSL_free(p);
return r;
}
int do_bn_print(FILE *out, const BIGNUM *bn)
{
int len, i;
unsigned char *tmp;
len = BN_num_bytes(bn);
if (len == 0)
{
fputs("00", out);
return 1;
}
tmp = OPENSSL_malloc(len);
if (!tmp)
{
fprintf(stderr, "Memory allocation error\n");
return 0;
}
BN_bn2bin(bn, tmp);
for (i = 0; i < len; i++)
fprintf(out, "%02x", tmp[i]);
OPENSSL_free(tmp);
return 1;
}
int do_bn_print_name(FILE *out, const char *name, const BIGNUM *bn)
{
int r;
fprintf(out, "%s = ", name);
r = do_bn_print(out, bn);
if (!r)
return 0;
fputs(RESP_EOL, out);
return 1;
}
int parse_line(char **pkw, char **pval, char *linebuf, char *olinebuf)
{
return parse_line2(pkw, pval, linebuf, olinebuf, 1);
}
int parse_line2(char **pkw, char **pval, char *linebuf, char *olinebuf, int eol)
{
char *keyword, *value, *p, *q;
strcpy(linebuf, olinebuf);
keyword = linebuf;
/* Skip leading space */
while (isspace((unsigned char)*keyword))
keyword++;
/* Look for = sign */
p = strchr(linebuf, '=');
/* If no '=' exit */
if (!p)
return 0;
q = p - 1;
/* Remove trailing space */
while (isspace((unsigned char)*q))
*q-- = 0;
*p = 0;
value = p + 1;
/* Remove leading space from value */
while (isspace((unsigned char)*value))
value++;
/* Remove trailing space from value */
p = value + strlen(value) - 1;
if (eol && *p != '\n')
fprintf(stderr, "Warning: missing EOL\n");
while (*p == '\n' || isspace((unsigned char)*p))
*p-- = 0;
*pkw = keyword;
*pval = value;
return 1;
}
BIGNUM *hex2bn(const char *in)
{
BIGNUM *p=NULL;
if (!do_hex2bn(&p, in))
return NULL;
return p;
}
/* To avoid extensive changes to test program at this stage just convert
* the input line into an acceptable form. Keyword lines converted to form
* "keyword = value\n" no matter what white space present, all other lines
* just have leading and trailing space removed.
*/
/* NB: this return the number of _bits_ read */
int bint2bin(const char *in, int len, unsigned char *out)
{
int n;
memset(out,0,len);
for(n=0 ; n < len ; ++n)
if(in[n] == '1')
out[n/8]|=(0x80 >> (n%8));
return len;
}
int bin2bint(const unsigned char *in,int len,char *out)
{
int n;
for(n=0 ; n < len ; ++n)
out[n]=(in[n/8]&(0x80 >> (n%8))) ? '1' : '0';
return n;
}
/*-----------------------------------------------*/
void PrintValue(char *tag, unsigned char *val, int len)
{
#ifdef VERBOSE
OutputValue(tag, val, len, stdout, 0);
#endif
}
void OutputValue(char *tag, unsigned char *val, int len, FILE *rfp,int bitmode)
{
char obuf[2048];
int olen;
if(bitmode)
{
olen=bin2bint(val,len,obuf);
fprintf(rfp, "%s = %.*s" RESP_EOL, tag, olen, obuf);
}
else
{
int i;
fprintf(rfp, "%s = ", tag);
for (i = 0; i < len; i++)
fprintf(rfp, "%02x", val[i]);
fputs(RESP_EOL, rfp);
}
#if VERBOSE
printf("%s = %.*s\n", tag, olen, obuf);
#endif
}
|
C
|
//structure_pointer with function and user_input
#include<stdio.h>
#include<string.h>
// we define structure before function prototypes and int main
//i.e. structure is global variable
struct Books //name of structure is Books
{
char title[50];
char author[50];
char subject[100];
int id;
};
//now we declare function prototypes
void printBooks( struct Books *book); // functioin name is printBooks
// now we define int main and structures book1 and book2 inside it.
int main()
{
printf("**************************************************\n");
struct Books book1;
struct Books book2;
//now we store book1 and book2 input using strcpy
strcpy(book1.title, " C Program 123");
strcpy(book1.author, "Ali");
strcpy(book1.subject, "Computer");
book1.id = 123;
strcpy(book2.title, "Quantum Mechanics");
strcpy(book2.author, "Zettili");
strcpy(book2.subject, "Physics");
book2.id = 236;
// now we will print details of book1 and book2
printBooks ( &book1); // invoking the void function called printBooks
printf("\n"); // pointer needs &
printBooks ( &book2);
printf("***************************************************\n");
return 0;
}
// after int main we define our functions(or, modules).
void printBooks(struct Books *book)
{ // for pointer we use -> instead of .
printf("Book title: %s\n", book->title);
printf("Book author: %s\n", book->author);
printf("Book subject: %s\n", book->subject);
printf("Book book id: %d\n", book->id);
} // void function doesnot have return values.
|
C
|
/*
2- Escrever uma função recursiva que retorna o tamanho de um string, tamstring(char s[])
*/
#include <stdio.h>
int tamstring(char s[])
{
if (s[0] == '\0')
return 0;
else
return 1 + tamstring(&s[1]);
}
void main()
{
char s[30];
printf("\nDigite a palavra que deseja saber o tamanho: ");
scanf("%s", s);
printf("\nA palavra '%s' possui %i letras", s, tamstring(s));
}
|
C
|
/*
* File: 4bit_mode_lcd.c
* Author: Yuvaraj
*
* Created on September 12, 2020, 4:38 PM
*/
// CONFIG
#pragma config FOSC = HS // Oscillator Selection bits (HS oscillator)
#pragma config WDTE = OFF // Watchdog Timer Enable bit (WDT disabled)
#pragma config PWRTE = OFF // Power-up Timer Enable bit (PWRT disabled)
#pragma config BOREN = OFF // Brown-out Reset Enable bit (BOR disabled)
#pragma config LVP = OFF // Low-Voltage (Single-Supply) In-Circuit Serial Programming Enable bit (RB3 is digital I/O, HV on MCLR must be used for programming)
#pragma config CPD = ON // Data EEPROM Memory Code Protection bit (Data EEPROM code-protected)
#pragma config WRT = 256 // Flash Program Memory Write Enable bits (0000h to 00FFh write-protected; 0100h to 1FFFh may be written to by EECON control)
#pragma config CP = ON // Flash Program Memory Code Protection bit (All program memory code-protected)
// #pragma config statements should precede project file includes.
// Use project enums instead of #define for ON and OFF.
//4 bit LCD Mode//
#include <xc.h>
#define _XTAL_FREQ 20000000
#define RS PORTBbits.RB0 /*PIN 0 of PORTB is assigned for register select Pin of LCD*/
#define EN PORTBbits.RB1 /*PIN 1 of PORTB is assigned for enable Pin of LCD */
#define ldata PORTD /*PORTB(PB4-PB7) is assigned for LCD Data Output*/
#define LCD_Port TRISD /*define macros for PORTB Direction Register*/
/*********************Proto-Type Declaration*****************************/
void MSdelay(unsigned int ); /*Generate delay in ms*/
void LCD_Init(); /*Initialize LCD*/
void LCD_Command(unsigned char ); /*Send command to LCD*/
void LCD_Char(unsigned char x); /*Send data to LCD*/
void LCD_String(const char *); /*Display data string on LCD*/
void LCD_String_xy(char, char , const char *);
void LCD_Clear(); /*Clear LCD Screen*/
int i=0;
unsigned char mod1;
unsigned char mod2;
int change1;
int change2;
int main(void)
{ TRISB=0x00;
LCD_Init(); /*Initialize LCD to 5*8 matrix in 4-bit mode*/
while(1){
__delay_ms(300);
i=i+1;
if(i<10){
change1=i;
}
else if(i<100){
change1=i%10;
change2=i/10;
}
else if(i>=100)
{
change1=0;
change2=0;
i=0;
}
mod1=change1+0X30;
mod2=change2+0X30;
LCD_Command(0x80);
LCD_Char('k');
LCD_Char(mod1);
}
}
/****************************Functions********************************/
void LCD_Init()
{
LCD_Port = 0; /*PORT as Output Port*/
MSdelay(15); /*15ms,16x2 LCD Power on delay*/
LCD_Command(0x02); /*send for initialization of LCD
for nibble (4-bit) mode */
LCD_Command(0x28); /*use 2 line and
initialize 5*8 matrix in (4-bit mode)*/
LCD_Command(0x01); /*clear display screen*/
LCD_Command(0x0c); /*display on cursor off*/
LCD_Command(0x06); /*increment cursor (shift cursor to right)*/
}
void LCD_Command(unsigned char cmd )
{
ldata = (ldata & 0x0f) |(0xF0 & cmd); /*Send higher nibble of command first to PORT*/
RS = 0; /*Command Register is selected i.e.RS=0*/
EN = 1; /*High-to-low pulse on Enable pin to latch data*/
__delay_ms(1);
EN = 0;
__delay_ms(1);
ldata = (ldata & 0x0f) | (cmd<<4); /*Send lower nibble of command to PORT */
EN = 1;
__delay_ms(1);
EN = 0;
__delay_ms(1);
}
void LCD_Char(unsigned char dat)
{
ldata = (ldata & 0x0f) | (0xF0 & dat); /*Send higher nibble of data first to PORT*/
RS = 1; /*Data Register is selected*/
EN = 1; /*High-to-low pulse on Enable pin to latch data*/
__delay_ms(10);
EN = 0;
__delay_ms(10);
ldata = (ldata & 0x0f) | (dat<<4); /*Send lower nibble of data to PORT*/
EN = 1; /*High-to-low pulse on Enable pin to latch data*/
__delay_ms(10);
EN = 0;
__delay_ms(10);
}
void LCD_String(const char *msg)
{
while((*msg)!=0)
{
LCD_Char(*msg); //send the data present in pointer to function
msg++; //increments the address
}
}
void LCD_String_xy(char row,char pos,const char *msg)
{
char location=0;
if(row<=1)
{
location=(0x80) | ((pos) & 0x0f); /*Print message on 1st row and desired location*/
LCD_Command(location);
}
else
{
location=(0xC0) | ((pos) & 0x0f); /*Print message on 2nd row and desired location*/
LCD_Command(location);
}
LCD_String(msg);
}
void LCD_Clear()
{
LCD_Command(0x01); /*clear display screen*/
__delay_ms(3);
}
void MSdelay(unsigned int val)
{
unsigned int i,j;
for(i=0;i<val;i++)
for(j=0;j<165;j++); /*This count Provide delay of 1 ms for 8MHz Frequency */
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main(){
int x = 2;
int y = 8;
int *p = &x;
int *q = &y;
printf("1) %p - %d\n",p ,*p);
printf("2) %d - %d\n",p ,*p);
printf("3) %p - %d\n",q ,*q);
printf("4) %d - %d\n",q ,*q);
int **pp = &p;
printf("5) %p\n",&p);
int **qq = &q;
printf("6) %p\n",&q);
return 0;
}
|
C
|
#ifndef RTCDRIVER.H
#define RTCDRIVER.H
#include <Wire.h>
#include "ds3231.h"
#define RTC RTCDriver()
/*
GND to GND
VCC to 5V
SDA to A4
SCL to A5
*/
#define FETCH_INTERVAL 60000
struct ts lastTimestamp;
long lastFetchMillis = -FETCH_INTERVAL;
struct RTCDriver {
void init() const {
Wire.begin();
DS3231_init(DS3231_INTCN);
}
void fetchTime(unsigned long currentMillis) const {
if (currentMillis - lastFetchMillis >= FETCH_INTERVAL || currentMillis < lastFetchMillis) {
lastFetchMillis = currentMillis;
DS3231_get(&lastTimestamp);
printTime();
}
}
unsigned int getHour() const {
return lastTimestamp.hour;
}
void printTime() const {
#ifdef LOG_INFO
char buff[50];
sprintf(buff, "%02d.%02d.%d %02d:%02d:%02d", lastTimestamp.mday, lastTimestamp.mon, lastTimestamp.year, lastTimestamp.hour, lastTimestamp.min, lastTimestamp.sec);
INFO(buff);
#endif
}
};
#endif
|
C
|
#include <stdio.h>
#include <string.h>
void main()
{
char src[20];
char dest[20];
strcpy(src,"beautiful");
strcpy(dest,src);
printf("destination string is %s\n",dest);
}
|
C
|
#include<stdio.h>
#include "pico/stdlib.h"
#include "hardware/gpio.h"
#include "pico/binary_info.h"
#include "hardware/uart.h"
#include "tusb.h" // this header file will handle the problem of losing initial output
// which port we want to use uart0 or uart1
#define UART_ID0 uart0
#define BAUD_RATE 115200
#define UART_ID1 uart1
// We are using pins 0 and 1 for uart0 and pins 6 and 7 for uart1, but see the GPIO function select table in the
// datasheet for information on which other pins can be used.
#define UART0_TX_PIN 0 // pin-1
#define UART0_RX_PIN 1 // pin-2
#define UART1_TX_PIN 4 // pin-6
#define UART1_RX_PIN 5 // pin-7
const uint LED_PIN = 25; // also set LED from gpio.h file
static bool ret;
//****************************Structure and Union for handling LiDAR Data***********
//Dist_L Dist_H Strength_L Strength_H Temp_L Temp_H Checksum
typedef struct{
unsigned short Header;
unsigned short Dist;
unsigned short Strength;
}structLidar;
union unionLidar{
unsigned char Byte[9];
structLidar lidar;
};
unsigned char lidarCounter=0;
union unionLidar Lidar;
//****************************Structure and Union for handling LiDAR Data***********
//****************************Function to read serial data***********
int isLidar(uart_inst_t * uart, union unionLidar * lidar)
{
int loop;
int checksum;
unsigned char serialChar;
while(uart_is_readable(uart))
{
if(lidarCounter > 8)
{
lidarCounter=0;
return 0; // something wrong
}
serialChar = uart_getc(uart); // Read a single character to UART.
lidar->Byte[lidarCounter]= serialChar;
switch(lidarCounter++)
{
case 0:
case 1:
if(serialChar !=0x59)
lidarCounter=0;
break;
case 8: // checksum
checksum=0;
lidarCounter=0;
for(loop=0;loop<8;loop++)
checksum+= lidar->Byte[loop];
if((checksum &0xff) == serialChar)
{
//printf("checksum ok\n");
lidar->lidar.Dist = lidar->Byte[2] | lidar->Byte[3] << 8;
lidar->lidar.Strength = lidar->Byte[4] | lidar->Byte[5] << 8;
return 1;
}
//printf("bad checksum %02x != %02x\n",checksum & 0xff, serialChar);
}
}
return 0;
}
//****************************Function to read serial data***********
//****************************Main Function**************************
int main(){
//******************************************************************
// add some binary info
// we need to add pico/binary_info.h for this.
bi_decl(bi_program_description("This is a program to read from UART!"));
bi_decl(bi_1pin_with_name(LED_PIN, "On-board LED"));
// add binary info for uart0 and uart1
bi_decl(bi_1pin_with_name(UART0_TX_PIN, "pin-0 for uart0 TX"));
bi_decl(bi_1pin_with_name(UART0_RX_PIN, "pin-1 for uart0 RX"));
bi_decl(bi_1pin_with_name(UART1_TX_PIN, "pin-5 for uart1 TX"));
bi_decl(bi_1pin_with_name(UART1_RX_PIN, "pin-6 for uart1 RX"));
//******************************************************************
// Enable UART so we can print status output
stdio_init_all();
gpio_init(LED_PIN); // initialize pin-25
gpio_set_dir(LED_PIN, GPIO_OUT); // set pin-25 in output mode
// Set up our UARTs with the required speed.
uart_init(UART_ID0, BAUD_RATE);
uart_init(UART_ID1, BAUD_RATE);
// Set the TX and RX pins by using the function
// Look at the datasheet for more information on function select
gpio_set_function(UART0_TX_PIN, GPIO_FUNC_UART);
gpio_set_function(UART0_RX_PIN, GPIO_FUNC_UART);
gpio_set_function(UART1_TX_PIN, GPIO_FUNC_UART);
gpio_set_function(UART1_RX_PIN, GPIO_FUNC_UART);
//************************************************************
cdcd_init();
printf("waiting for usb host");
while (!tud_cdc_connected()) {
printf(".");
sleep_ms(500);
}
printf("\nusb host detected!\n");
//************************************************************
// In a default system, printf will also output via the default UART
sleep_ms(5000);
ret = uart_is_enabled (uart1); // pass UART_ID1 or uart1 both are okay
if(ret == true){
printf("UART-1 is enabled\n");
}
printf("Ready to read data from Benewake LiDAR\n");
while(true){
gpio_put(LED_PIN, 0);
sleep_ms(100);
gpio_put(LED_PIN, 1);
if(isLidar(UART_ID1,&Lidar))
{
// ok we got valid data
// Here we utilized the Union
printf("Dist:%u Strength:%u \n",\
Lidar.lidar.Dist,\
Lidar.lidar.Strength);
}
}
return 0;
}
|
C
|
#include <stdio.h>
int main(void) {
int x;
float y, total;
scanf("%d%f", &x, &y);
total = x / y;
printf("%.3f km/l\n", total);
return 0;
}
|
C
|
/********************************************************
File Name:pcapanalysis.c
Author:Qingqing Liang
Description:This file include the implemention of the functions
of analyzing the PCAP file and return the result of the statistic.
And list the main function here:
total flow analysis
total_flow* totalflow(total_flow *tf,head_tag *phead,int *s);
ip to ip flow analysis
void iptoipflow(iptoip *itemsip,iptoip *ipflag,head_tag *phead,ip_tag *iphead);
timedelay analysis
void gettimedelay(head_tag *phead,ip_tag *iphead,tcp_tag *tcphead,timedelay **punhandled,timedelay **phandled,int *psyn_num,int *psyn_ack_num);
service analysis
int ClientIsIn(clientnode **root,uint_32 newip,uint_16 newport);
********************************************************/
#include "head.h"
#define PCAP_LEN 24L
#define PACKET_HEAD_LEN sizeof(head_tag)
#define CLIENT_SIZE sizeof(clientnode)
#define SERVER_SIZE sizeof(servernode)
uint_16 changeseq_s(uint_16 y)
{
uint_16 temp;
temp=y&255;
y=y>>8;
temp=temp<<8;
y=y|temp;
return y;
}
uint_32 changeseq_l(uint_32 y){
uint_32 temp3;
uint_32 temp2;
uint_32 temp1;
temp3=y&0xFF0000;
temp2=y&0xFF00;
temp1=y&0xFF;
y=y>>24;
temp3=temp3>>8;
temp2=temp2<<8;
temp1=temp1<<24;
y=y|temp3|temp2|temp1;
return y;
}
static clientnode * NewClientNode(uint_32 newip,uint_16 newport){
clientnode *temp;
temp=(clientnode *)malloc(CLIENT_SIZE);
memset(temp,0,CLIENT_SIZE);
temp->cip=newip;
temp->cport=newport;
return temp;
}
static servernode * NewServerNode(uint_32 newip){
servernode *temp;
temp=(servernode *)malloc(SERVER_SIZE);
memset(temp,0,SERVER_SIZE);
temp->sip=newip;
return temp;
}
/**********************************************************************
function:try to find if the new server is in the Tree.
If in return -1;
If not ,return 1;
root:the pointer to the Sorted Tree storing the server that already has been calculated.
newip:the ip address of the server
*********************************************************************/
static int ServerIsIn(servernode **root,uint_32 newip){
servernode *oncmp;
if(*root==NULL){
*root=NewServerNode(newip);
return 1;
}
oncmp=*root;
while(1){
if(newip<oncmp->sip){
if(oncmp->slc!=NULL){
oncmp=oncmp->slc;
continue;
}
oncmp->slc=NewServerNode(newip);
return 1;
}
if(newip==oncmp->sip)
return -1;
if(newip>oncmp->sip){
if(oncmp->src!=NULL){
oncmp=oncmp->src;
continue;
}
oncmp->src=NewServerNode(newip);
return 1;
}
}
}
/**********************************************************************
function:try to find if the new client is in the Tree.
If in return -1;
If not ,return 1;
root:the pointer to the Sorted Tree storing the client that already has been calculated.
newip:the ip address of the clinet
newport: the source port of the client
*********************************************************************/
static int ClientIsIn(clientnode **root,uint_32 newip,uint_16 newport){
clientnode *oncmp;
int i;
if(*root==NULL)
i=-1;
else
i=1;
if(*root==NULL){
*root=NewClientNode(newip,newport);
return 1;
}
oncmp=(*root);
while(1){
if(newip<oncmp->cip){
if(oncmp->clc!=NULL){
oncmp=oncmp->clc;
continue;
}
oncmp->clc=NewClientNode(newip,newport);
return 1;
}//1
if(newip==oncmp->cip){//2
if(newport<oncmp->cport){
if(oncmp->clc!=NULL){
oncmp=oncmp->clc;
continue;
}
oncmp->clc=NewClientNode(newip,newport);
return 1;
}
if(newport==oncmp->cport){
return -1;
}
if(newport>oncmp->cport){
if(oncmp->crc!=NULL){
oncmp=oncmp->crc;
continue;
}
oncmp->crc=NewClientNode(newip,newport);
return 1;
}
}//2
if(newip>oncmp->cip){//3
if(oncmp->crc!=NULL){
oncmp=oncmp->crc;
continue;
}
oncmp->crc=NewClientNode(newip,newport);
return 1;
}//3
}//4
}
void freeNode(clientnode** root){
if(*root!=NULL){
clientnode *ln=(*root)->clc;
clientnode *rn=(*root)->crc;
free(*root);
*root=NULL;
freeNode(&ln);
freeNode(&rn);
}
return;
}
void freeNodeS(servernode** root){
if(*root!=NULL){
servernode *ln=(*root)->slc;
servernode *rn=(*root)->src;
free(*root);
*root=NULL;
freeNodeS(&ln);
freeNodeS(&rn);
}
return;
}
/******************************************************************
function:get the totalflow of the IPv4 per seconds
return the link of the last node
tf:point to the last node of the link
head_tag:the pcap header of the packets
s:point to the num of the second
******************************************************************/
static total_flow* totalflow(total_flow *tf,head_tag *phead,int *s){
if(tf->sec==phead->sec){
++(tf->packets);
tf->bytes+=phead->packet_len;
}
else if(tf->sec!=phead->sec){
total_flow *tf_temp;
uint_32 j=tf->sec+1;
if(tf->sec==HEAD_FLAG)
j=phead->sec;
for(;j<=phead->sec;j++){
++*s;
tf_temp=(total_flow *)malloc(TOTAL_FLOW_SIZE);
memset(tf_temp,0,TOTAL_FLOW_SIZE);
tf_temp->sec=j;
tf_temp->nextsec=NULL;
if(j==phead->sec){
tf_temp->packets=1;
tf_temp->bytes=phead->packet_len;
}
tf->nextsec=tf_temp;
tf=tf_temp;
}
}
return tf;
}
static void InsertToChain(iptoip *pb,iptoip *pn,uint_32 src,uint_32 des,head_tag *phead){
iptoip *newip;
do
{
if(src<pn->src){
newip=(iptoip *)malloc(sizeof(iptoip));
memset(newip,0,sizeof(iptoip));
newip->src=src;
newip->des=des;
newip->packets=1;
newip->bytes=phead->packet_len;
newip->nextip=pn;
pb->nextip=newip;
break;
}
if(src==pn->src){
if(des<pn->des){
newip=(iptoip *)malloc(sizeof(iptoip));
memset(newip,0,sizeof(iptoip));
newip->src=src;
newip->des=des;
newip->packets=1;
newip->bytes=phead->packet_len;
newip->nextip=pn;
pb->nextip=newip;
break;
}
if(des==pn->des){
++pn->packets;
pn->bytes+=phead->packet_len;
break;
}
if(des>pn->des){
if(pn->nextip==NULL){
newip=(iptoip *)malloc(sizeof(iptoip));
memset(newip,0,sizeof(iptoip));
newip->src=src;
newip->des=des;
newip->packets=1;
newip->bytes=phead->packet_len;
newip->nextip=NULL;
pn->nextip=newip;
break;
}
pb=pn;
pn=pn->nextip;
continue;
}
}
if(src>pn->src){
if(pn->nextip==NULL){
newip=(iptoip *)malloc(sizeof(iptoip));
memset(newip,0,sizeof(iptoip));
newip->src=src;
newip->des=des;
newip->packets=1;
newip->bytes=phead->packet_len;
newip->nextip=NULL;
pn->nextip=newip;
break;
}
pb=pn;
pn=pn->nextip;
continue;
}
}while(1);
}
/******************************************************************************
function:get the ip to ip flow
itemsip:Array head of the store of the flow
ipflag:the new node of the package information
phead: the pcap header of the current package
iphead: the ip header of the current package
***************************************************************************/
void iptoipflow(iptoip *itemsip,iptoip *ipflag,head_tag *phead,ip_tag *iphead){
uint_16 lowip;
uint_16 highip;
uint_16 items;
iptoip *pnext=NULL;
iptoip *pbefore=NULL;
lowip=iphead->src_ip>>24;
highip=iphead->des_ip>>24;
items=lowip*highip;
if(itemsip[items].nextip==NULL){ //2
itemsip[items].src=iphead->src_ip;
itemsip[items].des=iphead->des_ip;
itemsip[items].bytes+=phead->packet_len;
itemsip[items].packets+=1;
itemsip[items].nextip=ipflag;
}
else if(itemsip[items].nextip==ipflag){ //3
if(itemsip[items].src==iphead->src_ip&&itemsip[items].des==iphead->des_ip){//4
itemsip[items].bytes+=phead->packet_len;
itemsip[items].packets+=1;
} //4
else{
pnext=(iptoip *)malloc(sizeof(iptoip));
memset(pnext,0,sizeof(iptoip));
pnext->src=iphead->src_ip;
pnext->des=iphead->des_ip;
pnext->bytes+=phead->packet_len;
pnext->packets+=1;
pnext->nextip=NULL;
itemsip[items].nextip=pnext;
pnext=NULL;
}
}
else{
if(itemsip[items].src==iphead->src_ip&&itemsip[items].des==iphead->des_ip){//4
itemsip[items].bytes+=phead->packet_len;
itemsip[items].packets+=1;
}
else{
pnext=itemsip[items].nextip;
pbefore=&itemsip[items];
InsertToChain(pbefore,pnext,iphead->src_ip,iphead->des_ip,phead);
}
}
}
void JoinLink(timedelay* join,timedelay **head){
timedelay *swap;
timedelay *beforeswap;
swap=*head;
if(*head==NULL){
*head=join;
join->nextDelay=NULL;
//printf("rm head\t");
return;
}
while(1){
if(join->add.src_ip<swap->add.src_ip){
// printf("rm small\t");
if(swap==*head){
join->nextDelay=*head;
*head=join;
return;
}
beforeswap->nextDelay=join;
join->nextDelay=swap;
return;
}
else if(join->add.src_ip==swap->add.src_ip){
if(join->add.des_ip<=swap->add.des_ip){
if(swap==*head){
// printf("rm des<= head\t");
join->nextDelay=*head;
*head=join;
return;
}
// printf("rm des<= mid\t");
beforeswap->nextDelay=join;
join->nextDelay=swap;
return;
}
if(join->add.des_ip>swap->add.des_ip){
if(swap->nextDelay==NULL){
swap->nextDelay=join;
join->nextDelay=NULL;
return;
}
beforeswap=swap;
swap=swap->nextDelay;
continue;
}
}
else if(join->add.src_ip>swap->add.src_ip){
if(swap->nextDelay==NULL){
// printf("rm big\t");
swap->nextDelay=join;
join->nextDelay=NULL;
return;
}
beforeswap=swap;
swap=swap->nextDelay;
continue;
}
}
}
static int match(address *s,address *c){
if(s->src_ip==c->des_ip&&s->des_ip==c->src_ip&&s->src_port==c->des_port&&s->des_port==c->src_port)
return 0;
return -1;
}
static int equal(address *s,address *c){
if(s->src_ip==c->src_ip&&s->des_ip==c->des_ip&&s->src_port==c->src_port&&s->des_port==c->des_port)
return 0;
return -1;
}
static void initdelay(timedelay *getinit,ip_tag* iphead,tcp_tag *tcphead,head_tag *packethead){
getinit->add.src_ip=iphead->src_ip;
getinit->add.des_ip=iphead->des_ip;
getinit->add.src_port=tcphead->src_port;
getinit->add.des_port=tcphead->des_port;
getinit->flag=1;
getinit->sec_f=packethead->sec;
getinit->millsec_f=packethead->millsec;
}
static int JoinUnhandle(timedelay *join,timedelay **Unhead){
timedelay *pb;
timedelay *pn;
if(*Unhead==NULL){
(*Unhead)=join;
join->nextDelay=NULL;
//printf("first join\n");
return 0;
}
pn=*Unhead;
while(1){
if(join->add.src_ip<pn->add.src_ip){
// printf("small join\n");
if(pn==*Unhead){
join->nextDelay=pn;
*Unhead=join;
return 0;
}
pb->nextDelay=join;
join->nextDelay=pn;
return 0;
}
if(join->add.src_ip==pn->add.src_ip){
if(equal(&(join->add),&(pn->add))==0){
// printf("join failure\n");
return -1;
}
// printf("equla join\n");
if(pn==*Unhead){
join->nextDelay=pn;
*Unhead=join;
return 0;
}
pb->nextDelay=join;
join->nextDelay=pn;
return 0;
}
if(join->add.src_ip>pn->add.src_ip){
if(pn->nextDelay==NULL){
// printf("big join\n");
pn->nextDelay=join;
join->nextDelay=NULL;
return 0;
}
pb=pn;
pn=pn->nextDelay;
continue;
}
}
return -1;
}
static int MatchUnhandle(ip_tag* ipinfo,tcp_tag* tcpinfo,head_tag *packetinfo,timedelay *Unhead){
timedelay *temp;
//printf("%u %u ",packetinfo->sec,packetinfo->millsec);
if(Unhead==NULL)
return -1;
address merage;
merage.src_ip=ipinfo->src_ip;
merage.des_ip=ipinfo->des_ip;
merage.src_port=tcpinfo->src_port;
merage.des_port=tcpinfo->des_port;
temp=Unhead;
while(1){
if(merage.des_ip<temp->add.src_ip)
return -1;
if(match(&(temp->add),&merage)==0){
temp->sec_s=packetinfo->sec;
temp->millsec_s=packetinfo->millsec;
if(temp->millsec_s<temp->millsec_f){
temp->millsec_f=(temp->millsec_s+1000000)-temp->millsec_f;
temp->sec_f=temp->sec_s-temp->sec_f-1;
}
else{
temp->millsec_f=(temp->millsec_s)-temp->millsec_f;
temp->sec_f=temp->sec_s-temp->sec_f;
}
temp->flag=2;
// printf("merage!\n");
return 0;
}
if(temp->nextDelay==NULL)
return -1;
temp=temp->nextDelay;
}
return -1;
}
static int RemoveUnhandle(ip_tag* ipinfo,tcp_tag* tcpinfo,head_tag *packetinfo,timedelay **Unhead,timedelay **Handled){
timedelay *temp;
timedelay *swap;
uint_32 temps;
uint_32 tempm;
if(*Unhead==NULL)
return -1 ;
address merage;
merage.src_ip=ipinfo->src_ip;
merage.des_ip=ipinfo->des_ip;
merage.src_port=tcpinfo->src_port;
merage.des_port=tcpinfo->des_port;
temp=*Unhead;
while(1){
if(merage.src_ip<temp->add.src_ip){
// printf("remove failure\n");
return -1;
}
if(equal(&merage,&(temp->add))==0){
temps=packetinfo->sec;
tempm=packetinfo->millsec;
if(tempm<temp->millsec_s){
temp->millsec_s=(tempm+1000000)-temp->millsec_s;
temp->sec_s=temps-temp->sec_s-1;
}
else{
temp->millsec_s=tempm-temp->millsec_s;
temp->sec_s=temps-temp->sec_s;
}
temp->flag=3;
if(temp==*Unhead){
*Unhead=temp->nextDelay;
}
else{
swap->nextDelay=temp->nextDelay;
}
// printf("%x %x yesremove\n",temp->add.src_ip,temp->add.des_ip);
JoinLink(temp,Handled);
/* temp->nextDelay=*Handled;
*Handled=temp;*/
return 0;
}
if(temp->nextDelay==NULL){
// printf("remove bad fail\n");
return -1;
}
swap=temp;
temp=temp->nextDelay;
}
}
/******************************************************************
function:get the timdelay of the ip to ip
phead:the pcap header of the current package
iphead:the ip header of the current package
tcphead:the tcp header of the current package
punhadled: point to the point of the unhandled link
phandled:point to the point of the handled link
psyn_num:point to the num of the syn package
psyn_ack_num:point to the nun of the syn_ack package
******************************************************************/
void gettimedelay(head_tag *phead,ip_tag *iphead,tcp_tag *tcphead,timedelay **punhandled,timedelay **phandled,int *psyn_num,int *psyn_ack_num){
timedelay *temp=NULL;
if(tcphead->flags==FLAG_SYN){
temp=(timedelay *)malloc(sizeof(timedelay));
memset(temp,0,sizeof(timedelay));
initdelay(temp,iphead,tcphead,phead);
if(JoinUnhandle(temp,punhandled)==0){
++*psyn_num;
}
return;
}
if(tcphead->flags==FLAG_SYN_ACK&&(*psyn_num)>0){
if(MatchUnhandle(iphead,tcphead,phead,*punhandled)==0){
++*psyn_ack_num;
}
return;
}
if(tcphead->flags==FLAG_ACK&&*psyn_ack_num>0){
if(RemoveUnhandle(iphead,tcphead,phead,punhandled,phandled)==0){
--*psyn_num;
--*psyn_ack_num;
}
return;
}
}
void del_unhandled(timedelay *un){
timedelay *swap;
timedelay *swap_next;
swap=un;
while(swap!=NULL){
swap_next=swap->nextDelay;
free(swap);
swap=swap_next;
}
un=NULL;
swap=NULL;
swap_next=NULL;
}
void handled_merage(timedelay *handled){
timedelay *swap=handled;
timedelay *swap_next;
int count=1;
while(swap!=NULL){
if(swap->nextDelay==NULL)
break;
swap_next=swap->nextDelay;
if(swap->add.src_ip==swap_next->add.src_ip&&swap->add.des_ip==swap_next->add.des_ip){
swap->sec_f+=swap_next->sec_f;
swap->millsec_f+=swap_next->millsec_f;
swap->sec_s+=swap_next->sec_s;
swap->millsec_s+=swap_next->millsec_s;
swap->nextDelay=swap_next->nextDelay;
count++;
free(swap_next);
continue;
}
/*handle the sec*/
uint_32 sectemp;
sectemp=swap->sec_f%count;
swap->sec_f=(swap->sec_f-sectemp)/count;
swap->millsec_f/=count;
swap->millsec_f+=sectemp/count*1000000;
sectemp=swap->sec_s%count;
swap->sec_s=(swap->sec_s-sectemp)/count;
swap->millsec_s/=count;
swap->millsec_s+=sectemp/count*1000000;
swap=swap->nextDelay;
count=1;
}
}
/************************************
function:the interface to the outside
fp: the pcap file pointer
tf_head:the link header point of the total flow
s:point to the num of the seconds
itemsip:the array header the stroing
num:size fo the array of ip to ip flow
ptimedelay_head:the pointer the pointer of the timdelay linker header
pservice:header of the array
******************************/
void getFileInfo(
FILE *fp,
total_flow *tf_head,int *s,
iptoip *itemsip,int num,iptoip *temp,
timedelay **ptimedelay_head,
service *pservice
)
{
fseek(fp,PCAP_LEN,SEEK_SET);
head_tag packet_head;
uint_16 type;
ip_tag packet_ip;
tcp_tag segment_tcp;
udp_tag datagrame_udp;
uint_8 ipheadlen;
uint_32 unread_tcp;
uint_32 unread_udp;
/*total flow init begin*/
total_flow *tf=tf_head;
/*total flow init end*/
/*iptoip flow init begin*/
memset(itemsip,0,num*sizeof(iptoip));
/*iptoip flow init end*/
/*timedelay init begin*/
timedelay *unhandled=NULL;
timedelay *handled=NULL;
uint_32 syn_num=0;
uint_32 syn_ack_num=0;
/*timedelay init end*/
/*service init begin*/
uint_16 porttemp,portswap;
/*service init end*/
while(1){
if(fread(&packet_head,PACKET_HEAD_LEN,1,fp)!=1)
break;
fseek(fp,12L,1);
fread(&type,sizeof(uint_16),1,fp);
if(type!=PROTOCOL_IP){
fseek(fp,packet_head.pcap_len-14,1);
continue;
}
/*total flow operation begin*/
tf=totalflow(tf,&packet_head,s);
/*total flow operation end*/
fread(&packet_ip,sizeof(ip_tag),1,fp);
/*iptoip flow operation begin*/
iptoipflow(itemsip,temp,&packet_head,&packet_ip);
/*iptoip flow operation end*/
if(packet_ip.protocol!=PROTOCOL_TCP&&packet_ip.protocol!=PROTOCOL_UDP){
fseek(fp,packet_head.pcap_len-34,1);
continue;
}
ipheadlen=packet_ip.version_headlen&0x0F;
if(ipheadlen==5){
unread_tcp=packet_head.pcap_len-54;
unread_udp=packet_head.pcap_len-42;
}
else{
ipheadlen=(ipheadlen-5)*4;
unread_tcp=packet_head.pcap_len-54-ipheadlen;
unread_udp=packet_head.pcap_len-42-ipheadlen;
fseek(fp,ipheadlen,1);
}
switch(packet_ip.protocol){
case PROTOCOL_TCP:{
fread(&segment_tcp,sizeof(tcp_tag),1,fp);
/*timedelay operation begin*/
gettimedelay(&packet_head,&packet_ip,&segment_tcp,&unhandled,&handled,&syn_num,&syn_ack_num);
/*timedelay operation end*/
/*service op begin*/
porttemp=changeseq_s(segment_tcp.des_port);
portswap=changeseq_s(segment_tcp.src_port);
if(porttemp<1024){
int j=ClientIsIn(&pservice[porttemp].pclient,packet_ip.src_ip,segment_tcp.src_port);
//printf("Later i=%d return=%d ip:%x port:%x\n",i,j,packet_ip.src_ip,segment_tcp.src_port);
if(j==1){
pservice[porttemp].clientnum+=1;
}
// printf("%d server_port:%u\n",i,porttemp);
// printf("%d tcp s:%u d:%u\n",i,segment_tcp.src_port,segment_tcp.des_port);
}
if(portswap<1024){
int k=ServerIsIn(&pservice[portswap].pserver,packet_ip.src_ip);
if(k==1){
pservice[portswap].servernum++;
}
}
/*service op end*/
fseek(fp,unread_tcp,1);
break;
}
case PROTOCOL_UDP:{
fread(&datagrame_udp,sizeof(udp_tag),1,fp);
/*service op begin*/
porttemp=changeseq_s(datagrame_udp.des_port);
portswap=changeseq_s(datagrame_udp.src_port);
if(porttemp<1024){
int j=ClientIsIn(&pservice[porttemp].udppclient,packet_ip.src_ip,datagrame_udp.src_port);
//printf("Later i=%d return=%d ip:%x port:%x\n",i,j,packet_ip.src_ip,segment_tcp.src_port);
if(j==1){
pservice[porttemp].udpclientnum+=1;
}
// printf("%d server_port:%u\n",i,porttemp);
// printf("%d tcp s:%u d:%u\n",i,segment_tcp.src_port,segment_tcp.des_port);
}
if(portswap<1024){
int k=ServerIsIn(&pservice[portswap].udppserver,packet_ip.src_ip);
if(k==1){
pservice[portswap].udpservernum++;
}
}
// printf("%d udp s:%u d:%u\n",i,datagrame_udp.src_port,datagrame_udp.des_port);
/*service op end*/
fseek(fp,unread_udp,1);
break;
}
default:
printf("error!addert\n");
break;
}
continue;
}
/*timdelay operation begin*/
del_unhandled(unhandled);
handled_merage(handled);
*ptimedelay_head=handled;
/*timedelay operarion end*/
}
|
C
|
#include <stdio.h>
void Grid(int n);
int main()
{
int n;
printf("n = ? ");
scanf("%d", &n);
Grid(n);
return 0;
}
void Grid(int n)
{
int j,i;
if(n)
{
printf("");
for(j = 1;j < n;j++)
{
printf("");
}
printf("\n");
for(i = 1;i < n;i++)
{
printf("");
for(j = 1;j < n;j++)
{
printf("");
}
printf("\n");
}
printf("");
for(i = 1;i < n;i++)
{
printf("");
}
printf("");
}
}
|
C
|
#include<stdlib.h>
#include<stdio.h>
unsigned char CautareLiniara(short int *TablouCautare, unsigned char NumarElementeTablou, short int ElementCautat)
{
unsigned char pozitie;
for (pozitie = 0; pozitie < NumarElementeTablou; pozitie++)
if (TablouCautare[pozitie] == ElementCautat)
return pozitie + 1;
return 0;
}
int main()
{
short int TablouCautare[40], ElementCautat;
unsigned char pozitie, NumarElementeTablou;
printf("Dati numarul de elemente al tabloului: ");
scanf("%d", &NumarElementeTablou);
printf("Dati elementele tabloului: ");
for (pozitie = 0; pozitie < NumarElementeTablou; pozitie++)
scanf("%d", &TablouCautare[pozitie]);
printf("Dati elementul de cautat: ");
scanf("%d", &ElementCautat);
printf("%d", CautareLiniara(TablouCautare, NumarElementeTablou, ElementCautat));
system("pause");
return 0;
}
|
C
|
// Name: Li-Ching, Cheng
// Student Number: 143292175
// Email: [email protected]
// Section: GG
// Date: 2018.05.29
#include<stdio.h>
#define _CRT_SECURE_NO_WARNINGS
#define NUMS 3
// Put your code below:
int main(void)
{
int i;
int high, low;
int sumHigh = 0;
int sumLow = 0;
float average;
printf("---=== IPC Temperature Analyzer ===---\n");
for(i=0; i<NUMS; i++) {
do {
printf("Enter the high value for day %d: ", i + 1);
scanf("%d", &high);
printf("\n");
printf("Enter the low value for day %d: ", i + 1);
scanf("%d", &low);
printf("\n");
if (high > 40 || low < -40 || low>high){
printf("Incorrect values, temperatures must be in the range -40 to 40, high must be greater than low.\n\n");
}
else {
sumHigh += high;
sumLow += low;
}
} while (high > 40 || low<-40 || low>high);
}
average = (sumHigh + sumLow) / (NUMS * 2.0f);
printf("The average (mean) temperature was: %.2f\n", average);
return 0;
}
|
C
|
#include "MKL46Z4.h"
#include "board.h"
/**
* @brief Init_Led
* @param[in] void
* @param[in,out] void
* @return void
*/
void Init_Led (void)
{
/* Enable clock for PORTE & PORTD*/
SIM->SCGC5 |= ( SIM_SCGC5_PORTD_MASK
| SIM_SCGC5_PORTE_MASK );
/*
* Initialize the RED LED (PTE5)
*/
PORTE->PCR[29] = PORT_PCR_MUX(1);
/* Set the pins direction to output */
FPTE->PDDR |= RED_LED_PIN;
/* Set the initial output state to high */
FPTE->PSOR |= RED_LED_PIN;
/*
* Initialize the Green LED (PTE5)
*/
/* Set the PTE29 pin multiplexer to GPIO mode */
PORTD->PCR[5]= PORT_PCR_MUX(1);
/* Set the pins direction to output */
FPTD->PDDR |= GREEN_LED_PIN;
/* Set the initial output state to high */
FPTD->PSOR |= GREEN_LED_PIN;
}
|
C
|
#include<stdio.h>
int main(void)
{
int i,j;
puts("(A)");
for ( i = 1; i <= 10; ++i)
{
for (j = 1; j <= i; j++)
{
printf("%s", "*");
}
printf("%s", "\n");
}
printf("\n\n\n");
puts("(B)");
for ( i = 10; i >= 1; i--)
{
for (j = 1; j <= i; j++)
{
printf("%s", "*");
}
printf("\n");
}
printf("\n\n\n");
puts("(C)");
for (i = 1; i <= 10; i++)
{
for (j = 1; j <= 10; j++)
{
if (j >= i)
{
printf("%s", "*");
}
else
{
printf("%s", " ");
}
}
printf("\n");
}
printf("\n\n\n");
puts("(D)");
for (i = 1; i <= 10; i++)
{
for (j = 1; j <= 10; j++)
{
if (j <= (10 - i))
{
printf("%s", " ");
}
else
{
printf("%s", "*");
}
}
printf("\n");
}
system("pause");
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
//On linux need below two
#include <sys/types.h>
#include <sys/wait.h>
//execl will success
#define IFCONFIG_CMD_PATH "/sbin/ifconfig"
//execl will fail intentionally
#define IFCONFIG_WRONG_CMD_PATH "/sbin/ifconfigasd"
//Check if table is valid
int is_valid_interface(const char *iface_str) {
pid_t pid = fork(); //Create a child process
int status;
if (pid < 0) {
printf("fork failed (%s)", strerror(errno));
return -1;
} else if (pid == 0) { //child (return value from fork() is 0)
if (execl(IFCONFIG_CMD_PATH, "ifconfig", iface_str, (char *) NULL)) { //如果execl執行成功則永遠不會return
printf("execl failed (%s)\n", strerror(errno));
exit(5); //return status from child
}
//所以不用判斷execl成功的狀態
} else { //parent (return value from fork() is parent’s pid)
wait(&status); //parent先暫停,等待child return後設定其return status (wait()本身會return child pid)
printf("WIFEXITED(status)=%d, WEXITSTATUS(status)=%d\n", WIFEXITED(status), WEXITSTATUS(status));
if (WIFEXITED(status) == 0) { //WIFEXITED不為0為正常退出
printf("Wrong terminate...\n");
return 0;
}
if (WEXITSTATUS(status) != 0) { //WEXITSTATUS為0為正常回傳值
printf("Invalid interface\n");
return 0;
}
}
return 1;
}
int main(int argc, char **argv) {
if (argc != 2) {
printf("Invalid arg number\n");
return 0;
}
const char *iface_str = argv[1]; //en0
if (is_valid_interface(iface_str)) {
printf("%s is valid\n", iface_str);
}
sleep(10);
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAXLENOPERAND 20
#define EMPTYPOS 10
#define UNDEFCHAR '*'
#define UNDEFVAL -1
typedef struct letravalor{
char letra;
int valor;
} SOLC;
SOLC Solucao[11] = {
{UNDEFCHAR,UNDEFVAL}, {UNDEFCHAR,UNDEFVAL}, {UNDEFCHAR,UNDEFVAL},
{UNDEFCHAR,UNDEFVAL}, {UNDEFCHAR,UNDEFVAL}, {UNDEFCHAR,UNDEFVAL},
{UNDEFCHAR,UNDEFVAL}, {UNDEFCHAR,UNDEFVAL}, {UNDEFCHAR,UNDEFVAL},
{UNDEFCHAR,UNDEFVAL}, {UNDEFCHAR,0}};
int DigitoVisitado[10] = {0};
int NLetras;
int Problem[10][MAXLENOPERAND+1];
int Length[10];
int resolve(int row, int column, int last, int carry, int n);
int last_row(int column, int last, int carry, int n);
int posicao(char c);
int soma_coluna(int column,int carry,int nr);
int min_left(int row,int column,int n);
int posicao(char c) {
int i;
for(i=0; i< NLetras; i++)
if (Solucao[i].letra == c)
return i;
Solucao[NLetras++].letra = c;
return NLetras-1;
}
int main(){
int j, n, i, numsols = 0, maxlen;
char linha[MAXLENOPERAND+2];
Solucao[EMPTYPOS].valor = 0;
for (i=0; i< 10; i++)
Solucao[i].valor = UNDEFVAL;
scanf("%d",&n);
NLetras = 0;
for (i=0; i<n;i++) {
scanf("%s",linha);
Length[i] = (int) strlen(linha);
for(j=0; linha[j] != '\0'; j++)
Problem[i][Length[i]-1-j] = posicao(linha[j]);
for(; j < MAXLENOPERAND+1; j++)
Problem[i][j] = EMPTYPOS;
}
maxlen = 0;
for (i=0; i <n-1; i++)
if (Length[i] > maxlen)
maxlen = Length[i];
if (Length[n-1] > maxlen+1)
return 0;
if (Length[n-1] > maxlen)
maxlen = Length[n-1];
numsols = resolve(0,0,maxlen-1,0,n);
printf("%d\n",numsols);
return 0;
}
int soma_coluna(int column,int carry,int nr){
int i, sum = carry;
for (i=0; i < nr; i++)
sum += Solucao[Problem[i][column]].valor;
return sum;
}
#ifdef DEBUG_PRINTSOLS
void escreve_sol(){
int i;
for (i=0; i< NLetras; i++)
printf("(%c,%d) ",Solucao[i].letra,Solucao[i].valor);
putchar(10);
}
#endif
int last_row(int column, int last, int carry, int n) {
int d, sols, soma;
soma = soma_coluna(column,carry,n-1);
d = soma % 10;
if (d == 0 && min_left(n-1,column,n) != 0)
return 0;
if (Solucao[Problem[n-1][column]].valor != UNDEFVAL) {
if (d != Solucao[Problem[n-1][column]].valor)
return 0;
if (column != last)
return resolve(0,column+1,last,soma/10,n);
if (soma/10 != 0)
return 0;
#ifdef DEBUG_PRINTSOLS
escreve_sol();
#endif
return 1;
}
else {
if (DigitoVisitado[d])
return 0;
if (column == last) {
if (soma/10 != 0)
return 0;
#ifdef DEBUG_PRINTSOLS
Solucao[Problem[n-1][column]].valor = d;
escreve_sol();
Solucao[Problem[n-1][column]].valor = UNDEFVAL;
#endif
return 1;
}
DigitoVisitado[d] = 1;
Solucao[Problem[n-1][column]].valor = d;
sols = resolve(0,column+1,last,soma/10,n);
DigitoVisitado[d] = 0;
Solucao[Problem[n-1][column]].valor = UNDEFVAL;
return sols;
}
}
int resolve(int row, int column, int last, int carry, int n) {
int d, dmin, sols;
if (row == n-1)
return last_row(column,last,carry,n);
if (Solucao[Problem[row][column]].valor != UNDEFVAL)
return resolve(row+1,column,last,carry,n);
sols = 0;
dmin = min_left(row,column,n);
for (d=dmin; d < 10; d++)
if (!DigitoVisitado[d]) {
DigitoVisitado[d] = 1;
Solucao[Problem[row][column]].valor = d;
sols += resolve(row+1,column,last,carry,n);
Solucao[Problem[row][column]].valor = UNDEFVAL;
DigitoVisitado[d] = 0;
}
return sols;
}
int min_left(int row,int column,int n) {
int i = 0;
if (column == Length[row]-1)
return 1;
for(i=0; i< n; i++)
if (Problem[row][column] == Problem[i][Length[i]-1])
return 1;
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
struct node
{
int value;
struct node *left, *right;
};
struct node *newNode(int n)
{
struct node *temp = (struct node *)malloc(sizeof(struct node));
temp->value = n;
temp->left = temp->right = NULL;
return temp;
}
void inorder(struct node *root)
{
if (root != NULL)
{
inorder(root->left);
printf("%d ", root->value);
inorder(root->right);
}
}
struct node* insert(struct node* node, int value)
{
if (node == NULL)
return newNode(value);
if (value < node->value)
node->left = insert(node->left, value);
else
node->right = insert(node->right, value);
return node;
}
struct node * minValueNode(struct node* node)
{
struct node* current = node;
while (current && current->left != NULL)
current = current->left;
return current;
}
struct node* deleteNode(struct node* root, int value)
{
if (root == NULL) return root;
if (value < root->value)
root->left = deleteNode(root->left, value);
else if (value > root->value)
root->right = deleteNode(root->right, value);
else
{
if (root->left == NULL)
{
struct node *temp = root->right;
free(root);
return temp;
}
else if (root->right == NULL)
{
struct node *temp = root->left;
free(root);
return temp;
}
struct node* temp = minValueNode(root->right);
root->value = temp->value;
root->right = deleteNode(root->right, temp->value);
}
return root;
}
void main()
{
struct node *root = NULL;
root = insert(root, 15);
root = insert(root, 18);
root = insert(root, 14);
root = insert(root, 11);
root = insert(root, 49);
root = insert(root, 54);
root = insert(root, 75);
root = insert(root, 01);
printf("Inorder traversal of the given tree \n");
inorder(root);
printf("\nDelete 02\n");
root = deleteNode(root, 02);
printf("Inorder traversal of the given tree \n");
inorder(root);
printf("\nDelete 14\n");
root = deleteNode(root, 14);
printf("Inorder traversal of the given tree \n");
inorder(root);
printf("\nDelete 08\n");
root = deleteNode(root, 18);
printf("Inorder traversal of the modified tree \n");
inorder(root);
printf("\nDelete 01\n");
root = deleteNode(root, 01);
printf("Inorder traversal of the modified tree \n");
inorder(root);
}
|
C
|
#include "tool.h"
#include <errno.h>
#include <sys/socket.h>
#define BUFLEN 128
void process(int sockfd)
{
char buf[BUFLEN], msg[BUFLEN];
FILE *fp;
int nbytes;
nbytes = read(sockfd, buf, BUFLEN);
guard(nbytes >= 0, "read failed");
if (nbytes == 0)
{
/* End-of-file */
close(sockfd);
}
strncpy(msg, buf, nbytes);
msg[nbytes] = '\0';
fprintf(stderr, "Server: got message: '%s'\n", msg);
if ((fp = popen("/bin/date", "r")) == NULL)
{
sprintf(buf, "error: %s\n", strerror(errno));
send(sockfd, buf, strlen(buf), 0);
}
else
{
while (fgets(buf, BUFLEN, fp) != NULL)
send(sockfd, buf, strlen(buf), 0);
pclose(fp);
}
close(sockfd);
}
|
C
|
/* Modo Synchronization from HUB
* This code is used to calculate the time difference from Node 1
*/
#include <unistd.h>
#include <signal.h>
#include <stdint.h>
#include <thread>
#include "mraa.hpp"
#define fSCLK 8000000
int running = 0;
int i,j=0;
int maxDif, error,restartCount = 0;
int timeNode1, timeNode2, prevTime1, prevTime2, timeNodesDrift, currentDiff1, currentDiff2, maxNodeDrift = 0;
static volatile bool timerFlag = false;
void
sig_handler(int signo)
{
if (signo == SIGINT) {
printf("\n MaxDifference Between Transmissions = %d \n Received_OK= %d \n error = %d \n Total Lost %d\n Nr DataLost %d\n", maxDif, j, error, i,restartCount);
printf("\n Max Drifting between Noded = %d", maxNodeDrift);
printf("\nClosing spi nicely\n");
running = -1;
}
}
void setInterval(){ // Manual implementation of setInterval Function
while(running == 0){
timerFlag = true;
usleep(950);
}
}
int main(){
FILE * fileWrite;
int firstFlag = 20;
fileWrite=fopen("DataIntCol.txt","w");
if(!fileWrite) {
printf("File not Opened");
return 0;
}
/* GPIO */
mraa::Gpio* gpio_cs = new mraa::Gpio(19);
mraa::Gpio* gpio_sync = new mraa::Gpio(20);
if (gpio_cs == NULL || gpio_sync==NULL) {
return mraa::ERROR_UNSPECIFIED;
}
mraa::Result response = gpio_cs->dir(mraa::DIR_OUT);
response = gpio_sync->dir(mraa::DIR_OUT);
if (gpio_sync->dir(mraa::DIR_OUT) != mraa::SUCCESS || gpio_cs->dir(mraa::DIR_OUT) !=mraa::SUCCESS) {
mraa::printError(response);
return 1;
}
signal(SIGINT, sig_handler);
mraa::Spi* spi;
spi = new mraa::Spi(5);
spi->frequency(fSCLK );
spi->mode(mraa::SPI_MODE3);
spi->lsbmode(0);
spi->bitPerWord(8);
// temporal
std::thread t1(setInterval);
uint8_t rxBuf[50];
uint8_t txBuf[4] = {1,2,3,4};
uint8_t* recv;
printf("\nSynchronization from HUB\n");
while (running == 0) {
if (timerFlag){
timerFlag = false;
prevTime1 = timeNode1;
gpio_sync->write(1); // trigger getData signal
usleep(400); // Time required for each node to get its data
gpio_sync->write(0); // trigger getData signal
gpio_cs->write(0);
if (spi->transfer(NULL, rxBuf,50) == mraa::SUCCESS) {
gpio_cs->write(1);
if (rxBuf[0] == 0xFF && rxBuf[25] == 0xFF ){ //Temporal Added to not include the frames not received
fprintf(fileWrite,"\nFrame Not Received");
}else{
timeNode1 = (rxBuf[4]<<24) | (rxBuf[3]<<16) | (rxBuf[2]<<8) |rxBuf[1] ;
currentDiff1 = timeNode1-prevTime1;
if(timeNode1 !=0){
j++;
fprintf(fileWrite,"\nDifBetTX_Node1: %d ; DifBetTX_Node2: %d \n", currentDiff1, currentDiff2);
}else{
i++;
}
}
}else { // else transfer not completed
error++;
}
memset(rxBuf,0,50);
} //end of IF timerFlag
}
delete spi;
delete gpio_cs;
// std::terminate();
// t1.~thread();
fseek (fileWrite, 0, SEEK_SET);
fprintf(fileWrite,"\n MaxDifference Between Transmissions = %d \n Received_OK= %d \n error = %d \n Total Lost %d\n Nr DataLost %d\n", maxDif, j, error, i,restartCount);
fprintf(fileWrite,"\nMax Drifting between Noded = %d", maxNodeDrift);
fprintf(fileWrite,"\nClosing spi nicely\n");
fclose(fileWrite);
return mraa::SUCCESS;
}
|
C
|
#include <stdio.h>
#include <pthread.h>
#include "mythreads.h"
#define NUMCPUS 5
#define ITERATIONS 1000000
#define THRESHOLD 1024
typedef struct counter_t{
int global;
pthread_mutex_t globalLock;
int local[NUMCPUS];
pthread_mutex_t glock[NUMCPUS];
int threshold;
}counter_t;
typedef struct __cthread
{
counter_t * counter;
int threadID;
int amt;
} cthread;
void init(counter_t *c , int threshold) {
c -> threshold = threshold;
c -> global = 0;
Pthread_mutex_init(&c-> globalLock, NULL);
int i = 0;
for(i=0; i< NUMCPUS; i++) {
c->local[i] = 0;
Pthread_mutex_init(&c-> glock[i], NULL);
}
}
void update(counter_t *c , int threadID, int amt) {
Pthread_mutex_lock(&c -> glock[threadID]);
c -> local[threadID] += amt;
if(c -> local[threadID] >= c-> threshold){
Pthread_mutex_lock(&c->globalLock);
c->global += c->local[threadID];
Pthread_mutex_unlock(&c->globalLock);
c->local[threadID] = 0;
}
Pthread_mutex_unlock(&c -> glock[threadID]);
}
int get(counter_t *c){
Pthread_mutex_lock(&c ->globalLock);
int val = c->global;
Pthread_mutex_unlock(&c -> globalLock);
return val;
}
void* worker(void *arg){
cthread * ct = (cthread *) arg;
for (int i=0; i < ITERATIONS; i++) {
update(ct->counter, ct->threadID, ct->amt);
}
return (void *) NULL;
}
int main() {
pthread_t p0,p1,p2,p3,p4;
counter_t counter;
cthread cp0, cp1, cp2, cp3, cp4;
cp0.counter = &counter;
cp0.threadID = 0;
cp0.amt = 1;
cp1.counter = &counter;
cp1.threadID = 1;
cp1.amt = 1;
cp2.counter = &counter;
cp2.threadID = 2;
cp2.amt = 1;
cp3.counter = &counter;
cp3.threadID = 3;
cp3.amt = 1;
cp4.counter = &counter;
cp4.threadID = 4;
cp4.amt = 1;
init(&counter, THRESHOLD);
struct timespec time_start,time_stop;
long sum = 0;
clock_gettime(CLOCK_MONOTONIC_RAW, &time_start);
pthread_create(&p0, NULL, worker,&cp0);
pthread_create(&p1, NULL, worker,&cp1);
pthread_create(&p2, NULL, worker,&cp2);
pthread_create(&p3, NULL, worker,&cp3);
pthread_create(&p4, NULL, worker,&cp4);
pthread_join(p0,NULL);
Pthread_join(p1,NULL);
Pthread_join(p2,NULL);
Pthread_join(p3,NULL);
Pthread_join(p4,NULL);
clock_gettime(CLOCK_MONOTONIC_RAW, &time_stop);
sum = time_stop.tv_nsec;
if (time_start.tv_nsec > time_stop.tv_nsec) {
sum += ((long) time_stop.tv_sec - (long) time_start.tv_sec) * 1000000000;
}
sum = (sum - time_start.tv_nsec);
double time = (double)sum/100000000;
printf("time taken %f s\n", time);
printf("%s %d \n", "counter value", get(cp4.counter));
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_num_player.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gleonett <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/06/22 17:41:54 by gleonett #+# #+# */
/* Updated: 2019/06/22 17:41:56 by gleonett ### ########.fr */
/* */
/* ************************************************************************** */
#include "visualizer.h"
int get_num_player(t_visualizer *vis, int x, int y)
{
const int num_pixel = get_num_pixel(vis, x, y);
if (ft_memcmp(WIN->data + num_pixel, PICTURES.player1,
sizeof(int) * SIDE_SQUARE) == 0)
return (0);
if (ft_memcmp(WIN->data + num_pixel, PICTURES.player2,
sizeof(int) * SIDE_SQUARE) == 0)
return (1);
if (ft_memcmp(WIN->data + num_pixel, PICTURES.player3,
sizeof(int) * SIDE_SQUARE) == 0)
return (2);
if (ft_memcmp(WIN->data + num_pixel + SIZE_FIELD_X,
PICTURES.player4 + SIDE_SQUARE, sizeof(int) * SIDE_SQUARE) == 0)
return (3);
return (4);
}
|
C
|
#include<stdio.h>
int main()
{
int n,sum;
while(scanf("%d",&n) != EOF)
{
sum = n * (n + 1) / 2;
printf("%d\n",sum);
}
return 0;
}
|
C
|
#include<stdio.h>
#include<conio.h>
#include<math.h>
int fact(int x)
{
int f=1,i;
for(i=1;i<=x;i++)
{
f=f*i;
}
return f;
}
int main()
{
int x[20],y[20],i,n,z[10],j=0,k;
float u,sum,t=1,a,h;
printf("enter value of n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&x[i]);
scanf("%d",&y[i]);
}
h=x[1]-x[0];
printf("from where we have to find value");
scanf("%f",&a);
u=(a-x[0])/h;
for(k=0;k<n-1;k++)
{
z[j++]=y[0];
for(i=0;i<n-1-k;i++)
{
int tmp=y[i+1]-y[i];
y[i]=tmp;
//printf("%d",tmp);
}
//printf(" ");
}
z[j++]=y[0];
/*for(i=0;i<j;i++)
printf("%d",z[i]);*/
sum=z[0];
i=1;
//printf("%f",u);
while(i<n)
{
t=(u*t)/i;
sum+=(t*z[i]);
i++;
u=u-1;
// printf("%f\n",u);
}
printf("%f",sum);
return 0;
}
|
C
|
#include <gb/gb.h>
#include "player.sprites.h"
// Id ("nb") of the two sprites used to represent the player
#define PLAYER_SPRITE_L_ID 0
#define PLAYER_SPRITE_R_ID 1
// Animations data for the players sprites
UINT8 PLAYER_SPRITE_ANIM_L[] = {
// LEN | FLIP | TILES ID | DIRECTION
4, 0, 0 , 4, 0, 8, // Down
4, 0, 12, 16, 12, 20, // Up
4, 0, 24, 28, 24, 32, // Right
4, 1, 26, 30, 26, 34, // Left
};
UINT8 PLAYER_SPRITE_ANIM_R[] = {
// LEN | FLIP | TILES | DIRECTION
4, 0, 2, 6, 2, 10, // Down
4, 0, 14, 18, 14, 22, // Up
4, 0, 26, 30, 26, 34, // Right
4, 1, 24, 28, 24, 32, // Left
};
// Offset of the animation of each direction in the global animation data
#define PLAYER_DIRECTION_DOWN 0
#define PLAYER_DIRECTION_UP 6
#define PLAYER_DIRECTION_RIGHT 12
#define PLAYER_DIRECTION_LEFT 18
// Variables containing player state
UINT8 player_x;
UINT8 player_y;
UINT8 player_direction;
UINT8 player_animation_frame;
UINT8 is_player_walking;
// Flip the given sprite on X axis.
//
// sprite_id: the id ("nb") of the sprite to update.
void flip_sprite_horiz(UINT8 sprite_id) {
set_sprite_prop(sprite_id, get_sprite_prop(sprite_id) | S_FLIPX);
}
// Remove the flip the given sprite on X axis.
//
// sprite_id: the id ("nb") of the sprite to update.
void unflip_sprite_horiz(UINT8 sprite_id) {
set_sprite_prop(sprite_id, get_sprite_prop(sprite_id) & ~S_FLIPX);
}
// Update the tiles of the sprite to animate it.
//
// sprite_id: the id ("nb") of the sprite to update
// anim: pointer to the animation data
// direction: direction of the animation (= offset of the animation in the global animation data)
// frame: the new frame of the animation that will be displayed
//
// Returns the next frame of the animation.
UINT8 update_sprite_animation(UINT8 sprite_id, UINT8 *anim, UINT8 direction, UINT8 frame) {
UINT8 len = anim[direction];
UINT8 flip = anim[direction + 1];
UINT8 tile_id = anim[direction + 2 + frame];
if (flip) {
flip_sprite_horiz(sprite_id);
} else {
unflip_sprite_horiz(sprite_id);
}
set_sprite_tile(sprite_id, tile_id);
return (frame + 1) % len;
}
void main(void) {
UINT8 keys = 0;
UINT8 frame_skip = 8; // Update player's animation every 8 frame to
// slow down the animation (8 frames = ~133 ms
// between each animation frames)
// Initialize player's state
player_x = 80;
player_y = 72;
player_direction = PLAYER_DIRECTION_DOWN;
player_animation_frame = 0;
is_player_walking = 0;
// Load sprites' tiles in video memory
set_sprite_data(0, PLAYER_SPRITES_TILE_COUNT, PLAYER_SPRITES);
// Use 8x16 sprites
SPRITES_8x16;
// Makes sprites "layer" visible
SHOW_SPRITES;
// Init the two sprites used for the player
move_sprite(PLAYER_SPRITE_L_ID, player_x, player_y);
set_sprite_prop(PLAYER_SPRITE_L_ID, S_PALETTE);
move_sprite(PLAYER_SPRITE_R_ID, player_x + 8, player_y);
set_sprite_prop(PLAYER_SPRITE_R_ID, S_PALETTE);
while (1) {
// Wait for v-blank (screen refresh)
wait_vbl_done();
// Read joypad keys to know if the player is walking
// and in which direction
keys = joypad();
if (keys & J_UP) {
player_direction = PLAYER_DIRECTION_UP;
is_player_walking = 1;
} else if (keys & J_DOWN) {
player_direction = PLAYER_DIRECTION_DOWN;
is_player_walking = 1;
} else if (keys & J_LEFT) {
player_direction = PLAYER_DIRECTION_LEFT;
is_player_walking = 1;
} else if (keys & J_RIGHT) {
player_direction = PLAYER_DIRECTION_RIGHT;
is_player_walking = 1;
} else {
is_player_walking = 0;
frame_skip = 1; // Force refresh of the animation frame
}
// Update the player position if it is walking
if (is_player_walking) {
if (player_direction == PLAYER_DIRECTION_RIGHT) player_x += 1;
else if (player_direction == PLAYER_DIRECTION_LEFT) player_x -= 1;
else if (player_direction == PLAYER_DIRECTION_UP) player_y -= 1;
else if (player_direction == PLAYER_DIRECTION_DOWN) player_y += 1;
move_sprite(PLAYER_SPRITE_L_ID, player_x, player_y);
move_sprite(PLAYER_SPRITE_R_ID, player_x + 8, player_y);
// We do not update the animation on each frame: the animation
// will be too quick. So we skip frames
frame_skip -= 1;
if (!frame_skip) {
frame_skip = 8;
} else {
continue;
}
} else {
player_animation_frame = 0;
}
// Update sprites' tiles
update_sprite_animation(
PLAYER_SPRITE_L_ID,
PLAYER_SPRITE_ANIM_L,
player_direction,
player_animation_frame);
player_animation_frame = update_sprite_animation(
PLAYER_SPRITE_R_ID,
PLAYER_SPRITE_ANIM_R,
player_direction,
player_animation_frame);
}
}
|
C
|
#include <sys/select.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/ioctl.h>
#include <string.h>
#include <strings.h>
#include <sys/epoll.h>
#include <linux/signal.h>
#include <errno.h>
#define MEM_SIZE 0x1000
#define FIFO_CLEAR 0x1
int main(int argc , char *argv[])
{
int fd;
char aRdch[MEM_SIZE];
int max_fd;
struct epoll_event event;
int epfd;
int ret;
//非阻塞打开
fd = open("/dev/lkm_memory", O_RDWR | O_NONBLOCK);
if (fd < 0) {
fprintf(stderr, "open device failed: %s\n", strerror(errno));
return -errno;
}
epfd = epoll_create(5);
if (epfd < 0) {
fprintf(stderr, "epoll create failed: %s\n", strerror(errno));
return -errno;
}
//设置可以触发的事件
bzero(&event, sizeof(struct epoll_event));
event.events = EPOLL_CTL_ADD | EPOLLPRI;
//当前句柄加入epoll监控句柄链表
ret = epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &event);
if (ret < 0) {
fprintf(stderr, "epoll_ctl EPOLL_CTL_ADD: %s\n", strerror(errno));
return -errno;
}
//调动epoll_wait进行epfd句柄链表的监控
ret = epoll_wait(epfd, &event, 1, 15000);
if (ret < 0) {
fprintf(stderr, "epoll_wait failed %s\n", strerror(errno));
return -errno;
} else if (ret == 0) {
fprintf(stdout, "epoll_wait time-out within 15 seconds\n");
} else {
read(fd, aRdch, 100);
fprintf(stdout, "%s\n", aRdch);
}
//删除fd从epfd链表上
ret = epoll_ctl(epfd, EPOLL_CTL_DEL, fd, &event);
if (ret < 0) {
fprintf(stderr, "epoll_ctl EPOLL_CTL_DEL: %s\n", strerror(errno));
return -errno;
}
return 0;
}
|
C
|
#include<stdio.h>
#include<math.h>
void push(int *a,int ele,int *top)
{
a[++(*top)]=ele;
}
int pop(int *a,int * top)
{
if(*top==-1)
printf("Stack Underflow");
else
printf("%d",a[(*top)--]);
}
void display(int *a, int n)
{
int i;
for(i=0;i<n;i++)
printf("%c",a[i]);
}
void main()
{
int stac[20],dec,n=0,t=-1;
int *top=&t;
printf("Enter number\n");
scanf("%d",&dec);
n=log10(dec)+1;
int i;
while(dec>0)
{ push(stac,dec%2,top);
dec/=2;
}
while(*top!=-1)
pop(stac,top);
}
|
C
|
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "ex19.h"
#include <assert.h>
void *Map_move(void *self, Direction direction)
{
assert(self != NULL);
// Should always be in some valid location
Map *map = self;
Room *location = map->location;
Room *next = NULL;
assert(map->location != NULL);
next = location->_(move)(location, direction);
if(next) {
map->location = next;
}
return next;
}
int Map_attack(void *self, int damage)
{
assert(self != NULL);
assert(damage >= 0);
Map* map = self;
Room *location = map->location;
assert(map->location != NULL);
return location->_(attack)(location, damage);
}
int Map_init(void *self)
{
assert(self != NULL);
Map *map = self;
// make some rooms for a small map
Room *hall = NEW(Room, "The great Hall");
assert(hall != NULL);
Room *throne = NEW(Room, "The throne room");
assert(throne != NULL);
Room *arena = NEW(Room, "The arena, with the minotaur");
assert(arena != NULL);
Room *kitchen = NEW(Room, "Kitchen, you have the knife now");
assert(kitchen);
Room *pantry = NEW(Room, "A pantry, it smells of jerky and of the goblin there");
// put the bad guy in the arena
arena->bad_guy = NEW(Monster, "The evil minotaur");
assert(arena->bad_guy != NULL);
pantry->bad_guy = NEW(Monster, "A scraggly goblin");
assert(pantry->bad_guy != NULL);
// setup the map rooms
hall->north = throne;
throne->west = arena;
throne->east = kitchen;
throne->south = hall;
arena->east = throne;
kitchen->west = throne;
kitchen->north = pantry;
pantry->south = kitchen;
// start the map and the character off in the hall
map->start = hall;
map->location = hall;
return 1;
}
Object MapProto = {
.init = Map_init,
.move = Map_move,
.attack = Map_attack
};
int main(int argc, char *argv[])
{
// simple way to setup the randomness
srand(time(NULL));
// make our map to work with
Map *game = NEW(Map, "The Hall of the Minotaur.");
assert(game != NULL);
printf("You enter the ");
game->location->_(describe)(game->location);
while(process_input(game)) {
}
return 0;
}
|
C
|
#include <stdio.h>
int main(int argc, char **argv){
int orig_stdout;
//duplicate the stdout file handle and store it in orig_stdout
orig_stdout = dup(fileno(stdout));
//this text appears on screen
printf("writing to original stdout .... \n");
//reopen stdout and redirect it to the "redir.txt" file.
freopen("redir.tmp.txt","w",stdout);
//this appears in the "redir.txt" file.
printf("writing to redirected stdout..\n");
fclose(stdout);
//restore the original stdout and print to the screen again.
fdopen(orig_stdout,"w");
printf("i'm back writing to the original stdout.\n");
return 0;
}
|
C
|
/*
* File: ser.h
* Author: Brendan
*
* Created on 24 September 2016, 1:24 PM
*/
#ifndef SER_H
#define SER_H
unsigned char speedH = 0;
unsigned char speedL = 0;
unsigned char radH = 0;
unsigned char radL = 0;
unsigned int VelocityRight = 0;
unsigned int VelocityLeft = 0;
unsigned char RightSpeedH = 0;
unsigned char RightSpeedL = 0;
unsigned char LeftSpeedH = 0;
unsigned char LeftSpeedL = 0;
//initalise serial comms
void ser_init(void);
//transmits char data through serial
void ser_putch(unsigned char c);
//receives serial data
unsigned char ser_getch();
//Drive command
void Drive(unsigned char speedH, unsigned char speedL, unsigned char radH, unsigned char radL);
void DriveDirect(signed int VelocityRight, signed int VelocityLeft);
//Given sensor packetID and expected number of bytes, outputs sensor value in a single variable.
signed int getSensorData(unsigned char packetID, unsigned char bytes);
#endif /* SER_H */
|
C
|
#include <stdio.h>
#include <string.h>
#define MAXWORDLEN 101
#define MAXNAMELEN 101
#define MAXWORDS 1000
/*David Hatcher
MW 9:30-10:45
This program allows a user to enter a file name
it will then take that file name read all the text out of that file
extract only the first letter from each word
then place those letters in another file with the same name but
with ".dcf" added to the end
*/
void extract(char words[][MAXWORDLEN], int num_words, char *result);
int readFile(char const *fileName, char words[][MAXWORDLEN]);
void writeFile(const char *fileName,char *wordToWrite);
int main(){
printf("Enter the file name:");
char fileName[MAXNAMELEN];
scanf("%s",fileName);
char words[MAXWORDS][MAXWORDLEN];
int numberOfWords = readFile(fileName,words);
if(numberOfWords > 0){
char secretString[MAXWORDS];
extract(words,numberOfWords,secretString);
writeFile(fileName,secretString);
}else{
printf("Nothing found in file.");
}
return 0;
}
/*extract function takes in an array of strings a number of words
in that string and a point to another string. It will then take the
first character from every string in the array and place that character
into the value at the string pointer
*/
void extract(char words[][MAXWORDLEN], int num_words, char *result){
char *ch;
int i;
for(ch = result, i = 0; strcmp(words[i], "\0") != 0; i++, ch++){
*ch = words[i][0];
}
}
/*writeFile function takes in two strings a file name and a string to write
it then creates a new file using the original fineName variable and adds
".dcf" to the end of it then write the wordToWrite to that file, if it
fails at creating the file it will output an error
*/
void writeFile(char const *fileName,char *wordToWrite){
char fileNameNew[MAXNAMELEN + 3];
strcpy(fileNameNew,fileName);
strcat(fileNameNew,".dcf");
FILE *fp = fopen(fileNameNew,"w");
if(fp == NULL){
printf("Error Writing File %s",fileNameNew);
return;
}else{
printf("Output file name: %s",fileNameNew);
fprintf(fp,"%s",wordToWrite);
}
}
/*readFile function takes a file name and a string array
then reads all of the words out of that file and places each of them in
its own index in the string array, if it fails at finding the file it
will output an error
*/
int readFile(char const *fileName, char words[][MAXWORDLEN]){
int i = -1;
FILE *fp = fopen(fileName,"r");
if(fp == NULL){
printf("Error reading %s", fileName);
return 0;
}
while(!feof(fp) && !ferror(fp)){
fscanf(fp,"%s",words[++i]);
}
return i;
}
|
C
|
/*
* Section: 1.6.6
* Problem: Interpreter
* UVa ID: 10033
*
* Solve by @alysonNBS
*/
#include <stdio.h>
int registers[10];
char ram[1000][4];
int instructions_size;
int current_instruction;
void (*encodings[10])(int, int);
void setup_encodings(void);
void reset_computer(void);
int read_instructions(void);
int execute_instructions(void);
int main() {
int n;
scanf("%d%*c", &n);
setup_encodings();
while (n--) {
reset_computer();
read_instructions();
printf("%d\n%s", execute_instructions(), n ? "\n" : "");
}
return 0;
}
void e1(int, int);
void e2(int, int);
void e3(int, int);
void e4(int, int);
void e5(int, int);
void e6(int, int);
void e7(int, int);
void e8(int, int);
void e9(int, int);
void e0(int, int);
void setup_encodings() {
encodings[0] = e0;
encodings[1] = e1;
encodings[2] = e2;
encodings[3] = e3;
encodings[4] = e4;
encodings[5] = e5;
encodings[6] = e6;
encodings[7] = e7;
encodings[8] = e8;
encodings[9] = e9;
}
void reset_computer() {
int i;
for(i=0; i<10; i++)
registers[i] = 0;
for(i=0; i<1000; i++)
ram[i][0] = ram[i][1] = ram[i][2] = '0',
ram[i][3] = 0;
}
int read_instructions() {
instructions_size = 0;
scanf("%*c");
while(scanf("%[0-9]%*c", ram+instructions_size++) == 1);
return instructions_size;
}
int execute_instructions() {
int instructions_executeds = 0;
current_instruction = 0;
while(current_instruction < 1000)
encodings[ram[current_instruction][0] - '0'](ram[current_instruction][1] - '0', ram[current_instruction][2] - '0'),
instructions_executeds++;
return instructions_executeds;
}
void e1(int a, int b) {
current_instruction = 1000;
}
void e2(int d, int n) {
registers[d] = n;
current_instruction++;
}
void e3(int d, int n) {
registers[d] = (registers[d] + n) % 1000;
current_instruction++;
}
void e4(int d, int n) {
registers[d] = (registers[d] * n) % 1000;
current_instruction++;
}
void e5(int d, int s) {
registers[d] = registers[s];
current_instruction++;
}
void e6(int d, int s) {
registers[d] = (registers[d] + registers[s]) % 1000;
current_instruction++;
}
void e7(int d, int s) {
registers[d] = (registers[d] * registers[s]) % 1000;
current_instruction++;
}
void e8(int d, int a) {
registers[d] = (ram[registers[a]][0]-'0')*100 + (ram[registers[a]][1]-'0')*10 + (ram[registers[a]][2]-'0');
current_instruction++;
}
void e9(int s, int a) {
ram[registers[a]][0] = registers[s] / 100 + '0';
ram[registers[a]][1] = (registers[s] % 100) / 10 + '0';
ram[registers[a]][2] = registers[s] % 10 + '0';
current_instruction++;
}
void e0(int d, int s) {
if(registers[s])
current_instruction = registers[d];
else
current_instruction++;
}
|
C
|
/******************************************************/
/********** TEST CODE Modified by Ziho Shin ***********/
/******************************************************/
/******************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <time.h>
#define MB 262144
////////////////////////////////////////////////////
int timeval_subtract(struct timeval *result, struct timeval *t2, struct timeval *t1){
long int diff = (t2->tv_usec + 1000000 * t2->tv_sec) - (t1->tv_usec + 1000000 * t1->tv_sec);
result->tv_sec = diff / 1000000;
result->tv_usec = diff % 1000000;
return (diff<0);
}
void error_handling(char *message);
void main(int argc, char **argv){
int serv_sock;
int clnt_sock;
int clnt_addr_size;
int fd;
int str_len;
char sync[MB];
char msg[MB];
struct sockaddr_in serv_addr;
struct sockaddr_in clnt_addr;
/******************************************************/
clock_t check;
struct timeval tvBegin, tvEnd, tvDiff;
// struct timespec start, stop;
// double ExeTime, ExeTime_nano;
char buf[100];
/******************************************************/
printf("\n\n================================================ \n");
printf("================================================ \n");
printf("Ethernet Networking Test Program - Server\n");
printf("================================================ \n");
printf("================================================ \n\n");
/******************************************************/
/******************************************************/
printf("\n");
check = time(NULL);
strftime(buf,sizeof(buf), "Program_Started: %a %Y-%m-%d %H:%M:%S location: %Z", localtime(&check));
printf("%s\n\n", buf);
/******************************************************/
if(argc!=2){
printf("Usage : %s <port>\n", argv[0]);
exit(1);
}
serv_sock = socket(PF_INET, SOCK_STREAM, 0);
//Sever socket create
if(serv_sock == -1)
error_handling("Socket create error");
memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
//Server IP adderess
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
//RX from anywhere
serv_addr.sin_port=htons(atoi(argv[1]));
//Server port number
if(bind(serv_sock, (struct sockaddr*) & serv_addr,
sizeof(serv_addr)) == -1) // Socket address assign
error_handling("Socket binding error");
if(listen(serv_sock, 5) == -1) // Connection waiting
error_handling("Server listen error");
clnt_addr_size = sizeof(clnt_addr);
clnt_sock = accept(serv_sock, (struct sockaddr*) & clnt_addr,
& clnt_addr_size); // Connection accepting
/////////////////////////////////////////////////////////////////////////
printf("Client connected Information :\n\n");
printf("Port Number : %s\n", argv[1]);
printf("Client address : %s\n", inet_ntoa(clnt_addr.sin_addr));
printf("================================================ \n");
if(clnt_sock == -1){
error_handling("Accept error");
}
printf("Waiting for Client Sync message\n");
str_len = read(clnt_sock, sync, MB);
printf("%s\n",sync);
write(clnt_sock, sync, str_len); //echo back
printf("Ready to send Dummy data\n");
printf("Start to transfer\n");
fd = open("dummy.db", O_RDONLY);
if(fd == -1)
error_handling("file open error");
//////////////////////////////////////////////////////////////////////////////////////////
// clock_gettime(CLOCK_MONOTONIC, &start);
gettimeofday(&tvBegin, NULL);
//////////////////////////////////////////////////////////////////////////////////////////
while((str_len = read(fd, msg, MB))!=0){
write(clnt_sock, msg, str_len);
}
// read(clnt_sock, sync,MB);
// printf("%s\n",sync);
close(fd);
//////////////////////////////////////////////////////////////////////////////////////////
gettimeofday(&tvEnd, NULL);
timeval_subtract(&tvDiff, &tvEnd, &tvBegin);
printf("ExeTime : %ld.%06ld s\n", tvDiff.tv_sec, tvDiff.tv_usec);
printf("ExeTime : %06ld us\n",tvDiff.tv_usec);
// clock_gettime(CLOCK_MONOTONIC, &stop);
// ExeTime_nano = (((long)stop.tv_nsec)-((long)start.tv_nsec));
//ExeTime_nano = ((stop.tv_sec-start.tv_sec));
// ExeTime = ExeTime_nano * (0.00001);
// printf("\nEXE Time_n: %f nsec\n", ExeTime_nano);
// printf("EXE Time_m: %f msec\n\n", ExeTime);
//////////////////////////////////////////////////////////////////////////////////////////
// read(clnt_sock, sync, MB);
// printf("%s\n", sync);
/*
while(1){
write(clnt_sock, (char*)&message[0],sizeof(int));
read(clnt_sock, sync, MB);
if(!strcmp(sync,"ack")) break;
}
*/
close(clnt_sock); // Connection close
printf("================================================ \n");
printf("TCP over dummy data transfer finished\n");
printf("Socket Connection closed\n");
printf("\n");
check = time(NULL);
strftime(buf,sizeof(buf), "Program_Ended: %a %Y-%m-%d %H:%M:%S location: %Z", localtime(&check));
printf("%s\n\n", buf);
}
void error_handling(char *message){
fputs(message, stderr);
fputc('\n', stderr);
exit(1);
}
|
C
|
// C program to find sum of digits of a number
#include <stdio.h>
int main()
{
int n,s=0;
scanf("%d",&n);
while(n>0)
{
s=s+n%10;
n=n/10;
}
printf("Sum of digits is %d",s);
}
|
C
|
#include <stdio.h>
int main()
{
int birimA, birimB, birimC;
int ekipA1, ekipA2, ekipA3, ekipA4,
ekipB1, ekipB2, ekipB3, ekipB4,
ekipC1, ekipC2, ekipC3, ekipC4;
printf("Birim A,B,C ve ekiplerinin(1,2,3,4) satış miktarlarını girin:\n");
printf("Birim A, Ekip 1: \n");
scanf("%d", &ekipA1);
printf("Birim A, Ekip 2: \n");
scanf("%d", &ekipA2);
printf("Birim A, Ekip 3: \n");
scanf("%d", &ekipA3);
printf("Birim A, Ekip 4: \n");
scanf("%d", &ekipA4);
printf("Birim B, Ekip 1: \n");
scanf("%d", &ekipB1);
printf("Birim B, Ekip 2: \n");
scanf("%d", &ekipB2);
printf("Birim B, Ekip 3: \n");
scanf("%d", &ekipB3);
printf("Birim B, Ekip 4: \n");
scanf("%d", &ekipB4);
printf("Birim C, Ekip 1: \n");
scanf("%d", &ekipC1);
printf("Birim C, Ekip 2: \n");
scanf("%d", &ekipC2);
printf("Birim C, Ekip 3: \n");
scanf("%d", &ekipC3);
printf("Birim C, Ekip 4: \n");
scanf("%d", &ekipC4);
int toplamBirimA = ekipA1 + ekipA2 + ekipA3 + ekipA4;
int toplamBirimB = ekipB1 + ekipB2 + ekipB3 + ekipB4;
int toplamBirimC = ekipC1 + ekipC2 + ekipC3 + ekipC4;
if (toplamBirimA > toplamBirimB && toplamBirimA > toplamBirimC)
{
printf("\nBirim A toplam %d satışı ile birincidir.\n", toplamBirimA);
}
else if (toplamBirimB > toplamBirimA && toplamBirimB > toplamBirimC)
{
printf("\nBirim B toplam %d satışı ile birincidir.\n", toplamBirimB);
}
else if (toplamBirimC > toplamBirimA && toplamBirimC > toplamBirimB)
{
printf("\nBirim C toplam %d satışı ile birincidir.\n", toplamBirimC);
}
return 0;
}
|
C
|
/*
*
* Demonstrates how to draw a cockpit view for a 3D scene.
*
* Key bindings:
* m Toggle cockpit mode
* a Toggle axes
* arrows Change view angle
* PgDn/PgUp Zoom in and out
* 0 Reset view angle
* l Enable lighting
* ESC Exit
*/
#include "CSCIx229.h"
int axes=0; // Display axes
int mode=0; // perspective or first person
int th=0; // Azimuth of view angle
int ph=0; // Elevation of view angle
int fov=25; // Field of view
double asp=1; // Aspect ratio
double dim=10.0; // Size of world
//lighting parameters
int movelight =1; // toggle for idlily moving light
int diffuse=50;
int specular=20;
int ambient=20;
int emission=30;
int light=1; //enable or disable light
double zh=0; //lighting angle of rotation
double distance = 2; // Light distance
float ylight = 0; // Elevation of light
int local = 0; // Local Viewer Model
float shiny = 1; // Shininess (value)
int shininess = 3; // Shininess (power of two)
//terrain parameter
float z[65][65];
float zmag=.1;
float zmin=+1e8; // DEM lowest location
float zmax=-1e8; // DEM highest location
//bounding boxes
int showboxes=0;
//texture parameters
int cockpit;
int land;
int wood;
int wood2;
int metal;
int water;
//movement parameters
double dirx=0;
double diry=0;
double dirz=0;
double movex=2;
double movey=2;
double movez=5;
double moveth=0;// angle for the planar movement
double moveph=0;// angle for the spherical cords
/*
* Draw a cube
* at (x,y,z)
* dimentions (dx,dy,dz)
* rotated th about the y axis
*/
static void Vertex(double th,double ph)
{
double x=Sin(th)*Cos(ph);
double y= Sin(ph);
double z= Cos(th)*Cos(ph);
glNormal3d(x,y,z);
glVertex3d(x , y , z);
}
double *normalplane(double *p1,double *p2, double *p3,double *norm)
{
double a1[3]={0,0,0};
double a2[3]={0,0,0};
a1[0]=p2[0]-p1[0];
a1[1]=p2[1]-p1[1];
a1[2]=p2[2]-p1[2];
a2[0]=p3[0]-p1[0];
a2[1]=p3[1]-p1[1];
a2[2]=p3[2]-p1[2];
//printf("x:%.2f, y:%.2f, z:%.2f",a1[0],a1[1],a1[2]);
norm[0]=(a1[1]*a2[2])-(a2[1]*a1[2]);
norm[1]=-(a1[0]*a2[2])+(a2[0]*a1[2]);
norm[2]=(a1[0]*a2[1])-(a2[0]*a1[1]);
return norm;
}
static void sphere1(double x,double y,double z,double r)
{
const int d=5;
int th,ph;
float yellow[] = {0,1.0,0.0,1.0};
float Emission[] = {0.01*emission,0.005*emission,0.0,1.0};
// Save transformation
glPushMatrix();
// Offset, scale and rotate
glTranslated(x,y,z);
glScaled(r,r,r);
// yellow ball
glColor3f(1,1,0);
glMaterialf(GL_FRONT,GL_SHININESS,shiny);
glMaterialfv(GL_FRONT,GL_SPECULAR,yellow);
glMaterialfv(GL_FRONT,GL_EMISSION,Emission);
// South pole cap
glBegin(GL_TRIANGLE_FAN);
Vertex(0,-90);
for (th=0;th<=360;th+=d)
{
Vertex(th,d-90);
}
glEnd();
// Latitude bands
for (ph=d-90;ph<=90-2*d;ph+=d)
{
glBegin(GL_QUAD_STRIP);
for (th=0;th<=360;th+=d)
{
Vertex(th,ph);
Vertex(th,ph+d);
}
glEnd();
}
// North pole cap
glBegin(GL_TRIANGLE_FAN);
Vertex(0,90);
for (th=0;th<=360;th+=d)
{
Vertex(th,90-d);
}
glEnd();
// Undo transformations
glPopMatrix();
}
static void cylinder(double x,double y,double z, double r,double d, double th, double ph)
{
int i,k;
// Save transformation
glPushMatrix();
// Offset and scale
glTranslated(x,y,z);
glRotated(ph,0,0,1);
glRotated(th,0,1,0);
glScaled(r,r,d);
// Head & Tail
glColor3f(1,1,1);
for (i=1;i>=-1;i-=2)
{
glNormal3f(0,0,i);
glBegin(GL_TRIANGLE_FAN);
glTexCoord2f(0.5,0.5);
glVertex3f(0.0,0.0,i);
for (k=0;k<=360;k+=10)
{
glTexCoord2f(0.5*Cos(k)+0.5,0.5*Sin(k)+0.5);
glVertex3f(Cos(k),Sin(k),i);
}
glEnd();
}
// Edge
glBegin(GL_QUAD_STRIP);
for (k=0;k<=360;k+=10)
{
glNormal3f(Cos(k),Sin(k),0);
glTexCoord2f(0,0.01*k); glVertex3f(Cos(k),Sin(k),+1);
glTexCoord2f(1,0.01*k); glVertex3f(Cos(k),Sin(k),-1);
}
glEnd();
// Undo transformations
glPopMatrix();
}
static void cube(double x,double y,double z,
double dx,double dy,double dz,
double th, double ph)
{
// Set specular color to white
float white[] = {1,1,1,1};
float black[] = {0,0,0,1};
glMaterialf(GL_FRONT_AND_BACK,GL_SHININESS,shiny);
glMaterialfv(GL_FRONT_AND_BACK,GL_SPECULAR,white);
glMaterialfv(GL_FRONT_AND_BACK,GL_EMISSION,black);
// Save transformation
glPushMatrix();
// Offset, scale and rotate
glTranslated(x,y,z);
glRotated(ph,0,0,1);
glRotated(th,0,1,0);
glScaled(dx,dy,dz);
// Cube
glBegin(GL_QUADS);
// Front
glNormal3f( 0, 0, 1);
glTexCoord2f(1.0,1.0);glVertex3f(-1,-1, 1);
glTexCoord2f(1.0,-1.0);glVertex3f(+1,-1, 1);
glTexCoord2f(-1.0,-1.0);glVertex3f(+1,+1, 1);
glTexCoord2f(-1.0,1.0);glVertex3f(-1,+1, 1);
// Back
glNormal3f( 0, 0,-1);
glTexCoord2f(1.0,1.0);glVertex3f(+1,-1,-1);
glTexCoord2f(1.0,-1.0);glVertex3f(-1,-1,-1);
glTexCoord2f(-1.0,-1.0);glVertex3f(-1,+1,-1);
glTexCoord2f(-1.0,1.0);glVertex3f(+1,+1,-1);
// Right
glNormal3f(+1, 0, 0);
glTexCoord2f(0.5,0.5);
glTexCoord2f(1.0,1.0);glVertex3f(+1,-1,+1);
glTexCoord2f(1.0,-1.0);glVertex3f(+1,-1,-1);
glTexCoord2f(-1.0,-1.0);glVertex3f(+1,+1,-1);
glTexCoord2f(-1.0,1.0);glVertex3f(+1,+1,+1);
// Left
glNormal3f(-1, 0, 0);
glTexCoord2f(1.0,1.0);glVertex3f(-1,-1,-1);
glTexCoord2f(1.0,-1.0);glVertex3f(-1,-1,+1);
glTexCoord2f(-1.0,-1.0);glVertex3f(-1,+1,+1);
glTexCoord2f(-1.0,1.0);glVertex3f(-1,+1,-1);
// Top
glNormal3f( 0,+1, 0);
glTexCoord2f(1.0,1.0);glVertex3f(-1,+1,+1);
glTexCoord2f(1.0,-1.0);glVertex3f(+1,+1,+1);
glTexCoord2f(-1.0,-1.0);glVertex3f(+1,+1,-1);
glTexCoord2f(-1.0,1.0);glVertex3f(-1,+1,-1);
// Bottom
glNormal3f( 0,-1, 0);
glTexCoord2f(1.0,1.0);glVertex3f(-1,-1,-1);
glTexCoord2f(1.0,-1.0);glVertex3f(+1,-1,-1);
glTexCoord2f(-1.0,-1.0);glVertex3f(+1,-1,+1);
glTexCoord2f(-1.0,1.0);glVertex3f(-1,-1,+1);
// End
glEnd();
// Undo transofrmations
glPopMatrix();
}
void weight(double x, double y, double z, double dx, double dy, double dz, double th, double ph)
{
glPushMatrix();
// Offset, scale and rotate
glTranslated(x,y,z);
glRotated(th,0,1,0);
glRotated(ph,0,0,1);
glScaled(dx,dy,dz);
glBegin(GL_QUADS);
//bottom of weight
glColor3f(1,1,1);
glNormal3f(0,-1,0);
glTexCoord2f(1.0,1.0);glVertex3f(0.1,0.0,0.1);
glTexCoord2f(1.0,-1.0);glVertex3f(-0.1,0.0,0.1);
glTexCoord2f(-1.0,-1.0);glVertex3f(-0.1,0.0,-0.1);
glTexCoord2f(-1.0,1.0);glVertex3f(0.1,0.0,-0.1);
// angled bottoms
glColor3f(1,1,1);
double n1[3]={0,0,0};
double p1[3]={0.1,0.0,0.1};
double p2[3]={0.3,0.1,0.1};
double p3[3]={0.3,0.1,-0.1};
normalplane(p1,p2,p3,n1);
glNormal3f(-n1[0],-n1[1],-n1[2]);
glTexCoord2f(1.0,1.0);glVertex3f(0.1,0.0,0.1);
glTexCoord2f(1.0,-1.0);glVertex3f(0.3,0.1,0.1);
glTexCoord2f(-1.0,-1.0);glVertex3f(0.3,0.1,-0.1);
glTexCoord2f(-1.0,1.0);glVertex3f(0.1,0.0,-0.1);
glColor3f(1,1,1);
double n2[3]={0,0,0};
double p4[3]={-0.1,0.0,0.1};
double p5[3]={-0.3,0.1,0.1};
double p6[3]={-0.3,0.1,-0.1};
normalplane(p4,p5,p6,n2);
glNormal3f(n2[0],n2[1],n2[2]);
glTexCoord2f(1.0,1.0);glVertex3f(-0.1,0.0,0.1);
glTexCoord2f(1.0,-1.0);glVertex3f(-0.3,0.1,0.1);
glTexCoord2f(-1.0,-1.0);glVertex3f(-0.3,0.1,-0.1);
glTexCoord2f(-1.0,1.0);glVertex3f(-0.1,0.0,-0.1);
//top
glColor3f(1,1,1);
glNormal3f(0,1,0);
glTexCoord2f(1.0,1.0);glVertex3f(0.3,0.25,0.1);
glTexCoord2f(1.0,-1.0);glVertex3f(0.3,0.25,-0.1);
glTexCoord2f(-1.0,-1.0);glVertex3f(-0.3,0.25,-0.1);
glTexCoord2f(-1.0,1.0);glVertex3f(-0.3,0.25,0.1);
//high sides
glColor3f(1,1,1);
glNormal3f(-1,0,0);
glTexCoord2f(1.0,1.0);glVertex3f(-0.3,0.1,0.1);
glTexCoord2f(1.0,-1.0);glVertex3f(-0.3,0.1,-0.1);
glTexCoord2f(-1.0,-1.0);glVertex3f(-0.3,0.25,-0.1);
glTexCoord2f(-1.0,1.0);glVertex3f(-0.3,0.25,0.1);
glColor3f(1,1,1);
glNormal3f(1,0,0);
glTexCoord2f(1.0,1.0);glVertex3f(0.3,0.1,0.1);
glTexCoord2f(1.0,-1.0);glVertex3f(0.3,0.1,-0.1);
glTexCoord2f(-1.0,-1.0);glVertex3f(0.3,0.25,-0.1);
glTexCoord2f(-1.0,1.0);glVertex3f(0.3,0.25,0.1);
glEnd();
//code to check normal vector correctness
//glBegin(GL_LINES);
//glColor3f(1,0,0);
//glVertex3d(p4[0],p4[1],p4[2]);
//glVertex3d(p4[0]+10*n2[0],p4[1]+10*n2[1],p4[2]+10*n2[2]);
//glEnd();
//odd sides
glBegin(GL_POLYGON);
glColor3f(1,1,1);
glNormal3f(0,0,1);
glTexCoord2f(.3,.25);glVertex3f( .3, .25, .1);
glTexCoord2f(-.3,.25);glVertex3f(-.3, .25, .1);
glTexCoord2f(-.3,.1);glVertex3f(-.3, .1 , .1);
glTexCoord2f(-1.0,0);glVertex3f(-.1, 0 , .1);
glTexCoord2f(.1,0);glVertex3f( .1, 0 , .1);
glTexCoord2f(.3,.1);glVertex3f( .3, .1 , .1);
glTexCoord2f(.3,.25);glVertex3f( .3, .25, .1);
glEnd();
glBegin(GL_POLYGON);
glColor3f(1,1,1);
glNormal3f(0,0,-1);
glTexCoord2f(.3,.25);glVertex3f( .3, .25, -.1);
glTexCoord2f(-.3,.25);glVertex3f(-.3, .25, -.1);
glTexCoord2f(-.3,.1);glVertex3f(-.3, .1 , -.1);
glTexCoord2f(-.1,0);glVertex3f(-.1, 0 , -.1);
glTexCoord2f(.1,0);glVertex3f( .1, 0 , -.1);
glTexCoord2f(.3,.1);glVertex3f( .3, .1 , -.1);
glTexCoord2f(.3,.25);glVertex3f( .3, .25, -.1);
glEnd();
glPopMatrix();
}
void terrain(float zmag,int texture)
{
int i,j;
double z0 = (zmin+zmax)/2;
glColor3f(1,1,1);
glEnable(GL_TEXTURE_2D);
glEnable(GL_DEPTH_TEST);
glBindTexture(GL_TEXTURE_2D,texture);
for (i=0;i<64;i++)
for (j=0;j<64;j++)
{
float x=16*i-512;
float y=16*j-512;
glBegin(GL_QUADS);
glTexCoord2f((i+0)/64.,(j+0)/64.); glVertex3d(x+ 0,zmag*(z[i+0][j+0]-z0)-2.8,y+0);
glTexCoord2f((i+1)/64.,(j+0)/64.); glVertex3d(x+16,zmag*(z[i+1][j+0]-z0)-2.8,y+0);
glTexCoord2f((i+1)/64.,(j+1)/64.); glVertex3d(x+16,zmag*(z[i+1][j+1]-z0)-2.8,y+16);
glTexCoord2f((i+0)/64.,(j+1)/64.); glVertex3d(x+ 0,zmag*(z[i+0][j+1]-z0)-2.8,y+16);
glEnd();
}
glDisable(GL_TEXTURE_2D);
}
void tree(double x, double y, double z, double dx, double dy, double dz, double th)
{
//generate object last due to transperancy property of foilage
}
void Trebuchet(double x, double y,double z,double dx, double dy, double dz, double th)
{
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D,wood2);
glPushMatrix();
// Offset, scale and rotate
glTranslated(x,y,z);
glRotated(th,0,1,0);
glScaled(dx,dy,dz);
glColor3f(1,1,1);
//base
cube(0.5,0.0,0.5,2.0,0.1,0.1,0,0);
cube(0.5,0.0,-0.5, 2.0,0.1,0.1, 0,0);
//arm support
cube(1.0,1.1, 0.5, 0.1,1.1,0.1, 0,0);
cube(1.0,1.1,-0.5, 0.1,1.1,0.1, 0,0);
cube(1.4,0.75, 0.5, 0.09,0.80,0.1, 0,30);
cube(0.6,0.75, 0.5, 0.09,0.80,0.1, 0,-30);
cube(1.4,0.75, -0.5, 0.09,0.80,0.1, 0,30);
cube(0.6,0.75, -0.5, 0.09,0.80,0.1, 0,-30);
//gear support
cube(-1.0,0.25, 0.5, 0.1,0.25,0.1, 0,0);
cube(-1.0,0.25,-0.5, 0.1,0.25,0.1, 0,0);
//gears
cylinder(-1.0,0.40,-0.7,.2,.05,0,0);
cylinder(-1.0,0.40, 0.7,.2,.05,0,0);
//rotation arm
cylinder(-1.0,0.40, 0.0,.05,0.7,0,0);
//arms for gears
glBindTexture(GL_TEXTURE_2D,metal);
cylinder(-1.0,0.40,-0.7,.05,.30,90,0);
cylinder(-1.0,0.40, 0.7,.05,.30,90,0);
cylinder(-1.0,0.40,-0.7,.05,.30,90,90);
cylinder(-1.0,0.40, 0.7,.05,.30,90,90);
glBindTexture(GL_TEXTURE_2D,wood);
//trebuchet arm
cylinder(1.0,2.0,0.0,.08,.8,0,0);
cylinder(1.0,2.0,0.0,.08,1.5,90,90);
// counterweight
glBindTexture(GL_TEXTURE_2D,wood2);
weight(1.0,.1,0,3,3,3,0,0);
glPopMatrix();
glDisable(GL_TEXTURE_2D);
boundingbox.trebuchetbox[0]=x+dx*(.5); //actual center
boundingbox.trebuchetbox[1]=y+dy*(1.5);//actual center
boundingbox.trebuchetbox[2]=z+dz*(0);//actual center
boundingbox.trebuchetbox[3]=dx*(2.2);
boundingbox.trebuchetbox[4]=dy*(2.2);
boundingbox.trebuchetbox[5]=dz*(.9);
}
/*
* OpenGL (GLUT) calls this routine to display the scene
*/
void display()
{
const double len=1.5; // Length of axes
// Erase the window and the depth buffer
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
// Undo previous transformations
glLoadIdentity();
// Perspective
if (mode==0)
{
double Ex = -2*dim*Sin(th)*Cos(ph);
double Ey = +2*dim *Sin(ph);
double Ez = +2*dim*Cos(th)*Cos(ph);
gluLookAt(Ex,Ey,Ez , 0,0,0 , 0,Cos(ph),0);
}
// first person view
else if(mode==1)
{
dirx = +dim*Sin(th)*Cos(ph);
diry = fmod(+dim*Sin(ph),89);
dirz = -dim*Cos(th)*Cos(ph);
gluLookAt(movex,movey,movez , dirx+movex,diry+movey,dirz+movez , 0,Cos(ph),0);
}
// Enable Z-buffering in OpenGL
glEnable(GL_DEPTH_TEST);
if (light)
{
// Translate intensity to color vectors
float Ambient[] = {0.01*ambient ,0.01*ambient ,0.01*ambient ,1.0};
float Diffuse[] = {0.01*diffuse ,0.01*diffuse ,0.01*diffuse ,1.0};
float Specular[] = {0.01*specular,0.01*specular,0.01*specular,1.0};
// Light position
float Position[] = {distance*Sin(zh),ylight,distance*Cos(zh),1.0};
// Draw light position as ball (still no lighting here)
glColor3f(1,1,1);
sphere1(Position[0],Position[1],Position[2] , 0.1);
// OpenGL should normalize normal vectors
glEnable(GL_NORMALIZE);
// Enable lighting
glEnable(GL_LIGHTING);
// Location of viewer for specular calculations
glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER,local);
// glColor sets ambient and diffuse color materials
glColorMaterial(GL_FRONT_AND_BACK,GL_AMBIENT_AND_DIFFUSE);
glEnable(GL_COLOR_MATERIAL);
// Enable light 0
glEnable(GL_LIGHT0);
// Set ambient, diffuse, specular components and position of light 0
glLightfv(GL_LIGHT0,GL_AMBIENT ,Ambient);
glLightfv(GL_LIGHT0,GL_DIFFUSE ,Diffuse);
glLightfv(GL_LIGHT0,GL_SPECULAR,Specular);
glLightfv(GL_LIGHT0,GL_POSITION,Position);
}
else
glDisable(GL_LIGHTING);
//code for rendering scene
terrain(0.1,land);
terrain(0.0,water);
//cylinder(0.5,0.5,0.5,0.1,1.0,0.0,10);
Trebuchet(0.15,0.15,0.05,.75,.75,.75,0);
Trebuchet(3.15,0.15,3.05,.75,.75,.75,0);
Trebuchet(-3.15,0.15,3.05,.75,.75,.75,0);
//diagnose boundingboxes
if(showboxes)
{
cube(boundingbox.trebuchetbox[0],boundingbox.trebuchetbox[1],boundingbox.trebuchetbox[2],boundingbox.trebuchetbox[3],boundingbox.trebuchetbox[4],boundingbox.trebuchetbox[5],0,0);
}
//weight(0,0,0,1,1,1,0,0);
glDisable(GL_LIGHTING);
// Draw axes
glColor3f(1,1,1);
if (axes)
{
glBegin(GL_LINES);
glVertex3d(0.0,0.0,0.0);
glVertex3d(len,0.0,0.0);
glVertex3d(0.0,0.0,0.0);
glVertex3d(0.0,len,0.0);
glVertex3d(0.0,0.0,0.0);
glVertex3d(0.0,0.0,len);
glEnd();
// Label axes
glRasterPos3d(len,0.0,0.0);
Print("X");
glRasterPos3d(0.0,len,0.0);
Print("Y");
glRasterPos3d(0.0,0.0,len);
Print("Z");
}
// Disable Z-buffering in OpenGL
glDisable(GL_DEPTH_TEST);
// Draw cockpit
// Display parameters
glWindowPos2i(5,5);
Print("Angle=%d,%d Dim=%.1f FOV=%d, move cords=(%f,%f,%Ff)",th,ph,dim,fov,movex, movey, movez);
glWindowPos2i(5,25);
Print("Ambient=%d Diffuse=%d Specular=%d Emission=%d Shininess=%.0f",ambient,diffuse,specular,emission,shiny);
// Render the scene and make it visible
ErrCheck("display");
glFlush();
glutSwapBuffers();
}
/*
* GLUT calls this routine when an arrow key is pressed
*/
void special(int key,int x,int y)
{
// Right arrow key - increase angle by 5 degrees
if (key == GLUT_KEY_RIGHT)
th += 5;
// Left arrow key - decrease angle by 5 degrees
else if (key == GLUT_KEY_LEFT)
th -= 5;
// Up arrow key - increase elevation by 5 degrees
else if (key == GLUT_KEY_UP)
ph += 5;
// Down arrow key - decrease elevation by 5 degrees
else if (key == GLUT_KEY_DOWN)
ph -= 5;
// PageUp key - increase dim
else if (key == GLUT_KEY_PAGE_UP)
dim += 0.1;
// PageDown key - decrease dim
else if (key == GLUT_KEY_PAGE_DOWN && dim>1)
dim -= 0.1;
// Keep angles to +/-360 degrees
th %= 360;
ph %= 360;
// Update projection
Project(fov,asp,dim,mode,dirx,diry,dirz,movex,movey,movez,th,ph);
// Tell GLUT it is necessary to redisplay the scene
glutPostRedisplay();
}
/*
* GLUT calls this routine when a key is pressed
*/
void key(unsigned char ch,int x,int y)
{
// Exit on ESC
if (ch == 27)
exit(0);
// Reset view angle
else if (ch == '0')
{
movex=2;
movey=2;
movez=5;
th = ph = 0;
}
// Toggle axes
else if (ch == '1')
light = fmod(light+1,2);
else if (ch == '2')
axes = fmod(axes+1,2);
// Switch display mode
else if (ch == '3')
mode = fmod(mode+1,2);
else if (ch == '4')
movelight = fmod(movelight+1,2);
else if (ch == '5')
showboxes = fmod(showboxes+1,2);
else if (ch == 'q')
zh -= 5;
else if (ch == 'Q')
zh += 5;
else if (ch == '8' && fov>0)
fov -= 1;
else if (ch == '9' && fov<180)
fov += 1;
// Light elevation
else if (ch=='[')
ylight -= 0.1;
else if (ch==']')
ylight += 0.1;
// Light distance
else if (ch=='k' && distance >0)
distance -= 0.1;
else if (ch=='l')
distance += 0.1;
else if (ch == 'Z' && ambient>0)
ambient-=1;
else if (ch == 'z' && ambient<100)
ambient+=1;
else if (ch == 'X' && diffuse>0)
diffuse-=1;
else if (ch == 'x' && diffuse<100)
diffuse+=1;
else if (ch == 'C' && specular>0)
specular-=1;
else if (ch == 'c' && specular<100)
specular+=1;
else if (ch == 'V' && emission>0)
emission-=1;
else if (ch == 'v' && emission<100)
emission+=1;
else if (ch=='B' && shininess>-1)
shininess -= 1;
else if (ch=='b' && shininess<7)
shininess += 1;
else if (ch == 'w' && AABB(movex+.1*dirx,movey+.1*diry+.1*dirx,movez+.1*dirz)== 0)
{
movex= movex+.1*dirx ;
movey= movey+.1*diry;
movez= movez+.1*dirz ;
}
else if (ch == 's' && AABB(movex-.1*dirx, movey-.1*diry, movez-.1*dirz)== 0)
{
movex= movex-.1*dirx ;
movey= movey-.1*diry ;
movez= movez-.1*dirz ;
}
// Translate shininess power to value (-1 => 0)
shiny = shininess<0 ? 0 : pow(2.0,shininess);
// Reproject
Project(fov,asp,dim,mode,dirx,diry,dirz,movex,movey,movez,th,ph);
// Tell GLUT it is necessary to redisplay the scene
glutPostRedisplay();
}
/*
* GLUT calls this routine when the window is resized
*/
void reshape(int width,int height)
{
// Ratio of the width to the height of the window
asp = (height>0) ? (double)width/height : 1;
// Set the viewport to the entire window
glViewport(0,0, width,height);
// Set projection
Project(fov,asp,dim,mode,dirx,diry,dirz,movex,movey,movez,th,ph);
}
//void mouse()
//{
// if(1){}
// else if(1){}
// glutPostRedisplay();
//}
void idle()
{
// Get elapsed (wall) time in seconds
double t = glutGet(GLUT_ELAPSED_TIME)/3000.0;
// Calculate spin angle 90 degrees/second
moveth = fmod(90*t,360);
//moveph = fmod(90*t,360);
if(movelight==1)
zh = fmod(90*t,360.0);
//moveph = fmod(90*t,360);
// Request display update
glutPostRedisplay();
}
/*
* Start up GLUT and tell it what to do
*/
void ReadDEM(char* file)
{
int i,j;
FILE* f = fopen(file,"r");
if (!f) Fatal("Cannot open file %s\n",file);
for (j=0;j<=64;j++)
for (i=0;i<=64;i++)
{
if (fscanf(f,"%f",&z[i][j])!=1) Fatal("Error reading saddleback.dem\n");
if (z[i][j] < zmin) zmin = z[i][j];
if (z[i][j] > zmax) zmax = z[i][j];
}
fclose(f);
}
int main(int argc,char* argv[])
{
//initialize struct bounding boxes
// Initialize GLUT
glutInit(&argc,argv);
// Request double buffered, true color window with Z buffering at 600x600
glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE);
glutInitWindowSize(600,600);
glutCreateWindow("Project by Dmitriy Tarasov");
// Set callbacks
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutSpecialFunc(special);
glutKeyboardFunc(key);
//glutMouseFunc(mouse);
glutIdleFunc(idle);
// Load textures
land=LoadTexBMP("grass.bmp");
wood=LoadTexBMP("wood.bmp");
wood2=LoadTexBMP("wood2.bmp");
metal=LoadTexBMP("metal.bmp");
water=LoadTexBMP("water.bmp");
ReadDEM("saddleback.dem");
// Pass control to GLUT so it can interact with the user
ErrCheck("init");
glutMainLoop();
return 0;
}
|
C
|
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- vim:set ts=4 sw=4 sts=4 noet: */
BOOST_AUTO_TEST_CASE(abs)
{
TESTCASE1(abs, 0, 0);
TESTCASE1(abs, 1, 1);
TESTCASE1(abs, -1, 1);
}
BOOST_AUTO_TEST_CASE(arccos)
{
TESTCASE1(arccos, 1, 0);
}
BOOST_AUTO_TEST_CASE(arccosh)
{
TESTCASE1(arccosh, 1, 0);
}
BOOST_AUTO_TEST_CASE(arccot)
{
TESTCASE1(arccot, 0, 1.5707963267948966); // pi/2
TESTCASE1(arccot, 1, .785398163397448309); // pi/4
TESTCASE1(arccot, -1, -.785398163397448309); // -pi/4
}
BOOST_AUTO_TEST_CASE(arccoth)
{
TESTCASE1(arccoth, 5, .20273255405408219);
TESTCASE1(arccoth, -5, -.20273255405408219);
}
BOOST_AUTO_TEST_CASE(arccsc)
{
TESTCASE1(arccsc, 1, 1.5707963267948966); // pi/2
TESTCASE1(arccsc, -1, -1.5707963267948966); // -pi/2
}
BOOST_AUTO_TEST_CASE(arccsch)
{
/* TODO */
}
BOOST_AUTO_TEST_CASE(arcsec)
{
TESTCASE1(arcsec, 1, 0);
}
BOOST_AUTO_TEST_CASE(arcsech)
{
TESTCASE1(arcsech, 1, 0);
}
BOOST_AUTO_TEST_CASE(arcsin)
{
TESTCASE1(arcsin, 0, 0);
}
BOOST_AUTO_TEST_CASE(arcsinh)
{
TESTCASE1(arcsinh, 0, 0);
}
BOOST_AUTO_TEST_CASE(arctan)
{
TESTCASE1(arctan, 0, 0);
}
BOOST_AUTO_TEST_CASE(arctanh)
{
TESTCASE1(arctanh, 0, 0);
}
BOOST_AUTO_TEST_CASE(ceiling)
{
TESTCASE1(ceiling, 0, 0);
TESTCASE1(ceiling, 1, 1);
TESTCASE1(ceiling, 1.5, 2);
TESTCASE1(ceiling, -0.8, 0);
TESTCASE1(ceiling, -1, -1);
}
BOOST_AUTO_TEST_CASE(cos)
{
TESTCASE1(cos, 0, 1);
}
BOOST_AUTO_TEST_CASE(cosh)
{
TESTCASE1(cosh, 0, 1);
}
BOOST_AUTO_TEST_CASE(cot)
{
/* TODO */
}
BOOST_AUTO_TEST_CASE(coth)
{
/* TODO */
}
BOOST_AUTO_TEST_CASE(csc)
{
/* TODO */
}
BOOST_AUTO_TEST_CASE(csch)
{
/* TODO */
}
BOOST_AUTO_TEST_CASE(divide)
{
TESTCASE2(divide, 1, 2, 0.5);
TESTCASE2(divide, -1, 2, -0.5);
TESTCASE2(divide, 1, -2, -0.5);
TESTCASE2(divide, -1, -2, 0.5);
}
BOOST_AUTO_TEST_CASE(eq)
{
TESTCASE2(eq, 0, 0, 1);
TESTCASE2(eq, 0, 1, 0);
TESTCASE2(eq, 1, 0, 0);
TESTCASE2(eq, 1, 1, 1);
}
BOOST_AUTO_TEST_CASE(exp)
{
TESTCASE1(exp, 0, 1);
}
BOOST_AUTO_TEST_CASE(factorial)
{
TESTCASE1(factorial, 1, 1);
TESTCASE1(factorial, 3, 6);
TESTCASE1(factorial, 10, 3628800);
}
BOOST_AUTO_TEST_CASE(floor)
{
TESTCASE1(floor, 0, 0);
TESTCASE1(floor, 0.5, 0);
TESTCASE1(floor, 1, 1);
TESTCASE1(floor, -1, -1);
TESTCASE1(floor, -1.2, -2);
}
BOOST_AUTO_TEST_CASE(geq)
{
TESTCASE2(geq, 0, 0, 1);
TESTCASE2(geq, 0, 1, 0);
TESTCASE2(geq, 1, 0, 1);
TESTCASE2(geq, 1, 1, 1);
}
BOOST_AUTO_TEST_CASE(gt)
{
TESTCASE2(gt, 0, 0, 0);
TESTCASE2(gt, 0, 1, 0);
TESTCASE2(gt, 1, 0, 1);
TESTCASE2(gt, 1, 1, 0);
}
BOOST_AUTO_TEST_CASE(leq)
{
TESTCASE2(leq, 0, 0, 1);
TESTCASE2(leq, 0, 1, 1);
TESTCASE2(leq, 1, 0, 0);
TESTCASE2(leq, 1, 1, 1);
}
BOOST_AUTO_TEST_CASE(ln)
{
TESTCASE1(ln, 1, 0);
}
BOOST_AUTO_TEST_CASE(log10)
{
TESTCASE1(log10, 1, 0);
TESTCASE1(log10, 10, 1);
TESTCASE1(log10, 100, 2);
TESTCASE1(log10, 0.1, -1);
TESTCASE1(log10, 0.01, -2);
}
BOOST_AUTO_TEST_CASE(log)
{
TESTCASE2(log, 2, 1, 0);
TESTCASE2(log, 2, 2, 1);
TESTCASE2(log, 2, 8, 3);
TESTCASE2(log, 2, 0.5, -1);
TESTCASE2(log, 3, 1, 0);
TESTCASE2(log, 3, 9, 2);
}
BOOST_AUTO_TEST_CASE(lt)
{
TESTCASE2(lt, 0, 0, 0);
TESTCASE2(lt, 0, 1, 1);
TESTCASE2(lt, 1, 0, 0);
TESTCASE2(lt, 1, 1, 0);
}
BOOST_AUTO_TEST_CASE(max)
{
TESTCASE2(max, 0, 0, 0);
TESTCASE2(max, 0, 1, 1);
TESTCASE2(max, 1, 0, 1);
TESTCASE2(max, 1, 1, 1);
}
BOOST_AUTO_TEST_CASE(min)
{
TESTCASE2(min, 0, 0, 0);
TESTCASE2(min, 0, 1, 0);
TESTCASE2(min, 1, 0, 0);
TESTCASE2(min, 1, 1, 1);
}
BOOST_AUTO_TEST_CASE(neq)
{
TESTCASE2(neq, 0, 0, 0);
TESTCASE2(neq, 0, 1, 1);
TESTCASE2(neq, 1, 0, 1);
TESTCASE2(neq, 1, 1, 0);
}
BOOST_AUTO_TEST_CASE(plus)
{
TESTCASE2(plus, 0, 0, 0);
TESTCASE2(plus, 0, 1, 1);
TESTCASE2(plus, 1, 0, 1);
TESTCASE2(plus, 1, -1, 0);
TESTCASE2(plus, 1, 2, 3);
TESTCASE2(plus, -1, -2, -3);
}
BOOST_AUTO_TEST_CASE(power)
{
TESTCASE2(power, 0, 0, 1);
TESTCASE2(power, 0, 1, 0);
TESTCASE2(power, 1, 0, 1);
TESTCASE2(power, 1, 1, 1);
TESTCASE2(power, 2, 3, 8);
}
BOOST_AUTO_TEST_CASE(rem)
{
TESTCASE2(rem, 0, 1, 0);
TESTCASE2(rem, 0, 2, 0);
TESTCASE2(rem, 1, 1, 0);
TESTCASE2(rem, 1, 2, 1);
TESTCASE2(rem, 2, 3, 2);
TESTCASE2(rem, 3, 2, 1);
}
BOOST_AUTO_TEST_CASE(root)
{
TESTCASE1(root, 1, 1);
TESTCASE1(root, 81, 9);
TESTCASE1(root, 1/4, 0.5);
TESTCASE1(root, 9/100, 0.3);
}
BOOST_AUTO_TEST_CASE(sec)
{
TESTCASE1(sec, 0, 1);
}
BOOST_AUTO_TEST_CASE(sech)
{
TESTCASE1(sech, 0, 1);
}
BOOST_AUTO_TEST_CASE(sin)
{
TESTCASE1(sin, 0, 0);
}
BOOST_AUTO_TEST_CASE(sinh)
{
TESTCASE1(sinh, 0, 0);
}
BOOST_AUTO_TEST_CASE(tan)
{
TESTCASE1(tan, 0, 0);
}
BOOST_AUTO_TEST_CASE(tanh)
{
TESTCASE1(tanh, 0, 0);
}
BOOST_AUTO_TEST_CASE(times)
{
TESTCASE2(times, 0, 0, 0);
TESTCASE2(times, 0, 1, 0);
TESTCASE2(times, 1, 0, 0);
TESTCASE2(times, 2, 3, 6);
TESTCASE2(times, 3, 2, 6);
TESTCASE2(times, -2, 3, -6);
TESTCASE2(times, 2, -3, -6);
TESTCASE2(times, -2, -3, 6);
}
BOOST_AUTO_TEST_CASE($Mod)
{
TESTCASE2($Mod, 0, 1, 0);
TESTCASE2($Mod, 8, 3, 2);
TESTCASE2($Mod, 8, -3, 2);
TESTCASE2($Mod, -8, 3, 1);
TESTCASE2($Mod, -8, -3, 1);
TESTCASE2($Mod, 1, 2, 1);
TESTCASE2($Mod, 1, -2, 1);
TESTCASE2($Mod, -1, 2, 1);
TESTCASE2($Mod, -1, -2, 1);
TESTCASE2($Mod, 2.25, 1, 0.25);
TESTCASE2($Mod, 7.5, 3.5, 0.5);
TESTCASE2($Mod, -7.5, 3.5, 3);
TESTCASE2($Mod, -7.5, 3.5, 3);
}
|
C
|
// Solution to week 3 ex. 1, timing division.
#include <stdlib.h>
#include <math.h> // M_PI
#include <stdio.h>
#include <time.h>
// This is to allow compilation on different compilers.
// If you are using gcc <x86intrin.h> is the right header.
//
#ifdef _MSC_VER
#include <intrin.h>
#else
#include <x86intrin.h>
#endif
double numerical_integration (double x_min, double x_max, int slices);
int main(int argc, char const *argv[]) {
int n_div;
if (argc > 1) {
n_div = atoi(argv[1]);
} else {
n_div = 10000;
}
// Testing the integration for 10, 100 and 1000 slices.
int n = 3;
int *slices = malloc(n * sizeof *slices);
slices[0] = 10;
for (size_t i = 1; i < n; i++) {
slices[i] = slices[i-1]*10;
}
double value, rel_e;
for (size_t i = 0; i < n; i++) {
value = numerical_integration(0, 1, slices[i]);
rel_e = value/M_PI - 1;
printf("slices: %*d, integral: %lf, relative error: %lf\n",
n+1, slices[i], value, rel_e);
}
// counting cycles.
unsigned long long start = __rdtsc();
value = numerical_integration(0, 1, n_div);
unsigned long long end = __rdtsc();
double avg = (double)(end - start)/n_div;
printf("Average number of cycles: %lf\n", avg);
free(slices);
return 0;
}
double numerical_integration (double x_min, double x_max, int slices)
{
double delta_x = (x_max-x_min)/slices;
double x, sum = 0.0;
for (int i=0; i<slices; i++)
{
x = x_min + (i+0.5)*delta_x;
sum = sum + 4.0/(1.0+x*x);
}
return sum*delta_x;
}
|
C
|
//Steven Touchstone
//Programming I
//Simple Arithmetic Examples in C
#include<stdio.h>
int main()
{
//Addition
int a,b,c;
a = 2;
b = 3;
c = a+b;
printf("%d + %d = %d \n",a,b,c);
//Subtraction
int d,e,f;
d = 10;
e= 7;
f = d-e;
printf("%d - %d = %d \n",d,e,f);
//Multiplication
int g,h,i;
g = 20;
h = 3;
i=g*h;
printf("%d * %d = %d \n", g,h,i);
//Division
float j,k,l;
j=1;
k=3;
l=j/k;
printf("%f / %f = %f \n", j,k,l);
//Addition and multiplication
int m,n,o,p;
m=3;
n=4;
o=5;
p = (m+n)*o;
printf("(%d + %d)*%d = %d \n",m,n,o,p);
//Remainder (mod)
int q,r,s;
q = 5;
r = 3;
s= q%r;
printf("%d mod %d = %d \n", q,r,s);
//Overwriting variables
int t;
t=0;
t = t+1;
t = t+1;
t =t*2;
printf("%d \n", t);
return 0;
}
|
C
|
#include "DS3232.h"
int main(void)
{
DateTime_t t;
RTC_Setup();
t.Second = 55;
t.Minute = 59;
t.Hour = 23;
t.Day = Sunday;
t.Date = 31;
t.Month = December;
t.Year = 2016;
RTC_Set(t);
while (1 == 1)
{
t = RTC_Get();
if (RTC_Status() == RTC_Ok)
{
//Do something
}
}
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.