language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
|---|---|
C
|
//Write a C program to check if the number of 3's is greater than the number of 5's in array of length 10.
#include<stdio.h>
#define SIZE 10 //Size if Fixed
void check_condition(int three,int five) //check the number of fives greter,or smaller,or equal
{
if(three == five) //check it equal or not
{
printf("Numbers Three and Five are Equal \n"); //printing a message both are equal
return 0;
}
three>five ?printf("Number of three is Greater %d \n",three): printf("Number of Five is Greater %d \n",five);//check five greter or three
}
int main()
{
int arr[SIZE]; //declaration of array
short int three=0,five=0,i; //declaration of a variables
printf("Enter the Array element of an array\n"); //Entering the Element of an array
for(i=0;i<SIZE;i++)
{
scanf("%d",&arr[i]);
}
for(i=0;i<SIZE;i++) //loop is execute till the size-1
{
if(arr[i]==3) //checking the array index of 3 is equal
{
three++; //count increment by one
}
if(arr[i]==5) //checking the array index of 5 is eqaal
{
five++; //count increment by one
}
}
check_condition(three,five);
}
|
C
|
#include"HashBucket.h"
void Test()
{
HashBucket hashbucket;
//初始化
InitHashBucket(&hashbucket);
//插入
InsertHashBucket(&hashbucket, 5);
InsertHashBucket(&hashbucket, 12);
InsertHashBucket(&hashbucket, 2);
InsertHashBucket(&hashbucket, 6);
InsertHashBucket(&hashbucket, 22);
InsertHashBucket(&hashbucket, 16);
InsertHashBucket(&hashbucket, 3);
//删除
DeleteHashBucket(&hashbucket, 2);
//查找
if (FindHashBucket(&hashbucket, 22))
{
printf("该元素存在!\n");
}
else
{
printf("找不到该元素!\n");
}
printf("Size=%d\n", SizeHashBucket(&hashbucket));
}
int main()
{
Test();
system("pause");
return 0;
}
|
C
|
#include<stdio.h>
#include<unistd.h>
#include<signal.h>
int main()
{
pid_t cpid = fork();
if (cpid ==0)
{
while(1)
{
printf("child in a loop\n");
sleep(1);
}
}
else
{
sleep(5);
kill(cpid,SIGINT);
printf("child killed by parent...\n");
_exit(0);
}
return 0;
}
|
C
|
#include<stdio.h>
#include<malloc.h>
struct node{
int data;
struct node *left, *right;
};
struct node *root=NULL;
void insert(struct node *ptr)
{
int x,i,j;
printf("enter element: ");
scanf("%d",&x);
struct node *ptr2=(struct node*)malloc(sizeof(struct node));
ptr2->data=x;
ptr2->left=NULL;
ptr2->right=NULL;
if(root==NULL){
root=ptr2;
return;}
while(1){
printf("left of %d (0) or right of %d (1): ",ptr->data,ptr->data);
scanf("%d",&j);
switch(j)
{
case 0: if(ptr->left==NULL)
{
ptr->left=ptr2;
return;
}
ptr=ptr->left;
break;
case 1: if(ptr->right==NULL)
{
ptr->right=ptr2;
return;
}
ptr=ptr->right;
break;
}
}
}
void inorder(struct node *ptr)
{
if(ptr==NULL)
return;
inorder(ptr->left);
printf("| %d ",ptr->data);
inorder(ptr->right);
}
int main()
{
int c;
while(1)
{
printf("1.insert\n2.display\n3.exit");
scanf("%d",&c);
switch(c)
{
case 1: insert(root);
break;
case 2: inorder(root);
printf("|\n");
break;
case 3: goto end;
}
}
end:;
}
|
C
|
#include "FTP.h"
int ftpConnect(ftp* ftp, const char* ip, int port) {
int socketfd;
char rd[1024];
socketfd = connectSocket(ip, port);
ftp->control_socket_fd = socketfd;
ftp->data_socket_fd = 0;
ftpRead(ftp, rd, sizeof(rd));
return 0;
}
static int connectSocket(const char* ip, int port) {
int sockfd;
struct sockaddr_in server_addr;
// server address handling
bzero((char*) &server_addr, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = inet_addr(ip);
server_addr.sin_port = htons(port);
// open an TCP socket
sockfd = socket(AF_INET, SOCK_STREAM, 0);
// connect to the server
connect(sockfd, (struct sockaddr *) &server_addr, sizeof(server_addr));
return sockfd;
}
int ftpRead(ftp* ftp, char* str, size_t size) {
FILE* fp = fdopen(ftp->control_socket_fd, "r");
do {
memset(str, 0, size);
str = fgets(str, size, fp);
printf("%s", str);
} while (!('1' <= str[0] && str[0] <= '5') || str[3] != ' ');
return 0;
}
|
C
|
#include <stdio.h>
int main(void)
{
int n1, d1, n2, d2, n_res, d_res;
char operator;
printf("Enter two fractions separated by +, -, * or /: ");
scanf("%d /%d %c %d /%d", &n1, &d1, &operator, &n2, &d2);
switch (operator) {
case '+':
n_res= n1 * d2 + n2 * d1;
d_res= d1 * d2;
break;
case '-':
n_res= n1 * d2 - n2 * d1;
d_res= d1 * d2;
break;
case '*':
n_res= n1 * n2;
d_res= d1 * d2;
break;
case '/':
n_res= n1 * d2;
d_res= n2 * d1;
break;
}
/* Find the GCD of the resulting fraction */
int temp, n_temp = n_res, gcd = d_res;
while (n_temp != 0) {
temp = gcd % n_temp;
gcd = n_temp;
n_temp = temp;
}
/* Print result in its simplest form */
if (n_res / gcd == d_res / gcd)
printf("Result is: %d", n_res / gcd);
else if (n_res > d_res)
printf("Result is: %d %d/%d", n_res / d_res, n_res % d_res, d_res);
else
printf("Result is: %d/%d", n_res / gcd, d_res / gcd);
return 0;
}
|
C
|
#ifndef PRIORITYQUEUE_H_
#define PRIORITYQUEUE_H_
#include <stdio.h>
#include <stdlib.h>
#include "heap.h"
typedef void* KEY_TYPE;
typedef void* VALUE_TYPE;
typedef struct PriorityQueue PriorityQueue;
struct PriorityQueue{
Heap *heap;
};
PriorityQueue* priorityqueue_constructor( int (*priority_queue_compare_function)(void*, void*) );
void priorityqueue_push(KEY_TYPE key, VALUE_TYPE value, PriorityQueue *queue);
VALUE_TYPE priorityqueue_pop(PriorityQueue *queue);
VALUE_TYPE priorityqueue_front(PriorityQueue *queue);
int priorityqueueIsEmpty(PriorityQueue *queue);
void priorityqueueSetKey(KEY_TYPE key, VALUE_TYPE value, PriorityQueue* queue);
#endif
|
C
|
#include <stdio.h>
#include <ctype.h>
/*
The program examines each character from the standart input until reaching EOF
The program is keeping track whether the currnt char is at a beginning of a sentance, at a middle of a sentane, or inside a quotation marks, and deals with the current character accordingly.
*/
enum status {SB, SEN, QM};
/* SB - sentance beginning, SEN - sentance, QM - quotation marks */
int main () {
int c;
int state = SB;
printf("Please enter your FRESHEST text:\n\n");
while ((c=getchar()) != EOF) {
switch (state) {
case SB: /* Beginning of sentance */
if (islower(c))
c = toupper(c);
if (!isspace(c))
state = SEN;
if (c == '\"')
state = QM;
break;
case QM: /* Inside quotation marks */
if (islower(c))
c = toupper(c);
if (c == '\"')
state = SEN;
break;
case SEN: /* Inside a sentance */
if (isupper(c))
c = tolower(c);
if (c == '\"')
state = QM;
if (c == '.')
state = SB;
break;
}
if (!isdigit(c))
putchar(c);
}
return 0;
}
|
C
|
/**
* C program to print the given number pattern
*/
#include <stdio.h>
int main()
{
int num;
printf("Enter any number: ");
scanf("%d", &num);
while(num != 0)
{
printf("%d\n", num);
num = num / 10;
}
return 0;
}
Outpu
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* check_instruction.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: nkamolba <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/02/07 18:33:17 by nkamolba #+# #+# */
/* Updated: 2018/03/16 16:37:15 by fbabin ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/asm.h"
static int check_label_infront(char *str, t_champ *champ, int line_nb)
{
int i;
int j;
t_label *label;
i = 0;
while (str[i] && !ft_isspace(str[i]))
{
if (str[i] == LABEL_CHAR)
{
j = 0;
while (j < i)
{
if (!ft_strchr(LABEL_CHARS, str[j++]))
ft_error_line("label contains non-LABEL_CHARS", line_nb);
}
if (!(label = (t_label *)malloc(sizeof(t_label))))
ft_error_line("failed to malloc label", line_nb);
label->name = ft_strsub(str, 0, i);
label->addr = champ->accu_len;
ft_lstpushback(&champ->labels, label, sizeof(t_label));
return (i + 1);
}
i++;
}
return (0);
}
static t_op *check_instruction(char *str, int line_nb)
{
int instruction_len;
char *instruction;
t_op *op;
instruction = NULL;
instruction_len = 0;
while (str[instruction_len] && !ft_isspace(str[instruction_len]))
instruction_len++;
if (!(instruction = ft_strsub(str, 0, instruction_len)))
ft_error_line("ft_strsub failed in check_instruction", line_nb);
if (!(op = get_op(instruction)))
ft_error_line("instuction not found", line_nb);
ft_strdel(&instruction);
return (op);
}
static t_inst *create_inst(t_champ *champ, t_op *op, int line_nb)
{
t_inst *inst;
if (!(inst = (t_inst *)malloc(sizeof(t_inst))))
ft_error_line("failed to malloc inst", line_nb);
inst->opcode = op->opcode;
inst->addr = champ->accu_len;
inst->len = 1 + op->ocp;
inst->ocp = op->ocp;
inst->direct_len = op->direct_len;
return (inst);
}
static void remove_comment(char *str)
{
int i;
i = ft_strchrindex(str, COMMENT_CHAR);
if (i >= 0)
{
while (str[i])
str[i++] = 0;
}
}
int check_instruction_line(t_champ *champ, char *line, int line_nb)
{
char *str;
int i;
t_op *op;
t_inst *inst;
remove_comment(line);
if (!(str = ft_strtrim(line)))
return (1);
i = check_label_infront(str, champ, line_nb);
if (!str[i])
{
ft_strdel(&str);
return (1);
}
i = skip_space(str, i);
op = check_instruction(&str[i], line_nb);
inst = create_inst(champ, op, line_nb);
i = skip_nonspace(str, i);
i = skip_space(str, i);
check_parameters(&str[i], op, inst, line_nb);
champ->accu_len += inst->len;
ft_lstpushback(&champ->inst, inst, sizeof(t_inst));
ft_strdel(&str);
return (1);
}
|
C
|
#include<stdio.h>
#include<string.h> //strlen
#include<stdlib.h> //strlen
#include<sys/socket.h>
#include<arpa/inet.h> //inet_addr
#include<unistd.h> //write
#include<pthread.h> //for threading , link with lpthread
clock_t start , end ;
//the thread function
void *client_connection(void *);
int main(int argc , char *argv[]){
int socket_desc , client_sock , c;
struct sockaddr_in server , client;
socket_desc = socket(AF_INET , SOCK_STREAM , 0);
if (socket_desc == -1)
printf("Could not create socket");
puts("Socket created");
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons( 9999 );
//Bind
if( bind(socket_desc,(struct sockaddr *)&server , sizeof(server)) < 0){
//print the error message
perror("bind failed. Error");
return 1;
}
puts("bind done");
//Listen
listen(socket_desc , 3);
//Accept and incoming connection
puts("Waiting for incoming connections...");
c = sizeof(struct sockaddr_in);
//Accept and incoming connection
//puts("Waiting for incoming connections...");
c = sizeof(struct sockaddr_in);
pthread_t thread_id[10];
int k= 0 ;
int pass[5] = {1234 , 4321 , 5700 , 5306 , 7300} ;
while( (client_sock = accept(socket_desc, (struct sockaddr *)&client, (socklen_t*)&c)) ){
int m , x ;
read(client_sock , &m , sizeof(int));
for(x=0 ; x<5 ; x++){
if(m == pass[x])
break ;
}
if( x < 5){
puts("Connection accepted\n");
write(client_sock , &m , sizeof(int));
if( pthread_create( &thread_id[k] , NULL , client_connection , (void*) &client_sock) < 0){
perror("could not create thread\n");
return 1;
}
if( k >= 10){
k = 0 ;
while(k < 10){
pthread_join(thread_id[k++], NULL);
}
k = 0 ;
}
}
else{
puts("Connection rejected Unauthorised user\n");
char *msg = "No user with this password is authorised" ;
int m = -1 ;
write(client_sock , &m , sizeof(int));
write(client_sock, msg , strlen(msg));
break ;
}
}
if (client_sock < 0)
{
perror("accept failed");
return 1;
}
return 0;
}
void *client_connection(void *socket_desc)
{
//Get the socket descriptor
int sock = *(int*)socket_desc;
int read_size;
char *message , client_message[2000];
while(1){
sleep(1) ;
message = "\n1. Echo request and reply\n2. Application Layer RTT management\n3. File uploading \n4. Sum of two numbers\n5. refresh and exit\n";
write(sock , message , strlen(message));
char choice[1000];
read(sock,choice,1000);
printf("choice %s ",choice);
int cond=0 , k=0;double trip[100];
if(choice[0]=='1'){
do{
read_size = recv(sock , client_message , 2000 , 0) ;
start = clock() ;
sleep(1) ;
client_message[read_size] = '\0';
printf("message recieved is : %s \n" , client_message) ;
write(sock , client_message , strlen(client_message));
read_size = recv(sock , client_message , 2000 , 0) ;
end = clock() ;
//clear the message buffer
memset(client_message, 0, 2000);
double d = ((double)(end-start))/CLOCKS_PER_SEC ;
read(sock,&cond,sizeof(cond));
write(sock , &d , sizeof(d));
}while(cond==1);
}
else if(choice[0]=='2'){
int i , k ;
read(sock,&k,sizeof(k));
double d[k] ;
for(i=0 ; i<k ; i++){
start = clock() ;
read_size = recv(sock , client_message , 2000 , 0) ;
client_message[read_size] = '\0';
write(sock , client_message , strlen(client_message));
memset(client_message, 0, 2000);
//sleep(1) ;
end = clock() ;
d[i] = ((double)(end-start))/CLOCKS_PER_SEC ;
}
double d1 = 0 ;
for(i=0 ; i<k ; i++){
printf("rtt : %lf\n", d[i]) ;
d1 += d[i] ;
}
d1 /= k ;
write(sock , &d1 , sizeof(double));
}
else if(choice[0]=='3'){
double d ;
char buffer[1024] ;
start = clock() ;
char* fr_name = "/home/sushant/Desktop/receive.txt";
FILE *fr = fopen(fr_name, "a");
if(fr == NULL)
printf("File %s Cannot be opened file on server.\n", fr_name);
else{
bzero(buffer, 1024);
int fr_block_sz = 0;
while(fr_block_sz = recv(sock , buffer,1024, 0)){
if(fr_block_sz < 0)
perror("Error receiving file from client to server.\n");
int write_sz = fwrite(buffer , sizeof(char), fr_block_sz, fr);
if(write_sz < fr_block_sz)
perror("File write failed on server.\n");
else if(fr_block_sz)
break;
bzero(buffer, 1024);
}
end = clock() ;
printf("File recieved from client \n");
d = ((double)(end-start))/CLOCKS_PER_SEC ;
write(sock , &d , sizeof(double));
fclose(fr);
}
}
else if(choice[0]=='4'){
int i , k , b , sum=0;
read(sock,&k,sizeof(k));
read(sock,&b,sizeof(b));
printf("\ntwo number recieved are : %d and %d\n" , k , b) ;
sum = k+b ;
write(sock , &sum , sizeof(sum));
}
}
return 0;
}
|
C
|
/************************************************************************
* Name: Rohan Sharma *
* Login: rsharma1 *
* Student Number: 639271 *
* COMP30023 Computer Systems Project 2 - server/client for connect4 *
* *
* client.c: The file which contains the client side code of connect4. *
***********************************************************************/
/*-------------------------- Libraries --------------------------------*/
#include "client.h"
/*---------------------------------------------------------------------*/
/*------------------------- Main ---------------------*/
int main(int argc, char *argv[]) {
/* Ensure enough arguments are passed */
if(argc < 3) {
fprintf(stderr, "Usage: %s host port.\n", argv[0]);
exit(EXIT_FAILURE);
}
/* Initialize a socket to communicate to the server */
int socket_fd = initialize_client_socket(argv[1], atoi(argv[2]));
/* Begin the connect4 game against the server. */
/* The data structures required for this game */
c4_t board;
int move, n;
init_empty(board);
print_config(board);
/* This loop does 2 moves each iteration. One for the
* human player and one for the server.
*/
while ((move = get_move(board)) != EOF) {
/* process the person's move */
if (do_move(board, move, YELLOW)!=1) {
printf("Panic\n");
break;
}
/* Send the move to the server */
int converted_move = htonl(move);
n = write(socket_fd, &converted_move, sizeof(converted_move));
if(n < 0) {
perror("Failed to write to socket.\n");
break;
}
print_config(board);
/* and did they win??? */
if (winner_found(board) == YELLOW) {
/* rats, the person beat us! */
printf("Ok, you beat me, beginner's luck!\n");
break;
}
/* was that the last possible move? */
if (!move_possible(board)) {
/* yes, looks like it was */
printf("An honourable draw\n");
break;
}
/* Ask the server for its move */
n = read(socket_fd, &move, sizeof(move));
move = ntohl(move);
if(n < 0) {
perror("Failed to read from socket.\n");
break;
}
/* pretend to be thinking hard */
printf("Ok, let's see now....");
sleep(1);
/* then play the move */
printf(" I play in column %d\n", move);
if (do_move(board, move, RED)!=1) {
printf("Panic\n");
break;
}
print_config(board);
/* and did we win??? */
if (winner_found(board) == RED) {
/* yes!!! */
printf("I guess I have your measure!\n");
break;
}
/* and did they win??? */
if (winner_found(board) == YELLOW) {
/* rats, the person beat us! */
printf("Ok, you beat me, beginner's luck!\n");
break;
}
/* Was that the last possible move? */
if (!move_possible(board)) {
/* yes, looks like it was */
printf("An honourable draw\n");
break;
}
/* otherwise, the game goes on */
}
printf("FINALMOVE=%d", move);
printf("\n");
close(socket_fd);
return 0;
}
/*---------------------------------------------------------------------*/
|
C
|
/*
* =====================================================================================
*
* Filename: hello.c
*
* Description: simple kernel module
*
* Version: 1.0
* Created: 09.02.2021 23:24:29
* Revision: none
* Compiler: gcc
*
* Author: YOUR NAME (),
* Organization:
*
* =====================================================================================
*/
#include <linux/module.h>
/* This func shall be invoked as soon as this LKM is loaded. Note the func prototype */
int hello_world_init_module(void) {
printk(KERN_INFO "Hello world Module Loaded Successfully\n");
/*
* A non 0 return means init_module failed; module can't be loaded
*/
return 0;
}
/*
This function shall be invoked as soon as this LKM is unloaded.
Note the function prototype
*/
void hello_world_cleanup_module(void) {
printk(KERN_INFO "Goodbye hello world LKM\n");
}
/*
Tell the kernel which are init and cleanup function for this module. If you do not do this module.
If you do not do this registration, kernel would try to use 'init_module' and 'cleanup_module' instead
*/
module_init(hello_world_init_module);
module_exit(hello_world_cleanup_module);
/*Module information*/
#define AUTHOR_NAME "MOS"
#define MODULE_DESC "HELLOWORLD"
MODULE_AUTHOR(AUTHOR_NAME);
MODULE_DESCRIPTION(MODULE_DESC);
MODULE_LICENSE("GPL");
|
C
|
//
// Sorts a list using multiple threads
//
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <limits.h>
#define MAX_THREADS 65536
#define MAX_LIST_SIZE 300000000
#define DEBUG 0
// Thread variables
//
// VS: ... declare thread variables, mutexes, condition varables, etc.,
// VS: ... as needed for this assignment
//
pthread_t threads[MAX_THREADS];
pthread_attr_t attr;
pthread_barrier_t barrier[3];
int q;
int *ptr;
// Global variables
struct timespec curr;
int num_threads; // Number of threads to create - user input
int list_size; // List size
int *list; // List of values
int *work; // Work array
int *list_orig; // Original list of values, used for error checking
// Print list - for debugging
void print_list(int *list, int list_size) {
int i;
for (i = 0; i < list_size; i++) {
printf("[%d] \t %16d\n", i, list[i]);
}
printf("--------------------------------------------------------------------\n");
}
// Comparison routine for qsort (stdlib.h) which is used to
// a thread's sub-list at the start of the algorithm
int compare_int(const void *a0, const void *b0) {
int a = *(int *)a0;
int b = *(int *)b0;
if (a < b) {
return -1;
} else if (a > b) {
return 1;
} else {
return 0;
}
}
// Return index of first element larger than or equal to v in sorted list
// ... return last if all elements are smaller than v
// ... elements in list[first], list[first+1], ... list[last-1]
//
// int idx = first; while ((v > list[idx]) && (idx < last)) idx++;
//
int binary_search_lt(int v, int *list, int first, int last) {
// Linear search code
// int idx = first; while ((v > list[idx]) && (idx < last)) idx++; return idx;
int left = first;
int right = last-1;
if (list[left] >= v) return left;
if (list[right] < v) return right+1;
int mid = (left+right)/2;
while (mid > left) {
if (list[mid] < v) {
left = mid;
} else {
right = mid;
}
mid = (left+right)/2;
}
return right;
}
// Return index of first element larger than v in sorted list
// ... return last if all elements are smaller than or equal to v
// ... elements in list[first], list[first+1], ... list[last-1]
//
// int idx = first; while ((v >= list[idx]) && (idx < last)) idx++;
//
int binary_search_le(int v, int *list, int first, int last) {
// Linear search code
// int idx = first; while ((v >= list[idx]) && (idx < last)) idx++; return idx;
int left = first;
int right = last-1;
if (list[left] > v) return left;
if (list[right] <= v) return right+1;
int mid = (left+right)/2;
while (mid > left) {
if (list[mid] <= v) {
left = mid;
} else {
right = mid;
}
mid = (left+right)/2;
}
return right;
}
// Sort list via parallel merge sort
//
// VS: ... to be parallelized using threads ...
//
void sort_list(int q) {
int i, level, my_id;
int np, my_list_size;
int ptr[num_threads+1];
int my_blk, my_idx;
int my_blk_size, my_search_blk, my_search_idx, my_search_idx_max;
int my_write_blk, my_write_idx;
int my_search_count;
int idx, i_write;
np = list_size/num_threads; // Sub list size
// Initialize starting position for each sublist
for (my_id = 0; my_id < num_threads; my_id++) {
ptr[my_id] = my_id * np;
}
ptr[num_threads] = list_size;
// Sort local lists
for (my_id = 0; my_id < num_threads; my_id++) {
my_list_size = ptr[my_id+1]-ptr[my_id];
qsort(&list[ptr[my_id]], my_list_size, sizeof(int), compare_int);
}
if (DEBUG) print_list(list, list_size);
// Sort list
for (level = 0; level < q; level++) {
// Each thread scatters its sub_list into work array
for (my_id = 0; my_id < num_threads; my_id++) {
my_blk_size = np * (1 << level);
my_blk = ((my_id >> level) << level);
my_idx = ptr[my_blk];
my_search_blk = ((my_id >> level) << level) ^ (1 << level);
my_search_idx = ptr[my_search_blk];
my_search_idx_max = my_search_idx+my_blk_size;
my_write_blk = ((my_id >> (level+1)) << (level+1));
my_write_idx = ptr[my_write_blk];
idx = my_search_idx;
my_search_count = 0;
// Binary search for 1st element
if (my_search_blk > my_blk) {
idx = binary_search_lt(list[ptr[my_id]], list, my_search_idx, my_search_idx_max);
} else {
idx = binary_search_le(list[ptr[my_id]], list, my_search_idx, my_search_idx_max);
}
my_search_count = idx - my_search_idx;
i_write = my_write_idx + my_search_count + (ptr[my_id]-my_idx);
work[i_write] = list[ptr[my_id]];
// Linear search for 2nd element onwards
for (i = ptr[my_id]+1; i < ptr[my_id+1]; i++) {
if (my_search_blk > my_blk) {
while ((list[i] > list[idx]) && (idx < my_search_idx_max)) {
idx++; my_search_count++;
}
} else {
while ((list[i] >= list[idx]) && (idx < my_search_idx_max)) {
idx++; my_search_count++;
}
}
i_write = my_write_idx + my_search_count + (i-my_idx);
work[i_write] = list[i];
}
}
// Copy work into list for next itertion
for (my_id = 0; my_id < num_threads; my_id++) {
for (i = ptr[my_id]; i < ptr[my_id+1]; i++) {
list[i] = work[i];
}
}
if (DEBUG) print_list(list, list_size);
}
}
void *multithreaded_routine(void *id){
int my_id = (int)(size_t)id;
int np = list_size/num_threads;
int my_list_size = ptr[my_id + 1] - ptr[my_id];
qsort(&list[ptr[my_id]], my_list_size, sizeof(int), compare_int);
pthread_barrier_wait(&barrier[0]);
for (int level = 0; level < q; level++) {
// Each thread scatters its sub_list into work array
int my_blk, my_idx;
int my_blk_size, my_search_blk, my_search_idx, my_search_idx_max;
int my_write_blk, my_write_idx;
int my_search_count;
int idx, i_write,i;
my_blk_size = np * (1 << level);
my_blk = ((my_id >> level) << level);
my_idx = ptr[my_blk];
my_search_blk = ((my_id >> level) << level) ^ (1 << level);
my_search_idx = ptr[my_search_blk];
my_search_idx_max = my_search_idx+my_blk_size;
my_write_blk = ((my_id >> (level+1)) << (level+1));
my_write_idx = ptr[my_write_blk];
idx = my_search_idx;
my_search_count = 0;
// Binary search for 1st element
if (my_search_blk > my_blk) {
idx = binary_search_lt(list[ptr[my_id]], list, my_search_idx, my_search_idx_max);
} else {
idx = binary_search_le(list[ptr[my_id]], list, my_search_idx, my_search_idx_max);
}
my_search_count = idx - my_search_idx;
i_write = my_write_idx + my_search_count + (ptr[my_id]-my_idx);
work[i_write] = list[ptr[my_id]];
// Linear search for 2nd element onwards
for (int i = ptr[my_id]+1; i < ptr[my_id+1]; i++) {
if (my_search_blk > my_blk) {
while ((list[i] > list[idx]) && (idx < my_search_idx_max)) {
idx++; my_search_count++;
}
} else {
while ((list[i] >= list[idx]) && (idx < my_search_idx_max)) {
idx++; my_search_count++;
}
}
i_write = my_write_idx + my_search_count + (i-my_idx);
work[i_write] = list[i];
}
pthread_barrier_wait(&barrier[1]);
// Copy work into list for next itertion
for (int i = ptr[my_id]; i < ptr[my_id+1]; i++) {
list[i] = work[i];
}
pthread_barrier_wait(&barrier[2]);
}
pthread_exit(NULL);
}
void sort_list_parallel(int q) {
int i, level, my_id,status;
int np, my_list_size;
np = list_size/num_threads; // Sub list size
ptr = (int*)malloc((num_threads+1) * sizeof(int));
// Initialize starting position for each sublist
for (my_id = 0; my_id < num_threads; my_id++) {
ptr[my_id] = my_id * np;
}
ptr[num_threads] = list_size;
// Sort local lists
if (DEBUG) print_list(list, list_size);
for (my_id = 0; my_id < num_threads; my_id++) {
// Sort list
status = pthread_create(&threads[my_id], &attr, multithreaded_routine, (void *)(size_t) my_id);
if (status != 0){
printf("Non-zero status when creating thread # %d\n", my_id);}
}
for (int i = 0; i < num_threads; i++) {
pthread_join(threads[i], NULL);
}
//-----if (DEBUG) print_list(list, list_size);
}
// Main program - set up list of random integers and use threads to sort the list
//
// Input:
// k = log_2(list size), therefore list_size = 2^k
// q = log_2(num_threads), therefore num_threads = 2^q
//
int main(int argc, char *argv[]) {
struct timespec start, stop, stop_qsort;
double total_time, time_res, total_time_qsort;
int k, j, error;
// Read input, validate
if (argc != 3) {
printf("Need two integers as input \n");
printf("Use: <executable_name> <log_2(list_size)> <log_2(num_threads)>\n");
exit(0);
}
k = atoi(argv[argc-2]);
if ((list_size = (1 << k)) > MAX_LIST_SIZE) {
printf("Maximum list size allowed: %d.\n", MAX_LIST_SIZE);
exit(0);
};
q = atoi(argv[argc-1]);
if ((num_threads = (1 << q)) > MAX_THREADS) {
printf("Maximum number of threads allowed: %d.\n", MAX_THREADS);
exit(0);
};
if (num_threads > list_size) {
printf("Number of threads (%d) < list_size (%d) not allowed.\n",
num_threads, list_size);
exit(0);
};
// Allocate list, list_orig, and work
list = (int *) malloc(list_size * sizeof(int));
list_orig = (int *) malloc(list_size * sizeof(int));
work = (int *) malloc(list_size * sizeof(int));
//
// VS: ... May need to initialize mutexes, condition variables,
// VS: ... and their attributes
//
// Initialize list of random integers; list will be sorted by
// multi-threaded parallel merge sort
// Copy list to list_orig; list_orig will be sorted by qsort and used
// to check correctness of multi-threaded parallel merge sort
srand48(0); // seed the random number generator
for (j = 0; j < list_size; j++) {
list[j] = (int) lrand48();
list_orig[j] = list[j];
}
// duplicate first value at last location to test for repeated values
list[list_size-1] = list[0]; list_orig[list_size-1] = list_orig[0];
// Create threads; each thread executes find_minimum
clock_gettime(CLOCK_REALTIME, &start);
//
// VS: ... may need to initialize mutexes, condition variables, and their attributes
//
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_JOINABLE);
int rc = pthread_barrier_init(&barrier[0], NULL, num_threads);
if (rc) {
fprintf(stderr, "pthread_barrier_init: %s\n", rc);
exit(1);
}
rc = pthread_barrier_init(&barrier[1], NULL, num_threads);
if (rc) {
fprintf(stderr, "pthread_barrier_init: %s\n", rc);
exit(1);
}
rc = pthread_barrier_init(&barrier[2], NULL, num_threads);
if (rc) {
fprintf(stderr, "pthread_barrier_init: %s\n", rc);
exit(1);
}
// Serial merge sort
// VS: ... replace this call with multi-threaded parallel routine for merge sort
// VS: ... need to create threads and execute thread routine that implements
// VS: ... parallel merge sort
// sort_list(q);
sort_list_parallel(q);
// Compute time taken
clock_gettime(CLOCK_REALTIME, &stop);
total_time = (stop.tv_sec-start.tv_sec)
+0.000000001*(stop.tv_nsec-start.tv_nsec);
// Check answer
qsort(list_orig, list_size, sizeof(int), compare_int);
clock_gettime(CLOCK_REALTIME, &stop_qsort);
total_time_qsort = (stop_qsort.tv_sec-stop.tv_sec)
+0.000000001*(stop_qsort.tv_nsec-stop.tv_nsec);
error = 0;
for (j = 1; j < list_size; j++) {
if (list[j] != list_orig[j]) error = 1;
}
if (error != 0) {
printf("Houston, we have a problem!\n");
}
// Print time taken
printf("List Size = %d, Threads = %d, error = %d, time (sec) = %8.4f, qsort_time = %8.4f\n",
list_size, num_threads, error, total_time, total_time_qsort);
// VS: ... destroy mutex, condition variables, etc.
pthread_attr_destroy(&attr);
free(list); free(work); free(list_orig);
}
|
C
|
/**
@file base_api.c
@brief Implementation of the basic parts of the OpenGrain API (init, shutdown, error reporting)
@author John Williamson
Copyright (c) 2011 All rights reserved.
Licensed under the BSD 3 clause license. See COPYING.
This file is part of the OpenGrain distribution.
http://opengrain.sourceforge.net
*/
#include "base_api.h"
#include "../sys_audio.h"
#include "errors.h"
#include "audio_api.h"
GRContext *gr_context;
/** Set the default settings for the context.
Sets all flags to the default state, creates all of the object lists,
initialises the audio device prototype.
@arg context The context to initialise
*/
static void setDefaultGrContext(GRContext *context)
{
int i;
// first disable everything
for(i=0;i<GR_MAX_FLAGS;i++)
context->global_flags[i] = 0;
}
/** Initialises the OpenGrain system. This must be called _before_ any other OpenGrain calls. */
void grInit(void)
{
gr_context = malloc(sizeof(*gr_context));
if(!gr_context)
{
// can't use grFatalError because that relies on a working context!
fprintf(stderr, "Fatal error: Out of memory when allocating context.\n");
exit(-1);
}
grClearError();
setDefaultGrContext(gr_context);
set_default_audio_api();
pre_init_sys_audio();
}
/** Shuts down the OpenGrain system, stopping playback, releasing audio devices, shutting down all
playback threads and freeing all allocated memory */
void grShutdown(void)
{
post_shutdown_sys_audio();
free(gr_context->prototype);
free(gr_context);
}
/**
Return the last error that occured.
@return The integer error code, or 0 if no error
**/
int grGetLastError(void)
{
return gr_context->last_error;
}
/** Return the last error that occured as a string description.
@return The description of the errorm or "No error" if no error.
**/
const char *grGetLastErrorString(void)
{
if(gr_context->last_error>=0 && gr_context->last_error<=GR_MAX_ERROR_CODE)
return opengrain_error_codes[gr_context->last_error];
else
return "Bad error code!";
}
/** Get the last error message in full, with any additional information
that the error might have
*/
char *grGetLastErrorMessage(void)
{
return gr_context->last_error_string;
}
/** Enable one of the global flags.
@arg flag Flag to enable
*/
void grEnable(int flag)
{
if(flag>=0 && flag<=GR_MAX_FLAGS)
gr_context->global_flags[flag] = 1;
else
grError(GR_ERROR_BAD_FLAG, "Invalid flag in grEnable()");
}
/** Disable one of the global flags.
@arg flag Flag to disable
*/
void grDisable(int flag)
{
if(flag>=0 && flag<=GR_MAX_FLAGS)
gr_context->global_flags[flag] = 0;
else
grError(GR_ERROR_BAD_FLAG, "Invalid flag in grDisable()");
}
/** Query the state of a global flag.
Returns 1 if the given flag is enabled, 0 otherwise.
@arg flag Flag to query
@return 0 if flag is disabled, 1 if it is enabled
*/
int grIsEnabled(int flag)
{
if(flag>=0 && flag<=GR_MAX_FLAGS)
return gr_context->global_flags[flag];
else
{
grError(GR_ERROR_BAD_FLAG, "Invalid flag in grIsEnabled()");
return 0;
}
}
|
C
|
/*
* communication.h
*
* Created on: 17 sty 2019
* Author: Dunajski
*/
#ifndef COMMUNICATION_H_
#define COMMUNICATION_H_
#include <avr/interrupt.h>
#include "types.h"
#include "random.h"
extern unsigned char * p_dada;
/*
*******************************************************************************
* Umozliwia wyslanie zmiennej o wielkosci 8b w postaci ASCII.
* [in] uint8 integer - wartosc liczbowa do wyslania.
*******************************************************************************
*/
void PutUInt8ToSerial(uint8 integer);
/*
*******************************************************************************
* Umozliwia wyslanie zmiennej o wielkosci 16b w postaci ASCII.
* [in] uint16 value - wartosc liczbowa do wyslania,
* [in] uchar leading_zeros - umozliwia wyslanie zer poprzedzajacych,
* [in] uchar size - ilosc znakow do wyslania,
* [out] uint8 - ilosc wyslanych znakow.
*******************************************************************************
*/
void PutUInt16ToSerial(uint16 value, uchar leading_zeros, uchar size);
/*
*******************************************************************************
* Umozliwia wyslanie zmiennej ze znakiem o wielkosci 16b w postaci ASCII.
* [in] uint16 value - wartosc liczbowa do wyslania,
* [in] uchar leading_zeros - umozliwia wyslanie zer poprzedzajacych,
* [in] uchar size - ilosc znakow do wyslania,
* [out] uint8 - ilosc wyslanych znakow.
*******************************************************************************
*/
void PutSInt16ToSerial(int16 value, uchar leading_zeros, uchar size);
/*
*******************************************************************************
* Umozliwia wyslanie zmiennej ze znakiem o wielkosci 32b w postaci ASCII.
* [in] uint32 value - wartosc liczbowa do wyslania,
* [in] uchar leading_zeros - umozliwia wyslanie zer poprzedzajacych,
* [in] uchar size - ilosc znakow do wyslania,
* [out] uint8 - ilosc wyslanych znakow.
*******************************************************************************
*/
void PutUInt32ToSerial(uint32 value, uchar leading_zeros, uchar size);
/*
*******************************************************************************
* Umozliwia wyslanie zmiennej ze znakiem o wielkosci 32b w postaci ASCII.
* [in] sint32 value - wartosc liczbowa do wyslania,
* [in] uchar leading_zeros - umozliwia wyslanie zer poprzedzajacych,
* [in] uchar size - ilosc znakow do wyslania,
* [out] uint8 - ilosc wyslanych znakow.
*******************************************************************************
*/
void PutSInt32ToSerial(int32 value, uchar leading_zeros, uchar size);
/*
*******************************************************************************
* Umozliwia umieszczenie w buforze nadawczym jednego znaku, po umieszczeniu
* uruchamia przerwania od wysylania.
* [in] uchar data - znak do wyslania.
*******************************************************************************
*/
void PutToSerial(uchar data);
/*
*******************************************************************************
* Umozliwia umieszczanie danych z bufora pod wskazany adres.
* [in] uchar * p_dada - adres do zapisu znakow z bufora odbiorczego.
*******************************************************************************
*/
uchar GetFromSerial(uchar *p_dada);
/*
*******************************************************************************
* Umozliwia umieszczenie w buforze nadawczym lancucha znakowego.
* [in] char * msg - lancuch znakow, do wyslania.
*******************************************************************************
*/
void StrToSerial(char *msg);
#endif /* COMMUNICATION_H_ */
|
C
|
// Authors: Connor Hanson, Tiger Ji
// Connor Hanson: cbhanson2@wisc.edu - chanson
// Tiger Ji: tfji@wisc.edu - tfji
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <semaphore.h>
#include "queue.h"
#include "queueStat.h"
/**
* Prints queue stats
*
* @param:
* Queue *q - pointer to queue to have stats printed to stderr
*/
void printQueueStats(Queue *q){
fprintf(stderr,"%s%d\n", "Capacity: ", q->capacity);
fprintf(stderr,"%s%d\n", "Enqueue Count: ", q->enqueueCount -1);
fprintf(stderr,"%s%d\n", "Dequeue Count: ", q->dequeueCount-1);
fprintf(stderr,"%s%f\n", "Enqueue Time: ", q->enqueueTime);
fprintf(stderr,"%s%f\n", "Dequeue Time: ", q->dequeueTime);
}
/**
* Increments enqueue count
*
* @param:
* Queue *q - pointer to queue to have stat changed
*/
void incEnqueue(Queue *q){
q->enqueueCount += 1;
}
/**
* Increments dequeue count
*
* @param:
* Queue *q - pointer to queue to have stat changed
*/
void incDequeue(Queue *q){
q->dequeueCount += 1;
}
/**
* Increments entries count
*
* @param:
* Queue *q - pointer to queue to have stat changed
*/
void incEntries(Queue *q){
q->numEntries += 1;
}
/**
* Decrements entries count
*
* @param:
* Queue *q - pointer to queue to have stat changed
*/
void decEntries(Queue *q){
q->numEntries -= 1;
}
/**
* Adds to total enqueue time
*
* @param:
* Queue *q - pointer to queue to have stat changed
*/
void addETime(Queue *q, double time){
q->enqueueTime += time;
}
/**
* Adds to total dequeue time
*
* @param:
* Queue *q - pointer to queue to have stat changed
*/
void addDTime(Queue *q, double time){
q->dequeueTime += time;
}
|
C
|
#include "ffisier.h"
//functia de creare a unui fisier
int creare(){
int n;
printf("**********Crearea fisierului**********\n");
printf("\nIntroduceti denumirea fisierului>>>");
scanf("%s", nume);
f=fopen(nume, "w");
if (f==NULL){
puts("\nFisierul nu a fost creat!");
return 0;
}
completare(0);
fclose(f);
printf("\nFisierul a fost creat cu succes!");
getch();
}
//functia completare face parte din functia adaugare
int completare(int i){
int n, j;
printf("\nIntroduceti numarul de participanti la cursa>>>");
scanf("%d", &n);
for(j=i; j<n+i; j++){
printf("\nIntroduceti numele participantului #%d>>>", j+1);
scanf("%s", moto.nume);
printf("\nIntroduceti prenumele participantului #%d>>>", j+1);
scanf("%s", moto.prenume);
printf("\nIntroduceti Data/Luna/Anul nasterii participantului #%d>>>", j+1);
scanf("%s", moto.data_nasterii);
printf("\nIntroduceti modelul motocicletei participantului #%d>>>", j+1);
scanf("%s", moto.model_moto);
printf("\nIntroduceti numarul de cursa al participantului #%d>>>", j+1);
scanf("%d", &moto.nr_cursa);
printf("\nIntroduceti locul ocupat in cursa participantului #%d>>>", j+1);
scanf("%d", &moto.nr_loc);
fprintf(f, "%d. %s %s %s %s %d %d\n", j+1, moto.nume, moto.prenume, moto.data_nasterii, moto.model_moto, moto.nr_cursa, moto.nr_loc);
}
if (f!=NULL){
puts("\nDatele au fost introduse cu succes!");
return 1;
}
}
int adaugare(){
int n, j, i=0;
char id[10];
printf("**********Adaugare in fisier**********\n");
printf("\nIntroduceti denumirea fisierului>>>");
scanf("%s", nume);
//deschiderea fisierului dupa numele introdus
f=fopen(nume, "r+");
if(f==NULL){
printf("\nFisier inexistent!!");
getch();
return 0;
}
//parcurgerea fisierului pana la ultimul element
while(!feof(f)) fgets(id, 100, f);
fseek(f, 0, SEEK_END);
completare(id[0]-'0');
fclose(f);
getch();
return 1;
}
//functia pentru afisare a datelor din fisier
int afisare(){
printf("**********Afisarea datelor**********\n");
int i;
printf("\nIntroduceti denumirea fisierului: ");
scanf("%s", nume);
f=fopen(nume, "r");
if (f==NULL){
printf("\nFisier inexistent!");
getch();
return 0;
}
printf("\n******************************Participantii la cursa***********************************");
printf("\n_______________________________________________________________________________________\n");
printf("|Nr| Nume/Prenume |DD/LL/AA nasterii|Modelul Motocicletei|Nr de cursa|Nr de finis|\n");
printf("---------------------------------------------------------------------------------------\n");
while(fscanf(f, "%d. %s %s %s %s %d %d", &i, &moto.nume, &moto.prenume, &moto.data_nasterii, &moto.model_moto, &moto.nr_cursa, &moto.nr_loc)!=EOF){
printf("|%2d|%9s %9s|%17s|%20s|%11d|%11d|\n", i, &moto.nume, &moto.prenume, &moto.data_nasterii, &moto.model_moto, moto.nr_cursa, moto.nr_loc);
}
printf("---------------------------------------------------------------------------------------\n");
fclose(f);
getch();
return 1;
}
//Divizarea fisierului principal in 2 secunde dupa numarul de cursa a participantilor (par/impar)
int divizare(){
printf("**********Divizarea in 2**********\n");
// char nume1[20], nume2[20];
int i, var;
printf("\nIntroduceti denumirea fisierului: ");
scanf("%s", nume);
afisare();
f=fopen(nume, "r");
if (f==NULL){
printf("\nFisier inexistent!");
getch();
return 0;
}
printf("\n***Fisierul introdus va fi divizat in 2 fisiere secundare***");
printf("\nIntroduceti numele primului fisier: ");
scanf("%s", nume1);
printf("\nIntroduceti numele fisierului doi: ");
scanf("%s", nume2);
FILE *f1, *f2;
f1 = fopen(nume1, "w");
f2 = fopen(nume2, "w");
//repartizarea dupa principiul par/impar
while(fscanf(f, "%d. %s %s %s %s %d %d", &i, &moto.nume, &moto.prenume, &moto.data_nasterii, &moto.model_moto, &moto.nr_cursa, &moto.nr_loc)!=EOF){
if(moto.nr_cursa %2 == 0){
fprintf(f1, "%d. %s %s %s %s %d %d\n", i, moto.nume, moto.prenume, moto.data_nasterii, moto.model_moto, moto.nr_cursa, moto.nr_loc);
} else {
fprintf(f2, "%d. %s %s %s %s %d %d\n", i, moto.nume, moto.prenume, moto.data_nasterii, moto.model_moto, moto.nr_cursa, moto.nr_loc);
}
}
if(f1!=NULL&&f2!=NULL){
printf("\nFisierele au fost create cu success");
}
fclose(f1); fclose(f2);
v2: printf("\nDoriti sa vizualizati fisierele? [1.DA/2.NU]>>>");
scanf("%d", &var);
printf("\n");
switch (var){
case 1: afisare(); afisare(); break;
case 2: break;
default: ("\nAti introdus o varianta inadmisibila"); goto v2; break;
}
getch();
return 1;
}
//Modificarea datelor din fisier
int modificare(){
printf("**********Modificarea fisierului**********\n");
int i, nr;
int n =0;
FILE * temp;
temp=fopen("temp.txt", "w");
printf("\nIntroduceti denumirea fisierului: ");
scanf("%s", nume);
afisare();
f=fopen(nume, "r");
if (f==NULL){
printf("\nFisier inexistent!");
getch();
return 0;
}
printf("\nIntroduceti numarul de ordine a participantului care necesita a fi modificat: ");
scanf("%d", &nr);
//introducerea datelor pentru modificare in structura
while(fscanf(f, "%d. %s %s %s %s %d %d", &i, &moto.nume, &moto.prenume, &moto.data_nasterii, &moto.model_moto, &moto.nr_cursa, &moto.nr_loc)!=EOF){
fprintf(temp, "%d. %s %s %s %s %d %d\n", i, moto.nume, moto.prenume, moto.data_nasterii, moto.model_moto, moto.nr_cursa, moto.nr_loc);
}
fclose(f); fclose(temp);
temp=fopen("temp.txt", "r");
f=fopen(nume, "w");
while(fscanf(temp, "%d. %s %s %s %s %d %d", &i, &moto.nume, &moto.prenume, &moto.data_nasterii, &moto.model_moto, &moto.nr_cursa, &moto.nr_loc)!=EOF){
if(nr==i){
printf("\nIntroduceti numele nou al participantului #%d>>>", nr);
scanf("%s", moto.nume);
printf("\nIntroduceti prenumele nou al participantului #%d>>>", nr);
scanf("%s", moto.prenume);
printf("\nIntroduceti Data/Luna/Anul nasterii nou al participantului #%d>>>", nr);
scanf("%s", moto.data_nasterii);
printf("\nIntroduceti modelul nou al motocicletei participantului #%d>>>", nr);
scanf("%s", moto.model_moto);
printf("\nIntroduceti numarul de cursa nou al participantului #%d>>>", nr);
scanf("%d", &moto.nr_cursa);
printf("\nIntroduceti locul nou ocupat in cursa participantului #%d>>>", nr);
scanf("%d", &moto.nr_loc);
}
fprintf(f, "%d. %s %s %s %s %d %d\n", i, moto.nume, moto.prenume, moto.data_nasterii, moto.model_moto, moto.nr_cursa, moto.nr_loc);
}
fclose(f); fclose(temp);
printf("\nFisierul a fost modificat cu success\n");
afisare();
getch();
return 1;
}
//afisarea selectiva a fisierului
int afis_selec(){
printf("**********Afisarea selectiva**********\n");
int i=1;
printf("\nIntroduceti denumirea fisierului: ");
scanf("%s", nume);
f=fopen(nume, "r");
if (f==NULL){
printf("\nFisier inexistent!");
getch();
return 0;
}
as: printf("____________________________\n");
printf("| Afisarea Selectiva |\n");
printf("----------------------------\n");
printf("| 1.Primul finalist |\n");
printf("| 2.Primii trei finalisti |\n");
printf("| 3.Primii cinci finalisti |\n");
printf("| 4.Primii zece finalisti |\n");
printf("| 0. Iesire |\n");
printf("----------------------------\n");
int nr;
fseek(f, 0, SEEK_SET);
printf("Alegeti una din optiunile propuse>>>");
scanf("%d", &nr);
//Transformarea variantei alese in valoarea indicata in conditie
switch(nr){
case 1: break;
case 2: nr=3; break;
case 3: nr=5; break;
case 4: nr=10; break;
case 0: fclose(f); return 1; break;
default: printf("\nAti introdus o varianta inadmisibila!"); goto as; break;
}
printf("\n_______________________________________________________________________________________\n");
printf("|Nr| Nume/Prenume |DD/LL/AA nasterii|Modelul Motocicletei|Nr de cursa|Nr de finis|\n");
printf("---------------------------------------------------------------------------------------\n");
//Afisarea selectiva
while(fscanf(f, "%d. %s %s %s %s %d %d", &i, &moto.nume, &moto.prenume, &moto.data_nasterii, &moto.model_moto, &moto.nr_cursa, &moto.nr_loc)!=EOF){
if(moto.nr_loc<=nr){
printf("|%2d|%9s %9s|%17s|%20s|%11d|%11d|\n", i, &moto.nume, &moto.prenume, &moto.data_nasterii, &moto.model_moto, moto.nr_cursa, moto.nr_loc);
// i++;
}
}
printf("---------------------------------------------------------------------------------------\n"); goto as;
fclose(f);
getch();
return 1;
}
//sortarea fisierului introdus
int sortare(){
printf("**********Sortarea fisierului**********\n");
int id, n=0;
int temp, i;
struct motociclisti moto2[100];
printf("\nIntroduceti denumirea fisierului: ");
scanf("%s", nume);
f=fopen(nume, "r+");
if (f==NULL){
printf("\nFisier inexistent!");
getch();
return 0;
}
while(fscanf(f, "%d. %s %s %s %s %d %d\n", &id, &moto2[n].nume, &moto2[n].prenume, &moto2[n].data_nasterii, &moto2[n].model_moto, &moto2[n].nr_cursa, &moto2[n].nr_loc)!=EOF) n++;
//algoritmul SHELL
for(temp=n/2; temp>0; temp/=2){
for (i=temp; i<n; i++){
moto = moto2[i];
int j;
for(j = i; j>=temp&&moto2[j-temp].nr_loc>moto.nr_loc; j-=temp)
moto2[j] = moto2[j-temp];
moto2[j] = moto;
}
}
//Inscrierea in fisier
fseek(f, 0, SEEK_SET);
for(i=0; i<n; i++)
fprintf(f, "%d. %s %s %s %s %d %d\n", i+1, &moto2[i].nume, &moto2[i].prenume, &moto2[i].data_nasterii, &moto2[i].model_moto, moto2[i].nr_cursa, moto2[i].nr_loc);
fclose(f);
printf("\nFisierul a fost sortat cu success!");
getch();
return 1;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* sort_input.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: slyazid <slyazid@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/12/20 22:01:07 by slyazid #+# #+# */
/* Updated: 2019/02/10 03:35:44 by slyazid ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_ls.h"
int ft_alphacmp(const char *item1, const char *item2)
{
if (ft_strcmp(item1, item2) > 0 && ft_strcmp(item1, item2) != 32)
return (1);
if (ft_strcmp(item1, item2) < 0 || ft_strcmp(item1, item2) == 32
|| ft_strcmp(item1, item2) == -32)
return (-1);
return (0);
}
int ft_size(const char *item1, const char *item2)
{
struct stat info1;
struct stat info2;
lstat(item2, &info2);
lstat(item1, &info1);
if (info2.st_size > info1.st_size)
return (1);
if (info2.st_size < info1.st_size)
return (-1);
return (0);
}
t_args *ft_sort_reverse(t_args *lst)
{
t_args *first;
t_args *last;
t_args *current;
t_args *next;
last = lst;
next = lst->next;
while (lst)
{
if (next)
{
current = next->next;
next->next = lst;
first = next;
}
lst = next;
next = current;
}
last->next = 0;
!first ? (first = last) : 0;
return (first);
}
t_args *ft_sort_bytime(t_args *lst, char *path, t_lsdet opts)
{
if (!opts.r && opts.u)
return (ft_merge_sort(lst, path, &ft_time_acmp));
if (!opts.r && opts.c)
return (ft_merge_sort(lst, path, &ft_time_ccmp));
if (!opts.r)
return (ft_merge_sort(lst, path, &ft_time_mcmp));
if (!opts.r && opts.u)
return (ft_merge_sort(lst, path, &ft_time_acmp));
if (!opts.r && opts.c)
return (ft_merge_sort(lst, path, &ft_time_ccmp));
if (opts.r && opts.u)
return (ft_sort_reverse(ft_merge_sort(lst, path, &ft_time_acmp)));
if (opts.r && opts.c)
return (ft_sort_reverse(ft_merge_sort(lst, path, &ft_time_ccmp)));
if (opts.r)
return (ft_sort_reverse(ft_merge_sort(lst, path, &ft_time_mcmp)));
return (lst);
}
t_args *ft_sort_input(t_args *lst, char *path, t_lsdet opts)
{
lst = ft_merge_sort(lst, path, &ft_strcmp);
if (!opts.r && !opts.t && !opts.scap)
return (lst);
if (opts.r && !opts.t && !opts.scap)
return (ft_sort_reverse(lst));
if (!opts.r && opts.scap)
return (ft_merge_sort(lst, path, &ft_size));
if (opts.r && opts.scap)
return (ft_sort_reverse(ft_merge_sort(lst, path, &ft_size)));
if (opts.t)
return (ft_sort_bytime(lst, path, opts));
return (lst);
}
|
C
|
//BORIS MOROZOV
#include "main.h"
// binary to "super" octal
char* binaryToSuperOctal(struct Instruction input){
struct Instruction revInst = reverseInstruction(input);
char* output = "";
char* currchar = "";
for(int i =0;i<15;i = i+3){
int temp =0;
for(int j =0;j<3;j++){
temp = temp +revInst.bits[i + j] * pow(2,j);
}
switch(temp){
case 0:
currchar = "!";
break;
case 1:
currchar = "@";
break;
case 2:
currchar = "#";
break;
case 3:
currchar = "$";
break;
case 4:
currchar = "%";
break;
case 5:
currchar = "^";
break;
case 6:
currchar = "&";
break;
case 7:
currchar = "*";
break;
}
output = concat(currchar,output);
}
return output;
}
//decimal to "super" octal
char* decimalToSuperOctal(int input){
int rem, i=1, octal=0;
while (input!=0)
{
rem=input%8;
input/=8;
octal+=rem*i;
i*=10;
}
char* output="";
while(10*octal / 10 !=0){
switch(octal % 10){
case 0:
output = concat("!",output);
break;
case 1:
output = concat("@",output);
break;
case 2:
output = concat("#",output);
break;
case 3:
output = concat("$",output);
break;
case 4:
output = concat("%",output);
break;
case 5:
output = concat("^",output);
break;
case 6:
output = concat("&",output);
break;
case 7:
output = concat("*",output);
break;
}
octal = octal /10;
}
return output;
}
|
C
|
#include<stdio.h>
int main()
{
int n=0;
scanf("%d",&n);
printf("%d",rev(n,0));
}
int rev(int x,int i)
{
if(x<10)
{
int r = (i*10)+x;
return r;
}
else
{
int c = x%10;
x=x/10;
i=(i*10)+c;
int r = rev(x,i);
return r;
}
}
|
C
|
#include <stdio.h>
#include <stddef.h>
#pragma pack(4)
struct bar {
int foo0;
int foo1;
int foo2;
long long bar;
};
#pragma pack()
#pragma pack(push, 4)
struct foo {
int foo0;
int foo1;
int foo2;
long long foo;
};
#pragma pack(pop)
int main(void)
{
printf("offset of bar is %zu\n", offsetof(struct bar, bar));
printf("sizeof struct bar is %zu\n", sizeof(struct bar));
printf("offset of foo is %zu\n", offsetof(struct foo, foo));
printf("sizeof struct foo is %zu\n", sizeof(struct foo));
return 0;
}
|
C
|
#ifndef ATTINY861_GPIOMAP_INCLUDED
#define ATTINY861_GPIOMAP_INCLUDED
#include "ATtiny861_Pins.h"
#include "ATtiny861_ReturnCodes.h"
/*
* Configuring and using GPIO requires knowledge of three registers:
* DDRxn: Data Direction Register, byte x, bit n
* PORTxn: Data Register, byte x, bit n
* PINxn: Port Input Pin Address, byte x, bit n
*
* This module provides functions to easily access these values.
*/
/*
* Get a pointer to the Data Direction Register for the given pin.
*
* Returns NULL on failure.
*/
volatile uint8_t * ATtiny861_GpioMap_GetDdrRegister(ATTINY861_PIN pin);
/*
* Get the 0-indexed bit number (0-7) of the given pin in the Data Direction register.
* Place the result in bit_number.
*
* On failure, bit_number is unmodified.
*/
ATTINY861_RETURN_CODE ATtiny861_GpioMap_GetDdrBit(ATTINY861_PIN pin, uint8_t * bit_number);
/*
* Get a pointer to the Port Register for the given pin.
*
* Returns NULL on failure.
*/
volatile uint8_t * ATtiny861_GpioMap_GetPortRegister(ATTINY861_PIN pin);
/*
* Get the 0-indexed bit number (0-7) of the given pin in the PORT register.
* Place the result in bit_number.
*
* On failure, bit_number is unmodified.
*/
ATTINY861_RETURN_CODE ATtiny861_GpioMap_GetPortBit(ATTINY861_PIN pin, uint8_t * bit_number);
/*
* Get a pointer to the Pin Register for the given pin.
*
* Returns NULL on failure.
*/
volatile uint8_t * ATtiny861_GpioMap_GetPinRegister(ATTINY861_PIN pin);
/*
* Get the 0-indexed bit number (0-7) of the given pin in the PIN register.
* Place the result in bit_number.
*
* On failure, bit_number is unmodified.
*/
ATTINY861_RETURN_CODE ATtiny861_GpioMap_GetPinBit(ATTINY861_PIN pin, uint8_t * bit_number);
#endif
|
C
|
#include <stdio.h>
int main(int argc, char const *argv[]){
int numb=-1;
int numero;
int i;
int rotacao;
scanf("%d", &i);
while(i>0){
char nome[1001];
char final[1001];
char varia[1001];
char snome[1001];
scanf("%s", nome);
scanf("%s", snome);
numero=0;
for(rotacao=0; nome[rotacao] !='\0';rotacao++){
if(nome[rotacao]!='a' && nome[rotacao]!='e'&& nome[rotacao]!='i'&& nome[rotacao]!='o'&& nome[rotacao]!='u'){
numb+=1;
varia[numb]=nome[rotacao];
}
}
for(rotacao=0; numb>=0;rotacao++){
final[rotacao]=varia[numb];
numb--;
}
final[rotacao]='\0';
for(rotacao=0; snome[rotacao] !='\0';rotacao++){
numero++;
}
printf("%s%d\n", final,numero);
i--;
}
return 0;
}
|
C
|
/*
08 Left vs Right.c
Run and end the sound process with different configurations. First,
both speaker channels, then just the right, then just the left.
NOTE: The takeaway from this is supposed to be that you can use -1
when starting a sound process to make only one of the two pin
options actually send audio signals. If you instead just need
to stop sound temporarily, set either the channel(s) volume(s)
or frequency(ies) to 0(s).
*/
#include "simpletools.h" // Library includes
#include "badgetools.h"
#include "sound.h"
sound *audio; // Pointer for audio process
int main() // Main function
{
badge_setup(); // Set up badge systems
audio = sound_run(9, 10); // Run sound, get audio pointer
oledprint(" BOTH SIDES "); // Display sound to both sides
sound_freq(audio, 0, 440); // Play a frequency
pause(1000); // ...for 1 s
sound_freq(audio, 0, 0); // Set frequency to 0
sound_end(audio); // End the audio process
pause(200); // Wait 0.2 s
audio = sound_run(-1, 10); // Run sound on right speaker
oledprint(" JUST RIGHT"); // Display just right
sound_freq(audio, 0, 440); // Play a frequency
pause(1000); // ...for 1 s
sound_freq(audio, 0, 0); // Set frequency to 0
sound_end(audio); // End audio process again
pause(200); // Wait 0.2 s
audio = sound_run(9, -1); // Run sound on left speaker
oledprint("JUST LEFT "); // Display just left
sound_freq(audio, 0, 440); // Play a frequency
pause(1000); // ...for 1 s
sound_freq(audio, 0, 0); // Set frequency to 0
sound_end(audio); // End audio process yet again
oledprint(" ALL OFF "); // Display all off
}
|
C
|
#include "8DigitsDisplay.h"
#include "7SegDisp.h"
static uint8_t data[AMAUNT_DIGITS_8_DISPLAY+DIGIT_AMOUNT-1]; //arreglo de los numores del display emulado, la posicion 0 es el mas significativo. ej 340 -> 3|4|0|..
uint8_t *_8digits;
static int8_t cursorPosition=0;//posicion del cursor - dot
static int8_t lastDigitPos=-1;//posicion del ultimo digito del display - otambien tamano del display menos uno
static int8_t DispOffset=0;//ofeset para mover cambiar la ventana de lo que se ve en los 7seg- maximo ofset es 4
static bool showCursor=false;//muestro o no el cursor en pantalla (true) - dot
static bool pinMode=false;
void _8DigitDisplay_reset(void){
_7SegDisp_clearDisplay();
for(int i=0;i<AMAUNT_DIGITS_8_DISPLAY+DIGIT_AMOUNT-1;i++){
data[i]=_7DIGIT_BLANK;
}
cursorPosition=0;
lastDigitPos=-1;
DispOffset=0;
showCursor=false;
pinMode=false;
}
void _8DigitDisplay_init(void){
_7SegDisp_display_init();
_8DigitDisplay_reset();
_8digits=data+(DIGIT_AMOUNT-1);
}
static void refresh7SegDisp(void){
_7SegDisp_clearCursor();
if(DispOffset>AMAUNT_DIGITS_8_DISPLAY-1){
DispOffset=AMAUNT_DIGITS_8_DISPLAY-1;
}
for(int i=0;i<DIGIT_AMOUNT;i++){
if(pinMode){//modo pin
if((DIGIT_AMOUNT-1+DispOffset-i)==(cursorPosition+DIGIT_AMOUNT-1)){
_7SegDisp_setDigit(i,data[DIGIT_AMOUNT-1+DispOffset-i]);
}else{
if(data[DIGIT_AMOUNT-1+DispOffset-i]==_7DIGIT_BLANK){
_7SegDisp_setDigit(i,_7DIGIT_BLANK);
}else{
_7SegDisp_setDigit(i,_7DIGIT_GUION);
}
}
}else{
_7SegDisp_setDigit(i,data[DIGIT_AMOUNT-1+DispOffset-i]);
}//fin modo pin
if((DIGIT_AMOUNT-1+DispOffset-i)==(cursorPosition+DIGIT_AMOUNT-1)){//cursor
if(showCursor){
_7SegDisp_setCursor(i);
_7SegDisp_updateCursor();
}
}//fin cursor
}
}
static bool shiftLeftDisp(void){
if(DispOffset>AMAUNT_DIGITS_8_DISPLAY-1){
DispOffset=AMAUNT_DIGITS_8_DISPLAY-1;
refresh7SegDisp();
return false;
}else{
refresh7SegDisp();
DispOffset++;
return true;
}
}
static bool shiftRightDisp(void){
DispOffset--;
if(DispOffset<0){
DispOffset=0;
refresh7SegDisp();
return false;
}else{
refresh7SegDisp();
return true;
}
}
void _8DigitDisplay_append(uint8_t num){
lastDigitPos++;
if(lastDigitPos>AMAUNT_DIGITS_8_DISPLAY-1){
lastDigitPos=AMAUNT_DIGITS_8_DISPLAY-1;
}
_8digits[lastDigitPos]=num;
cursorPosition=lastDigitPos;
shiftLeftDisp();
}
void _8DigitDisplay_cursorOn(void){
showCursor=true;
refresh7SegDisp();
}
void _8DigitDisplay_cursorOff(void){
showCursor=false;
refresh7SegDisp();
}
bool _8DigitDisplay_SetCursorPos(uint8_t pos){
if(pos>AMAUNT_DIGITS_8_DISPLAY-1){
return false;
}
cursorPosition=pos;
refresh7SegDisp();
return true;
}
uint8_t _8DigitDisplay_GetCursorPos(void){
return cursorPosition;
}
void _8DigitDisplay_SetCharInCursorPos(uint8_t num){
_8digits[cursorPosition]=num;
refresh7SegDisp();
}
void _8DigitDisplay_SetCursorPos2End(void){
cursorPosition=lastDigitPos;
refresh7SegDisp();
}
void _8DigitDisplay_SetCursorPosOnScrenn(void){
if(cursorPosition<DIGIT_AMOUNT){
DispOffset=DIGIT_AMOUNT-1;
}else{
DispOffset=AMAUNT_DIGITS_8_DISPLAY-1;
}
refresh7SegDisp();
}
void _8DigitDisplay_ShiftCursorLeft(void){
cursorPosition--;
if(cursorPosition<0){
cursorPosition=0;
}
_8DigitDisplay_SetCursorPosOnScrenn();
}
void _8DigitDisplay_ShiftCursorRight(void){
cursorPosition++;
if(!(cursorPosition<AMAUNT_DIGITS_8_DISPLAY)){
cursorPosition=AMAUNT_DIGITS_8_DISPLAY-1;
}
_8DigitDisplay_SetCursorPosOnScrenn();
}
void _8DigitDisplay_PinMode(bool mode){
pinMode=mode;
}
void _8DigitDisplay_SetBright(uint8_t b){
_7SegDisp_setBright(b);
}
void _8DigitDisplay_IncBright(void){
_7SegDisp_IncBright();
}
// | | | 0| | | 3| 4| | | 7|
|
C
|
#include "tickit.h"
#include "taplib.h"
#include "taplib-mockterm.h"
int main(int argc, char *argv[])
{
TickitTerm *tt = make_term(25, 80);
TickitRenderBuffer *rb;
int len;
rb = tickit_renderbuffer_new(10, 20);
// Clipping to edge
{
len = tickit_renderbuffer_text_at(rb, -1, 5, "TTTTTTTTTT", NULL);
is_int(len, 10, "len from text_at clipped off top");
len = tickit_renderbuffer_text_at(rb, 11, 5, "BBBBBBBBBB", NULL);
is_int(len, 10, "len from text_at clipped off bottom");
len = tickit_renderbuffer_text_at(rb, 4, -3, "[LLLLLLLL]", NULL);
is_int(len, 10, "len from text_at clipped off left");
len = tickit_renderbuffer_text_at(rb, 5, 15, "[RRRRRRRR]", NULL);
is_int(len, 10, "len from text_at clipped off right");
tickit_renderbuffer_flush_to_term(rb, tt);
is_termlog("RenderBuffer text rendering with clipping",
GOTO(4,0), SETPEN(), PRINT("LLLLLL]"),
GOTO(5,15), SETPEN(), PRINT("[RRRR"),
NULL);
TickitPen *pen;
tickit_renderbuffer_erase_at(rb, -1, 5, 10, pen = tickit_pen_new_attrs(TICKIT_PEN_FG, 1, -1)),
tickit_pen_destroy(pen);
tickit_renderbuffer_erase_at(rb, 11, 5, 10, pen = tickit_pen_new_attrs(TICKIT_PEN_FG, 2, -1)),
tickit_pen_destroy(pen);
tickit_renderbuffer_erase_at(rb, 4, -3, 10, pen = tickit_pen_new_attrs(TICKIT_PEN_FG, 3, -1)),
tickit_pen_destroy(pen);
tickit_renderbuffer_erase_at(rb, 5, 15, 10, pen = tickit_pen_new_attrs(TICKIT_PEN_FG, 4, -1)),
tickit_pen_destroy(pen);
tickit_renderbuffer_flush_to_term(rb, tt);
is_termlog("RenderBuffer erasech rendering with clipping",
GOTO(4,0), SETPEN(.fg=3), ERASECH(7,-1),
GOTO(5,15), SETPEN(.fg=4), ERASECH(5,-1),
NULL);
tickit_renderbuffer_goto(rb, 2, 18);
tickit_renderbuffer_text(rb, "A", NULL);
tickit_renderbuffer_text(rb, "B", NULL);
tickit_renderbuffer_text(rb, "C", NULL);
tickit_renderbuffer_text(rb, "D", NULL);
tickit_renderbuffer_text(rb, "E", NULL);
tickit_renderbuffer_flush_to_term(rb, tt);
is_termlog("RenderBuffer text at VC with clipping",
GOTO(2,18), SETPEN(), PRINT("A"),
SETPEN(), PRINT("B"),
NULL);
}
// Clipping to rect
{
tickit_renderbuffer_clip(rb, &(TickitRect){.top = 2, .left=2, .lines=6, .cols=16});
tickit_renderbuffer_text_at(rb, 1, 5, "TTTTTTTTTT", NULL);
tickit_renderbuffer_text_at(rb, 9, 5, "BBBBBBBBBB", NULL);
tickit_renderbuffer_text_at(rb, 4, -3, "[LLLLLLLL]", NULL);
tickit_renderbuffer_text_at(rb, 5, 15, "[RRRRRRRR]", NULL);
tickit_renderbuffer_flush_to_term(rb, tt);
is_termlog("RenderBuffer renders text rendering with rect clipping",
GOTO(4,2), SETPEN(), PRINT("LLLL]"),
GOTO(5,15), SETPEN(), PRINT("[RR"),
NULL);
tickit_renderbuffer_clip(rb, &(TickitRect){.top = 2, .left=2, .lines=6, .cols=16});
TickitPen *pen;
tickit_renderbuffer_erase_at(rb, 1, 5, 10, pen = tickit_pen_new_attrs(TICKIT_PEN_FG, 1, -1)),
tickit_pen_destroy(pen);
tickit_renderbuffer_erase_at(rb, 9, 5, 10, pen = tickit_pen_new_attrs(TICKIT_PEN_FG, 2, -1)),
tickit_pen_destroy(pen);
tickit_renderbuffer_erase_at(rb, 4, -3, 10, pen = tickit_pen_new_attrs(TICKIT_PEN_FG, 3, -1)),
tickit_pen_destroy(pen);
tickit_renderbuffer_erase_at(rb, 5, 15, 10, pen = tickit_pen_new_attrs(TICKIT_PEN_FG, 4, -1)),
tickit_pen_destroy(pen);
tickit_renderbuffer_flush_to_term(rb, tt);
is_termlog("RenderBuffer renders erasech with rect clipping",
GOTO(4,2), SETPEN(.fg=3), ERASECH(5,-1),
GOTO(5,15), SETPEN(.fg=4), ERASECH(3,-1),
NULL);
}
// Clipping with translation
{
tickit_renderbuffer_translate(rb, 3, 5);
tickit_renderbuffer_clip(rb, &(TickitRect){.top = 2, .left = 2, .lines = 3, .cols = 5});
tickit_renderbuffer_text_at(rb, 1, 0, "1111111111", NULL);
tickit_renderbuffer_text_at(rb, 2, 0, "2222222222", NULL);
tickit_renderbuffer_text_at(rb, 3, 0, "3333333333", NULL);
tickit_renderbuffer_text_at(rb, 4, 0, "4444444444", NULL);
tickit_renderbuffer_text_at(rb, 5, 0, "5555555555", NULL);
tickit_renderbuffer_flush_to_term(rb, tt);
is_termlog("RenderBuffer clipping rectangle translated",
GOTO(5,7), SETPEN(), PRINT("22222"),
GOTO(6,7), SETPEN(), PRINT("33333"),
GOTO(7,7), SETPEN(), PRINT("44444"),
NULL);
}
tickit_renderbuffer_destroy(rb);
return exit_status();
}
|
C
|
//defining our delay function.
// the input is our time delay value (defined in main)
void delay(long c)
{
long x;
for(x= c; x > 0; x--); //short delay of size 50, counts down from 50 to 1
}
|
C
|
#include <stdio.h>
#include <string.h>
#define max_string_size 100
#define max_pattern_size 100
int pmatch();
void fail();
int failure[max_pattern_size];
char string[max_string_size];
char pat[max_pattern_size];
int pmatch(char *string, char *pat)
{
int i = 0, j = 0;
int lens = strlen(string);
int lenp = strlen(pat);
while (i < lens && j < lenp) {
if (string[i] == pat[j]) {
i++; j++;
} else if (j == 0) i++;
else
j = failure[j-1] - 1;
}
return ((j == lenp) ? (i - lenp) : -1);
}
void fail(char *pat)
{
int n = strlen(pat);
int i, j;
failure[0] = -1;
for (j = 1; j < n; j++) {
i = failure[j-1];
while ((pat[j] != pat[i+1]) && (i >= 0))
i = failure[i];
if (pat[j] == pat[i+1])
failure[j] = i+1;
else
failure[j] = -1;
}
}
int main(int argc, char const *argv[])
{
char s[] = "abcabcacab";
fail(s);
return 0;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "mymalloc.c"
#define malloc(x) mymalloc(x, __FILE__, __LINE__);
//#define calloc(x, y) mycalloc(x,y, __FILE__, __LINE__);
//#define realloc(x,y) myrealloc(x,y, __FILE__, __LINE__);
#define free(x) myfree(x, __FILE__, __LINE__);
struct node{
struct node *next;
int data;
};
typedef struct node* nodeptr;
int main(int argc, char **argv){
//Implement Test Cases
printf("\n");
//PreliminaryTests
//MALLOC TEST
printf("Preliminary Malloc Tests:\n");
int* s = (int*) malloc(sizeof(int));
int*d = (int*) malloc(sizeof(int) *1250);
*s = 10;
//FREE TEST
printf("Preliminary Free Tests:\n");
free(s);
printf("s and d freed successfully");
printf("\n");
//HEAP STRESS TEST - Heap Overflow
printf("Heap Overflow Test:\n");
return 0;
}
|
C
|
/*
Bruce Maxwell
Fall 2014
A simple test function for Module_draw that creates 3 X-wing fighters as line drawings
Requires the following functions to be defined
element_create
element_init
element_delete
module_create
module_add
module_delete
module_translate2D
module_scale2D
module_point
module_line
module_module
module_draw
drawstate_create
drawstate_setColor
drawstate_copy
vector_set
point_set2D
point_copy
line_set2D
line_set
line_copy
matrix_setView2D
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <color.h>
#include <image.h>
#include <list.h>
#include <math.h>
#include "graphics.h"
#include "polygon.h"
#include "matrix.h"
#include "view.h"
#include "drawstate.h"
#include "model.h"
int main(int argc, char *argv[]) {
View2D view;
Matrix vtm;
Matrix gtm;
Module *scene;
Module *wing;
Module *engine;
Module *body;
Module *xwing;
Module *formation;
int i;
Point vrp;
Vector xaxis;
Point p[8];
Line l;
DrawState *ds;
MStack *stack;
Image *src;
srand48(42);
// setup gtm
matrix_identity( >m );
stack = mstack_create();
// setup vtm
point_set2D( &vrp, 0, 0 );
vector_set( &xaxis, 1, 0, 0 );
view2D_set( &view, &vrp, 2, &xaxis, 640, 360 );
matrix_setView2D( &vtm, &view );
// create a body
body = module_create();
point_set2D(&p[0], 0, 0);
point_set2D(&p[1], 2, .1);
point_set2D(&p[2], 2.2, 0.25 );
point_set2D(&p[3], 2, 0.4 );
point_set2D(&p[4], 0, .5 );
for(i=0;i<5;i++) {
int a = i;
int b = (i+1) % 5;
line_set( &l, p[a], p[b] );
module_line( body, &l );
}
line_set2D( &l, 0.6, 0.05, 0.6, 0.45 );
module_line( body, &l );
line_set2D( &l, 1.1, 0.08, 1.1, 0.42 );
module_line( body, &l );
printf("body created correctly\n");
// create an engine
engine = module_create();
point_set2D( &p[0], 0, 0 );
point_set2D( &p[1], .6, 0 );
point_set2D( &p[2], .6, .2 );
point_set2D( &p[3], 0, .2 );
for(i=0;i<4;i++) {
int a = i;
int b = (i+1) % 4;
line_set( &l, p[a], p[b] );
module_line( engine, &l );
}
printf(" engine created correctly\n");
// make a wing
wing = module_create();
point_set2D(&p[0], 0.5, 0);
point_set2D(&p[1], 0.3, 1.5);
point_set2D(&p[2], 0.7, 1.5 );
point_set2D(&p[3], 0, 1.5 );
point_set2D(&p[4], 0, 0 );
for(i=0;i<5;i++) {
int a = i;
int b = (i+1) % 5;
line_set( &l, p[a], p[b] );
module_line( wing, &l );
}
module_scale2D( wing, 1.5, 1.0 );
module_translate2D( wing, -0.05, 0.05 );
module_module( wing, engine );
printf(" wing created correctly\n");
// make an x-wing
xwing = module_create();
module_module(xwing, body );
module_translate2D( xwing, 0, .5 );
module_module( xwing, wing);
module_identity(xwing);
module_scale2D( xwing, 1, -1 );
module_translate2D( xwing, 0, 0 );
module_module( xwing, wing );
printf(" XWing created correctly\n");
// make a formation
formation = module_create();
module_module(formation, xwing );
module_translate2D(formation, -4, 3 );
module_module( formation, xwing );
module_translate2D(formation, 0, -5 );
module_module( formation, xwing );
// make a scene
scene = module_create();
module_scale2D( scene, 0.1, 0.1 );
module_translate2D( scene, 0.2, 0 );
module_module( scene, formation );
// draw stars into the scene
module_identity(scene);
for(i=0;i<30;i++) {
point_set2D( &(p[0]), drand48()*2 - 1, drand48()*1 - 0.5 );
module_point( scene, &(p[0]) );
}
// create the image and draw the module
//src = image_create( view.R, view.C );
src = image_read("../images/tat.ppm");
printf("\nEVERYTHING ELSE WORKS WOOOO\n");
ds = drawstate_create(); // default color is white
printf("this is the GTM in test6a:\n");
matrix_print(>m, NULL);
module_draw( scene, &vtm, >m, ds, NULL, src );
printf("drawing works?\n");
// write out the image
image_write( src, "../images/xwingsTat.ppm" );
// free modules
module_delete( scene );
module_delete( formation );
module_delete( xwing );
module_delete( body );
module_delete( wing );
// free drawstate
free( ds );
// free image
image_free( src );
return(0);
}
|
C
|
/*project euler problem 2*/
#include<stdio.h>
#include<stdlib.h>
int main()
{
long long int a=1,b=2,c,add=2;
int i=1;
while(i>0)
{
c=a+b;
a=b;
b=c;
if(c>=4000000)
{
printf("%lld",add);
exit (0);
}
if(c%2==0)
add=add+c;
}
return 0;
}
|
C
|
#include <stdio.h>
int sub(int x, int y) {
return x - y;
}
int main( ) {
int a = 5; int b = 10;
int diff1, diff2, diff3;
diff1 = sub(a,b);
diff2 = sub(100, b);
diff3 = sub(24, 25);
printf("diff1 = %d, diff2 = %d, diff3 = %d\n", diff1, diff2, diff3);
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
struct _node{
int data;
struct _node *next;
};
typedef struct _node node;
int main()
{
int i;
node *head,*ptr;
ptr = (node *)malloc(sizeof(node));
ptr->next = NULL;
while(1){
scanf("%d",&(ptr->data));
if(ptr->data==-1) break;
else {head = (node *)malloc(sizeof(node)); head->next = ptr;}
ptr = head;
}
ptr = head;
while(ptr!=NULL){
if (ptr->data!=-1) printf("%d ",ptr->data);
ptr = ptr->next;
}
printf("\n");
}
|
C
|
/*************************************************************************
> File Name: code12.c
> Author: SDW
> Mail:264459522@qq.com
> Created Time: 六 8/16 21:16:44 2014
************************************************************************/
//12.用 0-9 这十个数字可以组成多少无重复的 3 位数字
#include<stdio.h>
int main(int argc, char *argv[])
{
int i, j, k;
int cnt = 0;
for (i = 1; i < 10; i++) {
for (j = 0; j < 10; j++) {
for (k = 0; k < 10; k++) {
if ((i != j) && (i != k) && (j != k)) {
cnt++;
printf("%d: %d%d%d\t", cnt, i, j, k);
if (cnt % 4 == 0) {
printf("\n");
}
}
}
}
}
printf("\n");
return 0;
}
|
C
|
#include <stdio.h>
int func4(int edx, int esi, int edi) {
int eax = edx;
eax = eax - esi;
int ebx = eax;
ebx = ebx >> 31;
ebx = ebx + eax;
ebx = ebx >> 1;
ebx = ebx + esi;
if(ebx == edi) {
eax = ebx;
return eax;
} else if(ebx > edi) {
edx = ebx - 1;
eax = func4(edx, esi, edi);
ebx = ebx + eax;
eax = ebx;
return eax;
} else if(ebx < edi) {
esi = ebx + 1;
eax = func4(edx, esi, edi);
ebx = ebx + eax;
eax = ebx;
return eax;
}
}
int main() {
for(int i = 0; i <= 14; i++) {
printf("%d\t", func4(14, 0, i));
}
return 0;
}
|
C
|
#include <cs50.h>
#include <stdio.h>
void draw (int h);
int main (void)
{
int height = get_int("Height: ");
draw(height);
}
void draw (int h)
{
if (h == 0)
{
return;
}
draw(h - 1); // function call it self so if 0 return
for (int i = 0 ; i < h; i++)
{
printf("#");
}
printf("\n");
}
|
C
|
#include "./key/bsp_key.h"
/**
* @brief tmΨ쪺I/O
* @param L
* @retval L
*/
void Key_GPIO_Config(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
/*}ҫGPIOf*/
KEY1_GPIO_CLK_ENABLE();
KEY2_GPIO_CLK_ENABLE();
/*ܫ䪺}*/
GPIO_InitStructure.Pin = KEY1_PIN;
/*]m}JҦ*/
GPIO_InitStructure.Mode = GPIO_MODE_INPUT;
/*]m}WԤ]U*/
GPIO_InitStructure.Pull = GPIO_NOPULL;
/*ϥΤWclƫ*/
HAL_GPIO_Init(KEY1_GPIO_PORT, &GPIO_InitStructure);
/*ܫ䪺}*/
GPIO_InitStructure.Pin = KEY2_PIN;
/*ϥΤWclƫ*/
HAL_GPIO_Init(KEY2_GPIO_PORT, &GPIO_InitStructure);
}
/**
* @brief ˴O_U
* @param 骺M
* @arg GPIOx: xiHO]A...G^
* @arg GPIO_PIN iHOGPIO_PIN_x]xiHO1...16^
* @retval 䪺A
* @arg KEY_ON:U
* @arg KEY_OFF:SU
*/
uint8_t Key_Scan(GPIO_TypeDef* GPIOx,uint16_t GPIO_Pin)
{
/*˴O_U */
if(HAL_GPIO_ReadPin(GPIOx,GPIO_Pin) == KEY_ON )
{
/*ݫ */
while(HAL_GPIO_ReadPin(GPIOx,GPIO_Pin) == KEY_ON);
return KEY_ON;
}
else
return KEY_OFF;
}
/****************************END OF FILE**************************/
|
C
|
/*------Programmming Problem Chap 10 ---------
implement a virtual memory manager
group 16
------------------*/
//required header files
#include <string.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
const int PAGE_TABLE_SIZE = 256; //2^8 page table size
const int TLB_SIZE = 16; //16 enteries in table
struct TLB { //initializing TLB
unsigned char pageNo[16]; //page number size
unsigned char frameNo[16]; //frame number size
int ind; // index
};
const int BUFFER_SIZE = 256;
const int PHYS_MEM_SIZE = 256; //page frame size
int read_Frame (int pageNumber, char *phys_Mem, int* openFrame){
char one_frame[BUFFER_SIZE];
memset(one_frame, 0, sizeof(one_frame));
// Backing store is a random access file
FILE *fp;
fp = fopen("BACKING_STORE.bin", "rb");
if (fp == NULL){
printf("File failed to open\n");
exit(0);
}
// c functions fseek() , fread() are used for performing i/o
if (fread(one_frame, sizeof(char), PHYS_MEM_SIZE, fp)==0)
printf("error in fread() function \n");
// checking if the file has data available
if (fseek(fp, pageNumber * PHYS_MEM_SIZE, SEEK_SET)!=0)
printf("error in fseek() function \n");
// reading 256 bytes in available page frame
int i = 0;
for(i; i < PHYS_MEM_SIZE; i++){
*((phys_Mem+(*openFrame)*PHYS_MEM_SIZE)+i) = one_frame[i];
}
(*openFrame)++;
return (*openFrame)-1;
}
int findPage(int LAddress, char* PageTable, struct TLB *tlb, char* phyMem, int* openFrame, int* pageFaults, int* TLBhits){
unsigned char bit_mask = 0xFF; //used masking to bit_mask upper 16 bytes
unsigned char offset;
unsigned char pageNum;
bool TLBhit = false;
// printing the logical address of page
printf("Virtual adress: %d\t", LAddress);
// extracting the page number and offset
pageNum = (LAddress >> 8) & bit_mask;
offset = LAddress & bit_mask;
//checking if the tlb has the page present
int frame = 0;
int i = 0;
for (i; i < TLB_SIZE; i++){
if(tlb->pageNo[i] == pageNum){
frame = tlb->frameNo[i];
TLBhit = true;
(*TLBhits)++;
}
}
int value;
int newFrame = 0;
//Check if TLB does not contain the page we want
if (TLBhit == false){
//check if page table doesnot contain the page we want
if (PageTable[pageNum] != -1){
// printf("Pagehit");
}
else{
//in case of page fault here
newFrame = read_Frame(pageNum, phyMem, openFrame);
PageTable[pageNum] = newFrame;
(*pageFaults)++;
}
frame = PageTable[pageNum];
tlb->pageNo[tlb->ind] = pageNum;
tlb->frameNo[tlb->ind] = PageTable[pageNum];
tlb->ind = (tlb->ind + 1)%TLB_SIZE;
}
int index = ((unsigned char)frame*PHYS_MEM_SIZE)+offset;
value = *(phyMem+index);
printf("Physical address: %d\t Value: %d\n",index, value);
return 0;
}
//Main function begins here
int main (int argc, char* argv[]){
if (argc < 2){
printf("Not enough arguments\nProgram Exiting\n");
exit(0);
}
FILE *fd;
fd = fopen(argv[1], "r");
if (fd == NULL){
printf("File failed to open\n");
exit(0);
}
int openFrame = 0;
int pageFaults = 0;
int TLBhits = 0;
float pageFaultRate;
float TLBHitRate;
//initializing page table
unsigned char PageTable[PAGE_TABLE_SIZE];
memset(PageTable, -1, sizeof(PageTable));
//initializing TLB
struct TLB tlb;
memset(tlb.pageNo, -1, sizeof(tlb.pageNo));
memset(tlb.frameNo, -1, sizeof(tlb.frameNo));
tlb.ind = 0;
//iniitalizng phyisical memory
char PhyMem[PHYS_MEM_SIZE][PHYS_MEM_SIZE]; //65,536 bytes (256 frames × 256-byte frame size)
int inputCount = 0;
int v;
while (fscanf(fd, "%d", &v)==1){
findPage(v, PageTable, &tlb, (char*)PhyMem, &openFrame, &pageFaults, &TLBhits);
inputCount++;
}
pageFaultRate = (float)pageFaults / (float)inputCount;
TLBHitRate = (float)TLBhits / (float)inputCount;
printf("******* Page Fault Rate: %.4f \n TLB hit rate= %.4f\n*****",pageFaultRate, TLBHitRate);
pclose(fd);
return 0;
}
|
C
|
#include "common.h"
void print_queue(const Queue *q)
{
QueueNode *current = q->head;
while (current != NULL) {
printf("%d ", *((int *)current->value));
current = current->next;
}
printf("\n");
}
|
C
|
//authors:
// or shahar ( orshahar1@mail.tau.ac.il )
// michaelz ( zhitomirsky1@mail.tau.ac.il )
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include "common.h"
/// the base to be used for converting char to int
static const int BASE = 10;
FILE* read_num_from_file(FILE* f_input, int* num);
char* read_forest_from_file(FILE* f_input, int side_len);
/// parser
/// inputs: f_input - pointer to input file
/// p_side_len - pointer to number side_len
/// p_generations_num - pointer to number generations_num
/// outputs: char* - the initial forest
/// will updated p_side_len & p_generations_num with the correct numbers
/// extract values from first two lines in input.txt
/// summary: parses all data from input file
///
char* parser(FILE* f_input, int *p_side_len, int *p_generations_num)
{
char* init_forest;
f_input = read_num_from_file(f_input, p_side_len);
f_input = read_num_from_file(f_input, p_generations_num);
init_forest = read_forest_from_file(f_input, *p_side_len);
return init_forest;
}
/// read_num_from_file
/// inputs: f_input - pointer to file input.txt
/// num - pointer to number
/// outputs: returns f_input
/// summary: sets num with the number that located in line
///
FILE* read_num_from_file(FILE* f_input, int* num)
{
*num = 0;
char c = fgetc(f_input);
while (c != '\n' && c != EOF)
{
*num = atoi(&c) + (*num) * BASE;
c = fgetc(f_input);
}
return f_input;
}
/// read_forest_from_file
/// inputs: f_input - pointer to file input.txt
/// side_len - side length of the forest
/// outputs: char* - the initial forset
/// summary: read the initial forest from input file and return
/// the initial forest
///
char* read_forest_from_file(FILE* f_input, int side_len)
{
char* forest = (char*)malloc(side_len * side_len + 1);
char* init_forest = forest;
if (forest == NULL)
{
print_error(MSG_ERR_MEM_ALLOC, __FILE__, __LINE__, __func__);
return NULL_ERROR_CODE;
}
char forest_char = fgetc(f_input);
while (forest_char != EOF)
{
if (forest_char != ',' && forest_char != '\n')
{
*forest = forest_char;
forest++;
}
forest_char = fgetc(f_input);
}
*forest = '\0';
return init_forest;
}
|
C
|
/*
** algo.c for algo in /home/coodie_d/rendu/test/B2/Allum-1
**
** Made by Dylan Coodien
** Login <coodie_d@epitech.net>
**
** Started on Sat Feb 7 17:44:08 2015 Dylan Coodien
** Last update Fri Feb 20 10:07:11 2015 Dylan Coodien
*/
#include <stdlib.h>
#include <stdio.h>
#include "my.h"
#include "alum1.h"
int check_longer(t_list *list)
{
t_list *tmp;
int i;
int len;
tmp = list->next;
i = 0;
len = 0;
while (tmp != list)
{
i = my_putnbr_base_rev_i(tmp->num, BASE, 0);
if (i > len)
len = i;
tmp = tmp->next;
}
return (len);
}
int turn_in(t_list *list, t_algo *al)
{
t_list *tmp;
while (al->n <= (al->len - 1))
{
al->count = 0;
tmp = list->next;
while (tmp != list)
{
if (((tmp->num & my_power_it(2, al->n))
/ (my_power_it(2, al->n))) == 1)
al->count++;
tmp = tmp->next;
}
if (al->len == 1 && ((al->count % 2) == 1))
return (0);
else if (al->n == (al->len - 1) &&
((al->count % 2) == 0) && al->len > 1)
return (0);
else if (((al->count % 2) == 1))
return (-1);
al->n++;
}
return (-1);
}
int marienbad(t_list *list, t_algo *al)
{
t_list *tmp;
tmp = list->next;
while (tmp != list)
{
tmp->save = tmp->num;
tmp->num = 0;
while (tmp->num != tmp->save)
{
al->n = 0;
al->len = check_longer(list);
if ((turn_in(list, al)) == 0)
{
display_IA_move(tmp);
return (0);
}
tmp->num++;
}
tmp = tmp->next;
}
return (-1);
}
char *algo(t_list *list, t_vars *vars)
{
t_algo *al;
if ((al = malloc(sizeof(*al))) == NULL)
return (NULL);
marienbad(list, al);
if (al != NULL)
free(al);
if (check_game(list, vars) != 0)
my_show_list(list, list->num);
return (NULL);
}
|
C
|
#include "petsc_webserver.h"
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <petscsys.h>
#include <limits.h>
PetscErrorCode create_tcpaccept_entry_bag(tcpaccept_entry **entryptr, PetscBag *bagptr, PetscInt n)
{
PetscErrorCode ierr;
tcpaccept_entry *entry;
PetscBag bag;
char obj_name[100];
PetscFunctionBeginUser;
ierr = PetscBagCreate(PETSC_COMM_WORLD,sizeof(tcpaccept_entry),&bag);CHKERRQ(ierr);
ierr = PetscBagGetData(bag,(void**)&entry);CHKERRQ(ierr);
sprintf(obj_name,"tcpaccept_entry_%d",n);
ierr = PetscBagSetName(bag,obj_name,"An entry generated by the tcpaccept program");CHKERRQ(ierr);
ierr = PetscBagRegisterInt(bag,&entry->pid,-1,"pid","Process ID that accepted the connection");CHKERRQ(ierr);
ierr = PetscBagRegisterInt(bag,&entry->ip,4,"ip","IP address version");CHKERRQ(ierr);
ierr = PetscBagRegisterInt(bag,&entry->rport,0,"rport","Remote port");CHKERRQ(ierr);
ierr = PetscBagRegisterInt(bag,&entry->lport,0,"lport","Local port");CHKERRQ(ierr);
ierr = PetscBagRegisterString(bag,&entry->laddr,IP_ADDR_MAX_LEN,"0.0.0.0","laddr","Local IP address");CHKERRQ(ierr);
ierr = PetscBagRegisterString(bag,&entry->raddr,IP_ADDR_MAX_LEN,"0.0.0.0","raddr","Remote IP address");CHKERRQ(ierr);
ierr = PetscBagRegisterString(bag,&entry->comm,COMM_MAX_LEN,"[unknown]","comm","Process name");CHKERRQ(ierr);
*entryptr = entry;
*bagptr = bag;
PetscFunctionReturn(0);
}
PetscErrorCode buffer_create(entry_buffer *buf, size_t num_items)
{
PetscFunctionBeginUser;
buf->capacity = num_items;
if (num_items < 2) {
SETERRQ1(PETSC_COMM_WORLD,1,"Must allocate at least 2 slots in the buffer, not %D",num_items);
}
PetscCalloc1(num_items,&buf->buf);
buf->valid_start = 0;
buf->valid_end = 0;
buf->num_items = 0;
PetscFunctionReturn(0);
}
PetscErrorCode buffer_destroy(entry_buffer *buf)
{
PetscInt i;
for (i=buf->valid_start; i<buf->valid_end; ++i) {
if (buf->buf[i]) {
PetscBagDestroy(&(buf->buf[i]));
}
}
PetscFree(buf->buf);
buf->valid_start = 0;
buf->valid_end = 0;
buf->capacity = 0;
buf->num_items = 0;
return 0;
}
PetscBool buffer_full(entry_buffer *buf)
{
return (buf->num_items == buf->capacity);
}
PetscBool buffer_empty(entry_buffer *buf)
{
return (buf->num_items == 0);
}
size_t buffer_capacity(entry_buffer *buf)
{
return buf->capacity;
}
size_t buffer_size(entry_buffer *buf)
{
if (!buf) {
SETERRQ(PETSC_COMM_WORLD,PETSC_ERR_ARG_NULL,"Null buffer passed to buffer_size()!");
}
if (buffer_full(buf)) {
return buf->capacity;
}
return buf->num_items;
}
PetscInt buffer_try_insert(entry_buffer *buf, PetscBag dataptr)
{
if (!buf) {
SETERRQ(PETSC_COMM_WORLD,PETSC_ERR_ARG_NULL,"Null buffer passed to buffer_try_insert()!");
}
if (buffer_full(buf)) {
return -1;
}
buf->buf[buf->valid_end] = dataptr;
buf->valid_end = (buf->valid_end + 1) % buf->capacity;
++(buf->num_items);
return 0;
}
PetscErrorCode buffer_get_item(entry_buffer *buf, PetscBag *itemptr)
{
if (buffer_empty(buf)) {
return 0;
}
*itemptr = buf->buf[buf->valid_start];
return 0;
}
PetscErrorCode buffer_pop(entry_buffer *buf)
{
PetscBag bag;
PetscErrorCode ierr;
PetscFunctionBeginUser;
/* destroy existing entry */
ierr = buffer_get_item(buf,&bag);CHKERRQ(ierr);
if (bag) {
ierr = PetscBagDestroy(&bag);CHKERRQ(ierr);
}
buf->valid_start = (buf->valid_start + 1) % buf->capacity;
--(buf->num_items);
PetscFunctionReturn(0);
}
long get_file_end_offset(file_wrapper *file)
{
long offset;
fseek(file->file,0,SEEK_END);
offset = ftell(file->file);
file->offset = offset;
return offset;
}
long has_new_data(file_wrapper *file)
{
long old_offset, new_offset;
old_offset = file->offset;
new_offset = get_file_end_offset(file);
fseek(file->file,old_offset,SEEK_SET);
return new_offset - old_offset;
}
int next_occurance(const char *str, int curr_pos, char ch)
{
int i = curr_pos;
for (; str[i]; ++i) {
if (str[i] == ch) {
return i;
}
}
return i;
}
int next_nonoccurance(const char *str, int curr_pos, char ch)
{
int i = curr_pos;
for (; str[i]; ++i) {
if (str[i] != ch) {
return i;
}
}
return i;
}
int next_whitespace(const char *str, int curr_pos)
{
return next_occurance(str,curr_pos,' ');
}
int next_nonwhitespace(const char *str, int curr_pos)
{
return next_nonoccurance(str,curr_pos,' ');
}
PetscErrorCode parse_ipv4(const char *str, char *ip)
{
PetscFunctionBeginUser;
const char *format = "%15[0-9.]";
if (sscanf(str,format,ip) != 1) {
PetscFPrintf(PETSC_COMM_WORLD,stderr,"Error parsing string %s for ipv4 address.\n",str);
}
PetscFunctionReturn(0);
}
PetscErrorCode parse_ipv6(const char *str, char *ip)
{
PetscFunctionBeginUser;
const char *format = "%39[0-9:a-z]";
if (sscanf(str,format,ip) != 1) {
PetscFPrintf(PETSC_COMM_WORLD,stderr,"Error parsing string %s for ipv6 address.\n",str);
}
PetscFunctionReturn(0);
}
#define CHECK_TOKEN(str,tok,i) do { \
if (!tok) { \
PetscFPrintf(PETSC_COMM_WORLD,stderr,"Failed to find expected token number %D in string %s\n",i,str); \
return i; \
}\
} while(0)
PetscErrorCode tcpaccept_entry_parse_line(tcpaccept_entry *entry, char *str)
{
PetscErrorCode ierr;
char *substr;
const char sep[2] = " ";
size_t len;
PetscFunctionBeginUser;
substr = strtok(str,sep);
CHECK_TOKEN(str,substr,0);
entry->pid = atoi(substr);
substr = strtok(NULL,sep);
CHECK_TOKEN(str,substr,1);
ierr = PetscStrlen(substr,&len);CHKERRQ(ierr);
ierr = PetscStrncpy(entry->comm,substr,len+1);CHKERRQ(ierr);
substr = strtok(NULL,sep);
CHECK_TOKEN(str,substr,2);
entry->ip = atoi(substr);
substr = strtok(NULL,sep);
CHECK_TOKEN(str,substr,3);
if (entry->ip == 4) {
ierr = parse_ipv4(substr,entry->raddr);CHKERRQ(ierr);
} else {
ierr = parse_ipv6(substr,entry->raddr);CHKERRQ(ierr);
}
substr = strtok(NULL,sep);
CHECK_TOKEN(str,substr,4);
entry->rport = atoi(substr);
substr = strtok(NULL,sep);
CHECK_TOKEN(str,substr,5);
if (entry->ip == 4) {
ierr = parse_ipv4(substr,entry->laddr);CHKERRQ(ierr);
} else {
ierr = parse_ipv6(substr,entry->laddr);CHKERRQ(ierr);
}
substr = strtok(NULL,sep);
CHECK_TOKEN(str,substr,6);
entry->lport = atoi(substr);
PetscFunctionReturn(0);
}
PetscErrorCode tcpconnect_entry_parse_line(tcpconnect_entry *entry, char *str)
{
PetscErrorCode ierr;
char *substr;
const char sep[2] = " ";
size_t len;
PetscFunctionBeginUser;
substr = strtok(str,sep);
CHECK_TOKEN(str,substr,0);
entry->pid = atoi(substr);
substr = strtok(NULL,sep);
CHECK_TOKEN(str,substr,1);
ierr = PetscStrlen(substr,&len);CHKERRQ(ierr);
ierr = PetscStrncpy(entry->comm,substr,len+1);CHKERRQ(ierr);
substr = strtok(NULL,sep);
CHECK_TOKEN(str,substr,2);
entry->ip = atoi(substr);
while (entry->ip == 0) {
/* in case comm has a space */
substr = strtok(NULL,sep);
CHECK_TOKEN(str,substr,2);
entry->ip = atoi(substr);
}
substr = strtok(NULL,sep);
CHECK_TOKEN(str,substr,3);
if (entry->ip == 4) {
ierr = parse_ipv4(substr,entry->saddr);CHKERRQ(ierr);
} else {
ierr = parse_ipv6(substr,entry->saddr);CHKERRQ(ierr);
}
substr = strtok(NULL,sep);
CHECK_TOKEN(str,substr,4);
if (entry->ip == 4) {
ierr = parse_ipv4(substr,entry->daddr);CHKERRQ(ierr);
} else {
ierr = parse_ipv6(substr,entry->daddr);CHKERRQ(ierr);
}
substr = strtok(NULL,sep);
CHECK_TOKEN(str,substr,5);
entry->dport = atoi(substr);
PetscFunctionReturn(0);
}
PetscErrorCode create_tcpconnect_entry_bag(tcpconnect_entry **entryptr, PetscBag *bagptr, PetscInt n)
{
PetscErrorCode ierr;
tcpconnect_entry *entry;
PetscBag bag;
char obj_name[100];
PetscFunctionBeginUser;
ierr = PetscBagCreate(PETSC_COMM_WORLD,sizeof(tcpconnect_entry),&bag);CHKERRQ(ierr);
ierr = PetscBagGetData(bag,(void**)&entry);CHKERRQ(ierr);
sprintf(obj_name,"tcpconnect_entry_%d",n);
ierr = PetscBagSetName(bag,obj_name,"An entry generated by the tcpconnect program");CHKERRQ(ierr);
ierr = PetscBagRegisterInt(bag,&entry->pid,-1,"pid","Process ID that requested the connection");CHKERRQ(ierr);
ierr = PetscBagRegisterInt(bag,&entry->ip,4,"ip","IP address version");CHKERRQ(ierr);
ierr = PetscBagRegisterInt(bag,&entry->dport,0,"dport","Destination port");CHKERRQ(ierr);
ierr = PetscBagRegisterString(bag,&entry->saddr,IP_ADDR_MAX_LEN,"0.0.0.0","saddr","Source IP address");CHKERRQ(ierr);
ierr = PetscBagRegisterString(bag,&entry->daddr,IP_ADDR_MAX_LEN,"0.0.0.0","daddr","Destination IP address");CHKERRQ(ierr);
ierr = PetscBagRegisterString(bag,&entry->comm,COMM_MAX_LEN,"[unknown]","comm","Process name");CHKERRQ(ierr);
*entryptr = entry;
*bagptr = bag;
PetscFunctionReturn(0);
}
PetscErrorCode create_tcplife_entry_bag(tcplife_entry **entryptr, PetscBag *bagptr, PetscInt n)
{
PetscErrorCode ierr;
tcplife_entry *entry;
PetscBag bag;
char obj_name[100];
PetscFunctionBeginUser;
ierr = PetscBagCreate(PETSC_COMM_WORLD,sizeof(tcplife_entry),&bag);CHKERRQ(ierr);
ierr = PetscBagGetData(bag,(void**)&entry);CHKERRQ(ierr);
sprintf(obj_name,"tcplife_entry_%d",n);
ierr = PetscBagSetName(bag,obj_name,"An entry generated by the tcplife program");CHKERRQ(ierr);
ierr = PetscBagRegisterInt(bag,&entry->pid,-1,"pid","Process ID that requested the connection");CHKERRQ(ierr);
ierr = PetscBagRegisterInt(bag,&entry->ip,4,"ip","IP address version");CHKERRQ(ierr);
ierr = PetscBagRegisterInt(bag,&entry->lport,0,"lport","Local port");CHKERRQ(ierr);
ierr = PetscBagRegisterInt(bag,&entry->rport,0,"rport","Remote port");CHKERRQ(ierr);
ierr = PetscBagRegisterInt(bag,&entry->tx_kb,0,"tx_kb","Transmitted kB");CHKERRQ(ierr);
ierr = PetscBagRegisterInt(bag,&entry->rx_kb,0,"rx_kb","Received kB");CHKERRQ(ierr);
ierr = PetscBagRegisterReal(bag,&entry->ms,0.,"ms","Milliseconds");
ierr = PetscBagRegisterString(bag,&entry->laddr,IP_ADDR_MAX_LEN,"0.0.0.0","laddr","Local IP address");CHKERRQ(ierr);
ierr = PetscBagRegisterString(bag,&entry->raddr,IP_ADDR_MAX_LEN,"0.0.0.0","raddr","Remote IP address");CHKERRQ(ierr);
ierr = PetscBagRegisterString(bag,&entry->comm,COMM_MAX_LEN,"[unknown]","comm","Process name");CHKERRQ(ierr);
*entryptr = entry;
*bagptr = bag;
PetscFunctionReturn(0);
}
PetscErrorCode tcplife_entry_parse_line(tcplife_entry *entry, char *str)
{
PetscErrorCode ierr;
char *substr;
const char sep[2] = ",";
size_t len;
PetscFunctionBeginUser;
substr = strtok(str,sep);
CHECK_TOKEN(str,substr,0);
entry->pid = atoi(substr);
substr = strtok(NULL,sep);
CHECK_TOKEN(str,substr,1);
ierr = PetscStrlen(substr,&len);CHKERRQ(ierr);
ierr = PetscStrncpy(entry->comm,substr,len+1);CHKERRQ(ierr);
substr = strtok(NULL,sep);
CHECK_TOKEN(str,substr,2);
entry->ip = atoi(substr);
substr = strtok(NULL,sep);
CHECK_TOKEN(str,substr,3);
if (entry->ip == 4) {
ierr = parse_ipv4(substr,entry->laddr);CHKERRQ(ierr);
} else {
ierr = parse_ipv6(substr,entry->laddr);CHKERRQ(ierr);
}
substr = strtok(NULL,sep);
CHECK_TOKEN(str,substr,4);
entry->lport = atoi(substr);
substr = strtok(NULL,sep);
CHECK_TOKEN(str,substr,5);
if (entry->ip == 4) {
ierr = parse_ipv4(substr,entry->raddr);CHKERRQ(ierr);
} else {
ierr = parse_ipv6(substr,entry->raddr);CHKERRQ(ierr);
}
substr = strtok(NULL,sep);
CHECK_TOKEN(str,substr,6);
entry->rport = atoi(substr);
substr = strtok(NULL,sep);
CHECK_TOKEN(str,substr,7);
entry->tx_kb = atoi(substr);
substr = strtok(NULL,sep);
CHECK_TOKEN(str,substr,8);
entry->rx_kb = atoi(substr);
substr = strtok(NULL,sep);
CHECK_TOKEN(str,substr,9);
entry->ms = atof(substr);
PetscFunctionReturn(0);
}
PetscErrorCode create_tcpconnlat_entry_bag(tcpconnlat_entry **entryptr, PetscBag *bagptr, PetscInt n)
{
PetscErrorCode ierr;
tcpconnlat_entry *entry;
PetscBag bag;
char obj_name[100];
PetscFunctionBeginUser;
ierr = PetscBagCreate(PETSC_COMM_WORLD,sizeof(tcpconnlat_entry),&bag);CHKERRQ(ierr);
ierr = PetscBagGetData(bag,(void**)&entry);CHKERRQ(ierr);
sprintf(obj_name,"tcpconnlat_entry_%d",n);
ierr = PetscBagRegisterInt(bag,&entry->pid,-1,"pid","Process ID that accepted the connection");CHKERRQ(ierr);
ierr = PetscBagRegisterInt(bag,&entry->ip,4,"ip","IP address version");CHKERRQ(ierr);
ierr = PetscBagRegisterInt(bag,&entry->dport,0,"dport","Remote port");CHKERRQ(ierr);
ierr = PetscBagRegisterString(bag,&entry->saddr,IP_ADDR_MAX_LEN,"0.0.0.0","saddr","Source IP address");CHKERRQ(ierr);
ierr = PetscBagRegisterString(bag,&entry->daddr,IP_ADDR_MAX_LEN,"0.0.0.0","daddr","Destination IP address");CHKERRQ(ierr);
ierr = PetscBagRegisterString(bag,&entry->comm,COMM_MAX_LEN,"[unknown]","comm","Process name");CHKERRQ(ierr);
*entryptr = entry;
*bagptr = bag;
PetscFunctionReturn(0);
}
PetscErrorCode create_tcpretrans_entry_bag(tcpretrans_entry **entryptr, PetscBag *bagptr, PetscInt n)
{
PetscErrorCode ierr;
tcpretrans_entry *entry;
PetscBag bag;
char obj_name[100];
PetscFunctionBeginUser;
ierr = PetscBagCreate(PETSC_COMM_WORLD,sizeof(tcpconnlat_entry),&bag);CHKERRQ(ierr);
ierr = PetscBagGetData(bag,(void**)&entry);CHKERRQ(ierr);
sprintf(obj_name,"tcpconnlat_entry_%d",n);
ierr = PetscBagRegisterInt(bag,&entry->pid,-1,"pid","Process ID that accepted the connection");CHKERRQ(ierr);
ierr = PetscBagRegisterInt(bag,&entry->ip,4,"ip","IP address version");CHKERRQ(ierr);
ierr = PetscBagRegisterString(bag,&entry->laddr_port,COMM_MAX_LEN,"0.0.0.0:0","laddr_port","Local IP_address:tcp_port");CHKERRQ(ierr);
ierr = PetscBagRegisterString(bag,&entry->raddr_port,COMM_MAX_LEN,"0.0.0.0:0","raddr_port","Remote IP_address:tcp_port");CHKERRQ(ierr);
ierr = PetscBagRegisterString(bag,&entry->state,COMM_MAX_LEN,"[unknown]","state","TCP session state");CHKERRQ(ierr);
*entryptr = entry;
*bagptr = bag;
PetscFunctionReturn(0);
}
PetscErrorCode tcpretrans_entry_parse_line(tcpretrans_entry *entry, char *str)
{
PetscErrorCode ierr;
char *substr;
const char sep[2] = " ";
size_t len;
PetscFunctionBeginUser;
SETERRQ(PETSC_COMM_WORLD,1,"Error, tcpretrans_entry_parse_line() not implemented yet");
substr = strtok(str,sep);
CHECK_TOKEN(str,substr,0);
entry->pid = atoi(substr);
substr = strtok(NULL,sep);
CHECK_TOKEN(str,substr,1);
entry->ip = atoi(substr);
while (entry->ip == 0) {
/* in case comm has a space */
substr = strtok(NULL,sep);
CHECK_TOKEN(str,substr,1);
entry->ip = atoi(substr);
}
strtok(NULL,sep);
CHECK_TOKEN(str,substr,4);
ierr = PetscStrlen(substr,&len);CHKERRQ(ierr);
ierr = PetscStrncpy(entry->state,substr,len+1);CHKERRQ(ierr);
PetscFunctionReturn(0);
}
PetscErrorCode tcpconnlat_entry_parse_line(tcpconnlat_entry *entry, char *str)
{
PetscErrorCode ierr;
char *substr;
const char sep[2] = " ";
size_t len;
PetscFunctionBeginUser;
substr = strtok(str,sep);
CHECK_TOKEN(str,substr,0);
entry->pid = atoi(substr);
substr = strtok(NULL,sep);
CHECK_TOKEN(str,substr,1);
ierr = PetscStrlen(substr,&len);CHKERRQ(ierr);
ierr = PetscStrncpy(entry->comm,substr,len+1);CHKERRQ(ierr);
substr = strtok(NULL,sep);
CHECK_TOKEN(str,substr,2);
entry->ip = atoi(substr);
substr = strtok(NULL,sep);
CHECK_TOKEN(str,substr,3);
if (entry->ip == 4) {
ierr = parse_ipv4(substr,entry->saddr);CHKERRQ(ierr);
} else {
ierr = parse_ipv6(substr,entry->saddr);CHKERRQ(ierr);
}
substr = strtok(NULL,sep);
CHECK_TOKEN(str,substr,4);
if (entry->ip == 4) {
ierr = parse_ipv4(substr,entry->daddr);CHKERRQ(ierr);
} else {
ierr = parse_ipv6(substr,entry->daddr);CHKERRQ(ierr);
}
substr = strtok(NULL,sep);
CHECK_TOKEN(str,substr,6);
entry->dport = atoi(substr);
substr = strtok(NULL,sep);
CHECK_TOKEN(str,substr,7);
entry->lat_ms = atof(substr);
PetscFunctionReturn(0);
}
PetscErrorCode process_data_initialize(process_data *dat)
{
PetscMemzero(dat,sizeof(process_data));
return 0;
}
PetscErrorCode process_statistics_init(process_statistics *pstats)
{
PetscErrorCode ierr;
PetscFunctionBeginUser;
ierr = PetscHMapDataCreate(&(pstats->ht));CHKERRQ(ierr);
PetscFunctionReturn(0);
}
PetscErrorCode process_statistics_destroy(process_statistics *pstats)
{
PetscErrorCode ierr;
PetscFunctionBeginUser;
ierr = PetscHMapDataDestroy(&(pstats->ht));CHKERRQ(ierr);
PetscFunctionReturn(0);
}
PetscErrorCode process_statistics_add_accept(process_statistics *pstats,
tcpaccept_entry *entry)
{
PetscErrorCode ierr;
process_data pdata;
PetscFunctionBeginUser;
ierr = PetscHMapDataGet(pstats->ht,entry->pid,&pdata);CHKERRQ(ierr);
++pdata.naccept;
if (entry->ip == 4) {
++pdata.nipv4;
} else if (entry->ip == 6) {
++pdata.nipv6;
}
PetscStrncpy(pdata.comm,entry->comm,COMM_MAX_LEN);
ierr = PetscHMapDataSet(pstats->ht,entry->pid,pdata);CHKERRQ(ierr);
PetscFunctionReturn(0);
}
PetscErrorCode process_statistics_add_connect(process_statistics *pstats,
tcpconnect_entry *entry)
{
PetscErrorCode ierr;
process_data pdata;
PetscFunctionBeginUser;
ierr = PetscHMapDataGet(pstats->ht,entry->pid,&pdata);CHKERRQ(ierr);
++pdata.nconnect;
if (entry->ip == 4) {
++pdata.nipv4;
} else if (entry->ip == 6) {
++pdata.nipv6;
}
PetscStrncpy(pdata.comm,entry->comm,COMM_MAX_LEN);
ierr = PetscHMapDataSet(pstats->ht,entry->pid,pdata);CHKERRQ(ierr);
PetscFunctionReturn(0);
}
PetscErrorCode process_statistics_add_connlat(process_statistics *pstats,
tcpconnlat_entry *entry)
{
PetscErrorCode ierr;
process_data pdata;
PetscFunctionBeginUser;
ierr = PetscHMapDataGet(pstats->ht,entry->pid,&pdata);CHKERRQ(ierr);
++pdata.nconnlat;
pdata.latms += entry->lat_ms;
if (entry->ip == 4) {
++pdata.nipv4;
} else if (entry->ip == 6) {
++pdata.nipv6;
}
PetscStrncpy(pdata.comm,entry->comm,COMM_MAX_LEN);
ierr = PetscHMapDataSet(pstats->ht,entry->pid,pdata);CHKERRQ(ierr);
PetscFunctionReturn(0);
}
PetscErrorCode process_statistics_add_life(process_statistics *pstats,
tcplife_entry *entry)
{
PetscErrorCode ierr;
process_data pdata;
PetscFunctionBeginUser;
ierr = PetscHMapDataGet(pstats->ht,entry->pid,&pdata);CHKERRQ(ierr);
++pdata.nlife;
pdata.tx_kb += entry->tx_kb;
pdata.rx_kb += entry->rx_kb;
pdata.lifems += entry->ms;
if (entry->ip == 4) {
++pdata.nipv4;
} else if (entry->ip == 6) {
++pdata.nipv6;
}
PetscStrncpy(pdata.comm,entry->comm,COMM_MAX_LEN);
ierr = PetscHMapDataSet(pstats->ht,entry->pid,pdata);CHKERRQ(ierr);
PetscFunctionReturn(0);
}
PetscErrorCode process_statistics_add_retrans(process_statistics *pstats,
tcpretrans_entry *entry)
{
PetscErrorCode ierr;
process_data pdata;
PetscFunctionBeginUser;
ierr = PetscHMapDataGet(pstats->ht,entry->pid,&pdata);CHKERRQ(ierr);
++pdata.nretrans;
if (entry->ip == 4) {
++pdata.nipv4;
} else if (entry->ip == 6) {
++pdata.nipv6;
}
PetscStrncpy(pdata.comm,"[unknown]",sizeof("[unknown]"));
ierr = PetscHMapDataSet(pstats->ht,entry->pid,pdata);CHKERRQ(ierr);
PetscFunctionReturn(0);
}
static PetscBool registered = PETSC_FALSE;
PetscErrorCode register_mpi_types()
{
PetscFunctionBeginUser;
if (registered) {
PetscFunctionReturn(0);
}
MPI_Aint accept_displacements[] = {offsetof(tcpaccept_entry,pid),
offsetof(tcpaccept_entry,ip),
offsetof(tcpaccept_entry,rport),
offsetof(tcpaccept_entry,lport),
offsetof(tcpaccept_entry,laddr),
offsetof(tcpaccept_entry,raddr),
offsetof(tcpaccept_entry,comm)};
MPI_Datatype accept_dtypes[] = {MPI_INT,MPI_INT,MPI_INT,MPI_INT,MPI_CHAR,
MPI_CHAR,MPI_CHAR};
int accept_block_lens[] = {1,1,1,1,IP_ADDR_MAX_LEN,IP_ADDR_MAX_LEN,COMM_MAX_LEN};
MPI_Type_create_struct(7,accept_block_lens,accept_displacements,accept_dtypes,
&MPI_DTYPES[DTYPE_ACCEPT]);
MPI_Aint connect_displacements[] = {offsetof(tcpconnect_entry,pid),
offsetof(tcpconnect_entry,ip),
offsetof(tcpconnect_entry,dport),
offsetof(tcpconnect_entry,saddr),
offsetof(tcpconnect_entry,daddr),
offsetof(tcpconnect_entry,comm)};
MPI_Datatype connect_dtypes[] = {MPI_INT,MPI_INT,MPI_INT,MPI_CHAR,MPI_CHAR,
MPI_CHAR};
int connect_block_lens[] = {1,1,1,IP_ADDR_MAX_LEN,IP_ADDR_MAX_LEN,
COMM_MAX_LEN};
MPI_Type_create_struct(6,connect_block_lens,connect_displacements,connect_dtypes,
&MPI_DTYPES[DTYPE_CONNECT]);
MPI_Aint connlat_displacements[] = {offsetof(tcpconnlat_entry,pid),
offsetof(tcpconnlat_entry,ip),
offsetof(tcpconnlat_entry,dport),
offsetof(tcpconnlat_entry,lat_ms),
offsetof(tcpconnlat_entry,saddr),
offsetof(tcpconnlat_entry,daddr),
offsetof(tcpconnlat_entry,comm)};
MPI_Datatype connlat_dtypes[] = {MPI_INT,MPI_INT,MPI_INT,
MPI_DOUBLE,MPI_CHAR,MPI_CHAR,MPI_CHAR};
int connlat_block_lens[] = {1,1,1,1,IP_ADDR_MAX_LEN,IP_ADDR_MAX_LEN,
COMM_MAX_LEN};
MPI_Type_create_struct(7,connlat_block_lens,connlat_displacements,
connlat_dtypes,&MPI_DTYPES[DTYPE_CONNLAT]);
MPI_Aint life_displacements[] = {offsetof(tcplife_entry,pid),
offsetof(tcplife_entry,ip),
offsetof(tcplife_entry,lport),
offsetof(tcplife_entry,rport),
offsetof(tcplife_entry,tx_kb),
offsetof(tcplife_entry,rx_kb),
offsetof(tcplife_entry,ms),
offsetof(tcplife_entry,laddr),
offsetof(tcplife_entry,raddr),
offsetof(tcplife_entry,comm),
offsetof(tcplife_entry,time)};
MPI_Datatype life_dtypes[] = {MPI_INT,MPI_INT,MPI_INT,MPI_INT,MPI_INT,MPI_INT,
MPI_DOUBLE,MPI_CHAR,MPI_CHAR,MPI_CHAR,MPI_CHAR};
int life_block_lens[] = {1,1,1,1,1,1,1,IP_ADDR_MAX_LEN,IP_ADDR_MAX_LEN,
COMM_MAX_LEN,TIME_LEN};
MPI_Type_create_struct(11,life_block_lens,life_displacements,life_dtypes,
&MPI_DTYPES[DTYPE_LIFE]);
MPI_Aint retrans_displacements[] = {offsetof(tcpretrans_entry,pid),
offsetof(tcpretrans_entry,ip),
offsetof(tcpretrans_entry,laddr_port),
offsetof(tcpretrans_entry,raddr_port),
offsetof(tcpretrans_entry,state)};
MPI_Datatype retrans_dtypes[] = {MPI_INT,MPI_INT,MPI_CHAR,MPI_CHAR,MPI_CHAR};
int retrans_block_lens[] = {1,1,COMM_MAX_LEN,COMM_MAX_LEN,COMM_MAX_LEN};
MPI_Type_create_struct(5,retrans_block_lens,retrans_displacements,
retrans_dtypes,&MPI_DTYPES[DTYPE_RETRANS]);
MPI_Aint pdata_displacements[] = {offsetof(process_data_summary,pid),
offsetof(process_data_summary,rank),
offsetof(process_data_summary,tx_kb),
offsetof(process_data_summary,rx_kb),
offsetof(process_data_summary,n_event),
offsetof(process_data_summary,avg_latency),
//offsetof(process_data_summary,sd_latency),
offsetof(process_data_summary,avg_lifetime),
//offsetof(process_data_summary,sd_lifetime),
offsetof(process_data_summary,fraction_ipv6),
offsetof(process_data_summary,comm)};
MPI_Datatype pdata_dtypes[] = {MPI_INT,MPI_INT,MPI_LONG,MPI_LONG,MPI_LONG,
MPI_DOUBLE,MPI_DOUBLE,MPI_DOUBLE,MPI_CHAR};
int pdata_block_lens[] = {1,1,1,1,1,1,1,1,COMM_MAX_LEN};
MPI_Type_create_struct(9,pdata_block_lens,pdata_displacements,pdata_dtypes,
&MPI_DTYPES[DTYPE_SUMMARY]);
PetscInt i;
for (i=0; i<6; ++i) {
MPI_Type_commit(&MPI_DTYPES[i]);
}
registered = PETSC_TRUE;
PetscFunctionReturn(0);
}
PetscErrorCode process_data_summarize(PetscInt pid, process_data *pdata, process_data_summary *psumm)
{
PetscFunctionBeginUser;
psumm->pid = pid;
psumm->tx_kb = pdata->tx_kb;
psumm->rx_kb = pdata->rx_kb;
psumm->n_event = pdata->naccept + pdata->nconnect + pdata->nconnlat
+ pdata->nlife + pdata->nretrans;
psumm->avg_latency = pdata->latms / pdata->nconnlat;
psumm->avg_lifetime = pdata->lifems / pdata->nlife;
psumm->fraction_ipv6 = ((PetscReal)(pdata->nipv6))/ ((PetscReal)(pdata->nipv6) + (PetscReal)(pdata->nipv4));
PetscStrncpy(psumm->comm,pdata->comm,COMM_MAX_LEN);
PetscFunctionReturn(0);
}
PetscErrorCode process_statistics_get_summary(process_statistics *pstats, PetscInt pid, process_data_summary *psumm)
{
process_data pdata;
PetscErrorCode ierr;
PetscFunctionBeginUser;
ierr = PetscHMapDataGet(pstats->ht,pid,&pdata);CHKERRQ(ierr);
ierr = process_data_summarize(pid,&pdata,psumm);CHKERRQ(ierr);
PetscFunctionReturn(0);
}
PetscErrorCode process_statistics_get_pid_data(process_statistics *pstats,
PetscInt pid,
process_data *pdata)
{
PetscErrorCode ierr;
PetscFunctionBeginUser;
ierr = PetscHMapDataGet(pstats->ht,pid,pdata);CHKERRQ(ierr);
PetscFunctionReturn(0);
}
PetscErrorCode process_statistics_num_entries(process_statistics *pstats, PetscInt *n)
{
PetscErrorCode ierr;
PetscFunctionBeginUser;
ierr = PetscHMapDataGetSize(pstats->ht,n);CHKERRQ(ierr);
PetscFunctionReturn(0);
}
PetscErrorCode process_statistics_get_all(process_statistics *pstats, process_data *pdatas, PetscInt *pids)
{
PetscErrorCode ierr;
PetscInt off=0;
PetscFunctionBeginUser;
ierr = PetscHMapDataGetPairs(pstats->ht,&off,pids,pdatas);CHKERRQ(ierr);
PetscFunctionReturn(0);
}
PetscErrorCode create_process_summary_bag(process_data_summary **psumm, PetscBag *bag, PetscInt rank, PetscInt nentry)
{
PetscErrorCode ierr;
process_data_summary *ps;
PetscBag pbag;
char obj_name[100];
PetscFunctionBeginUser;
sprintf(obj_name,"process_data_summary_rank_%d_n_%d",rank,nentry);
ierr = PetscBagCreate(PETSC_COMM_WORLD,sizeof(process_data_summary),&pbag);CHKERRQ(ierr);
ierr = PetscBagGetData(pbag,(void**)&ps);CHKERRQ(ierr);
ierr = PetscBagSetName(pbag,obj_name,"A process summary");CHKERRQ(ierr);
ierr = PetscBagRegisterInt(pbag,&ps->pid,-1,"pid","Process ID");CHKERRQ(ierr);
ierr = PetscBagRegisterInt(pbag,&ps->rank,rank,"rank","MPI rank");CHKERRQ(ierr);
ierr = PetscBagRegisterInt64(pbag,&ps->tx_kb,0,"tx_kb","Transmitted kilobytes");CHKERRQ(ierr);
ierr = PetscBagRegisterInt64(pbag,&ps->rx_kb,0,"rx_kb","Received kilobytes");CHKERRQ(ierr);
ierr = PetscBagRegisterInt64(pbag,&ps->n_event,0,"n_event","Number of TCP events (e.g. connect, accept, life, etc.)");CHKERRQ(ierr);
ierr = PetscBagRegisterReal(pbag,&ps->avg_latency,0.0,"avg_latency","Average connection latency from tcpconnlat");CHKERRQ(ierr);
//ierr = PetscBagRegisterReal(pbag,&ps->sd_latency,0.0,"sd_latency","Standard deviation of connection latency from tcpconnlat");CHKERRQ(ierr);
ierr = PetscBagRegisterReal(pbag,&ps->avg_lifetime,0.0,"avg_lifetime","Average lifetime of a TCP event from tcplife");CHKERRQ(ierr);
//ierr = PetscBagRegisterReal(pbag,&ps->sd_lifetime,0.0,"sd_lifetime","Standard deviation of the lifetimes of TCP events from tcplife");CHKERRQ(ierr);
ierr = PetscBagRegisterReal(pbag,&ps->fraction_ipv6,0.0,"fraction_ipv6","Fraction of the TCP events that used IP v6 instead of v4");CHKERRQ(ierr);
ierr = PetscBagRegisterString(pbag,&ps->comm,COMM_MAX_LEN,"[unknown]","comm","Process name");CHKERRQ(ierr);
*bag = pbag;
*psumm = ps;
PetscFunctionReturn(0);
}
PetscErrorCode buffer_gather_summaries(entry_buffer *buf)
{
PetscErrorCode ierr;
PetscFunctionBeginUser;
ierr = buffer_gather(buf,DTYPE_SUMMARY);CHKERRQ(ierr);
PetscFunctionReturn(0);
}
#define summary_cpy(to,from) \
(to).rank = (from).rank;\
(to).tx_kb = (from).tx_kb;\
(to).rx_kb = (from).rx_kb;\
(to).n_event = (from).n_event;\
(to).avg_latency = (from).avg_latency;\
(to).fraction_ipv6 = (from).fraction_ipv6;\
PetscStrncpy((to).comm,(from).comm,COMM_MAX_LEN)
PetscErrorCode buffer_gather(entry_buffer *buf, SERVER_MPI_DTYPE dtype)
{
PetscErrorCode ierr;
PetscInt rank,size,nitem=0,nextant=0,i,ires;
process_data_summary *summaries=NULL,*summary,*ssummaries=NULL;
PetscBag bag;
PetscFunctionBeginUser;
MPI_Comm_rank(PETSC_COMM_WORLD,&rank);
MPI_Comm_size(PETSC_COMM_WORLD,&size);
PetscInt summs=0;
if (size == 1) {
/* only one process in the communicator; already on root */
PetscFunctionReturn(0);
}
/* prepare for MPI_Reduce() to get number of summaries coming into root */
if (rank) {
summs = 0;
if (buf->num_items > INT_MAX) {
SETERRQ2(PETSC_COMM_WORLD,1,"Number of items %D on rank %D is greater than INT_MAX! Try sending the buffer with fewer items.",buf->num_items,rank);
}
nitem = (PetscInt)buf->num_items;
ierr = PetscMalloc1(nitem*sizeof(ssummaries),&ssummaries);CHKERRQ(ierr);
/* fill the array with summaries */
i=0;
while (!buffer_empty(buf)) {
ierr = buffer_get_item(buf,&bag);CHKERRQ(ierr);
ierr = PetscBagGetData(bag,(void**)&summary);CHKERRQ(ierr);
summary_cpy(ssummaries[i],*summary); //ssummaries[i] = *summary;
ssummaries[i].rank = rank;
ierr = buffer_pop(buf);CHKERRQ(ierr);
++i;
}
} else {
nitem = 0;
if (buf->num_items > INT_MAX) {
SETERRQ2(PETSC_COMM_WORLD,1,"Number of items %D on rank %D is greater than INT_MAX! Try sending the buffer with fewer items.",buf->num_items,rank);
}
nextant = (PetscInt)buf->num_items;
}
MPI_Reduce(&nitem,&summs,1,MPI_INT,MPI_SUM,0,PETSC_COMM_WORLD);
if (!rank) {
if (nextant + summs >= buf->capacity) {
SETERRQ3(PETSC_COMM_WORLD,1,"Buffer on root has capacity %D, but currently holds %D entries and is being asked to accept %D more! Increase the buffer size on root.",buf->capacity,nextant,nitem);
}
ierr = PetscMalloc1((summs+nextant) * sizeof(summaries),&summaries);CHKERRQ(ierr);
}
MPI_Gather(ssummaries,nitem,MPI_DTYPES[dtype],
summaries,summs,MPI_DTYPES[dtype],
0,PETSC_COMM_WORLD);
/* push the new summaries into the buffer */
if (!rank) {
for (i=0; i<summs; ++i) {
ierr = create_process_summary_bag(&summary,&bag,summaries[i].rank,
i);
//*summary = summaries[i];
summary->pid = summaries[i].pid;
summary->rank = summaries[i].rank;
summary->tx_kb = summaries[i].tx_kb;
summary->rx_kb = summaries[i].rx_kb;
summary->n_event = summaries[i].n_event;
summary->avg_latency = summaries[i].avg_latency;
summary->fraction_ipv6 = summaries[i].fraction_ipv6;
ierr = PetscStrncpy(summary->comm,summaries[i].comm,COMM_MAX_LEN);CHKERRQ(ierr);
ires = buffer_try_insert(buf,bag);
if (ires == -1) {
PetscPrintf(PETSC_COMM_WORLD,"Error: buffer is full! Try increasing the capacity. Discarding this entry\n.");
}
}
}
if (rank) {
if (ssummaries) {
ierr = PetscFree(ssummaries);CHKERRQ(ierr);
}
} else {
if (summaries) {
ierr = PetscFree(summaries);CHKERRQ(ierr);
}
}
PetscFunctionReturn(0);
}
PetscErrorCode summary_view(FILE *fd, process_data_summary *psum)
{
PetscFunctionBeginUser;
PetscFPrintf(PETSC_COMM_WORLD,fd,"Summary of network traffic on rank %D, process %D:\n",psum->rank,psum->pid);
PetscFPrintf(PETSC_COMM_WORLD,fd,"pid = %D\n",psum->pid);
PetscFPrintf(PETSC_COMM_WORLD,fd,"name = %s\n",psum->comm);
PetscFPrintf(PETSC_COMM_WORLD,fd,"tx_kb = %D\n",psum->tx_kb);
PetscFPrintf(PETSC_COMM_WORLD,fd,"rx_kb = %D\n",psum->rx_kb);
PetscFPrintf(PETSC_COMM_WORLD,fd,"n_event = %D\n",psum->n_event);
PetscFPrintf(PETSC_COMM_WORLD,fd,"avg_latency = %g\n",psum->avg_latency);
PetscFPrintf(PETSC_COMM_WORLD,fd,"avg_lifetime = %g\n",psum->avg_lifetime);
PetscFPrintf(PETSC_COMM_WORLD,fd,"fraction_ipv6 = %.3g\n",psum->fraction_ipv6);
PetscFunctionReturn(0);
}
|
C
|
#include "raylib.h"
typedef struct Nave {
Vector2 posicao;
int vidas;
int pontos;
} Nave;
static Nave nave;
void Navinha_Mover (Vector2 *nav) {
if (IsKeyDown(KEY_RIGHT)) {
if (nave.posicao.x < 790.0f) { //para não sair da janela
nave.posicao.x += 5.0f;
}
}
if (IsKeyDown(KEY_LEFT)) {
if (nave.posicao.x > 12.0f) {
nave.posicao.x -= 5.0f;
}
}
if (IsKeyDown(KEY_UP)) {
if (nave.posicao.y > 10.0f) {
nave.posicao.y -= 5.0f;
}
}
if (IsKeyDown(KEY_DOWN)) {
if (nave.posicao.y < 440.0f) {
nave.posicao.y += 5.0f;
}
}
*nav = nave.posicao;
}
void Navinha_Desenhar (Vector2 *nav) {
BeginDrawing();
DrawCircleV(nave.posicao, 10, BLUE);
EndDrawing();
*nav = nave.posicao;
}
|
C
|
//==============================================================================
// 3D TEh̃TvłB
//==============================================================================
#include <stdio.h>
#include <LuminoC.h>
int main()
{
LNHandle sound;
LNVector3 soundPos = { 12.0, 0.0, 0.0 };
LNVector3 listenerPos = { 5, 0.0, 0.0 };
LNVector3 listenerDir = { 0.0, 0.0, 1.0 };
LNVector3 listenerVel = { 2.0, 0.0, 0.0 };
// @\
LNApplication_InitializeAudio();
// t@C Sound IuWFNg
LNSound_Create(_T("../Media/water02.wav"), &sound);
LNSound_Set3DEnabled(sound, LN_TRUE); // 3D ƂčĐ
LNSound_SetEmitterPosition(sound, &soundPos); // ʒu
LNSound_SetEmitterMaxDistance(sound, 10.0); // ̋܂ŕ
LNSound_SetLoopEnabled(sound, LN_TRUE); // [vON
// Xi[̈ʒuEExw肷
LNSoundListener_SetPosition(&listenerPos);
LNSoundListener_SetDirection(&listenerDir);
LNSoundListener_SetVelocity(&listenerVel);
// Đ
LNSound_Play(sound);
printf("Enter ƒ~܂...\n");
getchar();
// ~
LNSound_Stop(sound);
// CȕI
LNApplication_Terminate();
return 0;
}
|
C
|
/*
Tier 1 : Part 6 : Question 3
*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
char guessing_password_string[20] , password_string[20];
char user_name_string[20], guessing_user_name_string[20], catch_the_return_feed;
int clean_array;
//clean the arrays
for(clean_array = 0; clean_array < 20; clean_array++)
{
guessing_user_name_string[clean_array]='\0';
user_name_string[clean_array]='\0';
guessing_password_string[clean_array]='\0';
password_string[clean_array]='\0';
}
printf("What is the right word ?\r\n");
strcpy(user_name_string,"user");
strcpy(password_string,"password");
while(1)
{
printf("Please enter the User name\r\n");
scanf("%s",&guessing_user_name_string);
catch_the_return_feed = getchar();
printf("Please enter the password\r\n");
scanf("%s",&guessing_password_string);
catch_the_return_feed = getchar();
if(strcmp(password_string,guessing_password_string) == 0 && strcmp(user_name_string,guessing_user_name_string) == 0)
{
printf("Correct Login , Welcome %s \r\n",guessing_user_name_string);
exit(0);
}
else if(strcmp(user_name_string,guessing_user_name_string) == 0 && strcmp(password_string,guessing_password_string) != 0)
{
printf("Password doesn't match the User name , please try again\r\n");
}
else
{
printf("User name or password are incorrect , please enter them again\r\n");
}
}
return 0;
}
|
C
|
#include <stdlib.h>
#include "hello.h"
#include "empty.h"
void empty(void) {
return;
}
int iempty(int i) {
return i;
}
void *pempty(int i, int j) {
/* put some data on the stack to play with in the assembler */
int intiger = 1;
double dbl = 2;
char chr = 'c';
void *point = NULL;
char *msg = TESTSTRING_HELLO;
double unused1;
double unused2;
double unused3;
double unused4;
/* hush compiler warnings */
(void) i;
(void) j;
(void) intiger;
(void) dbl;
(void) chr;
(void) point;
(void) msg;
(void) unused1;
(void) unused2;
(void) unused3;
(void) unused4;
return NULL;
}
|
C
|
#include "lists.h"
#include <stdio.h>
#include <stdlib.h>
/**
* is_palindrome - check whether a linked list of integers is a palindrome
* @head: pointer to head in main function
* Return: 1 if it is a palindrome and -1 if not
*/
int is_palindrome(listint_t **head)
{
listint_t *ptr = *head;
int *arr, list_length = 0, index = 0, half;
if (head == NULL || *head == NULL)
return (0);
while (ptr != NULL)
ptr = ptr->next, list_length += 1;
ptr = *head;
arr = malloc(sizeof(int) * list_length);
if (arr == NULL)
return (-1);
while (ptr != NULL)
arr[index] = ptr->n, ptr = ptr->next, index++;
index = 0;
if ((list_length % 2) != 0)
half = ((list_length - 1) / 2);
else
half = (list_length / 2) - 1;
while (arr[index] == arr[list_length - 1] && half > 0)
{
index++, list_length--, half--;
if (half == 0)
{
free(arr);
return (1);
}
}
free(arr);
return (0);
}
|
C
|
//
// main.c
// 5.3.10
//
// Created by 雅 on 2019/11/21.
// Copyright © 2019 雅. All rights reserved.
//
#include <stdio.h>
#define M 6
int s[M][M];
int main(void)
{
int i=0,j=0,k=1;
s[0][0]=1;
while (k<M*M) {
while (j<M-1&&!s[i][j+1]) {
s[i][++j]=++k;
}
while (i<M-1&&!s[i+1][j]) {
s[++i][j]=++k;
}
while (j>0&&!s[i][j-1]) {
s[i][--j]=++k;
}
while (i>0&&!s[i-1][j]) {
s[--i][j]=++k;
}
}
for (i=0; i<M; i++) {
for (j=0; j<M; j++) {
printf("%6d",s[i][j]);
}
printf("\n");
}
return 0;
}
|
C
|
#include "Queue.h"
Queue *g_Queue = NULL;
// C캯
Queue *QueueListConstruction()
{
g_Queue = (Queue*)malloc(sizeof(Queue));
g_Queue->initQueue = InitQueue;
g_Queue->pushData = DataPush;
g_Queue->popData = DataPop;
g_Queue->delData = DataDel;
g_Queue->clearData= DataClear;
g_Queue->getAvliableSize = GetAvliableSize;
g_Queue->release = ReleaseQueue;
g_Queue->_this = g_Queue;
return (Queue*)g_Queue;
}
/************************************************************************
**InitQueue
**ܣʼ
**
[in] - v_pQueueеthisָ
v_kShmеıʶ
v_ulQueueSize:дС
v_iMsgIdԴݵϢID
v_iSocketSymbԴݵSoceketID
**أ0ɹʧ
************************************************************************/
int InitQueue(void *v_pQueue, unsigned long v_ulQueueSize )
{
if(v_pQueue == NULL)
{
return ERR_PAR;
}
if(0 == v_ulQueueSize )
{
return ERR_PAR;
}
Queue *_this = (Queue *)v_pQueue;
_this->m_ulMemSize = 0;
_this->m_iShmID = -1;
_this->m_pShareMem = NULL;
int iRet = 0;
void* pShare = NULL;
BOOL bFirstCreate = FALSE;
pShare = malloc(v_ulQueueSize);
if( NULL == pShare )
{
iRet = ERR_SHMAT;
_this->m_iShmID = -1;
LOGOUT( "shmat fail" );
goto INIT_END;
}
else
{
bFirstCreate = TRUE;
_this->m_iShmID = 1;
_this->m_pShareMem = (char*)pShare;
LOGOUT( "shmat succ" );
}
if( bFirstCreate )
{
memset( _this->m_pShareMem, 0, v_ulQueueSize );
}
_this->m_ulMemSize = v_ulQueueSize;
pthread_mutex_init(&_this->m_DataMutex, NULL);
INIT_END:
return iRet;
}
/************************************************************************
**DataPop
**ܣ
**
[in] - v_pQueueеthisָ
v_pPopDataݵĻָ
v_dwPopSizeݵĻС
[out] - v_p_dwPopLenݵij
v_p_dwPushSymbݵıʶ
v_p_iMsgIdԴݵϢID
v_p_iSocketSymbԴݵSoceketID
**أ0ɹʧ
**ע:
1).ÿֻһDataPop
************************************************************************/
int DataPop(void *v_pQueue, void* v_pPopData, DWORD v_dwPopSize, DWORD *v_p_dwPopLen, DWORD *v_p_dwPushSymb, int *v_p_iSocketSymb)
{
if(v_pQueue == NULL)
{
return ERR_PAR;
}
Queue *_this = (Queue *)v_pQueue;
if( !_this->m_pShareMem || 0 == _this->m_ulMemSize || -1 == _this->m_iShmID ) return ERR_MEMLACK;
if( NULL == v_pPopData || NULL == v_p_dwPopLen || NULL == v_p_dwPushSymb || NULL == v_p_iSocketSymb) return ERR_PAR;
int iRet = ERR_QUEUE_EMPTY;
INT32U sizeofAddr=sizeof(int *);
pthread_mutex_lock( &_this->m_DataMutex );
PQUEUEHEAD pHead = * (PQUEUEHEAD*) (_this->m_pShareMem); // Եַ
if( pHead ) pHead = (PQUEUEHEAD)( (DWORD)pHead + _this->m_pShareMem ); // Եַ
DWORD dwCur = getTickCountMs();
BOOL bEnd = FALSE;
do
{
// Եַ
if( !pHead )
{
break;
}
if( dwCur - pHead->m_dwPushTime <= QUEUEVALID_PERIOD && pHead->m_bValid ) // δʱЧ
{
if( pHead->m_dwDataLen > v_dwPopSize )
{
iRet = ERR_SPACELACK;
bEnd = TRUE;
goto _POP_ONELOOP_END;
}
memcpy( v_pPopData, (char*)pHead + sizeof(QUEUEHEAD), pHead->m_dwDataLen );
*v_p_dwPopLen = pHead->m_dwDataLen;
*v_p_dwPushSymb = pHead->m_dwPushSymb;
*v_p_iSocketSymb = pHead->m_iSocketSymb;
bEnd = TRUE;
iRet = 0;
goto _POP_ONELOOP_END;
}
else
{
LOGOUT("DataPop: Release overdue or invalid data" );
}
_POP_ONELOOP_END:
pHead = pHead->m_pNext; // ͷָ (õԵַ)
if( pHead )
{
* (PQUEUEHEAD*) (_this->m_pShareMem) = (PQUEUEHEAD)((char*)pHead) ; // ָ, Եַ
pHead = (PQUEUEHEAD)((DWORD)pHead + _this->m_pShareMem); // תΪԵַʹ
}
else
{
// סβָ
* (PQUEUEHEAD*) (_this->m_pShareMem) = NULL;
* (PQUEUEHEAD*) (_this->m_pShareMem + sizeofAddr) = NULL;
}
} while( !bEnd );
pthread_mutex_unlock( &_this->m_DataMutex );
return iRet;
}
/************************************************************************
**DataPush
**ܣв
**
[in] - v_pQueueеthisָ
v_pPushDataݵݻ
v_dwPushLenݵij
v_dwPushSymbݵıʶ
v_iMsgId:ϢID
v_iSocketSymbSocketID
[out] - null
**أ0ɹʧ
************************************************************************/
int DataPush(void *v_pQueue, void* v_pPushData, DWORD v_dwPushLen, DWORD v_dwPushSymb, int v_iSocketSymb)
{
if(v_pQueue == NULL)
{
return ERR_PAR;
}
Queue *_this = (Queue *)v_pQueue;
int iRet = 0;
if( !_this->m_pShareMem || 0 == _this->m_ulMemSize || -1 == _this-> m_iShmID ) return ERR_MEMLACK;
if( 0 == v_dwPushLen ) return ERR_PAR;
INT32U sizeofAddr=sizeof(int *);
pthread_mutex_lock( &_this->m_DataMutex );
PQUEUEHEAD pHead = NULL, pTail = NULL;
PQUEUEHEAD pNew = NULL, pNext = NULL;
// ʱõĽԵַ
pHead = * (PQUEUEHEAD*) (_this->m_pShareMem);
pTail = * (PQUEUEHEAD*) (_this->m_pShareMem + sizeofAddr);
// ʱõIJǾԵַ
if( pHead ) pHead = (PQUEUEHEAD)( (DWORD)pHead + _this->m_pShareMem );
if( pTail ) pTail = (PQUEUEHEAD)( (DWORD)pTail + _this->m_pShareMem );
DWORD dwCirFreeTotal = 0; // ηʱͷſռۻ
DWORD dwCur = getTickCountMs();
if( pHead ) // ʱΪǿն
{
if( !pTail )
{
LOGOUT("DataPush: Head Ptr Vaild but Tail Ptr NULL!" );
return ERR_QUEUE;
}
// ʱӦʹõʼַ
pNew = (PQUEUEHEAD)( (char*)pTail + sizeof(QUEUEHEAD) + pTail->m_dwDataLen ); // ·ַ,Եַ
pNew = (PQUEUEHEAD)( (char*)pNew + ( (DWORD)pNew % sizeofAddr ? sizeofAddr - (DWORD)pNew % sizeofAddr : 0 ) ); // ȷڴ
if( pTail >= pHead ) // ˳ (˶дʱֻһԪص)
{
goto _QUESUN_DEAL;
}
else
{
goto _QUECIR_DEAL;
}
}
else // ˵ʱΪ
{
if( pTail )
{
LOGOUT("DataPush: Head Ptr NULL but Tail Ptr Invalid!" );
return ERR_QUEUE;
}
goto _QUEEMPTY_DEAL;
}
_QUESUN_DEAL: // ˳
if( (char*)pNew + sizeof(QUEUEHEAD) + v_dwPushLen <= _this->m_pShareMem + _this->m_ulMemSize ) // ᳬڴTop߽
{
goto _DATAPUSH_END;
}
else
{
pNew = (PQUEUEHEAD)( _this->m_pShareMem + sizeofAddr*2 );
//PRTMSG( MSG_DBG, "4\n");
goto _QUECIR_DEAL;
}
_QUECIR_DEAL: // η
dwCirFreeTotal = 0;
while( TRUE )
{
// жHeadָ
if( (char*)pHead > _this->m_pShareMem + _this->m_ulMemSize )
{
iRet = ERR_QUEUE;
LOGOUT("DataPush: Head Ptr Over Top Side" );
goto _DATAPUSH_END;
}
// жۻͷſռСǷڴС,ֹѭ
if( dwCirFreeTotal > _this->m_ulMemSize )
{
iRet = ERR_QUEUE;
LOGOUT("DataPush: Cir Alloc Total Free Space Over Space Size" );
goto _DATAPUSH_END;
}
// жǷԻη
if( (char*)pNew + sizeof(QUEUEHEAD) + v_dwPushLen <= (char*)pHead ) // ᳬHeadλ
{
goto _DATAPUSH_END; // ѷ,ɹѭж
}
// жͷǷɾڳռ
if( dwCur <= pHead->m_dwPushTime + QUEUEVALID_PERIOD ) // ͷδʱ
{
iRet = ERR_QUEUE_FULL; // ɾ,Ԫ
goto _DATAPUSH_END; // ʧ,ѭж
}
else
{
LOGOUT( "DataPush: Release overdue data" );
}
// ͷݿͷ
// ͷͷݿռ
pNext = pHead->m_pNext; // Եַ
if( pNext ) pNext = (PQUEUEHEAD)( (DWORD)pNext + _this->m_pShareMem ); // Եַ
if( !pNext ) // ͷһԪ,бΪն
{
if( pTail != pHead )
{
iRet = ERR_QUEUE;
LOGOUT( "DataPush: For Last Element, Head Ptr != Tail Ptr" );
goto _DATAPUSH_END;
}
pHead = pTail = NULL; // ͷβָ
goto _QUEEMPTY_DEAL; // תΪն״̬
}
// ͷŵIJһԪ,ͷźȻǿ
// жǷͷŵTop߽Ԫ
if( pNext < pHead )
{
// ȼۻͷſռ
dwCirFreeTotal += (DWORD)( _this->m_pShareMem + _this->m_ulMemSize - (char*)pHead );
// ٸͷָ,Եַ
pHead = pNext;
// ȻжϼǷTop߽
if( (char*)pNew + sizeof(QUEUEHEAD) + v_dwPushLen <= _this->m_pShareMem + _this->m_ulMemSize ) // Top߽
{
//PRTMSG( MSG_DBG, "6\n");
goto _DATAPUSH_END;
}
else
{
pNew = (PQUEUEHEAD)( _this->m_pShareMem + sizeofAddr*2 ); // ´δBottom߽翪ʼжϿɷ
}
}
else
{
pHead = pNext; // ͷָ,Եַ
dwCirFreeTotal += (DWORD)( (char*)pNext - (char*)pHead ); // ۻͷſռ
}
}
_QUEEMPTY_DEAL: // նз
pHead = pTail = NULL; // ȷͷβָΪ
pNew = (PQUEUEHEAD)( _this->m_pShareMem + sizeofAddr*2 ); // ӱ߽翪ʼ,Եַ
if( (char*)pNew + sizeof(QUEUEHEAD) + v_dwPushLen <= _this->m_pShareMem + _this->m_ulMemSize ) // ᳬڴTop߽
{
pHead = pNew; // ֻͷָ (βָͳһ)
goto _DATAPUSH_END;
}
else
{
iRet = ERR_QUEUE_TOOSMALL;
goto _DATAPUSH_END;
}
_DATAPUSH_END:
// ǰɹ,ͳһԪز
if( !iRet )
{
// Ԫظֵ
memcpy( (char*)pNew + sizeof(QUEUEHEAD), v_pPushData, v_dwPushLen );
pNew->m_dwPushSymb = v_dwPushSymb;
pNew->m_iSocketSymb = v_iSocketSymb;
pNew->m_dwDataLen = v_dwPushLen;
pNew->m_dwPushTime = dwCur;
pNew->m_pNext = NULL;
pNew->m_bValid = TRUE;
// ԭβԪصĺָָεβԪ, Եַ (ԭβԪشʱ)
if( pTail ) pTail->m_pNext = (PQUEUEHEAD)( (char*)pNew - _this->m_pShareMem );
// βָ,Եַ
pTail = pNew;
}
// ڹڴиͷβָ (Եַ)
*(PQUEUEHEAD*) (_this->m_pShareMem) = (PQUEUEHEAD)( pHead ? ((char*)pHead - _this->m_pShareMem) : NULL ); // ͷָ
*(PQUEUEHEAD*) (_this->m_pShareMem + sizeofAddr) = (PQUEUEHEAD)( pTail ? ((char*)pTail - _this->m_pShareMem) : NULL ); // βָ
if( iRet ) LOGOUT("DataPush: Result %d", iRet );
pthread_mutex_unlock( &_this->m_DataMutex );
return iRet;
}
/************************************************************************
**DataDel
**ܣɾ
**
[in] - v_pQueueеthisָ
v_dwPushSymbɾݵıʶ
[out] - null
**أɹ0ʧܣ
************************************************************************/
int DataDel(void *v_pQueue, DWORD v_dwPushSymb )
{
if(v_pQueue == NULL)
{
return ERR_PAR;
}
Queue *_this = (Queue *)v_pQueue;
if( !_this->m_pShareMem || 0 == _this->m_ulMemSize || -1 == _this->m_iShmID ) return ERR_MEMLACK;
PQUEUEHEAD pHead = * (PQUEUEHEAD*) (_this->m_pShareMem); // Եַ
if( pHead ) pHead = (PQUEUEHEAD)( (DWORD)pHead + _this->m_pShareMem ); // Եַ
PQUEUEHEAD pCur = pHead;
pthread_mutex_lock( &_this->m_DataMutex );
while( pCur )
{
if( v_dwPushSymb == pCur->m_dwPushSymb )
{
pCur->m_bValid = FALSE;
}
pCur = pCur->m_pNext;
if( pCur )
{
pCur = (PQUEUEHEAD)( (DWORD)pCur + _this->m_pShareMem );
}
}
pthread_mutex_unlock( &_this->m_DataMutex );
return 0;
}
/************************************************************************
**DataClear
**ܣն
**
[in] - v_pQueueеthisָ
[out] - null
**أɹ0ʧܣ
************************************************************************/
int DataClear(void *v_pQueue)
{
if(v_pQueue == NULL)
{
return ERR_PAR;
}
Queue *_this = (Queue *)v_pQueue;
if( !_this->m_pShareMem || 0 == _this->m_ulMemSize || -1 == _this->m_iShmID )
{
return ERR_MEMLACK;
}
pthread_mutex_lock( &_this->m_DataMutex );
memset( _this->m_pShareMem, 0, _this->m_ulMemSize );
pthread_mutex_unlock( &_this->m_DataMutex );
return 0;
}
/************************************************************************
**GetAvliableSize
**ܣȡǰöпռ
**
[in] - v_pQueueеthisָ
[out] - null
**أпÿռС
************************************************************************/
DWORD GetAvliableSize(void *v_pQueue)
{
if(v_pQueue == NULL)
{
return ERR_PAR;
}
Queue *_this = (Queue *)v_pQueue;
int iSize = 0;
PQUEUEHEAD pHead = NULL, pTail = NULL;
INT32U sizeofAddr=sizeof(int *);
pthread_mutex_lock( &_this->m_DataMutex );
pHead = * (PQUEUEHEAD*) (_this->m_pShareMem);
pTail = * (PQUEUEHEAD*) (_this->m_pShareMem + sizeofAddr);
if( pHead ) pHead = (PQUEUEHEAD)( (DWORD)pHead + _this->m_pShareMem );
if( pTail ) pTail = (PQUEUEHEAD)( (DWORD)pTail + _this->m_pShareMem );
iSize = (char*)pTail - (char*)pHead;
if( iSize < 0 )
{
iSize += _this->m_ulMemSize;
}
iSize += sizeof(QUEUEHEAD);
if( pTail )
{
iSize += sizeof(QUEUEHEAD) + pTail->m_dwDataLen + ( pTail->m_dwDataLen % sizeofAddr ? sizeofAddr - pTail->m_dwDataLen % sizeofAddr : 0 );
}
pthread_mutex_unlock( &_this->m_DataMutex );
return (DWORD)(_this->m_ulMemSize - iSize - sizeofAddr*2);
}
/************************************************************************
**ReleaseQueue
**ܣͷŶ
**
[in] - v_pQueueеthisָ
[out] - null
**أvoid
************************************************************************/
void ReleaseQueue(void *v_pQueue)
{
if(v_pQueue == NULL)
{
LOGOUT("v_pQueue is NULL");
return ;
}
Queue *_this = (Queue *)v_pQueue;
if( _this->m_pShareMem )
{
free(_this->m_pShareMem);
_this->m_pShareMem = NULL;
}
if(_this->m_iShmID != -1)
_this->m_iShmID=-1;
pthread_mutex_destroy( &_this->m_DataMutex );
}
|
C
|
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int num,revn=0,p=0,temp,tdigit=0,originalnumber;
clrscr();
printf("Enter the number:-\n");
scanf("%d",&num);
temp=num;
originalnumber=num;
while(temp>0)
{
temp/=10;
tdigit++;
}
while(num>0)
{
revn+=((num%10)*pow(10,tdigit-1));
num/=10;
p++;
tdigit--;
}
printf("Reverse %d\n",revn);
if(originalnumber==revn)
printf("Palindrome.");
else
printf("Not palindrome.");
getch();
}
|
C
|
/*
* =============================================================================
*
* Filename: 8.c
*
* Description: itos converts non-negative integers < 100 into words.
*
* Version: 1.0
* Created: 11-11-19 23:15:53 PM
* Revision: none
* Compiler: gcc
*
* Author: Alan Kydd (), akydd@ualberta.net
* Company:
*
* =============================================================================
*/
#include <stdio.h>
#include <string.h>
#include <math.h>
static char *itos(int, char*);
char *itos(int number, char *s)
{
int divisor;
int remainder;
if ( (number <= 100) && (number >= 0) ) {
/* boundary cases */
if (number == 100) {
(void)strcat(s, "one hundred");
} else if (number == 0) {
(void)strcat(s, "zero");
} else {
/* handle numbers from 1 to 99 */
divisor = number / 10;
remainder = number % 10;
/* numbers >= 20 */
if (divisor >= 2) {
switch (divisor) {
case 9:
(void)strcat(s, "ninety");
break;
case 8:
(void)strcat(s, "eighty");
break;
case 7:
(void)strcat(s, "seventy");
break;
case 6:
(void)strcat(s, "sixty");
break;
case 5:
(void)strcat(s, "fifty");
break;
case 4:
(void)strcat(s, "fourty");
break;
case 3:
(void)strcat(s, "thirty");
break;
case 2:
(void)strcat(s, "twenty");
break;
default:
(void)printf("wft?");
}
} else if (divisor == 1) {
/* less than 20, greater or equal to 10 */
switch (number) {
case 19:
(void)strcat(s, "nineteen");
break;
case 18:
(void)strcat(s, "eighteen");
break;
case 17:
(void)strcat(s, "seventeen");
break;
case 16:
(void)strcat(s, "sixteen");
break;
case 15:
(void)strcat(s, "fifteen");
break;
case 14:
(void)strcat(s, "fourteen");
break;
case 13:
(void)strcat(s, "thirteen");
break;
case 12:
(void)strcat(s, "twelve");
break;
case 11:
(void)strcat(s, "eleven");
break;
case 10:
(void)strcat(s, "ten");
break;
}
}
/* handle the remainders */
if (divisor != 1) {
/* hyphen */
if ( (divisor > 1) && (remainder != 0) ) {
(void)strcat(s, "-");
}
switch (remainder) {
case 1:
(void)strcat(s, "one");
break;
case 2:
(void)strcat(s, "two");
break;
case 3:
(void)strcat(s, "three");
break;
case 4:
(void)strcat(s, "four");
break;
case 5:
(void)strcat(s, "five");
break;
case 6:
(void)strcat(s, "six");
break;
case 7:
(void)strcat(s, "seven");
break;
case 8:
(void)strcat(s, "eight");
break;
case 9:
(void)strcat(s, "nine");
break;
}
}
}
}
return s;
}
int main(void)
{
char input[10];
char string[200];
int number;
int result;
while (1 == 1) {
/* null out the string */
string[0] = '\0';
/* read in the number */
(void)printf("Enter a number (non number to quit): ");
(void)fgets(input, sizeof(input), stdin);
result = sscanf(input, "%d", &number);
/* if we didn't get a number, quit. */
if (result != 1) {
break;
}
/* call the itos method */
(void)itos(number, string);
(void)printf("Number %d converted to string is %s.\n",
number, string);
}
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* pixels_and_colors.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: psergean <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/09/14 13:02:36 by psergean #+# #+# */
/* Updated: 2017/10/29 14:50:43 by psergean ### ########.fr */
/* */
/* ************************************************************************** */
#include "./../includes/wolf3d.h"
int texture_colors(t_env *env, int x, int y)
{
int color;
int c;
c = (y * 64 + x) * 4;
color = env->texture[env->id]->pxl[c];
if (color == -120 && env->texture[env->id]->pxl[c + 1] == 0
&& env->texture[env->id]->pxl[c + 2] == -104)
return (256 * 256 * 256 + 256 * 256 + 256);
color += env->texture[env->id]->pxl[c + 1] * 256;
color += env->texture[env->id]->pxl[c + 2] * 256 * 256;
return (color);
}
void draw_texture(t_env *env, int x, int y, int color)
{
char b;
char g;
char r;
int i;
i = 0;
if (color == 256 * 256 * 256 + 256 * 256 + 256)
return ;
b = color % 256;
g = (color / 256) % 256;
r = (color / 256 / 256) % 256;
i = (x * (env->bpp / 8)) + (env->size_line * y);
env->pxl[i] = b;
env->pxl[++i] = g;
env->pxl[++i] = r;
}
void draw(t_calc *calc, t_env *env, int drawstart)
{
env->y = -1;
while (++env->y < drawstart)
{
}
env->y--;
calc_texture(calc, env);
calc_floor(calc, env);
}
|
C
|
/***************************************************************************************
* File Name : BSTree.h
* CopyRight : 2021 QG Studio
* SYSTEM : win10
* Create Data : 2021.4.24
*
*
*--------------------------------Revision History--------------------------------------
* No version Data Revised By Item Description
*
*
***************************************************************************************/
#ifndef BINARYSORTTREE_BINARY_SORT_TREE_H
#define BINARYSORTTREE_BINARY_SORT_TREE_H
#define true 1
#define false 0
#define succeed 1
#define failed 0
#define Status int
typedef int ElemType;
typedef struct Node {
ElemType value;
struct Node* left, * right;
}Node, *NodePtr;
typedef struct BinarySortTree {
NodePtr root ;
} BinarySortTree, *BinarySortTreePtr;
/**
* BST initialize
* @param BinarySortTreePtr BST
* @return is complete
*/
Status BST_init(BinarySortTreePtr);
/**
* BST insert
* @param BinarySortTreePtr BST
* @param ElemType value to insert
* @return is successful
*/
Status BST_insert(BinarySortTreePtr, ElemType);
/**
* BST delete
* @param BinarySortTreePtr BST
* @param ElemType the value for Node which will be deleted
* @return is successful
*/
Status BST_delete(BinarySortTreePtr, ElemType);
/**
* BST search
* @param BinarySortTreePtr BST
* @param ElemType the value to search
* @return is exist
*/
Status BST_search(BinarySortTreePtr, ElemType);
/**
* BST preorder traversal without recursion
* @param BinarySortTreePtr BST
* @param (*visit) callback
* @return is successful
*/
Status BST_preorderI(BinarySortTreePtr, void (*visit)(NodePtr));
/**
* BST preorder traversal with recursion
* @param BinarySortTreePtr BST
* @param (*visit) callback
* @return is successful
*/
Status BST_preorderR(BinarySortTreePtr, void (*visit)(NodePtr));
/**
* BST inorder traversal without recursion
* @param BinarySortTreePtr BST
* @param (*visit) callback
* @return is successful
*/
Status BST_inorderI(BinarySortTreePtr, void (*visit)(NodePtr));
/**
* BST inorder traversal with recursion
* @param BinarySortTreePtr BST
* @param (*visit) callback
* @return is successful
*/
Status BST_inorderR(BinarySortTreePtr, void (*visit)(NodePtr));
/**
* BST preorder traversal without recursion
* @param BinarySortTreePtr BST
* @param (*visit) callback
* @return is successful
*/
Status BST_postorderI(BinarySortTreePtr, void (*visit)(NodePtr));
/**
* BST postorder traversal with recursion
* @param BinarySortTreePtr BST
* @param (*visit) callback
* @return is successful
*/
Status BST_postorderR(BinarySortTreePtr, void (*visit)(NodePtr));
/**
* BST level order traversal
* @param BinarySortTreePtr BST
* @param (*visit) callback
* @return is successful
*/
Status BST_levelOrder(BinarySortTreePtr, void (*visit)(NodePtr));
void visit(Node *pnode);
#endif //BINARYSORTTREE_BINARY_SORT_TREE_H
|
C
|
#include "drawarea.h"
#include "config.h"
#include <stdlib.h>
#include <assert.h>
#include <stdio.h>
//获得新的画布对象
struct drawarea * drawarea_new(struct window *window)
{
struct drawarea * cthis = (struct drawarea *)malloc(sizeof(struct drawarea));
if(!cthis)
return NULL;
//初始化内部成员
cthis->window = window;
cthis->graph_objlist_count = 0;
cthis->graph_objlist_max = __DRAWAREA_GRAPH_OBJ_DEFAULT_MAX__;
cthis->graph_objlist = (struct graph **)calloc(__DRAWAREA_GRAPH_OBJ_DEFAULT_MAX__,sizeof(struct graph *));
cthis->graph_select = (struct graph **)calloc(__DRAWAREA_GRAPH_OBJ_DEFAULT_MAX__,sizeof(struct graph *));
cthis->graph_select_count = 0;
cthis->graph_select_max = __DRAWAREA_GRAPH_OBJ_DEFAULT_MAX__;
cthis->is_showtag = 0;
cthis->height = (cthis->window)->height;
cthis->width = (cthis->window)->width;
cthis->statusbar = POINT(30,50);
cthis->statusbar_info[0] = 0;
cthis->is_showbar = 1;
return cthis;
}
//状态栏提示:
int drawarea_statusbar_draw(struct drawarea *cthis)
{
window_draw_tag(cthis->window,cthis->statusbar,cthis->statusbar_info);
return 0;
}
int drawarea_statusbar_clear(struct drawarea *cthis)
{
cthis->statusbar_info[0] = 0;
return 0;
}
int drawarea_statusbar_print(struct drawarea *cthis,char *msg)
{
strncpy(cthis->statusbar_info,msg,__DRAWAREA_STATUSBAR_INFOTEXT_MAX__);
return 0;
}
//添加选中的对象
int drawarea_select_insert(struct drawarea *cthis,struct graph *object)
{
assert(cthis->graph_select_count <= cthis->graph_select_max);
if(cthis->graph_select_count == cthis->graph_select_max)
{
//空间不够
cthis->graph_select_max += __DRAWAREA_GRAPH_OBJ_DEFAULT_MAX__;
cthis->graph_select = (struct graph **)realloc(cthis->graph_select,
cthis->graph_select_max
* sizeof(struct graph *));
}
//查找对象在队列中是否已经存在
for(int i = 0; i < cthis->graph_select_count ; i++)
if(((cthis->graph_select)[i])->object_id == object->object_id) //对象已经存在
return 0;
cthis->graph_select[cthis->graph_select_count] = object;
(cthis->graph_select_count)++;
return 0;
}
int drawarea_delete_graph(struct drawarea *cthis,struct graph *gobj)
{
//删除指定的对象
int delete_id = -1;
for(int i = 0; i < cthis->graph_objlist_count ; i++)
if(((cthis->graph_objlist)[i]) == gobj)
{
delete_id = i;
break;
}
if(delete_id == -1 )
//未找到删除的对象:指针错误
return -1;
graph_exit((cthis->graph_objlist)[delete_id]);
//从队列中删除对象指针
for(int i = delete_id; i < cthis->graph_objlist_count - 1; i++)
(cthis->graph_objlist)[i] = (cthis->graph_objlist)[i+1];
(cthis->graph_objlist_count)--; // 减少计数
return 0;
}
//清空选中队列
int drawarea_select_empty(struct drawarea *cthis)
{
memset(cthis->graph_select,0,sizeof(struct graph *)*(cthis->graph_select_count));
cthis->graph_select_count = 0;
drawarea_statusbar_clear(cthis);
return 0;
}
int drawarea_select_show_selected(struct drawarea *cthis)
{
//显示当前选中的图形对象ID
char status_tmp[__DRAWAREA_STATUSBAR_INFOTEXT_MAX__];
strcpy(status_tmp,"SELECTED:");
for(int i = 0; i < cthis->graph_select_count ; i++)
{
char tmpchar[50];
sprintf(tmpchar,"%d ",((cthis->graph_select)[i])->object_id);
strcat(status_tmp,tmpchar);
}
drawarea_statusbar_print(cthis,status_tmp);
return 0;
}
struct graph * drawarea_search(struct drawarea *cthis,int id)
{
for(int i = 0; i < cthis->graph_objlist_count ; i++)
if((((cthis->graph_objlist)[i])->object_id) == id)
return ((cthis->graph_objlist)[i]);
return NULL;
}
int drawarea_delete(struct drawarea *cthis)
{
//TODO:存在内存泄露的可能
//TODO:释放存在队列中的对象本身的内存
free(cthis->graph_objlist);
free(cthis);
return 0;
}
int drawarea_insert_graph(struct drawarea *cthis,struct graph *gobj)
{
//断言:队列中对象的数量应当小于等于队列容量
assert(cthis->graph_objlist_count <= cthis->graph_objlist_max);
if(cthis->graph_objlist_count == cthis->graph_objlist_max)
{
//空间不够
cthis->graph_objlist_max += __DRAWAREA_GRAPH_OBJ_DEFAULT_MAX__;
cthis->graph_objlist = (struct graph **)realloc(cthis->graph_objlist,
cthis->graph_objlist_max
* sizeof(struct graph *));
}
//添加对象
cthis->graph_objlist[cthis->graph_objlist_count] = gobj;
(cthis->graph_objlist_count)++;
return 0;
}
//画标记
int drawarea_showtags(struct drawarea *cthis)
{
for(int i = 0; i < cthis->graph_objlist_count ; i++)
((cthis->graph_objlist)[i])->draw_tag(cthis->graph_objlist[i],cthis->window);
return 0;
}
int drawarea_draw(struct drawarea *cthis)
{
//清空缓冲区
window_zero(cthis->window);
//重画
for(int i = 0; i < cthis->graph_objlist_count ; i++)
((cthis->graph_objlist)[i])->draw(cthis->graph_objlist[i],cthis->window);
if(cthis->is_showtag)
drawarea_showtags(cthis);
if(cthis->is_showbar)
drawarea_statusbar_draw(cthis);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int *a, i;
a = (int *) calloc(5, sizeof(int));// Arreglo dinamico de 5
// este arreglo lo de arriba lo puedes poner mas adelante y cambiar como
// si fuera una variable lo puedes incrementar o decrementar
a[0] = 6;
a[1] = -512;
a[2] = 2001;
a[3] = -3;
a[4] = 10;
for (i = 0; i < 5; ++i)
printf("%d\n", a[i]);
printf("\n");
free(a);
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
// by debbah Mehdi Sofaine (MehdiSlik)
// note : in binarys search the vector must be sorted
// binary search of an element
int binary_search(int* vect ,int N,int x)
{
// debut :is the begin of vector vect
// fin : is the end of vector vect
// x :is the element we went to search
int debut =0 ; int fin= N-1,mil;
while( fin>=debut) {
mil=(int)((debut+fin)/2);
if (x==vect[mil]){
printf(" the element exist his index is :%d ",mil);
return mil;}
else if (x>vect[mil])debut=mil+1;
else fin=mil-1;
}
// if fin< debut
printf("the element doesnt exist ");
return -1 ;
}
int main(){
int n,i ;int * t,x;
printf("entre the size of the array :\n");
scanf("%d",&n);
//array allocation
t= (int*)(malloc(n* sizeof(int))) ;
//array initialization
for( i=0;i<n;i++){
*(t+i)=i+5;
fflush(stdin);
}
printf("\n show array: \n");
// array show
for( i=0;i<n;i++) {
printf("%d \t",t[i]);
}
printf("\n entre the element you went to search :");
fflush(stdin);
scanf("%d",&x);
int indexe=binary_search(t,n,x);
//printf("the indexe :%d",indexe);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <signal.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
void sigsegv_handler(int e){
fprintf(stderr, "Error: Segmentation fault by option --segfault registered by --catch\n");
fprintf(stderr, "Error Signal: %s \n", strerror(e));
exit(4);
}
int main(int argc, char**argv){
//flags
int in = 0;
int out = 0;
int seg = 0;
int cat = 0;
char* input_file = NULL;
char* output_file = NULL;
int len;
static struct option long_options[] = {
{"input", required_argument, NULL, 'i'},
{"output", required_argument, NULL, 'o'},
{"segfault", no_argument, NULL, 's'},
{"catch", no_argument, NULL, 'c'},
{0, 0, 0, 0}
};
int option;
while((option=getopt_long(argc, argv, ":i:o:sc", long_options, NULL))!=-1){
switch(option){
case 'i':
in = 1;
len = strlen(optarg);
input_file=malloc((len+1)*sizeof(char));
strcpy(input_file, optarg);
break;
case 'o':
out = 1;
len = strlen(optarg);
output_file=malloc((len+1)*sizeof(char));
strcpy(output_file, optarg);
break;
case 's':
seg=1;
break;
case 'c':
cat=1;
break;
case '?':
fprintf(stderr, "Error: Unknown argument\n");
fprintf(stderr, "Usage: ./lab0 --input <input_file_path> --output <output_file_path> --segfault --catch\n");
if(input_file){
free(input_file);
}
if(output_file){
free(output_file);
}
exit(1);
break;
case ':':
fprintf(stderr, "Error: An argument must be provided for --input or --output\n");
fprintf(stderr, "Usage: ./lab0 --input <input_file_path> --output <output_file_path> --segfault --catch\n");
if(input_file){
free(input_file);
}
if(output_file){
free(output_file);
}
exit(1);
}
}
if(in == 1){
int ifd = open(input_file, O_RDONLY);
if(ifd<0){
fprintf(stderr, "Error: Cannot open file %s on option --input\n", input_file);
fprintf(stderr, "%s\n", strerror(errno));
if(input_file){
free(input_file);
}
if(output_file){
free(output_file);
}
exit(2);
}
close(0);
dup(ifd);
close(ifd);
}
if(out == 1){
int ifd = creat(output_file, 0666);
if(ifd<0){
fprintf(stderr, "Error: Cannot create file %s on option --output\n", output_file);
fprintf(stderr, "%s\n", strerror(errno));
if(input_file){
free(input_file);
}
if(output_file){
free(output_file);
}
exit(3);
}
close(1);
dup(ifd);
close(ifd);
}
if(cat==1){
signal(SIGSEGV, sigsegv_handler);
}
if(seg==1){
char* gotcha = NULL;
*gotcha = 'g';
}
char* str = malloc(1);
int* c = malloc(1);
int index = 0;
int stat;
while(1){
stat = read(0, c, 1);
if(stat<=0)
break;
//write(1, c, 1);
str=realloc(str, index+1);
if(!str)
exit(1);
str[index]=*c;
index++;
}
write(1, str, index);
free(str);
free(c);
if(input_file){
free(input_file);
}
if(output_file){
free(output_file);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#if defined(_WIN32)
#include <winsock2.h>
int create_socket(char* destHost, short destPort, char* res)
{
WSADATA wsa;
SOCKET s;
// printw("\nInitialising Winsock...");
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0)
{
// printw("Failed. Error Code : %d", WSAGetLastError());
return 1;
}
if ((s = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET)
{
// printw("Could not create socket : %d", WSAGetLastError());
return 1;
}
// printw("Socket created.\n");
struct sockaddr_in server;
server.sin_family = AF_INET;
server.sin_port = htons(destPort);
server.sin_addr.s_addr = inet_addr(destHost);
// Connect to remote server
int connection_status = connect(s, (struct sockaddr *)&server, sizeof(server));
if (connection_status != 0) {
return connection_status;
}
// Receieve data from the server, load into res string
recv(s, res, sizeof(res), 0);
// Close socket
close(s);
return 0;
}
#else
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
// #include <ncurses.h>
int create_socket(char addr[], int port, char *res)
{
// Create a socket
int s = socket(AF_INET, SOCK_STREAM, 0);
// Specify address:port dest
struct sockaddr_in server;
server.sin_family = AF_INET;
server.sin_port = htons(port);
server.sin_addr.s_addr = inet_addr(addr);
int connection_status = connect(s, (struct sockaddr *)&server, sizeof(server));
// Connect to remote server
if (connection_status != 0)
{
// puts("connect error");
return connection_status;
}
// Receieve data from the server, load into res string
recv(s, res, sizeof(res), 0);
// Print response
// printw("The server responded with: %s\n", res);
// Close socket
close(s);
return 0;
}
#endif
|
C
|
#include "bs-tree.h"
node *Raiz;
/*----------------------------------------------------------------------------*/
/* Calcula altura da arvore */
/*----------------------------------------------------------------------------*/
int h_tree( node **n) {
node *current =*n;
int hl, hr;
if ( !current ) {
return 0;
}
hl =h_tree( &(current->left) );
hr =h_tree( &(current->right) );
if (hl>hr) {
return hl+1;
}
else {
return hr+1;
}
}
/*----------------------------------------------------------------------------*/
/* Visualizacao da arvore sem arquivo */
/*----------------------------------------------------------------------------*/
void show_tree_sem_arq( node *n, int b ) {
int i;
object o;
if (n == NULL) {
for (i = 0; i < b; i++)
printf(" ");
printf("*\n"); //aponta pra NULL
return;
}
show_tree_sem_arq( n->right, b+1 );
for (i = 0; i < b; i++)
printf(" ");
o =n->value;
printf("%d", o );
printf("(%i)", n->balance );
printf("\n");
show_tree_sem_arq( n->left, b+1 );
}
void show_tree_sem_arq1( node *n,int b ) {
printf("-------------------------------------------------------------------------------------------------\n");
show_tree_sem_arq (n, b);
printf("-------------------------------------------------------------------------------------------------\n");
}
/*----------------------------------------------------------------------------*/
/* Faz a compraracao entre dois objects */
/*----------------------------------------------------------------------------*/
int objectcmp( object *o1, object *o2 ) {
return *o1 < *o2 ? -1 : *o1 > *o2 ? 1 : 0;
}
/*----------------------------------------------------------------------------*/
/* Cria e aloca um novo no */
/*----------------------------------------------------------------------------*/
node *create_node( node **n) {
node *new_node;
if ( !(new_node = malloc(sizeof(node)))) {
fprintf (stderr, "Error while running Binary Tree Library: Alloc node failed.\n");
exit (1);
}
new_node->value = 0;
new_node->balance = 0;
new_node->left = NULL;
new_node->right = NULL;
*n = new_node;
return *n;
}
/*----------------------------------------------------------------------------*/
/* Rotaciona o node para a esquerda */
/*----------------------------------------------------------------------------*/
void rotation_left( node **n) {
node *a = *n;
node *b = (*n)->right;
a->right = b->left;
b->left = a;
(*n) = b;
}
/*----------------------------------------------------------------------------*/
/* Rotaciona o node para a direita */
/*----------------------------------------------------------------------------*/
void rotation_right( node **n) {
node *a = *n;
node *b = (*n)->left;
a->left = b->right;
b->right = a;
(*n) = b;
}
/*----------------------------------------------------------------------------*/
/* Conta Node */
/*----------------------------------------------------------------------------*/
int conta_node( node **n) {
int conta = 0 ;
node *current = *n;
if ( !current ) return 0;
conta = 1 + conta_node( &(current->left) ) + conta_node( &(current->right) );
return conta;
}
/*----------------------------------------------------------------------------*/
/* Insere um node na arvore */
/*----------------------------------------------------------------------------*/
int insert_node_r( node **n, object *o) {
// curret =enderco de uma estrutura de um ponteiro node
node *current = *n;
// Se nao tem curret alocado, cria um node (BASE)
if( !current ) {
// Se nao conseguir criar um novo node
if( !(current = create_node( ¤t ) ) )
return 0;
current->value = *o;
*n = current;
return 1;
// Senao compara o objeto com o objeto do valor que tem na arvore
} else if( objectcmp( o, ¤t->value ) == -1 ) {
if( insert_node_r( &(current->left ), o ) == 1){
current->balance++;
return 1;
}
} else if( objectcmp( o, ¤t->value ) == 1 ) {
if( insert_node_r( &(current->right ), o) == 1){
current->balance--;
return 1;
}
}
return 0;
}
int insert_node( node **n, object *o) {
// curret =enderco de uma estrutura de um ponteiro node
if ( !Raiz ) {
// Se nao conseguir criar um novo node
if( !(Raiz = create_node( &Raiz ) ) )
return 0;
Raiz->value = *o;
return 1;
}
if ( !(insert_node_r( n, o ) ) )
return 0;
return 1;
}
/*----------------------------------------------------------------------------*/
/* Particonamento da Arvore */
/*----------------------------------------------------------------------------*/
node *particao_arv_teste( node **n, int k ){
node *current = *n;
int t = conta_node ( &(current->left) ),
l = conta_node ( &(current->right) );
if ( t+1 == k) {
return current;
}
if ( k <= t) {
current->left = particao_arv_teste( &(current->left), k );
rotation_right( ¤t );
return current;
}
current->right = particao_arv_teste( &(current->right), k - t - 1);
rotation_left( ¤t );
return current;
}
node *particao_arv_r( node **n, int k ){
int t, l;
node *current = *n;
t = conta_node ( &(current->left) );
if( t > k ) {
current->left = particao_arv_r( &(current->left), k );
rotation_right( ¤t );
}
if( t < k ) {
current->right = particao_arv_r( &(current->right), k -t -1 );
rotation_left( ¤t );
}
return current;
}
node *particao( node **n, int k ){
node *current = *n;
if( (conta_node( ¤t )) <= k ) {
return current;
}
else {
return particao_arv_teste( ¤t, k );
}
}
/*----------------------------------------------------------------------------*/
/* Arruma Arvore */
/*----------------------------------------------------------------------------*/
node *arruma_arvore_r (node **n ) {
node *current = *n;
int qtd_nl = conta_node ( &(current->left) )/2,
qtd_nr = conta_node ( &(current->right) )/2;
if ( !current )
return NULL;
if ( qtd_nl > 0 ) {
current->left = particao( &(current->left), qtd_nl );
}
if (qtd_nr > 0 ) {
current->right = particao( &(current->right), qtd_nr );
}
return current;
}
node *arruma_arvore () {
node *l =Raiz->left,
*r =Raiz->right;
int qtd_n = conta_node ( &Raiz )/2;
Raiz = particao( &Raiz, qtd_n );
Raiz->left = arruma_arvore_r ( &(Raiz->left) );
Raiz->right = arruma_arvore_r ( &(Raiz->right) );
return Raiz;
}
main () {
char choose;
int control, altura;
object valor;
Raiz = NULL;
// Enquanto nao acabar o arquivo de leitura
while ( control ) {
printf("\nIniciando nova secao\n");
scanf("%c", &choose );
switch ( choose ) {
case 'i': printf("++ insercao\n");
scanf("%d", &valor );
printf("%d\n", valor );
insert_node( &Raiz, &valor );
break;
case 'b': printf("++ busca\n");
scanf("%d", &valor);
printf("%d\n", valor);
break;
case 'r': printf("++ remocao\n");
scanf("%d", &valor);
printf("%d\n", valor);
break;
default: printf("++ nada\n");
printf("Finalizando o Programa\n");
control =0;
break;
}
// Enquanto nao chegar no final da linha do arquivo lido
while (choose != 10) {
scanf("%c", &choose );
}
altura = h_tree( &Raiz );
show_tree_sem_arq1 ( Raiz, altura );
}
Raiz = arruma_arvore ();
printf("arvore final \n");
altura = h_tree( &Raiz );
show_tree_sem_arq1 ( Raiz, altura );
}
|
C
|
#include<stdio.h>
#include<string.h>
void main()
{
char string1[50],string2[50];
printf("Enter strings to concatenate: \n");
scanf ("%s",string1);
scanf ("%s",string2);
strcat (string1,string2);
printf ("The concatenated string is: %s.\n",string1);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* waiter_init.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: blacking <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/06/03 16:23:40 by blacking #+# #+# */
/* Updated: 2020/11/11 23:35:05 by stbaleba ### ########.fr */
/* */
/* ************************************************************************** */
#include "philo_three.h"
t_msg *fill_msg(void)
{
t_msg *res;
int i;
if (!(res = (t_msg *)malloc(sizeof(t_msg) * RESET)))
return (0);
i = 0;
while (i < RESET)
{
res[i].msg = 0;
res[i].time = 0;
i++;
}
return (res);
}
t_waiter *init_waiter(char **av, int ac)
{
t_waiter *waiter;
sem_unlink("/forks");
sem_unlink("/display");
if (!(waiter = (t_waiter *)malloc(sizeof(t_waiter) * ft_atoi(av[1]))))
return (NULL);
waiter->nthread = ft_atoi(av[1]);
waiter->tdie = ft_atoi(av[2]);
waiter->teat = ft_atoi(av[3]);
waiter->tsleep = ft_atoi(av[4]);
waiter->end = 0;
waiter->j = 0;
waiter->i = 0;
waiter->msg = fill_msg();
waiter->fork = sem_open("/forks", O_CREAT, S_IRWXU, ft_atoi(av[1]));
waiter->display = sem_open("/display", O_CREAT, S_IRWXU, 1);
if (ac == 6)
waiter->ntoeat = ft_atoi(av[5]);
else
waiter->ntoeat = -1;
return (waiter);
}
|
C
|
#include <stdio.h>
int main()
{
int a,sum=0,rem,base=1;
scanf("%d",&a);
while(a)
{
rem=a%2;
sum=rem*base+sum;
a=a/2;
base=base*10;
}
printf("%d",sum);
return 0;
}
|
C
|
/**************************************************/
/* */
/* Programmer: Abdullah Mahmoud */
/* */
/* Program 52: Mind your Ps and Qs */
/* */
/* Time to Complete: 10 minutes */
/* */
/**************************************************/
#include <stdio.h>
#include <stdlib.h>
int largestUpper( int **A, int *p, int *q ) ;
int main( int argc, char *argv[] ) {
int **A, i, p, q ;
FILE *fin ;
fin = fopen( argv[1], "r" ) ;
A = ( int ** ) malloc( sizeof( int * ) * 8 ) ;
for ( i = 0 ; i < 8 ; i++ )
A[i] = ( int * ) malloc( sizeof( int * ) * 8 ) ;
for ( p = 0 ; p < 8 ; p++ )
for ( q = 0 ; q < 8 ; q++ )
fscanf( fin, "%d", &A[p][q] ) ;
printf( " The largest value in the upper triangle is %d\n", largestUpper ( A, &p, &q ) ) ;
printf( " It is located in row %d, column %d\n", p, q ) ;
fclose( fin ) ;
return 0 ;
}
int largestUpper( int **A, int *p, int *q ) {
int i, j, maxsofar = 0, count = 1 ;
for ( i = 0 ; i < 8 ; i++ ) {
for ( j = count ; j < 8 ; j++ ) {
if ( A[i][j] > maxsofar ) {
maxsofar = A[i][j] ;
*p = i ;
*q = j ;
}
}
count++ ;
}
return maxsofar ;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include"header.h"
/* t@CI[vۂNULL`FbN */
void fileOpenCheck(FILE **fp, char *filename, char *mode){
if((*fp = fopen(filename, mode)) == NULL){
printf("%s is failed open\n", filename);
exit(1);
}
return;
}
|
C
|
#include "genericlist.h"
#include <stddef.h>
struct GenericList *reverseGenericList(struct GenericList *curr) {
if (!curr)
return NULL;
struct GenericList *prev = NULL, *next = NULL;
while (curr != NULL) {
next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
|
C
|
#include<stdio.h>
#include<process.h>
#include<conio.h>
#define max 6
int queue_arr[max];
int rear=-1;
int front=-1;
void main()
{
int choice,ch;
clrscr();
while(1)
{
printf("1.Insert\n2.Delete\n3.Display\n4.Quit\n");
printf("Enter your choice");
scanf("%d", &choice);
switch(choice)
{
case 1:
{
int added_item;
if(rear==max-1)
printf("queue overflow");
else
{
if(front==-1)
front=0;
printf("Enter the number to insert into queue\n");
scanf("%d", &added_item);
rear=rear+1;
queue_arr[rear]=added_item;
}
}
clrscr();
break;
case 2:
{
if(front==-1||front>rear)
{
printf("queue underflow");
return;
}
else
{
printf("\n Element deleted from queue is %d",queue_arr[front]);
front=front+1;
}
}
clrscr();
break;
case 3:
{
int i;
if(front==-1)
printf("\n queue is empty");
else
{
printf("\n queue is");
for(i=front;i<=rear;i++)
printf("\t%d",queue_arr[i]);
}
getch();
}
break;
case 4:
{
exit(0);
}
break;
}
clrscr();
}
}
|
C
|
#include "dsm.h"
int permissions[NPAGES];
int set_permissions(void *addr, size_t len, int prot)
{
int dsm_page_num;
dsm_page_num = get_pagenum(addr);
if (dsm_page_num < 0 || dsm_page_num > NPAGES - 1) {
fprintf(stderr, "Error: out of dsm range");
return -1;
}
permissions[dsm_page_num] = prot;
return mprotect(addr, len, prot);
}
int
get_pagenum(void *addr)
{
unsigned long a = (unsigned long) addr;
return (a - DSM_AREA_START) / PGSIZE;
}
void *
get_pageaddr(int pagenum)
{
return (void *) (pagenum * PGSIZE + (unsigned long) DSM_AREA_START);
}
void *
page_align(void *addr)
{
unsigned long page = (unsigned long) addr;
page %= PGSIZE;
return (void *) ((unsigned long) addr - page);
}
|
C
|
#ifndef REDUCE
#define REDUCE
bool equal_private_and_local(void *key1, unsigned size1, __local void *key2, unsigned size2)
{
/* bool flag1 = true, flag2 = true;
if(size1!=size2)
flag1 = false;
char *k1 = (char *)key1;
__local char *k2 = (__local char *)key2;
for(int i = 0; i< size1; i++)
{
if(k1[i]!=k2[i])
flag2 = false;
}
//printf("equal 2...\n");
return flag1 & flag2;*/
bool flag = ( *(int *)key1 == *(__local int *)key2 );
return flag;
}
bool equal_private_and_global(void *key1, unsigned size1, __global void *key2, unsigned size2)
{
bool flag1 = true, flag2 = true;
if(size1!=size2)
flag1 = false;
char *k1 = (char *)key1;
__global char *k2 = (__global char *)key2;
for(int i = 0; i< size1; i++)
{
if(k1[i]!=k2[i])
flag2 = false;
}
//printf("equal 2...\n");
return flag1 & flag2;
}
bool equal_private_and_cpu(void *key1, unsigned size1, __global void *key2, unsigned size2)
{
bool flag1 = true, flag2 = true;
if(size1!=size2)
flag1 = false;
char *k1 = (char *)key1;
__global char *k2 = (__global char *)key2;
for(int i = 0; i< size1; i++)
{
if(k1[i]!=k2[i])
flag2 = false;
}
//printf("equal 2...\n");
return flag1 & flag2;
}
equal_global_and_local(__global void *key1, unsigned size1, __local void *key2, unsigned size2)
{
if(size1!=size2)
return false;
__global char *k1 = (__global char *)key1;
__local char *k2 = (__local char *)key2;
for(int i = 0; i< size1; i++)
{
if(k1[i]!=k2[i])
return false;
}
//printf("equal 2...\n");
return true;
}
bool equal_global_and_global(__global void *key1, unsigned size1, __global void *key2, unsigned size2)
{
if(size1!=size2)
return false;
__global char *k1 = (__global char *)key1;
__global char *k2 = (__global char *)key2;
for(int i = 0; i< size1; i++)
{
if(k1[i]!=k2[i])
return false;
}
//printf("equal 2...\n");
return true;
}
bool equal_local_and_global(__local void *key1, unsigned size1, __global void *key2, unsigned size2)
{
/* bool flag1 = true, flag2 = true;
if(size1!=size2)
flag1 = false;
__local char *k1 = (__local char *)key1;
__global char *k2 = (__global char *)key2;
for(int i = 0; i< size1; i++)
{
if(k1[i]!=k2[i])
flag2 = false;
}
//printf("equal 2...\n");
return flag1 & flag2;
*/
bool flag = ( *(__local int *)key1 == *(__global int *)key2 );
return flag;
}
void reduce_local_to_global(__global void *value1, unsigned short value1_size, __local void *value2, unsigned short value2_size)
{
//printf("reducing .......********\n");
float num_points1 = ((__global float *)value1)[3];
float num_points2 = ((__local float *)value2)[3];
float dist1 = ((__global float *)value1)[4];
float dist2 = ((__local float *)value2)[4];
float total_points = num_points1 + num_points2;
float temp[5];
temp[0] = ((__global float *)value1)[0] + ((__local float *)value2)[0];
temp[1] = ((__global float *)value1)[1] + ((__local float *)value2)[1];
temp[2] = ((__global float *)value1)[2] + ((__local float *)value2)[2];
temp[3] = total_points;
temp[4] = dist1 + dist2;
copyVal_private_to_global(value1, temp, sizeof(float)*5);
}
void reduce_private_to_global(__global void *value1, unsigned short value1_size, void *value2, unsigned short value2_size)
{
unsigned int num_points1 = ((__global float *)value1)[3];
unsigned int num_points2 = ((float *)value2)[3];
float dist1 = ((__global float *)value1)[4];
float dist2 = ((float *)value2)[4];
unsigned int total_points = num_points1 + num_points2;
float temp[5];
temp[0] = ((__global float *)value1)[0] + ((float *)value2)[0];
temp[1] = ((__global float *)value1)[1] + ((float *)value2)[1];
temp[2] = ((__global float *)value1)[2] + ((float *)value2)[2];
temp[3] = total_points;
temp[4] = dist1 + dist2;
copyVal_private_to_global(value1, temp, sizeof(float)*5);
}
void reduce_private_to_local(__local void *value1, unsigned short value1_size, void *value2, unsigned short value2_size)
{
float num_points1 = ((__local float *)value1)[3];
float num_points2 = ((float *)value2)[3];
float dist1 = ((__local float *)value1)[4];
float dist2 = ((float *)value2)[4];
float total_points = num_points1 + num_points2;
float temp[5];
temp[0] = ((__local float *)value1)[0] + ((float *)value2)[0];
temp[1] = ((__local float *)value1)[1] + ((float *)value2)[1];
temp[2] = ((__local float *)value1)[2] + ((float *)value2)[2];
temp[3] = total_points;
temp[4] = dist1 + dist2;
copyVal_private_to_local(value1, temp, sizeof(float)*5);
}
void reduce_private_to_cpu(__global void *value1, unsigned short value1_size, void *value2, unsigned short value2_size)
{
float num_points1 = ((__global float *)value1)[3];
float num_points2 = ((float *)value2)[3];
float dist1 = ((__global float *)value1)[4];
float dist2 = ((float *)value2)[4];
float total_points = num_points1 + num_points2;
float temp[5];
temp[0] = ((__global float *)value1)[0] + ((float *)value2)[0];
temp[1] = ((__global float *)value1)[1] + ((float *)value2)[1];
temp[2] = ((__global float *)value1)[2] + ((float *)value2)[2];
temp[3] = total_points;
temp[4] = dist1 + dist2;
copyVal_private_to_global(value1, temp, sizeof(float)*5);
}
void reduce_global_to_cpu(__global void *value1, unsigned short value1_size, __global void *value2, unsigned short value2_size)
{
unsigned int num_points1 = ((__global float *)value1)[3];
unsigned int num_points2 = ((__global float *)value2)[3];
float dist1 = ((__global float *)value1)[4];
float dist2 = ((__global float *)value2)[4];
unsigned int total_points = num_points1 + num_points2;
float temp[5];
temp[0] = ((__global float *)value1)[0] + ((__global float *)value2)[0];
temp[1] = ((__global float *)value1)[1] + ((__global float *)value2)[1];
temp[2] = ((__global float *)value1)[2] + ((__global float *)value2)[2];
temp[3] = total_points;
temp[4] = dist1 + dist2;
copyVal_private_to_global(value1, temp, sizeof(float)*5);
}
#endif
|
C
|
/*
Copyright (C) 1997-2023 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely.
*/
/* Simple test of the SDL sensor code */
#include "SDL.h"
static const char *GetSensorTypeString(SDL_SensorType type)
{
static char unknown_type[64];
switch (type)
{
case SDL_SENSOR_INVALID:
return "SDL_SENSOR_INVALID";
case SDL_SENSOR_UNKNOWN:
return "SDL_SENSOR_UNKNOWN";
case SDL_SENSOR_ACCEL:
return "SDL_SENSOR_ACCEL";
case SDL_SENSOR_GYRO:
return "SDL_SENSOR_GYRO";
default:
SDL_snprintf(unknown_type, sizeof(unknown_type), "UNKNOWN (%d)", type);
return unknown_type;
}
}
static void HandleSensorEvent(SDL_SensorEvent *event)
{
SDL_Sensor *sensor = SDL_SensorFromInstanceID(event->which);
if (!sensor) {
SDL_Log("Couldn't get sensor for sensor event\n");
return;
}
switch (SDL_SensorGetType(sensor)) {
case SDL_SENSOR_ACCEL:
SDL_Log("Accelerometer update: %.2f, %.2f, %.2f\n", event->data[0], event->data[1], event->data[2]);
break;
case SDL_SENSOR_GYRO:
SDL_Log("Gyro update: %.2f, %.2f, %.2f\n", event->data[0], event->data[1], event->data[2]);
break;
default:
SDL_Log("Sensor update for sensor type %s\n", GetSensorTypeString(SDL_SensorGetType(sensor)));
break;
}
}
int
main(int argc, char **argv)
{
int i;
int num_sensors, num_opened;
/* Load the SDL library */
if (SDL_Init(SDL_INIT_SENSOR) < 0) {
SDL_Log("Couldn't initialize SDL: %s\n", SDL_GetError());
return (1);
}
num_sensors = SDL_NumSensors();
num_opened = 0;
SDL_Log("There are %d sensors available\n", num_sensors);
for (i = 0; i < num_sensors; ++i) {
SDL_Log("Sensor %" SDL_PRIs32 ": %s, type %s, platform type %d\n",
SDL_SensorGetDeviceInstanceID(i),
SDL_SensorGetDeviceName(i),
GetSensorTypeString(SDL_SensorGetDeviceType(i)),
SDL_SensorGetDeviceNonPortableType(i));
if (SDL_SensorGetDeviceType(i) != SDL_SENSOR_UNKNOWN) {
SDL_Sensor *sensor = SDL_SensorOpen(i);
if (sensor == NULL) {
SDL_Log("Couldn't open sensor %" SDL_PRIs32 ": %s\n", SDL_SensorGetDeviceInstanceID(i), SDL_GetError());
} else {
++num_opened;
}
}
}
SDL_Log("Opened %d sensors\n", num_opened);
if (num_opened > 0) {
SDL_bool done = SDL_FALSE;
SDL_Event event;
SDL_CreateWindow("Sensor Test", 0, 0, 0, 0, SDL_WINDOW_FULLSCREEN_DESKTOP);
while (!done) {
/* Update to get the current event state */
SDL_PumpEvents();
/* Process all currently pending events */
while (SDL_PeepEvents(&event, 1, SDL_GETEVENT, SDL_FIRSTEVENT, SDL_LASTEVENT) == 1) {
switch (event.type) {
case SDL_SENSORUPDATE:
HandleSensorEvent(&event.sensor);
break;
case SDL_MOUSEBUTTONUP:
case SDL_KEYUP:
case SDL_QUIT:
done = SDL_TRUE;
break;
default:
break;
}
}
}
}
SDL_Quit();
return (0);
}
|
C
|
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <signal.h>
int main()
{
FILE *pidnya;
pidnya = fopen("/home/becak/modul2/pid_nomor5.txt", "r");
int pid_kill;
fscanf(pidnya, "%d", &pid_kill);
kill(pid_kill, SIGKILL);
fclose(pidnya);
return 0;
}
|
C
|
#include "../includes/ft_printf.h"
void add_sharp(t_printf *list)
{
list->sharp = 1;
}
void add_minus(t_printf *list)
{
char *num;
list->minus = 1;
if (ft_isdigit(list->format[list->i + 1]) || list->format[list->i + 1] == '-' || list->format[list->i + 1] == '+')
{
list->i++;
num = list->format;
num += list->i;
list->width_space = ft_atoi(num);
while (ft_isdigit(list->format[list->i]))
list->i++;
list->i--;
}
}
void add_plus(t_printf *list)
{
list->space = 0;
list->plus = 1;
}
void add_space(t_printf *list)
{
if (list->plus != 1)
list->space = 1;
if (list->format[list->i + 1] == ' ')
{
while (list->format[list->i] == ' ')
list->i++;
list->i--;
}
}
void add_precision(t_printf *list)
{
char *num;
list->precision = 1;
if (list->format[list->i + 1] == '*')
{
list->precision_space = va_arg(list->argc, int);
list->i++;
}
else if (ft_isdigit(list->format[list->i + 1]))
{
list->i++;
num = list->format;
num += list->i;
list->precision_space = ft_atoi(num);
while (ft_isdigit(list->format[list->i]))
list->i++;
list->i--;
}
}
void add_width(t_printf *list)
{
char *num;
list->width = 1;
// if (list->zero == 1)
// return;
if (list->format[list->i] == '*')
{
list->width_space = va_arg(list->argc, int);
if (list->width_space < 0)
{
list->width = 0;
list->minus = 1;
list->minus_space = list->width_space * (-1);
}
}
else if (ft_isdigit(list->format[list->i]))
{
num = list->format;
num += list->i;
list->width_space = ft_atoi(num);
while (ft_isdigit(list->format[list->i]))
list->i++;
list->i--;
}
// printf("(%d)", list->width_space);
}
void add_zero(t_printf *list)
{
char *num;
list->zero = 1;
if (ft_isdigit(list->format[list->i + 1]) || list->format[list->i + 1] == '+')
{
list->i++;
num = list->format;
num += list->i;
list->width_space = ft_atoi(num);
while (ft_isdigit(list->format[list->i]))
list->i++;
list->i--;
}
// printf("(%d)", list->zero_space);
}
|
C
|
/**
* @file network.h Network API
* @ingroup core
*/
#ifndef _OUL_NETWORK_H_
#define _OUL_NETWORK_H_
#ifdef __cplusplus
extern "C" {
#endif
/**************************************************************************/
/** @name Network API */
/**************************************************************************/
/*@{*/
typedef struct _OulNetworkListenData OulNetworkListenData;
typedef void (*OulNetworkListenCallback) (int listenfd, gpointer data);
/**
* Converts a dot-decimal IP address to an array of unsigned
* chars. For example, converts 192.168.0.1 to a 4 byte
* array containing 192, 168, 0 and 1.
*
* @param ip An IP address in dot-decimal notiation.
* @return An array of 4 bytes containing an IP addresses
* equivalent to the given parameter, or NULL if
* the given IP address is invalid. This value
* is statically allocated and should not be
* freed.
*/
const unsigned char *oul_network_ip_atoi(const char *ip);
/**
* Sets the IP address of the local system in preferences. This
* is the IP address that should be used for incoming connections
* (file transfer, direct IM, etc.) and should therefore be
* publicly accessible.
*
* @param ip The local IP address.
*/
void oul_network_set_public_ip(const char *ip);
/**
* Returns the IP address of the local system set in preferences.
*
* This returns the value set via oul_network_set_public_ip().
* You probably want to use oul_network_get_my_ip() instead.
*
* @return The local IP address set in preferences.
*/
const char *oul_network_get_public_ip(void);
/**
* Returns the IP address of the local system.
*
* You probably want to use oul_network_get_my_ip() instead.
*
* @note The returned string is a pointer to a static buffer. If this
* function is called twice, it may be important to make a copy
* of the returned string.
*
* @param fd The fd to use to help figure out the IP, or else -1.
* @return The local IP address.
*/
const char *oul_network_get_local_system_ip(int fd);
/**
* Returns the IP address that should be used anywhere a
* public IP addresses is needed (listening for an incoming
* file transfer, etc).
*
* If the user has manually specified an IP address via
* preferences, then this IP is returned. Otherwise the
* IP address returned by oul_network_get_local_system_ip()
* is returned.
*
* @note The returned string is a pointer to a static buffer. If this
* function is called twice, it may be important to make a copy
* of the returned string.
*
* @param fd The fd to use to help figure out the IP, or -1.
* @return The local IP address to be used.
*/
const char *oul_network_get_my_ip(int fd);
#ifndef OUL_DISABLE_DEPRECATED
/**
* Should calls to oul_network_listen() and oul_network_listen_range()
* map the port externally using NAT-PMP or UPnP?
* The default value is TRUE
*
* @param map_external Should the open port be mapped externally?
* @deprecated In 3.0.0 a boolean will be added to the above functions to
* perform the same function.
* @since 2.3.0
*/
void oul_network_listen_map_external(gboolean map_external);
#endif
/**
* Attempts to open a listening port ONLY on the specified port number.
* You probably want to use oul_network_listen_range() instead of this.
* This function is useful, for example, if you wanted to write a telnet
* server as a Oul plugin, and you HAD to listen on port 23. Why anyone
* would want to do that is beyond me.
*
* This opens a listening port. The caller will want to set up a watcher
* of type OUL_INPUT_READ on the fd returned in cb. It will probably call
* accept in the watcher callback, and then possibly remove the watcher and close
* the listening socket, and add a new watcher on the new socket accept
* returned.
*
* @param port The port number to bind to. Must be greater than 0.
* @param socket_type The type of socket to open for listening.
* This will be either SOCK_STREAM for TCP or SOCK_DGRAM for UDP.
* @param cb The callback to be invoked when the port to listen on is available.
* The file descriptor of the listening socket will be specified in
* this callback, or -1 if no socket could be established.
* @param cb_data extra data to be returned when cb is called
*
* @return A pointer to a data structure that can be used to cancel
* the pending listener, or NULL if unable to obtain a local
* socket to listen on.
*/
OulNetworkListenData *oul_network_listen(unsigned short port,
int socket_type, OulNetworkListenCallback cb, gpointer cb_data);
/**
* Opens a listening port selected from a range of ports. The range of
* ports used is chosen in the following manner:
* If a range is specified in preferences, these values are used.
* If a non-0 values are passed to the function as parameters, these
* values are used.
* Otherwise a port is chosen at random by the operating system.
*
* This opens a listening port. The caller will want to set up a watcher
* of type OUL_INPUT_READ on the fd returned in cb. It will probably call
* accept in the watcher callback, and then possibly remove the watcher and close
* the listening socket, and add a new watcher on the new socket accept
* returned.
*
* @param start The port number to bind to, or 0 to pick a random port.
* Users are allowed to override this arg in prefs.
* @param end The highest possible port in the range of ports to listen on,
* or 0 to pick a random port. Users are allowed to override this
* arg in prefs.
* @param socket_type The type of socket to open for listening.
* This will be either SOCK_STREAM for TCP or SOCK_DGRAM for UDP.
* @param cb The callback to be invoked when the port to listen on is available.
* The file descriptor of the listening socket will be specified in
* this callback, or -1 if no socket could be established.
* @param cb_data extra data to be returned when cb is called
*
* @return A pointer to a data structure that can be used to cancel
* the pending listener, or NULL if unable to obtain a local
* socket to listen on.
*/
OulNetworkListenData *oul_network_listen_range(unsigned short start,
unsigned short end, int socket_type,
OulNetworkListenCallback cb, gpointer cb_data);
/**
* This can be used to cancel any in-progress listener connection
* by passing in the return value from either oul_network_listen()
* or oul_network_listen_range().
*
* @param listen_data This listener attempt will be canceled and
* the struct will be freed.
*/
void oul_network_listen_cancel(OulNetworkListenData *listen_data);
/**
* Gets a port number from a file descriptor.
*
* @param fd The file descriptor. This should be a tcp socket. The current
* implementation probably dies on anything but IPv4. Perhaps this
* possible bug will inspire new and valuable contributors to Oul.
* @return The port number, in host byte order.
*/
unsigned short oul_network_get_port_from_fd(int fd);
/**
* Detects if there is an available Internet connection. Note that this call
* could block for the amount of time specified in inet_detect_timeout, so
* using it in a UI thread may cause uncomfortableness
*
* @return TRUE if the Internet is available
*/
gboolean oul_network_is_available(void);
/**
* Get the handle for the network system
*
* @return the handle to the network system
*/
void *oul_network_get_handle(void);
/**
* Initializes the network subsystem.
*/
void oul_network_init(void);
/**
* Shuts down the network subsystem.
*/
void oul_network_uninit(void);
/*@}*/
#ifdef __cplusplus
}
#endif
#endif /* _OUL_NETWORK_H_ */
|
C
|
#include <stdio.h>
void count_func(int a[20]){
int count_par = 0;
int count_5 = 0;
for (int i = 0; i < 20; i++) {
if(a[i] % 2 == 0)
count_par++;
if (a[i] % 5 == 0)
count_5++;
}
printf("%d, %d\n", count_par, count_5);
}
int main(){
int a[20] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
count_func(a);
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* bsqv2.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: elacombe <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2014/08/18 23:44:33 by elacombe #+# #+# */
/* Updated: 2014/08/19 00:15:56 by elacombe ### ########.fr */
/* */
/* ************************************************************************** */
#include "./includes/ft_header.h"
int is_directory(char *filename)
{
int res;
res = open(filename, O_RDWR);
if (res == -1)
return (1);
return (0);
}
char *ft_read_file(char *filename)
{
int d;
int ret;
char buff[256 + 1];
char *content;
content = NULL;
if (is_directory(filename))
return (NULL);
d = open(filename, O_RDONLY);
if (d == -1)
return (NULL);
ret = 1;
while (ret)
{
ret = read(d, buff, 256);
if (ret <= 0)
break ;
buff[ret] = '\0';
content = ft_strconcat(content, buff);
}
return (content);
}
int main(int argc, char **argv)
{
return (0);
}
|
C
|
/*
* animation.c
*
* Created on: 05.01.2015
* Author: zaphod
*/
#include <avr/io.h>
#include <avr/interrupt.h>
#include <stdlib.h>
#include "util.h"
#include "stripcontrol.h"
#include "animation.h"
#include "color.h"
uint8_t target_r, target_g, target_b = 0;
volatile uint8_t current_r, current_g, current_b = 0;
uint8_t anim_mode = ANIM_MODE_SET;
uint8_t anim_delay = 0;
uint8_t anim_step = 0;
uint8_t anim_level = 0xFF;
void anim_init(void) {
// Timer 1 is used for the animation loop
// fast PWM, 16 bits, TOP in OCR1A
TCCR1A |= (_BV(WGM10) | _BV(WGM11));
TCCR1B |= (_BV(WGM12) | _BV(WGM13));
// prescaler set to clk/1024
TCCR1B |= (_BV(CS12));
// above settings create one count every 0.000064 seconds.
// 200 hz means 1 interrupt every 0.005 seconds
// => an overflow interrupt is required every 78.125 counts
OCR1A = 79;
// enable interrupts on overflow
TIMSK1 |= _BV(TOIE1);
}
void anim_set_delay(uint8_t delay) {
anim_delay = delay;
}
uint8_t anim_get_delay(void) {
return anim_delay;
}
void anim_set_level(uint8_t delay) {
anim_level = delay;
}
uint8_t anim_get_level(void) {
return anim_level;
}
void anim_set_step(uint8_t step) {
if (step != 0) {
anim_step = step;
}
}
uint8_t anim_get_step(void) {
return anim_step;
}
void anim_set_mode(uint8_t mode) {
anim_mode = mode;
if (mode == ANIM_MODE_DISCO) {
// initialize the random number generator with the current value of the animation timer
srand(TCNT1);
}
}
uint8_t anim_get_mode(void) {
return anim_mode;
}
void anim_set_rgb_components(uint8_t red, uint8_t green, uint8_t blue) {
target_r = red;
target_g = green;
target_b = blue;
if (anim_mode == ANIM_MODE_SET) {
current_r = red;
current_g = green;
current_b = blue;
strip_set_rgb_components(red, green, blue);
}
}
void anim_set_rgb_numeric(uint32_t colVal) {
uint8_t r, g, b;
get_components_from_numeric(colVal, &r, &g, &b);
anim_set_rgb_components(r, g, b);
}
uint32_t anim_get_current_rgb_numeric(void) {
return (uint32_t) current_b | ((uint32_t) current_g << 8)
| ((uint32_t) current_r << 16);
}
uint32_t anim_get_target_rgb_numeric(void) {
return (uint32_t) target_b | ((uint32_t) target_g << 8)
| ((uint32_t) target_r << 16);
}
uint8_t fade_to_target(volatile uint8_t* variable, const uint8_t target) {
if (*variable == target)
return 0;
if (*variable < target) {
if (anim_step <= (target - *variable)) {
(*variable) += anim_step;
} else {
*variable = target;
}
} else {
if (anim_step <= (*variable - target)) {
(*variable) -= anim_step;
} else {
*variable = target;
}
}
return 1;
}
uint8_t random_component(uint8_t cap) {
return (rand() / (RAND_MAX / cap + 1)) & 0xFF;
}
/*
* This routine is called with a frequency of 50Hz. It controls the animations for the
* LED strip.
*/
ISR(TIMER1_OVF_vect) {
static uint8_t anim_counter = 0;
if (anim_counter == 0) {
anim_counter = anim_delay;
uint8_t faded = 0;
faded += fade_to_target(¤t_r, target_r);
faded += fade_to_target(¤t_g, target_g);
faded += fade_to_target(¤t_b, target_b);
if (faded) {
strip_set_rgb_components(current_r, current_g, current_b);
} else if (anim_mode == ANIM_MODE_DISCO) {
// no fading occurred, so we have reached the target color and need a new one
uint8_t r,g,b;
hslToRgb(random_component(255), random_component(255), anim_level > 0 ? anim_level : random_component(255), &r, &g ,&b);
anim_set_rgb_components(r,g,b);
}
} else {
anim_counter--;
}
}
|
C
|
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
uint32_t i32;
// 1111 1111 1101 0110 1101 1011
// 0011 1111 1101 0110 1101 1011
uint64_t value = 9766683;
// int64_t value = 4183771;
char s[40];//要转换成的字符数组
itoa(value,s,2);//itoa转为二进制
printf("itoa %s\n",s);//s就是你转换成的数组
unsigned char *p;
// 1101 0110 1101 1011 0000 0000
// 1111 1111 1101 0110 1101 1011 0000 0000
i32 = value << 8;
itoa(i32,s,2);//itoa转为二进制
printf("itoa %s\n",s);//s就是你转换成的数组
memcpy(p, ((uint8_t*)&i32)+1, sizeof(i32)-sizeof(uint8_t));
// memcpy(p,((uint8_t*)&i32),sizeof(i32));
// 1111 1111 1101 0110 1101 1011 0000 0000
// <- p2 -> <- p1 -> <- p0 ->
printf("p0=%lld,p1=%lld,p2=%lld,p3=%lld\n",p[0],p[1],p[2],p[3]);
printf("value = %lld, i32=%lld\n",value,i32);
// memcpy(p, )
i32 = 0;
memcpy(((uint8_t*)&i32)+1, p, sizeof(i32)-sizeof(uint8_t));
// printf("p0=%lld,p1=%lld,p2=%lld,p3=%lld\n",p[0],p[1],p[2],p[3]);
itoa(i32,s,2);//itoa转为二进制
printf("itoa %s\n",s);//s就是你转换成的数组
printf("i32=%lld\n",i32);
i32 = i32 >> 8;
itoa(i32,s,2);//itoa转为二进制
printf("itoa %s\n",s);//s就是你转换成的数组
printf("i32=%lld\n",i32);
// 11111111110101101101101100000000
// 11111111111111111101011011011011
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
void Merge(int A[], int l, int m, int r) {
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m ;
int temp1[n1], temp2[n2];
for (int i = 0; i < n1; i++)
temp1[i] = A[l + i];
for (int j = 0; j < n2; j++)
temp2[j] = A[m + 1 + j];
i = 0;
j = 0;
k = l;
while (i < n1 && j < n2) {
if (temp1[i] <= temp2[j]) {
A[k] = temp1[i];
i++;
}
else {
A[k] = temp2[j];
j++;
}
k++;
}
while (i < n1) {
A[k] = temp1[i];
i++;
k++;
}
while (j < n2) {
A[k] = temp2[j];
j++;
k++;
}
}
void MergeSort(int A[], int l, int r) {
int m = l + (r - l) / 2;
if (l < r) {
MergeSort(A, l, m);
MergeSort(A, m + 1, r);
Merge(A, l, m, r);
}
}
void printFunction(int A[], int n) {
for (int m = 1; m < n + 1; m++)
printf("%d\n", A[m]);
}
int main() {
int n, l, r;
printf("Enter The No. of Elements in Array\n");
scanf("%d", &n); //Take the size of the Array
int A[n];
printf("Enter The Array:\n");
for (int i = 0; i < n; i++)
scanf("%d", &A[i]); //Input the Array
l = 0, r = n;
MergeSort(A, l, r);//Calling the Merge Sort Function
printf("The Sorted Array is:\n");
printFunction(A, n);
}
|
C
|
#include "levels.h"
#include "../herdem.h"
#include "../jaunty/jaunty.h"
void set_up_inter_level(void (*clean_up_function)())
{
int map_w = 1, map_h = 1, tw = WIN_W, th = WIN_H;
if(!(herdem_engine->parent.map = new_jty_map(
map_w, map_h, tw, th,
"images/scenes/level_intro.png",
"a",
"a",
"a"))) {
fprintf(stderr, "Error loading map\n");
exit(1);
}
jty_engine->is_level_finished = is_inter_level_finished;
jty_engine->clean_up_level = clean_up_function;
}
void clean_up_inter_level(void (*next_level_function)())
{
free_jty_map(jty_engine->map);
jty_engine->map = NULL;
jty_engine->set_up_level = next_level_function;
}
void set_up_inter_level_one()
{
set_up_inter_level(clean_up_inter_level_one);
}
void set_up_inter_level_two()
{
set_up_inter_level(clean_up_inter_level_two);
}
void set_up_inter_level_three()
{
set_up_inter_level(clean_up_inter_level_three);
}
void set_up_inter_level_four()
{
set_up_inter_level(clean_up_inter_level_four);
}
void set_up_inter_level_five()
{
set_up_inter_level(clean_up_inter_level_five);
}
void set_up_inter_level_six()
{
set_up_inter_level(clean_up_inter_level_six);
}
bool is_inter_level_finished()
{
SDL_Event selection;
if(SDL_PeepEvents(&selection, 1,
SDL_GETEVENT, SDL_EVENTMASK(SDL_KEYDOWN))){
return true;
}
return false;
}
void clean_up_inter_level_one()
{
clean_up_inter_level(set_up_level_two);
}
void clean_up_inter_level_two()
{
clean_up_inter_level(set_up_level_three);
}
void clean_up_inter_level_three()
{
clean_up_inter_level(set_up_level_four);
}
void clean_up_inter_level_four()
{
clean_up_inter_level(set_up_level_five);
}
void clean_up_inter_level_five()
{
clean_up_inter_level(set_up_level_six);
}
void clean_up_inter_level_six()
{
clean_up_inter_level(set_up_level_seven);
}
|
C
|
#include<stdio.h>
struct dist
{
int f;
int in;
}c,d,sumd;
int main()
{
scanf("%d",&c.f);
scanf("%d",&c.in);
scanf("%d",&d.f);
scanf("%d",&d.in);
sumd.f=c.f+d.f;
sumd.in=c.in+d.in;
if(sumd.in>=12.0)
{
sumd.in=sumd.in-12.0;
++sumd.f;
}
printf("Sum of distances = %d feet %d inches\n",sumd.f,sumd.in);
return 0;
}
|
C
|
//=============================================================================
//
// File: FrMath.h
//
// Header file for FrMath.c. Fractional Math.
//
// NOTES: 1) Named functions all start with Fr (Fract) or Fl (Float)
// followed by give <s,d> for the sizes of arguments and then
// the return values, using:
// i - integer scale factor (2^m) argument
// s - 16 bit short Qmdn
// w - 32 bit word (MCU32) Qmdn
// d - 64 bit double word Qmdn
//
// and then followed by function name (capitalized)
//
// 2) Conversion functions in FrConvert library.
//
// 3) Q format is designated by Qmdn, where m+n includes the sign bit of the
// 2's Complement integer and n is the number of 2'sC
// fractional bits.
// --> Short form Qn designates a Qmdn number with an known
// numerical bit length
//
//=============================================================================
#ifndef _FRMATH_H_
#define _FRMATH_H_
#include "FrConvert.h"
/* log10(2) scaled to Q5.11 format */
#define LOG102Q5D11 Fl2FxPnt16(0.301029996,11)
#define NINETYQ10D6 FlFxPnt16(90,6) /* Ninety degrees scaled to Q10d6 */
#define ONEEIGHTYQ10D6 FlFxPnt16(180,6) /* 180 degrees scaled to Q10d6 */
#define TWOSEVENTYQ10D6 Fl2FxPnt16(270,6) /* 270 degrees scaled to Q10d6 */
#define THREESIXTYQ10D6 Fl2FxPnt16(360,6) /* 360 degrees scaled to Q10d6 */
#define NINETYQ10D22 Fl2FxPnt32(90,22) /* Ninety degrees scaled to Q10d22*/
#define ONEEIGHTYQ10D22 Fl2FxPnt32(180,22) /* 180 degrees scaled to Q10d22 */
#define TWOSEVENTYQ10D22 Fl2FxPnt32(270,22) /* 270 degrees scaled to Q10d22 */
#define THREESIXTYQ10D22 Fl2FxPnt32(360,22) /* 360 degrees scaled to Q10d22 */
/* find the maximum of two numbers */
#define FrMax(a,b) ((a)>(b)?(a):(b))
/* find the minimum of two numbers */
#define FrMin(a,b) ((a)<(b)?(a):(b))
#ifdef __cplusplus
extern "C" {
#endif
//==============================================================================
//
// FrwsSqrt()
//
// Description:
// This routine takes a 32-bit number and returns a 16-bit result. The
// core algorithm is a 16-bit algorithm.
//
// The algorithm used in this function was created to take the square
// root of numbers 0.5 and 1.0. For numbers outside this range, they are
// scaled to that range and then square root rescaled at the end.
//
// The algorithm used is: sqrt(x) = 0.2075806 + 1.454895x - 1.34491x^2
// + 1.106812x^3 - 0.536499x^4 + 0.1121216x^5. The coefficients have
// been scaled by 1/2 to couch them in Fract16 (Q15) format. The result
// is then scaled up by 2.
//
// Magnitude scaling for the square root takes the following route:
// x is the number to find the square root of and y is the
// scaled value. Their relationship is: y = (2^n)*x, so
// sqrt(y) = sqrt(2^n)*sqrt(x)
// = 2^(n/2)*sqrt(x) for n even
// = sqrt(2)*(2^(n-1)/2)*sqrt(x) for n odd
//
// Representation scaling is also necessary & follows the pattern
// shown:
// IN OUT
// xQm.n [sqrt(x)/sqrt(2)][Q(m/2)+1].[16-(m/2)-1], for m even
// xQm.n sqrt(x)[Q(m+1)/2].[16 - (m+1)/2], for m odd
//
// xQ1d15 sqrt(x) in Q1d15, m is odd
// xQ2d14 [sqrt(x)/sqrt(2)] in Q2d14, m is even
// xQ3d13 sqrt(x) in Q2d14, m is odd
// xQ4d12 [sqrt(x)/sqrt(2)] in Q3d13, m even
//
// The user must fix the value of sqrt(x) for even values of m.
// For example for a Q2d14,
// use frsssMult(f2FxPnt16(1.414213562,14),sqrtQ1d15)
// to get the appropriately scaled representation described.
//
// Arguments:
// Fract32 xQ1d31
// -- The input value for which the square root is desired:
// Range: [0, 1).
//
// Return Value:
// Fract16 -- The square root of xQ1d31 in Q1d15 (possibly scaled)
//
//==============================================================================
Fract16 FrwsSqrt(Fract32);
//==============================================================================
//
// FrssLog10()
//
// Description:
// The following code calculates the log base 10. The log base 10 of
// any number x between 1 and 2 can be approximated using the following
// polynomial: 2*log10(x) = 0.8678284(x-1) - 0.42555677(x-1)^2 +
// 0.2481384(x-1)^3 - 0.1155701(x-1)^4 + 0.272522(x-1)^5,
//
// therefore:
// log10(x) = 0.4339142(x-1) - 0.21278385(x-1)^2 + 0.1240692(x-1)^3 -
// 0.05778505(x-1)^4 + 0.0136261(x-1)^5.
//
// To compute the log for numbers less than 1 or greater than 2, the
// input can be scaled to fit the range 1 to 2 and then rescaled to give
// the proper result.
//
// Arguments:
// FxPnt16 xQ1d15 -- The input value to find the log base 10 of.
// int16_t m -- The scale of x, i.e., if x is scaled Q10d6, m = 10
// suggest 2.14(m=2) format for x<1 and 11.5(m=11) for 2<=x<1023
//
// Return Value:
// FxPnt16 log10(xQmd<16-m>) in Q5d11
//
//==============================================================================
Fract16 FrsisLog10(FxPnt16, int16_t);
//==============================================================================
//
// FrwsLog10()
//
// Description:
// This routine takes a 32-bit number and returns a 16-bit result. The
// core algorithm is a 16-bit algorithm.
//
// The following code calculates the log base 10. The log base 10 of
// any number x between 1 and 2 can be approximated using the following
// polynomial: 2*log10(x) = 0.8678284(x-1) - 0.42555677(x-1)^2 +
// 0.2481384(x-1)^3 - 0.1155701(x-1)^4 + 0.272522(x-1)^5,
//
// therefore:
// log10(x) = 0.4339142(x-1) - 0.21278385(x-1)^2 + 0.1240692(x-1)^3 -
// 0.05778505(x-1)^4 + 0.0136261(x-1)^5.
//
// To compute the log for numbers less than 1 or greater than 2, the
// input can be scaled to fit the range 1 to 2 and then rescaled to give
// the proper result.
//
// Arguments:
// FxPnt32 xQ1d31 -- The input value to find the log base 10 of.
// int16_t m -- The scale of x, i.e., if x is scaled Q10d6, m = 10
// suggest 1.31(m=1) or 2:30 (m = 2) format for x<1 and
// 11.21(m=11) for 2<=x<1023.
//
// Return Value:
// FxPnt16 Log10(Qmd<32-m>) in Q5d11
//
//==============================================================================
Fract16 FrwsLog10(FxPnt32, int16_t);
//==============================================================================
//
// FrssCos()
//
// Description:
// This function returns the cosine of an angle.
// It uses the trig identity cos(theta) = sin(theta+90). So after
// adding 90 degrees to the value of the angle, it calls the sin
// function. Any angle between -360 and 360 can be entered. This
// value is expected to be scaled to a 10.6 format; the value of the
// cos is returned as a 1.15.
//
// Arguments:
// FxPnt16 angleQ10d6 -- The angle in degrees for which the cosine is to be
// computed.
//
// Return Value:
// Fract16. cos(Q10d6 degrees) in Q1d15
//
//==============================================================================
Fract16 FrssCos(FxPnt16);
//==============================================================================
//
// FrssSin()
//
// Description:
// This function approximates the sine of an angle using the
// following algorithm: sin(x) = 3.140625x + 0.02026367x^2 -
// 5.325196x^3 + 0.5446778x^4 + 1.800293x^5. The approximation
// is accurate for any value of x from 0 degrees to 90 degrees.
// Because sin(-x) = - sin(x) and sin(x) = sin(180 - x), the sine
// of any angle can be inferred from an angle in the first quadrant.
// Therefore, any angle > 90 is converted to an angle between 0 & 90.
// The coefficients of the algorithm have been scaled by 1/8 to
// fit a Q1d15 format. So the result is scaled up by 8 to obtain
// the proper magnitudes. The algorithm expects the angle to be in
// degrees and represented in 10.6 format. The computed sine value
// is returned in 1.15 format.
//
// Arguments:
// FxPnt16 angleQ10d6 -- The angle in degrees for which the sine is computed
//
// Return Value:
// Fract16. sin(Q10d6 degrees) in Q1d15
//
//==============================================================================
Fract16 FrssSin(FxPnt16);
//==============================================================================
//
// FrwsCos()
//
// Description:
// This function returns the cosine of an angle.
// It uses the trig identity cos(theta) = sin(theta+90). So after
// adding 90 degrees to the value of the angle, it calls the sin
// function. Any angle between -360 and 360 can be entered. This
// value is expected to be scaled to a 10.22 format; the value of the
// cos is returned as a 1.15.
//
// Arguments:
// FxPnt16 angleQ10d22
// -- The angle in degrees for which the cosine is to be computed.
//
// Return Value:
// Fract16. cos(10d22) in Q1d15
//
//==============================================================================
Fract16 FrwsCos(FxPnt32);
//==============================================================================
//
// FrwsSin()
//
// Description:
// This function takes a 32 bit angle and returns a 16 bit sine.
// It is derived from frssSin which uses a 16 bit core algorithm.
//
// This function approximates the sine of an angle using the
// following algorithm: sin(x) = 3.140625x + 0.02026367x^2 -
// 5.325196x^3 + 0.5446778x^4 + 1.800293x^5. The approximation
// is accurate for any value of x from 0 degrees to 90 degrees.
// Because sin(-x) = - sin(x) and sin(x) = sin(180 - x), the sine
// of any angle can be inferred from an angle in the first quadrant.
// Therefore, any angle > 90 is converted to an angle between 0 & 90.
// The coefficients of the algorithm have been scaled by 1/8 to
// fit a Q1d15 format. So the result is scaled up by 8 to obtain
// the proper magnitudes. The algorithm expects the angle to be in
// degrees and represented in 10.22 format. The computed sine value
// is returned in 1.15 format.
//
// Arguments:
// FxPnt32 angleQ10d22 -- The angle in degrees for which the sine is computed
//
// Return Value:
//
// Fract16. sin(Q10d22) in Q1d15
//
//==============================================================================
Fract16 FrwsSin(FxPnt32);
//==============================================================================
//
// FrssSqrt()
//
// Description:
// The algorithm used in this function was created to take the square
// root of numbers between 0.5 and 1.0. For numbers outside this range,
// they may be scaled to that range and then the square root rescaled at the
// end. The program will take any size number, in proper representation,
// and find the square root. The final scaling, if any is needed, is left
// to the user. This scaling is explained below.
//
// The algorithm used is: sqrt(x) = 0.2075806 + 1.454895x - 1.34491x^2
// + 1.106812x^3 - 0.536499x^4 + 0.1121216x^5. It was designed to find the
// square root of numbers between 0.5 and 1. However, the square root of
// any number can be found with proper scaling. In this program, the
// coefficients are scaled by 1/2 to represent them in Fract16 format.
// The final result, i.e. the square root, is then scaled up by 2.
//
// Magnitude scaling for the square root takes the following route:
// let x be the number to find the square root of and y be the
// scaled value. Their relationship is: y = (2^n)*x, so
// sqrt(y) = sqrt(2^n)*sqrt(x)
// = 2^(n/2)*sqrt(x) for n even
// = sqrt(2)*(2^(n-1)/2)*sqrt(x) for n odd
//
// However, the sqrt(x) is the value sought and may be found by proper
// algebraic manipulation.
//
// Representation scaling is also necessary & follows the pattern
// shown next:
// IN Representation OUT Representation (sqrt represented in this format)
// xQm.n [sqrt(x)/sqrt(2)][Q(m/2)+1].[16-(m/2)-1], for m even
// xQm.n sqrt(x)[Q(m+1)/2].[16 - (m+1)/2], for m odd
// Examples:
// xQ1d15 sqrt(x)Q1d15, m is odd
// xQ2d14 [sqrt(x)/sqrt(2)]Q2d14, m is even
// xQ3d13 sqrt(x)Q2d14, m is odd
// xQ4d12 [sqrt(x)/sqrt(2)]Q3d13, m even
//
// The user must fix the value of sqrt(x) for even values of m.
// For even values, use frsssMult(f2FxPnt16(1.414213562,14),sqrtQ1d15)
// to get the appropriately scaled representation described.
//
// Arguments:
// Fract16 xQ1d15
// -- The input value for which the square root is desired:
// Range: (0, 1).
//
// Return Value:
// Fract16 -- sqrtQ1d15: The square root of xQ1d15 (when input not scaled)
//
//==============================================================================
Fract16 FrssSqrt(Fract16);
//==============================================================================
//
// FrwssRand()
//
// Description:
// Generates a frame of 16-bit random numbers using the linear congruential
// method. The linear congruential method has the form:
// x(n) = M*x(n-1) + K
// where
// x(n) = Random number at sample n,
// M = Constant multiplier,
// K = Constant increment.
// The intent is that this routine is called using the last random value
// generated in the previous frame as the seed for the current frame. In
// this way, successive calls of the routine will produce 65,536 random
// numbers.
//
// Note that it is required that modulo-2^32 arithmetic be performed:
// operations should overflow and wrap. Future implementers should not "fix"
// the math by allowing guard bits, larger intermediate values, etc.
//
// Reference: "Random Number Generation on a TMS320C5x" Texas Instruments
// Application Brief: SPRA239, July, 1994.
//
// Arguments:
// int32_t *lastRand
// [in/out] This must be a persistent memory location. Initially it is
// the last random value generated during the previous call. After this
// routine completes, it is the last random generated in the current
// frame.
//
// int16_t *rand -- Pointer to the random output data.
//
// int16_t length -- size of output data frame
//
// Return Value -- None.
//
//==============================================================================
void FrwssRand(int32_t * prevValue, int16_t * newValue, int16_t frameLength);
//==============================================================================
//
// FrswwMult()
//
// Description:
// Implement 16 bit by 32 bit multiply. A textual pictoral representation of
// the extended precision math is shown below. The 's' and 'u' notation shows
// the processing of signed and unsigned numbers. Since the numbers are signed
// fractional numbers, the sign bit is replicated in the upper two bits of
// the product. Overflow detection is done on the two sign bits before they
// are combined into a single bit.
//
// -B1- -B0- s u 2nd argument is 32 bits
// -A0- s 1st argument is 16 bits
// --------------
// A0B0 A0B0 s=s*u 1st 32-bit product is A0*B0
// A0B1 A0B1 s=s*s 2nd 32-bit product is A0*B1
// --------------
// -S2- -S1- -S0- s=s+s 48-bit result is the sum of products
// -P1- -P0- 32-bit return is the most significant bits of the sum
//
// Arguments:
// Fract16 AQ1d15
// -- 16 bit argument A.
// Fract32 BQ1d31
// -- 2 bit argument B.
//
// Return Value:
// Fract32 - A x B in Q1d31
//
//==============================================================================
Fract32 FrswwMult(Fract16, Fract32);
/******************************************************************************
*
* FrwwwMult()
*
* Description:
* Implements a 32 bit by 32 bit multiply. This is a 32 bit by 32 bit
* multiply with 32 bit result. A textual pictoral representation of
* the extended precision math is shown below. The 's' and 'u' notation shows
* the processing of signed and unsigned numbers. Since the numbers are signed
* fractional numbers, the sign bit is replicated in the upper two bits of
* the product. Overflow detection is done on the two sign bits before they
* are combined into a single bit.
*
* In this implementation, the first product is ignored in the interests of
* speed and at the expense of a slight bit of accuracy. If the result of
* accumulating the first product would have increased bit 32 of the 64-bit
* result, the final product will be in error by 1 lsb.
*
* -B1- -B0- s u 2nd argument is 32 bits
* -A1- -A0- s u 1st argument is 32 bits
* -------------------
* A0B0 A0B0 u=u*u 1st 32-bit product is A0*B0 (ignored)
* A0B1 A0B1 s=u*s 2nd 32-bit product is A0*B1
* A1B0 A1B0 s=s*u 3rd 32-bit product is A1*B0
* A1B1 A1B1 s=s*s 4th 32-bit product is A1*B1
* -------------------
* -S2- -S1- -S0- s=s+s 48-bit result is the sum of products
* -P1- -P0- 32-bit return is the MSbits of the sum
*
* Arguments:
* Fract32 AQ1d31
* -- First multiplicand A.
* Fract32 BQ1d31
* -- Second multiplicand B.
*
* Return Value:
* Fract32 - A x B in Q1d31.
*
******************************************************************************/
Fract32 FrwwwMult(Fract32, Fract32);
//==============================================================================
//
// FrssssExpAvg()
//
// Description:
// Exponential averaging implements a smoothing function based on the
// recursive averaging form:
// avg[i+1] = avg[i] * lamda + new * (1-lamda)
//
// In this implementation, is has been optimized as follows.
// avg[i+1] = (avg[i] - new) * lamda + new
//
// The optimization precludes accurate processing of new numbers that differ
// from the current average by more than unity. If the difference is greater
// than unity or less than negative unity, the difference is saturated.
//
// The effect is akin to a smaller lambda, e.g., the new value will have a
// greater weight than expected. If the smoothing is of data that is entirely
// positive or entirely negative, then the saturation will not be an issue.
//
// Arguments:
// FxPnt16 prevAvg16 (Q15) -- Previous exponential average
// FxPnt16 newMeas16 (Q15) -- New value to be averaged in
// Fract16 lamdaQ1d15 -- exponential averaging constant
//
// Return Value:
// FxPnt16 - newAvg16 (Q15)
//
//==============================================================================
FxPnt16 frssssExpAvg(FxPnt16, FxPnt16, Fract16);
//==============================================================================
//******************************************************************************
// frsisLog()
//
// Description:
// The following code calculates the natural log. The natural log of a number
// can be approximated using the following Taylor's series.
//
// log(x) = (x-1) - 0.5(x-1)^2 + 0.3333333(x-1)^3 - 0.25(x-1)^4 + ........
//
// Arguments:
// Fract16 xQ1d15 -- The input value to find the natural log.
// int16_t polyOrder -- Order of taylor series apprx.
//
// Return Value:
// Fract16 -- log10 value in Q1d15
//
// !!!!! WARNING : This function expects the input in the range [0.5,1) !!!!!!!
// Maximum allowable polynomial value is 10
//==============================================================================
Fract16 FrsisLog(Fract16 xQ1d15, int16_t polyOrder);
//==============================================================================
// FrsisExp()
//
// Description:
// The following code calculates the exponential. The exponential of a number
// can be approximated using the following Taylor's series.
//
// exp(x) = 1 + x + x^2(2!) + x^3/(3!) + x^4/(4!) + ........
//
// Arguments:
// Fract16 xQ1d15 -- The input value to find the exponential.
//
// int16_t polyOrder -- order of taylor series
//
// Return Value:
// Fract16 -- exponential value in Q1d15
//
// !!!!! WARNING : This function expects the input in the range [-1,0) !!!!!!!
// Maximum allowable polynomial value is 10
//==============================================================================
Fract16 FrsisExp(Fract16 xQ1d15, int16_t polyOrder);
//==============================================================================
//
// FrssiCmplxMag()
//
// Description:
// This function calculates the magnitude of the complex vector.
// It accepts the complex data of size N and returns the real
// magnitude vector of size N.
//
// Arguments:
// Fract16 *cmplxData -- Pointer to complex data.
// Fract16 *realMag -- Pointer to real magnitude (result)
// int16_t len -- Array size.
//
// Return Value:
// none
//
// !!!!! WARNING : The real and imaginary part of the complex data should
// be in the same scale.
//==============================================================================
void frssiCmplxMag(Fract16 *cmplxData,
Fract16 *realMag,
int16_t len);
//==============================================================================
//
// frssiDotProd()
//
// Description:
// Performs element-by-element multiplication (dot product) of
// two vectors. Result is stored in the third vector.
//
// Arguments:
// Fract16 *arr1Q1d15 -- Pointer to the first input array
// Fract16 *arr2Q1d15 -- Pointer to the second input array
// Fract16 *resultQ1d15 -- Pointer to the output array (result)
// int16_t len -- Length of arrays
//
// Return Value:
// none
//
//==============================================================================
void frssiDotProd(Fract16 *arr1Q1d15,
Fract16 *arr2Q1d15,
Fract16 *resultQ1d15,
int16_t len);
//==============================================================================
//
// frssiScaleMult()
//
// Description:
// Multiplies a vector by a real value. Result is stored in
// the second vector.
//
// Arguments:
// Fract16 *vector -- Pointer to the first input array
// Fract16 scale -- scaler to multiply by
// Fract16 *result -- Pointer to the output array (result)
// int16_t len -- Length of arrays
//
// Return Value:
// none
//
//==============================================================================
void frssiScaleMult(Fract16 *vector,
Fract16 scale,
Fract16 *result,
int16_t len);
#ifdef __cplusplus
}
#endif
#endif /* _FRMATH_H_ */
|
C
|
//Header file for an implementation of a basic list ADT usuing the linked list data structure
//Keaton Armstrong
//STRUCTS
struct node{
int data;
struct node* next;
};
typedef struct node node_t;
struct list{
node_t* head;
node_t* tail;
};
typedef struct list Linkedlist_t;
//FUNCTIONS
node_t* nodeCreate (int value);
Linkedlist_t llCreate();
void llDelete(Linkedlist_t *list);
void llPrint(Linkedlist_t list);
bool llisEmpty(Linkedlist_t list);
int listLength(Linkedlist_t list);
void llAppend(Linkedlist_t* list, int value);
void llPush(Linkedlist_t *list, int value);
int llPop(Linkedlist_t *list);
node_t* llFind(Linkedlist_t list, int value);
void llLinkAfter(Linkedlist_t* list, node_t* cur, node_t* newNode);
node_t* llUnlinkAfter(Linkedlist_t* list, node_t* cur);
void llInsert(Linkedlist_t* list, node_t* cur, int data);
void llRemove(Linkedlist_t* list, node_t* cur);
node_t* findPrevNode(Linkedlist_t* list, node_t* cur);
|
C
|
# include <stdio.h>
# include <stdlib.h>
struct node
{
int data;
struct node* next;
};
void add(struct node* h,int a)
{
struct node* new=(struct node*)malloc(sizeof(struct node));
new->next=NULL;
struct node* temp;
temp=h;
while(temp->next!=NULL)
{
temp=temp->next;
}
temp->next=new;
new->data=a;
}
void print(struct node* h)
{
struct node* temp;
temp=h->next;
while(temp!=NULL)
{
printf("%d ",temp->data);
temp=temp->next;
}
printf("\n");
}
void removeDuplicates(struct node* h)
{
struct node* temp;
temp=h->next;
int v=temp->data;
while(temp->next!=NULL)
{
if(v==(temp->next)->data)
{
struct node* t=temp->next;
temp->next=(temp->next)->next;
free(t);
if(temp->next!=NULL)
{
if(v==(temp->next)->data);
else
{
temp=temp->next;
v=temp->data;
}
}
else break;
}
else
{
v=(temp->next)->data;
temp=temp->next;
}
}
}
void moveNode(struct node** a,struct node** b)
{
struct node* temp;
temp=*b;
if(temp->next!=NULL)
{
*b=temp->next;
}
temp->next=*a;
*a=temp;
}
void main()
{
struct node* h=(struct node*)malloc(sizeof(struct node));
h->next=NULL;
struct node* h1=(struct node*)malloc(sizeof(struct node));
h1->next=NULL;
add(h,1);
add(h,2);
add(h,3);
print(h);
add(h1,1);
add(h1,2);
add(h1,3);
print(h1);
printf("%d\n",h->data);
printf("%d\n",(h->next)->data);
//moveNode(&h,&h1);
//removeDuplicates(h);
//print(h);
//print(h1);
}
|
C
|
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <stdio.h>
#include "search.h"
int main(int argc, char *argv[]){
int min = atoi((argv[1]));
int max = atoi((argv[2]));
int rep = atoi((argv[3]));
int do_array=0,
do_barray=0,
do_list=0,
do_tree=0;
if(argv[4]!=NULL){
char *format=argv[4];
if(strchr(format,'a')){
do_array=1;
}
if(strchr(format,'b')){
do_barray=1;
}
if(strchr(format,'l')){
do_list=1;
}
if(strchr(format,'t')){
do_tree=1;
}
}
else{
do_array=1;
do_barray=1;
do_list=1,
do_tree=1;
}
clock_t begin, end;
double cpu_time;
printf("LENGTH");
printf("SEARCHES \t");
printf("array \t");
printf("list \t");
printf("binary \t");
printf("tree \t");
//loop that iterates from min size to max size
for(int size=min;size<=max;size++){
//loop to generate the 2^size
int power=2;
for(int i=0;i<size;i++){
power=power*2;
}
int length=power;
if(do_array){
int *arr= make_evens_array(length);
//begin clock before searches
begin=clock();
//loop to iterate through the reps
for(int j=0;j<rep;j++){
//loop to iterate through the search querys
for(int k=0;k<length*2;k++){
linear_array_search(arr, length, k);
}
}
//after reps loop, end clock and print out the
end=clock();
cpu_time = ((double) (end - begin)) / CLOCKS_PER_SEC; //calculating cpu time
printf("%5e",cpu_time);
free(arr); //freeing the memory
}
if(do_barray){
int *barr= make_evens_array(length);
//begin clock before searches
begin=clock();
//loop to iterate through the reps
for(int j=0;j<rep;j++){
//loop to iterate through the search querys
for(int k=0;k<length*2;k++){
linear_array_search(barr, length, k);
}
}
//after reps loop, end clock and print out the
end=clock();
cpu_time = ((double) (end - begin)) / CLOCKS_PER_SEC; //calculating cpu time
printf("%5e",cpu_time);
free(barr); //freeing the memory
}
if(do_tree){
bst_t *tree= make_evens_tree(length);
//begin clock before searches
begin=clock();
//loop to iterate through the reps
for(int j=0;j<rep;j++){
//loop to iterate through the search querys
for(int k=0;k<length*2;k++){
binary_tree_search(tree, length, k);
}
}
//after reps loop, end clock and print out the
end=clock();
cpu_time = ((double) (end - begin)) / CLOCKS_PER_SEC; //calculating cpu time
printf("%5e",cpu_time);
bst_free(tree); //freeing the memory
}
if(do_list){
list_t *list= make_evens_list(length);
//begin clock before searches
begin=clock();
//loop to iterate through the reps
for(int j=0;j<rep;j++){
//loop to iterate through the search querys
for(int k=0;k<length*2;k++){
linkedlist_search(list, length, k);
}
}
//after reps loop, end clock and print out the
end=clock();
cpu_time = ((double) (end - begin)) / CLOCKS_PER_SEC; //calculating cpu time
printf("%5e",cpu_time);
list_free(list); //freeing the memoryd
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////
|
C
|
#include <unistd.h>
void my_putchar(char c)
{
write (1, &c, 1);
}
int my_putstr(char const *str)
{
for (int i = 0; str[i] != 0; i++)
my_putchar(str[i]);
return (0);
}
int my_strlen(char const *str)
{
int i = 0;
for (; str[i] != 0; i++);
return (i);
}
void my_swap(char *a, char *b)
{
char c;
c = *a;
*a = *b;
*b = c;
}
char *my_evil_str(char *str)
{
int size = my_strlen(str) - 1;
for (int j = 0; j < size; j++, size--) {
my_swap(&str[j], &str[size]);
}
return (str);
}
int main(void)
{
char str[8] = "abcdefgh";
my_putstr(my_evil_str(str));
return (0);
}
|
C
|
#include <stdio.h>
#include<string.h>
void main()
{
char g[10];
int a,i,j,flag=0;
printf("enter any string");
scanf("%s",g);
a=strlen(g);
for(i=0,j=a-1;i<=a/2;i++,j--)
{
if(g[i]!=g[j])
{
printf("not a palindrome");
flag=1;
break;
}
}
if(flag==0)
{
printf("palindrome");
}
}
|
C
|
#include <unistd.h>
void ft_putchar(char c)
{
write(1, &c, 1);
}
void ft_putstr(char *str)
{
int index;
index = 0;
while(str[index] !='\0')
{
ft_putchar(str[index]);
index++;
}
}
void ft_print_comb(void)
{
int indexA;
int indexB;
int indexC;
char *nbr;
nbr = "0123456789";
indexA = 0;
indexB = 1;
indexC = 2;
while(indexA != 7 || indexB != 8 || indexC != 9)
{
if(indexC == 10)
{
indexB++;
indexC = indexB + 1;
}
if(indexB == 9)
{
indexA++;
indexB = indexA + 1;
indexC = indexB + 1;
}
else
{
ft_putchar(nbr[indexA]);
ft_putchar(nbr[indexB]);
ft_putchar(nbr[indexC]);
ft_putstr(", ");
indexC++;
}
}
ft_putstr("789");
}
|
C
|
#include <SDL2/SDL.h>
#include <SDL2/SDL_timer.h>
#include <stdio.h>
typedef int bool32;
typedef struct Vector2 {
float x, y;
} Vector2;
typedef struct Building {
Vector2 origin;
Vector2 position;
int width;
int height;
bool32 active;
} Building;
typedef struct Player {
Vector2 position;
int speed;
float vely;
} Player;
static int screenWidth = 1024;
static int screenHeight = 576;
static bool32 Running = 0;
static bool32 left = 0;
static bool32 right = 0;
static int OffsetX = -30;
static float gravity = 9.8;
int main(void)
{
SDL_Window *window = NULL;
SDL_Renderer *renderer = NULL;
SDL_Surface *surface = NULL;
SDL_Texture *texture = NULL;
// struct to hold the position and size of the sprite
SDL_Rect dest;
dest.w = 25;
dest.h = 50;
if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER) != 0)
{
printf("Error initializing SDL: %s\n", SDL_GetError());
return 1;
}
Uint32 window_flags = SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE;
window = SDL_CreateWindow(
"We're Going Dancing",
SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED,
screenWidth,
screenHeight,
window_flags);
if (!window)
{
printf("Could not create window: %s\n", SDL_GetError());
SDL_Quit();
return 1;
}
Uint32 render_flags = SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC;
renderer = SDL_CreateRenderer(window, -1, render_flags);
if (!renderer)
{
printf("error creating renderer: %s\n", SDL_GetError());
SDL_DestroyWindow(window);
SDL_Quit();
return 1;
}
// Initialization
Player shaw;
shaw.position = (Vector2){ screenWidth/2, screenHeight/2 };
shaw.speed = 5;
shaw.vely = 0;
Running = 1;
while (Running != 0) {
SDL_Event event;
while(SDL_PollEvent(&event))
{
switch (event.type)
{
case SDL_QUIT:
Running = 0;
break;
case SDL_WINDOWEVENT:
switch(event.window.event)
{
case SDL_WINDOWEVENT_SIZE_CHANGED:
{
int ClientWidth;
int ClientHeight;
SDL_GetWindowSize(window, &ClientWidth, &ClientHeight);
// TODO(shaw): On window resize, need to take the current buffer and scale it down to a new buffer and blit that to the screen.
// In the future I will probably want to have some sort of breakpoints of fixed resolution and fill the rest with a black frame
// or something like that. BlitScaled or perhaps RenderSetScale might be what I need here
// int SDL_BlitScaled(
// SDL_Surface* src,
// const SDL_Rect* srcrect,
// SDL_Surface* dst,
// SDL_Rect* dstrect);
// int SDL_RenderSetScale(
// SDL_Renderer* renderer,
// float scaleX,
// float scaleY)
} break;
} break;
case SDL_KEYDOWN:
switch( event.key.keysym.scancode )
{
case SDL_SCANCODE_A:
case SDL_SCANCODE_LEFT:
left = 1;
break;
case SDL_SCANCODE_D:
case SDL_SCANCODE_RIGHT:
right = 1;
break;
}
break;
case SDL_KEYUP:
switch( event.key.keysym.scancode )
{
case SDL_SCANCODE_A:
case SDL_SCANCODE_LEFT:
left = 0;
break;
case SDL_SCANCODE_D:
case SDL_SCANCODE_RIGHT:
right = 0;
break;
}
break;
}
}
// Update
if (left && !right) shaw.position.x -= shaw.speed;
if (right && !left) shaw.position.x += shaw.speed;
dest.x = (int)shaw.position.x;
dest.y = (int)shaw.position.y;
// Draw
SDL_SetRenderDrawColor(renderer, 0x00, 0x00, 0x00, 0x00);
SDL_RenderClear(renderer);
SDL_SetRenderDrawColor(renderer, 255, 0, 0, 255);
SDL_RenderFillRect(renderer, &dest);
// SDL_RenderCopy(renderer, texture, NULL, NULL);
// update the screen with any rendering performed since the previous call.
SDL_RenderPresent(renderer);
}
SDL_DestroyTexture(texture);
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}
|
C
|
/*!
* @file image_deal.c
* @brief ڵõĺ
* @details
* @author lvؼfox
* @version v1.0
* @date 2019-2-26
* @to do
*
*/
#include "include.h"
#include "image_deal.h"
#define Height ROW
#define Wide COL
ImageDeal_ForLight ImageDeal_Camera1;
ImageDeal_ForLight ImageDeal_Camera2;
void ImageDealStructInit(ImageDeal_ForLight * ImageDeal)
{
ImageDeal->Num_MidLine = 0;
ImageDeal->LastNum_MidLine = 0;
ImageDeal->Num_EffectiveMidLine = 0;
ImageDeal->Temp_Error = 0;
ImageDeal->Now_Error = 0;
ImageDeal->Mid_MidLine = 0;
ImageDeal->Sum_WhiteBlock = 0;
ImageDeal->LastSum_WhiteBlock = 0;
ImageDeal->Size_SumMid = 0;
ImageDeal->LightStatus = Light_Disappear;
for(int i = 0;i < EndLookLine - StartLookLine; i++)
{
ImageDeal->LeftLine[i] = -1;
ImageDeal->RightLine[i] = -1;
ImageDeal->MidLine[i] = -1;
}
ImageDeal->Count_LightOff = 0;
}
# define BoardWidthThreshold 2
# define JumpThreshold 35
uint8 flag_LookedLeftLine = 0;
uint8 flag_LookedRightLine = 0;
///Ѱ߳ҪѰͼеұ
void LookLine(ImageDeal_ForLight * ImageDeal,uint8 imagebuff[120][188])
{
flag_LookedLeftLine = 0;
flag_LookedRightLine = 0;
for (int i = StartLookLine, LineIndex = 0; i < EndLookLine; i++, LineIndex++)
{
for (int j = 0; j < Wide - BoardWidthThreshold; j++)
{
if ((imagebuff[i][j + BoardWidthThreshold] - imagebuff[i][j]) > JumpThreshold)
{
ImageDeal->LeftLine[LineIndex] = j;
flag_LookedLeftLine = 1;
break;
}
}
if (flag_LookedLeftLine == 1)
{
for (int j = ImageDeal->LeftLine[i]; j < Wide - BoardWidthThreshold; j++)
{
if (imagebuff[i][j] - (imagebuff[i][j + BoardWidthThreshold]) > JumpThreshold)
{
ImageDeal->RightLine[LineIndex] = j;
ImageDeal->ChaLine[LineIndex] = ImageDeal->RightLine[LineIndex] - ImageDeal->LeftLine[LineIndex];
flag_LookedRightLine = 1;
break;
}
}
}
else//ȫ
{
ImageDeal->LeftLine[i] = -1;
ImageDeal->RightLine[i] = -1;
ImageDeal->ChaLine[i] = -1;
}
}
}
# define LightDisappearCountThreshold 10
///µ״̬
void RenewLightStatus(ImageDeal_ForLight * ImageDeal, int MidLineNum)
{
if (ImageDeal->LightStatus == Light_Disappear)
{
if (MidLineNum > 2)
{
ImageDeal->LightStatus = Light_On;
ImageDeal->Count_LightOff = 0;
}
}
else if (ImageDeal->LightStatus == Light_On)
{
if (MidLineNum <= 0)
{
ImageDeal->LightStatus = Light_Off;
}
}
else
{
if (MidLineNum > 0)
{
ImageDeal->LightStatus = Light_On;
ImageDeal->Count_LightOff = 0;
}
else
{
ImageDeal->Count_LightOff++;
if (ImageDeal->Count_LightOff >= LightDisappearCountThreshold)
{
ImageDeal->LightStatus = Light_Disappear;
ImageDeal->Count_LightOff = 0;
}
}
}
}
uint8 flag_FindTopLine = 0;
uint8 flag_FindBottomLine = 0;
///ƫ
void CalError(ImageDeal_ForLight * ImageDeal)
{
ImageDeal->Temp_Error = ImageDeal->Now_Error;
ImageDeal->LastSum_WhiteBlock = ImageDeal->Sum_WhiteBlock;
ImageDeal->LastNum_MidLine = ImageDeal->Num_MidLine;
float MidSum = 0;
int MidLineIndex = 0;
ImageDeal->Sum_WhiteBlock = 0;
ImageDeal->Sum_LineSize = 0;
flag_FindTopLine = 0;
flag_FindBottomLine = 0;
for (int i = 0; i < EndLookLine - StartLookLine; i++)
{
if (ImageDeal->LeftLine[i] >= 0 && ImageDeal->RightLine[i] >= 0)
{
if(flag_FindTopLine)
{
ImageDeal->Sum_LineSize += ImageDeal->ChaLine[i];
}
else
{
ImageDeal->TopLineIndex = i;
flag_FindTopLine = 1;
}
MidLineIndex++;
}
else
{
if(flag_FindTopLine && !flag_FindBottomLine)
{
ImageDeal->BottomLineIndex = i;
flag_FindBottomLine = 1;
}
}
}
ImageDeal->Num_MidLine = MidLineIndex;
ImageDeal->AverageLineSize = ImageDeal->Sum_LineSize / MidLineIndex;
MidLineIndex = 0;
ImageDeal->MidSum = 0;
for (int i = ImageDeal->TopLineIndex; i < ImageDeal->BottomLineIndex; i++)
{
ImageDeal->MidLine[MidLineIndex] = 0.5 * (ImageDeal->LeftLine[i] + ImageDeal->RightLine[i]);
ImageDeal->MidSum += ImageDeal->MidLine[MidLineIndex];
//ImageDeal->Sum_WhiteBlock += (ImageDeal->RightLine[i] - ImageDeal->LeftLine[i]);
MidLineIndex++;
}
ImageDeal->Num_EffectiveMidLine = MidLineIndex;
RenewLightStatus(ImageDeal, ImageDeal->Num_MidLine);
if (ImageDeal->LightStatus == Light_Disappear)
{
ImageDeal->Now_Error = 0;
}
else if (ImageDeal->LightStatus == Light_On)
{
ImageDeal->Mid_MidLine = 0.5 * ImageDeal->Num_EffectiveMidLine;
if(ImageDeal->Mid_MidLine > ImageDeal->Num_MidLine)
ImageDeal->Mid_MidLine = ImageDeal->Num_MidLine;
if(ImageDeal->Mid_MidLine < 0)
ImageDeal->Mid_MidLine = 0;
ImageDeal->Now_Error = ImageDeal->MidLine[ImageDeal->Mid_MidLine]; // MidSum / MidLineIndex;
//ImageDeal->Size_SumMid = ImageDeal->Sum_WhiteBlock* 10.0 / ImageDeal->Num_MidLine / 3.5;
}
else
{
ImageDeal->Now_Error = ImageDeal->Temp_Error;
ImageDeal->Num_MidLine = ImageDeal->LastNum_MidLine;
ImageDeal->Sum_WhiteBlock = ImageDeal->LastSum_WhiteBlock;
}
}
RegionImageInfo NowRegionImage;
void CalRegionGrayMinMax(uint8 imagebuff[120][188], uint8 startx, uint8 starty, uint8 height, uint8 width)
{
float GraySum = 0;
unsigned int AddIndex = 0;
NowRegionImage.MaxGray = imagebuff[startx][starty];
NowRegionImage.MinGray = imagebuff[startx][starty];
NowRegionImage.MeanGray = imagebuff[startx][starty];
for (int i = startx; i < startx + width; i++)
{
for (int j = starty; j < starty + height; j++,AddIndex++)
{
if (imagebuff[i][j] > NowRegionImage.MaxGray)
NowRegionImage.MaxGray = imagebuff[i][j];
if (imagebuff[i][j] < NowRegionImage.MinGray)
NowRegionImage.MinGray = imagebuff[i][j];
GraySum += imagebuff[i][j];
}
}
NowRegionImage.MeanGray = (uint8)(GraySum / AddIndex);
}
|
C
|
// euler15.c
/*
Starting in the top left corner of a 2 x 2 grid, and being only able to move left and right,
there are exactly 6 routes to the bottom right corner.
rrdd,
rdrd, rddr,
drrd, drdr,
ddrr
How many such routes are there on a 20 x 20 grid
SOLVED
*/
/*
These are the number of coin flip sequences that produce n heads and n tails
1 Coin
H
T
2 coins
HH
HT TH
TT
3 coins
HHH
HHT HTH THH
HTT THT TTH
TTT
4 coins
HHHH
HHHT HHTH HTHH THHH
HHTT HTHT HTTH THHT THTH TTHH
HTTT THTT TTHT TTTH
TTTT
5 coins
HHHHH
HHHHT HHHTH HHTHH HTHHH THHHH
HHHTT HHTHT HHTTH HTHHT HTHTH HTTHH THHHT THHTH THTHH TTHHH
HHTTT HTHTT HTTHT HTTTH THHTT THTHT THTTH TTHHT TTHTH TTTHH
HTTTT THTTT TTHTT TTTHT TTTTH
TTTTT
It's clearly just Pascal's triangle. So the answer to our problem is C(n, k)
= n! / k! (n - k)!
where n is double the size of the grid and k is the size of the grid
*/
#include<stdio.h>
double f(int start, int stop); // factorial function
double f(int start, int stop) {
int i;
long out = 1;
for (i=start; i > stop; i-=1) {
out *= i;
printf("%d\n", i);
}
printf("-\n%f\n", out);
printf("--------\n");
return out;
}
int main() {
int k = 20;
int n = 2*k;
// int notanswer = f(5, 1);
// int answer = f(n, 1) / (f(n-k, 1) * f(k, 1));
double answer = f(n, k) / f(k, 1);
printf("and the answer is -- %f\n", answer);
// printf("and the answer is not -- %d\n", notanswer);
}
|
C
|
#include<stdio.h>
#include<string.h>
int main()
{
int i,j,flag;
int h[150];
char s[100001];
scanf("%s",s);
{
flag=0;
memset(h,0,sizeof(h));
j=strlen(s);
for(i=0;i<j;i++)
{
h[s[i]]++;
}
for(i=50;i<150;i++)
{
if(h[i]%2!=0)
{
flag++;
}
}
if(flag>1)
{
printf("NO\n");
}
else
{
printf("YES\n");
}
}
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
int main()
{
int x[100][100],y[100][100],z[100][100],i,j,k,l,a,b,c;
printf("Enter row and column number of first matrix: ");
scanf("%d%d",&i,&j);
printf("Enter row and column number of second matrix: ");
scanf("%d%d",&k,&l);
if(j!=k)
{
printf("\nMultiplication not porssble\n");
exit(0);
}
printf("Enter elements of first matrix: ");
for(a=0;a<i;a++)
{
for(b=0;b<j;b++)
scanf("%d",&x[a][b]);
}
printf("Enter elements of secod matrix: ");
for(a=0;a<k;a++)
{
for(b=0;b<l;b++)
scanf("%d",&y[a][b]);
}
for(a=0;a<i;a++)
{
for(b=0;b<l;b++)
{
z[a][b]=0;
}
}
for(a=0;a<i;a++)
{
for(b=0;b<l;b++)
{
for(c=0;c<j;c++)
{
z[a][b]=x[a][c]*y[c][b]+z[a][b];
}
}
}
printf("\nMultiplicated Matrix is given below: \n\n");
for(a=0; a<i; a++)
{
for(b=0; b<l; b++)
{
printf(" %d ",z[a][b]);
if(b==l-1)
{
printf("\n");
}
}
}
}
|
C
|
#include <getopt.h>
#include <stdio.h>
#include <stdlib.h>
#include "support.h"
/*
* tail_file() - display the last numlines lines of a file or stdin
*/
void tail_file(char *filename, int numlines) {
/* TODO: Complete this function */
if(numlines <= 0){
printf("Please enter a number greater than 0\n");
return;
}
FILE *file = fopen(filename, "r");
int currentLine = 1;
int charIndex = 0;
char curChar;
char lines[numlines][1024];
//if no file is given we switch to read from stdin
if(!file){
file = stdin;
}
while((curChar = fgetc(file)) != EOF){
//if the line is longer than 1024 characters we will start
//overwriting the initial characters of the line
if(charIndex > 1023){
charIndex = 0;
}
lines[currentLine % numlines][charIndex] = curChar;
//checks for a new line
if(curChar == '\n'){
//printf("Read in: %s\n", lines[currentLine % numlines]);
charIndex = 0;
currentLine++;
}else{
charIndex++;
}
}
//sets the line to start printing at
int printLine = 1;
if(currentLine > numlines){
printLine = currentLine - numlines;
}
int i = numlines;
while(currentLine > 0 && i > 0){
// iterates through the circular buffer
int line = printLine % numlines;
int j = 0;
//prints each line
while(lines[line][j] && ((curChar = lines[line][j]) != '\n')){
putchar(curChar);
j++;
}
//prints the newline character after each line
putchar('\n');
i--;
printLine++;
currentLine--;
}
fclose(file);
}
/*
* help() - Print a help message.
*/
void help(char *progname) {
printf("Usage: %s [FILE]\n", progname);
printf("Print the last 10 lines of FILE to STDOUT\n");
printf("With no FILE, read from STDIN\n");
printf(" -nK print the last K lines instead of the last 10\n");
}
/*
* main() - The main routine parses arguments and dispatches to the
* task-specific code.
*/
int main(int argc, char **argv) {
/* for getopt */
long opt;
/* run a student name check */
check_student(argv[0]);
/* parse the command-line options. For this program, we only support */
/* the parameterless 'h' option, for getting help on program usage, */
/* and the parametered 'n' option, for getting the number of lines. */
/* TODO: parse the arguments correctly */
//int linenumArg = 0;
int lines = 10;
int nFlag = 0;
while ((opt = getopt(argc, argv, "hn:")) != -1) {
switch(opt) {
case 'h': help(argv[0]); break;
case 'n': lines = atoi(optarg); nFlag = 1; break;
}
}
/*
while ((opt = getopt(argc, argv, "n")) != -1) {
switch(opt) {
case 'n': lines = atoi(optarg);; break;
}
}
*/
/*
if(linenumArg){
lines = atoi(argv[argc-2]);
}
*/
//printf("%i\n", linenumArg);
/* TODO: fix this invocation */
if(argc > (1 + nFlag)){
tail_file(argv[argc - 1], lines);
}else{
tail_file(NULL, lines);
}
}
|
C
|
double bilinear_int(CImg<double> &in,double x,double y,int c)
{
int i,j;
double a,b,first_pt,second_pt,third_pt,forth_pt;
if(x < 0 or y < 0 )
{
// cout << "inside bracket" << endl;
return 0.0;
}
else
{
// cout << "insice else" << endl;
i =floor(x);
j =floor(y);
// cout << "test3" << endl;
a = x - i;
b = y - j;
// cout << "test4" << endl;
// cout << x << " " << y << " " << " " << c << " " << endl;
first_pt = (1-a)*(1-b)*in(i,j,c);
second_pt = a*(1-b)*in(i+1,j,c);
third_pt = a*b*in(i+1,j+1,c);
forth_pt = (1-a)*b*in(i,j+1,c);
// cout << "test5" << endl;
//
// cout << first_pt << " " <<sec_pt<< " " << third_pt <<" " <<frth_pt << " " << endl;
return first_pt+second_pt+third_pt+forth_pt;
}
}
void warp_image(CImg<double> &in,const CImg<double> &matrix,CImg<double> &out)
{
double z = 1;
double _x,_y,_z;
double val;
cimg_forXYC(in,x,y,v)
{
_x = matrix(0,0)*x + matrix(0,1)*y + matrix(0,2)*z;
_y = matrix(1,0)*x + matrix(1,1)*y + matrix(1,2)*z;
_z = matrix(2,0)*x + matrix(2,1)*y + matrix(2,2)*z;
_x = (_x/_z);
_y = (_y/_z);
if( _x < 0)
{_x = 0;}
else if (_x > in.width())
{ _x = 0.0;}
// if (_x > in.width() or _y > in.height())
// {
// out(x,y,v) = 0.0;
// }
if ( _y < 0)
{_y = 0.0;}
else if (_y > in.height())
{_y = 0;}
// cout << " bilinear int called" << endl;
// cout << _x << " " << _y << " "<< " " << v<< " " << endl;
val = bilinear_int(in,_x,_y,v);
// cout << " bilinear completed" << endl;
out(x,y,v) = val;
};
}
|
C
|
#include "sniff.h"
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <pcap.h>
#include <netinet/if_ether.h>
#include <netinet/ip.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include "dispatch.h"
// Application main sniffing loop
void sniff(char *interface, int verbose) {
//Let's make some of that thread shit first.
// Open network interface for packet capture
char errbuf[PCAP_ERRBUF_SIZE];
pcap_t *pcap_handle = pcap_open_live(interface, 4096, 1, 0, errbuf);
if (pcap_handle == NULL) {
fprintf(stderr, "Unable to open interface %s\n", errbuf);
exit(EXIT_FAILURE);
} else {
printf("SUCCESS! Opened %s for capture\n", interface);
}
//Start thread pool.
if (!verbose) {
initThreadStuff();
printf("Init Thread Stuff\n");
} else {
//All the printfs mess with threads and pcap_loop for delays.
printf("No Thread Mode\n");
}
signal(SIGINT, gracefulkill);
pcap_loop(pcap_handle, -1, (pcap_handler) dispatch, (u_char *) &verbose);
}
// Utility/Debugging method for dumping raw packet data
void dump(const unsigned char *data, int length) {
int i;
static unsigned long pcount = 0;
// Decode Packet Header
struct ether_header *eth_header = (struct ether_header *) data;
printf("\n\n === PACKET %ld HEADER ===", pcount);
printf("\nSource MAC: ");
for (i = 0; i < 6; ++i) {
printf("%02x", eth_header->ether_shost[i]);
if (i < 5) {
printf(":");
}
}
printf("\nDestination MAC: ");
for (i = 0; i < 6; ++i) {
printf("%02x", eth_header->ether_dhost[i]);
if (i < 5) {
printf(":");
}
}
signal(SIGINT, gracefulkill);
printf("\nType: %04hx\n", ntohs(eth_header->ether_type));
if (ntohs(eth_header->ether_type) == ETH_P_IP) {
const unsigned char *ethpayload = data + ETH_HLEN;
struct ip *iphead = (struct ip *) ethpayload;
printf(" === IP HEADER === \n");
//printf("Ver: %hhu\n", iphead->ip_v);
//printf("HL: %hhu\n", iphead->ip_hl);
printf("ToS: %hhu\n", iphead->ip_tos);
printf("Len: %hu\n", iphead->ip_len);
printf("ID: %hu\n", ntohs(iphead->ip_id));
printf("Frag: %hu\n", ntohs(iphead->ip_off));
printf("TtL: %hhu\n", iphead->ip_ttl);
printf("Prot: %hhu\n", iphead->ip_p); //https://tools.ietf.org/html/rfc790
//printf("HCS: %hu\n", iphead->ip_sum);
char chrTempIP = 0;
printf("SRC: ");
for (i = 3; i >= 0; i--) {
chrTempIP = ((ntohl(iphead->ip_src.s_addr)) >> (i << 3)) & 0xff;
printf("%hhu", chrTempIP);
if (i > 0) printf(":");
}
printf("\n");
printf("DST: ");
for (i = 3; i >= 0; i--) {
chrTempIP = ((ntohl(iphead->ip_dst.s_addr)) >> (i << 3)) & 0xff;
printf("%hhu", chrTempIP);
if (i > 0) printf(":");
}
printf("\n");
const unsigned char *ippayload = data + ETH_HLEN + iphead->ip_hl*4;
if (iphead->ip_p == IPPROTO_TCP) {
struct tcphdr *tcphead = (struct tcphdr *) ippayload;
printf(" === TCP HEADER === \n");
printf("SrcPort: %u\n", ntohs(tcphead->source));
printf("DstPort: %u\n", ntohs(tcphead->dest));
printf("Seq Num: %lu\n", ntohl(tcphead->seq));
printf("Ack Num: %lu\n", ntohl(tcphead->ack_seq));
//printf("Offset: %u\n", tcphead->doff);
//printf("Window: %u\n", tcphead->window);
//printf("Checksum: %u\n", tcphead->check);
printf("UrgPtr: %u\n", ntohs(tcphead->urg_ptr));
printf("Flags:\n");
printf("URG|ACK|PSH|RST|SYN|FIN\n");
printf("[%u]|[%u]|[%u]|[%u]|[%u]|[%u]\n",
tcphead->urg, tcphead->ack, tcphead->psh,
tcphead->rst, tcphead->syn, tcphead->fin);
printf(" === PACKET %ld DATA == \n", pcount);
// Decode Packet Data (Skipping over the header)
int data_bytes = length - ETH_HLEN - iphead->ip_hl * 4 - tcphead->doff * 4;
const unsigned char *packetpayload = data + ETH_HLEN + iphead->ip_hl * 4 + tcphead->doff * 4 ;
const static int output_sz = 20; // Output this many bytes at a time
while (data_bytes > 0) {
int output_bytes = data_bytes < output_sz ? data_bytes : output_sz;
// Print data in raw hexadecimal form
for (i = 0; i < output_sz; ++i) {
if (i < output_bytes) {
printf("%02x ", packetpayload[i]);
} else {
printf (" "); // Maintain padding for partial lines
}
}
printf ("\b|");
// Print data in ascii form
for (i = 0; i < output_bytes; ++i) {
char byte = packetpayload[i];
if (byte > 31 && byte < 127) {
// Byte is in printable ascii range
printf("%c", byte);
} else {
printf(".");
}
}
printf("\n");
packetpayload += output_bytes;
data_bytes -= output_bytes;
}
} else if (iphead->ip_p == 1) {
//Do your ICMP shit
printf("ICPM: TYPE: %hhu", ippayload[0]);
} else {
printf("Not gonna touch that IP protocol.\n");
}
} else if (ntohs(eth_header->ether_type) == ETH_P_ARP) {
printf("INSERT ARP STUFF\n");
} else {
printf("Not gonna touch that ethernet type.\n");
}
++pcount;
}
|
C
|
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include "vector.h"
void vec_init(vector *v) {
v->cap = 0;
v->len = 0;
v->buf = NULL;
}
void vec_clear(vector *v) {
free(v->buf);
vec_init(v);
}
void vec_insert(vector *v, size_t idx, void *val) {
if(idx > v->len) {
return;
}
if(v->len >= v->cap) {
v->cap = v->cap * 2 + 1;
v->buf = realloc(v->buf, v->cap * sizeof(void *));
if(v->cap) {
assert(v->buf);
}
}
memmove(v->buf + (idx + 1), v->buf + idx, (v->len - idx) * sizeof(void *));
v->buf[idx] = val;
v->len++;
}
void *vec_remove(vector *v, size_t idx) {
void *temp;
if(idx >= v->len) {
return NULL;
}
temp = v->buf[idx];
v->len--;
memmove(v->buf + idx, v->buf + (idx + 1), (v->len - idx) * sizeof(void *));
return temp;
}
void vec_alloc(vector *v, size_t cap) {
v->buf = realloc(v->buf, cap * sizeof(void *));
if(cap) {
assert(v->buf);
}
v->cap = cap;
v->len = (v->cap < v->len ? v->cap : v->len);
}
void vec_map(vector *vin, vector *vout, vec_map_f map, void *data) {
size_t i;
vec_clear(vout);
vec_alloc(vout, vin->len);
for(i = 0; i < vin->len; i++) {
vout->buf[i] = map(vin->buf[i], data);
}
vout->len = vin->len; /* XXX Race condition if map modifies vout */
}
void *vec_reduce(vector *v, vec_reduce_f reduce, void *init) {
void *accum = init;
size_t i;
for(i = 0; i < v->len; i++) {
accum = reduce(accum, v->buf[i]);
}
return accum;
}
int vec_test(vector *v, vec_test_f test, void *data) {
size_t i;
int res;
for(i = 0; i < v->len; i++) {
if((res = test(data, v->buf[i], v, i))) {
return res;
}
}
return 0;
}
int vec_equal(vector *va, vector *vb, vec_eq_f eq) {
size_t i;
if(va->len != vb->len) {
return 0;
}
for(i = 0; i < va->len; i++) {
if(!eq(va->buf[i], vb->buf[i])) {
return 0;
}
}
return 1;
}
void vec_foreach(vector *v, vec_iter_f iter, void *data) {
size_t i;
for(i = 0; i < v->len; i++) {
iter(v->buf[i], data);
}
}
ssize_t vec_search(vector *v, void *val) {
size_t i;
for(i = 0; i < v->len; i++) {
if(val == v->buf[i]) {
return i;
}
}
return -1;
}
void vec_copy(vector *from, vector *into) {
size_t i;
vec_clear(into);
vec_alloc(into, from->len);
for(i = 0; i < from->len; i++) {
into->buf[i] = from->buf[i];
}
into->len = from->len; /* But also see vec_map */
}
#if !defined(VECTOR_NO_GETSET) && (defined(VECTOR_GETSET_FUNCS) || defined(VECTOR_GETSET_BOUNDS))
/* Hopefully, intelligent optimizers will lower this for the trivial case. These
* might be useful with function pointers, though.
*/
void *vec_get2(vector *v, size_t idx) {
#ifdef VECTOR_GETSET_BOUNDS
if(idx >= v->len) {
return NULL;
}
#endif
return v->buf[idx];
}
void *vec_get(vector *v, size_t idx) {
#ifdef VECTOR_GETSET_BOUNDS
if(idx >= v->len) {
return NULL;
}
#endif
return vec_get2(v, idx);
}
void *vec_set(vector *v, size_t idx, void *val) {
#ifdef VECTOR_GETSET_BOUNDS
if(idx >= v->len) {
return val;
}
#endif
return (v->buf[idx] = val); /* For compat with macro definition */
}
#endif
|
C
|
#include "graphics.h"
static byte* const framebuf = (byte*) 0xA0000;
byte* renderBuf;
#ifdef DOUBLE_BUFFERED
byte* depthBuf;
#endif
static byte depthVal;
static byte color;
static bool depthTest;
static int drawMode;
mat4 modelMat;
mat4 viewMat;
mat4 projMat;
static bool glDebugOn = false;
// (x1, y1) is the top of triangle, and y2 == y3
static int fillFlatBottomTriangle(int x1, int y1, int x2, int y2, int x3, int y3);
// (x3, y3) is the bottom of triangle, and y1 == y2
static void fillFlatTopTriangle(int x1, int y1, int x2, int y2, int x3, int y3);
// rearrange the given values in-place so y1 <= y2 <= y3
static void sortVerticesByY(int* x1, int* y1, int* x2, int* y2, int* x3, int* y3);
// swap vertices in-place (used by sort)
static void swapVertices(int* x1, int* y1, int* x2, int* y2);
void setColor(byte c)
{
color = c;
}
void drawLine(int x1, int y1, int x2, int y2)
{
int changed, x, y, dx, dy, signx, signy, i, e, temp;
x = x1;
y = y1;
dx = x2 - x1;
if(dx < 0)
dx = -dx;
dy = y2 - y1;
if(dy < 0)
dy = -dy;
signx = x2 - x1;
if(signx < 0)
signx = -1;
else
signx = 1;
signy = y2 - y1;
if(signy < 0)
signy = -1;
else
signy = 1;
if(dy > dx)
{
temp = dy;
dy = dx;
dx = temp;
changed = 1;
}
else
{
changed = 0;
}
e = (dy << 1) - dx;
for(i = 0; i <= dx; i++)
{
drawPixel(x, y);
if(e > 0)
{
if(changed)
x += signx;
else
y += signy;
e -= (dx << 1);
}
if(changed)
y += signy;
else
x += signx;
e += (dy << 1);
}
}
void drawTriangle(int x1, int y1, int x2, int y2, int x3, int y3)
{
drawLine(x1, y1, x2, y2);
drawLine(x1, y1, x3, y3);
drawLine(x2, y2, x3, y3);
}
void fillTriangle(int x1, int y1, int x2, int y2, int x3, int y3)
{
int minx = min(min(x1, x2), x3);
int miny = min(min(y1, y2), y3);
int maxx = max(max(x1, x2), x3);
int maxy = max(max(y1, y2), y3);
//triangle too big to rasterize
if(maxx - minx > 320 || maxy - miny > 200)
return;
sortVerticesByY(&x1, &y1, &x2, &y2, &x3, &y3);
int partition = fillFlatBottomTriangle(x1, y1, x2, y2, x3, y3);
if(x2 < x3)
fillFlatTopTriangle(partition, y2, x2, y2, x3, y3);
else
fillFlatTopTriangle(x2, y2, partition, y2, x3, y3);
}
void drawRect(int x, int y, int w, int h)
{
for(int i = x; i <= x + w; i++)
{
renderBuf[i + y * 320] = color;
renderBuf[i + (y + h) * 320] = color;
}
for(int i = y + 1; i <= y + h - 1; i++)
{
renderBuf[x + i * 320] = color;
renderBuf[x + w + i * 320] = color;
}
}
void fillRect(int x, int y, int w, int h)
{
for(int i = y; i < y + h; i++)
{
for(int j = x; j < x + w; j++)
{
drawPixel(j, i);
}
}
}
void drawBezier(vec2 p0, vec2 p1, vec2 p2, vec2 p3, int steps)
{
float dt = 1.0 / steps;
int prevx = p0.v[0];
int prevy = p0.v[1];
float t = dt;
for(int i = 1; i < steps; i++)
{
float t2 = t*t;
float t12 = (1-t)*(1-t);
float u1 = (1-t)*t12;
float u2 = 3*t12*t;
float u3 = 3*(1-t)*t2;
float u4 = t2*t;
int nextx = u1 * p0.v[0] + u2 * p1.v[0] + u3 * p2.v[0] + u4 * p3.v[0];
int nexty = u1 * p0.v[1] + u2 * p1.v[1] + u3 * p2.v[1] + u4 * p3.v[1];
drawLine(prevx, prevy, nextx, nexty);
prevx = nextx;
prevy = nexty;
t += dt;
}
}
// point 1 is peak
int fillFlatBottomTriangle(int x1, int y1, int x2, int y2, int x3, int y3)
{
int changed1, changed2, ix1, iy1, ix2, iy2, dx1, dy1, dx2, dy2,
signx1, signy1, signx2, signy2, partition, i, j, e1, e2, leg, temp;
/* set up bresenham between points 1 and 2 */
if(x2 > x3)
{
swapVertices(&x2, &y2, &x3, &y3);
leg = 0;
}
else
{
leg = 1;
}
ix1 = x1;
iy1 = y1;
dx1 = x2 - x1;
if(dx1 < 0)
{
signx1 = -1;
dx1 = -dx1;
}
else
{
signx1 = 1;
}
dy1 = y2 - y1;
if(dy1 < 0)
{
signy1 = -1;
dy1 = -dy1;
}
else
{
signy1 = 1;
}
if(dy1 > dx1)
{
changed1 = 1;
temp = dy1;
dy1 = dx1;
dx1 = temp;
}
else
{
changed1 = 0;
}
/* set up bresenham between points 2 and 3 */
ix2 = x1;
iy2 = y1;
dx2 = x3 - x1;
if(dx2 < 0)
{
signx2 = -1;
dx2 = -dx2;
}
else
{
signx2 = 1;
}
dy2 = y3 - y1;
if(dy2 < 0)
{
signy2 = -1;
dy2 = -dy2;
}
else
{
signy2 = 1;
}
if(dy2 > dx2)
{
changed2 = 1;
temp = dy2;
dy2 = dx2;
dx2 = temp;
}
else
{
changed2 = 0;
}
/* run two instances of bresenham simultaneously */
e1 = (dy1 << 1) - dx1;
e2 = (dy2 << 1) - dx2;
for(i = y1; i < y2 && i < y3; i++) /* want i to reach min(y2, y3) */
{
while(1) /* step forward by 1 unit in y */
{
drawPixel(ix1, iy1);
if(e1 > 0)
{
if(changed1)
{
ix1 += signx1;
e1 -= (dx1 << 1);
}
else
{
iy1 += signy1;
e1 -= (dx1 << 1);
break;
}
}
if(changed1)
{
iy1 += signy1;
e1 += (dy1 << 1);
break;
}
else
{
ix1 += signx1;
e1 += (dy1 << 1);
}
}
while(1)
{
drawPixel(ix2, iy2);
if(e2 > 0)
{
if(changed2)
{
ix2 += signx2;
e2 -= (dx2 << 1);
}
else
{
iy2 += signy2;
e2 -= (dx2 << 1);
break;
}
}
if(changed2)
{
iy2 += signy2;
e2 += (dy2 << 1);
break;
}
else
{
ix2 += signx2;
e2 += (dy2 << 1);
}
}
/* now both x and y have increased exactly one unit in y */
if(ix1 < ix2)
{
for(j = ix1; j < ix2; j++)
{
drawPixel(j, iy1);
}
}
else
{
for(j = ix2; j < ix1; j++)
{
drawPixel(j, iy1);
}
}
}
if(leg == 0)
return ix1;
else
return ix2;
}
//point 3 is bottom
void fillFlatTopTriangle(int x1, int y1, int x2, int y2, int x3, int y3)
{ /* preconditions: y1 == y2 and (x3, y3) is the bottom tip of tri */
int changed1, changed2, ix1, iy1, ix2, iy2, dx1, dy1, dx2, dy2,
signx1, signy1, signx2, signy2, i, j, e1, e2, temp;
/* set up bresenham between points 1 and 2 */
if(x1 > x2)
swapVertices(&x1, &y1, &x2, &y2);
for(i = x1; i <= x2; i++)
drawPixel(i, y1);
ix1 = x1;
iy1 = y1;
dx1 = x3 - x1;
if(dx1 < 0)
{
signx1 = -1;
dx1 = -dx1;
}
else
{
signx1 = 1;
}
dy1 = y3 - y1;
if(dy1 < 0)
{
signy1 = -1;
dy1 = -dy1;
}
else
{
signy1 = 1;
}
if(dy1 > dx1)
{
changed1 = 1;
temp = dy1;
dy1 = dx1;
dx1 = temp;
}
else
{
changed1 = 0;
}
/* set up bresenham between points 2 and 3 */
ix2 = x2;
iy2 = y2;
dx2 = x3 - x2;
if(dx2 < 0)
{
signx2 = -1;
dx2 = -dx2;
}
else
{
signx2 = 1;
}
dy2 = y3 - y2;
if(dy2 < 0)
{
signy2 = -1;
dy2 = -dy2;
}
else
{
signy2 = 1;
}
if(dy2 > dx2)
{
changed2 = 1;
temp = dy2;
dy2 = dx2;
dx2 = temp;
}
else
{
changed2 = 0;
}
/* run two instances of bresenham simultaneously */
e1 = (dy1 << 1) - dx1;
e2 = (dy2 << 1) - dx2;
for(i = y1; i < y3; i++)
{
while(1) /* step forward by 1 unit in y */
{
drawPixel(ix1, iy1);
if(e1 > 0)
{
if(changed1)
{
ix1 += signx1;
e1 -= (dx1 << 1);
}
else
{
iy1 += signy1;
e1 -= (dx1 << 1);
break;
}
}
if(changed1)
{
iy1 += signy1;
e1 += (dy1 << 1);
break;
}
else
{
ix1 += signx1;
e1 += (dy1 << 1);
}
}
while(1)
{
drawPixel(ix2, iy2);
if(e2 > 0)
{
if(changed2)
{
ix2 += signx2;
e2 -= (dx2 << 1);
}
else
{
iy2 += signy2;
e2 -= (dx2 << 1);
break;
}
}
if(changed2)
{
iy2 += signy2;
e2 += (dy2 << 1);
break;
}
else
{
ix2 += signx2;
e2 += (dy2 << 1);
}
}
/* now both x and y have increased exactly one unit in y */
if(ix1 < ix2)
{
for(j = ix1; j < ix2; j++)
{
drawPixel(j, iy1);
}
}
else
{
for(j = ix2; j < ix1; j++)
{
drawPixel(j, iy1);
}
}
}
}
void sortVerticesByY(int* x1, int* y1, int* x2, int* y2, int* x3, int* y3)
{
if(*y1 > *y2)
swapVertices(x1, y1, x2, y2);
if(*y2 > *y3)
swapVertices(x2, y2, x3, y3);
if(*y1 > *y2)
swapVertices(x1, y1, x2, y2);
if(*y2 > *y3)
swapVertices(x2, y2, x3, y3);
}
void swapVertices(int* x1, int* y1, int* x2, int* y2)
{
int temp;
temp = *x1;
*x1 = *x2;
*x2 = temp;
temp = *y1;
*y1 = *y2;
*y2 = temp;
}
//////////////////
// 3D functions //
//////////////////
mat4 fullMat;
static Plane frustum[5];
static float projFar;
static void updateMatrices()
{
fullMat = matmat(projMat, matmat(viewMat, modelMat));
}
void setModel(mat4 m)
{
modelMat = m;
updateMatrices();
}
void setView(mat4 v)
{
viewMat = v;
updateMatrices();
}
void setProj(float fovyDeg, float near, float far)
{
projFar = far;
projMat = perspective(fovyDeg / (180.0f / PI), near, far);
updateMatrices();
getFrustumPlanes(frustum, ((fovyDeg / 2) / (180.0f / PI)), near);
}
vec3 vshade(vec3 vertex)
{
vec4 result = matvec3(fullMat, vertex);
//divide by w
vec3 clip = {{result.v[0] / result.v[3], result.v[1] / result.v[3], result.v[2] / result.v[3]}};
return clip;
}
point viewport(vec3 clip)
{
point p;
p.x = (clip.v[0] + 1) * (VIEWPORT_X / 2);
if(p.x < 0)
p.x = 0;
if(p.x >= 320)
p.x = 319;
p.y = (-clip.v[1] + 1) * (VIEWPORT_Y / 2);
if(p.y < 0)
p.y = 0;
if(p.y >= 200)
p.y = 199;
return p;
}
//Simple OpenGL implementation
static int geomType = NO_GEOM;
static vec3 vertState[4];
static int numVerts = 0;
static bool enabled3D = true;
static const int vertsPerElement[] = {0, 2, 3, 4};
void glBegin(int type)
{
geomType = type;
numVerts = 0;
}
void glEnd()
{
geomType = NO_GEOM;
}
void glVertex2i(int x, int y)
{
glVertex3f(x, y, 0);
}
void glVertex3f(float x, float y, float z)
{
vec3 v = {x, y, z};
glVertex3fv(v);
}
//all triangles with > 0 vertices past far plane are completely culled
//other triangles are clipped in this order:
//z = -1 (near)
//x = -1
//x = 1
//y = -1
//y = 1
//Each clip-draw function clips one triangle against one plane
vec3 intersect(vec3 pt1, vec3 pt2, int dim, float val)
{
if(fabsf(pt1.v[dim] - pt2.v[dim]) < 1e-6)
{
//can't do intersection formula, so just return the midpt
//return vecscale(vecadd(pt1, pt2), 0.5);
return pt1;
}
else
{
return vecadd(pt1, vecscale(vecsub(pt2, pt1), (val - pt1.v[dim]) / (pt2.v[dim] - pt1.v[dim])));
}
}
#define VEC_SWAP(pt1, pt2) \
{ \
vec3 temp = pt1; \
pt1 = pt2; \
pt2 = temp; \
}
//Fill a triangle, and clip against frustum
//v1, v2, v3 in view space
//Pass clipPlane = 0 to start (is recursive)
//Pass clipPlane = 5 to do perspective trans and rasterize
//Precondition: already culled triangles beyond the far plane
static void drawClippedTri(vec3 v1, vec3 v2, vec3 v3, int clipPlane)
{
if(clipPlane == 0)
{
if(v1.v[2] < -projFar || v2.v[2] < -projFar || v3.v[3] < -projFar)
return;
}
if(clipPlane == 5)
{
vec4 proj1 = matvec3(projMat, v1);
vec4 proj2 = matvec3(projMat, v2);
vec4 proj3 = matvec3(projMat, v3);
point vp1 = viewport(vecscale(toVec3(proj1), 1.0f / proj1.v[3]));
point vp2 = viewport(vecscale(toVec3(proj2), 1.0f / proj2.v[3]));
point vp3 = viewport(vecscale(toVec3(proj3), 1.0f / proj3.v[3]));
fillTriangle(vp1.x, vp1.y, vp2.x, vp2.y, vp3.x, vp3.y);
return;
}
Plane toClip = frustum[clipPlane];
//test vertices against *toClip
//note: distance > 0 means "in front" or in same direction as plane normal,
//which means the point is on the visible side of the plane
int behind = 0;
float dist[3];
dist[0] = planeLineDistance(v1, toClip);
dist[1] = planeLineDistance(v2, toClip);
dist[2] = planeLineDistance(v3, toClip);
//sort vertices by dist, ascending
if(dist[0] > dist[1])
{
VEC_SWAP(v1, v2);
float temp = dist[0];
dist[0] = dist[1];
dist[1] = temp;
}
if(dist[1] > dist[2])
{
VEC_SWAP(v2, v3);
float temp = dist[1];
dist[1] = dist[2];
dist[2] = temp;
}
if(dist[0] > dist[1])
{
VEC_SWAP(v1, v2);
float temp = dist[0];
dist[0] = dist[1];
dist[1] = temp;
}
int beyond = 0;
for(int i = 0; i < 3; i++)
{
if(dist[i] < 0)
beyond++;
}
switch(beyond)
{
case 0:
//triangle does not intersect plane at all
drawClippedTri(v1, v2, v3, clipPlane + 1);
break;
case 1:
{
//one vertex invisible
//compute two intersection points and draw 2 triangles
//get v1 as the invisible vertex
vec3 inter1 = linePlaneIntersect(v1, v2, toClip);
vec3 inter2 = linePlaneIntersect(v1, v3, toClip);
drawClippedTri(inter1, v2, v3, clipPlane + 1);
drawClippedTri(inter1, v3, inter2, clipPlane + 1);
break;
}
case 2:
{
//2 vertices invisible
//compute two intersection points and draw one triangle
//get v1 as the only visible vertex
vec3 inter1 = linePlaneIntersect(v1, v3, toClip);
vec3 inter2 = linePlaneIntersect(v2, v3, toClip);
drawClippedTri(v3, inter1, inter2, clipPlane + 1);
break;
}
case 3:
default:;
}
}
void glVertex3fv(vec3 v)
{
vertState[numVerts++] = v;
int verts = vertsPerElement[geomType];
if(numVerts == verts)
{
//run vshader and draw the geometry, then flush vert buffer
//vertices in screen space
point screen[4];
vec3 clip[4];
if(!enabled3D)
{
for(int i = 0; i < verts; i++)
{
screen[i] = ((point) {vertState[i].v[0], vertState[i].v[1]});
}
}
else
{
for(int i = 0; i < verts; i++)
{
clip[i] = vshade(vertState[i]);
}
}
if(geomType == GL_LINES)
{
screen[0] = viewport(clip[0]);
screen[1] = viewport(clip[1]);
drawLine(screen[0].x, screen[0].y, screen[1].x, screen[1].y);
}
else if(geomType == GL_TRIANGLES)
{
if(drawMode == DRAW_FILL)
{
//do modelview transform only on vertstate[0:3]
//for now, ignore model
drawClippedTri(
toVec3(matvec3(viewMat, vertState[0])),
toVec3(matvec3(viewMat, vertState[1])),
toVec3(matvec3(viewMat, vertState[2])), 0);
}
else
{
screen[0] = viewport(clip[0]);
screen[1] = viewport(clip[1]);
screen[2] = viewport(clip[2]);
drawTriangle(screen[0].x, screen[0].y, screen[1].x, screen[1].y, screen[2].x, screen[2].y);
}
}
else if(geomType == GL_QUADS)
{
if(drawMode == DRAW_FILL)
{
drawClippedTri(
toVec3(matvec3(viewMat, vertState[0])),
toVec3(matvec3(viewMat, vertState[1])),
toVec3(matvec3(viewMat, vertState[2])), 0);
drawClippedTri(
toVec3(matvec3(viewMat, vertState[0])),
toVec3(matvec3(viewMat, vertState[2])),
toVec3(matvec3(viewMat, vertState[3])), 0);
}
else
{
screen[0] = viewport(clip[0]);
screen[1] = viewport(clip[1]);
screen[2] = viewport(clip[2]);
screen[3] = viewport(clip[3]);
drawLine(screen[0].x, screen[0].y, screen[1].x, screen[1].y);
drawLine(screen[1].x, screen[1].y, screen[2].x, screen[2].y);
drawLine(screen[2].x, screen[2].y, screen[3].x, screen[3].y);
drawLine(screen[0].x, screen[0].y, screen[3].x, screen[3].y);
}
}
numVerts = 0;
}
}
void glColor1i(byte c)
{
color = c;
}
void enable2D()
{
enabled3D = false;
depthTest = false;
}
void enable3D()
{
enabled3D = true;
}
void glClear(byte c)
{
memset(renderBuf, c, 64000);
}
void glDepth(int d)
{
if(d > 254)
d = 254;
if(d < 0)
d = 0;
depthVal = d;
}
void glEnableDepthTest(bool enable)
{
depthTest = enable;
}
void glDrawMode(int mode)
{
drawMode = mode;
}
void glFlush()
{
#ifdef DOUBLE_BUFFERED
memcpy(framebuf, renderBuf, 64000);
#endif
}
void glText(const char* text, int x, int y, byte bg)
{
byte* iter = renderBuf + x + y * 320;
for(const char* c = text; *c; c++)
{
const int stride = 312;
if(*c < '!' || *c > '~')
{
//non-visible character, clear that region
for(int i = 0; i < 8; i++)
{
for(int j = 0; j < 8; j++)
{
*iter = bg;
iter++;
}
iter += stride;
}
}
else
{
byte* glyph = fontbin + 8 * (*c - '!');
//stride is from right edge of character to left edge of char on next line
for(int row = 0; row < 8; row++)
{
for(byte mask = 0x1; mask; mask <<= 1)
{
if(glyph[row] & mask)
{
*iter = color;
}
else
{
*iter = bg;
}
iter++;
}
iter += stride;
}
}
iter = iter - 8 * 320 + 8;
}
}
void glDebug()
{
glDebugOn = true;
}
|
C
|
//
// strarr.c
//
//
// Created by Adrian Thomas Clinansmith on 2019-04-20.
//
#include "strarr.h"
/*********************************/
/*** private helper prototypes ***/
/*********************************/
FILE* openAndGetMetadata(const char* filepath, size_t* numWords, size_t* maxLength);
/******************************/
/*** public implementations ***/
/******************************/
char** readWords(const char* filepath, size_t *numWords)
{
size_t numWordsRead, maxWordLength;
if (numWords) *numWords = 0;
FILE* fp = openAndGetMetadata(filepath, &numWordsRead, &maxWordLength);
if (!fp) return NULL;
char** words = malloc(sizeof(char*)*(numWordsRead + 1));
if (!words)
{
fclose(fp);
return NULL;
}
words[0] = NULL;
char* buffer = malloc(maxWordLength + 1);
if (!buffer)
{
free(words);
fclose(fp);
return NULL;
}
size_t i = 0;
while (fscanf(fp, "%s", buffer) == 1)
{
words[i] = malloc(strlen(buffer)+1);
if (!words[i])
{
freeStrarr(words);
words = NULL;
numWordsRead = 0;
break;
}
strcpy(words[i], buffer);
words[++i] = NULL;
}
if (numWords) *numWords = numWordsRead;
free(buffer);
fclose(fp);
return words;
}
bool arrHasStr(const char** arr, const char* str)
{
for (size_t i = 0; arr[i]; i++)
{
if (!strcmp(arr[i], str))
{
return true;
}
}
return false;
}
size_t appendStrarr(char** dest, const char** src)
{
size_t i = strarrSize((const char **)dest);
for (size_t j = 0; src[j]; j++)
{
dest[i++] = (char*)src[j];
}
dest[i] = NULL;
return i;
}
size_t strarrSize(const char** arr)
{
size_t i = 0;
while (arr[i]) i++;
return i;
}
void freeStrarr(char** strarr)
{
if (strarr)
{
for (size_t i = 0; strarr[i]; i++)
{
free(strarr[i]);
}
free(strarr);
}
}
/*** private helper implementations ***/
FILE* openAndGetMetadata(const char* filepath, size_t* numWords, size_t* maxLength)
{
if (!filepath) return NULL;
FILE* fp = fopen(filepath, "r");
if (!fp) return NULL;
size_t numWordsRead = 0;
size_t maxLengthRead = 0;
int c;
while ((c = fgetc(fp)) != EOF)
{
if (isspace(c)) continue;
numWordsRead++;
size_t currentLength = 1;
while ((c = fgetc(fp)) != EOF && !isspace(c))
{
currentLength++;
}
if (currentLength > maxLengthRead)
{
maxLengthRead = currentLength;
}
}
if (numWords) *numWords = numWordsRead;
if (maxLength) *maxLength = maxLengthRead;
fseek(fp, 0, SEEK_SET);
return fp;
}
|
C
|
#include "complete_routh_array.h"
#include "source_1.h"
/**
* @brief attempts to complete routh array. Exits if row startinf with 0 or a row of 0s is encountered.
*
* @param rth
* @param i
* @return int
*/
int complete_routh__array(float* rth,int i)
{
float a1,a2,b1,b2,z;
//int changes=0;
int j;
completerouth:
b1=*(rth+(i+1)*c);
while(b1!=0)
{ for(j=1;j<c;j++)
{
a1=*(rth+i*c);
a2=*(rth+i*c+j);
b2=*(rth+(i+1)*c+j);
z=(b1*a2-a1*b2)/b1;
z=(z<0.000001 && z>-0.000001)?0:z;
*(rth+(i+2)*c+j-1)=z;
}
i++;
b1=*(rth+(i+1)*c);
}
return i;
}
|
C
|
// Karen Villarreal 1B
// Trabajo Practico N2
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "FuncionesEmpleados.h"
int main()
{
int respuesta;
int retorno;
int idIngresado;
int crearId = 99; //Se inicializa un contador en 99 para crear las ID
Employee listaEmpleados[TAM];
retorno = initEmployees(listaEmpleados,TAM); //Inicializa todos los cupos en VACIO
if(retorno == 0) //Si se inicializo correctamente se inicia el programa
{
do
{
switch(menu()) //Menu que devuelve la opcion elegida
{
case 1: //1. Llama a la funcion para crear un empleado
crearId++; //Se suma 1 cada vez que ingrese a la opcion 1
if(crearUnEmpleado(listaEmpleados,TAM,crearId) != 0) //Comprueba que se creo correctamente
{
crearId--; //Si no se completo el ingreso se resta 1
}
break;
case 2: //2. Llama a las funciones para modificar un empleado
if(contarEmpleados(listaEmpleados,TAM) > 0) //Si el contador devuelve 0 no deja continuar
{
idIngresado = pedirId(listaEmpleados,TAM,crearId); //Pide el ID, verifica y devuelve
modificarEmpleado(listaEmpleados,TAM,idIngresado); //Funcion para modificar al empleado
}
else
{
printf("\nError! No hay empleados ingresados.\n\n");
}
break;
case 3: //3. Llama a las funciones para borrar un empleado
if(contarEmpleados(listaEmpleados,TAM) > 0) //Si el contador devuelve 0 no deja continuar
{
idIngresado = pedirId(listaEmpleados,TAM,crearId); //Pide el ID, verifica y devulve
removeEmployee(listaEmpleados,TAM,idIngresado); //Funcion para borrar un empleado
}
else
{
printf("\nError! No hay empleados ingresados.\n\n");
}
break;
case 4: //4. Llama a la funcion para mostrar a los empleados ordenados y el informe sobre los salarios
if(contarEmpleados(listaEmpleados,TAM) > 0) //Si el contador devuelve 0 no deja continuar
{
informesEmpleados(listaEmpleados,TAM);
}
else
{
printf("\nError! No hay empleados ingresados.\n\n");
}
break;
case 5: //5. Salida, confirma que el usario quiere salir del programa
respuesta = confirmar();
break;
}
system("pause");
system("cls");
}while(respuesta != 's'); //Mientras el usario no responda "s" continua el programa
}
else
{
printf("\nHubo un error en cargar el programa.\n\n");
}
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.