Dataset Viewer
language
large_stringclasses 1
value | src_encoding
large_stringclasses 35
values | length_bytes
int64 6
7.13M
| score
float64 2.52
5.44
| int_score
int64 3
5
| detected_licenses
large listlengths 0
58
| license_type
large_stringclasses 2
values | text
stringlengths 8
7.13M
|
---|---|---|---|---|---|---|---|
C | UTF-8 | 408 | 2.609375 | 3 | [] | no_license | call(unsigned long long int a,unsigned long long int b)
{
/* if(a!=0)
call(b%a,a);
else{
return b;
}or*/
return a==0?b:call(b%a,a);
}
main()
{
unsigned long long int a,b;
int n,pro;
scanf("%d",&n);
scanf("%llu%llu",&a,&b);
// int pro=call(a,b);
for(int i=2;i<n;i++)
{
scanf("%llu",&b);
pro=call(a,b);
a=(a*b)/pro;
}
printf("%d",a);
}
|
C | UTF-8 | 1,212 | 3.078125 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
int main()
{
int a,b,c,d,t,x;
float per;
printf("Enter the marks of four subjects out of 100 ");
scanf("%d %d %d %d",&a,&b,&c,&d);
t=a+b+c+d;
per=t/4;
if((a>b) && (a>c) && (a>d))
{
if ((b>c) && (b>d))
printf("%f %d",per,b);
else if ((c>b) && (c>d))
printf("%f %d",per,c);
else if ((d>b) && (d>c))
printf("%f %d",per,d);
}
else if((b>a) && (b>c) && (b>d))
{
if ((a>c) && (a>d))
printf("%f %d",per,a);
else if ((c>a) && (c>d))
printf("%f %d",per,c);
else if ((d>a) && (d>c))
printf("%f %d",per,d);
}
else if((c>a) && (c>b) && (c>d))
{
if ((a>b) && (a>d))
printf("%f %d",per,a);
else if ((b>a) && (b>d))
printf("%f %d",per,b);
else if ((d>a) && (d>b))
printf("%f %d",per,d);
}
else if((d>a) && (d>b) && (d>c))
{
if ((c>a) && (c>b))
printf("%f %d",per,c);
else if ((b>a) && (b>c))
printf("%f %d",per,b);
else if ((a>b) && (a>c))
printf("%f %d",per,a);
}
return 0;
}
|
C | UTF-8 | 827 | 3.375 | 3 | [] | no_license | #include "time.c"
#include <stdio.h>
int main() {
Calendar *random_calendar = makeRandomCalendar();
//should be 0000-00-00
char *date_time = getDateTime(random_calendar, "YYYY-MM-DD");
puts(date_time);
setDateTimeRandomly(random_calendar);
TIME_COUNT date_time_counter = getDateTimeAsCounter(random_calendar);
if(dateTimeIsBefore(random_calendar, 0)) {
puts("Fail! random time is earlier than the dawn of time!");
}
TIME_COUNT date_time_old_counter = date_time_counter;
advanceTime(random_calendar, YEAR);
if(dateTimeIsAfter(random_calendar, date_time_old_counter)){
puts("Fail! advance (or associated checks) isn't working");
}
rewindTime(random_calendar, YEAR);
if(getDateTimeAsCounter(random_calendar) != date_time_old_counter) {
puts("Fail! rewind isn't working.");
}
return 0;
}
|
C | UTF-8 | 1,192 | 3.375 | 3 | [] | no_license | #include "concurrent_queue_2locks.c"
/* #include "queue.c" */
#include <pthread.h>
void spawnThreads(int n, int x);
void *dummy_function(void *arg);
#define foo 100000
int main(int argc, char *argv[])
{
int n = 6;
int x = 100000;
srand(time(NULL));
initialize_queue();
for (int i = 0; i < 100; i++) {
enqueue(rand());
}
struct timeval t0;
struct timeval t1;
gettimeofday(&t0, NULL);
spawnThreads(n, x);
gettimeofday(&t1, NULL);
long elapsed = (t1.tv_sec - t0.tv_sec) * 1000000 + t1.tv_usec - t0.tv_usec;
printf("Elapsed time: %ld\n", elapsed);
}
void spawnThreads(int n, int x)
{
pthread_t threadIds[n];
for (int i = 0; i < n; ++i) {
printf("Launching thread: %d\n", i);
int *number = malloc(sizeof(*number));
*number = x/n;
pthread_create(&(threadIds[i]), NULL, dummy_function, (void * ) number);
}
for (int i = 0; i < n; ++i) {
pthread_join(threadIds[i], NULL);
}
}
void *dummy_function(void *arg)
{
for (int i = 0; i < *((int *) arg); i ++) {
double coin = ((double) rand() / (RAND_MAX));
if (coin < 0.8) {
enqueue(rand());
}
else {
int val;
dequeue(&val);
}
}
return NULL;
}
|
C | UTF-8 | 1,641 | 2.59375 | 3 | [] | no_license | /*
* RFSwitch433.c
*
* Created on: Jun 30, 2018
* Author: robert
*/
#include <avr/io.h>
#include <util/delay.h>
#include "RF433_SF500.h"
//Kudos to the Arduino NewRFSwitch library for the timings and parts of the code
//Private, send the stoppulse
void send_stoppulse(){
PORTD |= (1<<PD4);
_delay_us(PERIOD_US);
PORTD &= ~(1<<PD4);
_delay_us(PERIOD_US*40);
}
void send_bit(uint8_t bit){
if (bit) {
// Send '1'
PORTD |= (1<<PD4);
_delay_us(PERIOD_US);
PORTD &= ~(1<<PD4);
_delay_us(PERIOD_US * 5);
PORTD |= (1<<PD4);
_delay_us(PERIOD_US);
PORTD &= ~(1<<PD4);
_delay_us(PERIOD_US);
} else {
// Send '0'
PORTD |= (1<<PD4);
_delay_us(PERIOD_US);
PORTD &= ~(1<<PD4);
_delay_us(PERIOD_US);
PORTD |= (1<<PD4);
_delay_us(PERIOD_US);
PORTD &= ~(1<<PD4);
_delay_us(PERIOD_US * 5);
}
}
//Private, send the address of the unit
void send_unit_address(uint8_t unit){
for (int8_t i=3; i>=0; i--) {
send_bit(unit & 1<<i);
}
}
//Private, send the address to the device
void send_address(uint32_t address){
for (int8_t i=25; i>=0; i--) {
send_bit((address >> i) & 1);
}
}
//Private, send start pulse to the device
void send_startpulse(){
PORTD |= (1<<PD4);
_delay_us(PERIOD_US);
PORTD &= ~(1<<PD4);
_delay_us(PERIOD_US * 10 + (PERIOD_US >> 1));
}
void RFS_init(){
//Set the TX pin to output
DDRD |= (1<<PD4);
//Set the TX pin to low
PORTD &= ~(1<<PD4);
}
void RFS_send_unit(uint32_t address, uint8_t unit, uint8_t state){
send_startpulse();
send_address(address);
//No group bit
send_bit(0);
//Send state
send_bit(state);
send_unit_address(unit);
send_stoppulse();
}
|
C | UTF-8 | 1,474 | 3.1875 | 3 | [] | no_license | #include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#include <time.h>
int child_pids[1000];
int parent_hp = 0;
int MAX_CHILDREN = 10;
int numChildren = 0;
void sig_handler_parent(int signum)
{
printf("\nParent: Inside handler function\n");
for(int i = 0; i < numChildren; i ++)
{
kill(child_pids[i], SIGUSR2);
}
exit(0);
}
void sig_handler_child(int signum)
{
printf("\nChild:Inside handler function\n");
printf("parent hp is %d!!!!\n", parent_hp);
//printf("%d", getpid());
printf("Now dying!!!%d\n", getpid());
exit(0);
}
void kidKiller(int kidToKill)
{
sleep(1);
printf("\nenter KILL MODE\n");
//added this 3 due to a weird race condition
sleep(3);
printf("Killed PID: %d\n", kidToKill);
kill(getpid(), SIGKILL);
}
int main()
{
//preset length of array TODO it would be cool not to but I also benefit in capping
//out the number of running procs. just as a saftey net.
time_t t;
srand((unsigned) time(&t));
parent_hp = rand() % 10 + 5;
signal(SIGINT, sig_handler_parent);
while(1)
{
int pid = fork();
if(pid == 0)
{
printf("Another kid born\n");
signal(SIGUSR2, sig_handler_child);
//pause keeps the child alive
pause();
}
else
{
//I am daddy
child_pids[numChildren] = pid;
numChildren ++;
// prevent race condition
sleep(1);
//kill(pid, SIGUSR2);
}
}
return 0;
}
|
C | UTF-8 | 318 | 3.234375 | 3 | [] | no_license | #include<stdio.h>
#include<string.h>
int main()
{
int size = 0;
int i = 0;
char str[50];
char* p_str = NULL;
scanf("%s", str);
size = strlen(str);
p_str = str;
for(i = size; i > 0;)
{
printf("%c", *p_str++);
i--;
if(i%3 == 0 && i > 0)
{
printf(",");
}
}
puts("");
return 0;
} |
C | UTF-8 | 3,323 | 4.4375 | 4 | [
"Apache-2.0"
] | permissive | /**
*
* Implementing Circular Queue
*
**/
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node *next;
};
struct CircularQueue {
struct Node *front;
struct Node *rear;
int size;
};
struct CircularQueue* createCircularQueue(){
struct CircularQueue *queue = (struct CircularQueue *) malloc(sizeof(struct CircularQueue));
queue->front = NULL;
queue->rear = NULL;
queue->size = 0;
return queue;
}
void enqueue(struct CircularQueue *queue, int data){
struct Node *newnode = (struct Node *) malloc(sizeof(struct Node));
newnode->data = data;
/*Check if the queue is empty or not */
if(queue->front == NULL){
queue->front = newnode;
queue->rear = newnode;
newnode->next = newnode;
queue->size++;
return;
}
queue->rear->next = newnode;
queue->rear = newnode;
newnode->next = queue->front;
queue->size++;
}
int dequeue(struct CircularQueue *queue){
/*Check whether the queue is empty or not*/
if(queue->front == NULL){
printf("The Queue is empty\n");
return INT_MIN;
}
/*When the queue has single element*/
if(queue->front == queue->rear){
int del = queue->front->data;
queue->front = NULL;
queue->rear = NULL;
queue->size--;
return del;
}
/*Other case*/
int item = queue->front->data;
queue->front = queue->front->next;
queue->rear->next = queue->front;
queue->size--;
return item;
}
int frontNode(struct CircularQueue *queue){
if(queue->front == NULL){
printf("The queue is empty\n");
return INT_MIN;
}
return queue->front->data;
}
int rearNode(struct CircularQueue *queue){
if(queue->rear == NULL){
printf("The queue is empty\n");
return INT_MIN;
}
return queue->rear->data;
}
void printQueue(struct CircularQueue *queue){
struct Node *temp = queue->front;
int size = queue->size;
printf("The Circular Queue is:\n");
while(size-->0){
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
int main(){
struct CircularQueue *queue = createCircularQueue();
int n, data;
while(1){
printf("Insert an item to queue(1)\n");
printf("Remove item from queue(2)\n");
printf("Retrieve the front item from queue(3)\n");
printf("Retrieve theL last item from queue(4)\n");
printf("Exit(0)\n");
scanf("%d", &n);
switch(n){
case 1:
printf("Enter an item: ");
scanf("%d", &data);
enqueue(queue, data);
printQueue(queue);
break;
case 2:
dequeue(queue);
if(queue->front != NULL){
printQueue(queue);
}
break;
case 3:
printf("%d\n", frontNode(queue));
break;
case 4:
printf("%d\n", rearNode(queue));
break;
case 0:
exit(1);
}
}
return 0;
} |
C | UTF-8 | 139 | 3.03125 | 3 | [] | no_license | #include<stdio.h>
void main()
{
char x,y,z;
x='A';
y=x+7;
printf("the value of x is %c\n",x);
printf("the value of y is %c\n",y);
}
|
C | UTF-8 | 2,098 | 3.84375 | 4 | [] | no_license | //
// lock_3.c - Using a mutex (mutual exclusion lock)
//
// pthread_mutex_lock() - acquire a lock on the specified mutex variable. If the mutex is already locked by another thread,
// this call will block the calling thread until the mutex is unlocked.
//
// pthread_mutex_unlock() - unlock a mutex variable. An error is returned if mutex is already unlocked or owned by another thread.
//
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
//
// input 10 numbers and print them
//
#define MAX_READ 1 // maximun number of readers
#define MAX_WRITE 1 // maximun number of writers
int v[100] = {};
pthread_mutex_t mtx; // a mutex
//
// Readers start routine
//
void* check(void* a)
{
int k = (int)a;
pthread_mutex_lock(&mtx); // lock
for (int i = 0; i < 10; ++i) scanf("%d", &v[i]);
pthread_mutex_unlock(&mtx); // unlock
return NULL;
}
//
// Writers start routine
//
void* buy(void* a)
{
int k = (int)a;
pthread_mutex_lock(&mtx); // lock
int num;
printf("read num to check: ");
scanf("%d", &num);
for (int i = 0; i < 10; ++i)
if (v[i] % num == 0) printf("%d mod %d == 0\n", v[i], num);
printf("end writer -------------\n");
pthread_mutex_unlock(&mtx); // unlock
return NULL;
}
int main(int argc, char* argv[])
{
pthread_t tr[MAX_READ];
pthread_t tw[MAX_WRITE];
pthread_mutex_init(&mtx, NULL); // init the mutex
int i;
for (i = 0; i < MAX_READ; i++)
{
pthread_create(&tr[i], NULL,
check, (void*)i); // create readers
}
for (i = 0; i < MAX_WRITE; i++)
{
pthread_create(&tw[i], NULL,
buy, (void*)i); // create writers
}
for (i = 0; i < MAX_READ; i++)
{
pthread_join(tr[i], NULL); // wait for readers to finish
}
for (i = 0; i < MAX_WRITE; i++)
{
pthread_join(tw[i], NULL); // wait for writers to finish
}
pthread_mutex_destroy(&mtx); // destroy the mutex
return 0;
}
|
C | UTF-8 | 326 | 2.59375 | 3 | [] | no_license | #ifndef DICEGAME_H
#define DICEGAME_H
typedef enum GuessType { REGULAR, BONUS, ELIMINATION } GuessType;
typedef struct Guess
{
int points;
int die1;
int die2;
GuessType type;
} Guess;
void printGuess( Guess g );
void getDice( int* d1, int* d2 );
void fillGuesses( Guess* guesses, int length ) ;
#endif |
C | UTF-8 | 424 | 3.625 | 4 | [] | no_license | #include <stdio.h>
#include <assert.h>
#include <string.h>
int _strlen(const char *s) {
if (s == NULL) return 0;
register const char* c = s;
while (*c) { c++; }
return (c - s);
}
int main(int argc, char ** argv) {
const char *test = "this is a test";
printf("my strlen is %d\n", _strlen(test));
assert(_strlen(test) == strlen(test));
printf("empty strlen is %d\n", _strlen(NULL));
} |
C | UTF-8 | 1,642 | 3.078125 | 3 | [
"MIT"
] | permissive | /*
** malloc.c for malloc in /home/erwan/Code/teck/PSU_2016_malloc
**
** Made by erwan
** Login <[email protected]>
**
** Started on Thu Jan 26 14:08:12 2017 erwan
** Last update Sat Feb 11 16:09:33 2017 Antoine
*/
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/mman.h>
#include <pthread.h>
#include "linked_list.h"
void my_put_nbr(int);
pthread_mutex_t g_mutex = PTHREAD_MUTEX_INITIALIZER;
void *malloc(size_t size)
{
void *ptr;
if (size % 8)
size = ((size / 8) * 8) + 8;
pthread_mutex_lock(&g_mutex);
ptr = searchSlot(size);
pthread_mutex_unlock(&g_mutex);
return (ptr);
}
void free(void *ptr)
{
pthread_mutex_lock(&g_mutex);
free_elem(ptr);
pthread_mutex_unlock(&g_mutex);
}
void *realloc(void *ptr, size_t size)
{
char *res;
char *src;
t_block *scroll;
if (ptr == NULL)
return (malloc(size));
scroll = g_start;
while (scroll && scroll->_end != ptr)
scroll = scroll->_next;
if (scroll != NULL && scroll->_blockSize >= size)
{
pthread_mutex_lock(&g_mutex);
scroll->_effSize = size;
pthread_mutex_unlock(&g_mutex);
return (ptr);
}
src = ptr;
if ((res = malloc(size)) == NULL)
return (NULL);
pthread_mutex_lock(&g_mutex);
res = memcpy(res, src, size);
pthread_mutex_unlock(&g_mutex);
free(ptr);
return (res);
}
void show_alloc_mem()
{
t_block *scroll;
printf("break : %p\n", sbrk(0));
scroll = g_start;
while (scroll)
{
if (scroll->_effSize > 0)
printf("%p - %p : %d\n", scroll->_end,
scroll->_end + scroll->_effSize, (int) scroll->_effSize);
scroll = scroll->_next;
}
}
|
C | UTF-8 | 265 | 2.53125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | #ifndef __AUTH_H__
#define __AUTH_H__
/**
* Uses PAM to authenticate the given user.
*
* @param user User to authenticate.
* @return `0` if the user successfully authenticated, `-1` otherwise.
*/
int auth_authenticate_user(char* user);
#endif
|
C | UTF-8 | 1,813 | 3.484375 | 3 | [
"MIT"
] | permissive | #include <stdio.h>
#include <stdlib.h>
#define NUM_ORGANISMS 3
#define DIMINISHING 0.25
int main(int argc, char* argv[]) {
int organisms[NUM_ORGANISMS];
float pr1[NUM_ORGANISMS] = {0};
float pr2[NUM_ORGANISMS * NUM_ORGANISMS] = {0};
float pr_dom, dim;
int t, i, j;
t = 0;
pr_dom = 0;
dim = 1;
/* Start by getting the number of each organism type */
printf("Homogenous Dominant: ");
scanf("%d", &organisms[0]);
printf("Hetrogenous: ");
scanf("%d", &organisms[1]);
printf("Homogenous Recessive: ");
scanf("%d", &organisms[2]);
/* Compute the total number of organisms */
for( i=0; i<NUM_ORGANISMS; i++ ) {
t += organisms[i];
}
/* For each type of organism, compute the probability that the first
* randomly chosen organism will be of that type */
for( i=0; i<NUM_ORGANISMS; i++) {
pr1[i] = (float)organisms[i]/t;
}
/* Decrement t as we have one less organism to choose from */
t--;
/* Compute the second round of probabilities accounting. What is the
* likelihood that a particular organism type will be chosen given
* that the first choice was of the same or a different type */
for( i=0; i<NUM_ORGANISMS; i++ ) {
for( j=0; j<NUM_ORGANISMS; j++ ) {
pr2[NUM_ORGANISMS*i+j] = (float)( organisms[j] - ((i==j)? 1 : 0))/t;
}
}
/* Compute the probability that a child will have a dominant
* allele */
for( i=0; i<NUM_ORGANISMS; i++ ) {
dim = 1;
for( j=0; j<NUM_ORGANISMS; j++ ) {
pr_dom += pr1[i] * pr2[NUM_ORGANISMS*i + j] * dim;
dim = dim - DIMINISHING*i;
}
}
/* Print the tree for aesthetics */
printf("%.4f\n", 1.0);
for( i=0; i<NUM_ORGANISMS; i++ ) {
printf("\t%.4f\n", pr1[i]);
for( j=0; j<NUM_ORGANISMS; j++ ) {
printf("\t\t%.4f\n", pr2[NUM_ORGANISMS*i + j]);
}
}
/* Print the result */
printf("%.4f\n", pr_dom);
return 0;
}
|
C | UTF-8 | 9,721 | 2.953125 | 3 | [] | no_license | /* This program sums all rows in an array using MPI parallelism.
* The root process acts as a master and sends a portion of the
* array to each child process. Master and child processes then
* all calculate a partial sum of the portion of the array assigned
* to them, and the child processes send their partial sums to
* the master, who calculates a grand total.
*/
#include <mpi.h>
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <unistd.h>
#include <string.h>
#include "plugin.h"
#include "aes.h"
#define DIR_UNKNOWN 0
#define DIR_CIPHER 1
#define DIR_DECIPHER 2
void memprint(uint8_t * ptr, int size, int width) {
int i;
for (i = 0; i < size; ++i) {
printf("%02x ", ptr[i]);
if ( ! ((i+1) % width) )
printf("\n");
}
}
int main(int argc, char **argv)
{
// variables necessary for MPI
int my_id, root, ierr, num_procs;
// variables used for storing cipher settings
char * in_fname = NULL;
char * out_fname = NULL;
int rel_out_fname = 0;
int key_size = 0;
char * key = NULL;
int direction = DIR_UNKNOWN;
char * algo = NULL;
char * generator = NULL;
int verbose = 0;
int failure = 0;
uint8_t genkey[32];
uint8_t * input_buffer;
void * buffer;
aes_global_t data;
lib_hash_t lib_hash;
int failed = 1;
aes_times_t times;
double ela;
/*
* Now replicate this process to create parallel processes.
* From this point on, every process executes a separate copy
* of this program
*/
ierr = MPI_Init(&argc, &argv);
if (ierr != MPI_SUCCESS) {
fprintf(stderr, "OpenMPI initialization failed.\n");
return -1;
}
// set root process number
root = 0;
/* find out MY process ID, and how many processes were started. */
ierr = MPI_Comm_rank(MPI_COMM_WORLD, &my_id);
ierr = MPI_Comm_size(MPI_COMM_WORLD, &num_procs);
if (my_id == root) {
//printf("Spawned %d processes.\n", num_procs);
//fflush(stdout);
if (argc < 2) {
//printUsage(argv[0]);
}
// Parsing console parameters
int c;
while ( (c = getopt(argc, argv, "a:cdg:hk:o:s:v")) != -1) {
switch (c) {
case 'a':
algo = optarg;
break;
case 'c':
if (direction == DIR_DECIPHER) {
printf("Conflicting direction flags specified (-c and -d)!\n");
failed = 2;
break;
} else {
direction = DIR_CIPHER;
}
break;
case 'd':
if (direction == DIR_CIPHER) {
printf("Conflicting direction flags specified (-c and -d)!\n");
failed = 2;
break;
} else {
direction = DIR_DECIPHER;
}
break;
case 'g':
generator = optarg;
break;
case 'h':
//printHelp();
failed = 2;
break;
case 'k':
key = optarg;
break;
case 'o':
if (out_fname) {
printf("Only one -o option allowed!\n");
failed = 2;
break;
} else {
out_fname = optarg;
}
break;
case 's':
key_size = atoi(optarg);
break;
case 'v':
verbose = 1;
break;
case '?':
//printHelp();
failed = 2;
break;
default:
printf("Unknown argument: %c!\n", c);
failed = 2;
break;
}
if (failed == 2)
break;
}
if ( (optind < argc) && (failed < 2) ) {
while (optind < argc) {
if (in_fname) {
printf("Too many input files specified!\n");
break;
} else {
in_fname = argv[optind];
}
optind++;
}
}
if (failed == 2) {
printf("failed.\n");
fflush(stdout);
}
// Checking, if all necessary parameters were set
if (direction == DIR_UNKNOWN && failed < 2) {
printf("Specify either cipher or decipher (-c/-d)!\n");
failed = 2;
}
if (!in_fname && failed < 2) {
printf("No input file specified!\n");
failed = 2;
}
if (!out_fname && failed < 2) {
rel_out_fname = 1;
out_fname = malloc(strlen(in_fname) + 8);
strcpy(out_fname, in_fname);
if (direction == DIR_CIPHER)
strcat(out_fname, ".secret");
else if (direction == DIR_DECIPHER)
strcat(out_fname, ".public");
}
if (key_size != 128 && key_size != 192 && key_size != 256 && failed < 2) {
printf("Key size have to be either 128, 192 or 256 bits!\n");
failed = 2;
}
if (!key && failed < 2) {
printf("Key not specified!\n");
failed = 2;
}
if (!algo) {
algo = "aes";
}
if (!generator) {
generator = "raw";
}
if (verbose && failed < 2) {
printf("Input file: %s\n", in_fname);
printf("Output file: %s\n", out_fname);
printf("Key: %s\n", key);
printf("Key length: %d bits\n", key_size);
printf("Key generator: %s\n", generator);
printf("Algorithm: %s\n", algo);
printf("Direction: %s\n", direction == DIR_CIPHER ? "cipher" : "decipher");
}
// find all required plugins
if (failed < 2 && loadHashPlugin(generator, &lib_hash) != 0) {
printf("Unable to load key generator plugin.\n");
failure = 1;
}
// prepare key from given input
lib_hash.hash(key, genkey, key_size / 8);
if (failed < 2 && verbose) {
printf("Key: ");
memprint(genkey, key_size / 8, key_size / 8);
}
// load data from file, compute all necessary parameters
if(failed < 2)
{
FILE * in_f;
int per_proc;
int rest;
aesInitGlobalData(&data, key_size);
in_f = fopen(in_fname, "rb");
if (in_f == NULL)
perror("Can't open input file!");
// get input file size
fseek(in_f, 0, SEEK_END);
data.in_size = ftell(in_f);
if (direction == DIR_DECIPHER)
data.in_size -= 8;
data.in_blocks = (uint32_t) ceil(1.0 * data.in_size / data.block_size);
data.in_blocks = (uint32_t) ceil(1.0 * data.in_blocks / num_procs) * num_procs;
fseek(in_f, 0, SEEK_SET);
per_proc = data.in_blocks / num_procs;
rest = data.in_blocks % num_procs;
//printf("Input file has %d bytes, which is %d blocks.\n", data.in_size, data.in_blocks);
//printf("Each of %d processes will have %d blocks in buffer (%d blocks left).\n", num_procs, per_proc, rest);
data.in_blocks /= num_procs;
// allocate memory for input buffer
input_buffer = (uint8_t *) malloc(data.in_blocks * data.block_size * num_procs);
if (input_buffer == NULL)
{
fclose(in_f);
perror("Can't allocate memory for input buffer!");
}
if (direction == DIR_CIPHER) {
data.nonce_0 = time(NULL);
data.nonce_1 = 1;
} else {
fread(&(data.nonce_0), sizeof(uint32_t), 1, in_f);
fread(&(data.nonce_1), sizeof(uint32_t), 1, in_f);
}
// load file content into buffer
if (data.in_size != fread(input_buffer, sizeof(uint8_t), data.in_size, in_f))
{
free(input_buffer);
fclose(in_f);
perror("Can't read input file to buffer!");
}
fclose(in_f);
failed = 0;
}
}
// end of data preparation
// ---------------------------------------------------------------------------------
// WARNING! MAGIC SECTION BEGINS HERE!!
// ---------------------------------------------------------------------------------
if (my_id == root) {
clock_gettime(CLOCK_REALTIME, &(times.t0));
}
// broadcast global data to all processes
MPI_Bcast(&key_size, 1, MPI_INT, root, MPI_COMM_WORLD);
MPI_Bcast(&direction, 1, MPI_INT, root, MPI_COMM_WORLD);
MPI_Bcast(genkey, key_size/8, MPI_BYTE, root, MPI_COMM_WORLD);
MPI_Bcast(&data.in_blocks, 4, MPI_BYTE, root, MPI_COMM_WORLD);
MPI_Bcast(&data.nonce_0, 4, MPI_BYTE, root, MPI_COMM_WORLD);
MPI_Bcast(&data.nonce_1, 4, MPI_BYTE, root, MPI_COMM_WORLD);
aesInitGlobalData(&data, key_size);
// allocate data buffer for each process
//buffer = malloc(data.in_blocks * data.block_size);
//MPI_Buffer_attach (buffer, data.in_blocks * data.block_size);
data.in_data = malloc(data.in_blocks * data.block_size);
aesKeyExpansion(&data, genkey);
// scatter data to all processes
MPI_Scatter(input_buffer, data.in_blocks*data.block_size, MPI_BYTE, data.in_data, data.in_blocks*data.block_size, MPI_BYTE, root, MPI_COMM_WORLD);
if (my_id == root) {
clock_gettime(CLOCK_REALTIME, &(times.t1));
}
// process data - cipher/decipher given block
aesCipherT(&data);
if (my_id == root) {
clock_gettime(CLOCK_REALTIME, &(times.t2));
}
// return processed data
MPI_Gather(data.in_data, data.in_blocks*data.block_size, MPI_BYTE, input_buffer, data.in_blocks*data.block_size, MPI_BYTE, root, MPI_COMM_WORLD);
if (my_id == root) {
clock_gettime(CLOCK_REALTIME, &(times.t3));
aesPrintTimes(times);
}
// ---------------------------------------------------------------------------------
// NOTE: Chill out, all the magic is gone now.
// ---------------------------------------------------------------------------------
// store processed file
if (my_id == root) {
{
FILE * out_f;
out_f = fopen(out_fname, "wb");
if (out_f == NULL)
printf("Can't open output file!\n");
if (direction == DIR_CIPHER) {
fwrite(&(data.nonce_0), sizeof(uint32_t), 1, out_f);
fwrite(&(data.nonce_1), sizeof(uint32_t), 1, out_f);
}
// write output buffer into file
if (data.in_size != fwrite(input_buffer, sizeof(uint8_t), data.in_size, out_f))
{
fclose(out_f);
perror("Can't store output file!");
}
fclose(out_f);
}
free(input_buffer);
unloadHashPlugin(&lib_hash);
}
free(data.in_data);
ierr = MPI_Finalize();
return 0;
}
|
C | UTF-8 | 332 | 2.984375 | 3 | [] | no_license | /* atexit function */
#include <stdlib.h>
/* external declarations */
extern void (*_Atfuns[])(void);
extern size_t _Atcount;
int (atexit)(void (*func)(void))
{ /* function to call at exit */
if (_Atcount == 0)
return (-1); /* list is full */
_Atfuns[--_Atcount] = func;
return (0);
}
|
C | UTF-8 | 17,317 | 2.5625 | 3 | [] | no_license | #include <types.h>
#include <kern/errno.h>
#include <kern/fcntl.h>
#include <kern/limits.h>
#include <kern/stat.h>
#include <kern/seek.h>
#include <lib.h>
#include <uio.h>
#include <thread.h>
#include <current.h>
#include <synch.h>
#include <vfs.h>
#include <vnode.h>
#include <file.h>
#include <syscall.h>
#include <copyinout.h>
#include <limits.h>
#include <kern/unistd.h>
#include <kern/fcntl.h>
#include<kern/seek.h>
//create an of_table at boot
int of_table_init(void){
//char c0[] = "con:";
char c1[] = "con:";
char c2[] = "con:";
int result = 0;
int retval;
// step 1: Create the current threads t_file_table using create_file_table
curthread->t_file_table = create_file_table();
if (curthread->t_file_table == NULL){
return EFAULT;
}
/*
// open fd 0
struct single_file *sf0 = create_single_file(c0, O_RDONLY, 0);
if (sf0 == NULL){
return ENOMEM;
}
result = put_file_in_filetable(sf0, &retval);
if (result){
return result;
}
result = vfs_open(c0, O_RDONLY, 0, &sf0->vn);
if (result){
return result;
}
*/
// open fd 1
struct single_file *sf1 = create_single_file(c1, O_WRONLY, 0);
if (sf1 == NULL){
return ENOMEM;
}
result = put_file_in_filetable(sf1, &retval);
if (result){
return result;
}
/* result = vfs_open(c1, O_WRONLY, 0, &sf1->vn);
if (result){
return result;
} */
// open fd 2
struct single_file *sf2 = create_single_file(c2, O_WRONLY, 0);
if (sf2 == NULL){
return ENOMEM;
}
result = put_file_in_filetable(sf2, &retval);
if (result){
return result;
}
/* result = vfs_open(c2, O_WRONLY, 0, &sf2->vn);
if (result){
return result;
} */
return 0;
}
struct single_file * create_single_file (char* dest, int flags, mode_t mode){
/*
struct single_file {
struct vnode * vn; //vnode corresponding to each file
off_t file_pointer_offset; //offset to the starting point
int permissions;
struct lock *f_lock; //file lock in case two process access to the same file leading to race condition
};
*/
//kprintf("create_single_file func is triggered\n");
int result;
struct vnode *node;
//step 4: pass the dest/flags/new_node to the vfs_open function
//kprintf("before vfs_open\n");
//kprintf ("The inputs are dest %s, flags %d\n", dest, flags);
result = vfs_open(dest, flags, mode, &node);
if (result){//if result is not 0 (unsuccessful, it's error code)
return NULL;
} //if result is 0 (successful), now we have obtained vnode info stored in new_node
//kprintf("Step 4 finished\n");
struct single_file * f = kmalloc(sizeof(struct single_file));
if (f == NULL){
//return ENOMEM;
return NULL;
}
//kprintf("file memory allocation finished\n");
f -> vn = node;
f -> file_pointer_offset = 0; //new file, start from beginning
f -> permissions = flags & O_ACCMODE;
KASSERT((f -> permissions == O_RDONLY) ||
(f -> permissions == O_WRONLY) ||
(f -> permissions == O_RDWR));
f -> f_lock = lock_create("lock created");
if (f -> f_lock == NULL){
return NULL;
}
return f;
}
/*
int delete_single_file(struct single_file *sf){
kfree(sf);
return 0;
}
*/
struct file_table * create_file_table (void){
struct file_table * new_ft = kmalloc(sizeof(struct file_table));
if (new_ft == NULL){
//return ENOMEM; //malloc error
return NULL;
}
for (int j = 0; j < __OPEN_MAX; j++){
new_ft -> multi_opens[j] = NULL;//initialization of a file_table
}
return new_ft;
}
int put_file_in_filetable(struct single_file * sf, int * retval){//if successfully, store fd in ret
//step 1: check if both pointers are valid
lock_acquire(sf -> f_lock);// one process should get access to ft at one time
//kprintf("put_file_in_filetable has acquired the lock\n");
if (sf == NULL){
lock_release(sf -> f_lock);
//kprintf("put_file_in_filetable has released the lock\n");
return ENOMEM;//should be memory allocation error while creating them
}
//step 2: now put the single_file into the file_table
for (int fd = 1; fd < __OPEN_MAX; fd++){
if (curthread->t_file_table-> multi_opens[fd] == NULL){//find the lowest available fd number
curthread->t_file_table-> multi_opens[fd] = sf; //also store the single file pointer into the multi_opens, notice that we use fd as index to indicate files
//kprintf("inserting file %d in file table\n", fd);
*retval = fd;//this is the fd we put in retval
//kprintf("the returned value is %d\n", *retval);
lock_release(sf -> f_lock);
//kprintf("put_file_in_filetable has released the lock\n");
return 0;//successful, return 0
}
// if we iterate through the entire file table and the last file in the
// table is taken, then the process's file table is full and return EMFILE
if ((fd == __OPEN_MAX - 1) && curthread->t_file_table-> multi_opens[fd] != NULL){
return EMFILE;
}
}
lock_release(sf->f_lock);
//kprintf("put_file_in_filetable has released the lock\n");
return 0;
}
// function to check if the file table is full or not. Used for returning EMFILE
int ft_isfull(void){
for (int fd = 1; fd < __OPEN_MAX; fd++){
if (curthread->t_file_table-> multi_opens[fd] == NULL){
return 0;
}
}
return EMFILE;
}
int check_valid_fd(int file_d){
//step 1: check if the user provided fd is a valid number
if ((file_d < 0) || (file_d >= __OPEN_MAX)){//smaller than 0 or bigger than max_open is invalid
return EBADF;
}
// step 2: is the file in the of_table?
struct file_table * cur_ft;
cur_ft = curthread -> t_file_table;
if (!cur_ft){
//file is not opened
return ENOENT;//no such file error
}
//step 3: since file is opened, is the fd correct?
if (cur_ft -> multi_opens[file_d] == NULL){
//invalid fd number
return EBADF;
}
return 0;
}
// ------------------------------------------major functions-----------------------------------------------
// sys_open
int sys_open (userptr_t filename, int flags, mode_t mode, int * retval){
//step 1: check if file name is safe input
//kprintf("sys_open is called\n");
char dest[__NAME_MAX];
//size_t actual;
int result;
// "If O_CREATE and O_EXCL are set, open shall fail if the file exists"
if (flags & ( O_EXCL & O_CREAT)){
return EEXIST;
}
// return an error if filename is an invalid pointer
if (!(char *)filename){
return EFAULT;
}
result = copyinstr(filename, dest, sizeof(dest), NULL);
if (result){
return result; //invalid filename is handled here
}
//kprintf("the current file is %s\n", dest);
//kprintf("step 1 finished\n");
//step 3: create a single new file
struct single_file * sf = create_single_file(dest, flags, mode);
if (sf == NULL){
return ENOMEM;//should be memory allocation error if single_file is not created successfully
}
//kprintf("step 3 finished\n");
//step 5: place the single file in filetable
struct file_table * cur_ft = curthread -> t_file_table;//get current file table
if (cur_ft == NULL){
return -1;//error handling if we cannot find t_file_table in the current thread
}
//kprintf("step 5 finished\n");
// step 6: return from sys_open the resulting fd number to the caller. If this fails, then return an error in step 7
result = put_file_in_filetable(sf, retval);//sf refer back to step 4, fd is also updated
//kprintf("in sys_open the returned value is %d\n", *retval);
if (result){
return result;
}
// step 7: if the single file is not placed in the filetable, return -1
return 0;
}
int sys_close(int file_d){
//step 1: check if the file_d is valid
int result = check_valid_fd(file_d);
if (result){
return result;
}
//step 2: get the current file table
struct file_table * cur_ft = curthread -> t_file_table;
//step 3: get current file and current vnode
struct single_file * cur_file = cur_ft -> multi_opens[file_d];
struct vnode * node = cur_file -> vn;
//step 4: delete single file and erase its record in the file table
//delete the single file
/*
result = delete_single_file(cur_file);//free the memory
if (result){
return result;
}
*/
//step 6: check how many times the file is opened. If 1, clean the vnode, otherwise, just decrement the open count
lock_acquire(cur_file -> f_lock);
//kprintf("sys_close has acquired the lock\n");
int open_counts = cur_file -> vn -> vn_refcount;
if (open_counts > 1){ // opened more than once
node -> vn_refcount --;
} else if (open_counts == 1){
//kprintf("the file is opened once\n");
vfs_close(node);//this will decref the vnode's refcount by 1
//kprintf("The current open %d is \n", cur_file -> vn -> vn_refcount);
} else {
lock_release(cur_file -> f_lock);
//kprintf("sys_close has released the lock\n");
lock_destroy(cur_file -> f_lock);
return -1;
}
cur_ft -> multi_opens[file_d] = NULL;//erase the single file from the multi_opens array in file_table
cur_file ->file_pointer_offset = 0;//clean the offset
cur_file ->vn = NULL;
lock_release(cur_file -> f_lock);
lock_destroy(cur_file -> f_lock);
cur_file = NULL;
//kprintf("sys_close has released the lock\n");
return 0;
}
//sys_read
int sys_read(int file_d, userptr_t buf, size_t buflen, int * retval){//store the size in retval
//step 1: check if the file_d is valid
int result = check_valid_fd(file_d);
if (result){
return result;
}
// if buf is invalid, return an EFAULT
if (!buf){
return EFAULT;
}
//step 2: get the current file table
struct file_table * cur_ft = curthread -> t_file_table;
//step 3: read from vnode in vfs
//step 3.0 get the file and check permission
struct single_file * f2_read = cur_ft -> multi_opens[file_d];
lock_acquire(f2_read -> f_lock);
//kprintf("sys_read has acquired the lock\n");
if (((f2_read -> permissions) & O_ACCMODE) == O_WRONLY){
lock_release(f2_read -> f_lock);
//kprintf("sys_read has released the lock\n");
return EBADF; //permission denied
}
//step 3.1: get the vnode from cur_ft (also get the single_file)
struct vnode * node = f2_read -> vn; //get the current vnode
//step 3.2: create a uio data struct and initialize it calling the uio_uinit func
struct uio u;
struct iovec iov;
off_t cur_offset = f2_read -> file_pointer_offset;//get the current offset
uio_kinit(&iov, &u, buf, buflen, cur_offset, UIO_READ);//knitilize a uio, this is read from kernel to user
//step 3.3 use vfs op to reach data
result = VOP_READ(node, &u);
if (result){
lock_release(f2_read -> f_lock);
//kprintf("sys_read has released the lock\n");
return result;
}
// the return value is the original buff size minus the residual size
*retval = buflen - u.uio_resid;
f2_read -> file_pointer_offset += *retval; //update current file pointer
lock_release(f2_read -> f_lock);
//kprintf("sys_read has released the lock\n");
return 0;
}
//sys_write
int sys_write(int fd, userptr_t buf, size_t nbytes, int *retval){
//kprintf("sys_write is called\n");
// write requires a vnode to operate on, which requires an uio struct for operation metadata
struct iovec iov;
struct uio u;
int result;
// step 1: Search the current filetable to see if the input file descriptor is valid
// if buf is invalid, return an EFAULT
if (!buf){
return EFAULT;
}
// check if the current fd exists, return an error if it doesnt
result = check_valid_fd(fd);
if (result){
return result;
}
// if the current fd is opened as read only, return EBADF
if (curthread->t_file_table->multi_opens[fd]->permissions == O_RDONLY){
return EBADF;
}
// step 3: Acquire a lock on the file so that no two processes can write at the same time. This requires synchronisation
// as there may be many processes that open a file, each updating the file pointer at any given time.
lock_acquire(curthread->t_file_table->multi_opens[fd]->f_lock);
//kprintf("sys_write has acquired the lock\n");
// if valid, get the current files file pointer offset
off_t file_offset = curthread->t_file_table->multi_opens[fd]->file_pointer_offset;
// step 4: construct a uio for write
uio_uinit(&iov, &u, buf, nbytes, file_offset, UIO_WRITE);
// step 5: Check if the right write permission is valid on the file
if (curthread->t_file_table->multi_opens[fd]->permissions == O_RDONLY){
// As per Man Pages, EBADF is returned if the file is not opened for writing
lock_release(curthread->t_file_table->multi_opens[fd]->f_lock);
//kprintf("sys_write has released the lock\n");
return EBADF;
}
result = VOP_WRITE(curthread->t_file_table->multi_opens[fd]->vn, &u);
if (result){
lock_release(curthread->t_file_table->multi_opens[fd]->f_lock);
//kprintf("sys_write has released the lock\n");
return result;
}
// step 6: update the file pointer offset. The uio struct keeps track of how much is written.
curthread->t_file_table->multi_opens[fd]->file_pointer_offset = u.uio_offset;
//lock_release(curthread->t_file_table->multi_opens[fd]->offset_lock); test test test
lock_release(curthread->t_file_table->multi_opens[fd]->f_lock);
// step 7: Record the amount of bytes written and save it in the return value. The amount written is the buffer length
// nbytes minus the residual amount that was not written in the uio struct
//kprintf("sys_write has release the lock\n");
//kprintf("sys_write is done\n");
*retval = nbytes - u.uio_resid;
return 0;
}
int dup2(int oldfd, int newfd, int *retval){
//kprintf("dup2 is triggered\n");
int result;
// "Using dup2 to clone a file handle onto itself has no effect" (Man Pages)
if (oldfd == newfd){
return 0;
}
// check if the file table is full
result = ft_isfull();
if (result){
return result;
}
//step 2: check if the old and new fds are valid (if they're already in the file_table)
result = check_valid_fd(oldfd);
if (result){
return result;
}
//step 3: check if the newfd is out of range or if some other file is already in the place of newfd's intended position
// we don't want it override other file's record
struct file_table * cur_ft = curthread -> t_file_table;
if ((newfd < 0) || (newfd >= __OPEN_MAX)){
return EBADF;
}
//step 4: now we can safely copy the handler
struct single_file * cur_file = cur_ft -> multi_opens[oldfd];
//step 4.1: firstly we need to manually increment the refcount in vnode
lock_acquire(cur_file ->f_lock);
cur_file -> vn -> vn_refcount ++;
//step 4.2: then we put the file into the new position
cur_ft -> multi_opens[newfd] = cur_file;
lock_release(cur_file ->f_lock);
*retval = newfd;
return 0;
}
int sys_lseek(int fd, int pos, int whence, off_t * retval){
//step 1: check if fd is valid and get the vnode
int result = check_valid_fd(fd);
if (result){
return result;
}
//step 2: check if the file fd points to is seekable
struct vnode * node = curthread ->t_file_table ->multi_opens[fd] ->vn;
result = VOP_ISSEEKABLE(node);
if (result == false){
return ESPIPE;
}
//step 3: check if whence is valid
if ((whence != SEEK_CUR) && (whence != SEEK_END) && (whence != SEEK_SET)){
return EINVAL;
}
//step 4 get current file
struct single_file * cur_file = curthread -> t_file_table ->multi_opens[fd];
lock_acquire(cur_file ->f_lock);
//step 5 check whence
if (whence == SEEK_SET){
*retval = pos;
} else if (whence == SEEK_CUR){
*retval = pos + cur_file->file_pointer_offset;
} else {//SEEK_END
off_t file_size;
struct stat * target_file_stat = NULL;
result = VOP_STAT(node, target_file_stat);
if (result){
lock_release(cur_file->f_lock);
return result;
}
file_size = target_file_stat->st_size;
*retval = pos + file_size;
}
cur_file ->file_pointer_offset = *retval;
lock_release(cur_file->f_lock);
return 0;
}
void sys_exit(void){
panic("Syscall 3 (sys_exit) called\n");
}
|
C | UTF-8 | 494 | 2.84375 | 3 | [] | no_license | #ifndef __QUEUE_ARRAY_H__
#define __QUEUE_ARRAY_H__
#include <stdio.h>
// FIFO Queue using circular arrays
typedef struct QueueArray {
void** q;
int first;
int last;
int cap;
int dim;
} QueueArray;
// initialize the queue
void init_queue_array (QueueArray*, int);
// enqueue the queue
void enqueue_array (QueueArray*, void*, size_t);
// dequeue the queue
void* dequeue_array (QueueArray*);
// vierifies whether the queue is empty or not
int empty_queue_array (QueueArray);
#endif
|
C | UTF-8 | 257 | 3.40625 | 3 | [] | no_license | #include<stdio.h>
int main()
{
int times=10;
float high=100,lenght=0,temp=0;
while(times)
{
lenght+=2*high;
high/=2;
times--;
}
lenght-=100;
printf("10th's height is %f\n",high);
printf("10th's lenght is %f\n",lenght);
return 0;
}
|
C | UTF-8 | 860 | 3.8125 | 4 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define N 10
#define NULL_PTHREAD 0
pthread_t tid[N];//Array of threads' id
void* thread_do(void *arg){
pthread_t id=pthread_self();
int i;
for(i=0;i<N;i++){//Try to find myself in array of threads' id
if(pthread_equal(id,tid[i])){
printf("Hello, I'm thread %d\n",i);
break;
}
}
}
int main(){
int i;
for(i=0;i<N;i++){
pthread_create(&(tid[i]),NULL,&thread_do,NULL);//Creating new thread and saving its id into tid[i]
printf("Thread %d is created\n",i);
pthread_join(tid[i],NULL);//Wait until i-th thread finish execution. If we remove this line, threads' outputs will be shuffled.
tid[i]=NULL_PTHREAD;//If we won't do this, then next thread will most possibly get id equal to id of previous thread, and all threads will recognize themselves as 0-th thread.
}
return 0;
}
|
C | UTF-8 | 3,987 | 2.578125 | 3 | [] | no_license | /* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __STM32F4xx_HAL_GPIO_H
#define __STM32F4xx_HAL_GPIO_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "stm32f4xx_hal_def.h"
#include "stm32f4xx_hal_gpio_ex.h"
/**
* @brief GPIO Bit SET and Bit RESET enumeration
*/
typedef enum
{
GPIO_PIN_RESET = 0,
GPIO_PIN_SET
} GPIO_PinState;
#define GPIO_MODE_OUTPUT_PP ((uint32_t)0x00000001U) /*!< Output Push Pull Mode */
#define GPIO_MODE_AF_PP ((uint32_t)0x00000002U) /*!< Alternate Function Push Pull Mode */
#define GPIO_NOPULL ((uint32_t)0x00000000U) /*!< No Pull-up or Pull-down activation */
#define GPIO_PULLUP ((uint32_t)0x00000001U) /*!< Pull-up activation */
/** @defgroup GPIO_pins_define GPIO pins define
* @{
*/
#define GPIO_SPEED_FREQ_LOW ((uint32_t)0x00000000U) /*!< IO works at 2 MHz, please refer to the product datasheet */
#define GPIO_SPEED_FREQ_HIGH ((uint32_t)0x00000002U) /*!< range 25 MHz to 100 MHz, please refer to the product datasheet */
#define GPIO_PIN_0 ((uint16_t)0x0001U) /* Pin 0 selected */
#define GPIO_PIN_1 ((uint16_t)0x0002U) /* Pin 1 selected */
#define GPIO_PIN_2 ((uint16_t)0x0004U) /* Pin 2 selected */
#define GPIO_PIN_3 ((uint16_t)0x0008U) /* Pin 3 selected */
#define GPIO_PIN_4 ((uint16_t)0x0010U) /* Pin 4 selected */
#define GPIO_PIN_5 ((uint16_t)0x0020U) /* Pin 5 selected */
#define GPIO_PIN_6 ((uint16_t)0x0040U) /* Pin 6 selected */
#define GPIO_PIN_7 ((uint16_t)0x0080U) /* Pin 7 selected */
#define GPIO_PIN_8 ((uint16_t)0x0100U) /* Pin 8 selected */
#define GPIO_PIN_9 ((uint16_t)0x0200U) /* Pin 9 selected */
#define GPIO_PIN_10 ((uint16_t)0x0400U) /* Pin 10 selected */
#define GPIO_PIN_11 ((uint16_t)0x0800U) /* Pin 11 selected */
#define GPIO_PIN_12 ((uint16_t)0x1000U) /* Pin 12 selected */
#define GPIO_PIN_13 ((uint16_t)0x2000U) /* Pin 13 selected */
#define GPIO_PIN_14 ((uint16_t)0x4000U) /* Pin 14 selected */
#define GPIO_PIN_15 ((uint16_t)0x8000U) /* Pin 15 selected */
#define GPIO_PIN_All ((uint16_t)0xFFFFU) /* All pins selected */
#define GPIO_PIN_MASK ((uint32_t)0x0000FFFFU) /* PIN mask for assert test */
/**
* @}
*/
/**
* @brief GPIO Init structure definition
*/
typedef struct
{
uint32_t Pin; /*!< Specifies the GPIO pins to be configured.
This parameter can be any value of @ref GPIO_pins_define */
uint32_t Mode; /*!< Specifies the operating mode for the selected pins.
This parameter can be a value of @ref GPIO_mode_define */
uint32_t Pull; /*!< Specifies the Pull-up or Pull-Down activation for the selected pins.
This parameter can be a value of @ref GPIO_pull_define */
uint32_t Speed; /*!< Specifies the speed for the selected pins.
This parameter can be a value of @ref GPIO_speed_define */
uint32_t Alternate; /*!< Peripheral to be connected to the selected pins.
This parameter can be a value of @ref GPIO_Alternate_function_selection */
}GPIO_InitTypeDef;
void HAL_GPIO_TogglePin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin);
void HAL_GPIO_Init(GPIO_TypeDef *GPIOx, GPIO_InitTypeDef *GPIO_Init);
GPIO_PinState HAL_GPIO_ReadPin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin);
void HAL_GPIO_WritePin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin, GPIO_PinState PinState);
#ifdef __cplusplus
}
#endif
#endif /* __STM32F4xx_HAL_GPIO_H */
|
C | UTF-8 | 3,504 | 2.953125 | 3 | [] | no_license | //
// Node.c
// SimpleDatabase
//
// Created by 顾超 on 2020/05/09.
// Copyright © 2020 Chao Gu. All rights reserved.
//
#include <stdlib.h>
#include <string.h>
#include "Node.h"
#include "Row.h"
#include "Table.h"
#include "Cursor.h"
#include "Pager.h"
typedef enum NodeType {
NODE_INTERNAL,
NODE_LEAF
} NodeType;
/*
* Common Node Header Layout
*/
const uint32_t NODE_TYPE_SIZE = sizeof(uint8_t);
const uint32_t NODE_TYPE_OFFSET = 0;
const uint32_t IS_ROOT_SIZE = sizeof(uint8_t);
const uint32_t IS_ROOT_OFFSET = NODE_TYPE_SIZE;
const uint32_t PARENT_POINTER_SIZE = sizeof(uint32_t);
const uint32_t PARENT_POINTER_OFFSET = IS_ROOT_OFFSET + IS_ROOT_SIZE;
const uint8_t COMMON_NODE_HEADER_SIZE =
NODE_TYPE_SIZE + IS_ROOT_SIZE + PARENT_POINTER_SIZE;
/*
* Leaf Node Header Layout
*/
const uint32_t LEAF_NODE_NUM_CELLS_SIZE = sizeof(uint32_t);
const uint32_t LEAF_NODE_NUM_CELLS_OFFSET = COMMON_NODE_HEADER_SIZE;
const uint32_t LEAF_NODE_HEADER_SIZE =
COMMON_NODE_HEADER_SIZE + LEAF_NODE_NUM_CELLS_SIZE;
/*
* Leaf Node Body Layout
*/
const uint32_t LEAF_NODE_KEY_SIZE = sizeof(uint32_t);
const uint32_t LEAF_NODE_KEY_OFFSET = 0;
uint32_t LEAF_NODE_VALUE_SIZE() { return ROW_SIZE; }
const uint32_t LEAF_NODE_VALUE_OFFSET =
LEAF_NODE_KEY_OFFSET + LEAF_NODE_KEY_SIZE;
uint32_t LEAF_NODE_CELL_SIZE() { return LEAF_NODE_KEY_SIZE + LEAF_NODE_VALUE_SIZE(); }
uint32_t LEAF_NODE_SPACE_FOR_CELLS() { return PAGE_SIZE - LEAF_NODE_HEADER_SIZE; }
uint32_t LEAF_NODE_MAX_CELLS() { return LEAF_NODE_SPACE_FOR_CELLS() / LEAF_NODE_CELL_SIZE(); }
uint32_t* leaf_node_num_cells(void* node) {
return node + LEAF_NODE_NUM_CELLS_OFFSET;
}
void* leaf_node_cell(void* node, uint32_t cell_num) {
return node + LEAF_NODE_HEADER_SIZE + cell_num * LEAF_NODE_CELL_SIZE();
}
uint32_t* leaf_node_key(void* node, uint32_t cell_num) {
return leaf_node_cell(node, cell_num);
}
void* leaf_node_value(void* node, uint32_t cell_num) {
return leaf_node_cell(node, cell_num) + LEAF_NODE_KEY_SIZE;
}
void initialize_leaf_node(void* node) { *leaf_node_num_cells(node) = 0; }
void leaf_node_insert(Cursor* cursor, uint32_t key, Row* value) {
void* node = get_page(cursor->table->pager, cursor->page_num);
uint32_t num_cells = *leaf_node_num_cells(node);
if (num_cells >= LEAF_NODE_MAX_CELLS()) {
// Node full
printf("Need to implement splitting a leaf node.\n");
exit(EXIT_FAILURE);
}
if (cursor->cell_num < num_cells) {
// Make room for new cell
for (uint32_t i = num_cells; i > cursor->cell_num; i--) {
memcpy(leaf_node_cell(node, i), leaf_node_cell(node, i - 1), LEAF_NODE_CELL_SIZE());
}
}
*(leaf_node_num_cells(node)) += 1;
*(leaf_node_key(node, cursor->cell_num)) = key;
serialize_row(value, leaf_node_value(node, cursor->cell_num));
}
void print_constants() {
printf("ROW_SIZE: %d\n", ROW_SIZE);
printf("COMMON_NODE_HEADER_SIZE: %d\n", COMMON_NODE_HEADER_SIZE);
printf("LEAF_NODE_HEADER_SIZE: %d\n", LEAF_NODE_HEADER_SIZE);
printf("LEAF_NODE_CELL_SIZE: %d\n", LEAF_NODE_CELL_SIZE());
printf("LEAF_NODE_SPACE_FOR_CELLS: %d\n", LEAF_NODE_SPACE_FOR_CELLS());
printf("LEAF_NODE_MAX_CELLS: %d\n", LEAF_NODE_MAX_CELLS());
}
void print_leaf_node(void* node) {
uint32_t num_cells = *leaf_node_num_cells(node);
printf("leaf (size %d)\n", num_cells);
for (uint32_t i = 0; i < num_cells; i++) {
uint32_t key = *leaf_node_key(node, i);
printf(" - %d : %d\n", i, key);
}
}
|
C | UTF-8 | 577 | 2.953125 | 3 | [] | no_license | /*
** rm_good_env.c for rm_good_env in /u/epitech_2012/jaspar_y/cu/rendu/c/minishell/v1
**
** Made by yoann jaspar
** Login <[email protected]>
**
** Started on Thu Feb 28 15:56:29 2008 yoann jaspar
** Last update Tue Jun 3 17:55:49 2008 yoann jaspar
*/
#include "sh.h"
char **rm_good_env(char **environ, int ref_env)
{
int i;
i = 0;
while (environ[ref_env][i++] != '=')
;
environ[ref_env][i] = '\0';
i = 0;
my_putstr("\e[1;34m");
while (environ[ref_env][i] != '=')
my_putchar(environ[ref_env][i++]);
my_putstr("\e[1;32m : Has been deleted\n\n\e[0m");
return (environ);
}
|
C | UTF-8 | 1,386 | 3.984375 | 4 | [
"Apache-2.0"
] | permissive |
#include <stdio.h>
#include <math.h>
//方法一,只要求是整数
int mySqrt0(int x){
if (x < 2) { return x; }
int i = 1;
while (i*i <= x) {
//超过int最大值溢出了为负的
if (i*i <= 0) { break; }
i++;
}
return --i;
}
//方法二,公式
int mySqrt1(int x){
if (x < 2) { return x; }
//sqrt(x) = e^(logx / 2)
int left = (int)pow(exp(1), 0.5 * log(x));
int right = left + 1;
return (long)right *right > x ? left : right;
}
//方法三,二分叉查找
int mySqrt2(int x){
if (x < 2) { return x; }
long num = 0;
int pivot = 0, left = 2, right = x/2;
while (left <= right) {
pivot = left + (right - left)/2;
num = (long)pivot*pivot;
if (num > x) {
right = pivot - 1;
} else if (num < x) {
left = pivot + 1;
} else {
return pivot;
}
}
return right;
}
//方法三,牛顿迭代法
int mySqrt(int x){
if (x < 2) { return x; }
double x0 = x;
double x1 = (x0 + x/x0) / 2.0;
while (fabs(x0 - x1) >= 1) {
printf("%.4lf %.4lf\n", x0, x1);
x0 = x1;
x1 = (x0 + x/x0)/2.0;
printf("%.4lf\n", x1);
}
return (int)x1;
}
int main(int argc, const char * argv[]) {
printf("%d\n", mySqrt(2147483647));
return 0;
}
|
C | UTF-8 | 426 | 3.3125 | 3 | [] | no_license | #include<stdio.h>
int main()
{
int i;
int key;
int arr[5]={10,20,30,40,50}; //arr dec
//return type array_name[size];
printf("Entered elements that you want to search : \n");
scanf("%d",&key);
for(i=0;i<5;i++)
{
if(arr[i]==key)
{
printf("found.. \n");
break;
}
else
{
printf("not found..\n");
break;
}
}
return 0;
}
|
C | UTF-8 | 1,581 | 2.8125 | 3 | [] | no_license | /*
* Account_Persist.c
*
* Created on: 2015年5月8日
* Author: Administrator
*/
#include "Account_Persist.h"
#include "../Service/Account.h"
#include "../Common/list.h"
#include <stdlib.h>
#include <stdio.h>
#include<unistd.h>
#include <assert.h>
#include <string.h>
static const char ACCOUNT_DATA_FILE[] = "Account.dat";
static const char ACCOUNT_DATA_TEMP_FILE[] = "AccountTmp.dat";
//判断账号文件是否存在,返回1存在,返回0不存在
int Account_Perst_CheckAccFile() {
return 1;
}
//根据用户名载入账号,载入成功 return 1;否则 return 0
int Account_Perst_SelByName(char usrName[], account_t *buf) {
return 1;
}
//新账号写入账号文件中,返回实际写入的数据块数目
int Account_Perst_Insert(const account_t *data) {
return 1;
}
//在账号文件中查找与参数账号匹配的账号,找到 return 1;否则 return 0;并进行覆盖重写
int Account_Perst_Update(const account_t * data) {
return 1;
}
//在账号文件中删除与参数id匹配的账号,删除成功 return 1;否则 return 0;
int Account_Perst_DeleteByID(int id) {
return 1;
}
//在账号文件中查找与参数id匹配的账号,并通过指针buf传出;匹配成功 return 1;否则 return 0;
int Account_Perst_SelectByID(int id, account_t *buf) {
return 1;
}
//遍历读ACCOUNT_DATA_FILE文件,动态构建用户账号list链表,list 为链表头指针,返回list长度
int Account_Perst_SelectAll(account_list_t list) {
return 1;
}
|
C | UTF-8 | 2,858 | 3.09375 | 3 | [] | no_license | #include <stdio.h>
#include "format.h"
#include "def.h"
void strCopyN(char *s1,char *s2, int num);
extern int formatFlag;
extern int numEnd;
extern int numBegin;
extern int cntCharacter;
void format(char *finalyLine, char *line)
{
switch(formatFlag)
{
case 0:
strCopyN(finalyLine,line,numEnd-numBegin);
break;
case 1:
formatLeft(finalyLine, line);
break;
case 2:
formatRight(finalyLine, line);
break;
case 3:
formatCenter(finalyLine, line);
break;
case 4:
formatLeftAndRight(finalyLine, line);
break;
}
}
void formatLeft(char *finalyLine, char *line)
{
while(*line && *line == ' ')
line++;
strCopyN(finalyLine,line,numEnd-numBegin);
}
void formatRight(char *finalyLine, char *line)
{
while(*(line+cntCharacter-1)==' ')
cntCharacter--;
if(numEnd - numBegin<cntCharacter)
cntCharacter = numEnd - numBegin + 1;
sprintf(finalyLine,"%*s",numEnd - numBegin - cntCharacter + 1,"");
strCopyN(finalyLine + numEnd - numBegin - cntCharacter + 1,line,cntCharacter);
}
void formatCenter(char *finalyLine, char *line)
{
int cntInterval;
int offset;
int numSpaces;
int numPlaces;
int space_a_place;
int extraSpace;
int tmp;
char *pStartCharInterval[WIDTH/2+1];
char *l;
char *nowInterval;
l = line;
for(cntInterval = 1; cntInterval<WIDTH/2; cntInterval++)
pStartCharInterval[cntInterval] = l;
cntInterval = 0;
pStartCharInterval[cntInterval] = 0;
offset = 0;
for(;*l;l++)
{
if(*l==' ')
pStartCharInterval[cntInterval] = 0;
else
{
if(!pStartCharInterval[cntInterval]) pStartCharInterval[cntInterval++] = finalyLine + offset;
*(finalyLine + offset++) = *l;
if(offset>numEnd-numBegin-cntInterval)
break;
}
}
numSpaces = numEnd - numBegin - offset;
numPlaces = cntInterval - 1;
if(numPlaces <= 0)
{
*(finalyLine + offset) = '\0';
return;
}
space_a_place = numSpaces / numPlaces;
extraSpace = numSpaces % numPlaces;
l = finalyLine+numEnd -numBegin-1;
pStartCharInterval[cntInterval--] = finalyLine+offset;
offset = 0;
while(cntInterval>=0)
{
offset++;
nowInterval = pStartCharInterval[cntInterval+1]-1;
while(nowInterval!=pStartCharInterval[cntInterval])
*l-- = *nowInterval--;
*l-- = *nowInterval--;
tmp = space_a_place;
while((tmp-->0) && (numSpaces-->0))
*l-- = ' ';
if(extraSpace-->0)
{
numSpaces--;
*l-- = ' ';
}
cntInterval--;
}
}
void formatLeftAndRight(char *finalyLine, char *line)
{
int offset;
if(numEnd - numBegin>cntCharacter)
offset = (numEnd - numBegin - cntCharacter + 1)/2;
else
offset = 0;
sprintf(finalyLine,"%*s",offset,"");
strCopyN(finalyLine + offset,line,cntCharacter);
sprintf(finalyLine + offset+cntCharacter,"%*s",offset,"");
} |
C | UTF-8 | 9,033 | 2.53125 | 3 | [] | no_license | #include "pool.h"
#include "detector.h"
void load_parameters(struct pool_info *pool,char *config)
{
int name,value;
char buf[SIZE_BUFFER];
char *ptr;
memset(buf,0,sizeof(char)*SIZE_BUFFER);
strcpy(pool->filename_config,config);
pool->file_config=fopen(pool->filename_config,"r");
while(fgets(buf,sizeof(buf),pool->file_config))
{
if(buf[0]=='#'||buf[0]==' ') continue;
ptr=strchr(buf,'=');
if(!ptr) continue;
name=ptr-buf; //the end of name string+1
value=name+1; //the start of value string
while(buf[name-1]==' ') name--;
buf[name]=0;
if(strcmp(buf,"size of scm")==0)
{
sscanf(buf+value,"%d",&pool->size_scm);
}
else if(strcmp(buf,"size of ssd")==0)
{
sscanf(buf+value,"%d",&pool->size_ssd);
}
else if(strcmp(buf,"size of hdd")==0)
{
sscanf(buf+value,"%d",&pool->size_hdd);
}
else if(strcmp(buf,"size of chunk")==0)
{
sscanf(buf+value,"%d",&pool->size_chunk);
}
else if(strcmp(buf,"size of subchk")==0)
{
sscanf(buf+value,"%d",&pool->size_subchk);
}
else if(strcmp(buf,"window type")==0)
{
sscanf(buf+value,"%d",&pool->window_type);
}
else if(strcmp(buf,"window size")==0)
{
sscanf(buf+value,"%d",&pool->window_size);
}
else if(strcmp(buf,"threshold rw")==0)
{
sscanf(buf+value,"%lf",&pool->threshold_rw);
}
else if(strcmp(buf,"threshold cbr")==0)
{
sscanf(buf+value,"%lf",&pool->threshold_cbr);
}
else if(strcmp(buf,"threshold car")==0)
{
sscanf(buf+value,"%lf",&pool->threshold_car);
}
else if(strcmp(buf,"threshold seq")==0)
{
sscanf(buf+value,"%d",&pool->threshold_sequential);
}
else if(strcmp(buf,"threshold inactive")==0)
{
sscanf(buf+value,"%d",&pool->threshold_inactive);
}
else if(strcmp(buf,"threshold intensive")==0)
{
sscanf(buf+value,"%d",&pool->threshold_intensive);
}
else if(strcmp(buf,"threshold free gc")==0)
{
sscanf(buf+value,"%d",&pool->threshold_gc_free);
}
else if(strcmp(buf,"size of stream")==0)
{
sscanf(buf+value,"%d",&pool->size_stream);
}
else if(strcmp(buf,"size of stride")==0)
{
sscanf(buf+value,"%d",&pool->size_stride);
}
else if(strcmp(buf,"size of interval")==0)
{
sscanf(buf+value,"%d",&pool->size_interval);
}
memset(buf,0,sizeof(char)*SIZE_BUFFER);
}
fclose(pool->file_config);
}
void initialize(struct pool_info *pool,char *trace,char *output,char *log)
{
unsigned int i,j;
pool->chunk_sum=((pool->size_scm+pool->size_ssd+pool->size_hdd)*1024-1)/pool->size_chunk+1;
pool->chunk_sub=pool->size_chunk/pool->size_subchk; //size_chunk%size_subchk must equal to 0 in config.txt
pool->chunk_max=0;
pool->chunk_min=0;
pool->chunk_all=0;
pool->chunk_win=0;
pool->chunk_scm=1024*pool->size_scm/pool->size_chunk;
pool->chunk_ssd=1024*pool->size_ssd/pool->size_chunk;
pool->chunk_hdd=1024*pool->size_hdd/pool->size_chunk;
pool->free_chk_scm=pool->chunk_scm;
pool->free_chk_ssd=pool->chunk_ssd;
pool->free_chk_hdd=pool->chunk_hdd;
pool->window_sum=0;
pool->window_time_start=0;
pool->window_time_end=0;
pool->time_start=0;
pool->time_end=0;
pool->req_sum_all=0;
pool->req_sum_read=0;
pool->req_sum_write=0;
pool->req_size_all=0;
pool->req_size_read=0;
pool->req_size_write=0;
pool->seq_sum_all=0;
pool->seq_sum_read=0;
pool->seq_sum_write=0;
pool->seq_size_all=0;
pool->seq_size_read=0;
pool->seq_size_write=0;
pool->seq_stream_all=0;
pool->seq_stream_read=0;
pool->seq_stream_write=0;
pool->migrate_scm_scm=0; //data migration
pool->migrate_scm_ssd=0;
pool->migrate_scm_hdd=0;
pool->migrate_ssd_scm=0;
pool->migrate_ssd_ssd=0;
pool->migrate_ssd_hdd=0;
pool->migrate_hdd_scm=0;
pool->migrate_hdd_ssd=0;
pool->migrate_hdd_hdd=0;
pool->size_in_window=0;
pool->req_in_window=0;
pool->time_in_window=0;
pool->i_non_access=0;
pool->i_inactive=0;
pool->i_seq_intensive=0;
pool->i_seq_less_intensive=0;
pool->i_random_intensive=0;
pool->i_random_less_intensive=0;
for(i=0;i<SIZE_ARRAY;i++)
{
pool->window_time[i]=0;
pool->chunk_access[i]=0;
pool->pattern_non_access[i]=0;
pool->pattern_inactive[i]=0;
pool->pattern_seq_intensive[i]=0;
pool->pattern_seq_less_intensive[i]=0;
pool->pattern_random_intensive[i]=0;
pool->pattern_random_less_intensive[i]=0;
}
strcpy(pool->filename_trace,trace);
strcpy(pool->filename_output,output);
strcpy(pool->filename_log,log);
pool->file_trace=fopen(pool->filename_trace,"r");
pool->file_output=fopen(pool->filename_output,"w");
pool->file_log=fopen(pool->filename_log,"w");
pool->chunk=(struct chunk_info *)malloc(sizeof(struct chunk_info)*pool->chunk_sum);
alloc_assert(pool->chunk,"pool->chunk");
memset(pool->chunk,0,sizeof(struct chunk_info)*pool->chunk_sum);
pool->req=(struct request_info *)malloc(sizeof(struct request_info));
alloc_assert(pool->req,"pool->req");
memset(pool->req,0,sizeof(struct request_info));
pool->stream=(struct stream_info *)malloc(sizeof(struct stream_info)*pool->size_stream);
alloc_assert(pool->stream,"pool->stream");
memset(pool->stream,0,sizeof(struct stream_info)*pool->size_stream);
pool->map=(struct map_info *)malloc(sizeof(struct map_info)*pool->chunk_sum);
alloc_assert(pool->map,"pool->map");
memset(pool->map,0,sizeof(struct map_info));
pool->record_win=(struct record_info *)malloc(sizeof(struct record_info)*pool->chunk_sum);
alloc_assert(pool->record_win,"pool->record_win");
memset(pool->record_win,0,sizeof(struct record_info)*pool->chunk_sum);
pool->record_all=(struct record_info *)malloc(sizeof(struct record_info)*pool->chunk_sum);
alloc_assert(pool->record_all,"pool->record_all");
memset(pool->record_all,0,sizeof(struct record_info)*pool->chunk_sum);
printf("-------------Initializing...chunk_sum=%d------------\n",pool->chunk_sum);
for(i=0;i<pool->chunk_sum;i++)
{
pool->map[i].lcn=i;
pool->map[i].pcn=i;
pool->record_win[i].accessed=0;
pool->record_all[i].accessed=0;
pool->chunk[i].status=FREE;
pool->chunk[i].pattern=PATTERN_UNKNOWN;
pool->chunk[i].pattern_last=PATTERN_UNKNOWN;
pool->chunk[i].location=HDD;
pool->chunk[i].location_next=HDD;
pool->chunk[i].req_sum_all=0;
pool->chunk[i].req_sum_read=0;
pool->chunk[i].req_sum_write=0;
pool->chunk[i].req_size_all=0;
pool->chunk[i].req_size_read=0;
pool->chunk[i].req_size_write=0;
pool->chunk[i].seq_sum_all=0;
pool->chunk[i].seq_sum_read=0;
pool->chunk[i].seq_sum_write=0;
pool->chunk[i].seq_size_all=0;
pool->chunk[i].seq_size_read=0;
pool->chunk[i].seq_size_write=0;
pool->chunk[i].seq_stream_all=0;
pool->chunk[i].seq_stream_read=0;
pool->chunk[i].seq_stream_write=0;
for(j=0;j<SIZE_ARRAY;j++)
{
pool->chunk[i].history_pattern[j]=' ';
pool->chunk[i].history_migration[j]=0;
}
pool->chunk[i].subchk=(struct chunk_info *)malloc(sizeof(struct chunk_info)*pool->chunk_sub);
alloc_assert(pool->chunk[i].subchk,"pool->chunk[i].subchk");
memset(pool->chunk[i].subchk,0,sizeof(struct chunk_info)*pool->chunk_sub);
for(j=0;j<pool->chunk_sub;j++)
{
pool->chunk[i].subchk[j].status=FREE;
pool->chunk[i].subchk[j].pattern=PATTERN_UNKNOWN;
pool->chunk[i].subchk[j].pattern_last=PATTERN_UNKNOWN;
pool->chunk[i].subchk[j].location=pool->chunk[i].location;
pool->chunk[i].subchk[j].location_next=pool->chunk[i].location_next;
pool->chunk[i].subchk[j].req_sum_all=0;
pool->chunk[i].subchk[j].req_sum_read=0;
pool->chunk[i].subchk[j].req_sum_write=0;
pool->chunk[i].subchk[j].req_size_all=0;
pool->chunk[i].subchk[j].req_size_read=0;
pool->chunk[i].subchk[j].req_size_write=0;
pool->chunk[i].subchk[j].seq_sum_all=0;
pool->chunk[i].subchk[j].seq_sum_read=0;
pool->chunk[i].subchk[j].seq_sum_write=0;
pool->chunk[i].subchk[j].seq_size_all=0;
pool->chunk[i].subchk[j].seq_size_read=0;
pool->chunk[i].subchk[j].seq_size_write=0;
pool->chunk[i].subchk[j].seq_stream_all=0;
pool->chunk[i].subchk[j].seq_stream_read=0;
pool->chunk[i].subchk[j].seq_stream_write=0;
}
}
pool->req->time=0;
pool->req->lba=0;
pool->req->type=0;
pool->req->size=0;
for(i=0;i<pool->size_stream;i++)
{
pool->stream[i].chk_id=0;
pool->stream[i].type=0;
pool->stream[i].sum=0;
pool->stream[i].size=0;
pool->stream[i].min=0;
pool->stream[i].max=0;
pool->stream[i].time=0;
}
}
|
C | UTF-8 | 764 | 3.15625 | 3 | [] | no_license | #include<stdio.h>
#include<string.h>
int nextFreeCell = 0;
char *ram[1000] = { NULL };
void removeFromRam (int start, int end){
for (int i = start; i <= end; i++)
{
ram[i] = NULL;
}
}
void addToRAM (FILE *p, int *start, int *end){
*start = nextFreeCell;
int i = *start;
char buffer[1000];
while (!feof(p) && i<1000){
fgets(buffer,999,p);
ram[i]= strdup(buffer);
i++;
}
if (i>=1000 && !feof(p)){
removeFromRam(0,i-1);
nextFreeCell = 0;
*start = -1;
*end = -1;
} else {
nextFreeCell=i;
*end=i-1;
}
}
/*
Reset free cell to 0
*/
void resetRAM(){
nextFreeCell = 0;
}
|
C | UTF-8 | 345 | 3.546875 | 4 | [] | no_license | #include <stdio.h>
int main()
{
int ligne,colonne;
for (ligne = 0; ligne < 16; ++ligne)
{
for (colonne = 0; colonne < 6; colonne++)
{
char c = 0x20+(0x10*colonne)+ligne;
if (c < 127)
printf("%c %d (%02x)\t", c,c,c);
}
putchar('\n');
}
return (0);
}
|
C | UTF-8 | 1,190 | 3.953125 | 4 | [] | no_license | /*
Author: Andrew DiCarlo
Assignment Number: Lab 2
File Name: lab2b.c
Course/Section: CS 3843 Section 003
Due Date: 02 Mar 2020
Instructor: Dr. Ku
Contains the modified code to complete the requirements of lab 2
*/
#include <stdio.h>
#include <string.h>
#define MAX 10
int readArray(int [], int);
void printArray(int [], int);
void reverseArray(int [], size_t);
int main(void) {
int array[MAX], numElements;
numElements = readArray(array, MAX);
reverseArray(array, numElements);
printArray(array, numElements);
return 0;
}
int readArray(int arr[], int limit) {
int i, input;
printf("Enter up to %d integers, terminating with a negative integer.\n", limit);
i = 0;
scanf("%d", &input);
while (input >= 0) {
arr[i] = input;
i++;
scanf("%d", &input);
}
return i;
}
void reverseArray(int arr[], size_t size) {
int *end, *start;
int temp;
start = arr;
end = &arr[size - 1];
while(start < end){
temp = *start;
*start = *end;
*end = temp;
start++;
end--;
}
}
void printArray(int arr[], int size) {
int i;
for (i=0; i<size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
|
C | UTF-8 | 8,615 | 3.1875 | 3 | [] | no_license | /*
* twi.c
*
* Created: 25/09/2013 6:05:40 PM
* Author: Eden Barby
*/
/* INCLUDES *****************************************************************/
#include <avr/io.h>
#include <stdint.h>
#include <stdio.h>
/* PRIVATE TYPEDEFS *********************************************************/
/* PRIVATE DEFINES **********************************************************/
/* Bit Rate Register = ((CPU Frequency) / (SCL Frequency) - 16) / (2 * Prescaler)
* CPU Frequency = 8MHz
* SCL Frequency = 100kHz
* Prescaler = 1
*/
#define BRR (uint8_t)(32)
#define IMU_ADDR 0b1101001 /* MPU6050 I2C address. */
/* PRIVATE MACROS ***********************************************************/
#define STATUS() (TWSR & 0xF8)
/* PRIVATE VARIABLES ********************************************************/
/* PRIVATE FUNCTION PROTOTYPES **********************************************/
static uint8_t twi_start(void);
static uint8_t twi_start_r(void);
static uint8_t twi_sla_w(uint8_t address);
static uint8_t twi_sla_r(uint8_t address);
static uint8_t twi_write(uint8_t data);
static uint8_t twi_read_ack(uint8_t *data);
static uint8_t twi_read_nack(uint8_t *data);
static void twi_stop(void);
static uint8_t handle_error(uint8_t status);
/* Initialize two wire interface.
*
*/
void init_twi(void) {
/* Set the bit rate register. Prescaler of 1 is default. */
TWBR = BRR;
}
/* Read num bytes starting from regAddrStart. Each subsequent byte will be from the register above (newRegPtr = oldRegPtr + 1).
*
* Input: regAddrStart The register address to start reading bytes from
* data Location to store read data
* num The number of registers to be read
* Return: 0 Succeeded
* >0 Failed, see handle_error() for relavant error codes
*/
uint8_t twi_read_bytes(uint8_t regAddrStart, uint8_t *data, uint8_t num) {
uint8_t i, error;
/* Transmit start condition. */
if((error = twi_start())) return error;
/* Transmit slave address and write bit. */
if((error = twi_sla_w(IMU_ADDR))) return error;
/* Transmit to slave the register to be read. */
if((error = twi_write(regAddrStart))) return error;
/* Transmit repeated start condition. */
if((error = twi_start_r())) return error;
/* Transmit slave address and read bit. */
if((error = twi_sla_r(IMU_ADDR))) return error;
/* Read data from slave. */
for(i = 0; i < num; i++) {
if(i == num - 1) {
/* Last byte, return NACK. */
if((error = twi_read_nack(&data[i]))) return error;
} else {
if((error = twi_read_ack(&data[i]))) return error;
}
}
/* Transmit stop condition. */
twi_stop();
return 0;
}
/* Writes num bytes starting from regAddrStart. Each subsequent byte will be written to the register above (newRegPtr = oldRegPtr + 1).
*
* Input: regAddrStart The register address to start reading bytes from
* data Pointer to data to be written
* num The number of registers to be read
* Return: 0 Succeeded
* >0 Failed, see handle_error() for relavant error codes
*/
uint8_t twi_write_bytes(uint8_t regAddrStart, uint8_t *data, uint8_t num) {
uint8_t i, error;
/* Transmit start condition. */
if((error = twi_start())) return error;
/* Transmit slave address and write bit. */
if((error = twi_sla_w(IMU_ADDR))) return error;
/* Transmit to slave the register to write to. */
if((error = twi_write(regAddrStart))) return error;
/* Write data to slave. */
for(i = 0; i < num; i++) {
if((error = twi_write(data[i]))) return error;
}
/* Transmit stop condition. */
twi_stop();
return 0;
}
/* Writes num bytes starting from regAddrStart. Each subsequent byte will be written to the register above (newRegPtr = oldRegPtr + 1). Respects regMasks.
*
* 76543210
* 00010100 value[n] to write
* 00011100 mask[n] byte
* 01101101 original register[regAddrStart + n]
* 01100001 original & ~mask
* 01110101 masked | value
*
* Input: regAddrStart The register address to start reading bytes from
* data Pointer to data to be written
* regMasks Pointer to byte masks for each register
* num The number of registers to be read
* Return: 0 Succeeded
* >0 Failed, see handle_error() for relavant error codes
*/
uint8_t twi_write_bits(uint8_t regAddrStart, uint8_t *data, uint8_t *regMasks, uint8_t num) {
uint8_t i;
uint8_t buffer[num];
twi_read_bytes(regAddrStart, buffer, num);
for(i = 0; i < num; i++) {
data[i] &= regMasks[i];
buffer[i] &= ~regMasks[i];
buffer[i] |= data[i];
}
twi_write_bytes(regAddrStart, buffer, num);
return 0;
}
/* Transmits start condition.
*
* Return: 0 Succeeded
* >0 Failed, see handle_error() for relavant error codes
*/
static uint8_t twi_start(void) {
/* Transmit start condition. */
TWCR = (1 << TWINT) | (1 << TWSTA) | (1 << TWEN);
/* Wait for transmission to complete. */
while(!(TWCR & (1 << TWINT)));
/* If status register indicates an error, handle it and return the appropriate error code. */
if(STATUS() != 0x08) return handle_error(STATUS());
return 0;
}
/* Transmits repeated start condition.
*
* Return: 0 Succeeded
* >0 Failed, see handle_error() for relavant error codes
*/
static uint8_t twi_start_r(void) {
/* Transmit repeated start condition. */
TWCR = (1 << TWINT) | (1 << TWSTA) | (1 << TWEN);
while(!(TWCR & (1 << TWINT)));
if(STATUS() != 0x10) return handle_error(STATUS());
return 0;
}
/* Transmits slave address and write bit condition.
*
* Input: address Slave address
* Return: 0 Succeeded
* >0 Failed, see handle_error() for relavant error codes
*/
static uint8_t twi_sla_w(uint8_t address) {
/* Transmit slave address and write bit. */
TWDR = (address << 1);
TWCR = (1 << TWINT) | (1 << TWEN);
while(!(TWCR & (1 << TWINT)));
if(STATUS() != 0x18) return handle_error(STATUS());
return 0;
}
/* Transmits slave address and read bit condition.
*
* Input: address Slave address
* Return: 0 Succeeded
* >0 Failed, see handle_error() for relavant error codes
*/
static uint8_t twi_sla_r(uint8_t address) {
/* Transmit slave address and read bit. */
TWDR = (address << 1) | 0x01;
TWCR = (1 << TWINT) | (1 << TWEN);
while(!(TWCR & (1 << TWINT)));
if(STATUS() != 0x40) return handle_error(STATUS());
return 0;
}
/* Transmits data to slave.
*
* Input: data Data to be transfered
* Return: 0 Succeeded
* >0 Failed, see handle_error() for relavant error codes
*/
static uint8_t twi_write(uint8_t data) {
/* Write data to slave. */
TWDR = data;
TWCR = (1 << TWINT) | (1 << TWEN);
while(!(TWCR & (1 << TWINT)));
if(STATUS() != 0x28) return handle_error(STATUS());
return 0;
}
/* Receives data from slave. Returns ACK to continue transfer.
*
* Input: data Location to store read data
* Return: 0 Succeeded
* >0 Failed, see handle_error() for relavant error codes
*/
static uint8_t twi_read_ack(uint8_t *data) {
TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWEA);
while(!(TWCR & (1 << TWINT)));
if(STATUS() != 0x50) return handle_error(STATUS());
(*data) = TWDR;
return 0;
}
/* Receives data from slave. Returns NACK to stop transfer.
*
* Input: data Location to store read data
* Return: 0 Succeeded
* >0 Failed, see handle_error() for relavant error codes
*/
static uint8_t twi_read_nack(uint8_t *data) {
TWCR = (1 << TWINT) | (1 << TWEN);
while(!(TWCR & (1 << TWINT)));
if(STATUS() != 0x58) return handle_error(STATUS());
(*data) = TWDR;
return 0;
}
/* Transmits stop condition.
*
*/
static void twi_stop(void) {
TWCR = (1 << TWINT) | (1 << TWSTO) | (1 << TWEN);
while(!(TWCR & (1 << TWSTO)));
}
/* Handles errors and returns relevant error code.
*
* Input: status TWI status register
* Return: 1 Bus error due to an illegal START or STOP condition
* Return: 2 SLA+W has been transmitted, NOT ACK has been received
* Return: 3 Data byte has been transmitted, NOT ACK has been received
* Return: 4 Control of TWI line lost
* Return: 5 SLA+R has been transmitted, NOT ACK has been received
* Return: 10 Unexpected status
*/
static uint8_t handle_error(uint8_t status) {
switch(status) {
case 0x00:
TWCR = (1 << TWINT) | (1 << TWSTO) | (1 << TWEN);
return 1;
case 0x20:
TWCR = (1 << TWINT) | (1 << TWSTO) | (1 << TWEN);
return 2;
case 0x30:
TWCR = (1 << TWINT) | (1 << TWSTO) | (1 << TWEN);
return 3;
case 0x38:
TWCR = (1 << TWINT) | (1 << TWEN);
return 4;
case 0x48:
TWCR = (1 << TWINT) | (1 << TWSTO) | (1 << TWEN);
return 5;
default:
TWCR = (1 << TWINT) | (1 << TWSTO) | (1 << TWEN);
return 10;
}
} |
C | UTF-8 | 21,626 | 3.21875 | 3 | [] | no_license | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdio_ext.h>
#define true 1
#define false 0
#define vazio -1
typedef struct estado
{
char Nest[20][5];/*contem os estados*/
int cont; /*conta os estados*/
}Estados;
typedef struct NState {/*tem o objetivo de obter os movimentos de um estado (seja ele do afd ou afn)
com as letras do alfabeto*/
char locale[20];
}Nstate;
typedef struct TMarcas {/*tem o objetivo de simular uma fila quando encontramos um
novo estado após fazer o fecho de um E[d(x,&)]*/
char resultado[20];
int marca;
}TMarcas;
void inicializa (Estados *N, int pos)
{
N[pos].cont=0;
}
/*---------------------------------------------------------------------------
OBJETIVO: RETIRAR AS VÍRGULAS DE UM MOVIMENTO DO N
PARAMETRO: N: QUE É A MOVIMENTACAO DOS ESTADOS COM AS LETRAS DO ALFABETO
pos: QUE É A POSICAO DO ESTADO QUE SE DESEJA RETIRAR VIRGULA
*aux que são os movimentos
---------------------------------------------------------------------------*/
void retiraVirgulaMove (char *aux, int pos, Estados *N)
{
int i,j;
i=j=0;
while( !(aux[i] == '\0') )
{
if ( !(aux[i] == ',') && !(aux[i] == '\n')){
N[pos].Nest[N[pos].cont][j++] = aux[i];
}
else
{
N[pos].Nest[N[pos].cont][j] = '\0';
N[pos].cont = N[pos].cont + 1;
j=0;
}
i++;
}
/*N[pos].Nest[j-1] = '\0';/*como o fgets lê tbm o '\n' precisamos
colocar o '\0' no seu lugar para finalizar a string*/
}
/*----------------------------------------------------------------------
OBJETIVO: RETIRAR AS VIRGULAS DO ALFABETO POIS ENTRA COM OS DADOS
SEPARADOS POR VÍRGULAS
PARAMETRO: A STRING
----------------------------------------------------------------------*/
void retiraVirgulaAlfa (char string[])
{
int i,j;
char aux[10];
i=j=0;
strcpy(aux,string);/*COPIA A STRING PARA PODER RETIRAR AS VIRGULAS*/
while( !(aux[i] == '\0') ) /*PROCURA ATÉ ENCONTRAR O FINAL DA STRING*/
{
if ( !(aux[i] == ',') ){
string[j++] = aux[i];
}
i++;
}
string[j-1] = '&'; /*ADICIONA A PALAVRA VAZIA NO ALFABETO*/
string[j] = '\0';/*como o fgets lê tbm o '\n' precisamos
colocar o '\0' no seu lugar para finalizar a string*/
}
/*----------------------------------------------------------------------
OBJETIVO: RETIRAR AS VIRGULAS DOS ESTADO POIS ENTRA COM OS DADOS
SEPARADOS POR VÍRGULAS
PARAMETRO: A MATRIZ QUE VAI GUARDAR OS ESTADOS,
est: POSSUI TODOS OS ESTADOS DIGITADOS PELO USUARIO
*tam: VAI OBTER O TAMANHO DE CADA ESTADO (NUMEROS DE LETRAS)
RETORNO: O TOTAL DE ESTADOS DO AFN
----------------------------------------------------------------------*/
void retiraVirgulaState (Estados *matriz, char est[])
{
int i,j,k;
int aux=0;
j=i=k=0;
inicializa(matriz,0);
while( !(est[k] == '\0') ) /*PROCURA ATÉ ENCONTRAR O FINAL DA STRING*/
{
if ( !(est[k] == ',') && !(est[k] == '\n')){
matriz->Nest[aux][j] = est[k];
j++;
}
else
{
matriz->Nest[aux][j] = '\0'; /*ADICIONA O FINALIZADOR DE STRING TODA VEZ QUE ENCONTRAR VIRGULA*/
matriz->cont = matriz->cont + 1;
i++; /*INCREMENTA PARA MUDAR A LINHA PARA OUTRA STRING DO ESTADO*/
j=0; /*COMEÇA DA POSICAO 0 POIS PULOU PARA A PROXIMA LINHA*/
aux = matriz->cont;
}
k++;
}
}
/*---------------------------------------------------------------------------
OBJETIVO: FAZER A LEITURA DO ESTADO INICIAL E FINAL
PARAMETROS: A MATRIZ COM OS ESTADOS
tot: QUE É O TOTAL DE ESTADOS
*q0: QUE É O ESTADO INICIAL
*qf: QUE É O ESTADO FINAL
---------------------------------------------------------------------------*/
void estadoInicial (Estados *matriz, char *q0, Estados *qf)
{
int i;
char aux[20]; /*auxilia quando obtemos o estado inicial para copiar ele para o primeiro estado*/
char oneEstate[4];/*obtem um estado para verificar se está em matriz*/
int cont = false;
int j,k,l;
int ver; /*VERIFICA QUANTAS VEZES ENTROU NO FOR, QUE REPRESENTA QUANTOS ESTADOS FINAIS POSSUI*/
int tam; /*obtem obtem o tamanho de qf*/
char estFinal[20];
int tamState;
do{
printf("\nEstado inical = ");
__fpurge(stdin);
fgets(q0,4,stdin);
q0[strlen(q0)-1] = '\0';/*COLOCA O FINALIZADOR POIS FGETS LÊ O '\n'*/
i=0;
while(!(strcmp(matriz->Nest[i],q0)==0) && i < matriz->cont)
{
i++;
}
if(i < matriz->cont){/*se estado incial e valido eu o coloco na primeira posicao*/
cont = true;
strcpy(aux,matriz->Nest[0]);
strcpy(matriz->Nest[0],matriz->Nest[i]);
strcpy(matriz->Nest[i],aux);
}
if(!cont)
printf("Entre com estado válido\n");
}while(!cont);
cont = false;
ver = 0;
do{
printf("\nEstado final = ");
__fpurge(stdin);
fgets(estFinal,20,stdin);
tam = strlen(estFinal);
estFinal[tam-1] = '\0';
j=0;
l=0;
printf("%s\n", estFinal);
/*retiro todas as vírgulas e também o '\n' da string para outra string*/
while(estFinal[j] != '\0')
{
if(estFinal[j]!=',' && estFinal[j]!='\n')
{
aux[l++] = estFinal[j];
}
j++;
}
aux[l] = '\0';
printf("%s\n",aux );
j=0;
tamState = strlen(matriz->Nest[i]);
/*obtenho 1 a 1 estado até encontrar o '\0' para verificar se esses estados
pertencem aos estados do AFN*/
while(aux[j] != '\0')
{
l=0;
for(k=j;k<j+tamState;k++)
{
oneEstate[l++] = aux[k];
}
oneEstate[l] = '\0';
printf("o = %s\n",oneEstate);
j = j+tamState;
ver++;
for(i=0;i<matriz->cont;i++)
{
if( !(strcmp(matriz->Nest[i],oneEstate)) )
{
cont++;
}
}
}
printf("ver = %d cont = %d\n",ver,cont);
if(cont != ver)
printf("Entre com estado válido\n");
}while(cont != ver);
inicializa(qf,0);
retiraVirgulaMove(estFinal,0,qf);
}
/*---------------------------------------------------------------------------
OBJETIVO: VERIFICAR SE OS DESTINOS DE UM CERTO ESTADO COM x LETRA DO ALFABETO
ESTÃO NA MATRIZ DE ESTADOS
PARÂMETROS: A MATRIZ DE ESTADOS
dest: DESTINO DE UM ESTADO
---------------------------------------------------------------------------*/
void verifica_destinos (Estados matriz, char *dest)
{
int i=0;
char aux[4];
int j=0,k=0;
if(dest[j] != '-')/*VERIFICA SE NAO EH ESTADO VAZIO*/
{
while(dest[j] != '\0')
{
while(dest[j] != ',' && dest[j] != '\0' && dest[j] != '\n')
aux[k++] = dest[j++];/*OBTEM UM ESTADO PURO, SOMENTE SUA STRING*/
j++;
aux[k] = '\0';
k = 0;
printf("%s\n",aux );
i=0;
while(strcmp(matriz.Nest[i],aux) && matriz.cont ) /*VERIFICA 1 A 1 ESTADO SE CORRESPONDE COM OS DA MATRIZ*/
i++;
if(!(i < matriz.cont)) /*CASO ELE PASSE DA POSICAO ACESSÍVEL O PROGRAMA PARA*/
exit(100);
}
}
}
/*---------------------------------------------------------------------------
OBJETIVO: FAZER A LEITURA DOS MOVIMENTOS DOS ESTADOS COM AS LETRAS DO ALFABETO
PARAMETROS: matriz: CONTENDO TODOS OS ESTADOS
alfa: CONTENDO O ALFABETO DA MAQUINA
N: QUE É O QUE VAI ADQUIRIR TODOS OS MOVIMENTOS DE UM ESTADO
totState: TOTAL DE ESTADOS DA MATRIZ
---------------------------------------------------------------------------*/
void read_move (Estados matriz, char alfa[], Estados N[], int *totN)
{
int i,j,cont=0;
char move[20];
printf("\n[obs: entre com os estados separados por vírgula]\n");
for(i=0;i<matriz.cont;i++)
{
for(j=0;j<3;j++)
{
printf("Delta(%s,%c) = ",matriz.Nest[i] , alfa[j]);
__fpurge(stdin);
fgets(move,20,stdin);
verifica_destinos(matriz,totState,move);
inicializa(N,cont);
retiraVirgulaMove(move,cont,N);
cont++;
}
}
*totN = cont;
}
/*---------------------------------------------------------------------------
OBJETIVO: IMPRIMIR AS INFORMAÇÕES DO AFN
---------------------------------------------------------------------------*/
void imprime (char *alfa, Estados state, char *q0, Estados qf, Estados *dest, int totDest)
{
int i,j,l,cont=0;
printf("Informações do AFN: \n");
printf("--------------------------------------------\n");
printf("\nAlfabeto = %s\n",alfa);
printf("--------------------------------------------\n");
printf("Estados = ");
for(i=0;i<state.cont;i++)
printf("%s ",state.Nest[i]);
printf("\n--------------------------------------------\n");
printf("\nEstado inicial = %s\n", q0);
printf("--------------------------------------------\n");
printf("Estado final = ");
for(i=0; i < qf.cont; i++){
printf(" %s ", qf.Nest[i]);
}
printf("--------------------------------------------\n");
for(i=0;i<state.cont;i++)
{
for(j=0;j<3;j++)
{
printf("\nDelta(%s,%c) = ",state.Nest[i] , alfa[j]);
for(l=0; l < dest[cont].cont; l++)
printf(" %s ",dest[cont].Nest[l]);
cont++;
}
printf("--------------------------------------------\n");
}
}
/*---------------------------------------------------------------------------
OBJETIVO: OBTER A POSICAO DE UM ESTADO
PARAMETRO: est: ESTADO QUE DESEJA OBTER A POSICAO
state: MATRIZ COM TODOS OS ESTADOS
tot: TOTAL DE ESTADOS DE state
RETORNO: A POSICAO DO ESTADO
---------------------------------------------------------------------------*/
int obtemPosEstado (char *est, char state[][4], int tot)
{
int i=0;
printf("--> est = %s\n",est);
while(i<tot)
{
if( strcmp(est,state[i])==0 )
return i;
i++;
}
return i;
}
/*---------------------------------------------------------------------------
OBJETIVO: OBTER A MOVIMENTACAO DE UM ESTADO COM A PRIMEIRA LETRA DO ALFABETO
PARAMETRO: *estado: ESTADO QUE VAMOS OBTER A MOVIMENTACAO
dest: EH O DESTINO DE CADA ESTADO COM UMA LETRA DO ALFABETO
tam1Estado: EH O TAMANHO DE UM ESTADO (QUANTAS LETRAS TEM)
*estFinal: EH O ESTADO FINAL COM O MOVIMENTO, POIS O A STRING *estado
PODE ESTAR COM UM CONJUNTO DE ESTADO E VAMOS RECEBER TAMBḾE OUTRO CONJUNTO
DE ESTADOS EM *estFinal
state: EH A MATRIZ COM TODOS OS ESTADOS
totState: EH O TOTAL DE ESTADOS DE state
---------------------------------------------------------------------------*/
void move1alfa (char *estado, Nstate dest[], int tam1Estado, char *estFinal, char state[][4], int totState)
{
int i=0,j,k;
char est[4];
int pos;
if(estado[i] != '-')/*representação de vazio*/
{
while(estado[i] != '\0')
{
k=0;
for(j=i;j<i+tam1Estado;j++){/*COMO JA SABEMOS O TAMANHO DE 1 ÚNICO ESTADO
FAZEMOS A ATRIBUIÇÃO EM est DIRETO*/
est[k++] = estado[i];
}
est[k] = '\0'; /*COMO SEMPRE K E INCREMENTADO, COLOCAMOS EM SUA ÚLTIMA POSICAO O FINALIZADOR*/
i = i+tam1Estado; /*COMO JÁ SEI O TAMANHO DA UM ESTADO E VAI ESTAR SEM VIRGULAS NA STRING *estado
PODEMOS AVANÇAR SEMPRE COM INCREMENTANDO i COM tam1Estado ATÉ ENCONTRA '\0'*/
pos = obtemPosEstado(est,state,totState);
/*como o dest ele tem as movimentacoes de um estado com todas letras do alfabeto
e de padrao temos sempre 3 letras, exemplo 0,1 e &, por tanto para cada
posicao de um estado temos 3 movientacoes em dest, uma para 0, outra para 1
e por ultimo o de &, por isso faço essa equacao pos*3*/
printf("move = %s\n",estFinal);
if(strcmp(dest[(pos*3)].locale,"-")){
strcat(estFinal,dest[(pos*3)].locale);
printf("move = %s\n",estFinal);
}
}
}
}
/*---------------------------------------------------------------------------
OBJETIVO: OBTER A MOVIMENTACAO DE UM ESTADO COM A SEGUNDA LETRA DO ALFABETO
PARAMETRO: *estado: ESTADO QUE VAMOS OBTER A MOVIMENTACAO
dest: EH O DESTINO DE CADA ESTADO COM UMA LETRA DO ALFABETO
tam1Estado: EH O TAMANHO DE UM ESTADO (QUANTAS LETRAS TEM)
*estFinal: EH O ESTADO FINAL COM O MOVIMENTO, POIS O A STRING *estado
PODE ESTAR COM UM CONJUNTO DE ESTADO E VAMOS RECEBER TAMBḾE OUTRO CONJUNTO
DE ESTADOS EM *estFinal
state: EH A MATRIZ COM TODOS OS ESTADOS
totState: EH O TOTAL DE ESTADOS DE state
---------------------------------------------------------------------------*/
void move2alfa (char *estado, Nstate dest[], int tam1Estado, char *estFinal, char state[][4], int totState)
{
int i=0,j,k;
char est[4];
int pos;
int l,m,n;
int q,r,s;
int cont=0;
char est1Dest[4],est1EstFin[4];
char final[20]={'\0'};
if(estado[i] != '-')/*representação de vazio*/
{
while(estado[i] != '\0')
{
k=0;
for(j=i;j<i+tam1Estado;j++)
{
est[k++] = estado[i];
}
est[k++] = '\0';
i = i+tam1Estado;
pos = obtemPosEstado(est,state,totState);
/*como o dest ele tem as movimentacoes de um estado com todos alfabeto
e de padrao temos sempre 3 letras, exemplo 0,1 e &, por tanto para cada
posicao de um estado temos 3 movientacoes em dest, uma para 0, outra para 1
e por ultimo o de &, por isso faço essa conta*/
printf("move2 = %s\n",estFinal);
if(strcmp(dest[(pos*3)+1].locale,"-"))
{
l=0;
if(strlen(estFinal)!=0)
{
while(dest[(pos*3)+1].locale[l] != '\0')
{
/*separa um estado da string para poder verificar se já esta em estFinal*/
n=0;
for(m=l;m<l+tam1Estado;m++)
{
est1Dest[n++] = dest[(pos+1)*3-1].locale[m] ;
}
est1Dest[n] = '\0';
l = l + tam1Estado;
q=0;
while(estFinal[q] != '\0')
{
r=0;
for(s=q;s<q+tam1Estado;s++)
{
est1EstFin[r++] = estFinal[m] ;
}
est1EstFin[r] = '\0';
q = q + tam1Estado;
if(strcmp(est1EstFin,est1Dest) == 0)/*caso o estado já esteja dentro de estFinal nao vou adicionar*/
cont = 1;
}
if(cont == 0)
strcat(final,est1Dest);
cont = 0;
}
}
else
strcat(estFinal,dest[(pos*3) + 1].locale);
}
}
strcat(estFinal,final);
printf("->move2 = %s\n",estFinal);
}
}
/*-----------------------------------------------------------------------------------
OBJETIVO: OBTER O FECHO DE UM ESTADO E JOGAR NA PILHA
PARAMETROS: estado: eh o estado que vamos verificar o fecho
state: eh a a matriz com todos os estados
pilha: eh onde guardo todos os estados finais apos o fecho
dest: eh a movimentacao de um estado com o alfabeto
fimpilha: eh o final da pilha
tam1estado: eh o tamanho de 1 unico estado, (q0 é de tamanho 2)
totState: eh o total de estados em state
---------------------------------------------------------------------------------------*/
void fecho (char *estado, char state[][4], TMarcas *Fila, Estados *N,
int *fimFila, int tam1Estado, int totState, Nstate *AFD, int *totAFD)
{
char est[5]; /*obtem um unico estado para ver o fecho dele só*/
char estFinal[20]={'\0'}; /*obtem o estado final após o fecho */
int i=0,j=0,k,z;
int ver = false;
int pos; /*obtem a posicao que um do(s) estado(s) do char *estado esta
para poder acessar em dest por essa posicao, pois as movimentações
estao em posicoes iguais para cada variavel*/
int l,m,n;
int q,r,s;
int cont=0;
char est1Dest[4],est1EstFin[4];
char final[20]={'\0'};
if(estado[i] != '-')
{/*representação de vazio*/
while(estado[i] != '\0')
{
k=0;
for(j=i;j<i+tam1Estado;j++)/*como os estados ja estao sem virgulas eu faco a copia direto
pois ja sei o tamanho(quantas letras tem) de cada estado, até
encontrar um '\0'*/
{
est[k++] = estado[i];
}
est[k] = '\0';
printf("EST = %s %i %i\n",estado,tam1Estado,i);
i = i+tam1Estado;
pos = obtemPosEstado(est,state,totState);
/*como o dest ele tem as movimentacoes de um estado com todos alfabeto
e de padrao temos sempre 3 letras, exemplo 0,1 e &, por tanto para cada
posicao de um estado temos 3 movientacoes em dest, uma para 0, outra para 1
e por ultimo o de &, por isso faço essa conta*/
printf("pos = %d ",pos);
/*if(pos == 0){
strcat(estFinal,dest[pos+2].locale);
printf(" %s\n",dest[pos+2].locale);
}
else{
strcat(estFinal,dest[(pos*3) - 1].locale);
printf(" %s\n",dest[(pos*3)-1].locale);
}*/
l=0;
if(strlen(estFinal)!=0)
{
while(N[(pos+1)*3-1].cont < l)
{
/*separa um estado da string para poder verificar se já esta em estFinal*/
strcpy(est1Dest,N[(pos+1)*3-1].Nest[l])
l++;
q=0;
while(estFinal[q] != '\0')
{
r=0;
for(s=q;s<q+tam1Estado;s++)
{
est1EstFin[r++] = estFinal[m] ;
}
est1EstFin[r] = '\0';
q = q + tam1Estado;
if(strcmp(est1EstFin,est1Dest) == 0)/*caso o estado já esteja dentro de estFinal nao vou adicionar*/
cont = 1;
}
if(cont == 0)
strcat(final,est1Dest);
cont = 0;
}
}
else
strcpy(estFinal,N[(pos+1)*3-1].Nest[l]);
}
strcat(estFinal,final);
if(strcmp(estFinal,"-")){/*se for igual ele da falso e vai para o else*/
for (z = 0; z < *fimFila; z++)/*verifico se o fecho do estado já esta na pilha*/
{
printf(" %s -",Fila[z].resultado);
if ( strcmp(Fila[z].resultado,estFinal)==0 )
{
ver = true;
}
}
}
else
{
ver = true;
}
printf("verficacao = %i estFinal = %s\n", ver,estFinal);
if(!ver){
printf("Acrescentou!!!!!!!!!!!!!!!!!! %s\n",estFinal);
strcpy(Fila[*fimFila].resultado,estFinal); /*jogo para a fila um estado que nao tem ainda*/
Fila[*fimFila].marca = false;
*fimFila = *fimFila + 1; /*aumento a fila */
}
strcpy(AFD[*totAFD++].locale,estFinal);/*faco a copia do fecho para o AFD, pois
trabalho com respectivas posicoes, as mesmas para os estados
e também para a movimentacao com a primeira e segunda letra
de alfa*/
}
}
/*-----------------------------------------------------------------------------------
OBJETIVO: FAZER A TRANSICAO DE ESTADO DE CADA ESTADO COM UMA LETRA DO ALFABETO
E FAZ TAMBÉM A TRANSFORMAÇÃO DO AFN EM AFD DIRETO
PARAMETRO: state: eh a a matriz com todos os estados
dest: eh a movimentacao de um estado com o alfabeto
tam1estado: eh o tamanho de 1 unico estado, (q0 é de tamanho 2)
totState: eh o total de estados em state
AFD: vai ser as novas transicoes com a transformacao
NewState: sao os novos estados do AFD
totAFD: quantidade de transicoes do AFD (acho dispensavel)
--------------------------------------------------------------------------------------*/
int delta (char state[][4], Nstate dest[], int tam1Estado,
int totState, Nstate AFD[], char NewState[][10], int *totAFD, Estados *N)
{
int iniFila=0 /*trabalho com fila para ver as marcacoes*/;
int fimFila=0; /*final da fila para poder retirar um estado*/
Estados Fila[20]; /*o registro trabalho com fila para enfileirar os estados novos*/
Estados estado; /*obtem um estado da fila para fazer o fecho do delta do estado*/
Estados moveAlfa1; /*obtem o movimento de um estado com a primeira letra do alfabeto*/
Estados moveAlfa2; /*obtem o movimento de um estado com a segunda letra do alfabeto*/
int aux; /*um simples auxiliar para fazer a primeira chamada do fecho*/
Nstate aux1[2]; /*o mesmo acima*/
int i,j;
estado.cont = 0;
moveAlfa1.cont = 0;
moveAlfa2.cont = 0;
fecho(state[0], state, Fila, N, &fimFila, tam1Estado, totState,aux1,&aux);
printf("%i\n",fimFila );
while(iniFila != fimFila)
{
j=0;
while(Fila[iniFila].cont>j)
{
printf("fimfila = %d\n", fimFila);
printf("Entrou\n");
strcpy(estado,Fila[iniFila].Nest[j]);/*faco a copia de um estado da fila e ando com ela*/
Fila[iniFila].marca = true;/*faz a marcacao*/
printf("inifila = %d\n",iniFila);
move1alfa(estado,dest,tam1Estado,moveAlfa1,state,totState,j);
j++;
}
fecho(moveAlfa1,state, Fila, dest, &fimFila, tam1Estado, totState, AFD, totAFD);
moveAlfa1[0]='\0';
move2alfa(estado,dest,tam1Estado,moveAlfa2,state,totState);
fecho(moveAlfa2,state, Fila, dest, &fimFila, tam1Estado, totState, AFD, totAFD);
moveAlfa2[0]='\0';
iniFila = iniFila + 1;/*retira da fila*/
}
for(i=0;i<fimFila;i++)
{
strcpy(NewState[i],Fila[i].resultado);
}
return fimFila;
}
void AfnAfd ()
{
char alfa[10]; /*é o alfabeto*/
Estados state; /*vai conter os estados do AFN*/
state.cont=0;
char totstate[100]; /*faz a primeira leitura dos estados para depois jogar em state*/
Estados destino[20]; /*é um registro que vai conter a informação de quantas
estados uma letra do alfabeto pode influenciar em um único estado
por exemplo no delta(q0,&) = {q1,q2,q3}*/
int totDestino=0;
char q0[4]; /*estado inicial*/
Estados qf; /*estado final*/
Nstate AFD[20]; /*eh o AFD pronto, com os movimentos divididos 2 a 2,
conforme a posicao de cada NewState*/
Estados NewState[20]; /*sao os novos estados apos a transformacao em AFD*/
int tamAFD=0; /*obtem o tamanho de estados do AFD(penso dispensavel)*/
int tamNewState; /*Obtem o novo total de estados*/
int i;
Estados est[20]; /*obtem todas as movimentacoes dos estados*/
printf("Digite o alfabeto separado por vírgula\n");
__fpurge(stdin);
fgets(alfa,10,stdin);
retiraVirgulaAlfa(alfa);
printf("Digite os estados separados por vírgula\n");
__fpurge(stdin);
fgets(totstate,100,stdin);
retiraVirgulaState(&state,totstate);
estadoInicial(&state,q0,&qf);
read_move(state,alfa,est,&totDestino);
imprime(alfa,state,q0,qf,destino,totDestino);
tamNewState = delta(state, destino, tam, contState, AFD, NewState, &tamAFD);
printf("------------------------------------------------------------\n");
printf("%d\n",tamNewState );
printf("\n\tNOVOS ESTADOS DO AFD\n");
for ( i = 0; i < tamNewState; i++)
{
printf("%s\n",NewState[i]);
}
}
int main()
{
int opc;
do {
printf("1 - Converta AFN-AFD\n");
scanf("%d",&opc);
if (opc==1) {
AfnAfd();
}
} while(opc == 1);
/*__fpurge(stdin);
fgets(a,10,stdin);
printf("%s\n",a);
a[strlen(a) - 1] = '\0';
if(strcmp(a,state[0])==0)
printf("ok\n");*/
return 0;
}
|
C | UTF-8 | 140 | 2.890625 | 3 | [] | no_license | #include <stdlib.h>
int main(void) {
char *buf = malloc(20);
int i = 0;
buf[-1] = '0';
for (i = 0; i <=20; i++) {
buf[i] = '0';
}
}
|
C | UTF-8 | 1,193 | 2.90625 | 3 | [] | no_license |
/******************************************************************************/
/* generate.c - create a new generation of individuals */
/******************************************************************************/
#include "external.h"
generation ()
{
int mate1, mate2, jcross, j = 0;
/* perform any preselection actions necessary before generation */
preselect ();
/* select, crossover, and mutation */
do {
/* pick a pair of mates */
mate1 = select ();
mate2 = select ();
/* Crossover and mutation */
jcross = crossover (oldpop[mate1].chrom, oldpop[mate2].chrom,
newpop[j].chrom, newpop[j + 1].chrom);
mutation (newpop[j].chrom);
mutation (newpop[j + 1].chrom);
/* Decode string, evaluate fitness, & record */
/* parentage date on both children */
objfunc (&(newpop[j]));
newpop[j].parent[0] = mate1 + 1;
newpop[j].xsite = jcross;
newpop[j].parent[1] = mate2 + 1;
objfunc (&(newpop[j + 1]));
newpop[j + 1].parent[0] = mate1 + 1;
newpop[j + 1].xsite = jcross;
newpop[j + 1].parent[1] = mate2 + 1;
/* Increment population index */
j = j + 2;
}
while (j < (popsize - 1));
}
|
C | UTF-8 | 2,345 | 3.171875 | 3 | [
"BSD-3-Clause"
] | permissive | #include "speed_meter.h"
#include "util.h"
/**
* Initialize speed meter.
* @param[in] speed
*/
void spdm_init(struct speed_meter *speed)
{
atomic_init(&speed->i, 0);
atomic_init(&speed->speed_aux, 0);
atomic_init(&speed->last_update, 0);
for (size_t i = 0; i < ARRAYSIZE(speed->backlog); i++) {
atomic_init(&speed->backlog[i].speed, 0);
atomic_init(&speed->backlog[i].timestamp, 0);
}
}
/**
* Destroy speed meter.
* @param[in] speed
*/
void spdm_destroy(struct speed_meter *speed)
{
(void) speed;
}
/**
* Update speed meter.
* @param[in] speed
* @param[in] count
*/
void spdm_update(struct speed_meter *speed, uint64_t count)
{
uint64_t curr_time = zclock(false);
uint64_t last_update = atomic_load_explicit(&speed->last_update, memory_order_acquire);
if (curr_time - last_update >= SEC2USEC(1)) {
if (atomic_compare_exchange_strong_explicit(&speed->last_update, &last_update, curr_time, memory_order_release,
memory_order_relaxed)) {
size_t i = atomic_load_explicit(&speed->i, memory_order_acquire);
uint64_t speed_aux = atomic_load_explicit(&speed->speed_aux, memory_order_acquire);
atomic_store_explicit(&speed->backlog[i].speed, speed_aux, memory_order_release);
atomic_fetch_sub_explicit(&speed->speed_aux, speed_aux, memory_order_release);
atomic_store_explicit(&speed->backlog[i].timestamp, last_update, memory_order_release);
i++;
if (SPEED_METER_BACKLOG == i) {
i = 0;
}
atomic_store_explicit(&speed->i, i, memory_order_release);
}
}
atomic_fetch_add_explicit(&speed->speed_aux, count, memory_order_release);
}
/**
* Calculate speed.
* @param[in] speed
* @return Calculated speed.
*/
uint64_t spdm_calc(const struct speed_meter *speed)
{
uint64_t aux = 0;
uint64_t curr_time = zclock(false);
for (size_t i = 0; i < SPEED_METER_BACKLOG; i++) {
uint64_t diff = USEC2SEC(curr_time - atomic_load_explicit(&speed->backlog[i].timestamp, memory_order_acquire));
if (diff <= SPEED_METER_BACKLOG) {
aux += atomic_load_explicit(&speed->backlog[i].speed, memory_order_acquire);
}
}
return aux / SPEED_METER_BACKLOG;
} |
C | UTF-8 | 2,085 | 2.796875 | 3 | [
"mpich2"
] | permissive | /*
* Copyright (C) by Argonne National Laboratory
* See COPYRIGHT in top-level directory
*/
#include <stdio.h>
#include <mpi.h>
#include "mpitest.h"
/* This test checks request-based get with MPI_Testall. Both the return value of
* MPI_Testall and status.MPI_ERROR should be correctly set.
*
* Thanks for Joseph Schuchart reporting this bug in MPICH and contributing
* the prototype of this test program. */
int main(int argc, char **argv)
{
int rank, size;
MPI_Win win = MPI_WIN_NULL;
int *baseptr = NULL;
int errs = 0, mpi_errno = MPI_SUCCESS;
int val1 = 0, val2 = 0, flag = 0;
MPI_Request reqs[2];
MPI_Status stats[2];
MTest_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_set_errhandler(MPI_COMM_WORLD, MPI_ERRORS_RETURN);
MPI_Win_allocate(2 * sizeof(int), sizeof(int), MPI_INFO_NULL, MPI_COMM_WORLD, &baseptr, &win);
/* Initialize window buffer */
MPI_Win_lock(MPI_LOCK_EXCLUSIVE, rank, 0, win);
baseptr[0] = 1;
baseptr[1] = 2;
MPI_Win_unlock(rank, win);
/* Synchronize the processes before starting the second access epoch */
MPI_Barrier(MPI_COMM_WORLD);
/* Issue request-based get with testall. */
MPI_Win_lock_all(0, win);
MPI_Rget(&val1, 1, MPI_INT, 0, 0, 1, MPI_INT, win, &reqs[0]);
MPI_Rget(&val2, 1, MPI_INT, 0, 1, 1, MPI_INT, win, &reqs[1]);
do {
mpi_errno = MPI_Testall(2, reqs, &flag, stats);
} while (flag == 0);
/* Check get value. */
if (val1 != 1 || val2 != 2) {
printf("%d - Got val1 = %d, val2 = %d, expected 1, 2\n", rank, val1, val2);
fflush(stdout);
errs++;
}
/* Check return error code. */
if (mpi_errno != MPI_SUCCESS) {
printf("%d - Got return errno %d, expected MPI_SUCCESS(%d)\n",
rank, mpi_errno, MPI_SUCCESS);
fflush(stdout);
errs++;
}
MPI_Win_unlock_all(win);
MPI_Barrier(MPI_COMM_WORLD);
MPI_Win_free(&win);
MTest_Finalize(errs);
return MTestReturnValue(errs);
}
|
C | UTF-8 | 1,560 | 2.828125 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "mpi.h"
/* int MPI_Send(const void *buf, int count, MPI_Datatype datatype, int dest, */
/* int tag, MPI_Comm comm); */
/* int MPI_Recv(void *buf, int count, MPI_Datatype datatype, */
/* int source, int tag, MPI_Comm comm, MPI_Status *status) */
void my_int_sum_reduce(int *sendbuf, int *recvbuf, int count,
int root, MPI_Comm comm)
{
int size, rank;
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
if (rank == root) {
memcpy(recvbuf, sendbuf, count * sizeof(int));
int temp[count];
for (int i = 0; i < size; i++) {
if (i == root) continue;
MPI_Recv(temp, count, MPI_INT, i, 0, comm, MPI_STATUS_IGNORE);
for (int j = 0; j < count; j++) {
recvbuf[j] += temp[j];
}
}
} else {
MPI_Send(sendbuf, count, MPI_INT, root, 0, comm);
}
}
int main(int argc, char*argv[]) {
MPI_Init(&argc, &argv);
int size, rank;
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
int sendbuffer[4];
int recvbuffer[4];
for (int i = 0; i < 4; i++) {
sendbuffer[i] = 100 + (10 * rank) + i;
}
/* int MPI_Reduce(const void *sendbuf, void *recvbuf, int count, */
/* MPI_Datatype datatype, MPI_Op op, int root, */
/* MPI_Comm comm) */
my_int_sum_reduce(sendbuffer, recvbuffer, 4, 0, MPI_COMM_WORLD);
if (rank == 0) {
for (int i = 0; i < 4; i++) {
printf("%d ", recvbuffer[i]);
}
printf("\n");
}
MPI_Finalize();
return EXIT_SUCCESS;
}
|
C | UTF-8 | 3,772 | 3.75 | 4 | [
"MIT"
] | permissive | #include<stdio.h>
struct polynode
{
int coef;
int exp;
struct polynode *next;
};
typedef struct polynode *polyptr;
polyptr createPoly()
{
polyptr p, tmp, start = NULL;
int ch=1;
while(ch)
{
p = (polyptr)malloc(sizeof(struct polynode));
printf("Enter the coefficient: ");
scanf("%d",&p->coef);
printf("Enter the exponent: ");
scanf("%d",&p->exp);
p->next = NULL;
if(start==NULL) start=p;
else
{
tmp=start;
while(tmp->next!=NULL)
tmp=tmp->next;
tmp->next=p;
}
printf("More nodes to be added (1/0): ");
scanf("%d",&ch);
}
return start;
}
void display(polyptr *poly)
{
polyptr list;
list=*poly;
while(list!=NULL)
{
if(list->next!=NULL)
printf("%d X^ %d + " ,list->coef,list->exp);
else
printf("%d X^ %d " ,list->coef,list->exp);
list=list->next;
}
}
polyptr addTwoPolynomial(polyptr *F,polyptr *S)
{
polyptr A,B,p,result,C=NULL;
A=*F;B=*S; result=C;
while(A!=NULL && B!=NULL)
{
switch(compare(A->exp,B->exp))
{
case 1:
p=(polyptr)malloc(sizeof(struct polynode));
p->coef=A->coef;
p->exp=A->exp;
p->next=NULL;
A=A->next;
if (result==NULL) result=p;
else
attachTerm(p->coef,p->exp,&result);
break;
case 0:
p=(polyptr)malloc(sizeof(struct polynode));
p->coef=A->coef+B->coef;
p->exp=A->exp;
p->next=NULL;
A=A->next;
B=B->next;
if (result==NULL) result=p;
else
attachTerm(p->coef,p->exp,&result);
break;
case -1:
p=(polyptr)malloc(sizeof(struct polynode));
p->coef=B->coef;
p->exp=B->exp;
p->next=NULL;
B=B->next;
if (result==NULL) result=p;
else
attachTerm(p->coef,p->exp,&result);
break;
}
}
while(A!=NULL)
{
attachTerm(A->coef,A->exp,&result);
A=A->next;
}
while(B!=NULL)
{
attachTerm(B->coef,B->exp,&result);
B=B->next;
}
return result;
}
int compare(int x, int y)
{
if(x==y) return 0;
if(x<y) return -1;
if(x>y) return 1;
}
attachTerm(int c,int e,polyptr *p)
{
polyptr ptr,tmp;
ptr=*p;
tmp=(polyptr)malloc(sizeof(struct polynode));
while(ptr->next!=NULL)
{
ptr=ptr->next;
}
ptr->next=tmp;
tmp->coef=c;
tmp->exp=e;
tmp->next=NULL;
}
main()
{
polyptr Apoly,Bpoly;
clrscr();
printf("Enter the first polynomial : \n");
Apoly=createPoly();
display(&Apoly);
printf("\n");
Bpoly=createPoly();
display(&Bpoly);
printf("\nResult is : ");
C=addTwoPolynomial(&Apoly,&Bpoly);
display(&C);
getch();
}
|
C | UTF-8 | 4,873 | 3.65625 | 4 | [
"Zlib"
] | permissive | #include "hashMap.h"
#include <assert.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
/**
* Allocates a string for the next word in the file and returns it. This string
* is null terminated. Returns NULL after reaching the end of the file.
* @param file
* @return Allocated string or NULL.
*/
char* nextWord(FILE* file)
{
int maxLength = 16;
int length = 0;
char* word = malloc(sizeof(char) * maxLength);
while (1)
{
char c = fgetc(file);
if ((c >= '0' && c <= '9') ||
(c >= 'A' && c <= 'Z') ||
(c >= 'a' && c <= 'z') ||
c == '\'')
{
if (length + 1 >= maxLength)
{
maxLength *= 2;
word = realloc(word, maxLength);
}
word[length] = c;
length++;
}
else if (length > 0 || c == EOF)
{
break;
}
}
if (length == 0)
{
free(word);
return NULL;
}
word[length] = '\0';
return word;
}
/**
* Loads the contents of the file into the hash map.
* @param file
* @param map
*/
void loadDictionary(FILE* file, HashMap* map)
{
// FIXME: implement
char* word = nextWord(file);
while(word != NULL)
{
hashMapPut(map, word, 1);
free(word);
word = nextWord(file);
}
}
/**
* Calculates the Levenshtein Distance Between two strings.
* @param string 1 to compare
* @param string 2 to compare
*/
int calcLeven(char* string1, char* string2)
{
int sum = 0;
char* toUse;
char* other;
if(strlen(string1) <= strlen(string2))
{
toUse = string1;
other = string2;
}
else
{
toUse = string2;
other = string1;
}
for(int i = 0; i < strlen(toUse); i++)
{
if(toUse[i] != other[i])
{
sum++;
}
}
sum += (strlen(other) - strlen(toUse));
return sum;
}
/**
* Changes all of the value pairs to be the Levenshtein Distance between the input.
* @param Hashmap to change
* @param String to use in calculation
*/
void changeWeight(HashMap* map, char* comparedString)
{
for(int i = 0; i < map->capacity; i++)
{
HashLink* lnk = map->table[i];
if (lnk != NULL)
{
while (lnk != NULL)
{
lnk->value = calcLeven(lnk->key, comparedString);
lnk = lnk->next;
}
}
}
}
/**
* Returns an array of length 5 that has words with the lowest Levenshtein Distance
* @param Map to search
*/
char** recomend(HashMap* map)
{
char** arr;
int size = 0;
int compareLen = 1;
while(size < 5)
{
for(int i = 0; i < map->capacity; i++)
{
HashLink* lnk = map->table[i];
if (lnk != NULL)
{
while (lnk != NULL)
{
if(lnk->value == compareLen)
{
if(size >= 5)
{
break;
}
arr[size] = lnk->key;
size++;
}
lnk = lnk->next;
}
}
}
compareLen++;
}
return arr;
}
/**
* Prints the concordance of the given file and performance information. Uses
* the file input1.txt by default or a file name specified as a command line
* argument.
* @param argc
* @param argv
* @return
*/
int main(int argc, const char** argv)
{
// FIXME: implement
HashMap* map = hashMapNew(1000);
FILE* file = fopen("dictionary.txt", "r");
clock_t timer = clock();
loadDictionary(file, map);
timer = clock() - timer;
printf("Dictionary loaded in %f seconds\n", (float)timer / (float)CLOCKS_PER_SEC);
fclose(file);
char inputBuffer[256];
int quit = 0;
while (!quit)
{
printf("Enter a word or \"quit\" to quit: ");
scanf("%s", inputBuffer);
// Implement the spell checker code here..
for(int i = 0; inputBuffer[i] != '\0'; i++)
{
inputBuffer[i] = tolower(inputBuffer[i]);
}
if(hashMapContainsKey(map, inputBuffer))
{
printf("The inputted word, %s, was spelled correctly.\n", inputBuffer);
}
else
{
char** poss;
changeWeight(map, inputBuffer);
poss = recomend(map);
printf("The inputted word was spelled incorrectly. Did you mean:");
for(int i = 0; i < 5; i++)
{
printf(" %s", poss[i]);
}
printf("?\n");
}
// file = fopen("dictionary.txt", "r");
// loadDictionary(file, map);
// fclose(file);
if (strcmp(inputBuffer, "quit") == 0)
{
quit = 1;
}
}
hashMapDelete(map);
return 0;
}
|
C | UTF-8 | 2,738 | 3.875 | 4 | [] | no_license |
/**
Utilizando uma estrutura de pilha, Implemente uma calculadora pós-fixada,
contendo as operações básicas (+, -, *, /)
**/
#include <stdio.h>
#include <stdlib.h>
#define MAX 10
#define BASE 0
int TOPO=0, OPERACAO=0;
float VETOR[MAX], VALOR=0, N1=0, N2=0, RESULTADO=0;
void EMPILHAR(float VALOR)
{
VETOR[TOPO] = VALOR;
TOPO++;
}
float DESEMPILHAR()
{
TOPO--;
RESULTADO = VETOR[TOPO];
return RESULTADO;
}
void CALCULA()
{
int RESULT = 0;
if (OPERACAO == 1) {
printf("\nAdicao\n");
N1 = DESEMPILHAR();
N2 = DESEMPILHAR();
RESULTADO = N1 + N2;
printf("\n%f + %f = %f\n",N1,N2,RESULTADO);
EMPILHAR(RESULTADO);
RESULT = 1;
}
if (OPERACAO == 2) {
printf("\nSubtracao\n");
N1 = DESEMPILHAR();
N2 = DESEMPILHAR();
RESULTADO = N1 - N2;
printf("\n%f - %f = %f\n",N1,N2,RESULTADO);
EMPILHAR(RESULTADO);
RESULT = 1;
}
if (OPERACAO == 3) {
printf("\nMultiplicacao\n");
N1 = DESEMPILHAR();
N2 = DESEMPILHAR();
RESULTADO = N1 * N2;
printf("\n%f * %f = %f\n",N1,N2,RESULTADO);
EMPILHAR(RESULTADO);
RESULT = 1;
}
if (OPERACAO == 4) {
printf("\nDivisao\n");
N1 = DESEMPILHAR();
N2 = DESEMPILHAR();
RESULTADO = N2 / N1;
printf("\n%f / %f = %f\n",N2,N1,RESULTADO);
EMPILHAR(RESULTADO);
RESULT = 1;
}
if (RESULT==0)
{
printf("\nOpcao nao valida!!! \n1 -> Adicao\n2 -> Subtracao\n3 -> Multiplicacao\n4 -> Divisao\nInforme a operacao novamente: ");
scanf("%d",&OPERACAO);
CALCULA();
}
}
void MOSTRARESULTADO()
{
printf("Resultado da operacao e' %f\n",VETOR[BASE]);
}
int main()
{
int aux =1;
printf("\n Calculadora basica (+, -, *, /) \n");
while (aux != 0)
{
printf("\nDigite o valor1: ");
scanf("%f",&N1);
EMPILHAR(N1);
printf("\nDigite o valor2: ");
scanf("%f",&N2);
EMPILHAR(N2);
printf("\n1 -> Adicao\n2 -> Subtracao\n3 -> Multiplicacao\n4 -> Divisao");
printf("\nDigite a operacao: ");
scanf("%d",&OPERACAO);
CALCULA();
MOSTRARESULTADO();
printf("\nDigite 0 para sair ou 1 para realizar outra operacao: ");
scanf("%d",&aux);
TOPO = BASE;
}
return 0;
}
|
C | UTF-8 | 554 | 3.546875 | 4 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFERSIZE 100
void setint(int* ip, int i) {
*ip = i;
}
void write_message(char *message) {
char buffer[BUFFERSIZE];
memset(buffer, '\0', BUFFERSIZE);
strcpy(buffer, message);
printf("%s\n", buffer);
}
int main() {
char message[] = "Look, this seems like an innocent message!";
int a;
int c;
int *b = &c;
a++;
setint(&a, 10);
printf("%d\n", a);
setint(b, 20);
printf("%d\n", *b);
write_message(message);
return 0;
}
|
C | UTF-8 | 2,642 | 2.734375 | 3 | [] | no_license | /*
* TaskRS485.c
*
* Created on: 10/09/2015
* Author: patrizio
*/
#include <FreeRTOS.h>
#include <queue.h>
#include <task.h>
#include <rs485.h>
#include <TaskRS485Slave.h>
// Estado do processo.
static unsigned char processState;
static xQueueHandle commandQueue;
static xQueueHandle responseQueue;
enum {
WAITING_RX_MESSAGE,
PARSING_RESPONSE,
PARSING_MESSAGE,
PUBLISHING_MESSAGE,
SENDING_MESSAGE
};
static void prvRS485SlaveTask(void *arg);
static unsigned char isValidMessageHeader(unsigned char c);
static unsigned char isValidMessageEnd(unsigned char c);
void xStartRS485SlaveTask(void) {
processState = WAITING_RX_MESSAGE;
commandQueue = xQueueCreate(1, 3);
responseQueue = xQueueCreate(1, 3);
if (commandQueue != NULL && responseQueue != NULL) {
xTaskCreate(prvRS485SlaveTask, (signed portCHAR *) "R485", configMINIMAL_STACK_SIZE, NULL, 3, NULL);
}
}
xQueueHandle getRs485CommandQueue(void) {
return commandQueue;
}
xQueueHandle getRs485ResponseQueue(void) {
return responseQueue;
}
static void prvRS485SlaveTask(void *arg) {
unsigned char rxChar;
unsigned char rxMessage[3];
unsigned char* msg;
unsigned char response[3];
unsigned char rxIndex = 0;
for (;;) {
switch (processState) {
case WAITING_RX_MESSAGE:
rs485SetRead();
vTaskDelay(RS485_TRANSITION_DELAY_MS);
rxChar = readRS485();
if (rxChar && isValidMessageHeader(rxChar)) {
rxIndex = 0;
rxMessage[rxIndex] = rxChar;
rxIndex++;
processState = PARSING_MESSAGE;
} else {
flushRs485RxBuffer();
}
break;
case PARSING_MESSAGE:
rxChar = readRS485();
if (rxChar != '\0') {
rxMessage[rxIndex] = rxChar;
if (isValidMessageEnd(rxMessage[rxIndex])) {
flushRs485RxBuffer();
processState = PUBLISHING_MESSAGE;
} else {
rxIndex++;
}
}
break;
case PUBLISHING_MESSAGE:
msg = rxMessage;
while (xQueueSend(commandQueue, msg, portMAX_DELAY) != pdPASS);
processState = PARSING_RESPONSE;
break;
case PARSING_RESPONSE:
while (xQueueReceive(responseQueue, response, portMAX_DELAY) != pdPASS);
processState = SENDING_MESSAGE;
break;
case SENDING_MESSAGE:
rs485SetWrite();
vTaskDelay(RS485_TRANSITION_DELAY_MS);
writeRS485(response);
while (!rs485TransmitComplete());
vTaskDelay(RS485_CHECK_TRANSMIT_OK_DELAY);
processState = WAITING_RX_MESSAGE;
break;
}
}
}
static unsigned char isValidMessageHeader(unsigned char c) {
if (c == '|') {
return 1;
}
return 0;
}
static unsigned char isValidMessageEnd(unsigned char c) {
if (c == '\n') {
return 1;
}
return 0;
}
|
C | UTF-8 | 1,250 | 2.90625 | 3 | [] | no_license | #include "utils.h"
int go = 1;
void Server(char* userFile, char* logFile){
printf("server pid: %d\n", getpid());
int sock, newSocket;
struct sockaddr_in my_addr;
bzero(&my_addr,sizeof(struct sockaddr_in));
sock = socket(AF_INET, SOCK_STREAM, 0);
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(5001);
my_addr.sin_addr.s_addr = INADDR_ANY;
if (bind(sock, (struct sockaddr *) &my_addr, sizeof(my_addr)) < 0) {
perror("bind");
exit(-1);
}
listen(sock, 10);
while(go){
newSocket = accept(sock, NULL, 0);
char message[256];
bzero(message, sizeof(message));
read(newSocket, message, 256);
fprintf(stderr, "Server received:%s\n", message);
//lancia un worker detached
//termina su SIGTERM o SIGINT (go = 0)
}
close(sock);
exit(0);
}
void* Dispatcher(void* data) {
//while (go)
//prod-cons buffer circolare
//controlla se gli utenti sono online (hash table in mutex)
//nel caso invia il messaggio tramite socket
}
void* Worker(void* data) {
//while (go)
//registra nel log-file in mutex
//exec reg o ls | prod-cons con dispatcher (buffer circolare)
}
int main(int argc, char** argv) {
pid_t p;
p = fork();
if(p==0)
Server(userFile, logFile);
else if(p < 0)
printf("fork fallita");
exit(0);
}
|
C | UTF-8 | 10,698 | 2.609375 | 3 | [] | no_license | /** \file client-run.c
* \brief Основные функции.
*
* В этом файле описана главная функция программы.
*/
#include <client-worker-commands.h>
#include <time.h>
#include "client-run.h"
#include "client-logger.h"
#include "client-worker.h"
#include "smtp_sockets.h"
#include "hashtable.h"
int scan_dir_for_new_mail(struct smtp_client_context *ctx, struct hashtable *directory_dict);
int spawn_worker_process(struct smtp_client_context* main_ctx, struct smtp_client_worker_context* worker_ctx);
int spawn_logger_process(struct smtp_client_context* main_ctx);
int dispatch_task_to_worker(struct smtp_client_context* ctx, struct hashtable_node_list *list);
int initialize_client_fd_set(struct smtp_client_context* ctx);
int initialize_directories(struct smtp_client_context* ctx);
static bool main_process_running;
int spawn_worker_process(struct smtp_client_context* main_ctx, struct smtp_client_worker_context* worker_ctx)
{
int sockets[2];
if (create_local_socket_pair(sockets) != 0)
{
log_print(main_ctx->name, "Failed to spawn worker process - socket pair creation failed");
return -1;
}
worker_ctx->process_dir = main_ctx->process_dir;
worker_ctx->sent_dir = main_ctx->sent_dir;
worker_ctx->master_socket = sockets[0];
worker_ctx->worker_socket = sockets[1];
worker_ctx->logger_socket = main_ctx->logger_socket;
worker_ctx->mail_send_timeout = main_ctx->mail_send_timeout;
worker_ctx->mail_retry_wait_time = main_ctx->mail_retry_wait_time;
worker_ctx->is_running = true;
pid_t pid = fork();
worker_ctx->pid = pid;
if (pid == 0)
{
worker_process_run(worker_ctx);
logger_socket = sockets[0];
}
return 0;
}
int spawn_logger_process(struct smtp_client_context* main_ctx)
{
int sockets[2];
if (create_local_socket_pair(sockets) != 0)
{
perror("Failed to spawn logger process - socket pair creation failed");
return -1;
}
main_ctx->logger_socket = sockets[0];
pid_t pid = fork();
if (pid == 0)
{
log_process_run(sockets[1], main_ctx->log_file_name);
}
else
{
main_ctx->logger_pid = pid;
logger_socket = sockets[0];
}
return 0;
}
int initialize_client_fd_set(struct smtp_client_context* ctx)
{
fd_set write_sd;
FD_ZERO(&write_sd);
for (uint32_t i = 0; i < ctx->number_of_workers; i++)
{
int socket = ctx->worker_ctx[i].master_socket;
socket_set_nonblocking(socket, true);
FD_SET(socket, &write_sd);
}
memcpy(&ctx->worker_task_fds, &write_sd, sizeof(write_sd));
}
int initialize_directories(struct smtp_client_context *ctx)
{
log_print(ctx->name, "Checking if directory '%s' exists", ctx->root_dir);
if (!check_if_directory_exists(ctx->root_dir))
{
if(!create_path(ctx->root_dir, 0666))
{
log_print(ctx->name, "Unable to create directory %s", ctx->root_dir);
}
}
if (!check_if_directory_exists(ctx->process_dir))
{
log_print(ctx->name, "Creating '%s' directory", ctx->root_dir);
if(!create_path(ctx->process_dir, 0666))
{
log_print(ctx->name, "Unable to create directory '%s'", ctx->process_dir);
}
}
log_print(ctx->name, "Checking if directory '%s' exists", ctx->process_dir);
if (!check_if_directory_exists(ctx->sent_dir))
{
log_print(ctx->name, "Creating '%s' directory", ctx->process_dir);
if(!create_path(ctx->sent_dir, 0666))
{
log_print(ctx->name, "Unable to create directory '%s'", ctx->sent_dir);
}
}
for (uint32_t i = 0; i < ctx->number_of_workers; i++)
{
char buffer[20];
struct smtp_client_worker_context *worker_ctx = ctx->worker_ctx + i;
log_print(ctx->name, "Creating directory for pid: %d", worker_ctx->pid);
snprintf(buffer, 20, "%d", worker_ctx->pid);
create_subdirectory(ctx->process_dir, buffer, 0666);
}
}
int main_loop(struct smtp_client_context* ctx)
{
log_print(ctx->name, "Starting to look for new mail to send in maildir");
struct hashtable *directory_dict = outgoing_mail_dictionary_create();
initialize_client_fd_set(ctx);
initialize_directories(ctx);
while (main_process_running)
{
scan_dir_for_new_mail(ctx, directory_dict);
sleep(30);
}
log_print(ctx->name, "Finished main loop");
return 0;
}
int scan_dir_for_new_mail(struct smtp_client_context *ctx, struct hashtable *directory_dict)
{
log_print(ctx->name, "Start scanning for new mail");
outgoing_mail_dictionary_add_files_from_directory(directory_dict, ctx->outmail_dir);
for (int i = 0; i < directory_dict->current_size; i++)
{
if (directory_dict->data[i].list_length == 0)
{
continue;
}
log_print(ctx->name, "Found mail for %s domain", directory_dict->data[i].list->key);
dispatch_task_to_worker(ctx, directory_dict->data);
}
log_print(ctx->name, "Scan finished, going to sleep");
}
char *generate_filename(struct smtp_client_context* ctx, const char *domain)
{
char *result = NULL;
char current_time_string[32];
time_t current_time = time(NULL);
strftime(current_time_string, 32, "%Y%m%d%H%M%S", localtime(¤t_time));
int len = snprintf(result, 0, "%s%s%d", current_time_string, domain, ctx->number_of_mail_sent);
result = (char *)malloc(len + 1);
snprintf(result, len + 1, "%s%s%d", current_time_string, domain, ctx->number_of_mail_sent);
ctx->number_of_mail_sent++;
return result;
}
int dispatch_task_to_worker(struct smtp_client_context* ctx, struct hashtable_node_list *list)
{
log_print(ctx->name, "Waiting on select()...");
fd_set fds;
memcpy(&fds, &ctx->worker_task_fds, sizeof(ctx->worker_task_fds));
int result = select(ctx->number_of_workers + 1, NULL, &fds, NULL, NULL);
if (result < 0)
{
log_print(ctx->name, "select() failed");
return -1;
}
char *path = NULL;
struct smtp_client_worker_context *worker_ctx = NULL;
for (uint32_t i = 0; i < ctx->number_of_workers; i++)
{
worker_ctx = ctx->worker_ctx + i;
if (FD_ISSET(worker_ctx->master_socket, &fds))
{
break;
}
else
{
worker_ctx = NULL;
}
}
if (worker_ctx == NULL)
{
log_print(ctx->name, "unable to get free worker after select()");
return -1;
}
int len = snprintf(path, 0, "%s/%d", ctx->process_dir, worker_ctx->pid);
path = (char *)malloc(len + 1);
snprintf(path, len + 1, "%s/%d", ctx->process_dir, worker_ctx->pid);
const char *domain = list->list->key;
size_t domain_len = list->list->key_size;
struct hashtable_node *current_node = list->list;
for (uint32_t i = 0; i < list->list_length; i++)
{
if (strncmp(domain, current_node->key, domain_len) == 0)
{
char *path_to_file = NULL;
char * filename = generate_filename(ctx, domain);
len = snprintf(path_to_file, 0, "%s/%s/%s", path, domain, filename);
path_to_file = (char *)malloc(len + 1);
snprintf(path_to_file, len + 1, "%s/%s/%s", path, domain, filename);
log_print(ctx->name, "Moving '%s' to '%s'", current_node->value, path_to_file);
if (rename(current_node->value, path_to_file) != 0)
{
log_print(ctx->name, "Moving failed");
}
free(path_to_file);
free(filename);
}
}
send_task_to_worker(worker_ctx, domain, domain_len);
free(path);
return 0;
}
int stop_all_worker_processes(struct smtp_client_context* ctx)
{
log_print(ctx->name, "Stopping all workers");
struct client_process_command command =
{
.type = SMTP_CLIENT_PROCESS_STOP
};
for (int i = 0; i < ctx->number_of_workers; i++)
{
struct smtp_client_worker_context *worker_ctx = ctx->worker_ctx + i;
send_terminate_to_worker(worker_ctx);
int status;
waitpid(worker_ctx->pid, &status, 0);
}
return 0;
}
int stop_logger_process(struct smtp_client_context* ctx)
{
log_print(ctx->name, "Stopping logger thread");
log_process_send_terminate();
int status;
waitpid(ctx->logger_pid, &status, 0);
return 0;
}
int run(const char *root_dir, const char *outmail_dir, const char *process_dir, const char *sent_dir,
const char *log_file_name, uint32_t mail_send_timeout, uint32_t mail_retry_wait_time,
uint32_t number_of_workers)
{
main_process_running = true;
int result = 0;
struct smtp_client_context ctx;
// initialize client context
ctx.root_dir = root_dir;
size_t root_dir_len = strlen(root_dir);
char *outmail_path = (char*)malloc(0x100);
strncpy(outmail_path, root_dir, 0x100);
strncat(outmail_path, outmail_dir, 0x100 - root_dir_len);
ctx.outmail_dir = outmail_path;
char *process_path = (char*)malloc(0x100);
strncpy(process_path, root_dir, 0x100);
strncat(process_path, process_dir, 0x100 - root_dir_len);
ctx.process_dir = process_path;
char *sent_path = (char*)malloc(0x100);
strncpy(sent_path, root_dir, 0x100);
strncat(sent_path, sent_dir, 0x100 - root_dir_len);
ctx.sent_dir = sent_path;
ctx.log_file_name = log_file_name;
ctx.mail_send_timeout = mail_send_timeout;
ctx.mail_retry_wait_time = mail_retry_wait_time;
ctx.number_of_workers = number_of_workers;
ctx.worker_ctx = (struct smtp_client_worker_context*)malloc(sizeof(struct smtp_client_worker_context) * number_of_workers);
ctx.number_of_mail_sent = 0;
ctx.name = MAIN_PROCESS_NAME;
spawn_logger_process(&ctx);
log_print(ctx.name, "Starting SMTP client");
log_print(ctx.name, "Number of worker processes: %d");
//spawn worker processes
for (unsigned int i = 0; i < number_of_workers; i++)
{
if (spawn_worker_process(&ctx, ctx.worker_ctx + i) != 0)
{
log_print(ctx.name, "Spawning worker process failed (id=%d)", i);
return -1;
}
}
log_print(ctx.name, "All worker processes started");
log_print(ctx.name, "Start main loop");
main_loop(&ctx);
log_print(ctx.name, "Quitted main loop");
log_print(ctx.name, "Stopping all workers");
stop_all_worker_processes(&ctx);
log_print(ctx.name, "Stopping logger");
stop_logger_process(&ctx);
free(ctx.worker_ctx);
free(ctx.outmail_dir);
free(ctx.process_dir);
free(ctx.sent_dir);
return result;
};
|
C | UTF-8 | 2,438 | 2.59375 | 3 | [] | no_license | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* set_file.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: piquerue <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/05/19 00:50:46 by piquerue #+# #+# */
/* Updated: 2018/07/30 00:50:30 by piquerue ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int set_file_get_command(char *cmd, int type)
{
if (ft_strcmp(cmd, "##start") == 0)
return (1);
if (ft_strcmp(cmd, "##end") == 0)
return (2);
return (type);
}
static int set_file_set_ants(char *cmd, t_lem *lem)
{
char *rk;
lem->atns = ft_atoi(cmd);
rk = ft_itoa(lem->atns);
if (ft_strcmp(rk, cmd) != 0 || lem->atns <= 0)
exit(0);
ft_strdel(&rk);
return (1);
}
static int set_file_set_tube(char *l, int tube, t_lem *lem, int type)
{
t_listroom *room;
tube = is_tube_or_not(l);
if (type >= 0)
{
if (tube == 1)
add_tube(l, &(lem->rooms));
else
add_room(set_room(l, type), &(lem->rooms));
if (type == 2)
{
room = *(&(lem->rooms));
while (room->next)
{
if (room->room->start == 1)
return (1);
room = room->next;
}
tube = (room->room->start == 1) ? 1 : 0;
}
}
return (tube);
}
static int set_file_exist(t_lem *lem)
{
if (!lem->filecontents)
exit(0);
return (0);
}
void set_file(t_lem *lem)
{
int i;
int type;
int tube;
int done;
i = -1;
type = 0;
tube = 0;
done = set_file_exist(lem);
while (lem->filecontents[++i])
if (ft_strlen(lem->filecontents[i]) == 0)
return ;
else if (lem->filecontents[i][0] == '#')
type = set_file_get_command(lem->filecontents[i], type);
else
{
if (done == 0 && type == 0)
done = set_file_set_ants(lem->filecontents[i], lem);
else if (done == 0 && type >= 1)
exit(0);
else
tube = set_file_set_tube(lem->filecontents[i], tube, lem, type);
type = 0;
}
}
|
C | UTF-8 | 920 | 3.671875 | 4 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
struct vec {
int arrSize;
int arr[];
};
struct vec *vecArr;
vecArr = malloc(sizeof(struct vec));
if (vecArr == NULL) {
perror("Error ");
return EXIT_FAILURE;
}
if (argc != 2) {
fprintf(stderr, "Parameter missing or too many");
return EXIT_FAILURE;
}
int amountOfElements = atoi(argv[1]);
if (amountOfElements < 0) {
fprintf(stderr, "Parameter needs to be >= 0");
return EXIT_FAILURE;
}
vecArr->arrSize = vecArr->arrSize + amountOfElements;
vecArr = realloc(vecArr, amountOfElements * sizeof(int));
if (vecArr == NULL) {
perror("Error");
return EXIT_FAILURE;
}
for (int i = 0; i < vecArr->arrSize; i++) {
printf("%u\n", vecArr->arr[i]);
}
free(vecArr);
return EXIT_SUCCESS;
}
|
C | UTF-8 | 4,378 | 2.703125 | 3 | [] | no_license | #include <Windows.h>
#include <stdio.h>
#include <string.h>
#include "common.h"
#define buffSize 1000
HANDLE hComm; // Handle to the Serial port
OVERLAPPED o;
void openComPort()
{
BOOL Status; // Status of the various operations
char ComPortName[] = "\\\\.\\COM3"; // Name of the Serial port(May Change) to be opened,
hComm = CreateFile(ComPortName, // Name of the Port to be Opened
GENERIC_READ | GENERIC_WRITE, // Read/Write Access
0, // No Sharing, ports cant be shared
NULL, // No Security
OPEN_EXISTING, // Open existing port only
/*FILE_FLAG_OVERLAPPED*/0,
NULL); // Null for Comm Devices
/*if (hComm == INVALID_HANDLE_VALUE)
printf("\n Error! - Port %s can't be opened\n", ComPortName);
else
printf("\n Port %s Opened\n ", ComPortName);*/
o.hEvent = CreateEvent(
NULL, // default security attributes
TRUE, // manual-reset event
FALSE, // not signaled
NULL // no name
);
// Initialize the rest of the OVERLAPPED structure to zero.
o.Internal = 0;
o.InternalHigh = 0;
o.Offset = 0;
o.OffsetHigh = 0;
/*------------------------------- Setting the Parameters for the SerialPort ------------------------------*/
DCB dcbSerialParams = { 0 }; // Initializing DCB structure
dcbSerialParams.DCBlength = sizeof(dcbSerialParams);
Status = GetCommState(hComm, &dcbSerialParams); //retreives the current settings
/*if (Status == FALSE)
printf("\n Error! in GetCommState()");
*/
dcbSerialParams.BaudRate = CBR_115200; // Setting BaudRate = 115200
dcbSerialParams.ByteSize = 8; // Setting ByteSize = 8
dcbSerialParams.StopBits = ONESTOPBIT; // Setting StopBits = 1
dcbSerialParams.Parity = NOPARITY; // Setting Parity = None
dcbSerialParams.fDtrControl = 0;
dcbSerialParams.fRtsControl = 0;
Status = SetCommState(hComm, &dcbSerialParams); //Configuring the port according to settings in DCB
SetCommMask(hComm, EV_RXCHAR);
//if (Status == FALSE)
//{
// printf("\n Error! in Setting DCB Structure");
//}
//else //If Successfull display the contents of the DCB Structure
//{
// printf("\n\n Setting DCB Structure Successfull\n");
// printf("\n Baudrate = %d", dcbSerialParams.BaudRate);
// printf("\n ByteSize = %d", dcbSerialParams.ByteSize);
// printf("\n StopBits = %d", dcbSerialParams.StopBits);
// printf("\n Parity = %d", dcbSerialParams.Parity);
//}
/*------------------------------------ Setting Timeouts --------------------------------------------------*/
COMMTIMEOUTS timeouts = { 0 };
timeouts.ReadIntervalTimeout = 50;
timeouts.ReadTotalTimeoutConstant = 50;
timeouts.ReadTotalTimeoutMultiplier = 10;
timeouts.WriteTotalTimeoutConstant = 50;
timeouts.WriteTotalTimeoutMultiplier = 10;
SetCommTimeouts(hComm, &timeouts);
/* printf("\n\n Error! in Setting Time Outs");
else
printf("\n\n Setting Serial Port Timeouts Successfull");*/
/*------------------------------------ Setting Receive Mask ----------------------------------------------*/
Status = SetCommMask(hComm, EV_RXCHAR); //Configure Windows to Monitor the serial device for Character Reception
/*if (Status == FALSE)
printf("\n\n Error! in Setting CommMask");
else
printf("\n\n Setting CommMask successfull\n");*/
}
void comSend(const char* data, int len)
{
char lpBuffer[buffSize]; // lpBuffer should be char or byte array, otherwise write wil fail
DWORD dNoOFBytestoWrite; // No of bytes to write into the port
DWORD dNoOfBytesWritten = 0; // No of bytes written to the port
dNoOFBytestoWrite = min(buffSize, len); // Calculating the no of bytes to write into the port
strncpy(lpBuffer, data, dNoOFBytestoWrite);
BOOL Status = WriteFile(hComm, // Handle to the Serialport
lpBuffer, // Data to be written to the port
dNoOFBytestoWrite, // No of bytes to write into the port
&dNoOfBytesWritten, // No of bytes written to the port
NULL);
}
int comRead(char *buff, int bufSize)
{
int bytesRead;
ReadFile(hComm, buff, bufSize, &bytesRead, 0);
if (bytesRead > 0 && bytesRead < bufSize)
{
buff[bytesRead] = 0;
}
return bytesRead;
} |
C | UTF-8 | 2,017 | 3.265625 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <strings.h>
#define BUFFER_SIZE 1024
int main(int argc, char **argv) {
if (argc != 3) {
fprintf(stderr, "usage: ./tcp_client <Sever IP> <Port>\n");
exit(-1);
}
const char* ip = argv[1];
int port = atoi(argv[2]);
// 0. 初始化服务端地址(IP+Port)
struct sockaddr_in server_addr;
bzero(&server_addr, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(port);
inet_pton(AF_INET, ip, &server_addr.sin_addr);
// 1. 创建socket
int sock_fd;
sock_fd = socket(AF_INET, SOCK_STREAM, 0);
// 2. 建立连接
int conn_ret = connect(sock_fd, (struct sockaddr *) &server_addr, sizeof(server_addr));
if (conn_ret < 0) {
perror("connect()");
exit(-1);
}
fprintf(stdout, "connect Server(%s:%d) success.\n", ip, port);
// 3. 发送数据
char buff[BUFFER_SIZE];
bzero(buff, BUFFER_SIZE);
strcpy(buff, "Hello, Server!");
int send_ret = send(sock_fd, buff, sizeof(buff), 0);
if (send_ret < 0) {
perror("send()");
close(sock_fd);
exit(-1);
} else if (send_ret == 0) {
fprintf(stderr, "server close socket!\n");
close(sock_fd);
exit(-1);
}
fprintf(stdout, "Client: %s\n", buff);
// 4. 接收数据
bzero(buff, BUFFER_SIZE);
int recv_ret = recv(sock_fd, buff, BUFFER_SIZE, 0);
if (recv_ret < 0) {
perror("recv()");
close(sock_fd);
exit(-1);
} else if (recv_ret == 0) {
fprintf(stderr, "server close socket!\n");
close(sock_fd);
exit(-1);
}
fprintf(stdout, "Server: %s\n", buff);
// 5、关闭连接
close(sock_fd);
exit(0);
}
// build:
// gcc -o tcp_client tcp_client.c
// run
// ./tcp_client 127.0.0.1 8080 |
C | GB18030 | 584 | 4.125 | 4 | [] | no_license | #include <stdio.h>
void fun(int a)
{
if (a == 1)
{
printf("a == %d\n", a);
return; // жϺҪ
}
fun(a - 1);
printf("a = %d\n", a);
}
// ݹۼ
int add(int n)
{
if (n < 1)
{
return n;
}
return n + add(n - 1);
}
int add2(int n)
{
if (n == 100)
{
return n;
}
return n + add2(n + 1);
}
int main()
{
//fun(6);
//ݹ1-100ĺ
int a = add(100);
printf("add:%d\n", a);
a = add2(1);
printf("add2:%d\n", a);
int n = 100;
int sum = 0;
for (int i = 0; i <= 100; i++)
{
sum += i;
}
printf("sum=%d\n", sum);
return 0;
} |
C | UTF-8 | 2,637 | 2.828125 | 3 | [] | no_license | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ligne_img.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jmoussu <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/02/12 16:09:28 by jmoussu #+# #+# */
/* Updated: 2019/02/15 17:00:49 by jmoussu ### ########.fr */
/* */
/* ************************************************************************** */
#include "fdf.h"
void linebhi(t_coord p1, t_coord p2, t_mv v)
{
int dx;
int dy;
int cumul;
int x;
int y;
x = p1.x;
y = p1.y;
dx = p2.x - p1.x;
dy = p2.y - p1.y;
fill_pixel(v.img, x, y);
y = p1.y + 1;
cumul = dy / 2;
while (y <= p2.y)
{
cumul += dx;
if (cumul >= dy)
{
cumul -= dy;
x += 1;
}
fill_pixel(v.img, x, y);
y++;
}
}
void linebli(t_coord p1, t_coord p2, t_mv v)
{
int dx;
int dy;
int cumul;
int x;
int y;
x = p1.x;
y = p1.y;
dx = p2.x - p1.x;
dy = (p2.y - p1.y);
fill_pixel(v.img, x, y);
x = p1.x + 1;
cumul = dx / 2;
while (x <= p2.x)
{
cumul += dy;
if (cumul >= dx)
{
cumul -= dx;
y += 1;
}
fill_pixel(v.img, x, y);
x++;
}
}
void linehli(t_coord p1, t_coord p2, t_mv v)
{
int dx;
int dy;
int cumul;
int x;
int y;
x = p1.x;
y = p1.y;
dx = ABS(p2.x - p1.x);
dy = ABS(p2.y - p1.y);
fill_pixel(v.img, x, y);
x = p1.x + 1;
cumul = dx / 2;
while (x <= p2.x)
{
cumul += dy;
if (cumul >= dx)
{
cumul -= dx;
y -= 1;
}
fill_pixel(v.img, x, y);
x++;
}
}
void linehhi(t_coord p1, t_coord p2, t_mv v)
{
int dx;
int dy;
int cumul;
int x;
int y;
x = p1.x;
y = p1.y;
dx = ABS(p2.x - p1.x);
dy = ABS(p2.y - p1.y);
fill_pixel(v.img, x, y);
y = p1.y + 1;
cumul = dy / 2;
while (y >= p2.y)
{
cumul += dx;
if (cumul >= dy)
{
cumul -= dy;
x += 1;
}
fill_pixel(v.img, x, y);
y--;
}
}
void linei(t_coord p1, t_coord p2, t_mv v)
{
t_coord pt;
int dx;
int dy;
if (p1.x > p2.x)
{
pt = p1;
p1 = p2;
p2 = pt;
}
dx = ABS(p2.x - p1.x);
dy = ABS(p2.y - p1.y);
if (p1.y > p2.y)
{
if (dx > dy)
linehli(p1, p2, v);
else
linehhi(p1, p2, v);
}
else if (dx > dy)
linebli(p1, p2, v);
else
linebhi(p1, p2, v);
}
|
C | UTF-8 | 2,640 | 3.859375 | 4 | [] | no_license | #include "GeraSemente.h"
int SementeMain (char *senha) {
int semente=0;
if ((senha[0] >= 'A') && (senha[0] <= 'Z')) {
//converte com os valores de letra maiuscula
semente = ConverteMaiuscula (senha);
} else if ((senha[0] >= 'a') && (senha[0] <= 'z')) {
//converte com os valores de letra minuscula
semente = ConverteMinuscula (senha);
} else if ((senha[0] >= '0') && (senha[0]) <= '9') {
//converte com os valores de numeros
semente = ConverteNumero (senha);
}
return semente;
//retorna a semente
}
int ConverteMaiuscula (char *senha) {
//vai converter a senha quando o primeiro caractere e uma letra maiuscula
//le a quantidade de cada tipo de caractere para gerar a semente
int tamanho=0, semente=0;
int maiuscula=0, minuscula=0, numeros=0;
tamanho = strlen (senha);
LeQuantidades (senha, tamanho, &maiuscula, &minuscula, &numeros);
if (minuscula == 0) {
//caso a quantidade de minusculas seja 0
semente = ((maiuscula * 8) * (1 * 1)) - (numeros * 7);
} else {
semente = ((maiuscula * 8) * (minuscula * 4)) - (numeros * 7);
}
return semente;
}
int ConverteMinuscula (char *senha) {
//vai converter a senha quando o primeiro caractere e uma letra minuscula
int tamanho=0, semente=0;
int maiuscula=0, minuscula=0, numeros=0;
tamanho = strlen (senha);
LeQuantidades (senha, tamanho, &maiuscula, &minuscula, &numeros);
if (maiuscula == 0) {
//caso a quantidade de maiusculas seja 0
semente = ((1 * 1) * (minuscula * 6)) - (numeros * 5);
} else {
semente = ((maiuscula * 3) * (minuscula * 6)) - (numeros * 5);
}
return semente;
}
int ConverteNumero (char *senha){
//vai converter a senha quando o primeiro caractere e um numero
int tamanho=0, semente=0;
int maiuscula=0, minuscula=0, numeros=0;
tamanho = strlen (senha);
LeQuantidades (senha, tamanho, &maiuscula, &minuscula, &numeros);
if (maiuscula == 0) {
//caso o numero de maiusculas seja 0
semente = ((1 * 1) * (minuscula * 2)) - (numeros * 11);
} else if (minuscula == 0) {
//caso o numero de minusculas seja 0
semente = ((maiuscula * 9) * (1 * 2)) - (numeros * 11);
} else {
semente = ((maiuscula * 9) * (minuscula * 2)) - (numeros * 11);
}
return semente;
}
void LeQuantidades (char *senha, int tamanho, int *maiuscula, int *minuscula, int *numeros) {
int i;
for (i=0; i < tamanho; i++) {
if ((senha[i] >= 'A') && (senha[i] <= 'Z')) {
*maiuscula += 1;
} else if ((senha[i] >= 'a') && (senha[i] <= 'z')) {
*minuscula += 1;
} else if ((senha[i] >= '0') && (senha[i]) <= '9') {
*numeros += 1;
}
}
}
|
C | UTF-8 | 2,297 | 2.9375 | 3 | [] | no_license | #include <stdint.h>
#include <unistd.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#define WITH_PRINT ( 0 )
/*
Lorant SZABO
Build with:
`gcc -Wall -Wextra -pedantic -O0 -ggdb -o branch_test branch_test.c'
Inspect assembly code for the critical section (e.g. compiler doesn't optimized
away important steps):
`objdump -d -S (-M intel) branch_test'
Run with perf (usually perf packed with 'linux-tools-generic' / 'linux-tools-common')
`perf stat ./branch_test 17 3'
And watch for branch-misses!
E.g.:
``
*/
int main(int argc, char const *argv[]) {
register uint64_t shr;
register volatile uint64_t x = 0;
int shr_len = 32;
register int shr_len_minus_1 = 31;
register uint64_t mask = (1UL << shr_len) - 1;
/* run for only 1 sec */
alarm(1);
signal(SIGALRM, exit);
/*
* To test every 0-1 cases which are rotary invariant but the 0s and 1s' order matters,
* simply odd numbers should be used as input. To test **only** the different
* integer partitions of 0s and 1s, A194602 series could be used (from oeis.org)
* - this ommit the 0s and 1s groups to be varible (e.g. 0111011011 and 0110111011
* are not used in that series at the same time).
*/
if (argc == 3) {
shr_len = atoi(argv[1]);
shr_len_minus_1 = shr_len - 1;
if (shr_len == 64)
mask = 0xffffffffffffffffUL;
else
mask = (1UL << shr_len) - 1;
shr = atol(argv[2]);
shr &= mask;
} else {
printf("Usage: %s <shr_length> <shr_init_value>\n", argv[0]);
exit(-1);
}
#if WITH_PRINT
printf("shr_len: %d, shr: 0x%0*lx\n", shr_len, ((shr_len + 3) >> 2), shr);
#endif
while (1) {
if (shr & 1) {
/* dummy, unreductible instructions to (hopefully) fill the pipeline */
++x;
x &= 0x1234567890111111UL;
x ^= 0x1edcba9876111111UL;
++x;
x &= 0x2234567890222222UL;
x ^= 0x2edcba9876222222UL;
++x;
x &= 0x3234567890333333UL;
x ^= 0x3edcba9876333333UL;
} else {
--x;
x &= 0x4234567890444444UL;
x ^= 0x4edcba9876444444UL;
--x;
x &= 0x5234567890555555UL;
x ^= 0x5edcba9876555555UL;
--x;
x &= 0x6234567890666666UL;
x ^= 0x6edcba9876666666UL;
}
/* rotate around shift register with the initial content */
shr = ( shr >> (shr_len_minus_1) ) | ( shr << 1 );
shr &= mask;
}
return 0;
} |
C | UTF-8 | 1,264 | 3.171875 | 3 | [] | no_license | #include <stdio.h>
#include <string.h>
#include <malloc.h>
#include <stdlib.h>
int main(){
char **line=NULL, c;
int linenum=0, letternum=0, nword=0, j, i=0;
FILE *fpin, *fpout;
fpin=fopen("file.txt", "rt");
if(fpin==NULL)
return;
fpout=fopen("result.txt", "wt");
if(fpout==NULL)
return;
line=(char**)malloc(sizeof(char*));
line[0]=(char*)malloc(sizeof(char));
while((c=fgetc(fpin))!=EOF){
line[linenum] = (char*)realloc(line[linenum], letternum + 1);
line[linenum][letternum++] = c;
if (c=='\n'){
line[linenum] = (char*)realloc(line[linenum], letternum + 1);
line[linenum][letternum] = '\0';
line = (char**)realloc(line, ((++linenum) + 1) * sizeof(char*));
line[linenum] = (char*)malloc(sizeof(char));
letternum = 0;
}
}
line[linenum] = (char*)realloc(line[linenum], letternum + 1);
line[linenum][letternum] = '\n';
line[linenum] = (char*)realloc(line[linenum], letternum );
line[linenum][letternum] = '\0';
for(i=0;i<=linenum;i++){
for(j=0;line[i][j]!='\0';j++){
printf("%c", line[i][j]);
}
}
printf("\n");
fclose(fpin);
fclose(fpout);
return 0;
} |
C | UTF-8 | 900 | 2.796875 | 3 | [
"MIT"
] | permissive | #pragma once
#include "core.h"
#include "ir/ir.h"
i64 convertLiteralToInt64(IR::Literal& literal)
{
auto& primitive = literal.getType()->getPrimitive();
assert(primitive.isConcrete() && primitive.isInteger());
if (primitive.Signed)
{
switch (primitive.size)
{
case 8: return literal.readValue<i8>();
case 16: return literal.readValue<i16>();
case 32: return literal.readValue<i32>();
case 64: return literal.readValue<i64>();
default:
assert("int size not supported in evaluation");
}
}
else
{
switch (primitive.size)
{
case 8: return literal.readValue<u8>();
case 16: return literal.readValue<u16>();
case 32: return literal.readValue<u32>();
case 64:
{
auto uvalue = literal.readValue<u64>();
assert(uvalue < (u64)INT64_MAX);
return uvalue;
}
default:
assert("int size not supported in evaluation");
}
}
return -1;
} |
C | UTF-8 | 4,227 | 2.859375 | 3 | [] | no_license | #include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<memory.h>
int numlen(int al[]);
void plus(void);
int minus(void);
void mutiply(void);
void divise(void);
void stvnum(int num[]);
void rm0(int num[]);
void rm1(int num[]);
int num1[501]={-1};
int num2[501]={-1};
char non[501]={0};
int main(void){
int ch;
char op;
int i=0;
int j;
while(1){
// ch=getchar();
i=0;
memset(num1,-1,sizeof(num1));
memset(num2,-1,sizeof(num1));
// for(i=0;i<=500;i++){
// printf("%d",num1[i]);
// }
// puts("----");
//exit(0);
// printf("hello");
//exit(0);
while((ch=getchar())!=' '){
if(ch==EOF){
exit(0);
}
ch-=48;
num1[i]=ch;
// printf("%d",num1[i]);
i++;
// if(i==10){
// break;
// }
}
// exit(0);
// puts(" ");
// puts("----");
// for(j=0;j<=50;j++){
// printf("%d",num2[j]);
// }
// puts(" ");
// puts("----");
op=getchar();
// putchar(op);
ch=getchar();
// puts("----");
// for(j=0;j<=50;j++){
// printf("%d ",num1[j]);
// }
// puts("");
// puts("----");
// exit(0);
i=0;
while(!(((ch=getchar())=='\n')||(ch==EOF))){
// printf("%c\n",ch);
ch-=48;
num2[i]=ch;
// printf("num2[%d]=%d\n",i,num2[i]);
i++;
}
// puts("----");
// puts(" ");
// for(j=0;j<=50;j++){
// printf("%d ",num2[j]);
// }
// puts("");
// puts("----");
// exit(0);
if(op=='+'){
plus();
// puts("plus");
// exit(0);
}
else if(op=='-'){
minus();
}
else if(op=='*'){
mutiply();
}
else if(op=='/'){
divise();
}
i=0;
while(num1[i]!=-1){
printf("%d",num1[i]);
i++;
}
puts("");
// if(ch==10){
// exit(0);
// }
// printf("ch=%d\n",ch);
// printf("1");
}
return 0;
}
void plus(void){
int ans[501]={0};
int len,i;
if(numlen(num1)>=numlen(num2)){
len=numlen(num1);
}
else{
len=numlen(num2);
}
// exit(0);
stvnum(num1);
stvnum(num2);
rm1(num1);
rm1(num2);
for(i=0;i<len;i++){
ans[i]=num1[i]+num2[i];
}
for(i=0;i<=499;i++){
ans[i+1]+=ans[i]/10;
ans[i]=ans[i]%10;
}
rm0(ans);
stvnum(ans);
// exit(0);
for(i=0;i<=500;i++){
num1[i]=ans[i];
}
return;
}
int minus(void){
int ans[501]={0};
int len,i;
int plus;
plus=1;
if(numlen(num1)>=numlen(num2)){
len=numlen(num1);
}
else if(numlen(num1)<numlen(num2)){
printf("-");
plus=0;
len=numlen(num2);
}
else{
len=numlen(num1);
for(i=0;i<=500;i++){
if(num1[i]>num2[i]){
break;
}
else if(num1[i]<num2[i]){
printf("-");
plus=0;
len=numlen(num2);
break;
}
}
}
// for(i=0;i<=10;i++){
// printf("%d",num1[i]);
// }
// puts("--num1 ");
// for(i=0;i<=10;i++){
// printf("%d",num2[i]);
// }
// puts("--num2 ");
stvnum(num1);
stvnum(num2);
// for(i=0;i<=10;i++){
// printf("%d",num1[i]);
// }
// puts("--num1 ");
// for(i=0;i<=10;i++){
// printf("%d",num2[i]);
// }
// puts("--num2 ");
rm1(num1);
rm1(num2);
// for(i=0;i<=10;i++){
// printf("%d",num1[i]);
// }
// puts("--num1 ");
// for(i=0;i<=10;i++){
// printf("%d",num2[i]);
// }
// puts("--num2 ");
for(i=0;i<len;i++){
if(plus==1){
ans[i]=num1[i]-num2[i]+ans[i];
}
else{
ans[i]=num2[i]-num1[i]+ans[i];
}
if(ans[i]<0){
ans[i]+=10;
ans[i+1]-=1;
}
}
// for(i=0;i<=499;i++){
// ans[i+1]+=ans[i]/10;
// ans[i]=ans[i]%10;
// }
rm0(ans);
stvnum(ans);
// exit(0);
for(i=0;i<=500;i++){
num1[i]=ans[i];
}
return 0;
}
void divise(void){
return;
}
void mutiply(void){
int ans[501]={0};
int i,j;
stvnum(num1);
stvnum(num2);
for(i=0;i<numlen(num2);i++){
for(j=0;j<numlen(num1);j++){
ans[j+i]+=num2[i]*num1[j];
}
}
for(i=0;i<=499;i++){
ans[i+1]+=ans[i]/10;
ans[i]=ans[i]%10;
}
rm0(ans);
stvnum(ans);
for(i=0;i<=500;i++){
num1[i]=ans[i];
}
return;
}
void stvnum(int *av){
int i;
int len;
int r;
len=numlen(av);
for(i=1;i<=len/2;i++){
r=av[i-1];
av[i-1]=av[len-i];
av[len-i]=r;
}
return;
}
int numlen(int al[]){
int i=0;
while(al[i]!=-1){
i++;
}
return i;
}
void rm0(int num[]){
int i;
for(i=500;i>=1;i--){
if(num[i]==0){
num[i]=-1;
}
else{
// printf("break; whe i=%d\n",i);
break;
}
}
return;
}
void rm1(int num[]){
int i;
// for(i=0;i<=500;i++){
// printf("%d",num[i]);
// }
// puts("");
for(i=500;i>=1;i--){
if(num[i]==-1){
num[i]=0;
}
else{
// printf("break when i=%d\n",i);
break;
}
}
return;
}
|
C | UTF-8 | 703 | 4 | 4 | [] | no_license | #include <stdio.h>
/* prints a histogram of the lengths of words */
main()
{
int c, i, j;
int count = 0;
int words[10];
for (i = 0; i < 10; ++i)
words[i] = 0;
while ((c = getchar()) != EOF) {
if (c != ' ' && c != '\n' && c != '\t' && c != '.') {
++count;
} else {
if (count != 0)
++words[count];
count = 0;
}
}
printf("words lengths =");
for (i = 0; i < 10; ++i)
printf(" %d", words[i]);
printf("\n\n");
printf("%10s", " ");
printf("Histogram of Word Lengths\n");
for (i = 1; i < 10; ++i) {
printf("Length of");
printf(" %d", i);
for (j = 0; j < words[i]; ++j) {
printf("-");
}
printf("\n");
}
}
|
C | UTF-8 | 213 | 3.53125 | 4 | [] | no_license | #include <stdio.h>
#include <math.h>
int main()
{
int x1, y1, x2, y2;
scanf("%d %d %d %d", &x1, &y1, &x2, &y2);
double distancia = sqrt(pow((x2 - x1),2) + pow((y2 - y1),2));
printf("%.4lf\n", distancia);
} |
C | UTF-8 | 717 | 3.59375 | 4 | [] | no_license | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
void str_sum_digits(const char *cs);
int main()
{
const char cs[100] = { 0 };
printf("enter string with digits\n");
scanf("%[0-9]", &cs);
printf("cs %s\n", cs);
str_sum_digits(cs);
//*cs=getchar();
//printf("Hello World!");
return 0;
}
void str_sum_digits(const char *cs)
{
int a;
int b;
int i;
int sum = 0;
// const char cs[100] = { 0 };
// printf("enter string with digits\n");
// scanf("%[0-9]", &cs);
b = strlen(cs);
printf("len %d\n", b);
a = atoi(cs);
printf("a=%d\n", a);
for(i=0; i<=b; i++)
{
sum = sum+=(a % 10);
a = a / 10;
}
printf("sum digits=%d\n", sum);
} |
C | UTF-8 | 1,650 | 2.78125 | 3 | [] | no_license | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_formstr_s.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: dbennie <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/08/22 20:43:02 by dbennie #+# #+# */
/* Updated: 2019/08/22 20:43:03 by dbennie ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
static char *ft_printf_s(t_format *form, char *s)
{
char *buf;
char *tmp;
int j;
tmp = s;
if (!s)
tmp = "(null)";
j = ft_strlen(tmp);
if (form->p >= 0 && form->p < j)
j = form->p;
form->len = j;
if (!(buf = (char *)malloc(sizeof(char) * j + 1)))
return (NULL);
buf[j] = '\0';
while (--j >= 0)
buf[j] = tmp[j];
return (buf);
}
void ft_formstr_s(t_format *form, char *s)
{
if (!(form->str = ft_printf_s(form, s)))
exit(0);
if ((form->w && form->f[4] && !form->f[0])
&& form->p < 0 && form->w > form->len)
ft_addstr(form, form->w - form->len, '0', 0);
if (form->w > form->len)
{
if (form->f[0])
ft_addstr(form, form->w - form->len, ' ', 1);
else
ft_addstr(form, form->w - form->len, ' ', 0);
}
}
|
C | UTF-8 | 884 | 2.75 | 3 | [] | no_license | #ifndef R_PIN_H
#define R_PIN_H
#include <stdio.h>
#include "struct.h"
#define LED_1 ("4") //Pines GPIO
#define LED_2 ("17")
#define LED_3 ("27")
#define LED_4 ("22")
#define LED_5 ("18")
#define LED_6 ("23")
#define LED_7 ("24")
//Las siguientes funciones son para el manejo de pines en el RASPBERRY PI
// Esta función cambia el estados de los pines seteados como salidas
//
// char *pin: es un puntero a un string que indica el pin GPIO
// char led_state: caracter 0 o 1 que indica el estado de OFF o ON del pin
void state_set(char * pin, char led_state);
// Esta funcion prepara los pines para ser utilizados en el Rasp pi
//
// void * pointer: puntero a la estructura que acompaña al manejo de estados de los pines
void set_leds (void * pointer);
// Esta funcion finaliza el uso de los pines
//
// No recibe parámetros
void unset_leds (void);
#endif /* LED_PRINT_H */
|
C | UTF-8 | 577 | 3.171875 | 3 | [] | no_license | #include<stdio.h>
main()
{
int mid,n,a[10],i,ele,j;
ele=sizeof(a)/sizeof (a[0]);
for(i=0;i<ele;i++)
{
printf("enter a number...\n");
scanf("%d",&a[i]);
}
for(i=0;i<ele;i++)
printf("%d\t",a[i]);
printf("\n");
int sum=0,k=0,l=0,b[6],c[6];
for(i=0;i<(ele/2+1);i++)
{
if((ele-i)>=5)
{
sum=0;
for(j=i;j<(i+5);j++)
sum=sum+a[j];
b[k++]=sum;
c[l++]=i;
printf("sum=%d\t",sum);
}
}
l=b[0];
j=0;
for(i=0;i<k;i++)
if(l<b[i])
j=i;
printf("index=%d\narray elements\n",j);
for(i=j;i<(j+5);i++)
printf("%d\t",a[i]);
printf("\n");
}
|
C | UTF-8 | 480 | 3.3125 | 3 | [] | no_license | #include<stdio.h>
#include<conio.h>
void main()
{
int size,i,j,sum=0;;
printf("enter size of matrix:-\n ");
scanf("%d",&size);
int arr[size][size];
printf("enter elements in matrix:- \n");
for(i=0;i<size;i++)
{
for(j=0;j<size;j++)
{
scanf("%d",&arr[i][j]);
}
}
for(i=0;i<size;i++)
{
for(j=0;j<size;j++)
{
if(i+j==size-1)
{
sum=sum+arr[i][j];
}
}
}
printf("sum= %d",sum);
}
|
C | UTF-8 | 5,012 | 3.984375 | 4 | [
"MIT"
] | permissive | #include "vector.h"
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <assert.h>
/**
* Struct: Vector
*
* Implements the storage for the vector type defined in `vector.h`. The vector
* struct uses three members:
* `elems` Array of pointers; stores the vector's contents.
* `capacity` Max number of elements the vector can store without
* reallocating.
* `size` Number of elements currently stored.
*/
struct vector {
void **elems;
int capacity;
int size;
};
// Two internal helper functions. Implemented at the bottom of this file.
static void **get_element(const vector v, int i);
static void extend_if_necessary(vector v);
/**
* Create a new, empty vector.
*
* The returned vector will have been dynamically allocated, and must be
* destroyed after use using `vector_destroy`.
*/
vector vector_create() {
// Allocate space for the vector itself, as well as its internal element
// storage (capacity 1 to start).
vector v = malloc(sizeof (vector));
assert(v != NULL);
v->elems = malloc(sizeof (void *));
assert(v->elems != NULL);
// Vector metadata. Capacity starts at one, since we have allocated space for
// one element already.
v->capacity = 1;
v->size = 0;
return v;
}
/**
* Clean up a vector after use.
*
* This function must be called to avoid memory leaks. It frees the vector's
* own storage, but it does not clean up the values that may exist inside of
* it. If a vector is storing the only reference to any dynamically allocated
* values, that memory must be freed by the client beforehand.
*/
void vector_destroy(vector v) {
free(v->elems);
free(v);
}
/**
* Get the size (number of elements stored) of `v`.
*/
int vector_size(const vector v) {
return v->size;
}
/**
* Determine whether `i` is a valid index within `v`.
*/
bool vector_in_bounds(const vector v, int i) {
return i < (size_t) v->size;
}
/**
* Write `value` at the existing index `i` in the vector `v`.
*/
void vector_set(vector v, int i, void *value) {
// We use the `get_element` helper routine to safely get a pointer to the
// given index's location in the vector's own internal storage.
*get_element(v, i) = value;
}
/**
* Get the value at index `i` in `v`.
*/
void *vector_get(const vector v, int i) {
// Hand off the work to the `get_element` helper, which gives us a pointer to
// the matching element within the vector's internal storage. Then, just
// dereference.
return *get_element(v, i);
}
/**
* Insert `value` at index `i` in the vector `v`.
*
* This will shift all existing elements, starting at index `i`, one position
* to the right, so that `value` can occupiy the space at index `i`.
*/
void vector_insert(vector v,int i, void *value) {
v->size += 1;
extend_if_necessary(v);
// Get a reference to the desired element position within the vector's own
// internal storage.
void **target = get_element(v, i);
// We compute the number of elements *including and after* the element to
// remove, and then use `memmove` to shift those elements to the right so as
// to make room for the new value.
int remaining = v->size - i - 1;
memmove(target + 1, target, remaining * sizeof (void *));
*target = value;
}
/**
* Remove and return the value at index `i` of the vector `v`.
*/
void *vector_remove(vector v, int i) {
// Get a reference to the desired element position within the vector's own
// internal storage, and save the found value to return.
void **target = get_element(v, i);
void *result = *target;
// We compute the number of elements *after* the element to remove, and then
// use `memmove` to shift all subsequent elements down to cover the removed
// element.
int remaining = v->size - i - 1;
memmove(target, target + 1, remaining * sizeof (void *));
v->size -= 1;
return result;
}
/**
* Push `value` onto the end of the vector `v`.
*/
void vector_push(vector v, void *value) {
// Offload to the existing insertion routine.
vector_insert(v, v->size, value);
}
/**
* Remove and return the value at the end of the vector `v`.
*/
void *vector_pop(vector v) {
// Offload to `vector_remove`.
return vector_remove(v, v->size - 1);
}
/**
* Internal helper; computes a pointer to the memory location for a given index
* `i` within `v`.
*/
static void **get_element(const vector v, int i) {
assert(i < (size_t) v->size);
return &v->elems[i];
}
/**
* Internal helper; doubles the vector's internal storage capacity when
* necessary (*i.e.*, the vector's `size` becomes greater than its `capacity`).
*/
static void extend_if_necessary(vector v) {
if (v->size > v->capacity) {
// Doubling the capacity when necessary allows for an amortized constant
// runtime for extensions. Using `realloc` will conveniently copy the
// vector's existing contents to any newly allocated memory.
v->capacity *= 2;
v->elems = realloc(v->elems, v->capacity * sizeof (void *));
}
}
|
C | UTF-8 | 1,447 | 4.25 | 4 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
struct value
{
int v;
struct value *next;
};
/*
* Inserts a new value into the LLL. Creates a new node as well
*/
int
insert_LLL(struct value **head, int new_value)
{
struct value *new_node;
/* If head doesn't exist we need to make it */
if(!*head)
{
*head = (struct value*) malloc(sizeof(struct value));
(*head) -> v = new_value;
(*head) -> next = NULL;
return 1;
}
/* If new_value is higher than us, keep going. */
if( (*head) -> v < new_value)
{
return insert_LLL(&((*head) -> next), new_value);
}
/* If we're higher than new_value then we need to change head and put
* the new node in our place and shift us up */
/* if ( (*head) -> v > new_value) */
new_node = (struct value*) malloc(sizeof(struct value));
new_node -> v = new_value;
new_node -> next = (*head);
*head = new_node;
return 1;
}
/*
* Implementation of the insertion sort
*/
int
insertion(int *array, size_t len)
{
struct value *head, *temp;
int i;
head = (struct value*) malloc(sizeof(struct value));
temp = head;
head -> v = array[0];
head -> next = NULL;
for(i = 1; i < len; ++i)
insert_LLL(&(head), array[i]);
for(i = 0; i < len; ++i)
{
array[i] = head -> v;
temp = head;
head = head -> next;
free(temp);
}
return 1;
}
|
End of preview. Expand
in Data Studio
No dataset card yet
- Downloads last month
- 4