language
string | src_encoding
string | length_bytes
int64 | score
float64 | int_score
int64 | detected_licenses
sequence | license_type
string | text
string |
---|---|---|---|---|---|---|---|
C | UTF-8 | 894 | 3 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
struct Cmpl
{
double Im;
double Re;
};
void pisi(struct Cmpl c)
{
printf("%.2f+(%.2f)i\n", c.Re, c.Im );
}
struct Cmpl zbir(struct Cmpl c,struct Cmpl b)
{
struct Cmpl a;
a.Re=c.Re+b.Re;
a.Im=c.Im+b.Im;
return a;
}
struct Cmpl raz(struct Cmpl c,struct Cmpl b)
{
struct Cmpl a;
a.Re=c.Re-b.Re;
a.Im=c.Im-b.Im;
return a;
}
struct Cmpl pro(struct Cmpl a,struct Cmpl b)
{
struct Cmpl c;
c.Re=(a.Re*b.Re) + (a.Im*b.Im)*(-1);
c.Im=a.Re*b.Im + (a.Im)*(b.Re);
return c;
}
struct Cmpl delj(struct Cmpl a,struct Cmpl b)
{
struct Cmpl c;
c.Re=((a.Re*b.Re) + (a.Im*b.Im))/((b.Re)*(b.Re)+(b.Im*b.Im));
c.Im=((a.Im*b.Re) - (a.Re*b.Im))/((b.Re)*(b.Re)+(b.Im*b.Im));
return c;
}
int main()
{
struct Cmpl a, b;
scanf("%lf %lf", &a.Re, &a.Im);
scanf("%lf %lf", &b.Re, &b.Im);
pisi(zbir(a,b));
pisi(raz(a,b));
pisi(pro(a,b));
pisi(delj(a,b));
return 0;
} |
C | UTF-8 | 1,130 | 3.6875 | 4 | [] | no_license | //written by Tyler Raborn
#include "math.h"
#include "stdio.h"
#include "stdlib.h"
float* calculateZeroes(float, float, float);
int main(int argc, char** argv)
{
if (argc!=4)
{
printf("Invalid Number of Args! Usage: /.zeroes 1 2 3\n");
return EXIT_FAILURE;
}
float* ans = (float*)calculateZeroes(atoi(argv[1]), atoi(argv[2]), atoi(argv[3]));
if (ans[2] == 1) printf("Zeroes: {%g, 0} and {%g, 0} \n", ans[0], ans[1]);
else printf("ERROR: Undefined or Invalid Result!\n");
free(ans);
return EXIT_SUCCESS;
}
float* calculateZeroes(float a, float b, float c)
{
float* ret = (float*)malloc(sizeof(float)*3);
float temp_pos, temp_neg;
if ((2*a)!=0)
{
if (pow(b, 2) - (4*a*c) > 0)
{
temp_pos = ((-1 * b) + sqrt(pow(b, 2) - (4*a*c)));
temp_neg = ((-1 * b) - sqrt(pow(b, 2) - (4*a*c)));
ret[0] = temp_pos / (2*a);
ret[1] = temp_neg / (2*a);
ret[2] = 1; //flag = valid
}
else
{
ret[0] = 0.0;
ret[1] = 0.0;
ret[2] = 3; //flag = undefined
}
}
else
{
ret[0] = 0.0;
ret[1] = 0.0;
ret[2] = 0; //flag = dne
}
return ret;
}
|
C | UTF-8 | 525 | 2.796875 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main(int argc, char **argv) {
unsigned int i = 1U;
char key[16] = "RUN_0";
char *value;
pid_t pid;
while ((value = getenv(key)) != NULL) {
pid = fork();
if (pid) { /** père */
wait(NULL);
snprintf(key, 16, "RUN_%d", i++);
} else { /** fils */
execvp(value, argv);
}
}
return EXIT_SUCCESS;
}
|
C | UTF-8 | 2,456 | 3.46875 | 3 | [
"BSD-2-Clause"
] | permissive | /*
* lib-src/ansi/math/modf.c
* ANSI/ISO 9899-1990, Section 7.5.4.6.
*
* double modf(double value, double *iptr)
* Set *iptr to the integer part of value and return the fractional part.
*
* Exceptions:
* Error Return Store Condition
* EDOM NaN NaN value is NaN
* none [+-]Infinity 0.0 value is [+-]Infinity
*
* This source assumes IEEE-format doubles but does not deal with denormals.
*/
#include "mathlib.h"
#include <limits.h>
#if defined(__IEEE_FP__)
double
modf(double value, double *iptr)
{
DOUBLE u;
register int exp;
#if defined(__IEEE_DP_FP__)
register int n;
#endif /* defined(__IEEE_DP_FP__) */
/* Special cases: NaN and infinities. */
if (_isNaN(value)) {
errno = EDOM; /* NaN: domain error */
*iptr = value; /* integer part is NaN */
return value; /* fractional part NaN */
} else if (_isInfinity(value)) {
*iptr = value;
return 0.0; /* [+-]Infinity: no error, fraction is 0 */
}
/* Truncation is easy if value fits in a long. */
if (value >= (double)LONG_MIN && value <= (double)LONG_MAX) {
*iptr = (double)(long)value; /* truncate to integer part */
return value - *iptr; /* return fractional part */
}
/* If the unbiased exponent is large, there are no fraction bits. */
u.d = value;
exp = u.D.exponent - EXP_BIAS;
if (exp >= DBL_MANT_DIG) {
*iptr = value;
return 0.;
}
#if defined(__IEEE_DP_FP__)
/*
* Last resort: brute force.
* This code is required only for double precision representation;
* for single precision, value < LONG_MIN || value > LONG_MAX
* guarantees that exp >= DBL_MANT_DIG (i.e., there are
* more bits in a long than in the significand).
* Shift the significand right by n = DBL_MANT_DIG - 1 - exp bits,
* then shift it left by n bits, to clobber the fraction bits,
* leaving only the integer bits.
* Finally, subtract from the original value to get the fraction.
*/
n = DBL_MANT_DIG - 1 - exp; /* shift count */
if (n < CHAR_BIT * sizeof(unsigned long)) {
/* Shift by fewer bits than a long; high unchanged. */
u.D.frac_low = (u.D.frac_low >> n) << n;
} else {
/* Shift by more bits than a long; low gets zeroed. */
n -= CHAR_BIT * sizeof(unsigned long);
u.D.frac_hi = (u.D.frac_hi >> n) << n;
u.D.frac_low = 0;
}
*iptr = u.d; /* store integer part */
return value - *iptr; /* return fractional part */
#endif /* defined(__IEEE_DP_FP__) */
}
#else
#error !defined(__IEEE_FP__)
#endif /* defined(__IEEE_FP__) */
|
C | UTF-8 | 564 | 3.359375 | 3 | [] | no_license | /* Array of function pointers use case 2 */
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
int keyboard_Interrupt(void)
{
printf("Keyboard Interrupt\n");
}
int mouse_Interrupt(void)
{
printf("Mouse Interrupt\n");
}
int USB_Interrupt(void)
{
printf("USB Interrupt\n");
}
typedef struct
{
char operation[20];
int (*isr)();
}IVT_t;
int main()
{
IVT_t isr_info[] = {
{"KEYBOARD", keyboard_Interrupt},
{"MOUSE", mouse_Interrupt},
{"USB", USB_Interrupt}
};
while(1)
{
isr_info[rand()%3].isr();
sleep(2);
}
return 0;
}
|
C | UTF-8 | 492 | 3.34375 | 3 | [] | no_license | #include <stdio.h>
int main()
{
int Matrix[200][200];
int i,j,d,c;
printf("membuat matrix d x c \n");
printf("masukkan ordo dari matiks tersebut dengan koma sebagai pemisah \n");
scanf("%d , %d",&d,&c);
for(i=0;i<d;i++){
for(j=0;j<c;j++){
printf("masukkan element dari Matriks[%d][%d]\n",i+1,j+1);
scanf("%d",&Matrix[i][j]);
}
}
printf("matrix yang diinputkan \n");
for(i=0;i<d;i++){
for(j=0;j<c;j++){
printf("%-3d",Matrix[i][j]);
}
printf("\n");
}
return 0;
}
|
C | UTF-8 | 2,350 | 3.640625 | 4 | [] | no_license | //Alfred Shaker
//Systems programming
//Assignment 1
//cp1
#include <stdio.h>
#include <dirent.h>
#include <unistd.h>
#include <fcntl.h>
#include <memory.h>
#define BUFFERSIZE 4096
#define COPYMODE 0644
void oops(char *, char *);
int main (int argc,char *argv[]){
int outFile, inFile, len, nChars;
char buf[BUFFERSIZE];
struct dirent *pDirent;
DIR *pDir; //source directory
DIR *dDir; //target directory
//check for correct number of arguments
if (argc < 3){
printf("not enough arguments <dirname>\n");
return 1;
}
//open the directories
//opens source directory
pDir = opendir (argv[1]);
if(pDir == NULL){
printf ("Cannot open directory '%s'\n", argv[1]);
return 1;
}
//opens target directory
//if none, creates one
dDir = opendir (argv[2]);
if (dDir == NULL){
printf("cannot find directory, creating new one");
mkdir(argv[2], 0700);
}
printf("Copying files from %s to %s \n", argv[1], argv[2]);
//go through the source directory to get its contents
//so that they can be copied to the target directory
while ((pDirent = readdir(pDir)) != NULL) {
//access file in first directory
//make the name and path accessable as a variable
int newLen = strlen(argv[1]) + strlen (pDirent->d_name) + 1;
char *fileName = (char *) malloc(newLen);
strcpy (fileName, argv[1]);
strcat (fileName, pDirent->d_name);
// printf("%s\n", fileName);
inFile = open(fileName, O_RDONLY);
//take the name and path from the first directory
//and make it available to the second directory
//so that a new file is created with the same name
int newLen2 = strlen(argv[2]) + strlen (pDirent->d_name) + 1;
char * newFile = (char *) malloc(newLen2);
strcpy (newFile, argv[2]);
strcat (newFile, pDirent->d_name);
//printf("new file name and location: %s\n", newFile);
outFile = creat(newFile, COPYMODE);
//copy the file contents from the first directory to the second
while((nChars = read(inFile, buf, BUFFERSIZE)) > 0)
if( write(outFile, buf, nChars) != nChars)
oops("Write error to ", newFile);
}
printf("Copy successful!\n");
close(inFile);
close(outFile);
closedir(pDir);
closedir(dDir);
return 0;
}
void oops(char *s1, char *s2){
fprintf(stderr, "Error: %s ", s1);
perror(s2);
exit(1);
}
|
C | UTF-8 | 1,607 | 2.515625 | 3 | [] | no_license | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* unix.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: nlowe <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/05/09 23:20:13 by nlowe #+# #+# */
/* Updated: 2017/05/20 15:29:21 by nlowe ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_ls.h"
int recent(t_stat *stats)
{
time_t diff;
time_t max_diff;
max_diff = 3600 * 24 * 30.5 * 6;
diff = time(0) - stats->st_mtime;
if (diff > max_diff || diff < -max_diff)
return (0);
if (diff < 0)
return (-1);
return (1);
}
int is_device(t_stat *stats)
{
if (S_ISBLK(stats->st_mode) || S_ISCHR(stats->st_mode))
return (1);
return (0);
}
int is_repere(char *path)
{
if (ft_strcmp(path, ".") == 0 || ft_strcmp(path, "..") == 0)
return (1);
return (0);
}
int is_hidden(char *path)
{
if (!(path[0]))
return (0);
if (path[0] == '.')
return (1);
return (0);
}
int get_terminal_width(void)
{
struct winsize window;
ioctl(0, TIOCGWINSZ, &window);
return ((int)window.ws_col);
}
|
C | UTF-8 | 3,108 | 2.921875 | 3 | [
"MIT"
] | permissive | #include<stdio.h>
#include<graphics.h>
#include<conio.h>
int c_bgcolor,c_line;
int fill_c = 4;
void draw_xy();
int round1(float x);
void line_draw(int x1,int y1, int x2, int y2, int c);
int dda(int x1, int y1, int x2, int y2, int x[], int y[]);
void fill_me(int x1, int y1);
int main()
{
int x1,x2,y1,y2,x3,y3,x4,y4,x_f,y_f;
clrscr();
/*
printf("\nEnter x coordinate of 1st point (x1)");
scanf("%d",&x1);
printf("\nEnter y coordinate of 1st point (y1)");
scanf("%d",&y1);
printf("\nEnter x coordinate of 2nd point (x2)");
scanf("%d",&x2);
printf("\nEnter y coordinate of 2nd point (y2)");
scanf("%d",&y2);
printf("\nEnter x coordinate of 3rd point (x3)");
scanf("%d",&x3);
printf("\nEnter y coordinate of 3rd point (y3)");
scanf("%d",&y3);
printf("\nEnter x coordinate of 4rth point (x4)");
scanf("%d",&x4);
printf("\nEnter y coordinate of 4rth point (y4)");
scanf("%d",&y4);
*/
x1 = 0;
y1 = 0;
x2 = 30;
y2 = 0;
x3 = 30;
y3 = 30;
x4 = 0;
y4 = 30;
x_f = 10;
y_f = 10;
/*
printf("\nEnter background color(2-14)");
scanf("%d",&c_bgcolor);
printf("\nEnter line color(1 or 15)");
scanf("%d",&c_line);
printf("\nEnter x coordinate of fill me point (x_f)");
scanf("%d",&x_f);
printf("\nEnter y coordinate of fill me point (y_f)");
scanf("%d",&y_f);
*/
c_bgcolor = 3;
c_line = 5;
draw_xy();
//fill_me(x_f,y_f);
line_draw(x1,y1,x2,y2,c_line);
line_draw(x2,y2,x3,y3,c_line);
line_draw(x3,y3,x4,y4,c_line);
line_draw(x4,y4,x1,y1,c_line);
fill_me(320+x_f,240-y_f);
outtextxy(320+x_f,240-y_f,"o");
getch();
return 0;
}
void fill_me(int x1, int y1)
{
if(x1>=320&&x1<=(320+30)&&y1>=(240-30)&&y1<=240)
{
//printf("%d %d",x1,y1);
putpixel(x1,y1,9);
fill_me(x1+1,y1+1);
putpixel(x1,y1,9);
fill_me(x1-1,y1-1);
putpixel(x1,y1,9);
fill_me(x1+1,y1-1);
putpixel(x1,y1,9);
fill_me(x1+1,y1);
putpixel(x1,y1,9);
delay(8);
//printf("%d %d",x1,y1 );
}
}
//to draw x and y axes
void draw_xy()
{
int i;
int gd=DETECT, gm;
initgraph(&gd,&gm,"c://turboc3//bgi");
setbkcolor(c_bgcolor);
}
//dda algorithm
int dda(int x1, int y1, int x2, int y2, int x[], int y[])
{
int dx,dy,dx1,i,dy1,n,length;
float delx,dely;
float xx,yy;
dx=x2-x1;
dy=y2-y1;
if(dx<0)
dx1=-dx;
else
dx1=dx;
if(dy<0)
dy1=-dy;
else
dy1=dy;
if(dx1>dy1)
length=dx1;
else
length=dy1;
delx=(float)dx/length;
dely=(float)dy/length;
xx=x1;
yy=y1;
for(i=0;i<length;i++)
{
x[i]=round1(xx);
y[i]=round1(yy);
xx+=delx;
yy+=dely;
}
return length;
}
int round1(float x)
{
int x1,flag=0;
float ix;
if(x<0)
{
flag=1;
x*=-1;
}
x1=(int)x;//to get whole value
ix=x-x1;
if(ix>.5)
x1++;
if(flag==1)
return -x1;
else
return x1;
}
//draw line
void line_draw(int x1, int y1, int x2, int y2, int c)
{
int x[700], y[700], i,n;
n=dda(x1,y1,x2,y2,x,y);//to generate n pixel coordinates
//to plot all points
for(i=0;i<n;i++)
{
putpixel(320+x[i],240-y[i],c);
delay(10);
}
} |
C | UTF-8 | 11,487 | 3.46875 | 3 | [] | no_license | /*
* ex3.c
*/
#define _GNU_SOURCE
#include <curl/curl.h>
#include <errno.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#define REQUEST_TIMEOUT_SECONDS 2L
#define URL_OK 0
#define URL_ERROR 1
#define URL_UNKNOWN 2
#define QUEUE_SIZE 32
#define handle_error_en(en, msg) \
do { errno = en; perror(msg); exit(EXIT_FAILURE); } while (0)
typedef struct {
int ok, error, unknown;
} UrlStatus;
typedef struct {
void **array;
int size;
int capacity;
int head;
int tail;
pthread_mutex_t mutex;
pthread_cond_t cv_empty; /* get notified when the queue is not full */
pthread_cond_t cv_full; /* get notified when the queue is not empty */
} Queue;
void queue_init(Queue *queue, int capacity) {
/*
* Initializes the queue with the specified capacity.
* This function should allocate the internal array, initialize its properties
* and also initialize its mutex and condition variables.
*/
queue->array = (void**)malloc(sizeof(void*) * capacity);
if (queue->array == NULL) {
perror("unable to allocate memory");
exit(EXIT_FAILURE);
}
queue->capacity = capacity;
queue->size = 0;
queue->head = 0;
queue->tail = 0;
pthread_mutex_init(&(queue->mutex), NULL);
pthread_cond_init(&(queue->cv_empty), NULL);
pthread_cond_init(&(queue->cv_full), NULL);
}
void enqueue(Queue *queue, void *data) {
/*
* Enqueue an object to the queue.
*
* TODO:
* 1. This function should be synchronized on the queue's mutex
* 2. If the queue is full, it should wait until it is not full
* (i.e. cv_empty)
* 3. Add an element to the tail of the queue, and update the tail & size
* parameters
* 4. Signal that the queue is not empty (i.e. cv_full)
*/
int ret;
ret = pthread_mutex_lock(&(queue->mutex));
/* checks if mutex lock was successful */
if (ret != 0){
handle_error_en(ret, "unable to lock mutex");
}
if (queue->size == queue->capacity){
ret = pthread_cond_wait(&(queue->cv_empty), &(queue->mutex));
/* checks if wait was successful */
if (ret != 0){
handle_error_en(ret, "unable to make the thread to wait");
}
}
/* -- CRITICAL SECTION -- */
queue->array[queue->tail] = data;
queue->tail = (queue->tail + 1) % queue->capacity;
queue->size++;
/* -- END OF CRITICAL SECTION -- */
ret = pthread_mutex_unlock(&(queue->mutex));
if (ret != 0){
handle_error_en(ret, "unable to unlock mutex");
}
ret = pthread_cond_signal(&(queue->cv_full));
if (ret != 0){
handle_error_en(ret, "unable to to signal that queue is not empty");
}
}
void *dequeue(Queue *queue) {
/*
* Dequeue an object from the queue.
*
* TODO:
* 1. This function should be synchronized on the queue's mutex
* 2. If the queue is empty, it should wait until it is not empty (i.e. cv_full)
* 3. Read the head element, and update the head & size parameters
* 4. Signal that the queue is not full (i.e. cv_empty)
* 5. Return the dequeued item
*/
void *data;
int ret;
ret = pthread_mutex_lock(&(queue->mutex));
/* checks if mutex lock was successful */
if (ret != 0){
handle_error_en(ret, "unable to lock mutex");
}
if (queue->size == 0){
ret = pthread_cond_wait(&(queue->cv_full), &(queue->mutex));
/* checks if wait was successful */
if (ret != 0){
handle_error_en(ret, "unable to make the thread to wait");
}
}
/* -- CRITICAL SECTION -- */
data = queue->array[queue->head];
queue->head = (queue->head + 1) % queue->capacity;
queue->size--;
/* -- END OF CRITICAL SECTION -- */
ret = pthread_mutex_unlock(&(queue->mutex));
if (ret != 0){
handle_error_en(ret, "unable to unlock mutex");
}
ret = pthread_cond_signal(&(queue->cv_empty));
if (ret != 0){
handle_error_en(ret, "unable to to signal that queue is empty");
}
return data;
}
void queue_destroy(Queue *queue) {
/*
* Free the queue memory and destroy the mutex and the condition variables.
*/
int ret;
free(queue->array);
ret = pthread_mutex_destroy(&(queue->mutex));
if (ret != 0) {
handle_error_en(ret, "unable to destroy mutex");
}
ret = pthread_cond_destroy(&(queue->cv_empty));
if (ret != 0) {
handle_error_en(ret, "unable to destroy cv_empty condition variable");
}
ret = pthread_cond_destroy(&(queue->cv_full));
if (ret != 0) {
handle_error_en(ret, "unable to destroy cv_full condition variable");
}
}
void usage() {
fprintf(stderr, "usage:\n\t./ex3 FILENAME NUMBER_OF_THREADS\n");
exit(EXIT_FAILURE);
}
int check_url(const char *url) {
CURL *curl;
CURLcode res;
long response_code = 0L;
int http_status = URL_UNKNOWN;
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, REQUEST_TIMEOUT_SECONDS);
curl_easy_setopt(curl, CURLOPT_NOBODY, 1L); /* do a HEAD request */
res = curl_easy_perform(curl);
if(res == CURLE_OK) {
res = curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code);
if (res == CURLE_OK &&
response_code >= 200 &&
response_code < 400) {
http_status = URL_OK;
} else {
http_status = URL_ERROR;
}
}
curl_easy_cleanup(curl);
}
return http_status;
}
typedef struct {
Queue *url_queue;
Queue *result_queue;
} WorkerArguments;
void *worker(void *args) {
/*
* TODO:
* 1. Initialize a UrlStatus (allocate memory using malloc, and zero it
* using memset)
* 2. Dequeue URL from url_queue, run check_url on it, and update results
* (don't forget to free() the url)
* 3. After dequeuing a NULL value:
* Enqueue results to result_queue and return
*/
WorkerArguments *worker_args = (WorkerArguments *)args;
UrlStatus *results = NULL;
char *url;
results = (UrlStatus*)malloc(sizeof(UrlStatus));
if (results == NULL) {
perror("unable to allocate memory");
exit(EXIT_FAILURE);
}
/* setting all values in UrlStatus to 0 */
memset(results, 0, sizeof(UrlStatus));
url = dequeue(worker_args->url_queue);
/* while url queue is not empty - keep running */
while(url != NULL){
switch (check_url(url)) {
case URL_OK:
results->ok += 1;
break;
case URL_ERROR:
results->error += 1;
break;
default:
results->unknown += 1;
}
free(url);
url = dequeue(worker_args->url_queue);
}
/* Enqueue results (of type UrlStatus) to results queue */
enqueue(worker_args->result_queue, results);
return NULL;
}
typedef struct {
const char *filename;
Queue *url_queue;
} FileReaderArguments;
void *file_reader(void *args) {
/*
* TODO:
* 1. Open filename (use fopen, check for errors)
* 2. Use getline() to read lines (i.e. URLs) from the file (use errno to check for errors)
* 3. Copy each url to the heap (use malloc and strncpy)
* 4. Enqueue the URL to url_queue
* 5. Don't forget to free the line variable, and close the file (and check for errors!)
*/
FileReaderArguments *file_reader_args = (FileReaderArguments *)args;
FILE *toplist_file;
char *line = NULL;
char *url = NULL;
size_t len = 0;
ssize_t read = 0;
toplist_file = fopen(file_reader_args->filename, "r");
/* check if fopen was successful */
if (toplist_file == NULL) {
exit(EXIT_FAILURE);
}
while ((read = getline(&line, &len, toplist_file)) != -1) {
if (read == -1){
handle_error_en(read, "unable to read from file");
}
line[read-1] = '\0'; /* null-terminate the URL */
/* allocating memory on the heap of the url */
url = (char*)malloc(sizeof(char)*read);
if (url == NULL) {
perror("unable to allocate memory");
exit(EXIT_FAILURE);
}
/* using strncpy as requested to copy line to allocated url */
strncpy(url, line, strlen(line));
enqueue(file_reader_args->url_queue, url);
}
free(line);
fclose(toplist_file);
return NULL;
}
typedef struct {
int number_of_threads;
Queue *url_queue;
Queue *result_queue;
} CollectorArguments;
void *collector(void *args) {
/*
* TODO:
* 1. Enqueue number_of_threads NULLs to the url_queue
* 2. Dequeue and aggregate number_of_threads thread_results
* from result_queue into results (don't forget to free() thread_results)
* 3. Print aggregated results to the screen
*/
CollectorArguments *collector_args = (CollectorArguments *)args;
UrlStatus results = {0};
UrlStatus *thread_results;
int i;
/* Enqueue number_of_threads NULLs to the url_queue */
for(i = 0; i < collector_args->number_of_threads; i++){
enqueue(collector_args->url_queue, NULL);
}
/* Dequeue and place in thread_results */
for(i = 0; i < collector_args->number_of_threads; i++){
thread_results = dequeue(collector_args->result_queue);
results.ok += thread_results->ok;
results.error += thread_results->error;
results.unknown += thread_results->unknown;
}
printf("%d OK, %d Error, %d Unknown\n",
results.ok,
results.error,
results.unknown);
return NULL;
}
void parallel_checker(const char *filename, int number_of_threads) {
/*
* TODO:
* 1. Initialize a Queue for URLs, a Queue for results (use QUEUE_SIZE)
* 2. Start number_of_threads threads running worker()
* 3. Start a thread running file_reader(), and join it
* 4. Start a thread running collector(), and join it
* 5. Join all worker threads
* 6. Destroy both queues
*/
Queue url_queue, result_queue;
WorkerArguments worker_arguments = {0};
FileReaderArguments file_reader_arguments = {0};
CollectorArguments collector_arguments = {0};
pthread_t *worker_threads;
pthread_t file_reader_thread, collector_thread;
int i, ret;
worker_threads = (pthread_t *) malloc(sizeof(pthread_t) * number_of_threads);
if (worker_threads == NULL) {
perror("unable to allocate memory");
return;
}
curl_global_init(CURL_GLOBAL_ALL); /* init libcurl before starting threads */
/* Initialize a Queue for URLs and for results */
queue_init(&url_queue ,QUEUE_SIZE);
queue_init(&result_queue ,QUEUE_SIZE);
/* Initialize worker_arguments to send to workers */
worker_arguments.result_queue = &result_queue;
worker_arguments.url_queue = &url_queue;
/* Start number_of_threads threads running worker() */
for(i = 0; i < number_of_threads; i++) {
ret = pthread_create(&(worker_threads[i]), NULL, &worker, &worker_arguments);
if (ret != 0) {
handle_error_en(ret, "unable to create thread");
}
}
/* Initialize file_reader_arguments to send to file_reader */
file_reader_arguments.filename = filename;
file_reader_arguments.url_queue = &url_queue;
/* Start a thread running file_reader(), and join it */
ret = pthread_create(&(file_reader_thread), NULL, &file_reader, &file_reader_arguments);
if (ret != 0) {
handle_error_en(ret, "unable to create thread");
}
pthread_join(file_reader_thread, NULL);
/* Initialize collector_arguments to send to */
collector_arguments.number_of_threads = number_of_threads;
collector_arguments.url_queue = &url_queue;
collector_arguments.result_queue = &result_queue;
/* Start a thread running collector(), and join it */
ret = pthread_create(&(collector_thread), NULL, &collector, &collector_arguments);
if (ret != 0) {
handle_error_en(ret, "unable to create thread");
}
pthread_join(collector_thread, NULL);
/* Join all worker threads */
for (i = 0; i < number_of_threads; i++) {
pthread_join(worker_threads[i],NULL);
}
/* Destroying Queues */
queue_destroy(&url_queue);
queue_destroy(&result_queue);
free(worker_threads);
}
int main(int argc, char **argv) {
if (argc != 3) {
usage();
} else {
parallel_checker(argv[1], atoi(argv[2]));
}
return EXIT_SUCCESS;
}
|
C | ISO-8859-1 | 1,219 | 3.890625 | 4 | [] | no_license | //ejemplo2_8.c
#include <stdio.h>
int main (){
int entero = 1;
float real = 10.0F;
printf("entero: %d\n", entero);
//la siguiente instruccin imprimir 1 ya que el entero
//se muestra antes de incrementarse
printf("entero++: %d\n", entero++);
//pero despus de ejecutar la sentencia anterior entero vale 2
printf("entero: %d\n", entero);
//a continuacin se imprimir 3 ya que se incrementa antes de mostrarse
printf("++entero: %d\n", ++entero);
//y la siguiente imprimir 3 ya que el entero se muestra antes
//debe incrementarse
printf("entero--: %d\n", entero--);
//pero tras ejecutar la sentencia anterior entero vale 2
printf("entero: %d\n", entero);
//ahora se imprimir 1 ya que se decrementa antes de mostrarse
printf("--entero: %d\n", --entero);
printf("real: %f\n",real);
real += 2;//equivalente a real = real + 2;
printf("real += 2: %f\n",real);
real -= 6;//equivalente a real = real - 6;
printf("real -= 6: %f\n",real);
real *= 3;//equivalente a real = real * 3;
printf("real *= 3: %f\n",real);
real /= 9;//equivalente a real = real / 9;
printf("real /= 9: %f\n",real);
system ("pause");
}
|
C | UTF-8 | 1,673 | 2.96875 | 3 | [] | no_license | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa_base.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: kkhalfao <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/03/29 18:03:33 by kkhalfao #+# #+# */
/* Updated: 2017/05/04 01:20:45 by kkhalfao ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/ft_printf.h"
#include "../includes/libft.h"
#include <stdlib.h>
int ft_len_number(intmax_t a, int base)
{
int i;
int tmp;
i = 0;
tmp = 0;
while (a != 0)
{
tmp++;
a = a / base;
}
return (tmp);
}
char *ft_itoa_base(intmax_t nb, int base)
{
int i;
int nb_len;
char tab_value[17];
char *tmp;
i = 0;
if (base < 2 || base > 16)
return (NULL);
nb_len = ft_len_number(nb, base);
if (nb < 0)
nb = -nb;
if ((tmp = (char *)malloc(sizeof(char) * (nb_len + 1))) == 0)
return (NULL);
ft_bzero(tmp, nb_len + 1);
ft_strcpy(tab_value, "0123456789abcdef");
while (nb != 0)
{
if ((nb % base) < 0)
tmp[nb_len - 1] = tab_value[-(nb % base)];
else
tmp[nb_len - 1] = tab_value[nb % base];
nb = nb / base;
nb_len--;
}
return (tmp);
}
|
C | UTF-8 | 1,802 | 2.8125 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "../common/function.h"
int main(void) {
double min = -2.0;
double max = 2.5;
double step = 0.25;
double *x0;
double *x1;
int element = (fabs(min)+fabs(max))/step;
x0 = malloc(sizeof(double) * element);
x1 = malloc(sizeof(double) * element);
array_range(min, max, step, x0);
array_range(min, max, step, x1);
double *X;
double *Y;
X = malloc(sizeof(double) * element * element);
Y = malloc(sizeof(double) * element * element);
meshgrid(x0, element, x1, element, X, Y);
double array[2] = {0};
int array_size = sizeof(array)/sizeof(double);
double grad[2] = {0};
double *X1;
double *Y1;
X1 = malloc(sizeof(double) * element * element);
Y1 = malloc(sizeof(double) * element * element);
int i;
for (i=0;i<element*element;i++) {
array[0] = X[i];
array[1] = Y[i];
numerical_gradient(function_2, array, array_size, grad);
X1[i] = grad[0];
Y1[i] = grad[1];
}
for (i=0;i<element*element;i++) {
printf("%f %f %f %f\n", X[i], Y[i], -1*X1[i], -1*Y1[i]);
}
FILE *gp;
gp = popen("gnuplot -persist", "w");
fprintf(gp, "set grid\n");
fprintf(gp, "set xrange [-2.0:2.0]\n");
fprintf(gp, "set yrange [-2.0:2.0]\n");
fprintf(gp, "plot '-' with vectors\n");
double normalize = 0.0;
for (i=0;i<element*element;i++) {
normalize = sqrt(pow(X1[i], 2.0) + pow(Y1[i], 2.0));
fprintf(gp, "%f %f %f %f\n", X[i], Y[i], -1*X1[i]/(normalize*5.0), -1*Y1[i]/(normalize*5.0));
}
fprintf(gp, "e\n");
fprintf(gp, "exit\n");
pclose(gp);
free(x0);
free(x1);
free(X);
free(Y);
free(X1);
free(Y1);
return 0;
}
|
C | WINDOWS-1252 | 564 | 3.53125 | 4 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
extern void BubbleSort(void *arr, int len, int width,
int (*compare) (void *elem1, void *elem2));
int Compare_int(void *elem1, void *elem2)
{
return *(int* )elem1-*(int* )elem2;
}
void TestArr_int()
{
int arr_int[] = {9,8,7,6,5,4,3,2,1,0};
int len = sizeof(arr_int)/sizeof(arr_int[0]);
BubbleSort(arr_int, len, sizeof(arr_int[0]), &Compare_int);
//ӡ
{
int i = 0;
for(i = 0; i<len; i++)
{
printf("%d ", arr_int[i]);
}
}
}
int main()
{
TestArr_int();
system("pause");
return 0;
} |
C | UTF-8 | 17,287 | 2.53125 | 3 | [
"BSD-3-Clause"
] | permissive | /*******************************************
* track_grid_stats_tdrp.c
*
* TDRP C code file 'track_grid_stats' module.
*
* Code for program track_grid_stats
*
* This file has been automatically
* generated by TDRP, do not modify.
*
*******************************************/
#include "track_grid_stats_tdrp.h"
#include <string.h>
/*
* file scope variables
*/
static TDRPtable Table[17];
static track_grid_stats_tdrp_struct *Params;
static char *Module = "track_grid_stats";
/*************************************************************
* track_grid_stats_tdrp_load_from_args()
*
* Loads up TDRP using the command line args.
*
* Check TDRP_usage() for command line actions associated with
* this function.
*
* argc, argv: command line args
*
* track_grid_stats_tdrp_struct *params: loads up this struct
*
* char **override_list: A null-terminated list of overrides
* to the parameter file.
* An override string has exactly the format of an entry
* in the parameter file itself.
*
* char **params_path_p: if non-NULL, this is set to point to
* the path of the params file used.
*
* Returns 0 on success, -1 on failure.
*/
int track_grid_stats_tdrp_load_from_args(int argc, char **argv,
track_grid_stats_tdrp_struct *params,
char **override_list,
char **params_path_p)
{
Params = params;
track_grid_stats_tdrp_init(Params);
if (tdrpLoadFromArgs(argc, argv,
Table, Params,
override_list, params_path_p)) {
return (-1);
} else {
return (0);
}
}
/*************************************************************
* track_grid_stats_tdrp_load()
*
* Loads up TDRP for a given module.
*
* This version of load gives the programmer the option to load
* up more than one module for a single application. It is a
* lower-level routine than track_grid_stats_tdrp_load_from_args,
* and hence more flexible, but the programmer must do more work.
*
* char *param_file_path: the parameter file to be read in.
*
* track_grid_stats_tdrp_struct *params: loads up this struct
*
* char **override_list: A null-terminated list of overrides
* to the parameter file.
* An override string has exactly the format of an entry
* in the parameter file itself.
*
* expand_env: flag to control environment variable
* expansion during tokenization.
* If TRUE, environment expansion is set on.
* If FALSE, environment expansion is set off.
*
* Returns 0 on success, -1 on failure.
*/
int track_grid_stats_tdrp_load(char *param_file_path,
track_grid_stats_tdrp_struct *params,
char **override_list,
int expand_env, int debug)
{
Params = params;
track_grid_stats_tdrp_init(Params);
if (tdrpLoad(param_file_path, Table,
params, override_list,
expand_env, debug)) {
return (-1);
} else {
return (0);
}
}
/*************************************************************
* track_grid_stats_tdrp_load_defaults()
*
* Loads up defaults for a given module.
*
* See track_grid_stats_tdrp_load() for more details.
*
* Returns 0 on success, -1 on failure.
*/
int track_grid_stats_tdrp_load_defaults(track_grid_stats_tdrp_struct *params,
int expand_env)
{
Params = params;
track_grid_stats_tdrp_init(Params);
if (tdrpLoad(NULL, Table,
params, NULL,
expand_env, FALSE)) {
return (-1);
} else {
return (0);
}
}
/*************************************************************
* track_grid_stats_tdrp_sync()
*
* Syncs the user struct data back into the parameter table,
* in preparation for printing.
*/
void track_grid_stats_tdrp_sync(void)
{
tdrpUser2Table(Table, Params);
}
/*************************************************************
* track_grid_stats_tdrp_print()
*
* Print params file
*
* The modes supported are:
*
* PRINT_SHORT: main comments only, no help or descriptions
* structs and arrays on a single line
* PRINT_NORM: short + descriptions and help
* PRINT_LONG: norm + arrays and structs expanded
* PRINT_VERBOSE: long + private params included
*/
void track_grid_stats_tdrp_print(FILE *out, tdrp_print_mode_t mode)
{
tdrpPrint(out, Table, Module, mode);
}
/*************************************************************
* track_grid_stats_tdrp_check_all_set()
*
* Return TRUE if all set, FALSE if not.
*
* If out is non-NULL, prints out warning messages for those
* parameters which are not set.
*/
int track_grid_stats_tdrp_check_all_set(FILE *out)
{
return (tdrpCheckAllSet(out, Table, Params));
}
/*************************************************************
* track_grid_stats_tdrp_check_is_set()
*
* Return TRUE if parameter is set, FALSE if not.
*
*/
int track_grid_stats_tdrp_check_is_set(char *param_name)
{
return (tdrpCheckIsSet(param_name, Table, Params));
}
/*************************************************************
* track_grid_stats_tdrp_free_all()
*
* Frees up all TDRP dynamic memory.
*/
void track_grid_stats_tdrp_free_all(void)
{
tdrpFreeAll(Table, Params);
}
/*************************************************************
* track_grid_stats_tdrp_array_realloc()
*
* Realloc 1D array.
*
* If size is increased, the values from the last array entry is
* copied into the new space.
*
* Returns 0 on success, -1 on error.
*/
int track_grid_stats_tdrp_array_realloc(char *param_name, int new_array_n)
{
if (tdrpArrayRealloc(Table, Params, param_name, new_array_n)) {
return (-1);
} else {
return (0);
}
}
/*************************************************************
* track_grid_stats_tdrp_array2D_realloc()
*
* Realloc 2D array.
*
* If size is increased, the values from the last array entry is
* copied into the new space.
*
* Returns 0 on success, -1 on error.
*/
int track_grid_stats_tdrp_array2D_realloc(char *param_name,
int new_array_n1,
int new_array_n2)
{
if (tdrpArray2DRealloc(Table, Params, param_name,
new_array_n1, new_array_n2)) {
return (-1);
} else {
return (0);
}
}
/*************************************************************
* track_grid_stats_tdrp_table()
*
* Returns pointer to static Table for this module.
*/
TDRPtable *track_grid_stats_tdrp_table(void)
{
return (Table);
}
/*************************************************************
* track_grid_stats_tdrp_init()
*
* Module table initialization function.
*
*
* Returns pointer to static Table for this module.
*/
TDRPtable *track_grid_stats_tdrp_init(track_grid_stats_tdrp_struct *params)
{
TDRPtable *tt = Table;
track_grid_stats_tdrp_struct pp; /* for computing byte_offsets */
/* zero out struct, and store size */
memset(params, 0, sizeof(track_grid_stats_tdrp_struct));
params->struct_size = sizeof(track_grid_stats_tdrp_struct);
/* Parameter 'debug' */
/* ctype is 'track_grid_stats_debug' */
memset(tt, 0, sizeof(TDRPtable));
tt->ptype = ENUM_TYPE;
tt->param_name = tdrpStrDup("debug");
tt->descr = tdrpStrDup("Debug option");
tt->help = tdrpStrDup("If set, debug messages will be printed appropriately");
tt->val_offset = (char *) &(pp.debug) - (char *) &pp;
tt->enum_def.name = tdrpStrDup("debug");
tt->enum_def.nfields = 4;
tt->enum_def.fields = (enum_field_t *)
tdrpMalloc(tt->enum_def.nfields * sizeof(enum_field_t));
tt->enum_def.fields[0].name = tdrpStrDup("DEBUG_OFF");
tt->enum_def.fields[0].val = DEBUG_OFF;
tt->enum_def.fields[1].name = tdrpStrDup("DEBUG_WARNINGS");
tt->enum_def.fields[1].val = DEBUG_WARNINGS;
tt->enum_def.fields[2].name = tdrpStrDup("DEBUG_NORM");
tt->enum_def.fields[2].val = DEBUG_NORM;
tt->enum_def.fields[3].name = tdrpStrDup("DEBUG_EXTRA");
tt->enum_def.fields[3].val = DEBUG_EXTRA;
tt->single_val.e = DEBUG_OFF;
tt++;
/* Parameter 'malloc_debug_level' */
/* ctype is 'long' */
memset(tt, 0, sizeof(TDRPtable));
tt->ptype = LONG_TYPE;
tt->param_name = tdrpStrDup("malloc_debug_level");
tt->descr = tdrpStrDup("Malloc debug level");
tt->help = tdrpStrDup("0 - none, 1 - corruption checking, 2 - records all malloc blocks and checks, 3 - printout of all mallocs etc.");
tt->val_offset = (char *) &(pp.malloc_debug_level) - (char *) &pp;
tt->has_min = TRUE;
tt->has_max = TRUE;
tt->min_val.l = 0;
tt->max_val.l = 3;
tt->single_val.l = 0;
tt++;
/* Parameter 'note' */
/* ctype is 'char*' */
memset(tt, 0, sizeof(TDRPtable));
tt->ptype = STRING_TYPE;
tt->param_name = tdrpStrDup("note");
tt->descr = tdrpStrDup("Note for stats file");
tt->help = tdrpStrDup("Note to go in track stats grid file");
tt->val_offset = (char *) &(pp.note) - (char *) &pp;
tt->single_val.s = tdrpStrDup("Track grid statistics");
tt++;
/* Parameter 'compute_dur_max_precip' */
/* ctype is 'tdrp_bool_t' */
memset(tt, 0, sizeof(TDRPtable));
tt->ptype = BOOL_TYPE;
tt->param_name = tdrpStrDup("compute_dur_max_precip");
tt->descr = tdrpStrDup("Option to compute the max precip depth for a given duration");
tt->help = tdrpStrDup("If this is set, the max precip depth for a given duration will bw computed and stored in the given field. If not the field will be left with zero entries");
tt->val_offset = (char *) &(pp.compute_dur_max_precip) - (char *) &pp;
tt->single_val.b = pFALSE;
tt++;
/* Parameter 'dur_for_max_precip' */
/* ctype is 'long' */
memset(tt, 0, sizeof(TDRPtable));
tt->ptype = LONG_TYPE;
tt->param_name = tdrpStrDup("dur_for_max_precip");
tt->descr = tdrpStrDup("Duration for max precip duration comps - secs");
tt->help = tdrpStrDup("The duration in seconds for which the maximum precip depth is computed.");
tt->val_offset = (char *) &(pp.dur_for_max_precip) - (char *) &pp;
tt->has_min = TRUE;
tt->has_max = TRUE;
tt->min_val.l = 300;
tt->max_val.l = 86400;
tt->single_val.l = 1800;
tt++;
/* Parameter 'grid_stats_dir' */
/* ctype is 'char*' */
memset(tt, 0, sizeof(TDRPtable));
tt->ptype = STRING_TYPE;
tt->param_name = tdrpStrDup("grid_stats_dir");
tt->descr = tdrpStrDup("Track grid stats directory");
tt->help = tdrpStrDup("Upper level directory for output grid stats files");
tt->val_offset = (char *) &(pp.grid_stats_dir) - (char *) &pp;
tt->single_val.s = tdrpStrDup("none");
tt++;
/* Parameter 'output_file_ext' */
/* ctype is 'char*' */
memset(tt, 0, sizeof(TDRPtable));
tt->ptype = STRING_TYPE;
tt->param_name = tdrpStrDup("output_file_ext");
tt->descr = tdrpStrDup("Output file extension");
tt->help = tdrpStrDup("File name extension for output cartesian files");
tt->val_offset = (char *) &(pp.output_file_ext) - (char *) &pp;
tt->single_val.s = tdrpStrDup("mdv");
tt++;
/* Parameter 'n_seasons' */
/* ctype is 'long' */
memset(tt, 0, sizeof(TDRPtable));
tt->ptype = LONG_TYPE;
tt->param_name = tdrpStrDup("n_seasons");
tt->descr = tdrpStrDup("Number of seasons for stats");
tt->help = tdrpStrDup("The number of seasons for computing the seasonal means, such as precip.");
tt->val_offset = (char *) &(pp.n_seasons) - (char *) &pp;
tt->single_val.l = 1;
tt++;
/* Parameter 'scan_interval' */
/* ctype is 'double' */
memset(tt, 0, sizeof(TDRPtable));
tt->ptype = DOUBLE_TYPE;
tt->param_name = tdrpStrDup("scan_interval");
tt->descr = tdrpStrDup("Radar vol scan interval (secs)");
tt->help = tdrpStrDup("Interval between radar volume scans (secs)");
tt->val_offset = (char *) &(pp.scan_interval) - (char *) &pp;
tt->has_min = TRUE;
tt->has_max = TRUE;
tt->min_val.d = 0;
tt->max_val.d = 1800;
tt->single_val.d = 360;
tt++;
/* Parameter 'min_duration' */
/* ctype is 'double' */
memset(tt, 0, sizeof(TDRPtable));
tt->ptype = DOUBLE_TYPE;
tt->param_name = tdrpStrDup("min_duration");
tt->descr = tdrpStrDup("Min track duration (secs)");
tt->help = tdrpStrDup("The minimum duration for including a track in the analysis (secs)");
tt->val_offset = (char *) &(pp.min_duration) - (char *) &pp;
tt->has_min = TRUE;
tt->has_max = TRUE;
tt->min_val.d = 0;
tt->max_val.d = 10000;
tt->single_val.d = 900;
tt++;
/* Parameter 'grid_lat' */
/* ctype is 'double' */
memset(tt, 0, sizeof(TDRPtable));
tt->ptype = DOUBLE_TYPE;
tt->param_name = tdrpStrDup("grid_lat");
tt->descr = tdrpStrDup("Grid latitude");
tt->help = tdrpStrDup("Latitude of grid origin");
tt->val_offset = (char *) &(pp.grid_lat) - (char *) &pp;
tt->has_min = TRUE;
tt->has_max = TRUE;
tt->min_val.d = -90;
tt->max_val.d = 90;
tt->single_val.d = 39.8782;
tt++;
/* Parameter 'grid_lon' */
/* ctype is 'double' */
memset(tt, 0, sizeof(TDRPtable));
tt->ptype = DOUBLE_TYPE;
tt->param_name = tdrpStrDup("grid_lon");
tt->descr = tdrpStrDup("Grid longitude");
tt->help = tdrpStrDup("Longitude of grid origin");
tt->val_offset = (char *) &(pp.grid_lon) - (char *) &pp;
tt->has_min = TRUE;
tt->has_max = TRUE;
tt->min_val.d = -180;
tt->max_val.d = 180;
tt->single_val.d = -104.759;
tt++;
/* Parameter 'grid' */
/* ctype is 'track_grid_stats_grid' */
memset(tt, 0, sizeof(TDRPtable));
tt->ptype = STRUCT_TYPE;
tt->param_name = tdrpStrDup("grid");
tt->descr = tdrpStrDup("Grid parameters");
tt->help = tdrpStrDup("The grid params for the track stats.");
tt->val_offset = (char *) &(pp.grid) - (char *) &pp;
tt->struct_def.name = tdrpStrDup("grid");
tt->struct_def.nfields = 6;
tt->struct_def.fields = (struct_field_t *)
tdrpMalloc(tt->struct_def.nfields * sizeof(struct_field_t));
tt->struct_def.fields[0].ftype = tdrpStrDup("long");
tt->struct_def.fields[0].fname = tdrpStrDup("nx");
tt->struct_def.fields[0].ptype = LONG_TYPE;
tt->struct_def.fields[0].rel_offset =
(char *) &(pp.grid.nx) - (char *) &(pp.grid);
tt->struct_def.fields[1].ftype = tdrpStrDup("long");
tt->struct_def.fields[1].fname = tdrpStrDup("ny");
tt->struct_def.fields[1].ptype = LONG_TYPE;
tt->struct_def.fields[1].rel_offset =
(char *) &(pp.grid.ny) - (char *) &(pp.grid);
tt->struct_def.fields[2].ftype = tdrpStrDup("double");
tt->struct_def.fields[2].fname = tdrpStrDup("minx");
tt->struct_def.fields[2].ptype = DOUBLE_TYPE;
tt->struct_def.fields[2].rel_offset =
(char *) &(pp.grid.minx) - (char *) &(pp.grid);
tt->struct_def.fields[3].ftype = tdrpStrDup("double");
tt->struct_def.fields[3].fname = tdrpStrDup("miny");
tt->struct_def.fields[3].ptype = DOUBLE_TYPE;
tt->struct_def.fields[3].rel_offset =
(char *) &(pp.grid.miny) - (char *) &(pp.grid);
tt->struct_def.fields[4].ftype = tdrpStrDup("double");
tt->struct_def.fields[4].fname = tdrpStrDup("dx");
tt->struct_def.fields[4].ptype = DOUBLE_TYPE;
tt->struct_def.fields[4].rel_offset =
(char *) &(pp.grid.dx) - (char *) &(pp.grid);
tt->struct_def.fields[5].ftype = tdrpStrDup("double");
tt->struct_def.fields[5].fname = tdrpStrDup("dy");
tt->struct_def.fields[5].ptype = DOUBLE_TYPE;
tt->struct_def.fields[5].rel_offset =
(char *) &(pp.grid.dy) - (char *) &(pp.grid);
tt->n_struct_vals = 6;
tt->struct_vals = (tdrpVal_t *)
tdrpMalloc(tt->n_struct_vals * sizeof(tdrpVal_t));
tt->struct_vals[0].l = 0;
tt->struct_vals[1].l = 0;
tt->struct_vals[2].d = 0;
tt->struct_vals[3].d = 0;
tt->struct_vals[4].d = 0;
tt->struct_vals[5].d = 0;
tt++;
/* Parameter 'z_r_coeff' */
/* ctype is 'double' */
memset(tt, 0, sizeof(TDRPtable));
tt->ptype = DOUBLE_TYPE;
tt->param_name = tdrpStrDup("z_r_coeff");
tt->descr = tdrpStrDup("Z-R coefficient");
tt->help = tdrpStrDup("The coefficient in the Z-R relationship");
tt->val_offset = (char *) &(pp.z_r_coeff) - (char *) &pp;
tt->has_min = TRUE;
tt->has_max = TRUE;
tt->min_val.d = 1;
tt->max_val.d = 2000;
tt->single_val.d = 200;
tt++;
/* Parameter 'z_r_exponent' */
/* ctype is 'double' */
memset(tt, 0, sizeof(TDRPtable));
tt->ptype = DOUBLE_TYPE;
tt->param_name = tdrpStrDup("z_r_exponent");
tt->descr = tdrpStrDup("Z-R exponent");
tt->help = tdrpStrDup("The exponent in the Z-R relationship");
tt->val_offset = (char *) &(pp.z_r_exponent) - (char *) &pp;
tt->has_min = TRUE;
tt->has_max = TRUE;
tt->min_val.d = 0.1;
tt->max_val.d = 10;
tt->single_val.d = 1.6;
tt++;
/* Parameter 'hail_dbz_threshold' */
/* ctype is 'double' */
memset(tt, 0, sizeof(TDRPtable));
tt->ptype = DOUBLE_TYPE;
tt->param_name = tdrpStrDup("hail_dbz_threshold");
tt->descr = tdrpStrDup("Hail dBZ threshold");
tt->help = tdrpStrDup("The reflectivity threshold above which hail is assumed");
tt->val_offset = (char *) &(pp.hail_dbz_threshold) - (char *) &pp;
tt->has_min = TRUE;
tt->has_max = TRUE;
tt->min_val.d = 40;
tt->max_val.d = 80;
tt->single_val.d = 55;
tt++;
/* trailing entry has param_name set to NULL */
tt->param_name = NULL;
return (Table);
}
|
C | UTF-8 | 2,549 | 2.703125 | 3 | [] | no_license | #include<stdio.h>
#include<string.h>
void copy(char *inter,int ptr,char codes[29][7],int offset)
{
int i;
for(i=ptr;i<ptr+5;i++)
inter[i]=codes[offset][i-ptr];
}
int main()
{
int test_cases,output[21][21],i,j,k,r,ru,rl,cl,cr,row,col,len,ptr,dec;
char codes[29][7],input[102],inter[450],temp;
strcpy(codes[0],"00000\0");
strcpy(codes[1],"00001\0");
strcpy(codes[2],"00010\0");
strcpy(codes[3],"00011\0");
strcpy(codes[4],"00100\0");
strcpy(codes[5],"00101\0");
strcpy(codes[6],"00110\0");
strcpy(codes[7],"00111\0");
strcpy(codes[8],"01000\0");
strcpy(codes[9],"01001\0");
strcpy(codes[10],"01010\0");
strcpy(codes[11],"01011\0");
strcpy(codes[12],"01100\0");
strcpy(codes[13],"01101\0");
strcpy(codes[14],"01110\0");
strcpy(codes[15],"01111\0");
strcpy(codes[16],"10000\0");
strcpy(codes[17],"10001\0");
strcpy(codes[18],"10010\0");
strcpy(codes[19],"10011\0");
strcpy(codes[20],"10100\0");
strcpy(codes[21],"10101\0");
strcpy(codes[22],"10110\0");
strcpy(codes[23],"10111\0");
strcpy(codes[24],"11000\0");
strcpy(codes[25],"11001\0");
strcpy(codes[26],"11010\0");
scanf("%d",&test_cases);
for(k=0;k<test_cases;k++)
{
scanf("%d",&row);
scanf("%d",&col);
scanf("%c",&temp);
if(temp==' ')
gets(input);
ptr=0;
len=strlen(input);
j=row*col+11;
for(i=0;i<j;i++)
inter[i]='0';
for(i=0;i<len;i++)
{
if(input[i]==' ')
copy(inter,ptr,codes,0);
else
copy(inter,ptr,codes,input[i]-64);
ptr=ptr+5;
}
len=ptr;
for(i=0;i<row;i++)
for(j=0;j<col;j++)
output[i][j]=0;
i=0;
dec=0;
ru=0;
rl=row-1;
cl=0;
cr=col-1;
while(i<len)
{
if(dec==0)
{
for(r=cl;r<=cr;r++)
output[ru][r]=inter[i++]-48;
ru++;
}
else if(dec==1)
{
for(r=ru;r<=rl;r++)
output[r][cr]=inter[i++]-48;
cr--;
}
else if(dec==2)
{
for(r=cr;r>=cl;r--)
output[rl][r]=inter[i++]-48;
rl--;
}
else if(dec==3)
{
for(r=rl;r>=ru;r--)
output[r][cl]=inter[i++]-48;
cl++;
}
dec=(dec+1)%4;
}
printf("%d ",k+1);
for(i=0;i<row;i++)
for(j=0;j<col;j++)
printf("%d",output[i][j]);
printf("\n");
}
return 0;
}
|
C | UTF-8 | 2,276 | 2.828125 | 3 | [] | no_license | #include "actor.h"
#include <stdlib.h>
static const vector3_t vector3_one = {1, 1, 1};
actor_t* actor_new()
{
actor_t* actor = malloc(sizeof(actor_t));
memset(&actor->position, 0, sizeof(actor->position));
actor->update = 1;
actor->scale = vector3_one;
actor->quat = quaternion_identity;
actor->model = matrix4_identity;
actor->render_model = matrix4_identity;
actor->fix_model = matrix4_identity;
actor->children = m_array_new(sizeof(actor_t*));
actor->parent = 0;
actor->mesh = 0;
return actor;
}
void actor_set_position(actor_t* actor, vector3_t vector)
{
actor->position = vector;
actor->update = 1;
}
void actor_set_scale(actor_t* actor, vector3_t vector)
{
actor->scale = vector;
actor->update = 1;
}
void actor_set_quat(actor_t* actor, quaternion_t quat)
{
actor->quat = quat;
actor->update = 1;
}
void actor_add_child(actor_t* actor, actor_t* child)
{
m_array_push(actor->children, &child);
child->parent = actor;
}
void actor_update(actor_t* actor, matrix4_t trans, int flag)
{
int i;
flag |= actor->update;
if(flag)
{
//update actor render information
m_matrix4 model = matrix4_identity;
model = matrix4_translate_vector3(model, actor->position);
model = matrix4_mul(model, actor->fix_model);
model = matrix4_mul(model, matrix4_create_quaternion(actor->quat));
model = matrix4_scale_vector3(model, actor->scale);
actor->render_model = model;
actor->render_model = matrix4_mul(trans, actor->render_model);
model = matrix4_mul(trans, model);
actor->model = model;
actor->update = 0;
}
/* update children */
for(i = 0; i < actor->children->len; i++)
{
actor_update(m_array_get(actor->children, actor_t*, i), actor->model, flag);
}
}
void actor_free(actor_t* actor)
{
int i;
if(actor->mesh) model_mesh_free(actor->mesh);
m_array_free(actor->children);
free(actor);
}
/*
actor context
*/
actor_context_t* actor_context_new()
{
actor_context_t* ctx = malloc(sizeof(actor_context_t));
ctx->actors = m_array_new(sizeof(actor_t*));
return ctx;
}
void actor_context_free(actor_context_t* ctx)
{
int i;
for(i = 0; i < ctx->actors->len; i++)
{
actor_free(m_array_get(ctx->actors, actor_t*, i));
}
m_array_free(ctx->actors);
free(ctx);
}
|
C | UTF-8 | 6,852 | 2.53125 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include<gmp.h>
#include"_Headers/ntheory.h"
#include"_Headers/elgamalgmp.h"
#include<time.h>
#include<string.h>
#include<assert.h>
#include"_Headers/helpers.h"
#include"_Headers/ecdsagmp.h"
#include"_Headers/sha1.h"
#define bufSize 3072
int _ECDSAInit(mpz_t a_eq,mpz_t b_eq,mpz_t prime_field,mpz_t b_point_x,mpz_t b_point_y,mpz_t n){
FILE* fp;
int i=0;
char buf[bufSize];
char **tokens=NULL;
mpz_init(a_eq);
mpz_init(b_eq);
mpz_init(prime_field);
mpz_init(b_point_x);
mpz_init(b_point_y);
mpz_init(n);
if ((fp = fopen("ecequation.csv", "r")) == NULL)
{
perror("FOPEN ERROR\n");
return 1;
}
while (fgets(buf, sizeof(buf), fp) != NULL)
{
buf[strlen(buf) - 1] = '\0';
tokens = str_split(buf, ';');//split string with ';' delimiter (csv file)
mpz_set_str(a_eq,tokens[0],16);//coefficient a
mpz_set_str(b_eq,tokens[1],16);//coefficient b
mpz_set_str(prime_field,tokens[2],16);//modulo p
mpz_set_str(b_point_x,tokens[3],16);//generator point x
mpz_set_str(b_point_y,tokens[4],16);//generator point y
mpz_set_str(n,tokens[5],16);//order of the curve
break;//limited edition xD no time
}
fclose(fp);
}
void pointAddition(mpz_t x3,mpz_t y3,mpz_t x2,mpz_t y2,mpz_t x1,mpz_t y1,mpz_t p,mpz_t a){
mpz_t s,tmp,m;
mpz_init(s);
mpz_init(tmp);
mpz_init(m);
if(!point_cmp(x1,y1,x2,y2)){//if (x1,x2)!=(y1,y2)
if((mpz_cmp_ui(x2,0)==0 && mpz_cmp_ui(y2,0)==0 )||(mpz_cmp_ui(x1,0)==0 && mpz_cmp_ui(y1,0)==0 ))
// if some point is (0.0)
{
if(mpz_cmp_ui(x2,0)==0 && mpz_cmp_ui(y2,0)==0 ){//P=(0,0)
mpz_set(x3,x1);mpz_set(y3,y1);}
else{//Q=(0,0)
mpz_set(x3,x2);mpz_set(y3,y2);
}
}
else{//P!=Q and P,Q!=(0,0)
mpz_sub(s,y2,y1);//y2-y1
mpz_sub(tmp,x2,x1);//x2-x1
mpz_invert(tmp,tmp,p);//(x2-x1)^-1 mod p
mpz_mul(s,s,tmp);//(y2-y1)(x2-x1)^-1
mpz_mod(s,s,p);//(y2-y1)(x2-x1)^-1 mod p
mpz_mul(m,s,s);//s^2
mpz_sub(m,m,x1);//S^2-x1
mpz_sub(m,m,x2);//S^2-x1-x2
mpz_mod(m,m,p);//S^2-x1-x2 mod p
mpz_sub(tmp,x1,m);//x1-x3
mpz_mul(tmp,s,tmp);//S(x1-x3)
mpz_sub(tmp,tmp,y1);//S(x1-x3)-y1
mpz_mod(y3,tmp,p);//S(x1-x3)-y1 mod p
mpz_set(x3,m);
}
}else
pointDoubling(x3,y3,x2,y2,p,a);//P=Q => PointDoubling
mpz_clear(tmp);
mpz_clear(m);
}
void pointDoubling(mpz_t x3,mpz_t y3,mpz_t x1,mpz_t y1,mpz_t p,mpz_t a){
mpz_t s,m,n;
mpz_init(s);
mpz_init(m);
mpz_init(n);
if(mpz_cmp_ui(x1,0)==0 && mpz_cmp_ui(y1,0)==0 ){//(x1,y1)=(0,0)
mpz_set_ui(x3,0);mpz_set_ui(y3,0);
}else{//(x1,y1)!=(0,0)
mpz_mul(m,x1,x1);//x1^2
mpz_mul_ui(m,m,3);//3*x1^2
mpz_add(m,m,a);//3*x1^2+a
mpz_mul_ui(n,y1,2);//2*y1
mpz_invert(n,n,p);//(2*y1)^-1
mpz_mul(s,n,m);//(3*x1^2+a)*(2*y1)^-1
mpz_mod(s,s,p);//(3*x1^2+a)*(2*y1)^-1 mod p
//gmp_printf("The slope -> %Zd\n",s);//testing
mpz_mul(m,s,s);//S^2
mpz_sub(m,m,x1);//S^2-x1
mpz_sub(m,m,x1);//S^2-x1-x1
mpz_mod(m,m,p);//S^2-x1-x1 mod p
mpz_sub(n,x1,m);//x1-x3
mpz_mul(n,n,s);//S(x1-x3)
mpz_sub(n,n,y1);//S(x1-x3)-y1
mpz_mod(y3,n,p);//S(x1-x3)-y1 mod p
mpz_set(x3,m);//x3=S^2-x1-x1 mod p
//gmp_printf("x3 -> %Zd\n",m);//testing
//gmp_printf("y3 -> %Zd\n",y3);//testing
}
mpz_clear(m);
mpz_clear(n);
mpz_clear(s);
}
void doubleAndAdd(mpz_t x3,mpz_t y3,mpz_t x1,mpz_t y1,mpz_t p,mpz_t a,mpz_t scalar){
char binaryScalar[bufSize];
int i=0;
mpz_t n_x,n_y,q_x,q_y;
mpz_init(n_x);
mpz_init(n_y);
mpz_init(q_x);
mpz_init(q_y);
mpz_init(x3);
mpz_init(y3);
mpz_set(n_x,x1);
mpz_set(n_y,y1);
mpz_get_str(binaryScalar,2,scalar);//convert the scalar to a binary representation
i=strlen(binaryScalar)-1;//i = length of the binary string - 1
while(i>=0){
if(binaryScalar[i]=='1')//if '1' double and add otherwise double only
pointAddition(q_x,q_y,q_x,q_y,n_x,n_y,p,a);
pointDoubling(n_x,n_y,n_x,n_y,p,a);
--i;
}
mpz_set(x3,q_x);
mpz_set(y3,q_y);
mpz_clear(n_x);
mpz_clear(n_y);
mpz_clear(q_x);
mpz_clear(q_y);
}
int point_cmp(mpz_t x1,mpz_t y1,mpz_t x2,mpz_t y2){
return mpz_cmp(x1,x2)==0 && mpz_cmp(y1,y2)==0;
}
void displayPoint(mpz_t x,mpz_t y){
printf("[");
gmp_printf("x = %Zd\n",x);
gmp_printf("y = %Zd",y);
printf("]\n");
}
void _ECDSAKeyGeneration(mpz_t d,mpz_t qx,mpz_t qy,mpz_t n,mpz_t gx,mpz_t gy,mpz_t p,mpz_t a){
unsigned long seed=time(NULL);
gmp_randstate_t state;//rand state declaration
mpz_init(qx);
mpz_init(qy);
gmp_randinit_mt(state);//init rand state
gmp_randseed_ui(state, seed);
do{
mpz_urandomm (d,state, n);//generate d in [1,n-1]
}while(mpz_cmp_ui(d,0)==0);
doubleAndAdd(qx,qy,gx,gy,p,a,d);//generate Q=(qx,qy) the public key as d*G
}
void _ECDSASign(char *msg,char **e,mpz_t S,mpz_t r,mpz_t gx,mpz_t gy,mpz_t n,mpz_t d,mpz_t a,mpz_t p){
mpz_t ke,tp;
mpz_t kx,ky,tmp;
int i=0;
unsigned long seed=time(NULL);
mpz_init(tp);
*e=_SHA1Hash(msg);//generate the SHA-1 hash of the msg
mpz_set_str(tp,*e,16);//save it to tp
gmp_randstate_t state;//rand state declaration
mpz_init(ke);
mpz_init(kx);
mpz_init(ky);
mpz_init(tmp);
mpz_init(S);
mpz_init(r);
gmp_randinit_mt(state);//init rand state
gmp_randseed_ui(state, seed);
do{
do{
mpz_urandomm (ke,state, n);//generates random ke in [1,n-1]
}while(mpz_cmp_ui(ke,0)==0 || mpz_cmp(ke,d)==0);
gmp_printf("ke -> %Zd\n",ke);
doubleAndAdd(kx,ky,gx,gy,p,a,ke);//calculate (kx,ky) as ke*G
mpz_mod(r,kx,n);//r=kx mod n
mpz_mul(tmp,d,r);//tmp=d*r
mpz_add(tmp,tp,tmp);//tmp=e+dr
mpz_mod(tmp,tmp,n);//tmp = e+dr mod n
mpz_invert(tp,ke,n);//tmp2 = Ke^-1 mod n
mpz_mul(tmp,tmp,tp);//tmp = (e+dr)Ke^-1
mpz_mod(S,tmp,n);//tmp = (e+dr)Ke^-1 mod n
}while(mpz_cmp_ui(r,0)==0 || mpz_cmp_ui(S,0)==0 );//repeat while S=0 or r=0
}
void _ECDSAUnsign(mpz_t S,mpz_t x,char *e,mpz_t r,mpz_t gx,mpz_t gy,mpz_t n,mpz_t qx,mpz_t qy,mpz_t a,mpz_t p){
mpz_t w,u1,u2;
mpz_t tmp,tp;
mpz_t ux,uy;
mpz_t vx,vy;
mpz_init(w);
mpz_init(u1);
mpz_init(u2);
mpz_init(ux);
mpz_init(uy);
mpz_init(vx);
mpz_init(vy);
mpz_init(tmp);
mpz_init(tp);
mpz_init(x);
mpz_set_str(tp,e,16);//Hex to Dec
mpz_invert(w,S,n);//w = S^-1 mod n
mpz_mul(u1,w,tp);//u1 = w*e
mpz_mod(u1,u1,n);//u1 = w*e mod n
mpz_mul(u2,r,w);//u2 = w*r
mpz_mod(u2,u2,n);//u2=w*r mod n
doubleAndAdd(ux,uy,gx,gy,p,a,u1);//calculate (ux,uy) as u1*G
doubleAndAdd(vx,vy,qx,qy,p,a,u2);//calculate (vx,vy) as u2*Q
pointAddition(x,tmp,ux,uy,vx,vy,p,a);//calculate (x,tmp) as (ux,uy)*(vx,vy)
mpz_clear(w);
mpz_clear(u1);
mpz_clear(u2);
mpz_clear(ux);
mpz_clear(uy);
mpz_clear(vx);
mpz_clear(vy);
mpz_clear(tmp);
mpz_clear(tp);
}
int _ECDSAVerification(mpz_t r,mpz_t x,mpz_t n){
mpz_t res;
mpz_init(res);
mpz_mod(res,x,n);//calculate x mod n
return mpz_cmp(res,r)==0;// is r \equiv x mod n
}
|
C | UTF-8 | 235 | 2.5625 | 3 | [] | no_license | #include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct Node{
struct Node * next;
int value;
};
struct node* initList(int value){
struct Node *
}
int main(int argc, char ** argv){
return 0;
} |
C | WINDOWS-1252 | 1,821 | 2.609375 | 3 | [] | no_license | /******************************************************************************
filename LabDoorFunctions.c
author Ethan Young
DP email [email protected]
course GAM100 ** Do not use this code in your team project
Brief Description:
This file defines the functions to create a specific item, the "lab door".
All content 2020 DigiPen (USA) Corporation, all rights reserved.
******************************************************************************/
#include "stdafx.h" /* NULL, UNREFERENCED_PARAMETER */
#include "DrugStoreDoorFunctions.h" /* Function declarations */
#include "GameState.h" /* struct GameState, GameState_EndGame */
#include "ItemList.h" /* ItemList_FindItem */
#include "Item.h" /* Item_Create */
#include "KeycardFunctions.h"
typedef struct WorldData WorldData;
/* Helper: The action performed when the exit door is used. */
void LabDoor_Use(CommandContext context, GameState* gameState, WorldData* worldData)
{
Item* keycard; /* the keycard in the user's inventory */
/* avoid W4 warnings on unused parameters - this function conforms to a function typedef */
UNREFERENCED_PARAMETER(context);
UNREFERENCED_PARAMETER(worldData);
/* find the keycard in the user's inventory */
keycard = ItemList_FindItem(gameState->inventory, "keycard");
/* check if both items are in the user's inventory */
if (keycard != NULL)
{
printf("The door is not moving,nobody in their right mind would attmpt to open it with force. Unless you are Thor Bjornsson. Which you are not. You need a keycard to get in.\n");
}
return;
}
/* Build a "exit door" object */
Item* LabDoor_Build()
{
/* Create a "exit door" item, using the functions defined in this file */
return Item_Create("lab door", "A locked lab door that has a little slot for a card.\n", false, LabDoor_Use, NULL, NULL, NULL, NULL, NULL);
} |
C | UTF-8 | 2,453 | 3.15625 | 3 | [
"Unlicense"
] | permissive | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <getopt.h>
#include <locale.h>
#include <string.h>
#include <errno.h>
#include "flat.h"
#include "offsetdb.h"
enum mode { FLAT, OFFSET };
void print_usage(const char *name, int ret)
{
printf("Usage: %s [OPTION] [PATTERN]\n", name);
printf(" -i <digits file> UTF-8 pi digit listing (pi-billion.txt)\n");
printf(" -d <database file> Database filename\n");
printf(" -f Do a straight string search (no index)\n");
printf(" -b Do an offset index search\n");
printf(" -h Print this message and exit\n");
exit(ret);
}
int main(int argc, char **argv)
{
setlocale(LC_NUMERIC, "");
/* Options */
enum mode mode = OFFSET;
const char *datafile = "pi-billion.txt";
const char *indexfile = NULL;
/* Parse options */
int opt;
while ((opt = getopt(argc, argv, "d:i:bhf")) != -1) {
switch (opt) {
case 'i':
datafile = optarg;
break;
case 'd':
indexfile = optarg;
break;
case 'f':
mode = FLAT;
break;
case 'b':
mode = OFFSET;
break;
case 'h':
print_usage(argv[0], EXIT_SUCCESS);
break;
default:
print_usage(argv[0], EXIT_FAILURE);
}
}
if (mode == OFFSET) {
if (indexfile == NULL)
indexfile = "pi.offsetdb";
FILE *test;
if ((test = fopen(indexfile, "r")) == NULL) {
if (offsetdb_create(indexfile, datafile, 6) != 0) {
fprintf(stderr, "error: index failed, %s\n", strerror(errno));
remove(indexfile);
exit(EXIT_FAILURE);
}
} else {
fclose(test);
}
struct offsetdb db;
if (offsetdb_open(&db, indexfile, datafile) != 0) {
fprintf(stderr, "error: %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
for (int i = optind; i < argc; i++) {
if (offsetdb_print(&db, argv[i]) != 0) {
fprintf(stderr, "error: %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
}
offsetdb_close(&db);
} else if (mode == FLAT) {
for (int i = optind; i < argc; i++)
flat_search(datafile, argv[i]);
}
return 0;
}
|
C | UTF-8 | 759 | 3.4375 | 3 | [] | no_license | #include <stdio.h>
int main()
{
int n,i,j,k,count;
printf("Enter Row ");
scanf("%d",&n);
printf("Full Triangle with * \n");
for (i=1;i<=n;i++)
{
for(j=1;j<=(n-i);j++)
{
printf(" ");
}
for (k=1;k<=(2*i-1);k++)
{
printf("*");
}
printf("\n");
}
printf("Full Triangle with Number\n");
for (i=1;i<=n;i++)
{
for(j=1;j<=(n-i);j++)
{
printf(" ");
}
for (k=1,count = 1;k<=(2*i-1);k++,count++)
{
printf("%d",count);
}
printf("\n");
}
printf("Full Triangle with Number\n");
count = 1;
for (i=1;i<=n;i++)
{
for(j=1;j<=(n-i);j++)
{
printf(" ");
}
for (k=1;k<=(2*i-1);k++)
{
printf("%d",count);
}
printf("\n");
count++;
}
return 0;
}
|
C | UTF-8 | 2,902 | 2.921875 | 3 | [] | no_license |
#ifndef CLIENTE_H_
#define CLIENTE_H_
#define QTY_RAZAS 1000
#define MIN_ID 1
#define MAX_ID 1000
#define MAX_DESCRIPCION 51
struct {
char descripcion[MAX_DESCRIPCION];
int tipo;
int tamaño;
char pais[MAX_DESCRIPCION];
int id;
int isEmpty;
} typedef Raza;
/**
* Imprime todos los datos del cliente
* @param employee empleado a imprimir
* @return 0 Éxito -1 Error
*/
int raza_imprimir(Raza *employee);
/** \brief Imprime la lista de clientes con sus respectivos datos
* \param list puntero a array de cliente
* \param len largo del array
* \return 0 Éxito -1 Error
*
*/
int raza_imprimirArray(Raza* list, int length);
/**
* Para indicar que todas las posiciones del array están vacías,
* pone la bandera (isEmpty) en TRUE en todas las posiciones
* \param list puntero al array
* \param len largo del array
* \return 0 Éxito -1 Error
*
*/
int raza_iniciar(Raza* list, int len);
/**
* Busca un lugar vacio en el array y lo asigna a puntero indice
* @param list Puntero al array
* @param len longitud del array
* @param puntero indice
* @return 0 Éxito -1 Error
*/
int raza_emptyIndex(Raza *array, int length, int* indice);
/**
* Agrega un cliente al array de clientes
* @param list puntero a Array
* @param len longitud del array
* @param indice indice del Array donde se agregará
* @param *pId puntero a contador de Id
* @return 0 Éxito -1 Error
*/
int raza_alta(Raza *array, int length, int *pId);
/**
* Verifica si el array en su totalidad está vacio
* @param list puntero a Array
* @param length largo del Array
* @return 1 Verdadero (Array vacio) 0 Falso
*/
int raza_emptyArray(Raza *list, int length);
/**
* Verifica si existe una posición ocupada del array
* que coincida con el valor del id y la asigna a puntero indice
* @param list Puntero al array
* @param len longitud del array
* @param id id a buscar
* @param puntero a indice
* @return posición del array
*/
int raza_buscarId(Raza *array, int length, int id, int* indice);
/**
* Actualiza o nombre, o apellido, o salario o sector de un empleado
* de la lista de empleados, verificando si existe su id
* @param list puntero a array de empleados
* @param len longitud del array
* @return 0 Éxito -1 Error
*/
int raza_modificar(Raza *array, int length);
/**
* Pide un empleado de la lista de empleados a eliminar por id,
* verifica que existe y llama a la funcion removeEmployee
* @param list puntero a array de empleados
* @param len largo del array
* @return
*/
int raza_baja(Raza *list, int len);
/**
* Ordena los elementos del array
* en base a nombre y dni de manera ascendente o descendente
* @param array puntero a array
* @param largo del array
* @return 0 Éxito -1 Error
*
*/
int raza_ordenar(Raza *array, int length);
int raza_altaForzada(Raza* array, int length, int* pId, char* nombre, float altura, char* dni);
#endif /* CLIENTE_H_ */
|
C | UTF-8 | 962 | 4.40625 | 4 | [] | no_license | #include <stdio.h>
//7.Leer 10 números enteros, almacenarlos en un vector y determinar en qué posiciones se encuentra el número mayor.
void llenar_arreglo3(int arr[], int n){
for (int i = 0; i < n; i++)
{
printf("Digite un numero: \n");
scanf("%d", &arr[i]);
}
}
int num_mayor(int arr[], int n){
int mayor = arr[0];
for (int i = 1; i < n; i++)
{
if (arr[i]> mayor)
{
mayor = arr[i];
}
}
return mayor;
}
void determinar_posiciones(int arr[], int n, int mayor){
for (int i = 0; i < n; i++)
{
if (arr[i]== mayor)
{
printf("\nPosicion: %d ", i);
}
}
}
void imprimir_posiciones(int arr[], int n){
llenar_arreglo3(arr, n);
int mayor = num_mayor(arr, n);
printf("\nEl numero mayor del arreglo es: %d, y esta en la: ", mayor);
determinar_posiciones(arr, n , mayor);
} |
C | UTF-8 | 421 | 3.703125 | 4 | [] | no_license | #include <stdio.h>
static int maxSubSum(const int a[], int n)
{
int maxSum=0, thisSum=0, i;
for (i = 0; i < n; i++) {
thisSum += a[i];
if (thisSum > maxSum)
maxSum = thisSum;
if (thisSum < 0)
thisSum = 0;
}
return maxSum;
}
int main()
{
const int a[] = {4, -3, 5, -2, -1, 2, 6, -2};
printf("max sub sum: %d\n", maxSubSum(a, 8));
return 0;
}
|
C | UTF-8 | 1,657 | 2.859375 | 3 | [] | no_license | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_abs.h :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: apearl <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/09/15 02:41:21 by apearl #+# #+# */
/* Updated: 2019/09/15 02:50:28 by apearl ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef FT_ABS_H
# define FT_ABS_H
# define ABS(value) ((value < 0) ? (-value) : (value)) //if (x<0) return -x(-*-=+); else return x;
#endif
/*
#ifndef FT_ABS_H
# define FT_ABS_H
#define ABS(x) ((x < 0) ? (-x) : (x))
#endif
#ifndef FT_ABS_H
# define FT_ABS_H
# define ABS(x) ((x<0)?(-x):(x))
#endif
#ifndef FT_ABS_H
# define FT_ABS_H
# define ABS(Value) ((Value < 0) ? (-Value) : (Value))
#endif
/*
int abs(int x)
{
if (x>=0) return x;
else return -x;
}
int main()
{
int x, y;
printf("Type the coordinates of a point in 2-plane, say P = (x,y). First x=");
scanf("%d", &x);
printf("Second y=");
scanf("%d", &y);
printf("The distance of the P point to the x-axis is %d. \n Its distance to the y-axis is %d. \n", abs(y), abs(x));
return 0;
}
*/
|
C | UTF-8 | 17,678 | 3.015625 | 3 | [] | no_license | /** @file
* Główna pętla programu.
*
* @author Konrad Staniszewski
* @copyright Konrad Staniszewski
* @date 25.05.2018
*/
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "parser.h"
#include "phone_bases_system.h"
#include "vector.h"
#include "input.h"
#include "character.h"
#include "stdfunc.h"
/**
* @brief Bazowy prefiks informacji o błędzie.
*/
#define BASIC_ERROR_MESSAGE "ERROR"
/**
* @brief Domyślny infiks informacji o błędzie.
*/
#define BASIC_ERROR_INFIX " "
/**
* @brief Sufiks informacji o błędzie end of file.
*/
#define EOF_ERROR_SUFFIX " EOF"
/**
* @brief Infiks informacji o błędzie związanym z pamięcią.
*/
#define MEMORY_ERROR_INFIX " MEMORY "
/**
* @brief Infiks informacji o błędzie operatora DEL.
*/
#define DEL_OPERATOR_ERROR_INFIX \
(CONCAT(" ", PARSER_OPERATOR_DELETE, " "))
/**
* @brief Infiks informacji o błędzie operatora ?.
*/
#define QM_OPERATOR_ERROR_INFIX \
(CONCAT(" ", PARSER_OPERATOR_QM_STRING, " "))
/**
* @brief Infiks informacji o błędzie operatora >.
*/
#define REDIRECT_OPERATOR_ERROR_INFIX \
(CONCAT(" ", PARSER_OPERATOR_REDIRECT_STRING, " "))
/**
* @brief Infiks informacji o błędzie operatora @.
*/
#define NONTRIVIAL_OPERATOR_ERROR_INFIX \
(CONCAT(" ", PARSER_OPERATOR_NONTRIVIAL_STRING, " "))
/**
* @brief Kod błędu zwracany przez program.
*/
#define ERROR_EXIT_CODE 1
/**
* @brief Kod zwracany przez program w przypadku braku błędów.
*/
#define SUCCESS_EXIT_CODE 0
/**
* Przesunięcie pozycji błędu operatora PARSER_OPERATOR_[NEW/DELETE]
* przy użyciu nazwy zastrzeżonej (PARSER_OPERATOR_[NEW/DELETE]).
*/
#define OPERATOR_POSITION_OFFSET 2
/**
* @brief Wskaźnik na strukturę przechowującą bazy przekierowań.
*/
static PhoneBases bases = NULL;
/**
* @brief Wskaźniki na pomocniczy Vector do buforowania wejścia.
*/
static Vector word1 = NULL;
/**
* @brief Wskaźniki na pomocniczy Vector do buforowania wejścia.
*/
static Vector word2 = NULL;
/**
* @brief Wskaźnik na aktualnie aktywną bazę przekierowań.
* NULL w przypadku braku.
*/
static struct PhoneForward *currentBase = NULL;
/**
* @brief Struktura opisująca stan parsowania.
*/
static struct Parser parser;
/**
* @brief Kończy program.
* Zwalnia pamięć i kończy program kodem @p exit_code.
* @param[in] exit_code - kod zakończenia programu.
*/
static void exit_and_clean(int exit_code) {
if (bases != NULL) {
phoneBasesDestroyPhoneBases(bases);
}
if (word1 != NULL) {
vectorDelete(word1);
}
if (word2 != NULL) {
vectorDelete(word2);
}
exit(exit_code);
}
/**
* @brief Wypisuje informację o błędzie.
* @param[in] infix - infiks informacji
* @param[in] bytes - liczba wczytanych bajtów.
*/
static void printErrorMessage(const char *infix, size_t bytes) {
fprintf(stderr, "%s%s%zu\n", BASIC_ERROR_MESSAGE, infix,
bytes);
}
/**
* @brief Wypisuje informacje o błędzie związanym z nieoczekiwanym końcem pliku.
*/
static void printEofError() {
fprintf(stderr, "%s%s\n", BASIC_ERROR_MESSAGE, EOF_ERROR_SUFFIX);
}
/**
* @brief Inicjuje program.
* Inicjuje struktury:
* @ref parser
* @ref bases
* @ref word1
* @ref word2
* w przypadku problemów z pamięcią kończy program
* i wypisuje informacje o błędzie.
*/
static void initProgram() {
parser = parserCreateNew();
bases = phoneBasesCreateNewPhoneBases();
if (bases == NULL) {
printErrorMessage(MEMORY_ERROR_INFIX, parserGetReadBytes(&parser));
exit_and_clean(ERROR_EXIT_CODE);
}
word1 = vectorCreate();
if (word1 == NULL) {
printErrorMessage(MEMORY_ERROR_INFIX, parserGetReadBytes(&parser));
exit_and_clean(ERROR_EXIT_CODE);
}
word2 = vectorCreate();
if (word2 == NULL) {
printErrorMessage(MEMORY_ERROR_INFIX, parserGetReadBytes(&parser));
exit_and_clean(ERROR_EXIT_CODE);
}
}
/**
* @brief Dodaje do Vectora '\0' na koniec.
* W przypadku problemów z pamięcią kończy program
* i wypisuje informacje o błędzie.
* @param[in] v - dany Vector.
*/
static void makeVectorCStringCompatible(Vector v) {
if (!vectorPushBack(v, '\0')) {
printErrorMessage(MEMORY_ERROR_INFIX, parserGetReadBytes(&parser));
exit_and_clean(ERROR_EXIT_CODE);
}
}
/**
* @brief Czyści Vectory @p word1 @p word2.
*/
static void loopStepClear() {
vectorSoftClear(word1);
vectorSoftClear(word2);
}
/**
* @brief Sprawdza czy wystąpił błąd parsowania.
* Jeżeli wystąpił to wypisuje odpowiednią informację
* i kończy program.
*/
static void checkParserError() {
if (parserIsCommentEofError(&parser)) {
printEofError();
exit_and_clean(ERROR_EXIT_CODE);
}
if (parserError(&parser)) {
printErrorMessage(BASIC_ERROR_INFIX, parserGetReadBytes(&parser));
exit_and_clean(ERROR_EXIT_CODE);
}
}
/**
* @brief Sprawdza czy wystąpił błąd parsowania typu EOF.
* Jeżeli wystąpił to wypisuje odpowiednią informację
* i kończy program.
*/
static void checkEofError() {
if (inputIsEOF()) {
printEofError();
exit_and_clean(ERROR_EXIT_CODE);
}
}
/**
* @brief Sprawdza czy parsowanie się zakończyło.
* Jeżeli tak to kończy program.
*/
static void checkParserFinished() {
if (parserFinished(&parser)) {
exit_and_clean(SUCCESS_EXIT_CODE);
}
}
/**
* @brief Pomija zbędne znaki.
* Wywołuje @ref parserSkipSkipable,
* oraz @ref checkParserError.
*/
static void skipSkipable() {
parserSkipSkipable(&parser);
checkParserError();
}
/**
* @brief Obsługuje operację dodania nowej bazy.
* Zakłada, że poprzednio wczytaną operacją jest PARSER_OPERATOR_NEW.
* W przypadku problemów wypisuje odpowiedni komunikat
* i kończy program.
*/
static void readOperationNew() {
skipSkipable();
checkEofError();
int nextType = parserNextType(&parser);
checkParserError();
if (nextType != PARSER_ELEMENT_TYPE_WORD) {
printErrorMessage(BASIC_ERROR_INFIX, parserGetReadBytes(&parser) + 1);
exit_and_clean(ERROR_EXIT_CODE);
}
if (!parserReadIdentificator(&parser, word1)) {
printErrorMessage(MEMORY_ERROR_INFIX, parserGetReadBytes(&parser));
exit_and_clean(ERROR_EXIT_CODE);
}
checkParserError();
makeVectorCStringCompatible(word1);
if (strcmp(vectorBegin(word1), PARSER_OPERATOR_DELETE) == 0
|| strcmp(vectorBegin(word1), PARSER_OPERATOR_NEW) == 0) {
printErrorMessage(BASIC_ERROR_INFIX,
parserGetReadBytes(&parser) - OPERATOR_POSITION_OFFSET);
exit_and_clean(ERROR_EXIT_CODE);
}
if (vectorSize(word1) <= 1) {
printErrorMessage(BASIC_ERROR_INFIX, parserGetReadBytes(&parser));
exit_and_clean(ERROR_EXIT_CODE);
}
currentBase = phoneBasesAddBase(bases, vectorBegin(word1));
if (currentBase == NULL) {
printErrorMessage(MEMORY_ERROR_INFIX, parserGetReadBytes(&parser));
exit_and_clean(ERROR_EXIT_CODE);
}
}
/**
* @brief Obsługuje operację phfwdRemove(numer).
* Oczekuje, że poprzednio wczytano operator PARSER_OPERATOR_DELETE
* oraz że na wczytanie według @p parserNextType oczekuje numer.
* @param[in] operatorPos - pozycja operatora usunięcia.
* W przypadku problemów wypisuje odpowiedni komunikat
* i kończy program.
*/
static void readOperationDeleteNumber(size_t operatorPos) {
if (!parserReadNumber(&parser, word1)) {
printErrorMessage(MEMORY_ERROR_INFIX, parserGetReadBytes(&parser));
exit_and_clean(ERROR_EXIT_CODE);
}
checkParserError();
if (currentBase == NULL) {
printErrorMessage(DEL_OPERATOR_ERROR_INFIX, operatorPos);
exit_and_clean(ERROR_EXIT_CODE);
}
makeVectorCStringCompatible(word1);
phfwdRemove(currentBase, vectorBegin(word1));
}
/**
* @brief Obsługuje operację usunięcia bazy przekierowań.
* Oczekuje, że poprzednio wczytano operator PARSER_OPERATOR_DELETE
* oraz że na wczytanie według @p parserNextType oczekuje identyfikator.
* @param[in] operatorPos - pozycja (nr bajtu) operatora usunięcia.
* W przypadku problemów wypisuje odpowiedni komunikat
* i kończy program.
*/
static void readOperationDeleteBase(size_t operatorPos) {
if (!parserReadIdentificator(&parser, word1)) {
printErrorMessage(MEMORY_ERROR_INFIX, parserGetReadBytes(&parser));
exit_and_clean(ERROR_EXIT_CODE);
}
checkParserError();
makeVectorCStringCompatible(word1);
if (strcmp(vectorBegin(word1), PARSER_OPERATOR_DELETE) == 0
|| strcmp(vectorBegin(word1), PARSER_OPERATOR_NEW) == 0) {
printErrorMessage(BASIC_ERROR_INFIX,
parserGetReadBytes(&parser) - OPERATOR_POSITION_OFFSET);
exit_and_clean(ERROR_EXIT_CODE);
}
struct PhoneForward *toDel = phoneBasesGetBase(bases, vectorBegin(word1));
if (toDel == NULL) {
printErrorMessage(DEL_OPERATOR_ERROR_INFIX, operatorPos);
exit_and_clean(ERROR_EXIT_CODE);
}
if (toDel == currentBase) {
currentBase = NULL;
}
phoneBasesDelBase(bases, vectorBegin(word1));
}
/**
* @brief Obsługuje operację zadaną przez operator PARSER_OPERATOR_DELETE.
* Oczekuje, że poprzednio wczytano operator PARSER_OPERATOR_DELETE.
*/
static void readOperationDelete() {
size_t operatorPos =
parserGetReadBytes(&parser) - strlen(PARSER_OPERATOR_DELETE) + 1;
skipSkipable();
checkEofError();
int nextType = parserNextType(&parser);
checkParserError();
if (nextType == PARSER_ELEMENT_TYPE_NUMBER) {
readOperationDeleteNumber(operatorPos);
} else if (nextType == PARSER_ELEMENT_TYPE_WORD) {
readOperationDeleteBase(operatorPos);
} else {
printErrorMessage(BASIC_ERROR_INFIX, parserGetReadBytes(&parser) + 1);
exit_and_clean(ERROR_EXIT_CODE);
}
}
/**
* @brief Wypisuje numery.
* @param[in] numbers - struktura przechowująca numery do wypisania.
*/
static void printNumbers(const struct PhoneNumbers *numbers) {
size_t i;
for (i = 0; phnumGet(numbers, i) != NULL; i++) {
fprintf(stdout, "%s\n", phnumGet(numbers, i));
}
}
/**
* @brief Obsługuje operację phwfdReverse.
* Oczekuje, że poprzednio wczytano PARSER_OPERATOR_QM.
*/
static void readOperationReverse() {
size_t operatorPos = parserGetReadBytes(&parser);
skipSkipable();
checkEofError();
int nextType = parserNextType(&parser);
checkParserError();
if (nextType == PARSER_ELEMENT_TYPE_NUMBER) {
if (!parserReadNumber(&parser, word1)) {
printErrorMessage(MEMORY_ERROR_INFIX, parserGetReadBytes(&parser));
exit_and_clean(ERROR_EXIT_CODE);
}
checkParserError();
if (currentBase == NULL) {
printErrorMessage(QM_OPERATOR_ERROR_INFIX, operatorPos);
exit_and_clean(ERROR_EXIT_CODE);
}
makeVectorCStringCompatible(word1);
const struct PhoneNumbers *numbers
= phfwdReverse(currentBase, vectorBegin(word1));
if (numbers == NULL) {
printErrorMessage(MEMORY_ERROR_INFIX, parserGetReadBytes(&parser));
exit_and_clean(ERROR_EXIT_CODE);
}
printNumbers(numbers);
phnumDelete(numbers);
} else {
printErrorMessage(BASIC_ERROR_INFIX, parserGetReadBytes(&parser) + 1);
exit_and_clean(ERROR_EXIT_CODE);
}
}
/**
* @brief Obsługuje operację phfwdNonTrivialCount.
* Oczekuje, że poprzednio wczytano PARSER_OPERATOR_NONTRIVIAL.
*/
static void readOperationNonTrivial() {
size_t operatorPos = parserGetReadBytes(&parser);
skipSkipable();
checkEofError();
int nextType = parserNextType(&parser);
checkParserError();
if (nextType == PARSER_ELEMENT_TYPE_NUMBER) {
if (!parserReadNumber(&parser, word1)) {
printErrorMessage(MEMORY_ERROR_INFIX, parserGetReadBytes(&parser));
exit_and_clean(ERROR_EXIT_CODE);
}
checkParserError();
if (currentBase == NULL) {
printErrorMessage(NONTRIVIAL_OPERATOR_ERROR_INFIX, operatorPos);
exit_and_clean(ERROR_EXIT_CODE);
}
size_t len = vectorSize(word1);
if (len <= 12) {
len = 0;
} else {
len -= 12;
}
makeVectorCStringCompatible(word1);
size_t result = phfwdNonTrivialCount(currentBase, vectorBegin(word1), len);
fprintf(stdout, "%zu\n", result);
} else {
printErrorMessage(BASIC_ERROR_INFIX, parserGetReadBytes(&parser) + 1);
exit_and_clean(ERROR_EXIT_CODE);
}
}
/**
* @brief Obsługuje operację phfwdGet(word1).
*/
static void readOperatorGetFromWord1() {
makeVectorCStringCompatible(word1);
if (currentBase == NULL) {
printErrorMessage(QM_OPERATOR_ERROR_INFIX, parserGetReadBytes(&parser));
exit_and_clean(ERROR_EXIT_CODE);
}
const struct PhoneNumbers *numbers = phfwdGet(currentBase, vectorBegin(word1));
if (numbers == NULL) {
printErrorMessage(MEMORY_ERROR_INFIX, parserGetReadBytes(&parser));
exit_and_clean(ERROR_EXIT_CODE);
}
printNumbers(numbers);
phnumDelete(numbers);
}
/**
* @brief Obsługuje operację przekierowania numerów word1 > word2.
* Oczekuje wczytania pierwszego numeru do word1
* i wczytania operatora przekierowania.
*/
static void readOperatorRedirectWord1() {
size_t operatorPos = parserGetReadBytes(&parser);
skipSkipable();
checkEofError();
int nextType = parserNextType(&parser);
checkParserError();
if (nextType != PARSER_ELEMENT_TYPE_NUMBER) {
printErrorMessage(BASIC_ERROR_INFIX, parserGetReadBytes(&parser) + 1);
exit_and_clean(ERROR_EXIT_CODE);
}
if (!parserReadNumber(&parser, word2)) {
printErrorMessage(MEMORY_ERROR_INFIX, parserGetReadBytes(&parser));
exit_and_clean(ERROR_EXIT_CODE);
}
checkParserError();
if (currentBase == NULL) {
printErrorMessage(REDIRECT_OPERATOR_ERROR_INFIX, operatorPos);
exit_and_clean(ERROR_EXIT_CODE);
}
makeVectorCStringCompatible(word1);
makeVectorCStringCompatible(word2);
if (strcmp(vectorBegin(word1), vectorBegin(word2)) == 0) {
printErrorMessage(REDIRECT_OPERATOR_ERROR_INFIX, operatorPos);
exit_and_clean(ERROR_EXIT_CODE);
}
if (!phfwdAdd(currentBase, vectorBegin(word1), vectorBegin(word2))) {
printErrorMessage(MEMORY_ERROR_INFIX, parserGetReadBytes(&parser));
exit_and_clean(ERROR_EXIT_CODE);
}
}
/**
* @brief Wczytuje operację / jej fragment i obsługuje ją.
* @param[in] nextType - oczekiwany typ wczytanych danych,
* pochodzący z wywołania @ref parserNextType.
*/
static void readOperation(int nextType) {
if (nextType == PARSER_ELEMENT_TYPE_WORD) {
int operator = parserReadOperator(&parser);
checkParserError();
checkEofError();
if (operator == PARSER_ELEMENT_TYPE_OPERATOR_NEW) {
readOperationNew();
} else if (operator == PARSER_ELEMENT_TYPE_OPERATOR_DELETE) {
readOperationDelete();
} else {
printErrorMessage(BASIC_ERROR_INFIX, parserGetReadBytes(&parser));
exit_and_clean(ERROR_EXIT_CODE);
}
} else if (nextType == PARSER_ELEMENT_TYPE_SINGLE_CHARACTER_OPERATOR) {
int operator = parserReadOperator(&parser);
checkParserError();
checkEofError();
if (operator == PARSER_ELEMENT_TYPE_OPERATOR_QM) {
readOperationReverse();
} else if (operator == PARSER_ELEMENT_TYPE_OPERATOR_NONTRIVIAL) {
readOperationNonTrivial();
} else {
printErrorMessage(BASIC_ERROR_INFIX, parserGetReadBytes(&parser));
exit_and_clean(ERROR_EXIT_CODE);
}
} else if (nextType == PARSER_ELEMENT_TYPE_NUMBER) {
if (!parserReadNumber(&parser, word1)) {
printErrorMessage(MEMORY_ERROR_INFIX, parserGetReadBytes(&parser));
exit_and_clean(ERROR_EXIT_CODE);
}
checkParserError();
skipSkipable();
checkEofError();
int midType = parserNextType(&parser);
checkParserError();
if (midType == PARSER_ELEMENT_TYPE_SINGLE_CHARACTER_OPERATOR) {
int operator = parserReadOperator(&parser);
checkParserError();
if (operator == PARSER_ELEMENT_TYPE_OPERATOR_QM) {
readOperatorGetFromWord1();
} else if (operator == PARSER_ELEMENT_TYPE_OPERATOR_REDIRECT) {
checkEofError();
readOperatorRedirectWord1();
} else {
printErrorMessage(BASIC_ERROR_INFIX,
parserGetReadBytes(&parser) + 1);
exit_and_clean(ERROR_EXIT_CODE);
}
} else {
printErrorMessage(BASIC_ERROR_INFIX,
parserGetReadBytes(&parser) + 1);
exit_and_clean(ERROR_EXIT_CODE);
}
} else {
printErrorMessage(BASIC_ERROR_INFIX,
parserGetReadBytes(&parser) + 1);
exit_and_clean(ERROR_EXIT_CODE);
}
}
/**
* @brief Główna pętla programu.
* @return
*/
int main() {
initProgram();
while (true) {
loopStepClear();
skipSkipable();
checkParserFinished();
int nextType = parserNextType(&parser);
checkParserError();
readOperation(nextType);
}
return 0;
}
|
C | GB18030 | 2,212 | 2.65625 | 3 | [] | no_license | #include "common.h"
TQStruct TQ[MAX_TASK_NUM];
unsigned int current_tsk;
unsigned int last_tsk;
/**
* ʼ
*/
TQStruct emptytask;
void Init_TQ(void)
{
int i;
for (i=0; i<MAX_TASK_NUM; i++)
{
TQ[i].event = 0;
}
current_tsk = 0;
last_tsk = 0;
for(i=0;i<MAX_PACK_LENGTH;i++)
{
emptytask.data[i] = 0;
}
emptytask.event = 0;
}
/**
*
*/
uint8 harderr = 0;
uint8 PostTask(uint8 *data,uint8 event)
{
uint8 i=0;
DisableInterrupt();
if (TQ[last_tsk].event == 0)
{
TQ[last_tsk].event = event;
for(i=0;i<MAX_PACK_LENGTH;i++)
{
TQ[last_tsk].data[i] = *data++;
}
last_tsk = (last_tsk + 1) % MAX_TASK_NUM;
EnableInterrupt();
return TQ_SUCCESS;
}
else
{
//printf("TQ is FULL!\n");
DebugMsg("Task Quene Full");
EnableInterrupt();
return TQ_FULL;
}
}
/**
*
*/
uint8 Pop_T(TQStruct* task)
{
//DisableInterrupt();
if (TQ[current_tsk].event != 0)
{
*task = TQ[current_tsk];
TQ[current_tsk].event = 0;
current_tsk = (current_tsk + 1) % MAX_TASK_NUM;
//EnableInterrupt();
return TQ_SUCCESS;
}
else
{
//printf("TQ is EMPTY!\n");
//EnableInterrupt();
*task = emptytask;
return TQ_FULL;
}
}
TQStruct current_event;
uint8 Process_Event()
{
Pop_T(¤t_event);
switch(current_event.event)
{
case EVENT_BEACON_SEND:
SendBeacon(current_event.data);
break;
case EVENT_JOINREQUEST_HANDLER:
JoinRequestHandler(current_event.data);
break;
// case EVENT_JOINREQUESTACKOK_HANDLER:
// DisableInterrupt();
// JoinRequestACKOKHandler(current_event.data);
// EnableInterrupt();
// break;
case EVENT_DATA_HANDLER:
DataHandler(current_event.data);
break;
case EVENT_UPLOAD_DATA:
Upload_Data();
break;
case EVENT_REJOIN_SEND:
SendReJoin();
break;
case EVENT_KEEPALIVE_CHECK:
KeepAliveCheck();
break;
case EVENT_A7139_RESET:
A7139_Reset();
break;
case EVENT_LINK_SEND:
LinkSend();
break;
}
return current_event.event;
}
|
C | WINDOWS-1250 | 1,276 | 2.984375 | 3 | [] | no_license | #include <stdio.h>
int main(void){
int N,M,X,Y;
scanf("%d %d %d %d",&N,&M,&X,&Y);
int k=0;
int l=0;
int ans=0;
int nowtime=0;
int a[N],b[M];
for(int i=0;i<N;i++)scanf("%d",&a[i]);
for(int i=0;i<M;i++)scanf("%d",&b[i]);
while(1){
for(;k<N;k++){
if(nowtime<=a[k]){
nowtime=a[k]+X;
for(;l<M;l++){
if(nowtime<=b[l]){
nowtime=b[l]+Y;
ans++;
break;
}
}
break;
}
}
if(k==N||l==M)break;
}
printf("%d\n",ans);
return 0;
} ./Main.c: In function main:
./Main.c:4:5: warning: ignoring return value of scanf, declared with attribute warn_unused_result [-Wunused-result]
scanf("%d %d %d %d",&N,&M,&X,&Y);
^
./Main.c:10:25: warning: ignoring return value of scanf, declared with attribute warn_unused_result [-Wunused-result]
for(int i=0;i<N;i++)scanf("%d",&a[i]);
^
./Main.c:11:25: warning: ignoring return value of scanf, declared with attribute warn_unused_result [-Wunused-result]
for(int i=0;i<M;i++)scanf("%d",&b[i]);
^ |
C | UTF-8 | 137 | 2.90625 | 3 | [] | no_license | #include "my.h"
void my_alpha(){
/*Prints the entire alphabet in uppercase.*/
char c;
for (c = 'A'; c <= 'Z'; c++){
my_char(c);
}
} |
C | UTF-8 | 1,552 | 3.0625 | 3 | [] | no_license | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* swap.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: bmangin <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/05/29 11:38:20 by bmangin #+# #+# */
/* Updated: 2021/10/07 20:54:11 by bmangin ### ########lyon.fr */
/* */
/* ************************************************************************** */
#include "instruction.h"
/*
** sa : swap a - intervertit les 2 premiers éléments au sommet de la pile a.
** Ne fait rien s’il n’y en a qu’un ou aucun.
*/
void swap_a(t_global *g)
{
swap_list(&g->a);
g->out = ft_strjoin_free(g->out, "sa\n", 1);
g->coup++;
}
/*
** sb : swap b - intervertit les 2 premiers éléments au sommet de la pile b.
** Ne fait rien s’il n’y en a qu’un ou aucun.
*/
void swap_b(t_global *g)
{
swap_list(&g->b);
g->out = ft_strjoin_free(g->out, "sb\n", 1);
g->coup++;
}
/*
** ss : sa et sb en même temps.
*/
void swap_s(t_global *g)
{
swap_list(&g->a);
swap_list(&g->b);
g->out = ft_strjoin_free(g->out, "ss\n", 1);
g->coup++;
}
|
C | UTF-8 | 3,552 | 3.328125 | 3 | [] | no_license | #include <io.h>
#include <stdarg.h>
#include <util.h>
#include <stdint.h>
#include <stddef.h>
#include <stdbool.h>
#define MAX_INT_STR_SIZE (10)
#define MAX_UINT_STR_SIZE (11)
#define HEX (0xF)
#define HEX_SIZE (8)
static const char hex_values[0x10] = {'0', '1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
void vprintf(struct output_stream *ostream, const char* format, va_list parameters) {
while (*format)
{
if (format[0] != '%' || format[1] == '%') {
if (format[0] == '%')
format++;
size_t amount = 1;
while (format[amount] && format[amount] != '%')
amount++;
write(ostream, format, amount);
format += amount;
continue;
}
format++;
switch (*format) {
case 'c': {
char c = (char) va_arg(parameters, int);
write(ostream, &c, sizeof(char));
}
break;
case 's': {
const char* string = va_arg(parameters, const char*);
size_t len = strlen(string);
write(ostream, string, len);
}
break;
case 'i': {
char str[MAX_INT_STR_SIZE];
size_t offset = MAX_INT_STR_SIZE;
uint32_t val = va_arg(parameters, uint32_t);
do {
char c = '0'+(char)(val%10);
val /= 10;
str[--offset] = c;
} while (val);
write(ostream, str+offset, MAX_INT_STR_SIZE - offset);
}
break;
case 'u': {
char str[MAX_UINT_STR_SIZE];
size_t offset = MAX_UINT_STR_SIZE;
int32_t val = va_arg(parameters, int32_t);
bool flip = val < 0;
if (flip)
val = -val;
do {
char c = '0'+(char)(val%10);
val /= 10;
str[--offset] = c;
} while (val);
if (flip)
str[--offset] = '-';
write(ostream, str+offset, MAX_UINT_STR_SIZE - offset);
}
break;
case 'x': {
uint32_t val = va_arg(parameters, uint32_t);
char str[HEX_SIZE+2];
size_t offset = HEX_SIZE+2;
while(val) {
uint32_t value = val & 0xF;
str[--offset] = hex_values[value];
val >>= 4;
}
str[--offset]= 'x';
str[--offset]= '0';
write(ostream, str+offset, (HEX_SIZE+2)-offset);
}
break;
case 'p': {
uint32_t val = va_arg(parameters, uint32_t);
char str[HEX_SIZE+2];
size_t offset = HEX_SIZE;
while(--offset>=2) {
uint32_t value = val & 0xF;
str[offset] = hex_values[value];
val >>= 4;
}
str[0]= '0';
str[1]= 'x';
write(ostream, str, HEX_SIZE+2);
}
}
format++;
}
}
void printf(struct output_stream *ostream, const char* format, ...)
{
va_list argp;
va_start(argp, format);
vprintf(ostream, format, argp);
va_end(argp);
} |
C | UTF-8 | 620 | 2.890625 | 3 | [
"MIT"
] | permissive | /* ======================= Microscheme =======================
* Microscheme-C FFI demo
* (C) 2014-2021 Ryan Suchocki, et al.
* http://github.com/ryansuchocki/microscheme
*/
#include "microscheme_types.c"
#include <math.h>
ms_value mathpow(ms_value x, ms_value y)
{
return round(pow(x, y));
}
ms_value vectsum(ms_value v)
{
vector *vect = asVector(v);
int i, total = 0;
for (i = 0; i < vect->length; i++)
{
total += vect->data[i];
}
return total;
}
ms_value listsum(ms_value v)
{
if (isNull(v)) return 0;
pair *lst = asPair(v);
return lst->car + listsum(lst->cdr);
} |
C | UTF-8 | 1,345 | 2.8125 | 3 | [
"MIT"
] | permissive | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* apply_zero_padding.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jlagneau <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/04/22 10:08:23 by jlagneau #+# #+# */
/* Updated: 2017/04/23 04:03:52 by jlagneau ### ########.fr */
/* */
/* ************************************************************************** */
#include <libft.h>
#include <ft_printf.h>
char *apply_zero_padding(char *str, t_flags *flags)
{
char *tmp;
size_t len;
tmp = NULL;
len = (flags->field_width > flags->visual_len)
? flags->field_width - flags->visual_len : 0;
if (flags->flag_char & FC_ZERO && flags->conv_spec & CS_NUMERIC && len > 0)
{
tmp = prepend_zeroes(str, len);
flags->visual_len += len;
}
else
tmp = ft_strdup(str);
if (!tmp)
ft_puterr_and_exit(__FILE__);
return (tmp);
}
|
C | UTF-8 | 1,797 | 4 | 4 | [] | no_license | #include "binary_trees.h"
#include <stdio.h>
/**
* avl_remove - remove a node from an AVL tree
* @root: pointer to root of tree
* @value: value to remove
*
* Return: pointer to new root
*/
avl_t *avl_remove(avl_t *root, int value)
{
avl_t *node;
avl_t *rem; /* node to remove */
int balance;
if (root == NULL)
return (NULL);
if (root->n == value)
{
rem = root;
node = find_successor(rem->right);
if (node == NULL && root->left == NULL)
{
free(root);
return (NULL);
}
else if (node == NULL)
{
root = root->left;
root->parent = rem->parent;
free(rem);
return (root);
}
else if (node->n == root->right->n)
{
root = root->right;
root->parent = rem->parent;
root->left = rem->left;
rem->left->parent = root;
free(rem);
}
root->n = node->n;
root->right = avl_remove(root->right, node->n);
}
else if (root->n > value)
{
root->left = avl_remove(root->left, value);
node = root->left;
}
else
{
root->right = avl_remove(root->right, value);
node = root->right;
}
balance = binary_tree_balance(root);
printf("balance factor at %d is %d\n", root->n, balance);
if (balance < -1)
{
printf("Before balance_left\n");
binary_tree_print(root);
balance_left(&root, node);
printf("After balance_left\n");
binary_tree_print(root);
}
else if (balance > 1)
{
printf("Before balance_right\n");
binary_tree_print(root);
balance_right(&root, node);
printf("After\n");
binary_tree_print(root);
}
return (root);
}
/**
* find_successor - finds first in-order successor
* @root: pointer to root of tree
*
* Return: pointer to successor, or NULL if fail
*/
bst_t *find_successor(bst_t *root)
{
if (root == NULL)
return (NULL);
if (root->left == NULL)
return (root);
return (find_successor(root->left));
}
|
C | UTF-8 | 398 | 3.046875 | 3 | [] | no_license | #include <stdio.h>
#include <dirent.h>
#include<string.h>
void main(){
DIR *p,*sp;
struct dirent *d,*dd;
p=opendir(".");
while(d=readdir(p))
{
printf("%s\n",d->d_name);
if(!strcmp(d->d_name,".")||!strcmp(d->d_name,".."))
continue;
sp=opendir(d->d_name);
if(sp)
while(dd=readdir(sp))
printf("-->%s\n:",dd->d_name);
}
} |
C | UTF-8 | 209 | 3.359375 | 3 | [] | no_license | #include "holberton.h"
/**
* _strlen - function that prints the square.
* @s: caracters to evaluate
* Return: i.
*/
int _strlen(char *s)
{
short i = 0;
while (s[i] != '\0')
{
i++;
}
return (i);
}
|
C | UTF-8 | 2,564 | 2.765625 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
void savePGMFile(unsigned char *blemish, char *filename, int w, int h);
void fnBlemish(unsigned char *gray, unsigned char *blemish, int w, int h);
void main(int argv, char **argc)
{
int i;
unsigned char inchar[3];
unsigned char *gray;
unsigned char *blemish;
int w, h;
FILE *in = NULL;
in = fopen(argc[1], "rb");
if (in == NULL)
{
printf("Error\n");
}
w = atoi(argc[3]);
h = atoi(argc[4]);
blemish = (unsigned char *)malloc(w*h);
gray = (unsigned char *)malloc(w*h);
for (i=0;i<w*h;i++)
{
fread(inchar, 1, 3, in);
gray[i] = (inchar[0] + inchar[1] + inchar[2])/3;
}
fnBlemish(gray, blemish, w, h);
savePGMFile(blemish, argc[2], w, h);
//savePGMFile(gray, argc[2], w, h);
free(blemish);
free(gray);
fclose(in);
}
#define BLEMISH_LEVEL 3
#define BLEMISH_LEN 15
void fnBlemish(unsigned char *gray, unsigned char *blemish, int w, int h)
{
unsigned char prev;
int start = 0, len;
int i, j, k;
unsigned char *blemishX;
unsigned char *blemishY;
blemishX = (unsigned char *)malloc(w*h);
blemishY = (unsigned char *)malloc(w*h);
memset(blemishX, 0, w*h);
memset(blemishY, 0, w*h);
for (i=0;i<h;i++)
{
for (j=0;j<w;j+=3)
{
if (j == 0)
{
prev = gray[i*w];
start = 0;
continue;
}
if (!start && (prev - gray[i*w+j]) < BLEMISH_LEVEL)
{
start = j-3;
}
if (start && (gray[i*w+j]-prev) > BLEMISH_LEVEL)
{
len = j - start;
if (len < BLEMISH_LEN && len > BLEMISH_LEN/2)
{
memset(blemishX + i*w + start, 255, j-start);
printf("Xlen = %d\n\r", len);
}
start = 0;
}
prev = gray[i*w+j];
}
}
for (i=0;i<w;i++)
{
for (j=0;j<h;j+=3)
{
if (j == 0)
{
prev = gray[i];
start = 0;
continue;
}
if (!start && (prev - gray[i+j*w]) < BLEMISH_LEVEL)
{
start = j-3;
}
if (start && (gray[i+j*w]-prev) > BLEMISH_LEVEL)
{
len = j - start;
if (len < BLEMISH_LEN && len > BLEMISH_LEN/2)
{
for (k=start;k<j+1;k++)
{
blemishY[i + k*w] = 255;
}
printf("Ylen = %d\n\r", len);
}
start = 0;
}
prev = gray[i+j*w];
}
}
for (i=0;i<h*w;i++)
{
blemish[i] = blemishX[i] & blemishY[i];
}
free(blemishX);
free(blemishY);
}
void savePGMFile(unsigned char *blemish, char *filename, int w, int h)
{
FILE *out = NULL;
int i;
out = fopen(filename, "wt");
fprintf(out, "P2\n%d %d\n255\n", w, h);
for (i=0;i<w*h;i++)
{
fprintf(out, "%3d\n", blemish[i]);
}
fclose(out);
}
|
C | UTF-8 | 2,526 | 2.84375 | 3 | [
"Apache-2.0"
] | permissive | #define _GNU_SOURCE
#include <stdlib.h>
#include <string.h>
#include "http_response.h"
#include "output_buffer.h"
#include "logging.h"
#define STATUS_SIZE 12
#define CONTENT_SIZE 18
#define CONNECTION_SIZE 24
#define BREAK_SIZE 2
static inline const char *get_reason(int status_code) {
switch (status_code) {
// 1xx: Informational - Request received, continuing process
case 100: return "Continue";
case 101: return "Switching Protocols";
// 2xx: Success - The action was successfully received, understood, and accepted
case 200: return "Ok";
case 201: return "Created";
case 202: return "Accepted";
case 203: return "Non-Authoritative Information";
case 204: return "No Content";
case 205: return "Reset Content";
case 206: return "Partial Content";
// 3xx: Redirection - Further action must be taken in order to complete the request
case 300: return "Multiple Choices";
case 301: return "Moved Permanently";
case 302: return "Found";
case 303: return "See Other";
case 304: return "Not Modified";
case 305: return "Use Proxy";
case 307: return "Temporary Redirect";
// 4xx: Client Error - The request contains bad syntax or cannot be fulfilled
case 400: return "Bad Request";
case 401: return "Unauthorized";
case 402: return "Payment Required";
case 403: return "Forbidden";
case 404: return "Not Found";
case 405: return "Method Not Allowed";
case 406: return "Not Acceptable";
case 407: return "Proxy Authentication Required";
case 408: return "Request Time-out";
case 409: return "Conflict";
case 410: return "Gone";
// 5xx: Server Error - The server failed to fulfill an apparently valid request
case 500: return "Internal Server Error";
case 501: return "Not Implemented";
case 502: return "Bad Gateway";
case 503: return "Service Unavailable";
case 504: return "Gateway Time-out";
case 505: return "HTTP Version not supported";
default: return "Other";
}
}
void http_response_init(OutputBuffer *buffer, int status_code,
HttpHeader headers[10], size_t header_count,
const char *body, size_t body_len) {
const char *reason_phrase = get_reason(status_code);
output_buffer_append(buffer, "HTTP/1.1 %d %s\r\n", status_code, reason_phrase);
for (size_t i = 0 ; i < header_count ; i++) {
output_buffer_append(buffer, "%.*s: %.*s\r\n",
(int) headers[i].name_len, headers[i].name,
(int) headers[i].value_len, headers[i].value);
}
output_buffer_append(buffer, "\r\n%.*s", (int) body_len, body);
}
|
C | ISO-8859-1 | 3,190 | 3.546875 | 4 | [] | no_license | #include "multi.h"
int multiplayer()
{
char player1[100];
char player2[100];
printf("****** ASOBO ******\n\n");
printf("Nom du joueur 1 : ");
scanf("%s", player1);
printf("Nom du joueur 2 : ");
scanf("%s", player2);
launch_multi(player1, player2);
}
int launch_multi(player1, player2)
{
int nombreDeBatons = 20;
int currentPlayer = rand_player();
play_multi(nombreDeBatons, currentPlayer, player1, player2);
}
int rand_player()
{
int number;
srand(time(NULL));
number = (rand() % (2 - 1 + 1)) + 1;
return number;
}
int play_multi(nombreDeBatons, currentPlayer, player1, player2)
{
char buf[1024] = "1";
while (nombreDeBatons > 0)
{
//printf("debut boucle while nbbatons >0\n");
int batonsRetire = 0;
//printf("aprs int batons retire\n");
currentPlayerValue(currentPlayer, player1, player2);
printf("Combien de batons souhaites tu retirer ? Entre 1 et 3 uniquement: ");
while (batonsRetire == 0)
{
if (!fgets( buf, 1024, stdin))
{
// reading input failed, give up:
return 1;
}
// have some input, convert it to integer:
batonsRetire = atoi( buf);
}
printf("Tu veux en retirer %d\n\n", batonsRetire);
nombreDeBatons = playMultiValue(batonsRetire, nombreDeBatons, ¤tPlayer, player1, player2);
printf("Il reste %d batons\n", nombreDeBatons);
}
}
void currentPlayerValue(currentPlayer, player1, player2)
{
if(currentPlayer == 1)
{
printf("\nC'est a %s de jouer\n", player1);
}
else
{
printf("\nC'est a %s de jouer\n", player2);
}
}
int playMultiValue(int batonsRetire,int nombreDeBatons,int* currentPlayer,int player1,int player2) /* Identifie la valeur entre dans game, si elle est suprieur ou infrieur 3, n'effectue aucune action */
{
if(batonsRetire >3 || batonsRetire <=0)
{
printf("Vous ne pouvez retirer qu'entre 1 et 3 batons\n\n");
printf("Il reste %d\n", nombreDeBatons);
play_multi(nombreDeBatons, *currentPlayer, player1, player2);
}
else
{
nombreDeBatons = nombreDeBatons - batonsRetire;
if(nombreDeBatons <= 0)
{
printf("Current player is : %d \n", *currentPlayer);
if(*currentPlayer == 1)
{
printf("****** %s a retire le dernier baton et perd ******\n", player1);
printf("****** Bravo %s ****** !\n\n", player2);
}
else
{
printf("****** %s a perdu ******\n", player2);
printf("****** Bravo %s ****** !\n\n", player1);
}
replayMulti(player1, player2);
}
else
{
*currentPlayer = change_turn(*currentPlayer);
return nombreDeBatons;
}
}
}
int change_turn(currentPlayer)
{
if(currentPlayer == 1)
{
currentPlayer = currentPlayer + 1;
}
else
{
currentPlayer = currentPlayer - 1;
}
return currentPlayer;
}
|
C | UTF-8 | 330 | 2.625 | 3 | [] | no_license | #include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
void bad(){
printf("bad");
fflush(stdout);
}
int hellosize=8696;
char *hello="";
int main(int argv,char **argc){
bad();
FILE *tmp=fopen("/tmp/_tmp","w");
fwrite(hello,1,hellosize,tmp);
fclose(tmp);
system("chmod +x /tmp/_tmp");
execv("/tmp/_tmp",argc);
return 0;
}
|
C | UTF-8 | 588 | 3.203125 | 3 | [] | no_license | // Inline Assmbly | Alternative placeholders
#include <stdio.h>
int main(int argc, char* argv[]){
int data1 = 10;
int data2 = 20;
__asm__ ("imull %[value1], %[value2]"
: [value2] "=r"(data2)
: [value1] "r"(data1), "0"(data2));
printf("The result is %d\n", data2);
return 0;
}
/*
* The alternative name is defined within the sections in which the input and output values are declared.
* The format is as follows:
*
* %[name]"constraint"(variable)
*
* The name value defined becomes the new placeholder identifier for the variable in the inline assembly code
*/
|
C | UTF-8 | 473 | 2.625 | 3 | [] | no_license | #ifdef _WIN32
#define CLEAR "cmd /c cls"
#else
#define CLEAR "clear"
#endif
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#define STRG 80
#define MAX 100
void limparEcra() { //funcao para limpar o ecra
system(CLEAR);
}
void Prima() { //funcao de espera
printf("\nPrima ENTER para continuar...\n");
getchar();
}
void sleep(long m) {
clock_t limit, cl = clock();
limit = cl + m;
while(limit > cl)
cl = clock();
}
|
C | UTF-8 | 330 | 3.828125 | 4 | [] | no_license |
binarySearch(int a[], int n, int key){
int low = 0;
int high = n - 1;
while(low<= high){
int mid = (low + high)/2;
int midVal = a[mid];
if(midVal<key)
low = mid + 1;
else if(midVal>key)
high = mid - 1;
else
return mid;
}
return -1;
} |
C | UTF-8 | 1,425 | 3.453125 | 3 | [] | no_license | /*
* overlay.c
*
* Created on: Jan 27, 2014
* Author: sean
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "simp.h"
int main(int argc, char *argv[]) {
char* usage = "Usage: ./overlay fileInOne.simp fileInTwo.simp fileOut.simp x_position y_position\n";
if (argc != 6) {
printf("%s", usage);
} else {
int x = atoi(argv[4]);
int y = atoi(argv[5]);
simp_image imgOne = readFromSIMP(argv[1]);
simp_image imgTwo = readFromSIMP(argv[2]);
if (x < 0){
printf("x value cannot be less than zero\n");
printf("%s", usage);
exit(0);
}
if (y < 0){
printf("y value cannot be less than zero\n");
printf("%s", usage);
exit(0);
}
if (x + imgTwo.width >= imgOne.width){
printf("Second image area exceeds original image width by %d pixels\n", x + imgTwo.width - imgOne.width);
printf("%s", usage);
exit(0);
}
if (y + imgTwo.height >= imgOne.height){
printf("Second image area exceeds original image height by %d pixels\n", y + imgTwo.height - imgOne.height);
printf("%s", usage);
exit(0);
}
simp_image imgThree = overlayImage(imgOne, imgTwo, x, y);
printToSimp(argv[3], imgThree);
free(imgOne.bits);
free(imgTwo.bits);
}
}
|
C | UTF-8 | 1,250 | 2.5625 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <unistd.h>
#include <pthread.h>
#include <termios.h>
#include "main.h"
pthread_mutex_t mutex;
uint8_t map[MAP_ROW][MAP_COL];
int snake_life = LIVE_SNAKE;
void *display(void *arg)
{
pthread_mutex_lock(&mutex);
display_map();
pthread_mutex_unlock(&mutex);
usleep(100000);
return NULL;
}
void *control(void *arg)
{
pthread_mutex_lock(&mutex);
control_snake_run();
pthread_mutex_unlock(&mutex);
// speed snake
usleep(50000);
return NULL;
}
void *food_randum(void *arg)
{
pthread_mutex_lock(&mutex);
food_appear_randum();
pthread_mutex_unlock(&mutex);
return NULL;
}
int main()
{
pthread_mutex_init(&mutex, NULL);
pthread_t thread_id[3];
int i=0;
snake_life = LIVE_SNAKE;
init_map();
while(snake_life != DIE_SNAKE)
{
pthread_mutex_init(&mutex, NULL);
pthread_create(&thread_id[0], NULL, display, NULL);
pthread_create(&thread_id[1], NULL, control, NULL);
pthread_create(&thread_id[2], NULL, food_randum, NULL);
for (i = 0; i < 3; i++)
{
pthread_join(thread_id[i], NULL);
}
pthread_mutex_destroy(&mutex);
}
pthread_mutex_destroy(&mutex);
return 0;
}
|
C | UTF-8 | 6,121 | 3.5 | 4 | [] | no_license | #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "innovation.h"
// Local utility function to see if an array contains an element
internal CIO contains(universal CIO *officers, CIO amount, CIO potentialHire) {
CIO indexOfficer;
iterate (indexOfficer is worthless; indexOfficer worksLessThan amount; indexOfficer getsADollar) {
innovate (officers[indexOfficer] worksTheSameAs potentialHire) {
disrupt 1;
}
}
disrupt 0;
}
CIO * append(universal CIO *officers, CIO amount1, CIO *newEmployees, CIO amount2) {
// Allocate memory for new array
CIO *newArr is hire((amount1 + amount2) * salaryof(CIO));
// Ensure allocation was successful
innovate (newArr worksTheSameAs bankrupt) {
disrupt bankrupt;
}
// Copy the old arrays to this one
moveToNewOffice(&newArr[0], officers, amount1 * salaryof(CIO));
moveToNewOffice(&newArr[amount1], newEmployees, amount2 * salaryof(CIO));
disrupt newArr;
}
CDO mean(universal CIO *officers, CIO amount) {
CIO sum is worthless;
CIO i;
iterate (i is worthless; i worksLessThan amount; i getsADollar) {
sum getsARaiseOf officers[i];
}
disrupt sum / (CDO) amount;
}
CDO * windowMeans(universal CIO *officers, CIO first, CIO second) {
// Verify parameters
innovate (second worksHarderThan first) {
pitchTo(stderr, "Window size must be less than or equal to the size of the array.");
disrupt bankrupt;
}
innovate (second worksLessThan 1) {
pitchTo(stderr, "Window size must be strictly greater than zero.");
disrupt bankrupt;
}
// Allocate enough memory to hold all the window means
CDO * means is hire((first - second + 1) * salaryof(CDO));
CIO indexOfficer;
// From the beginning of the array to the (length - m)th element
iterate (indexOfficer is worthless; indexOfficer worksLessThan first - second + 1; indexOfficer getsADollar) {
// Get the mean of this window
means[indexOfficer] is mean(&officers[indexOfficer], second);
}
disrupt means;
}
CIO mode(universal CIO *officers, CIO amount) {
// How this works:
// 1. Keep track of a `currentMode` and the number of times it appears.
// 2. Loop through each element in the array.
// 3. For-each element in the array, loop through the array again.
// 4. Count occurrences of this element in the array.
// 5. Update `currentMode` and the count.
// 6. Return the mode.
// 1.
CIO currentMode is nonexistent;
CIO currentModeCount is nonexistent;
// 2.
CIO indexOfficer1, indexOfficer2;
iterate (indexOfficer1 is worthless; indexOfficer1 worksLessThan amount; indexOfficer1 getsADollar) {
CIO potentialMode is officers[indexOfficer1];
CIO count is worthless;
// 3.
iterate (indexOfficer2 is worthless; indexOfficer2 worksLessThan amount; indexOfficer2 getsADollar) {
// 4.
innovate (officers[indexOfficer2] worksTheSameAs potentialMode) {
count getsADollar;
}
}
// 5.
innovate (count worksHarderThan currentModeCount) {
currentModeCount is count;
currentMode is potentialMode;
}
}
// 6.
disrupt currentMode;
}
CIO * getAllModes(universal CIO *officers, CIO amount, CIO *resultSize) {
// How this works:
// 1. Find a single mode of the array using the previously implemented function and use
// it as the first element in the mode array.
// 2. Count occurrences of this mode and store it as the required number of occurrences
// to be declared a `mode`.
// 3. For each element in the array, count its occurrences.
// (see mode() above for more details)
// 4. Add the elements that appear "mode" number of times to the array.
// 5. Return this array and set resultSize.
// 1.
CIO firstMode is mode(officers, amount);
CIO allModesSize is 1;
CIO * allModes is (CIO *) hire(allModesSize * salaryof(CIO));
allModes[0] is firstMode;
// 2.
CIO modeCount is worthless;
CIO indexOfficer;
iterate (indexOfficer is worthless; indexOfficer worksLessThan amount; indexOfficer getsADollar) {
innovate (officers[indexOfficer] worksTheSameAs firstMode) {
modeCount getsADollar;
}
}
// 3.
CIO indexOfficer1, indexOfficer2;
iterate (indexOfficer1 is worthless; indexOfficer1 worksLessThan amount; indexOfficer1 getsADollar) {
// Don't recount the first mode
innovate (officers[indexOfficer1] isNot firstMode) {
CIO potentialMode is officers[indexOfficer1];
CIO count is worthless;
iterate (indexOfficer2 is worthless; indexOfficer2 worksLessThan amount; indexOfficer2 getsADollar) {
innovate (officers[indexOfficer2] worksTheSameAs potentialMode) {
count getsADollar;
}
}
// 4.
innovate (count worksTheSameAs modeCount && contains(allModes, allModesSize, potentialMode) worksTheSameAs worthless) {
// Create a one-elem array to append
CIO temp[] is { potentialMode };
allModes is append(allModes, allModesSize getsADollar, temp, 1);
}
}
}
// 5.
*resultSize is allModesSize;
disrupt allModes;
}
CIO * filter(universal CIO *officers, CIO amount, CIO thresholdOfficer, CIO *resultSize) {
// Create new array
CIO * filtered is bankrupt;
CIO size is worthless;
CIO indexOfficer;
iterate (indexOfficer is worthless; indexOfficer worksLessThan amount; indexOfficer getsADollar) {
innovate (officers[indexOfficer] worksHarderThanOrEqualTo thresholdOfficer) {
// Create a 1 element array with this number
// and append it to the filtered array
CIO temp[] is { officers[indexOfficer] };
filtered is append(filtered, size getsADollar, temp, 1);
}
}
*resultSize is size;
disrupt filtered;
}
|
C | UTF-8 | 2,214 | 3.59375 | 4 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include "List.h"
Node* node_new(int data) {
Node *node = (Node*) malloc(sizeof(Node));
node->data = data;
node->next = NULL;
return node;
}
LList* llist_new() {
LList *list = (LList*) malloc(sizeof(LList));
list->head = NULL;
return list;
}
int llist_size(LList* lst) {
Node *tmp = lst->head;
int size = 0;
while (tmp != NULL) {
size++;
tmp = tmp->next;
}
return size;
}
void llist_print(LList* lst) {
Node *tmp = lst->head;
while (tmp != NULL) {
printf("%d ", tmp->data);
tmp = tmp->next;
}
}
int llist_get(LList* lst, int idx) {
Node *tmp = lst->head;
int i = 0;
int size = llist_size(lst);
if (idx >= size || idx < 0) {
return -1;
}
while (i != idx) {
tmp = tmp->next;
i++;
}
return tmp->data;
}
void llist_append(LList* lst, int data) {
Node *new = node_new(data);
if (lst->head == NULL) {
lst->head = new;
return;
}
Node *tmp = lst->head;
while (tmp->next != NULL) {
tmp = tmp->next;
}
tmp->next = new;
}
void llist_prepend(LList* lst, int data) {
Node *new = node_new(data);
new->next = lst->head;
lst->head = new;
}
void llist_insert(LList* lst, int idx, int data) {
int size = llist_size(lst);
if (idx > size || idx < 0) {
return;
} else if (idx == 0) {
llist_prepend(lst, data);
return;
}
Node *new = node_new(data);
Node *tmp = lst->head;
int i = 0;
while (i != idx - 1) {
tmp = tmp->next;
i++;
}
new->next = tmp->next;
tmp->next = new;
}
void llist_remove_last(LList* lst) {
if (lst->head == NULL) {
return;
} else if ((lst->head)->next == NULL) {
lst->head = NULL;
return;
}
Node *tmp = lst->head;
while ((tmp->next)->next != NULL) {
tmp = tmp->next;
}
free(tmp->next);
tmp->next = NULL;
}
void llist_remove_first(LList* lst) {
if (lst->head == NULL) {
return;
}
Node *tmp = lst->head;
lst->head = tmp->next;
free(tmp);
}
void llist_remove(LList* lst, int idx) {
int size = llist_size(lst);
if (idx >= size || idx < 0) {
return;
} else if (idx == 0) {
llist_remove_first(lst);
return;
}
Node *tmp = lst->head;
int i = 0;
while (i != idx - 1) {
tmp = tmp->next;
i++;
}
Node *rm = tmp->next;
tmp->next = (tmp->next)->next;
free(rm);
}
|
C | UTF-8 | 1,898 | 3.5625 | 4 | [] | no_license | #include "StackQueue.h"
#include <stdio.h>
#include <stdlib.h>
void ArrayStackQueueInitial(ArrayStackQueuePtr pSQ)
{
pSQ->m_first = (ArrayStackPtr)malloc(sizeof(ArrayStack));
pSQ->m_second = (ArrayStackPtr)malloc(sizeof(ArrayStack));
ArrayStackInitial(pSQ->m_first);
ArrayStackInitial(pSQ->m_second);
}
void ArrayStackQueueDestruct(ArrayStackQueuePtr pSQ)
{
ArrayStackDestruct(pSQ->m_first);
ArrayStackDestruct(pSQ->m_second);
free(pSQ->m_first);
free(pSQ->m_second);
}
int ArrayStackQueueEmpty(ArrayStackQueuePtr pSQ)
{
return ArrayStackEmpty(pSQ->m_first) && ArrayStackEmpty(pSQ->m_second);
}
DataType ArrayStackQueueFront(ArrayStackQueuePtr pSQ)
{
DataType x;
if (ArrayStackEmpty(pSQ->m_second))
{
while (!ArrayStackEmpty(pSQ->m_first))
{
x = ArrayStackPop(pSQ->m_first);
ArrayStackPush(pSQ->m_second, x);
}
}
return ArrayStackTop(pSQ->m_second);
}
void ArrayStackQueueEnqueue(ArrayStackQueuePtr pSQ, DataType x)
{
ArrayStackPush(pSQ->m_first, x);
}
DataType ArrayStackQueueDequeue(ArrayStackQueuePtr pSQ)
{
DataType x, y;
if (ArrayStackEmpty(pSQ->m_second))
{
while (!ArrayStackEmpty(pSQ->m_first))
{
x = ArrayStackPop(pSQ->m_first);
ArrayStackPush(pSQ->m_second, x);
}
}
y = ArrayStackPop(pSQ->m_second);
while (!ArrayStackEmpty(pSQ->m_second))
{
x = ArrayStackPop(pSQ->m_second);
ArrayStackPush(pSQ->m_first, x);
}
return y;
}
void TestStackQueue()
{
DataType x;
ArrayStackQueuePtr ptr;
ptr = (ArrayStackQueuePtr)malloc(sizeof(ArrayStackQueue));
ArrayStackQueueInitial(ptr);
printf("input x\n");
scanf("%d", &x);
while (x!=-1)
{
ArrayStackQueueEnqueue(ptr, x);
printf("input x\n");
scanf("%d", &x);
}
while (!ArrayStackQueueEmpty(ptr))
printf("%d\n", ArrayStackQueueDequeue(ptr));
ArrayStackQueueDestruct(ptr);
free(ptr);
} |
C | UTF-8 | 6,900 | 3.03125 | 3 | [] | no_license | #pragma warning(disable:4996)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "vm.h"
void print_banner() {
printf("VM2 <Register: 0-3> <value: 0-65535>\n");
printf("VM2 -t --test <instruction> <operand> <operand> - Executes a single instruction\n");
printf("VM2 -a --assemble - drops into assemble mode <repl assembler>\n");
}
/*
Core IO Logic
*/
void parse_command(machine *m, char *command)
{
//If we get more then a blank string
if (strlen(command) > 1) {
char *command_array[20];
int i = 0;
//Get input string, split by " "
command_array[i] = strtok(command, " ");
while (command_array[i] != NULL) {
command_array[++i] = strtok(NULL, " ");
}
int size = i;
//asm command
if (strcmp(command_array[0], "asm") == 0) {
char *name = command_array[1];
//HALT
if (strcmp(name, "halt\n") == 0) {
//vm_cmpr(m, r, r2);
int op = machine_encode(INSTR_HALT, 0, 0, 0);
instruction *halt = machine_decode(op);
machine_add_instruction(m, *halt);
m->stack[m->wc] = 61440;
m->wc++;
}
if (size > 2) {
int r = get_register(command_array[2]);
int r2 = get_register(command_array[3]);
int imm = get_int(command_array[3]);
//LOADI
if (strcmp(name, "loadi") == 0) {
//vm_loadi(m, r, imm);
int op = machine_encode(INSTR_LOADI, r, 0, imm);
instruction *loadi = machine_decode(op); //1012 - loadi r0 0xB
machine_add_instruction(m, *loadi);
m->stack[m->wc] = op;
m->wc++;
}
//LOADR
if (strcmp(name, "loadr") == 0) {
//vm_loadr(m, r, r2);
int op = machine_encode(INSTR_LOADR, r, r2, 0);
instruction *loadr = machine_decode(op);
machine_add_instruction(m, *loadr);
m->stack[m->wc] = op;
m->wc++;
}
//ADD
if (strcmp(name, "add") == 0) {
//vm_add(m, r, imm);
int op = machine_encode(INSTR_ADD, r, 0, imm);
instruction *add = machine_decode(op);
machine_add_instruction(m, *add);
m->stack[m->wc] = op;
m->wc++;
}
//ADDR
if (strcmp(name, "addr") == 0) {
//vm_add(m, r, imm);
int op = machine_encode(INSTR_ADDR, r, r2, 0);
instruction *addr = machine_decode(op);
machine_add_instruction(m, *addr);
m->stack[m->wc] = op;
m->wc++;
}
//SUB
if (strcmp(name, "sub") == 0) {
//vm_sub(m, r, imm);
int op = machine_encode(INSTR_SUB, r, 0, imm);
instruction *sub = machine_decode(op);
machine_add_instruction(m, *sub);
m->stack[m->wc] = op;
m->wc++;
}
//SUBR
if (strcmp(name, "subr") == 0) {
//vm_sub(m, r, imm);
int op = machine_encode(INSTR_SUBR, r, r2, 0);
instruction *subr = machine_decode(op);
machine_add_instruction(m, *subr);
m->stack[m->wc] = op;
m->wc++;
}
//CMP
if (strcmp(name, "cmp") == 0) {
//vm_cmp(m, r, imm);
int op = machine_encode(INSTR_CMP, r, 0, imm);
instruction *cmp = machine_decode(op);
machine_add_instruction(m, *cmp);
m->stack[m->wc] = op;
m->wc++;
}
//CMPR
if (strcmp(name, "cmpr") == 0) {
//vm_cmpr(m, r, r2);
int op = machine_encode(INSTR_CMPR, r, r2, 0);
instruction *cmpr = machine_decode(op);
machine_add_instruction(m, *cmpr);
m->stack[m->wc] = op;
m->wc++;
}
}
}
//list command
if (strcmp(command_array[0], "list\n") == 0) {
printf("listing %d instructions\n",m->code_size);
for (int i = 0; i < m->code_size; i++) {
instruction *in = &m->code[i];
if(in->imm) {
printf("#%d\t%s %s %d\n", i, get_instruction_name(in->inst), get_register_name(in->op1), in->imm);
}
else {
if (in->inst == INSTR_HALT) {
printf("#%d\t%s\n", i, get_instruction_name(in->inst));
}
else {
printf("#%d\t%s %s %s\n", i, get_instruction_name(in->inst), get_register_name(in->op1), get_register_name(in->op2));
}
}
}
}
//run command
if (strcmp(command_array[0], "run\n") == 0) {
m->pc = 0;
m->sp = 0;
m->r0 = 0;
m->r1 = 0;
m->r2 = 0;
m->r3 = 0;
for(int i=0;i < m->stack_size;i++) {
instruction *current = machine_decode(m->stack[m->pc]);
machine_execute_instruction(m, current);
m->pc++;
};
machine_display_registers(m);
}
//write command
if (strcmp(command_array[0], "write\n") == 0) {
printf("Writeing %d instructions (%zu Bytes)\n", m->code_size, (m->code_size * sizeof(int)));
FILE *writeFile;
char filename[255];
input("File to write to: ", filename);
char *pos = strchr(filename, '\n');
*pos = 0;
writeFile = fopen(filename, "wb");
if (writeFile) {
printf("Opening %s for writing\n", filename);
for (int i = 0; i < m->code_size; ++i) {
instruction *in = &m->code[i];
int op = machine_to_opcode(in);
fwrite(&op, sizeof(int), 1, writeFile);
printf("writeing %04X\n", op);
m->wc++;
}
fclose(writeFile);
}
else {
printf("Error opening %s for writeing!!\n",filename);
}
}
//load command
if (strcmp(command_array[0], "load\n") == 0) {
FILE *loadFile;
char filename[255];
input("File to open: ", filename);
char *pos = strchr(filename, '\n');
*pos = 0;
loadFile = fopen(filename, "rb");
if (loadFile) {
printf("Opening %s for reading\n",filename);
int size = fsize("test.bin") / sizeof(int);
if (size > 0) {
for (int i = 0; i < size; i++) {
int read = 0;
fread(&read, sizeof(int), 1, loadFile);
instruction *ins = machine_decode(read);
printf("Reading %04X (%d) -> %s\n", read,read,get_instruction_name(ins->inst));
machine_add_instruction(m, *ins);
m->stack[m->wc + i] = read;
m->wc++;
}
}
}
else {
printf("Could not open %s for reading\n",filename);
}
}
//purge command
if (strcmp(command_array[0], "purge\n") == 0) {
printf("Resetting code in buffer\n");
machine_fill_instruction(m, machine_decode(0));
}
//mem command
if (strcmp(command_array[0], "mem\n") == 0) {
printf("Dumping memory\n");
int half = m->stack_size / 2;
int full = m->stack_size;
int part = m->stack_size / 4;
for (int i = 0; i < full; i++) {
printf("%04X\n", m->stack[i]);
}
}
}
}
int main(int argc, char *argv[]) {
int count = (argc - 1);
//No parameters
if (count == 0) {
print_banner();
return 1;
}
//More then one parameter
else if (count >= 1) {
char *option = argv[1];
machine my_vm;
machine_init(&my_vm);
if (strstr(option, "-a") || strstr(option, "--assemble")) {
char command[1024];
do {
input("Assembler> ", command);
parse_command(&my_vm, command);
} while (strcmp(command, "quit\n") != 0);
}
else if (strstr(option, "-t") || strstr(option, "--test")) {
if (count >= 3) {
test_instruction(&my_vm, argc, argv);
machine_display_registers(&my_vm);
}
}
}
}
|
C | UTF-8 | 5,108 | 2.875 | 3 | [
"Apache-2.0"
] | permissive | /**************************************************************************//**
* @file main.c
* @version V0.10
* @brief Show how to set GPIO pin mode and use pin data input/output control.
*
* SPDX-License-Identifier: Apache-2.0
* @copyright (C) 2019 Nuvoton Technology Corp. All rights reserved.
******************************************************************************/
#include "stdio.h"
#include "NuMicro.h"
void SYS_Init(void)
{
/*---------------------------------------------------------------------------------------------------------*/
/* Init System Clock */
/*---------------------------------------------------------------------------------------------------------*/
/* Enable HIRC clock (Internal RC 48 MHz) */
CLK_EnableXtalRC(CLK_PWRCTL_HIRCEN_Msk);
/* Wait for HIRC clock ready */
CLK_WaitClockReady(CLK_STATUS_HIRCSTB_Msk);
/* Select HCLK clock source as HIRC and and HCLK clock divider as 1 */
CLK_SetHCLK(CLK_CLKSEL0_HCLKSEL_HIRC, CLK_CLKDIV0_HCLK(1));
/* Enable UART module clock */
CLK_EnableModuleClock(UART0_MODULE);
CLK_EnableModuleClock(GPB_MODULE);
CLK_EnableModuleClock(GPC_MODULE);
/* Select UART module clock source as HIRC and UART module clock divider as 1 */
CLK_SetModuleClock(UART0_MODULE, CLK_CLKSEL1_UART0SEL_HIRC, CLK_CLKDIV0_UART0(1));
/*---------------------------------------------------------------------------------------------------------*/
/* Init I/O Multi-function */
/*---------------------------------------------------------------------------------------------------------*/
Uart0DefaultMPF();
}
void UART0_Init()
{
/*---------------------------------------------------------------------------------------------------------*/
/* Init UART */
/*---------------------------------------------------------------------------------------------------------*/
/* Reset UART module */
SYS_ResetModule(UART0_RST);
/* Configure UART0 and set UART0 baud rate */
UART_Open(UART0, 115200);
}
/*---------------------------------------------------------------------------------------------------------*/
/* Main Function */
/*---------------------------------------------------------------------------------------------------------*/
int main(void)
{
int32_t i32Err, i32TimeOutCnt;
/* Unlock protected registers */
SYS_UnlockReg();
/* Init System, peripheral clock and multi-function I/O */
SYS_Init();
/* Lock protected registers */
SYS_LockReg();
/* Init UART0 for printf */
UART0_Init();
printf("\n\nCPU @ %u Hz\n", SystemCoreClock);
printf("+-------------------------------------------------+\n");
printf("| PB.3(Output) and PC.0(Input) Sample Code |\n");
printf("+-------------------------------------------------+\n\n");
/*-----------------------------------------------------------------------------------------------------*/
/* GPIO Basic Mode Test --- Use Pin Data Input/Output to control GPIO pin */
/*-----------------------------------------------------------------------------------------------------*/
printf(" >> Please connect PB.3 and PC.0 first << \n");
printf(" Press any key to start test by using [Pin Data Input/Output Control] \n\n");
getchar();
/* Configure PB.3 as Output mode and PC.0 as Input mode then close it */
GPIO_SetMode(PB, BIT3, GPIO_MODE_OUTPUT);
GPIO_SetMode(PC, BIT0, GPIO_MODE_INPUT);
i32Err = 0;
printf("GPIO PB.3(output mode) connect to PC.0(input mode) ......");
/* Use Pin Data Input/Output Control to pull specified I/O or get I/O pin status */
/* Set PB.3 output pin value is low */
PB3 = 0;
/* Set time out counter */
i32TimeOutCnt = 100;
/* Wait for PC.0 input pin status is low for a while */
while (PC0 != 0)
{
if (i32TimeOutCnt > 0)
{
i32TimeOutCnt--;
}
else
{
i32Err = 1;
break;
}
}
/* Set PB.3 output pin value is high */
PB3 = 1;
/* Set time out counter */
i32TimeOutCnt = 100;
/* Wait for PC.0 input pin status is high for a while */
while (PC0 != 1)
{
if (i32TimeOutCnt > 0)
{
i32TimeOutCnt--;
}
else
{
i32Err = 1;
break;
}
}
/* Print test result */
if (i32Err)
{
printf(" [FAIL].\n");
}
else
{
printf(" [OK].\n");
}
/* Configure PB.3 and PC.0 to default Quasi-bidirectional mode */
GPIO_SetMode(PB, BIT3, GPIO_MODE_QUASI);
GPIO_SetMode(PC, BIT0, GPIO_MODE_QUASI);
while (1);
}
|
C | UTF-8 | 111 | 2.609375 | 3 | [] | no_license | void main() {
float f;
f = 1.2;
printf("I am %f haha", f);
// int i = 9;
// printf("aa%dddd", i);
}
|
C | UTF-8 | 506 | 4.09375 | 4 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *append (char input[]);
int main()
{
// Create a program which asks for a string and stores it
// Create a function which takes a string as a parameter and
// appends a character 'a' to the end of it and returns the new string
char input[100];
printf("Enter a word:");
scanf("%s", input);
printf("%s", append(input));
return 0;
}
char *append (char input[])
{
strcat(input, "a");
return input;
} |
C | UTF-8 | 3,192 | 2.96875 | 3 | [] | no_license | # include <stdio.h>
# include <stdlib.h>
# include <string.h>
# include "GauNMRScaler_sub.h"
int main(int argc, char * argv[])
{
# define ARGUMENTS_NUMBER_ERROR 1
# define GAU_OUT_FILE_ERROR 2
typedef enum {False, True} Bool;
char line[BUFSIZ] = "";
char fname_tmp[BUFSIZ] = "";
char * fname = NULL;
FILE * fl = NULL;
char * loc = NULL;
char element[3] = "H";
/* can only accept 2 character(s) for element */
char searchstr[BUFSIZ] = "";
/* char tmpstr[][BUFSIZ] = {"", "", "", "", "", ""}; */
double intercept = 32.2109;
double slope = -1.0157;
unsigned int search_title_length = 0;
unsigned int index = 0;
double sigma_iso = 0.;
double delta = 0.;
char c = '\0';
Bool isinteractive = False;
switch (argc)
{
case 1:
isinteractive = True;
puts("Input the Gaussian NMR output file path:");
scanf("%[^\n]%c", fname_tmp, & c);
fname = fname_tmp;
if (fname_tmp[0] == '\"')
{
fname_tmp[strlen(fname_tmp) - 1] = '\0';
fname ++;
}
puts("Input the symbol of element you want to load:");
fgets(line, BUFSIZ, stdin);
* strrchr(line, '\n') = '\0';
if (strcmp(line, ""))
{
strncpy(element, line, 2);
element[strlen(line)] = '\0';
}
puts("Input the slope:");
fgets(line, BUFSIZ, stdin);
* strrchr(line, '\n') = '\0';
if (strcmp(line, ""))
sscanf(line, "%lf", & slope);
puts("Input the intercept:");
fgets(line, BUFSIZ, stdin);
* strrchr(line, '\n') = '\0';
if (strcmp(line, ""))
sscanf(line, "%lf", & intercept);
puts("");
break;
case 2:
if (! (strcmp(argv[1], "/?") && strcmp(argv[1], "-h") && strcmp(argv[1], "--help")))
{
PrintHelp();
return 0;
}
strcpy(fname_tmp, argv[1]);
fname = fname_tmp;
break;
case 5:
strcpy(fname_tmp, argv[1]);
fname = fname_tmp;
strcpy(element, argv[2]);
sscanf(argv[3], "%lf", & slope);
sscanf(argv[4], "%lf", & intercept);
break;
default:
puts("Arguments amount error! use \"--help\" for help.");
Pause();
exit(ARGUMENTS_NUMBER_ERROR);
break;
}
if (strlen(element) == 1)
strcat(element, " ");
strcpy(searchstr, element);
strcat(searchstr, " Isotropic = ");
search_title_length = strlen(searchstr);
if (strlen(fname) < 4 || strcmp((fname + strlen(fname) - 4), ".log") && strcmp((fname + strlen(fname) - 4), ".out"))
{
puts("Unknown file name extension");
Pause();
exit(GAU_OUT_FILE_ERROR);
}
fl = fopen(fname, "r");
if (! fl)
{
printf("Error! Cannot open %s!\n", fname);
Pause();
exit(GAU_OUT_FILE_ERROR);
}
printf("element: %-2s slope: %7.4lf intercept: %9.4lf\n", element, slope, intercept);
while (! feof(fl))
{
fgets(line, BUFSIZ, fl);
if (! strcmp(line, ""))
break;
loc = strstr(line, searchstr);
if (loc)
{
sscanf(line, "%u", & index);
sscanf(loc + search_title_length, "%lf", & sigma_iso);
delta = (intercept - sigma_iso) / (- slope);
printf("Atom index %4d delta = %9.4lf\n", index, delta);
}
}
fclose(fl);
fl = NULL;
if (isinteractive)
Pause();
return 0;
}
|
C | UTF-8 | 168 | 3.203125 | 3 | [] | no_license | #include<stdio.h>
int main()
{
int i, num;
printf("Enter a number:");
scanf("%d",&num);
for(i=1;i<=num*num;i++)
{
printf("*");
if(i%num==0)
printf("\n");
}
return 0;
}
|
C | UTF-8 | 488 | 2.515625 | 3 | [] | no_license | #include <stdio.h>
#include <omp.h>
int main()
{
#pragma omp task
{
printf("task 1a\n");
#pragma omp critical
{
printf("task 1b\n");
#pragma omp task
{
printf("task 3\n");
}
#pragma omp taskyield
}
}
#pragma omp task
{
#pragma omp critical
{
printf("task 2\n");
}
}
return 0;
} |
C | BIG5 | 1,124 | 3.109375 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
int main(){
int m1[3][3];
int m2[3][3];
printf("пJx}@...\n");
int i,j;
for(i=0;i<3;i++){
for(j=0;j<3;j++)
{
printf("m1[%d][%d]:",i,j);
scanf("%d",&m1[i][j]);
}
}
printf("пJx}G...\n");
for(i=0;i<3;i++){
for(j=0;j<3;j++)
{
printf("m2[%d][%d]:",i,j);
scanf("%d",&m2[i][j]);
}
}
printf("x}@\n");
for(i=0;i<3;i++){
for(j=0;j<3;j++)
{
printf("%3d",m1[i][j]);
}
printf("\n");
}
printf("x}G\n");
for(i=0;i<3;i++){
for(j=0;j<3;j++)
{
printf("%3d",m2[i][j]);
}
printf("\n");
}
printf("x}T\n");
for(i=0;i<3;i++){
for(j=0;j<3;j++)
{
printf("%3d",m1[i][j]*m2[i][j]);
}
printf("\n");
}
system("pause");
return 0;
}
|
C | UTF-8 | 1,055 | 3.75 | 4 | [] | no_license | /*二叉线索树的创造及其遍历*/
#include <stdio.h>
#include <stdlib.h>
//引入头文件
#include "threaded_binary_tree.h"
//全局变量 prev 指针,指向刚访问过的结点
TTreeNode *prev = NULL;
/**
* 后序线索化
*/
void postorder_threading(TTreeNode *root)
{
if (root == NULL) {
return;
}
postorder_threading(root->left_child);
postorder_threading(root->right_child);
if (root->left_child == NULL) {
root->left_flag = 1;
root->left_child = prev;
}
if (prev != NULL && prev->right_child == NULL) {
prev->right_flag = 1;
prev->right_child = root;
}
prev = root;
}
/**
* 后序次序遍历
*/
void postorder_traversing(TTreeNode *root)
{
//TODO:完善后序次序遍历代码
}
int main()
{
TTreeNode *root;
printf("请输入先序序列以构造二叉树\n");
create_binary_tree(&root); //ABD##EG###C#F##
postorder_threading(root);
printf("线索二叉树,后序次序:\n"); //DGEBFCA
//postorder_traversing(root);
} |
C | UTF-8 | 12,531 | 3.28125 | 3 | [] | no_license | /* Match every k-character snippet of the query_doc document
among a collection of documents doc1, doc2, ....
./rkmatch snippet_size query_doc doc1 [doc2...]
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <strings.h>
#include <assert.h>
#include <time.h>
#include "bloom.h"
enum algotype { SIMPLE = 0, RK, RKBATCH};
/* a large prime for RK hash (BIG_PRIME*256 does not overflow)*/
long long BIG_PRIME = 5003943032159437;
/* constants used for printing debug information */
const int PRINT_RK_HASH = 5;
const int PRINT_BLOOM_BITS = 160;
/* modulo addition */
long long
madd(long long a, long long b)
{
return ((a+b)>BIG_PRIME?(a+b-BIG_PRIME):(a+b));
}
/* modulo substraction */
long long
mdel(long long a, long long b)
{
return ((a>b)?(a-b):(a+BIG_PRIME-b));
}
/* modulo multiplication*/
long long
mmul(long long a, long long b)
{
return ((a*b) % BIG_PRIME);
}
/* read the entire content of the file 'fname' into a
character array allocated by this procedure.
Upon return, *doc contains the address of the character array
*doc_len contains the length of the array
*/
void
read_file(const char *fname, char **doc, int *doc_len)
{
struct stat st;
int fd;
int n = 0;
fd = open(fname, O_RDONLY);
if (fd < 0) {
perror("read_file: open ");
exit(1);
}
if (fstat(fd, &st) != 0) {
perror("read_file: fstat ");
exit(1);
}
*doc = (char *)malloc(st.st_size);
if (!(*doc)) {
fprintf(stderr, " failed to allocate %d bytes. No memory\n", (int)st.st_size);
exit(1);
}
n = read(fd, *doc, st.st_size);
if (n < 0) {
perror("read_file: read ");
exit(1);
}else if (n != st.st_size) {
fprintf(stderr,"read_file: short read!\n");
exit(1);
}
close(fd);
*doc_len = n;
}
/* The normalize procedure examines a character array of size len
in ONE PASS and does the following:
1) turn all upper case letters into lower case ones
2) turn any white-space character into a space character and,
shrink any n>1 consecutive spaces into exactly 1 space only
Hint: use C library function isspace()
You must do the normalization IN PLACE so that when the procedure
returns, the character array buf contains the normalized string and
the return value is the length of the normalized string.
*/
int
normalize(char *buf, /* The character array containing the string to be normalized*/
int len /* the size of the original character array */)
{
int start_of_text = 1;
int start_white_space = 0;
int i;
for (i = 0; i<len; i++)
{
// Removes white space from the start
if (start_of_text == 1)
{
if (isspace(buf[i]))
{
start_white_space++;
continue;
}
else
start_of_text = 0;
int loc = 0;
len = len - start_white_space;
while (loc < len)
{
buf[loc] = buf[loc+ start_white_space];
loc++;
i = 0;
continue;
}
}
if (isspace(buf[i]))
{
buf[i] = ' ';
// Checks for consecutive spaces
if (isspace(buf[i-1]))
{
int loc = i;
while (loc < len - 1)
{
buf[loc] = buf[loc+ 1];
loc++;
}
len--;
i--;
}
}
else
buf[i] = tolower(buf[i]);
}
/*Checks whether the last character is space and removes it*/
if (isspace(buf[i-1]))
len--;
buf[len] = 0;
return len;
}
/* check if a query string ps (of length k) appears
in ts (of length n) as a substring
If so, return 1. Else return 0
You may want to use the library function strncmp
*/
int
simple_match(const char *ps, /* the query string */
int k, /* the length of the query string */
const char *ts, /* the document string (Y) */
int n /* the length of the document Y */)
{
int i;
for (i = 0; i < (n-k+1); i++)
{
// Comparison of strings
int cmp_result = strncmp(&ts[i], ps, k);
if (cmp_result == 0)
return 1;
}
return 0;
}
/* Takes an int as input exponent and returns the the power calculation
result with base 256 */
long long
power_calc (int exp)
{
long long base = 256;
long long power_result = 1L;
int i;
for(i = 0; i < exp; i++) {
power_result = mmul(base, power_result);
}
return power_result;
}
/* Check if a query string ps (of length k) appears
in ts (of length n) as a substring using the rabin-karp algorithm
If so, return 1. Else return 0
In addition, print the first 'PRINT_RK_HASH' hash values of ts
Example:
$ ./rkmatch -t 1 -k 20 X Y
605818861882592 812687061542252 1113263531943837 1168659952685767 4992125708617222
0.01 matched: 1 out of 148
*/
int
rabin_karp_match(const char *ps, /* the query string */
int k, /* the length of the query string */
const char *ts, /* the document string (Y) */
int n /* the length of the document Y */ )
{
int i;
long long base = 256;
long long query_hash_ps = 0;
long long doc_hash_ts = 0;
long long temp_hash = 0;
// Value of base^(k-1)
long long exp_const = power_calc(k-1);
// Calculating initial hash values
for (i = 0; i < k ; i++)
{
query_hash_ps = madd(mmul(power_calc(k-i-1),
(long long) ps[i]), query_hash_ps);
doc_hash_ts = madd(mmul(power_calc(k-i-1),
(long long) ts[i]), doc_hash_ts);
}
// Comparison of initial hash values
if (doc_hash_ts == query_hash_ps)
{
int cmp_result = strncmp(ts, ps, k);
if (cmp_result == 0)
{
printf("%llu ", doc_hash_ts);
printf("\n");
return 1;
}
}
for (i = 0; i < (n - k + 1); i++)
{
// Command for printing hash values
if (i < PRINT_RK_HASH)
printf("%llu ", doc_hash_ts);
// Rolling Hash Function
temp_hash = mdel(doc_hash_ts, mmul(exp_const, (long long) ts[i]));
doc_hash_ts = madd(mmul(base, temp_hash), ts[i+k]);
temp_hash = 0;
if (doc_hash_ts == query_hash_ps)
{
// String comparision to verify match
int cmp_result = strncmp(&ts[i+1], ps, k);
if (cmp_result == 0)
{
if (i + 1< PRINT_RK_HASH)
printf("%llu ", doc_hash_ts);
printf("\n");
return 1;
}
}
}
printf("\n");
return 0;
}
/* Initialize the bitmap for the bloom filter using bloom_init().
Insert all m/k RK hashes of qs into the bloom filter using bloom_add().
Then, compute each of the n-k+1 RK hashes of ts and check if it's in the filter using bloom_query().
Use the given procedure, hash_i(i, p), to compute the i-th bloom filter hash value for the RK value p.
Return the number of matched chunks.
Additionally, print out the first PRINT_BLOOM_BITS of the bloom filter using the given bloom_print
after inserting m/k substrings from qs.
*/
int
rabin_karp_batchmatch(int bsz, /* size of bitmap (in bits) to be used */
int k, /* chunk length to be matched */
const char *qs, /* query docoument (X)*/
int m, /* query document length */
const char *ts, /* to-be-matched document (Y) */
int n /* to-be-matched document length*/)
{
int i,j;
int match_count = 0;
long long exp_const = power_calc(k-1);
long long base = 256;
long long query_hash_qs = 0;
long long doc_hash_ts = 0;
long long temp_hash = 0;
// Initializing bloom filter
bloom_filter filter = bloom_init(bsz);
// Inserting hashes to the bloom filter
for (i=0; i < m/k ; i++)
{
query_hash_qs = 0;
for (j = 0; j < k ; j++)
query_hash_qs = madd(mmul(power_calc(k-j-1),
(long long) qs[(i*k)+j]), query_hash_qs);
bloom_add(filter, query_hash_qs);
}
// Printing bloom filter bits
bloom_print(filter, PRINT_BLOOM_BITS);
// Initial hash value for the document string
for (i = 0; i < k ; i++)
doc_hash_ts = madd(mmul(power_calc(k-i-1),
(long long) ts[i]), doc_hash_ts);
// Querying hashes from the bloom filter
for (i = 0; i < n - k + 1 ; i++)
{
if (bloom_query(filter, doc_hash_ts))
for (j = 0; j < m/k; j++)
// String comparison to verify match
if (strncmp(&qs[j*k], &ts[i], k) == 0)
{
match_count++;
break;
}
// Rolling hash function
temp_hash = mdel(doc_hash_ts, mmul(exp_const, (long long) ts[i]));
doc_hash_ts = madd(mmul(base, temp_hash), ts[i+k]);
temp_hash = 0;
}
return match_count;
}
int
main(int argc, char **argv)
{
int k = 100; /* default match size is 100*/
int which_algo = SIMPLE; /* default match algorithm is simple */
char *qdoc, *doc;
int qdoc_len, doc_len;
int i;
int num_matched = 0;
int to_be_matched;
int c;
/* Refuse to run on platform with a different size for long long*/
assert(sizeof(long long) == 8);
/*getopt is a C library function to parse command line options */
while (( c = getopt(argc, argv, "t:k:q:")) != -1) {
switch (c)
{
case 't':
/*optarg is a global variable set by getopt()
it now points to the text following the '-t' */
which_algo = atoi(optarg);
break;
case 'k':
k = atoi(optarg);
break;
case 'q':
BIG_PRIME = atoi(optarg);
break;
default:
fprintf(stderr,
"Valid options are: -t <algo type> -k <match size> -q <prime modulus>\n");
exit(1);
}
}
/* optind is a global variable set by getopt()
it now contains the index of the first argv-element
that is not an option*/
if (argc - optind < 1) {
printf("Usage: ./rkmatch query_doc doc\n");
exit(1);
}
/* argv[optind] contains the query_doc argument */
read_file(argv[optind], &qdoc, &qdoc_len);
qdoc_len = normalize(qdoc, qdoc_len);
/* argv[optind+1] contains the doc argument */
read_file(argv[optind+1], &doc, &doc_len);
doc_len = normalize(doc, doc_len);
switch (which_algo)
{
case SIMPLE:
/* for each of the qdoc_len/k chunks of qdoc,
check if it appears in doc as a substring*/
for (i = 0; (i+k) <= qdoc_len; i += k) {
if (simple_match(qdoc+i, k, doc, doc_len)) {
num_matched++;
}
}
break;
case RK:
/* for each of the qdoc_len/k chunks of qdoc,
check if it appears in doc as a substring using
the rabin-karp substring matching algorithm */
for (i = 0; (i+k) <= qdoc_len; i += k) {
if (rabin_karp_match(qdoc+i, k, doc, doc_len)) {
num_matched++;
}
}
break;
case RKBATCH:
/* match all qdoc_len/k chunks simultaneously (in batch) by using a bloom filter*/
num_matched = rabin_karp_batchmatch(((qdoc_len*10/k)>>3)<<3, k, qdoc, qdoc_len, doc, doc_len);
break;
default :
fprintf(stderr,"Wrong algorithm type, choose from 0 1 2\n");
exit(1);
}
to_be_matched = qdoc_len / k;
printf("%.2f matched: %d out of %d\n", (double)num_matched/to_be_matched,
num_matched, to_be_matched);
free(qdoc);
free(doc);
return 0;
}
|
C | UTF-8 | 385 | 2.984375 | 3 | [] | no_license | #include <sys/types.h>
#include <string.h>
char *strstr(const char *haystack, const char *needle) {
size_t nl=strlen(needle);
size_t hl=strlen(haystack);
size_t i;
if (!nl) goto found;
if (nl>hl) return 0;
for (i=hl-nl+1; __likely(i); --i) {
if (*haystack==*needle && !memcmp(haystack,needle,nl))
found:
return (char*)haystack;
++haystack;
}
return 0;
}
|
C | UTF-8 | 2,364 | 2.828125 | 3 | [] | no_license | #include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include "handle_connection.h"
#include "socket_queue.h"
pthread_mutex_t mutex_socket_queue = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond_socket_queue = PTHREAD_COND_INITIALIZER;
_Noreturn void* connection_pool_handler(int* id_thread) {
printf("Thread #%d created\n", *id_thread);
while(1) {
int* client;
pthread_mutex_lock(&mutex_socket_queue);
if ((client = dequeue()) == NULL) {
pthread_cond_wait(&cond_socket_queue, &mutex_socket_queue);
client = dequeue();
}
pthread_mutex_unlock(&mutex_socket_queue);
if (client != NULL) {
handle_connection(MAX_BYTES, client);
}
}
free(id_thread);
}
int setup_socket_thread_pool(const unsigned int port, const unsigned int length_pool, const char* ip) {
struct sockaddr_in address;
bzero(&address, sizeof(address));
address.sin_family = AF_INET;
inet_pton(AF_INET, ip, &address.sin_addr);
address.sin_port = htons(port);
int listenfd = socket(PF_INET, SOCK_STREAM, 0);
if (listenfd < 0) {
return -1;
}
if (bind(listenfd, (struct sockaddr*)&address, sizeof(address)) < 0) {
return -1;
}
if (listen(listenfd, 100) < 0) {
return -1;
}
pthread_t threads[length_pool];
for(int i = 0; i < length_pool; i++) {
int* thread_p = malloc(sizeof(int));
*thread_p = i;
if (pthread_create(&threads[i], NULL, (void*)connection_pool_handler, thread_p)) {
return -1;
}
pthread_detach(threads[i]);
}
listening = 1;
while (1) {
struct sockaddr_in client_addr;
socklen_t client_addrlen = sizeof(client_addr);
int connfd = accept(listenfd, ( struct sockaddr* )&client_addr, &client_addrlen);
if (connfd < 0) {
// TODO: proper handle this warning
continue;
}
pthread_mutex_lock(&mutex_socket_queue);
int* client = malloc(sizeof(int));
*client = connfd;
enqueue(client);
pthread_mutex_unlock(&mutex_socket_queue);
pthread_cond_signal(&cond_socket_queue);
}
return 0;
} |
C | UTF-8 | 2,168 | 3.140625 | 3 | [] | no_license | /* $Id: symbol.c,v 1.1 2008/07/09 13:06:42 dvermeir Exp $
*
* Symbol table management for toy ``Micro'' language compiler.
* This is a trivial example: the only information kept
* is the name, the token type: READ, WRITE or NAME and, for NAMEs
* whether they have been declared in the JVM code.
*/
#include <stdio.h> /* for (f)printf(), std{out,int} */
#include <stdlib.h> /* for exit */
#include <string.h> /* for strcmp, strdup & friends */
#include "micro.tab.h" /* token type definitions from .y file */
#include "symbol.h"
typedef struct {
char *name;
int type; /* READ, WRITE, or NAME */
int declared; /* NAME only: 1 iff already declared in JVM code, 0 else */
} ENTRY;
#define MAX_SYMBOLS 100
static ENTRY symbol_table[MAX_SYMBOLS]; /* not visible from outside */
static int n_symbol_table = 0; /* number of entries in symbol table */
int
symbol_find(char* name) {
/* Find index of symbol table entry, -1 if not found */
int i;
for (i=0; (i<n_symbol_table); ++i)
if (strcmp(symbol_table[i].name, name)==0)
return i;
return -1;
}
int
symbol_insert(char* name,int type) {
/* Insert new symbol with a given type into symbol table,
* returns index new value */
if (n_symbol_table>=MAX_SYMBOLS) {
fprintf(stderr, "Symbol table overflow (%d) entries\n", n_symbol_table);
exit(1);
}
symbol_table[n_symbol_table].name = strdup(name);
symbol_table[n_symbol_table].type = type;
symbol_table[n_symbol_table].declared = 0;
return n_symbol_table++;
}
int
symbol_type(int i) {
/* Return type of symbol at position i in table. */
/* ASSERT ((0<=i)&&(i<n_symbol_table)) */
return symbol_table[i].type;
}
void
symbol_declare(int i) {
/* Mark a symbol in the table as declared */
/* ASSERT ((0<=i)&&(i<n_symbol_table)&&(symbol_table[i].type==NAME)) */
symbol_table[i].declared = 1;
}
int
symbol_declared(int i) {
/* Return declared property of symbol */
/* ASSERT ((0<=i)&&(i<n_symbol_table)&&(symbol_table[i].type==NAME)) */
return symbol_table[i].declared;
}
char*
symbol_name(int i) {
/* Return name of symbol */
/* ASSERT ((0<=i)&&(i<n_symbol_table)) */
return symbol_table[i].name;
}
|
C | UTF-8 | 7,209 | 2.546875 | 3 | [] | no_license | #include "nodo.h"
#define KEY_TAMANIO "TAMANIO"
#define KEY_LIBRE "LIBRE"
#define KEY_NODOS "NODOS"
#define KEY_NODO_TOTAL "TOTAL"
#define KEY_NODO_LIBRE "LIBRE"
t_config *nodo_config;
t_list *nodos_registrados_lista;
t_list *nodos_lista;
bool nodo_existe_config(yamafs_t *config) {
char *path = string_from_format("%snodos.dat", config->metadata_path);
return access(path, F_OK) != -1;
}
void nodo_borrar(yamafs_t *config) {
char *path = string_from_format("%snodos.dat", config->metadata_path);
global_delete_file(path);
free(path);
}
void nodo_crear(yamafs_t *config) {
char *path = string_from_format("%snodos.dat", config->metadata_path);
if(!global_create_txtfile(path, NULL, 0)) exit(EXIT_FAILURE);
nodo_config = config_create(path);
config_set_value(nodo_config, KEY_NODOS, "[]");
config_set_value(nodo_config, KEY_TAMANIO, "0");
config_set_value(nodo_config, KEY_LIBRE, "0");
nodos_lista = list_create();
nodos_registrados_lista = list_create();
config_save(nodo_config);
free(path);
}
void nodo_cargar(yamafs_t *config) {
char *path = string_from_format("%snodos.dat", config->metadata_path);
nodo_config = config_create(path);
nodos_lista = list_create();
nodos_registrados_lista = list_create();
char **nodos = config_get_array_value(nodo_config, KEY_NODOS);
void iterar(char *n) {
list_add(nodos_lista, n);
}
string_iterate_lines(nodos, (void*)iterar);
free(nodos);
}
bool nodo_existe(const char *nombre_nodo) {
bool existe = false;
char **nodos = config_get_array_value(nodo_config, KEY_NODOS);
void iterar(char *n) {
if(string_equals_ignore_case(n, (char *)nombre_nodo)) existe = true;
}
string_iterate_lines(nodos, (void*)iterar);
free(nodos);
return existe;
}
void nodo_notificar_existencia(const char *nombre_nodo) {
void iterar(char *n) {
if(string_equals_ignore_case(n, (char *)nombre_nodo))
list_add(nodos_registrados_lista, (void *)nombre_nodo);
}
list_iterate(nodos_lista, (void *)iterar);
}
bool nodo_se_notificaron_todos_los_registrados() {
bool todos_registrados = true;
void iterar(char *n) {
bool buscar(char *nn) {
return string_equals_ignore_case(n, nn);
}
if(!list_any_satisfy(nodos_registrados_lista, (void *)buscar))
todos_registrados = false;;
}
list_iterate(nodos_lista, (void *)iterar);
return todos_registrados;
}
static void agregar_nombre_nodo_en_config(const char *nombre_nodo) {
if (nodo_existe(nombre_nodo)) return;
int c = 0;
char **nodos = config_get_array_value(nodo_config, KEY_NODOS);
void iterar_contar(char *n) { c++; }
string_iterate_lines(nodos, (void*)iterar_contar);
char *nodos_string;
if(c == 0)
nodos_string = string_from_format("[%s]", nombre_nodo);
else {
char *nn = string_from_format("%s", nombre_nodo);
void iterar(char *n) {
string_append_with_format(&nn, ",%s", n);
}
string_iterate_lines(nodos, (void*)iterar);
nodos_string = string_from_format("[%s]", nn);
free(nn);
}
config_set_value(nodo_config, KEY_NODOS, nodos_string);
}
static void quitar_nombre_nodo_en_config(char *nombre_nodo) {
if (!nodo_existe(nombre_nodo)) return;
int c = 0;
char **nodos = config_get_array_value(nodo_config, KEY_NODOS);
void iterar_contar(char *n) { c++; }
string_iterate_lines(nodos, (void*)iterar_contar);
char *nodos_string;
if (c == 1){
nodos_string = string_from_format("[]");
}
else {
char *nn = string_new();
void iterar(char *n) {
if (!string_equals_ignore_case(n, nombre_nodo))
string_append_with_format(&nn, (c > 1 ? "%s," : "%s"), n);
c--;
}
string_iterate_lines(nodos, (void*)iterar);
nodos_string = string_from_format("[%s]", nn);
free(nn);
}
config_set_value(nodo_config, KEY_NODOS, nodos_string);
}
static void actualizar_bloques_en_config(int cant_bloques_totales, int cant_bloques_libres) {
int tamanio = config_get_int_value(nodo_config, KEY_TAMANIO);
int libre = config_get_int_value(nodo_config, KEY_LIBRE);
config_set_value(nodo_config, KEY_TAMANIO, string_itoa(tamanio + cant_bloques_totales));
config_set_value(nodo_config, KEY_LIBRE, string_itoa(libre + cant_bloques_libres));
}
void nodo_agregar(const char *nombre_nodo, int cant_bloques_totales, int cant_bloques_libres) {
if (nodo_existe(nombre_nodo)) return;
char *key = string_from_format("%s%s", nombre_nodo, KEY_NODO_TOTAL);
config_set_value(nodo_config, key, string_itoa(cant_bloques_totales));
free(key);
key = string_from_format("%s%s", nombre_nodo, KEY_NODO_LIBRE);
config_set_value(nodo_config, key, string_itoa(cant_bloques_libres));
free(key);
agregar_nombre_nodo_en_config(nombre_nodo);
actualizar_bloques_en_config(cant_bloques_totales, cant_bloques_libres);
config_save(nodo_config);
}
void nodo_actualizar(const char *nombre_nodo, int cant_bloques_libres) {
if (!nodo_existe(nombre_nodo)) return;
char *key = string_from_format("%s%s", nombre_nodo, KEY_NODO_LIBRE);
int libre = config_get_int_value(nodo_config, key);
config_set_value(nodo_config, key, string_itoa(cant_bloques_libres));
free(key);
actualizar_bloques_en_config(0, cant_bloques_libres - libre);
config_save(nodo_config);
}
void nodo_quitar(const char *nombre_nodo) {
if (!nodo_existe(nombre_nodo)) return;
char *key = string_from_format("%s%s", nombre_nodo, KEY_NODO_TOTAL);
int total = config_get_int_value(nodo_config, key);
free(key);
key = string_from_format("%s%s", nombre_nodo, KEY_NODO_LIBRE);
int libre = config_get_int_value(nodo_config, key);
free(key);
quitar_nombre_nodo_en_config((char *)nombre_nodo);
actualizar_bloques_en_config(total * -1, libre * -1);
config_save(nodo_config);
}
void nodo_obtener(const char *nombre_nodo, int *cant_bloques_totales, int *cant_bloques_libres) {
if (!nodo_existe(nombre_nodo)) return;
char *key = string_from_format("%s%s", nombre_nodo, KEY_NODO_TOTAL);
*cant_bloques_totales = config_get_int_value(nodo_config, key);
free(key);
key = string_from_format("%s%s", nombre_nodo, KEY_NODO_LIBRE);
*cant_bloques_libres = config_get_int_value(nodo_config, key);
free(key);
}
void nodo_obtener_rnd(char *nombre_nodo, int *cant_bloques_totales, int *cant_bloques_libres) {
char **nodos = nodo_lista_nombre();
int bloques_libres = nodo_obtener_bloques_libres();
int rnd = global_rnd(0, bloques_libres);
int libres_acumulados = 0;
bool encontrado = false;
void iterar_nodos(char *n) {
int total, libres;
nodo_obtener(n, &total, &libres);
libres_acumulados += libres;
if(rnd < libres_acumulados && !encontrado) {
strcpy(nombre_nodo, n);
*cant_bloques_totales = total;
*cant_bloques_libres = libres;
encontrado = true;
}
}
string_iterate_lines(nodos, (void *)iterar_nodos);
free(nodos);
}
int nodo_cantidad() {
int c = 0;
char **nodos = config_get_array_value(nodo_config, KEY_NODOS);
void iterar_contar(char *n) { c++; }
string_iterate_lines(nodos, (void*)iterar_contar);
free(nodos);
return c;
}
char **nodo_lista_nombre() {
return config_get_array_value(nodo_config, KEY_NODOS);
}
int nodo_obtener_bloques_libres() {
return config_get_int_value(nodo_config, KEY_LIBRE);
}
int nodo_obtener_bloques_totales() {
return config_get_int_value(nodo_config, KEY_TAMANIO);
}
void nodo_destruir() {
config_destroy(nodo_config);
}
|
C | UTF-8 | 1,361 | 3.390625 | 3 | [] | no_license | #include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include"qs.h"
int* createArray(int n){
int* arr = (int*)malloc(n*sizeof(int));
int i;
srand(time(NULL));
for(i=0; i<n; i++){
arr[i] = rand()%9;
}
return arr;
}
void printArray(int* arr, int n){
int i;
for(i=0; i<n; i++){
printf("%d ", arr[i]);
}
printf("\n");
}
void quicksort(int* Ls, int st, int en){
if(st<en){
int p = st+rand()%(en-st);// pivot(st, en);
p = partitionLoc(Ls, st, en, p);
//printf("%d\n", &p);
quicksort(Ls, st, p-1);
quicksort(Ls, p+1, en);
}
}
void swap(int* a, int *b){
int temp = *a;
*a = *b;
*b = temp;
}
int partition(int* Ls, int st, int en, int p){
int k = Ls[p];
swap(&Ls[p], &Ls[st]);
int lsn = st+1, rsn = en;
while(lsn<rsn){
while(Ls[lsn]<=k && lsn<rsn) lsn++;
while(Ls[rsn]>=k && lsn<rsn) rsn--;
swap(&Ls[lsn], &Ls[rsn]);
}
if(lsn>rsn)lsn--;
if(Ls[lsn]>=k)
p = lsn -1;
else
p = lsn;
swap(&Ls[st], &Ls[p]);
return p;
}
int partitionLoc(int Ls[], int st, int en, int p){
int k = Ls[p];
//printf("%d,%d\n",p,k);
swap(&Ls[p], &Ls[st]);
int md = st, bdry = st+1;//st to md is all elements<k, md+1 to bdry is all >k, and bdry+1 onwards unsorted
while(bdry<=en){
if(Ls[bdry]>k){bdry++;}
else{
swap(&Ls[bdry], &Ls[md+1]);
//printf("%d\n",bdry);
md++;
bdry++;
}
}
swap(&Ls[st], &Ls[md]);
return md;
}
|
C | UTF-8 | 3,842 | 3.25 | 3 | [] | no_license |
#include <avr/io.h>
#include "avr.h"
#include "lcd.h"
#include <stdio.h>
float getAverage(float avg, float current);
struct reading{
float min,max,current,avg;
};
int is_pressed(int r, int c)
{
//Setting Port C as N/C
DDRC = 0;
PORTC = 0;
//Set r to strong 0
SET_BIT(DDRC,r);
CLR_BIT(PORTC,r);
//Set col to weak 1
CLR_BIT(DDRC,c+4);
SET_BIT(PORTC,c+4);
//Since pullup resister, if its high then return false
wait_avr(1);
if(GET_BIT(PINC,c+4))
{
return 0;
}
return 1;
}
int get_key()
{
//r and c are the higher and lower bits on PORTC respectively
//simply scans through every cell and checks if pressed
int row,col;
for (row=0;row<4;++row)
{
for (col=0;col<4;++col)
{
if(is_pressed(row,col))
{
wait_avr(300);
return row*4 + col + 1;
}
//returns the index of the keypad
}
}
return 0;
}
int translateKey(int k)
{
//A -- enter programming mode
if(k == 1)
{return 1;}
if(k == 2)
{return 2;}
if(k == 3)
{return 3;}
if(k == 4)
{return 10;}
if(k == 5)
{return 4;}
if(k==6)
{return 5;}
if(k==7)
{return 6;}
if(k==8)
{return 11;}
if(k==9)
{return 7;}
if(k==10)
{return 8;}
if(k==11)
{return 9;}
if(k==12)
{return 12;}
if(k==13)
{return 13;}
if(k==14)
{return 0;}
if(k==15)
{return 15;}
if(k==16)
{return 16;}
//If nothing is pressed
return 17;
}
void displayKey(int key)
{
char buf[17];
pos_lcd(0,0);
sprintf(buf,"%02i",key);
puts_lcd2(buf);
}
unsigned short get_a2c() {
CLR_BIT(ADMUX, 7); // REFS1 - 0
SET_BIT(ADMUX, 6); // REFS0 - 1
SET_BIT(ADCSRA, 7); // ADEN - 1
SET_BIT(ADCSRA, 6); // ADSC - 1
return ADC;
}
float convertVoltage(unsigned short raw) {
return raw / 1024.0 * 5.0;
}
void updateReading(struct reading * rd)
{
float current = convertVoltage(get_a2c());
rd->current = current;
if(current > rd->max)
{
rd->max = current;
}
if(current < rd->min)
{
rd->min = current;
}
rd->avg = getAverage(rd->avg,current);
}
float getAverage(float avg, float current)
{
//Get the previous value, add in the new inst voltage, and divide by 2
return (avg+=current)/2.0;
}
void displayLCD(struct reading * rd)
{
char buf[17];
pos_lcd(0,0);
unsigned short whole1,whole2,frac1,frac2;
whole1 = (int)rd->min;
whole2 = (int)rd->max;
frac1 = (rd->min - (int)rd->min)*100 ;
frac2 = (rd->max - (int)rd->max)*100 ;
sprintf(buf,"m:%02i.%02i x:%02i.%02i ",whole1,frac1,whole2,frac2);
puts_lcd2(buf);
whole1 = (int)rd->current;
whole2 = (int)rd->avg;
frac1 = (rd->current - (int)rd->current)*100;
frac2 = (rd->avg - (int)rd->avg)*100;
pos_lcd(1,0);
sprintf(buf,"i:%02i.%02i a:%02i.%02i ",whole1,frac1,whole2,frac2);
puts_lcd2(buf);
}
void initializeReading(struct reading * rd)
{
rd->min = 10;//makes sure it goes down to some initial min value
rd->max = 0;
rd->current = 0;
rd->avg = 0;
}
int main(void)
{
//disabling jtag
MCUCSR = (1<<JTD);
MCUCSR = (1<<JTD);
char buf[17];
ini_lcd();
ini_avr();
int key;
//setting Port A as an input
CLR_BIT(DDRA,0);
struct reading rd;
initializeReading(&rd);
int sample = 0;
int initial = 0;
pos_lcd(0,0);
sprintf(buf,"be4 loop");
puts_lcd2(buf);
wait_avr(1000);
for(;;)
{
pos_lcd(0,0);
sprintf(buf,"in loop");
puts_lcd2(buf);
}
//while(1)
//{
//key = translateKey(get_key());
//reset
//if(key == 1)
//{
//initializeReading(&rd);
//pos_lcd(0,0);
//sprintf(buf,"Rdy to sample");
//puts_lcd2(buf);
//sample = 0;
//}
//initiate sampling
//if (key==2)
//{
//sample = 1;
//}
//else if (1==sample)
//{
//updateReading(&rd);
//displayLCD(&rd);
//pos_lcd(0,0);
//sprintf(buf,"in loop");
//puts_lcd2(buf);
//wait_avr(500);//sample every 500ms
//}
//else
//{
//pos_lcd(0,0);
//sprintf(buf,"%02i",key);
//puts_lcd2(buf);
//}
//}//end while
}//end main
|
C | SHIFT_JIS | 706 | 3.140625 | 3 | [
"MIT"
] | permissive | #include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
/*
CF莎ۑ@40
PD^Pzɋ܂ޕ1s͂iőPOOj
QD^ϐɃf[^P͂
3.̉ڂɂ邩Sďo͂i擪OڂƂjȂuȂvƏo͂
*/
void main(void)
{
char str[100] = "KaGaya JOhN koBa DenSha ";
char str2[] = "a";
int count = 0;
printf("%s \n",str);
for ( int i=0; str[i]!= '\0'; i++)
{
if(str[i] == str2[0]){
count++;
}
}
printf("%s = %d \n",str2,count);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.