language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C
|
#include<stdio.h>
#include<stdlib.h>
#include <time.h>
struct Page
{
int page_no;
}frames[7];
int faults=0,q,p,n,page_no,flag=0;
int page_found(int page_no)
{
for(q=0;q<n;q++)
{
if(frames[q].page_no == page_no)
return q;
}
return 'a';
}
int main()
{
int len;
srand ( time(NULL));
printf("Enter number of pages (b/w 0 to 9) :");
scanf("%d",&len);
if(len<0 || len>9)
{
printf("\nInput out of bounds.\n");
exit(0);
}
int *arr = (int *)malloc(len*sizeof(int));
for (int q=0;q<len;q++)
{
arr[q] = ( rand()%9 )+1 ;
}
printf("\nEnter no of frames (b/w 1 to 7) :");
scanf("%d",&n);
if(n<1 || n>7)
{
printf("\nInput out of bounds.\n");
exit(0);
}
printf("Length:%d",len);
for (q=0;q<n;q++)
{
frames[q].page_no = -1;
}
printf("\n Page no page frames page faults fault count");
printf("\n-----------------------------------------------------------");
for(p=0;p<len;p++)
{
page_no = arr[p];
flag=0;
if(page_found(page_no) == 'a')
{
frames[faults%n].page_no = page_no;
faults++;
flag=1;
}
printf("\n%5d\t",page_no);
printf("\t");
for(q=0;q<n;q++)
{
printf("%d ",frames[q].page_no);
}
if(flag==1)
{
printf("\t\t MISS");
}
else
{
printf("\t\t HIT");
}
printf("\t\t%d",faults);
}
printf("\n------------------------------------------------------------");
printf("\nTotal page faults:%d", faults);
free(arr);
return 0;
}
|
C
|
#include <signal.h>
#include <unistd.h>
#include <pthread.h>
#include <stdio.h>
#include <errno.h>
//using namespace std;
//int main()
//{//3.如果多线程模型中,一个线程有异常,比如1/0,这时候这个程序会怎么样?
// 如果是发信号,是哪个线程发送的信如果出现这种情况,应该怎么处理?
// void bbb(int t)
//void *bbb()
//{
// cout << "float err" << endl;
// printf("floa err\n");
// pthread_cancel(pthread_self());
// sleep(2);
//}
void aaa()
{signal(SIGFPE, SIG_IGN);
int a = 1/0;
}
int main()
{
pthread_t t;
int errno;
signal(SIGFPE, SIG_IGN);
pthread_create(&t,NULL,(void *)aaa,NULL);
while(1)
{
//int t = sleep(10);
//if(t)
//cout << "wark up" << endl;
int t = sleep(3);//t每隔3秒返回的是0 说明时间达到,返回 若有信号中断返回剩余秒数
printf("%d\n",t);
while(t)
{
if(errno = EINTR)
printf("is eintr\n");
t = sleep(t);
}
if(t) //打印不了下一句说明信号来了去处理了然后回不来了?
printf("wark up\n");
}
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
//Node to store data of type int
struct Node{
int data;
struct Node *next;
};
//Node to store Address
struct Stack{
struct Node *data;
struct Stack *next;
};
struct Node *head=NULL;
struct Stack *stackhead=NULL;
struct Node *createNode(int data);
void show();
int isEmpty();
void pop();
void insert(int data);
void reverse();
struct Node *top();
void push(struct Node *data);
struct Stack *createstackNode(struct Node *data);
void showInStack();
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include "eps.h"
int main()
{
char * file_path = "out.eps";
char * consoleCommand = "xdg-open ";
int width = 1500;
int height = 3200;
float square_scale = 6.0f;
FILE * file_ptr = fopen(file_path, "w+");
setHeader(file_ptr, "Sorting", width, height);
//int array[] = {11, -2, 9, 93, 47, 98, 12, 13, 7, 0, 1, 4, 3, 77, 88, 15, 16, 91, 24, 21, 32, 73, 89, 26, 29, 87, 76, 94, -4, -5, 93, 85, 32, 62, 83, 91, 71, 17, 19, 34};
int array [] = {98, 94, 93, 93, 91, 91, 89, 88, 87, 85, 83, 77, 76, 73, 71, 62, 47, 34, 32, 32, 29, 26, 24, 21, 19, 17, 16, 15, 13, 12, 11, 9, 7, 4, 3, 1, 0, -2, -4, -5};
//int array[] = {-5, -4, -2, 0, 1, 3, 4, 7, 9, 11, 12, 13, 15, 16, 17, 19, 21, 24, 26, 29, 32, 32, 34, 47, 62, 71, 73, 77, 76, 83, 85, 87, 88, 89, 91, 91, 93, 93, 94, 98};
int n = sizeof(array) / sizeof(int);
//draw_array(file_ptr,array ,1 ,10 , 0,500, 8, (rgb){0,1,0}, (rgb){0,0,0});
//binary_search(array, n, 87, file_ptr, width-100);
// selection sort
/*drawText(file_ptr, (rgb){0,0,0}, 40, 0, height -50, "Selection Sort");
drawLine(file_ptr, (rgb){0,0,0}, 2, height -52 , width -2, height -52, 1);
drawText(file_ptr, (rgb){0,1,0}, 20, 100, height - 70, "Unsorted item");
drawText(file_ptr, (rgb){0,0,1}, 20, 100, height - 90, "Minimum item");
drawText(file_ptr, (rgb){1,0,0}, 20, 100, height - 110, "Item to be swapped");
drawText(file_ptr, (rgb){0.25,0.25,0.25}, 20, 100, height - 130, "Sorted item");
selection_sort(array, n, file_ptr, height - 140, square_scale);
*/
// insetion sort
// draw_text(file_ptr, (rgb){0,0,0}, 40, 0, height -50, "Insertion Sort");
// draw_line(file_ptr, (rgb){0,0,0}, 2, height -52 , width -2, height -52, 1);
// draw_text(file_ptr, (rgb){0,1,0}, 20, 100, height - 70, "Unsorted item");
// draw_text(file_ptr, (rgb){0,0,1}, 20, 100, height - 90, "Key");
// draw_text(file_ptr, (rgb){1,0,0}, 20, 100, height - 110, "Item to be moved");
// draw_text(file_ptr, (rgb){0.25,0.25,0.25}, 20, 100, height - 130, "Sorted item");
// insertion_sort(array, n, file_ptr, height - 140, square_scale);
// bubble sort
drawText(file_ptr, (rgb){0,0,0}, 40, 0, height -50, "Bubble Sort");
drawLine(file_ptr, (rgb){0,0,0}, 2, height -52 , width -2, height -52, 1);
drawText(file_ptr, (rgb){0,1,0}, 20, 100, height - 70, "Unsorted item");
drawText(file_ptr, (rgb){0,0,1}, 20, 100, height - 90, "Current item (bubble)");
drawText(file_ptr, (rgb){1,0,0}, 20, 100, height - 110, "Correct position of the bubble");
drawText(file_ptr, (rgb){0.25,0.25,0.25}, 20, 100, height - 130, "Sorted item");
bubble_sort(array, n, file_ptr, height - 140, square_scale);
fprintf(file_ptr, "showpage\n");
fprintf(file_ptr, "%%%%EOF");
fclose(file_ptr);
char str1[10] ;
char str2[7] ;
strcpy(str1, consoleCommand);
strcpy(str2, file_path);
strcat(str1, str2);
system(str1);
//printf("%s", str1);*/
return 0;
}
|
C
|
#include "internal.h"
/// <summary>
/// Downscale the image by half and write the result to the output.
/// </summary>
/// <param name="image"> IN: Image to downscale. </param>
/// <param name="output"> OUT: Downscaled image. </param>
/// <returns> 1 IF generation was successful, ELSE 0. </returns>
int ethsift_downscale_half(struct ethsift_image image, struct ethsift_image output){
int srcW = image.width, srcH = image.height;
int dstW = output.width, dstH = output.height;
for (int r = 0; r < dstH; r++) {
for (int c = 0; c < dstW; c++) {
int ori_r = r << 1;
int ori_c = c << 1;
output.pixels[r * dstW + c] = image.pixels[ori_r * srcW + ori_c];
inc_read(1, float);
inc_write(1, float);
}
}
return 1;
}
|
C
|
#include <gb/gb.h>
#include <stdio.h>
#include "sprites.c"
struct Box {
int size;
int x;
int y;
int vx;
int vy;
};
void updatePoint(struct Box *b) {
b->x += b->vx;
b->y += b->vy;
if (b->x > SCREENWIDTH - b->size || b->x < 0) {
b->vx = b->vx * -1;
}
if (b->y > SCREENHEIGHT || b->y < 0 + b->size) {
b->vy = b->vy * -1;
}
}
void main() {
struct Box b = {8, 50, 50, 1, 1};
// init sprite stuff
set_sprite_data(0, sprite_size, sprite_data);
set_sprite_tile(0,0);
move_sprite(0, 8, 8);
SHOW_SPRITES;
while (!0) {
set_sprite_tile(0, 0);
set_sprite_prop(0,0);
move_sprite(0, b.x + b.size, b.y + b.size);
updatePoint(&b);
wait_vbl_done();
}
}
|
C
|
#include <unistd.h>
void ft_print_alphabet(void)
{
write(1, "abcdefghijklmnopqrstuvwxyz", 26);
}
void ft_print_alphabet_1(void)
{
char i = 'a';
while (i <= 'z')
{
write(1, &i, 1);
i++;
}
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* parsing.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: thflahau <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/03/20 15:46:19 by thflahau #+# #+# */
/* Updated: 2019/04/12 14:50:30 by thflahau ### ########.fr */
/* */
/* ************************************************************************** */
#include "../include/ft_ls.h"
void ft_add_slash_to_path(t_list *list)
{
char *ptr;
while (list != NULL)
{
if (list->name != NULL)
{
ptr = list->name;
list->name = ft_strjoin(list->name, "/");
free((void *)ptr);
}
list = list->next;
}
}
void ft_get_single_files_details(t_parsing *ptr, char const *str)
{
t_stat buffer;
lstat(str, &buffer);
ft_append(&ptr->sinfile, str, ft_fast_strlen(str), &buffer);
}
void ft_are_valid_directories(t_parsing *parsing)
{
DIR *dir;
t_list *ptr;
ptr = parsing->list;
while (ptr != NULL)
{
if ((dir = opendir(ptr->name)) != NULL)
closedir(dir);
else
{
if (errno != ENOTDIR)
{
write(1, "ft_ls: ", 7);
perror(ptr->name);
}
else if (ptr->name[ft_strlen(ptr->name) - 1] == '/')
ft_printf("ft_ls: %s: Not a directory\n", ptr->name);
else
ft_get_single_files_details(parsing, ptr->name);
ft_strdel(&ptr->name);
}
ptr = ptr->next;
}
ft_add_slash_to_path(parsing->list);
}
static int8_t ft_parse_options(char const *options, t_parsing **ptr)
{
while (*(++options))
{
if (*options == 'l')
(*ptr)->options |= OPTION_L;
else if (*options == 'a')
(*ptr)->options |= OPTION_A;
else if (*options == 't')
(*ptr)->options |= OPTION_T;
else if (*options == 'r')
(*ptr)->options |= OPTION_R;
else if (*options == 'R')
(*ptr)->options |= OPTION_CR;
else if (*options == 'f')
{
(*ptr)->options |= OPTION_F;
(*ptr)->options |= OPTION_A;
}
else
{
ft_printf("ft_ls: illegal option -- %c\n", *options);
return (EXIT_FAILURE);
}
}
return (EXIT_SUCCESS);
}
int8_t ft_parse_args(int argc, char const **argv, t_parsing *ptr)
{
char *path;
uint16_t index;
index = 0;
while (index++ < argc - 1)
{
if (*argv[index] == '-')
{
if (ft_parse_options(argv[index], &ptr) == EXIT_FAILURE)
return (EXIT_FAILURE);
}
else if (++ptr->size)
if (ft_lst_pushback(&ptr->list, argv[index]) < 0)
return (EXIT_FAILURE);
}
if (!ptr->size)
{
path = ft_strdup(".");
if (ft_lst_pushback(&ptr->list, path) < 0)
return (EXIT_FAILURE);
free((void *)path);
}
return (EXIT_SUCCESS);
}
|
C
|
int main(){
double r,pi=3.141592653589;
scanf("%lf",&r);
printf("%lf %lf\n",pi*r*r,2*pi*r);
return 0;
}
|
C
|
#include <product.h>
#include "button.h"
#define BUTTON_PORT (GPIOA)
#define BUTTON_PIN (0)
#define BUTTON_GPIOMODER_MASK (GPIO_MODER_MODER0_0 | GPIO_MODER_MODER0_1)
#define BUTTON_RCCEN (RCC_AHB1ENR_GPIOAEN)
// private filds
static button_mode buttonMode = BUTTON_MODE_MAX;
static button_callback buttonCallback = NULL;
static bool isButtonInitialized = false;
// callback is required for iterrupt mode
button_status Button_Initialize(button_mode mode, void (*callback)())
{
if (BUTTON_MODE_MAX <= mode || true == isButtonInitialized) {
return BUTTON_ERROR;
}
// enable the clock to GPIO
RCC->AHB1ENR |= BUTTON_RCCEN;
__DSB();
// set pin as input
BUTTON_PORT->MODER &= ~BUTTON_GPIOMODER_MASK;
// set pull up - button is active low
BUTTON_PORT->PUPDR |= GPIO_PUPDR_PUPDR0_0;
// fallthrough
if (BUTTON_MODE_INTERRUPT == mode) {
// set port A as the port on line EXTI0
SYSCFG->EXTICR[0] |= SYSCFG_EXTICR1_EXTI0_PA;
// set sensitive to falling edge
EXTI->FTSR = EXTI_FTSR_TR0;
// set mask for interrupt
EXTI->IMR = EXTI_IMR_IM0;
// enable interrupt
NVIC_EnableIRQ(EXTI0_IRQn);
}
buttonMode = mode;
buttonCallback = callback;
isButtonInitialized = true;
return BUTTON_SUCCESS;
}
button_status Button_IsPushed(bool *isPushed)
{
// function is avaliable for initialized button in pooling mode
if (buttonMode != BUTTON_MODE_POLLING || false == isButtonInitialized) {
return BUTTON_ERROR;
}
// check if the button is pushed
if (BUTTON_PORT->IDR & (1U << BUTTON_PIN)) {
*isPushed = false;
}
else {
*isPushed = true;
}
return BUTTON_SUCCESS;
}
// call button callback when interrupt
__attribute__((interrupt))
void EXTI0_IRQHandler(void)
{
if (EXTI->PR & EXTI_PR_PR0) {
EXTI->PR = EXTI_PR_PR0;
if (NULL != buttonCallback) {
buttonCallback();
}
}
}
|
C
|
#include <stdio.h>
#define MAXLINE 1000
#define YES 1
#define NO 0
char OPENERS[4] = {'(', '{', '[', '\0'};
char CLOSERS[4] = {')', '}', ']', '\0'};
int getline2(char line[], int maxline);
int push(char value);
int index_in_list(char options[], char ch);
char pop();
char top();
int is_empty();
char stack[MAXLINE];
int stack_end = 0;
main()
{
int len, i;
char line[MAXLINE];
int open_index, close_index;
int line_num = 0;
int is_in_comment = NO;
int is_in_string = NO;
int is_in_double_string = NO;
int is_in_one_line_comment = NO;
int is_in_code;
while ((len = getline2(line, MAXLINE)) > 0){
++line_num;
if (is_in_one_line_comment == YES)
is_in_one_line_comment = NO;
for (i = 0; i < len; i++)
{
is_in_code = is_in_comment == NO && is_in_string == NO && is_in_double_string == NO && is_in_one_line_comment == NO;
if (is_in_code){
open_index = index_in_list(OPENERS, line[i]);
close_index = index_in_list(CLOSERS, line[i]);
if (close_index != -1)
{
if (close_index == index_in_list(OPENERS, top()))
{
pop();
}
else
if (close_index != open_index)
printf("close character %c one in line %d:%d mismatch character %c\n", line[i],line_num, i + 1, top());
}
else if (open_index != -1)
{
push(line[i]);
if (line[i] == '\'' || line[i] == '\"')
is_in_string = YES;
}
}
if (line[i] == '\\')
++i;
else if (line[i] == '/' && line[i + 1] == '*')
is_in_comment = YES;
else if (line[i] == '*' && line[i + 1] == '/')
is_in_comment = NO;
else if (line[i] == '\'')
is_in_string = xor(is_in_string);
else if (line[i] == '\"')
is_in_double_string = xor(is_in_double_string);
else if (line[i] == '/' && line[i + 1] == '/')
is_in_one_line_comment = YES;
}
}
while (is_empty() == NO)
{
printf("unclosed brackets %c\n", pop());
}
if (is_in_comment == YES)
printf("unclosed comment\n");
if (is_in_string == YES)
printf("unclosed \' string\n") ;
if (is_in_double_string == YES)
printf("unclosed \" string\n");
return 0;
}
int getline2(char s[],int lim)
{
int c, i, len;
len = i = 0;
while ((c=getchar())!=EOF && c!='\n')
{
if (i < lim - 2)
{
s[i] = c;
++i;
}
++len;
}
if (c == '\n') {
s[i] = c;
++i;
++len;
}
s[i] = '\0';
return len;
}
int push(char value)
{
extern char stack[];
extern int stack_end;
if (stack_end >= MAXLINE)
return -1;
stack[stack_end + 1] = value;
++stack_end;
return 0;
}
char pop()
{
extern char stack[];
extern int stack_end;
--stack_end;
return stack[stack_end + 1];
}
char top()
{
extern char stack[];
extern int stack_end;
return stack[stack_end];
}
int is_empty()
{
extern int stack_end;
if (stack_end == 0)
return YES;
return NO;
}
int index_in_list(char options[], char ch)
{
int i;
for (i = 0; options[i] != '\0'; i++)
if (options[i] == ch)
return i;
return -1;
}
int xor(int exp)
{
if (exp == YES)
return NO;
if (exp == NO)
return YES;
}
|
C
|
#include <linux/engineer_debugs.h>
//获取链表中的某个调试项的节点,num表示第几个
debug_list* engineer_debugs_find_option(const debug_list *head,short num)
{
debug_list *aim = head;
//为0或小于0处理----
num--; //列表从1开始,最小为1
printk("[px_test]enter %s\n",__func__);
while(num--)
{
aim = aim->next;
}
return aim;
}
int engineer_debugs_check_property(char *property)
{
switch(property[0])
{
case 'R':
return COMMAND_RUN;
break;
case 'P':
return COMMAND_PARAMETER;
break;
case 'S':
return COMMAND_SWITCH;
break;
case 'T':
return COMMAND_TRANSFORM;
break;
case 'I':
return COMMAND_INFO;
break;
default :
return -1;
}
}
int engineer_debugs_init(char *device_name, const struct file_operations *ops)
{
//添加到所有链表上,总体管理
debugfs_create_file(device_name,S_IFREG | S_IRWXU |S_IRWXG|S_IRWXO, engineer_debug_root!=NULL?engineer_debug_root:NULL, (void *)0,ops);
return 0;
}
char *engineer_debugs_get_item_info(char *device_name, struct engineer_debug_info *engineer_debug_info)
{
char *buffer;
debug_list *local_run_list = engineer_debug_info->run_list;
debug_list *local_parame_list = engineer_debug_info->parame_list;
debug_list *local_switch_list = engineer_debug_info->switch_list;
debug_list *local_transform_list = engineer_debug_info->transform_list;
debug_list *local_info_list = engineer_debug_info->info_list;
short local_run_num = engineer_debug_info->run_num;
short local_parame_num = engineer_debug_info->parame_num;
short local_switchs_num = engineer_debug_info->switchs_num;
short local_transform_num = engineer_debug_info->transform_num;
short local_info_num = engineer_debug_info->info_num;
printk("get %s item information\n", device_name);
buffer = kmalloc(EN_DE_READ_BUF_SIZE,GFP_KERNEL);
if(buffer == NULL)
{
printk("[px_test]buffer alloc failed...");
return "error";
}
memset(buffer,'\0',EN_DE_READ_BUF_SIZE);
sprintf(buffer,"R=%d,P=%d,S=%d,T=%d,I=%d\n",local_run_num, local_parame_num, local_switchs_num, local_transform_num, local_info_num);
sprintf(buffer+strlen(buffer),"R<");
while(local_run_num--)
{
if(local_run_list == NULL) return "error";
sprintf(buffer+strlen(buffer),"%s:%s|", local_run_list->debug_option.laber, local_run_list->debug_option.property);
printk("[px_test]R sprintf success\n");
if(local_run_list->next != NULL)
{
local_run_list = local_run_list->next;
}
printk("[px_test]next node:%s\n",local_run_list->debug_option.laber);
}
sprintf(buffer+strlen(buffer),"\nP<");
while(local_parame_num--)
{
if(local_parame_list == NULL) return "error";
sprintf(buffer+strlen(buffer),"%s:%s|", local_parame_list->debug_option.laber, local_parame_list->debug_option.property);
printk("[px_test]P sprintf success\n");
if(local_parame_list->next != NULL)
{
local_parame_list = local_parame_list->next;
}
printk("[px_test]next node:%s\n",local_parame_list->debug_option.laber);
}
sprintf(buffer+strlen(buffer),"\nS<");
while(local_switchs_num--)
{
if(local_switch_list == NULL) return "error";
sprintf(buffer+strlen(buffer),"%s:%s|", local_switch_list->debug_option.laber, local_switch_list->debug_option.property);
printk("[px_test]S sprintf success\n");
if(local_switch_list->next != NULL)
{
local_switch_list = local_switch_list->next;
}
printk("[px_test]next node:%s\n",local_switch_list->debug_option.laber);
}
sprintf(buffer+strlen(buffer),"\nT<");
while(local_transform_num--)
{
if(local_transform_list == NULL) return "error";
sprintf(buffer+strlen(buffer),"%s:%s|", local_transform_list->debug_option.laber, local_transform_list->debug_option.property);
printk("[px_test]T sprintf success\n");
if(local_transform_list->next != NULL)
{
local_transform_list = local_transform_list->next;
}
printk("[px_test]next node:%s\n",local_transform_list->debug_option.laber);
}
sprintf(buffer+strlen(buffer),"\nI<");
while(local_info_num--)
{
if(local_info_list == NULL) return "error";
sprintf(buffer+strlen(buffer),"%s:%s|", local_info_list->debug_option.laber, local_info_list->debug_option.property);
printk("[px_test]I sprintf success\n");
if(local_info_list->next != NULL)
{
local_info_list = local_info_list->next;
}
printk("[px_test]next node:%s\n",local_info_list->debug_option.laber);
}
//kfree(buffer);
return buffer;
}
int engineer_debugs_get_status(const debug_list *head, short num)
{
debug_list *aim = engineer_debugs_find_option(head, num);
int (*switchs_addr)(bool);
printk("enter %s, %d\n",__func__,num);
if(head == NULL) return -1;
else if(aim->debug_option.property[0] == 'R')
{
//return times;
printk("get switch status\n");
return 1;
}
else if(aim->debug_option.property[0] == 'P')
{
printk("get parame status\n");
return *(int *)aim->debug_option.addr.parame_addr;
}
else if(aim->debug_option.property[0] == 'S')
{
printk("get switch status\n");
if(aim->debug_option.property[2] == 'p')
return *(int *)aim->debug_option.addr.parame_addr;
else
{
switchs_addr = (int *)(*aim).debug_option.addr.switchs_addr;
return switchs_addr(3);
}
}
else if(aim->debug_option.property[0] == 'T')
{
printk("get transform status\n");
return 1;
}
else if(aim->debug_option.property[0] == 'I')
{
printk("get info status\n");
return 1;
}
else
return -1;
}
struct dentry *engineer_debug_root;
static int __init engineer_debugs_local_init(void)
{
engineer_debug_root = debugfs_create_dir("engineer_debugs", NULL);
if(engineer_debug_root == NULL)
printk("create engineer_debug_root dir failed...\n");
}
subsys_initcall(engineer_debugs_local_init);
|
C
|
#ifndef SPT_LINKEDLIST_H
#define SPT_LINKEDLIST_H
#include "spt_linkedlist_struct.h"
/* Creates an spt_linkedlist in memory and returns a pointer to it
*
* @param node The first node in the new spt_linkedlist
* @return A pointer to a newly created spt_linkedlist with node as its
* first node
*/
spt_linkedlist *spt_linkedlist_init(spt_linkedlist_node *node);
/* Destroys all nodes in the spt_linkedlist and frees up the space in memory
* that they occupied
*
* @param list The spt_linkedlist to be destroyed.
*/
void spt_linkedlist_destroy(spt_linkedlist *list);
/* Returns the number of nodes in the specified spt_linkedlist
*
* @pre The linkedlist terminates
* @param list The spt_linkedlist to get the size of
* @return The number of nodes in the spt_linkedlist
*/
uint16_t spt_linkedlist_get_size(spt_linkedlist *list);
/* Returns the first node in the specified spt_linkedlist
*
* @param list The spt_linkedlist to get the first node from
* @return A pointer to the head node in the spt_linkedlist
*/
spt_linkedlist_node *spt_linkedlist_get_head(spt_linkedlist *list);
/* Returns the last node in the specified spt_linkedlist
*
* @pre The linkedlist terminates
* @param list The spt_linkedlist to get the last node from
* @return A pointer to the last node in the spt_linkedlist
*/
spt_linkedlist_node *spt_linkedlist_get_last(spt_linkedlist *list);
/* Removes the node with the specified str from the spt_linkedlist
*
* @param list The spt_linkedlist to remove the node from
* @param str The value of str within the str_ptr_tuple we want to remove from
* the specified list
* @return True iff the node is successfully removed
*/
bool spt_linkedlist_remove_node_by_str(spt_linkedlist *list, char *str);
/* Sets the head of the linkedlist to the linkedlist's head's next, and returns
* the former head node.
*
* @param list The list to pop the head from
* @return A pointer to the former head item of the list
*/
spt_linkedlist_node *spt_linkedlist_pop(spt_linkedlist *list);
/* Returns the node within the linkedlist that holds the specified str
*
* @param list The linkedlist to obtain the node from
* @param str The str of the node we are trying to find
* @return The str_ptr_tuple with string equal to str. If there is no match
* then returns NULL
*/
spt_linkedlist_node *spt_linkedlist_get_node_by_str(spt_linkedlist *list, char *str);
/* Returns the node at the index within the specified spt_linkedlist
*
* @param list The spt_linkedlist which provides ordering to its nodes
* @param index The numerical index of the tuple to get
* @return The tuple at the specified index within list. If there is no
* match then returns NULL.
*/
spt_linkedlist_node *spt_linkedlist_get_node_by_index(spt_linkedlist *list, uint16_t index);
/* Sets the tuple at the specified index within the linkedlist
*
* @param list The spt_linkedlist which provides ordering to its nodes
* @param index The numerical index of the tuple to change
* @param tuple The new value for the tuple at the specified index
* @return True iff the tuple was successfully set to the new value
*/
bool spt_linkedlist_set_tuple_at_index(spt_linkedlist *list, uint16_t index, str_ptr_tuple *tuple);
/* Adds an spt_linkedlist_node to the specified linkedlist
*
* @param list The list to add the new node to
* @param node The node to add to the specified linkedlist
* @return True iff the node was successfully added to list
*/
bool spt_linkedlist_add(spt_linkedlist *list, spt_linkedlist_node *node);
/* Returns the tuple within the node where the str is equal to the specified str
*
* @param list The list to search within
* @param str The str to search for within the specified list
* @return The tuple within the list which has a str value equal to the str
* param. If no match found, then return NULL
*/
str_ptr_tuple *spt_linkedlist_find_str(spt_linkedlist *list, char *str);
#endif
|
C
|
#include <locale.h>
#include <stdio.h>
#include <stdlib.h>
#include <float.h>
struct Client
{
int id;
float balance;
int gender; // 0: M, 1: F
};
float average_by_gender(struct Client *clients, int gender)
{
float sum = 0.0;
int len_of_gender = 0;
for (int i = 0; i < sizeof(*clients)/sizeof(struct Client); i++)
{
if (clients[i].gender == gender)
{
sum += clients[i].balance;
len_of_gender += 1;
}
}
if (len_of_gender)
{
return sum/len_of_gender;
}
return 0;
}
float highest_by_gender(struct Client *clients, int gender)
{
float highest = -FLT_MAX;
for (int i = 0; i < sizeof(*clients)/sizeof(struct Client); i++)
{
if (clients[i].gender == gender)
{
if (clients[i].balance > highest)
{
highest = clients[i].balance;
}
}
}
return highest;
}
int main()
{
setlocale(LC_ALL, "Portuguese");
struct Client *banco = (struct Client*)malloc(6 * sizeof(struct Client));
char *gender = (char*)malloc(sizeof(char));
for (int i = 0; i < 6; i++)
{
printf("\n%dº Cliente\n", i+1);
printf("Código: ");
scanf("%d", &(banco[i].id));
printf("Saldo: [R$] ");
scanf("%f", &(banco[i].balance));
while (1)
{
printf("Gênero: [M: Masc, F: Fem] ");
scanf("\n%c", gender);
if (*gender == 'M' || *gender == 'm')
{
banco[i].gender = 0;
}
else if (*gender == 'F' || *gender == 'f')
{
banco[i].gender = 1;
}
else
{
printf("Desculpe, opção inválida. Tente novamente.\n");
continue;
}
break;
}
}
free(gender);
gender = NULL;
// A
printf("\nA média do saldo dos homens é R$ %.2f\n", average_by_gender(banco, 0));
printf("A média do saldo das mulheres é R$ %.2f\n", average_by_gender(banco, 1));
// B
float highest = highest_by_gender(banco, 0);
if (highest == -FLT_MAX)
{
printf("Não há clientes registrados do gênero feminino.\n");
}
else
{
printf("\nO maior saldo de mulheres é R$ %.2f\n", highest_by_gender(banco, 0));
}
highest = highest_by_gender(banco, 1);
if (highest == -FLT_MAX)
{
printf("Não há clientes registrados do gênero masculino.\n");
}
else
{
printf("\nO maior saldo de homens é R$ %.2f\n", highest_by_gender(banco, 0));
}
return 0;
}
|
C
|
/*ch6 sum.c*/
#include <stdio.h>
#include <stdlib.h>
int main(){
int number;
int total=0,item=1;
printf("%d. Input a number to be sumed:\n",item);
while(scanf("%d",&number)==1){
total=total+number;
printf("%d. Input a number to be sumed : \n",++item);
}
item--;
printf("\nThere are %d numbers entered,\n",item);
printf("their sum is %d\n",total);
system("PAUSE");
return 0;
}
|
C
|
#include<stdio.h>
#include "struct.h"
#include "array.h"
/**
* Hlavni program.
*/
int main()
{
printf("STRUKTURY\n------------\n");
// vytvoreni objektu
Object o1 = object_ctor(10,"Alice");
Object o2 = object_ctor(20,"Petr");
// vypiseme objekty
print_object(&o1);
print_object(&o2);
printf("------------\nVymena objektu\n------------\n");
object_swap(&o1,&o2);
print_object(&o1);
print_object(&o2);
printf("------------\nKopie objektu\n------------\n");
Object o3 = object_ctor(0, NULL);
item_cpy(&o3, &o1);
print_object(&o3);
// dealokace pameti
object_dtor(&o1);
object_dtor(&o2);
object_dtor(&o3);
//////////////////////////////////////////////////
printf("POLE\n------------\n");
// vytvoreni pole
Array arr = array_ctor(5);
array_print("Nove inicializovane pole\n------------\n", &arr);
Object ao1 = object_ctor(110,"Ananas");
Object ao2 = object_ctor(240,"Broskev");
Object ao3 = object_ctor(80,"Citron");
Object ao4 = object_ctor(60,"Hruska");
Object ao5 = object_ctor(20,"Meloun");
int status = 0;
status = array_insert_item(&arr, &ao1, 0);
if (status == -1)
return -1;
status = array_insert_item(&arr, &ao2, 1);
if (status == -1)
return -1;
status = array_insert_item(&arr, &ao3, 2);
if (status == -1)
return -1;
status = array_insert_item(&arr, &ao4, 3);
if (status == -1)
return -1;
status = array_insert_item(&arr, &ao5, 4);
if (status == -1)
return -1;
array_print("------------\nPole s inicializovanymi polozkami\n------------\n", &arr);
// rozsireni pole - 7 polozek
arr = array_resize(&arr, 7);
array_print("------------\nRozsirene pole\n------------\n", &arr);
// zmenseni pole - 2 polozky
arr = array_resize(&arr, 2);
array_print("------------\nZmensene pole\n------------\n", &arr);
// nastaveni pole na puvodni velikost
arr = array_resize(&arr, 5);
array_print("------------\nRozsirene pole na puvodni velikost\n------------\n", &arr);
// otestujeme, jestli funguje vlozeni prvku na obsazenou polozku
Object ao6 = object_ctor(70, "Jablko");
status = array_insert_item(&arr, &ao6, 1);
printf("%d\n", status);
if (status == -1)
return -1;
array_print("------------\nPole s dalsim prvkem\n------------\n", &arr);
// vkladani za meze pole
printf("------------\nExperiment s vlozenim za meze pole\n------------\n");
Object ao7 = object_ctor(70, "Mandarinka");
status = array_insert_item(&arr, &ao7, 20);
if (status == -1)
{
fprintf(stderr,"Chyba pri vlozeni.\n");
object_dtor(&ao7);
}
// zmenseni pole - 3 prvky
arr = array_resize(&arr, 3);
array_print("------------\nZmensene pole na 3 prvky\n------------\n", &arr);
// vyhledani objektu s nejmensim ID a se zadanym nazvem
printf("------------\nObjekt s nejmensim ID\n------------\n\n");
print_object(&arr.items[array_find_min(&arr)]);
int findID = 240;
printf("------------\nObjekt s ID %d\n------------\n", findID);
print_object(&arr.items[array_find_id(&arr, findID)]);
char* findName = "Broskev";
printf("------------\nObjekt se jmenem %s\n------------\n", findName);
print_object(&arr.items[array_find_name(&arr, findName)]);
// serazeni pole
array_sort_bubble(&arr);
// pripadne: array_sort_select(&arr);
array_print("------------\nSerazene pole\n------------\n", &arr);
// uvolneni pameti
array_dtor(&arr);
return 0;
}
|
C
|
/**
* @file act1.c
* @author NIVESH ([email protected])
* @brief
* @version 0.1
* @date 2021-04-30
*
* @copyright Copyright (c) 2021
*
*/
#include <avr/io.h>
#include "act1.h"
void act1()
{
DDRB |= (1<<PB0);//set the bit PB0
DDRC &= ~(1<<PC0);//clear the bit PD0
DDRD &= ~(1<<PD0);//clear the bit PD1
PORTB |= (1<<PB0);
PORTC |= (1<<PC0);
if(((PINB & (1<<PB0))) && ((PINC & (1<<PC0))))
{
PORTB &= ~(1<<PB0);
}
else if(((PINB & (1<<PB0))) && (!(PINC & (1<<PC0))))
{
PORTB &= ~(1<<PB0);
}
else if((!(PINB & (1<<PB0))) && ((PINC & (1<<PC0))))
{
PORTB &= ~(1<<PB0);
}
else if((!(PINB & (1<<PB0))) && (!(PINC & (1<<PC0))))
{
PORTB |= (1<<PB0);
}
}
|
C
|
#define _GNU_SOURCE
#include "helpers.h"
#include <sys/wait.h>
#include <stdio.h>
#include <errno.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <signal.h>
#define RERROR(_X) \
if (_X == -1) { \
int old_trigger = sigint_catched_runpipe; \
if (sigint_catched_runpipe == 0) { kill(0, SIGINT); } \
sigaction(SIGINT, &old_action, NULL); \
return (old_trigger == 0 ? -1 : 0); \
}
ssize_t read_(int fd, void* buf, size_t count)
{
size_t readed = 0;
ssize_t readCount = 0;
while (readed < count)
{
readCount = read(fd, (char*)buf + readed, count - readed);
if (readCount == -1)
{
return -1;
}
else if (readCount == 0)
{
break;
}
readed += readCount;
}
return readed;
}
ssize_t write_(int fd, void* buf, size_t count)
{
size_t writted = 0;
ssize_t writeCount = 0;
while (writted < count)
{
writeCount = write(fd, (char*)buf + writted, count - writted);
if (writeCount == -1)
{
return -1;
}
writted += writeCount;
}
return writted;
}
ssize_t read_until(int fd, void* buf, size_t count, char delimeter)
{
ssize_t readCount = 0;
size_t readed = 0;
char chr;
char* array = (char*)buf;
while (readed < count)
{
readCount = read_(fd, &chr, 1);
if (readCount < 0)
{
return readCount;
}
if (readCount == 0)
{
break;
}
array[readed++] = chr;
if (chr == delimeter)
{
break;
}
}
return readed;
}
int spawn(const char* file, char* const argv[])
{
int status = 0;
pid_t childPid = -1;
int default_stderr = dup(STDERR_FILENO);
int devNull = open("/dev/null", O_WRONLY);
switch (childPid = fork()) {
case -1:
status = -1;
break;
case 0:
dup2(devNull, STDERR_FILENO);
execvp(file, argv);
default:
while (waitpid(childPid, &status, 0) == -1) {
if (errno != EINTR) {
status = -1;
break;
}
}
break;
}
if (devNull != -1) {
close(devNull);
}
dup2(default_stderr, STDERR_FILENO);
return status;
}
int exec(struct execargs_t* program)
{
pid_t childPid = -1;
switch (childPid = fork()) {
case -1:
break;
case 0:
execvp(program->command, program->args);
exit(EXIT_FAILURE);
}
return childPid;
}
int sigint_catched_runpipe = 0;
void sig_handler_runpiped(int signo)
{
if (signo == SIGINT)
{
sigint_catched_runpipe = 1;
while (wait(NULL) != -1)
{
}
}
}
int runpiped(struct execargs_t** programs, size_t n)
{
struct sigaction new_action;
struct sigaction old_action;
new_action.sa_handler = sig_handler_runpiped;
sigemptyset(&new_action.sa_mask);
new_action.sa_flags = 0;
sigint_catched_runpipe = 0;
sigaction(SIGINT, &new_action, &old_action);
int pipefd[2];
int default_stdin = dup(STDIN_FILENO);
int default_stdout = dup(STDOUT_FILENO);
for (size_t i = 0; i < n; ++i)
{
if (i != 0)
{
RERROR(dup2(pipefd[0], STDIN_FILENO));
RERROR(close(pipefd[0]));
}
if (i != n - 1)
{
RERROR(pipe2(pipefd, O_CLOEXEC))
RERROR(dup2(pipefd[1], STDOUT_FILENO));
RERROR(close(pipefd[1]));
}
else
{
RERROR(dup2(default_stdout, STDOUT_FILENO));
}
RERROR(exec(programs[i]));
}
RERROR(dup2(default_stdin, STDIN_FILENO));
size_t dead_childs = 0;
int status = 0;
int result = 0;
while (dead_childs < n)
{
int cpid = wait(&status);
RERROR(cpid);
if (WIFEXITED(status) && WEXITSTATUS(status) != 0)
{
result = -1;
}
++dead_childs;
}
sigaction(SIGINT, &old_action, NULL);
return result;
}
|
C
|
/**
* start_hp.c
*
* opening screen handler
*/
#include "start_up.h"
#include "../text/text.h"
#include "../battle/battle.h"
#include "../assets/sprite_palette.h"
#include "../assets/bkg_palette.h"
#include "../assets/level_assets/level_assets.h"
/* actions that can be taken and returned */
UINT8 GAME_OVER = 0;
UINT8 START = 1;
UINT8 LEVEL_2 = 2;
UINT8 LEVEL_3 = 3;
UINT8 NEW_GAME = 4;
UINT8 QUIT = 5;
/* option chosen */
UINT8 option;
/* chosen decision */
UINT8 choice = 0;
void opening(void)
{
DISPLAY_OFF;
// set bkg property
set_bkg_palette(0, 1, bkg_palette);
// set sprite properties
set_sprite_palette(0, 2, sprite_palette);
sprite_clean(0);
LETTER_COUNT = 0;
clear_screen();
print("PRESSiA\nTOiSTART\0", 56, 54);
for(i = 0; i < LETTER_COUNT; ++i)
set_sprite_prop(i, 0);
SHOW_BKG;
SHOW_SPRITES;
DISPLAY_ON;
delay(2000);
while(1)
{
if(joypad() & J_A)
{
option = START;
break;
}
}
}
|
C
|
#ifndef _HISTOGRAM_TYPE_H
#define _HISTOGRAM_TYPE_H
/* The functions here come from GSL libaray */
struct histogram {
size_t n ;
double * range ; /* size of range should be size of bin + 1 */
double * bin ;
};
void free_histogram(struct histogram* h)
{
if(h)
{
if(h->range)
free(h->range);
if(h->bin)
free(h->bin);
free(h);
}
}
#endif
|
C
|
// ABC061 B - Counting Roads
#include <stdio.h>
int main(void) {
int N, M;
int roads[51] = { 0 };
scanf("%d %d", &N, &M);
for (int i = 0; i < M; i++) {
int a, b;
scanf("%d %d", &a, &b);
roads[a] += 1;
roads[b] += 1;
}
for (int i = 1; i <= N; i++) {
printf("%d\n", roads[i]);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <unistd.h>
#include <sys/epoll.h>
#include <string.h>
#include <errno.h>
#include<unistd.h>
#include<sys/epoll.h>
#define MAX_EVENTS 5
#define READ_SIZE 10
int main(){
int running =1, event_count, i;
size_t bytes_read;
char read_buffer[READ_SIZE+1];
struct epoll_event event;
struct epoll_event events[MAX_EVENTS];
int epoll_fd = epoll_create(10);
if( epoll_fd == -1){
fprintf(stderr, "Failed to create epoll file descriptor:%d\n",errno);
return 1;
}
event.events = EPOLLIN;
event.data.fd = 0;
if(epoll_ctl(epoll_fd, EPOLL_CTL_ADD, 0, &event)){
fprintf(stderr, "Failed to add fail descriptor to epoll\n");
close(epoll_fd);
return -2;
}
while(running){
printf("\n Polling for input ...\n");
event_count = epoll_wait(epoll_fd, events, MAX_EVENTS, 30000);
printf("%d ready events\n", event_count);
for(i = 0; i < event_count; i++){
printf("Reading file descriptor '%d' --", events[i].data.fd);
bytes_read = read(events[i].data.fd, read_buffer, READ_SIZE);
printf("%zd bytes read.\n", bytes_read);
read_buffer[bytes_read] = '\0';
printf("Read '%s'\n", read_buffer);
if(!strncmp(read_buffer, "stop\n",5)){
running = 0;
}
}
}
if(close(epoll_fd)){
fprintf(stderr, "Failed to close epoll file descriptor\n");
return 2;
}
return 0;
}
|
C
|
#include "UserManage.h"
/*
*注册账号
*参数:用户信息指针
*成功:0,失败:-1
*/
int register_user(user_info* info)
{
if(!info) {
printf("param is NULL in %s\n", __func__);
return -1;
}
if(sqlite3_insert(info) != 0){
printf(" register user failed\n");
return -1;
}
return 0;
}
/**
* 登录验证,验证成功在传入参数结构体填入昵称
* 参数:用户信息结构体地址
* 成功:0,失败:-1
*/
int sign_in(user_info* info)
{
if(!info){
printf("param is NULL in %s\n", __func__);
return -1;
}
user_info* result = sqlite3_find(info->account);
if(!result){
printf("user inexistent\n");
return -1;
}
//核对密码
if(strcmp(info->password, result->password) != 0){
//printf("user password mismatch\n");
return -1;
}else{
printf("user password is match\n");
strcpy(info->nick_name, result->nick_name);
free(result);
result = NULL;
}
return 0;
}
/**
* 注销账号
* 参数:用户信息结构体地址
* 成功:0,失败:-1
*/
int unregister_user(user_info* info)
{
if(!info){
printf("param is NULL in %s\n", __func__);
return -1;
}
if(sqlite3_delete(info) != 0){
printf("delete user info failed\n");
return -1;
}
return 0;
}
/**
* 修改密码或昵称
* 参数:用户信息结构体
* 成功:0,失败:-1
*/
int updata_user_info(user_info* info)
{
if(!info){
printf("param is NULL in %s\n", __func__);
return -1;
}
int ret = -1;
if(info->password[0] == 0){
ret = sqlite3_update(info, NICK_NAME);
}else if(info->nick_name[0] == 0){
ret = sqlite3_update(info, PASSWORD);
}else{
//其他情况不处理
}
if(ret != 0){
printf("update user info failed\n");
}
return ret;
}
#if 0
/*test code*/
void test(char* test_name)
{
if(!test_name){
printf("param is NULL in %s\n", __func__);
return;
}
printf("%s\n", test_name);
user_info info = {
"1454865804",
"1234567890",
"ydszze"
};
do{
//注册
//无效数据
if(register_user(NULL) != -1){
break;
}
printf("1\n");
//正常数据
if(register_user(&info) != 0){
break;
}
printf("2\n");
//登录
//有效数据
if(sign_in(&info) != 0){
break;
}
printf("3\n");
//错误密码
info.password[0] = 5;
if(sign_in(&info) != -1){
break;
}
printf("4\n");
//修改密码
memset(info.nick_name, 0, sizeof(info.nick_name));
if(updata_user_info(&info) != 0){
break;
}
printf("5\n");
//删除账号
if(unregister_user(&info) != 0){
break;
}
printf("6\n");
}while(0);
}
int main(void)
{
test("test1:");
return 0;
}
#endif
|
C
|
#include <stdio.h>
int main(int argc, char *argv[])
{
int a, b = 2, c = 5;
for(a = 1; a < 4; a++)
{
switch(a)
{
b = 99; // 永远不会被用到
case 2:
printf("c is %d\n", c);
break;
default:
printf("a is %d\n", a);
case 1:
printf("b is %d\n", b);
break;
}
}
//b is 2
//c is 5
//a is 3
//b is 2
return 0;
}
|
C
|
/*
spamdyke -- a filter for stopping spam at connection time.
Copyright (C) 2015 Sam Clippinger (samc (at) silence (dot) org)
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as
published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <string.h>
#include "spamdyke.h"
#include "base64.h"
/*
* These algorithms are described in RFC 2045.
*/
/*
* Expects:
* destination == a preallocated buffer
* size_destination == the max size of destination
*
* Return value:
* length of the data added to destination, not counting null termination
*/
int base64_encode(unsigned char *destination, int size_destination, unsigned char *source, int strlen_source)
{
int return_value;
int i;
int j;
char *alphabet = ALPHABET_BASE64;
int dest_index[4];
return_value = 0;
i = 0;
while ((i < strlen_source) &&
(return_value < size_destination))
{
for (j = 0; j < 4; j++)
dest_index[j] = -1;
if (i < strlen_source)
{
dest_index[0] = (source[i] & 0xFC) >> 2;
dest_index[1] = (source[i] & 0x03) << 4;
}
if ((i + 1) < strlen_source)
{
dest_index[1] |= (source[i + 1] & 0xF0) >> 4;
dest_index[2] = (source[i + 1] & 0x0F) << 2;
}
if ((i + 2) < strlen_source)
{
dest_index[2] |= (source[i + 2] & 0xC0) >> 6;
dest_index[3] = source[i + 2] & 0x3F;
}
for (j = 0; j < 4; j++)
if (return_value < size_destination)
destination[return_value++] = (dest_index[j] != -1) ? alphabet[dest_index[j]] : PAD_BASE64;
i += 3;
}
if (return_value < size_destination)
destination[return_value] = '\0';
return(return_value);
}
/*
* Expects:
* destination == a preallocated buffer
* size_destination == the max size of destination
*
* Return value:
* length of the data added to destination, not counting null termination
*/
int base64_decode(unsigned char *destination, int size_destination, unsigned char *source, int strlen_source)
{
int return_value;
int i;
int j;
char *alphabet = ALPHABET_BASE64;
char *tmp_match;
int source_index[4];
return_value = 0;
i = 0;
while ((i < strlen_source) &&
(return_value < size_destination))
{
for (j = 0; j < 4; j++)
source_index[j] = -1;
j = 0;
while ((j < 4) &&
((i + j) < strlen_source))
/* If necessary, this could be made faster with an ASCII->index lookup table instead of using strchr(). */
if ((tmp_match = strchr(alphabet, source[i + j])) != NULL)
{
source_index[j] = tmp_match - alphabet;
j++;
}
else
i++;
if ((return_value < size_destination) &&
(source_index[0] != -1))
destination[return_value++] = ((source_index[0] & 0x3F) << 2) | ((source_index[1] != -1) ? ((source_index[1] & 0x30) >> 4) : 0);
if ((return_value < size_destination) &&
(source_index[1] != -1))
destination[return_value++] = ((source_index[1] & 0x0F) << 4) | ((source_index[2] != -1) ? ((source_index[2] & 0x3C) >> 2) : 0);
if ((return_value < size_destination) &&
(source_index[2] != -1))
destination[return_value++] = ((source_index[2] & 0x03) << 6) | ((source_index[3] != -1) ? (source_index[3] & 0x3F) : 0);
i += 4;
}
if ((return_value > 0) &&
(destination[return_value - 1] == '\0'))
return_value--;
else if (return_value < size_destination)
destination[return_value] = '\0';
return(return_value);
}
|
C
|
#include <stdio.h>
int main()
{
int marks;
printf("Please enter your marks: ");
scanf("%d", &marks);
if (marks >= 80){
printf("Your grade is A+!\n");
}
else if (marks >= 70){
printf("Your grade is A!\n");
}
else if (marks >= 60){
printf("Your grade is A-!\n");
}
else if (marks >= 50){
printf("Your grade is B!\n");
}
else if (marks >= 40){
printf("Your grade is C!\n");
}
else if (marks >= 33){
printf("Your grade is D!\n");
}
else{
printf("Your grade is F!\n");
}
return 0;
}
|
C
|
#include "controller.h"
#include "zone_monitor.h"
#include "relay.h"
#include "furnace_power_sensor.h"
#include <string.h>
static uint16_t timer_remaining; // in seconds
static void (*msg_sender)(const void *data, const size_t data_len);
void furnace_controller_init(
void (*msg_sender_fn)(const void *data, const size_t data_len)
) {
msg_sender = msg_sender_fn;
furnace_timer_cancel();
}
FurnaceStatus furnace_get_status() {
FurnaceStatus status;
status.timer_remaining = timer_remaining;
status.furnace_powered = is_furnace_power_on();
status.zone_state = ZONE_STATE_UNKNOWN;
if (status.timer_remaining == 0) {
// timer should be inactive, so only the zone monitor is relevant
if (is_zone_active()) {
status.zone_state = ZONE_STATE_ACTIVE;
} else {
status.zone_state = ZONE_STATE_INACTIVE;
}
}
return status;
}
void furnace_timer_start(const uint16_t duration_seconds) {
// don't allow the timer to be started for a duration that's too long
if (duration_seconds <= TIMER_MAX) {
relay_on();
timer_remaining = duration_seconds;
}
}
void furnace_timer_cancel() {
relay_off();
timer_remaining = 0;
}
void furnace_update_timer() {
if (timer_remaining > 0) {
timer_remaining -= 1;
if (timer_remaining == 0) {
furnace_timer_cancel();
}
}
}
void furnace_handle_incoming_msg(const void *msg_ptr, const size_t len) {
// by convention, all commands MUST have their first byte be a char
// this will determine the type of structure received
const char cmd_byte = ((char *)msg_ptr)[0];
if (cmd_byte == 'S') {
FurnaceStartTimerCommand fst;
memcpy(&fst, msg_ptr, len);
furnace_timer_start(fst.duration_seconds);
} else if (cmd_byte == 'C') {
furnace_timer_cancel();
}
}
void furnace_send_status() {
FurnaceStatus status = furnace_get_status();
msg_sender((const void *)&status, sizeof(FurnaceStatus));
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* test.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: evgenkarlson <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/05/12 12:33:14 by evgenkarlson #+# #+# */
/* Updated: 2020/05/12 10:51:23 by evgenkarlson ### ########.fr */
/* */
/* ************************************************************************** */
/* команда для компиляции и одновременного запуска */
/* */
/* gcc -Wall -Werror -Wextra test.c && chmod +x ./a.out && ./a.out */
/* ************************************************************************** */
/*
* ===-----------------------------------------------------------------------===
*
* • Написать функцию "ft_decrypt". Эта функция примет строку символов в
* качестве параметра и разделит ее на массив структуры "t_perso". Массив будет
* разделен 0.
*
* • Эта функция будет прототипирована следующим образом:
* t_perso **ft_decrypt(char *str)
*
* • Строка, переданная в качестве параметра, будет отформатирована следующим
* образом:
* Age|Name;Age2|Name2;Age3|Name3
*
* • Структура "t_perso" должна сказать вам что-то! Неуказанные поля не будут
* инициализированы. Подумайте о том, чтобы включить "ft_perso.н "в свой".с"!
*
* ===-----------------------------------------------------------------------===
*/
#include <unistd.h> /* Подключаем библиотеку содержащую функцию "write" */
#include <stdlib.h> /* Подключаем библиотеку содержащую функцию "malloc" */
#include "ft_perso.h" /* Подключаем библиотеку содержащую структуру "t_perso" */
/* ************************************************************************** */
void ft_putchar(char c) /* Функция печати символа */
{
write(1, &c, 1);
}
/* ************************************************************************** */
void ft_putstr(char *str) /* Функция печати строки */
{
while(*str)
ft_putchar(*str++);
}
/* ************************************************************************** */
void ft_putnbr(int nb) /* Функция печати числа */
{
int temp;
int size;
size = 1;
if (nb < 0)
{
ft_putchar('-');
nb = -nb;
}
if (nb == -2147483648)
{
ft_putchar('2');
nb = 147483648;
}
temp = nb;
while ((temp /= 10) > 0)
size *= 10;
temp = nb;
while (size)
{
ft_putchar((char)((temp / size)) + 48);
temp %= size;
size /= 10;
}
}
/* ************************************************************************** */
void ft_put_struct(t_perso *perso)/* Функция печати содержимого струкуры */
{
ft_putnbr(perso->age);
ft_putchar('\t');
ft_putstr(perso->name);
}
/* ************************************************************************** */
void ft_put_tab_struct(t_perso **tab)/* Функция печати содержимого массива со струкурами */
{
while (*tab)
{
ft_put_struct(*tab++);
write(1, "\n", 1);
}
}
/* ************************************************************************** */
int ft_isspace(char c) /* Функция узнает является ли наш символ разделителем между словами */
{
return (c == ' ' || c == '\t' || c == '\n' || c == '|' || c == ';');/* Если наш символ это пробел или табуляция,
* или концом строки то завершаем функцию и возвращаем '1'.
* Если это какой то др символ то завершаем функцию и возвращаем '0' */
}
int ft_wordlen(char *str) /* Функция узнает длинну ближайшего слова */
{
int i;
i = 0;
while (*str && !(ft_isspace(*str++)))
{
i++;
}
return (i);
}
char *ft_get_name(char *str) /* Функция находит первое имя из строки, выделяет память для дубликата
* и возвращает его адрес */
{ int j;
char *name;
j = 0;
while(*str && (ft_isspace(*str) || (*str >= '0' && *str <= '9')))
str++;
name = (char *)malloc(sizeof(char) * ft_wordlen(str) + 1);
while (*str && !(ft_isspace(*str)) && ((*str >= 'a' && *str <= 'z') || (*str >= 'A' && *str <= 'Z')))
name[j++] = *str++;
name[j] = '\0';
return (name);
}
int ft_get_age(char *str) /* Функция находит в строке первые попавшееся цифровые символы указывающее
* на возраст, переводит их в целое число и его возвращает */
{
int age;
age = 0;
while (*str >= '0' && *str <= '9')
age = (age * 10) + (*str++ - '0');
return (age);
}
t_perso **ft_decrypt(char *str) /* функция анализирует строку и вычисляет сколько нужно будет создать экземпляров структуры
* "t_perso" чтобы сохранить в каждом из них данные о возрасте и имени из строки каждого */
{
t_perso **tab; /* Обьявим указатель на указатель типа структуры "t_perso" чтобы позже сохранить туда адрес
* выделеной нами памяти под массив указателей типа "t_perso", которые уже будут хранить
* адреса самих структур (память для них мы тоже выделим. Для каждой структуры отдельно) */
int numstructs; /* Обьявим целочисленную переменную для хранения информации о количестве нужных структур */
int j; /* Обьявим целочисленную переменную для счетчика */
numstructs = 0; /* Инициализируем переменную, для хранения информации о количестве нужных структур, нулем */
j = 0; /* Инициализируем счетчик нулем */
while (str[j]) /* Анализируем строку чтобы посчитать количестов нужных экземпляров */
{
if (str[j] && str[j++] == '|')
numstructs++;
}
if (numstructs > 0) /* Если внутри строки данные найдены то запускем код внутри скобок */
{
j = 0; /* Обнуляем счетчик "j" чтобы использовать его в другой части кода */
if ((tab = (t_perso **)malloc(sizeof(t_perso *) * (numstructs + 1))) == ((void *)0))/* Выделяем память под массив указателей на указатели */
return ((void *)0); /* Если память не выделилась то завершаем функцию и возвращаем нулевой указатель */
while (j < numstructs) /* Запускаем цикл который запишет в каждую ячейку массива указателей адреса экземпляров структур типа "t_perso" */
{
if ((*(tab + j) = (t_perso *)malloc(sizeof(t_perso))) == ((void *)0)) /* Выделяем память под экземпляры структуры типа "t_perso" */
return ((void *)0); /* Если память не выделилась то завершаем функцию и возвращаем нулевой указатель */
while(*str && (ft_isspace(*str) || !(*str >= '0' && *str <= '9'))) /* Пропускаем все символы которые не являются возрастом */
str++;
(*(tab + j))->age = ft_get_age(str); /* Получаем число с возрастом из строки и сохраняем его */
while(*str && (ft_isspace(*str) || (*str >= '0' && *str <= '9'))) /* Пропускаем все символы которые не являются именем */
str++;
(*(tab + j))->name = ft_get_name(str); /* Получаем дубликат имени из строки и сохраняем его адресс */
j++; /* Переходим к след ячейке массива указателей */
}
return (tab); /* Завершаем функцию и возвращаем адрес массива с адресами экземпляров структуры "t_perso" */
}
return ((void *)0); /* Если внутри строки данные не найдены то завершаем функцию и возвращаем нулевой указатель */
}
int main(void)
{
char *arr = "28 JohnRembo; 21|ChakNoris; 27|YourMom"; /* Создадим строку с возрастами и Именами чтобы разобрать это на состовляющие и разложить */
ft_put_tab_struct(ft_decrypt(arr)); /* Отправляем адресс строки в функцию "ft_decrypt" для разложения строки, Эта функция должна вернуть адресс
* массива с адресами экземпляров структуры "t_perso" в которые функция "ft_decrypt" разложила строку. Этот
* адрес мы отправим в функцию "ft_put_tab_struct" которая напечатает содержимое каждой структуры */
return (0);
}
|
C
|
int main(int argc, char* argv[])
{ int i,len,n;
char str[256],str2[256];
scanf("%d",&n);
while(n>0)
{
scanf("%s",str);
len=strlen(str);
for(i=0;i<len;i++)
{
if(str[i]=='A')
str2[i]='T';
if(str[i]=='T')
str2[i]='A';
if(str[i]=='C')
str2[i]='G';
if(str[i]=='G')
str2[i]='C';
}
str2[len]='\0';
printf("%s\n",str2);
n--;
}
return 0;
}
|
C
|
/*--------------------------------------------------------------------- *
* Arquivo: moveServo.c *
* Criador: João Pedro Melquiades Gomes Mat: 118110077 *
* Descrição: Arquivo com a definição da função moveServo() *
*--------------------------------------------------------------------- */
#include "moveServo.h"
/*
* Função: moveServo()
* Parâmetros: Inteiro de 8 bits com o volume atual de respiração
* Descrição: De acordo com a frequência passada para a função, o retorno da
* função será o dutyCycle responsável pela posição do servo motor naquele
* momento
*/
uint16_t moveServo(uint8_t volume){
static uint8_t count = 0; //Variável que irá definir quando a configuração de LEDs irá mudar
static uint16_t pwm = 12; //~5% duty cycle (0.05 * 256)
if(count < volume){ //Movimenta de acordo com o volume de ar injetado
pwm += 1;
count++;
}else{
pwm -= 1;
if(pwm == 12)
count = 0;
}
return pwm;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "pcx.h"
void read_header(FILE *fp) {
PCX_Header header;
fread(&header, sizeof(PCX_Header), 1, fp);
}
RGBColor* read_palette(FILE *fp) {
fseek(fp, -768, SEEK_END);
RGBColor *extended_palette = malloc(256 * 3);
fread(extended_palette, 3, 256, fp);
return extended_palette;
}
RGBColor* read_pcx_palette(char* path) {
FILE *fp = fopen(path, "r");
RGBColor *palette = read_palette(fp);
fclose(fp);
return palette;
}
|
C
|
/*
* mm-naive.c - The fastest, least memory-efficient malloc package.
*
* In this naive approach, a block is allocated by simply incrementing
* the brk pointer. A block is pure payload. There are no headers or
* footers. Blocks are never coalesced or reused. Realloc is
* implemented directly using mm_malloc and mm_free.
*
* NOTE TO STUDENTS: Replace this header comment with your own header
* comment that gives a high level description of your solution.
*/
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <unistd.h>
#include <string.h>
#include "mm.h"
#include "memlib.h"
/*********************************************************
* NOTE TO STUDENTS: Before you do anything else, please
* provide your team information in the following struct.
********************************************************/
team_t team = {
/* Team name */
"Team48",
/* First member's full name */
"Joshua Kennedy",
/* First member's NetID */
"jfk7486",
/* Second member's full name (leave blank if none) */
"Christoph Sauter",
/* Second member's NetID */
"cds6792"
};
/* Private global variables */
static char *heap_listp; /* Pointer to list */
static char *free_headp; /* Pointer to head of free list */
/* Basic constants and some macros */
#define WSIZE 4 /* Word and header/footer size */
#define DSIZE 8 /* Double word size */
#define CHUNKSIZE (1<<12) /* Extend heap by this amount */
#define MIN_BLK_SIZE 24 /* Minimum block size for overhead */
#define MAX(x,y) ((x) > (y) ? (x) : (y)) /* returns max value */
/* Pack a size and the allocated bit into a single word */
#define PACK(size, alloc) ((size) | (alloc))
/* Read and write a word at address p */
#define GET(p) (*(unsigned int *)(p))
#define PUT(p, val) (*(unsigned int *)(p) = (val))
/* Read the size and allocated bit from address p */
#define GET_SIZE(p) (GET(p) & ~0x7)
#define GET_ALLOC(p) (GET(p) & 0x1)
/* Returns pointers to block header/footer */
#define HEADERP(bp) ((char *)(bp) - WSIZE)
#define FOOTERP(bp) ((char *)(bp) + GET_SIZE(HEADERP(bp)) - DSIZE)
/* Return block pointers of next/previous block */
#define NEXT_BLKP(bp) ((char *)(bp) + GET_SIZE(((char *)(bp) - WSIZE)))
#define PREV_BLKP(bp) ((char *)(bp) - GET_SIZE(((char *)(bp) - DSIZE)))
/* Return block pointers of next free block in free block list */
#define NEXT_FREE_BLKP(bp) ((void*)GET(bp + DSIZE))
#define PREV_FREE_BLKP(bp) ((void*)GET(bp))
/* Set next and prev pointers for free block list */
//#define SET_NEXT(bp, ptr) (PUT((bp) + DSIZE, (long)(ptr)))
//#define SET_PREV(bp, ptr) (PUT((bp), (long)(ptr)))
/* Return block pointers of next/previous free block */
//#define NEXT_FREE_BLKP(bp) ((char*)(bp) + (char*)(bp))
//#define PREV_FREE_BLKP(bp) ((char*)(bp) + ((char*)(bp) + DSIZE))
/* Set next/prev address pointers */
#define SET_NEXT(bp, addr) ((*(void**)(bp + DSIZE)) = (addr))
#define SET_PREV(bp, addr) ((*(void**)(bp)) = (addr))
/* single word (4) or double word (8) alignment */
#define ALIGNMENT 8
/* rounds up to the nearest multiple of ALIGNMENT */
#define ALIGN(size) (((size) + (ALIGNMENT-1)) & ~0x7)
#define SIZE_T_SIZE (ALIGN(sizeof(size_t)))
/* Function definitions */
static void* extend_heap(size_t words);
static void place(void* bp, size_t asize);
static void* find_fit(size_t asize);
static void* coalesce(void* bp);
static void remove_block(void* bp);
static void add_block(void* bp);
/* Functions for debugging */
static void printb(void* bp);
static void check_heap();
static void real_check_heap();
/* Debugging booleans */
#define db1 0
#define db2 1
/*
* mm_init - initialize the malloc package.
*/
int mm_init(void)
{
if (db1) printf("Running mm_init...\n");
/* Create initial empty heap */
if ((heap_listp = mem_sbrk(4*WSIZE)) == (void *)-1) return -1;
PUT(heap_listp, 0); /* Alignment padding */
PUT(heap_listp + (WSIZE), PACK(DSIZE, 1)); /* Header for first block in heap */
PUT(heap_listp + (DSIZE), PACK(DSIZE, 1)); /* Footer for first block in heap */
PUT(heap_listp + (3*WSIZE), PACK(0, 1)); /* Header for last byte in heap */
heap_listp += DSIZE;
free_headp = 0;
if (db1) printf("Creating initial free block by calling extend_heap...\n");
/* Create initial free block by extending the heap by CHUNKSIZE */
if (extend_heap(CHUNKSIZE/WSIZE) == NULL) return -1;
if (db1) printf("Heap initialized\n");
//if (db1) check_heap();
return 0;
}
/*
* mm_malloc - Allocate a block by incrementing the brk pointer.
* Always allocate a block whose size is a multiple of the alignment.
*/
void *mm_malloc(size_t size)
{
size_t asize; /* Adjusted block size */
size_t extendsize; /* Amount to extend heap if no fit */
char *bp;
if (db2) printf("Call to malloc...\n");
//if (db2) if (size == 72) check_heap();
if (db2) printf("size = %d\n", size);
//if (db2) check_heap();
//if (db2) real_check_heap();
/* Ignore stupid requests */
if (size <= 0) return NULL;
/* Adjust block size for overhead and alignment requirements */
if (size <= DSIZE) {
asize = MIN_BLK_SIZE;
} else {
asize = DSIZE * ((size + (DSIZE) + (DSIZE-1)) / DSIZE );
}
/* Search the free list for a fit */
if ((bp = find_fit(asize)) != NULL) {
place(bp, asize);
return bp;
}
/* If no fit has been found, get more memory and place the block at the end */
extendsize = MAX(asize, CHUNKSIZE);
if ((bp = extend_heap(extendsize/WSIZE)) == NULL) return NULL;
place(bp, asize);
return bp;
}
/*
* mm_free - Freeing a block does nothing.
*/
void mm_free(void *ptr)
{
size_t size = GET_SIZE(HEADERP(ptr));
if (db2) printf("Call to free...\n");
PUT(HEADERP(ptr), PACK(size,0));
PUT(FOOTERP(ptr), PACK(size,0));
coalesce(ptr);
}
/*
* mm_realloc - Implemented simply in terms of mm_malloc and mm_free
*/
void *mm_realloc(void *ptr, size_t size)
{
/* If given NULL pointer, redirect to mm_malloc */
if (ptr == NULL) {
return mm_malloc(size);
} else if (size == 0) {
mm_free(ptr);
return NULL;
} else {
size_t oldsize = GET_SIZE(HEADERP(ptr));
void* newptr = mm_malloc(size);
if (newptr == NULL) return NULL; /* If, for some reason, malloc fails */
/* Need to copy data */
if (size < oldsize) oldsize = size;
memcpy(newptr, ptr, oldsize);
mm_free(ptr);
return newptr;
}
}
/*
* extend_heap: extend heap by adding free block to end of it
*/
static void *extend_heap(size_t words) {
char *bp;
size_t size;
if (db1) printf("Running extend_heap...\n");
/* Allocate an even number of words to maintain alignment */
size = (words%2) ? (words+1) * WSIZE : words * WSIZE;
if ((long)(bp = mem_sbrk(size)) == -1) return NULL;
/* Initialize free block header/footer and the epilogue header */
PUT(HEADERP(bp), PACK(size,0)); /* New block header */
PUT(FOOTERP(bp), PACK(size,0)); /* New block footer */
PUT(HEADERP(NEXT_BLKP(bp)), PACK(0,1)); /* New epilogue header */
/* Check if setting the first/only node or not
if (free_headp == 0) {
SET_NEXT(bp, 0);
SET_PREV(bp, 0);
if (db1) printf("Extend_heap completed.\n");
if (db1) printb(bp);
return bp;
} else {
if (db1) printf("Extend heap completed, coalescing...\n");
return coalesce(bp);
}
*/
return coalesce(bp);
}
/*
* place: place block at bp with size asize
*/
static void place(void *bp, size_t asize) {
size_t csize = GET_SIZE(HEADERP(bp));
//if (db1) printf("place working...\n");
//if (db1) printb(bp);
if (db2) printf("place(%p, %d)\n", bp, asize);
if (db2) printb(bp);
if ((csize - asize) >= (MIN_BLK_SIZE)) {
if (db2) printf("if\n");
/*
void* tmp_next = NEXT_FREE_BLKP(bp);
void* tmp_prev = NEXT_FREE_BLKP(bp);
*/
PUT(HEADERP(bp), PACK(asize,1));
PUT(FOOTERP(bp), PACK(asize,1));
remove_block(bp);
bp = NEXT_BLKP(bp);
PUT(HEADERP(bp), PACK(csize-asize,0));
PUT(FOOTERP(bp), PACK(csize-asize,0));
/*
SET_NEXT(bp, tmp_next);
SET_PREV(bp, tmp_prev);
SET_NEXT(tmp_prev, bp);
if (tmp_next != 0) SET_PREV(tmp_next, bp);
*/
coalesce(bp);
} else {
if (db2) printf("else\n");
PUT(HEADERP(bp), PACK(csize,1));
PUT(FOOTERP(bp), PACK(csize,1));
remove_block(bp);
}
//if (db1) printf("place done working\n");
}
/*
* find_fit: find first free block in list of size asize
*/
static void *find_fit(size_t asize) {
void *bp;
/* Loops through all blocks in list until large enough block is found */
for (bp = free_headp; bp != 0; bp = NEXT_FREE_BLKP(bp)) {
if (asize <= GET_SIZE(HEADERP(bp))) {
return bp;
}
}
return NULL; /* Couldn't find any fit */
}
/*
* remove_block: removes block from free list and keeps list intact
*/
static void remove_block(void* bp) {
void* prev = PREV_FREE_BLKP(bp);
void* next = NEXT_FREE_BLKP(bp);
if (prev == 0) {
/* bp is first block in list, set next to free_headp */
free_headp = next;
} else {
/* bp is not first block in list, set prev's next to next */
SET_NEXT(prev, next);
}
/* If bp is not the end of the list, set next's prev to prev */
if (next != 0) SET_PREV(next, prev);
}
/*
* add_block: add block to beginning of free list and maintain list's integrity
*/
static void add_block(void* bp) {
/* Set next to current head */
SET_NEXT(bp, free_headp);
/* If next block exists, set its prev to bp */
if (free_headp != 0) SET_PREV(free_headp, bp);
/* Set bp to current head */
free_headp = bp;
/* Set bp's prev to 0 */
SET_PREV(bp, 0);
}
/*
* coalesce: join free block with its neighbors, if possible
*/
static void *coalesce(void *bp) {
size_t prev_alloc = GET_ALLOC(FOOTERP(PREV_BLKP(bp)));
size_t next_alloc = GET_ALLOC(HEADERP(NEXT_BLKP(bp)));
size_t size = GET_SIZE(HEADERP(bp));
/* Coalesce conditions */
if (prev_alloc && next_alloc) {
/* If both neighbors are allocated, do nothing */
add_block(bp);
return bp;
} else if (prev_alloc && !next_alloc) {
/* If next neighbor free, join them */
size += GET_SIZE(HEADERP(NEXT_BLKP(bp)));
remove_block(NEXT_BLKP(bp));
PUT(HEADERP(bp), PACK(size,0));
PUT(FOOTERP(bp), PACK(size,0));
} else if (!prev_alloc && next_alloc) {
/* If prev neighborn is free, join them */
size += GET_SIZE(HEADERP(PREV_BLKP(bp)));
remove_block(PREV_BLKP(bp));
PUT(FOOTERP(bp), PACK(size,0));
PUT(HEADERP(PREV_BLKP(bp)), PACK(size,0));
bp = PREV_BLKP(bp);
} else {
/* Both neighbors are free, join all of them for one big free block! */
size += GET_SIZE(HEADERP(PREV_BLKP(bp))) + GET_SIZE(FOOTERP(NEXT_BLKP(bp)));
remove_block(PREV_BLKP(bp));
remove_block(NEXT_BLKP(bp));
PUT(HEADERP(PREV_BLKP(bp)), PACK(size,0));
PUT(FOOTERP(NEXT_BLKP(bp)), PACK(size,0));
bp = PREV_BLKP(bp);
}
add_block(bp);
return bp;
}
/*
* printb: prints a block from list
*/
static void printb(void* bp) {
size_t head = GET_SIZE(HEADERP(bp));
size_t foot = GET_SIZE(FOOTERP(bp));
size_t h_alloc = GET_ALLOC(HEADERP(bp));
size_t f_alloc = GET_ALLOC(FOOTERP(bp));
void* next = NEXT_FREE_BLKP(bp);
void* prev = PREV_FREE_BLKP(bp);
if (h_alloc != f_alloc) printf("Alloc bits do not match!\n");
if (head != foot) printf("Header and footer sizes do not match!\n");
if ((size_t)bp % ALIGNMENT) printf("Block not aligned to %d bytes!\n", ALIGNMENT);
printf("%p: head = %d, foot = %d, alloc = %d\n", bp, head, foot, h_alloc);
printf("\tNext = %p, Prev = %p\n", next, prev);
}
/*
* check_heap: prints out status of the heap
*/
static void check_heap() {
void* bp = free_headp;
printf("CHECKING HEAP -----------------------\n");
printf("Head: %p ", bp);
bp = free_headp;
while (bp != 0) {
printb(bp);
bp = NEXT_FREE_BLKP(bp);
}
printf("-------------------------------------\n");
}
/*
* real_check_heap: checks entire heap, even allocated blocks
*/
static void real_check_heap() {
void* bp = heap_listp;
printf("ACTUALLY CHECKING HEAP -----------------------\n");
printf("Head: %p ", bp);
while (GET_SIZE(HEADERP(bp)) != 0) {
printb(bp);
bp = NEXT_BLKP(bp);
}
printf("----------------------------------------------\n");
}
|
C
|
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <michel_getdpids.h>
#define LEN 14 /* buffer size, in PIDs (can't be > 14) */
int main(int argc, char** args) {
pid_t pid, cpid; /* PIDs */
pid_t dpids[LEN]; /* buffer for descendant PIDs */
int i, r; /* control vars */
printf("Test 1 - Single child\n");
/* get the PID */
pid = getpid();
/* print the PID */
printf("My PID is %d\n", pid);
cpid = fork();
if (cpid!=0) { /* in parent! */
printf("Child PID is %d\n", cpid);
/* get and print all descendants */
r = michel_getdpids(pid, dpids, LEN);
printf("Tree has %d process(es)\n", r);
for (i=0;i<r;i++) { printf("%d ", dpids[i]); };
printf("\n");
} else { /* in child! */
sleep(10); /* sleep 10 seconds */
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include "library.h"
#include "liballoc.h"
#include "libinout.h"
#include "global.h"
int compare ( const void *pa, const void *pb )
{
const int *a = *(const int **)pa;
const int *b = *(const int **)pb;
return a[ID_COL] - b[ID_COL];
}
void sort_by_column (int** matrix, int max_lin, int max_col)
{
qsort (matrix, max_lin, sizeof matrix[0], compare);
//printf("ordenei\n");
//print_matrix (matrix, max_lin, max_col);
}
void allels_def (int** matrix, int max_lin, int max_col, int last_col)
{
int i, j, k, m;
int freq1, freq2, freq3, freq4;
m = 0;
j = (max_col - (last_col*2));
while(j < max_col)
{
freq1 = 0;
freq2 = 0;
freq3 = 0;
freq4 = 0;
for(k=0; k < 2; k++)
{
for(i=0; i < max_lin; i++)
{
//printf ("matriz[%d][%d] = rs_markers[%d] = %d\n", i, j, m, matrix[i][j]);
if(matrix[i][j] == 1)
{
freq1++;
}
else if(matrix[i][j] == 2)
{
freq2++;
}
else if(matrix[i][j] == 3)
{
freq3++;
}
else if(matrix[i][j] == 4)
{
freq4++;
}
else if(matrix[i][j] != 0)
{
error_screen (6);
}
}
j++;
}
// ARRUMAR !!!!!!!!!!!!!!!!!!!!!!!!!!!1
//if ( (freq1 != 0) && (freq2 != 0) && (freq3 != 0) ) || ( (freq1 != 0) && (freq2 != 0) && (freq4 != 0) ) || ( (freq2 != 0) && (freq3 != 0) && (freq4 != 0) ) || ( (freq1 != 0) && (freq3 != 0) && (freq4 != 0) )
//{
// error_screen (7);
//}
if( (freq1>=freq2) && (freq1>=freq3) && (freq1>=freq4)) // 1 is major
{
(markers_list[m]).major_allele = 1;
if (freq2 != 0)
{
(markers_list[m]).minor_allele = 2;
}
else if (freq3 != 0)
{
(markers_list[m]).minor_allele = 3;
}
else if (freq4 != 0)
{
(markers_list[m]).minor_allele = 4;
}
}
else if( (freq2>=freq1) && (freq2>=freq3) && (freq2>=freq4)) // 2 is major
{
(markers_list[m]).major_allele = 2;
if (freq1 != 0)
{
(markers_list[m]).minor_allele = 1;
}
else if (freq3 != 0)
{
(markers_list[m]).minor_allele = 3;
}
else if (freq4 != 0)
{
(markers_list[m]).minor_allele = 4;
}
}
else if( (freq3>=freq2) && (freq3>=freq1) && (freq3>=freq4)) // 3 is major
{
(markers_list[m]).major_allele = 3;
if (freq2 != 0)
{
(markers_list[m]).minor_allele = 2;
}
else if (freq1 != 0)
{
(markers_list[m]).minor_allele = 1;
}
else if (freq4 != 0)
{
(markers_list[m]).minor_allele = 4;
}
}
else if( (freq4>=freq2) && (freq4>=freq1) && (freq4>=freq3)) // 4 is major
{
(markers_list[m]).major_allele = 4;
if (freq2 != 0)
{
(markers_list[m]).minor_allele = 2;
}
else if (freq3 != 0)
{
(markers_list[m]).minor_allele = 3;
}
else if (freq1 != 0)
{
(markers_list[m]).minor_allele = 1;
}
}
printf ("\t%s: \t major = %d, minor = %d.\n", ((markers_list[m]).marker_name), (markers_list[m]).major_allele, (markers_list[m]).minor_allele);
m++;
}
printf("\n");
}
int find_family ()
{
trio_list = malloc_vector_trio (trio_list, (num_ind*TRIO_RATE) );
printf("Counting trios:\n");
find_trios(input_matrix, num_ind, num_col_in);
output_vector = malloc_vector_natural_sibs (output_vector, num_trios);
// find_natural_sibs (output_vector, num_trios);
return(num_trios*4 + num_solo);
}
void find_natural_sibs (int ** vector, int max_lin)
{
int i, t;
int v = 0;
int lin = max_lin;
int more_two = FALSE;
for (t=0; t<lin; t++)
{
for (i=t+1; i<lin; i++)
{
while ( ((trio_list[t]).father == (trio_list[i]).father) && ((trio_list[t]).mather == (trio_list[i]).mather) )
{
printf("Achei um irmão natural no trio %d!\n", t);
if ( (trio_list[t]).child2 == NULL )
{
(trio_list[t]).child2 = (trio_list[i]).child1;
if (i != lin)
{
(trio_list[i]).father = (trio_list[lin]).father;
(trio_list[i]).mather = (trio_list[lin]).mather;
(trio_list[i]).child1 = (trio_list[lin]).child1;
(trio_list[i]).child2 = NULL;
}
lin = lin -1;
}
else if ( (trio_list[t]).child2 != NULL )
{
more_two = TRUE;
(vector[v]) = (trio_list[i]).child1;
printf("Vector1[%d] = %p\n", v, (vector[v]));
v = v + 1;
if (i != lin)
{
(trio_list[i]).father = (trio_list[lin]).father;
(trio_list[i]).mather = (trio_list[lin]).mather;
(trio_list[i]).child1 = (trio_list[lin]).child1;
(trio_list[i]).child2 = NULL;
}
lin = lin -1;
}
}
}
if (more_two == TRUE)
{
(vector[v]) = (trio_list[t]).child1;
printf("Vector2[%d] = %p\n", v, (vector[v]));
v = v + 1;
(vector[v]) = (trio_list[t]).child2;
printf("Vector3[%d] = %p\n", v, (vector[v]));
v = v + 1;
(trio_list[t]).father = (trio_list[lin-1]).father;
(trio_list[t]).mather = (trio_list[lin-1]).mather;
(trio_list[t]).child1 = (trio_list[lin-1]).child1;
(trio_list[t]).child2 = NULL;
lin = lin -1;
more_two = FALSE;
}
}
num_trios = lin;
num_solo = v;
}
void find_trios (int** matrix, int max_lin, int max_col) // Coloca os trios na estrutura
{
int i, t;
t = 0;
//printf("Entrei achar trios\n");
for(i=0; i < max_lin; i++)
{
//printf("Linha %d: ID = %d, FT = %d, MT = %d \n", i, matrix[i][ID_COL], matrix[i][FT_COL], matrix[i][MT_COL]);
if ( (matrix[i][ST_COL] == 2) && (matrix[i][FT_COL] != 0) && (matrix[i][MT_COL] != 0) ) // Se nenhum dos pais é zero
{
(trio_list[t]).father = search_id(matrix, max_lin, matrix[i][FT_COL]);
(trio_list[t]).mather = search_id(matrix, max_lin, matrix[i][MT_COL]);
(trio_list[t]).child1 = matrix[i];
(trio_list[t]).child2 = NULL;
(trio_list[t]).mendelian_error = 0;
//printf("Ponteiro f = %p, m = %p\n", (trio_list[t]).father, (trio_list[t]).mather);
if ( ( (trio_list[t]).father != NULL ) && ( (trio_list[t]).mather != NULL ) ) // Se os pais existem na tabela
{
if ( ( ((trio_list[t]).father)[SX_COL] != 1 ) || ( ((trio_list[t]).mather)[SX_COL] != 2 ) )
{
// ERRO DE GENERO DOS PAIS
}
else
{
printf("\tI found the %d trio: c = %d, f = %d, m = %d \n", t + 1, ((trio_list[t]).child1)[ID_COL], ((trio_list[t]).father)[ID_COL], ((trio_list[t]).mather)[ID_COL]);
t++;
}
}
else // Se os pais não existem
{
//printf(" Um ou mais pais não estão na tabela\n");
// Futuro caso dos irmãos;
(trio_list[t]).child1 = NULL;
(trio_list[t]).father = NULL;
(trio_list[t]).mather = NULL;
}
}
else
{
//printf(" Um ou mais pais zerados\n");
}
}
num_trios = t; // conferir
}
int * search_id (int** matrix, int max_lin, int query_id)
{
// No momento busca um por um, pode ser otimizado
//printf("Busca\n");
int test = 0;
while ( matrix[test][ID_COL] < query_id )
{
//printf("Procurando %d, na linha %d achei %d \n", query_id, test, matrix[test][ID_COL] );
test++;
}
if ( matrix[test][ID_COL] == query_id )
{
return(matrix[test]);
}
else
{
return(NULL);
}
}
void output_make()
{
int i, j, t, k, l, s;
int info;
//printf("Entrei em output_make.\n");
printf("\nCounting mendelian erros:\n");
i = 0;
t = -1;
k = input_matrix[num_ind-1][ID_COL] +1; // Numeração IDs irmãos, a partir do ultimo numero de ID + 1;
if (mark_col == ONE_COL)
{
num_col_out = FIXED_COL + covariables + markers;
}
else if (mark_col == TWO_COL)
{
num_col_out = num_col_in;
}
output_matrix = malloc_matrix_int (output_matrix, num_output, num_col_out);
//printf("i = %d ; num_output = %d ; t = %d ; num_trios = %d. \n", i, num_output, t, num_trios);
while( (i<num_output) && (t<num_trios) )
{
//printf("i = %d, iresto4 = %d.\n", i, (i%4));
if (i%4 == 0)
{
t++;
//printf("Linha %d = Filho real do trio %d\n", i, t );
for(j=0; j<FIXED_COL+covariables; j++)
{
output_matrix[i][j] = ((trio_list[t]).child1)[j];
}
if (mark_col == ONE_COL)
{
j=FIXED_COL+covariables;
l=FIXED_COL+covariables;
while (j<num_col_in)
{
if ( ((trio_list[t]).child1)[j] != ((trio_list[t]).child1)[j + 1] )
{
output_matrix[i][l] = HETOR;
}
else if ( ((trio_list[t]).child1)[j] == (markers_list[l-(FIXED_COL+covariables)]).major_allele )
{
output_matrix[i][l] = HOM_MAJ;
}
else if ( ((trio_list[t]).child1)[j] == (markers_list[l-(FIXED_COL+covariables)]).minor_allele )
{
output_matrix[i][l] = HOM_MIN;
}
//printf("J = %d, L = %d, m = %d\n",j, l, output_matrix[i][l]);
j = j + 2;
l++;
}
}
else if (mark_col == TWO_COL)
{
for(j=FIXED_COL+covariables; j<num_col_out; j++)
{
output_matrix[i][j] = ((trio_list[t]).child1)[j];
}
}
/*
for(j=0; j<num_col_out;j++)
{
printf("%d ", output_matrix[i][j]);
}
printf("\n");
*/
i++;
}
else
{
for (s=0; s<NUM_SIBS;s++)
{
//printf("Linha %d = Filho virtual do trio %d\n", i, t );
output_matrix[i+s][FM_COL] = ((trio_list[t]).child1)[FM_COL];
output_matrix[i+s][ID_COL] = k;
k++;
output_matrix[i+s][FT_COL] = ((trio_list[t]).child1)[FT_COL];
output_matrix[i+s][MT_COL] = ((trio_list[t]).child1)[MT_COL];
output_matrix[i+s][SX_COL] = ((trio_list[t]).child1)[SX_COL];
output_matrix[i+s][ST_COL] = NOT_AFT;
for(j=FIXED_COL; j<FIXED_COL+covariables; j++)
{
output_matrix[i+s][j] = ((trio_list[t]).child1)[j];
}
}
j = FIXED_COL + covariables;
l = FIXED_COL + covariables;
while(j<num_col_in) // por coluna
{
info = make_sibs( ((trio_list[t]).father)[j], ((trio_list[t]).father)[j+1], ((trio_list[t]).mather)[j], ((trio_list[t]).mather)[j+1], ((trio_list[t]).child1)[j], ((trio_list[t]).child1)[j+1]);
//printf("Linha(i) = %d, Coluna(j) = %d, Info = %d \n", i, j, info );
if (info == 1) // não informativo
{
//printf("Info = 1\n");
if (mark_col == ONE_COL) // Só para testar
{
for(s=-1; s<NUM_SIBS; s++)
{
output_matrix[i+s][l] = valor_nao_info;
}
}
else if (mark_col == TWO_COL) // Só para testar
{
for(s=-1; s<NUM_SIBS; s++)
{
output_matrix[i+s][j] = valor_nao_info;
output_matrix[i+s][j+1] = valor_nao_info;
}
}
}
else if (info == 2) // sem informação de genotipo
{
if (mark_col == ONE_COL) // Só para testar
{
for(s=-1; s<NUM_SIBS; s++)
{
output_matrix[i+s][l] = valor_sem_genot;
}
}
else if (mark_col == TWO_COL) // Só para testar
{
for(s=-1; s<NUM_SIBS; s++)
{
output_matrix[i+s][j] = valor_sem_genot;
output_matrix[i+s][j+1] = valor_sem_genot;
}
}
}
else if (info == 3) // erro mendeliano
{
if (mark_col == ONE_COL) // Só para testar
{
for(s=-1; s<NUM_SIBS; s++)
{
output_matrix[i+s][l] = valor_erro_mend;
}
}
else if (mark_col == TWO_COL) // Só para testar
{
for(s=-1; s<NUM_SIBS; s++)
{
output_matrix[i+s][j] = valor_erro_mend;
output_matrix[i+s][j+1] = valor_erro_mend;
}
}
(trio_list[t]).mendelian_error = (trio_list[t]).mendelian_error + 1;
printf( "\tTrio = %d, Child = %d, Mendelian error = %d\n", t, (((trio_list[t]).child1)[ID_COL]), (trio_list[t]).mendelian_error);
if ( (lme_on_off == TRUE) && (trio_list[t]).mendelian_error > max_lme)
{
printf( "Essa familia tem erro mendeliano demais = %d\n", (trio_list[t]).mendelian_error );
}
}
else if (info == 0)
{
//printf("Sibs: %d, %d, %d\n", sibs[0], sibs[1], sibs[2]);
if (mark_col == ONE_COL) // Só para testar
{
for (s=0; s<3; s++)
{
if ( (sibs[s] / 10) != (sibs[s] % 10) )
{
output_matrix[i+s][l] = HETOR;
}
else if ( (sibs[s] / 10) == (markers_list[l-(FIXED_COL+covariables)]).major_allele )
{
output_matrix[i+s][l] = HOM_MAJ;
}
else if ( (sibs[s] / 10) == (markers_list[l-(FIXED_COL+covariables)]).minor_allele )
{
output_matrix[i+s][l] = HOM_MIN;
}
}
}
else if (mark_col == TWO_COL) // Só para testar
{
for (s=0; s<NUM_SIBS; s++)
{
output_matrix[i+s][j] = sibs[s] / 10;
output_matrix[i+s][j+1] = sibs[s] % 10;
}
}
}
j = j+2;
l++;
}
i = i+3;
}
}
/*
printf("Imprimindo matriz output.\n");
print_matrix (output_matrix, num_output, num_col_out);
printf("Fim da matriz.\n");
*/
}
int make_sibs( int fa1, int fa2, int ma1, int ma2, int ca1, int ca2)
{
int s1a1, s1a2, s2a1, s2a2, s3a1, s3a2, s4a1, s4a2;
//printf("Na make sibs.\n");
//printf("Pai: %d %d, Mae: %d %d, Filho: %d %d\n", fa1, fa2, ma1, ma2, ca1, ca2);
if ( (fa1 == 0) || (fa2 == 0) || (ma1 == 0) || (ma2 == 0) || (ca1 == 0) || (ca2 == 0) )
{
return(2); // sem informação de genotipo
}
s1a1 = fa1;
s1a2 = ma1;
s2a1 = fa1;
s2a2 = ma2;
s3a1 = fa2;
s3a2 = ma1;
s4a1 = fa2;
s4a2 = ma2;
if ( ( (ca1 == fa1) && ( (ca2 == ma1) || (ca2 == ma2) ) ) ||
( (ca1 == fa2) && ( (ca2 == ma1) || (ca2 == ma2) ) ) ||
( (ca2 == fa1) && ( (ca1 == ma1) || (ca1 == ma2) ) ) ||
( (ca2 == fa2) && ( (ca1 == ma1) || (ca1 == ma2) ) ) )
{
if ( (fa1 != fa2) && (ma1 != ma2)) // Pais heterozigotos
{
if ( ((ca1 == s1a1) && (ca2 == s1a2)) || ((ca2 == s1a1) && (ca1 == s1a2)) )
{
sibs[0] = s2a1 * 10 + s2a2;
sibs[1] = s3a1 * 10 + s3a2;
sibs[2] = s4a1 * 10 + s4a2;
}
else if ( ((ca1 == s2a1) && (ca2 == s2a2)) || ((ca2 == s2a1) && (ca1 == s2a2)) )
{
sibs[0] = s1a1 * 10 + s1a2;
sibs[1] = s3a1 * 10 + s3a2;
sibs[2] = s4a1 * 10 + s4a2;
}
else if ( ((ca1 == s3a1) && (ca2 == s3a2)) || ((ca2 == s3a1) && (ca1 == s3a2)) )
{
sibs[0] = s2a1 * 10 + s2a2;
sibs[1] = s1a1 * 10 + s1a2;
sibs[2] = s4a1 * 10 + s4a2;
}
else if ( ((ca1 == s4a1) && (ca2 == s4a2)) || ((ca2 == s4a1) && (ca1 == s4a2)) )
{
sibs[0] = s2a1 * 10 + s2a2;
sibs[1] = s1a1 * 10 + s1a2;
sibs[2] = s3a1 * 10 + s3a2;
}
return(0);
}
else if ( (fa1 == fa2) && (ma1 == ma2) ) //ambos os pais homozigotos
{
// if (fa1 != ma1) // homo diferentes
// if (fa1 == ma1) // homo iguais
// De qualquer forma não é informativo
return(1); // não informativo, zera todos os filhos
}
else // Um pai heterozigoto
{
if ( ((ca1 == fa1) && (ca2 == fa2)) || ((ca2 == fa2) && (ca1 == fa1)) )
{
sibs[0] = ma1 *10 + ma2;
sibs[1] = 0;
sibs[2] = 0;
}
else if ( ((ca1 == ma1) && (ca2 == ma2)) || ((ca2 == ma2) && (ca1 == ma1)) )
{
sibs[0] = fa1 *10 + fa2;
sibs[1] = 0;
sibs[2] = 0;
}
return(0);
}
}
else
{
return(3); // erro mendeliano
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int *Data;
double START, END;
void insertionsort(int *seq, int size) {
for (int j = 1; j < size; j++) {
int key, i;
key = seq[j];
i = j - 1;
while (i > -1 && seq[i] > key) {
seq[i + 1] = seq[i];
i--;
}
seq[i + 1] = key;
}
}
int main() {
// Input and Output file names
char *filename;
// Input a filename
printf("Please text a input file name: ");
scanf("%ms", &filename);
// Open the file
FILE *file;
file = fopen(filename, "r");
// Input size
int size;
fscanf(file, "%d", &size);
// Initialize the array
Data = (int*) malloc(size*sizeof(int));
// Put element into array
for (int i = 0; i < size; i++) {
fscanf(file, "%d", &Data[i]);
}
fclose(file);
free(filename);
// Start time
START = clock();
// Do insertion sort
insertionsort(Data, size);
// End time
END = clock();
// Print the total time
printf("The total time is %d\n", (END-START)/CLOCKS_PER_SEC);
// Input a file name
printf("Please text a output file name: ");
scanf("%ms", &filename);
// Open the file
file = fopen(filename, "w");
// Output the size
fprintf(file, "%d\n", size);
// Output the array
for (int i = 0; i < size; i++) {
fprintf(file, "%d\n", Data[i]);
}
fclose(file);
free(filename);
free(Data);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "SLL.h"
NodeT *search(NodeT *head, int givenKey)
{
//TODO: search the given key and return the first node containing it or NULL
NodeT *p = head;
while(p != NULL)
{
if(p->key == givenKey)
return p;
else
p = p->next;
}
return NULL;
}
void print_list(NodeT *head)
{
//TODO: print list keys
NodeT* p = head;
while(p != NULL)
{
printf("%d ", p->key);
p = p->next;
}
printf("\n");
}
void insert_first(NodeT **head, NodeT **tail, int givenKey)
{
//TODO: insert the given key in the first position of the list given by head and tail;
NodeT *p = malloc(sizeof(NodeT));
p->key = givenKey;
p->next = NULL;
if(*head == NULL) /// the list is empty
{
*head = p;
*tail = p;
}
else ///the list is not empty, insert before first node
{
p->next = *head;
*head = p;
}
}
void insert_last(NodeT **head, NodeT **tail, int givenKey)
{
//TODO: insert the given key in the last position of the list given by head and tail;
NodeT *p = malloc(sizeof(NodeT));
p->key = givenKey;
p->next = NULL;
if(*head == NULL) /// the list is empty
{
*head = p;
*tail = p;
}
else ///the list is not empty, insert after last node
{
(*tail)->next = p;
*tail = p;
}
}
void insert_after_key(NodeT** head, NodeT** tail, int afterKey, int givenKey)
{
//TODO: insert the given key after afterKey, in list given by head and tail;
NodeT *p = malloc(sizeof(NodeT));
NodeT *search = malloc(sizeof(NodeT));
p->key = givenKey;
p->next = NULL;
search = *head;
while(search != NULL)
{
if(search->key == afterKey)
break; ///searching for the node with the key - afterKey
search = search->next;
}
/* node with key afterKey has address search */
if (search != NULL) ///we found the node
{
p->next = search->next;
search->next = p;
if (search == *tail)
*tail = p;
}
}
void delete_first(NodeT** head, NodeT** tail)
{
//TODO: delete first list element
NodeT* p;
if(*head != NULL)
{
p = *head;
*head = (*head)->next;
free(p);
}
if(*head == NULL)
*tail == NULL;
}
void delete_last(NodeT** head, NodeT** tail)
{
//TODO: delete last list element
NodeT* search2 = NULL;
NodeT* search = *head;
if(search != NULL)
{
while(search != *tail)
{
search2 = search;
search = search->next;
}
if(search == *head) ///only one node
{
*head = NULL;
*tail = NULL;
free(search);
}
}
else ///more than one node
{
search2->next = NULL;
* tail = search2;
free(search);
}
}
void delete_key(NodeT** first, NodeT** last, int givenKey)
{
//TODO: delete element having given key
NodeT *search = *first;
NodeT *search2 = NULL;
while(search != NULL)
{
if(search->key == givenKey)
break;
search2 = search;
search = search->next;
}
if(search != NULL) ///found the node with given key
{
if(search == *first)///only one node
{
*first = (*first)->next;
if(*first == NULL)
*last == NULL;
free(search);
}
else
{
search2->next = search->next;
if(search == *last)
*last = search2;
free(search);
}
}
}
|
C
|
// { dg-do assemble }
// Make sure we make the right unqualified class a friend
// See PR c++/4403
template <class T> struct A
{
struct AA;
struct AC;
};
template <class T> class B
:public A<T>
{
friend struct B::AA; // OK, this has an implicit typename
// as if it is 'friend struct typename B::AA'
// (I think there's a defect report
// about that)
friend struct AC; // this makes ::AC a friend *not* A<T>::AC
private: // only our friends can get out values
static T valueA_AA;
static T valueA_AC;
static T value_AC;
};
template <typename T> T B<T>::valueA_AA;
template <typename T> T B<T>::valueA_AC;// { dg-message "" } private -
template <typename T> T B<T>::value_AC; // { dg-bogus "" } -
// this one is a friend
template <class T> struct A<T>::AA
{
int M ()
{
return B<T>::valueA_AA;
}
};
// this is not a friend
template <class T> struct A<T>::AC
{
T M ()
{
return B<T>::valueA_AC; // { dg-error "" } within this context -
}
};
// this is a friend
struct AC
{
int M ()
{
return B<int>::value_AC; // { dg-bogus "" } -
}
};
B<int> b;
A<int>::AA a_aa;
A<int>::AC a_ac;
AC ac;
int main ()
{
a_aa.M ();
a_ac.M ();
ac.M ();
}
|
C
|
/* 29-time.c --- time */
#define _XOPEN_SOURCE 700
#define _DEFAULT_SOURCE /* tm_gmtoff, tm_zone */
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <time.h>
#include <assert.h>
int
main()
{
/* 日历时间 */
struct timeval tv;
if (gettimeofday(&tv, NULL) == -1) {
perror("gettimeofday");
exit(EXIT_FAILURE);
}
printf("sec: %ld, usec: %ld\n", tv.tv_sec, (long) tv.tv_usec);
time_t t = time(NULL);
printf("sec: %ld\n", t);
/* gettimeofday 是系统调用,而 time 是库函数
struct timeval 比 time_t 更精确
*/
printf("'%s'\n", ctime(&t));
/* struct tm 叫做 broken-down time
gmtime 使用 UTC
*/
struct tm* tt = gmtime(&t);
printf("%d-%02d-%02d %02d:%02d:%02d %ld\n",
tt->tm_year + 1900,
tt->tm_mon + 1,
tt->tm_mday,
tt->tm_hour,
tt->tm_min,
tt->tm_sec,
tt->tm_gmtoff
);
printf("Seconds since Epoch: %ld\n",
timegm(tt));
{
/* localtime 受 TZ 环境变量影响 */
struct tm* tt = localtime(&t);
printf("%d-%02d-%02d %02d:%02d:%02d %ld %s\n",
tt->tm_year + 1900,
tt->tm_mon + 1,
tt->tm_mday,
tt->tm_hour,
tt->tm_min,
tt->tm_sec,
tt->tm_gmtoff,
tt->tm_zone
);
printf("'%s'\n", asctime(tt));
printf("Seconds since Epoch: %ld\n",
mktime(tt));
#define BUF_SIZE 1024
char buf[BUF_SIZE];
if (strftime(buf, BUF_SIZE, "%Y-%m-%d %H:%M:%S %z %Z", tt) == 0) {
// perror("strftime");
printf("ERROR: strftime returns 0\n");
exit(EXIT_FAILURE);
}
printf("'%s'\n", buf);
{
struct tm tt = {0};
assert(strptime("2020-05-01 19:13:52 +0800", "%Y-%m-%d %H:%M:%S %z", &tt));
puts(asctime(&tt));
}
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int a=0;
int suma(int num1, int num2){
return num1+num2;
}
int resta(int num1, int num2){
return num1-num2;
}
int multiplicacion(int num1, int num2){
return num1*num2;
}
int division(int num1, int num2){
return num1/num2;
}
void todasLasFunciones(int num1, int num2){
printf("Suma: %i", suma(num1, num2));
printf("\nResta%i", resta(num1, num2));
printf("\nMultiplicacion%i", multiplicacion(num1, num2));
printf("\nDivision%i", division(num1, num2));
}
void calculadora(){
int opcion = 0;
while(opcion == 0){
// ingreso de opciones
printf("Ingrese una opcion: ");
printf("1) Sumar ");
printf("\n2) Restar ");
printf("\n3) Mulriplicar ");
printf("\n4) Dividir ");
printf("\n5) Todas las funciones ");
scanf("%d", &opcion);
// opciones
if(opcion == 1){
int num1, num2;
system("cls");
printf("Ingrese el numero 1: ");
scanf("%d",&num1);
printf("\nIngrese el numero 2: ");
scanf("%d",&num2);
printf("\nEl resultado es: %i\n", suma(num1, num2));
system("pause");
system("cls");
opcion = 0;
}
if(opcion == 2){
int num1, num2;
system("cls");
printf("Ingrese el numero 1: \n");
scanf("%d",&num1);
printf("\nIngrese el numero 2: ");
scanf("%d",&num2);
printf("\nEl resultado es: %i\n", resta(num1, num2));
system("pause");
system("cls");
opcion = 0;
}
if(opcion == 3){
int num1, num2;
system("cls");
printf("Ingrese el numero 1: \n");
scanf("%d",&num1);
printf("\nIngrese el numero 2: ");
scanf("%d",&num2);
printf("\nEl resultado es: %i\n", multiplicacion(num1, num2));
system("pause");
system("cls");
opcion = 0;
}
if(opcion == 4){
int num1, num2;
system("cls");
printf("Ingrese el numero 1: \n");
scanf("%d",&num1);
printf("\nIngrese el numero 2: ");
scanf("%d",&num2);
printf("\nEl resultado es: %i\n", division(num1, num2));
system("pause");
system("cls");
opcion = 0;
}
if(opcion == 5){
int num1, num2;
system("cls");
printf("Ingrese el numero 1: \n");
scanf("%d",&num1);
printf("\nIngrese el numero 2: ");
scanf("%d",&num2);
todasLasFunciones(num1, num2);
system("pause");
system("cls");
opcion = 0;
}
}
}
int main(){
int a=0;
int opcion = (a>0) ? 1 : 2;
int opcion;
if(a>0)
opcion =1;
else
opcion=2;
printf("\n%i", opcion);
calculadora();
return 0;
}
|
C
|
// modele implicite
/* BORDET Dennis */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <glpk.h> // nous allons utiliser la bibliothèque de fonctions de GLPK
/* Déclarations pour le compteur de temps CPU */
#include <time.h>
#include <sys/time.h>
#include <sys/resource.h>
/*
#define nbvilles N
#define NBCONTR 2*N
#define NBCREUX 2*N*N
*/
struct timeval start_utime, stop_utime;
void crono_start()
{
struct rusage rusage;
getrusage(RUSAGE_SELF, &rusage);
start_utime = rusage.ru_utime;
}
void crono_stop()
{
struct rusage rusage;
getrusage(RUSAGE_SELF, &rusage);
stop_utime = rusage.ru_utime;
}
double crono_ms()
{
return (stop_utime.tv_sec - start_utime.tv_sec) * 1000 +
(stop_utime.tv_usec - start_utime.tv_usec) / 1000 ;
}
/* Structure contenant les données du problème */
typedef struct {
int nbvilles; // Nombre de villes
int **distances; // Tableau des couts
} donnees;
/* lecture des donnees */
void lecture_data(char *file, donnees *p)
{
FILE *fin; // Pointeur sur un fichier
int i,j;
int val;
fin = fopen(file,"r"); // Ouverture du fichier en lecture
/* Première ligne du fichier, on lit le nombre de variables */
fscanf(fin,"%d",&val);
p->nbvilles = val;
/* On peut maintenant faire les allocations dynamiques dépendant du nombre de variables et du nombre de contraintes */
p->distances = (int **) malloc (p->nbvilles * sizeof(int *));
for(i = 0;i < p->nbvilles;i++) p->distances[i] = (int *) malloc (p->nbvilles * sizeof(int));
// Il restera ensuite à dimensionner chaque "ligne" de la matrice creuse des contraintes
/* Deuxième ligne du fichier, on lit les coefficients de la fonction objectif */
for(i = 0;i < p->nbvilles;i++)
{
for(j=0; j< p->nbvilles;j++)
{
fscanf(fin,"%d",&val);
p->distances[i][j] = val;
}
}
fclose(fin); // Fermeture du fichier
}
int main(int argc, char *argv[])
{
double temps;
int nbsol = 0; /* Compteur du nombre d'appels au solveur GLPK */
int nbcontr = 0; /* Compteur du nombre de contraintes ajoutées pour obtenir une solution composée d'un unique cycle */
/* Déclarations à compléter... */
crono_start(); /* Lancement du compteur (juste après le chargement des données à partir d'un fichier */
glp_prob *prob; /* déclaration du pointeur sur le problème */
donnees p;
int *ia;
int *ja;
double *ar; // déclaration des 3 tableaux servant à définir la matrice "creuse" des contraintes
/* Les déclarations suivantes sont optionnelles, leur but est de donner des noms aux variables et aux contraintes.
Cela permet de lire plus facilement le modèle saisi si on en demande un affichage à GLPK, ce qui est souvent utile pour détecter une erreur! */
char **nomcontr;
char **numero;
char **nomvar;
/* variables récupérant les résultats de la résolution du problème (fonction objectif et valeur des variables) */
double z;
double *x;
/* autres déclarations */
int i,j;
int nbcreux; // nombre d'éléments de la matrice creuse
int pos; // compteur utilisé dans le remplissage de la matrice creuse
/* Chargement des données à partir d'un fichier */
lecture_data(argv[1],&p);
/* Transfert de ces données dans les structures utilisées par la bibliothèque GLPK */
prob = glp_create_prob(); /* allocation mémoire pour le problème */
glp_set_prob_name(prob, "Robots"); /* affectation d'un nom (on pourrait mettre NULL) */
glp_set_obj_dir(prob, GLP_MIN); /* Il s'agit d'un problème de minimisation, on utiliserait la constante GLP_MAX dans le cas contraire */
nbcontr =2*p.nbvilles;
/* Déclaration du nombre de contraintes (nombre de lignes de la matrice des contraintes) : p.nbcontr */
glp_add_rows(prob, nbcontr);
nomcontr = (char **) malloc (nbcontr * sizeof(char *));
numero = (char **) malloc (nbcontr * sizeof(char *));
/* On commence par préciser les bornes sur les contraintes, les indices commencent à 1 (!) dans GLPK */
for(i=1;i<=p.nbvilles;i++)
{
/* partie optionnelle : donner un nom aux contraintes */
nomcontr[i - 1] = (char *) malloc (8 * sizeof(char)); // hypothèse simplificatrice : on a au plus 7 caractères, sinon il faudrait dimensionner plus large!
numero[i - 1] = (char *) malloc (3 * sizeof(char)); // Même hypothèse sur la taille du problème
strcpy(nomcontr[i-1], "contA");
sprintf(numero[i-1], "%d", i);
strcat(nomcontr[i-1], numero[i-1]); /* Les contraintes sont nommés "salle1", "salle2"... */
glp_set_row_name(prob, i, nomcontr[i-1]); /* Affectation du nom à la contrainte i */
/* partie indispensable : les bornes sur les contraintes */
glp_set_row_bnds(prob, i, GLP_FX, 1.0, 1.0);
glp_add_cols(prob, p.nbvilles);
nomvar = (char **) malloc (p.nbvilles * sizeof(char *));
}
for(i=p.nbvilles+1;i<=2*p.nbvilles;i++)
{
/* partie optionnelle : donner un nom aux contraintes */
nomcontr[i - 1] = (char *) malloc (8 * sizeof(char)); // hypothèse simplificatrice : on a au plus 7 caractères, sinon il faudrait dimensionner plus large!
numero[i - 1] = (char *) malloc (3 * sizeof(char)); // Même hypothèse sur la taille du problème
strcpy(nomcontr[i-1], "contB");
sprintf(numero[i-1], "%d", i-p.nbvilles);
strcat(nomcontr[i-1], numero[i-1]);
glp_set_row_name(prob, i, nomcontr[i-1]); /* Affectation du nom à la contrainte i */
/* partie indispensable : les bornes sur les contraintes */
glp_set_row_bnds(prob, i, GLP_FX, 1.0, 1.0);
glp_add_cols(prob, p.nbvilles);
nomvar = (char **) malloc (p.nbvilles * sizeof(char *));
}
for(i=1;i<=p.nbvilles;i++)
{
for(j=1;j<=p.nbvilles;j++){
/* partie optionnelle : donner un nom aux variables */
nomvar[(i-1)*p.nbvilles+j] = (char *) malloc (3 * sizeof(char));
sprintf(nomvar[(i-1)*p.nbvilles+j],"V%d%d",i,j);
glp_set_col_name(prob, (i-1)*p.nbvilles+j , nomvar[(i-1)*p.nbvilles+j]);
/* partie obligatoire : bornes éventuelles sur les variables, et type */
glp_set_col_bnds(prob, (i-1)*p.nbvilles+j, GLP_DB, 0.0, 1.0); /* bornes sur les variables, comme sur les contraintes */
glp_set_col_kind(prob, (i-1)*p.nbvilles+j, GLP_BV); /* les variables sont par défaut continues, nous précisons ici qu'elles sont binaires avec la constante GLP_BV, on utiliserait GLP_IV pour des variables entières */
}
}
/* définition des coefficients des variables dans la fonction objectif */
for(i=1;i<=p.nbvilles;i++)
{
for(j=1;j<=p.nbvilles;j++){
glp_set_obj_coef(prob,(i-1)*p.nbvilles,p.distances[i-1][j-1]);
}
}
/* Définition des coefficients non-nuls dans la matrice des contraintes, autrement dit les coefficients de la matrice creuse */
/* Les indices commencent également à 1 ! */
nbcreux = p.nbvilles*p.nbvilles*(2);
// on alloue un poil plus pour mettre les contraintes de sous tours apres
/* SOUS TOURS
sum(i,j € S)(Xij) <= #S -1
POUR TOUT S
*/
ia = (int *) malloc ((1 + nbcreux) * sizeof(int));
ja = (int *) malloc ((1 + nbcreux) * sizeof(int));
ar = (double *) malloc ((1 + nbcreux) * sizeof(double));
pos = 1;
for(i = 1;i <= p.nbvilles;i++)
{
for(j = 1;j <= p.nbvilles;j++)
{
ia[pos] = i;
ja[pos] = (i-1)*p.nbvilles+j;
ar[pos] = 1.0;
pos++;
ia[pos] = p.nbvilles +j;
ja[pos] = (i-1)*p.nbvilles+j;
ar[pos] = 1.0;
pos++;
}
}
/* chargement de la matrice dans le problème */
glp_load_matrix(prob,nbcreux,ia,ja,ar);
/* Optionnel : écriture de la modélisation dans un fichier (utile pour debugger) */
glp_write_lp(prob,NULL,"Robots.lp");
/* Résolution, puis lecture des résultats */
//REVOIR CI DESSOUS, CEST FAUX LE TRUC AVEC X[]
glp_simplex(prob,NULL); glp_intopt(prob,NULL); /* Résolution */
z = glp_mip_obj_val(prob); /* Récupération de la valeur optimale. Dans le cas d'un problème en variables continues, l'appel est différent : z = glp_get_obj_val(prob);*/
x = (double *) malloc (p.nbvilles * sizeof(double));
for(i = 0;i < p.nbvilles; i++) x[i] = glp_mip_col_val(prob,i+1); /* Récupération de la valeur des variables, Appel différent dans le cas d'un problème en variables continues : for(i = 0;i < p.nbvilles;i++) x[i] = glp_get_col_prim(prob,i+1); */
printf("z = %lf\n",z);
for(i=1;i<=p.nbvilles;i++)
{
for(j=1;j<=p.nbvilles;j++){
printf("x%d%d = %d, ",i,j,(int)(x[i] + 0.5));
}
}
puts("");
/* libération mémoire */
glp_delete_prob(prob);
for(i = 0;i < p.nbvilles;i++) free(p.distances[i]);
free(p.distances);
//free(p.nbvilles);
free(ia);
free(ja);
free(ar);
free(x);
/* J'adore qu'un plan se déroule sans accroc! */
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main() {
float nota1, nota2, nota3, nota4, media;
nota1 = nota2 = nota3 = nota4 = media = 0;
printf("\t\t\t\t Media Escolar 1.0\n");
printf("Digite sua primeira nota bimestral:\n");
scanf("%f", ¬a1);
printf("Digite sua segunda nota bimestral:\n");
scanf("%f", ¬a2);
printf("Digite sua terceira nota bimestral:\n");
scanf("%f", ¬a3);
printf("Digite sua quarta nota bimestral:\n");
scanf("%f", ¬a4);
media = (nota1 + nota2 + nota3 + nota4) / 4;
printf("Sua media anual eh: %f", media);
if (media >= 7)
{
printf("Voce foi aprovado\n");
}else
{
printf("Voce foi reprovado\n");
}
return 0;
}
|
C
|
/*
** EPITECH PROJECT, 2018
** PSU_42sh_2017
** File description:
** Cd builtins functions.
*/
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include "shell.h"
#include "instruction.h"
#include "execution.h"
#include "mylib.h"
static unsigned int clear_folder_name(char *folder)
{
unsigned int roll_back = 0;
unsigned int i = 0;
unsigned int gap = 0;
while ((folder[i] == '.' || folder[i] == '/') && folder[i] != '\0') {
if (folder[i] == '.' && folder[i + 1] == '.' &&
(folder[i + 2] != '.' || folder[i + 2] == '/'))
roll_back++;
i++;
}
while (folder[gap] == '.' || folder[gap] == '/')
gap++;
i = gap;
while (folder[i] != '\0') {
folder[i - gap] = folder[i];
i++;
}
folder[i - gap] = '\0';
return (roll_back);
}
static void change_env_roll_back(char *env, int roll_back)
{
unsigned int i = strlen(env);
while (i > 0 && roll_back > 0) {
if (env[i] == '/') {
roll_back--;
env[i] = '\0';
}
i--;
}
if (env[4] == '\0') {
env[4] = '/';
env[5] = '\0';
}
}
static char *add_folder_name_env(char *env, char *folder)
{
char *new = malloc(sizeof(char) * (strlen(env) + strlen(folder) + 2));
unsigned int i = 0;
unsigned int j = 0;
if (new != NULL && folder[0] != '\0') {
for (i = 0; env[i]; i++) {
new[j] = env[i];
j++;
}
new[j] = '/';
j++;
for (i = 0; folder[i]; i++) {
new[j] = folder[i];
j++;
}
new[j] = '\0';
return (new);
}
return (env);
}
static char *change_directory(char *folder, char *env, shell_t *shell)
{
unsigned int roll_back = 0;
int changed = 0;
env = cd_special_cases(folder, env, &changed);
if (env && changed == 0) {
roll_back = clear_folder_name(folder);
roll_back > 0 ? change_env_roll_back(env, roll_back) : 0;
env = add_folder_name_env(env, folder);
} else if (env == NULL) {
roll_back = clear_folder_name(folder);
roll_back > 0 ? change_env_roll_back(
shell->backup->current_pwd, roll_back) : 0;
shell->backup->current_pwd = add_folder_name_env(
shell->backup->current_pwd, folder);
return (shell->backup->current_pwd);
}
return (env);
}
/*
** The char *fl defines the folder's name.
** The pipe_t *p variables defines the current given pipe.
*/
int cd_built(shell_t *shell, pipe_t *p)
{
unsigned int pos = get_line_env_zero(shell->env, "PWD");
char *fl = p->args[1] ? strdup(p->args[1]) : NULL;
char *buf = my_get_env(shell->env, "PWD");
fl != NULL && fl[0] == '.' ?
pos = check_rollback_path(shell, p->full_instruction, pos, p->fd) : 0;
if (fl != NULL && pos != 0 && strcmp(fl, "-") != 0) {
save_old_pwd(shell->env);
buf = change_directory(fl, shell->env[pos], shell);
(chdir(buf + 4) < 0) ? folder_error(shell, errno, fl, p->fd)
: 0;
(chdir(buf + 4) != -1) && shell->env[pos] ? shell->env[pos]
= buf : 0;
} else if (fl == NULL || strcmp(fl, "-") == 0) {
fl == NULL ? go_home_cd(shell, p->fd) : 0;
fl != NULL ? go_back_cd(shell, p->fd) : 0;
put_new_old_pwd(shell, buf);
} else
folder_error(shell, 0, fl, p->fd);
return (0);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
struct process{
int pid;
int arr_time;
int burst_time;
};
int n;
typedef struct process Process;
int proc_arrives(int i, Process ps[]){
for(int k = 0; k<n; k++){
if(ps[k].arr_time == i)
return ps[k].pid;
}
return 0;
}
int get_new_proc(int k, Process ps[]){
int proc_time= (int) INFINITY;
int proc_id = -1;
for(int i = 0; i<n; i++){
if(ps[i].burst_time > 0 && ps[i].burst_time < proc_time && ps[i].arr_time <= k){
proc_time = ps[i].burst_time;
proc_id = i;
}
}
if(proc_id<n && proc_id>=0)
return proc_id;
else
return -1;
}
void calculate_and_disp(Process ps[]){
int tot_time = 0;
int curr_exec;
int bts[n];
int ft[n];
for(int i = 0; i<n; i++)
tot_time+=ps[i].burst_time;
for(int i = 0; i<n; i++)
bts[i] = ps[i].burst_time;
curr_exec = 0;
for(int curr_time = 0; curr_time<=tot_time; curr_time++){
int pid;
if((pid = proc_arrives(curr_time, ps)) != 0){
if(ps[pid-1].burst_time < ps[curr_exec].burst_time){
printf("Curr. Time: %d; Process: %d stopped; Process: %d starts.\n", curr_time, curr_exec+1, pid);
curr_exec = pid - 1;
}
}
if(ps[curr_exec].burst_time>0)
ps[curr_exec].burst_time--;
else{
ft[curr_exec] = curr_time;
int temp = curr_exec;
curr_exec = get_new_proc(curr_time, ps);
if(curr_exec == -1)
break;
printf("Curr. Time: %d; Process: %d stopped; Process: %d starts.\n", curr_time, temp+1, curr_exec+1);
ps[curr_exec].burst_time--;
}
}
printf("\n");
int avg_wt = 0, avg_tat = 0;
for(int i = 0; i<n; i++){
printf("For P%d, FT: %d, TAT: %d, WT: %d\n", (i+1), ft[i], ft[i] - ps[i].arr_time, ft[i] - ps[i].arr_time - bts[i]);
avg_wt += ft[i] - ps[i].arr_time - bts[i];
avg_tat += ft[i] - ps[i].arr_time;
}
printf("Average WT = %d, Average TAT = %d\n", (avg_wt/n),(avg_tat/n));
}
int main(){
printf("Enter number of processes: \n");
scanf("%d", &n);
Process ps[n];
for(int i = 0; i<n; i++){
printf("Enter AT and BT for Process [%d]:\n", (i+1));
scanf("%d", &ps[i].arr_time);
scanf("%d", &ps[i].burst_time);
ps[i].pid = i+1;
}
calculate_and_disp(ps);
exit(0);
}
|
C
|
#include <stdio.h>
int main(){
int m,n;
char ch;
//clrscr();
y:printf("Key-in two numbers: ");
scanf("%d%d", &m,&n);
printf("The first number is %d\n",m);
printf("The second number is %d\n",n);
printf("The addition of the two numbers is: %d+%d=%d\n",m,n,m+n);
printf("\n Would you like to do more additions? Type Yes or NO ");
scanf(" %c",&ch);
if(ch=='y'){
goto y;
}
else if (ch == 'n'){
goto n;
}
else{
printf("Invalid selecton. Please type y for 'yes' and n for 'n");
}
n:printf("Thank you for exiting!");
}
|
C
|
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <signal.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXBUF 1024
int main(int argc, char *argv[]) // char ** argv
{
int server_sockfd, client_sockfd;
int state, client_len;
int pid;
struct sockaddr_in clientaddr, serveraddr;
char buf[MAXBUF];
char tcp[] = "TCP : ";
char buff_snd[MAXBUF];
if (argc != 2){
printf("Usage : %s [port]\n", argv[0]);
return 1;
}
//create TCP socket
server_sockfd = socket(AF_INET, SOCK_STREAM, 0);
if(server_sockfd < 0){
perror("socket error : ");
exit(0);
}
// 서버에서 받아들인 클라이언트 주소와 포트 주소를 설정
bzero(&serveraddr, sizeof(serveraddr));
serveraddr.sin_family = AF_INET;
serveraddr.sin_addr.s_addr = htonl(INADDR_ANY);
serveraddr.sin_port = htons(atoi(argv[1]));
// 설정된 주소를 소켓에 연결
state = bind(server_sockfd , (struct sockaddr *)&serveraddr,
sizeof(serveraddr));
if (state == -1) // 리턴 값의 상태 확인
{
perror("bind error : ");
exit(0);
}
// 수신할 수 있는 클라이언트 연결 수가 5개로 설정
state = listen(server_sockfd, 5);
if (state == -1) // 리턴 값의 상태 확인
{
perror("listen error : ");
exit(0);
}
// 다음장에 계속
while(1)
{
printf("\n");
// 클라이언트의 연결을 받아들임
client_sockfd = accept(server_sockfd, (struct sockaddr *)&clientaddr, &client_len);
if (client_sockfd == -1) // 항상 오류는 검사해주어야 함
{
perror("Accept error : ");
exit(0);
}
// 클라이언트와 연결이 성공적이면 자식 프로세스를 하나 만듦
pid = fork();
if (pid == 0) // 자식 프로세스인 경우 다음 문장들을 수행하고, 부모인 경우 계속하여 while() 수행
{
printf("getchar : ");
getchar();
while(1)
{
printf("\n");
memset(buf, 0, MAXBUF);
if (read(client_sockfd, buf, MAXBUF) <= 0) // 데이터가 존재할 때까지 계속 읽음
{
close(client_sockfd);
exit(0);
}
printf("received : ");
printf(" > %s", buf);
fputs("\n", stdout);
//문자열에 TCP 붙이기
strcat(buff_snd, tcp);
strcat(buff_snd, buf);
write(client_sockfd, buff_snd, strlen(buff_snd)); // echo
buff_snd[0] = '\0';
buf[0] = '\0';
//write(client_sockfd, buf, strlen(buf)); // edho
}
}
if (pid == -1) // 항상 오류는 검사해주어야 함
{
perror("fork error : ");
return 1;
}
}
close(client_sockfd);
}
|
C
|
#include <stdio.h>
int main(){
char entrada;
int forca, T;
scanf("%c\n%d", &entrada, &forca);
if(entrada == 'c') T = 18;
else T = 20;
int poder = ((forca * T) - 80)/10;
if(poder < 150){
printf("Fraco, nem passou");
}else if(poder < 180){
printf("Perfeito");
}else if(poder < 210){
printf("Satisfeito");
}else{
printf("Muito forte, bola fora");
}
}
|
C
|
#include <stdio.h>
int factorial(int n) {
// 해당되는 팩토리얼 파트를 구성하시오
}
int main() {
printf("Factorial Result (5!) = %d\n",factorial(5));
return 0;
}
// Main 함수에는 손을 대지 마시오
// Factorial 함수를 완성하여 5! = 120 이라는 결과값이 나오게 출력하시오
// 메인 함수에서 입출력을 해서 변형을 해도 좋음
|
C
|
#include <stdio.h>
int main() {
//Declarao
int num;
printf ("Digite um nmero inteiro: ");
fflush (stdout);
scanf ("%d", &num);
if (num > 100) {
printf ("%d", num);
} else {
num = 0;
printf ("%d", num);
}
}
|
C
|
/* SPDX-License-Identifier: GPL-2.0 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <fcntl.h>
#include <errno.h>
#include <ctype.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include "kselftest.h"
struct test {
const char *const name;
const char *const dev;
int flags;
int nr;
char mark[5];
size_t size;
size_t want;
size_t alloc;
};
static void dump(FILE *s, const char *tag, const unsigned char *restrict buf, size_t len)
{
int i, j, width = 16;
fprintf(s, "%s> ", tag);
for (i = 0; i < len; i++) {
fprintf(s, "%02x ", buf[i]);
/* check if we are done for this line */
if (i%width == (width-1) || i+1 == len) {
/* fill the gap */
for (j = (i%width); j < (width-1); j++)
fprintf(s, " ");
/* ascii print */
fprintf(s, "| ");
for (j = i-(i%width); j <= i; j++)
fprintf(s, "%c", isprint(buf[j]) ? buf[j] : '.');
fprintf(s, "\n%s> ", tag);
}
}
fprintf(s, "\n");
}
static void test(const struct test *restrict t)
{
char *ptr, obuf[t->size], ibuf[t->size];
char path[PATH_MAX];
ssize_t len, rem, got;
int i, err, fd;
FILE *fp;
err = snprintf(path, sizeof(path), "/dev/%s", t->dev);
if (err < 0)
goto perr;
ptr = obuf;
for (i = 0; i < t->size/sizeof(t->mark); i++) {
memcpy(ptr, t->mark, sizeof(t->mark));
ptr += sizeof(t->mark);
}
for (i = 0; i < t->size%sizeof(t->mark); i++)
ptr[i] = t->mark[i];
for (i = 0; i < t->nr; i++) {
int flags = t->flags|O_WRONLY;
fd = open(path, i == 0 ? flags|O_TRUNC : flags);
if (fd == -1)
goto perr;
rem = t->size;
ptr = obuf;
do {
len = write(fd, ptr, rem);
if (len == -1) {
fprintf(stderr, "%s: write: %s\n",
t->name, strerror(errno));
goto err;
}
rem -= len;
ptr += len;
} while (rem > 0);
if (close(fd) == -1)
goto perr;
}
fd = open(path, O_RDONLY);
if (fd == -1)
goto perr;
rem = sizeof(ibuf);
ptr = ibuf;
got = 0;
while ((len = read(fd, ptr, rem)) > 0) {
if (len == 0) {
if (memcmp(ibuf, obuf, got%sizeof(ibuf)))
goto dataerr;
break;
}
got += len;
rem -= len;
ptr += len;
if (rem == 0) {
if (memcmp(ibuf, obuf, sizeof(ibuf)))
goto dataerr;
rem = sizeof(ibuf);
ptr = ibuf;
}
}
if (close(fd) == -1)
goto perr;
if (got != t->want) {
fprintf(stderr, "%s: unexpected read result:\n\t- want: %ld\n\t- got: %ld\n",
t->name, t->want, got);
goto err;
}
err = snprintf(path, sizeof(path), "/sys/devices/%s/size", t->dev);
if (err < 0)
goto perr;
fp = fopen(path, "r");
if (!fp)
goto perr;
err = fread(ibuf, sizeof(ibuf), 1, fp);
if (err == 0 && ferror(fp))
goto perr;
if (fclose(fp) == -1)
goto perr;
got = strtol(ibuf, NULL, 10);
if (got != t->want) {
fprintf(stderr, "%s: unexpected %s value:\n\t- want: %ld\n\t- got: %ld\n",
t->name, path, t->want, got);
goto err;
}
err = snprintf(path, sizeof(path), "/sys/devices/%s/alloc", t->dev);
if (err < 0)
goto perr;
fp = fopen(path, "r");
if (!fp)
goto perr;
err = fread(ibuf, sizeof(ibuf), 1, fp);
if (err == 0 && ferror(fp))
goto perr;
got = strtol(ibuf, NULL, 10);
if (got != t->alloc) {
fprintf(stderr, "%s: unexpected %s value:\n\t- want: %ld\n\t- got: %ld\n",
t->name, path, t->alloc, got);
goto err;
}
exit(EXIT_SUCCESS);
dataerr:
fprintf(stderr, "%s: unexpected receive data\n",
t->name);
dump(stderr, "ibuf", (unsigned char *)ibuf, sizeof(ibuf));
dump(stderr, "obuf", (unsigned char *)obuf, sizeof(ibuf));
goto err;
perr:
perror(t->name);
err:
exit(EXIT_FAILURE);
}
int main(void)
{
long pagesize = sysconf(_SC_PAGESIZE);
const struct test *t, tests[] = {
{
.name = "signle 4095 write no O_APPEND flag",
.dev = "append0",
.flags = 0,
.mark = {0x01, 0xde, 0xad, 0xbe, 0xef},
.nr = 1,
.size = 4095,
.want = 4095,
.alloc = (4095/pagesize+1)*pagesize,
},
{
.name = "single 4095 write with O_APPEND flag",
.dev = "append1",
.flags = O_APPEND,
.mark = {0x02, 0xde, 0xad, 0xbe, 0xef},
.nr = 1,
.size = 4095,
.want = 4095,
.alloc = (4095/pagesize+1)*pagesize,
},
{
.name = "signle 4096 write no O_APPEND flag",
.dev = "append2",
.flags = 0,
.mark = {0x03, 0xde, 0xad, 0xbe, 0xef},
.nr = 1,
.size = 4096,
.want = 4096,
.alloc = (4096/pagesize+1)*pagesize,
},
{
.name = "single 4096 write with O_APPEND flag",
.dev = "append3",
.flags = O_APPEND,
.mark = {0x04, 0xde, 0xad, 0xbe, 0xef},
.nr = 1,
.size = 4096,
.want = 4096,
.alloc = (4096/pagesize+1)*pagesize,
},
{
.name = "signle 4097 write no O_APPEND flag",
.dev = "append0",
.flags = 0,
.mark = {0x05, 0xde, 0xad, 0xbe, 0xef},
.nr = 1,
.size = 4097,
.want = 4097,
.alloc = (4097/pagesize+1)*pagesize,
},
{
.name = "single 4097 write with O_APPEND flag",
.dev = "append1",
.flags = O_APPEND,
.mark = {0x06, 0xde, 0xad, 0xbe, 0xef},
.nr = 1,
.size = 4097,
.want = 4097,
.alloc = (4097/pagesize+1)*pagesize,
},
{
.name = "double 4095 writes no O_APPEND flag",
.dev = "append2",
.flags = 0,
.mark = {0x07, 0xde, 0xad, 0xbe, 0xef},
.nr = 2,
.size = 4095,
.want = 4095,
.alloc = (4095/pagesize+1)*pagesize,
},
{
.name = "double 4095 writes with O_APPEND flag",
.dev = "append3",
.flags = O_APPEND,
.mark = {0x08, 0xde, 0xad, 0xbe, 0xef},
.nr = 2,
.size = 4095,
.want = 8190,
.alloc = (8190/pagesize+1)*pagesize,
},
{
.name = "double 4096 writes no O_APPEND flag",
.dev = "append0",
.flags = 0,
.mark = {0x09, 0xde, 0xad, 0xbe, 0xef},
.nr = 2,
.size = 4096,
.want = 4096,
.alloc = (4096/pagesize+1)*pagesize,
},
{
.name = "double 4096 writes with O_APPEND flag",
.dev = "append1",
.flags = O_APPEND,
.mark = {0x0a, 0xde, 0xad, 0xbe, 0xef},
.nr = 2,
.size = 4096,
.want = 8192,
.alloc = (8192/pagesize)*pagesize,
},
{
.name = "double 4097 writes no O_APPEND flag",
.dev = "append2",
.flags = 0,
.mark = {0x0b, 0xde, 0xad, 0xbe, 0xef},
.nr = 2,
.size = 4097,
.want = 4097,
.alloc = (4097/pagesize+1)*pagesize,
},
{
.name = "double 4097 writes with O_APPEND flag",
.dev = "append3",
.flags = O_APPEND,
.mark = {0x0c, 0xde, 0xad, 0xbe, 0xef},
.nr = 2,
.size = 4097,
.want = 8194,
.alloc = (8194/pagesize+1)*pagesize,
},
{
.name = "triple 4095 writes no O_APPEND flag",
.dev = "append0",
.flags = 0,
.mark = {0x0d, 0xde, 0xad, 0xbe, 0xef},
.nr = 3,
.size = 4095,
.want = 4095,
.alloc = (4095/pagesize+1)*pagesize,
},
{
.name = "triple 4095 writes with O_APPEND flag",
.dev = "append1",
.flags = O_APPEND,
.mark = {0x0e, 0xde, 0xad, 0xbe, 0xef},
.nr = 3,
.size = 4095,
.want = 12285,
.alloc = (12285/pagesize+1)*pagesize,
},
{
.name = "triple 4096 writes no O_APPEND flag",
.dev = "append2",
.flags = 0,
.mark = {0x0f, 0xde, 0xad, 0xbe, 0xef},
.nr = 3,
.size = 4096,
.want = 4096,
.alloc = (4096/pagesize+1)*pagesize,
},
{
.name = "triple 4096 writes with O_APPEND flag",
.dev = "append3",
.flags = O_APPEND,
.mark = {0x10, 0xde, 0xad, 0xbe, 0xef},
.nr = 3,
.size = 4096,
.want = 12288,
.alloc = (12288/pagesize+1)*pagesize,
},
{
.name = "triple 4097 writes no O_APPEND flag",
.dev = "append0",
.flags = 0,
.mark = {0x11, 0xde, 0xad, 0xbe, 0xef},
.nr = 3,
.size = 4097,
.want = 4097,
.alloc = (4097/pagesize+1)*pagesize,
},
{
.name = "triple 4097 writes with O_APPEND flag",
.dev = "append1",
.flags = O_APPEND,
.mark = {0x12, 0xde, 0xad, 0xbe, 0xef},
.nr = 3,
.size = 4097,
.want = 12291,
.alloc = (12291/pagesize+1)*pagesize,
},
{.name = NULL},
};
for (t = tests; t->name; t++) {
int ret, status;
pid_t pid;
pid = fork();
if (pid == -1)
goto perr;
else if (pid == 0)
test(t);
ret = waitpid(pid, &status, 0);
if (ret == -1)
goto perr;
if (WIFSIGNALED(status)) {
fprintf(stderr, "%s: signaled with %s\n",
t->name, strsignal(WTERMSIG(status)));
goto err;
}
if (!WIFEXITED(status)) {
fprintf(stderr, "%s: does not exit\n",
t->name);
goto err;
}
if (WEXITSTATUS(status))
goto err;
ksft_inc_pass_cnt();
continue;
perr:
perror(t->name);
err:
ksft_inc_fail_cnt();
}
if (ksft_get_fail_cnt())
ksft_exit_fail();
ksft_exit_pass();
}
|
C
|
#include "RoketLink.h"
#include <assert.h>
void manual_assignment_test();
void test_altitude();
void test_latitude();
void test_longitude();
void test_pressure();
void test_temperature();
void test_tracker_yaw();
void test_tracker_pitch();
void test_payload_roll();
void test_payload_pitch();
void test_payload_yaw();
void test_humidity();
void test_parsing();
int main () {
// test_altitude();
// test_latitude();
// test_longitude();
// test_pressure();
// test_temperature();
// test_tracker_yaw();
// test_tracker_pitch();
// test_payload_roll();
// test_payload_pitch();
// test_payload_yaw();
test_humidity();
// ^ TODO : ganti pake define buat switching test
test_parsing();
return 0;
}
void manual_assignment_test()
{
printf("======================================\n");
printf(" Beginning of Manual Test \n");
printf("======================================\n");
// Variable needed
rocketlink_message_t *pMessage;
pMessage = (rocketlink_message_t*) malloc(sizeof(rocketlink_message_t));
altType *pUInt = malloc(sizeof(altType));
trackerYawType *pInt = malloc(sizeof(trackerYawType));
latType *pFloat = malloc(sizeof(latType));
// Data Conversion
*pUInt = 12345;
*pInt = -12300;
*pFloat = 3.14159;
uint8_t *pChr;
pChr = (uint8_t*) pUInt;
// Assignment Process;
pMessage->header.startBit = 0x0D;
pMessage->header.id[0] = 0x0A;
pMessage->header.id[1] = 0x0B;
pMessage->header.messageId = 0;
pMessage->payload = pChr;
// Altitude Test
printf("Altitude Test Begin\n");
print_rocketlink(pMessage);
printf("Altitude Extractor\n");
altType altitudeCondition = extract_altitude(pMessage->payload);
printf("Altitude extracted: %d m \n\n", altitudeCondition);
assert(altitudeCondition == 12345);
pChr = (uint8_t*) pInt;
pMessage->header.messageId = 5;
pMessage->payload = pChr;
printf("Yaw Test Begin\n");
print_rocketlink(pMessage);
trackerYawType trackerYawCondition = extract_tracker_yaw(pMessage->payload);
printf("Tracker Yaw extracted: %.2f degree \n\n", (float) (trackerYawCondition/100));
pChr = (uint8_t*) pFloat;
pMessage->header.messageId = 2;
pMessage->payload = pChr;
printf("Pressure Test Begin\n");
print_rocketlink(pMessage);
latType latCondition = extract_pressure(pMessage->payload);
printf("Pressure extracted: %f \n\n", latCondition);
free(pInt);
free(pFloat);
free(pMessage);
printf("======================================\n");
printf(" End of Test \n");
printf("======================================\n");
printf("\n\n");
}
void test_altitude()
{
printf("======================================\n");
printf(" Altitude Test \n");
printf("======================================\n");
/* Functional Assignment */
// Declaration of input
uint8_t startBit = 0x0D;
uint8_t id[] = { 0x0C, 0xF2 };
uint8_t messageId = 0;
altType testAltitude = 250;
altType extractedAltitude;
uint8_t *testPointer = (uint8_t*) &testAltitude;
rocketlink_message_t testMessage;
construct_rocketlink_altitude(&testMessage, startBit, id, testAltitude);
assert(testMessage.header.startBit == startBit);
assert(testMessage.header.id[0] == id[0]);
assert(testMessage.header.id[1] == id[1]);
assert(testMessage.header.messageId == messageId);
extractedAltitude = extract_altitude(testMessage.payload);
assert(extractedAltitude == testAltitude);
printf("Rocketlink constructor test (Altitude) passed.\n");
/* Reconstruct message from array of char */
uint8_t *containerMsg;
deconstruct_message(&containerMsg, &testMessage);
assert(containerMsg[0] == startBit);
assert(containerMsg[1] == id[0]);
assert(containerMsg[2] == id[1]);
assert(containerMsg[3] == messageId);
assert(containerMsg[4] == testPointer[0]);
assert(containerMsg[5] == testPointer[1]);
assert(containerMsg[6] == testPointer[2]);
assert(containerMsg[7] == testPointer[3]);
printf("Rocketlink deconstructor test (Altitude) passed.\n");
rocketlink_message_t deconstructedMessage;
reconstruct_rocketlink(&deconstructedMessage, containerMsg);
assert(deconstructedMessage.header.startBit == startBit);
assert(deconstructedMessage.header.id[0] == id[0]);
assert(deconstructedMessage.header.id[1] == id[1]);
assert(deconstructedMessage.header.messageId == messageId);
extractedAltitude = extract_altitude(deconstructedMessage.payload);
assert(extractedAltitude == testAltitude);
printf("Rocketlink reconstructor test (Altitude) passed.\n");
free(testMessage.payload);
// free(testMessage->payload);
// free(testMessage);
free(containerMsg);
free(deconstructedMessage.payload);
// free(deconstructedMessage->payload);
// free(deconstructedMessage);
printf("======================================\n");
printf(" End of Test \n");
printf("======================================\n");
printf("\n\n");
}
void test_latitude()
{
printf("======================================\n");
printf(" Latitude Test \n");
printf("======================================\n");
/* Functional Assignment */
// Declaration of input
uint8_t startBit = 0x0D;
uint8_t id[] = { 0x0C, 0xF2 };
uint8_t messageId = 1;
latType testLatitude = -106.141548;
latType extractedLatitude;
uint8_t *testPointer = (uint8_t*) &testLatitude;
rocketlink_message_t testMessage;
construct_rocketlink_latitude(&testMessage, startBit, id, testLatitude);
assert(testMessage.header.startBit == startBit);
assert(testMessage.header.id[0] == id[0]);
assert(testMessage.header.id[1] == id[1]);
assert(testMessage.header.messageId == messageId);
extractedLatitude = extract_latitude(testMessage.payload);
assert(extractedLatitude == testLatitude);
printf("Rocketlink constructor test (Latitude) passed.\n");
/* Reconstruct message from array of char */
uint8_t *containerMsg;
deconstruct_message(&containerMsg, &testMessage);
assert(containerMsg[0] == startBit);
assert(containerMsg[1] == id[0]);
assert(containerMsg[2] == id[1]);
assert(containerMsg[3] == messageId);
assert(containerMsg[4] == testPointer[0]);
assert(containerMsg[5] == testPointer[1]);
assert(containerMsg[6] == testPointer[2]);
assert(containerMsg[7] == testPointer[3]);
printf("Rocketlink deconstructor test (Latitude) passed.\n");
rocketlink_message_t deconstructedMessage;
reconstruct_rocketlink(&deconstructedMessage, containerMsg);
assert(deconstructedMessage.header.startBit == startBit);
assert(deconstructedMessage.header.id[0] == id[0]);
assert(deconstructedMessage.header.id[1] == id[1]);
assert(deconstructedMessage.header.messageId == messageId);
extractedLatitude = extract_latitude(deconstructedMessage.payload);
assert(extractedLatitude == testLatitude);
printf("Rocketlink reconstructor test (Latitude) passed.\n");
free(testMessage.payload);
free(containerMsg);
free(deconstructedMessage.payload);
printf("======================================\n");
printf(" End of Test \n");
printf("======================================\n");
printf("\n\n");
}
void test_longitude()
{
printf("======================================\n");
printf(" Longitude Test \n");
printf("======================================\n");
/* Functional Assignment */
// Declaration of input
uint8_t startBit = 0x0D;
uint8_t id[] = { 0x0C, 0xF2 };
uint8_t messageId = 2;
lonType testLongitude = 6.2831648;
lonType extractedLongitude;
uint8_t *testPointer = (uint8_t*) &testLongitude;
rocketlink_message_t testMessage;
construct_rocketlink_longitude(&testMessage, startBit, id, testLongitude);
assert(testMessage.header.startBit == startBit);
assert(testMessage.header.id[0] == id[0]);
assert(testMessage.header.id[1] == id[1]);
assert(testMessage.header.messageId == messageId);
extractedLongitude = extract_longitude(testMessage.payload);
assert(extractedLongitude == testLongitude);
printf("Rocketlink constructor test (Longitude) passed.\n");
/* Reconstruct message from array of char */
uint8_t *containerMsg;
deconstruct_message(&containerMsg, &testMessage);
assert(containerMsg[0] == startBit);
assert(containerMsg[1] == id[0]);
assert(containerMsg[2] == id[1]);
assert(containerMsg[3] == messageId);
assert(containerMsg[4] == testPointer[0]);
assert(containerMsg[5] == testPointer[1]);
assert(containerMsg[6] == testPointer[2]);
assert(containerMsg[7] == testPointer[3]);
printf("Rocketlink deconstructor test (Longitude) passed.\n");
rocketlink_message_t deconstructedMessage;
reconstruct_rocketlink(&deconstructedMessage, containerMsg);
assert(deconstructedMessage.header.startBit == startBit);
assert(deconstructedMessage.header.id[0] == id[0]);
assert(deconstructedMessage.header.id[1] == id[1]);
assert(deconstructedMessage.header.messageId == messageId);
extractedLongitude = extract_longitude(deconstructedMessage.payload);
assert(extractedLongitude == testLongitude);
printf("Rocketlink reconstructor test (Longitude) passed.\n");
free(testMessage.payload);
free(containerMsg);
free(deconstructedMessage.payload);
printf("======================================\n");
printf(" End of Test \n");
printf("======================================\n");
printf("\n\n");
}
void test_pressure()
{
printf("======================================\n");
printf(" Pressure Test \n");
printf("======================================\n");
/* Functional Assignment */
// Declaration of input
uint8_t startBit = 0x0D;
uint8_t id[] = { 0x0C, 0xF2 };
uint8_t messageId = 3;
preType testPressure = 123456789;
preType extractedPressure;
uint8_t *testPointer = (uint8_t*) &testPressure;
rocketlink_message_t testMessage;
construct_rocketlink_pressure(&testMessage, startBit, id, testPressure);
assert(testMessage.header.startBit == startBit);
assert(testMessage.header.id[0] == id[0]);
assert(testMessage.header.id[1] == id[1]);
assert(testMessage.header.messageId == messageId);
extractedPressure = extract_pressure(testMessage.payload);
assert(extractedPressure == testPressure);
printf("Rocketlink constructor test (Pressure) passed.\n");
/* Reconstruct message from array of char */
uint8_t *containerMsg;
deconstruct_message(&containerMsg, &testMessage);
assert(containerMsg[0] == startBit);
assert(containerMsg[1] == id[0]);
assert(containerMsg[2] == id[1]);
assert(containerMsg[3] == messageId);
assert(containerMsg[4] == testPointer[0]);
assert(containerMsg[5] == testPointer[1]);
assert(containerMsg[6] == testPointer[2]);
assert(containerMsg[7] == testPointer[3]);
printf("Rocketlink deconstructor test (Pressure) passed.\n");
rocketlink_message_t deconstructedMessage;
reconstruct_rocketlink(&deconstructedMessage, containerMsg);
assert(deconstructedMessage.header.startBit == startBit);
assert(deconstructedMessage.header.id[0] == id[0]);
assert(deconstructedMessage.header.id[1] == id[1]);
assert(deconstructedMessage.header.messageId == messageId);
extractedPressure = extract_pressure(deconstructedMessage.payload);
assert(extractedPressure == testPressure);
printf("Rocketlink reconstructor test (Pressure) passed.\n");
free(testMessage.payload);
free(containerMsg);
free(deconstructedMessage.payload);
printf("======================================\n");
printf(" End of Test \n");
printf("======================================\n");
printf("\n\n");
}
void test_temperature()
{
printf("======================================\n");
printf(" Temperature Test \n");
printf("======================================\n");
/* Functional Assignment */
// Declaration of input
uint8_t startBit = 0x0D;
uint8_t id[] = { 0x0C, 0xF2 };
uint8_t messageId = 4;
tempType testTemperature = -369852;
tempType extractedTemperature;
uint8_t *testPointer = (uint8_t*) &testTemperature;
rocketlink_message_t testMessage;
construct_rocketlink_temperature(&testMessage, startBit, id, testTemperature);
assert(testMessage.header.startBit == startBit);
assert(testMessage.header.id[0] == id[0]);
assert(testMessage.header.id[1] == id[1]);
assert(testMessage.header.messageId == messageId);
extractedTemperature = extract_temperature(testMessage.payload);
assert(extractedTemperature == testTemperature);
printf("Rocketlink constructor test (Temperature) passed.\n");
/* Reconstruct message from array of char */
uint8_t *containerMsg;
deconstruct_message(&containerMsg, &testMessage);
assert(containerMsg[0] == startBit);
assert(containerMsg[1] == id[0]);
assert(containerMsg[2] == id[1]);
assert(containerMsg[3] == messageId);
assert(containerMsg[4] == testPointer[0]);
assert(containerMsg[5] == testPointer[1]);
assert(containerMsg[6] == testPointer[2]);
assert(containerMsg[7] == testPointer[3]);
printf("Rocketlink deconstructor test (Temperature) passed.\n");
rocketlink_message_t deconstructedMessage;
reconstruct_rocketlink(&deconstructedMessage, containerMsg);
assert(deconstructedMessage.header.startBit == startBit);
assert(deconstructedMessage.header.id[0] == id[0]);
assert(deconstructedMessage.header.id[1] == id[1]);
assert(deconstructedMessage.header.messageId == messageId);
extractedTemperature = extract_temperature(deconstructedMessage.payload);
assert(extractedTemperature == testTemperature);
printf("Rocketlink reconstructor test (Temperature) passed.\n");
free(testMessage.payload);
free(containerMsg);
free(deconstructedMessage.payload);
printf("======================================\n");
printf(" End of Test \n");
printf("======================================\n");
printf("\n\n");
}
void test_tracker_yaw()
{
printf("======================================\n");
printf(" Tracker_yaw Test \n");
printf("======================================\n");
/* Functional Assignment */
// Declaration of input
uint8_t startBit = 0x0D;
uint8_t id[] = { 0x0C, 0xF2 };
uint8_t messageId = 5;
trackerYawType testTrackerYaw = -106236;
trackerYawType extractedTrackerYaw;
uint8_t *testPointer = (uint8_t*) &testTrackerYaw;
rocketlink_message_t testMessage;
construct_rocketlink_tracker_yaw(&testMessage, startBit, id, testTrackerYaw);
assert(testMessage.header.startBit == startBit);
assert(testMessage.header.id[0] == id[0]);
assert(testMessage.header.id[1] == id[1]);
assert(testMessage.header.messageId == messageId);
extractedTrackerYaw = extract_tracker_yaw(testMessage.payload);
assert(extractedTrackerYaw == testTrackerYaw);
printf("Rocketlink constructor test (TrackerYaw) passed.\n");
/* Reconstruct message from array of char */
uint8_t *containerMsg;
deconstruct_message(&containerMsg, &testMessage);
assert(containerMsg[0] == startBit);
assert(containerMsg[1] == id[0]);
assert(containerMsg[2] == id[1]);
assert(containerMsg[3] == messageId);
assert(containerMsg[4] == testPointer[0]);
assert(containerMsg[5] == testPointer[1]);
assert(containerMsg[6] == testPointer[2]);
assert(containerMsg[7] == testPointer[3]);
printf("Rocketlink deconstructor test (TrackerYaw) passed.\n");
rocketlink_message_t deconstructedMessage;
reconstruct_rocketlink(&deconstructedMessage, containerMsg);
assert(deconstructedMessage.header.startBit == startBit);
assert(deconstructedMessage.header.id[0] == id[0]);
assert(deconstructedMessage.header.id[1] == id[1]);
assert(deconstructedMessage.header.messageId == messageId);
extractedTrackerYaw = extract_tracker_yaw(deconstructedMessage.payload);
assert(extractedTrackerYaw == testTrackerYaw);
printf("Rocketlink reconstructor test (TrackerYaw) passed.\n");
free(testMessage.payload);
free(containerMsg);
free(deconstructedMessage.payload);
printf("======================================\n");
printf(" End of Test \n");
printf("======================================\n");
printf("\n\n");
}
void test_tracker_pitch()
{
printf("======================================\n");
printf(" Tracker_pitch Test \n");
printf("======================================\n");
/* Functional Assignment */
// Declaration of input
uint8_t startBit = 0x0D;
uint8_t id[] = { 0x0C, 0xF2 };
uint8_t messageId = 6;
trackerPitchType testTrackerPitch = 17523;
trackerPitchType extractedTrackerPitch;
uint8_t *testPointer = (uint8_t*) &testTrackerPitch;
rocketlink_message_t testMessage;
construct_rocketlink_tracker_pitch(&testMessage, startBit, id, testTrackerPitch);
assert(testMessage.header.startBit == startBit);
assert(testMessage.header.id[0] == id[0]);
assert(testMessage.header.id[1] == id[1]);
assert(testMessage.header.messageId == messageId);
extractedTrackerPitch = extract_tracker_pitch(testMessage.payload);
assert(extractedTrackerPitch == testTrackerPitch);
printf("Rocketlink constructor test (TrackerPitch) passed.\n");
/* Reconstruct message from array of char */
uint8_t *containerMsg;
deconstruct_message(&containerMsg, &testMessage);
assert(containerMsg[0] == startBit);
assert(containerMsg[1] == id[0]);
assert(containerMsg[2] == id[1]);
assert(containerMsg[3] == messageId);
assert(containerMsg[4] == testPointer[0]);
assert(containerMsg[5] == testPointer[1]);
assert(containerMsg[6] == testPointer[2]);
assert(containerMsg[7] == testPointer[3]);
printf("Rocketlink deconstructor test (TrackerPitch) passed.\n");
rocketlink_message_t deconstructedMessage;
reconstruct_rocketlink(&deconstructedMessage, containerMsg);
assert(deconstructedMessage.header.startBit == startBit);
assert(deconstructedMessage.header.id[0] == id[0]);
assert(deconstructedMessage.header.id[1] == id[1]);
assert(deconstructedMessage.header.messageId == messageId);
extractedTrackerPitch = extract_tracker_pitch(deconstructedMessage.payload);
assert(extractedTrackerPitch == testTrackerPitch);
printf("Rocketlink reconstructor test (TrackerPitch) passed.\n");
free(testMessage.payload);
free(containerMsg);
free(deconstructedMessage.payload);
printf("======================================\n");
printf(" End of Test \n");
printf("======================================\n");
printf("\n\n");
}
void test_payload_roll()
{
printf("======================================\n");
printf(" Payload Roll Test \n");
printf("======================================\n");
/* Functional Assignment */
// Declaration of input
uint8_t startBit = 0x0D;
uint8_t id[] = { 0x0C, 0xF2 };
uint8_t messageId = 7;
payloadRollType testPayloadRoll = -365723;
payloadRollType extractedPayloadRoll;
uint8_t *testPointer = (uint8_t*) &testPayloadRoll;
rocketlink_message_t testMessage;
construct_rocketlink_payload_roll(&testMessage, startBit, id, testPayloadRoll);
assert(testMessage.header.startBit == startBit);
assert(testMessage.header.id[0] == id[0]);
assert(testMessage.header.id[1] == id[1]);
assert(testMessage.header.messageId == messageId);
extractedPayloadRoll = extract_payload_roll(testMessage.payload);
assert(extractedPayloadRoll == testPayloadRoll);
printf("Rocketlink constructor test (PayloadRoll) passed.\n");
/* Reconstruct message from array of char */
uint8_t *containerMsg;
deconstruct_message(&containerMsg, &testMessage);
assert(containerMsg[0] == startBit);
assert(containerMsg[1] == id[0]);
assert(containerMsg[2] == id[1]);
assert(containerMsg[3] == messageId);
assert(containerMsg[4] == testPointer[0]);
assert(containerMsg[5] == testPointer[1]);
assert(containerMsg[6] == testPointer[2]);
assert(containerMsg[7] == testPointer[3]);
printf("Rocketlink deconstructor test (PayloadRoll) passed.\n");
rocketlink_message_t deconstructedMessage;
reconstruct_rocketlink(&deconstructedMessage, containerMsg);
assert(deconstructedMessage.header.startBit == startBit);
assert(deconstructedMessage.header.id[0] == id[0]);
assert(deconstructedMessage.header.id[1] == id[1]);
assert(deconstructedMessage.header.messageId == messageId);
extractedPayloadRoll = extract_payload_roll(deconstructedMessage.payload);
assert(extractedPayloadRoll == testPayloadRoll);
printf("Rocketlink reconstructor test (PayloadRoll) passed.\n");
free(testMessage.payload);
free(containerMsg);
free(deconstructedMessage.payload);
printf("======================================\n");
printf(" End of Test \n");
printf("======================================\n");
printf("\n\n");
}
void test_payload_pitch()
{
printf("======================================\n");
printf(" Payload Pitch Test \n");
printf("======================================\n");
/* Functional Assignment */
// Declaration of input
uint8_t startBit = 0x0D;
uint8_t id[] = { 0x0C, 0xF2 };
uint8_t messageId = 8;
payloadPitchType testPayloadPitch = 753951;
payloadPitchType extractedPayloadPitch;
uint8_t *testPointer = (uint8_t*) &testPayloadPitch;
rocketlink_message_t testMessage;
construct_rocketlink_payload_pitch(&testMessage, startBit, id, testPayloadPitch);
assert(testMessage.header.startBit == startBit);
assert(testMessage.header.id[0] == id[0]);
assert(testMessage.header.id[1] == id[1]);
assert(testMessage.header.messageId == messageId);
extractedPayloadPitch = extract_payload_pitch(testMessage.payload);
assert(extractedPayloadPitch == testPayloadPitch);
printf("Rocketlink constructor test (PayloadPitch) passed.\n");
/* Reconstruct message from array of char */
uint8_t *containerMsg;
deconstruct_message(&containerMsg, &testMessage);
assert(containerMsg[0] == startBit);
assert(containerMsg[1] == id[0]);
assert(containerMsg[2] == id[1]);
assert(containerMsg[3] == messageId);
assert(containerMsg[4] == testPointer[0]);
assert(containerMsg[5] == testPointer[1]);
assert(containerMsg[6] == testPointer[2]);
assert(containerMsg[7] == testPointer[3]);
printf("Rocketlink deconstructor test (PayloadPitch) passed.\n");
rocketlink_message_t deconstructedMessage;
reconstruct_rocketlink(&deconstructedMessage, containerMsg);
assert(deconstructedMessage.header.startBit == startBit);
assert(deconstructedMessage.header.id[0] == id[0]);
assert(deconstructedMessage.header.id[1] == id[1]);
assert(deconstructedMessage.header.messageId == messageId);
extractedPayloadPitch = extract_payload_pitch(deconstructedMessage.payload);
assert(extractedPayloadPitch == testPayloadPitch);
printf("Rocketlink reconstructor test (PayloadPitch) passed.\n");
free(testMessage.payload);
free(containerMsg);
free(deconstructedMessage.payload);
printf("======================================\n");
printf(" End of Test \n");
printf("======================================\n");
printf("\n\n");
}
void test_payload_yaw()
{
printf("======================================\n");
printf(" Payload Yaw Test \n");
printf("======================================\n");
/* Functional Assignment */
// Declaration of input
uint8_t startBit = 0x0D;
uint8_t id[] = { 0x0C, 0xF2 };
uint8_t messageId = 9;
payloadYawType testPayloadYaw = 456852;
payloadYawType extractedPayloadYaw;
uint8_t *testPointer = (uint8_t*) &testPayloadYaw;
rocketlink_message_t testMessage;
construct_rocketlink_payload_yaw(&testMessage, startBit, id, testPayloadYaw);
assert(testMessage.header.startBit == startBit);
assert(testMessage.header.id[0] == id[0]);
assert(testMessage.header.id[1] == id[1]);
assert(testMessage.header.messageId == messageId);
extractedPayloadYaw = extract_payload_yaw(testMessage.payload);
assert(extractedPayloadYaw == testPayloadYaw);
printf("Rocketlink constructor test (PayloadYaw) passed.\n");
/* Reconstruct message from array of char */
uint8_t *containerMsg;
deconstruct_message(&containerMsg, &testMessage);
assert(containerMsg[0] == startBit);
assert(containerMsg[1] == id[0]);
assert(containerMsg[2] == id[1]);
assert(containerMsg[3] == messageId);
assert(containerMsg[4] == testPointer[0]);
assert(containerMsg[5] == testPointer[1]);
assert(containerMsg[6] == testPointer[2]);
assert(containerMsg[7] == testPointer[3]);
printf("Rocketlink deconstructor test (PayloadYaw) passed.\n");
rocketlink_message_t deconstructedMessage;
reconstruct_rocketlink(&deconstructedMessage, containerMsg);
assert(deconstructedMessage.header.startBit == startBit);
assert(deconstructedMessage.header.id[0] == id[0]);
assert(deconstructedMessage.header.id[1] == id[1]);
assert(deconstructedMessage.header.messageId == messageId);
extractedPayloadYaw = extract_payload_yaw(deconstructedMessage.payload);
assert(extractedPayloadYaw == testPayloadYaw);
printf("Rocketlink reconstructor test (PayloadYaw) passed.\n");
free(testMessage.payload);
free(containerMsg);
free(deconstructedMessage.payload);
printf("======================================\n");
printf(" End of Test \n");
printf("======================================\n");
printf("\n\n");
}
void test_humidity()
{
printf("======================================\n");
printf(" Payload Humidity Test \n");
printf("======================================\n");
/* Functional Assignment */
// Declaration of input
uint8_t startBit = 0x0D;
uint8_t id[] = { 0x0C, 0xF2 };
uint8_t messageId = 11;
humidityType testHumidity = 9234;
humidityType extractedHumidity;
uint8_t *testPointer = (uint8_t*) &testHumidity;
rocketlink_message_t testMessage;
construct_rocketlink_humidity(&testMessage, startBit, id, testHumidity);
assert(testMessage.header.startBit == startBit);
assert(testMessage.header.id[0] == id[0]);
assert(testMessage.header.id[1] == id[1]);
assert(testMessage.header.messageId == messageId);
extractedHumidity = extract_humidity(testMessage.payload);
printf("Extracted (Humidity): %.2lf\n", extractedHumidity/100.0);
printf("Test Value (Humidity): %.2lf\n", testHumidity/100.0);
assert(extractedHumidity == testHumidity);
printf("Rocketlink constructor test (Humidity) passed.\n");
/* Reconstruct message from array of char */
uint8_t *containerMsg;
deconstruct_message(&containerMsg, &testMessage);
assert(containerMsg[0] == startBit);
assert(containerMsg[1] == id[0]);
assert(containerMsg[2] == id[1]);
assert(containerMsg[3] == messageId);
assert(containerMsg[4] == testPointer[0]);
assert(containerMsg[5] == testPointer[1]);
assert(containerMsg[6] == testPointer[2]);
assert(containerMsg[7] == testPointer[3]);
printf("Rocketlink deconstructor test (Humidity) passed.\n");
rocketlink_message_t deconstructedMessage;
reconstruct_rocketlink(&deconstructedMessage, containerMsg);
assert(deconstructedMessage.header.startBit == startBit);
assert(deconstructedMessage.header.id[0] == id[0]);
assert(deconstructedMessage.header.id[1] == id[1]);
assert(deconstructedMessage.header.messageId == messageId);
extractedHumidity = extract_humidity(deconstructedMessage.payload);
assert(extractedHumidity == testHumidity);
printf("Rocketlink reconstructor test (PayloadYaw) passed.\n");
free(testMessage.payload);
free(containerMsg);
free(deconstructedMessage.payload);
printf("======================================\n");
printf(" End of Test \n");
printf("======================================\n");
printf("\n\n");
}
void test_parsing() {
puts("======================================");
puts(" Parsing Test ");
puts("======================================");
// Test Input
uint8_t startBit = 0x0D;
uint8_t id[] = { 0x0C, 0xF2 };
latType testPayloadLatitude = -4.156484;
payloadYawType testPayloadYaw2 = -1245;
payloadYawType extractedPayloadYaw;
latType extractedLatitude;
puts("Test Value and Variable Created.");
uint8_t testArray[20]; // Input simulation
rocketlink_message_t testMessage;
rocketlink_message_t testMessage2;
construct_rocketlink_latitude(&testMessage, startBit, id, testPayloadLatitude);
construct_rocketlink_payload_yaw(&testMessage2, startBit, id, testPayloadYaw2);
puts("Rocketlink constructed.");
uint8_t *containerMsg; // Container to array version of message
uint8_t *containerMsg2; // Container to array version of message
deconstruct_message(&containerMsg, &testMessage);
deconstruct_message(&containerMsg2, &testMessage2);
for (int i = 0; i<20; i++) {
if (i<8) {
testArray[i] = containerMsg[i];
} else if ((i>=10) && (i<18)) {
testArray[i] = containerMsg2[i-10];
} else {
testArray[i] = i+100;
}
}
// Print Test Message and Test array
puts("Test Message 1: StartBit 0x0D, ID 0x0C and 0xF2, Message ID 1, Payload Latitude -4.156484");
for (int i = 0; i<8; i++) {
printf("%.2x ",containerMsg[i]);
}
printf("\n\n");
puts("Test Message 2: StartBit 0x0D, ID 0x0C and 0xF2, Message ID 9, Payload Yaw -12.45 degree");
for (int i = 0; i<8; i++) {
printf("%.2x ",containerMsg[i]);
}
printf("\n\n");
puts("Test Array: (unaltered)");
for (int i = 0; i<20; i++) {
printf("%.2x ",testArray[i]);
}
printf("\n\n");
testArray[2] = 0xFF;
puts("Test Array: (altered) bit 3 modified to break message 1");
for (int i = 0; i<20; i++) {
printf("%.2x ",testArray[i]);
}
printf("\n");
// Parsing Test with the input Message
rocketlink_message_t output_message;
for (int i = 0; i<20; i++) {
if(!parseRocketlink(&output_message,testArray[i],startBit,id)) {
printf("Message Retrieved.\n");
if (output_message.header.messageId == 9) {
extractedPayloadYaw = extract_payload_yaw(output_message.payload);
free(output_message.payload);
printf("Extracted Payload Yaw: %.2f\n\n", (float) extractedPayloadYaw/100);
} else {
extractedLatitude = extract_latitude(output_message.payload);
free(output_message.payload);
printf("Extracted Latitude: %.6f\n\n", extractedLatitude);
}
}
}
puts("Test Passed.");
free(testMessage.payload);
free(testMessage2.payload);
free(containerMsg);
free(containerMsg2);
free(output_message.payload);
printf("======================================\n");
printf(" End of Test \n");
printf("======================================\n");
printf("\n\n");
}
|
C
|
#ifndef MINI_RPG_EVENTPACKAGE_H
#define MINI_RPG_EVENTPACKAGE_H
struct EventPackage {
enum Type {
MOVE_PLAYER, PLAYER_ATTACK, CHANGE_PLAYER, SELECT_PLAYER, VIEW_STATS,
QUIT, RESET, EXIT_SPECIAL_SCREEN, QUICK_ACCESS
};
EventPackage() {};
EventPackage(Type t) : type(t){};
EventPackage(Type t, int q) : type(t){
quickAccess = q;
};
EventPackage(Type t, int a, int b) : type(t) {
switch (t) {
case MOVE_PLAYER:
x = a;
y = b;
break;
case SELECT_PLAYER:
row = a;
col = b;
break;
default: break;
}
};
Type type;
int x;
int y;
int row;
int col;
int quickAccess;
};
#endif //MINI_RPG_EVENTPACKAGE_H
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/shm.h>
#include <sys/msg.h>
#include "log_write.h"
#include "message.h"
#include "equipment.h"
#include "power_system.h"
void log_write_handle(FILE *log_server, int shmid_equipment, int shmid_system, int msqid)
{
message_t got_msg;
equip_t *equipment;
power_system_t *powsys;
// Connect to shared memory
if ((equipment = (equip_t *)shmat(shmid_equipment, (void *)0, 0)) == (void *)-1)
{
printf("shmat() failed\n");
exit(1);
}
if ((powsys = (power_system_t *)shmat(shmid_system, (void *)0, 0)) == (void *)-1)
{
printf("shmat() failed\n");
exit(1);
}
// Listen to elec_poser_ctrl
while (1)
{
// Receive message
if (msgrcv(msqid, &got_msg, MAX_MESSAGE_LENGTH, LOG_WRITE_MESS_CODE, 0) == -1)
{
printf("msgrcv() error");
exit(1);
}
// header = 's' => Write log to server
if (got_msg.mtext[0] == 's')
{
char buff[MAX_MESSAGE_LENGTH];
//extract from message
sscanf(got_msg.mtext, "%*2c%[^|]|", buff);
// get time now
char log_time[20];
time_t t = time(NULL);
struct tm *now = localtime(&t);
strftime(log_time, sizeof(log_time), "%Y/%m/%d_%H:%M:%S", now);
// write log
fprintf(log_server, "%s | %s\n", log_time, buff);
}
}
}
|
C
|
#include <stdio.h>
#include "../include/list_def.h"
void list_close(list_data* list)
{
lst_assert(list);
lst_check(list,);
pthread_mutex_destroy(&list->mutex);
free_list_item(list->root);
if(list->root)
{
if(list->subdir)
{
if(list->root->dirct_num)
free(list->root->dirct_num);
if(list->root->link_num)
free(list->root->link_num);
}
if(list->root->name)
{
free(list->root->name);
}
free(list->root);
}
free(list);
list=NULL;
}
void free_list_item(list_item* start)
{
list_item *curr, *item;
if((curr=list_next_entry_or_null(start, head[eHeadAll])) == NULL)
return;
for(item=NULL;;curr=list_next_entry_or_null(curr, head[eHeadAll]))
{
if(item == NULL)
{
item = curr;
continue;
}
if(item->name)
free(item->name);
if((item->exte_type == dirct))
{
if(item->dirct_num)
free(item->dirct_num);
if(item->link_num)
free(item->link_num);
}
free(item);
if(curr == NULL)
break;
item = curr;
}
}
|
C
|
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main(){
/*
nhap n
*/
int n,tu=1,mau =0,i=1;
float sum=0;
printf("nhap n = ");
scanf("%d", &n);
while(i<=n){
mau= mau+i;
sum=sum + (float)tu/mau;
i++;
}
printf("in ra man hinh s = %f", sum);
}
|
C
|
/*
16. Write a program to send and receive data from parent to child vice versa. Use two way communication.
*/
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
int pipe_parent[2];// from parent to child
int pipe_child[2];// from parent to child
if(pipe(pipe_parent)<0 || pipe(pipe_child)<0)
perror("PIPE");
char writebuffer_parent[200],readbuffer_parent[200],writebuffer_child[200],readbuffer_child[200];
int readbuff,writebuff;
int child_pid =fork();
if(child_pid > 0)
{
close(pipe_parent[0]);//reading end of pipe_parent is closed
close(pipe_child[1]);//close the writing end of the child pipe
printf("This is the parent process...\n");
printf("\nParent pid %d", getpid());
printf("\nEnter message to write in pipe for the child: ");
fgets(writebuffer_parent, 200, stdin);
write(pipe_parent[1], writebuffer_parent, sizeof(writebuffer_parent));
//sleep(8);
//printf("Let's see the msg from child to me if any...\n");
//let parent read any msg from the child...
read(pipe_child[0],readbuffer_child,sizeof(writebuffer_child));
printf("Child sent me this msg::%s\n",readbuffer_child);
}
else
{
sleep(15);
close(pipe_parent[1]);//close the writing end of the parent pipe
close(pipe_child[0]);//close the reading end of the child pipe
printf("\nThis is the child process...\n");
printf( "\nChild pid %d\n", getpid());
printf("\nParent Process Pid of the child %d", getppid());
read(pipe_parent[0], readbuffer_parent, sizeof(writebuffer_parent));
printf(" \nParent says : %s ", readbuffer_parent);
//sleep(3);
//lets write the msg to the parents
printf("\nEnter message to write in pipe for the parent: ");
fgets(writebuffer_child, 200, stdin);
write(pipe_child[1],writebuffer_child,sizeof(writebuffer_child));
printf("got the message..\n");
}
return 0;}
/*
int pipe1[2], pipe2[2];
pipe(pipe1);
pipe(pipe2);
int child_pid = fork();
if(child_pid > 0){
// close read1 and close write2, parent process write1
// read from read2
}else{
// close read2 and write1, child process read1
// write from write2
}
*/
|
C
|
#include "helpers.h"
#include <stdio.h>
#include <math.h>
// Convert image to grayscale
void grayscale(int height, int width, RGBTRIPLE image[height][width])
{
float avg;
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
avg = (image[i][j].rgbtBlue + image[i][j].rgbtGreen + image[i][j].rgbtRed) / (float) 3;
image[i][j].rgbtBlue = round(avg);
image[i][j].rgbtGreen = round(avg);
image[i][j].rgbtRed = round(avg);
}
}
return;
}
// Convert image to sepia
void sepia(int height, int width, RGBTRIPLE image[height][width])
{
//make copy
int sepiaRed = 0, sepiaGreen = 0, sepiaBlue = 0;
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
sepiaGreen = round(.349 * image[i][j].rgbtRed + .686 * image[i][j].rgbtGreen + .168 * image[i][j].rgbtBlue);
sepiaRed = round(.393 * image[i][j].rgbtRed + .769 * image[i][j].rgbtGreen + .189 * image[i][j].rgbtBlue);
sepiaBlue = round(.272 * image[i][j].rgbtRed + .534 * image[i][j].rgbtGreen + .131 * image[i][j].rgbtBlue);
image[i][j].rgbtRed = sepiaRed < 255? sepiaRed: 255;
image[i][j].rgbtGreen = sepiaGreen < 255? sepiaGreen: 255;
image[i][j].rgbtBlue = sepiaBlue < 255? sepiaBlue: 255;
}
}
return;
}
// Reflect image horizontally
void reflect(int height, int width, RGBTRIPLE image[height][width])
{
RGBTRIPLE tmp;
for (int i = 0; i < height; i++)
{
for (int j = 0, n = width / 2; j < n; j++)
{
tmp = image[i][j];
image[i][j] = image[i][width - j - 1];
image[i][width - j - 1] = tmp;
}
}
return;
}
// Blur image
RGBTRIPLE avg(RGBTRIPLE neighbor[], int num)
{
int red = 0, blue = 0, green = 0;
RGBTRIPLE result;
for (int i = 0; i < num; i++)
{
red += neighbor[i].rgbtRed;
blue += neighbor[i].rgbtBlue;
green += neighbor[i].rgbtGreen;
}
result.rgbtRed = round(red / (float) num);
result.rgbtBlue = round(blue / (float) num);
result.rgbtGreen = round(green / (float) num);
return result;
}
void blur(int height, int width, RGBTRIPLE image[height][width])
{
RGBTRIPLE copy[height][width];
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
copy[i][j] = image[i][j];
}
}
int idx[3] = {1, 0, -1};
RGBTRIPLE neighbor[9];
int counter = 0;
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
counter = 0;
for (int a = 0; a < 3; a++)
{
for (int b = 0; b < 3; b++)
{
if (i + idx[a] >= 0 && j + idx[b] >= 0 && i + idx[a] < height && j + idx[b] < width)
{
neighbor[counter] = image[i + idx[a]][j + idx[b]];
counter++;
}
}
}
copy[i][j] = avg(neighbor, counter);
}
}
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
image[i][j] = copy[i][j];
}
}
return;
}
|
C
|
/*
两种构建最大堆的方法:
1. 将元素一个一个Insert进堆中
2. 先把所有元素依次加入到完全二叉树中, 再调用MakeMaxHeap调整成堆
*/
#define INFINITE 1<<30
typedef int bool;
typedef int ElementType;
typedef struct HeapStruct *MaxHeap;
struct HeapStruct
{
ElementType *Elements; //存储堆元素的数组
int size; //堆中当前元素个数
int capacity; //堆的最大容量
};
/*创建一个空堆*/
MaxHeap CreateMaxHeap(int MaxSize)
{
MaxHeap H = malloc(sizeof(struct HeapStruct));
H->capacity = MaxSize;
H->Elements = malloc((MaxSize + 1) * sizeof(ElementType)); //堆中元素从下标为1的位置开始存放
H->size = 0;
H->Elements[0] = INFINITE; //0位置设立哨兵, 其值为最大数字
return H;
}
bool isFull(MaxHeap H)
{
return (H->size == H->capacity);
}
bool isEmpty(MaxHeap H)
{
return (H->size == 0);
}
/*将元素item插入到堆中,其中0号位置已经定义为哨兵*/
void Insert(MaxHeap H, ElementType item)
{
if (isFull(H))
{
printf("堆已满!\n");
return;
}
int i = ++H->size; //1.将H的元素个数加一个 2.用i指示最后一个元素的位置
for (; H->Elements[i / 2] < item; i /= 2) //从父节点开始一直往上比较,如果上面小,就把父亲往下挪一层
{//因为元素是从1号位置开始存的,所以正常i>1也要作为循环条件,而加入哨兵的意义就在此,跟哨兵比循环一定退出
H->Elements[i] = H->Elements[i / 2];
}
H->Elements[i] = item;
}
/*删除堆顶最大元素并重新调整成堆*/
ElementType DeleteMax(MaxHeap H)
{
if (isEmpty(H))
{
printf("堆为空!\n");
return INFINITE;
}
ElementType MaxItem = H->Elements[1]; //元素是从1开始存的
int Parent, Child;
ElementType tmp = H->Elements[H->size--]; //1.将最后位置的元素保存到tmp中 2.元素数减一
for (Parent = 1; Parent * 2 <= H->size; Parent = Child)
{//初始假设最后一个元素放到堆顶 一直往后找直到出界
/*将Child指向Parent最大的孩子*/
Child = Parent * 2;
if(Child!=H->size && //如果有右儿子再做第二个判断
(H->Elements[Child] < H->Elements[Child + 1])) {
Child++;
}
if (tmp > H->Elements[Child]) { break; }
else { H->Elements[Child] = H->Elements[Parent]; }
}
H->Elements[Parent] = tmp; //把最后一个元素归位
return MaxItem;
}
/*----------- 建造最大堆 -----------*/
void FilterDown(MaxHeap H, int current)
{
int Parent, Child;
ElementType tmp = H->Elements[current];
for (Parent = current; Parent * 2 <= H->size; Parent = Child)
{
Child = Parent * 2;
if (Child != H->size &&
(H->Elements[Child] < H->Elements[Child + 1])) {
Child++;
}
if (tmp >= H->Elements[Child]) { break; } //找到合适的位置
else { H->Elements[Parent] = H->Elements[Child]; }
}
H->Elements[Parent] = tmp;
}
void MakeMaxHeap(MaxHeap H)
{
for (int i = H->size / 2; i > 0; --i)
{//从最后一个非叶子结点开始向下调整成堆
FilterDown(H, i);
}
}
|
C
|
#include <stdio.h>
main() {
char inp[50];
char *rev;
int i, j=100,h;
char temp;
printf("Enter a line of text : ");
scanf("%[^\n]" ,inp);
printf("%s" ,inp);
j=(int) strlen(inp);
rev=(char *)malloc(j+1);
h=j;
for(i=0;i<h;i++) {
rev[i] = inp[j-1];
j--;
}
rev[i] = '\n';
printf("Here is the reversed verion : \n%s\n" ,rev);
}
|
C
|
/* Computer DJ */
#include <stdio.h>
char music[27][102];
int sum[50];
void newl() {
char ch;
while ((getchar() != '\n') && (ch != EOF));
}
int getint() {
int ch, i, sign = 1;
while (((ch = getchar()) == ' ') || (ch == '\n'));
if (ch == EOF) return (EOF);
for (i = 0; ch >= '0' && ch <= '9'; ch = getchar() )
i = 10 * i + (ch - '0');
ungetc(ch, stdin);
return i;
}
int main() {
int n, q, k;
int i, j;
int l, c, d, pos;
while (1) {
n = getint();
q = getint();
newl();
if ((!n) && (!q)) break;
for (i = 0; i < n; i++) scanf("%s%*c", music[i]);
if (n == 1) {
for (i = 0; i < q; i++) {
k = getint();
puts(music[0]);
}
putchar('\n');
continue;
}
sum[0] = 0;
j = n;
for (i = 0; sum[i] <= 100000000; i++) {
sum[i+1] = sum[i] + (i+1)*j;
j = j*n;
}
l = i;
for (i = 0; i < q; i++) {
k = getint();
for (j = 1; (j < l) && (sum[j] < k); j++);
c = j;
d = k-1-sum[c-1];
pos = c - (d%c);
k = d/c;
for (j = 1; j < pos; j++) k = k / n;
puts(music[k%n]);
}
putchar('\n');
}
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int main()
{
double c, c1;
int c2,c3;
printf("Conversor de Fahrenheit para Graus Celsius \n");
printf("Digite o numero a ser convertido: \n");
scanf("%f", &c1);
c=(c1-32.0) * (5.0/9.0);
printf("A conversao %.f Fahrenhit para graus Celsius eh igual a %.3f. \n", c1, c);
//printf("A conversao %.f Fahrenhit para graus Celsius eh igual a %.3f. \n", c2, c3);
return 0;
}
|
C
|
/*************************************
* Lab 3 Exercise 1
* Name: Jerrell Ezralemuel
* Student No: A0181002B
* Lab Group: 08
*************************************/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h> // For Predefined constants
#include <sys/ipc.h> // For POSIX IPC
#include <sys/shm.h> // For POSIX Shared Memory
int main()
{
int result, arraySize, initValue;
char* shdMemRegion;
int shdMemId, shdMemSize;
printf("Enter Array Size: ");
scanf("%i",&arraySize);
printf("Enter Start Value: ");
scanf("%i",&initValue);
// Create a new shared memory region
shdMemSize = sizeof(int) * (arraySize + 1);
shdMemId = shmget(IPC_PRIVATE, shdMemSize, IPC_CREAT | 0666);
if (shdMemId < 0){
printf("Cannot create shared memory region!\n");
exit(1);
}
printf("Shared Memory Id is %i\n",shdMemId);
// Attach a new shared memory region
shdMemRegion = (char*) shmat(shdMemId, NULL, 0);
if ( shdMemRegion == (char*) -1){
printf("Cannot attach shared memory region!\n");
exit(1);
}
int* arr = (int*) shdMemRegion;
// Initialize the shared memory region
for (int i = 0; i < arraySize; i++)
arr[i] = initValue + i;
arr[arraySize] = -1;
// Shared memory regions remained attached after fork()
// Parent and child can now communicate with each other!
result = fork();
if (result){ //Parent
int parentSum = 0;
for (int i = arraySize / 2; i < arraySize; i++)
parentSum += arr[i];
printf("Parent Sum = %d\n", parentSum);
while(arr[arraySize] == -1) sleep(0.1);
int childSum = arr[arraySize];
printf("Child Sum = %d\n", childSum);
printf("Total = %d\n", parentSum + childSum);
shmdt(shdMemRegion);
} else {
int childSum = 0;
for (int i = 0; i < arraySize / 2; i++)
childSum += arr[i];
arr[arraySize] = childSum;
shmdt(shdMemRegion);
return 0;
}
shmctl(shdMemId, IPC_RMID, NULL);
return 0;
}
|
C
|
// use hash ?? to find the next biggest ???
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* prevPermOpt1(int* A, int ASize, int* returnSize)
{
*returnSize = ASize;
int min = 10001;
int s[10001] = {0};
for (int i = ASize - 1; i >= 0; i --)
{
int c = A[i];
if (c > min)
{
for (int j = c - 1; j >= 0; j --)
if (s[j])
{
A[s[j] - 1] = c;
A[i] = j;
break;
}
break;
}
s[c] = i + 1;
min = min < c ? min : c;
}
return A;
}
|
C
|
#include <stdio.h>
#include <time.h>
int main(int argc, char const *argv[])
{
long int second_since_epoch;
struct tm current_time, *time_ptr;
int hour, minute, second, day, month, year;
second_since_epoch=time(0); // передает значение ,сколько прошло с начала эры,так сказать
printf("time() секунд с начала эры :%ld\n",second_since_epoch);
time_ptr=¤t_time;
localtime_r(&second_since_epoch,time_ptr);
hour=current_time.tm_hour;
minute=time_ptr->tm_min;
second=current_time.tm_sec;
printf("время %d h. %d min\n",hour,minute);
return 0;
}
|
C
|
/*Задача 9. Направете функця add(), която събира две точки.*/
#include <stdio.h>
struct point
{
int x;
int y;
};
void addPoints(struct point *a, struct point *b, struct point *c)
{
c->x = a->x + b->x;
c->y = a->y + b->y;
}
int main()
{
struct point a = {0, 5}, b = {3, 2}, c;
addPoints(&a, &b, &c);
printf("Resulting point is %d,%d\n", c.x, c.y);
return 0;
}
|
C
|
#include "scrollconsole.h"
#include <stdlib.h>
#include <string.h>
#include <tilesense.h>
ScrollConsole scrollconsole_new() {
return calloc(1, sizeof(struct _scroll_console));
}
ScrollConsole scrollconsole_init(ScrollConsole sc, int w, int h) {
sc->w = w;
sc->h = h;
sc->cons = TCOD_console_new(w, h);
sc->lines = TCOD_list_new();
return sc;
}
void scrollconsole_free(ScrollConsole sc) {
TCOD_console_delete(sc->cons);
TCOD_list_clear_and_delete(sc->lines);
free(sc);
}
void scrollconsole_push(ScrollConsole sc, char *msg) {
//for each line in msg:
//if the buffer is full:
//should shuffle all existing text up by one line
//then print line at the bottom
//otherwise: print line as far down as there is text.
TCOD_list_push(sc->lines, strdup(msg));
//now, figure out mappings from lines to y values.
//now, count backwards and count the number of real lines each line takes up. When we get past our height, that's the number of lines we want.
int lineCount = 0;
int elements = 0;
int lastLineCount = 0;
for(int i = TCOD_list_size(sc->lines)-1; i >= 0; i--) {
char *line = TCOD_list_get(sc->lines, i);
lastLineCount = TCOD_console_height_left_rect(sc->cons, 0, 0, sc->w, sc->h, line);
lineCount += lastLineCount;
elements++;
//we have more lines than we need. first of all, we need to counteract the element addition.
if(lineCount > sc->h) {
elements--;
//now, pop off the last dealie and insert blank lines to fill the empty space
int fullLines = (lineCount - lastLineCount);
int underFlow = sc->h - fullLines - 1;
for(int j = 0; j < underFlow; j++) {
lineCount--;
TCOD_list_insert_before(sc->lines, strdup(" "), i+1);
//we want this blank line in the output
elements++;
}
}
if(lineCount == sc->h) {
//this is the last line, break.s
break;
}
}
//now, chop off the lines we won't be printing any of
while(TCOD_list_size(sc->lines) > elements) {
char *l = TCOD_list_get(sc->lines, 0);
TCOD_list_remove(sc->lines, l);
free(l);
}
//now, insert blank lines at the beginning if we're in the unenviable position of scrolling out an old line
TCOD_console_clear(sc->cons);
int currentY = (lineCount > sc->h) ? sc->h : lineCount;
for(int i = TCOD_list_size(sc->lines)-1; i >= 0; i--) {
char *line = TCOD_list_get(sc->lines, i);
currentY -= TCOD_console_height_left_rect(sc->cons, 0, 0, sc->w, sc->h, line);
TCOD_console_print_left_rect(sc->cons, 0, currentY, sc->w, sc->h, line);
if(currentY < 0) {
break;
}
}
}
void scrollconsole_blit(ScrollConsole sc, TCOD_console_t dest, int destX, int destY, char destOpacity) {
TCOD_console_blit(sc->cons, 0, 0, sc->w, sc->h, dest, destX, destY, destOpacity, destOpacity);
}
|
C
|
// Copyright © 2021 Kris Nóva <[email protected]>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// ███╗ ██╗ ██████╗ ██╗ ██╗ █████╗
// ████╗ ██║██╔═████╗██║ ██║██╔══██╗
// ██╔██╗ ██║██║██╔██║██║ ██║███████║
// ██║╚██╗██║████╔╝██║╚██╗ ██╔╝██╔══██║
// ██║ ╚████║╚██████╔╝ ╚████╔╝ ██║ ██║
// ╚═╝ ╚═══╝ ╚═════╝ ╚═══╝ ╚═╝ ╚═╝
#include "dname.h"
#include "bijective.h"
#include "names.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
/**
* dname_bijection()
*
* Take a 32 byte digest from sha-256 and create an 8 byte
* bijective name from the name list.
*
* ----------------------------------------------------------+
* Each SHA-256 Digest is 32 Bytes ling. |
* 32 Bytes = (32 * 8 bits) = 256 bits = {0,255} |
* 32 Bytes = 8 Bytes * 4 Segments |
* ----------------------------------------------------------+
*
*
* [ 8 Bytes ] 1 Segment
* +---------------------------------------------------------+
* | [ 0] [ 1] [ 2] [ 3] [ 4] [ 5] [ 6] [ 7] |
* | [255] [255] [255] [255] [255] [255] [255] [255] |
* | [16^2] [16^2] [16^2] [16^2] [16^2] [16^2] [16^2] [16^2] |
* | [0F] [0F] [0F] [0F] [0F] [0F] [0F] [0F] |
* +---------------------------------------------------------+
*
*
* [8 Bytes] 4 Pairs (1 Pair = 0->130,560)
* +---------------------------------------------------------+
* | [ 0] [ 1] [ 2] [ 3] [ 4] [ 5] [ 6] [ 7] |
* | [0,130560 ] [0,130560 ] [0,130560 ] [0,130560 ] |
* +---------------------------------------------------------+
*
* dname_bijection is a deterministic bijective function for
* a 32 byte sha256 digest.
*
* @param digest
*/
void dname_bijection(struct dname_digest *digest) {
// [8 Byte] truncated bijective name
// -------------------------------------------------------------------------------------
// Allocate 32 bits * 4 words + 3 dashes + 1 bit
char *name = malloc(DNAME_SHA256_DIGEST_32 * 4 + 4);
char *s0 = getnamei(dname_pair(digest->sha256hash[0], digest->sha256hash[1]));
char *s1 = getnamei(dname_pair(digest->sha256hash[2], digest->sha256hash[3]));
char *s2 = getnamei(dname_pair(digest->sha256hash[4], digest->sha256hash[5]));
char *s3 = getnamei(dname_pair(digest->sha256hash[6], digest->sha256hash[7]));
sprintf(name,"%s-%s-%s-%s", s0, s1, s2, s3);
digest->name = malloc(strlen( name));
strcpy(digest->name, name);
free(name);
// -------------------------------------------------------------------------------------
}
// dname_pair implements the Cantor pairing function for
// deterministically pairing integers together.
/**
* dname_pair()
*
* Use math (The Cantor Pairing Function) to deterministically pair integers together.
*
* We know we are paring bytes, so we know this value will never exceed 130,560.
*
* @param i1
* @param i2
* @return int
*/
int dname_pair(int i1, int i2) {
return (i1+i2) * (i1+i2+1) / 2 + i2;
}
|
C
|
#include "stego.h"
// reads the PGM file and fills in the values for image
void
readImage( char fileName[], Image *image )
{
FILE *in = fopen( fileName, "rb" );
if( in == NULL )
error( "File was not opened correctly!");
char buffer[100];
if( fgets( buffer, 100, in ) == NULL )
error( "Error reading magic number!" );
if( strcmp( "P5\n", buffer) != 0 )
error( "File's magic number must be P5!" );
strcpy( image->name, fileName );
// iterate through all comments to find height & width of image
while( 1 )
{
if( fgets( buffer, 50, in ) == NULL )
error( "End of file reached when looking for image height & width!");
if( buffer[0] == '#' )
continue;
sscanf(buffer,"%d %d",&(image->width),&(image->height));
break;
}
// iterate through all comments to find max grayscale value
while( 1 )
{
if( fgets( buffer, 100, in ) == NULL )
error( "End of file reached when looking for max grayscale value!");
if( buffer[0] == '#' )
continue;
sscanf( buffer, "%d", &(image->maxVal));
break;
}
image->data = (unsigned char *) malloc( sizeof( unsigned char ) * image->width * image->height );
if( image->data == NULL )
error( "Not enough memory!" );
int i, j, k;
k = 0;
for( i = 0; i < image->height; i++ ){
for( j = 0; j < image->width; j++ ){
fscanf( in, "%c", &(image->data[k++]) );
}
}
fclose( in );
}
void
writeImage( char fileName[], Image *image )
{
FILE *out = fopen( fileName, "wb" );
if( out == NULL )
error( "Error when writing a new PGM file!" );
fprintf( out, "%s\n%d %d\n%d\n", "P5", image->width, image->height, 255 );
int i, j, k;
k = 0;
for( i = 0; i < image->height; i++ ){
for( j = 0; j < image->width; j++ ){
fwrite( &(image->data[k++]), sizeof( unsigned char ), 1, out );
}
}
fclose( out );
}
void
readPayload( char *fileName, Payload *payload )
{
FILE *pf = fopen( fileName, "rb" );
if( pf == NULL )
error( "Could not open payload file!" );
unsigned char storage[4096]; // max amount of storage
payload->size = fread( storage, sizeof(unsigned char), 4096, pf );
payload->data = malloc( sizeof( unsigned char ) * payload->size );
int i;
for( i = 0; i < payload->size; i++ )
payload->data[i] = storage[i];
fclose( pf );
}
void
setlsbs( unsigned char p[], unsigned char b0, int total, Image *img )
{
int i = 0;
int iter;
for( iter = total - 8; iter < total; iter++ )
{
img->data[iter] |= (b0 >> i) & 0x01;
if( (img->data[iter] % 2) && (b0 >> i) % 2 == 0 ){
img->data[iter]--;
}
i++;
}
}
void
printBinary( unsigned char byte )
{
int rtnByte[8];
rtnByte[7] = (byte & 0x80) > 0 ? 1 : 0;
rtnByte[6] = (byte & 0x40) > 0 ? 1 : 0;
rtnByte[5] = (byte & 0x20) > 0 ? 1 : 0;
rtnByte[4] = (byte & 0x10) > 0 ? 1 : 0;
rtnByte[3] = (byte & 0x08) > 0 ? 1 : 0;
rtnByte[2] = (byte & 0x04) > 0 ? 1 : 0;
rtnByte[1] = (byte & 0x02) > 0 ? 1 : 0;
rtnByte[0] = (byte & 0x01) > 0 ? 1 : 0;
int i;
for( i = 7; i >= 0; i-- )
{
printf("%d", rtnByte[i]);
}
printf("\n");
}
void
error( char *msg )
{
printf("%s", msg );
exit( 1 );
}
|
C
|
#include <quicksort.h>
#include <assert.h>
void fill_test_data(int v[], int n) {
int i;
srandomdev();
for (i = 0; i < n; i++) {
v[i] = random();
}
}
int is_sorted(int v[], int n) {
int i;
for (i = 1; i < n; i++) {
if (v[i - 1] > v[i]) {
return 0;
}
}
return 1;
}
enum { TEST_SIZE = 200000 };
int main(void) {
int i, nums[TEST_SIZE];
fill_test_data(nums, TEST_SIZE);
fprintf(stderr, ">> 100 => %d\n", nums[99]);
fprintf(stderr, ">> end => %d\n", nums[TEST_SIZE - 1]);
assert(( is_sorted(nums, TEST_SIZE) == 0 ) && "test data is sorted");
quicksort(nums, TEST_SIZE);
assert(( is_sorted(nums, TEST_SIZE) == 1 ) && "test data is NOT sorted");
for (i = 0; i < TEST_SIZE; i++) {
if ((i % 100) == 0)
fprintf(stderr, "nums[i] = %d\n", nums[i]);
}
return 0;
}
|
C
|
#include<stdio.h>
#include<string.h>
int abc(char ar[1009])
{
int a,b,c,d,i,j,k;
d=strlen(ar);
c=0;
k=1;
b=0;
a=0;
for(i=0;i<d;i++){
if(ar[i]=='('){
c++;
a++;
}
if(ar[i]==')'){
c--;
b++;
if(c<0){
k=0;
break;
}
}
}
if(a!=b)
k=0;
return k;
}
int main()
{
int a,b,c,d,i,j,k;
char ar[1009];
while(scanf("%s%*c",ar)!=EOF){
k=abc(ar);
if(k==1)
printf("correct\n");
else
printf("incorrect\n");
}
return 0;
}
|
C
|
// Implement the Queues with structures pointers
#include <stdio.h>
#include <stdlib.h>
struct queue
{
int q[20];
int head;
int tail;
int max;
};
int main() {
struct queue *q;
q = (struct queue *) malloc(sizeof(struct queue));
q->head = -1;
q->tail = -1;
printf("Input the size of queue: ");
scanf("%d",&q->max);
int ele,opt;
do{
printf("Select an option to perform on queue\n1. Enqueue\n2. Dequeue\n 3. Exit\n __ ");
scanf("%d",&opt);
switch (opt)
{
case 1:
if(q->tail == q->max - 1) {
printf("Queue is full can't enqueue.\n");
}else if(q->tail != q->max - 1) {
printf("Enter the element to insert in Queue: ");
scanf("%d",&ele);
q->q[++q->tail] = ele;
}
break;
case 2:
if(q->head == q->tail) {
printf("Queue is empty can't dequeue.\n");
}else if(q->head != q->tail) {
printf("The element got Dequeued is: %d\n",q->q[++q->head]);
}
break;
case 3:
printf("Hey you have exited..");
default:
break;
}
}while(opt != 3);
}
//Vivek Tej B172299
|
C
|
#include "config.h"
#include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h>
#include <unistd.h>
#include "sensor_db.h"
/* when DB connection fails we wait a bit
* then reconnect, after 3 attempts we close
*/
#define conn_attempt_wait 0.3
/*If the table existed, clear up the existing data if clear_up_flag is set to 1 */
DBCONN * init_connection(char clear_up_flag)
{
DBCONN *conn;
char *err_msg = 0;
char *sql;
int rc = sqlite3_open(TO_STRING(DB_NAME), &conn);
if (rc != SQLITE_OK)
{
DEBUG_PRINTF("Cannot open database: %s\n", sqlite3_errmsg(conn));
WRITE_FIFO("Cannot open database: %s\n", sqlite3_errmsg(conn));
sqlite3_close(conn);
free(err_msg);
return NULL;
}
DEBUG_PRINTF("Connection to SQL server established\n");
WRITE_FIFO("Connection to SQL server established\n");
/* when clear_up is needed */
if(clear_up_flag == 1)
{
asprintf(&sql,"DROP TABLE IF EXISTS %s;", TO_STRING(TABLE_NAME));
rc = sqlite3_exec(conn, sql, 0, 0, &err_msg);
if(rc!= SQLITE_OK)
{
DEBUG_PRINTF("Cannot drop the table: %s\n",sqlite3_errmsg(conn));
sqlite3_close(conn);
free(sql);
sqlite3_free(err_msg);
return NULL;
}
OBSERVE_PRINTF("Table dropped\n");
DEBUG_PRINTF("Table dropped\n");
free(sql);
}
asprintf(&sql, "CREATE TABLE %s(Id INTEGER PRIMARY KEY, sensor_id INT, sensor_value DECIMAL(4,2), timestamp TIMESTAMP);", TO_STRING(TABLE_NAME));
rc = sqlite3_exec(conn, sql, 0, 0, &err_msg);
if (rc != SQLITE_OK )
{
DEBUG_PRINTF("Initialization: %s\n", sqlite3_errmsg(conn));
sqlite3_free(err_msg);
free(sql);
return conn;
}
else
{
WRITE_FIFO("New table %s created\n", TO_STRING(TABLE_NAME));
OBSERVE_PRINTF("New table %s created\n", TO_STRING(TABLE_NAME));
DEBUG_PRINTF("New table %s created\n", TO_STRING(TABLE_NAME));
}
free(sql);
free(err_msg);
return conn;
}
void storagemgr_parse_sensor_data(DBCONN * conn, sbuffer_t ** buffer)
{
printf("HERE WE CAN SEE IF THE VARIABLE FORTEST IS ACCESSIBLE IN STORAGEMGR: %d\n", forTest);
int nr_conn_fail = 0;
sbuffer_t * buffer_temp = (sbuffer_t *)*buffer;
sensor_data_t * data = malloc(sizeof(sensor_data_t));
ERR_HANDLER(data == NULL, ERROR_MEMORY);
while(sbuffer_remove(buffer_temp, data) == SBUFFER_SUCCESS)
{
OBSERVE_PRINTF("The above sensor data read by storagemgr\n");
sensor_id_t id = data->id;
sensor_value_t value = data->value;
sensor_ts_t ts = data->ts;
/*check if DB connection fails*/
while (insert_sensor(conn,id, value, ts) == 1)
{
if(nr_conn_fail == 3)
{
/* if 3 failed attempts, no more wait
and close this whole manager*/
DEBUG_PRINTF("3 attempts failed = CONNECTION LOST");
WRITE_FIFO("Connection to SQL server lost\n");
free(data);
return;
}
sleep(conn_attempt_wait);
nr_conn_fail++;
}
}
OBSERVE_PRINTF("Storagemgr: NO DATA IN THE BUFFER or BUFFER IS NULL\n");
free(data);
}
void disconnect(DBCONN *conn)
{
OBSERVE_PRINTF("Connection to SQL server lost\n");
DEBUG_PRINTF("Connection to SQL server lost\n");
WRITE_FIFO("Connection to SQL server lost\n");
sqlite3_close(conn);
}
int insert_sensor(DBCONN * conn, sensor_id_t id, sensor_value_t value, sensor_ts_t ts)
{
char *err_msg = 0;
char* sql;
asprintf(&sql,"INSERT INTO %s VALUES(NULL,%f,%f,%f)", TO_STRING(TABLE_NAME),(double)id,(double)value, (double)ts);
int rc = sqlite3_exec(conn, sql, 0, 0, &err_msg);
free(sql);
//sqlite3_free(err_msg);
if (rc == SQLITE_OK )
{
OBSERVE_PRINTF("Sensor data inserted\n");
return 0; //successful,return 0
}
DEBUG_PRINTF("Error: %s\n",sqlite3_errmsg(conn));
sqlite3_free(err_msg);
return 1; //fail, return 1
}
/*
int insert_sensor_from_file(DBCONN * conn, FILE * sensor_data)
{
sensor_value_t value=0.0;
sensor_id_t id;
sensor_ts_t ts;
while(!feof(sensor_data))
{
//fread(&id,sizeof(sensor_id_t),1,sensor_data);
//fread(&value,sizeof(sensor_value_t),1,sensor_data);
//fread(&ts,sizeof(sensor_ts_t),1,sensor_data);
if((fread(&id,sizeof(sensor_id_t),1,sensor_data)==0) || (fread(&value,sizeof(sensor_value_t),1,sensor_data)==0) || (fread(&ts,sizeof(sensor_ts_t),1,sensor_data)==0))
{
fprintf(stdout,"Cannot read data from the FILE\n");
return 1;
}
else
{
fread(&id,sizeof(sensor_id_t),1,sensor_data);
fread(&value,sizeof(sensor_value_t),1,sensor_data);
fread(&ts,sizeof(sensor_ts_t),1,sensor_data);
//insert_sensor(conn, id, value, ts);
} //data read successfully
if(insert_sensor(conn, id, value, ts) == 0)
{
fprintf(stdout,"Data from the FILE inserted\n");
}
else
{
fprintf(stderr,"Cannot insert data\n");
return 1;
}
}
return 0;
}
*/
int find_sensor_all(DBCONN * conn, callback_t f) //return all sensor measurements
{
char *err_msg = 0;
char* sql;
asprintf(&sql,"SELECT * FROM %s;", TO_STRING(TABLE_NAME));
int rc = sqlite3_exec(conn, sql, f, 0, &err_msg); // third parameter is for call back function
free(sql);
if (rc != SQLITE_OK )
{
DEBUG_PRINTF("Error: %s\n",sqlite3_errmsg(conn));
sqlite3_free(err_msg);
return 1;
}
sqlite3_free(err_msg);
return 0;
}
int find_sensor_by_value(DBCONN * conn, sensor_value_t value, callback_t f)
{
char *err_msg = 0;
char* sql;
asprintf(&sql,"SELECT * FROM %s WHERE sensor_value=%g", TO_STRING(TABLE_NAME), value);
int rc = sqlite3_exec(conn, sql, f, 0, &err_msg);
free(sql);
if (rc != SQLITE_OK )
{
DEBUG_PRINTF("Error: %s\n",err_msg);
sqlite3_free(err_msg);
return 1;
}
sqlite3_free(err_msg);
return 0;
}
int find_sensor_exceed_value(DBCONN * conn, sensor_value_t value, callback_t f)
{
char *err_msg = 0;
char* sql;
asprintf(&sql, "SELECT * FROM %s WHERE sensor_value>%g", TO_STRING(TABLE_NAME), value);
int rc = sqlite3_exec(conn, sql, f, 0, &err_msg);
free(sql);
if (rc != SQLITE_OK )
{
DEBUG_PRINTF("Error: %s",err_msg);
sqlite3_free(err_msg);
return 1;
}
sqlite3_free(err_msg);
return 0;
}
int find_sensor_by_timestamp(DBCONN * conn, sensor_ts_t ts, callback_t f)
{
char *err_msg = 0;
char *sql;
asprintf(&sql,"SELECT * FROM %s WHERE timestamp=%ld;", TO_STRING(TABLE_NAME), ts);
int rc = sqlite3_exec(conn, sql, f, 0, &err_msg);
free(sql);
if (rc != SQLITE_OK )
{
DEBUG_PRINTF("Error: %s",err_msg);
sqlite3_free(err_msg);
return 1;
}
sqlite3_free(err_msg);
return 0;
}
int find_sensor_after_timestamp(DBCONN * conn, sensor_ts_t ts, callback_t f)
{
char *err_msg = 0;
char* sql;
asprintf(&sql,"SELECT * FROM %s WHERE timestamp>%ld;", TO_STRING(TABLE_NAME), ts);
int rc = sqlite3_exec(conn, sql, f, 0, &err_msg);
free(sql);
if (rc != SQLITE_OK )
{
DEBUG_PRINTF("Error: %s",err_msg);
sqlite3_free(err_msg);
return 1;
}
sqlite3_free(err_msg);
return 0;
}
|
C
|
#ifndef __MULLINSN__TODO__
#define __MULLINSN__TODO__
//will close the file, print an error msg and then exit
void exitWithError(char* line, FILE* f);
//parse through the file and load the ints into an array
void parseFile(char arr[20][10][3]);
//swap a with b
void swap(int* a, int* b);
//perform downheap on an array based heap
void downHeap(int arr[20]);
//gets the key of a given line
int getKey(char arr[20][10][3], int i);
//prints a line given a key
void printKey(int key, char arr[20][10][3]);
#endif
|
C
|
#include "monty.h"
/**
* pop - This removes the top element of the stack.
* @command: This is data we are accessing from the command.
*
* Return: Void.
*/
void pop(command_t *command)
{
stack_t **head = command->head;
stack_t *the_removed = NULL;
if (head == NULL || *head == NULL)
{
printf("L%d: can't pop an empty stack\n",
command->line_number);
exit(EXIT_FAILURE);
}
the_removed = *head;
*head = (*head)->next;
free(the_removed);
}
|
C
|
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void hicm()
{
float no,nocov;
printf("Enter your height :");
scanf("%f", &no);
nocov=no/30.48;
printf("\nYour height in feet is %f",nocov);
}
void hift()
{
float no,nocov;
printf("Enter your height :");
scanf("%f", &no);
nocov=no*30.48;
printf("\nYour height in cm is %f",nocov);
}
void yes()
{
printf("1) From cm to feet \n2) For feet to cm\n3) Exit");
}
void no()
{
printf("No Problem");
}
int main()
{
int ch,ch1;
printf("Do you want to know your height ?\n");
printf("1) From cm to feet \n2) For feet to cm \n3) Exit");
while(1)
{
printf("\nEnter your choice: ");
scanf("%d",&ch);
switch(ch)
{
case 1:hicm();
break;
case 2:hift();
break;
case 3:exit(0);
default:printf("Invalid Choice\n");
}
printf("\nDo you want to print menu (0/1)");
printf("\nType.... \n");
scanf("%d",&ch1);
switch(ch1)
{
case 0:yes();
break;
case 1:no();
exit(0);
break;
default:printf("Incorrect Value");
}
}
return 0;
}
|
C
|
#include<stdio.h>
#include <stdlib.h>
struct A
{
int x;
char *str; // (or) char str[20];
};
main()
{
struct A a1 = { 101, "abc" } , a2;
a1.x=10;
a1.str="hello"; //works?:-when we used array this not works array assignment used only integer value.
scanf("%d%s",&a1.x,a1.str); //works?:- when we used pointer this not works because pointer cannot get input directly
a2 = a1; //shallow copy or deep copy?:- yes works in both.
}
|
C
|
#include "genresult.cuh"
#include <sys/time.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct{
int row;
int num;
}rowstruct;
typedef struct ohyah{
int index;
struct ohyah * next;
}list;
int cmpfunc (const void * a, const void * b)
{
rowstruct * ap = (rowstruct *)a;
rowstruct * bp = (rowstruct *)b;
return ( ap-> num - bp->num );
}
void getMulDesign(MatrixInfo * mat, MatrixInfo * vec, MatrixInfo * res, int blockSize, int blockNum){
/*change rows according to count to avoid thread Divergence */
list ** array = (list **) calloc(mat->M, sizeof(list *));
int * count = (int *)calloc(mat -> M, sizeof(int));
rowstruct * hello = (rowstruct *) calloc(mat -> M, sizeof(rowstruct));
float * tempval = (float *)calloc(mat->nz, sizeof(float));
int * temprIndex =(int *) calloc(mat->nz, sizeof(int));
int * tempcIndex =(int *)calloc(mat->nz, sizeof(int));
int i;
/*Count the numbers of appearce of each row*/
for(i=0; i< mat-> nz; i++){
count[mat->rIndex[i]]++;
list * prev = array[mat->rIndex[i]];
/*fill in linked list*/
if (prev == NULL){
list * add = (list * )calloc(1, sizeof(list));
add->index = i;
add->next = NULL;
array[mat->rIndex[i]] = add;
}else{
while(prev->next != NULL){
prev = prev->next;
}
list * add = (list * )calloc(1, sizeof(list));
add->index = i;
add->next = NULL;
prev->next = add;
}
}
for(i=0;i< mat->M;i++){
hello[i].row = i;
hello[i].num = count[i];
}
qsort (hello, mat->M, sizeof(rowstruct), cmpfunc);
int countrow = 0;
for(i=0; i<mat->M; i++){
int rowindex = hello[i].row;
list * node = array[rowindex];
while( node != NULL){
temprIndex[countrow] = mat->rIndex[node->index];
tempcIndex[countrow] = mat->cIndex[node->index];
tempval[countrow] = mat->val[node->index];
countrow++;
node = node->next;
}
}
memcpy(mat ->rIndex , temprIndex, mat->nz * sizeof(int));
memcpy(mat ->cIndex , tempcIndex, mat->nz * sizeof(int));
memcpy(mat -> val, tempval, mat->nz * sizeof(float));
free(tempval);
free(tempcIndex);
free(temprIndex);
free(count);
/*Allocate things...*/
/**/
cudaError_t err = cudaSuccess;
int size = mat -> nz;
printf("Start Device Memory Allocation \n");
/*Device Allocation -- coord_row*/
int * coord_row =NULL;
err = cudaMalloc((void **)&coord_row, size*sizeof(int));
if (err != cudaSuccess)
{
fprintf(stderr, "Failed to allocate device coord_row (error code %s)!\n", cudaGetErrorString(err));
exit(EXIT_FAILURE);
}
/*Device Allocation -- coord_col*/
int * coord_col =NULL;
err = cudaMalloc((void **)&coord_col, size*sizeof(int));
if (err != cudaSuccess)
{
fprintf(stderr, "Failed to allocate device coord_col (error code %s)!\n", cudaGetErrorString(err));
exit(EXIT_FAILURE);
}
/*Device Allocation -- value of Matrix A*/
float * d_A =NULL;
err = cudaMalloc((void **)&d_A, size*sizeof(float));
if (err != cudaSuccess)
{
fprintf(stderr, "Failed to allocate device d_A (error code %s)!\n", cudaGetErrorString(err));
exit(EXIT_FAILURE);
}
/*Device Allocation -- d_x Vector*/
float * d_x =NULL;
err = cudaMalloc((void **)&d_x, vec->M*sizeof(float));
if (err != cudaSuccess)
{
fprintf(stderr, "Failed to allocate device d_x Vector (error code %s)!\n", cudaGetErrorString(err));
exit(EXIT_FAILURE);
}
/*Device Allocation -- d_y Vector*/
float * d_y =NULL;
err = cudaMalloc((void **)&d_y, mat->M*sizeof(float));
if (err != cudaSuccess)
{
fprintf(stderr, "Failed to allocate device d_y Result (error code %s)!\n", cudaGetErrorString(err));
exit(EXIT_FAILURE);
}
printf("Start Copying contents \n");
/*Device Memcpy */
err = cudaMemcpy(coord_row, mat->rIndex, size*sizeof(int), cudaMemcpyHostToDevice);
if (err != cudaSuccess)
{
fprintf(stderr, "Failed to copy rindex from host to device (error code %s)!\n", cudaGetErrorString(err));
exit(EXIT_FAILURE);
}
err = cudaMemcpy(coord_col, mat->cIndex, size*sizeof(int), cudaMemcpyHostToDevice);
if (err != cudaSuccess)
{
fprintf(stderr, "Failed to copy cindex from host to device (error code %s)!\n", cudaGetErrorString(err));
exit(EXIT_FAILURE);
}
err = cudaMemcpy(d_A, mat->val, size*sizeof(float), cudaMemcpyHostToDevice);
if (err != cudaSuccess)
{
fprintf(stderr, "Failed to copy val from host to device (error code %s)!\n", cudaGetErrorString(err));
exit(EXIT_FAILURE);
}
err = cudaMemcpy(d_x, vec->val, vec->M*sizeof(float), cudaMemcpyHostToDevice);
if (err != cudaSuccess)
{
fprintf(stderr, "Failed to copy Vector from host to device (error code %s)!\n", cudaGetErrorString(err));
exit(EXIT_FAILURE);
}
float *init = (float *)calloc(mat->M,sizeof(float));
err = cudaMemcpy(d_y, init, mat->M*sizeof(float), cudaMemcpyHostToDevice);
if (err != cudaSuccess)
{
fprintf(stderr, "Failed to copy Vector from host to device (error code %s)!\n", cudaGetErrorString(err));
exit(EXIT_FAILURE);
}
/**/
/**/
struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC_RAW, &start);
/*Your own magic here*/
/**/
putProduct_kernel<<<blockNum,blockSize>>>(size, coord_row,coord_col,d_A,d_x,d_y);
err = cudaGetLastError();
if (err != cudaSuccess)
{
fprintf(stderr, "Failed to launch spmvAtomic kernel (error code %s)!\n", cudaGetErrorString(err));
exit(EXIT_FAILURE);
}
/* Write back from Device*/
printf("Copy output data from the CUDA device to the host memory\n");
err = cudaMemcpy(res->val, d_y, mat->M * sizeof(float), cudaMemcpyDeviceToHost);
if (err != cudaSuccess)
{
fprintf(stderr, "Failed to copy d_y from device to host (error code %s)!\n", cudaGetErrorString(err));
exit(EXIT_FAILURE);
}
/**/
cudaDeviceSynchronize();
clock_gettime(CLOCK_MONOTONIC_RAW, &end);
printf("Your Own Kernel Time: %lu micro-seconds\n", 1000000 * (end.tv_sec - start.tv_sec) + (end.tv_nsec - start.tv_nsec) / 1000);
/*Deallocate, please*/
/**/
err = cudaFree(coord_row);
if (err != cudaSuccess)
{
fprintf(stderr, "Failed to free device coord_row (error code %s)!\n", cudaGetErrorString(err));
exit(EXIT_FAILURE);
}
err = cudaFree(coord_col);
if (err != cudaSuccess)
{
fprintf(stderr, "Failed to free device coord_col (error code %s)!\n", cudaGetErrorString(err));
exit(EXIT_FAILURE);
}
err = cudaFree(d_A);
if (err != cudaSuccess)
{
fprintf(stderr, "Failed to free device d_A(error code %s)!\n", cudaGetErrorString(err));
exit(EXIT_FAILURE);
}
err = cudaFree(d_x);
if (err != cudaSuccess)
{
fprintf(stderr, "Failed to free device d_x (error code %s)!\n", cudaGetErrorString(err));
exit(EXIT_FAILURE);
}
err = cudaFree(d_y);
if (err != cudaSuccess)
{
fprintf(stderr, "Failed to free device d_y (error code %s)!\n", cudaGetErrorString(err));
exit(EXIT_FAILURE);
}
free(init);
err = cudaDeviceReset();
if (err != cudaSuccess)
{
fprintf(stderr, "Failed to deinitialize the device! error=%s\n", cudaGetErrorString(err));
exit(EXIT_FAILURE);
}
/**/
}
|
C
|
#include<stdio.h>
int main()
{
int l=0,i,n,a;
printf("entr limit");
scanf("%d",&n);
printf("entr nmbr");
for(i=1;i<=n;i++)
{
scanf("%d",&a);
if(a>l)
l=a;
}
printf("\n largst nmbr= %d ",l);
}
|
C
|
#include <stdio.h>
#include <stdlib.h> // malloc, free Լ
struct Phone { // ȭ ü
int areacode; // ȣ
unsigned long long number; // ȭ ȣ
};
struct Person { // ü
char name[20]; // ̸
int age; //
struct Phone phone; // ȭ. ü
};
int main()
{
struct Person *p1 = malloc(sizeof(struct Person)); // ü Ϳ Ҵ
p1->phone.areacode = 82; // ->. Ͽ Ҵ
p1->phone.number = 3045671234; // ->. Ͽ Ҵ
printf("%d %llu\n", p1->phone.areacode, p1->phone.number); // 82 3045671234
free(p1); //
return 0;
}
|
C
|
#include "device_functions.h"
#include <libopencm3/stm32/rcc.h>
#include <libopencm3/stm32/gpio.h>
#include <libopencm3/stm32/flash.h>
#include <libopencm3/stm32/pwr.h>
/* Function to Initialise all GPIOs */
void vGPIOInitialize() {
/* Enable GPIOC clock. */
rcc_periph_clock_enable(RCC_GPIOB);
/* System LED */
gpio_mode_setup(GPIOB, GPIO_MODE_OUTPUT, GPIO_PUPD_NONE, GPIO0);
/* Status LED */
gpio_mode_setup(GPIOB, GPIO_MODE_OUTPUT, GPIO_PUPD_NONE, GPIO7);
/* Warning LED */
gpio_mode_setup(GPIOB, GPIO_MODE_OUTPUT, GPIO_PUPD_NONE, GPIO14);
}
/* Function to Toggle System LED */
void vSystemLEDToggle() {
gpio_toggle(GPIOB, GPIO0);
}
/* Function to Toggle Status LED */
void vStatusLEDToggle() {
gpio_toggle(GPIOB, GPIO7);
}
/* Function to Toggle Warning LED */
void vWarningLEDToggle() {
gpio_toggle(GPIOB, GPIO14);
}
/* Initialise All System Clock Architecture */
// TODO: investigate systick divisor (currently 64 seems to work)
void vConfigureClock() {
struct rcc_clock_scale rcc_config;
/* Clock Configuration Settings */
rcc_config.plln = SYSCLK_FREQ/500000;
rcc_config.pllp = 0x02; // PLLP divisor of 2
rcc_config.pllq = 0x04; // PLLQ divisor of 4
rcc_config.flash_waitstates = FLASH_ACR_LATENCY_3WS;
rcc_config.hpre = RCC_CFGR_HPRE_DIV_NONE;
rcc_config.ppre1 = RCC_CFGR_PPRE_DIV_2;
rcc_config.ppre2 = RCC_CFGR_PPRE_DIV_NONE;
rcc_config.vos_scale = PWR_SCALE1; // Max power mode
rcc_config.overdrive = 0; // No overdrive
rcc_config.ahb_frequency = SYSCLK_FREQ;
rcc_config.apb1_frequency = SYSCLK_FREQ/2;
rcc_config.apb2_frequency = SYSCLK_FREQ;
/* Write Clock Configuration to RCC */
rcc_clock_setup_hse(&rcc_config, HSE_FREQ);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strsplit.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: lucmarti <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/11/09 11:56:50 by lucmarti #+# #+# */
/* Updated: 2018/11/14 18:44:00 by lucmarti ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int ft_getdim(char const *s, char c)
{
while (*s != '\0')
{
if (*s != c)
{
while (*s != c && *s != '\0')
++s;
return (1 + ft_getdim(s, c));
}
++s;
}
return (0);
}
static int ft_getlength(char const *s, char c)
{
int i;
i = 0;
while (*s != '\0' && *s != c)
{
++s;
++i;
}
return (i);
}
static int ft_getsplit(char const *s, char c, char **tab, int j)
{
int i;
size_t splitlength;
i = 0;
splitlength = 0;
while (*s != '\0')
{
if (*s != c)
{
splitlength = ft_getlength(s, c);
if (!(tab[i] = (char *)malloc(sizeof(char) * (splitlength + 1))))
return (0);
j = 0;
while (*s != c && *s != '\0')
{
tab[i][j] = *s;
++s;
++j;
}
tab[i++][splitlength] = '\0';
}
else
++s;
}
return (1);
}
char **ft_strsplit(char const *s, char c)
{
char **tab;
size_t splitlength;
if (!s)
return (NULL);
splitlength = ft_getdim(s, c);
if (!(tab = (char **)malloc(sizeof(char*) * (splitlength + 1))))
return (NULL);
tab[splitlength] = 0;
return (ft_getsplit(s, c, tab, 0) ? tab : NULL);
}
|
C
|
// SKIP PARAM: --set ana.activated[+] "'file'" --enable ana.file.optimistic
#include <stdio.h>
int main(){
FILE *fp1;
fp1 = fopen("test1.txt", "a");
fprintf(fp1, "Testing...\n");
FILE *fp2;
fp2 = fopen("test2.txt", "a");
fprintf(fp2, "Testing...\n");
FILE *fp;
int b;
if(b){
fp = fp1;
}else{
fp = fp2;
}
fclose(fp);
fclose(fp1); // WARN: MAYBE closeing already closed file handle fp1
fclose(fp2); // WARN: MAYBE closeing already closed file handle fp2
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
typedef struct No
{
float payload;
struct No* prox;
} No_t;
typedef struct
{
struct No* inicio;
struct No* fim;
} Fila_t;
Fila_t* criar(void)
{
Fila_t* fila = (Fila_t*)malloc(sizeof(Fila_t));
fila->inicio = fila->fim = NULL;
return fila;
}
/* função auxiliar: inserir no fim */
No_t* ins_fim(No_t* fim, float v)
{
No_t* p = (No_t*) malloc(sizeof(No_t));
p->payload = v;
p->prox = NULL;
if (fim != NULL) // verifica se a lista não estava vazia
fim->prox = p;
return p;
}
void inserir(Fila_t* f, float v)
{
f->fim = ins_fim(f->fim,v);
if (f->inicio == NULL) // fila antes vazia?
f->inicio = f->fim;
}
/* função auxiliar: retirar do início */
No_t* ret_ini(No_t* inicio)
{
No_t* p = inicio->prox;
free(inicio);
return p;
}
float retirar(Fila_t* f)
{
float v;
if (vazia(f))
{
printf("Fila vazia!\n");
exit(1); // aborta programa
}
v = f->inicio->payload;
f->inicio = ret_ini(f->inicio);
if (f->inicio == NULL) // fila ficou vazia?
f->fim = NULL;
return v;
}
int vazia(Fila_t* f)
{
return(f->inicio == NULL);
}
void imprimir(Fila_t* f)
{
No_t* q;
for (q = f->inicio; q != NULL; q = q->prox)
printf("%f\n", q->payload);
}
void liberar(Fila_t* f)
{
No_t* q = f->inicio;
while(q != NULL)
{
No_t* t = q->prox;
free(q);
q = t;
}
free(f);
}
void main(void)
{
Fila_t* fila;
fila = criar();
inserir(fila, 1.1);
inserir(fila, 2.1);
inserir(fila, 3.1);
inserir(fila, 4.1);
imprimir(fila);
liberar(fila);
}
|
C
|
#include <cstdlib>
#include "semantic.h"
#include "common.h"
#define SEM_ERROR(n, fmt, ...) { \
fprintf(errorFile, "SEMANTIC ERROR (line %d, column %d): " fmt "\n", n->line, n->column, ##__VA_ARGS__); \
errorOccurred = true; \
}
typedef struct {
std::vector<unsigned int> scope_id_stack;
} visit_data;
void semantic_preorder(node *n, void *data) {
visit_data *vd = (visit_data *) data;
switch (n->kind) {
case SCOPE_NODE:
vd->scope_id_stack.push_back(n->scope.scope_id);
break;
case DECLARATIONS_NODE:
break;
case DECLARATION_NODE:
break;
case STATEMENTS_NODE:
break;
case IF_STATEMENT_NODE:
break;
case ASSIGNMENT_NODE:
break;
case NESTED_SCOPE_NODE:
break;
case EXPRESSION_NODE:
// EXPRESSION_NODE is an abstract node
break;
case UNARY_EXPRESSION_NODE:
break;
case BINARY_EXPRESSION_NODE:
break;
case INT_NODE:
break;
case FLOAT_NODE:
break;
case BOOL_NODE:
break;
case IDENT_NODE:
break;
case VAR_NODE:
break;
case FUNCTION_NODE:
break;
case CONSTRUCTOR_NODE:
break;
case TYPE_NODE:
break;
case ARGUMENT_NODE:
break;
default: break;
}
}
void semantic_postorder(node *n, void *data) {
visit_data *vd = (visit_data *) data;
switch (n->kind) {
case SCOPE_NODE:
vd->scope_id_stack.pop_back();
break;
case DECLARATIONS_NODE:
break;
case DECLARATION_NODE:
validate_declaration_node(vd->scope_id_stack, n);
if (n->declaration.assignment_expr != NULL) {
validate_declaration_assignment_node(vd->scope_id_stack, n);
}
break;
case STATEMENTS_NODE:
break;
case IF_STATEMENT_NODE:
// An if condition must be a boolean
if (n->statement.if_else_statement.condition->expression.expr_type != TYPE_BOOL) {
SEM_ERROR(n->statement.if_else_statement.condition,
"If statement condition must be a boolean value");
}
break;
case ASSIGNMENT_NODE:
validate_assignment_node(vd->scope_id_stack, n);
break;
case NESTED_SCOPE_NODE:
break;
case EXPRESSION_NODE:
// EXPRESSION_NODE is an abstract node
break;
case UNARY_EXPRESSION_NODE:
validate_unary_expr_node(n);
break;
case BINARY_EXPRESSION_NODE:
validate_binary_expr_node(n);
break;
case INT_NODE:
break;
case FLOAT_NODE:
break;
case BOOL_NODE:
break;
case IDENT_NODE:
break;
case VAR_NODE:
validate_variable_node(vd->scope_id_stack, n);
break;
case FUNCTION_NODE:
validate_function_node(n);
break;
case CONSTRUCTOR_NODE:
validate_constructor_node(n);
break;
case TYPE_NODE:
break;
case ARGUMENT_NODE:
break;
default: break;
}
}
void semantic_check(node *ast) {
// Perform semantic analysis
visit_data vd;
ast_visit(ast, semantic_preorder, semantic_postorder, &vd);
}
/****** SEMANTIC VALIDATION FUNCTIONS ******/
symbol_type validate_binary_expr_node(node *binary_node, bool log_errors) {
node *right = binary_node->expression.binary.right;
node *left = binary_node->expression.binary.left;
symbol_type r_type = right->expression.expr_type;
symbol_type l_type = left->expression.expr_type;
symbol_type r_base_type = get_base_type(r_type);
symbol_type l_base_type = get_base_type(l_type);
bool r_is_vec = r_type & TYPE_ANY_VEC;
bool l_is_vec = l_type & TYPE_ANY_VEC;
binary_op op = binary_node->expression.binary.op;
// TODO: In alot of the cases below we can just log something and fall
// through to the return statement at the bottom of the function. This
// would remove alot of extra code and make it more readable
// TODO: we can also print out the actual operator using get_binary_op_name()
// For a binary op, base types must match
if (r_base_type != l_base_type) {
if (log_errors){
SEM_ERROR(binary_node,
"Binary operator %s has operands with incompatible base types %s and %s",
get_binary_op_name(op),
get_type_name(l_base_type),
get_type_name(r_base_type));
}
return TYPE_UNKNOWN;
}
// Check for unknown input type
if (l_type == TYPE_UNKNOWN || r_type == TYPE_UNKNOWN) {
return TYPE_UNKNOWN;
}
switch (op) {
case OP_AND: case OP_OR:
// The types must be logical and equal
if (r_type == l_type && r_base_type == TYPE_BOOL) {
return r_type;
} else {
if(log_errors){
SEM_ERROR(binary_node,
"Binary operator %s has operands with invalid types %s and %s, expected them to be equal and logical",
get_binary_op_name(op),
get_type_name(l_type),
get_type_name(r_type));
};
return TYPE_UNKNOWN;
}
break;
case OP_PLUS: case OP_MINUS:
// The types must be equal and arithmetic
if (r_type == l_type && r_base_type != TYPE_BOOL) {
return r_type;
} else {
if(log_errors){
SEM_ERROR(binary_node,
"Binary operator %s has operands with invalid types %s and %s, expected them to be equal and arithmetic",
get_binary_op_name(op),
get_type_name(l_type),
get_type_name(r_type));
};
return TYPE_UNKNOWN;
}
break;
case OP_DIV: case OP_XOR:
// The types must be equal, non-vector and arithmetic
if (r_type == l_type && !r_is_vec && !l_is_vec && r_base_type != TYPE_BOOL) {
return r_type;
} else {
if(log_errors){
SEM_ERROR(binary_node,
"Binary operator %s has operands with invalid types %s and %s, expected them to be equal, scalar, and arithmetic",
get_binary_op_name(op),
get_type_name(l_type),
get_type_name(r_type));
}
return TYPE_UNKNOWN;
}
break;
case OP_MUL:
if (r_base_type == TYPE_BOOL) {
if(log_errors){
SEM_ERROR(binary_node,
"Binary operator %s has operands with invalid types %s and %s, expected them to be arithmetic",
get_binary_op_name(op),
get_type_name(l_type),
get_type_name(r_type));
}
return TYPE_UNKNOWN;
}
if (l_is_vec && r_is_vec) {
if (r_type == l_type) {
return r_type;
} else {
// trying to multiply 2 vectors with different size
if(log_errors){
SEM_ERROR(binary_node,
"Binary operator %s has operands with invalid types %s and %s, expected them to be vectors of the same dimension",
get_binary_op_name(op),
get_type_name(l_type),
get_type_name(r_type));
}
return TYPE_UNKNOWN;
}
} else if (l_is_vec && !r_is_vec) {
return l_type;
} else if (!l_is_vec && r_is_vec) {
return r_type;
} else /* !l_is_vec && !r_is_vec */ {
return r_base_type;
}
case OP_LT: case OP_LEQ: case OP_GT: case OP_GEQ:
// The types must be equal, non-vector and arithmetic
if (r_type == l_type && !r_is_vec && !l_is_vec && r_base_type != TYPE_BOOL) {
return TYPE_BOOL;
} else {
if(log_errors){
SEM_ERROR(binary_node,
"Binary operator %s has operands with invalid types %s and %s, expected them to be equal, scalar, and arithmetic",
get_binary_op_name(op),
get_type_name(l_type),
get_type_name(r_type));
}
return TYPE_UNKNOWN;
}
case OP_EQ: case OP_NEQ:
// The types for OP_EQ and OP_NEQ must be equal and arithmetic
if (r_type == l_type && r_base_type != TYPE_BOOL) {
return TYPE_BOOL;
}
if(log_errors && r_type != l_type){
SEM_ERROR(binary_node,
"Binary operator %s has operands with invalid types %s and %s, expected them to be equal",
get_binary_op_name(op),
get_type_name(l_type),
get_type_name(r_type));
}
if(log_errors && r_base_type == TYPE_BOOL){
SEM_ERROR(binary_node,
"Binary operator %s has operands with invalid types %s and %s, expected them to be arithmetic",
get_binary_op_name(op),
get_type_name(l_type),
get_type_name(r_type));
}
return TYPE_UNKNOWN;
default:
break;
}
return TYPE_UNKNOWN;
}
symbol_type validate_unary_expr_node(node *unary_node, bool log_errors) {
symbol_type type = unary_node->expression.unary.right->expression.expr_type;
symbol_type base_type = get_base_type(type);
switch (unary_node->expression.unary.op) {
case OP_UMINUS:
// Unary minus is an arithmetic operator, so only allow
// base types of int and float
if (base_type == TYPE_INT || base_type == TYPE_FLOAT) {
// Return the original type (preserving scalar/vector)
return type;
} else if (log_errors) {
SEM_ERROR(unary_node,
"Operand of unary operator %s is of type %s but expected an arithmetic type",
get_unary_op_name(unary_node->expression.unary.op),
get_type_name(type));
}
break;
case OP_NOT:
// Unary not is a logical operator, so only allow a boolean
// base type
if (base_type == TYPE_BOOL) {
// Return the original type (preserving scalar/vector)
return type;
} else if (log_errors) {
SEM_ERROR(unary_node,
"Operand of unary operator %s is of type %s but expected a logical type",
get_unary_op_name(unary_node->expression.unary.op),
get_type_name(type));
}
break;
default: break;
}
// Fall through to an unknown type
return TYPE_UNKNOWN;
}
void validate_function_node(node *func_node, bool log_errors) {
node *first_arg = func_node->expression.function.arguments,
*second_arg = first_arg != NULL ? first_arg->argument.next_argument : NULL;
node *first_expr = first_arg != NULL ? first_arg->argument.expression : NULL,
*second_expr = second_arg != NULL ? second_arg->argument.expression : NULL;
symbol_type first_type = first_expr != NULL ? first_expr->expression.expr_type : TYPE_UNKNOWN,
second_type = second_expr != NULL ? second_expr->expression.expr_type : TYPE_UNKNOWN;
int num_args = first_arg != NULL ? first_arg->argument.num_arguments : 0;
switch (func_node->expression.function.func_id) {
case FUNC_DP3:
if (num_args > 2) {
if (log_errors) {
SEM_ERROR(func_node, "Too many arguments provided for dp3");
}
} else if (num_args < 2) {
if (log_errors) {
SEM_ERROR(func_node, "Too few arguments provided for dp3");
}
} else {
switch (first_type) {
case TYPE_VEC3: case TYPE_VEC4: case TYPE_IVEC3: case TYPE_IVEC4:
if (second_type != first_type) {
if (log_errors) {
SEM_ERROR(second_expr,
"Argument 2 of dp3 has type %s but expected %s",
get_type_name(second_type),
get_type_name(first_type));
}
}
break;
default:
if (log_errors) {
SEM_ERROR(first_expr,
"Argument 1 of dp3 has type %s but expected one of vec3, vec4, ivec3, ivec4",
get_type_name(first_type));
}
break;
}
}
break;
case FUNC_RSQ:
if (num_args > 1) {
if (log_errors) {
SEM_ERROR(func_node, "Too many arguments provided for rsq");
}
} else if (num_args < 1) {
if (log_errors) {
SEM_ERROR(func_node, "Too few arguments provided for rsq");
}
} else {
if (first_type != TYPE_INT && first_type != TYPE_FLOAT) {
if (log_errors) {
SEM_ERROR(first_expr,
"Argument 1 of rsq has type %s but expected one of int, float",
get_type_name(first_type));
}
}
}
break;
case FUNC_LIT:
if (num_args > 1) {
if (log_errors) {
SEM_ERROR(func_node, "Too many arguments provided for lit");
}
} else if (num_args < 1) {
if (log_errors) {
SEM_ERROR(func_node, "Too few arguments provided for lit");
}
} else {
if (first_type != TYPE_VEC4) {
if (log_errors) {
SEM_ERROR(first_expr,
"Argument 1 of lit has type %s but expected vec4",
get_type_name(first_type));
}
}
}
break;
}
}
void validate_constructor_node(node *constructor_node, bool log_errors) {
symbol_type constructor_type = constructor_node->expression.constructor.type->type.type;
symbol_type expected_arg_type = get_base_type(constructor_type);
node *first_arg = constructor_node->expression.constructor.arguments;
int num_args = first_arg != NULL ? first_arg->argument.num_arguments : 0,
expected_num_args;
if (constructor_type & TYPE_ANY_VEC) {
// We know that the type is a vector, the dimension of the type is given
// by the lowest 3 bits of the type
expected_num_args = constructor_type & 0x7;
} else {
switch (constructor_type) {
case TYPE_INT: case TYPE_FLOAT: case TYPE_BOOL:
expected_num_args = 1;
break;
default:
// This should never happen.
if (log_errors) {
SEM_ERROR(constructor_node, "Unknown constructor type");
}
return;
}
}
if (num_args > expected_num_args) {
if (log_errors) {
SEM_ERROR(constructor_node,
"Too many arguments provided for %s constructor",
get_type_name(constructor_type));
}
} else if (num_args < expected_num_args) {
if (log_errors) {
SEM_ERROR(constructor_node,
"Too few arguments provided for %s constructor",
get_type_name(constructor_type));
}
}
node *cur_arg;
int i;
for (i = 1, cur_arg = constructor_node->expression.constructor.arguments;
i <= expected_num_args && cur_arg != NULL;
i++, cur_arg = cur_arg->argument.next_argument) {
node *cur_expr = cur_arg->argument.expression;
symbol_type arg_type = cur_expr->expression.expr_type;
if (arg_type != expected_arg_type) {
if (log_errors) {
SEM_ERROR(cur_expr,
"Argument %d of %s constructor has type %s but expected type %s",
i,
get_type_name(constructor_type),
get_type_name(arg_type),
get_type_name(expected_arg_type));
}
}
}
}
void validate_variable_index_node(node *var_node, bool log_errors) {
node *ident = var_node->expression.variable.identifier;
node *index = var_node->expression.variable.index;
symbol_type var_type = ident->expression.expr_type;
int i = index->expression.int_expr.val;
if (var_type & TYPE_ANY_VEC) {
// The dimension of the vector is encoded in the lowest 3 bits of the type
int dim = var_type & 0x7;
if (i >= dim) {
if (log_errors) {
SEM_ERROR(var_node,
"Variable %s of type %s indexed at %d but only has dimension %d",
ident->expression.ident.val,
get_type_name(var_type),
i,
dim);
}
}
} else {
if (log_errors) {
SEM_ERROR(var_node,
"Variable %s of type %s cannot be indexed as it is not a vector",
ident->expression.ident.val,
get_type_name(var_type));
}
}
}
void validate_declaration_node(std::vector<unsigned int> &scope_id_stack,
node *decl_node,
bool log_errors) {
node *ident = decl_node->declaration.identifier;
char *symbol_name = ident->expression.ident.val;
symbol_info &sym_info = get_symbol_info(scope_id_stack, symbol_name);
if(sym_info.already_declared == true){
// report error
if(log_errors){
SEM_ERROR(decl_node, "Variable %s has alreay been declared in this scope", symbol_name);
}
} else {
sym_info.already_declared = true;
}
}
void validate_declaration_assignment_node(std::vector<unsigned int> &scope_id_stack,
node *decl_node,
bool log_errors) {
node *ident = decl_node->declaration.identifier;
node *expr = decl_node->declaration.assignment_expr;
symbol_type var_type = ident->expression.expr_type;
symbol_type expr_type = expr->expression.expr_type;
// If the expr_type is unknown then the error should be reported somewhere else
if (expr_type == TYPE_UNKNOWN) {
return;
}
// Ensure that variables declared as const are assigned const values
if (decl_node->declaration.is_const && !is_const_expr(scope_id_stack, expr)) {
if (log_errors) {
SEM_ERROR(decl_node,
"Const variable %s cannot be assigned a non-const value",
ident->expression.ident.val);
}
}
// If expr_type isn't the same as var_type and can't be widened to var_type
if (var_type != expr_type && get_base_type(var_type) != expr_type) {
if (log_errors) {
SEM_ERROR(decl_node,
"Variable %s of type %s cannot be assigned a value of type %s",
ident->expression.ident.val,
get_type_name(var_type),
get_type_name(expr_type));
}
}
}
void validate_assignment_node(std::vector<unsigned int> &scope_id_stack,
node *assign_node,
bool log_errors) {
node *var = assign_node->statement.assignment.variable;
node *expr = assign_node->statement.assignment.expression;
node *ident = var->expression.variable.identifier;
symbol_type var_type = var->expression.expr_type;
symbol_type expr_type = expr->expression.expr_type;
// TODO: We should be making checks for TYPE_UNKNOWN everywhere so we don't log
// errors for unknown type. Or maybe we shouldn't, i dont know
// If var_type or expr_type are unknown then the error should be
// reported somewhere else
if (var_type == TYPE_UNKNOWN || expr_type == TYPE_UNKNOWN) {
return;
}
// Ensure that variables declared as readonly cannot be assigned to
if (get_symbol_info(scope_id_stack, ident->expression.ident.val).read_only) {
if (log_errors) {
SEM_ERROR(assign_node,
"Read-only variable %s cannot be assigned to",
ident->expression.ident.val);
}
}
// If expr_type isn't the same as var_type and can't be widened to var_type
if (var_type != expr_type && get_base_type(var_type) != expr_type) {
if (log_errors) {
SEM_ERROR(assign_node,
"Variable %s of type %s cannot be assigned a value of type %s",
ident->expression.ident.val,
get_type_name(var_type),
get_type_name(expr_type));
}
}
}
void validate_variable_node(std::vector<unsigned int> &scope_id_stack,
node *var_node,
bool log_errors) {
// Validate the index of the variable, if there is one
if (var_node->expression.variable.index != NULL) {
validate_variable_index_node(var_node);
}
node *ident = var_node->expression.variable.identifier;
symbol_info sym_info = get_symbol_info(scope_id_stack, ident->expression.ident.val);
// If the variable has TYPE_UNKNOWN then it wasn't declared
if (sym_info.type == TYPE_UNKNOWN) {
if (log_errors) {
SEM_ERROR(var_node,
"Undeclared variable %s",
ident->expression.ident.val);
}
} else if (!sym_info.already_declared) {
// If the variable has a type, but isn't already_declared, then it hasn't been declared yet
if (log_errors) {
SEM_ERROR(var_node,
"Variable %s used before it was declared",
ident->expression.ident.val);
}
}
// If we have a write-only variable, it must appear on the LHS of an assignment node
if (sym_info.write_only &&
(var_node->parent->kind != ASSIGNMENT_NODE ||
var_node->parent->statement.assignment.expression == var_node)) {
// If the RHS of an ASSIGNMENT_NODE was exactly the var_node, then the parent would
// still be an ASSIGNMENT_NODE. We thus need the second condition to make sure that
// the VAR_NODE is appearing on the LHS. Because of lazy evaluation, we know that
// if the third condition is evaluated, the second must have been false.
if (log_errors) {
SEM_ERROR(var_node,
"Write-only variable %s cannot be read from",
ident->expression.ident.val);
}
}
}
/****** SEMANTIC TYPE FUNCTIONS ******/
symbol_type get_binary_expr_type(node *binary_node) {
return validate_binary_expr_node(binary_node, false);
}
symbol_type get_unary_expr_type(node *unary_node) {
return validate_unary_expr_node(unary_node, false);
}
symbol_type get_function_return_type(node *func_node) {
node *first_arg = func_node->expression.function.arguments;
switch (func_node->expression.function.func_id) {
case FUNC_DP3:
// Look at the first argument to determine the return type.
if (first_arg != NULL) {
switch (first_arg->argument.expression->expression.expr_type) {
// If the first argument is TYPE_VEC[43], return TYPE_FLOAT
case TYPE_VEC4: case TYPE_VEC3:
return TYPE_FLOAT;
// If the first argument is TYPE_IVEC[43], return TYPE_INT
case TYPE_IVEC4: case TYPE_IVEC3:
return TYPE_INT;
// Otherwise fall through to TYPE_UNKNOWN
default: break;
}
}
break;
case FUNC_RSQ:
return TYPE_FLOAT;
case FUNC_LIT:
return TYPE_VEC4;
}
return TYPE_UNKNOWN;
}
symbol_type get_base_type(symbol_type type) {
if (type & TYPE_VEC) {
return TYPE_FLOAT;
} else if (type & TYPE_IVEC) {
return TYPE_INT;
} else if (type & TYPE_BVEC) {
return TYPE_BOOL;
} else {
return type;
}
}
bool is_const_expr(std::vector<unsigned int> &scope_id_stack, node *expr_node) {
// TODO: Evaluate constant expressions
switch (expr_node->kind) {
case UNARY_EXPRESSION_NODE:
break;
case BINARY_EXPRESSION_NODE:
break;
case INT_NODE: case FLOAT_NODE: case BOOL_NODE:
return true;
case IDENT_NODE:
return get_symbol_info(scope_id_stack, expr_node->expression.ident.val).constant;
case VAR_NODE:
return is_const_expr(scope_id_stack, expr_node->expression.variable.identifier);
case FUNCTION_NODE:
break;
case CONSTRUCTOR_NODE:
break;
default: break;
}
return false;
}
|
C
|
#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
#include <stdlib.h> // rand(), srand()
#include <time.h> // time()
#define NUM_OF_SBOXES 4
#define SIZE_OF_SBOX 16
#define NUM_OF_STAGES 4
#define BITS_OF_INPUT 16
#define NUM_OF_CYPHER_PAIRS 5000
struct nibbleList{
uint16_t currentLocation;
struct nibblelist * nextNibble;
};
typedef struct nibbleList nibbleList;
//using arrays as a key:value pair to convert 4 bit values. (example 0x4 will convert to 0x2)
const int sbox[SIZE_OF_SBOX] = {0xE, 0x4, 0xD, 0x1, 0x2, 0xF, 0xB, 0x8, 0x3, 0xA, 0x6, 0xC, 0x5, 0x9, 0x0, 0x7};
int reverseSbox[SIZE_OF_SBOX];// = {0x, 0x, 0x, 0x, 0x, 0x, 0x, 0x, 0x, 0x, 0x, 0x, 0x, 0x, 0xE, 0x};
//not zero based, we will minus one from all of these in code.
//I did it this way just so there isn't a human error with off by one issues from copying the values from the PDF
const int permutation[] = {1-1, 5-1, 9-1, 13-1, 2-1, 6-1, 10-1, 14-1, 3-1, 7-1, 11-1, 15-1, 4-1, 8-1, 12-1, 16-1};
//randomly selected xor values on 16 bit values.
const uint16_t keyXor[NUM_OF_STAGES + 1] = {0x3354, 0x23F3, 0x5FEA, 0x9812, 0x8CC9};
int DiffDistTable[BITS_OF_INPUT][BITS_OF_INPUT];
uint32_t TotalProbabilityNumerator = 1;
uint32_t TotalProbabilityDenominator = 1;
int cyphertextPairs[2][NUM_OF_CYPHER_PAIRS];
bool activeNibbles[BITS_OF_INPUT/4];
uint16_t numOfActiveNibbles = 0;
uint16_t rightPairs[32767] = {0};
// This generates the Diffenece Distribution table. Print the values 6 or greater
void findDiffs()
{
printf("\nDifference Distribution Table:\n");
for(int x1 = 0; x1 < BITS_OF_INPUT; x1++){
for(int x2 = 0; x2 < BITS_OF_INPUT; x2++){
int deltax = x1 ^ x2;
int deltay = sbox[x1] ^ sbox[x2];
//Add a note to the difference dist table that we have hit that point.
DiffDistTable[deltax][deltay]++;
}
}
for(int i = 0; i < BITS_OF_INPUT; i++){
printf("%3d ,", i);
}
printf("\n");
for(int x1 = 0; x1 < BITS_OF_INPUT; x1++)
{
printf("%3d ,", x1);
for(int x2 = 0; x2 < BITS_OF_INPUT; x2++){
printf("%3d ,", DiffDistTable[x1][x2]);
}
printf("\n");
}
printf("\nDisplaying most probable values (6 or greater only):\n");
printf("num of occurances Delta X Delta Y\n");
for(int deltaX = 1; deltaX < BITS_OF_INPUT; deltaX++){
for(int deltaY = 1; deltaY < BITS_OF_INPUT; deltaY++){
if (DiffDistTable[deltaX][deltaY] >= 6 && DiffDistTable[deltaX][deltaY] < BITS_OF_INPUT){
printf(" %2d %2d %2d\n",DiffDistTable[deltaX][deltaY], deltaX, deltaY);
}
}
}
}
//Get the most common DeltaX -> DeltaY combo.
uint8_t getMostCommonDeltasTotal(){
uint8_t deltaXOut = 0;
int MostCommon = 0;
//Dont do zero since 0->0 is always BITS_OF_INPUT times
for(uint8_t deltaX = 1; deltaX < BITS_OF_INPUT; deltaX++){
for(uint8_t deltaY = 1; deltaY < BITS_OF_INPUT; deltaY++){
if(MostCommon < DiffDistTable[deltaX][deltaY]){
MostCommon = DiffDistTable[deltaX][deltaY];
deltaXOut = deltaX;
//*deltaYOut = deltaY;
}
}
}
return deltaXOut;
}
//Gives the most common deltaY given a deltaX
uint8_t getMostCommonDeltaY(uint8_t deltaX){
//TODO: add tracking of previously selected delta X/Y combos
int MostCommon = 0;
uint8_t deltaYOut = 0;
for(uint8_t deltaY = 1; deltaY < BITS_OF_INPUT; deltaY++){
if(MostCommon < DiffDistTable[deltaX][deltaY]){
MostCommon = DiffDistTable[deltaX][deltaY];
deltaYOut = deltaY;
}
}
TotalProbabilityNumerator *= MostCommon;
TotalProbabilityDenominator *= BITS_OF_INPUT;
return deltaYOut;
}
//Generates the initial input.
uint16_t generateInputPlainText(uint8_t inputByte){
uint16_t plaintext = inputByte << 8; //shift 2 bytes over
printf("plaintext is: %04X\n", plaintext);
return plaintext;
}
uint16_t doSboxForAttack(uint16_t valueToDoSboxOn){
uint16_t sboxOutTotal = 0x0;
//loop through all non-zero values to see which is the most common DeltaY per input.
for(int i = 0; i < NUM_OF_SBOXES; i++){
uint16_t sboxInput = ((valueToDoSboxOn>>(4*i)&0xF)); //This grabs 4 bits at a time
if(sboxInput == 0){
//don't deal with zeros
continue;
}
uint16_t sboxOutput = getMostCommonDeltaY(sboxInput);
sboxOutTotal += (sboxOutput<<(4*i));
}
return sboxOutTotal;
}
uint16_t doReverseSbox(uint16_t valueToReverse){
uint16_t ReverseSboxOut = 0x0;
//loop through all non-zero values to see which is the most common DeltaY per input.
for(int i = 0; i < NUM_OF_SBOXES; i++){
//only deal with the nibbles we care about.
if(!activeNibbles[i]){
continue;
}
uint16_t sboxInput = ((valueToReverse>>(4*i)&0xF)); //This grabs 4 bits at a time
if(sboxInput > 0xF){
printf("ERROR THIS CANNOT HAPPEN. input is: %04X\n");
break;
}
uint16_t sboxOutput = reverseSbox[sboxInput];
ReverseSboxOut += (sboxOutput<<(4*i));
}
return ReverseSboxOut;
}
uint16_t doSboxForEncryption(uint16_t valueToDoSboxOn){
uint16_t sboxOutTotal = 0x0;
for(int i = 0; i < NUM_OF_SBOXES; i++){
//grab 4 bits at a time
uint16_t sboxInput = ((valueToDoSboxOn>>(4*i)&0xF)); //This grabs 4 bits at a time
//use sboxInput as the key for the key:value pair
uint16_t sboxOutput = sbox[sboxInput];
//recombine the 16 bits
sboxOutTotal += (sboxOutput<<(4*i));
}
return sboxOutTotal;
}
uint16_t doPermutation(uint16_t valueToPermutate){
uint16_t permutateOut = 0;
//TODO: make this dynamic later
for(int i = 0; i < BITS_OF_INPUT ; i++){
uint16_t invertedIndex = 15 - i;
if((valueToPermutate >> invertedIndex) & 1U){
uint16_t permutatedIndex = permutation[invertedIndex];
permutateOut |= 1UL << permutatedIndex;
}
}
return permutateOut;
}
//Doing page 24 of the tutorial
uint16_t findDeltaU(uint16_t deltaB){
uint16_t modifiedValue = deltaB;
//Dont run over the last stage because that is when we will be extracting key bits (section 4.4)
for (int i = 0; i < NUM_OF_STAGES-1; i++){
//do sbox
modifiedValue = doSboxForAttack(modifiedValue);
printf("end of sbox iteration %d is %04X\n", i, modifiedValue);
//do permutation
modifiedValue = doPermutation(modifiedValue);
printf("end of permutation %d is %04X\n", i, modifiedValue);
}
fflush(stdout);
//At last stage here.
uint16_t deltaU = modifiedValue;
return deltaU;
}
uint16_t runEncryption(uint16_t message){
uint16_t intermediate_val = message;
printf("start: %X\n", intermediate_val);
for(int i = 0; i < NUM_OF_STAGES; i++){
//xor
intermediate_val = intermediate_val^keyXor[i];
//printf("xor stage %d: %X with %X\n", i, intermediate_val, keyXor[i]);
//sbox
intermediate_val = doSboxForEncryption(intermediate_val);
//printf("sbox stage %d: %X\n", i,intermediate_val);
//permutation - don't permutate on round 4
if(i != (NUM_OF_STAGES-1)){
intermediate_val = doPermutation(intermediate_val);
//printf("perm stage %d: %X\n", i, intermediate_val);
}
}
//final XOR
uint16_t finalxor = keyXor[NUM_OF_STAGES];
intermediate_val = intermediate_val^finalxor;
//printf("final out: %X, with %X\n", intermediate_val, finalxor);
fflush(stdout);
return intermediate_val;
}
void generatePairs(uint16_t deltaU4, uint16_t deltaB){
//TODO: fill cyphertextPairs[2][5000]
int numOfPairs = 0;
bool isDeltaU4NibbleZero[BITS_OF_INPUT/4];
// Intializes random number generator
// We could change the seed, but doing this will give us the same execution per run and easier to debug.
// We could change this to ensure the system works no matter the input.
srand((unsigned) time(NULL));
//Find which nibbles have 0s. We will ensure only active nibbles have a difference in when looking for Crypto Pairs.
for(int i = 0; i < (BITS_OF_INPUT/4); i++){
uint16_t currNibbleDeltaU = ((deltaU4 >> (4*i)&0xF)); //This grabs 4 bits at a time
activeNibbles[i] = (currNibbleDeltaU != 0);
if(activeNibbles[i]){
numOfActiveNibbles++;
}
}
for(int i = 0; i < NUM_OF_CYPHER_PAIRS; i++){
//create a pair of inputs that is only different by deltaB.
uint16_t firstInput = rand() % 0xFFFF;
uint16_t secondInput = firstInput ^ deltaB;
//put both through the encryption.
uint16_t firstEncrypt = runEncryption(firstInput);
uint16_t secondEncrypt = runEncryption(secondInput);
//check the delta of the 2 outputs only has changes on active nibbles.
uint16_t deltaC = firstEncrypt ^ secondEncrypt;
bool isInvalidPair = false;
for(int i = 0; i < (BITS_OF_INPUT/4); i++){
uint16_t currNibbleDeltaC = ((deltaC >> (4*i)&0xF)); //This grabs 4 bits at a time
// Check for invalid pairs. if there is a difference in a nibble that shouldn't be different, bail out.
if(!activeNibbles[i] && (currNibbleDeltaC != 0)){
isInvalidPair = true;
}
}
//invalid pair, do not save this pair, skip and go to another randomly generated one.
if(isInvalidPair){
// printf("P = first, %04X --- second, %04X\n", firstInput, secondInput);
// printf("C = first, %04X --- second, %04X\n", firstEncrypt, secondEncrypt);
// printf("deltaC is %04X\n invalid \n", deltaC);
continue;
}
//if only active nibbles have a difference, save as a pair.
cyphertextPairs[0][numOfPairs] = firstEncrypt;
cyphertextPairs[1][numOfPairs] = secondEncrypt;
numOfPairs++;
}
for(int i = 0; i < numOfPairs; i++){
//printf("first cyphertext %04X\nsecond cyphertext %04X\n\n", cyphertextPairs[0][i], cyphertextPairs[1][i]);
}
}
void generateReverseSboxes(){
for(int i = 0; i < SIZE_OF_SBOX; i++){
reverseSbox[sbox[i]] = i;
}
printf("reverse sbox is:\n");
for(int i = 0; i < SIZE_OF_SBOX; i++){
printf("%X, ", reverseSbox[i]);
}
printf("\n");
for(int i = 0; i < SIZE_OF_SBOX; i++){
//print the sboxe table
printf("%X -> %X\n", i, sbox[i]);
}
printf("\n\n");
for(int i = 0; i < SIZE_OF_SBOX; i++){
//print the reverse sbox table
printf("%X -> %X\n", i, reverseSbox[i]);
}
}
void iterateWithPartialKey(uint16_t partialKey, uint16_t deltaU4){
for(int i = 0; i < NUM_OF_CYPHER_PAIRS; i++){
uint16_t xorWithPossibleKey1 = cyphertextPairs[0][i] ^ partialKey;
uint16_t xorWithPossibleKey2 = cyphertextPairs[1][i] ^ partialKey;
uint16_t reverseCypher1 = doReverseSbox(xorWithPossibleKey1);
uint16_t reverseCypher2 = doReverseSbox(xorWithPossibleKey2);
uint16_t reverseCypherXor = reverseCypher1 ^ reverseCypher2;
if (reverseCypherXor == deltaU4){
rightPairs[partialKey]++;
printf("C1 %04X, revC1 %04X C2 %04X rev C2 %04X, Partial %04X\n", cyphertextPairs[0][i], reverseCypher1, cyphertextPairs[1][i], reverseCypher2, reverseCypherXor);
}
}
}
//recursion over all permutations of Z5. Only iterate over all active nibbles.
void loopOverNibbles(nibbleList *nibbleList, uint16_t lastPartialKey, uint16_t deltaU4){
//hit end of recursion system.
if(nibbleList == NULL){
iterateWithPartialKey(lastPartialKey, deltaU4);
return;
}
// while(nibbleListCurrent != NULL){
// printf("current index is %X and nibble List next is %s\n", nibbleListCurrent->currentLocation, nibbleListCurrent->nextNibble);
// nibbleListCurrent = nibbleListCurrent->nextNibble;
// }
for(int i = 0; i < BITS_OF_INPUT; i++){
uint16_t currentPartialKey = lastPartialKey;
//bitshift the values by currentPartialKey += i << 4*nibbleList
currentPartialKey += ( i <<(4*nibbleList->currentLocation));
loopOverNibbles(nibbleList->nextNibble, currentPartialKey, deltaU4);
}
}
void generateMostLikelyKeyBits(uint16_t deltaU4){
//I am just keeping an array of every possible subkey. I do not know which nibbles we are looking for partial subkeys. Bad for memory space, good for all cases.
generateReverseSboxes();
nibbleList *nibbleListHead = (nibbleList*)malloc(sizeof(nibbleList));
nibbleListHead->currentLocation = 0xFF;
nibbleListHead->nextNibble = NULL;
nibbleList *NibbleListCurrent = nibbleListHead;
//generate the link lists of nibbles
for(int i = 0; i < 4; i++){
if(!activeNibbles[i]){
continue;
}
if(NibbleListCurrent->currentLocation == 0xFF){
NibbleListCurrent->currentLocation = i;
}else{
nibbleList *nibbleListNext = (nibbleList*)malloc(sizeof(nibbleList));
nibbleListNext->currentLocation = i;
nibbleListNext->nextNibble = NULL;
NibbleListCurrent->nextNibble = nibbleListNext;
NibbleListCurrent = NibbleListCurrent->nextNibble;
}
}
loopOverNibbles(nibbleListHead, 0, deltaU4);
uint16_t mostLikelySubkey = 0;
uint16_t numOfTimesSubkeyFound = 0;
for (int i = 0; i < 32767; i++)
{
//if(rightPairs[i] > 0){
//printf("right pair %X happened %u times\n", i, rightPairs[i]);
//}
if (numOfTimesSubkeyFound < rightPairs[i]){
numOfTimesSubkeyFound = rightPairs[i];
mostLikelySubkey = i;
}
}
printf("most Likely Key: %04X with probability %d\n", mostLikelySubkey, numOfTimesSubkeyFound);
}
uint16_t FindK5(uint16_t deltaU4, uint16_t deltaB){
generatePairs(deltaU4, deltaB);
generateMostLikelyKeyBits(deltaU4);
return 0;
}
void main(){
findDiffs();
//same as deltaU1
uint8_t mostCommonNibble = getMostCommonDeltasTotal(); //TODO: check if we need to grab this delta y
uint16_t deltaB = generateInputPlainText(mostCommonNibble);
uint16_t deltaU4 = findDeltaU(deltaB);
printf("DeltaU is %04X\n", deltaU4);
FindK5(deltaU4, deltaB);
float Probabilityfloat = (float)TotalProbabilityNumerator/(float)TotalProbabilityDenominator;
printf("theoretical chance is: %u/%u or %f\n", TotalProbabilityNumerator, TotalProbabilityDenominator, Probabilityfloat);
fflush(stdout);
}
|
C
|
/**
* yaw.c - Yaw access and control for heli project
*
* Authors: Jos Craw, Josh Hulbert, Harry Dobbs
* Last Modified: 28.07.2020
*/
#include <stdint.h>
#include <stdbool.h>
#include <inc/hw_memmap.h>
#include <inc/hw_types.h>
#include <inc/hw_ints.h>
#include <driverlib/gpio.h>
#include <driverlib/sysctl.h>
#include <driverlib/pin_map.h>
#include <stdio.h>
#include "heli.h"
#include "yaw.h"
int32_t volatile yawSlotCount = 0;
static int currentYawState; // The current state of the yaw sensors
static int previousYawState; // The previous state of the yaw sensors
void initYawReferenceSignal(void);
void init_yaw(void);
void yawRefSignalIntHandler(void);
void increment_yaw(void);
void quadratureDecode(void);
int get_current_yaw(void);
void reset_yaw(void);
void init_yaw_reference_signal(void) {
SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOC);
GPIOPinTypeGPIOInput(GPIO_PORTC_BASE, GPIO_PIN_4);
}
void set_yaw_ref_callback(void (*callback)()) {
GPIOIntRegister(GPIO_PORTC_BASE, callback);
}
void init_yaw(void) {
init_yaw_reference_signal();
SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOB);
GPIOPinTypeGPIOInput(GPIO_PORTB_BASE, CHANNEL_A | CHANNEL_B);
GPIOIntEnable(GPIO_PORTB_BASE, GPIO_INT_PIN_0 | GPIO_INT_PIN_1);
GPIOIntTypeSet(GPIO_PORTB_BASE, CHANNEL_A | CHANNEL_B, GPIO_BOTH_EDGES);
GPIOIntRegister(GPIO_PORTB_BASE, increment_yaw);
GPIOIntEnable(GPIO_PORTC_BASE, GPIO_INT_PIN_4);
GPIOIntTypeSet(GPIO_PORTC_BASE, GPIO_PIN_4, GPIO_FALLING_EDGE);
currentYawState = GPIOPinRead(GPIO_PORTB_BASE, CHANNEL_A | CHANNEL_B);
}
void increment_yaw(void) {
GPIOIntClear(GPIO_PORTB_BASE, GPIO_INT_PIN_0 | GPIO_INT_PIN_1); // Clear the interrupt
previousYawState = currentYawState; // Save the previous state
currentYawState = (int) GPIOPinRead(GPIO_PORTB_BASE, CHANNEL_A | CHANNEL_B);
// Determine the direction of rotation. Increment or decrement yawSlotCount appropriately.
quadrature_decode();
}
void quadrature_decode(void) {
// FSM implementation for quadrature decoding.
// States are changed by the interrupt handler.
if (currentYawState == B_HIGH_A_LOW) {
if (previousYawState == B_LOW_A_LOW) {
yawSlotCount = yawSlotCount + YAW_INCREMENT; // Clockwise rotation
} else {
yawSlotCount = yawSlotCount - YAW_DECREMENT; // Anticlockwise rotation
}
} else if (currentYawState == B_HIGH_A_HIGH) {
if (previousYawState == B_HIGH_A_LOW) {
yawSlotCount = yawSlotCount + YAW_INCREMENT;
} else {
yawSlotCount = yawSlotCount - YAW_DECREMENT;
}
} else if (currentYawState == B_LOW_A_HIGH) {
if (previousYawState == B_HIGH_A_HIGH) {
yawSlotCount = yawSlotCount + YAW_INCREMENT;
} else {
yawSlotCount = yawSlotCount - YAW_DECREMENT;
}
} else {
if (previousYawState == B_LOW_A_HIGH) {
yawSlotCount = yawSlotCount + YAW_INCREMENT;
} else {
yawSlotCount = yawSlotCount - YAW_DECREMENT;
}
}
}
int get_current_yaw(void) {
return yawSlotCount;
}
void set_current_yaw(int yaw) {
yawSlotCount = yaw;
}
void reset_yaw(void) {
yawSlotCount = 0;
}
|
C
|
#include <stdio.h>
int main(void)
{
int num1, num2;
printf("Enter first number:");
scanf("%d", &num1);
printf("%d\n", num1 >= 76 && num1 <= 78);
printf("Enter second number:");
scanf("%d", &num2);
printf("%d", (num2 & 64) == 64);
return 0;
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <malloc.h>
char **divide_string(char *s){
int len,j=0,i;
char **subs;
*subs = (char *)malloc(sizeof(char *)*2);
if((len = strlen(s))%2 ==0){
subs[0] = (char *)malloc(len/2+1);
subs[1] = (char *)malloc(len/2+1);
for ( i = 0; i < len/2; i++) {
subs[0][i] = s[i];
}
subs[0][i] = '\0';
for ( i = len/2; i < len; i++) {
subs[1][j] = s[i];
j++;
}
subs[1][j] = '\0';
return subs;
}else{
return NULL;
}
}
int main() {
char s[100]="FOUR";
char **sr;
sr = divide_string(s);
if(sr!=NULL){
printf("Lenght of 1 %s.\n",sr[0]);
printf("Lenght of 2 %s.\n",sr[1]);
}else{
printf("Cant Be done!!!!!!!!!!!!!!!!!!!!\n");
}
return 0;
}
|
C
|
#include "inc/key.h"
#include <stdlib.h>
Key* getKey(Key* self, int8_t keyNumber) {
uint8_t oct;
oct = MIN_OCTAVE;
// determine which octave we are in
while (keyNumber > KEYS_PER_OCT) {
keyNumber -= KEYS_PER_OCT;
oct++;
}
self->octave = oct;
self->letter = keyNumber;
return self;
}
Key* initKey() {
Key* self = malloc(sizeof(Key));
self->letter = NO_NOTE;
self->octave = MIN_OCTAVE;
return self;
}
|
C
|
#include<stdio.h>
int main()
{
int a, b, sum;
a = 520;
b = 1314;
sum = a + b;
printf("sum=%d\n", sum);
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_sprite.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mbari <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/08/16 14:26:22 by mbari #+# #+# */
/* Updated: 2020/10/17 13:14:09 by mbari ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/cub3d.h"
t_sprite *ft_get_sprite(t_mlx *mlx)
{
t_sprite *sprites;
int i;
int x;
int y;
mlx->sprite_num = ft_count_sprotes(mlx);
sprites = malloc(mlx->sprite_num * sizeof(t_sprite));
mlx->sprite_order = malloc(mlx->sprite_num * sizeof(int));
i = 0;
x = 0;
while (x < mlx->max_x)
{
y = 0;
while (y < mlx->max_y)
{
if (mlx->worldmap[x][y] == '2')
{
sprites[i].x = x;
sprites[i++].y = y;
}
y++;
}
x++;
}
return (sprites);
}
void ft_sort_sprites(t_mlx *mlx)
{
double distance[mlx->sprite_num];
int tmp;
int disttmp;
int i;
i = -1;
while (++i < mlx->sprite_num)
{
distance[i] = ((mlx->posx - mlx->sp[i].x) * (mlx->posx -
mlx->sp[i].x) + (mlx->posy - mlx->sp[i].y) * (mlx->posy -
mlx->sp[i].y));
mlx->sprite_order[i] = i;
}
i = -1;
while (++i < mlx->sprite_num - 1)
if (distance[i] < distance[i + 1])
{
disttmp = distance[i];
distance[i] = distance[i + 1];
distance[i + 1] = disttmp;
tmp = mlx->sprite_order[i];
mlx->sprite_order[i] = mlx->sprite_order[i + 1];
mlx->sprite_order[i + 1] = tmp;
i = -1;
}
}
void ft_sprite_height(t_sprtools *sprite, t_mlx *mlx)
{
sprite->spriteheight = abs((int)(mlx->win.heigth / (sprite->transformy)));
sprite->drawstarty = -sprite->spriteheight / 2 + mlx->win.heigth / 2;
if (sprite->drawstarty < 0)
sprite->drawstarty = 0;
sprite->drawendy = sprite->spriteheight / 2 + mlx->win.heigth / 2;
if (sprite->drawendy >= mlx->win.heigth)
sprite->drawendy = mlx->win.heigth;
}
void ft_sprite_width(t_sprtools *sprite, t_mlx *mlx)
{
sprite->spritewidth = abs((int)(mlx->win.heigth / (sprite->transformy)));
sprite->drawstartx = -sprite->spritewidth / 2 + sprite->spritescreenx;
if (sprite->drawstartx < 0)
sprite->drawstartx = 0;
sprite->drawendx = sprite->spritewidth / 2 + sprite->spritescreenx;
if (sprite->drawendx >= mlx->win.width)
sprite->drawendx = mlx->win.width;
}
void ft_drawsprites(t_mlx *mlx)
{
int i;
t_sprite sprite_ptr;
t_sprtools sprite;
ft_sort_sprites(mlx);
i = 0;
while (i < mlx->sprite_num)
{
sprite_ptr = mlx->sp[mlx->sprite_order[i++]];
sprite.spritex = (sprite_ptr.x + 0.5) - mlx->posx;
sprite.spritey = (sprite_ptr.y + 0.5) - mlx->posy;
sprite.invdet = 1.0 / (mlx->planex *
mlx->diry - mlx->dirx * mlx->planey);
sprite.transformx = sprite.invdet * (mlx->diry *
sprite.spritex - mlx->dirx * sprite.spritey);
sprite.transformy = sprite.invdet *
(-mlx->planey * sprite.spritex + mlx->planex * sprite.spritey);
sprite.spritescreenx = (int)((mlx->win.width / 2) *
(1 + sprite.transformx / sprite.transformy));
ft_sprite_height(&sprite, mlx);
ft_sprite_width(&sprite, mlx);
ft_drawspritelines(&sprite, mlx);
}
}
|
C
|
/**
* @author SANKALP SAXENA
*/
#include<stdio.h>
int main()
{
int t,x,y;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&x,&y);
x=x%4;
y=y%4;
if((x==0) || (x==3) || (y==0) || (y==3))
printf("First\n");
else
printf("Second\n");
}
return 0;
}
|
C
|
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include "myStringFxns.h"
/***************************************************************
* myGetline
* Description: reads a file for all characters before it finds
* a delimiter or the end of file. Then updates strPtr with the
* string of characters found. Returns the number of characters
* in a line if sucessful or -1 if there is an error.
***************************************************************/
int myGetline(char ** strPtr, int fileDescriptor, char delimiter)
{
// declare variables
int i,
lineSize = 0,
readReturn,
decisionSwitch = 0;
off_t startOffset;
char charBuffer[1];
// get the offset we are already at
startOffset = lseek(fileDescriptor, 0, SEEK_CUR);
if (startOffset == -1)
{
perror("myGetline: startOffset lseek error");
return -1;
}
// counts the number of characters from the starting
// offset to the delimiter or end of file
while (decisionSwitch == 0)
{
readReturn = read(fileDescriptor, charBuffer, 1);
// read error handler
if (readReturn == -1)
{
lseek(fileDescriptor, startOffset, SEEK_SET);
perror("myGetline: read error");
return -1;
}
// end of file handler
else if (readReturn == 0)
decisionSwitch = 1;
// letter or delimiter handler
else
{
lineSize++;
if (charBuffer[0] == delimiter)
decisionSwitch = 1;
}
}
// case when end of file is reached
if (lineSize == 0)
return lineSize;
// reset file pointer to position when myGetline was called
if (lseek(fileDescriptor, startOffset, SEEK_SET) == -1)
{
perror("myGetline: lseek back to start offset error");
return -1;
}
// free the previous string buffer and dynamically assign a
// new buffer for the new line
if (*strPtr != NULL)
free(*strPtr);
*strPtr = malloc(sizeof(char) * (lineSize + 1));
if (strPtr == NULL)
{
perror("myGetline: malloc error");
return -1;
}
// initialize buffer with null terminators
memset(*strPtr, '\0', lineSize + 1);
// copy line into buffer
for (i = 0; i < lineSize; i++)
{
if (read(fileDescriptor, charBuffer, 1) == -1)
{
lseek(fileDescriptor, startOffset, SEEK_SET);
perror("myGetline: read error");
}
(*strPtr)[i] = charBuffer[0];
}
return lineSize;
}
/***************************************************************
* strToPosInt
* Description: Reads a string containing only numbers and
* returns the number as a positive integer.
***************************************************************/
int strToPosInt(char * intStr)
{
int i,
k,
numDigits = 0,
exponent,
muliplier,
number = 0;
char * curChar;
// check all characters are valid numbers and determine the
// number of digits
curChar = intStr;
while (*curChar != '\0')
{
if ((int)(*curChar) >= 0x30 && (int)(*curChar) <= 0x39)
{
curChar += sizeof(char);
numDigits++;
}
else
return -1;
}
// for each digit, obtain the correct power of 10 and
// multiply this power of 10 by the digit
exponent = numDigits - 1;
curChar = intStr;
for (i = 0; i < numDigits; i++)
{
muliplier = 1;
for (k = 0; k < exponent; k++)
muliplier *= 10;
number += ((int)(*curChar) - 0x30) * muliplier;
exponent--;
curChar += sizeof(char);
}
return number;
}
|
C
|
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char **get_inner_cmd(int *cmd_num) {
const int MAX_CMD_COUNT = 32;
const int MAX_CMD_LENGTH = 128;
char **commands = calloc(MAX_CMD_COUNT, sizeof(char *));
int cmd_cnt = 0;
DIR *dir = opendir("./commands");
if (dir == NULL) {
fprintf(stderr, "unable to opendir ./commands\n");
exit(1);
}
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
if (entry->d_name[0] == '.') {
continue;
}
int len = strlen(entry->d_name);
if (len > MAX_CMD_LENGTH) {
len = MAX_CMD_LENGTH;
}
char *cmd = calloc(len, sizeof(char));
strncpy(cmd, entry->d_name, len);
commands[cmd_cnt++] = cmd;
printf("found: %s\n", entry->d_name);
}
closedir(dir);
*cmd_num = cmd_cnt;
return commands;
}
char *check_inner_cmd(int cmd_cnt, char **cmds, char **argv) {
if (cmds == NULL) {
return argv[0];
}
const int MAX_CMD_LENGTH = 128;
char *cmd = malloc(sizeof(char) * MAX_CMD_LENGTH);
memset(cmd, 0, sizeof(char) * MAX_CMD_LENGTH);
for (int i = 0; i < cmd_cnt; i++) {
if (strcmp(argv[0], cmds[i])) {
continue;
}
snprintf(cmd, MAX_CMD_LENGTH, "./commands/%s/%s", cmds[i], cmds[i]);
break;
}
if (cmd[0] == '\0') {
free(cmd);
cmd = argv[0];
}
return cmd;
}
void free_inner_cmds(int cnt, char **cmds) {
for (int i = 0; i < cnt; i++) {
free(cmds[i]);
}
free(cmds);
}
|
C
|
/***************************************************************
Student Name: Mikayla Timm
File Name: BruteForce.c
Assignment number 3
Genetic
*BruteForce.c implements all the functions that deal with the brute force algorithm for
* solving the Traveling salesman problem.
***************************************************************/
#include "BruteForce.h"
#include <stdio.h>
#include <stdlib.h>
/*
* Main function called for performing the BF approach.
* Computes the number of permutations we need and calls perm1.
*/
void PermuteIter(int numCPermute){
int i;
int n;
long long unsigned int nfact = 1;//factorial of numCPermute
n = numCPermute; //number of cities to permute = numcities -1
for(i=1; i <=n; i++){
nfact *= i;
}
perm1(n, nfact);
//printf("\n");
}
/*
* Perm1 function goes through every possible permutation, or every possible
* path. Saves the optimal path and cost.
*/
void perm1(int n, long long unsigned int nfact){
int m, k, p, q;
double cost;
long long unsigned int i;
//printS(n);
for(i = 1; i < nfact; i++){
m = n-2;
while(s[m]>s[m+1]){
m = m-1;
}
k = n-1;
while(s[m]>s[k]){
k = k-1;
}
swap(m,k);
p =m+1;
q = n-1;
while(p<q){
swap(p,q);
p++;
q--;
}
//calculate cost
cost = calculateCost(n);
if(cost < lowestCost){
int ctr;
lowestCost = cost;
for(ctr=0; ctr < n; ctr++){
lowestPath[ctr] = s[ctr];
}
}
}
}
/*
* Swaps the two items located at index m and k.
*/
void swap(int m, int k){
int tempK = s[k];
s[k] = s[m];
s[m] = tempK;
}
/*
* Prints the current path array with leading and ending 0's.
*/
void printS(int n){
//print current path array with 0 in front and 0 at the end
int i;
fprintf(stderr, "0");
for(i=0; i < n; i++){
fprintf(stderr, "%d", s[i]);
}
fprintf(stderr, "0\n");
}
/*
* Calculates the cost of the current path by adding up the weights between the
* cities in the path.
*/
double calculateCost(int n){
int i;
double cost = 0;
for(i=0; i < n-1; i++){
cost+=weights[s[i]][s[i+1]]; //add up the costs for the path found in permutation
}
//add in the cost for the last city to 0
cost += weights[s[n-1]][0];
//add in the cost for 0 to the first city in the permutation
cost += weights[0][s[0]];
return cost;
}
|
C
|
#include <assert.h>
#include <errno.h>
// #include <error.h>
#include <fcntl.h>
#include <limits.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#define BUFSIZE 4096
#include "compute.h"
int main(int argc, char *argv[]) {
const char *app_reader = "/tmp/app_reader";
const char *app_writer = "/tmp/app_writer";
int read_fd, write_fd;
char buf[BUFSIZE] = {'\n'};
int count = 0;
int j;
if (access(app_writer, F_OK)) {
mkfifo(app_writer, 0666);
}
if (access(app_reader, F_OK)) {
mkfifo(app_reader, 0666);
}
read_fd = open(app_writer, O_RDONLY);
if (read_fd < 0) {
printf("%s:Could not open %s for reading %s\n", argv[0], app_writer,
strerror(errno));
exit(1);
}
printf("opened read_fd\n");
// write computation output
write_fd = open(app_reader, O_WRONLY);
if (write_fd < 0) {
printf("%s:Could not open %s for writing %s\n", argv[0], app_reader,
strerror(errno));
exit(1);
}
printf("opened write_fd\n");
// read application data
while (1) {
printf("Start Read\n");
int numInputs = 0;
check( read(read_fd, &numInputs, sizeof(int)) );
printf("read bytes %d\n", numInputs);
// printf("All Reads Complete\n");
j = compute(read_fd, numInputs);
printf("computation complete, writing output \n");
count = j;
int result = write(write_fd, &count, sizeof(int));
if (result < 0) {
printf("%s:Could not write %s\n", argv[0], strerror(errno));
exit(1);
}
}
close(read_fd);
close(write_fd);
printf("done\n");
}
|
C
|
#include "qdbmp.h"
#include <stdio.h>
int main()
{
BMP* bmp;
UCHAR r, g, b;
UINT width, height;
UINT x, y;
bmp = BMP_ReadFile("/home/ap4ep25/CLionProjects/untitled11/lena.bmp");
BMP_CHECK_ERROR( stderr, -1 ); /* If an error has occurred, notify and exit */
width = BMP_GetWidth( bmp );
height = BMP_GetHeight( bmp );
for ( x = 0 ; x < width ; ++x )
{
for ( y = 0 ; y < height ; ++y )
{
/* Get pixel's RGB values */
BMP_GetPixelRGB( bmp, x, y, &r, &g, &b );
/* Invert RGB values */
BMP_SetPixelRGB( bmp, x, y, 255 - r, 255 - g, 255 - b );
}
}
BMP_WriteFile( bmp, "/home/ap4ep25/CLionProjects/untitled11/lena_orig.bmp");
BMP_CHECK_ERROR( stderr, -2 );
BMP_Free( bmp );
return 0;
}
|
C
|
int my_strcmp(const char *s1, const char *s2)
{
int iter = 0;
while ((s1[iter] == s2[iter]) && (s1[iter] != '\0') && (s2[iter] != '\0'))
iter++;
return (s1[iter] - s2[iter]);
}
|
C
|
/*
Copyright (C) 2015 Alin Mindroc
(mindroc dot alin at gmail dot com)
This is a sample program that shows how to use InstructionAPI in order to
6 print the assembly code and functions in a provided binary.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
11 License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
*/
#include <iostream>
#include "CodeObject.h"
#include "InstructionDecoder.h"
using namespace std;
using namespace Dyninst;
using namespace ParseAPI;
using namespace InstructionAPI;
int main(int argc, char **argv){
if(argc != 2){
printf("Usage: %s <binary path>\n", argv[0]);
return -1;
}
char *binaryPath = argv[1];
SymtabCodeSource *sts;
CodeObject *co;
Instruction instr; //mod
SymtabAPI::Symtab *symTab;
std::string binaryPathStr(binaryPath);
bool isParsable = SymtabAPI::Symtab::openFile(symTab, binaryPathStr);
if(isParsable == false){
const char *error = "error: file can not be parsed";
cout << error;
return - 1;
}
sts = new SymtabCodeSource(binaryPath);
co = new CodeObject(sts);
//parse the binary given as a command line arg
co->parse();
//exit(-1);
//get list of all functions in the binary
const CodeObject::funclist &all = co->funcs();
if(all.size() == 0){
const char *error = "error: no functions in file";
cout << error;
return - 1;
}
auto fit = all.begin();
Function *f = *fit;
//create an Instruction decoder which will convert the binary opcodes to strings
InstructionDecoder decoder(f->isrc()->getPtrToInstruction(f->addr()),
InstructionDecoder::maxInstructionLength,
f->region()->getArch());
for(;fit != all.end(); ++fit){
Function *f = *fit;
//get address of entry point for current function
Address crtAddr = f->addr();
int instr_count = 0;
instr = decoder.decode((unsigned char *)f->isrc()->getPtrToInstruction(crtAddr));
auto fbl = f->blocks().end();
fbl--;
Block *b = *fbl;
Address lastAddr = b->last();
//if current function has zero instructions, don’t output it
if(crtAddr == lastAddr)
continue;
cout << "\n\n\"" << f->name() << "\" :";
while(crtAddr <= lastAddr){
//decode current instruction
instr = decoder.decode((unsigned char *)f->isrc()->getPtrToInstruction(crtAddr));
cout << hex << crtAddr << ":" << instr.format() << endl;
//go to the address of the next instruction
crtAddr += instr.size();
instr_count++;
}
}
cout<<"\n";
return 0;
}
|
C
|
#include <Python.h>
#include <structmember.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <sys/stat.h>
#define min(a,b) (((a)<(b))?(a):(b))
#define max(a,b) (((a)>(b))?(a):(b))
void __swap( long flg, char* txt ) {
char s;
if( flg == 1 ) { s = txt[0]; txt[0] = txt[3]; txt[3] = s; s = txt[1]; txt[1] = txt[2]; txt[2] = s; }
}
typedef struct {
PyObject_HEAD
FILE *fdes;
long natm, free, curr, head, crys, *sele, fsiz, swap;
char *buff, fnam[2048];
} oDCD;
static int __init( oDCD *self, PyObject *args, PyObject *kwds ) {
return( 0 );
}
static PyObject* __new( PyTypeObject *type, PyObject *args, PyObject *kwds ) {
oDCD *self;
self = (oDCD*) type->tp_alloc( type, 0 );
self->fdes = NULL;
self->natm = 0;
self->free = 0;
self->curr = 0;
self->head = 0;
self->crys = 0;
self->sele = NULL;
self->fsiz = 0;
self->buff = NULL;
self->swap = 0;
bzero( self->fnam, 2048 );
return( (PyObject*) self ) ;
}
static void __dealloc( oDCD *self ) {
free( self->sele );
free( self->buff );
self->fdes = NULL;
self->natm = 0;
self->free = 0;
self->curr = 0;
self->head = 0;
self->crys = 0;
self->sele = NULL;
self->fsiz = 0;
self->buff = NULL;
self->swap = 0;
bzero( self->fnam, 2048 );
Py_TYPE( self )->tp_free( (PyObject*) self );
}
static PyObject* __read( PyObject *self, PyObject *args ) {
PyObject *o_flg;
char *fname, buf[2048];
oDCD *obj = NULL;
int blk;
long i, tmp, fix, nfr = 0;
struct stat inf;
obj = (oDCD*) self;
o_flg = Py_True;
if( PyArg_ParseTuple( args, "s|O", &fname, &o_flg ) ) {
obj->fdes = fopen( fname, "rb" );
if( obj->fdes == NULL ) { Py_INCREF( Py_None ); return( Py_None ); }
stat( fname, &inf );
obj->fsiz = (long) inf.st_size;
if( o_flg == Py_True ) {
printf( "* [%s] ", fname );
for( i = 0; i < 55 - (long)strlen( fname ); i++ ) printf( "-" );
printf( "\n" );
}
fread( buf, 1, 4, obj->fdes ); memcpy( &blk, &buf[0], 4 );
if( blk == 84 ) {
obj->swap = 0;
if( o_flg == Py_True ) { printf( "+ \tSame Endian\n" ); }
} else {
obj->swap = 1;
if( o_flg == Py_True ) { printf( "+ \tSwapping Endian\n" ); }
}
fread( buf, 1, 4, obj->fdes );
fread( buf, 1, 4, obj->fdes ); __swap( obj->swap, buf ); memcpy( &blk, &buf[0], 4 );
nfr = (long) blk;
if( o_flg == Py_True ) { printf( "+ \tNFrames: %ld\n", nfr ); }
fread( buf, 1, 28, obj->fdes );
fread( buf, 1, 4, obj->fdes ); __swap( obj->swap, buf ); memcpy( &blk, &buf[0], 4 );
fix = (long) blk;
fread( buf, 1, 4, obj->fdes );
fread( buf, 1, 4, obj->fdes ); __swap( obj->swap, buf ); memcpy( &blk, &buf[0], 4 );
obj->crys = (long) blk;
fread( buf, 1, 40, obj->fdes );
fread( buf, 1, 4, obj->fdes ); __swap( obj->swap, buf ); memcpy( &blk, &buf[0], 4 );
tmp = 8 + (long) blk;
fread( buf, 1, tmp, obj->fdes );
fread( buf, 1, 4, obj->fdes ); __swap( obj->swap, buf ); memcpy( &blk, &buf[0], 4 );
obj->natm = (long) blk;
if( o_flg == Py_True ) { printf( "+ \tAtoms: %ld\n", obj->natm ); }
fread( buf, 1, 4, obj->fdes );
obj->free = obj->natm - (long)fix;
if( fix > 0 ) {
obj->sele = (long*) malloc( obj->free * sizeof( long ) );
if( o_flg == Py_True ) {
printf( "+ \tFixed Atoms: %ld\n", (long)fix );
printf( "+ \tFree Atoms: %ld\n", obj->free );
}
fread( buf, 1, 4, obj->fdes );
for( i = 0; i < obj->free; i++ ) {
fread( buf, 1, 4, obj->fdes ); __swap( obj->swap, buf ); memcpy( &blk, &buf[0], 4 );
obj->sele[i] = (long) blk - 1;
}
fread( buf, 1, 4, obj->fdes );
}
obj->curr = 0;
obj->head = ftell( obj->fdes );
if( o_flg == Py_True )
{ printf( "------------------------------------------------------------\n" ); }
obj->buff = (char*) malloc( 4 * obj->natm * sizeof( char ) );
bzero( obj->fnam, 2048 );
}
return( Py_BuildValue( "l", nfr ) );
}
static PyObject* __next( PyObject *self, PyObject *args ) {
PyObject *o_mol, *o_crd;
float blk;
long i, j, k;
oDCD *obj = NULL;
obj = (oDCD*) self;
if( PyArg_ParseTuple( args, "O", &o_mol ) ) {
if( obj->fdes == NULL ) {
printf( "* No DCD open...\n" );
Py_INCREF( Py_False ); return( Py_False );
}
if( fread( obj->buff, 1, 4, obj->fdes ) < 4 ) {
printf( "* End-Of-File reached...\n" );
Py_INCREF( Py_False ); return( Py_False );
}
if( obj->crys == 1 ) {
if( fread( obj->buff, 1, 56, obj->fdes ) < 56 ) {
printf( "* End-Of-File reached...\n" );
Py_INCREF( Py_False ); return( Py_False );
}
}
if( obj->natm != obj->free && obj->curr > 0 ) {
k = 4 * obj->free;
if( obj->fsiz - ftell( obj->fdes ) - 20 - 3 * k < 0 ) {
printf( "* End-Of-File reached...\n" );
Py_INCREF( Py_False ); return( Py_False );
}
o_crd = PyObject_GetAttrString( o_mol, "coor" );
fread( obj->buff, 1, k, obj->fdes );
for( i = 0, j = 0; i < obj->free; i++, j += 4 ) {
__swap( obj->swap, &(obj->buff[j]) ); memcpy( &blk, &(obj->buff[j]), 4 );
PyList_SetItem( o_crd, 3 * obj->sele[i], PyFloat_FromDouble( (double) blk ) );
}
fread( obj->buff, 1, 8, obj->fdes );
fread( obj->buff, 1, k, obj->fdes );
for( i = 0, j = 0; i < obj->free; i++, j += 4 ) {
__swap( obj->swap, &(obj->buff[j]) ); memcpy( &blk, &(obj->buff[j]), 4 );
PyList_SetItem( o_crd, 3 * obj->sele[i] + 1, PyFloat_FromDouble( (double) blk ) );
}
fread( obj->buff, 1, 8, obj->fdes );
fread( obj->buff, 1, k, obj->fdes );
for( i = 0, j = 0; i < obj->free; i++, j += 4 ) {
__swap( obj->swap, &(obj->buff[j]) ); memcpy( &blk, &(obj->buff[j]), 4 );
PyList_SetItem( o_crd, 3 * obj->sele[i] + 2, PyFloat_FromDouble( (double) blk ) );
}
fread( obj->buff, 1, 4, obj->fdes );
Py_DECREF( o_crd );
} else {
k = 4 * obj->natm;
if( obj->fsiz - ftell( obj->fdes ) - 20 - 3 * k < 0 ) {
printf( "* End-Of-File reached...\n" );
Py_INCREF( Py_False ); return( Py_False );
}
o_crd = PyObject_GetAttrString( o_mol, "coor" );
fread( obj->buff, 1, k, obj->fdes );
for( i = 0, j = 0; i < obj->natm; i++, j += 4 ) {
__swap( obj->swap, &(obj->buff[j]) ); memcpy( &blk, &(obj->buff[j]), 4 );
PyList_SetItem( o_crd, 3 * i, PyFloat_FromDouble( (double) blk ) );
}
fread( obj->buff, 1, 8, obj->fdes );
fread( obj->buff, 1, k, obj->fdes );
for( i = 0, j = 0; i < obj->natm; i++, j += 4 ) {
__swap( obj->swap, &(obj->buff[j]) ); memcpy( &blk, &(obj->buff[j]), 4 );
PyList_SetItem( o_crd, 3 * i + 1, PyFloat_FromDouble( (double) blk ) );
}
fread( obj->buff, 1, 8, obj->fdes );
fread( obj->buff, 1, k, obj->fdes );
for( i = 0, j = 0; i < obj->natm; i++, j += 4 ) {
__swap( obj->swap, &(obj->buff[j]) ); memcpy( &blk, &(obj->buff[j]), 4 );
PyList_SetItem( o_crd, 3 * i + 2, PyFloat_FromDouble( (double) blk ) );
}
fread( obj->buff, 1, 4, obj->fdes );
Py_DECREF( o_crd );
}
obj->curr += 1;
}
Py_INCREF( Py_True );
return( Py_True );
}
static PyObject* __close( PyObject *self, PyObject *args ) {
FILE *fd;
char buf[4];
oDCD *obj = NULL;
obj = (oDCD*) self;
if( obj->fdes != NULL ) { fclose( obj->fdes ); obj->fdes = NULL; }
if( obj->fnam[0] != 0 ) {
fd = fopen( obj->fnam, "rb+" );
memcpy( &buf[0], &(obj->curr), 4 ); __swap( obj->swap, buf );
fseek( fd, 8, SEEK_SET );
fwrite( buf, 1, 4, fd );
fseek( fd, 20, SEEK_SET );
fwrite( buf, 1, 4, fd );
fclose( fd );
bzero( obj->fnam, 2048 );
}
Py_INCREF( Py_None );
return( Py_None );
}
static PyObject* __goto( PyObject *self, PyObject *args ) {
long num = 0, dsp;
oDCD *obj = NULL;
obj = (oDCD*) self;
if( PyArg_ParseTuple( args, "l", &num ) ) {
if( obj->fdes != NULL && num >= 0 ) {
if( obj->natm != obj->free && num > 1 ) {
dsp = 4 + obj->crys * 56 + 3 * 4 * obj->free + 20;
} else {
dsp = 4 + obj->crys * 56 + 3 * 4 * obj->natm + 20;
}
obj->curr = num;
fseek( obj->fdes, obj->head + dsp * num, SEEK_SET );
}
}
Py_INCREF( Py_None );
return( Py_None );
}
static PyObject* __write( PyObject *self, PyObject *args ) {
PyObject *o_sele = NULL;
char *fname;
long natom;
char buf[256];
int blk;
long i, fix;
oDCD *obj = NULL;
obj = (oDCD*) self;
if( PyArg_ParseTuple( args, "sl|O", &fname, &natom, &o_sele ) ) {
obj->natm = natom;
obj->curr = 0;
snprintf( obj->fnam, 2048, "%s", fname );
fprintf(stderr,"[%s] %ld\n", obj->fnam, obj->natm );
obj->fdes = fopen( obj->fnam, "wb" );
blk = 84; memcpy( &buf[0], &blk, 4 ); fwrite( buf, 1, 4, obj->fdes );
memcpy( &buf[0], "CORD", 4 ); fwrite( buf, 1, 4, obj->fdes );
blk = -1; memcpy( &buf[0], &blk, 4 ); fwrite( buf, 1, 4, obj->fdes );
blk = 1; memcpy( &buf[0], &blk, 4 ); fwrite( buf, 1, 4, obj->fdes );
blk = 1; memcpy( &buf[0], &blk, 4 ); fwrite( buf, 1, 4, obj->fdes );
blk = -1; memcpy( &buf[0], &blk, 4 ); fwrite( buf, 1, 4, obj->fdes );
blk = 0; memcpy( &buf[0], &blk, 4 ); fwrite( buf, 1, 4, obj->fdes );
blk = 0; memcpy( &buf[0], &blk, 4 ); fwrite( buf, 1, 4, obj->fdes );
blk = 0; memcpy( &buf[0], &blk, 4 ); fwrite( buf, 1, 4, obj->fdes );
obj->free = natom;
obj->sele = NULL;
fix = 0;
if( o_sele != NULL && PyList_Check( o_sele ) ) {
i = (long) PyList_Size( o_sele );
if( i > 0 && i < natom ) {
obj->free = i;
obj->sele = (long*) malloc( obj->free * sizeof( long ) );
for( i = 0; i < obj->free; i++ )
obj->sele[i] = PyLong_AsLong( PyList_GetItem( o_sele, i ) );
fix = natom - obj->free;
}
}
blk = (int)( 3 * obj->free ); memcpy( &buf[0], &blk, 4 ); fwrite( buf, 1, 4, obj->fdes );
blk = (int) fix; memcpy( &buf[0], &blk, 4 ); fwrite( buf, 1, 4, obj->fdes );
blk = 0; memcpy( &buf[0], &blk, 4 ); for( i = 0; i < 11; i++ ) fwrite( buf, 1, 4, obj->fdes );
blk = 84; memcpy( &buf[0], &blk, 4 ); fwrite( buf, 1, 4, obj->fdes ); fwrite( buf, 1, 4, obj->fdes );
blk = 1; memcpy( &buf[0], &blk, 4 ); fwrite( buf, 1, 4, obj->fdes );
memcpy( &buf[0], "* Created with QMCube (qm3) ", 80 );
fwrite( buf, 1, 80, obj->fdes );
blk = 84; memcpy( &buf[0], &blk, 4 ); fwrite( buf, 1, 4, obj->fdes );
blk = 4; memcpy( &buf[0], &blk, 4 ); fwrite( buf, 1, 4, obj->fdes );
blk = (int) natom; memcpy( &buf[0], &blk, 4 ); fwrite( buf, 1, 4, obj->fdes );
blk = 4; memcpy( &buf[0], &blk, 4 ); fwrite( buf, 1, 4, obj->fdes );
if( obj->sele != NULL ) {
blk = (int)( 4 * obj->free ); memcpy( &buf[0], &blk, 4 ); fwrite( buf, 1, 4, obj->fdes );
for( i = 0; i < obj->free; i++ ) {
blk = (int)( obj->sele[i] + 1 ); memcpy( &buf[0], &blk, 4 ); fwrite( buf, 1, 4, obj->fdes );
}
blk = (int)( 4 * obj->free ); memcpy( &buf[0], &blk, 4 ); fwrite( buf, 1, 4, obj->fdes );
}
obj->buff = (char*) malloc( 4 * obj->natm * sizeof( char ) );
}
Py_INCREF( Py_None );
return( Py_None );
}
static PyObject* __append( PyObject *self, PyObject *args ) {
PyObject *o_mol, *o_crd;
char buf[4];
int cnt;
float blk;
long i, j;
oDCD *obj = NULL;
obj = (oDCD*) self;
if( PyArg_ParseTuple( args, "O", &o_mol ) ) {
if( obj->fdes == NULL ) {
printf( "* No DCD open...\n" );
Py_INCREF( Py_False ); return( Py_False );
}
o_crd = PyObject_GetAttrString( o_mol, "coor" );
if( obj->natm != obj->free && obj->curr > 0 ) {
cnt = (int)( 4 * obj->free );
memcpy( &buf[0], &cnt, 4 ); fwrite( buf, 1, 4, obj->fdes );
for( i = 0, j = 0; i < obj->free; i++, j += 4 ) {
blk = (float) PyFloat_AsDouble( PyList_GetItem( o_crd, 3 * obj->sele[i] ) );
memcpy( &(obj->buff[j]), &blk, 4 );
}
fwrite( obj->buff, 1, cnt, obj->fdes );
fwrite( buf, 1, 4, obj->fdes ); fwrite( buf, 1, 4, obj->fdes );
for( i = 0, j = 0; i < obj->free; i++, j += 4 ) {
blk = (float) PyFloat_AsDouble( PyList_GetItem( o_crd, 3 * obj->sele[i] + 1 ) );
memcpy( &(obj->buff[j]), &blk, 4 );
}
fwrite( obj->buff, 1, cnt, obj->fdes );
fwrite( buf, 1, 4, obj->fdes ); fwrite( buf, 1, 4, obj->fdes );
for( i = 0, j = 0; i < obj->free; i++, j += 4 ) {
blk = (float) PyFloat_AsDouble( PyList_GetItem( o_crd, 3 * obj->sele[i] + 2 ) );
memcpy( &(obj->buff[j]), &blk, 4 );
}
fwrite( obj->buff, 1, cnt, obj->fdes );
fwrite( buf, 1, 4, obj->fdes );
} else {
cnt = (int)( 4 * obj->natm );
memcpy( &buf[0], &cnt, 4 ); fwrite( buf, 1, 4, obj->fdes );
for( i = 0, j = 0; i < obj->natm; i++, j += 4 ) {
blk = (float) PyFloat_AsDouble( PyList_GetItem( o_crd, 3 * i ) );
memcpy( &(obj->buff[j]), &blk, 4 );
}
fwrite( obj->buff, 1, cnt, obj->fdes );
fwrite( buf, 1, 4, obj->fdes ); fwrite( buf, 1, 4, obj->fdes );
for( i = 0, j = 0; i < obj->natm; i++, j += 4 ) {
blk = (float) PyFloat_AsDouble( PyList_GetItem( o_crd, 3 * i + 1 ) );
memcpy( &(obj->buff[j]), &blk, 4 );
}
fwrite( obj->buff, 1, cnt, obj->fdes );
fwrite( buf, 1, 4, obj->fdes ); fwrite( buf, 1, 4, obj->fdes );
for( i = 0, j = 0; i < obj->natm; i++, j += 4 ) {
blk = (float) PyFloat_AsDouble( PyList_GetItem( o_crd, 3 * i + 2 ) );
memcpy( &(obj->buff[j]), &blk, 4 );
}
fwrite( obj->buff, 1, cnt, obj->fdes );
fwrite( buf, 1, 4, obj->fdes );
}
Py_DECREF( o_crd );
obj->curr++;
}
Py_INCREF( Py_True );
return( Py_True );
}
static struct PyMethodDef __methods [] = {
{ "open_read", (PyCFunction)__read, METH_VARARGS },
{ "open_write", (PyCFunction)__write, METH_VARARGS },
{ "close", (PyCFunction)__close, METH_VARARGS },
{ "next", (PyCFunction)__next, METH_VARARGS },
{ "goto", (PyCFunction)__goto, METH_VARARGS },
{ "append", (PyCFunction)__append, METH_VARARGS },
{ 0, 0, 0 }
};
static struct PyMemberDef __members [] = {
{ "curr", T_LONG, offsetof( oDCD, curr ), 0 },
{ "natm", T_LONG, offsetof( oDCD, natm ), 0 },
{ 0, 0, 0, 0 }
};
// --------------------------------------------------------------------------------------
static struct PyMethodDef methods [] = {
{ 0, 0, 0 }
};
#if PY_MAJOR_VERSION >= 3
static PyTypeObject tDCD = {
PyVarObject_HEAD_INIT( NULL, 0 )
.tp_name = "dcd",
.tp_doc = "(fast) DCD IO support",
.tp_basicsize = sizeof( oDCD ),
.tp_itemsize = 0,
.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
.tp_new = __new,
.tp_init = (initproc) __init,
.tp_dealloc = (destructor) __dealloc,
.tp_members = __members,
.tp_methods = __methods,
};
static struct PyModuleDef moddef = {
PyModuleDef_HEAD_INIT,
"_dcd",
NULL,
-1,
methods
};
PyMODINIT_FUNC PyInit__dcd( void ) {
PyObject *my_module;
my_module = PyModule_Create( &moddef );
PyType_Ready( &tDCD );
Py_INCREF( &tDCD );
PyModule_AddObject( my_module, "dcd", (PyObject *) &tDCD );
return( my_module );
}
#else
static PyTypeObject tDCD = {
PyVarObject_HEAD_INIT(NULL, 0)
"dcd", // tp_name
sizeof( oDCD ), // tp_basicsize
0, // tp_itemsize
(destructor)__dealloc, // tp_dealloc
0, // tp_print
0, // tp_getattr
0, // tp_setattr
0, // tp_compare
0, // tp_repr
0, // tp_as_number
0, // tp_as_sequence
0, // tp_as_mapping
0, // tp_hash
0, // tp_call
0, // tp_str
0, // tp_getattro
0, // tp_setattro
0, // tp_as_buffer
Py_TPFLAGS_DEFAULT |
Py_TPFLAGS_BASETYPE, // tp_flags
"(fast) DCD IO support",
// tp_doc
0, // tp_traverse
0, // tp_clear
0, // tp_richcompare
0, // tp_weaklistoffset
0, // tp_iter
0, // tp_iternext
__methods, // tp_methods
__members, // tp_members
0, // tp_getset
0, // tp_base
0, // tp_dict
0, // tp_descr_get
0, // tp_descr_set
0, // tp_dictoffset
(initproc)__init, // tp_init
0, // tp_alloc
__new, // tp_new
};
void init_dcd( void ) {
PyObject *my_module;
my_module = Py_InitModule( "_dcd", methods );
PyType_Ready( &tDCD );
Py_INCREF( &tDCD );
PyModule_AddObject( my_module, "dcd", (PyObject *) &tDCD );
}
#endif
|
C
|
/*
connect.c
Mike Hufnagel & Bill Kendrick
Last modified 11/17/95 (changed to return NULL on error)
*/
#include <X11/Xlib.h>
#include "connect.h"
Display *ConnectToServer(char* display_name, int *screen, Window *rootwindow)
{
Display *display;
/* connect & check for problems */
display = XOpenDisplay(display_name);
if (display != NULL)
{
/* get screen # */
*screen = DefaultScreen(display);
/* get screens root window id */
*rootwindow = RootWindow(display,*screen);
}
return(display);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.