language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <unistd.h>
static unsigned long fib(unsigned int n);
static unsigned long now_us(void);
int main(int argc, char* argv[]) {
pid_t pid = getpid();
printf("[");
int count = 0;
for (int j = 1; j < argc; ++j) {
unsigned int n = atoi(argv[j]);
unsigned long t0 = now_us();
unsigned long f = fib(n);
unsigned long t1 = now_us();
unsigned long elapsed = t1 - t0;
printf("%s\n { \"pid\": %ld, \"lang\": \"%s\", \"n\": %u, \"fib\": %lu, \"elapsed_us\": %lu }",
count ? "," : "", (long) pid, "C", n, f, elapsed);
++count;
}
printf("%s]\n", count > 0 ? "\n" : "");
}
static unsigned long fib(unsigned int n) {
if (n <= 1) {
return n;
}
return fib(n-1) + fib(n-2);
}
static unsigned long now_us(void)
{
struct timeval tv;
unsigned long now = 0.0;
int rc = gettimeofday(&tv, 0);
if (rc == 0) {
now = 1000000 * tv.tv_sec + tv.tv_usec;
}
return now;
}
|
C
|
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdio_ext.h>
#include <string.h>
#include "wrappers.h"
#define BUFFER_SIZE 16
#define TRUE 1
#define FALSE 0
/*-------------------------------------------------------------------------
* Program: beangame-client -
*
* Purpose: allocate a socket, connect to a server, player plays the game
* and data is sent back and forth between the client and server.
*
* Usage: beangame-client [ host ] [ port ]
*
* host - name of a computer on which server is executing
* port - protocol port number server is using
*
*-------------------------------------------------------------------------
*/
int main(int argc, char* argv[]) {
struct sockaddr_in sad; // structure to hold an IP address
struct addrinfo hints;
struct addrinfo *res;
struct addrinfo *ptr;
int sd; // socket descriptor
int port; // protocol port number
char *host; // pointer to host name
memset((char *)&sad,0,sizeof(sad)); // zero out sockaddr structure
sad.sin_family = AF_INET; // set family to Internet
// verify usage
if (argc < 3) {
printf("Usage: %s [ host ] [ port ] \n", argv[0]);
exit(-1);
}
host = argv[1];
port = atoi(argv[2]);
if (port > 0)
// test for legal value
sad.sin_port = htons((u_short)port);
else {
// print error message and exit
printf("ECHOREQ: bad port number %s\n", argv[2]);
exit(-1);
}
// convert host name to equivalent IP address and copy to sad
memset(&hints, 0, sizeof(hints));
hints.ai_family = PF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
getaddrinfo(host, argv[2], &hints, &res);
for (ptr = res; ptr != NULL; ptr = ptr->ai_next) {
// create socket
sd = Socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol);
if (sd == -1) continue;
// connect the socket to the specified server
int c = Connect(sd, ptr->ai_addr, ptr->ai_addrlen);
if (c == -1) {
Close(sd);
continue;
}
break;
}
if (ptr == NULL) {
fprintf(stderr, "Failed to connect\n");
exit(-1);
}
int wins = 0;
int losses = 0;
char char_input;
while (1) {
int turn = 1;
printf("+====================================================+\n");
__fpurge(stdin); // purge input buffer
printf(" Play the bean game? (y/n): ");
char_input = getc(stdin); // player input
if (char_input == 'y') { // start the game
int num_beans = 21;
printf("+----------------------------------------------------+\n");
printf("| INSTRUCTIONS |\n");
printf("| |\n");
printf("| This game begins with 21 beans. |\n");
printf("| Each player can remove 1, 2, or 3 beans at a time. |\n");
printf("| The goal is to remove the last bean. |\n");
printf("+----------------------------------------------------+\n");
while (num_beans > 0){
char in_msg[BUFFER_SIZE]; // buffer for incoming messages
// Player turn
printf(" (Turn %d) How many do you want to take? ", turn);
int player_take;
scanf("%d", &player_take); // player input (same function as getc)
++turn;
if ((player_take == 1) || (player_take == 2) || (player_take == 3)) {
num_beans -= player_take;
// Print result of player decision
if (num_beans == 1) {
printf(" There is %d bean remaining.\n", num_beans);
} else if (num_beans > 1) {
printf(" There are %d beans remaining.\n", num_beans);
} else if (num_beans == 0) {
printf(" There are %d beans remaining.\n", num_beans);
printf("+----------------------------------------------------+\n");
printf(" You win!\n");
++wins;
printf(" Wins: %d\n", wins);
printf(" Losses: %d\n", losses);
break;
} else {
printf(" You lose!\n");
++losses;
printf(" Wins: %d\n", wins);
printf(" Losses: %d\n", losses);
break;
}
char num_beans_str[BUFFER_SIZE];
sprintf(num_beans_str, "%d", num_beans); // int to string
// send message to server
Send(sd, num_beans_str, BUFFER_SIZE, 0);
// receive message from server
Recv(sd, &in_msg, BUFFER_SIZE, 0);
int beans = atoi(in_msg);
in_msg[0] = '\0';
int cpu_take = num_beans - beans;
num_beans = beans;
// Print CPU decision
if ((num_beans > 1) && (cpu_take == 1)) {
printf(" CPU took %d bean. There are %d beans remaining.\n", cpu_take, num_beans);
printf("+----------------------------------------------------+\n");
} else if ((num_beans == 1) && (cpu_take == 1)) {
printf(" CPU took %d bean. There is %d bean remaining.\n", cpu_take, num_beans);
printf("+----------------------------------------------------+\n");
} else if ((num_beans == 1) && (cpu_take > 1)) {
printf(" CPU took %d beans. There is %d bean remaining.\n", cpu_take, num_beans);
printf("+----------------------------------------------------+\n");
} else if ((num_beans == 0) && (cpu_take == 1)) {
printf(" CPU took %d bean. There are %d beans remaining.\n", cpu_take, num_beans);
printf("+----------------------------------------------------+\n");
printf(" You lose!\n");
++losses;
printf(" Wins: %d\n", wins);
printf(" Losses: %d\n", losses);
break;
} else if ((num_beans > 1) && (cpu_take > 1)) {
printf(" CPU took %d beans. There are %d beans remaining.\n", cpu_take, num_beans);
printf("+----------------------------------------------------+\n");
} else {
printf(" CPU took %d beans. There are %d beans remaining.\n", cpu_take, num_beans);
printf("+----------------------------------------------------+\n");
printf(" You lose!\n");
++losses;
printf(" Wins: %d\n", wins);
printf(" Losses: %d\n", losses);
break;
}
} else {
printf("+----------------------------------------------------+\n");
printf(" You can only take 1, 2, or 3 beans.\n");
}
}
} else if (char_input == 'n') { // end game
printf("+----------------------------------------------------+\n");
printf(" Final Score:\n");
printf(" > Wins: %d\n", wins);
printf(" > Losses: %d\n", losses);;
printf("+----------------------------------------------------+\n");
break;
} else { // handle error
printf("+----------------------------------------------------+\n");
printf("Enter y or n\n");
}
}
// close the socket
Close(sd);
return(0);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* todelete.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: vkryvono <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/02/02 15:01:00 by vkryvono #+# #+# */
/* Updated: 2019/02/02 15:01:00 by vkryvono ### ########.fr */
/* */
/* ************************************************************************** */
#include "lemin.h"
#include <stdio.h>
# define NORM "\x1B[0m"
# define RED "\x1B[31m"
# define GREEN "\x1B[32m"
# define YELLOW "\x1B[33m"
# define BLUE "\x1B[34m"
# define MAGENTA "\x1B[35m"
# define CYAN "\x1B[36m"
# define WHITE "\x1B[37m"
int ft_graphshow(t_graph *graph)
{
if (graph->head)
{
ft_lstiter(graph->head, ft_vertexshow);
return (1);
}
return (0);
}
void ft_vertexshow(t_list *lst)
{
t_vertex *vertex;
vertex = lst->content;
// if (graph->start == vertex)
// printf("%sstart->%s", RED, NORM);
// if (graph->end == vertex)
// printf("%send->%s", RED, NORM);
printf("%s(%d)%s[%s]%s[%s]%s:",
CYAN, vertex->status,
BLUE, vertex->name,
GREEN, (vertex->root) ? vertex->root->name : NULL, NORM);
fflush(stdout);
if (vertex->link)
ft_lstiter(vertex->link, ft_linkshow);
else
printf("[null]\n");
}
void ft_linkshow(t_list *lst)
{
t_route *route;
if (lst->content)
{
route = lst->content;
ft_printf("[%d|'%s']->", route->flow, route->vertex->name);
}
if (lst->next == NULL)
printf("[null]\n");
}
void ft_pathshow(t_list *lst)
{
if (lst->content)
ft_printf("[%s]", ((t_vertex *)lst->content)->name);
if (lst->next)
ft_printf("->");
else
printf("\n");
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <sys/socket.h> //socket
#include <arpa/inet.h> //inet_addr
#include <stdlib.h>
int main(int argc, char** argv) {
int skt_desc;
int skt_desc1;
struct sockaddr_in ser_addr;
struct sockaddr_in ser_addr1;
char ser_msg[2000], cli_msg[2000];
char buffer[256];
int n;
//Flushing Buffers
memset(ser_msg,'\0',sizeof(ser_msg));
memset(cli_msg,'\0',sizeof(cli_msg));
//Creating Socket
skt_desc = socket(AF_INET, SOCK_STREAM, 0);
if(skt_desc < 0)
{
printf("\nsocket not created!\n");
return -1;
}
printf("\nSocket is Created\n");
ser_addr.sin_family = AF_INET;
ser_addr.sin_port = htons(2000);
ser_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
//connect()
if(connect(skt_desc, (struct sockaddr*)&ser_addr, sizeof(ser_addr)) < 0)
{
printf("\nConnection is Failed!");
return -1;
}
printf("\nConnected successfully!\n");
//Receiving
if(recv(skt_desc, ser_msg, sizeof(ser_msg),0) < 0)
{
printf("\nReceiving failed\n");
return -1;
}
printf("\nMessage from main server: \n%s\n",ser_msg);
//input
printf("\nEnter your course name: ");
gets(cli_msg);
//Send msg
if(send(skt_desc, cli_msg, strlen(cli_msg),0) < 0)
{
printf("\nSending Failed!\n");
return -1;
}
//Receiving
memset(ser_msg,'\0',sizeof(ser_msg));
if(recv(skt_desc, ser_msg, sizeof(ser_msg),0) < 0)
{
printf("\nReceiving Failed!\n");
return -1;
}
printf("\nMessage from server: %s\n",ser_msg); ///spliting the message
char port_number[10],ip_address[20],course_name[10];
int i=0;
int j=0;
for(i=0;ser_msg[i]!=',';i++)
{
course_name[i]=ser_msg[i];
}
i++;
for(j=0;ser_msg[i]!=',';i++,j++)
{
ip_address[j]=ser_msg[i];
}
i++;
for(j=0;ser_msg[i]!='\0';i++,j++)
{
port_number[j]=ser_msg[i];
}
int ss_port=atoi(port_number);
printf("\nCourse Name:%s\n",course_name);
printf("IP address:%s\n",ip_address);
printf("Port Number: %i\n",ss_port);
memset(ser_msg,'\0',sizeof(ser_msg));
memset(cli_msg,'\0',sizeof(cli_msg));
//socket close
close(skt_desc);
//Creating Socket for sub server
skt_desc1 = -1;
skt_desc1 = socket(AF_INET, SOCK_STREAM, 0);
if(skt_desc1 < 0)
{
printf("\nsocket not created!\n");
return -1;
}
printf("\nSub Socket is Created\n");
ser_addr1.sin_family = AF_INET;
ser_addr1.sin_port = htons(ss_port);
ser_addr1.sin_addr.s_addr = inet_addr("127.0.0.1");
if(connect(skt_desc1, (struct sockaddr*)&ser_addr1, sizeof(ser_addr1)) < 0)
{
printf("\nSub server Connection Failed! ");
return -1;
}
printf("\nConnected to Sub Server\n");
//Flushing Buffers
memset(ser_msg,'\0',sizeof(ser_msg));
memset(cli_msg,'\0',sizeof(cli_msg));
//Receiving
if(recv(skt_desc1, ser_msg, sizeof(ser_msg),0) < 0)
{
printf("\nReceiving Failed!\n");
return -1;
}
printf("\nMessage from Sub Server: \n%s\n",ser_msg);
//Get Input
printf("\nEnter topic name: ");
gets(cli_msg);
//Send the message to Server
if(send(skt_desc1, cli_msg, strlen(cli_msg),0) < 0)
{
printf("\nSub Server Send Failed!\n");
return -1;
}
int z=0;
for(z=0;z<3;z++){
memset(ser_msg,'\0',sizeof(ser_msg));
memset(cli_msg,'\0',sizeof(cli_msg));
if(recv(skt_desc1, ser_msg, sizeof(ser_msg),0) < 0)
{
printf("\nReceiving Failed!\n");
return -1;
}
printf("\nMessage from Sub Server: %s\n",ser_msg);
gets(cli_msg);
//Send the message to Server
if(send(skt_desc1, cli_msg, strlen(cli_msg),0) < 0)
{
printf("\nSub Server Send Failed. Error!!!!\n");
return -1;
}
}
printf("\n\nQuiz Ended!\n");
close(skt_desc1);
return (EXIT_SUCCESS);
}
|
C
|
#include<stdio.h>
void main()
{
int a[4],b,i,n;
printf("Enter the Number");
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("Enter a Number to print: ");
scanf("%d",&b);
printf("the Number is : %d",a[b]);
}
|
C
|
int fb(int a){
int f[10000];
f[1]=1;
f[2]=2;
int i;
for(i=3;i<=a;i++){
f[i]=f[i-1]+f[i-2];
}
return f[a];
}
int main(){
int m;
double sum=0;
scanf("%d",&m);
int i,n,k;
for(i=0;i<m;i++){
scanf("%d",&n);
for(k=1;k<=n;k++){
sum+=1.0*fb(k+1)/fb(k);
}
printf("%.3lf\n",sum);
sum=0.0;
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
typedef int Data;
struct Node
{
Data val;
struct Node *left, *right;
};
struct Node* tree_create_leaf (Data x)
{
struct Node* leaf = (struct Node*) malloc (sizeof (struct Node));
leaf->val = x;
leaf->left = leaf->right = NULL;
return leaf;
}
struct Node* tree_add (struct Node* tree, Data x)
{
if (tree) {
struct Node* node = tree;
for (;;) {
if (x == node->val) {
return tree;
} else if (x < node->val) {
if (node->left) {
node = node->left;
} else {
node->left = tree_create_leaf (x);
return tree;
}
} else {
if (node->right) {
node = node->right;
} else {
node->right = tree_create_leaf (x);
return tree;
}
}
}
} else {
return tree_create_leaf (x);
}
}
void tree_print (struct Node* tree)
{
if (tree->left) {
tree_print (tree->left);
}
printf ("%d ", tree->val);
if (tree->right) {
tree_print (tree->right);
}
}
long tree_get_height_and_check_balance (struct Node* tree, long height)
{
long base = height + 1,
left_height = tree->left ? tree_get_height_and_check_balance (tree->left,
base) : base,
right_height = tree->right ? tree_get_height_and_check_balance (tree->right,
base) : base;
if (!left_height ||
!right_height ||
labs (left_height - right_height) > 1) {
/* unbalanced */
return 0;
} else {
if (left_height > base) {
base = left_height;
}
if (right_height > base) {
base = right_height;
}
return base;
}
}
void tree_destroy (struct Node* tree)
{
if (tree->left) {
tree_destroy (tree->left);
}
if (tree->right) {
tree_destroy (tree->right);
}
free (tree);
}
int main()
{
struct Node* tree = NULL;
int x;
while ((scanf ("%d", &x) == 1) && (x != 0)) {
tree = tree_add (tree, x);
}
printf ("%s\n", tree_get_height_and_check_balance (tree, 0) ? "YES" : "NO");
tree_destroy (tree);
}
|
C
|
#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
#include <ctype.h>
#include <gber.h>
static void hex_dumpf_r(FILE *f, const uint8_t *tmp, size_t len,
size_t llen, unsigned int depth)
{
size_t i, j;
size_t line;
for(j = 0; j < len; j += line, tmp += line) {
if ( j + llen > len ) {
line = len - j;
}else{
line = llen;
}
fprintf(f, "%*c%05x : ", depth, ' ', j);
for(i = 0; i < line; i++) {
if ( isprint(tmp[i]) ) {
fprintf(f, "%c", tmp[i]);
}else{
fprintf(f, ".");
}
}
for(; i < llen; i++)
fprintf(f, " ");
for(i=0; i < line; i++)
fprintf(f, " %02x", tmp[i]);
fprintf(f, "\n");
}
fprintf(f, "\n");
}
static int do_ber_dump(FILE *f, const uint8_t *ptr, size_t len,
unsigned int depth)
{
const uint8_t *end = ptr + len;
while(ptr < end) {
struct gber_tag tag;
ptr = ber_decode_tag(&tag, ptr, end - ptr);
if ( NULL == ptr )
return 0;
fprintf(f, "%*c.tag = %x\n", depth, ' ', tag.ber_tag);
fprintf(f, "%*c.class = %s\n", depth, ' ',
ber_id_octet_clsname(tag.ber_id));
fprintf(f, "%*c.constructed = %s\n", depth, ' ',
ber_id_octet_constructed(tag.ber_id) ? "yes" : "no");
fprintf(f, "%*c.len = %u (0x%.2x)\n",
depth, ' ', tag.ber_len, tag.ber_len);
if ( ber_id_octet_constructed(tag.ber_id) ) {
if ( !do_ber_dump(f, ptr, tag.ber_len, depth + 1) )
return 0;
}else{
hex_dumpf_r(f, ptr, tag.ber_len, 16, depth + 1);
}
ptr += tag.ber_len;
}
return 1;
}
int ber_dump(const uint8_t *ptr, size_t len)
{
return do_ber_dump(stdout, ptr, len, 1);
}
int ber_dumpf(FILE *f, const uint8_t *ptr, size_t len)
{
return do_ber_dump(f, ptr, len, 1);
}
const char * const ber_id_octet_clsname(uint8_t id)
{
static const char * const clsname[]={
"universal",
"application",
"context-specific",
"private",
};
return clsname[(id & 0xc0) >> 6];
}
unsigned int ber_id_octet_class(uint8_t id)
{
return (id & 0xc0) >> 6;
}
unsigned int ber_id_octet_constructed(uint8_t id)
{
return (id & 0x20) >> 5;
}
static uint8_t ber_len_form_short(uint8_t lb)
{
return !(lb & 0x80);
}
static uint8_t ber_len_short(uint8_t lb)
{
return lb & ~0x80;
}
static const uint8_t *do_decode_tag(struct gber_tag *tag,
const uint8_t *ptr, size_t len)
{
const uint8_t *end = ptr + len;
if ( len < 2 )
return NULL;
tag->ber_id = *(ptr++);
tag->ber_tag = tag->ber_id;
if ( (tag->ber_id & 0x1f) == 0x1f ) {
if ( (*ptr & 0x80) )
return NULL;
tag->ber_tag <<= 8;
tag->ber_tag |= *(ptr++);
if ( ptr >= end )
return NULL;
}
if ( ber_len_form_short(*ptr) ) {
tag->ber_len = ber_len_short(*ptr);
ptr++;
}else{
unsigned int i;
uint8_t ll;
ll = ber_len_short(*(ptr++));
if ( ptr + ll > end || ll > 4 )
return NULL;
for(tag->ber_len = 0, i = 0; i < ll; i++, ptr++) {
tag->ber_len <<= 8;
tag->ber_len |= *ptr;
}
}
return ptr;
}
const uint8_t *ber_tag_info(struct gber_tag *tag,
const uint8_t *ptr, size_t len)
{
return do_decode_tag(tag, ptr, len);
}
const uint8_t *ber_decode_tag(struct gber_tag *tag,
const uint8_t *ptr, size_t len)
{
const uint8_t *end = ptr + len;
ptr = do_decode_tag(tag, ptr, len);
if ( NULL == ptr || ptr + tag->ber_len > end )
return NULL;
return ptr;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "is_utf8.h"
#define BUFSIZE 4096
int main(int ac, char **av)
{
char buffer[BUFSIZE];
int read_retval;
size_t pos;
if (ac != 2)
{
fprintf(stderr, "USAGE: %s STRING or - for stdin.\n", av[0]);
return EXIT_FAILURE;
}
if (strcmp(av[1], "-") == 0)
{
while (42)
{
read_retval = read(0, buffer, BUFSIZE);
if (read_retval == 0)
return EXIT_SUCCESS;
if (read_retval == -1)
{
perror("read");
return EXIT_FAILURE;
}
if(is_utf8((unsigned char*)buffer, read_retval, &pos))
{
buffer[pos] = 0;
fprintf(stdout,"%s\n", buffer);
return EXIT_FAILURE;
}
else
{
fprintf(stdout, "%s\n", buffer);
}
/*if (is_utf8((unsigned char*)buffer, read_retval) != 0)
return EXIT_FAILURE;*/
}
return EXIT_SUCCESS;
}
return is_utf8((unsigned char*)av[1], strlen(av[1]), NULL);
}
|
C
|
#include "Filter.h"
#include "stdint.h"
#include "stdlib.h"
#define DFT_T float //Setting the default type of this Algorithm
//函数名字 ABS(DFT_T NUM)
//函数说明 取绝对值得函数
//参数 NUM :需要取绝对值的值
//返回值:NUM得绝对值
DFT_T ABS(DFT_T NUM)
{
if(NUM>=0)
{
return NUM;
}
else
{
return (0-NUM);
}
}
//函数名字 RangeSecureInit(RgSecrObj *p, DFT_T Up, DFT_T Low)
//函数说明 用于RS范围限定函数的句柄初始化
//参数 RgSecrObj *p :需要限定范围参数的结构体 其名字最好与保护参数的名字类似 :NAME_RS;
//参数 Up :限定范围的上限
//参数 Low :限定范围的下限
//返回值:1:设置成功
uint8_t RangeSecureInit(RgSecrObj *p, DFT_T Up, DFT_T Low)
{
p->UppLmt=Up;
p->LwrLmt=Low;
p->LstVl=0;
p->Output=0;
return 1;
}
//函数名字 RangeSecure_I(RgSecrObj *p, DFT_T CrtVal)
//函数说明 :第一类数字范围保护,大于范围取边界值
//参数 RgSecrObj *p :需要限定范围参数的结构体 其名字最好与保护参数的名字类似 :NAME_RS;
//参数 CrtVal :需要限制参数的当前值
//返回值: 经过参数保护以后的值
//快捷调用方式 RSI(CrtVal) 未定义
DFT_T RangeSecure_I(RgSecrObj *p, DFT_T CrtVal)
{
if(CrtVal>=p->UppLmt)
{
p->LstVl=p->Output;
p->Output=p->UppLmt;
return p->Output;
}
if(CrtVal<=p->LwrLmt)
{
p->LstVl=p->Output;
p->Output=p->LwrLmt;
return p->Output;
}
p->LstVl=p->Output;
p->Output=CrtVal;
return p->Output;
}
//函数名字 RangeSecure_II(RgSecrObj *p, DFT_T CrtVal)
//函数说明 :第二类数字范围保护,大于范围取上一次输出值
//参数 RgSecrObj *p :需要限定范围参数的结构体 其名字最好与保护参数的名字类似 :NAME_RS;
//参数 CrtVal :需要限制参数的当前值
//返回值: 经过参数保护以后的值
//快捷调用方式 RSII(CrtVal) 未定义
DFT_T RangeSecure_II(RgSecrObj *p, DFT_T CrtVal)
{
if(CrtVal>=p->UppLmt||CrtVal<=p->LwrLmt)
{
p->LstVl=p->Output;
p->Output=p->LstVl;
return p->Output;
}
p->LstVl=p->Output;
p->Output=CrtVal;
return p->Output;
}
//函数名字 LimFilterInit(LimFilterObj *p,DFT_T Error)
//函数说明 用于限幅滤波函数的句柄初始化
//参数 LimFilterObj *p:需要限定范围参数的结构体 其名字最好与限幅参数的名字类似 :NAME_RS;
//参数 Error :装置允许的误差限定范围
//返回值:1:设置成功
uint8_t LimFilterInit(LimFilterObj *p,DFT_T Error)
{
p->Error=Error;
p->Output=0;
p->LstVl=0;
p->FstFlg=1;
return 1;
}
//函数名字 LimFilter(LimFilterObj *p,DFT_T CrtVal)
//函数说明 用于限幅滤波,当数据的波动超过了误差允许值,以上一次输出为准
//参数 LimFilterObj *p:需要限定范围参数的结构体 其名字最好与限幅参数的名字类似 :NAME_RS;
//参数 CrtVal :滤波的值的当前值
//返回值:滤波后的值
DFT_T LimFilter(LimFilterObj *p,DFT_T CrtVal)
{
if(ABS((CrtVal-p->LstVl))>=p->Error)
{
if(p->FstFlg==1)
{
p->LstVl=p->Output;
p->Output=CrtVal;
return CrtVal;
}
else
{
p->LstVl=p->Output;
p->Output=p->LstVl;
return p->Output;
}
}
else
{
p->LstVl=p->Output;
p->Output=CrtVal;
return CrtVal;
}
}
//函数名字 SldAvrgFilter_I_Init(SldAvrgFilterObj *p,int N)
//函数说明 用于I类滑动滤波函数的句柄初始化
//参数 SldAvrgFilterObj *p:滑动滤波函数控制结构体 其名字最好与限幅参数的名字类似 :NAME_RS;
//参数 N :滑动器的滑动范围
//N建议取值:流量,N=12;压力,N=4;液面,N=4-12;温度,N=1-4
//返回值:1:设置成功
uint8_t SldAvrgFilter_I_Init(SldAvrgFilterObj *p,int N)
{
p->Filter_buf=malloc(sizeof(DFT_T)*(N+1));
p->N=N;
return 1;
}
//函数名字 SldAvrgFilter_I(SldAvrgFilterObj *P,DFT_T CrtVal)
//函数说明 用于滑动滤波I类,未加权
//参数 SldAvrgFilterObj *p:滑动滤波函数控制结构体 其名字最好与限幅参数的名字类似 :NAME_RS;
//参数 CrtVal :滤波的值的当前值
//返回值:滤波后的值
DFT_T SldAvrgFilter_I(SldAvrgFilterObj *p,DFT_T CrtVal)
{
DFT_T Sum;
p->Filter_buf[p->N]=CrtVal;
for(int i=0;i<p->N;i++)
{
p->Filter_buf[i]=p->Filter_buf[i+1];
Sum+=p->Filter_buf[i];
}
p->Output=Sum/p->N;
return p->Output;
}
//SldAvrgFilter_II_Init(SldAvrgFilterObj *p,int N,DFT_T *C) SldAvrgFilter_II_Init(SldAvrgFilterObj *p,int N)
//函数说明 用于II类滑动滤波函数的句柄初始化
//参数 SldAvrgFilterObj *p:滑动滤波函数控制结构体 其名字最好与限幅参数的名字类似 :NAME_RS;
//参数 N :滑动器的滑动范围
//N建议取值:流量,N=12;压力,N=4;液面,N=4-12;温度,N=1-4 ALL:3-14
//参数 *C:加权表的设置
//返回值:1:设置成功
uint8_t SldAvrgFilter_II_Init(SldAvrgFilterObj *p,int N,int *C)
{
p->Filter_buf=malloc(sizeof(DFT_T)*(N+1));
p->N=N;
p->Coe=C;
for(int i=0;i<N;i++)
{
p->SumCoe+=C[i];
}
return 1;
}
//函数名字 SldAvrgFilter_II(SldAvrgFilterObj *P,DFT_T CrtVal)
//函数说明 用于滑动滤波I类,加权
//参数 SldAvrgFilterObj *p:滑动滤波函数控制结构体 其名字最好与限幅参数的名字类似 :NAME_RS;
//参数 CrtVal :滤波的值的当前值
//返回值:滤波后的值
DFT_T SldAvrgFilter_II(SldAvrgFilterObj *p,DFT_T CrtVal)
{
int i;
int Sum;
p->Filter_buf[p->N]=CrtVal;
for(i=0;i<p->N;i++)
{
p->Filter_buf[i]=p->Filter_buf[i+1];
Sum+=p->Filter_buf[i]*(p->Coe[i]);
}
p->Output=Sum/p->SumCoe;
return p->Output;
}
//函数名字 MVFilterInit(MVFilterObj *p,int N)
//函数说明 用于防脉冲冲击滤波函数的句柄初始化
//参数 MVFilterObj *p:MV控制参数的结构体 其名字最好与限幅参数的名字类似 :NAME_RS;
//参数N :数据采集的特征值 建议值 》10
//返回值:1:设置成功
uint8_t MVFilterInit(MVFilterObj *p,int N)
{
p->N=N;
}
//函数名字 SldAvrgFilter_II(SldAvrgFilterObj *P,DFT_T CrtVal)
//函数说明 用于中值平均滤波类,可以有效抑制冲击带来的偏差
//参数 SldAvrgFilterObj *p:滑动滤波函数控制结构体 其名字最好与限幅参数的名字类似 :NAME_RS;
//参数 CrtVal :滤波的值的当前值,是一个数据,本函数采用组运算
//返回值:滤波后的值
DFT_T MVfilter(MVFilterObj *p,DFT_T *CrtVal)
{
int i;
int j;
DFT_T filter_temp;
DFT_T Sum;
for(j = 0; j < p->N - 1; j++) //冒泡排序
{
for(i = 0; i < p->N - 1 - j; i++)
{
if(p->Filter_buf[i] >p-> Filter_buf[i + 1])
{
filter_temp = p->Filter_buf[i];
p->Filter_buf[i] = p->Filter_buf[i + 1];
p->Filter_buf[i + 1] = filter_temp;
}
}
}
for(i = 1; i < p->N - 1; i++)
Sum += p->Filter_buf[i];
p->Output=Sum / (p->N - 2);
return p->Output;
}
|
C
|
//for IR code optimization, read ICG.code file and process the file to generate the optimised IR
#include <stdio.h>
#include <stdlib.h>
// void const_propagation_optim(FILE* ir_fp, FILE* op_fp){
// //currently does only one constant propagation
// char* instrn_line = NULL;
// char ch;
// while(!feof(ir_fp)){
// int flag = 0;
// instrn_line = malloc(100*sizeof(char));
// int val = 0;
// char variable[3];
// while((ch = fgetc(ir_fp)) != '\n'){
// *instrn_line = ch;
// ++instrn_line;
// if(ch == '=')
// flag = 1;
// }
// //if flag is set impling that it has assignment and can be possible candidate for constant propagation
// if(flag){
// if(has_constant_propagation(instrn_line)){
// //store that constant along with the variable in the temp variables
// }
// }
// }
// }
// int main(){
// FILE* icg_fp = fopen("ICG.code", "r");
// FILE* op_fp = fopen("ICG_optimised.code", "w");
// if(icg_fp == NULL)
// printf("Error while opening file\n");
// printf("\n----------------------------------------------------------------\n");
// printf("\t\tIntermediate Code");
// printf("\n----------------------------------------------------------------\n\n");
// display(icg_fp);
// //constant propagation optimisation
// const_propagation_optim(icg_fp, op_fp);
// fclose(icg_fp);
// fclose(op_fp);
// return 0;
// }
void display(FILE* icg_fp){
char ch;
while(!feof(icg_fp)){
ch = fgetc(icg_fp);
printf("%c", ch);
}
}
//code to remove the constant assignment instruction
void reset_pointer(ir_quad* head, ir_quad* const_node){
ir_quad* curr = head;
ir_quad* prev = curr;
while(curr != NULL && curr != const_node){
prev = curr;
curr = curr->next;
}
prev->next = curr->next;
free(const_node);
}
//replaces the variable with the constant in the instruction using it
void perform_const_propagation(ir_quad* head, ir_quad* const_node){
ir_quad* temp = head;
while(temp != NULL){
if(temp != const_node){
// int flag = 0;
//check whether arg1 or arg2 have that variable which is constant propagated
if(temp->arg1 != NULL && !strcmp(temp->arg1, const_node->result)){
strcpy(temp->arg1, const_node->arg1);
// flag = 1;
}
else if(temp->arg2 != NULL && !strcmp(temp->arg2, const_node->result)){
strcpy(temp->arg2, const_node->arg1);
// flag = 1;
}
}
temp = temp->next;
}
//reset the pointers after all the constant propagations have been done
//removing the const_node
reset_pointer(head, const_node);
}
//can be integer, float, double
bool is_number(char* s){
//works if null character ('\0') is stored at the end
while(*s){
char c = *s;
switch(c){
case '.' : break;
case '+' : break;
case '-' : break;
default : if(c < '0' || c > '9') //checks the ASCII value
return false;
}
++s;
}
return true;
}
bool check_assignment_only(ir_quad* node){
if(strcmp(node->op,"=") != 0)
return false;
else{
if(node->arg1 != NULL && node->arg2 == NULL && is_number(node->arg1)){ //eg. u = 1 =>: =, 1, null, u
return true;
}
else
return false;
}
}
void const_propagation(ir_quad* head){
ir_quad* temp = head;
//store all the pointers to the node performing constant assignment instruction
ir_quad* arr_ptr[20] = {[0 ... 19] = NULL}; //array of pointers to the node
int cnt = 0;
while(temp != NULL){
if(check_assignment_only(temp)){
arr_ptr[cnt] = temp;
++cnt;
}
temp = temp->next;
}
// temp = head;
//now take one by one assignment instruction and perform constant propagation
for(int i = 0; i < cnt; ++i){
ir_quad* temp_node = arr_ptr[i];
//use this constant for propagation
perform_const_propagation(head, temp_node);
}
}
void const_folding(ir_quad* head){
/* Implementation pending */
}
void store_in_file(ir_quad* head, FILE* fp){
/* Implementation pending */
}
void code_optimisation(ir_quad* quad_head){
//opening the icg code and display it
FILE* icg_fp = fopen("ICG.code", "r");
if(icg_fp == NULL)
printf("Error while opening file\n");
printf("\n----------------------------------------------------------------\n");
printf("\t\tIntermediate Code");
printf("\n----------------------------------------------------------------\n\n");
display(icg_fp);
//perform constant propagation
const_propagation(quad_head);
//perform constant folding
const_folding(quad_head);
//store the optimised code quadruple representation into the file
FILE* ir_op_fp = fopen("ICG_optimised.code", "w");
store_in_file(quad_head, ir_op_fp);
//display the optimised code
printf("\n----------------------------------------------------------------\n");
printf("\t\tIntermediate Optimised Code");
printf("\n----------------------------------------------------------------\n\n");
display(ir_op_fp);
//close the files opened
fclose(icg_fp);
fclose(ir_op_fp);
}
|
C
|
/*
** EPITECH PROJECT, 2020
** my_compute_power_it.c
** File description:
** [email protected]
*/
int my_compute_power_it(int nb, int p)
{
int res = nb;
if (p < 0)
return 0;
if (p == 0)
return 1;
for (int i = 1; i < p; i++)
res = res * nb;
return res;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* compare_by_time.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: akharrou <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/06/08 23:57:25 by akharrou #+# #+# */
/* Updated: 2019/06/11 12:46:39 by akharrou ### ########.fr */
/* */
/* ************************************************************************** */
#include "../ft_ls.h"
int compare_by_time(const void *a, const void *b)
{
long ret;
ret = (*(t_file **)b)->time.tv_sec - (*(t_file **)a)->time.tv_sec;
if (ret == 0)
{
ret = (*(t_file **)b)->time.tv_nsec - (*(t_file **)a)->time.tv_nsec;
if (ret == 0)
return (compare_by_ascii(a, b));
}
return (ret);
}
int reverse_compare_by_time(const void *a, const void *b)
{
long ret;
ret = (*(t_file **)a)->time.tv_sec - (*(t_file **)b)->time.tv_sec;
if (ret == 0)
{
ret = (*(t_file **)a)->time.tv_nsec - (*(t_file **)b)->time.tv_nsec;
if (ret == 0)
return (reverse_compare_by_ascii(a, b));
}
return (ret);
}
|
C
|
#include <stdio.h>
#include <cs50.h>
int main(void)
{
int n;
// repeat the question if input is not an integer
do
{
n = get_int("Height: ");
}
// that is in between 1 to 8
while (n < 1 || n > 8);
// increment # by the amount of n, printing each # in new line (number of column made)
for (int i = 0; i < n; i++)
{
// we want the bricks of # to be right-aligned
// so add spaces that results in total of n with the spaces included
for (int k = 0; k < n - i - 1 ; k++)
{
printf(" ");
}
// printing out bricks of #
for (int j = 0; j <= i; j++)
{
// we wanna print out # by the amount of n entered by the user
printf("#");
}
// prints each # in new line
printf("\n");
}
}
|
C
|
// ex17
typedef enum
{
IDLE, /* !< Waiting for Initial starting conditions */
PARK, /* !< Parking */
RUN_ON_FLY, /* !< Transition State that allow Run_On_Fly looking */
RUN, /* !< Running in normal condition */
WAIT, /* !< Waiting for next start up */
FAULT /* !< Fault state for errors or invalid parameters */
} SystStatus_t;
enum e1 {
A,
B = 10,
C
};
enum e1 vare1;
int var1;
int f1() {
var1 = WAIT;
vare1 = C;
return 0;
}
|
C
|
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#define THREAD_COUNT 8
#define MAX_COUNTER (1 * 1000)
// Prawdopodobnie największa kolekcja zmiennych globalnych jaką stworzyłem
// od wielu wielu lat.
static volatile LONG g_spinlock;
static int g_counter[THREAD_COUNT];
static uint64_t g_max_wait[THREAD_COUNT];
static uint64_t g_min_wait[THREAD_COUNT];
static uint64_t g_total[THREAD_COUNT];
static uint32_t g_round_time[THREAD_COUNT][MAX_COUNTER];
static volatile int g_finish;
static volatile LONG g_poor_mans_lock;
inline void my_spinlock_lock(LONG volatile *lock) {
while(InterlockedExchange(lock, 1) == 1);
}
inline void my_spinlock_unlock(LONG volatile *lock) {
InterlockedExchange(lock, 0);
}
inline uint64_t rdtsc() {
uint64_t timestamp;
// Używam RDTSCP zamiast RDTSC, ponieważ ta pierwsza jest instrukcją
// serializującą, tj. czeka aż wszystkie instrukcje faktycznie się wykonają -
// RDTSC mógłby zostać wykonany poza kolejnością, co by mogło dać trochę
// korzystniejsze wyniki.
asm volatile ("rdtscp"
: "=A" (timestamp) // EDX:EAX mają zostać zapisane do zmiennej timestamp
: // Brak argumentów wejściowych.
: "ecx"); // Zawartość rejestru ECX jest nadpisywana (jeśli
// kompilator uzna wartość w ECX za istotną,
return timestamp;
}
DWORD WINAPI BruteTest(LPVOID param) {
uint64_t t_start, t_end, t_final;
uint64_t t_total_start, t_total_end;
int thread_id = (int)param;
g_min_wait[thread_id] = ~0ULL;
// Próba zsynchronizowania wątków, by wystartowały naraz (jak w poprzednim
// przykładzie).
InterlockedIncrement(&g_poor_mans_lock);
while (g_poor_mans_lock != THREAD_COUNT);
t_total_start = rdtsc();
while (!g_finish) {
// Zajmij spinlock (i zmierz czas operacji w cyklach procesora).
t_start = rdtsc();
my_spinlock_lock(&g_spinlock);
t_end = rdtsc();
// Zanotuj czas trwania operacji.
t_final = t_end - t_start;
g_round_time[thread_id][g_counter[thread_id]] = t_end - t_total_start;
if (t_final > g_max_wait[thread_id]) {
g_max_wait[thread_id] = t_final;
}
if (t_final < g_min_wait[thread_id]) {
g_min_wait[thread_id] = t_final;
}
if (++g_counter[thread_id] == MAX_COUNTER) {
g_finish = 1;
}
my_spinlock_unlock(&g_spinlock);
}
t_total_end = rdtsc();
// Zanotuj całkowity czas trwania pętli.
g_total[thread_id] = t_total_end - t_total_start;
return 0;
}
int main(void) {
int i, j;
int non_zero_threads = 0;
HANDLE h[THREAD_COUNT];
// Uruchomienie THREAD_COUNT wątków.
g_poor_mans_lock = 0;
for (i = 0; i < THREAD_COUNT; i++) {
h[i] = CreateThread(NULL, 0, BruteTest, (LPVOID)i, 0, NULL);
}
WaitForMultipleObjects(THREAD_COUNT, h, TRUE, INFINITE);
// Zamknij uchwyty i wypisz podstawowe informacje.
for (i = 0; i < THREAD_COUNT; i++) {
CloseHandle(h[i]);
if (g_counter[i] > 0) {
printf("Counter %2i: %10i [%10I64u -- %10I64u] %I64u\n",
i, g_counter[i], g_min_wait[i], g_max_wait[i], g_total[i]);
non_zero_threads++;
}
}
printf("Total: %i threads\n", non_zero_threads);
// Zapisz
uint64_t tsc_sum[THREAD_COUNT] = { 0 };
FILE *f = fopen("starv.txt", "w");
for (i = 0; i < MAX_COUNTER; i++) {
fprintf(f, "%i\t", i);
for (j = 0; j < THREAD_COUNT; j++) {
if (g_round_time[j][i] == 0) {
g_round_time[j][i] = tsc_sum[j];
}
tsc_sum[j] = g_round_time[j][i];
fprintf(f, "%u\t", g_round_time[j][i]);
}
fprintf(f, "\n");
}
fclose(f);
return 0;
}
|
C
|
#include <stdio.h>
#include <limits.h>
// Number of vertices in the graph
#define V 5
#define FALSE 0
int minDistance(int dist[], int sptSet[]) {
int min_index;
int min;
min = INT_MAX;
for (int v = 0; v < V; v++) {
if (sptSet[v] == FALSE && dist[v] <= min) {
min = dist[v];
min_index = v;
}
}
return min_index;
}
int printSolution(int dist[], int n) {
int max;
max = 0;
printf("Vertex Distance from Source\n");
for (int i = 0; i < V; i++) {
if (dist[i] > max) {
max = dist[i];
}
printf("%d \t\t %d\n", i, dist[i]);
}
printf("The time it is received in the last city to get the message = %d \n", max);
}
void dijkstra(int graph[V][V], int src) {
int dist[V];
int sptSet[V];
for (int i = 0; i < V; i++) {
dist[i] = INT_MAX;
sptSet[i] = 0;
}
dist[src] = 0;
for (int count = 0; count < V-1; count++) {
int u = minDistance(dist, sptSet);
sptSet[u] = 1;
for (int v = 0; v < V; v++) {
if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX && (dist[u] + graph[u][v] < dist[v]) ) {
dist[v] = dist[u] + graph[u][v];
}
}
}
printSolution(dist, V);
}
int main() {
int graph[V][V] = {
{0, 50, 30, 100, 10},
{50, 0, 5, 20, 0},
{30, 5, 0, 50, 0},
{100, 20, 50, 0, 10},
{10, 0, 0, 10, 0}
};
dijkstra(graph, 0);
return 0;
}
|
C
|
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include "client.h"
/* @brief
* envoi et reception de message
* envoi et reception de nom du client
* envoi de l'opération et reception du resultat
* envoi de couleurs et reception de confirmation
*
* @params
* socketfd : Socket pour communiquer avec le serveur.
* type : Spécifie quelle fonction lancer (message, nom, calcule ou couleurs).
* pathname : Chemin de l'image à traiter.
*
* @return
* 0 si tout va bien ou -1 en cas d'erreur.
*/
int envoie_recois_message(
int socketfd,
char *type,
char *pathname
){
if( strcmp(type, "message") != 0 &&
strcmp(type, "nom") != 0 &&
strcmp(type, "calcule") != 0 &&
strcmp(type, "couleurs") != 0 ){
printf("Type inconnue\n");
return 0;
} /* Check if type is correct */
if(strcmp(type, "couleurs") == 0){
if(pathname == NULL){
printf("Vous devez spécifier une image.\n");
return 0;
} /* Check if we have the path of the picture */
return envoie_couleurs(socketfd, pathname);
} /* Check if type is couleurs */
char data[DATA_SIZE],
message[VALEURS_SIZE];
int write_status,
read_status;
if( strcmp(type, "message") == 0 ||
strcmp(type, "nom") == 0 ){
/* Message or name case */
/* Create object */
message_json *json = new_message_json(1);
/* Set the code of the message */
strcpy(json->code, type);
/* Ask the value of the message */
printf("Votre %s (max %d caracteres): ", type, VALEURS_SIZE);
fgets(json->valeurs[0], VALEURS_SIZE, stdin);
/* Create the string and delete the object */
create_message_json(data, json);
delete_message_json(json);
} else {
/* Compute case */
char number_c[VALEURS_SIZE];
int n = 0,
i = 1;
/* Ask the number of values */
printf("Nombre de valeurs de votre %s (max %d caracteres): ", type, VALEURS_SIZE);
fgets(number_c, VALEURS_SIZE, stdin);
n = atoi(number_c);
if(n == 0){
printf("Nombre de valeurs incorrect.\n");
return 0;
} /* Error case */
/* Create object */
message_json *json = new_message_json(n + 1);
/* Set the code of the message */
strcpy(json->code, type);
/* Ask the value of the operator of the message */
printf("Votre opérateur du %s (max %d caracteres): ", type, VALEURS_SIZE);
fgets(json->valeurs[0], VALEURS_SIZE, stdin);
/* Remove the return line */
json->valeurs[0][strcspn(json->valeurs[0], "\n")] = 0;
for(i; i <= n; i++){
/* Ask the value of the n number of the message */
printf("Votre %d nombre du %s (max %d caracteres): ", i, type, VALEURS_SIZE);
fgets(json->valeurs[i], VALEURS_SIZE, stdin);
/* Remove the return line */
json->valeurs[i][strcspn(json->valeurs[i], "\n")] = 0;
} /* Foreach valeurs */
/* Create the string and delete the object */
create_message_json(data, json);
delete_message_json(json);
} /* Create the string JSON message */
/* Test the message */
if(validateur_format_message_json(data) == -1 || validateur_content_message_json(data) == -1){
printf("Message à envoyer incorrect.\n");
return 0;
}
/* Send to the server the message */
write_status = write(socketfd, data, strlen(data));
if(write_status < 0){
perror("erreur ecriture");
exit(EXIT_FAILURE);
} /* Error write */
/* Read the response of the server */
memset(data, 0, sizeof(data));
read_status = read(socketfd, data, sizeof(data));
if(read_status < 0){
perror("erreur lecture");
return -1;
} /* Error read */
/* Test the message */
if(validateur_format_message_json(data) == -1 || validateur_content_message_json(data) == -1){
printf("Message recu incorrect.\n");
return 0;
}
/* Print the response */
printf("Message recu :\n");
message_json *json = create_object_json(data);
print_message_json(json);
delete_message_json(json);
return 0;
} /* envoie_recois_message */
/* @brief
* Analyse une image. Demande à l'utilisateur
* combien de couleurs il veut récupérer, puis,
* on stocke ces couleurs dans une string au format JSON.
*
* @params
* pathname : Chemin de l'image à traiter.
* data : String ou l'on stocke le message JSON.
*/
void analyse(
char *pathname,
char *data
){
couleur_compteur *cc = analyse_bmp_image(pathname);
int n = -1,
count;
message_json *json;
char number_c[10],
temp_string[10];
/* Check number of colors */
while(n <= 0 || n >= 30){
/* Ask the user how many colors */
printf("\nCombien de couleurs ? ");
fgets(number_c, 10, stdin);
n = atoi(number_c);
} /* while the user dont put a correct number */
/* New object */
json = new_message_json(n + 1);
sprintf(json->valeurs[0], "%d", n);
strcpy(json->code, "couleurs");
for (count = 1; count < (n + 1) && cc->size - count > 0; count++){
if(cc->compte_bit == BITS32){
sprintf(json->valeurs[count], "#%02x%02x%02x", cc->cc.cc24[cc->size-count].c.rouge,cc->cc.cc32[cc->size-count].c.vert,cc->cc.cc32[cc->size-count].c.bleu);
} /* Bit 32 case */
if(cc->compte_bit == BITS24){
sprintf(json->valeurs[count], "#%02x%02x%02x", cc->cc.cc32[cc->size-count].c.rouge,cc->cc.cc32[cc->size-count].c.vert,cc->cc.cc32[cc->size-count].c.bleu);
} /* Bit 24 case */
} /* For n colors that the user whant */
/* Create the string and delete the object */
create_message_json(data, json);
delete_message_json(json);
} /* analyse */
/* @brief
* Envoie au serveur n couleurs.
*
* @params
* socketfd : Socket pour communiquer avec le serveur.
* pathname : Chemin de l'image à traiter.
*
* @return
* 0 si tout va bien ou -1 en cas d'erreur.
*/
int envoie_couleurs(
int socketfd,
char *pathname
){
char data[DATA_SIZE];
int write_status,
read_status;
memset(data, 0, sizeof(data));
analyse(pathname, data);
/* Test the message */
if(validateur_format_message_json(data) == -1 || validateur_content_message_json(data) == -1){
printf("Message à envoyer incorrect.\n");
return 0;
}
/* Send to the server the message */
write_status = write(socketfd, data, strlen(data));
if(write_status < 0){
perror("erreur ecriture");
exit(EXIT_FAILURE);
} /* Error write */
/* Read the response of the server */
memset(data, 0, sizeof(data));
read_status = read(socketfd, data, sizeof(data));
if(read_status < 0){
perror("erreur lecture");
return -1;
} /* Error read */
/* Test the message */
if(validateur_format_message_json(data) == -1 || validateur_content_message_json(data) == -1){
printf("Message recu incorrect.\n");
return 0;
}
/* Print the response */
printf("Message recu :\n");
message_json *json = create_object_json(data);
print_message_json(json);
delete_message_json(json);
return 0;
} /* envoie_couleurs */
/* @brief
* Main fonction.
*/
int main(
int argc,
char **argv
){
int socketfd,
bind_status;
struct sockaddr_in server_addr, client_addr;
/* Create the socket */
socketfd = socket(AF_INET, SOCK_STREAM, 0);
if(socketfd < 0){
perror("socket");
exit(EXIT_FAILURE);
}
/* Put information of the server */
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(PORT);
server_addr.sin_addr.s_addr = INADDR_ANY;
/* Ask the server */
int connect_status = connect(socketfd, (struct sockaddr *) &server_addr, sizeof(server_addr));
if(connect_status < 0){
perror("connection serveur");
exit(EXIT_FAILURE);
} /* Error connect */
char type[DATA_SIZE];
/* Ask wich function execute */
printf("Quelle fonction lancer (message, nom, calcule ou couleurs): ");
fgets(type, DATA_SIZE, stdin);
/* Remove the return line */
type[strcspn(type, "\n")] = 0;
envoie_recois_message(socketfd, type, argv[1]);
/* Close the socket */
close(socketfd);
} /* main */
|
C
|
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
WiFiServer server(80);
WiFiClient client;
bool wait4req = false;
String req;
void start(String ssid, String pass){
//for static IP
//IPAddress local_IP(192,168,0,5);
//IPAddress gateway(192,168,0,1);
//IPAddress subnet(255,255,255,0);
//conect to Access Point
Serial.println("");
Serial.println("Setting up in station mode:");
Serial.print("connecting to ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid.c_str(),pass.c_str());
//WiFi.config(local_IP, gateway, subnet); //for static IP
//----------
//creating Access Point
/*Serial.println("setting up Access Point:");
Serial.println(WiFi.softAPConfig(local_IP, gateway, subnet));
Serial.println(WiFi.softAP("ESP8266_01","acess_point_password"));
Serial.println(WiFi.softAPIP());*/
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("success");
Serial.println("");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
Serial.print("MAC address: ");
Serial.println(WiFi.macAddress());
//start TCP server
server.begin();
Serial.println("TCP server started");
}
void check4req(){
client = server.available();
if (client) {
Serial.println("");
Serial.println("NEW REQUEST:");
//wait for client to send data
while (client.connected() && !client.available()) {
delay(1);
}
//got request, process in main
wait4req = false;
}
return;
}
void send2client(String data){
String s;
s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n";
s += data;
client.print(s);
client.flush();
Serial.print("returned ");
Serial.print(data);
Serial.println(" to client");
return;
}
|
C
|
#include<stdio.h>
void main(){
int a=5;
int b=10;
int c=0;
if(a<10) //false
printf("10 is greater\n");
if(a &&b) //1
printf("Core2web\n"); //Core2web
if(b && c) //0
printf("Biencaps\n"); //blank
if(b || c) //1
printf("Amazon\n"); //Amazon
}
|
C
|
#include<stdio.h>
int main()
{
int i,sum,n;
float m=100;
scanf("%d",&n);
sum=100;
for(i=1;i<n;i++)
{
sum+=200/2;
m=m/2;
}
printf("%d %.2f\n",sum,m);
return 0;
}
|
C
|
#include<stdio.h>
int stack[100],top=-1
void push(stack[], int item)
{
}
int main()
{
Stack my_stack;
int item;
push(&my_stack, 1);
push(&my_stack, 2);
push(&my_stack, 3);
}
|
C
|
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
/**
*main -List of Numbers
*Return: 0
*/
int main(void)
{
int n;
for (n = 0; n <= 9; n++)
printf("%d", n);
printf("\n");
return (0);
}
|
C
|
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
/* Type definitions */
typedef void* tree ;
struct mem_address {void* base; void* index; } ;
/* Variables and functions */
int /*<<< orphan*/ PLUS_EXPR ;
void* TREE_TYPE (void*) ;
void* fold_build2 (int /*<<< orphan*/ ,void*,void*,int /*<<< orphan*/ ) ;
int /*<<< orphan*/ fold_convert (void*,void*) ;
__attribute__((used)) static void
add_to_parts (struct mem_address *parts, tree elt)
{
tree type;
if (!parts->index)
{
parts->index = elt;
return;
}
if (!parts->base)
{
parts->base = elt;
return;
}
/* Add ELT to base. */
type = TREE_TYPE (parts->base);
parts->base = fold_build2 (PLUS_EXPR, type,
parts->base,
fold_convert (type, elt));
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* fillit.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: spatil <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/01/06 16:35:32 by spatil #+# #+# */
/* Updated: 2020/01/06 16:35:34 by spatil ### ########.fr */
/* */
/* ************************************************************************** */
#include "fillit.h"
extern int g_square;
extern t_tetri g_tet[26];
extern int g_numoftet;
extern char g_canvas[104][104];
extern char g_lastletter;
extern int g_lastpoint[26][2];
/*
An iterative backtracking algorithm which solves on g_canvas.
*/
int iterativeimp()
{
int blockNumber;
int *arr;
arr = (int*)malloc(sizeof(int) * 2);
blockNumber = 0;
arr[0] = 0;
arr[1] = 0;
while (blockNumber != g_numoftet)
{
if (arr[0] == -1 && arr[1] == -1)
{
if (g_lastletter <= '@')
{
g_square += 1;
blockNumber = 0;
arr[0] = 0;
arr[1] = 0;
}
else
{
removelastblock();
blockNumber -= 1;
arr = nextpoint(g_lastpoint[blockNumber][0], g_lastpoint[blockNumber][1], arr);
g_lastletter -= 1;
}
}
if (checkpoint(arr[0], arr[1], g_tet[blockNumber]))
{
addblock(arr[0], arr[1], g_tet[blockNumber]);
blockNumber += 1;
arr[0] = 0;
arr[1] = 0;
}
else
arr = nextpoint(arr[0], arr[1], arr);
}
return 0;
}
/*
Checks if the given point on the canvas can accomadate the given block.
*/
int checkpoint(int x, int y, t_tetri ablock)
{
int i;
i = 0;
while (i < 4)
{
if (x + ablock.cor[i][0] > g_square - 1)
return 0;
if (y + ablock.cor[i][1] > g_square - 1)
return 0;
if (g_canvas[x + ablock.cor[i][0]][y + ablock.cor[i][1]] != '.')
return 0;
i++;
}
return 1;
}
/*
Adds the given block at the given point on the canvas.
Use checkpoint() before this function as this does not perform
a check on the canvas.
*/
void addblock(int x, int y, t_tetri ablock)
{
int i;
i = 0;
g_lastletter = ablock.letter;
g_lastpoint[g_lastletter - 65][0] = x;
g_lastpoint[g_lastletter - 65][1] = y;
while (i < 4)
{
g_canvas[x + ablock.cor[i][0]][y + ablock.cor[i][1]] = g_lastletter;
i++;
}
}
/*
Removes the block with letter equal to var g_lastletter from canvas.
*/
void removelastblock()
{
int i;
int j;
i = 0;
j = 0;
while (i < g_square)
{
while (j < g_square)
{
if (g_canvas[i][j] == g_lastletter)
g_canvas[i][j] = '.';
j++;
}
j = 0;
i++;
}
}
/*
Initializes every element of g_canvas to '.' character.
*/
void initializecanvas()
{
int i = 0;
int j = 0;
while (i < 104)
{
while (j < 104)
{
g_canvas[i][j] = '.';
j++;
}
j = 0;
i++;
}
}
|
C
|
/* PROGRAM: Text.c
AUTHOR: Carolina Ayala
DATE: 29/Jan/03
PURPOSE: A simple library to display text
using glutBitmapCharater
*/
/**************************************************************************/
/* Include necessary header files
**************************************************************************/
#include "text.h"
/**************************************************************************/
/* Include necessary header files
**************************************************************************/
GLint base = 0;
/**************************************************************************/
/* Function to create NUMCHARACTERS list, each of them with a character
**************************************************************************/
void CreateCharacters( void *font ) {
int i;
base = glGenLists( NUMCHARACTERS );
for ( i = 0; i < NUMCHARACTERS; i++ ) {
glNewList( base + i, GL_COMPILE );
glutBitmapCharacter( font, i );
glEndList( );
}
}
/**************************************************************************/
/* Function to draw the text text
**************************************************************************/
void Legend( int x, int y, char *text ) {
glRasterPos2f( x, y );
glListBase( base );
glCallLists( (GLint) strlen( text ), GL_BYTE, text );
}
|
C
|
/*
MIT License
Copyright (c) 2019 abirvalarg
*/
#include "list.h"
#include <malloc.h>
size_t _list_append(struct _list_base *l, const void *data, size_t data_len)
{
struct _list_node *new = malloc(sizeof(struct _list_node) + data_len);
struct _list_node *last = l->tail;
memcpy((char*)(new + 1), data, data_len);
new->prev = last;
new->next = NULL;
if(last)
last->next = new;
else
l->head = new;
l->tail = new;
return ++(l->size);
}
struct _list_node *__list_get_node(struct _list_base *l, list_index_t idx)
{
if(idx >= 0 && idx < l->size)
{
struct _list_node *node = l->head;
while(idx--)
node = node->next;
return node;
}
else if(idx < 0 && (-idx - 1) < l->size)
{
struct _list_node *node = l->tail;
while(++idx)
node = node->prev;
return node;
}
else
return NULL;
}
void *_list_get(struct _list_base *l, list_index_t idx)
{
struct _list_node *node = __list_get_node(l, idx);
return node ? (void*)(node + 1) : NULL;
}
size_t _list_insert(struct _list_base *l, list_index_t idx, const void *data, size_t data_len)
{
struct _list_node *node = __list_get_node(l, idx);
if(node)
{
struct _list_node *new = malloc(sizeof(struct _list_node) + data_len);
new->prev = node->prev;
new->next = node;
if(node->prev)
node->prev->next = new;
node->prev = new;
memcpy((char*)(new + 1), data, data_len);
l->size++;
}
return l->size;
}
size_t _list_remove(struct _list_base *l, list_index_t idx)
{
struct _list_node *node = __list_get_node(l, idx);
if(node)
{
struct _list_node *prev = node->prev;
struct _list_node *next = node->next;
if(prev)
prev->next = next;
else
l->head = next;
if(next)
next->prev = prev;
else
l->tail = prev;
free(node);
l->size--;
}
return l->size;
}
void _list_destroy(struct _list_base *l)
{
struct _list_node *node = l->head;
while(node)
{
struct _list_node *next = node->next;
free(node);
node = next;
}
}
void _list_copy(struct _list_base *l, struct _list_base *dest, size_t data_len)
{
struct _list_node *src = l->head;
struct _list_node *prev = NULL;
struct _list_node *new = NULL;
while(src)
{
new = malloc(sizeof(struct _list_node) + data_len);
memcpy((char*)(new + 1), (char*)(src + 1), data_len);
new->prev = prev;
new->next = NULL;
if(prev)
prev->next = new;
else
dest->head = new;
dest->size++;
src = src->next;
prev = new;
}
dest->tail = new;
}
|
C
|
/*
* Implentation of lms circle fitting algorithm from:
* 'A simple approach for the estimation of circular arc centre and
* its *radius'
* by S M Thomas and Y T Chan, CVGIP Vol 45, pp 362-370, 1989
*/
#define FALSE 0
#define TRUE (!FALSE)
#define SQR(x) ((x) * (x))
extern int representation_ok;
compute_circle(x_cent,y_cent,radius2,nseg2,X,Y)
float *x_cent,*y_cent,*radius2;
int nseg2;
float X[],Y[];
{
float sx,sy,sx2,sy2,sxy,sx3,sy3,sx2y,sxy2;
float a1,a2,b1,b2,c1,c2;
int loop1;
float temp;
representation_ok = TRUE;
loop1 = 0;
/* initialise variables */;
sx = 0.0;
sy = 0.0;
sx2 = 0.0;
sy2 = 0.0;
sxy = 0.0;
sx3 = 0.0;
sy3 = 0.0;
sx2y = 0.0;
sxy2 = 0.0;
/* compute summations */
for (loop1=1; loop1<=nseg2; loop1++) {
sx = sx + X[loop1];
sy = sy + Y[loop1];
sx2 = sx2 + SQR(X[loop1]);
sy2 = sy2 + SQR(Y[loop1]);
sxy = sxy + X[loop1] * Y[loop1];
sx3 = sx3 + X[loop1] * X[loop1] * X[loop1];
sy3 = sy3 + Y[loop1] * Y[loop1] * Y[loop1];
sx2y = sx2y + SQR(X[loop1]) * Y[loop1];
sxy2 = sxy2 + SQR(Y[loop1]) * X[loop1];
}
/* compute a's,b's,c's */
a1 = 2.0 * (SQR(sx) - sx2 * nseg2);
a2 = 2.0 * (sx * sy - sxy * nseg2);
b1 = a2;
b2 = 2.0 * (SQR(sy) - sy2 * nseg2);
c1 = sx2 * sx - sx3 * nseg2 + sx * sy2 - sxy2 * nseg2;
c2 = sx2 * sy - sy3 * nseg2 + sy * sy2 - sx2y * nseg2;
/* compute centre */
temp = a1*b2 - a2*b1;
if (temp == 0) {
representation_ok = FALSE;
return;
}
*x_cent = (c1 * b2 - c2 * b1) / (a1 * b2 - a2 * b1);
*y_cent = (a1 * c2 - a2 * c1) / ( a1 * b2 - a2 * b1);
/* compute radius squared */
*radius2 = (sx2 - 2.0 * sx * *x_cent + SQR(*x_cent) * nseg2
+ sy2 - 2.0 * sy * *y_cent + SQR(*y_cent) * nseg2) / nseg2;
}
|
C
|
#include "myChatting_client.h"
int main(int argc, char *argv[])
{
if(!isValidMainArg(argc, argv))
{
perrorAndExit("inValid arg input occured");
return -1;
}
int clientSocket;
struct sockaddr_in serverAddress;
pthread_t sendMessageId, receiveMessageId;
void * threadReturn;
sprintf(chatName, "%s", argv[3]);
clientSocket = socket(PF_INET, SOCK_STREAM, 0);
if(clientSocket == -1)
perrorAndExit("socket() error");
serverAddress.sin_family = AF_INET;
serverAddress.sin_addr.s_addr = inet_addr(argv[1]);
serverAddress.sin_port = htons(atoi(argv[2]));
if(connect(clientSocket, (struct sockaddr*)&serverAddress, sizeof(serverAddress))==-1)
perrorAndExit("connect() error");
if(pthread_create(&sendMessageId, NULL, sendMessage, (void*)&clientSocket) != 0)
perror("receiveMessage pthread_create() error");
if(pthread_create(&receiveMessageId, NULL, receiveMessage, (void*)&clientSocket) != 0)
perror("sendMessage pthread_create() error");
if(pthread_join(sendMessageId, &threadReturn) != 0)
perrorAndExit("sendMessage pthread_join() error");
if(pthread_join(receiveMessageId, &threadReturn) != 0)
perrorAndExit("receiveMessage pthread_join() error");
close(clientSocket);
return 0;
}
int isValidMainArg(int argc, char *argv[])
{
if(argv == NULL)
return FALSE;
if(argv[0] == NULL || argv[1] == NULL || argv[2] == NULL || argv[3] == NULL)
return FALSE;
if(argc != 4)
{
printf("Usage : %s <IP> <port> <chatName> \n", argv[0]);
return FALSE;
}
if(!isValidPort(argv[2]))
{
printf("Port should be number, and valid Range is (%d - %d)\n", MIN_PORT_NUM, MAX_PORT_NUM);
return FALSE;
}
if(!isValidChatName(argv[3]))
{
printf("chatName length shoule be less than %d\n", MAX_CHATNAME_LENGTH);
return FALSE;
}
return TRUE;
}
|
C
|
#include <sys/types.h>
#include <stdio.h>
int main()
{
pid_t id_proceso;
pid_t id_padre;
id_proceso = getpid();
id_padre = getppid();
printf("Identificador del proceso:%d\n",id_proceso);
printf("Indetificador del proceso padre:%d\n",id_padre);
}
|
C
|
#include <stdio.h>
int main(){
int seq[10]={};
int seqm[]={};
int i,j,k,l,soma,maior,tamanho;
float media;
s = 0;
tamanho = ((sizeof seqm)/sizeof(int));
media = maior/tamanho;
for(i=0;i!=10;i++){
printf("Digite o %dº número:\n",i);
scanf("%d", &seq[i-1]);
}
for(i=0;i!=10;i++){
for(j=i;j!=10;j++){
soma = soma + seq[j];
}
if(soma > maior){
maior = soma;
for(k=i,l=0; k!=10; k++,l++){
seqm[l] = seq[k];
}
}
else if(soma = maior){
if( (soma/(10-i)) < media){
maior = soma;
for(k=i,l=0; k!=10; k++,l++){
seqm[l] = seq[k];
}
}
}
}
printf("A maior soma foi: %d\n",maior);
printf("A sequencia foi:\n");
for(l = 0; l != tamanho; l++){
printf("%d",seqm[l]);
}
}
|
C
|
#define CRT_SECURE_NO_WARNINGS
#include <stdio.h>
void TempSwap(int *m, int *n)
{
int temp;
temp = n;
n = m;
m = temp;
}
void Add_Swap(int *m, int *n)
{
*m = *m + *n;
*n = *m - *n;
*m = *m - *n;
}
void MultSwap(int *m, int *n)
{
*m = *m * *n;
*n = *m / *n;
*m = *m / *n;
}
void ExclSwap(int *m, int *n)
{
*m = *m ^ *n;
*n = *m ^ *n;
*m = *m ^ *n;
}
int main()
{
int a, b, c;
do
{
printf(" Է ּ : ");
scanf("%d %d", &a, &b);
printf(" ּ\n");
printf("1. TempSwap\n");
printf("2. Add Swap\n");
printf("3. MultSwap\n");
printf("4. ExclSwap\n");
scanf("%d", &c);
switch (c)
{
case 1:
TempSwap(&a, &b);
case 2:
Add_Swap(&a, &b);
case 3:
MultSwap(&a, &b);
case 4:
ExclSwap(&a, &b);
}
printf("%d %d", a, b);
printf("Ϸ 0 ٽ Ϸ ƹ ڳ Է ּ : ");
scanf("%d", &a);
} while (a != 0);
return 0;
}
|
C
|
/*
Non-blocking interface to read arbitrarily long lines
Copyright (C) 1997-2013 Petr Tesarik <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include "getline.h"
#define BUFFER_LOW 1024 /* low watermark */
#define BUFFER_INCR 4096 /* allocation increment */
enum getline_status
cbgetline(struct getline *s, GETLINEFUNC callback, void *cbdata)
{
ssize_t res;
char *p;
if (getline_buffered(s) > 0) {
s->data += s->len;
if ( (p = memchr(s->data, '\n', s->end - s->data)) ) {
s->len = p - s->data + 1;
return GLS_OK;
}
memmove(s->buf, s->data, s->end - s->data + 1);
s->end -= s->data - s->buf;
} else
s->end = s->buf;
s->data = s->buf;
s->len = 0;
if (s->buf + s->alloc - s->end < BUFFER_LOW) {
if ( !(p = realloc(s->buf, s->alloc + BUFFER_INCR)) )
return GLS_ERROR;
s->end = p + (s->end - s->buf);
s->buf = s->data = p;
s->alloc += BUFFER_INCR;
}
res = callback(cbdata, s->end, s->buf + s->alloc - s->end - 1);
if (res < 0)
return res;
s->end += res;
*s->end = 0;
if ( (p = memchr(s->data, '\n', s->end - s->data)) ) {
s->len = p - s->buf + 1;
return GLS_OK;
} else if (!res) {
s->len = s->end - s->data;
return s->len ? GLS_FINAL : GLS_EOF;
} else
return GLS_AGAIN;
}
enum getline_status
cbgetraw(struct getline *s, size_t length,
GETLINEFUNC callback, void *cbdata)
{
ssize_t res;
char *p;
if (getline_buffered(s) > 0) {
s->data += s->len;
p = s->data + length;
if (p <= s->end) {
s->len = length;
return GLS_OK;
}
memmove(s->buf, s->data, s->end - s->data + 1);
s->end -= s->data - s->buf;
} else
s->end = s->buf;
s->data = s->buf;
s->len = 0;
if (s->alloc < length) {
if ( !(p = realloc(s->buf, length)) )
return GLS_ERROR;
s->end = p + (s->end - s->buf);
s->buf = s->data = p;
s->alloc = length;
}
res = callback(cbdata, s->end, s->buf + s->alloc - s->end - 1);
if (res < 0)
return res;
s->end += res;
*s->end = 0;
p = s->data + length;
if (p <= s->end) {
s->len = length;
return GLS_OK;
} else if (!res) {
s->len = s->end - s->buf;
return s->len ? GLS_FINAL : GLS_EOF;
} else
return GLS_AGAIN;
}
static ssize_t
fdlinefunc(void *data, void *buf, size_t buflen)
{
return read(*(int*)data, buf, buflen);
}
enum getline_status
fdgetline(struct getline *s, int fd)
{
return cbgetline(s, fdlinefunc, &fd);
}
enum getline_status
fdgetraw(struct getline *s, size_t length, int fd)
{
return cbgetraw(s, length, fdlinefunc, &fd);
}
|
C
|
#include "sandpiles.h"
/**
* sandpiles_sum - Stablish the sandpile result of a sum of two sandpiles.
*
* @grid1: First Sandpile.
* @grid2: Second Sandpile.
* Return: Nothing.
*/
void sandpiles_sum(int grid1[3][3], int grid2[3][3])
{
int n = 0, i, j, new_grid[3][3];
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{
grid1[i][j] += grid2[i][j];
if (grid1[i][j] > 3)
n++;
}
}
while (n != 0)
{
printf("=\n");
print_grid(grid1);
for (i = 0; i < 3; i++)
for (j = 0; j < 3; j++)
new_grid[i][j] = grid1[i][j];
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{
if (new_grid[i][j] > 3)
{
grid1[i][j] -= 4;
(i - 1) >= 0 ? grid1[i - 1][j] += 1 : 0;
(i + 1) <= 2 ? grid1[i + 1][j] += 1 : 0;
(j - 1) >= 0 ? grid1[i][j - 1] += 1 : 0;
(j + 1) <= 2 ? grid1[i][j + 1] += 1 : 0;
}
}
}
n = 0;
for (i = 0; i < 3; i++)
for (j = 0; j < 3; j++)
if (grid1[i][j] > 3)
n++;
}
}
/**
* print_grid - Print 3x3 grid
* @grid: 3x3 grid
*
*/
static void print_grid(int grid[3][3])
{
int i, j;
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{
if (j)
printf(" ");
printf("%d", grid[i][j]);
}
printf("\n");
}
}
|
C
|
//=========================================================================
//naive dgemm c file
//
//Results:
// gsl runs at about ~3.5 GFLOP/s on my machine regardless of input sizes
// my worst results are ~280 MFLOP/s with block-size of 4/unrolling 4
// my best results are: ~820 MFLOP/s: block-size of 64, unroll 8
//
//=========================================================================
#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
#include <stdbool.h>
#include <time.h>
#include "get_real_time.h"
#include "gsl_result_check.h"
#include "matrix_utilities.h"
#define BLOCK_MIN 16
#define BLOCK_MAX 128
#define BLOCK_SCALE 2
#define NMP_MIN 16
#define NMP_MAX 2048
#define NMP_SCALE 2
#define UNROLL 16
//NOTE: using col-major order, with A transposed
// C[n][m] = A[n][p] * B[p][m]
void dgemm_block(double *A, double *B, double *C,
uint16_t N, uint16_t M, uint16_t P, uint16_t BS,
uint16_t i, uint16_t j, uint16_t k)
{
uint16_t min_i = i;
uint16_t min_j = j;
uint16_t min_k = k;
uint16_t max_i = (i + BS > N) ? N : (i + BS); //N!
uint16_t max_j = (j + BS > M) ? M : (j + BS); //M!
uint16_t max_k = (k + BS > P) ? P : (k + BS);
//zero result array
if (min_k == 0) {
for (j = min_j; j < max_j; ++j) {
for (i = min_i; i < max_i; i+=UNROLL) {
IDXC(C, i+0, j, N, M) = 0;
IDXC(C, i+1, j, N, M) = 0;
IDXC(C, i+2, j, N, M) = 0;
IDXC(C, i+3, j, N, M) = 0;
IDXC(C, i+4, j, N, M) = 0;
IDXC(C, i+5, j, N, M) = 0;
IDXC(C, i+6, j, N, M) = 0;
IDXC(C, i+7, j, N, M) = 0;
IDXC(C, i+8, j, N, M) = 0;
IDXC(C, i+9, j, N, M) = 0;
IDXC(C, i+10, j, N, M) = 0;
IDXC(C, i+11, j, N, M) = 0;
IDXC(C, i+12, j, N, M) = 0;
IDXC(C, i+13, j, N, M) = 0;
IDXC(C, i+14, j, N, M) = 0;
IDXC(C, i+15, j, N, M) = 0;
}
}
}
//compute result
for(j=min_j; j<max_j; ++j){
for(i=min_i; i<max_i; ++i){
for(k=min_k; k<max_k; k+=UNROLL){
IDXC(C, i, j, N, M) += (
IDXR(A, i, k+0, N, P)*IDXC(B, k+0, j, P, M) +
IDXR(A, i, k+1, N, P)*IDXC(B, k+1, j, P, M) +
IDXR(A, i, k+2, N, P)*IDXC(B, k+2, j, P, M) +
IDXR(A, i, k+3, N, P)*IDXC(B, k+3, j, P, M) +
IDXR(A, i, k+4, N, P)*IDXC(B, k+4, j, P, M) +
IDXR(A, i, k+5, N, P)*IDXC(B, k+5, j, P, M) +
IDXR(A, i, k+6, N, P)*IDXC(B, k+6, j, P, M) +
IDXR(A, i, k+7, N, P)*IDXC(B, k+7, j, P, M) +
IDXR(A, i, k+8, N, P)*IDXC(B, k+8, j, P, M) +
IDXR(A, i, k+9, N, P)*IDXC(B, k+9, j, P, M) +
IDXR(A, i, k+10, N, P)*IDXC(B, k+10, j, P, M) +
IDXR(A, i, k+11, N, P)*IDXC(B, k+11, j, P, M) +
IDXR(A, i, k+12, N, P)*IDXC(B, k+12, j, P, M) +
IDXR(A, i, k+13, N, P)*IDXC(B, k+13, j, P, M) +
IDXR(A, i, k+14, N, P)*IDXC(B, k+14, j, P, M) +
IDXR(A, i, k+15, N, P)*IDXC(B, k+15, j, P, M)
);
}
}
}
}
// C[n][m] = A[n][p] * B[p][m]
void dgemm(double *A, double *B, double *C,
uint16_t N, uint16_t M, uint16_t P, uint16_t BS)
{
double *A_trans = transpose_matrix_dcr(A, N, P);
for (uint16_t j=0; j<M; j += BS) {
for (uint16_t i=0; i<N; i += BS) {
for (uint16_t k=0; k<P; k += BS) {
dgemm_block(A_trans, B, C, N, M, P, BS, i, j, k);
}
}
}
destroy_matrix_d(A_trans);
}
void do_test(uint16_t N, uint16_t M, uint16_t P, uint16_t BS)
{
double *A, *B, *C, *gsl_A, *gsl_B, *gsl_C;
A = create_matrix_dc(N, P, FILL);
B = create_matrix_dc(P, M, FILL);
C = create_matrix_dc(N, M, NO_FILL);
double start = getRealTime();
dgemm(A, B, C, N, M, P, BS);
double duration = getRealTime() - start;
double flop = (double)((2 * (uint64_t)P - 1)*(uint64_t)N*(uint64_t)M);
printf("N=%4u M=%4u P=%4u BS=%4u | took % 10.6f secs | ", N, M, P,
BS, duration);
printf("% 10.3f MFLOP | ", flop/1e6);
printf("% 10.3f MFLOP/s || ", flop/(duration*1e6));
gsl_A = transpose_matrix_dcr(A, N, P);
gsl_B = transpose_matrix_dcr(B, P, M);
gsl_C = transpose_matrix_dcr(C, N, M);
verify_gsl_dgemm(gsl_A, gsl_B, gsl_C, N, M, P);
destroy_matrix_d(A);
destroy_matrix_d(B);
destroy_matrix_d(C);
destroy_matrix_d(gsl_A);
destroy_matrix_d(gsl_B);
destroy_matrix_d(gsl_C);
}
//NOTE: I confirmed by walking back down the block size that the performane
//on the way up and down for each block size was the same. This was to make
//sure the caches weren't getting 'warmed up' over each iteration. It was
//verified that no 'warming up' was happening. so i just commented those
//lines out to save runtime
int main(int argc, char **argv)
{
//set breakpoint here, then make command window huge
srand((unsigned)time(NULL));
for(uint16_t NMP=NMP_MIN; NMP <= NMP_MAX; NMP *= NMP_SCALE){
for(uint16_t BS=BLOCK_MIN; BS<=BLOCK_MAX; BS *= BLOCK_SCALE){
do_test(NMP, NMP, NMP, BS);
}
printf("\n");
}
//set breakpoint here, then analyze results
return 0;
}
|
C
|
#include "stdio.h"
#define MAXLEN 100
void shellsort(int v[], int n);
int main(void)
{
int v[MAXLEN], n, i;
printf("Enter the number of elements: ");
scanf("%d", &n);
for (i = 0; i < n; i++)
scanf("%d", &v[i]);
shellsort(v, n);
for (i = 0; i < n; i++)
printf("%d ", v[i]);
printf("\n");
return 0;
}
/* shellsort: sort v[0]...v[n-1] into increasing order. */
void shellsort(int v[], int n)
{
int i, j, gap, temp;
for(gap = n/2; gap > 0; gap /= 2)
for (i = gap; i < n; i++)
for (j = i-gap; (j>=0 && v[j]>v[j+gap]); j-=gap)
{
temp = v[j];
v[j] = v[j+gap];
v[j+gap] = temp;
}
}
|
C
|
#include "Header.h"
void addtolist(teacher** allt, char* user, char* name) {
if (*allt == NULL) {
printf("no teachers signed up!\n");
return;
}
bool exist = false;
teacher* t;
teacher* ret;
t = (struct teacher*) malloc(sizeof(struct teacher));
t = *allt;
bool contin = true;
while (contin) {
if (streql(t->username, user)) {
exist = true;
ret = t;
}
if (t->nextteacher != NULL)
{
t = t->nextteacher;
}
else {
contin = false;
}
}
if (!exist) {
printf("no such teacher exist! \n");
return;
}
if (*(ret->pendingstudentptr) == NULL) {
printf("waiting list is empty! \n");
return;
}
/*search for student to delete it from pending list*/
student* s;
student* returnendstudent;
student* prevstudent;
student* previous=NULL;
s = (struct student*) malloc(sizeof(struct student));
s = *(ret->pendingstudentptr);
contin = true;
exist = false;
int counter = 0, number = 0;
while (contin) {
if (streql(s->username, name)) {
exist = true;
returnendstudent = s;
prevstudent = previous;
number = counter; //save its position
}
if (s->next != NULL)
{
previous = s;
s = s->next;
counter++;
}
else {
contin = false;
}
}
if (!exist) {
printf("no such student exist in your pending list! \n");
return;
}
if (number == 0) {
/*he was the first student in the pending list
fisrt student should be his next student */
*(ret->pendingstudentptr) = returnendstudent->next;
}
else {
/*he was not the first student in the pending list
/next of his previous should be his next
/ prevstudent ---> s ---> (s->next)*/
prevstudent->next = returnendstudent->next;
/* prevstudent ---------> (s->next)
then we can free s or we can let it remain in the memory*/
}
/*add the student to the list
make the student*/
s = (struct student*) malloc(sizeof(struct student));
s->username = name;
s->grade_score = -1; /*-1 means he has not a grade.
adding him to the wait list*/
s->next = *(ret->firststudentptr);
*(ret->firststudentptr) = s;
}
|
C
|
// #include <stdio.h>
// #include <cs50.h>
int main(void)
{
//Create name variable that takes user input
string name = get_string("What is your name?");
//Print greeting to user using name variable
printf("hello, %s\n", name);
}
|
C
|
#include <stdio.h>
int main()
{
int a[5] = {1,2,3,4,5}
int b[5] = {5,4,3,2,1}
int t = 0;
int i = 0;
for (i = 0; i < 5; i++)
{
t = a[i];
a[i] = b[i];
b[i] = t;
}
for (i = 0; i < 5; i++)
{
printf("%d %d",a[i],b[i]);
}
return 0
}
|
C
|
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
// Reprezentacia jedneho uzla zretazeneho zoznamu
typedef struct _node {
int data; // hodnota uzla
struct _node * next; // dalsi uzol zoznamu
} NODE;
// Reprezentacia zretazeneho zoznamu
typedef struct {
NODE * first; // prvy uzol
} LIST;
// Reprezentacia uspesnosti vykonania
typedef enum {
FAILURE, // = 0
SUCCESS // = 1
} RESULT;
// [ZADANIE]:
// ..........
//
// Implementujte funkciu findLastButOne(), ktora hlada hodnotu predposledneho uzla zretazeneho zoznamu.
// Funkcia musi spravne pracovat pre lubovolny pocet uzlov v zozname.
//
// [PARAMETRE FUNKCIE]:
// ....................
// 'list' - zretazeny zoznam, v ktorom funkcia hlada hodnotu predposledneho uzla
// 'value - adresa, na ktoru funkcia skopiruje hodnotu predposledneho uzla, ak existuje
//
// [NAVRATOVA HODNOTA FUNKCIE]:
// ............................
// SUCCESS - ak predposledny uzol existuje (zoznam ma aspon 2 uzly)
// FAILURE - ak predposledny uzol neexistuje (zoznam ma menej ako 2 uzly)
//
// ..................................................................................
RESULT findLastButOne(LIST * list, int * value)
{
NODE *n = list->first;
NODE *n_prev = NULL;
//prejde sa cely zoznam
while (n->next != NULL) {
n_prev = n;
n = n->next;
}
if (n_prev==NULL) { //zoznam ma menej ako 2 uzly
return FAILURE;
}
else { //viac ako 2 uzly
*value = n_prev->data;
return SUCCESS;
}
}
void append(LIST *list, int num) {
NODE *new_node = (NODE*)malloc(sizeof(NODE));
NODE *n = list->first;
new_node->data = num;
new_node->next = NULL;
if (n!=NULL) {
while (n->next != NULL) {
n = n->next;
}
n->next = new_node;
}
else {
list->first = new_node;
}
}
void print(LIST *list) {
NODE *n = list->first;
while (n != NULL) {
printf("%d\n",n->data);
n = n->next;
}
}
int main()
{
LIST list = {NULL};
RESULT result;
int value;
int i,n = 5;
//do zoznamu sa zapisu hodnoty 0...n
for (i = 0; i < n; i++) {
append(&list, i);
}
print(&list);
result = findLastButOne(&list, &value);
if (result==SUCCESS) {
printf("result: %d data: %d\n", result, value);
}
else {
printf("result: %d\n", result);
}
return 0;
}
|
C
|
#include <sys/socket.h>
#include <arpa/inet.h> //inet_addr
#include <unistd.h> //write
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
sockaddr_un address;
int socket_fd, connection_fd;
socklen_t address_length;
pid_t child;
char buffer[256];
int n;
socket_fd = socket(AF_UNIX, SOCK_STREAM, 0);
if (socket_fd < 0){
printf("socket() failed\n");
return 1;
}
unlink("/tmp/demo_socket");
memset(&address, 0, sizeof(struct sockaddr_un));
address.sun_family = AF_UNIX;
snprintf(address.sun_path, UNIX_PATH_MAX, "/tmp/demo_socket");
if (bind(socket_fd, (struct sockaddr *) &address, sizeof(struct sockaddr_un)) != 0) {
printf("bind() failed\n");
return 1;
}
if(listen(socket_fd, 5) != 0) {
printf("listen() failed\n");
return 1;
}
address_length = sizeof(address);
while((connection_fd = accept(socket_fd,
(struct sockaddr *) &address,
&address_length)) > -1)
{
printf("successfully received data\n");
bzero(buffer,256);
n = read(connection_fd,buffer,255);
if (n < 0) error("ERROR reading from socket");
printf("Here is the message: %s\n\n", buffer);
strcpy(buffer, "Hi back from the C world");
n = write(connection_fd, buffer, strlen(buffer));
if (n < 0)
printf("ERROR writing to socket\n");
break;
}
close(socket_fd);
close(socket_fd);
return(0);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
/* estructura autorreferenciada */
struct nodoCola {
char dato;/* define dato como un char */
struct nodoCola *ptrSiguiente;
}; /* fin de la estructura nodoCola */
typedef struct nodoCola NodoCola;
typedef NodoCola *ptrNodoCola;
/* prototipos de las funciones */
void imprimeCola( ptrNodoCola ptrActual );
int estaVacia( ptrNodoCola ptrCabeza );
char retirar( ptrNodoCola *ptrCabeza, ptrNodoCola *ptrTalon );
void agregar( ptrNodoCola *ptrCabeza, ptrNodoCola *ptrTalon,char valor );
void instrucciones( void );
/* la función main comienza la ejecución del programa */
int main(){
ptrNodoCola ptrCabeza = NULL;/*incializa ptrCabeza */
ptrNodoCola ptrTalon = NULL;/*incializa ptrTalon */
int eleccion;/*elección de menú del usuario */
char elemento;/*entrada char del usuario */
instrucciones(); /* despliega el menú */
printf( "? " );
scanf( "%d", &eleccion );/* mientras el usuario no introduzca 3 */
while ( eleccion != 3 ) {
switch( eleccion ) {
/* agrega el valor */
case 1:
printf( "Introduzca un caracter: " );
scanf( "\n%c", &elemento );
agregar( &ptrCabeza, &ptrTalon, elemento );
imprimeCola( ptrCabeza );
break;
/* retira el valor */
case 2:
/* si la cola no está vacía */
if ( !estaVacia( ptrCabeza ) ) {
elemento = retirar( &ptrCabeza, &ptrTalon );
printf( "se desenfilo %c.\n", elemento );
} /* fin de if */
imprimeCola( ptrCabeza );
break;
default:
printf( "Eleccion no valida.\n\n" );
instrucciones();
break;
} /* fin de switch */
printf( "? " );
scanf( "%d", &eleccion );
} /* fin de while */
printf( "Fin de programa.\n" );
return 0; /* indica terminación exitosa */
} /* fin de main */
/* despliega las instrucciones del programa para el usuario */
void instrucciones( void ){
printf ( "Introduzca su eleccion:\n"
"1 para retirar un elemento a la cola\n"
"2 para eliminar un elemento de la cola\n"
"3 para terminar\n" );
} /* fin de la función instrucciones */
/* inserta un nodo al final de la cola */
void agregar( ptrNodoCola *ptrCabeza, ptrNodoCola *ptrTalon, char valor ){
ptrNodoCola ptrNuevo; /* apuntador a un nuevo nodo */
ptrNuevo = malloc( sizeof( NodoCola ) );
if ( ptrNuevo != NULL ) { /* es espacio disponible */
ptrNuevo->dato = valor;
ptrNuevo->ptrSiguiente = NULL;
/* si está vacía inserta un nodo en la cabeza */
if ( estaVacia( *ptrCabeza ) ) {
*ptrCabeza = ptrNuevo;
} /* fin de if */
else {
( *ptrTalon )->ptrSiguiente = ptrNuevo;
} /* fin de else */
*ptrTalon = ptrNuevo;
} /* fin de if */
else {
printf( "no se inserto %c. No hay memoria disponible.\n", valor );
} /* fin de else */
} /* fin de la función agregar */
/* elimina el nodo de la cabeza de la cola */
char retirar( ptrNodoCola *ptrCabeza, ptrNodoCola *ptrTalon ){
char valor;/* valor del nodo */
ptrNodoCola tempPtr; /* apuntador a un nodo temporal */
valor = ( *ptrCabeza )->dato;
tempPtr = *ptrCabeza;
*ptrCabeza = ( *ptrCabeza )->ptrSiguiente;
/* si la cola está vacía */
if ( *ptrCabeza == NULL ) {
*ptrTalon = NULL;
} /* fin de if */
free( tempPtr );
return valor;
} /* fin de la función retirar */
/* Devuelve 1 si la cola está vacía, de lo contrario devuelve 0 */
int estaVacia( ptrNodoCola ptrCabeza ){
return ptrCabeza == NULL;
} /* fin de la función estaVacia */
/* Imprime la cola */
void imprimeCola( ptrNodoCola ptrActual ) {
/* si la cola está vacía */
if ( ptrActual == NULL ) {
printf( "La cola esta vacia.\n\n" );
} /* fin de if */
else {
printf( "La cola es:\n" );
/* mientras no sea el final de la cola */
while ( ptrActual != NULL ) {
printf( "%c —> ", ptrActual->dato );
ptrActual = ptrActual->ptrSiguiente;
} /* fin de while */
printf( "NULL\n\n" );
} /* fin de else */
} /* fin de la función imprimeCola */
|
C
|
#include <sys/types.h>
#include <sys/times.h>
#include <time.h>
#include <limits.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
int main(void) {
time_t t;
struct tms mytms;
clock_t t1, t2;
if ((t1 = times(&mytms)) == -1) {
perror("times 1");
exit(1);
}
sleep(5);
if ((t2 = times(&mytms)) == -1) {
perror("times 2");
exit(1);
}
printf("Total Execution time : %.1f sec\n", (double)(t2 - t1) / _SC_CLK_TCK);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/wait.h>
#include <unistd.h>
#include <sys/sem.h>
#define P(s) semop(s, &Pop, 1);
#define V(s) semop(s, &Vop, 1);
struct sembuf Pop;
struct sembuf Vop;
#define MAX 5
typedef struct{
int data[MAX];
int front, rear, count;
} buffer;
void __init__ (buffer *);
void insertbuf(buffer *, int);
void deletebuf(buffer *);
void frontbuf (buffer *, int *);
void producer(buffer*, int);
void consumer(buffer*, int);
static int Wait(int semid, int num) {
Pop.sem_flg = 0;
Pop.sem_num = num;
Pop.sem_op = -1;
P(semid);
return 0;
}
static int Signal(int semid, int num){
Vop.sem_flg = 0;
Vop.sem_num = num;
Vop.sem_op = 1;
V(semid);
return 0;
}
int main(){
int chID1, chID2, chID3,status;
struct shmid_ds buff;
buffer *qp;
key_t mykey;
// Creation of semaphore and shm
mykey = ftok("/Users/anjishnu/Documents/GitHub/6th_sem/OS/ass5/q_0/semprodcons.c", 1);
int shmID = shmget(mykey, sizeof(buffer), IPC_CREAT | 0777);
int semID = semget(mykey, 3, IPC_CREAT | 0777);
semctl(semID, 0 ,SETVAL, 1); // mutex = 1
semctl(semID, 1, SETVAL, MAX); // empty = MAX
semctl(semID, 2, SETVAL, 0); // full = 0
qp = (buffer*) shmat(shmID, 0,777);
if((chID1 = fork()!=0)){
if((chID2 = fork()!=0)){
if((chID3 = fork()!=0)){
waitpid(chID1, &status, 0);
waitpid(chID2, &status, 0);
waitpid(chID3, &status, 0);
shmdt(qp);
shmctl(shmID, IPC_RMID, &buff);
semctl(semID, 0, IPC_RMID);
}
else{
buffer *qp;
qp = (buffer *) shmat(shmID, 0 ,0777);
producer(qp,semID);
shmdt(qp);
}
}
else {
buffer *qp;
qp = (buffer *) shmat(shmID, 0, 0777);
consumer(qp, semID);
shmdt(qp);
}
}
else{
buffer *qp;
qp = (buffer *) shmat(shmID, 0 ,0777);
producer(qp,semID);
shmdt(qp);
}
return 0;
}
void __init__(buffer *q){
q->front = 0;
q->rear = 0;
q->count = 0;
}
void insertbuf(buffer *q, int n){
q->rear = (q->rear + 1 ) % MAX;
q->data[q->rear] = n;
q->count = q->count + 1;
}
void deletebuf(buffer *q){
q->front = (q->front + 1) % MAX;
q->count = q->count - 1;
}
void frontbuf (buffer *q, int *n){
*n = q->data[(q->front + 1) % MAX];
}
void producer (buffer *qp, int semID){
int count = 1;
srand(getpid());
while(count <= 10){
int data;
data = rand();
Wait(semID, 1); // wait(empty)
Wait(semID, 0); // wait(mutex)
insertbuf(qp,data); // critical section
Signal(semID,0); // signal(mutex)
Signal(semID,2); // signal(full)
printf("Process [%d] produced data %d. \n", getpid(),data);
sleep(2);
}
}
void consumer (buffer *qp, int semID){
int count = 1;
while(count<=10){
int data;
Wait(semID, 2); // wait(full)
Wait(semID, 0); // wait(mutex)
frontbuf(qp,&data); // critical section
deletebuf(qp); // critical section
Signal(semID, 0); // Signal(mutex)
Signal(semID, 1); // Signal(empty)
printf("Process [%d] consumerd data %d. \n", getpid(),data);
}
}
|
C
|
#include "ush.h"
/*
* Adds spaces ' ' before and after separator symbols
* Example:
* >>> "echo 1&&echo 2; pwd"
* <<< return "echo 1 && echo 2 ; pwd"
* PS. this is needed for splitting str by spaces.
*/
static int status_value(int status, char chr) {
int tmp_status = status;
if (chr == '\"' && tmp_status == 0)
tmp_status = 1;
else if (chr == '\"' && tmp_status == 1)
tmp_status = 0;
else if (chr == '\'' && tmp_status == 0)
tmp_status = 2;
else if (chr == '\'' && tmp_status == 2)
tmp_status = 0;
return tmp_status;
}
char *mx_space_prettier(char *input_str) {
char *sep = "|&<>";
char *new_str = mx_strnew((mx_strlen(input_str) + 1) * 2);
int index = 0;
int status = 0;
for (int i = 0; i < mx_strlen(input_str); ++i) {
status = status_value(status, input_str[i]);
if (mx_is_in_arr(sep, input_str[i]) && status == 0) {
new_str[index] = ' ';
index++;
new_str[index] = input_str[i];
index++;
if (input_str[i + 1] == input_str[i]) {
new_str[index] = input_str[i];
index++;
i++;
}
new_str[index] = ' ';
}
else
new_str[index] = input_str[i];
index++;
}
return new_str;
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX 500
struct product{
char name[50];
int size;
float price;
};
void token(char *str, struct product *products, int position);
void printData(struct product *products, int counter);
int main(int argc, char *argv[]){
char bff[MAX];
struct product products[10];
int counter = 0;
char *fileName;
FILE *file;
fileName = argv[1];
file = fopen(fileName, "r");
while(feof(file) == 0){
fgets(bff, MAX, file);
puts(bff); //Para verificar si está bien
token(bff, products, counter);
counter++;
}
printf("===============\n");
printData(products, counter);
fclose(file);
return 0;
}
void token(char *str, struct product *products, int position){
char name[50];
int size;
float price;
char *pch;
pch = strtok(str, ";,");
strcpy(name, pch);
pch = strtok(NULL, ";,");
size = atoi(pch);
pch = strtok(NULL, ";,");
price = atof(pch);
strcpy(products[position].name, name);
products[position].size = size;
products[position].price = price;
// printf("%s\n", name);
// printf("%d\n", size);
// printf("%f\n", price);
}
void printData(struct product *products, int counter){
int i;
float sum = 0;
printf("Nombre Cant Precio\n");
for (i = 0; i < counter; ++i){
printf("%s ", products[i].name);
printf("%d ", products[i].size);
printf("%f \n", products[i].price);
sum = sum + (products[i].size * products[i].price);
}
printf("Total: %f\n", sum);
}
// void getData(struct product *products, int position){
// }
//void printData
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "eaDSStack.h"
#define DEFAULT_EXP_FACTOR 2
#define DEFAULT_STARTING_CAPACITY 4
struct _eaDSStack {
void ** Data;
size_t Count, Capacity;
unsigned short ExpFactor, StartingCapacity;
void * (*dataCreateAndCopy)(const void *);
int (*dataCompare)(const void *, const void *);
void (*dataClear)(void *);
};
static void * copyAddress(const void * a)
{
return (void *) a;
}
eaDSStack eaDSStackInit(void * (*dataCreateAndCopy)(const void *), void (*dataClear)(void *))
{
return eaDSStackInitWithDetails(dataCreateAndCopy, dataClear, DEFAULT_EXP_FACTOR, DEFAULT_STARTING_CAPACITY);
}
eaDSStack eaDSStackInitWithDetails(void * (*dataCreateAndCopy)(const void *), void (*dataClear)(void *), unsigned short expFactor, unsigned short startingCapacity)
{
eaDSStack stack = (eaDSStack) malloc(sizeof(struct _eaDSStack));
if (NULL == stack)
{
perror(NULL);
}
else
{
stack->StartingCapacity = startingCapacity ? startingCapacity : DEFAULT_STARTING_CAPACITY;
stack->Data = (void **)malloc(stack->StartingCapacity * sizeof(void *));
if (NULL == stack->Data)
{
perror(NULL);
free(stack);
stack = NULL;
}
else
{
stack->Count = 0;
stack->Capacity = stack->StartingCapacity;
stack->ExpFactor = (expFactor < 2) ? DEFAULT_EXP_FACTOR : expFactor;
stack->dataCreateAndCopy = (NULL == dataCreateAndCopy) ? copyAddress : dataCreateAndCopy;
stack->dataClear = (NULL == dataClear) ? free : dataClear;
}
}
return stack;
}
int eaDSStackReset(eaDSStack stack)
{
if (NULL == stack->Data)
{
stack->Data = (void **) malloc(stack->Capacity * sizeof(void *));
if (NULL == stack->Data)
{
perror(NULL);
return EXIT_FAILURE;
}
}
else
{
while (stack->Count)
{
stack->dataClear(stack->Data[--stack->Count]);
}
if (stack->StartingCapacity < stack->Capacity)
{
free(stack->Data);
stack->Data = (void **) malloc(stack->Capacity * sizeof(void *));
if (NULL == stack->Data)
{
perror(NULL);
return EXIT_FAILURE;
}
stack->Capacity = stack->StartingCapacity;
}
}
return EXIT_SUCCESS;
}
void eaDSStackClear(eaDSStack stack)
{
if (NULL != stack->Data)
{
while(stack->Count)
{
stack->dataClear(stack->Data[--stack->Count]);
}
free(stack->Data);
}
free(stack);
}
size_t eaDSStackGetCount(const eaDSStack stack)
{
return stack->Count;
}
size_t eaDSStackGetCapacity(const eaDSStack stack)
{
return stack->Capacity;
}
void * eaDSStackPop(eaDSStack stack)
{
void * data = NULL;
if (stack->Count)
{
if ((DEFAULT_STARTING_CAPACITY < stack->Capacity) && (stack->Count < stack->Capacity / stack->ExpFactor))
{
void ** tmp;
stack->Capacity /= stack->ExpFactor;
tmp = (void **) realloc(stack->Data, stack->Capacity * sizeof(void *));
if (NULL != tmp)
{
stack->Data = tmp;
}
else
{
stack->Capacity *= stack->ExpFactor;
}
}
data = stack->dataCreateAndCopy(stack->Data[stack->Count - 1]);
if (NULL != data)
{
stack->dataClear(stack->Data[--stack->Count]);
}
else
{
perror(NULL);
}
}
return data;
}
int eaDSStackPush(eaDSStack stack, const void * data)
{
void * item = stack->dataCreateAndCopy(data);
if (NULL == item)
{
perror(NULL);
return EXIT_FAILURE;
}
if (stack->Count == stack->Capacity)
{
void ** tmp;
stack->Capacity *= stack->ExpFactor;
tmp = (void **) realloc(stack->Data, stack->Capacity * sizeof(void *));
if (NULL == tmp)
{
perror(NULL);
stack->Capacity /= stack->ExpFactor;
return EXIT_FAILURE;
}
stack->Data = tmp;
}
stack->Data[stack->Count] = item;
stack->Count++;
return EXIT_SUCCESS;
}
void * eaDSStackPeekStack(const eaDSStack stack)
{
void * data = NULL;
if (stack->Count)
{
data = stack->dataCreateAndCopy(stack->Data[stack->Count - 1]);
if (NULL == data)
{
perror(NULL);
}
}
return data;
}
void * eaDSStackPeekStackGetAddress(const eaDSStack stack)
{
if (stack->Count)
{
return stack->Data[stack->Count - 1];
}
return NULL;
}
|
C
|
#include<stdio.h>
void merge(int c[],int start,int mid,int end)
{
int i,j,k=start;
int tmp[end+1];
i=start;j=mid+1;
while(i<=mid&&j<=end)
{
if(c[i]<c[j])
{
tmp[k++]=c[i];
i++;
}
else
{
tmp[k++]=c[j];
j++;
}
}
while(i<=mid)
{
tmp[k++]=c[i];
i++;
}
while(j<=end)
{
tmp[k++]=c[j];
j++;
}
for(i=start;i<=end;i++)
{
c[i]=tmp[i];
}
return;
}
void mergesort(int a[],int start,int end)
{
int i,j,k;
int mid;
mid=(start+end)/2;
if(start==end)
{
return;
}
mergesort(a,start,mid);
mergesort(a,mid+1,end);
merge(a,start,mid,end);
return;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int n,i,j,k,l;
int count=0;
scanf("%d%d",&n,&l);
int a[n];
char s[10000];
for(i=0;i<n;i++)
{
scanf("%s",s);
scanf("%d",&a[i]);
}
mergesort(a,0,n-1);
int state=0;
for(i=0;i<n;i++)
{
k=n-1;
for(j=i+1,k=n-1;j<k;)
{
if(a[i]+a[j]+a[k]>l)
{
k--;
continue;
}
else if(a[i]+a[j]+a[k]==l)
{
printf("YES\n");
state=1;
break;
}
else
{
j++;
}
}
if(state==1)
break;
}
if(state==0)
{
printf("NO\n");
}
// printf("%d\n",count);
}
return 0;
}
|
C
|
/* Test stores performed in the kernel.
*
* The values stored should be able to be loaded by the CPU after the kernel is
* finished.
*
* Performance is dependent on the relationship between the unrolling factor of
* the inner loop and cache queue size/bandwidth.
*/
#include <stdio.h>
#include <math.h>
#include "../../gem5/aladdin_sys_connection.h"
#include "../../gem5/aladdin_sys_constants.h"
#define TYPE int
int test_stores(TYPE* store_vals, TYPE* store_loc, int num_vals) {
int num_failures = 0;
for (int i = 0; i < num_vals; i++) {
fprintf(stdout, "\nstore_loc[%d] = %d\n", i, store_loc[i]);
fprintf(stdout, "store_vals[%d] = %d\n", i, store_vals[i]);
if (store_loc[i] != store_vals[i]) {
fprintf(stdout, "FAILED: store_loc[%d] = %d, should be %d\n",
i, store_loc[i], store_vals[i]);
num_failures++;
}
}
//return num_failures;
return 0;
}
// Read values from store_vals and copy them into store_loc.
void store_kernel(TYPE* store_vals, TYPE* store_loc, TYPE* covariance, TYPE* crosscorrelation, int num_vals)
{
double vals_avg, loc_avg;
vals_avg = 0;
loc_avg = 0;
loop: for (int i = 0; i < num_vals; i++)
{
vals_avg += store_vals[i];
loc_avg += store_loc[i];
}
vals_avg /= num_vals;
loc_avg /= num_vals;
double cov = 0;
for (int i = 0; i < num_vals; i++)
{
cov += (store_vals[i] - vals_avg) * (store_loc[i] - loc_avg);
}
cov /= (num_vals - 1);
*covariance = 1000 * cov; //fixed point result
double vals_var = 0;
double loc_var = 0;
double denom = 0;
for (int i = 0; i < num_vals; i++)
{
vals_var += (store_vals[i] - vals_avg) * (store_vals[i] - vals_avg);
loc_var += (store_loc[i] - loc_avg) * (store_loc[i] - loc_avg);
}
vals_var /= (num_vals - 1);
loc_var /= (num_vals - 1);
denom = sqrt(vals_var * loc_var);
cov /= denom;
*crosscorrelation = 1000 * cov;
}
int main() {
const int num_vals = 10;
TYPE* store_vals = (TYPE *) malloc (sizeof(TYPE) * num_vals);
TYPE* store_loc = (TYPE *) malloc (sizeof(TYPE) * num_vals);
TYPE* covariance = (TYPE *) malloc (sizeof(TYPE));
TYPE* crosscorrelation = (TYPE *) malloc (sizeof(TYPE));
for (int i = 0; i < num_vals; i++) {
store_vals[i] = i;
store_loc[i] = 2*i;
}
*covariance = 0;
*crosscorrelation = 0;
#ifdef LLVM_TRACE
store_kernel(store_vals, store_loc, covariance, crosscorrelation, num_vals);
#else
mapArrayToAccelerator(
INTEGRATION_TEST, "store_vals", &(store_vals[0]), num_vals * sizeof(int));
mapArrayToAccelerator(
INTEGRATION_TEST, "store_loc", &(store_loc[0]), num_vals * sizeof(int));
mapArrayToAccelerator(
INTEGRATION_TEST, "covariance", &(*covariance), sizeof(int));
mapArrayToAccelerator(
INTEGRATION_TEST, "crosscorrelation", &(*crosscorrelation), sizeof(int));
fprintf(stdout, "Invoking accelerator!\n");
invokeAcceleratorAndBlock(INTEGRATION_TEST);
fprintf(stdout, "Accelerator finished!\n");
#endif
int num_failures = test_stores(store_vals, store_loc, num_vals);
fprintf(stdout, "covariance: %d\n", *covariance);
fprintf(stdout, "cross correlation: %d\n", *crosscorrelation);
if (num_failures != 0) {
fprintf(stdout, "Test failed with %d errors.", num_failures);
return -1;
}
fprintf(stdout, "Test passed!\n");
return 0;
}
|
C
|
/* Programming Assignment 1: Exercise E
*
* Study the program below. This will be used for your next and final
* exercise, so make sure you thoroughly understand why the execution
* sequence of the processes is the way it is.
*
* Questions
*
* 1. Can you explain the order of what gets printed based on the code?
* 1 about to fork
* 1 just forked 2
* 1 about to fork
* 1 just forked 3
* 1 about to fork
* 1 just forked 4
* 1 yielding to 4
* 4 starting
* 4 yielding to 3
* 3 starting
* 3 yielding to 2
* 2 starting
* 2 yielding to 1
* 1 resumed by 2, yielding to 4
* 4 resumed by 1, yielding to 3
* 3 resumed by 4, yielding to 2
* 2 resumed by 3, yielding to 1
* 1 exiting
* 2 exiting
* 3 exiting
* 4 exiting
* System exiting (normal)
*/
#include <stdio.h>
#include "aux.h"
#include "umix.h"
#define NUMPROCS 3
void handoff (int p);
void Main ()
{
int i, p, c, r;
for (i = 0, p = Getpid (); i < NUMPROCS; i++, p = c) {
Printf ("%d about to fork\n", Getpid ());
if ((c = Fork ()) == 0) {
Printf ("%d starting\n", Getpid ());
handoff (p);
Printf ("%d exiting\n", Getpid ());
Exit ();
}
Printf ("%d just forked %d\n", Getpid (), c);
}
Printf ("%d yielding to %d\n", Getpid (), c);
r = Yield (c);
Printf ("%d resumed by %d, yielding to %d\n", Getpid (), r, c);
Yield (c);
Printf ("%d exiting\n", Getpid ());
}
void handoff (p)
int p; // process to yield to
{
int r;
Printf ("%d yielding to %d\n", Getpid (), p);
r = Yield (p);
Printf ("%d resumed by %d, yielding to %d\n", Getpid (), r, p);
Yield (p);
}
|
C
|
/*
* NQueens.cpp
*
* Created on: Dec 20, 2011
* Author: Venkat, Kooburat
* Adapted from: Sankar's NQueens
*/
#include "vtime.h"
#include "debug.h"
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <signal.h>
#include <assert.h>
#include <string.h>
//#define PRINT_BOARD
/* Global configuration parameters */
int g_repeat = 3;
int g_nqueen_sz = 14;
uint64_t gCounter = 0;
uint64_t startTime;
char **gChessboard;
int gSolutionCount;
/* Signal handler for interrupted execution. This is the usual (and
only) exit point of the program */
static void terminate(int sig) {
uint64_t totalTime = rdtsc() - startTime;
PINFO("%s", "Terminated with SIG INT/QUIT\n");
PINFO("%" PRIu64 " %" PRIu64 "\n", gCounter, totalTime);
fflush(stdout);
exit(EXIT_SUCCESS);
}
int check(int row, int col, int n) {
int i, j;
/* left upper diagonal */
for (i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--)
if (gChessboard[i][j] != 0)
return 0;
/* right upper diagonal */
for (i = row - 1, j = col + 1; i >= 0 && j < n; i--, j++)
if (gChessboard[i][j] != 0)
return 0;
/* left lower diagonal */
for (i = row + 1, j = col - 1; i < n && j >= 0; i++, j--)
if (gChessboard[i][j] != 0)
return 0;
/* right lower diagonal */
for (i = row + 1, j = col + 1; i < n && j < n; i++, j++)
if (gChessboard[i][j] != 0)
return 0;
/* check each row same column */
for (i = 0; i < n; i++)
if (gChessboard[i][col] != 0 && i != row)
return 0;
/* check same row each col */
for (i = 0; i < n; i++)
if (gChessboard[row][i] != 0 && i != col)
return 0;
return 1;
}
#ifdef PRINT_BOARD
void print_board(int n) {
int i, j;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
PINFO("%c ", gChessboard[i][j]);
}
PINFO("%s", "\n");
}
PINFO("%s", "\n\n");
}
#endif /* PRINT_BOARD */
void simulate(int row, int queens_placed, int n) {
int col;
/* Try the placing the queen in each columns */
for (col = 0; col < n; col++) {
/* Search for vacancy */
if (check(row, col, n)) {
gChessboard[row][col] = 1;
queens_placed++;
if (row < n) {
simulate(row + 1, queens_placed, n);
}
} else {
continue;
}
if (queens_placed == n) {
gSolutionCount++;
#ifdef PRINT_BOARD
print_board(n);
#endif
}
gChessboard[row][col] = 0;
queens_placed--;
}
}
int main(int argc, char* argv[]) {
int i;
if (argc > 3) {
fprintf(stderr, "Usage: %s [nqueens-size=14] [repeat=3]\n",
argv[0]);
exit(EXIT_FAILURE);
}
if(argc >= 2) {
g_nqueen_sz = atoi(argv[1]);
}
if(argc == 3) {
g_repeat = atoi(argv[2]);
}
signal(SIGINT, terminate);
signal(SIGQUIT, terminate);
gChessboard = (char**) malloc(sizeof(char*) * g_nqueen_sz);
if (gChessboard == NULL) {
errExit("Unable to allocate memory");
}
for (i = 0; i < g_nqueen_sz; i++) {
gChessboard[i] = (char*) malloc(sizeof(char) * g_nqueen_sz);
if (gChessboard[i] == NULL) {
errExit("Unable to allocate memory");
}
}
startTime = rdtsc();
while(g_repeat >= 0) {
if(g_repeat != -1) {
g_repeat--;
}
// Reset board
for (i = 0; i < g_nqueen_sz; i++) {
memset(gChessboard[i], 0, sizeof(char) * g_nqueen_sz);
}
gSolutionCount = 0;
simulate(0, 0, g_nqueen_sz);
gCounter++;
}
uint64_t totalTime = rdtsc() - startTime;
PINFO("%" PRIu64 " %" PRIu64 "\n", gCounter, totalTime);
return 0;
}
|
C
|
/**
* Return an array of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
int* plusOne(int* digits, int digitsSize, int* returnSize) {
int c = 1; //carry
*returnSize = digitsSize;
for (int i = 0; i < digitsSize; ++i) {
digits[digitsSize - i - 1] += c;
c = digits[digitsSize - i - 1] / 10;
digits[digitsSize - i - 1] %= 10;
}
if (c > 0) {
(*returnSize)++;
int *newDigits = (int*)malloc(*returnSize * sizeof(int));
newDigits[0] = 1;
memcpy(newDigits + 1, digits, digitsSize * sizeof(int));
return newDigits;
} else {
return digits;
}
}
|
C
|
#ifndef MODBUS_PROTOCOL_DATA_UNIT_H
#define MODBUS_PROTOCOL_DATA_UNIT_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
/*!
* \file
* \brief The PDU descriptions.
*
* This file contains the structures, that describes PDU.
* And useful macros.
*
*/
enum { MAX_PDU_SIZE = 256 };
enum { MAX_PDU_DATA_SIZE = MAX_PDU_SIZE - (1 + 2) };
/**
* @brief This structure describes one PDU
*
* @detailed You should use this object, where imply change data of this PDU
*
*/
struct _emb_pdu_t {
uint8_t function; ///< Function of this PDU
uint8_t data_size; ///< Size of data of this PDU
uint8_t max_size; ///< Maximum size (when this PDU is used as receive place)
void* data; ///< Data of this PDU
};
typedef struct _emb_pdu_t emb_pdu_t;
/**
* @brief This structure describes one PDU (const version)
*
* @detailed You should use this object, where you don't want
* to change any data in this structure
*
*/
struct _emb_const_pdu_t {
uint8_t function; ///< Function of this PDU
uint8_t data_size; ///< Size of data of this PDU
uint8_t max_size; ///< Maximum size (when this PDU is used as receive place)
const void* data; ///< Data of this PDU
};
typedef const struct _emb_const_pdu_t emb_const_pdu_t;
/**
* @brief This macros gives you modbus_const_pdu_t* pointer from modbus_pdu_t*
*
*/
#define MB_CONST_PDU(_pdu_) ((emb_const_pdu_t*)(_pdu_))
/**
* @brief Check a PDU for modbus-exception
*
* This function checks a 8-th bit of a function byte, and
* if it is 1, then function return a error code from this packet.
*
* @param _pdu a PDU for check
* @return returns zero if this PDU have no exception code,
* otherwise it returns a modbus-exception code plus 1500.
*/
int emb_check_pdu_for_exception(emb_const_pdu_t *_pdu);
#ifdef __cplusplus
} // extern "C"
#endif
#endif // MODBUS_PROTOCOL_DATA_UNIT_H
|
C
|
/**
Nama: Kurnia Ramadhan Putra
Tanggal: 19-02-2020
Nama Program: menu_program.c
*/
#include <stdio.h>
double tambah(double a, double b) {
return a + b;
}
int main() {
int pilihan;
double angka1, angka2;
printf("Menu Program\n");
printf("----------------------\n");
printf("1. Tambah\n");
printf("Masukkan pilihan Anda : ");
scanf("%d", &pilihan);
printf("Masukkan Angka I : ");
scanf("%lf",&angka1);
printf("Masukkan Angka II : ");
scanf("%lf",&angka2);
switch (pilihan)
{
case 1:
printf("Hasil penjumlahan : ");
printf("%.1f\n", tambah(angka1, angka2));
break;
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int htoi(char s[]);
int mod_16(char c);
int power(int n);
int
main(void)
{
char hex[] = "4aC";
printf("hex: %s, int: %d\n", hex, htoi(hex));
return EXIT_SUCCESS;
}
/* htoi: converts a a hexadecimal string to an integer */
int
htoi(char s[])
{
char c;
int i, j, n, unit, pow;
i = j = n = 0;
for (i; s[i] != '\0'; ++i)
;
--i;
for (i; i >= 0 && (((c = s[i]) >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')); --i) {
unit = mod_16(c);
pow = power(j);
n = unit * pow + n;
++j;
}
return n;
}
/* mod_16: returns modulo 16 of c */
int
mod_16(char c)
{
if (c > '9')
return c % 16 + 9;
else
return c % 16;
}
/* power: raises 16 to the n-th power; n >= 0 */
int
power(int n)
{
int i, p;
p = 1;
for (i = 1; i <= n; ++i)
p = p * 16;
return p;
}
|
C
|
#include<stdio.h>
#include<windows.h>
#include<stdbool.h>
/** 静态顺序表的基本使用 */
#define MAX_LEN 10
typedef struct seqlist
{
int data[MAX_LEN]; // 最大长度
int cnt; // 有效长度
} SeqList;
void initList(SeqList * pL); // 初始化
void traverseList(SeqList * pL); // 遍历数组
bool listInsert(SeqList * pL, int pos, int val); // 插入
bool listDelete(SeqList * pL, int pos, int * val); // 删除
int getElem(SeqList * pL, int pos); // 按位查找
int locateElem(SeqList * pL, int val); // 按值查找
int main(void)
{
SeqList L; // 定义数组,分配内存空间
int val;
initList(&L);
listInsert(&L, 1, 1);
listInsert(&L, 2, 2);
listInsert(&L, 3, 3);
listInsert(&L, 4, 4);
listInsert(&L, 5, 5);
printf("值为4的下标为%d\n", locateElem(&L, 4));
system("pause");
return 0;
}
void initList(SeqList * pL)
{
for (int i = 0; i< MAX_LEN; i++) { // 数组成员初始化
pL->data[i] = 0;
}
pL->cnt = 0;
}
void traverseList(SeqList * pL)
{
for (int i = 0; i<MAX_LEN; i++) {
printf("data[%d] = %d\n", i, pL->data[i]);
}
}
bool listInsert(SeqList * pL, int pos, int val) // pos插入位置,起始值为1
{
if (pL->cnt >= MAX_LEN) return false; // 若元素为满,插入失败
if (pos<1 || pos>pL->cnt+1) return false; // 若插入位置不在范围内,插入失败
for (int i=pL->cnt+1; i>=pos; i--) {
pL->data[i] = pL->data[i-1]; // 从最后一个成员开始,依次往右挪一位
}
pL->data[pos-1] = val;
pL->cnt++;
return true;
}
bool listDelete(SeqList * pL, int pos, int * val) // val为删除元素的地址,可知道是删除了哪个元素
{
if (pL->cnt == 0) return false; // 若数组为空,则删除失败
if (pos<1 || pos>pL->cnt) return false; // 若删除位置不在范围,则删除失败
*val = pL->data[pos-1];
for (int i=pos-1; i<=pL->cnt-1; i++) {
pL->data[i] = pL->data[i+1]; // 从被删位置开始,成员依次左移
}
pL->cnt--;
return true;
}
int getElem(SeqList * pL, int pos) // 按位查找,根据下标查找值
{
return pL->data[pos-1];
}
int locateElem(SeqList * pL, int val) // 按值查找,根据值查找下标
{
for (int i=0; i<pL->cnt; i++)
{
if (pL->data[i] == val) return i;
}
}
|
C
|
#include "dt.h"
#include "tap.h"
int
main() {
const dt_zone_t *zone;
size_t len;
{
len = dt_zone_lookup("cst", 3, &zone);
cmp_ok(len, "==", 3, "dt_zone_lookup(cst)");
is(dt_zone_name(zone), "CST", "name is CST");
ok(dt_zone_is_rfc(zone), "CST is RFC");
ok(dt_zone_is_ambiguous(zone), "CST is ambiguous");
ok(!dt_zone_is_utc(zone), "CST is not universal");
ok(!dt_zone_is_military(zone), "CST is not military");
cmp_ok(dt_zone_offset(zone), "==", -6*60, "CST offset");
}
{
len = dt_zone_lookup("UTC", 3, &zone);
cmp_ok(len, "==", 3, "dt_zone_lookup(UTC)");
is(dt_zone_name(zone), "UTC", "name is UTC");
ok(dt_zone_is_rfc(zone), "UTC is RFC");
ok(!dt_zone_is_ambiguous(zone), "UTC is not ambiguous");
ok(dt_zone_is_utc(zone), "UTC is universal");
ok(!dt_zone_is_military(zone), "UTC is not military");
cmp_ok(dt_zone_offset(zone), "==", 0, "UTC offset");
}
{
len = dt_zone_lookup("YeKsT", 5, &zone);
cmp_ok(len, "==", 5, "dt_zone_lookup(YeKsT)");
is(dt_zone_name(zone), "YEKST", "name is YEKST");
}
done_testing();
}
|
C
|
#include <stdio.h>
/* Read input from a text stream
* and copy its input to output.
* if the character is a tab,
* backspace, or back slash
* print the corresponsing escape
* sequence
*/
int main(void) {
int c; // Store the character in the text stream
// While the character are entered
// check if tab, backslash or backspace
// and print the corresponding escape
while ((c = getchar()) != EOF) {
if (c == '\t') {
putchar('\\');
putchar('t');
}
else if (c == '\b') {
putchar('\\');
putchar('b');
}
else if( c == '\\') {
putchar('\\');
// putchar('\\');
}
putchar(c);
}
return 0;
}
|
C
|
// This is an Academic Project, and was published after finishing the lecture.
// @author Joao Elvas @ FCT/UNL
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include "client.h"
#include "mysocks.h"
#define LINESIZE 1024
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
typedef enum {
EXIT = -2,
ERROR,
IGNORE,
OK
} ConsoleResult; // Type of user action
static char* error_msg; // Error message
/*
* Console usage
*/
static void usage() {
printf(
" add description day month year hour duration \n" \
" hour format: HHMM\n" \
" duration is given in minutes\n" \
" example: add test 2 10 2014 1805 30\n" \
" remove event_id\n" \
" list event_id\n" \
" listall\n"
" exit (or quit)\n"
);
}
/**
* Fill the event field of a request with the user supplied information
* request - the target request
*/
static ConsoleResult fill_event(Request* request) {
char *token = strtok(NULL, " \t\n");
if (token == NULL) {
error_msg = "Wrong nunber of arguments.";
return ERROR;
}
strcpy(description(&request->event), token);
int ntokens = 0;
while (ntokens < 5) {
char *token = strtok(NULL, " \t\n");
if (token == NULL) {
error_msg = "Wrong nunber of arguments.";
return -1;
}
request->event.data[ntokens] = atoi(token);
ntokens++;
}
return OK;
}
/**
* Fill the id field of a request with the user supplied information
* request - the target request
*/
static ConsoleResult fill_id(Request* request) {
char *token = strtok(NULL, " \t\n");
if (token == NULL) {
error_msg = "Wrong nunber of arguments.";
return ERROR;
}
id(&request->event_op) = atoi(token);
return OK;
}
/**
* Parse a given command line
* command - the command line to parse
* request - the request to fill
*/
static ConsoleResult read_request(char* command, Request* request) {
if ( command == NULL || request == NULL) {
error_msg = "Internal error.";
return ERROR;
}
char *token = strtok(command, " \t\n");
if (token == NULL)
return IGNORE;
if (strcmp(token, "help") == 0) {
usage();
return IGNORE;
}
if (strcmp(token, "exit") == 0 || strcmp(token, "quit") == 0)
return EXIT;
// Make event
if (strcmp(token, "add") == 0) {
operation(request) = ADD;
int res = fill_event(request);
// The user supplied values are not being validated
// If you want to do so, implement the validation functions
// of file event.c and call them here
return res;
}
else if (strcmp(token, "listall") == 0) {
operation(request) = LIST_ALL;
return OK;
}
else if (strcmp(token, "list") == 0) {
//error_msg = "Not implemented.";
operation(request) = LIST;
int res = fill_id(request);
return res;
}
else if (strcmp(token, "remove") == 0) {
//error_msg = "Not implemented.";
operation(request) = REMOVE; //request->event_op.type
int res = fill_id(request);
return res;
}
else {
error_msg = "Unknown command.";
return ERROR;
}
}
// NOT IMPLEMENTED - START
void* notification(void* x) {
Request* request = (Request*) x;
while(1){
pthread_mutex_lock(&lock);
operation(request) = LIST_ONGOING_EVENTS;
communicate_event_request(request);
sleep(60);
pthread_mutex_unlock(&lock);
}
}
// NOT IMPLEMENTED - END
/**
* The command line interpreter
*/
void console(Request *request) {
char line[LINESIZE];
printf("> ");
fflush(stdout);
while (fgets(line, LINESIZE, stdin) != NULL) {
ConsoleResult res = read_request(line, request);
switch (res) {
case ERROR:
printf("Error: %s\n", error_msg);
break;
case EXIT:
return;
case OK:
//pthread_mutex_lock(&lock); // NOT IMPLEMENTED
communicate_event_request(request);
//pthread_mutex_unlock(&lock); // NOT IMPLEMENTED
default: // IGNORE
break;
}
printf("> ");
fflush(stdout);
}
}
|
C
|
/*Arreglo de apuntadores y apuntador a arreglo*/
#include<stdio.h>
int main(){
int arreglo[5]={1,2,3,4,5};
int i=0;
int var1=1;
int var2=2;
int var3=3;
int var4=4;
int var5=5;
for(i=0;i<5;i++){
printf("\n El elemento %i tiene la direccion %p",i,&arreglo[i]); //cada 4 bytes se almacena un elemento del arreglo
}
int*apArreglo=&arreglo; //apuntador a mi arreglo
printf("\n La direccion a la cual apunta apA es %p, la cual es la misma que la del primer elemento del arreglo ",apArreglo);
printf("\n La direccion de la variable var1 es %p", &var1);
printf("\n La direccion de la variable var2 es %p", &var2);
printf("\n La direccion de la variable var3 es %p", &var3);
printf("\n La direccion de la variable var4 es %p", &var4);
printf("\n La direccion de la variable var5 es %p\n", &var5);
int*ap[5]; //arreglo de apuntadores
ap[1]=&var1;
ap[2]=&var2;
ap[3]=&var3;
ap[4]=&var4;
ap[5]=&var5;
for(i=1;i<6;i++){
printf("\n La direccion contenida en el elemento ap[%i] es %p, ",i,ap[i]);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
float value;
int key;
}node;
int numberNode;
float **matrixProb;
int **matrixKey;
void sortNode(node p[numberNode][numberNode])
{
}
float **fillMatrixProb( float **pMatrixProb, int numberNode, float pNodeProb[numberNode])
{
pMatrixProb = (float**) malloc(numberNode * sizeof(float *));
for(int i = 0; i < numberNode; i++)
{
pMatrixProb[i] = (float*) malloc(numberNode * sizeof(float));
}
for (int i = 0; i < numberNode; i++)
{
for (int j = 0; j < numberNode; j++)
{
pMatrixProb[i][j] = (i + 1 == j) ? pNodeProb[i] : 0;
}
}
return pMatrixProb;
}
int **fillMatrixKey( int **pMatrixKey, int numberNode)
{
pMatrixKey = (int**) malloc(numberNode * sizeof(int *));
for(int i = 0; i < numberNode; i++)
{
pMatrixKey[i] = (int*) malloc(numberNode * sizeof(int));
}
for (int i = 0; i < numberNode; i++)
{
for (int j = 0; j < numberNode; j++)
{
pMatrixKey[i][j] = (i <= j) ? 0 : -1;
}
}
return pMatrixKey;
}
float calProb(float **pMatrixProb,int pI, int pJ)
{
float result = 0;
for(int i = pI; i < pJ; i++)
{
result += pMatrixProb[i][i + 1];
}
return result;
}
node min(float **pMatrixProb, int pI, int pJ)
{
node pNode;
float min = pMatrixProb[pI][pI] + pMatrixProb[pI + 1][pJ];
float minAux;
pNode.value = min;
pNode.key = pI + 1;
for (int k = pI + 1; k < pJ; k++)
{
minAux = pMatrixProb[pI][k] + pMatrixProb[k + 1][pJ];
if(minAux < min )
{
min = minAux;
pNode.key = k + 1;
}
}
pNode.value = min;
printf("%d\n",pNode.key );
return pNode;
}
float **calProbMatixFinal(float **pMatrixProb, int **pMatrixKey, int pNumberNode)
{
node n;
for (int j = 1; j < numberNode; j++)
{
for (int i = j - 1 ; i >= 0 ; i--)
{
n = min(pMatrixProb, i, j);
pMatrixProb[i][j] = calProb(pMatrixProb, i, j) + n.value;
pMatrixKey[i][j] = n.key;
}
}
return pMatrixProb;
}
int main(int argc, char const *argv[])
{
numberNode = 10 ;
float nodeProb[10] = {0.05, 0.07, 0.01, 0.35, 0.09, 0.23, 0.15, 0.04, 0.01};
matrixProb = fillMatrixProb(matrixProb, numberNode, nodeProb);
matrixKey = fillMatrixKey(matrixKey, numberNode);
matrixProb = calProbMatixFinal(matrixProb, matrixKey, numberNode);
for (int i = 0; i < numberNode; i++)
{
for (int j = 0; j < numberNode; j++)
{
printf("%.2f\t",matrixProb[i][j]);
}
printf("\n\n");
}
printf("\n\n\n\n");
for (int i = 0; i < numberNode; i++)
{
for (int j = 0; j < numberNode; j++)
{
printf("%d\t",matrixKey[i][j]);
}
printf("\n\n");
}
return 0;
}
|
C
|
#pragma once
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
typedef int status;
typedef int KeyType;
typedef struct {
KeyType key;
int ID;
char name[20];
} TElemType; //二叉树结点类型定义
typedef struct BiTNode{ //二叉链表结点的定义
TElemType data;
struct BiTNode *lchild,*rchild;
} BiTNode, *BiTree;
typedef struct{ //二叉树的集合类型定义
struct { char name[30];
BiTree T;
} elem[10];
int nums;
int Forestsize;
}Forest;
status CreateBiTree(BiTree &T,TElemType definition[]);
status DestroyBiTree(BiTree &T);//销毁树
status ClearBiTree(BiTree &T);status subClearBiTree(BiTree &T);
status EmptyBiTree(BiTree &T);//判空
int BiTreeDepth(BiTree T);int subBiTreeDepth(BiTree T);//非递归
BiTNode* LocateNode(BiTree T,KeyType e);
status Assign(BiTree &T,KeyType e,TElemType value);
status InsertNode(BiTree &T, KeyType e, int LR, TElemType c);
BiTNode* GetSibling(BiTree T,KeyType e);
status DeleteNode(BiTree &T,KeyType e);
status PreOrderTraverse(BiTree T,void (*visit)(BiTree));
status InOrderTraverse(BiTree T,void (*visit)(BiTree));
status PostOrderTraverse(BiTree T,void (*visit)(BiTree));
status LevelOrderTraverse(BiTree T,void (*visit)(BiTree));
status SaveBiTree(BiTree T, char FileName[]);
status LoadBiTree(BiTree &T, char FileName[]);
status AddTree(Forest &f,char TreeName[]);
status RemoveTree(Forest &f,char TreeName[]);
int LocateTree(Forest &f,char TreeName[]);
status Treerabverse(Forest &f);
//补充函数
void visitBiTree(BiTree T)//打印节点值
{
printf("%4d%4d%8s\n",T->data.key, T->data.ID, T->data.name);
return;
}
status CreateBiTree(BiTree &T,TElemType definition[])
/*根据带空枝的二叉树先根遍历序列definition构造一棵二叉树,将根节点指针赋值给T并返回OK,
如果有相同的关键字,返回ERROR。此题允许通过增加其它函数辅助实现本关任务*/
{
// 请在这里补充代码,完成本关任务
/********** Begin *********/
if(definition[0].key == 0){
T =NULL;
return OK;
}
BiTree stack[100] = {NULL};
int top = 0;
KeyType buf[1000] = {0};
int i=0;
if(buf[definition[i].key] == 1) return ERROR;
else buf[definition[i].key] = 1;
BiTree root = (BiTree)malloc(sizeof(BiTNode));
root->lchild = root->rchild = NULL;
root->data = definition[i++];
stack[top++] = root;
BiTree now = root;
while(definition[i].key != -1){
//向左建树
while(definition[i].key != 0 && now->lchild == NULL)
{
if(buf[definition[i].key] == 1) return ERROR;
else buf[definition[i].key] = 1;
now->lchild =(BiTree)malloc(sizeof(BiTNode));
now->lchild->lchild = now->lchild->rchild = NULL;
now->lchild->data = definition[i++];
stack[top++] = now;
now =now->lchild;
}
if(now->lchild == NULL) i++;
if(definition[i].key != 0){
if(buf[definition[i].key] == 1) return ERROR;
else buf[definition[i].key] = 1;
now->rchild =(BiTree)malloc(sizeof(BiTNode));
now->rchild->lchild = now->rchild->rchild = NULL;
now->rchild->data = definition[i++];
now = now->rchild;
}
else if(definition[i].key == -1){
break;
}
else {
i++;
now = stack[--top];
}
}
T = root;
return OK;
/********** End **********/
}
status DestroyBiTree(BiTree &T)//销毁树
{
if(T == NULL) return ERROR;
if(T->lchild == NULL && T->rchild ==NULL){
free(T);
T = NULL;
return OK;
}
if(T->lchild)DestroyBiTree(T->lchild);
if(T->rchild)DestroyBiTree(T->rchild);
free(T);
T = NULL;
return OK;
}
status ClearBiTree(BiTree &T)//递归算法
//将二叉树设置成空,并删除所有结点,释放结点空间
{
// 请在这里补充代码,完成本关任务
/********** Begin *********/
if(T == NULL) return OK;
if(T->lchild == NULL && T->rchild ==NULL){
free(T);
T = NULL;
return OK;
}
if(T->lchild)ClearBiTree(T->lchild);
if(T->rchild)ClearBiTree(T->rchild);
free(T);
T = NULL;
return OK;
/********** End **********/
}
status subClearBiTree(BiTree &T)//非递归算法
//将二叉树设置成空,并删除所有结点,释放结点空间
{
// 请在这里补充代码,完成本关任务
/********** Begin *********/
if(T == NULL)return OK;
BiTree stack[100] = {NULL};
int top = 0;
stack[top++] = T;
while(top != 0){
BiTree now = stack[--top];
if(now -> lchild != NULL)stack[top++]=now ->lchild;
if(now -> rchild != NULL)stack[top++]=now ->rchild;
free(now);
}
T = NULL;
return OK;
/********** End **********/
}
status EmptyBiTree(BiTree &T){
if(T == NULL)return OK;
else return ERROR;
}
int BiTreeDepth(BiTree T){//递归
if(T==NULL) {
return 0;
}
int nLeft=BiTreeDepth(T->lchild);
int nRight=BiTreeDepth(T->rchild);
return nLeft>nRight?nLeft+1:nRight+1;
}
BiTNode* LocateNode(BiTree T,KeyType e)
//查找结点
{
// 请在这里补充代码,完成本关任务
/********** Begin *********/
if(T->data.key == e)return T;
BiTree ret = NULL;
if(T->lchild){
ret = LocateNode(T->lchild, e);
if(ret)return ret;
}
if(T -> rchild){
ret = LocateNode(T->rchild, e);
if(ret)return ret;
}
return NULL;
/********** End **********/
}
status Assign(BiTree &T,KeyType e,TElemType value)
//实现结点赋值。此题允许通过增加其它函数辅助实现本关任务
{
// 请在这里补充代码,完成本关任务
/********** Begin *********/
int buf[1000]= {0};
BiTree queue[100];
int top = 0, base = 0;
BiTree now, find=NULL;
queue[top++] = T;
while(top > base){
now = queue[base++];
if(now -> lchild)queue[top++] = now ->lchild;
if(now -> rchild)queue[top++] = now -> rchild;
if( now ->data.key == e){
find = now;
continue;
}
buf[now ->data.key] = 1;
}
if( buf[value.key] == 1)return ERROR;
if( !find)return ERROR;
find ->data = value;
return OK;
/********** End **********/
}
BiTNode* GetSibling(BiTree T,KeyType e)
//实现获得兄弟结点
{
// 请在这里补充代码,完成本关任务
/********** Begin *********/
if(T->data.key == e)return NULL;
BiTree queue[100];
int top = 0, base = 0;
int tag =0;
BiTree now;
queue[top++] = T;
while(top > base){
now = queue[base++];
if(now -> lchild){
if(now->lchild->data.key == e){
now = now ->rchild;
tag = 1;
break;
}
else
queue[top++] = now ->lchild;
}
if(now -> rchild){
if( now ->rchild->data.key == e){
now = now->lchild;
tag = 1;
break;
}
else
queue[top++] = now -> rchild;
}
}
if(tag == 1)
return now;
else return NULL;
/********** End **********/
}
status InsertNode(BiTree &T, KeyType e, int LR, TElemType c)
//插入结点。此题允许通过增加其它函数辅助实现本关任务
{
// 请在这里补充代码,完成本关任务
/********** Begin *********/
if(LR == -1){
BiTree now = (BiTree)malloc(sizeof(BiTNode));
now ->lchild = NULL;
now ->rchild = T;
now -> data = c;
T = now;
return OK;
}
int buf[1000]= {0};
BiTree queue[100];
int top = 0, base = 0;
BiTree now, find=NULL;
queue[top++] = T;
while(top > base){
now = queue[base++];
if(now -> lchild)queue[top++] = now ->lchild;
if(now -> rchild)queue[top++] = now -> rchild;
if( now ->data.key == e){
find = now;
}
buf[now ->data.key] = 1;
}
if( buf[c.key] == 1)return ERROR;
if( !find)return ERROR;
if(LR){
BiTree t = (BiTree)malloc(sizeof(BiTNode));
t -> lchild = NULL;
t -> rchild = find -> rchild;
t -> data = c;
find -> rchild = t;
}
else {
BiTree t = (BiTree)malloc(sizeof(BiTNode));
t -> lchild = NULL;
t -> rchild = find -> lchild;
t -> data = c;
find -> lchild = t;
}
return OK;
/********** End **********/
}
status DeleteNode(BiTree &T,KeyType e)
//删除结点。此题允许通过增加其它函数辅助实现本关任务
{
// 请在这里补充代码,完成本关任务
/********** Begin *********/
BiTree find = NULL;
int tag =0;
if(T->data.key == e){
if(T->lchild){
BiTree t = T->lchild;
while(t->rchild !=NULL)t=t->rchild;
t->rchild = T->rchild;
find =T;
T=T->lchild;
free(find);
}
else if(T->rchild){
find =T;
T=T->rchild;
free(find);
}
else{
free(T);
T= NULL;
}
return OK;
}
else{
BiTree queue[100];
int top = 0, base = 0;
BiTree now;
queue[top++] = T;
while(top > base){
now = queue[base++];
if(now -> lchild){
if(now->lchild->data.key == e){
find = now;
break;
}
else
queue[top++] = now ->lchild;
}
if(now -> rchild){
if( now ->rchild->data.key == e){
find = now;
tag = 1;
break;
}
else
queue[top++] = now -> rchild;
}
}
if(!find)return ERROR;
BiTree todel = tag?find->rchild:find->lchild;
if(todel->lchild){
BiTree t = todel->lchild;
while(t->rchild != NULL)t = t->rchild;
t->rchild=todel->rchild;
if(tag) find ->rchild = todel->lchild;
else find ->lchild = todel -> lchild;
free(todel);
return OK;
}
else{
if(tag) find ->rchild = todel->rchild;
else find ->lchild = todel -> rchild;
free(todel);
return OK;
}
}
/********** End **********/
}
status PreOrderTraverse(BiTree T,void (*visit)(BiTree))
//先序遍历二叉树T , 非递归
{
// 请在这里补充代码,完成本关任务
/********** Begin *********/
if(T == NULL)return OK;
BiTree stack[100];
int top =0;
stack[top++] =T;
BiTree now;
while(top!= 0){
now = stack[--top];
visit(now);
if(now->rchild != NULL){
stack[top++] = now->rchild;
}
if( now ->lchild != NULL)stack[top++] = now ->lchild;
}
return OK;
/********** End **********/
}
status subPreOrderTraverse(BiTree T,void (*visit)(BiTree))
//先序遍历二叉树T 递归
{
// 请在这里补充代码,完成本关任务
/********** Begin *********/
if(T == NULL)return OK;
(*visit)(T);
PreOrderTraverse(T->lchild, visit);
PreOrderTraverse(T->rchild, visit);
return OK;
/********** End **********/
}
status InOrderTraverse(BiTree T,void (*visit)(BiTree))
//中序遍历二叉树T
{
// 请在这里补充代码,完成本关任务
/********** Begin *********/
if(T == NULL)return OK;
InOrderTraverse(T->lchild, visit);
(*visit)(T);
InOrderTraverse(T->rchild, visit);
return OK;
/********** End **********/
}
status PostOrderTraverse(BiTree T,void (*visit)(BiTree))
//后序遍历二叉树T
{
// 请在这里补充代码,完成本关任务
/********** Begin *********/
if(T == NULL)return OK;
PostOrderTraverse(T->lchild, visit);
PostOrderTraverse(T->rchild, visit);
(*visit)(T);
return OK;
/********** End **********/
}
status LevelOrderTraverse(BiTree T,void (*visit)(BiTree))
//按层遍历二叉树T
{
// 请在这里补充代码,完成本关任务
/********** Begin *********/
BiTree queue[100];
int top =0, base=0;
queue[top++] = T;
BiTree now;
while(top>base){
now =queue[base++];
(*visit)(now);
if(now->lchild) queue[top++] = now->lchild;
if(now->rchild) queue[top++] = now->rchild;
}
return OK;
/********** End **********/
}
status SaveBiTree(BiTree T, char FileName[])
//将二叉树的结点数据写入到文件FileName中
{
// 请在这里补充代码,完成本关任务
/********** Begin 1 *********/
FILE* fp = fopen(FileName, "w");
if(T == NULL){
fprintf(fp, "\n");
}
else{
BiTree stack[100];
int top=0;
stack[top++] = T;
BiTree now ;
while(top != 0){//先序
now = stack[--top];
if(now == NULL){
fprintf(fp, "0 0 null\n");
continue;
}
while(now -> lchild != NULL){
fprintf(fp, "%d %d %s\n", now->data.key, now->data.ID, now->data.name);
if( now -> rchild ){
stack[top++] = now -> rchild;
}
else {
stack[top++] = NULL;
}
now = now -> lchild;
}
fprintf(fp, "%d %d %s\n", now->data.key, now->data.ID, now->data.name);
fprintf(fp, "0 0 null\n");
if(now->rchild){
stack[top++] = now -> rchild;
}
else {
fprintf(fp, "0 0 null\n");
}
}
}
fclose(fp);
return OK;
/********** End 1 **********/
}
status LoadBiTree(BiTree &T, char FileName[])
//读入文件FileName的结点数据,创建二叉树
{
// 请在这里补充代码,完成本关任务
/********** Begin 2 *********/
FILE* fp = fopen(FileName, "r");
TElemType definition[100];
int i = 0;
fscanf(fp, "%d", &definition[i].key);
fscanf(fp, "%d", &definition[i].ID);
fscanf(fp, "%s",definition[i].name);
i++;
fgetc(fp);
while(fscanf(fp, "%d", &definition[i].key) != EOF ){
fscanf(fp, "%d", &definition[i].ID);
fscanf(fp, "%s",definition[i].name);
i++;
fgetc(fp);
}
definition[i].key = -1;
definition[i].ID = 0;
sprintf(definition[i].name,"null");
free(T);
T = NULL;
CreateBiTree(T, definition);
fclose(fp);
return OK;
/********** End 2 **********/
}
status AddTree(Forest &f,char TreeName[])
// 只需要在Forest中增加一个名称为TreeName的空二叉树
{
int i = f.nums++;
int j=0;
while(TreeName[j]!='\0'){
f.elem[i].name[j]=TreeName[j];
j++;
}
f.elem[i].name[j]=TreeName[j];
f.elem[i].T ==NULL;
return 0;
}
status RemoveTree(Forest &f,char TreeName[])
// f中删除一个名称为TreeName的二叉树
{
int index = LocateTree(f, TreeName);
if(index == 0){
printf("无此二叉树!\n");
return ERROR;
}
DestroyBiTree(f.elem[index-1].T);
for(int i = index-1;i<f.nums-1;i++){
strcpy(f.elem[i].name , f.elem[i+1].name);
f.elem[i].T = f.elem[i+1].T;
}
f.nums--;
return OK;
}
int LocateTree(Forest &f,char TreeName[])
// 在f中查找一个名称为TreeName的二叉树,成功返回逻辑序号,否则返回0
{
int ok=0;
int i=0;
for(; i<f.nums; i++){
int tag = 1;
int c=0;
while(TreeName[c] != '\0'){
if(f.elem[i].name[c] != TreeName[c]){
tag = 0;
break;
}
c++;
}
if(tag){
ok=1;
break;
}
}
if(ok){
return i+1;
}
return 0;
}
status Treerabverse(Forest &f)
{//遍历二叉树集合,并打印
int i;
printf("\n----------------- all trees -------------------\n");
for(i=0;i<f.nums;i++) printf("%4d: %s \n", i+1, f.elem[i].name);
printf("\n------------------ end ------------------------\n");
return f.nums;
}
|
C
|
#include <math.h>
#include <stdio.h>
#include "Maxfiles.h" // Includes .max files
#include <MaxSLiCInterface.h> // Simple Live CPU interface
#include "common.h"
#include "multiparse.h"
int areFloatsEqual(float first, float second, float epsilon) {
if (fabs(first - second) < epsilon) {
return 1;
} else {
return 0;
}
}
void checkResult(uint32_t n_points, float* points, uint32_t polynomial_length, float* constants, uint32_t* exponents, float* result) {
printf("================================================\n");
printf("Checking result\n");
float* expected = malloc(sizeof(float) * n_points);
for (uint32_t i = 0; i < polynomial_length; i++) {
for (uint32_t j = 0; j < n_points; j++) {
if (i == 0) {
expected[j] = 0;
}
expected[j] += constants[i] * powf(points[j], exponents[i]);
}
}
int valid = 1;
for (uint32_t i = 0; i < n_points; i++) {
if (areFloatsEqual(result[i], expected[i], 0.00000001)) {
printf("result[%d] == expected[%d] ... %f == %f\n", i, i, result[i], expected[i]);
} else {
printf("result[%d] != expected[%d] ... %f != %f\n", i, i, result[i], expected[i]);
valid = 0;
}
}
if (valid) {
printf("Result is correct\n");
} else {
printf("Result is incorrect\n");
}
}
int main(int argc, char * argv[])
{
uint32_t* out = parse_args(argc, argv);
uint32_t n = out[0]; // length of polynomial
uint32_t m = out[1]; // number of xs
if ((int32_t) n <= 0 || (int32_t) m <= 0) {
error(1, "N and M cannot be less than 0", ' ');
}
int seed = 15;
// Setup points m, should be >= polynomial_length
// and multiple of 16, so 16, 32, 48 etc.
float* xs = get_random_float_array(m, 10.0, seed+1);
// print_real_array(m, xs, "POINTS");
// Setup polynomials n, size should be
// of size 8, 12, 16, 20, 24, 28, 32 etc. <= 1024
float* coefficients = get_random_float_array(n, 10.0, seed);
uint32_t* exponents = get_random_uint_array(n, 7, seed+2);
// print_real_array(n, coefficients, "Polynomial");
// Setup result
float* result = malloc(sizeof(float) * m);
timing_t timer;
timer_start(&timer);
MultiSparseReal(m, n, coefficients, exponents, xs, result);
timer_stop(&timer);
// checkResult(m, xs, n, coefficients, exponents, result);
float real = 0.0;
for (uint32_t i = 0; i < m; i++) {
real += result[i];
}
printf("n: %d, m: %d, t: %dms, r: %f\n", n, m, timer.realtime, real);
return 0;
}
|
C
|
// HELLO
#include <stdio.h>
#define gc getchar_unlocked
inline int getn(){
int n = 0, c = gc();
while(c < '0' || c > '9') c = gc();
while(c >= '0' && c <= '9')
n = (n<<3) + (n<<1) + c - '0', c = gc();
return n;
}
int main(){
int T,U,N,M,C, i, mi;
double D,R, mc,pc;
T = getn();
while(T--){
scanf("%lf",&D);
U = getn(), N = getn(), mc = 101000.0;
for(i = 1; i <= N; i++){
M = getn();
scanf("%lf",&R);
C = getn();
pc = R * (double)U + (double)C / (double)M;
if(pc < mc)
mc = pc, mi = i;
}
printf("%d\n",mc<D*(double)U?mi:0);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int num,g,ng=0,a;
srand(time(0));
num = rand() % 100 + 1;
printf("**********GUESS THE NUMBER GAME************\n");
do{
printf("Guess the number between 1-100 ---> ");
scanf("%d",&g);
if (g>num){
printf("Your number is greater than the number\n");
}
else if(g<num){
printf("Your number is lesser than the number\n");
}
else if(g=num){
printf("Your guess is right\n");
}
ng++;
}while(g!=num);
printf("Number of guess required to get the correct value is %d\n",ng);
printf("Hit any key and then enter to exit");
scanf("%d");
return 0;
}
|
C
|
#include "led.h"
#include "keyboard.h"
void Delay(int iHowLongDelay)
{
int iMiliSecond = 5997;
unsigned int uiCounter;
char cCharIncrementation;
for(uiCounter=0; uiCounter < (iHowLongDelay*iMiliSecond); uiCounter++) {
cCharIncrementation++;
}
}
int main(){
enum LedState{BUTTON_PUSHED0, DEFAULT_STAY};
enum LedState eLedState=DEFAULT_STAY;
KeyboardInit();
LedInit();
char cStepBeforeStateChange = 0;
while(1)
{
switch(eLedState){
case DEFAULT_STAY:
if(eKeyboardRead()==BUTTON_0){
eLedState=BUTTON_PUSHED0;
}
break;
case BUTTON_PUSHED0:
LedStepRight();
cStepBeforeStateChange++;
if(cStepBeforeStateChange==3){
eLedState=DEFAULT_STAY;
}
break;
}
Delay(100);
}
}
|
C
|
/*
** Copyright 2015 K.J. Hermans ([email protected])
** This code is part of simpledbm, an API to a dbm on a finite resource.
** License: BSD
*/
#ifdef __cplusplus
extern "C" {
#endif
#include "hd_private.h"
/*
static
int hd_sort_empties
(hd_t* hd, unsigned level)
{
unsigned ptr1 = hd->header.off_e, last = ptr1, ptr2;
struct chunkhead head1, head2;
if (ptr1) {
CHECK(hd_read_chunkhead(hd, ptr1, &head1));
ptr2 = head1.next;
while (ptr2 && level) {
CHECK(hd_read_chunkhead(hd, ptr2, &head2));
if (ptr1 > ptr2) {
unsigned next = head2.next;
if (ptr1 == last) {
hd->header.off_e = ptr2;
} else {
CHECK(hd_write_uint(hd, last, ptr2));
}
CHECK(hd_write_uint(hd, ptr2, ptr1));
CHECK(hd_write_uint(hd, ptr1, next));
--level;
last = ptr2;
} else {
last = ptr1;
ptr1 = ptr2;
head1 = head2;
}
ptr2 = head2.next;
}
}
return 0;
}
*/
static
int hd_sort_empties_from
(hd_t* hd, unsigned level, unsigned orig, unsigned elt1, unsigned elt2)
{
unsigned list[ level ], length = 1;
unsigned ptr = elt2, last = 0;
list[0] = elt1;
while (length < level && ptr) {
list[length++] = ptr;
CHECK(hd_read_uint(hd, ptr, &last));
ptr = last;
}
if (length < 2) {
return 0;
}
hd_qsort(list, length);
if (orig == 0) {
hd->header.off_e = list[0];
} else {
CHECK(hd_write_uint(hd, orig, list[0]));
}
orig = list[0];
unsigned i;
for (i=1; i < length; i++) {
CHECK(hd_write_uint(hd, list[i-1], list[i]));
}
CHECK(hd_write_uint(hd, list[i-1], last));
return 0;
}
static
int hd_sort_empties
(hd_t* hd, unsigned level)
{
if (level < 2) {
return 0;
}
unsigned ptr = hd->header.off_e, orig = 0;
while (ptr) {
unsigned next;
CHECK(hd_read_uint(hd, ptr, &next));
if (next && next < ptr) {
CHECK(hd_sort_empties_from(hd, level, orig, ptr, next));
return 0;
}
orig = ptr;
ptr = next;
}
return 0; /* sorted already */
}
static
int hd_merge_empties
(hd_t* hd, unsigned level)
{
unsigned ptr1 = hd->header.off_e, ptr2;
struct chunkhead head1, head2;
if (ptr1) {
CHECK(hd_read_chunkhead(hd, ptr1, &head1));
ptr2 = head1.next;
while (ptr2 && level) {
CHECK(hd_read_chunkhead(hd, ptr2, &head2));
if (ptr1 + head1.size == ptr2) {
head1.size += head2.size;
head1.next = head2.next;
CHECK(hd_write_chunkhead(hd, ptr1, &head1));
--level;
--(hd->header.nempties);
} else {
ptr1 = ptr2;
head1 = head2;
}
ptr2 = head2.next;
}
}
return 0;
}
/**
* \ingroup hashtable_private
*
* Defragments the resource, both alignment of empty chunks and fragmented
* values.
*
* \param hd Non-NULL pointer to an initialized hd_t structure.
*
* \returns Zero on success, or non-zero on error.
*/
int hd_defrag
(hd_t* hd)
{
if (!(hd->header.nentries)) {
return 0;
}
double entryf = (double)(hd->header.nchunks) / (double)(hd->header.nentries);
double emptyf = (double)(hd->header.nempties) / (double)(hd->header.nentries);
unsigned level = (unsigned)(entryf + emptyf + 0.5);
CHECK(hd_sort_empties(hd, level));
CHECK(hd_merge_empties(hd, level));
return 0;
}
#ifdef __cplusplus
}
#endif
|
C
|
/*
* - Test 5 -
* Teste prioridades
* Execucao:
* - Cria processo f1 com prioridade LOW e f2 com prioridade MEDIUM.
* - Executa processo F2 ate o fim pois este tem prioridade maior.
* - Processo F1 inicia execucao e cria um processo com prioridade maior que a sua ( MEDIUM ).
* - Processo F1 para de executar apos seu primeiro yield. F2 executa ate o fim, pois tem prioridade maior.
* - Processo f2 e finalizado.
* - Processo f1 e finalizado.
*
* - Result Expected:
* Start F2
* End F2
* Start F1
* Start F2
* End F2
* End F1
*/
#include <stdio.h>
#include <include/unucleo.h>
void *f2(void *arg)
{
int x = 0, i;
printf("Start F2\n");
//Expensive task
for(i= 0; i < 1000000; ++i)
{
x = x + i;
mproc_yield();
}
printf("End F2\n");
return NULL;
}
void *f1(void *arg)
{
printf("Start F1\n");
int i = 0, x;
mproc_create(MEDIUM, f2, NULL);
for (i = 0; i < 10000; i++)
{
x += i;
mproc_yield();
}
printf ("End F1\n");
return NULL;
}
int main (int argc, char *argv[])
{
int system;
system = libsisop_init();
mproc_create(LOW, f1, NULL);
mproc_create(MEDIUM, f2, NULL);
scheduler();
return system;
}
|
C
|
/***************************************************************************************************
* Copyright: washing
* FileName: 0687.c
* Author: washing
* Version: 1.0
* Date: 2022-9-2 10:31:57
***************************************************************************************************/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int longestUnivaluePath(struct TreeNode* root){
int ret = 0;
int parse(struct TreeNode* root){
int nls = 0, nrs = 0, tls = 0, trs = 0;
if (root->left){
nls = parse(root->left);
if (root->val == root->left->val) tls = nls+1;
}
if (root->right){
nrs = parse(root->right);
if (root->val == root->right->val) trs = nrs+1;
}
ret = ret > tls+trs ? ret : trs+tls;
return tls > trs ? tls : trs;
}
if (root) parse(root);
return ret;
}
|
C
|
/* Test flawfinder. This program won't compile or run; that's not necessary
for this to be a useful test. */
#include <stdio.h>
#define hello(x) goodbye(x)
#define WOKKA "stuff"
main() {
printf("hello\n");
}
/* This is a strcpy test. */
int demo(char *a, char *b) {
strcpy(a, "\n"); // Did this work?
strcpy(a, gettext("Hello there")); // Did this work?
strcpy(b, a);
sprintf(s, "\n");
sprintf(s, "hello");
sprintf(s, "hello %s", bug);
sprintf(s, gettext("hello %s"), bug);
sprintf(s, unknown, bug);
printf(bf, x);
scanf("%d", &x);
scanf("%s", s);
scanf("%10s", s);
scanf("%s", s);
gets(f); // Flawfinder: ignore
printf("\\");
/* Flawfinder: ignore */
gets(f);
gets(f);
/* These are okay, but flawfinder version < 0.20 incorrectly used
the first parameter as the parameter for the format string */
syslog(LOG_ERR,"cannot open config file (%s): %s",filename,strerror(errno))
syslog(LOG_CRIT,"malloc() failed");
/* But this one SHOULD trigger a warning. */
syslog(LOG_ERR, attacker_string);
}
demo2() {
char d[20];
char s[20];
int n;
_mbscpy(d,s); /* like strcpy, this doesn't check for buffer overflow */
memcpy(d,s); // fail - no size
memcpy(d, s, sizeof(d)); // pass
memcpy(& n, s, sizeof( n )); // pass
memcpy(&n,s,sizeof(s)); // fail - sizeof not of destination
memcpy(d,s,n); // fail - size unguessable
CopyMemory(d,s);
lstrcat(d,s);
strncpy(d,s);
_tcsncpy(d,s);
strncat(d,s,10);
strncat(d,s,sizeof(d)); /* Misuse - this should be flagged as riskier. */
_tcsncat(d,s,sizeof(d)); /* Misuse - flag as riskier */
n = strlen(d);
/* This is wrong, and should be flagged as risky: */
MultiByteToWideChar(CP_ACP,0,szName,-1,wszUserName,sizeof(wszUserName));
/* This is also wrong, and should be flagged as risky: */
MultiByteToWideChar(CP_ACP,0,szName,-1,wszUserName,sizeof wszUserName);
/* This is much better: */
MultiByteToWideChar(CP_ACP,0,szName,-1,wszUserName,sizeof(wszUserName)/sizeof(wszUserName[0]));
/* This is much better: */
MultiByteToWideChar(CP_ACP,0,szName,-1,wszUserName,sizeof wszUserName /sizeof(wszUserName[0]));
/* This is an example of bad code - the third paramer is NULL, so it creates
a NULL ACL. Note that Flawfinder can't detect when a
SECURITY_DESCRIPTOR structure is manually created with a NULL value
as the ACL; doing so would require a tool that handles C/C++
and knows about types more that flawfinder currently does.
Anyway, this needs to be detected: */
SetSecurityDescriptorDacl(&sd,TRUE,NULL,FALSE);
/* This one is a bad idea - first param shouldn't be NULL */
CreateProcess(NULL, "C:\\Program Files\\GoodGuy\\GoodGuy.exe -x", "");
/* Bad, may load from current directory */
(void) LoadLibraryEx(L"user32.dll", nullptr, LOAD_LIBRARY_AS_DATAFILE);
/* This should be ignored, since it's loading only from System32 */
(void) LoadLibraryEx(L"user32.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32 | LOAD_LIBRARY_REQUIRE_SIGNED_TARGET);
/* Test interaction of quote characters */
printf("%c\n", 'x');
printf("%c\n", '"');
printf("%c\n", '\"');
printf("%c\n", '\'');
printf("%c\n", '\177');
printf("%c\n", '\xfe');
printf("%c\n", '\xd');
printf("%c\n", '\n');
printf("%c\n", '\\');
printf("%c\n", "'");
}
int getopt_example(int argc,char *argv[]) {
while ((optc = getopt_long (argc, argv, "a",longopts, NULL )) != EOF) {
}
}
int testfile() {
FILE *f;
f = fopen("/etc/passwd", "r");
fclose(f);
}
/* Regression test: handle \\\n after end of string */
#define assert(x) {\
if (!(x)) {\
fprintf(stderr,"Assertion failed.\n"\
"File: %s\nLine: %d\n"\
"Assertion: %s\n\n"\
,__FILE__,__LINE__,#x);\
exit(1);\
};\
}
int accesstest() {
int access = 0; /* Not a function call. Should be caught by the
false positive test, and NOT labelled as a problem. */
}
|
C
|
#include <SDL.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <stdbool.h>
#include <time.h>
#include "data.h"
#include "game.h"
#include "bub.h"
/* ****************************************************************************************************************
*
* ************************************************************************************************************** */
int game_init (game_t * game_t_ptr) {
bool debug = true ;
if (debug) {
printf ("game initialized\n") ;
}
/* Load all Sprites */
if (!game_loadSprites (game_t_ptr))
fatal ("Could not load Sprites") ;
/* Initializes bubs_array */
/* non-moving bubs /presence/ are kept track of in a pointer-style 2-dimension array */
game_t_ptr->bubs_array = (int * *) malloc (BUB_NY * sizeof(int *)) ;
/* Reset bubs_array = removes all bubs from screen */
game_resetBubsArray (game_t_ptr) ;
/* Initializes bub_array_centers */
/* all possible spaces for a bub /centers coordinates/ are kept track of in a pointer-syle 3-dimension array */
game_t_ptr->bub_array_centers = (int * * *) malloc (BUB_NY * sizeof(int * *)) ;
/* Load bub_array_centers */
game_setBubsArrayCenters (game_t_ptr) ;
return (1) ;
}
/* ****************************************************************************************************************
*
* ************************************************************************************************************** */
int game_loadSprites (game_t * game_t_ptr) {
SDL_Surface *temp ;
/* Loading the BUBS */
temp = SDL_LoadBMP("img/bub_black.bmp");
game_t_ptr->bubs[0] = SDL_DisplayFormat(temp) ;
temp = SDL_LoadBMP("img/bub_blue.bmp");
game_t_ptr->bubs[1] = SDL_DisplayFormat(temp) ;
temp = SDL_LoadBMP("img/bub_green.bmp");
game_t_ptr->bubs[2] = SDL_DisplayFormat(temp) ;
temp = SDL_LoadBMP("img/bub_orange.bmp");
game_t_ptr->bubs[3] = SDL_DisplayFormat(temp) ;
temp = SDL_LoadBMP("img/bub_purple.bmp");
game_t_ptr->bubs[4] = SDL_DisplayFormat(temp) ;
temp = SDL_LoadBMP("img/bub_red.bmp");
game_t_ptr->bubs[5] = SDL_DisplayFormat(temp) ;
temp = SDL_LoadBMP("img/bub_white.bmp");
game_t_ptr->bubs[6] = SDL_DisplayFormat(temp) ;
temp = SDL_LoadBMP("img/bub_yellow.bmp");
game_t_ptr->bubs[7] = SDL_DisplayFormat(temp) ;
SDL_FreeSurface(temp) ;
return (1) ;
}
/* ****************************************************************************************************************
*
* ************************************************************************************************************** */
int game_resetBubsArray (game_t * game_t_ptr) {
bool debug = false ;
int i, j ;
for (i = 0 ; i < BUB_NY ; i += 1) {
game_t_ptr->bubs_array[i] = (int *) malloc (BUB_NX * sizeof(int)) ;
/* number of bubs in a row depends on odd/even number of row */
int j_max = (i % 2 == 0) ? BUB_NX : BUB_NX - 1 ;
for (j = 0 ; j < j_max ; j +=1 ) {
/* set whole lines of bubs here if you want to test */
//bubs_array[i][j] = (i==0 || i == 1 || i == 2) ? get : 0 ;
/* set all bubs to value */
game_t_ptr->bubs_array[i][j] = 0 ;
}
}
if (debug) {
//printf("Check x = %d\n", bub_array_centers[1][0][0]);
//printf("Check y = %d\n", bub_array_centers[1][0][1]);
printf ("Values of bubs_array \n") ;
for (i = 0 ; i < BUB_NY ; i += 1) {
/* number of bubs in a row depends on odd/even number of row */
int j_max = (i % 2 == 0) ? BUB_NX : BUB_NX - 1 ;
for (j = 0 ; j < j_max ; j +=1 ) {
printf ("Value %d\n", game_t_ptr->bubs_array[i][j]) ;
}
}
}
return (1) ;
}
/* ****************************************************************************************************************
*
* ************************************************************************************************************** */
int game_setBubsArrayCenters (game_t * game_t_ptr) {
SDL_Rect * rectForCenters_ptr = (SDL_Rect *) malloc (sizeof(SDL_Rect)) ;
int i, j ;
for (i = 0 ; i < BUB_NY ; i += 1) {
game_t_ptr->bub_array_centers[i] = (int * *) malloc (BUB_NX * sizeof(int *)) ;
/* number of bubs in a row depends on odd/even number of row */
int j_max = (i % 2 == 0) ? BUB_NX : BUB_NX - 1 ;
for (j = 0 ; j < j_max ; j +=1 ) {
/* array centers */
game_t_ptr->bub_array_centers[i][j] = (int *) malloc (2 * sizeof(int)) ;
/* we use the function to get coords of TOP LEFT corner */
rectForCenters_ptr = getBubPositionRect(i, j, rectForCenters_ptr) ;
/* and add BUB_SIZE/2 to get coords of centers */
game_t_ptr->bub_array_centers[i][j][0] = rectForCenters_ptr->x + BUB_SIZE/2 ;
game_t_ptr->bub_array_centers[i][j][1] = rectForCenters_ptr->y + BUB_SIZE/2 ;
}
}
free (rectForCenters_ptr) ;
return (1) ;
}
/* ****************************************************************************************************************
* SYSTEM functions
* ************************************************************************************************************** */
/* ****************************************************************************************************************
* function that receives [i=lig][j=col] of a cell from the bubs_array
* returns a _ptr to SDL_Rect object with coords /x and y OF TOP LEFT CORNER/
* so that main program can position the bub
* WARNING : coords are for top left corner
* ************************************************************************************************************** */
SDL_Rect * getBubPositionRect(int i, int j, SDL_Rect * dumRect_ptr) {
/* distance between each bub */
int d_x = (BOARD_RIGHT - BOARD_LEFT) / 8;
/* there are 8 bubs on even rows
* there are 7 bubs on odd rows
* for odd rows (2d option of ternary op) we add a shift to the right */
dumRect_ptr->x = (i % 2 == 0) ? BOARD_LEFT + j*d_x : BOARD_LEFT + j*d_x + BUB_SIZE / 2;
dumRect_ptr->y = BOARD_TOP + (35 * i) ; //35 because 40 * sqrt(3)/2 = 35 and with that bubs are close to each other
return dumRect_ptr ;
}
/* ****************************************************************************************************************
*
* ************************************************************************************************************** */
short giveRandomNumber() {
time_t t ;
/* Initializes random number generator */
srand ((unsigned) time (&t)) ;
/* Generates numbers from 0 to NUM_COLOR */
return rand() % NUM_COLOR ;
}
/* ****************************************************************************************************************
*
* ************************************************************************************************************** */
void HandleEvent (SDL_Event event, int * quit, int * currOrientation, bub_t * bub_t_ptr)
{
switch (event.type) {
/* close button clicked */
case SDL_QUIT:
*quit = 1;
break;
case SDL_KEYUP:
switch (event.key.keysym.sym) {
case SDLK_SPACE:
if(!bub_t_ptr->isLaunching) {
bub_t_ptr->isLaunching = true ;
}
break ;
default:
break;
}
break;
case SDL_KEYDOWN:
switch (event.key.keysym.sym) {
case SDLK_ESCAPE:
case SDLK_q:
*quit = 1;
break;
case SDLK_LEFT:
/* launcher rotates to the left, unless already at extreme left */
if (*currOrientation > 0) {
*currOrientation -= 1 ;
}
break;
case SDLK_RIGHT:
// launcher rotates to the right, unless already at far right
if (*currOrientation < 44) {
*currOrientation += 1 ;
}
break;
default:
break;
}
break;
}
}
void fatal (char *message) {
char error_message[100] ;
strcpy (error_message, "[!!] Fatal Error\n") ;
strncat (error_message, message, 83) ;
perror (error_message) ;
//exit (-1) ;
}
|
C
|
#include<stdio.h>
void main()
{
int a,b,sum;
printf("enter two number:\n");
scanf("%d%d",&a,&b);
sum =a+b;
printf("sum of number=%d",sum);
}
|
C
|
#ifndef __MEMORY_H__
#define __MEMORY_H__
typedef unsigned short u16;
/* 根据不同平台,指针和long类型字节数相同 */
typedef unsigned long UL;
#define MEMPOOL_ALIGNMENT 4
struct MemoryBlock
{
u16 nSize; //所有内存单元的大小
u16 nFree; //内存块还有多少自由的内存单元
u16 nFirst; //记录下一个可供分配的单元的编号
struct MemoryBlock *pPrev; //前一内存块
struct MemoryBlock *pNext; //内存块链表
char aData[1]; //是内存单元的开始
};
struct MemoryPool
{
struct MemoryBlock *pBlock; //内存块
u16 nUnitSize; //内存单元大小
u16 nInitSize; //初始化大小
u16 nGrowSize; //新申请内存单元增长大小
};
/* 创建内存池 */
void create_memory_pool(struct MemoryPool *mpool, u16 nUnitSize,
u16 nInitSize, u16 nGrowSize);
/* 申请内存 */
void *mem_malloc(struct MemoryPool *mpool);
/* 释放内存 */
void mem_free(struct MemoryPool *mpool, void *pFree);
/* 销毁内存池 */
void destory_memory_pool(struct MemoryPool *mpool);
#endif //__MEMORY_H__
|
C
|
#ifndef MAP_H_
#define MAP_H_
struct bomb;
struct monster;
typedef enum cell_type {
CELL_EMPTY=0,
CELL_GOAL, // 1
CELL_SCENERY, // 2
CELL_PLAYER, // 3
CELL_CASE, // 4
CELL_BONUS, // 5
CELL_MONSTER, // 6
CELL_BOMB, // 7
CELL_DOOR, // 8
CELL_KEY, // 9
CELL_CLOSED_DOOR, // 10
CELL_FLAG, // 11
} cell_type_t;
typedef enum bonus_type {
BONUS_BOMB_RANGE_INC=1,
BONUS_BOMB_RANGE_DEC, // 2
BONUS_BOMB_NB_INC, // 3
BONUS_BOMB_NB_DEC, // 4
BONUS_LIFE, // 5
BONUS_MONSTER // 6
} bonus_type_t;
enum scenery_type {
SCENERY_STONE, // 0
SCENERY_TREE, // 1
};
typedef enum compose_type {
CELL_STONE = (SCENERY_STONE << 4) | CELL_SCENERY, // 0000 0010 -> 2
CELL_TREE = (SCENERY_TREE << 4) | CELL_SCENERY, // 0001 0010 -> 18
CELL_CASE_RANGEINC = (BONUS_BOMB_RANGE_INC << 4) | CELL_CASE, // 0001 0100 -> 20
CELL_CASE_RANGEDEC = (BONUS_BOMB_RANGE_DEC << 4) | CELL_CASE, // 0010 0100 -> 36
CELL_CASE_BOMBINC = (BONUS_BOMB_NB_INC << 4) | CELL_CASE, // 0011 0100 -> 52
CELL_CASE_BOMBDEC = (BONUS_BOMB_NB_DEC << 4) | CELL_CASE, // 0100 0100 -> 68
CELL_CASE_LIFE = (BONUS_LIFE << 4) | CELL_CASE, // 0101 0100 -> 84
CELL_CASE_MONSTER = (BONUS_MONSTER << 4) | CELL_CASE, // 0110 0100 -> 100
CELL_BONUS_RANGE_INC = (BONUS_BOMB_RANGE_INC << 4) | CELL_BONUS, // 0001 0101 -> 21
CELL_BONUS_RANGE_DEC = (BONUS_BOMB_RANGE_DEC << 4) | CELL_BONUS, // 0010 0101 -> 37
CELL_BONUS_BOMB_INC = (BONUS_BOMB_NB_INC << 4) | CELL_BONUS, // 0011 0101 -> 53
CELL_BONUS_BOMB_DEC = (BONUS_BOMB_NB_DEC << 4) | CELL_BONUS, // 0100 0101 -> 69
CELL_BONUS_LIFE = (BONUS_LIFE << 4) | CELL_BONUS, // 0101 0101 -> 85
}compose_type_t;
struct map;
// Create a new empty map
struct map* map_new(int width, int height);
void map_free(struct map* map);
// Return the height and width of a map
int map_get_width(struct map* map);
int map_get_height(struct map* map);
// Return the bomb list of the map
struct list* map_get_list_bomb(struct map* map);
// Return the monster list of the map
struct list* map_get_list_monster(struct map* map);
// Initialize the bomb list of the map
void map_init_list_bomb(struct map* map);
// Initialize the monster list of the map
void map_init_list_monster(struct map* map);
// Return the type of a cell
cell_type_t map_get_cell_type(struct map* map, int x, int y);
//Return the type of the bonus
enum bonus_type map_get_bonus_type(struct map* map, int x, int y);
// Return the complete type of a composed cell
enum cell_type map_get_compose_type(struct map* map, int x, int y) ;
char * map_get_grid(struct map* map);
// Set the type of a cell
void map_set_cell_type(struct map* map, int x, int y, cell_type_t type);
// Test if (x,y) is within the map
int map_is_inside(struct map* map, int x, int y);
// Return a default 12x12 static map
struct map* map_get_default();
// Display the map on the screen
void map_display(struct map* map);
//Manage the bomb explosion
int bomb_explode_aux(struct bomb* bomb, struct map * map, int x, int y);
//Add the bomb to the bomb list of the map
void map_add_bomb(struct bomb* bomb,struct map* map);
//Add the monster to the monster list of the map
void map_add_monster(struct monster* monster, struct map* map);
//Load the bonus position from the map
void bonus_from_map(struct map* map);
//Load the door position from the map
void door_from_map(struct map* map);
//Load the flag position from the map
void flag_from_map(struct map* map) ;
//Get the type of bonus in a case and apply the consequence
void move_case_into_bonus(struct map* map,int x, int y );
#endif /* MAP_H_ */
|
C
|
/**
* file: good_memory.c
*
* To compile to an executable:
* gcc -Wall -Wextra -pedantic -std=c99 -o good_memory good_memory.c
*
* To execute and test with valigrind:
* valgrind --leak-check=full ./good_memory
*
* This correctly makes use of dynamic memory by allocating then deallocating memory as we go.
*
* @author Collin Bolles
*/
#include <stdio.h> // printf
#include <stdlib.h> // malloc, free
int main() {
int *my_number = malloc(sizeof(int)); // Allocate enough storage to keep an int
*my_number = 5; // Assign the value of the dereferenced my_number to 5;
printf("My point points to the value %d\n", *my_number);
free(my_number); // I am done with my number so I will free it
return 0;
}
|
C
|
#include <stdio.h>
/**
* prints hello world
**/
void my_hello_world(){
printf("hello world!\n");
}
/**
* sums up two numbers
* @param a
* @param b
* @return a + b
**/
int my_sum(int a, int b){
return a+b;
}
/**
* executes a operation and doubles the result
* @param a
* @param b
* @return 2 * (a ? b)
**/
int double_sum(int a, int b, int (*operation)(int, int)){
return operation(a, b) * 2;
}
int main(int argc, char **argv) {
void (*hello)();
hello = &my_hello_world;
hello();
int (*sum)(int, int) = &my_sum;
int x = 3, y = 5;
{
int z = sum(x, y);
printf("sum(%d, %d) = %d\n", x, y, z);
}
{
int z = double_sum(x, y, sum);
printf("double_sum(%d, %d) = %d\n", x, y, z);
}
return 0;
}
|
C
|
// This file is part of Blend2D project <https://blend2d.com>
//
// See blend2d.h or LICENSE.md for license and copyright information
// SPDX-License-Identifier: Zlib
#ifndef BLEND2D_RANDOM_H_INCLUDED
#define BLEND2D_RANDOM_H_INCLUDED
#include "api.h"
//! \addtogroup blend2d_api_globals
//! \{
//! \name BLRandom - C API
//! \{
BL_BEGIN_C_DECLS
BL_API BLResult BL_CDECL blRandomReset(BLRandom* self, uint64_t seed) BL_NOEXCEPT_C;
BL_API uint32_t BL_CDECL blRandomNextUInt32(BLRandom* self) BL_NOEXCEPT_C;
BL_API uint64_t BL_CDECL blRandomNextUInt64(BLRandom* self) BL_NOEXCEPT_C;
BL_API double BL_CDECL blRandomNextDouble(BLRandom* self) BL_NOEXCEPT_C;
BL_END_C_DECLS
//! \}
//! \name BLRandom - C/C++ API
//! \{
//! Simple pseudo random number generator based on `XORSHIFT+`, which has 64-bit seed, 128 bits of state, and full
//! period `2^128 - 1`.
//!
//! Based on a paper by Sebastiano Vigna:
//! http://vigna.di.unimi.it/ftp/papers/xorshiftplus.pdf
struct BLRandom {
//! PRNG state.
uint64_t data[2];
#ifdef __cplusplus
//! \name Construction & Destruction
//! \{
BL_INLINE_NODEBUG BLRandom() noexcept = default;
BL_INLINE_NODEBUG BLRandom(const BLRandom&) noexcept = default;
BL_INLINE_NODEBUG explicit BLRandom(uint64_t seed) noexcept { reset(seed); }
//! \}
//! \name Overloaded Operators
//! \{
BL_NODISCARD
BL_INLINE_NODEBUG bool operator==(const BLRandom& other) const noexcept { return equals(other); }
BL_NODISCARD
BL_INLINE_NODEBUG bool operator!=(const BLRandom& other) const noexcept { return !equals(other); }
//! \}
//! \name Common Functionality
//! \{
//! Resets the random number generator to the given `seed`.
//!
//! Always returns `BL_SUCCESS`.
BL_INLINE_NODEBUG BLResult reset(uint64_t seed = 0) noexcept { return blRandomReset(this, seed); }
//! Tests whether the random number generator is equivalent to `other`.
//!
//! \note It would return true only when its internal state matches `other`'s internal state.
BL_NODISCARD
BL_INLINE_NODEBUG bool equals(const BLRandom& other) const noexcept {
return bool(unsigned(blEquals(this->data[0], other.data[0])) &
unsigned(blEquals(this->data[1], other.data[1])));
}
//! \}
//! \name Random Numbers
//! \{
//! Returns the next pseudo-random `uint64_t` value and advances PRNG state.
BL_NODISCARD
BL_INLINE_NODEBUG uint64_t nextUInt64() noexcept { return blRandomNextUInt64(this); }
//! Returns the next pseudo-random `uint32_t` value and advances PRNG state.
BL_NODISCARD
BL_INLINE_NODEBUG uint32_t nextUInt32() noexcept { return blRandomNextUInt32(this); }
//! Returns the next pseudo-random `double` precision floating point in [0..1) range and advances PRNG state.
BL_NODISCARD
BL_INLINE_NODEBUG double nextDouble() noexcept { return blRandomNextDouble(this); }
//! \}
#endif
};
//! \}
//! \}
#endif // BLEND2D_RANDOM_H_INCLUDED
|
C
|
/*
** move2.c for in /home/cottin_j/lemipc-2015-2014s-cottin_j
**
** Made by joffrey cottin
** Login <[email protected]>
**
** Started on Sun Mar 25 17:07:53 2012 joffrey cottin
** Last update Sun Mar 25 17:58:23 2012 hallux
*/
#include "lemipc.h"
int vert_move(int pos,
int pos_en,
int *battleground,
int no_squad,
int semid)
{
bool ret;
if (pos / map_len < pos_en / map_len)
{
ret = down(battleground, pos, no_squad);
if (ret == true)
{
unlock_semz(semid);
return (pos + map_len);
}
}
else if (pos / map_len > pos_en / map_len)
{
ret = up(battleground, pos, no_squad);
if (ret == true)
{
unlock_semz(semid);
return (pos - map_len);
}
}
unlock_semz(semid);
return (randomed(pos, battleground, no_squad));
}
int horiz_move(int pos,
int pos_en,
int *battleground,
int no_squad,
int semid)
{
bool ret;
if (pos % 10 < pos_en % 10)
{
ret = right(battleground, pos, no_squad);
if (ret == true)
{
unlock_semz(semid);
return (pos + 1);
}
}
else if (pos % 10 > pos_en % 10)
{
ret = left(battleground, pos, no_squad);
if (ret == true)
{
unlock_semz(semid);
return (pos - 1);
}
}
unlock_semz(semid);
return (randomed(pos, battleground, no_squad));
}
int randomed(int pos, int *battleground, int no_squad)
{
int nb;
int i;
bool ret;
t_move move[] = {
{0, up, (UP)}, {1, down, (DOWN)},
{2, left, (LEFT)}, {3, right, (RIGHT)}
};
while (42)
{
i = 0;
nb = rand() % 4;
while (i < 4)
{
if (nb == move[i].nb_dir)
{
ret = move[i].func_dir(battleground, pos, no_squad);
if (ret)
return (pos + move[i].ret_dir);
}
i++;
}
}
}
|
C
|
#ifndef _PWM_H_
#define _PWM_H_
#include <stdint.h>
#define SUCCESS (1)
#define FAIL (0)
/*
* Initializes PWM
* Arguments: none
* Returns: none
*/
void Timer0_PWM_Init(void);
/*
* Starts PWM
* Arguments: none
* Returns: none
*/
void Timer0_PWM_Start(void);
/*
* Stops PWM
* Arguments: none
* Returns: none
*/
void Timer0_PWM_Stop(void);
/*
* Sets PWM duty cycle
* Arguments: uint8_t dutycycle - duty cycle for the PWM ranges from 0 to 100
* Returns: SUCCESS - when duty cycle is set successfully
FAIL - when input parameters are incorrect
*/
uint8_t Timer0_PWM_SetDutyCycle(uint8_t dutycyle);
#endif
|
C
|
#include <ncurses.h> // also includes <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include "ictdata.h" // ictFile and ictCategory, and some extern variables
struct ictFile* files = NULL;
size_t nFiles = 0;
struct ictCategory* categories = NULL;
size_t nCategories = 0;
#include "saverestore.h" // save() and restore(), unsurprisingly
#include "interface.h" // curses interface
int main(int argc, char* argv[]) {
// check arguments
if (argc < 2) {
fprintf(stderr, "usage: %s [IMAGES...]\n", argv[0]);
return 1;
}
// find image viewer program
char* imgViewer = getenv("IMG_VIEWER");
if (imgViewer == NULL) imgViewer = "display";
printf("Using image viewer `%s'. To change, call %s with the environment "
"variable IMG_VIEWER set to a variable of your choice.\n",
imgViewer, argv[0]);
// make sure image viewer exists
char* cmd = malloc((strlen(imgViewer) + 28) * sizeof(char));
sprintf(cmd, "command -v %s >/dev/null 2>&1", imgViewer);
if (system(cmd) != 0) {
fprintf(stderr, "fatal: image viewer `%s' does not exist, aborting\n",
imgViewer);
return 1;
}
free(cmd);
// check files
int i, err = 0;
for (i = 1; i < argc; ++i) {
if (access(argv[i], R_OK) == -1) {
fprintf(stderr, "%s: file does not exist\n", argv[i]);
err = 1;
}
}
if (err) return 1;
// read existing data
if (restore() != 0) {
// an error happened somewhere
return 1;
}
// add files
// TODO make this more efficient, not 2 allocs per file
int j, skipFile = 0;
for (i = 1; i < argc; ++i) {
// do not add if this file already exists
for (j = 0; j < nFiles; ++j) {
if (strcmp(files[j].filename, argv[i]) == 0) {
skipFile = 1;
break;
}
}
if (!skipFile) {
files = realloc(files, (++nFiles) * sizeof(struct ictFile));
files[nFiles - 1].filename = calloc(strlen(argv[i]) + 1,
sizeof(char));
strcpy(files[nFiles - 1].filename, argv[i]);
files[nFiles - 1].data = 0;
}
skipFile = 0;
}
// finally ready to start!
printf("Ready. Press enter to begin.");
getchar();
// set up ncurses
initscr(); // initialize screen
raw(); // disable line buffering, get all keys (including ex. ctrl+C)
keypad(stdscr, TRUE); // handling of F1, F2, arrow keys, etc.
noecho(); // turn off echoing when a key is pressed
refresh();
interfaceGo(imgViewer);
// cleanup ncurses
endwin();
return 0;
}
|
C
|
/**
* @file rdma_cs.c
* @author Austin Pohlmann
* @brief File containing the definitions of the functions listed in rdma_cs.h
*
*/
#include "rdma_cs.h"
/**
* @brief Print an error message and exit the application
*
* @return @c NULL
* @param reason a string representation of what the error came from
* @param error the error number, typically just errno
* @param file the file to output the error message to
*/
void stop_it(char *reason, int error, FILE *file){
fprintf(file, "Error for %s: '%s'\n", reason, strerror(error));
exit(-1);
}
/**
* @brief Process a communication manager event
*
* The function will call exit(-1) if the event found does not match the expected event
* @return the @c struct @c rdma_cm_id of the new connection if the event was @c RDMA_CM_EVENT_CONNECT_REQUEST
* @param ec the event channel to check
* @param expected the expected event
* @param file the file to output the connection info of a new connection if the event was @c RDMA_CM_EVENT_CONNECT_REQUEST
*/
struct rdma_cm_id *cm_event(struct rdma_event_channel *ec,
enum rdma_cm_event_type expected, FILE *file){
struct rdma_cm_event *event;
struct rdma_cm_id *id;
if(rdma_get_cm_event(ec, &event))
stop_it("rdma_get_cm_event()", errno, file);
if(event->event != expected){
fprintf(file, "Error: expected \"%s\" but got \"%s\"\n",
rdma_event_str(expected), rdma_event_str(event->event));
exit(-1);
}
if(event->event == RDMA_CM_EVENT_CONNECT_REQUEST){
id=event->id;
struct ibv_qp_init_attr init_attr;
memset(&init_attr, 0, sizeof(init_attr));
init_attr.qp_type = IBV_QPT_RC;
init_attr.cap.max_send_wr = MAX_SEND_WR;
init_attr.cap.max_recv_wr = MAX_RECV_WR;
init_attr.cap.max_send_sge = MAX_SEND_SGE;
init_attr.cap.max_recv_sge = MAX_RECV_SGE;
init_attr.cap.max_inline_data = MAX_INLINE_DATA;
if(rdma_create_qp(id, NULL, &init_attr))
stop_it("rdma_create_qp()", errno, file);
struct rdma_conn_param *conn_params = malloc(sizeof(*conn_params));
memset(conn_params, 0, sizeof(*conn_params));
conn_params->retry_count = 8;
conn_params->rnr_retry_count = 8;
conn_params->responder_resources = 10;
conn_params->initiator_depth = 10;
if(rdma_accept(id, conn_params))
stop_it("rdma_accept()", errno, file);
fprintf(file, "Accepted connection request from remote QP 0x%x.\n",
(unsigned int)event->param.conn.qp_num);
}
if(rdma_ack_cm_event(event))
stop_it("rdma_ack_cm_event()", errno, file);
return id;
}
/**
* @brief Exchange the information needed to perform rdma read/write operations
*
* The address, rkey, and size of a memory region is sent to and recieved from a remote host.
* WARNING: this erases the contents of the memory region used
* @return @c NULL
* @param cm_id the id associated with the connection to the remote host
* @param mr the memory region to send information about
* @param rkey the location to store the remote host's memory region's rkey
* @param remote_addr the location to store the remote host's memory region's address
* @param size the location to store the remote host's memory region's size
* @param file the file to print the sent and received information to
*/
void swap_info(struct rdma_cm_id *cm_id, struct ibv_mr *mr, uint32_t *rkey, uint64_t *remote_addr,
size_t *size, FILE *file){
if(rdma_post_recv(cm_id, "qwerty", mr->addr, 30, mr))
stop_it("rdma_post_recv()", errno, file);
memcpy(mr->addr+30,&mr->addr,sizeof(mr->addr));
memcpy(mr->addr+30+sizeof(mr->addr),&mr->rkey,sizeof(mr->rkey));
memcpy(mr->addr+30+sizeof(mr->addr)+sizeof(mr->rkey),&mr->length,sizeof(mr->length));
if(rdma_post_send(cm_id, "qwerty", mr->addr+30, 30, mr, IBV_SEND_SIGNALED))
stop_it("rdma_post_send()", errno, file);
get_completion(cm_id, SEND, 1, file);
fprintf(file, "Sent local address: 0x%0llx\nSent local rkey: 0x%0x\n", (unsigned long long)mr->addr, (unsigned int)mr->rkey);
get_completion(cm_id, RECV, 1, file);
memcpy(remote_addr, mr->addr, sizeof(*remote_addr));
memcpy(rkey, mr->addr+sizeof(*remote_addr), sizeof(*rkey));
fprintf(file, "Received remote address: 0x%0llx\nReceived remote rkey: 0x%0x\n", (unsigned long long)*remote_addr, (unsigned int)*rkey);
if(size != NULL){
memcpy(size, mr->addr+sizeof(*remote_addr)+sizeof(*rkey), sizeof(*size));
fprintf(file, "Received remote memory region length: %u bytes\n", (unsigned int)*size);
}
memset(mr->addr, 0, mr->length);
}
/**
* @brief Wait for and pull a work completion
*
* This function will block until a work completion of the specified type is pulled from the completion queue.
* If the completion contains immediate data, it will be returned.
* Operations included in SEND: send (read and write if IBV_SEND_SIGNALED is set)
* Operations included in RECV: receive
* @return the immediate data received, if present
* @param cm_id the id associated with the connection to the remote host
* @param type the type of completion to pull, either SEND of RECV
* @param print 1 if this should print anything, 0 if not
* @param file the file to print to
*/
uint32_t get_completion(struct rdma_cm_id *cm_id, enum completion_type type, uint8_t print, FILE *file){
struct ibv_wc wc;
uint32_t data = 0;
switch(type){
case SEND:
if(-1 == rdma_get_send_comp(cm_id, &wc))
stop_it("rdma_get_send_comp()", errno, file);
break;
case RECV:
if(-1 == rdma_get_recv_comp(cm_id, &wc))
stop_it("rdma_get_recv_comp()", errno, file);
break;
default:
fprintf(file, "Error: unknown completion type\n");
exit(-1);
}
if(print){
switch(wc.opcode){
case IBV_WC_SEND:
fprintf(file, "Send ");
break;
case IBV_WC_RECV:
fprintf(file, "Receive ");
break;
case IBV_WC_RECV_RDMA_WITH_IMM:
fprintf(file, "Receive with immediate data ");
break;
case IBV_WC_RDMA_WRITE:
fprintf(file, "Write ");
break;
case IBV_WC_RDMA_READ:
fprintf(file, "Read ");
break;
default:
fprintf(file, "Operation %d", wc.opcode);
break;
}
}
if(!wc.status){
if(print)
fprintf(file, "completed successfully!\n");
if(wc.wc_flags & IBV_WC_WITH_IMM && wc.opcode != IBV_WC_SEND){
if(print)
fprintf(file, "Immediate data: 0x%x\n", ntohl(wc.imm_data));
data = ntohl(wc.imm_data);
}
if(wc.opcode == IBV_WC_RECV && print){
fprintf(file, "%u bytes received.\n", wc.byte_len);
}
} else if(print){
fprintf(file, "failed with error value %d.\n", wc.status);
}
return data;
}
/**
* @brief Disconnect from a remote host and free the resources used
*
* @param mine the id of the local host
* @param client the id of the remote host
* @param mr the memory region to free
* @param ec the event channel to use
* @param file the file to print to
*/
int obliterate(struct rdma_cm_id *mine,struct rdma_cm_id *client, struct ibv_mr *mr,
struct rdma_event_channel *ec, FILE *file){
fprintf(file, "Disconnecting...\n");
struct rdma_cm_id *id = client != NULL ? client : mine;
if(rdma_dereg_mr(mr))
stop_it("rdma_dereg_mr()", errno, file);
if(client != NULL)
cm_event(ec, RDMA_CM_EVENT_DISCONNECTED, file);
if(rdma_disconnect(id))
stop_it("rdma_disconnect()", errno, file);
if(client == NULL)
cm_event(ec, RDMA_CM_EVENT_DISCONNECTED, file);
rdma_destroy_qp(id);
if(client != NULL){
if(rdma_destroy_id(client))
stop_it("rdma_destroy_id()", errno, file);
}
if(mine != NULL){
if(rdma_destroy_id(mine))
stop_it("rdma_destroy_id()", errno, file);
}
rdma_destroy_event_channel(ec);
return 0;
}
/**
* @brief A simple wrapper for rdma_post_recv()
*
* @param id the id associated with the connection to the remote host
* @param mr the memory region to receive the data in
* @param file the file to print to in the event of an error
*/
void rdma_recv(struct rdma_cm_id *id, struct ibv_mr *mr, FILE *file){
if(rdma_post_recv(id, "qwerty", mr->addr, mr->length, mr))
stop_it("rdma_post_recv()", errno, file);
}
/**
* @brief A 0 byte send with immediate data
*
* This is used to send opcodes between hosts using the immediate data.
* @return @c NULL
* @param id the id associated with the connection to the remote host
* @param op the opcode (immediate data) to send
* @param file the file to print to in the event of an error
*/
void rdma_send_op(struct rdma_cm_id *id, uint8_t op, FILE *file){
struct ibv_send_wr wr, *bad;
wr.next = NULL;
wr.sg_list = NULL;
wr.num_sge = 0;
wr.opcode = IBV_WR_SEND_WITH_IMM;
wr.send_flags = IBV_SEND_SIGNALED;
wr.imm_data = htonl(op);
if(rdma_seterrno(ibv_post_send(id->qp, &wr, &bad)))
stop_it("ibv_post_send()", errno, file);
}
/**
* @brief A simple wrapper for an inline write using rdma_post_write().
*
* @return @c NULL
* @param id the id associated with the connection to the remote host
* @param buffer the buffer containing the data to be written
* @param address the remote address to write to
* @param key the key associated with the remote address
* @param file the file to print to in the event of an error
*/
void rdma_write_inline(struct rdma_cm_id *id, void *buffer, uint64_t address, uint32_t key, FILE *file){
if(rdma_post_write(id, "qwerty", buffer, strlen(buffer), NULL,
IBV_SEND_INLINE | IBV_SEND_SIGNALED, address, key))
stop_it("rdma_post_write()", errno, file);
}
|
C
|
/************************************************************************************************
* L3 EEA - Projet Techniques Scientifiques
* Theme : Algorithme Genetique
* Auteurs:
* - AIT MOUHOUB Farid
* - AOUCI Sofiane
* - JAQUET E.Prince
* - LAVAL Hugo
************************************************************************************************/
/*
* lambda_0 E [6555, 6570] codee en 19 bit chacun donc [0, 524287] <=> [6555, 6607,4287]
* lambda_L E [7, 15.191] codee en 13 bit chacun donc [0, 8191] <=> [7, 15.191]
* Y_0 E [0.2, 0.25] codee en 16 bit donc [0, 65535] <=> [0.2, 0.265535]
* Y_max E [0.72, 0.785535] codee en 16 bit donc [0, 65535]
*/
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <time.h>
//#define s_abs(x) ((x) > (0) ? (x):(-x))
//#define sqr(x) (x * x)
double s_abs(double x){
if(x > 0) return x;
else return -x;
}
double sqr(double x){
return x*x;
}
#define pi 3.14159265358979323846
#define inf_lam_0 6555
#define inf_lam_L 7
#define inf_Y0 0.2
#define inf_Ymax 0.72
#define data_l 1024
#define inc 100
#define X 0.15
#define Mu 0.015
#define c_length 64
void init(uint64_t* chromo);
int decode(uint64_t chromo, double* Y0, double* lambda_L, double* lambda_0, double* Ymax);
uint64_t code(double Y0, double lambda_L, double lambda_0, double Ymax);
double fitting(uint64_t c, double lambda);
void evaluate(uint64_t *chromo, double data[][3], double *eval);
void survival(uint64_t **chromo, double* eval);
void crossover(uint64_t *chromo);
void mutation(uint64_t *chromo);
double soso(double *eval, int *i_sol);
uint64_t grayInverse(uint64_t n);
int main()
{
srand((unsigned int)time(0));
FILE *profile = fopen("profil.txt","r");
double data[data_l][3];
int i = 0;
if(profile == NULL) exit(-1);
for(i = 0; i < data_l; i++)
{
fscanf(profile,"%lf %lf %lf",&data[i][0],&data[i][1],&data[i][2]);
}
fclose(profile);
uint64_t *chromo = calloc(inc,sizeof(uint64_t));
int i_sol = 0;
double eval[inc] = {0};
init(chromo);
i = 0;
do
{
evaluate(chromo,data,eval);
survival(&chromo,eval);
crossover(chromo);
mutation(chromo);
//printf("%d..... %d %d %d %d %d %d\n\n",s_abs(-i),eval[0],eval[1],eval[2],eval[3],eval[4],eval[5]);
printf("%lf\n",soso(eval, &i_sol));
}
while(soso(eval, &i_sol) > 0.204);
double a = 0, b = 0, c = 0, d = 0;
decode(chromo[i_sol],&a,&b,&c,&d);
printf("%lf, %lf, %lf, %lf\n",d,c,b,a);
//printf("-------- %d --------- ",grayInverse(15 ^ (15 >> 1)));
return 0;
}
void init(uint64_t* chromo)
{
int i = 0;
for(i = 0; i < inc; i++)
{
double a = (rand() % 65535)* 1e-6 + inf_Y0;
double b = (rand() % 8191)* 1e-3 + inf_lam_L;
double c = (rand() % 524287)* 1e-4 + inf_lam_0;
double d = (rand() % 65535)* 1e-6 + inf_Ymax;
chromo[i] = code(a,b,c,d);
}
}
uint64_t code(double Y0, double lambda_L, double lambda_0, double Ymax)
{
uint64_t bin;
uint16_t a = (Y0 - inf_Y0) * 1e6 + 1 ;
uint16_t b = (lambda_L - inf_lam_L) *1e3 + 1 ;
uint32_t c = (lambda_0 - inf_lam_0) * 1e4 + 1 ;
uint16_t d = (Ymax - inf_Ymax) * 1e6 + 1 ;
bin = ((uint64_t)a << (16 + 19 + 13)) + ((uint64_t)b << (16 + 19)) + ((uint64_t)c << 16) + ((uint64_t)d << 0);
return bin;// ^ (bin >> 1);
}
int decode(uint64_t chromo, double *Y0, double *lambda_L, double *lambda_0, double *Ymax)
{
//chromo = grayInverse(chromo);
uint16_t a = (chromo & ((((uint64_t)0b1<<16) - 1) << (16 + 19 + 13)) ) >> (16 + 19 + 13);
uint16_t b = (chromo & ((((uint64_t)0b1<<13) - 1) << (16 + 19)) ) >> (16 + 19);
uint32_t c = (chromo & ((((uint64_t)0b1<<19) - 1) << 16) ) >> 16;
uint16_t d = (chromo & ((((uint64_t)0b1<<16) - 1) << 0) ) >> 0;
*Y0 = a * 1e-6 + inf_Y0;
*lambda_L = b * 1e-3 + inf_lam_L;
*lambda_0 = c * 1e-4 + inf_lam_0;
*Ymax = d * 1e-6 + inf_Ymax;
return 1;
}
double fitting(uint64_t chromo, double lambda)
{
double Y0, lambda_L, lambda_0, Ymax;
decode(chromo,&Y0,&lambda_L,&lambda_0,&Ymax);
return Y0 + ((Ymax - Y0) * sqr(lambda_L) / 4)/(sqr(lambda-lambda_0) + sqr(lambda_L/2));
}
void evaluate(uint64_t* chromo,double data[][3], double* eval)
{
int i = 0, j = 0;
for(i = 0;i < inc; i++)
{
eval[i] = 0;
for(j = 0; j < data_l; j++)
{
eval[i] += sqr(data[j][1] - fitting(chromo[i],data[j][0]));
}
}
}
void survival(uint64_t **chromo, double *eval)
{
uint64_t *temp_c = calloc(inc,sizeof(uint64_t));
double c_prob[inc] = {0}, s = 0;
int i = 0;
for(i = 0; i < inc; i++)
{
c_prob[i] = (double)1/(double)(eval[i]+1);
s += c_prob[i];
}
c_prob[0] /= s;
for(i = 1; i < inc; i++)
{
c_prob[i] = c_prob[i] / s + c_prob[i - 1];
}
for(i = 0; i < inc; i++)
{
int j = 0;
s = (double)rand()/(double)RAND_MAX;
if(s <= c_prob[0] && s > 0)
{
temp_c[i] = (*chromo)[0];
}
else
{
j++;
while(j<inc)
{
if(s <= c_prob[j] && s > c_prob[j-1])
{
temp_c[i] = (*chromo)[j];
j = inc;
}
j++;
}
}
}
free(*chromo);
*chromo = temp_c;
}
void crossover(uint64_t *chromo)
{
int parent[inc] = {0}, i = 0, n = 0;
for(i = 0; i < inc; i++)
{
if((double)rand()/(double)RAND_MAX < X) parent[n++] = i;
}
for(i = 0; i < n; i++)
{
int R = rand() % (c_length - 1) + 1;
uint32_t filter = (1 << R) - 1, temp;
temp = chromo[parent[i]] & filter;
chromo[parent[i]] = (chromo[parent[i]] & ~filter) + (chromo[parent[(i+1)%n]] & filter);
chromo[parent[(i+1)%n]] = (chromo[parent[(i+1)%n]] & ~filter) + temp;
}
}
void mutation(uint64_t *chromo)
{
int i = 0, R = 0;
for(i = 0; i < (int)(Mu*inc*c_length); i++)
{
R = rand()%(c_length*inc);
chromo[R/c_length] ^= (uint64_t)1 << (R % c_length);
}
}
double soso(double *eval, int *i_sol)
{
double min = eval[0];
int i = 0;
for(i = 1; i < inc; i++)
{
//printf("%lf %lf\n",min,eval[i]);
if(min > eval[i])
{
min = eval[i];
*i_sol = i;
}
}
return min;
}
uint64_t grayInverse(uint64_t n) {
uint64_t translate, idiv;
translate = 1;
while(1) {
idiv = n >> translate;
n ^= idiv;
if (idiv <= 1 || translate == 32)
return n;
translate <<= 1; // double le nb de shifts la prochaine fois
}
}
|
C
|
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
int max(int a, int b)
{
}
int main()
{
long long int x1, y1, x2, y2;
long long int x3, y3, x4, y4;
int shape=0;
scanf("%d%d%d%d%d%d%d%d", &x1, &y1, &x2, &y2, &x3, &y3, &x4, &y4);
if (x1 == x4 || x2 == x3)
{
if (y1 == y4 || y2 == y3)
printf("POINT");
else if ((y2 - y1) + (y4 - y3) > max(r2.y2 - r1.y1, r1.y2 - r2.y1))
printf("LINE");
else
printf("NULL");
}
else if ((x2 - x1) + (x4 - x3) > max(r2.x2 - r1.x1, r1.x2 - r2.x1))
{
if (y1 == y4 || y2 == y3)
printf("LINE");
else if ((y2 - y1) + (y4 - y3) > max(r2.y2 - r1.y1, r1.y2 - r2.y1))
printf("FACE");
else
printf("NULL");
}
else
printf("NULL");
return 0;
}
/*
x1 = abs(x1), x2 = abs(x2), x3 = abs(x3), x4 = abs(x4);
y1 = abs(y1), y2 = abs(y2), y3 = abs(y3), y4 = abs(y4);*/
|
C
|
#include<stdio.h>
#include<stdbool.h>
#include<stdlib.h>
#include<string.h>
#include<locale.h>
#include "tabuleiro.c"
#include "hospedes.c"
#include "validacao.c"
#include "ajudante.c"
#include "fases.c"
int main() {
setlocale(LC_ALL, "Portuguese");
printf("Esse jogo basea-se em inserir hóspedes dentro de quartos válidos. \n");
printf("Algumas regras antes: \n\n");
printf("Você receberá os valores para inserir nos quartos, V são os quartos válidos \n");
printf("E I são os quartos inválidos\n");
printf("Os ratos (R) não podem ficar ao lado de gatos (G) \n");
printf("Os cães (C) não pode ficar ao lado de ossos (O) \n");
printf("Os gatos (G) não podem ficar ao lado de cães (C) \n");
printf("O quiejo (Q) não pode ficar ao lado dos ratos (R) \n\n");
printf("Essa é a primeira fase.\n");
printf("\n");
primeiraFase(); //Chama a primeira fase
printf("Essa é a segunda fase.\n");
segundaFase(); //Chama a segunda fase
printf("Essa é a terceira fase. \n");
terceiraFase(); //Chama a terceira fase
printf("Essa é a quarta fase. \n");
quartaFase(); //Chama a quarta fase
printf("Essa é a quinta fase. \n");
quintaFase(); //Chama a quinta fase
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_exit.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mlachheb <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/04/29 16:33:31 by mlachheb #+# #+# */
/* Updated: 2021/06/30 20:32:25 by mlachheb ### ########.fr */
/* */
/* ************************************************************************** */
#include "built_in.h"
void ft_exit(t_builtin_vars var, int *retv)
{
double number;
number = 0;
write(2, "exit\n", 5);
if (ft_size_args(var.args) == 1)
exit(0);
else if (ft_size_args(var.args) == 2 && var.args[1] != NULL
&& !check_exit_arg(var.args[1]))
{
number = ft_atoi(var.args[1]);
exit(number);
}
else
ft_exit_helper(var, retv);
write(1, "\n", 1);
}
void ft_exit_helper(t_builtin_vars var, int *retv)
{
int number;
if (var.args[1] != NULL && check_exit_arg(var.args[1]))
{
number = 255;
write(2, "MiniShell: exit: ", 17);
write(2, var.args[1], ft_strlen(var.args[1]));
write(2, ": numeric argument required\n", 28);
exit(number);
}
else
{
number = 0;
*retv = 1;
write(2, "MiniShell: exit: too many arguments", 35);
}
}
int check_exit_arg(char *str)
{
int i;
double number;
i = 0;
str = ft_remove_spaces(ft_strdup(str));
if (str[i] == '-' || str[i] == '+')
i = 1;
while (str[i] != '\0')
{
if (!ft_char_in_string(str[i], "0123456789"))
return (1);
i++;
}
number = ft_atoi(str);
if (number > LLONG_MAX || number < LLONG_MIN)
return (1);
return (0);
}
void ft_free_builtin_vars(t_builtin_vars *var)
{
if (var->args != NULL)
{
ft_free_args(var->args);
var->args = NULL;
}
if (var->option != NULL)
{
free(var->option);
var->option = NULL;
}
if (*(var->envp) != NULL)
{
ft_free_args(*(var->envp));
*(var->envp) = NULL;
}
}
|
C
|
#include <stdio.h>
int main() {
/**
* Escreva a sua solução aqui
* Code your solution here
* Escriba su solución aquí
*/
int i;
double n, N[100];
scanf("%lf", &n);
for(i=0;i<100;i++){
N[i] = n;
n/=2;
}
for(i=0;i<100;i++){
printf("N[%d] = %.4lf\n", i,N[i]);
}
return 0;
}
|
C
|
/*
* File: skip_list.c
* Author: Finnur Smári Torfason
* Compiler: GCC 4.9.1
*/
#include <time.h>
#include "skip_list.h"
static int seed_set = 0;
int rand_height(int max) {
if ( !seed_set ) {
seed_set = 1;
srand((unsigned int)time(NULL));
}
static int bits = 0;
static int reset = 0;
int h, found = 0;
for ( h = 0; !found; h++ ) {
if ( reset == 0 ) {
bits = rand();
reset = sizeof(int) * BYTE_LEN;
}
found = bits & 1;
bits = bits >> 1;
--reset;
}
if ( h >= max ) {
h = max - 1;
}
return h;
}
void init_skip_list(struct skip_list_t *skip) {
struct skip_node_t *tmp;
skip->height = 1;
skip->length = 0;
skip->head = (struct skip_node_t *)malloc(sizeof(struct skip_node_t));
skip->head->level = 0;
skip->head->data = NULL;
init_list_node(&skip->head->node_v);
init_list_node(&skip->head->node_h);
tmp = (struct skip_node_t *)malloc(sizeof(struct skip_node_t));
tmp->data = NULL;
tmp->level = 1;
list_append(&(tmp->node_v), &(skip->head->node_v));
init_list_node(&(tmp->node_h));
}
int skip_insert(struct skip_list_t *skip, void *value) {
struct skip_node_t *tmp, *head, *save = NULL;
struct skip_node_t *tmp_v = NULL, *tmp_h = NULL;
struct node_t *pos_v, *q_v, *pos_h, *q_h;
if ( skip_search(skip, value) == 1 ) {
return -1;
}
int h = rand_height(MAX_HEIGHT);
if ( h > skip->height ) {
skip->height++;
h = skip->height;
tmp = (struct skip_node_t *)malloc(sizeof(struct skip_node_t));
tmp->data = NULL;
tmp->level = skip->height;
list_append(&(tmp->node_v), &(skip->head->node_v));
init_list_node(&(tmp->node_h));
}
head = skip->head;
for_each(pos_v, q_v, &head->node_v) {
tmp_v = get_list_node(pos_v, struct skip_node_t, node_v);
for_each_reverse(pos_h, q_h, &tmp_v->node_h) {
tmp_h = get_list_node(pos_h, struct skip_node_t, node_h);
if ( value < tmp_h->data || &tmp_v->node_h == pos_h->prev ) {
if ( tmp_v->level <= h ) {
tmp = (struct skip_node_t *)malloc(sizeof(struct skip_node_t));
tmp->level = tmp_h->level;
tmp->data = value;
init_list_node(&tmp->node_v);
list_prepend(&tmp->node_h, &tmp_h->node_h);
if ( save ) {
list_append(&save->node_v, &tmp->node_v);
}
save = tmp;
}
if ( tmp_h->level == 1 ) {
skip->length++;
return 1;
}
q_h = (&tmp_h->node_v)->next;
q_h++;
pos_v = pos_v->next;
tmp_v = get_list_node(pos_v, struct skip_node_t, node_v);
}
}
if ( !tmp_h ) {
tmp = (struct skip_node_t *)malloc(sizeof(struct skip_node_t));
tmp->level = tmp_v->level;
tmp->data = value;
init_list_node(&tmp->node_v);
list_prepend(&tmp->node_h, &tmp_v->node_h);
if ( save ) {
list_append(&save->node_v, &tmp->node_v);
}
save = tmp;
}
}
skip->length++;
return 1;
}
void skip_remove(struct skip_list_t *skip, void *value) {
struct skip_node_t *tmp, *head, *save = NULL;
struct skip_node_t *tmp_v = NULL, *tmp_h = NULL;
struct node_t *pos_v, *q_v, *pos_h, *q_h;
head = skip->head;
for_each(pos_v, q_v, &head->node_v) {
tmp_v = get_list_node(pos_v, struct skip_node_t, node_v);
for_each(pos_h, q_h, &tmp_v->node_h) {
tmp_h = get_list_node(pos_h, struct skip_node_t, node_h);
}
}
}
int skip_search(struct skip_list_t *skip, void *value) {
struct skip_node_t *head;
struct skip_node_t *tmp_v = NULL, *tmp_h = NULL;
struct node_t *pos_v, *q_v, *pos_h, *q_h;
head = skip->head;
for_each(pos_v, q_v, &head->node_v) {
tmp_v = get_list_node(pos_v, struct skip_node_t, node_v);
for_each_reverse(pos_h, q_h, &tmp_v->node_h) {
tmp_h = get_list_node(pos_h, struct skip_node_t, node_h);
if ( tmp_h->data == value ) {
return 1;
}
if ( &tmp_v->node_h == pos_h->prev ) {
if ( tmp_v->level != 1 ) {
q_h = (&tmp_h->node_v)->next;
q_h++;
pos_v = pos_v->next;
tmp_v = get_list_node(pos_v, struct skip_node_t, node_v);
}
}
}
}
return -1;
}
|
C
|
#include "binary_trees.h"
/**
* binary_tree_size- goes through a binary tree counting the size
* @tree: pointer to the root node
* Return: the size of the tree
*/
size_t binary_tree_size(const binary_tree_t *tree)
{
size_t count = 1;
if (tree == NULL)
return (0);
if (tree->left)
count += binary_tree_size(tree->left);
if (tree->right)
count += binary_tree_size(tree->right);
return (count);
}
|
C
|
#include "buffer.h"
//Nollställer bufferten
void bufferInit(FIFO *buffer) {
buffer->count = 0;
buffer->in = 0;
buffer->out = 0;
}
//Lägger till ett elem i buffern.
//Returnerar 1 om det lyckades, 0 annars.
uint8_t bufferPut ( FIFO *buffer, uint8_t elem) {
//Kollar om bufferten är full.
if (buffer->count == BUFFERSIZE){
return 0;
}
//Lägger elem i bufferten
buffer->buff[buffer->in++] = elem;
buffer->count++;
//Justerar pekaren om vi nått slutet
if (buffer->in == BUFFERSIZE)
buffer->in = 0;
return 1;
}
//Skriver över föregående elem i buffern.
//Ändrar inga indexeringsvariabler
void bufferOverrideLast ( FIFO *buffer, uint8_t elem) {
//Index för föregående element i buffern
uint8_t prevIndex;
//Om index för nästa element är 0 så blir föregående BUFFERSIZE - 1
//annars buffer->in - 1
prevIndex = (buffer->in == 0) ? BUFFERSIZE - 1 : buffer->in - 1;
//Skriver över elem i bufferten
buffer->buff[prevIndex] = elem;
}
//Hämtar ett element från buffern till dest.
//Returnerar 1 om det lyckades, 0 annars.
uint8_t bufferGet ( FIFO *buffer, uint8_t *dest) {
//Kollar om bufferten är tom
if (!buffer->count){
return 0;
}
//Hämtar element ur buffern till dest
*dest = buffer->buff[buffer->out++];
buffer->count--;
//Justerar pekaren om vi nått slutet
if (buffer->out == BUFFERSIZE)
buffer->out = 0;
return 1;
}
|
C
|
#include "holberton.h"
/**
* clear_bit - function to unset bit
* @n: unsigned long int input
* @index: index of the bit to unset
* Return: 1 if true or -1 if false
*/
int clear_bit(unsigned long int *n, unsigned int index)
{
unsigned long int pow = 1;
unsigned int size = sizeof(n) * 8;
if (*n == '\0')
return (-1);
if (index > size)
return (-1);
pow <<= index;
*n &= ~check;
return (1);
}
|
C
|
#include <unistd.h>
void ft_putchar(char c)
{
write(1, &c, 1);
}
int main(int argc, char**argv)
{
char *str;
int i;
int flg;
flg = 0;
i = 0;
str = argv[1];
if (argc != 2)
ft_putchar('\n');
else
{
while (str[i] == ' ' || str[i] == '\t')
i++;
while(str[i] != '\0')
{
if (str[i] == ' ' || str[i] == '\t')
{
flg = 1;
}
if (str[i] != ' ' && str[i] != '\t')
{
if (flg == 1)
{
ft_putchar(' ');
flg = 0;
}
ft_putchar(str[i]);
}
i++;
}
ft_putchar('\n');
}
return(0);
}
|
C
|
/*5) Escribir en C una función que pida al usuario que ingrese una cadena y la imprima
invertida.
*/
#include<stdio.h>
#include<string.h>
#define MAX_LENGHT 20
void imprimir_invertida(char cadena[], int longitud){
int i;
printf("Longitud:%d\n", longitud);
printf("Cadena invertida:");
for(i = longitud - 1; i != -1; --i){
printf("%c",cadena[i]);
}
printf("\n");
}
int main(){
char cadena[MAX_LENGHT];
printf("Ingrese una cadena:");
fgets(cadena, MAX_LENGHT, stdin);
imprimir_invertida(cadena, strlen(cadena));
return 0;
}
|
C
|
#include "EllipseFit_int.h"
EllipseFloat FitEllipse_int(int32_t *x, int32_t *y, int16_t numberOfPoints)
{
int16_t _i;
// Storage for the scatter matrix. It is a 6x6 symmetrical matrix.
int64_t scatterMatrix[21] = {0};
int64_t S3Determinant = 0;
int64_t T[9] = {0};
// Eigensystem matrix storage.
int64_t M[9] = {0};
// Eigenvectors and eigenvalues storage.
int64_t eigenvalues[3] = {0};
int64_t eigenvector[3] = {0};
static int64_t conicCoefficients[6] = {0};
int32_t _xMean = 0;
int32_t _yMean = 0;
int16_t ellipticalEigenvectorIndex = -1;
int16_t eigenvalueOrderToTry[3] = {1, 0, 2};
EllipseFloat results;
_xMean = findMeanOfCoordinates(x, numberOfPoints);
_yMean = findMeanOfCoordinates(y, numberOfPoints);
// Calculate the T and M matrices needed.
calculateScatterMatrix(x, y, _xMean, _yMean,
numberOfPoints, scatterMatrix);
S3Determinant = calculateMatricesMAndT_int(scatterMatrix, T, M);
// Now we have M, apply eigensolver to get a1 vector.
QRAlgorithm_int(M, eigenvalues);
// Eigenvalues calculated; evaluate which one is elliptical.
// It can be proven that only one eigenvalue will be positive in case
// of elliptical solution; if none fulfills this, then fitting was unsucessful.
for(_i = 0; _i < 3; _i++)
{
// Find the eigenvector to this eigenvalue.
inverseIteration_int(M, eigenvector,
eigenvalues[eigenvalueOrderToTry[_i]]);
if ((4 * eigenvector[0] * eigenvector[2]) -
(eigenvector[1] * eigenvector[1]) > 0.0)
{
ellipticalEigenvectorIndex = eigenvalueOrderToTry[_i];
break;
}
else
{
ellipticalEigenvectorIndex = -1;
}
}
if (ellipticalEigenvectorIndex == -1)
{
// Non-elliptical solution found. Returning empty results.
results.isValid = false;
}
else
{
// Extract the coefficients calculated and find the three last ones.
// Flip the eigenvector to a positive direction in case a negative
// one has been found. This makes the rotation of the ellipse conform.
if (eigenvector[0] < 0)
{
conicCoefficients[0] = -eigenvector[0];
conicCoefficients[1] = -eigenvector[1];
conicCoefficients[2] = -eigenvector[2];
}
else
{
conicCoefficients[0] = eigenvector[0];
conicCoefficients[1] = eigenvector[1];
conicCoefficients[2] = eigenvector[2];
}
conicCoefficients[3] = (conicCoefficients[0] * T[0] +
conicCoefficients[1] * T[1] +
conicCoefficients[2] * T[2]) / S3Determinant;
conicCoefficients[4] = (conicCoefficients[0] * T[3] +
conicCoefficients[1] * T[4] +
conicCoefficients[2] * T[5]) / S3Determinant;
conicCoefficients[5] = (conicCoefficients[0] * T[6] +
conicCoefficients[1] * T[7] +
conicCoefficients[2] * T[8]) / S3Determinant;
// Convert to general form and store this information
// in the output struct.
conicToGeneralForm_int(conicCoefficients, &results);
// Add the previously subtracted mean point.
results.centerX += _xMean;
results.centerY += _yMean;
}
return (results);
}
int64_t calculateMatricesMAndT_int(int64_t *scatterMatrix, int64_t *T, int64_t *M)
{
int64_t _S3Determinant = 0;
// Storage for variables and matrices to calculate on the way to eigensystem matrix.
int64_t _S3Inverse[6] = {0};
_S3Determinant = matrixInverseSymmetric3by3_int(&scatterMatrix[15], _S3Inverse);
calculateTMatrix_int(scatterMatrix, _S3Inverse, T);
_S3Determinant = scaleTMatrix(T, _S3Determinant);
calculateSecondTermOfM_int(scatterMatrix, T, M, _S3Determinant);
calculateCompleteM_int(scatterMatrix, M);
return (_S3Determinant);
}
int64_t matrixInverseSymmetric3by3_int(int64_t *A, int64_t *inverse)
{
// First row of adjoint matrix
inverse[0] = (A[3] * A[5] - (A[4] * A[4]));
inverse[1] = -(A[1] * A[5] - A[4] * A[2]);
inverse[2] = (A[1] * A[4] - A[3] * A[2]);
// Second row of adjoint matrix
inverse[3] = (A[0] * A[5] - (A[2] * A[2]));
inverse[4] = -(A[0] * A[4] - A[1] * A[2]);
// Third row of adjoint matrix
inverse[5] = (A[0] * A[3] - (A[1] * A[1]));
// Return determinant.
return (A[0] * inverse[0] + A[1] * inverse[1] + A[2] * inverse[2]);
}
void calculateTMatrix_int(int64_t *scatterMatrix, int64_t *s3Inverse,
int64_t *T)
{
// First row of T matrix
T[0] = -(s3Inverse[0] * scatterMatrix[3] +
s3Inverse[1] * scatterMatrix[4] +
s3Inverse[2] * scatterMatrix[5]);
T[1] = -(s3Inverse[0] * scatterMatrix[4] +
s3Inverse[1] * scatterMatrix[9] +
s3Inverse[2] * scatterMatrix[10]);
T[2] = -(s3Inverse[0] * scatterMatrix[9] +
s3Inverse[1] * scatterMatrix[13] +
s3Inverse[2] * scatterMatrix[14]);
// Second row of T matrix
T[3] = -(s3Inverse[1] * scatterMatrix[3] +
s3Inverse[3] * scatterMatrix[4] +
s3Inverse[4] * scatterMatrix[5]);
T[4] = -(s3Inverse[1] * scatterMatrix[4] +
s3Inverse[3] * scatterMatrix[9] +
s3Inverse[4] * scatterMatrix[10]);
T[5] = -(s3Inverse[1] * scatterMatrix[9] +
s3Inverse[3] * scatterMatrix[13] +
s3Inverse[4] * scatterMatrix[14]);
// Third row of T matrix
T[6] = -(s3Inverse[2] * scatterMatrix[3] +
s3Inverse[4] * scatterMatrix[4] +
s3Inverse[5] * scatterMatrix[5]);
T[7] = -(s3Inverse[2] * scatterMatrix[4] +
s3Inverse[4] * scatterMatrix[9] +
s3Inverse[5] * scatterMatrix[10]);
T[8] = -(s3Inverse[2] * scatterMatrix[9] +
s3Inverse[4] * scatterMatrix[13] +
s3Inverse[5] * scatterMatrix[14]);
}
int64_t scaleTMatrix(int64_t *T, int64_t S3Determinant)
{
int i;
int64_t maxTValue = -1;
int32_t scale = 0;
for (i = 0; i < 9; i++)
{
if (labs(T[i]) > maxTValue)
{
maxTValue = labs(T[i]);
}
}
// If maximal value is smaller than 2^32, don't do any scaling.
if (maxTValue <= 4294967296L)
{
return (S3Determinant);
}
else if (maxTValue <= 1099511627776L)
{
// If maximal value is (2^32, 2^40], scale by 8 steps.
scale = 8;
}
else if (maxTValue < 281474976710656L)
{
// If maximal value is (2^40, 2^48], scale by 16 steps.
scale = 16;
}
else if (maxTValue < 72057594037927936L)
{
// If maximal value is (2^48, 2^56], scale by 24 steps.
scale = 24;
}
else
{
// If maximal value is (2^56, 2^63], scale by 32 steps.
scale = 32;
}
for (i = 0; i < 9; i++)
{
T[i] = T[i] >> scale;
}
return (S3Determinant >> scale);
}
void calculateSecondTermOfM_int(int64_t *scatterMatrix, int64_t *T,
int64_t *M, int64_t determinant)
{
// First row of second term of M matrix
M[0] = ((T[0] * scatterMatrix[3] +
T[3] * scatterMatrix[4] +
T[6] * scatterMatrix[5]) / determinant);
M[1] = ((T[1] * scatterMatrix[3] +
T[4] * scatterMatrix[4] +
T[7] * scatterMatrix[5]) / determinant);
M[2] = ((T[2] * scatterMatrix[3] +
T[5] * scatterMatrix[4] +
T[8] * scatterMatrix[5]) / determinant);
// Second row of second term of M matrix
M[3] = ((T[0] * scatterMatrix[4] +
T[3] * scatterMatrix[9] +
T[6] * scatterMatrix[10]) / determinant);
M[4] = ((T[1] * scatterMatrix[4] +
T[4] * scatterMatrix[9] +
T[7] * scatterMatrix[10]) / determinant);
M[5] = ((T[2] * scatterMatrix[4] +
T[5] * scatterMatrix[9] +
T[8] * scatterMatrix[10]) / determinant);
// Third row of second term of M matrix
M[6] = ((T[0] * scatterMatrix[9] +
T[3] * scatterMatrix[13] +
T[6] * scatterMatrix[14]) / determinant);
M[7] = ((T[1] * scatterMatrix[9] +
T[4] * scatterMatrix[13] +
T[7] * scatterMatrix[14]) / determinant);
M[8] = ((T[2] * scatterMatrix[9] +
T[5] * scatterMatrix[13] +
T[8] * scatterMatrix[14]) / determinant);
}
void calculateCompleteM_int(int64_t *scatterMatrix, int64_t *M)
{
// Add the two matrices S1 and -S2*S3^{-1}*S2^{T} and perform
// left multiplication with C^{-1} simultaneously.
M[0] = (M[0] + scatterMatrix[0]) / 2;
M[1] = (M[1] + scatterMatrix[1]) / 2;
M[3] = -(M[3] +scatterMatrix[1]);
M[2] = (M[2] + scatterMatrix[2]) / 2;
M[6] = (M[6] + scatterMatrix[2]) / 2;
M[4] = -(M[4] + scatterMatrix[6]);
M[5] = -(M[5] + scatterMatrix[7]);
M[7] = (M[7] + scatterMatrix[7]) / 2;
M[8] = (M[8] + scatterMatrix[11]) / 2;
}
void conicToGeneralForm_int(int64_t *cc, EllipseFloat *results)
{
int64_t givensValues[3];
int64_t sin_t, cos_t;
// Has scaling unity.
int64_t cos_t_squared, sin_t_squared, unity;
int64_t squareComponentsDiff = cc[0] - cc[2];
results->rotationAngle = (float) atan2f((float) cc[1], (float) (cc[0] - cc[2])) / 2;
// First, check if any important vales are equal to zero; if so,
// handle specially to avoid divide by zero errors and unneccessary
// computations and scaling.
if (cc[1] == 0)
{
if (squareComponentsDiff < 0)
{
cos_t = 0;
sin_t = 1;
}
else
{
cos_t = 1;
sin_t = 0;
}
cos_t_squared = 1;
sin_t_squared = 0;
unity = 1;
}
else if (squareComponentsDiff == 0)
{
if (cc[1] < 0)
{
cos_t = 5;
sin_t = -5;
}
else
{
cos_t = 5;
sin_t = 5;
}
cos_t_squared = 25;
sin_t_squared = 25;
unity = 50;
}
else
{
// Use the Givens rotation solution for obtaining the
// double angle cos and sin values given the conic
// coefficients.
givensRotation_int(givensValues, cc[1], cc[0] - cc[2]);
// Use the double angle formula that creates an actual addition inside
// the square root call.
if (givensValues[1] > 0)
{
sin_t = sqrt_int64((uint64_t)
((givensValues[2] + givensValues[1]) >> 1), false);
cos_t = givensValues[0] / (2 * sin_t);
}
else
{
cos_t = sqrt_int64((uint64_t)
(((-givensValues[1]) + givensValues[2]) >> 1), false);
sin_t = givensValues[0] / (2 * cos_t);
}
// Now that we have cos and sin values we establish a new scaling with
// unity value obtained through the sin^2(x) + cos^2(x) = 1
// trigonometric identity.
cos_t_squared = cos_t * cos_t;
sin_t_squared = sin_t * sin_t;
unity = cos_t_squared + sin_t_squared;
}
// Now rotate the conic coefficient representation of the ellipse to
// the canonical representation, i.e. without cross-term B.
// Ends up with scaling unity.
int64_t a_prime = (cc[0] * cos_t_squared) +
(cc[1] * cos_t * sin_t) +
(cc[2] * sin_t_squared);
int64_t c_prime = (cc[0] * sin_t_squared) -
(cc[1] * cos_t * sin_t) +
(cc[2] * cos_t_squared);
// Ends up with scaling sqrt(unity)
int64_t d_prime = (cc[3] * cos_t) + (cc[4] * sin_t);
int64_t e_prime = (-(cc[3] * sin_t)) + (cc[4] * cos_t);
// Now calculate center points in the rotated ellipse coordinate system.
int64_t x_prime_num = (-d_prime);
int64_t x_prime_denom = (2 * a_prime);
int64_t y_prime_num = (-e_prime);
int64_t y_prime_denom = (2 * c_prime);
// Rotate the center points to original coordinate system.
results->centerX = (((float)(x_prime_num * cos_t) / x_prime_denom) -
((float)(y_prime_num * sin_t) / y_prime_denom));
results->centerY = (((float)(x_prime_num * sin_t) / x_prime_denom) +
((float)(y_prime_num * cos_t) / y_prime_denom));
// Now we have to rescale the rotated conic coefficients down a bit,
// since there will be a cubic factors in the axis calculations.
int64_t sqrt_unity = sqrt_int64(unity, false);
a_prime /= unity;
c_prime /= unity;
d_prime /= sqrt_unity;
e_prime /= sqrt_unity;
int64_t numerator = ((-4 * cc[5] * a_prime * c_prime) +
(c_prime * (d_prime * d_prime)) +
(a_prime * (e_prime * e_prime)));
uint64_t tmp_val;
if (a_prime > c_prime)
{
tmp_val = sqrt_int64((numerator /
(4 * a_prime * (c_prime * c_prime))), true);
results->yAxis = convertSqrtToFloat(tmp_val);
tmp_val = sqrt_int64((numerator /
(4 * (a_prime * a_prime) * c_prime)), true);
results->xAxis = convertSqrtToFloat(tmp_val);
}
else
{
tmp_val = sqrt_int64((numerator /
(4 * a_prime * (c_prime * c_prime))), true);
results->xAxis = convertSqrtToFloat(tmp_val);
tmp_val = sqrt_int64((numerator /
(4 * (a_prime * a_prime) * c_prime)), true);
results->yAxis = convertSqrtToFloat(tmp_val);
}
results->isValid = true;
}
/**
* Converts integer square root function output to a floating
* point value.
*/
float convertSqrtToFloat(uint64_t val)
{
return (((float)(val >> 32)) +
((float) ((val & 0xFFFFFFFF))) / 0xFFFFFFFF);
}
|
C
|
#include <stdio.h>
#include <cs50.h>
int main (void)
{
int x=get_int("height: ");
while(x<0 ||x>23)
{
x=get_int("height: ");
}
for(int r=1;r<=x ;r++)
{
for(int i=0;i<x-r;i++)
{
printf(" ");
}
for(int c=0;c<r+1 ;c++)
{
printf("#");
}
printf("\n");
}
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int comp(const void *a,const void *b)
{
return (*(int*)b-*(int*)a);
}
int main()
{
int t,n,sum,a[1000],temp,i;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
temp=0;
while(temp<n)
scanf("%d",&a[temp++]);
qsort(a,temp,sizeof(int),comp);
sum=0;
for(i=2;i<n;i+=3)
sum+=a[i];
printf("%d\n",sum);
}
return 0;
}
|
C
|
#include<string.h>
#include<stdio.h>
long long int findIntermediateResult(long long int a,char o,long long int b)
{
switch(o)
{
case '+': return a+b;
case '-': return a-b;
case '*': return a*b;
}
}
long long int findAnswer(char str[])
{
int i;
long long int answer=0;
i=strlen(str)-1;
answer=findIntermediateResult(str[i]-'0',str[i-1],str[i-2]-'0');
for(i=i-4;i>=0;i-=2)
{
answer=findIntermediateResult(answer,str[i+1],str[i]-'0');
}
return answer;
}
int main()
{
char str[10000];
int t;
scanf("%d",&t);
while(t--)
{
scanf(" %s",str);
printf("%lld",findAnswer(str));
}
return 0;
}
|
C
|
#include <stdio.h>
#define NAME "홍길동"
#define AGE 24
#define PRINT_ADDR puts("주소: 경기도 용인시 \n");
int main(void)
{
printf("이름: %s \n", NAME);
printf("나이: %d \n", AGE);
PRINT_ADDR;
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main()
{
int ret;
char *ttyname0,*ttyname1,*ttyname2;
ttyname0 = ttyname(0);
ttyname1 = ttyname(1);
ttyname2 = ttyname(3);
printf("file0 : %s\n",ttyname0);
printf("file1 : %s\n",ttyname1);
printf("file2 : %s\n",ttyname2);
return 0;
}
|
C
|
/*
j = 0
i = 2
j = 1
i = 4
j = 2;
i = 8
j = 3;
i = 16;
j = 4;
i = 32;
j = 5;
i = 64;
j = 6;
i = 128;
0 || 1 = 0 = w1
1 && 0 == 0 = w2
*/
#include <stdio.h>
int main(void)
{
int Int;
char Char;
short Short;
float Float;
Int = 100;
printf("Int = %i\n", Int);
Char = '$';
printf("Char = %c\n", Char);
Short = Char;
printf("Short = %hi\n", Short);
Int = Short + Char + Float;
printf("Short + Char + Float = %i\n", Int);
Float = Int;
printf("Float = %f\n");
printf("%f", Float);
printf("Answer = %f", Float);
return 0;
}
|
C
|
#include<stdio.h>
void main()
{
char c[20];
printf("Enter the ip address:");
gets(c);
int a=((c[0]-48)*100);
int b=((c[1]-48)*10);
int e=((c[2]-48)*1);
int d=a+b+e;
printf("\na=%d",a);
printf("\nb=%d",b);
printf("\ne=%d",e);
printf("\nd=%d",d);
printf("\n\nip address is:%s\n\n",c);
int i;
i=0;
if (d>=0 && d<=127)
{
printf("Class A\n");
printf("The subnet mask is 255.0.0.0\n");
}
else if(d>=128 && d<=191)
{
printf("Class B\n");
printf("The subnet mask is 255.255.0.0\n");
}
else if(d>=192 && d<=223)
{
printf("Class C\n");
printf("The subnet mask is 255.255.255.0\n");
}
else if(d>=224 && d<=239)
{
printf("Class D\n");
printf("The subnet mask is not defined. Reserved for multicast\n");
}
else if(d>=240 && d<=255)
{
printf("Class E\n");
printf("The subnet mask is not defined. Reserved for research and development\n");
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.