language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C | #include "holberton.h"
/**
* *_strchr - locates a character
* @s: character s
* @c: character c
*
* Description: this function locates a character in a string
* Return: it returns a char
*/
char *_strchr(char *s, char c)
{
int i = 0, j;
while (s[i])
{
i++;
}
for (j = 0; j <= i; j++)
{
if (s[j] == c)
{
s = (s + j);
break;
}
else if (j == i)
{
s = 0;
}
}
return (s);
}
|
C | /*!
*
* @file : common.c
*
* project : PROG1970 - System Programming - Assignment #3
*
* @author : Brendan Rushing & Conor MacPherson
*
* @date : 2018-07-12
*
* @brief : Hoochamacallit System - Common code used for all 3 programs in Hoochamacallit System:
* - Functions, Include files, Constants, Definitions
*
*/
//Include files
#include "../inc/common.h"
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
//EO Include files
/*!
*
* @brief : This function creates a random number from min to max
*
* @param[in] - min - <b>double</b> - The minimum return value.
*
* @param[in] - max - <b>double</b> - The maximum return value.
*
* @return - <b>double</b> - The sudo random number.
*
*/
double RAND(double min, double max){
srand( time(NULL) * clock() );
return (double)rand()/(double)RAND_MAX*(max-min) + min;
}//eo double RAND(double min, double max)
/*!
*
* @brief This function prints the time, date, and a string to a log file.
*
* @param[in] - FILENAME - <b>FILE*</b> - The file pointer to print to.
*
* @param[in] - input - <b>char*</b> - The string data to print to the file.
*
* @return - <b>void</b>
*
*/
void printLogFile(FILE *FILENAME, char* input){
char outputBuffer[FILE_TEXT_WIDTH] = { 0 };
time_t T= time(NULL);
struct tm tm = *localtime(&T);
sprintf(outputBuffer, "\n[%04d-%02d-%02d %02d:%02d:%02d]",tm.tm_year+1900,tm.tm_mon+1,tm.tm_mday,tm.tm_hour, tm.tm_min, tm.tm_sec);
strcat(outputBuffer, input);
if (fputs(outputBuffer, FILENAME) == EOF) {
printf("\n END OF FILE ERROR ");
}
}//eo void printLogFile(void)
/*!
*
* @brief : This function prints the time and date to the screen
*
* @param[] - <b>void</b>
*
* @return - <b>void</b>
*
*/
void printTimeAndDateToScreen(void){
time_t T= time(NULL);
struct tm tm = *localtime(&T);
printf("\n[%04d-%02d-%02d ",tm.tm_year+1900,tm.tm_mon+1,tm.tm_mday);
printf("%02d:%02d:%02d] : ",tm.tm_hour, tm.tm_min, tm.tm_sec);
}//eo void printTimeAndDateToScreen(void)
/*!
*
* @brief This function prints the status for the Hoochamacallit machine
*
* @param[in] - input - <b>int</b> - The status of the machine.
*
* @return - <b>void</b>
*
*/
void printStatus (int input){
printf("Hoochamacallit Machine Status: #%d --- ", input);
switch(input){
case EVERYTHING_OKAY:
printf("Everything Is Okay");
break;
case HYDRAULIC_PRESSURE_FAILURE:
printf("Hydraulic Pressure Failure");
break;
case SAFETY_BUTTON_FAILURE:
printf("Safety Button Failure");
break;
case NO_RAW_MATERIAL_IN_PROCESS:
printf("No Raw Material In Process");
break;
case OPERATING_TEMPERATURE_OUT_OF_RANGE:
printf("Operating Temperature Out of Range");
break;
case OPERATOR_ERROR:
printf("Operator Error");
break;
case MACHINE_OFFLINE:
printf("Machine Offline");
break;
default:
printf("Unkown State");
break;
}//eo switch
}//eo void printStatus (int) |
C | #include "imp_exp.h"
#include <stdlib.h>
#include <stdio.h>
img import_1(char* f, int* plig, int* pcol)
{
int i,j; //Indices
pixel** I;
FILE *fichier;
fichier = fopen(f,"r");
// Ouverture du fichier
if (fichier==NULL) printf("Erreur ouverture image\n");
else
{
int lecture;
int color;
char stri[3];
fgets(stri,3,fichier); //lire la première ligne
lecture = fscanf(fichier,"%d %d",plig,pcol);
if (lecture != 2 ) return NULL;
//Allocation mémoire
I = calloc(*plig,sizeof(*I));
if (I==NULL) printf("/!\ Erreur allocation\n");
else
{
for(i=0;i<*plig;i++)
{
I[i] = calloc(*pcol,sizeof(**I));
}
//Lecture des pixels du fichier
for(i=0;i<*plig;i++)
{
for(j=0;j<*pcol;j++)
{
fscanf(fichier, "%d", &color);
I[i][j].couleur=color;
I[i][j].etat=0;
}
}
}
fclose(fichier);
}
return I;
}
void desallocation_1(img I, int lig)
{
int i;
for(i=0;i<lig;i++)
{
free(I[i]);
}
free(I);
}
int export_1(img I, char* f, int ext, int lig , int col)
{
int i,j,ecriture;
FILE* fichier;
fichier = fopen(f,"w");
if ( fichier == NULL ) return 0;
else
{
if (ext==0) fprintf(fichier,"P1\n");
if (ext==1) fprintf(fichier,"P3\n");
fprintf(fichier,"%d %d\n",lig, col);
for(i=0;i<lig;i++)
{
for(j=0;j<col;j++)
{
fprintf(fichier,"%d ",I[i][j].couleur);
}
fprintf(fichier,"\n");
}
}
fclose(fichier);
return 1;
}
img_RGB import_RGB(char* f, int* plig, int* pcol)
{
int i,j;
img_RGB Irgb;
FILE *fichier;
fichier = fopen(f,"r");
if (fichier==NULL) printf("Erreur ouverture image\n");
else
{
int lecture;
int lig = *plig;
int col = *pcol;
int red,green,blue;
char stri[3];
fgets(stri,3,fichier);
// lecture = fscanf(fichier,"%s", stri);
lecture = fscanf(fichier,"%d %d",&lig,&col);
lecture = fscanf(fichier, "%d", &i);
printf("lignes: %d colonnes: %d\n",lig,col);
Irgb = calloc(lig,sizeof(*Irgb));
if (Irgb ==NULL) printf("Erreur allocation\n");
else
{
for(i=0;i<lig;i++)
{
Irgb[i] = calloc(col,sizeof(**Irgb));
}
for(i=0;i<lig;i++)
{
for(j=0;j<col;j++)
{
fscanf(fichier, "%d %d %d", &red, &green, &blue);
Irgb[i][j].R=red;
Irgb[i][j].G=green;
Irgb[i][j].B=blue;
Irgb[i][j].etat=0;
}
}
*plig=lig;
*pcol=col;
fclose(fichier);
}
}
return Irgb;
}
int export_RGB(img_RGB Irgb, char* f, int lig , int col) //Matrice -> .ppm
{
int i,j,ecriture;
FILE* fichier;
fichier = fopen(f,"w");
if ( fichier == NULL ) return 0;
else
{
fprintf(fichier,"P3\n");
fprintf(fichier,"%d %d\n",lig, col);
fprintf(fichier, "%d\n", 255);
for(i=0;i<lig;i++)
{
for(j=0;j<col;j++)
{
fprintf(fichier,"%d %d %d ",Irgb[i][j].R, Irgb[i][j].G, Irgb[i][j].B );
}
fprintf(fichier,"\n");
}
}
return 1;
}
void desallocation_RGB(img_RGB Irgb, int lig)
{
int i;
for(i=0;i<lig;i++)
{
free(Irgb[i]);
}
free(Irgb);
}
|
C | #include<stdio.h>
void main()
{
int char ch;
int n;
clrscr();
void main(){
printf("Print 1 to 5 again and again");
while(1){
for(n=1;n<=5;n++)
printf("\n%d",n);
ch=getch();
if(ch=='Q')
exit(0)
}
getch();
}
|
C | #include<stdio.h>
#define MIN 0
void main6()
{
int num1, num2;
printf(" Է : ");
scanf_s("%d %d", &num1, &num2);
#ifdef ADD
printf("%d + %d = %d\n", num1, num2, num1+num2);
#endif
#ifdef MIN
printf("%d - %d = %d\n", num1, num2, num1 - num2);
#endif
} |
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* room_management.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: adhondt <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/06/22 11:58:26 by adhondt #+# #+# */
/* Updated: 2018/06/27 21:10:00 by avallois ### ########.fr */
/* */
/* ************************************************************************** */
#include "../inc/lem_in.h"
static char *check_room_validity(t_pm *w, char *str)
{
char **room_data;
int i;
int k;
k = 0;
room_data = NULL;
while (str[0] == '#')
{
ft_putstr(str);
ft_putchar('\n');
free(str);
get_next_line(w->fd, &str);
k = is_cmd_tube(str);
if (k == 1 || k == 2 || k == 3)
ft_error(2);
}
room_data = ft_split(str);
i = tablen(room_data);
if (tablen(room_data) < 3 || !ft_onlydigit(room_data[i - 1])
|| !ft_onlydigit(room_data[i - 2]) || is_cmd_tube(str) != 0)
display_room_error(str);
else
free_room_data(room_data);
return (str);
}
void init_room_struct(t_pm *w, t_rooms *new)
{
if (w->first)
{
w->last->next_room = new;
w->last = new;
}
else
{
w->last = new;
w->first = new;
}
}
static void cons_to_room_list(t_pm *w, char **room_data, int i)
{
t_rooms *new;
w->options_info[0] += 1;
if (w->cmd == 1)
{
if (w->entrance)
free(w->entrance);
w->entrance = ft_cattab_str(room_data, i - 2);
}
else if (w->cmd == 2)
{
if (w->exit)
free(w->exit);
w->exit = ft_cattab_str(room_data, i - 2);
}
if (!(new = (t_rooms *)malloc(sizeof(t_rooms))))
ft_error(0);
new->name = ft_cattab_str(room_data, i - 2);
new->weight = 0;
new->next_room = NULL;
new->next_tube = NULL;
init_room_struct(w, new);
}
static void manage_room_lst(t_pm *w, char *str)
{
char **room_data;
int i;
room_data = ft_split(str);
i = tablen(room_data);
if (tablen(room_data) < 3 || !ft_onlydigit(room_data[i - 1])
|| !ft_onlydigit(room_data[i - 2]))
ft_error(2);
cons_to_room_list(w, room_data, i);
i = 0;
while (room_data[i])
free(room_data[i++]);
free(room_data);
free(str);
}
void is_room_ok(t_pm *w, char *str, int *n)
{
w->cmd = is_cmd_tube(str);
if (w->cmd == 1 || w->cmd == 2)
{
ft_putstr(str);
ft_putchar('\n');
free(str);
get_next_line(w->fd, &str);
str = check_room_validity(w, str);
}
else if (w->cmd == 3 && (*n)++)
{
display_start_end_error(w);
return ;
}
else if (w->cmd == -1)
{
ft_putstr(str);
ft_putchar('\n');
free(str);
return ;
}
ft_putstr(str);
ft_putchar('\n');
manage_room_lst(w, str);
return ;
}
|
C | #include <stdio.h>
#include <stdlib.h>
typedef TYPEELT tMatrix[NLINE][NCOL];
void printMatrix(tMatrix a)
{
int line, col;
for (line = 0; line < NLINE; line++)
{
for (col = 0; col < NCOL; col++)
printf("%08f ", a[line][col]);
printf("\n");
}
printf("\n");
}
void cleanMatrix(tMatrix a)
{
int line, col;
for (line = 0; line < NLINE; line++)
for (col = 0; col < NCOL; col++)
a[line][col] = 0;
}
void sumMatrix(tMatrix a, tMatrix b, tMatrix res)
{
int line, col;
for (line = 0; line < NLINE; line++)
for (col = 0; col < NCOL; col++)
res[line][col] = a[line][col] + b[line][col];
}
void mulMatrix(tMatrix a, tMatrix b, tMatrix res)
{
int line, col, k;
for (line = 0; line < NLINE; line++)
for (col = 0; col < NCOL; col++)
{
res[line][col] = 0;
for (k = 0; k < NCOL; k++)
res[line][col] += a[line][k] * b[k][col];
}
}
void diagMatrix(tMatrix a, TYPEELT value)
{
int indice, line;
indice = (NLINE < NCOL)?NLINE:NCOL;
for (line = 0; line < indice; line++)
a[line][line] = value;
}
void firstLineMatrix(tMatrix a, TYPEELT value)
{
int col;
for (col = 0; col < NCOL; col++)
a[0][col] = value;
}
void firstColMatrix(tMatrix a, TYPEELT value)
{
int line;
for (line = 0; line < NCOL; line++)
a[line][0] = value;
}
void randMatrix(tMatrix a)
{
int line, col;
for (line = 0; line < NLINE; line++)
for (col = 0; col < NCOL; col++)
a[line][col] = (TYPEELT) (rand () % 1000);
}
int main(int argc, char * argv[])
{
tMatrix a, b, c;
int i;
cleanMatrix(a); cleanMatrix(b); cleanMatrix(c);
randMatrix(a); randMatrix(b);
for (i = 0; i< 1000; i++)
mulMatrix(a, b, c);
/* printMatrix (a); */
/* printMatrix (c); */
printf("Value :%f\n",c[0][0]);
return 0;
}
|
C | /*
** EPITECH PROJECT, 2020
** PSU_minishell2_2019
** File description:
** utils3
*/
#include <minishell.h>
#include <my_printf.h>
#include <my_tools.h>
bool loop_cpy(char *s, char **t, int **k, char q)
{
int i = *k[0], j = *k[1];
if (j > 0 && (*t)[j - 1] != ' ')
j++, (*t) = my_strncdup2((*t), " ", my_strlen(s) + 3);
(*t)[j++] = s[i++];
for (; s[i] != '\0' && s[i] != q; i++) (*t)[j++] = s[i];
if (s[i] == '\0') {
*k[0] = i - 1, *k[1] = j - 1;
return true;
}
*k[0] = i, *k[1] = j;
return false;
}
bool cpy_brackets(char *s, char **t, int **k, char **cmd)
{
int i = *k[0], j = *k[1];
if (s == NULL || t == NULL) return false;
if (s[i] == '(') {
if (loop_cpy(s, t, k, ')')) return true;
i = *k[0], j = *k[1];
(*t)[j++] = s[i++];
if (s[i] != '\0' && s[i] != ' ' && cmpstrtab(cmd, &s[i]) == false) {
(*t)[j] = '\0';
j++, (*t) = my_strncdup2((*t), " ", my_strlen(s) + 3);
}
*k[0] = i - 1, *k[1] = j - 1;
if (s[i] == '\0') *k[0] = i - 1;
return true;
}
return false;
}
bool cmpsp2(char *s1, char **s2, int i, int ln)
{
if (ln < 0) return false;
int li = my_strlen(s2[ln]);
if (li < 0) return false;
if (i < li) return true;
if (my_strncmp(&s1[i - li], s2[ln], li) != 0) return true;
return false;
}
bool cpy_cmd2(char *s, char *t, char **cmd, int **k)
{
int i = *k[0], j = *k[1];
int l_c = getlenstrtab(cmd, &s[i]);
if (cmpstrtab(cmd, &s[i])) {
*k[2] = get_tab_str_num(cmd, &s[i]);
for (int y = 0; y < l_c; y++) t[j++] = s[i++];
if (s[i] != ' ' && s[i] != '\0') {
t[j] = ' ', t[j + 1] = '\0', i--;
*k[0] = i, *k[1] = j;
return true;
}
}
*k[0] = i, *k[1] = j;
return false;
}
char *cmd_add_spaces2(char *s, char **cmd, bool f)
{
if (s == NULL || cmd == NULL) return NULL;
char *t = malloc(sizeof(char) * (my_strlen(s) + 2));
int j = 0, ln = -1;
for (int i = 0; s[i] != '\0'; i++, t[++j] = '\0') {
if (cpy_quets(s, &t, (int *[]){&i, &j}, cmd)) continue;
if (cpy_quet(s, &t, (int *[]){&i, &j}, cmd)) continue;
if (cpy_brackets(s, &t, (int *[]){&i, &j}, cmd)) continue;
if (cmpstrtab(cmd, &s[i]) && i != 0 &&
(cmpsp2(s, cmd, i, ln) && s[i - 1] != ' ' || ln == -1))
j++, t = my_strncdup2(t, " ", my_strlen(s) + 3);
if (cpy_cmd2(s, t, cmd, (int *[]){&i, &j, &ln})) continue;
t[j] = s[i];
}
if (f) free(s), s = NULL;
return t;
} |
C | #include<stdio.h>
int main (void)
{
int case_no = 0;
int n;
while(scanf("%d", &n) == 1 && n)
{
int h[n], i, avg = 0;
for(i = 0; i < n; i++)
{
scanf("%d", &h[i]);
avg += h[i];
}
avg /= n;
int moves = 0;
for(i = 0; i < n; i++)
{
if(h[i] > avg) moves += (h[i] - avg);
}
printf("Set #%d\nThe minimum number of moves is %d.\n\n", ++case_no, moves);
}
return 0;
}
|
C | #include <stdio.h>
#include <stdint.h>
int main(void) {
for (size_t i = 0; i < SIZE_MAX; ++i)
printf("%zu\n", i);
}
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_printf_utils2.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: cvoltorb <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/08/02 18:06:49 by cvoltorb #+# #+# */
/* Updated: 2020/08/02 19:22:57 by cvoltorb ### ########.fr */
/* */
/* ************************************************************************** */
#include <stdlib.h>
#include "../ft_printf.h"
char *ft_llitoa_base(ssize_t n, int base)
{
char *str;
char *symbols;
int i;
ssize_t m;
size_t num;
if ((base < 2 || base > 16) || (base != 10 && n < 0))
return (NULL);
if (n == 0)
return (ft_printf_strdup("0"));
i = (n < 0) ? 2 : 1;
m = n;
while (m /= base)
i++;
if (!(symbols = ft_printf_strdup("0123456789abcdef")) || \
!(str = malloc(sizeof(char) * (i + 1))))
return (NULL);
(n < 0) ? str[0] = '-' : 0;
num = (n < 0) ? ((size_t)n * -1) : (size_t)n;
str[i--] = '\0';
str[i--] = symbols[num % base];
while (num /= base)
str[i--] = symbols[num % base];
free(symbols);
return (str);
}
char *ft_ullitoa_base(unsigned long long n, int base)
{
char *str;
char *symbols;
int i;
long long m;
unsigned long long num;
if (base < 2 || base > 16)
return (NULL);
if (n == 0)
return (ft_printf_strdup("0"));
i = 1;
m = n;
while (m /= base)
i++;
if (!(symbols = ft_printf_strdup("0123456789abcdef")) || \
!(str = malloc(sizeof(char) * (i + 1))))
return (NULL);
num = n;
str[i--] = '\0';
str[i--] = symbols[num % base];
while (num /= base)
str[i--] = symbols[num % base];
free(symbols);
return (str);
}
char *ft_strupper(char *s)
{
int len;
char *dest;
len = ft_printf_strlen(s);
if (!(dest = malloc((sizeof(char) * len + 1))))
return (NULL);
while (*s)
*dest++ = ft_printf_toupper(*s++);
*dest = '\0';
free(s - len);
return (dest - len);
}
int ft_save_count_printed(va_list params, t_options *opts)
{
int *count_printed;
count_printed = va_arg(params, int*);
*count_printed = opts->count_already_printed;
return (0);
}
int ft_print_e_pow(t_options *opts)
{
int count;
int len;
char *s;
count = 0;
if (opts->spec == 'e')
count += ft_putchar_count('e', 1);
else if (opts->spec == 'E')
count += ft_putchar_count('E', 1);
count += (opts->e_pow < 0) ? \
ft_putchar_count('-', 1) : ft_putchar_count('+', 1);
if (opts->e_pow > -10 && opts->e_pow < 10)
count += ft_putchar_count('0', 1);
if (!(s = ft_llitoa_base(opts->e_pow, 10)))
return (-1);
len = ft_printf_strlen(s);
if (opts->e_pow < 0)
{
s++;
len--;
}
count += ft_putstr_count(s, 1);
(opts->e_pow < 0) ? free(--s) : free(s);
return (count);
}
|
C | #include<stdio.h>
#include<math.h>
void main()
{
int a,b,c,d,e;
float distance;
printf("enter the first coordinate");
scanf("%d%d",&a,&b);
printf("enter the values of constant of cx+dy+e=0");
scanf("%d%d%d",&c,&d,&e);
distance=(c*a+b*d+e)/sqrt(c*c+d*d);
printf("%f",distance);
} |
C | #include "holberton.h"
#include <stdlib.h>
#include <stdio.h>
/**
* *string_nconcat - Ceate array.
* @s1: string 1.
* @s2: string 2.
* @n: Number.
* Return: char.
*/
char *string_nconcat(char *s1, char *s2, unsigned int n)
{
char *concat;
unsigned int ts1, ts2, tconc, tconc2, T2 = 0;
if (s1 == NULL)
{
s1 = "";
}
if (s2 == NULL)
{
s2 = "";
}
ts1 = 0;
while (s1[ts1] != '\0')
{
ts1++;
}
ts2 = 0;
while (s2[ts2] != '\0')
{
if (ts2 < n)
T2++;
ts2++;
}
tconc = ts1 + T2 + 1;
concat = malloc(sizeof(char) * tconc);
if (concat == NULL)
{
return (NULL);
}
for (tconc2 = 0; tconc2 < ts1; tconc2++)
{
concat[tconc2] = s1[tconc2];
}
for (tconc2 = 0; tconc2 < T2; tconc2++)
{
concat[tconc2 + ts1] = s2[tconc2];
}
concat[ts1 + T2] = '\0';
return (concat);
}
|
C | #include <stdlib.h>
#include <stdio.h>
#include <time.h>
//#define VERB
int main(int argc, char **argv) {
int n = (int) atoi(argv[1]), k = (int) atoi(argv[2]), r, nr;
char cmd[50];
sprintf(cmd, "mkdir data");
system("rm -rf data");
system(cmd); // Run command in cmd from the same process
srand(time(NULL));
for(int i=0; i<n; ++i) {
sprintf(cmd, "touch data/f%d.txt", i);
system(cmd); // Run command in cmd from the same process
nr = rand()%100; // #ofRandomNumber
#ifdef VERB
printf("#randNum %d in file: f%d\n", nr, i); //debug purpose
#endif
// nr Random number written in the file
for(int j=0; j<nr; ++j) {
r = rand()%k;
sprintf(cmd, "echo '%d' >> data/f%d.txt", r, i);
system(cmd); // Run command in cmd from the same process
#ifdef VERB
printf("rand %d in file: f%d\n", r, i); //debug purpose
#endif
}
}
}
|
C | #include <stdio.h>
int max(int x,int y){
return x>y? x:y;
}
int main() {
int n,i,j;
scanf("%d", &n);
int arr[n];
for(i=0; i<n; i++){
scanf("%d", &arr[i]);
}
int all_max=arr[0], curr_max=arr[0]; //initial
int templ,tempr,a_i,l=0,r=0; //initial
templ=0,tempr=0;
for(i=1;i<n;i++){
// curr_max = max(arr[i], curr_max+arr[i]);
if(arr[i]>curr_max+arr[i]){
templ=i;
tempr=i;
curr_max=arr[i];
}else{
tempr++;
curr_max=curr_max+arr[i];
}
// all_max = max(all_max, curr_max);
if(curr_max>all_max){
l=templ;
r=tempr;
all_max=curr_max;
}
}
printf("%d %d %d", all_max,l,r);
} |
C |
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include <string.h>
#include <errno.h>
#define N_TIMES 5
#define MAX 128
#define TAM_BUF 10
char* get_from_circular_buf();
void set_in_circular_buf(char*);
sem_t s_prod, s_bufleft, s_mutex; // semaforos
int posi=-1,posl=-1;
char* buf[TAM_BUF];
int sai=0;
void *produz(void *n_times)
{
while (sai==0){
int* valor_s_bufleft;
sem_getvalue(&s_bufleft,(int*)&valor_s_bufleft);
if((int*)valor_s_bufleft != 0){
//Espera at resurso estar disponivel
sem_wait(&s_mutex);
//Diminiu espaco no buffer
sem_trywait(&s_bufleft);
//aumentar numero de produtos
sem_post(&s_prod);
char* lido;
printf("Entre com o texto:");
scanf("%s",(char*)&lido);
strcat((char*)&lido,"\0");
if (strcmp((char*)&lido,"fim")!=0){
sleep(random()%5);
set_in_circular_buf((char*)&lido);
}
else {
sai=1;
}
//libera recurso
sem_post(&s_mutex);
}
//Buffer cheio
else {
printf("Buffer Cheio, esperando...\n");
sleep(random()%15);
}
}
pthread_exit(NULL);
}
void *consome(void *n_times)
{
while (sai==0){
int* valor_s_prod;
sem_getvalue(&s_prod,(int*)&valor_s_prod);
if ((int*)valor_s_prod > 0){
//Espera at o buffer no ser utilizado
sem_wait(&s_mutex);
//Consome um produto
sem_trywait(&s_prod);
//Disponibiliza um espao no buffer
sem_post(&s_bufleft);
//Consumo propriamente dito
char* lido;
lido=get_from_circular_buf();
printf("Consumindo o texto: %s\n",lido);
//Libera Recurso
sem_post(&s_mutex);
sleep(random()%4);
}
//Buffer vazio
else{
printf("Buffer Vazio, esperando...\n");
sleep(random()%15);
}
}
pthread_exit(NULL);
}
int main()
{
pthread_t th_prod, th_cons;
char err_msg[MAX];
// char *strerror_r(int errnum, char *buf, size_t buflen);
//Cria os trs semaforos
if (sem_init(&s_bufleft, 0, TAM_BUF) < 0) {
strerror_r(errno,err_msg,MAX);
printf("Erro em sem_init: %s\n",err_msg);
exit(1);
}
if (sem_init(&s_prod, 0, 0) < 0) {
strerror_r(errno,err_msg,MAX);
printf("Erro em sem_init: %s\n",err_msg);
exit(1);
}
if (sem_init(&s_mutex,0,1) < 0 ){
strerror_r(errno,err_msg,MAX);
printf("Erro em sem_init: %s\n",err_msg);
exit(1);
}
//Cria os threads
if (pthread_create(&th_prod, NULL, produz, (void *)N_TIMES) != 0) {
strerror_r(errno,err_msg,MAX);
printf("Erro em pthread_create: %s\n",err_msg);
exit(1);
}
if (pthread_create(&th_cons, NULL, consome, (void *)N_TIMES) != 0) {
strerror_r(errno,err_msg,MAX);
printf("Erro em pthread_create: %s\n",err_msg);
exit(1);
}
//Inicializa o thread
pthread_join(th_prod, NULL);
pthread_join(th_prod, NULL);
//Destroi os semaforos
sem_destroy(&s_prod);
sem_destroy(&s_mutex);
sem_destroy(&s_bufleft);
return(0);
}
//Simula um _get_ numa lista circular
char* get_from_circular_buf(){
posl++;
posl = posl%TAM_BUF;
return (char*)&buf[posl];
}
//Simula um _set_ numa lista circular
void set_in_circular_buf(char* conteudo){
posi++;
posi=posi%TAM_BUF;
buf[posi]="";
strcpy((char*)&buf[posi],conteudo);
}
|
C | #define FLASH_KEY1 ((uint32_t)0x45670123)
#define FLASH_KEY2 ((uint32_t)0xCDEF89AB)
uint8_t Hi_Flash_IsReady(void) {
return !(FLASH->SR & FLASH_SR_BSY);
}
void Hi_Flash_EraseAllPages(void) {
FLASH->CR |= FLASH_CR_MER;
FLASH->CR |= FLASH_CR_STRT;
while(!Hi_Flash_IsReady()) {}
FLASH->CR &= FLASH_CR_MER;
}
void Hi_Flash_ErasePage(uint32_t address) {
FLASH->CR|= FLASH_CR_PER;
FLASH->AR = address;
FLASH->CR|= FLASH_CR_STRT;
while(!Hi_Flash_IsReady()) {}
FLASH->CR&= ~FLASH_CR_PER;
}
void Hi_Flash_Unlock(void) {
FLASH->KEYR = FLASH_KEY1;
FLASH->KEYR = FLASH_KEY2;
}
void Hi_Flash_Lock() {
FLASH->CR |= FLASH_CR_LOCK;
}
#define FlashRdy() while(!Hi_Flash_IsReady()) {}
uint32_t Hi_Flash_Read32(uint32_t address) {
return (*(__IO uint32_t*) address);
}
uint16_t Hi_Flash_Read16(uint32_t address) {
return (*(__IO uint16_t*) address);
}
uint8_t Hi_Flash_Read1(uint32_t address) {
return (uint8_t) (Hi_Flash_Read16(address) & 0xFF);
}
uint8_t Hi_Flash_Read2(uint32_t address) {
return (uint8_t) ((Hi_Flash_Read16(address) >> 8) & 0xFF);
}
uint32_t Hi_Flash_GetPage(uint8_t pageNumber) {
return FLASH_BASE + 2048 * pageNumber;
}
uint32_t Hi_Flash_GetOPage(uint8_t pageNumber, uint16_t offset) {
return FLASH_BASE + 2048 * pageNumber + offset;
}
void Hi_Flash_StartRecord() {
FLASH->CR |= FLASH_CR_PG;
FlashRdy();
}
void Hi_Flash_EndRecord() {
FLASH->CR &= ~(FLASH_CR_PG);
}
void Hi_Flash_Write(uint32_t address, uint8_t b1, uint8_t b2) {
if(address % 2 == 0) {
*(__IO uint16_t*) address = ((b2 & 0xFF) << 8) | (b1 & 0xFF);
} else {
Hi_Flash_Write(address-1, 0xFF, b1);
Hi_Flash_Write(address+1, b2, 0xFF);
}
while(FLASH->SR & FLASH_SR_BSY) {}
}
void Hi_Flash_Write16(uint32_t address, uint16_t data) {
*(__IO uint16_t*) address = data;
while(FLASH->SR & FLASH_SR_BSY) {}
}
|
C | /*
* To run server, first compile the program then run this command in the terminal:
* ./server [PORT]
*
*/
#include <stdio.h> // Input & output
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <pthread.h>
#define CHARNUM 159
#define MAX_CLIENT 5
// Error function that takes message as parameter
char buffer1[CHARNUM];
int sockfd, portNum, n,newsockfd,temp;
int sockhd[MAX_CLIENT];
void error(const char *msg){
perror(msg);
exit(1);
}
void* Write(int* arg){
while (1){
int* temp=(int*) arg;
int newTemp=*temp;
temp = recv(newTemp, buffer1, sizeof(buffer1), 0);
n = send(newTemp, buffer1, strlen(buffer1), 0);
if (n < 0 && temp < 0){
error("Error writing");
}
int i = strncmp(":exit", buffer1, 5);//replace with select statment
if (i == 0){
break;
}
}
pthread_exit(0);
}
int main(int argc, char *argv[])
{
// If port number is not provided, print error and exit program
if (argc < 2)
{
// Print no port number error
fprintf(stderr, "Port number not provided. Program terminated.\n");
exit(1);
}
struct sockaddr_in server_addr, client_addr;
socklen_t clientLen;
// Create socket
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
{
// Print socket connection error
error("Error opening socket.");
}
memset((char *) &server_addr, 0, sizeof(server_addr));
portNum = atoi(argv[1]);
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = INADDR_ANY;
server_addr.sin_port = htons(portNum);
if (bind(sockfd, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0)
{
// Print binding error
error("Binding failed.");
}
pthread_t tid[MAX_CLIENT];
pthread_attr_t attr;
pthread_attr_init(&attr);
int i=0;
for(i=0;i<MAX_CLIENT;i++){
// Listen for connection, allow maximum of 5 clients
listen(sockfd, MAX_CLIENT);
clientLen = sizeof(client_addr);
// Lets users see that the server is on and listening
puts("Waiting for incoming connections...");
long long V=(long long)i;
newsockfd = accept(sockfd, (struct sockaddr *) &client_addr, &clientLen);
sockhd[i]=newsockfd;
if (newsockfd < 0)
{
// Print accepting error
error("Error accepting.");
}
pthread_create(&tid[i], &attr,Write,&sockhd[i]);
}
int j=0;
for(j=0;j<MAX_CLIENT;j++){
pthread_join(tid[j],NULL);
}
close(newsockfd);
close(sockfd);
return 0;
}
|
C | #include <stdlib.h>
#include "wayland.h"
int wl_hash_insert(struct wl_hash *hash, struct wl_object *object)
{
struct wl_object **objects;
uint32_t alloc;
if (hash->count == hash->alloc) {
if (hash->alloc == 0)
alloc = 16;
else
alloc = hash->alloc * 2;
objects = realloc(hash->objects, alloc * sizeof *objects);
if (objects == NULL)
return -1;
hash->objects = objects;
hash->alloc = alloc;
}
hash->objects[hash->count] = object;
hash->count++;
return 0;
}
struct wl_object *
wl_hash_lookup(struct wl_hash *hash, uint32_t id)
{
int i;
for (i = 0; i < hash->count; i++) {
if (hash->objects[i]->id == id)
return hash->objects[i];
}
return NULL;
}
void
wl_hash_delete(struct wl_hash *hash, struct wl_object *object)
{
/* writeme */
}
|
C | #include<stdio.h>
#include<math.h>
int main()
{
int m,n;
scanf("%d %d\n",&m,&n);
int i,j,a[100],b[100],count=0;
for(i=0;i<m;i++)
{
scanf("%d",&a[i]);
}
for(j=0;j<n;j++)
{
scanf("%d",&b[j]);
}
for(j=0;j<n;j++)
{
for(i=0;i<m;i++)
{
if(b[j]==a[i])
{
count=count+1;
}
}
}
if(count==n)
{
printf("YES\n");
}
else
{
printf("NO\n");
}
return 0;
}
|
C | /*
============================================================================
Name : mmn21.c
Author : Amir Dror
Version :
Copyright : Amir Dror
Description : find path in adjacency tree
============================================================================
*/
#include <stdio.h>
#define Node 4
typedef int adj_mat[Node][Node];
enum boolean {
false, true
};
/* return parent number, or -1 if no parent or wrong input (not a tree)*/
int findParent(adj_mat A, int son, int count) {
int i;
if (count == 0)
return -1;
for (i = 0; i < Node; i++) {
if (A[i][son] == true)
return i;
}
return -1;
}
/*check for path from parent to son */
int path(adj_mat A, int parent, int son, int count) {
int temp = 0;
if (parent == son)
return true;
else {
temp = findParent(A, son, count);
if (temp == -1)
return false;
}
return path(A, parent, temp, count - 1); /* recursive call*/
}
int main() {
adj_mat adjtree;
int i, j;
int parent = 0, son = 0, again = 0, count = Node;
printf("Please enter values for adjacency tree,\n"
"all numbers except zero will be count as 1\n");
for (i = 0; i < Node; i++) {
for (j = 0; j < Node; j++) {
printf("value %d,%d -> is %d son of %d\n", i + 1, j + 1, j + 1,
i + 1);
scanf("%d", &adjtree[i][j]);
if (adjtree[i][j] != false)
adjtree[i][j] = true; /*all numbers except zero will be count as 1*/
}
}
do {
printf("enter parent node -\n");
scanf("%d", &parent);
printf("enter son node -\n");
scanf("%d", &son);
if (path(adjtree, parent - 1, son - 1, count)) {
printf("is %d parent of %d - true\n\n", parent, son);
} else
printf("is %d parent of %d - false\n\n", parent, son);
printf("enter 1 for another check\n");
scanf("%d", &again);
} while (again == 1);
return 0;
}
|
C | #include <stdlib.h>
#include <stdio.h>
#include <time.h>
int main(){
srand(time(NULL));
int szam;
float kosar = 0;
FILE *input;
input = fopen("100szam.txt","r");
while(!feof(input))
{
fscanf(input,"%d\n",&szam);
kosar += szam;
}
printf("Kosar tartalma: %f\nAtlag: %f\n",kosar, kosar/100);
fclose(input);
return 0;
}
/*
linuxra
gcc nev.c -o nev
./nev
*/
|
C | #include<stdio.h>
#include<signal.h>
void handle_sigint(int sig)
{
printf("Caught signal %d\n", sig);
}
int main()
{
signal(SIGINT, handle_sigint);
while (1){
printf("Hello......\n");
sleep(1);
}
return 0;
}
/*
Hello......
Hello......
Hello......
Hello......
Hello......
Hello......
^CCaught signal 2
Hello......
Hello......
^CCaught signal 2
Hello......
Hello......
^CCaught signal 2
Hello......
Hello......
Hello......
Hello......
^\./script_sig.sh: line 5: 28023 Quit (core dumped) ./01
Displaying Hello Infinitely.
Ctrl+C : causes "Caught Signal 2" as it has been handled.
Finally Terminated by Ctrl+\
*/
|
C | #include <stdio.h>
#define INDENT_SPACING 3
static unsigned int indent=0;
void indentPlus ()
{
indent++;
}
void indentMinus ()
{
if (indent > 0)
indent--;
}
void makeIndent (FILE *fp)
{
fprintf (fp, "%*s", indent*INDENT_SPACING, "");
}
void newLine (FILE *fp)
{
fputc ('\n', fp);
}
void openBlock (FILE *fp)
{
makeIndent (fp);
fprintf (fp, "{");
newLine (fp);
indentPlus ();
}
void closeBlock (FILE *fp)
{
indentMinus ();
makeIndent (fp);
fprintf (fp, "}");
newLine (fp);
}
void main ()
{
openBlock (stdout);
makeIndent (stdout);
fprintf (stdout, "level 1");
newLine (stdout);
makeIndent (stdout);
fprintf (stdout, "level 1");
newLine (stdout);
openBlock (stdout);
makeIndent (stdout);
fprintf (stdout, "level 2");
newLine (stdout);
openBlock (stdout);
makeIndent (stdout);
fprintf (stdout, "level 3");
newLine (stdout);
makeIndent (stdout);
fprintf (stdout, "level 3");
newLine (stdout);
openBlock (stdout);
makeIndent (stdout);
fprintf (stdout, "level 4");
newLine (stdout);
closeBlock (stdout);
makeIndent (stdout);
fprintf (stdout, "level 3");
newLine (stdout);
openBlock (stdout);
makeIndent (stdout);
fprintf (stdout, "level 4");
newLine (stdout);
makeIndent (stdout);
fprintf (stdout, "level 4");
newLine (stdout);
closeBlock (stdout);
closeBlock (stdout);
makeIndent (stdout);
fprintf (stdout, "level 2");
newLine (stdout);
openBlock (stdout);
makeIndent (stdout);
fprintf (stdout, "level 3");
newLine (stdout);
closeBlock (stdout);
closeBlock (stdout);
makeIndent (stdout);
fprintf (stdout, "level 1");
newLine (stdout);
closeBlock (stdout);
}
|
C | #include "i2cEeprom.h"
#include "iic.h"
list_t eepromFrames;
void eeprom_init(void) {
list_init(&eepromFrames); // Prepare the list
}
void eeprom_update(void) {
// Check there are frames to send
if (list_hasData(&eepromFrames) == False)
return;
// Check the I2C module is free
// TODO: Support multiple I2C modules
if (I2C_2.state != IDLE)
return;
I2CFrame_t * frame;
list_pop(&eepromFrames, &frame); // Retrieve a frame from the list
i2c_prepareFrame(EEPROM_MODULE, frame); // Send it to the I2C module
}
Bool eeprom_putData(uint8_t * src, uint16_t addr, uint16_t len, void (*callback)(void), void (*error)(void)) {
// Chop the data into frames, and add to the list
}
Bool eeprom_getData(uint8_t * dest, uint16_t addr, uint16_t len, void (*callback)(void), void (*error)(void)) {
uint8_t * readData = calloc(2, sizeof(uint8_t));
readData[0] = (uint8_t)((addr >> 8) & 0xFF); // Split the address word into bytes
readData[1] = (uint8_t)(addr & 0xFF);
I2CFrame_t * frame = malloc(sizeof(I2CFrame_t)); // Create an empty frame
// Fill the frame details
frame->address = EEPROM_ADDR;
frame->bytesToRead = len;
frame->rx_buf = dest;
frame->tx_buf = readData;
frame->callback = callback;
frame->error = error;
list_add(&eepromFrames, frame); // Add the frame to the list
}
|
C | #include "tokenizer.h"
void PrintCommands (CommandList* list)
{
if(list->tail == NULL)
{
return;
}
commandnode* ptr = list->tail->next; //delete a linked list
commandnode* tmp;
tmp = ptr;
int count = list->count;
if(ptr == NULL)
{
puts(list->tail->command->token);
return;
}
while (count!=1)
{
ptr = ptr->next;
puts(tmp->command->token);
tmp = ptr;
count--;
}
puts(ptr->command->token);
return;
}
void addcommand (TokenizerT* command,CommandList* list)
{
commandnode* tmp = NULL;
commandnode* new = NULL;
new = (commandnode*)malloc(1*sizeof(commandnode));
new -> command = command;
new -> next = NULL;
if (list->tail == NULL)
{
list->tail = new; //insert into linked list
list-> tail->next = NULL;
list->count++;
return;
}
else if (list->tail->next == NULL)
{
tmp =list->tail;
list-> tail = new;
list-> tail->next = tmp;
tmp->next =list-> tail;
list->count++;
return;
}
else
{
tmp = list ->tail;
list-> tail = new;
list-> tail->next = tmp ->next;
tmp->next = list->tail;
list->count++;
return;
}
}
void deleteCommandList (CommandList* list)
{
if(list->tail == NULL)
{
return;
}
commandnode* ptr = list->tail->next; //delete a linked list
commandnode* tmp;
tmp = ptr;
int count = list->count;
if(ptr == NULL)
{
TKDestroy(list->tail->command);
free(list->tail);
list->tail = NULL;
list->count = 0;
return;
}
while (count!=1)
{
ptr = ptr->next;
TKDestroy(tmp->command);
free(tmp);
tmp = ptr;
count--;
}
TKDestroy(ptr->command);
free(ptr);
ptr = NULL;
tmp = NULL;
list->tail = NULL;
list->count = 0;
return;
}
void addEnd (char val,CLL* list)
{
linknode* tmp = NULL;
linknode* new = NULL;
new = (linknode*)malloc(1*sizeof(linknode));
new -> data = val;
new -> next = NULL;
if (list->tail == NULL)
{
list->tail = new; //insert into linked list
list-> tail->next = NULL;
list->count++;
return;
}
else if (list->tail->next == NULL)
{
tmp =list->tail;
list-> tail = new;
list-> tail->next = tmp;
tmp->next =list-> tail;
list->count++;
return;
}
else
{
tmp = list ->tail;
list-> tail = new;
list-> tail->next = tmp ->next;
tmp->next = list->tail;
list->count++;
return;
}
}
char* CLLtoStr(CLL* list)
{
linknode* point;
int count = list->count;
char* str = NULL;
str = (char *) calloc(count,sizeof(char));
int ptr;
if(list->tail == NULL)
{
free(str);
str = NULL;
return NULL;
}
else if(list->tail->next == NULL)
{
point = list->tail;
}
else //turn linked list into a string
{
point = list->tail->next;
}
for(ptr = 0; ptr<count;ptr++)
{
str[ptr] = point->data;
point = point->next;
}
return str;
}
void deleteCLL (CLL* list)
{
if(list->tail == NULL)
{
return;
}
linknode* ptr = list->tail->next; //delete a linked list
linknode* tmp;
tmp = ptr;
int count = list->count;
if(ptr == NULL)
{
free(list->tail);
list->tail = NULL;
list->count = 0;
return;
}
while (count!=1)
{
ptr = ptr->next;
free(tmp);
tmp = ptr;
count--;
}
free(ptr);
ptr = NULL;
tmp = NULL;
list->tail = NULL;
list->count = 0;
return;
}
TokenizerT *TKCreate( char * ts ) {
CLL* list = (CLL*) malloc(sizeof(CLL));
list->tail = NULL;
list->count = 0;
TokenizerT* new = (TokenizerT*)malloc(sizeof(TokenizerT));
char * ptr= ts;
char* temp;
int i;
if(ptr!=NULL&&*ptr!=' '){
while(*ptr!=' '&&*ptr!='\0'){
addEnd(*ptr,list);
ptr++;
}
addEnd('\0',list);
temp = CLLtoStr(list);
for(i = 0; temp[i]; i++){
temp[i] = tolower(temp[i]);
}
new->token = temp;
new->thistoken = word;
deleteCLL(list);
return new;
}
else{
free(new);
return NULL;
}
}
void TKDestroy( TokenizerT * tk ) {
free(tk->token);
free(tk);
}
char *TKGetNextToken(char*here ) {
char* ptr = here;
while(*ptr != '\0'&&*ptr==' '){ //Find next token
ptr++;
}
if(*ptr!='\0'){ //if found, return pointer to beginning
return ptr;
}
else{ //else all tokens found, return null
return NULL;
}
}
CommandList* TokenizeString(char* string){
char* ptr;
TokenizerT* new;
CommandList* commando = (CommandList*) calloc(1,sizeof(CommandList));
commando->count = 0;
ptr = string;
while(ptr!= NULL &&*ptr!='\0'){
ptr = TKGetNextToken(ptr); //find token
new = TKCreate(ptr); //use token
if(new!=NULL){ //if token was found do this
addcommand(new,commando);
new = NULL;
}
while(ptr!=NULL&& *ptr != '\0'&&*ptr!=' '){ //get to end of token
ptr++;
}
}
return commando;
}
|
C | /* Copyright Statement:
*
*/
#include <stdint.h>
/*slim version for uart logging*/
void uart_init_boot_phase(void)
{
/*enable PDN*/
*(volatile uint32_t*)0xA0210320 = 0x100000;
*(volatile uint32_t *)0xA00C0058 = 0x016C;
/* set DLM/DLL for buardrate */
*(volatile uint32_t *)0xA00C0008 = 0x0001;
/* set UART TX/RX threshold rx--12, tx --4*/
*(volatile uint32_t *)0xA00C0014 = 0x901;
}
void uart_deinit_boot_phase(void)
{
/*disable PDN*/
*(volatile uint32_t*)0xA0210310 = 0x100000;
}
void uart_put_onechar_boot_phase(uint8_t c)
{
while ((*(volatile uint32_t*)0xA00C0028) == 0)
;
*(volatile uint32_t*)0xA00C0004 = c;
if (c != '\n')
return;
while ((*(volatile uint32_t*)0xA00C0028) == 0)
;
*(volatile uint32_t*)0xA00C0004 = '\r';
while ((*(volatile uint32_t*)0xA00C0028) == 0)
;
}
void uart_put_char_boot_phase(uint8_t *data, uint32_t size)
{
uint32_t index = 0;
for (index = 0; index < size; index++)
uart_put_onechar_boot_phase(*(data++));
}
|
C | #include <errno.h>
#include <stdio.h>
// #include <string.h>
/*
This program will work fine on x86 architecture, but will crash on x86_64 architecture.
Let us see what was wrong with code. Carefully go through the program,
deliberately I haven’t included prototype of “strerror()” function.
This function returns “pointer to character”, which will print error
message which depends on errno passed to this function. Note that x86
architecture is ILP-32 model, means integer, pointers and long are 32-bit wide,
that’s why program will work correctly on this architecture. But x86_64
is LP-64 model, means long and pointers are 64 bit wide. In C language,
when we don’t provide prototype of function, the compiler assumes that
function returns an integer. In our example, we haven’t included “string.h”
header file (strerror’s prototype is declared in this file),
that’s why compiler assumed that function returns integer.
But its return type is pointer to character. In x86_64, pointers are 64-bit
wide and integers are 32-bits wide, that’s why while returning from function,
the returned address gets truncated (i.e. 32-bit wide address, which is size
of integer on x86_64) which is invalid and when we try to dereference this address,
the result is segmentation fault.
*/
int main(int argc, char *argv[])
{
FILE *fp;
fp = fopen(argv[1], "r");
if (fp == NULL) {
fprintf(stderr, "%s\n", strerror(errno)); /* IA86 - works good, IA64 - Segmentation fault (core dumped) */
return errno;
}
printf("file exist\n");
fclose(fp);
return 0;
}
// http://www.geeksforgeeks.org/importance-of-function-prototype-in-c/
|
C | #include <stdint.h>
#define FALSE 0
#define TRUE 1
/******************************************************************************/
/* MIPS memory layout */
/******************************************************************************/
#define MEM_TEXT_BEGIN 0x00400000
#define MEM_TEXT_END 0x0FFFFFFF
/*Memory address 0x10000000 to 0x1000FFFF access by $gp*/
#define MEM_DATA_BEGIN 0x10010000
#define MEM_DATA_END 0x7FFFFFFF
#define MEM_KTEXT_BEGIN 0x80000000
#define MEM_KTEXT_END 0x8FFFFFFF
#define MEM_KDATA_BEGIN 0x90000000
#define MEM_KDATA_END 0xFFFEFFFF
/*stack and data segments occupy the same memory space. Stack grows backward (from higher address to lower address) */
#define MEM_STACK_BEGIN 0x7FFFFFFF
#define MEM_STACK_END 0x10010000
typedef struct {
uint32_t begin, end;
uint8_t *mem;
} mem_region_t;
/* memory will be dynamically allocated at initialization */
mem_region_t MEM_REGIONS[] = {
{ MEM_TEXT_BEGIN, MEM_TEXT_END, NULL },
{ MEM_DATA_BEGIN, MEM_DATA_END, NULL },
{ MEM_KDATA_BEGIN, MEM_KDATA_END, NULL },
{ MEM_KTEXT_BEGIN, MEM_KTEXT_END, NULL }
};
#define NUM_MEM_REGION 4
#define MIPS_REGS 32
typedef struct CPU_State_Struct {
uint32_t PC; /* program counter */
uint32_t REGS[MIPS_REGS]; /* register file. */
uint32_t HI, LO; /* special regs for mult/div. */
} CPU_State;
/***************************************************************/
/* CPU State info. */
/***************************************************************/
CPU_State CURRENT_STATE, NEXT_STATE;
int RUN_FLAG; /* run flag*/
uint32_t INSTRUCTION_COUNT;
uint32_t PROGRAM_SIZE; /*in words*/
char prog_file[32];
/***************************************************************/
/* Function Declarations. */
/***************************************************************/
void help();
uint32_t mem_read_32(uint32_t address);
void mem_write_32(uint32_t address, uint32_t value);
void cycle();
void run(int num_cycles);
void runAll();
void mdump(uint32_t start, uint32_t stop) ;
void rdump();
void handle_command();
void reset();
void init_memory();
void load_program();
void initialize();
void print_program();
/************************************************************/
/* decode and execute instruction */
/************************************************************/
void handle_instruction()
{
uint32_t instr = mem_read_32(CURRENT_STATE.PC);
uint32_t opcode = instr >> 26;
uint32_t s_opcode = instr & 0x3F; //gets special op;
//instruction registers
int rd = (instr >> 11) & 0x1F;
int rt = (instr >> 16) & 0x1F;
int rs = (instr >> 21) & 0x1F;
int im = instr & 0xFFFF;
int off = instr & 0xFFFF;
int r_opcode = rt; //regimm id
int tar = instr & 0x3FFFFFF; //target
int base = rs;
int sa = (instr >> 6) & 0x1F;
switch(opcode){
case 0://special
switch(s_opcode){
case 0: //Shift left logical
printf("SLL\n");
uint32_t sllval;
sllval = CURRENT_STATE.REGS[rt];
NEXT_STATE.REGS[rd] = sllval << sa;
NEXT_STATE.PC += 4;
break;
case 2: //Shift right logical
printf("SRL\n");
uint32_t srlval;
srlval = CURRENT_STATE.REGS[rt];
NEXT_STATE.REGS[rd] = srlval >> sa;
NEXT_STATE.PC += 4;
break;
case 3: //Shift right arithmetic
printf("SRA\n");
uint32_t sraval;
sraval = CURRENT_STATE.REGS[rt];
NEXT_STATE.REGS[rd] = sraval >> sa;
NEXT_STATE.PC += 4;
break;
case 8: //Jump register
printf("JR\n");
uint32_t jrval;
jrval = CURRENT_STATE.REGS[rs];
NEXT_STATE.PC = jrval;
break;
case 9: //Jump and link
printf("JALR\n");
int32_t jalrval;
jalrval = CURRENT_STATE.REGS[rs];
NEXT_STATE.REGS[rd] = CURRENT_STATE.PC += 4;
NEXT_STATE.PC = jalrval;
break;
case 12: //System call
printf("SYSCALL\n");
int32_t sysval;
sysval = CURRENT_STATE.REGS[2];
switch( sysval ){
case 0x0A:
RUN_FLAG = FALSE;
default:
return;
}
break;
case 16: //Move from high
printf("MFHI\n");
int32_t mfhival;
mfhival = NEXT_STATE.HI;
NEXT_STATE.REGS[rd] = mfhival;
NEXT_STATE.PC += 4;
break;
case 17: //Move to high
printf("MTHI\n");
int32_t mthival;
mthival = CURRENT_STATE.REGS[rs];
NEXT_STATE.HI = mthival;
NEXT_STATE.PC += 4;
break;
case 18: //Move from low
printf("MFLO\n");
int32_t mfloval;
mfloval = NEXT_STATE.LO;
NEXT_STATE.REGS[rd] = mfloval;
NEXT_STATE.PC += 4;
break;
case 19: //Move to low
printf("MTLO\n");
int32_t mtloval;
mtloval = CURRENT_STATE.REGS[rs];
NEXT_STATE.LO = mtloval;
NEXT_STATE.PC += 4;
break;
case 24: //Multiply
printf("MULT\n");
int32_t mult1, mult2;
int64_t product;
mult1 = CURRENT_STATE.REGS[rs];
mult2 = CURRENT_STATE.REGS[rd];
product = mult1 * mult2;
NEXT_STATE.HI = ( product >> 32);
NEXT_STATE.LO = ( product & 0xFFFFFFFF );
NEXT_STATE.PC += 4;
break;
case 25: //Multiply unsigned
printf("MULTU\n");
uint32_t mult3, mult4;
uint64_t product2;
mult3 = CURRENT_STATE.REGS[rs];
mult4 = CURRENT_STATE.REGS[rd];
product2 = mult3 * mult4;
NEXT_STATE.HI = ( product2 >> 32);
NEXT_STATE.LO = ( product2 & 0xFFFFFFFF );
NEXT_STATE.PC += 4;
break;
case 26: //Divide
printf("DIV\n");
int32_t div1, div2, quotient1, remainder1;
div1 = CURRENT_STATE.REGS[rs];
div2 = CURRENT_STATE.REGS[rt];
quotient1 = div1 / div2;
remainder1 = div1 % div2;
NEXT_STATE.HI = remainder1;
NEXT_STATE.LO = quotient1;
NEXT_STATE.PC += 4;
break;
case 27: //Divide unsigned
printf("DIVU\n");
uint32_t div3, div4, quotient2, remainder2;
div3 = CURRENT_STATE.REGS[rs];
div4 = CURRENT_STATE.REGS[rt];
quotient2 = div3 / div4;
remainder2 = div3 % div4;
NEXT_STATE.HI = remainder2;
NEXT_STATE.LO = quotient2;
NEXT_STATE.PC += 4;
break;
case 32: //Add
printf("ADD\n");
int32_t rs_val, rt_val, sum;
rs_val = CURRENT_STATE.REGS[rs];
rt_val = CURRENT_STATE.REGS[rt];
sum = rs_val + rt_val;
NEXT_STATE.REGS[rd] = sum;
NEXT_STATE.PC += 4;
break;
case 33: //Add unsigned
printf("ADDU\n");
NEXT_STATE.REGS[rd] = CURRENT_STATE.REGS[rs] + CURRENT_STATE.REGS[rt];
NEXT_STATE.PC += 4;
break;
case 34: //Subtract
printf("SUB\n");
NEXT_STATE.REGS[rd] = CURRENT_STATE.REGS[rs] - CURRENT_STATE.REGS[rt];
NEXT_STATE.PC += 4;
break;
case 35: //Subtract unsigned
printf("SUBU\n");
NEXT_STATE.REGS[rd] = CURRENT_STATE.REGS[rs] - CURRENT_STATE.REGS[rt];
NEXT_STATE.PC += 4;
break;
case 36: //AND
printf("AND\n");
NEXT_STATE.REGS[rd] = CURRENT_STATE.REGS[rs] & CURRENT_STATE.REGS[rt];
NEXT_STATE.PC += 4;
break;
case 37: //OR
printf("OR\n");
NEXT_STATE.REGS[rd] = CURRENT_STATE.REGS[rs] | CURRENT_STATE.REGS[rt];
NEXT_STATE.PC += 4;
break;
case 38: //XOR
printf("XOR\n");
NEXT_STATE.REGS[rd] = CURRENT_STATE.REGS[rs] ^ CURRENT_STATE.REGS[rt];
NEXT_STATE.PC += 4;
break;
case 39: //NOR
printf("NOR\n");
NEXT_STATE.REGS[rd] = ~( CURRENT_STATE.REGS[rs] | CURRENT_STATE.REGS[rt] );
NEXT_STATE.PC += 4;
break;
case 42: //Set on less than
printf("SLT\n");
NEXT_STATE.REGS[rd] = ( CURRENT_STATE.REGS[rs] < CURRENT_STATE.REGS[rt] ) ? 1 : 0;
NEXT_STATE.PC += 4;
break;
default:
break;
}
break;
case 1: //REGIMM
switch(r_opcode){
case 0: //Branch on less than zero
printf("BLTZ\n");
if( CURRENT_STATE.REGS[rs] < 0x0 ){
NEXT_STATE.PC = NEXT_STATE.PC + 4 + off;
}
break;
case 1: //Branch on greater than or equal to
printf("BGEZ\n");
if( CURRENT_STATE.REGS[rs] >= 0x0 ){
NEXT_STATE.PC = NEXT_STATE.PC + 4 + off;
}
break;
default:
break;
}
break;
case 2: //Jump
printf("J\n");
NEXT_STATE.PC = ( CURRENT_STATE.PC & 0xF0000000 ) | ( tar << 2 );
break;
case 3: //Jump and link
printf("JAL\n");
NEXT_STATE.REGS[31] = CURRENT_STATE.PC + 4;
NEXT_STATE.PC = ( CURRENT_STATE.PC & 0xF0000000 ) | ( tar << 2 );
break;
case 4: //Branch on equal
printf("BEQ\n");
uint32_t beq1 = CURRENT_STATE.REGS[rs];
uint32_t beq2 = CURRENT_STATE.REGS[rt];
if( beq1 == beq2 ){
NEXT_STATE.PC = NEXT_STATE.PC + off;
}
break;
case 5: //Branch not equal
printf("BNE\n");
uint32_t bne1 = CURRENT_STATE.REGS[rs];
uint32_t bne2 = CURRENT_STATE.REGS[rt];
if( bne1 != bne2 ){
NEXT_STATE.PC = NEXT_STATE.PC + off;
}
break;
case 6: //Branch on less than or equal to zero
printf("BLEZ\n");
uint32_t blez = CURRENT_STATE.REGS[rs];
if( blez <= 0x0){
NEXT_STATE.PC = NEXT_STATE.PC + 4 + off;
}
break;
case 7: //Branch greater than zero
printf("BGTZ\n");
uint32_t bgtz = CURRENT_STATE.REGS[rs];
if( bgtz >= 0x0){
NEXT_STATE.PC = NEXT_STATE.PC + 4 + off;
}
break;
case 8: //Add immediate
printf("ADDI\n");
int32_t addi = CURRENT_STATE.REGS[rs];
NEXT_STATE.REGS[rt] = addi + im;
NEXT_STATE.PC += 4;
break;
case 9: //Add immediate unsigned
printf("ADDIU\n");
uint32_t addiu = CURRENT_STATE.REGS[rs];
NEXT_STATE.REGS[rt] = addiu + im;
NEXT_STATE.PC += 4;
break;
case 10: //Set on less than immediate
printf("SLTI\n");
int32_t slti = CURRENT_STATE.REGS[rs];
if( slti < im){
NEXT_STATE.REGS[rt] = 0x1;
}else{
NEXT_STATE.REGS[rt] = 0x0;
}
NEXT_STATE.PC += 4;
break;
case 12: //ANDI
printf("ANDI\n");
uint32_t andi = CURRENT_STATE.REGS[rs];
NEXT_STATE.REGS[rt] = andi & im;
NEXT_STATE.PC += 4;
break;
case 13: //ORI
printf("ORI\n");
uint32_t ori = CURRENT_STATE.REGS[rs];
NEXT_STATE.REGS[rt] = ori | im;
NEXT_STATE.PC += 4;
break;
case 14: //XORI
printf("XOR\n");
uint32_t xori = CURRENT_STATE.REGS[rs];
NEXT_STATE.REGS[rt] = xori ^ im;
NEXT_STATE.PC += 4;
break;
case 15: //Load upper immediate
printf("LUI\n");
im <<= 16;
NEXT_STATE.REGS[rt] = im;
NEXT_STATE.PC += 4;
break;
case 32: //Load byte
printf("LB\n");
int32_t lb = CURRENT_STATE.REGS[base];
int32_t lbaddress = lb + off;
NEXT_STATE.REGS[rt] = 0xFF & mem_read_32( lbaddress );
NEXT_STATE.PC += 4;
break;
case 33: //Load half
printf("LF\n");
int32_t lh = CURRENT_STATE.REGS[base];
int32_t lhaddress = lh + off;
NEXT_STATE.REGS[rt] = 0xFFF & mem_read_32( lhaddress );
NEXT_STATE.PC += 4;
break;
case 35: //Load word
printf("LW\n");
int32_t lw = CURRENT_STATE.REGS[base];
int32_t lwaddress = lw + off;
NEXT_STATE.REGS[rt] = mem_read_32( lwaddress );
NEXT_STATE.PC += 4;
break;
case 40: //Store byte
printf("SB");
int32_t sbval1 = CURRENT_STATE.REGS[base];
uint32_t sbval2 = CURRENT_STATE.REGS[rt];
int32_t sbaddress = sbval1 + off;
uint8_t sbval3 = 0xFF & sbval2;
mem_write_32( sbaddress, sbval3 );
NEXT_STATE.PC += 4;
break;
case 41: //Store half
printf("SH\n");
int32_t shval1 = CURRENT_STATE.REGS[base];
uint32_t shval2 = CURRENT_STATE.REGS[rt];
int32_t shaddress = shval1 + off;
uint8_t shval3 = 0xFFFF & shval2;
mem_write_32( shaddress, shval3);
NEXT_STATE.PC += 4;
break;
case 43: //Store word
printf("SW\n");
int32_t swval1 = CURRENT_STATE.REGS[base];
uint32_t swval2 = CURRENT_STATE.REGS[rt];
int32_t swaddress = swval1 + off;
mem_write_32( swaddress, swval2 );
NEXT_STATE.PC += 4;
break;
default:
break;
}
}
/************************************************************/
/* Print the instruction at given memory address (in MIPS assembly format) */
/************************************************************/
void print_instruction(uint32_t addr){
/*IMPLEMENT THIS*/
uint32_t instr = mem_read_32(addr);
uint32_t opcode = instr >> 26;
//printf("\nopcode, 0x%02x\n", opcode);
uint32_t s_opcode = instr & 0x3F; //get's special op;
//instruction registers
int rd = (instr >> 11) & 0x1F;
int rt = (instr >> 16) & 0x1F;
int rs = (instr >> 21) & 0x1F;
int im = instr & 0xFFFF;
int off = instr & 0xFFFF;
int r_opcode = rt; //regimm id
int tar = instr & 0x2FFFFFF; //target
int base = rs;
int sa = (instr >> 6) & 0x1F;
switch(opcode){
case 0://special
switch(s_opcode){
case 0: //SLL
printf("SLL %d, %d, %d\n", rd, rt, sa);
break;
case 2: //SRL
printf("SRL %d, %d, %d\n", rd, rt, sa);
break;
case 3: //SRA
printf("SRA %d, %d, %d\n", rd, rt, sa);
break;
case 8: //JR
printf("JR %d\n", rs);
break;
case 9: //JALR
if(rd==31){
printf("JALR %d\n", rs);
}else
printf("JALR %d, %d\n", rd, rs);
break;
case 12: //SYSCALL
printf("SYSCALL\n");
break;
case 16: //MFHI
printf("MFHI %d\n", rd);
break;
case 17: //MTHI
printf("MTHI %d\n", rs);
break;
case 18: //MFLO
printf("MFLO %d\n", rd);
break;
case 19: //MTLO
printf("MTLO %d\n", rs);
break;
case 24: //MULT
printf("MULT %d, %d\n", rs, rt);
break;
case 25: //MULTU
printf("MULTU %d, %d\n", rs, rt);
break;
case 26: //DIV
printf("DIV %d, %d\n", rs, rt);
break;
case 27: //DIVU
printf("DIVU %d, %d\n", rs, rt);
break;
case 32: //ADD
printf("ADD %d, %d, %d\n", rd, rs, rt);
break;
case 33: //ADDU
printf("ADDU %d, %d, %d\n", rd, rs, rt);
break;
case 34: //SUB
printf("SUB %d, %d, %d\n", rd, rs, rt);
break;
case 35: //SUBU
printf("SUBU %d, %d, %d\n", rd, rs, rt);
break;
case 36: //AND
printf("AND %d, %d, %d\n", rd, rs, rt);
break;
case 37: //OR
printf("OR %d, %d, %d\n", rd, rs, rt);
break;
case 38: //XOR
printf("XOR %d, %d, %d\n", rd, rs, rt);
break;
case 39: //NOR
printf("NOR %d, %d, %d\n", rd, rs, rt);
break;
case 42: //SLT
printf("SLT %d, %d,%d\n", rd, rs, rt);
break;
default:
break;
}
break;
case 1: //REGIMM
switch(r_opcode){
case 0: //BLTZ
printf("BLTZ %d, %d\n", rs, off);
break;
case 1: //BGEZ
printf("BGEZ %d, %d\n", rs, off);
break;
default:
break;
}
break;
case 2: //J
printf("J %d\n", tar);
break;
case 3: //JAL
printf("JAL %d\n", tar);
break;
case 4: //BEQ
printf("BEQ %d, %d, %d\n", rs, rt, off);
break;
case 5: //BNE
printf("BNE %d, %d, %d\n", rs, rt, off);
break;
case 6: //BLEZ
printf("BLEZ %d, %d\n", rs, off);
break;
case 7: //BGTZ
printf("BGTZ %d, %d\n", rs, off);
break;
case 8: //ADDI
printf("ADDI %d, %d, %d\n", rt, rs, im);
break;
case 9: //ADDIU
printf("ADDIU %d, %d, %d\n", rt, rs, im);
break;
case 10: //SLTI
printf("SLTI %d, %d, %d\n", rt, rs, im);
break;
case 12: //ANDI
printf("ANDI %d, %d, %d\n", rt, rs, im);
break;
case 13: //ORI
printf("ORI %d, %d, %d\n", rt, rs, im);
break;
case 14: //XOR
printf("XOR %d, %d, %d\n", rt, rs, im);
break;
case 15: //LUI
printf("LUI %d, %d\n", rt, im);
break;
case 32: //LB
printf("LB %d, %d(%d)\n", rt, off, base);
break;
case 33: //LH
printf("LF %d, %d(%d)\n", rt, off, base);
break;
case 35: //LW
printf("LW %d, %d(%d)\n", rt, off, base);
break;
case 40: //SB
printf("SB %d, %d(%d)\n", rt, off, base);
break;
case 41: //SH
printf("SH %d, %d(%d)\n", rt, off, base);
break;
case 43: //SW
printf("SW %d, %d(%d)\n", rt, off, base);
break;
default:
break;
}
}
|
C | /*==============================================================*/
/* program: freetree.h */
/* purpose: generating all free trees */
/* input : n -- number of nodes */
/* m -- max degree */
/* lb, ub -- lower and upper bound on diameter */
/* output : listing of free trees in relex order */
/* date : September 1995, updated September 2000 */
/* programmers: Gang Li & Frank Ruskey */
/* algorithm: From the paper: G. Li and F. Ruskey, "The */
/* Advantages of Forward Thinking in Generating Rooted and */
/* Free Trees", 10th Annual ACM-SIAM Symposium on Discrete */
/* Algorithms (SODA), (1999) S939-940. See the web page at */
/* http://webhome.cs.uvic.ca/~ruskey/fruskey.html */
/* Publications/RootedFreeTree.html */
/* more info: see */
/* http://theory.cs.uvic.ca/inf/tree/FreeTrees.html */
/*==============================================================*/
// TODO: Put into namespace
const int MAX_SIZE = 50; /* max size of the tree */
int par[MAX_SIZE]; /* parent position of i */
int L[MAX_SIZE]; /* level of node i */
int k; /* max number of children */
int chi[MAX_SIZE]; /* number of children of a node */
int nextp[MAX_SIZE]; /* next good pos to add nodes */
int rChi[MAX_SIZE]; /* the right most child of node i */
int ub; /* upper bound */
int num; /* number of trees */
int outputP, outputL;
int N; /* Corresponds to -n */
int K; /* -k */
int M; /* -m */
int out_format; /* -o */
int U; /* -u */
short treeDatabase[30000000][30];
static int totalAmount = 0;
void PrintIt() {
++num;
if (outputP) {
for (int i = 1; i <= N; ++i) {
printf("%d", par[i]);
if (N > 9 && i < N) {
printf(",");
}
}
}
if (outputL) {
if (outputL && outputP)
printf(" : ");
for (int i = 1; i <= N; ++i) {
printf("%d", L[i]);
if (N > 9 && i < N) {
printf(",");
}
}
}
if (outputP || outputL) {
printf("\n");
}
}
void updateL() {
L[1] = 0;
for (int i = 2; i <= N; ++i) {
L[i] = L[par[i]] + 1;
}
}
bool good(int p, int h, int t) {
if (p == 2 && K <= 2 && t == 0)
return true;
if (t == 1) {
if ((2 * h >= K + 1) && (2 * h <= U + 1)) {
if ((p - 1) * 2 >= N) {
return true;
} else if (p - h - 1 == 1) {
if (par[p] > 2) {
return true;
}
} else if ((p - h - 1 >= 2) && ((par[h + 2] > 2) || (par[h + 3] > 2))) {
return true;
}
}
} else if ((N - p >= h) && (2 * h >= K)) {
if ((U == N - 1) && (N % 2 == 0)) {
return (2 * h <= U + 1);
} else {
return(2 * h <= U);
}
}
return false;
}
void GenTree(int p, int s, int cL, int h, int l, int n, int f, int g) {
int hh, flag, entry, temp;
if (p > n)
if (f == 0) {
if (good(p - 1, h, 0)) {
GenTree(p, 2, p - 2, h, n, N, 1, 0);
}
if (good(p - 1, h, 1)) {
GenTree(p, 2, p - 3, h, n, N, 1, 1);
}
}
else {
updateL();
//PrintIt();
treeDatabase[totalAmount][0] = N;
for (size_t i = 1; i <= static_cast<size_t>(N); ++i)
treeDatabase[totalAmount][i] = par[i] - 1;
++totalAmount;
}
else {
if (cL == 0) {
if (p < ub + 2) {
par[p] = p - 1;
} else {
GenTree(p, p - 1, 1, h, l, n, f, g);
return;
}
} else if (par[p - cL] < s) {
par[p] = par[p - cL];
} else {
par[p] = cL + par[p - cL];
if (g == 1) {
if (((l - 1) * 2 < n) && (p - cL <= l) && (
((p - cL + 1 < l) && (par[p - cL + 1] == 2)
&& (p - cL + 2 <= l) && (par[p - cL + 2] == 2)) /* case 1 */
|| ((p - cL + 1 == l) && (par[p - cL + 1] == 2)) /* case 2 */
|| (p - cL + 1 > l))) /* case 3 */
{
s = par[p];
cL = p - s;
par[p] = par[par[p]];
} else {
if (par[p - cL] == 2) {
par[p] = 1;
}
}
}
}
if (s != 0 || p <= ub + 1) {
chi[par[p]] = chi[par[p]] + 1;
temp = rChi[par[p]];
rChi[par[p]] = p;
if (chi[par[p]] <= ((par[p] == 1) ? k : k - 1)) {
if (chi[par[p]] < (par[p] == 1 ? k : k - 1))
nextp[p] = par[p];
else
nextp[p] = nextp[par[p]];
GenTree(p + 1, s, cL, h, l, n, f, g);
}
chi[par[p]] = chi[par[p]] - 1;
rChi[par[p]] = temp;
}
if (s == 0 && 2 * (p - 2) < K)
return;
nextp[p] = nextp[par[p]];
entry = nextp[p];
flag = 0;
hh = 1;
while ((((f == 0) && (entry >= 2)) || ((f == 1) && (entry >= 1))) && (flag == 0)) {
if (s == 0)
h = p - 2;
if (p <= l + h - g)
hh = 0;
if ((f == 0) || (hh == 1)) {
//s = par[p];
//par[p] = par[s];
par[p] = entry;
chi[entry] = chi[entry] + 1;
temp = rChi[par[p]];
rChi[par[p]] = p;
if (chi[entry] >= (entry == 1 ? k : k - 1))
nextp[p] = nextp[entry];
if (f == 0)
GenTree(p + 1, temp, p - temp, h, 0, N - h + 1, f, g);
else if (hh == 1)
GenTree(p + 1, temp, p - temp, h, l, n, f, g);
chi[entry] = chi[entry] - 1;
rChi[par[p]] = temp;
entry = nextp[entry];
nextp[p] = entry;
} else {
flag = 1;
}
}
if (f == 0) {
if (good(p - 1, h, 0)) {
GenTree(p, 2, p - 2, h, p - 1, N, 1, 0);
}
if (good(p - 1, h, 1)) {
GenTree(p, 2, p - 3, h, p - 1, N, 1, 1);
}
}
}
} /* GenTree */
void ProcessInput(int n) {
/*
printf("Usage: freetree -n N [-d D] [-l L] [-u U] [-o O]\n");
printf(" where N is the number of nodes in the tree,\n");
printf(" D is an upper bound on the degree of any node,\n");
printf(" L is a lower bound on the diameter of the tree,\n");
printf(" U is an upper bound on the diameter of the tree,\n");
printf(" O specifies output:\n");
printf(" O = 0 output the number of trees only.\n");
printf(" O = 1 output parent array,\n");
printf(" O = 2 output level array,\n");
printf(" O = 3 output both,\n");
printf(" Default values: K = U = N - 1, L = 2, O = 3.\n");
printf(" Frank Ruskey, 1995, 2000\n.");
*/
N = n;
M = N - 1;
K = 2;
U = 4;
U = N - 1;
out_format = 1;
out_format = 0;
}
int freeTree(int n) {
num = 0;
/* first set all the parameters */
ProcessInput(n);
if (out_format & 1)
outputP = 1;
if (out_format & 2)
outputL = 1;
if (K > U) {
//printf("ERROR: lb > ub !!\n");
return -1;
}
if (U > 1) {
if (U < N) {
ub = (U + 1) / 2;
} else {
ub = N / 2;
U = N - 1;
}
} else {
//printf("ERROR: ub is too small, should be >= 2\n");
return -1;
}
if (M > 0)
k = M;
else
k = -1;
if (K <= 1) {
//printf("ERROR: k is too small, should be >= 2\n");
return -1;
} else {
for (int i = 1; i <= N; i++)
chi[i] = 0;
par[1] = 0;
par[2] = 1;
nextp[1] = 0;
nextp[2] = 1;
chi[1] = 1;
GenTree(3, 0, 0, ub, 0, N - ub + 1, 0, 0);
//printf("The total number of trees is : %4d\n", num);
}
return 0;
}
|
C | #include "libft.h"
char *ft_strdup(const char *s)
{
char *dest;
int i;
if (dest = (char*)malloc(sizeof(char)*strlen(s) == NULL))
return (NULL);
i = 0;
while (src[i] != '\0')
{
dest[i] = src[i];
i++;
}
dest[i] = '\0';
return (dest);
}
|
C | #ifndef STAKABLE_COIN_H
#define STAKABLE_COIN_H
#include <uint256.h>
#include <primitives/transaction.h>
struct StakableCoin
{
const CTransaction* tx;
unsigned outputIndex;
uint256 blockHashOfFirstConfirmation;
StakableCoin(
): tx(nullptr)
, outputIndex(0u)
, blockHashOfFirstConfirmation(0u)
{
}
StakableCoin(
const CTransaction* txIn,
unsigned outputIndexIn,
uint256 blockHashIn
): tx(txIn)
, outputIndex(outputIndexIn)
, blockHashOfFirstConfirmation(blockHashIn)
{
}
bool operator<(const StakableCoin& other) const
{
return blockHashOfFirstConfirmation < other.blockHashOfFirstConfirmation;
}
};
#endif//STAKABLE_COIN_H |
C | #include<stdio.h>
#include<math.h>
int main()
{
float i,S=0;
for(i=0;i<=19;i++)
{
S=S+(((2*i)+1)/(pow(2,i)));
}
printf("%.2f\n",S);
return 0;
}
|
C | #include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#pragma pack(push,2)
#include <dos/dos.h>
#include <proto/dos.h>
#pragma pack(pop)
int truncate(const char *path, off_t length)
{
int retval;
BPTR fd = Open((CONST_STRPTR)path, MODE_OLDFILE);
if(fd != 0)
{
retval = (SetFileSize(fd, length, OFFSET_BEGINNING) >= 0) ? 0 : -1;
Close(fd);
}
else
{
errno = ENOENT;
retval = -1;
}
return retval;
}
|
C | #include <gtk/gtk.h>
int main(int argc, char *argv[]) {
GtkWidget *window;
GtkWidget *table;
GtkWidget *label1;
GtkWidget *label2;
GtkWidget *label3;
GtkWidget *entry1;
GtkWidget *entry2;
GtkWidget *entry3;
gtk_init(&argc, &argv);
window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
gtk_window_set_title(GTK_WINDOW(window), "GtkEntry");
gtk_container_set_border_width(GTK_CONTAINER(window), 10);
table = gtk_grid_new();
gtk_grid_insert_row (GTK_GRID(table),0);
gtk_grid_insert_row (GTK_GRID(table),1);
gtk_grid_insert_row (GTK_GRID(table),2);
gtk_grid_insert_column (GTK_GRID(table),0);
gtk_grid_insert_column (GTK_GRID(table),1);
gtk_grid_set_row_homogeneous(GTK_GRID(table),TRUE);
gtk_grid_set_column_homogeneous(GTK_GRID(table),TRUE);
gtk_container_add(GTK_CONTAINER(window), table);
label1 = gtk_label_new("Name");
label2 = gtk_label_new("Age");
label3 = gtk_label_new("Occupation");
gtk_grid_attach(GTK_GRID(table), label1, 0, 0, 1, 1);
gtk_grid_attach(GTK_GRID(table), label2, 0, 1, 1, 1);
gtk_grid_attach(GTK_GRID(table), label3, 0, 2, 1, 1);
entry1 = gtk_entry_new();
entry2 = gtk_entry_new();
entry3 = gtk_entry_new();
gtk_grid_attach(GTK_GRID(table), entry1, 1, 0, 1, 1);
gtk_grid_attach(GTK_GRID(table), entry2, 1, 1, 1, 1);
gtk_grid_attach(GTK_GRID(table), entry3, 1, 2, 1, 1);
gtk_widget_show(table);
gtk_widget_show(label1);
gtk_widget_show(label2);
gtk_widget_show(label3);
gtk_widget_show(entry1);
gtk_widget_show(entry2);
gtk_widget_show(entry3);
gtk_widget_show(window);
g_signal_connect(window, "destroy",
G_CALLBACK(gtk_main_quit), NULL);
gtk_main();
return 0;
}
|
C | /*Angelis Marios-Kasidakis Theodoros*/
/*Prime number recognition*/
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>
#include <error.h>
#include <sched.h>
#include <fcntl.h>
struct T {
pthread_t id;
int iret;
int job_flag; /*If job_flag==1,thread has work to do*/
int close_flag; /*If close_flag==1,main is clossing this thread*/
int position; /*Thread position in struct's array*/
long int prime;
};
struct T *info;
int primetest(long int v);
void *thread_func(void *arg);
int main(int args,char* argv[]){
if(args<2){
fprintf(stderr,"Error - Not enough arguments\n");
exit(EXIT_FAILURE);
}
int i,size,exit_flag,number_of_closed_threads=0;
long int number;
size=atoi(argv[1]);
FILE* fp;
fp = fopen("primes.txt", "r");
info = (struct T *)malloc(size*sizeof(struct T));
for(i=0;i<size;i++){ /*Create "size" threads-workers*/
info[i].position=i;
info[i].job_flag=0;
info[i].close_flag=0;
info[i].iret=pthread_create(&info[i].id, NULL,thread_func,(void *)(&info[i]));
if(info[i].iret){
fprintf(stderr,"Error - pthread_create() return code: %d\n",info[i].iret);
exit(EXIT_FAILURE);
}
}
while(1){
char string[100];
if (fgets(string,100,fp) == NULL){ /*Reading numbers from a file,if EOF->break*/
break;
}
number=atol(string);
while(1){
for(i=0;i<size;i++){ /*Main is trying to find an available worker*/
if(info[i].job_flag==0){
info[i].prime=number; /*Main gives job to available worker*/
info[i].job_flag=1; /*Worker has job now*/
exit_flag=1;
break;
}
}
if(exit_flag==1){
exit_flag=0;
break;
}
}
}
while(1){ /*Main is waiting for all threads to finish work*/
for(i=0;i<size;i++){ /*Main is closing all threads and returns*/
if(info[i].job_flag==0 && info[i].close_flag==0){
info[i].close_flag=1;
number_of_closed_threads++;
}
}
if(number_of_closed_threads==size){break;}
}
return(0);
}
void *thread_func(void *arg){ /*Worker function*/
struct T *thread_struct=(struct T*)arg;
while(1){ /*Worker thread is spinning until main gives him work*/
while(info[thread_struct->position].job_flag==0 && info[thread_struct->position].close_flag==0){}
if(info[thread_struct->position].close_flag==1){ /*Main has no more work to give,all threads must close*/
break;
}
primetest(info[thread_struct->position].prime);
info[thread_struct->position].job_flag=0; /*Thread is available now*/
}
return(NULL);
}
int primetest(long int v){
int i, flag = 0;
for(i = 2; i <= v/2; ++i){
// condition for nonprime number
if(v%i == 0){
flag = 1;
break;
}
}
if (v == 1) {
printf("1 is neither a prime nor a composite number.\n");
}
else{
if (flag == 0)
printf("%ld is a prime number.\n", v);
else
printf("%ld is not a prime number.\n", v);
}
return 0;
}
|
C | #include<stdio.h>
#include<conio.h>
void main()
{
int s=1,a,n;
printf("Enter the number:\t");
scanf("%d",&n);
for(a=1;a<=n;a++)
{
s=s*a;
}
printf("The factorial of a given number =\t%d",s);
getch();
}
|
C | #include <conio.h>
int main()
{
int a[1000], i, n, sum = 0;
printf("Enter size of the array : ");
scanf("%d", &n);
printf("Enter elements in array : ");
for (i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}
for (i = 0; i < n; i++)
{
sum += a[i];
}
printf("sum of array is : %d", sum);
return 0;
} |
C | #include <stdbool.h>
#include "aux_macros.h"
#include "pokemon.h"
static bool testCombo() {
bool result = true;
Pokemon pikachu = pokemonCreate("Pikachu", TYPE_ELECTRIC, 20, 4);
TEST_DIFFERENT(result, pikachu, NULL);
Pokemon pikachu_copy = pokemonCopy(pikachu);
TEST_DIFFERENT(result, pikachu_copy, NULL);
pokemonDestroy(pikachu_copy);
TEST_EQUALS(result, pokemonTeachMove(
pikachu, "Thunder", TYPE_ELECTRIC, 10, 110), POKEMON_SUCCESS);
TEST_EQUALS(result, pokemonUnteachMove(pikachu, "Thunder"), POKEMON_SUCCESS);
TEST_EQUALS(result, pokemonGetLevel(pikachu), 1);
TEST_EQUALS(result, pokemonGetRank(pikachu), 0);
Pokemon squirtle = pokemonCreate("Squirtle", TYPE_WATER, 10, 4);
pokemonTeachMove(squirtle, "Bubble", TYPE_WATER, 30, 40);
TEST_EQUALS(result, pokemonUseMove(
squirtle, pikachu, "Bubble"), POKEMON_SUCCESS);
TEST_EQUALS(result, pokemonHeal(pikachu), POKEMON_SUCCESS);
TEST_EQUALS(result, pokemonEvolve(squirtle, "Wartortle"), POKEMON_SUCCESS);
pokemonDestroy(pikachu);
pokemonDestroy(squirtle);
return result;
}
static bool testPokemonCreate() {
bool result = true;
Pokemon charizard;
charizard = pokemonCreate("Charizard", (PokemonType)5, 9900, 10);
TEST_EQUALS(result, charizard, NULL);
pokemonDestroy(charizard);
charizard = pokemonCreate("Charizard", (PokemonType)-1, 9900, 10);
TEST_EQUALS(result, charizard, NULL);
pokemonDestroy(charizard);
charizard = pokemonCreate("Charizard", TYPE_FIRE, 9902, 10);
TEST_EQUALS(result, charizard, NULL);
pokemonDestroy(charizard);
charizard = pokemonCreate("Charizard", TYPE_FIRE, -1, 10);
TEST_EQUALS(result, charizard, NULL);
pokemonDestroy(charizard);
charizard = pokemonCreate("", TYPE_FIRE, 9900, 10);
TEST_EQUALS(result, charizard, NULL);
pokemonDestroy(charizard);
charizard = pokemonCreate(NULL, TYPE_FIRE, 9900, 10);
TEST_EQUALS(result, charizard, NULL);
pokemonDestroy(charizard);
charizard = pokemonCreate("Charizard", TYPE_FIRE, 9900, -1);
TEST_EQUALS(result, charizard, NULL);
pokemonDestroy(charizard);
charizard = pokemonCreate("Charizard", TYPE_FIRE, 9900, 10);
TEST_DIFFERENT(result, charizard, NULL);
pokemonDestroy(charizard);
return result;
}
static bool testPokemonDestroy() {
bool result = true;
Pokemon charizard = pokemonCreate("Charizard", TYPE_FIRE, 9900, 10);
Pokemon charizardClone = pokemonCopy(charizard);
pokemonTeachMove(charizard, "Fireball", TYPE_FIRE, 10, 5);
pokemonDestroy(NULL);
pokemonDestroy(charizard);
pokemonDestroy(charizardClone);
return result;
}
static bool testPokemonCopy() {
bool result = true;
PokemonResult pokemon_result;
Pokemon charizard = pokemonCreate("Charizard", TYPE_FIRE, 9900, 10);
pokemonTeachMove(charizard, "Fireball", TYPE_FIRE, 10, 5);
Pokemon charizardClone = pokemonCopy(charizard);
TEST_DIFFERENT(result, charizardClone, NULL);
pokemon_result = pokemonUnteachMove(charizardClone, "Fireball");
TEST_EQUALS(result, pokemon_result, POKEMON_SUCCESS);
pokemonDestroy(charizard);
pokemonDestroy(charizardClone);
return result;
}
static bool testPokemonTeachMove() {
bool result = true;
PokemonResult pokemon_result;
Pokemon charizard = pokemonCreate("Charizard", TYPE_FIRE, 9900, 10);
pokemon_result = pokemonTeachMove(charizard, "Fireball", TYPE_FIRE, 10, 5);
TEST_EQUALS(result, pokemon_result, POKEMON_SUCCESS);
pokemon_result = pokemonTeachMove(NULL, "", TYPE_GRASS, -10, -5);
TEST_EQUALS(result, pokemon_result, POKEMON_NULL_ARG);
pokemon_result = pokemonTeachMove(charizard, NULL, TYPE_GRASS, -10, -5);
TEST_EQUALS(result, pokemon_result, POKEMON_NULL_ARG);
pokemon_result = pokemonTeachMove(charizard, "", TYPE_GRASS, -10, -5);
TEST_EQUALS(result, pokemon_result, POKEMON_INVALID_MOVE_NAME);
pokemon_result = pokemonTeachMove(charizard, "Fireball", -1, -10, -5);
TEST_EQUALS(result, pokemon_result, POKEMON_INVALID_TYPE);
pokemon_result = pokemonTeachMove(charizard, "Fireball", TYPE_GRASS, 10, 5);
TEST_EQUALS(result, pokemon_result, POKEMON_INCOMPATIBLE_MOVE_TYPE);
pokemon_result = pokemonTeachMove(charizard, "Fireball", TYPE_NORMAL, -1, -5);
TEST_EQUALS(result, pokemon_result, POKEMON_INVALID_POWER_POINTS);
pokemon_result = pokemonTeachMove(charizard, "Fireball", TYPE_NORMAL, 10, -1);
TEST_EQUALS(result, pokemon_result, POKEMON_INVALID_STRENGTH);
pokemon_result = pokemonTeachMove(charizard, "Fireball", TYPE_FIRE, 10, 5);
TEST_EQUALS(result, pokemon_result, POKEMON_MOVE_ALREADY_EXISTS);
pokemonDestroy(charizard);
return result;
}
static bool testPokemonUnteachMove() {
bool result = true;
PokemonResult pokemon_result;
Pokemon charizard = pokemonCreate("Charizard", TYPE_FIRE, 9900, 10);
pokemonTeachMove(charizard, "Fireball", TYPE_FIRE, 10, 5);
pokemon_result = pokemonUnteachMove(NULL, "");
TEST_EQUALS(result, pokemon_result, POKEMON_NULL_ARG);
pokemon_result = pokemonUnteachMove(charizard, NULL);
TEST_EQUALS(result, pokemon_result, POKEMON_NULL_ARG);
pokemon_result = pokemonUnteachMove(charizard, "");
TEST_EQUALS(result, pokemon_result, POKEMON_INVALID_MOVE_NAME);
pokemon_result = pokemonUnteachMove(charizard, "Firestorm");
TEST_EQUALS(result, pokemon_result, POKEMON_MOVE_DOES_NOT_EXIST);
pokemon_result = pokemonUnteachMove(charizard, "Fireball");
TEST_EQUALS(result, pokemon_result, POKEMON_SUCCESS);
pokemon_result = pokemonUnteachMove(charizard, "Fireball");
TEST_EQUALS(result, pokemon_result, POKEMON_MOVE_DOES_NOT_EXIST);
pokemonDestroy(charizard);
return result;
}
static bool testPokemonGetLevel() {
bool result = true;
int level;
Pokemon charizard = pokemonCreate("Charizard", TYPE_FIRE, 9900, 10);
level = pokemonGetLevel(charizard);
TEST_EQUALS(result, level, 99);
pokemonDestroy(charizard);
charizard = pokemonCreate("Charizard", TYPE_FIRE, 9901, 10);
level = pokemonGetLevel(charizard);
TEST_EQUALS(result, level, 100);
pokemonDestroy(charizard);
return result;
}
static bool testPokemonGetRank() {
bool result = true;
int rank;
Pokemon charizard = pokemonCreate("Charizard", TYPE_FIRE, 1000, 10);
rank = pokemonGetRank(charizard);
TEST_EQUALS(result, rank, 0);
pokemonTeachMove(charizard, "Fireball", TYPE_FIRE, 2, 10);
rank = pokemonGetRank(charizard);
TEST_EQUALS(result, rank, 20);
pokemonTeachMove(charizard, "Firestorm", TYPE_FIRE, 2, 20);
rank = pokemonGetRank(charizard);
TEST_EQUALS(result, rank, 25);
pokemonDestroy(charizard);
return result;
}
static bool testPokemonUseMove() {
bool result = true;
PokemonResult pokemon_result = 0;
Pokemon charizard = pokemonCreate("Charizard", TYPE_FIRE, 20, 10);
Pokemon pidgey = pokemonCreate("Pidgey", TYPE_NORMAL, 10, 10);
pokemonTeachMove(charizard, "Tackle", TYPE_NORMAL, 100, 10);
pokemonTeachMove(charizard, "Tail-Whip", TYPE_NORMAL, 1, 10);
pokemon_result = pokemonUseMove(charizard, pidgey, "Bite");
TEST_EQUALS(result, pokemon_result, POKEMON_MOVE_DOES_NOT_EXIST);
pokemon_result = pokemonUseMove(charizard, pidgey, "Tail-Whip");
TEST_EQUALS(result, pokemon_result, POKEMON_SUCCESS);
pokemon_result = pokemonUseMove(charizard, pidgey, "Tail-Whip");
TEST_EQUALS(result, pokemon_result, POKEMON_NO_POWER_POINTS);
for (int i = 0; i <= 50; i++) { // poor pidgey (:
pokemon_result = pokemonUseMove(charizard, pidgey, "Tackle");
TEST_EQUALS(result, pokemon_result, POKEMON_SUCCESS);
}
pokemon_result = pokemonUseMove(charizard, pidgey, "Tackle");
TEST_EQUALS(result, pokemon_result, POKEMON_NO_HEALTH_POINTS);
pokemonDestroy(charizard);
pokemonDestroy(pidgey);
return result;
}
static bool testPokemonHeal() {
bool result = true;
PokemonResult pokemon_result = 0;
Pokemon charizard = pokemonCreate("Charizard", TYPE_FIRE, 20, 10);
Pokemon blastoise = pokemonCreate("Blastoise", TYPE_WATER, 20, 10);
pokemonTeachMove(blastoise, "Water-Gun", TYPE_WATER, 1000, 5000);
pokemon_result = pokemonHeal(NULL);
TEST_EQUALS(result, pokemon_result, POKEMON_NULL_ARG);
pokemon_result = pokemonHeal(charizard);
TEST_EQUALS(result, pokemon_result, POKEMON_SUCCESS);
pokemonUseMove(blastoise, charizard, "Water-Gun");
pokemon_result = pokemonHeal(charizard);
TEST_EQUALS(result, pokemon_result, POKEMON_SUCCESS);
pokemon_result = pokemonUseMove(blastoise, charizard, "Water-Gun");
TEST_EQUALS(result, pokemon_result, POKEMON_SUCCESS);
pokemonDestroy(charizard);
pokemonDestroy(blastoise);
return result;
}
static bool testPokemonEvolve() {
bool result = true;
PokemonResult pokemon_result;
int level;
Pokemon charmander = pokemonCreate("charmander", TYPE_FIRE, 1000, 10);
pokemon_result = pokemonEvolve(NULL, "");
TEST_EQUALS(result, pokemon_result, POKEMON_NULL_ARG);
pokemon_result = pokemonEvolve(charmander, "");
TEST_EQUALS(result, pokemon_result, POKEMON_INVALID_NAME);
pokemon_result = pokemonEvolve(charmander, NULL);
TEST_EQUALS(result, pokemon_result, POKEMON_NULL_ARG);
for (int i = 0; i < 90; i++) {
level = pokemonGetLevel(charmander);
pokemon_result = pokemonEvolve(charmander, "Charmeleon");
TEST_EQUALS(result, pokemon_result, POKEMON_SUCCESS);
TEST_EQUALS(result, pokemonGetLevel(charmander), level + 1);
}
pokemon_result = pokemonEvolve(charmander, "Charmeleon");
TEST_EQUALS(result, pokemon_result, POKEMON_CANNOT_EVOLVE);
pokemonDestroy(charmander);
return result;
}
static bool testPokemonPrintName() {
bool result = true;
PokemonResult pokemon_result;
Pokemon charmander = pokemonCreate("charmander", TYPE_FIRE, 1000, 10);
pokemon_result = pokemonPrintName(charmander, NULL);
TEST_EQUALS(result, pokemon_result, POKEMON_NULL_ARG);
pokemon_result = pokemonPrintName(NULL, NULL);
TEST_EQUALS(result, pokemon_result, POKEMON_NULL_ARG);
pokemonDestroy(charmander);
return result;
}
static bool testPokemonPrintVoice() {
bool result = true;
PokemonResult pokemon_result;
Pokemon charmander = pokemonCreate("charmander", TYPE_FIRE, 1000, 10);
pokemon_result = pokemonPrintVoice(charmander, NULL);
TEST_EQUALS(result, pokemon_result, POKEMON_NULL_ARG);
pokemon_result = pokemonPrintVoice(NULL, NULL);
TEST_EQUALS(result, pokemon_result, POKEMON_NULL_ARG);
pokemonDestroy(charmander);
return result;
}
int main() {
RUN_TEST(testCombo);
RUN_TEST(testPokemonCreate);
RUN_TEST(testPokemonDestroy);
RUN_TEST(testPokemonCopy);
RUN_TEST(testPokemonTeachMove);
RUN_TEST(testPokemonUnteachMove);
RUN_TEST(testPokemonGetLevel);
RUN_TEST(testPokemonGetRank);
RUN_TEST(testPokemonUseMove);
RUN_TEST(testPokemonHeal);
RUN_TEST(testPokemonEvolve);
RUN_TEST(testPokemonPrintName);
RUN_TEST(testPokemonPrintVoice);
return 0;
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
struct figura{
int fig;
float *T;
};
float pole(struct figura F){
int wybor;
if(F.fig==2){
printf("Wybierz figure: Trojkat 0, Rownoleglobok 1\n");
scanf("%i", &wybor);
if(wybor==0){
return (F.T[0]*F.T[1])/2;
}
else{
return F.T[0]*F.T[1];
}
}
else if(F.fig==3){
((F.T[0]+F.T[1])*F.T[2])/2;
}
else{
return F.T[0]*F.T[1];
}
}
int main()
{
/*
Trjkt: 2 parametry (bok, wysoko)
Prostokt: 4 parametry (2*bok a, 2*bok b)
Rwnolegobok: 2 parametry (bok, wysoko)
Trapez: 3 parametry (2 podstawy, wysoko)
*/
struct figura trojkat;
trojkat.fig=2;
trojkat.T=malloc(2*sizeof(float));
trojkat.T[0]=2.45;
trojkat.T[1]=5.12;
printf("%Pole Wybranej figury: %0.2f \n", pole(trojkat));
return 0;
}
|
C |
/*
John Stachurski, March 2012
A collection of functions for working with the AR1 model defined by
X' = beta + alpha x + s Z where Z ~ N(0,1)
*/
#include <stdio.h>
#include <math.h>
#include <time.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_fit.h>
#include "utilities.h"
int ar1_ts (double * x, double * params, int n, unsigned long int seed)
{
double beta = params[0];
double alpha = params[1];
double s = params[2];
/* create a generator chosen by the environment variable GSL_RNG_TYPE */
const gsl_rng_type * T;
gsl_rng * r;
gsl_rng_env_setup();
T = gsl_rng_default;
r = gsl_rng_alloc(T);
gsl_rng_set(r, seed);
int i;
x[0] = beta / (1 - alpha); // Start at mean of stationary dist
for (i = 1; i < n; i++)
{
x[i] = beta + alpha * x[i-1] + gsl_ran_gaussian(r, s);
}
gsl_rng_free (r);
return 0;
}
int cont_time_to_ar1(double kappa, double b, double sigma, double delta, double * beta, double * alpha, double * s)
{
*beta = b * (1 - exp(- kappa * delta));
*alpha = exp(- kappa * delta);
double s2 = sigma * sigma * (1 - exp(- 2 * kappa * delta)) / (2 * kappa);
*s = sqrt(s2);
return 0;
}
int fit_params(double *x, int n, double * beta, double * alpha, double * s)
{
double cov00, cov01, cov11, chisq;
double * y = x + 1;
gsl_fit_linear (x, 1, y, 1, n-1,
beta, alpha, &cov00, &cov01, &cov11, &chisq);
int i;
double u;
double sum = 0.0;
for (i = 0; i < n - 1; i++)
{
u = y[i] - (* beta) - (* alpha) * x[i];
sum += u * u;
}
*s = sqrt(sum / (n - 1));
return 0;
}
|
C | /* You're given a number N. Print the first N lines of the below-given pattern.
*
**
***
****
*****
Input:
First-line will contain the number N.
Output:
Print the first N lines of the given pattern.
Constraints
1≤N≤200
Sample Input 1:
4
Sample Output 1:
*
**
***
****
Sample Input 2:
2
Sample Output 2:
*
**
EXPLANATION:
In the first example, we'll print the first 4 lines of the given pattern.
In the second example, we'll print the first 2 lines of the given pattern */
#include <stdio.h>
int main(void) {
int t;
scanf("%d",&t);
for(int i=1;i<=t;i++)
{
for(int j=t;j>i;j--)
printf(" ");
for(int k=1;k<=i;k++)
printf("*");
printf("\n");
}
return 0;
}
|
C | /*
int ft_strcmp(char *s1, char *s2)
{
while (*s1 && *s2 && *s1 == *s2)
{
s1++;
s2++;
}
return (*s1 - *s2);
}
*/
#include <stdio.h>
int ft_strcmp(char *s1, char *s2)
{
return ((*s1 && *s2 && *s1 == *s2) ? ft_strcmp(++s1, ++s2) : (*s1 - *s2));
}
int main()
{
printf("%d", ft_strcmp("abcde", "abcd"));
printf("%d", ft_strcmp("abcd", "abcde"));
printf("%d", ft_strcmp("abcd", "abce"));
}
|
C | /*
* main.c
*
* Created on: 11 mar. 2021
* Author: JFSR00
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void * copiar_bloque_memoria(void * destino, void * origen, unsigned int longitud);
int main(int argc, char *argv[]){
int orig[20], dest[20];
//char t;
/* Desactivar el buffer de stdout para facilitar la depuracin a travs de
* la consola de Eclipse.
*/
setvbuf(stdout, NULL,_IONBF, 0);
for(int i = 0; i < 20; i++){
orig[i]=i;
printf("%d ", i);
}
copiar_bloque_memoria(orig, dest, sizeof(int)*20);
printf("\nResultado copia: %d", memcmp(orig, dest, sizeof(int)*20));
printf("\n");
for(int i = 0; i < 20; i++){
printf("%d ", dest[i]);
}
printf("\nPulse 's' y ENTER para salir. ");
/*do{
scanf("%c", &t);
}while(t != 's' && t != 'S');*/
return 0;
}
|
C | /*
** base.c for bistro in /home/carle_s/depot/bistro/bistro2
**
** Made by Carle Sacha
** Login <[email protected]>
**
** Started on Fri Oct 31 10:45:07 2014 Carle Sacha
** Last update Fri Oct 31 21:48:10 2014 Carle Sacha
*/
#include <stdlib.h>
#include "./include/struct.h"
int valbase(char c, char *base)
{
int i;
i = 0;
while (base[i] != '\0')
{
if (base[i] == c)
{
return (i);
}
i = i + 1;
}
return (-1);
}
int expr_sup(char *nbr1, char *nbr2, PARAM param)
{
int i;
int test;
i = 0;
if (my_strlen(nbr1) > my_strlen(nbr2))
return (1);
else if (my_strlen(nbr1) < my_strlen(nbr2))
return (-1);
while (nbr1[i] != '\0' && nbr2[i] != '\0')
{
test = valbase(nbr1[i], param->base) > valbase(nbr2[i], param->base);
if (test == 1)
return (1);
else if (nbr1[i] != nbr2[i])
return (-1);
i = i + 1;
}
if (nbr1[i] == '\0' && nbr2[i] == '\0')
return (0);
else if (nbr1[i] == '\0')
return (-1);
else
return (1);
}
NBR newnbr(char *val, int signe)
{
NBR nbr;
nbr = malloc(sizeof(struct s_number));
nbr->val = val;
nbr->sign = signe;
return (nbr);
}
void my_putbase_nbr(NBR nbr)
{
if (nbr->sign == -1)
my_putchar('-');
my_putstr(nbr->val);
}
|
C | #include <jni.h>
#include "file.h"
struct DIR_NODE {
char *path;
size_t size;
};
JNIEXPORT void JNICALL
Java_psycho_euphoria_file_Native_renameMp3File(JNIEnv *env, jobject thiz, jstring path) {
const char *f = (*env)->GetStringUTFChars(env, path, NULL);
RenameMp3File(f);
(*env)->ReleaseStringChars(env, path, (jchar *) f);
}
JNIEXPORT void JNICALL
Java_psycho_euphoria_file_Native_deleteFile(JNIEnv *env, jobject thiz, jstring path) {
const char *dir = (*env)->GetStringUTFChars(env, path, NULL);
remove_directory(dir);
(*env)->ReleaseStringChars(env, path, (jchar *) dir);
}
JNIEXPORT jstring JNICALL
Java_psycho_euphoria_file_Native_calculateDirectory(JNIEnv *env, jobject thiz, jstring path) {
const char *dir = (*env)->GetStringUTFChars(env, path, NULL);
LIST *dirtories = list_directories(dir);
size_t len = 10;
size_t t = 0;
char *l = malloc(len);
memset(l, '\0', len);
while (dirtories) {
size_t total = 0;
calculate_files_recursively(dirtories->line, &total);
char buf[10];
readable_size(total, buf);
size_t tl = strlen(dirtories->line) + strlen(buf) + 3;
t += tl;
char b[tl];
sprintf(b, "%s %s\n", dirtories->line, buf);
if (len < t) {
len = t << 1;
l = realloc(l, len);
}
strcat(l, b);
l[len - 1] = '\0';
dirtories = dirtories->next;
}
(*env)->ReleaseStringChars(env, path, (jchar *) dir);
return (*env)->NewStringUTF(env, (const char *) l);
} |
C | /* misc.h
* maths Macros
* 6/21/99 */
#ifndef __GNUC__
/* Use the C* extensions: >? (MAX) and <? (MIN) operators */
#ifndef MAX
#define MAX(x, y) ((x) >? (y))
#endif
#ifndef MIN
#define MIN(x, y) ((x) <? (y))
#endif
#ifndef ABS
#define ABS(x) ((x) >? (-(x)))
#endif
#ifndef ROUND
#define ROUND(a) ( (int) {a > 0 ? a + 0.5 : a - 0.5; })
#endif
#else
#define ROUND(a) ({ typeof (a) __a = (a); (int) ((__a > 0) ? (__a + 0.5) : (__a - 0.5)); })
#define MAX(a, b) ({ typeof (a) _a = (a); typeof (b) _b = (b); _a > _b ? _a : _b; })
#define MIN(a, b) ({ typeof (a) _a = (a); typeof (b) _b = (b); _a < _b ? _a : _b; })
#define ABS(a) ({ typeof (a) _a = (a); _a < (typeof (a)) 0 ? -_a : _a; })
#endif
|
C | // Emrehan ILHAN 13011021 - Algoritma Analizi 2. dev
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
#define TESTSIZE 95
#define HASHSIZE 267569
#define DICTIONARYSIZE 133780
#define CHANGE 2
#define DELETE 1
#define INSERT 1
#define HASHWORD 50
#define MINRESULT 4
#define TESTOUT "testout.txt"
#define DEBUG 0
struct HASH{
char word[HASHWORD];
int isEmpty; // 0&1
}HASH[HASHSIZE];
//Hash struct yapisini sifirlar.
void initHash(){
int i;
for(i=0; i<HASHSIZE; i++){
HASH[i].isEmpty=1;
strcpy(HASH[i].word,"");
}
}
//Hash bellege alinmis mi kontrol eder
int hashIsSet(){
int i;
for(i=0; i<HASHSIZE; i++){
if(HASH[i].isEmpty==0){
return 1;
}
}
return 0;
}
//Olusan hash yapisini yazdirir.
void printHash(){
int i;
for(i=0; i<HASHSIZE; i++){
if(HASH[i].isEmpty==1){
printf("%d=> EMPTY", i);
}else{
printf("%d=> %s",i,HASH[i].word);
}
printf("\n");
}
}
//Dosya adini okuyan fonksiyon, sureyi kisaltmak icin direk default degeri donduruyor
int readFile(char name[], char info[], char defaultName[]){
strcpy(name,defaultName);
return 0;
int devam;
printf("%s\n\n",info);
printf("Dosya adi varsayilan (%s) olarak devam etmek ister misiniz?\n",name);
printf("Evet = 1 / Hayir = 0\n");
scanf("%d",&devam);
if(devam==0) {
printf("\nDosya adini giriniz. \n=");
scanf("%s",name);
}
printf("Kullanilan dosya adi = |%s|\n\n",name);
}
int hashId(char word[]){
int i, addr=0;
for(i=0; i<strlen(word); i++){
addr += word[i]*26*i;
}
addr = addr % HASHSIZE;
return addr;
}
int calculateHashId(char word[]){
int i;
int addr=0;
addr=hashId(word);
//printf("Hash'e gelen kelime |%s|, ilk adres %d\n",word,addr);
while(HASH[addr].isEmpty==0){
addr++;
addr = addr % HASHSIZE;
}
//printf("Hash'e gelen kelime |%s|, son adres %d\n",word,addr);
return addr;
}
void toLowerCase(char word[]){
int i;
for(i=0; i<strlen(word); i++){
if(word[i]>'A' && word[i]<'Z'){
word[i]=word[i]+'a'-'A';
}
}
}
//dict.txt isimli dosyadan hash yapisini olusturur ve hash.txt yazar
int createHash(){
char dictionaryName[50];
char hashName[50];
char tmp[50];
int count=0;
int i;
int addr;
readFile(dictionaryName,"Kelimelerin okunacagi sozlugun adresini giriniz","dict.txt");
readFile(hashName,"Hash'in yazilacagi adresi giriniz","hash.txt");
FILE *fpr=fopen(dictionaryName,"r");
FILE *fpw=fopen(hashName,"w");
if(!fpr || !fpw) {
printf("Error!");
return -1;
}
for(i=0; i<DICTIONARYSIZE; i++){
fscanf(fpr,"%s",tmp);
toLowerCase(tmp);
strlwr(tmp);
addr=calculateHashId(tmp);
HASH[addr].isEmpty=0;
strcpy(HASH[addr].word,tmp);
printf("%s %d\n",tmp,strlen(tmp));
count++;
}
fclose(fpr);
for(i=0; i<HASHSIZE; i++){
fprintf(fpw,"%s\n",(HASH[i].isEmpty==0)?HASH[i].word:"-");
}
fclose(fpw);
printf("%d adet kelime hash tablosuna yerlestirildi ve %s isimli dosyaya yazildi. Devam etmek icin bir tusa basin.",count,hashName);
getch();
system("cls");
}
//createHash fonksiyonunun olusturdugu dosyadan hash yapisini okuyan fonksiyon.
int readHashFromFile(){
char hashFileName[50];
char tmp[50];
int i;
int addr;
readFile(hashFileName,"Hash'in okunacagi dosyanin adresini giriniz","hash.txt");
FILE *fp=fopen(hashFileName,"r");
if(!fp) {
printf("Error!");
return -1;
}
for(i=0; i<HASHSIZE; i++){
fscanf(fp,"%s",tmp);
strlwr(tmp);
toLowerCase(tmp);
if(tmp[0]!='-'){
HASH[i].isEmpty=0;
strcpy(HASH[i].word,tmp);
printf("%s\n",tmp);
}
}
printf("%d adet kelime hash tablosuna yerlestirildi. Devam etmek icin bir tusa basin.",HASHSIZE);
getch();
system("cls");
fclose(fp);
}
//Bir kelimeyi bir dosyanin sonuna yazmayi saglayan fonksiyon
int appendFile( char text[]){
FILE *fp=fopen(TESTOUT,"a");
if(!fp){
printf("Error append file\n");
return -1;
}
fprintf(fp,"%s",text);
fclose(fp);
return 0;
}
//Verilen kelimeyi sozlukteki tum kelimelerle karsilastirir, distance sonucunu bir threshold degeriyle kontrol eder.
void findWord(char manuel[], int useManuel, char fileName[]){
char target[20];
int addr;
int devam=1;
int i;
while(devam==1){
char string[50];
int step=0;
if(useManuel==0){
printf("Aranan kelimeyi giriniz\n");
scanf("%s",target);
}else{
strcpy(target,manuel);
}
addr = hashId(target);
step++;
if(strcmp(HASH[addr].word,target)==0){
if(DEBUG==1) printf("<%s> OK (%d.adreste, %d adimda)\n",HASH[addr].word,addr,step);
sprintf(string,"<%s> OK\n",HASH[addr].word);
printf("<%s> OK\n",HASH[addr].word);
if(useManuel==1) appendFile(string);
}else if(HASH[addr].isEmpty==0){
while(HASH[addr].isEmpty==0 && strcmp(HASH[addr].word,target)!=0 && (step-1)<HASHSIZE){
addr++;
addr%=HASHSIZE;
step++;
}
if(strcmp(HASH[addr].word,target)==0){
sprintf(string,"<%s> OK\n",HASH[addr].word);
printf("<%s> OK\n",HASH[addr].word);
if(useManuel==1) appendFile(string);
//printf("<%s> OK (%d.adreste, %d adimda)\n",HASH[addr].word,addr,step);
}
}
if(strcmp(HASH[addr].word,target)!=0){
int min=100,result=-1, minI=-1;
for(i=0; i<HASHSIZE; i++){
if(HASH[i].isEmpty==0){
if(DEBUG==1) printf("HASH <%s> ve <%s> gonderildi\n",target,HASH[i].word);
result=levenshtein_distance(target,HASH[i].word,0,"",0);
if(DEBUG==1) printf("%s sonuc=>%d\n",HASH[i].word,result);
if(result<min){
if(DEBUG==1) printf("result(%d)<min(%d) yeni minI %d\n",result,min,i);
min=result;
minI=i;
}
}
}
if(DEBUG==1) printf("fordan cikti\n");
if(DEBUG==1) printf("min %d minresult %d\n",min,MINRESULT);
if(min<MINRESULT){
if(DEBUG==1) printf("min<MINRESUlT\n",min);
if(DEBUG==1) printf("%s tekrar minI=%d\n",HASH[minI].word,minI);
levenshtein_distance(target,HASH[minI].word,1,fileName,1);
}else{
sprintf(string,"<%s> NONE\n",target);
if(useManuel==1){
appendFile(string);
}
}
printf("%s",string);
}
if(useManuel==0){
printf("Devam(1) / Bitir(0)\n");
scanf("%d",&devam);
system("cls");
}else{
devam=0;
}
}
}
//distance matrisini sifirlayan fonksiyon
void initDistance(int matrix[][HASHWORD]){
int i,j;
for(i=0; i<HASHWORD; i++){
for(j=0; j<HASHWORD; j++){
matrix[i][j]=0;
}
}
for(i=0; i<HASHWORD; i++){
matrix[0][i]=i;
}
for(i=0; i<HASHWORD; i++){
matrix[i][0]=i;
}
}
int min3(int a, int b, int c){
return (a<b)?((a<c)?a:c):((b<c)?b:c);
}
//Backtrack eksik
void backtrack(int distance[][HASHWORD],char wrong[], char right[], int isBest,char fileName[], int useManuel){
char result[50];
if(isBest==1){
sprintf(result,"<%s> <%s> \n",wrong,right);
if(useManuel==1) appendFile(result);
printf("%s",result);
}
}
//distance matrisini olusturan fonksiyon
//Eger isBest==1 ise ayrica backtrack yapar
int levenshtein_distance(char w1[], char w2[], int isBest, char fileName[], int useManuel){
if(DEBUG==1) printf("leven w1 w2 isbest filename usemanuel\n%s %s %d %s %d\n",w1,w2,isBest,fileName,useManuel);
int distance[HASHWORD][HASHWORD];
int i,j;
initDistance(distance);
for(i=1; i<strlen(w2)+1;i++){
for(j=1; j<strlen(w1)+1; j++){
if(w1[j-1]==w2[i-1]){
distance[i][j]=distance[i-1][j-1];
}else{
distance[i][j]=(min3(
distance[i-1][j]+DELETE,
distance[i][j-1]+INSERT,
distance[i-1][j-1]+CHANGE
)
);
}
}
}
if(isBest==1){
backtrack(distance,w1,w2,isBest,fileName,useManuel);
}
if(DEBUG==1) printf("leven kelime %s %s sonuc %d\n",w1,w2,distance[strlen(w2)][strlen(w1)]);
return distance[strlen(w2)][strlen(w1)];
}
//test.txt dosyasindan kelime okuyup szlkte arayip, sonucu testout.txt yazan fonksiyon
int findWordFromFile(){
char rfileName[50]="test.txt";
char wfileName[50]="testout.txt";
int i;
FILE *fpr=fopen(rfileName,"r");
if(!fpr) {
printf("Error!");
return -1;
}
for(i=0; i<TESTSIZE; i++){
char tmp[50];
fscanf(fpr,"%s",tmp);
toLowerCase(tmp);
strlwr(tmp);
findWord(tmp,1,"testout.txt");
}
fclose(fpr);
}
//Edit distance'i ayri bir fonksiyon olarak denemek icin
void editDistance(){
char w1[50], w2[50];
int i,j;
printf("Birinci kelimeyi girin\n");
scanf("%s",w1);
printf("Ikinci kelimeyi girin\n");
scanf("%s",w2);
int distance[HASHWORD][HASHWORD];
initDistance(distance);
for(i=1; i<strlen(w2)+1;i++){
for(j=1; j<strlen(w1)+1; j++){
//printf("Bakilan %c ve %c => ",w1[j-1],w2[i-1]);
if(w1[j-1]==w2[i-1]){
distance[i][j]=distance[i-1][j-1];
//printf("ayni d[%d][%d]<=%d\n",i,j,distance[i-1][j-1]);
}else{
distance[i][j]=(min3(distance[i-1][j],distance[i][j-1],distance[i-1][j-1])+1);
//printf("farkli d[%d][%d]<=%d\n",i,j,(min3(distance[i-1][j],distance[i][j-1],distance[i-1][j-1])+1));
}
}
}
printf("\nSonuc = %d\n\nSonuc matrisi\n",distance[strlen(w2)][strlen(w1)]);
for(i=0; i<strlen(w2)+1; i++){
for(j=0; j<strlen(w1)+1; j++){
printf("%d ",distance[i][j]);
}
printf("\n");
}
printf("Devam etmek icin bir tusa basin.",HASHSIZE);
getch();
system("cls");
}
//Menu isleri icin kullanilan fonksiyon
int menu(){
int menu=0;
char c;
int maxMenu=5;
int devam=1;
char space[]= " ";
while(devam==1){
printf("%s",space);printf("Did You Mean???\n\n");
printf("%s",space);printf("W/S, E for Enter\n");
printf("%s",space);if(hashIsSet()==1)printf("Hash mevcut\n\n");else printf("Hash mevcut degil\n\n");
printf("%s",space);if(menu==0)printf("=>");else printf(" "); printf("Hash Olustur\n");
printf("%s",space);if(menu==1)printf("=>");else printf(" "); printf("Dosyadan Hash Oku\n");
printf("%s",space);if(menu==2)printf("=>");else printf(" "); if(hashIsSet()==1) printf("Hash Tablosu\n"); else printf("Hash Tablosu(Once Hashleme gerekiyor)\n");
printf("%s",space);if(menu==3)printf("=>");else printf(" "); if(hashIsSet()==1) printf("Dosyadan Kelime Bul\n"); else printf("Dosyadan Kelime Bul(Once Hashleme gerekiyor)\n");
printf("%s",space);if(menu==4)printf("=>");else printf(" "); if(hashIsSet()==1) printf("Kelime Bul\n"); else printf("Kelime Bul(Once Hashleme gerekiyor)\n");
printf("%s",space);if(menu==5)printf("=>");else printf(" "); printf("Edit Distance(Demo)\n");
printf("%s",space);if(menu==6)printf("=>");else printf(" "); printf("Cikis\n");
c=getch();
system("cls");
if(c=='w' || c==72){
menu--;
menu=menu<0?maxMenu:menu;
}else if(c=='s' || c==80){
menu++;
menu=menu>maxMenu?0:menu;
}
if(c=='e'){
return menu;
}
}
}
int main(){
initHash();
int menuDonen;
do {
menuDonen = menu();
if(menuDonen==0) createHash();
if(menuDonen==1) readHashFromFile();
if(menuDonen==2) printHash();
if(menuDonen==3) findWordFromFile();
if(menuDonen==4) findWord("",0,"");
if(menuDonen==5) editDistance();
} while(menuDonen!=6);
printf("Cikis yaptiniz.");
return 0;
}
|
C | /* Hash routine.
* Copyright (C) 1998 Kunihiro Ishiguro
*
* This file is part of GNU Zebra.
*
* GNU Zebra is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation; either version 2, or (at your
* option) any later version.
*
* GNU Zebra is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with GNU Zebra; see the file COPYING. If not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
#include "zebra.h"
#include "hash.h"
#include "memory.h"
/* Allocate a new hash. */
struct hash *
hash_create_size (unsigned int size, unsigned int (*hash_key) (void *),
int (*hash_cmp) (const void *, const void *))
{
struct hash *hash;
assert ((size & (size-1)) == 0);
hash = XMALLOC (MTYPE_HASH, sizeof (struct hash));
hash->index = XCALLOC (MTYPE_HASH_INDEX,
sizeof (struct hash_backet *) * size);
hash->size = size;
hash->no_expand = 0;
hash->hash_key = hash_key;
hash->hash_cmp = hash_cmp;
hash->count = 0;
return hash;
}
/* Allocate a new hash with default hash size. */
struct hash *
hash_create (unsigned int (*hash_key) (void *),
int (*hash_cmp) (const void *, const void *))
{
return hash_create_size (HASH_INITIAL_SIZE, hash_key, hash_cmp);
}
/* Utility function for hash_get(). When this function is specified
as alloc_func, return arugment as it is. This function is used for
intern already allocated value. */
void *
hash_alloc_intern (void *arg)
{
return arg;
}
/* Expand hash if the chain length exceeds the threshold. */
static void hash_expand (struct hash *hash)
{
unsigned int i, new_size, losers;
struct hash_backet *hb, *hbnext, **new_index;
new_size = hash->size * 2;
new_index = XCALLOC(MTYPE_HASH_INDEX, sizeof(struct hash_backet *) * new_size);
if (new_index == NULL)
return;
for (i = 0; i < hash->size; i++)
for (hb = hash->index[i]; hb; hb = hbnext)
{
unsigned int h = hb->key & (new_size - 1);
hbnext = hb->next;
hb->next = new_index[h];
new_index[h] = hb;
}
/* Switch to new table */
XFREE(MTYPE_HASH_INDEX, hash->index);
hash->size = new_size;
hash->index = new_index;
/* Ideally, new index should have chains half as long as the original.
If expansion didn't help, then not worth expanding again,
the problem is the hash function. */
losers = 0;
for (i = 0; i < hash->size; i++)
{
unsigned int len = 0;
for (hb = hash->index[i]; hb; hb = hb->next)
{
if (++len > HASH_THRESHOLD/2)
++losers;
if (len >= HASH_THRESHOLD)
hash->no_expand = 1;
}
}
if (losers > hash->count / 2)
hash->no_expand = 1;
}
/* Lookup and return hash backet in hash. If there is no
corresponding hash backet and alloc_func is specified, create new
hash backet. */
void *
hash_get (struct hash *hash, void *data, void * (*alloc_func) (void *))
{
unsigned int key;
unsigned int index;
void *newdata;
unsigned int len;
struct hash_backet *backet;
key = (*hash->hash_key) (data);
index = key & (hash->size - 1);
len = 0;
for (backet = hash->index[index]; backet != NULL; backet = backet->next)
{
if (backet->key == key && (*hash->hash_cmp) (backet->data, data))
return backet->data;
++len;
}
if (alloc_func)
{
newdata = (*alloc_func) (data);
if (newdata == NULL)
return NULL;
if (len > HASH_THRESHOLD && !hash->no_expand)
{
hash_expand (hash);
index = key & (hash->size - 1);
}
backet = XMALLOC (MTYPE_HASH_BACKET, sizeof (struct hash_backet));
backet->data = newdata;
backet->key = key;
backet->next = hash->index[index];
hash->index[index] = backet;
hash->count++;
return backet->data;
}
return NULL;
}
/* Hash lookup. */
void *
hash_lookup (struct hash *hash, void *data)
{
return hash_get (hash, data, NULL);
}
/* Simple Bernstein hash which is simple and fast for common case */
unsigned int string_hash_make (const char *str)
{
unsigned int hash = 0;
while (*str)
hash = (hash * 33) ^ (unsigned int) *str++;
return hash;
}
/* This function release registered value from specified hash. When
release is successfully finished, return the data pointer in the
hash backet. */
void *
hash_release (struct hash *hash, void *data)
{
void *ret;
unsigned int key;
unsigned int index;
struct hash_backet *backet;
struct hash_backet *pp;
key = (*hash->hash_key) (data);
index = key & (hash->size - 1);
for (backet = pp = hash->index[index]; backet; backet = backet->next)
{
if (backet->key == key && (*hash->hash_cmp) (backet->data, data))
{
if (backet == pp)
hash->index[index] = backet->next;
else
pp->next = backet->next;
ret = backet->data;
XFREE (MTYPE_HASH_BACKET, backet);
hash->count--;
return ret;
}
pp = backet;
}
return NULL;
}
/* Iterator function for hash. */
void
hash_iterate (struct hash *hash,
void (*func) (struct hash_backet *, void *), void *arg)
{
unsigned int i;
struct hash_backet *hb;
struct hash_backet *hbnext;
for (i = 0; i < hash->size; i++)
for (hb = hash->index[i]; hb; hb = hbnext)
{
/* get pointer to next hash backet here, in case (*func)
* decides to delete hb by calling hash_release
*/
hbnext = hb->next;
(*func) (hb, arg);
}
}
/* Clean up hash. */
void
hash_clean (struct hash *hash, void (*free_func) (void *))
{
unsigned int i;
struct hash_backet *hb;
struct hash_backet *next;
for (i = 0; i < hash->size; i++)
{
for (hb = hash->index[i]; hb; hb = next)
{
next = hb->next;
if (free_func)
(*free_func) (hb->data);
XFREE (MTYPE_HASH_BACKET, hb);
hash->count--;
}
hash->index[i] = NULL;
}
}
/* Free hash memory. You may call hash_clean before call this
function. */
void
hash_free (struct hash *hash)
{
XFREE (MTYPE_HASH_INDEX, hash->index);
XFREE (MTYPE_HASH, hash);
}
|
C | #include <stdio.h>
#include <string.h>
int a[100],b[100];
void transp(int *mas, int *ans, int k) {
int j;
int p=0, q=k;//q=strlen(mas);
for (j=0; j<strlen(mas); j++)
if (mas[j]>k) {
ans[q]=mas[j];
q--;
}
else {
ans[p]=mas[j];
p++;
}
ans[strlen(mas)]=0;
}
int main(void) {
int i,n;
for (i=0; ; i++) {
if (scanf("%d",&n)==1)
a[i]=n;
else {
printf("Error!\n");
break;
}
}
scanf("%d",&n);
transp(a,b,n);
for (i=0; i<strlen(b); i++)
printf("%d ",b[i]);
printf("\n");
return 0;
}
|
C | #include "flash.h"
#include "stm32f10x.h"
#define DEBUG_NAME "flash"
#define DEBUG_LEVEL 3
#include "debug.h"
/* Private typedef -----------------------------------------------------------*/
typedef enum {FAILED = 0, PASSED = !FAILED} TestStatus;
/* Private define ------------------------------------------------------------*/
/* Define the STM32F10x FLASH Page Size depending on the used STM32 device */
#if defined (STM32F10X_HD) || defined (STM32F10X_HD_VL) || defined (STM32F10X_CL) || defined (STM32F10X_XL)
#define FLASH_PAGE_SIZE ((uint16_t)0x800)
#else
#define FLASH_PAGE_SIZE ((uint16_t)0x400)
#endif
#define BANK1_WRITE_START_ADDR ((uint32_t)0x0804E000)
#define BANK1_WRITE_END_ADDR ((uint32_t)0x08080000)
#ifdef STM32F10X_XL
#define BANK2_WRITE_START_ADDR ((uint32_t)0x08088000)
#define BANK2_WRITE_END_ADDR ((uint32_t)0x0808C000)
#endif /* STM32F10X_XL */
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
uint32_t EraseCounter = 0x00, Address = 0x00;
uint32_t Data = 0x3210ABCD;
uint32_t NbrOfPage = 0x00;
volatile FLASH_Status FLASHStatus = FLASH_COMPLETE;
volatile TestStatus MemoryProgramStatus = PASSED;
#ifdef STM32F10X_XL
volatile TestStatus MemoryProgramStatus2 = PASSED;
#endif /* STM32F10X_XL */
/* Private function prototypes -----------------------------------------------*/
/* Private functions ---------------------------------------------------------*/
/**
* @brief Main program
* @param None
* @retval None
*/
__IO uint32_t* flash_read(uint8_t index)
{
/* Define the number of page to be erased */
NbrOfPage = (BANK1_WRITE_END_ADDR - BANK1_WRITE_START_ADDR) / FLASH_PAGE_SIZE;
if (index >= NbrOfPage)
{
log_error("index too large:%d max:%d\r\n",index,NbrOfPage);
return NULL;
}
EraseCounter = index;
/* Check the correctness of written data */
Address = BANK1_WRITE_START_ADDR + (FLASH_PAGE_SIZE * EraseCounter);
return (__IO uint32_t*) Address;
}
int flash_data(uint8_t index,uint32_t * data,uint16_t length)
{
/*!< At this stage the microcontroller clock setting is already configured,
this is done through SystemInit() function which is called from startup
file (startup_stm32f10x_xx.s) before to branch to application main.
To reconfigure the default setting of SystemInit() function, refer to
system_stm32f10x.c file
*/
/* Porgram FLASH Bank1 ********************************************************/
/* Unlock the Flash Bank1 Program Erase controller */
FLASH_UnlockBank1();
/* Define the number of page to be erased */
NbrOfPage = (BANK1_WRITE_END_ADDR - BANK1_WRITE_START_ADDR) / FLASH_PAGE_SIZE;
/* Clear All pending flags */
FLASH_ClearFlag(FLASH_FLAG_EOP | FLASH_FLAG_PGERR | FLASH_FLAG_WRPRTERR);
if (index >= NbrOfPage)
{
log_error("index too large:%d max:%d\r\n",index,NbrOfPage);
return -1;
}
EraseCounter = index;
/* Erase the FLASH pages */
FLASHStatus = FLASH_ErasePage(BANK1_WRITE_START_ADDR + (FLASH_PAGE_SIZE * EraseCounter));
if(FLASHStatus != FLASH_COMPLETE)
{
log_error("Page Index %d Erase Failed! error:%d",index,FLASHStatus);
return -1;
}
/* Program Flash Bank1 */
Address = BANK1_WRITE_START_ADDR + (FLASH_PAGE_SIZE * EraseCounter);
for(uint16_t i=0;i<length && i<500;i++)
{
FLASHStatus = FLASH_ProgramWord(Address, data[i]);
Address = Address + 4;
if(FLASHStatus != FLASH_COMPLETE)
{
log_error("Page Index %d Progrem Failed! error:%d",index,FLASHStatus);
return -1;
}
}
FLASH_LockBank1();
/* Check the correctness of written data */
Address = BANK1_WRITE_START_ADDR + (FLASH_PAGE_SIZE * EraseCounter);
for(uint16_t i=0;i<length && i<500;i++)
{
if((*(__IO uint32_t*) Address) != data[i])
{
MemoryProgramStatus = FAILED;
log_error("Page Index %d Check Failed! data:%08X error:%08X",index,data[i],(*(__IO uint32_t*) Address));
return -1;
}
Address += 4;
}
log_info("EraseCounter:%d\r\n",EraseCounter);
log_info("Address:0x%08X\r\n",Address);
log_info("NbrOfPage:%d\r\n",NbrOfPage);
log_info("MemoryProgramStatus:%d\r\n",MemoryProgramStatus);
log_info("FLASHStatus:%d\r\n",FLASHStatus);
return 0;
}
|
C | #include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <syslog.h>
#include <string.h>
//Time Library
#include <time.h>
int main() {
pid_t pid, sid;
pid = fork();
if (pid < 0) {
exit(EXIT_FAILURE);
}
if (pid > 0) {
exit(EXIT_SUCCESS);
}
umask(0);
sid = setsid();
if (sid < 0) {
exit(EXIT_FAILURE);
}
if ((chdir("/home/dejahvoe/log")) < 0) {
exit(EXIT_FAILURE);
}
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
while(1) {
time_t rawtime = time(NULL);
char strtime[200];
strftime(strtime, 200, "%d:%m:%Y-%H:%M", localtime(&rawtime));
// printf("%s", strtime);
mkdir(strtime, S_IRWXU | S_IRWXG | S_IRWXO);
int i;
for(i = 1; i <= 30; i++) {
sleep(60);
char combined[200] = "";
strcat(combined, strtime);
char filename[20];
sprintf(filename, "/log%d.log", i);
strcat(combined, filename);
FILE *source, *target;
char sourcefile[200] = "/var/log/syslog";
char targetfile[200];
strcpy(targetfile, combined);
// printf("%s\n", sourcefile);
// printf("%s\n", targetfile);
source = fopen(sourcefile, "r");
target = fopen(targetfile, "w");
char ch;
while((ch = fgetc(source)) != EOF){
fputc(ch, target);
}
fclose(source);
fclose(target);
}
}
exit(EXIT_SUCCESS);
}
|
C | /*
** EPITECH PROJECT, 2019
** Pushswap
** File description:
** [Pushswap - Simple Linked List File]
*/
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "include/my.h"
#include "include/my_list.h"
void push_simple_list(linked_list_b **head, linked_list_b *elem)
{
if (*head == NULL) {
*head = elem;
return;
}
linked_list_b *temp = *head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = elem;
return;
}
linked_list_b *node_create(char *value)
{
linked_list_b *node = malloc(sizeof(linked_list_b));
node->value = value;
node->data = my_getnbr(value);
node->next = NULL;
return (node);
}
void insertBeginSimple(linked_list_b **head, char *value)
{
linked_list_b *new_node = malloc(sizeof(linked_list_b));
new_node->value = value;
new_node->data = my_getnbr(value);
new_node->next = (*head);
(*head) = new_node;
}
void deleteFirstNodeSimple(linked_list_b **head)
{
linked_list_b *tmp = *head;
if (*head == NULL)
return;
*head = tmp->next;
free(tmp);
return;
}
int count_simple_list(linked_list_b *head)
{
int n = 0;
while (head) {
n++;
head = head->next;
}
return (n);
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <pthread.h>
#include <semaphore.h>
void* thread_func(void* arg);
typedef struct thread_data {
int in;
int out;
} thread_data_t;
static sem_t count_sem;
int quit = 0;
int main(int argc, char** argv)
{
pthread_t tid[2];
thread_data_t a[2];
thread_data_t *b[2] = { NULL, NULL };
int ret, v;
a[0].in = 2; a[0].out = 0;
a[1].in = 4; a[1].out = 0;
if (sem_init(&count_sem, 0, 1) == -1) {
printf("sem_init: failed: %s\n", strerror(errno));
}
if (argc > 1)
quit = atoi(argv[1]);
pthread_create(&tid[0], NULL, thread_func, (void*)&a[0]);
pthread_create(&tid[1], NULL, thread_func, (void*)&a[1]);
printf("main: process id %d, thread id = %d\n", getpid(), pthread_self());
printf("main: tid[0] = %d, tid[1] = %d\n", tid[0], tid[1]);
printf("main: &a[0] = 0x%08lx, &a[1] = 0x%08lx\n", &a[0], &a[1]);
printf("main: b[0] = 0x%08lx, b[1] = 0x%08lx\n", b[0], b[1]);
printf("main: a[0].in = %d, a[1].in = %d\n", a[0].in, a[1].in);
printf("main: a[0].out = %d, a[1].out = %d\n", a[0].out, a[0].out);
if (sem_getvalue(&count_sem, &v) == -1) {
printf("sem_getvalue: failed: %s\n", strerror(errno));
}
else {
printf("main: count_sem value = %d\n", v);
}
if (quit == 1) pthread_exit(NULL);
else if (quit == 2) exit(0);
else if (quit == 3) pthread_cancel(tid[1]);
pthread_join(tid[0], (void**)&b[0]);
return 0;
}
|
C | /*
* File: huffman_encoding.c
* Author: d|kargatzis
*
* Created on February
*/
#include <stdio.h>
#include <stdlib.h>
#include "huffman_encoding.h"
#include "encoding.h"
void write_bitstream(huff_tree tree, int *diff_array){
FILE *output;
int i,num=0;
output = fopen(file_output, "w");
if(output == NULL)
printf("Unable to create file.");
for (i=0;i<block_size;i++){
if(diff_array[i] == -222)
break;
if(abs(diff_array[i])>15 && case_A == 0){
fprintf(output, "%d\n", diff_array[i]);
huffman_bits++;
continue;
}
found_node = init_node(found_node);
found = 0;
search_huff_tree(tree->root, diff_array[i]);
int j=0;
while(j < found_node->pointer && found == 1){
num++;
fprintf(output, "%d\n", found_node->bin[j]);
huffman_bits++;
j++;
}
//fprintf(output, "\n" );
//print_node(found_node);
//free(found_node);
}
fclose(output);
}
void decode_bitstream(huff_tree tree){
FILE *input1,*validation;
int bit;
int tmp = 0;
node current;
current = init_node(current);
current = tree->root;
validation = fopen(valid, "a");
if(validation == NULL)
printf("Unable to create file.");
input1 = fopen(file_output,"r");
if(input1 == NULL)
printf("Unable to open file.");
while(fscanf(input1,"%d",&bit) == 1){
if(bit != 0 && bit != 1){
tmp = tmp + bit;
fprintf(validation, "%d\n", tmp);
continue;
}
if(current->left_node !=NULL && current->right_node != NULL){
if(bit == 0)
current = current->left_node;
else
current = current->right_node;
}
if(current->left_node == NULL && current->right_node == NULL){
//print_node(current);
fprintf(validation, "%d\n", tmp + current->value);
tmp = tmp + current->value;
current = tree->root;
}
}
fclose(validation);
fclose(input1);
}
void print_menu() {
printf("\nData compression program:\n");
printf("----------------------------------------------\n\n");
printf("\t1. Huffman encoding.\n");
printf("\t2. Residual encoding.\n");
printf("\t3. Golomb rice encoding.\n");
printf("\t4. Golomb rice exponential encoding.\n\n");
printf("----------------------------------------------\n\n");
printf("Please give a choise:\n");
}
int main(int argc, char const *argv[])
{
printf("\nInput training data file name:\t");
scanf("%s",&file_input);
printf("\nInput validation file name:\t");
scanf("%s",&valid);
print_menu();
int choise;
scanf("%d", &choise);
FILE *input;
int mean_v, s;
int i,measure,array[block_size],diff_array[block_size];
int eof=0; /* END OF FILE */
input = fopen(file_input, "r");
if(input == NULL)
printf("Unable to open file.");
//printf("\nData compression program started!\n");
//printf("----------------------------------\n\n");
while(1){
huff_heap heap;
huff_tree h_tree;
//printf("\tInitializing heap...\n");
heap = init_heap(heap);
//print_heap(heap);
//printf("\tInitializing huffman tree...\n");
h_tree = init_huff_tree(h_tree);
//printf("\tReading training data from file...\n");
for (i=0;i<block_size;i++){
if((eof=fscanf(input,"%d",&measure)) != 1){
diff_array[i] = -222;
break;
}
array[i] = measure;
//printf("%d\n", array[i]);
if(i==0)
diff_array[i] = array[i];
else
diff_array[i] = array[i] - array[i-1];
if(case_A == 1){
insert_value_to_heap(diff_array[i],heap);
}
else if(case_A == 0){
if(abs(diff_array[i])<=15)
insert_value_to_heap(diff_array[i],heap);
}
}
if(eof != 1 && i < 1)
break;
if (choise == RES) {
residual_bits = 0;
printf("\n\tResidual Mapping Table:\n");
printf("\t-------------------------\n\n");
residual_encode(diff_array, i);
printf("\n");
printf("Total written residual bits:\t%d\n", residual_bits);
decode_residual_bitstream();
}
//print_heap(heap);
if (choise == GOL) {
golomb_bits = 0;
printf("\n\tGolomb-Rice Mapping Table:\n");
printf("\t----------------------------\n\n");
golomb_rice_encode(diff_array, i, 4);
printf("\n");
//printf("End of golomb-rice encoding.\n");
printf("Total written golomb bits:\t%d\n", golomb_bits);
decode_golomb_bitstream(4);
}
if (choise == GOL_EXP) {
exp_golomb_bits = 0;
printf("\n\tGolomb-Rice Exponential Mapping Table:\n");
printf("\t----------------------------------------\n\n");
golomb_rice_exp_encode(diff_array,i);
printf("\n");
printf("Total written exponential golomb bits:\t%d\n", exp_golomb_bits);
decode_golomb_exp_bitstream();
}
//mean_v = array_mean_value(diff_array);
//s = array_s(diff_array, mean_v);
//printf("************************* Counter: %d\n", heap->counter);
//printf("\tBuilding huffman tree...\n");
if (choise == HUFF){
huffman_bits = 0;
build_wide_huff_tree(h_tree, heap);
//print_huff_tree_preorder(h_tree->root);
int j;
for (j=0; j < K_BITS; j++) {
h_tree->root->bin[j] = EMPTY_CELL;
//printf("CELL: %d\n", h_tree->root->bin[j]);
}
h_tree->root->pointer = 0;
//printf("\tUpdating huffman tree...\n");
update_huff_tree(h_tree->root, h_tree, h_tree->root->bin, h_tree->root->pointer, BIT_0);
printf("\n\tHuffman Mapping Table:\n");
printf("\t------------------------\n\n");
print_huff_tree_codes(h_tree->root);
printf("\n");
//printf("\tWriting the encoded file...\n");
write_bitstream(h_tree, diff_array);
printf("Total written huffman bits:\t%d\n", huffman_bits);
//printf("\tDecoding procedure...\n");
decode_bitstream(h_tree);
//printf("\tFree huffman tree...\n");
free_huff_tree(h_tree->root);
}
if(eof != 1)
break;
}
printf("Data compression program successfully finished...\n\n");
fclose(input);
return 0;
}
|
C | #include <stdio.h>
#include <stdlib.h>
int main(int argc, char const *argv[])
{
int ia=3;
float fa=2.6;
int ib=ia+fa;
float fb=ia+fa;
printf("int: %d\n", ib);
printf ("float: %f\n", fb);
return 0;
} |
C | #include <stdio.h>
#include <stdlib.h>
#include "matriz.h"
struct matriz{
int ** mat;
int linhas, colunas;
};
void erroInicializacao() {
printf("Erro ao alocar memória\n");
exit(1);
}
Matriz* inicializaMatriz(int nlinhas, int ncolunas) {
Matriz *m = (Matriz *) malloc(sizeof(Matriz));
if(!m)
erroInicializacao();
m->linhas = nlinhas;
m->colunas = ncolunas;
m->mat = (int **) malloc(sizeof(int*) * m->linhas);
if(!m->mat)
erroInicializacao();
for(int i = 0; i < m->linhas; i++){
m->mat[i] = (int *) malloc(sizeof(int) * m->colunas);
if(!m->mat[i])
erroInicializacao();
}
return m;
}
void modificaElemento(Matriz* mat, int linha, int coluna, int elem) {
mat->mat[linha][coluna] = elem;
}
int recuperaElemento(Matriz* mat, int linha, int coluna) {
return mat->mat[linha][coluna];
}
int recuperaNColuna(Matriz* mat) {
return mat->colunas;
}
int recuperaNLinhas(Matriz* mat) {
return mat->linhas;
}
Matriz* transposta(Matriz *mat) {
Matriz *matTrans;
matTrans = inicializaMatriz(mat->colunas, mat->linhas);
for(int i = 0; i < matTrans->linhas; i++) {
for(int j = 0; j < matTrans->colunas; j++) {
modificaElemento(matTrans, i, j, mat->mat[j][i]);
}
}
return matTrans;
}
Matriz* multiplicacao(Matriz* mat1, Matriz* mat2) {
if(mat1->colunas != mat2->linhas) {
printf("Não podemos multiplicar as matrizes\n");
exit(1);
}
Matriz* matMul = inicializaMatriz(mat1->linhas, mat2->colunas);
int elem = 0;
for(int i = 0; i < matMul->linhas; i++) {
for(int j = 0; j < matMul->colunas; j++) {
for(int k = 0; k < mat1->colunas; k++) {
elem += mat1->mat[i][k] * mat2->mat[k][j];
}
matMul->mat[i][j] = elem;
elem = 0;
}
}
return matMul;
}
void imprimeMatriz(Matriz* mat) {
for(int i = 0; i < mat->linhas; i++) {
for(int j = 0; j < mat->colunas; j++) {
printf("%d ", mat->mat[i][j]);
}
printf("\n");
}
}
void destroiMatriz(Matriz* mat) {
for(int i = 0; i < mat->linhas; i++) {
free(mat->mat[i]);
}
free(mat->mat);
free(mat);
} |
C | #include "STM32L1xx.h" /* Microcontroller information */
/* Define global variables */
int counter1;
int counter2;
int direction;
/*---------------------------------------------------*/
/* Initialize GPIO pins used in the program */
/*---------------------------------------------------*/
void PinSetup () {
RCC->AHBENR |= 0x01; /* Enable GPIOA clock (bit 0) */
// GPIOA->MODER &= ~(0x0000000F); /* General purpose input mode for PA0-1 */
RCC->AHBENR |= 0x04; /* Enable GPIOC clock (bit 2) */
GPIOA->MODER &= ~(0x00000FF); /* Clear PA0-1 for input mode */
GPIOC->MODER |= (0x00055555); /* General purpose output mode for LEDS PC0-9*/
}
/*---------------------------------------------------*/
/* Initialize interrupts used in the program */
/*---------------------------------------------------*/
void interrupt_setup() {
EXTI->RTSR |= 0x03; // line1-0 are rising edge triggered
EXTI->IMR |= 0x03; //line 1-0 are not masked; therefore they're enabled
EXTI->PR |= 0x03; //clear pending for EXTI1-0
EXTI->PR |= 0x0003; //clear pending for PA1-0
NVIC_EnableIRQ(EXTI0_IRQn);
NVIC_EnableIRQ(EXTI1_IRQn);
SYSCFG->EXTICR[0] &= 0xFF00;
__enable_irq();
}
/*----------------------------------------------------------*/
/* Delay function - do nothing for about 0.5 seconds */
/*----------------------------------------------------------*/
void delay () {
int i,j,n;
for (i=0; i<20; i++) { //outer loop
for (j=0; j<8800; j++) { //inner loop
n = j; //dummy operation for single-step test
} //do nothing
}
}
/*----------------------------------------------------------*/
/*Counter: if counter1 = 9, roll over to 0; otherwise increment count by 1*/
/*Counter2: if direction = 0, counter2 functions as counter1.*/
/*If direction = 0, counter2 counts down instead. It also counts at half */
/* the rate of counter1 due to the placement of the delays and updates*/
/*----------------------------------------------------------*/
void count() {
counter1 = (counter1 < 9) ? (counter1 + 1) : 0;
if (direction == 0) {
counter2 = (counter2 < 9) ? (counter2 + 1) : 0;
}
else {
counter2 = (counter2 > 0) ? (counter2 - 1) : 9;
}
GPIOC->ODR &= 0xFF00; //clears ODR LEDS PC7-0
GPIOC ->ODR |= counter1; //Sets ODR LEDS PC3-0 to counter 1
GPIOC ->ODR |= counter2 << 4; //Sets ODR LEDS PC7-4 to counter2
delay(); //delay half a second
counter1 = (counter1 < 9) ? (counter1 + 1) : 0;
GPIOC->ODR &= 0xFFF0;//clears ODR LEDS PC3-0
GPIOC ->ODR |= counter1 ; //Sets ODR LEDS PC3-0 to counter 1
delay(); //delay half a second
}
//Interrupt called when PA0 (User Button) is pressed
void EXTI0_IRQHandler() {
__disable_irq();
direction = 1; //set direction for counter2 to the reverse direction.
GPIOC->ODR ^= 0x0100; //Set PC8=1 to turn on blue LED (in BSRR lower half)
EXTI->PR |= 0x0001;
NVIC_ClearPendingIRQ(EXTI0_IRQn);
__enable_irq();
}
//Interrupt called when PA1 (Waveforms Button) is pressed
void EXTI1_IRQHandler() {
__disable_irq();
direction = 0; //set direction for counter2 to the forwards direction.
GPIOC->ODR ^= 0x0200; //Set PC9 = 1 to turn ON green LED (in BSRR lower half)
EXTI->PR |= 0x0002;
NVIC_ClearPendingIRQ(EXTI1_IRQn);
__enable_irq();
}
int main() {
PinSetup();
interrupt_setup();
counter1 = 0;
counter2 = 9;
direction = 0;
GPIOC->ODR &= 0xFF00;
while(1) {
count();
}
}
|
C | #include<stdio.h>
int fact(int);
int main()
{
int num,f;
scanf("%d",&num);
f=fact(num);
printf("\nFactorial of %d is: %d",num,f);
return 0;
}
int fact(int n){
if(n==1)
return 1;
else
return(n*fact(n-1));
}
|
C | #include "Globals.h"
void printWord(struct word W)
{
int i;
printf("Word:\n");
for (i = 1 << 11; i > 0; i >>= 1)
{
if (W.instructionBinary & i)
printf("1");
else
printf("0");
}
printf("\n");
}
void InsertExtern(char *name, int address)
{
struct extLabel* cntPtr = headExternList;
while (cntPtr->next)
cntPtr = cntPtr->next;
cntPtr->next = (struct label*)malloc(sizeof(struct label));
cntPtr = cntPtr->next;
cntPtr->address = address;
cntPtr->name = (char*)malloc(sizeof(char*)*(strlen(name) + 1));
strcpy(cntPtr->name, name);
cntPtr->next = NULL;
}
void InsertWord(struct word*a)
{
struct word*cWord = headWordList;
while (cWord->next)
cWord = cWord->next;
cWord->next = a;
printWord(*a);
}
/*Calculates the final label's address (data rows appear after instruction rows, and address is relative to type)*/
int CalcLabelAddress(struct label*a)
{
struct rowComp type = a->rowType;
if (type.isData)
return PROGRAM_OFFSET + totalIC + a->address;
else if (type.isExtern)
return NULL;
else if (type.isInstruction)
return PROGRAM_OFFSET + a->address;
}
/*Iterates over all labels, returns matching struct labelor NULL if not found.*/
struct label*GetLabelFromList(char *name)
{
struct label*cLabel = headLabelList->next;
/*Iterate over list until reaching the last "next" member*/
while (cLabel)
{
if (!strcmp(cLabel->name, name))
return cLabel;
cLabel = cLabel->next;
}
return NULL;
}
void InsertLabel(char* c, int cnt, struct rowComp rc)
{
struct label* cntPtr = headLabelList;
while (cntPtr->next)
cntPtr = cntPtr->next;
cntPtr->next = (struct label*)malloc(sizeof(struct label));
cntPtr = cntPtr->next;
cntPtr->address = cnt;
cntPtr->name = (char*)malloc(sizeof(char*)*(strlen(c) + 1));
strcpy(cntPtr->name, c);
cntPtr->rowType = rc;
cntPtr->next = NULL;
}
void InsertDataOrString(int cnt, int n)
{
struct dataNode* cntPtr = headDataList;
while (cntPtr->next)
cntPtr = cntPtr->next;
cntPtr->next = (struct dataNode*)malloc(sizeof(struct dataNode));
cntPtr = cntPtr->next;
cntPtr->address = cnt;
cntPtr->data = n;
cntPtr->next = NULL;
} |
C | #include <std.h>
#include <new_exp_table.h>
inherit OBJECT;
int TAR;
string *unlocked_to, *recorded;
string MYQUEST = "%^BOLD%^%^WHITE%^Achieved: %^BOLD%^%^CYAN%^Expanded The "+
"Cube of %^CYAN%^I%^WHITE%^nf%^CYAN%^"+
"i%^WHITE%^n%^CYAN%^i%^WHITE%^t%^CYAN%^e %^WHITE%^Kn%^CYAN%^"+
"owl%^WHITE%^edge%^RESET%^";
void create()
{
::create();
set_name("strange cube");
set_id(({"cube", "strange cube", "warped cube", "magical cube",
"dimensional cube", "cube of infinite knowledge", "knowledge cube"}));
set_short("%^BOLD%^%^WHITE%^Cube of %^CYAN%^I%^WHITE%^nf%^CYAN%^"+
"i%^WHITE%^n%^CYAN%^i%^WHITE%^t%^CYAN%^e %^WHITE%^Kn%^CYAN%^"+
"owl%^WHITE%^edge%^RESET%^");
set_obvious_short("strange cube");
set_long("%^BOLD%^%^WHITE%^This strange cube is composed from a "+
"silver material. It is very sturdy and no amount of pressure seems to have "+
"any impact on it. There are elaborate %^BOLD%^%^CYAN%^symbols%^BOLD%^%^WHITE%^"+
" carved into each side of it. The symbols depict books, scrolls, and the knowledge "+
"contained within them. However, they offer no hint at what that knowledge might be or "+
"anyway in which it might be accessed. A profoundly powerful magical aura is being "+
"given off by the cube, it is almost overwhelming.%^RESET%^");
set_lore("%^BOLD%^%^WHITE%^This cube was a recent creation by a man named "+
"Dygarius Elwood. Dygarius wanted to create a way to document all the knowledge "+
"hidden through the realm, so he created this cube with the intention of using it "+
"to absorb knowledge about items and creatures found through out the world. "+
"It is rumored that he also locked the cube in such a way that only one who he thought"+
" to %^CYAN%^bestow%^WHITE%^ access to could use it. If one were granted such access "+
"he or she could use the cube to %^CYAN%^record%^WHITE%^ information about an item "+
"or a creature. It is also rumored that the cube would only record information about "+
"magical items or strange creatures that are not typically found wandering the "+
"safe streets that Dygarius himself has been known to wander.%^RESET%^");
set_property("lore difficulty", 10);
set_value(10000);
set_weight(1);
recorded = ({});
unlocked_to = ({"dygarius"});
TAR = 100;
}
void init()
{
::init();
add_action("bestow","bestow");
add_action("record", "record");
}
void check_recorded()
{
int y, perc, myExp, lvl;
if(!objectp(TO)) return;
if(!objectp(ETO)) return;
if(!living(ETO)) return;
if(!objectp(EETO)) return;
if(member_array(ETO->query_true_name(), unlocked_to) == -1) return;
y = sizeof(recorded);
perc = percent(y, TAR);
switch(perc)
{
case 0..10:
tell_object(ETO, "%^BOLD%^%^WHITE%^The knowledge within the cube "+
"is still miniscule compared what it is capable of understanding."+
"%^RESET%^");
return 1;
case 11..25:
tell_object(ETO, "%^BOLD%^%^WHITE%^The knowledge within the cube "+
"is continuing to expand, but it still far from reaching capacity."+
"%^RESET%^");
return 1;
case 26..50:
tell_object(ETO, "%^BOLD%^%^WHITE%^The knowledge within the cube "+
"continus to expand, approaching the half-way point of what it is "+
"able to contain.%^RESET%^");
return 1;
case 51..75:
tell_object(ETO, "%^BOLD%^%^WHITE%^The knowledge within the cube "+
"grows closer to its apex.%^RESET%^");
return 1;
case 76..99:
tell_object(ETO, "%^BOLD%^%^WHITE%^The knowledge within the cube "+
"grows ever closer to its apex!%^RESET%^");
return 1;
case 100..200:
tell_object(ETO, "%^BOLD%^%^WHITE%^You feel the powerful aura of magic "+
"from the cube wash over you and you feel your mind flooded with knowledge!");
lvl = (int)ETO->query_character_level();
if(lvl < sizeof(EXP_NEEDED) && (lvl-1) < sizeof(EXP_NEEDED)) myExp = EXP_NEEDED[lvl] - EXP_NEEDED[(lvl-1)];
else myExp = 100000;
myExp / 2;
if(member_array(MYQUEST, (string *)ETO->query_mini_quests()) == -1)
{
ETO->set_mini_quest(MYQUEST, myExp, MYQUEST);
tell_object(ETO, "%^BOLD%^%^WHITE%^You feel more experienced!%^RESET%^");
tell_object(ETO, "%^BOLD%^%^WHITE%^You have gained the innate ability to "+
"cure moderate wounds!%^RESET%^");
ETO->add_bonus_innate((["cure moderate wounds" : (["type" : "spell", "casting level" : 10,
"daily uses" : 2, "delay" : 1, "uses left" : 2]),]));
}
tell_object(ETO, "%^BOLD%^%^WHITE%^The cube vanishes in an explosion of "+
"harmless but %^BOLD%^%^YELLOW%^c%^MAGENTA%^o%^CYAN%^l%^BLACK%^o%^WHITE%^r"+
"%^YELLOW%^f%^MAGENTA%^u%^CYAN%^l %^WHITE%^light!%^RESET%^");
tell_room(EETO, ETOQCN+"%^BOLD%^%^WHITE%^'s cube vanishes in an explosion of "+
"harmless but %^BOLD%^%^YELLOW%^c%^MAGENTA%^o%^CYAN%^l%^BLACK%^o%^WHITE%^r"+
"%^YELLOW%^f%^MAGENTA%^u%^CYAN%^l %^WHITE%^light!%^RESET%^", ETO);
TO->remove();
return 1;
}
return;
}
int bestow(string str)
{
object targ;
string myName, theirName;
if(!objectp(TO)) return 0;
if(!objectp(ETO)) return 0;
if(!objectp(EETO)) return 0;
myName = ETO->query_name();
if(member_array(myName, unlocked_to) == -1) return 0;
if(!str)
{
tell_object(ETO, "%^BOLD%^%^RED%^Who do you wish to "+
"bestow access to?");
return 1;
}
if(!objectp(targ = present(str, EETO)))
{
tell_object(ETO, "%^BOLD%^%^RED%^There is no one by "+
"the name "+str+" here.");
return 1;
}
if(!userp(targ))
{
tell_object(ETO, "%^BOLD%^%^RED%^You cannot bestow access to "+
"the cube to "+targ->QCN+".");
return 1;
}
theirName = targ->query_true_name();
if(member_array(theirName, unlocked_to) != -1)
{
tell_object(TP, targ->QCN+"%^BOLD%^%^RED%^ already has access "+
"to the cube.%^RESET%^");
return 1;
}
tell_object(ETO, "%^BOLD%^%^WHITE%^You focus intently on "+
targ->QCN+" and bestow access to the cube to "+targ->QO+"!");
tell_object(targ, ETOQCN+"%^BOLD%^%^WHITE%^ focuses intently on "+
"you and you feel your knowledge expand as "+ETO->QS+" bestows access "+
"to "+ETO->QP+" cube to you.%^RESET%^");
tell_room(EETO, ETOQCN+"%^BOLD%^%^WHITE%^ focuses intently on "+
targ->QCN+"!%^RESET%^", ({targ, ETO}));
unlocked_to += ({theirName});
return 1;
}
int record(string str)
{
object targ;
string myName, fileName;
if(!objectp(TO)) return 0;
if(!objectp(ETO)) return 0;
if(!objectp(EETO)) return 0;
myName = ETO->query_name();
if(member_array(myName, unlocked_to) == -1) return 0;
if(!str)
{
tell_object(ETO, "%^BOLD%^%^RED%^What do you wish to "+
"use the cube to record?%^RESET%^");
return 1;
}
if(!objectp(targ = present(str, ETO)))
{
if(!objectp(targ = present(str, EETO)))
{
tell_object(ETO, "%^BOLD%^%^RED%^There is no "+str+
" here.%^RESET%^");
return 1;
}
}
if(targ == TO || base_name(targ) == base_name(TO))
{
tell_object(ETO, "%^BOLD%^%^RED%^The cube will not record "+
"information about itself.%^RESET%^");
return 1;
}
if(userp(targ))
{
tell_object(ETO, "%^BOLD%^%^RED%^The cube warms to your touch "+
"for a brief instant but fails to record anything...%^RESET%^");
return 1;
}
fileName = base_name(targ);
if(!pointerp(recorded)) recorded = ({});
if(member_array(fileName, recorded) != -1)
{
tell_object(ETO, "%^BOLD%^%^RED%^The cube warms to your touch "+
"for a brief instant but does nothing, as it has already recorded "+
"information about "+targ->QCN+"!%^RESET%^");
return 1;
}
if(living(targ))
{
if(targ->is_townsman() && targ->is_npc())
{
tell_object(ETO, "%^BOLD%^%^RED%^The cube warms to your touch "+
"for a brief instant but fails to record anything...%^RESET%^");
return 1;
}
tell_object(ETO, "%^BOLD%^%^WHITE%^You focus on the cube and "+
targ->QCN+" carefully, allowing the cube to record information "+
"about "+targ->QCN+"!%^RESET%^");
tell_object(targ, ETOQCN+"%^BOLD%^%^WHITE%^ starts focusing on "+
ETO->QP+" cube and you intently... you feel something invisible probing "+
"your mind for a brief instant... it does not feel intrusive.. before it "+
"fades away.%^RESET%^");
tell_room(EETO, ETOQCN+"%^BOLD%^%^WHITE%^ starts focusing on "+
ETO->QP+" cube and "+targ->QCN+" intently, as "+targ->QCN+" seems "+
"momentarily perplexed!%^RESET%^", ({targ, ETO}));
recorded += ({fileName});
check_recorded();
return 1;
}
if(!targ->isMagic())
{
tell_object(ETO, "%^BOLD%^%^RED%^The cube warms to your touch "+
"for a brief instant but does nothing.%^RESET%^");
return 1;
}
tell_object(ETO, "%^BOLD%^%^WHITE%^You focus on the cube and "+
targ->QCN+" carefully, allowing the cube to record information "+
"about "+targ->QCN+"!%^RESET%^");
tell_room(EETO, ETOQCN+"%^BOLD%^%^WHITE%^ starts focusing on "+
ETO->QP+" cube and "+targ->QCN+" intently!%^RESET%^", ({ETO}));
recorded += ({fileName});
check_recorded();
return 1;
}
|
C | /* Author: Dishank Goel
* Date written: 21st August 2020
*
* mv.c implements the `mv` command in UNIX without any options
* mv either renames the file to a new file, or moves a file or directory into another directory
* Usage: ./mv SOURCE DESTINATION
* or: mv SOURCE(s) DIRECTORY
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <dirent.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
#include "util.h"
/* move - given an old file [old], and a new destination [new] (either new name or existing directory)
* either renames the old file to new name, or moves it into the directory
* n is check_dir status for the new file, check util.h for check_dir return status
*/
int move(char *old, char *new, int n) {
int result;
if(n && n != -1) { // New file is directory
char *new_path;
new_path = make_path(new, old); // the new path will be inside the new folder with old name
result = rename(old, new_path); // renames the old file to new path
if(result == 0) {
return 0;
} else {
fprintf(stderr, "mv: cannot move '%s' to '%s': %s\n", old, new_path, strerror(errno));
return -1;
}
}else { // New path is not a directory, so it either a new name, or existing file
result = rename(old, new); // overwrites the new file if it already exists
if(result == 0) {
return 0;
} else {
fprintf(stderr, "mv: cannot move '%s' to '%s': %s\n", old, new, strerror(errno));
return -1;
}
}
}
int main(int argc, char *argv[]) {
if(argc < 3) {
fprintf(stderr, "mv: missing operands\n");
printf("Usage: mv SOURCE DESTINATION\n");
printf("or: mv SOURCE(s) DIRECTORY\n");
printf("A utility to Rename source to destination, or Move source(s) to directory\n");
exit(EXIT_FAILURE);
} else if(argc == 3) { // if only ./mv OLD NEW is given, then NEW can be a file or directory
int n = check_dir(argv[2]);
move(argv[1], argv[2], n);
} else {
int n = check_dir(argv[argc - 1]);
if(n && n != -1) { // if there are >2 arguments, then the last has to be a directory
for(int i = 1; i < argc - 1; i++) {
move(argv[i], argv[argc - 1], n);
}
} else {
fprintf(stderr, "mv: target '%s' is not a directory\n", argv[argc - 1]);
exit(EXIT_FAILURE);
}
}
exit(EXIT_SUCCESS);
} |
C | //
// Project: KTRW
// Author: Brandon Azad <[email protected]>
//
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#ifndef LOG__H_
#define LOG__H_
#include <stdarg.h>
#include <stdio.h>
/*
* log_implementation
*
* Description:
* This is the log handler that will be executed when code wants to log a message. The default
* implementation logs the message to stderr. Setting this value to NULL will disable all
* logging. Specify a custom log handler to process log messages in another way.
*
* Parameters:
* type A character representing the type of message that is being
* logged.
* format A printf-style format string describing the error message.
* ap The variadic argument list for the format string.
*
* Log Type:
* The type parameter is one of:
* - D: Debug: Used for debugging messages. Set the DEBUG build variable to control debug
* verbosity.
* - I: Info: Used to convey general information about the exploit or its progress.
* - W: Warning: Used to indicate that an unusual but possibly recoverable condition was
* encountered.
* - E: Error: Used to indicate that an unrecoverable error was encountered. The code
* might continue running after an error was encountered, but it probably will
* not succeed.
*/
extern void (*log_implementation)(char type, const char *format, va_list ap);
#define DEBUG_LEVEL(level) (DEBUG && level <= DEBUG)
#if DEBUG
#define DEBUG_TRACE(level, fmt, ...) \
do { \
if (DEBUG_LEVEL(level)) { \
log_internal('D', fmt, ##__VA_ARGS__); \
} \
} while (0)
#else
#define DEBUG_TRACE(level, fmt, ...) do {} while (0)
#endif
#define INFO(fmt, ...) log_internal('I', fmt, ##__VA_ARGS__)
#define WARNING(fmt, ...) log_internal('W', fmt, ##__VA_ARGS__)
#define ERROR(fmt, ...) log_internal('E', fmt, ##__VA_ARGS__)
// A function to call the logging implementation.
void log_internal(char type, const char *format, ...) __printflike(2, 3);
#endif
|
C | #include "animator_component.h"
void AnimatorBehaviour(struct Component *selfComponent, struct Game *game)
{
struct AnimatorComponent *animatorComponent = (struct AnimatorComponent*)selfComponent->data;
if (animatorComponent->currentAnimation.frames <= 1) //if an asshole has created an animation spritesheet with 1 or less frames...
return;
struct RenderComponent *renderComponent = (struct RenderComponent*)GetComponentData(selfComponent->owner, RenderC);
animatorComponent->timeElapsed += game->engine->time->deltaTimeInSeconds;
if (animatorComponent->timeElapsed >= animatorComponent->frameDuration)
{
animatorComponent->timeElapsed = 0;
animatorComponent->currentFrameIndex++;
if (animatorComponent->currentFrameIndex >= animatorComponent->currentAnimation.frames)
animatorComponent->currentFrameIndex = 0;
renderComponent->sprite.originRect.x = animatorComponent->currentFrameIndex * animatorComponent->currentAnimation.frameWidth;
}
}
//Set the animation to perform on the given animator component.
//If you also want to alter the frame duration of the spritesheet, pass a value > 0.
void SetAnimation(struct Component *selfComponent, AnimationType type, float frameDuration)
{
struct AnimatorComponent *animatorComponent = selfComponent->data;
struct RenderComponent *renderComponent = GetComponentData(selfComponent->owner, RenderC);
animatorComponent->currentAnimation = GetAnimation(animatorComponent->engine, type);
animatorComponent->frameDuration = animatorComponent->currentAnimation.baseFrameDuration;
animatorComponent->timeElapsed = 0;
animatorComponent->currentFrameIndex = 0;
if (frameDuration > 0)
animatorComponent->frameDuration = frameDuration;
renderComponent->sprite.texture = animatorComponent->currentAnimation.texture;
renderComponent->sprite.originRect.w = animatorComponent->currentAnimation.frameWidth;
renderComponent->sprite.originRect.h = animatorComponent->currentAnimation.frameHeight;
renderComponent->sprite.originRect.x = animatorComponent->currentFrameIndex * animatorComponent->currentAnimation.frameWidth;
struct TransformComponent* tc = GetComponentData(selfComponent->owner, TransformC);
renderComponent->sprite.spriteRect.w = animatorComponent->currentAnimation.frameWidth * tc->scale.x;
renderComponent->sprite.spriteRect.h = animatorComponent->currentAnimation.frameHeight * tc->scale.y;
}
void InitAnimatorComponent(struct Component *selfComponent, struct GFXEngine *engine, AnimationType animationType, float frameDuration, void (*SetAnimation)(struct Component *selfComponent, AnimationType type, float frameDuration))
{
struct AnimatorComponent *animatorComponent = selfComponent->data;
animatorComponent->engine = engine;
animatorComponent->SetAnimation = SetAnimation;
animatorComponent->SetAnimation(selfComponent, animationType, frameDuration);
} |
C | /**
\file sumup_loop_up.C
\mainpage The sumup_loop plotting routine.
\brief A flexible plotting program.
The program defines a set of objects (functions, struct-s, map-s, vectors etc)
to be used in the construction of the event loop in the `main` function.
These objects basically define the information about the input datasets,
distributions to record, systematics to apply etc.
They correspond to the old `std_defs.py` module.
The `main` function operates on the defined objects and consists of 3 parts:
1. parsing user's input and filling up the data structures operating the event loop
2. the event loop
3. application of final systematic corrections and normalizations to the recorded histograms and writing the output.
# Naming style
The beginning of the `typedef` names has 1 capital letter mnemonic for the defined type: S for struct, F for function, T for any other type.
The names starting with underscore, such as `_TH1D_histo_def` are not intendet to be used in `main` directly.
The collections of definitions for `main` start with `known_`, like `known_dtags_info`.
The corresponding functions defining these collections start with `create_known_`, like `create_known_dtags_info`.
Now, the names of the functions operating in the namespace of the interface of the TTree, i.e. on variables like `NT_event_leptons`,
start with `NT_` like `NT_distr_leading_lep_pt`.
In future we may try to separate them in an altogether different namespace,
with a separate function to connect an input TTree to that namespace etc.
*/
#include <iostream>
#include "TSystem.h"
#include "TFile.h"
#include "TTree.h"
#include "TCanvas.h"
#include "TLegend.h"
#include "THStack.h"
#include "TH1F.h"
#include "TH2F.h"
#include "TH3F.h"
#include "TProfile.h"
#include "TProfile2D.h"
#include "TEventList.h"
#include "TROOT.h"
#include "TNtuple.h"
#include <Math/VectorUtil.h>
#include "TMath.h" // Cos
#include <map>
#include <string>
#include <vector>
#include <stdlib.h> // abort
#include "UserCode/proc/interface/handy_macros.h"
#include "UserCode/proc/interface/sumup_loop_ntuple.h"
#include "UserCode/proc/interface/ntuple_stage2.h"
#include "UserCode/proc/interface/ntuple_ntupler.h"
// the ntuple interface declarations
// to be connected to one of the ntuple_ interfaces in main
T_known_defs_systs known_systematics;
T_known_defs_channels known_defs_channels;
T_known_defs_distrs known_defs_distrs;
T_known_defs_procs known_procs_info;
T_known_MC_normalization_per_somename known_normalization_per_syst;
T_known_MC_normalization_per_somename known_normalization_per_proc;
T_known_MC_normalization_per_somename known_normalization_per_chan;
//typedef int (*F_connect_ntuple_interface)(TTree*);
F_connect_ntuple_interface connect_ntuple_interface;
// -----
using namespace std;
// TODO: turn these into arguments for main
bool do_not_overwrite = true;
bool normalise_per_weight = true;
/* --------------------------------------------------------------- */
/* main structure of the event loop
// the struct-s of the structure of the event loop
// since systematics affect event selection (final state channel) and distributions
// they must be up the hierarchy
// process definition is purely gen-level, independent from reco
// it can be the top-most level for a dtag
// but in daily usage we usually hadd everything, open a final state and look at distributions in the same or different processes.
// Ok, purely for the sake of symmetry and easy memorization, let's just revert the nesting w.r.t the usual one:
SYSTEMATIC / PROCESS / CHANNEL / channel_process_systematic_distrname
*/
/** \brief An instance of an output histogram.
The function calculating the parameter, the `TH1D*` to the histogram object, the current calculated value (placeholder for future memoization).
*/
typedef struct {
string main_name;
TH1D* histo;
double (*func)(ObjSystematics);
double value;
} TH1D_histo;
typedef struct{
string name; /**< \brief keep the name of this process to assign final per-proc normalization */
_F_genproc_def proc_def; /**< \brief `bool` function defining whether an event passes this gen proc definition */
vector<TH1D_histo> histos; /**< \brief the distributions to record */
} T_proc_histos;
typedef struct{
string name; /**< \brief keep the name of this process to assign final per-channel normalization */
_S_chan_def chan_def; /**< \brief channel definition: `bool` function selecting events, and the nominal event weight funciton */
vector<T_proc_histos> procs; /**< \brief the channels with distributions to record */
string name_catchall_proc; /**< \brief the name of the catchall processes */
vector<TH1D_histo> catchall_proc_histos; /**< \brief the channels with distributions to record in the catchall process */
} T_chan_proc_histos;
typedef struct{
string name; /**< \brief keep the name of this process to assign final per-systematic normalization */
_S_systematic_definition syst_def; /**< \brief the definition of a given systematic */
vector<T_chan_proc_histos> chans; /**< \brief the per-proc channels with distributions to record */
} T_syst_chan_proc_histos;
/** \brief A helper function creating the instances of TH1D_histos with a specific name from the given _TH1D_histo_def definition.
Creates a `new TH1D(name, ..., range)` according to the linear or custom range in the _TH1D_histo_def definition.
\param _TH1D_histo_def& def
\param TString name
\return TH1D_histo
*/
TH1D_histo create_TH1D_histo(_TH1D_histo_def& def, TString name, string main_name)
{
TH1D* histo;
if (def.range.linear)
{
//cout << "making linear bins histogram " << endl;
histo = (TH1D*) new TH1D(name, name, def.range.nbins, def.range.linear_min, def.range.linear_max);
}
else
{
//cout << "making custom bins histogram " << def.range.nbins << " " << def.range.custom_bins << endl;
histo = (TH1D*) new TH1D(name, name, def.range.nbins, def.range.custom_bins);
//cout << "making custom bins histogram DONW" << endl;
}
//TH1D_histo a_distr = {ahist, def.func, 0.};
//distrs.push_back(a_distr);
return {main_name, histo, def.func, 0.};
}
/* --------------------------------------------------------------- */
// dtag info -- move to yet another src file
typedef struct {
double cross_section;
double usual_gen_lumi;
_S_proc_ID_defs std_procs;
vector<TString> std_systs;
// all available systematics
} S_dtag_info;
double W_lep_br = 0.108;
double W_alllep_br = 3*0.108;
double W_qar_br = 0.676;
double W_lep_br2 = W_lep_br*W_lep_br;
double W_alllep_br2 = W_alllep_br*W_alllep_br;
double W_qar_br2 = W_qar_br*W_qar_br;
double br_tau_electron = 0.1785;
double br_tau_muon = 0.1736;
double br_tau_lepton = br_tau_electron + br_tau_muon;
double br_tau_hadronic = 1. - br_tau_lepton;
double ttbar_xsec = 831.76; // at 13 TeV
map<TString, S_dtag_info> create_known_dtags_info(T_known_defs_procs known_procs_info)
{
//map<const char*, S_dtag_info> m;
map<TString, S_dtag_info> m;
m["MC2017_Fall17_WJetsToLNu_13TeV" ] = {.cross_section= 52940. ,
.usual_gen_lumi= 23102470.188817,
.std_procs = known_procs_info["wjets"],
.std_systs = {SYSTS_OTHER_MC}};
m["MC2016_Summer16_WJets_madgraph" ] = {.cross_section= 52940. ,
.usual_gen_lumi= 23102470.188817,
.std_procs = known_procs_info["wjets"],
.std_systs = {SYSTS_OTHER_MC}};
m["MC2016_Summer16_W1Jets_madgraph" ] = {.cross_section= 9493. ,
.usual_gen_lumi= 23102470.188817,
.std_procs = known_procs_info["wjets"],
.std_systs = {SYSTS_OTHER_MC}};
m["MC2016_Summer16_W2Jets_madgraph" ] = {.cross_section= 3120. ,
.usual_gen_lumi= 23102470.188817,
.std_procs = known_procs_info["wjets"],
.std_systs = {SYSTS_OTHER_MC}};
m["MC2016_Summer16_W3Jets_madgraph" ] = {.cross_section= 942.29999999999995 ,
.usual_gen_lumi= 23102470.188817,
.std_procs = known_procs_info["wjets"],
.std_systs = {SYSTS_OTHER_MC}};
m["MC2016_Summer16_W4Jets_madgraph" ] = {.cross_section= 524.20000000000005 ,
.usual_gen_lumi= 23102470.188817,
.std_procs = known_procs_info["wjets"],
.std_systs = {SYSTS_OTHER_MC}};
m["MC2016_Summer16_QCD_HT-100-200" ] = {.cross_section= 27540000 / 0.131 ,
.usual_gen_lumi= 23102470.188817,
.std_procs = known_procs_info["qcd"],
.std_systs = {SYSTS_QCD_MC}};
m["MC2016_Summer16_QCD_HT-200-300" ] = {.cross_section= 1717000 / 0.098 ,
.usual_gen_lumi= 23102470.188817,
.std_procs = known_procs_info["qcd"],
.std_systs = {SYSTS_QCD_MC}};
m["MC2016_Summer16_QCD_HT-300-500" ] = {.cross_section= 351300 / (0.088 * 100) ,
.usual_gen_lumi= 23102470.188817,
.std_procs = known_procs_info["qcd"],
.std_systs = {SYSTS_QCD_MC}};
m["MC2016_Summer16_QCD_HT-500-700" ] = {.cross_section= 31630 / (0.067 * 2) ,
.usual_gen_lumi= 23102470.188817,
.std_procs = known_procs_info["qcd"],
.std_systs = {SYSTS_QCD_MC}};
m["MC2016_Summer16_QCD_HT-700-1000" ] = {.cross_section= 6802 / (0.066 * 2) ,
.usual_gen_lumi= 23102470.188817,
.std_procs = known_procs_info["qcd"],
.std_systs = {SYSTS_QCD_MC}};
m["MC2016_Summer16_QCD_HT-1000-1500" ] = {.cross_section= 1206 * 10 / 0.059 ,
.usual_gen_lumi= 23102470.188817,
.std_procs = known_procs_info["qcd"],
.std_systs = {SYSTS_QCD_MC}};
m["MC2016_Summer16_QCD_HT-1500-2000" ] = {.cross_section= 120.4 / 0.067 ,
.usual_gen_lumi= 23102470.188817,
.std_procs = known_procs_info["qcd"],
.std_systs = {SYSTS_QCD_MC}};
m["MC2016_Summer16_QCD_HT-2000-Inf" ] = {.cross_section= 25.25 / 0.07 ,
.usual_gen_lumi= 23102470.188817,
.std_procs = known_procs_info["qcd"],
.std_systs = {SYSTS_QCD_MC}};
// there is also MC2016_Summer16_DYJetsToLL_10to50_amcatnlo but it is not important
m["MC2017legacy_Fall17_DYJetsToLL_50toInf_madgraph" ] = {.cross_section= 6225.42 ,
.usual_gen_lumi= 18928303.971956,
.std_procs = known_procs_info["dy"],
.std_systs = {SYSTS_OTHER_MC}};
m["MC2016_Summer16_DYJetsToLL_50toInf_madgraph" ] = {.cross_section= 6225.42 ,
.usual_gen_lumi= 18928303.971956,
.std_procs = known_procs_info["dy"],
.std_systs = {SYSTS_OTHER_MC}};
m["MC2017legacy_Fall17_SingleT_tW_5FS_powheg" ] = {.cross_section= 35.6 ,
.usual_gen_lumi= 5099879.048270,
.std_procs=known_procs_info["stop"],
.std_systs = {SYSTS_OTHER_MC}};
m["MC2016_Summer16_SingleT_tW_5FS_powheg" ] = {.cross_section= 35.6 ,
.usual_gen_lumi= 5099879.048270,
.std_procs=known_procs_info["stop"],
.std_systs = {SYSTS_OTHER_MC}};
m["MC2017legacy_Fall17_SingleTbar_tW_5FS_powheg" ] = {.cross_section= 35.6 ,
.usual_gen_lumi= 2349775.859249,
.std_procs=known_procs_info["stop"],
.std_systs = {SYSTS_OTHER_MC}};
m["MC2016_Summer16_SingleTbar_tW_5FS_powheg" ] = {.cross_section= 35.6 ,
.usual_gen_lumi= 2349775.859249,
.std_procs=known_procs_info["stop"],
.std_systs = {SYSTS_OTHER_MC}};
m["MC2017_Fall17_TTToHadronic_13TeV" ] = {.cross_section= 831.76 * W_qar_br2 ,
.usual_gen_lumi= 29213134.729453,
.std_procs=known_procs_info["tt"],
.std_systs = {SYSTS_TT}};
m["MC2017_Fall17_TTToSemileptonic_13TeV" ] = {.cross_section= 831.76 * 2*W_alllep_br*W_qar_br ,
.usual_gen_lumi= 21966343.919990,
.std_procs=known_procs_info["tt"],
.std_systs = {SYSTS_TT}};
m["MC2017_Fall17_TTTo2L2Nu" ] = {.cross_section= 831.76 * W_alllep_br2 ,
.usual_gen_lumi= 2923730.883332,
.std_procs=known_procs_info["tt"],
.std_systs = {SYSTS_TT}};
m["MC2016_Summer16_TTJets_powheg" ] = {.cross_section= 831.76 ,
.usual_gen_lumi= 1.,
.std_procs = known_procs_info["tt"],
.std_systs = {SYSTS_TT}};
// I probably need some defaults for not found dtags
// TODO: for now enter Data as any MC
m["Data2017legacy" ] = {.cross_section= 1. ,
.usual_gen_lumi= 1.,
.std_procs = known_procs_info["data"],
.std_systs = {"NOMINAL"}};
// the 2016 cross section analysis
m["Data13TeV_SingleElectron2016" ] = {.cross_section= 1. ,
.usual_gen_lumi= 1.,
.std_procs = known_procs_info["data"],
.std_systs = {"NOMINAL"}};
m["Data13TeV_SingleMuon2016" ] = {.cross_section= 1. ,
.usual_gen_lumi= 1.,
.std_procs = known_procs_info["data"],
.std_systs = {"NOMINAL"}};
/* there are more:
MC2016_Summer16_DYJetsToLL_10to50_amcatnlo MC2016_Summer16_QCD_HT-200-300 MC2016_Summer16_W1Jets_madgraph MC2016_Summer16_WJets_madgraph MC2016_Summer16_ZZTo2L2Nu_powheg
MC2016_Summer16_DYJetsToLL_10to50_amcatnlo_v1_ext1 MC2016_Summer16_QCD_HT-2000-Inf MC2016_Summer16_W2Jets_madgraph MC2016_Summer16_WJets_madgraph_ext2_v1 MC2016_Summer16_ZZTo2L2Q_amcatnlo_madspin
MC2016_Summer16_DYJetsToLL_10to50_amcatnlo_v2 MC2016_Summer16_QCD_HT-300-500 MC2016_Summer16_W2Jets_madgraph_ext1 MC2016_Summer16_WWTo2L2Nu_powheg MC2016_Summer16_schannel_4FS_leptonicDecays_amcatnlo
MC2016_Summer16_DYJetsToLL_50toInf_madgraph MC2016_Summer16_QCD_HT-500-700 MC2016_Summer16_W3Jets_madgraph MC2016_Summer16_WWToLNuQQ_powheg MC2016_Summer16_tchannel_antitop_4f_leptonicDecays_powheg
MC2016_Summer16_DYJetsToLL_50toInf_madgraph_ext2_v1 MC2016_Summer16_QCD_HT-700-1000 MC2016_Summer16_W3Jets_madgraph_ext1 MC2016_Summer16_WZTo1L1Nu2Q_amcatnlo_madspin MC2016_Summer16_tchannel_top_4f_leptonicDecays_powheg
MC2016_Summer16_QCD_HT-100-200 MC2016_Summer16_SingleT_tW_5FS_powheg MC2016_Summer16_W4Jets_madgraph MC2016_Summer16_WZTo1L3Nu_amcatnlo_madspin
MC2016_Summer16_QCD_HT-1000-1500 MC2016_Summer16_SingleTbar_tW_5FS_powheg MC2016_Summer16_W4Jets_madgraph_ext1 MC2016_Summer16_WZTo2L2Q_amcatnlo_madspin
MC2016_Summer16_QCD_HT-1500-2000 MC2016_Summer16_TTJets_powheg MC2016_Summer16_W4Jets_madgraph_ext2 MC2016_Summer16_WZTo3LNu_powheg
*/
return m;
}
// ----------------- dtag info
/* it was used for tau ID uncertainty, which is implemented per-channel now
TODO: remove if this system is absolutely not needed
double rogue_mixed_corrections(const TString& name_syst, const TString& name_chan, const TString& name_proc)
{
double correction = 1.;
// tau ID correction
// apply it in channels with a selected tau
// to processes with genuine taus
// TODO: it probably must be done via event weight in stage2
double tau_ID_correction = 0.95;
set<TString> tau_channels = {"mu_sel", "el_sel", "mu_sel_ss", "el_sel_ss", "mu_selSV", "el_selSV", "mu_selSV_ss", "el_selSV_ss", "dy_mutau", "ctr_old_mu_sel", "ctr_old_mu_sel", "ctr_old_el_sel", "optel_tight_2L1M", "optmu_tight_2L1M"};
set<TString> tau_processes = {"tt_mutau3ch", "tt_eltau3ch", "tt_mutau", "tt_eltau", "tt_taultauh", "dy_tautau", "s_top_eltau", "s_top_mutau"};
if ((tau_channels.find(name_chan) != tau_channels.end()) && (tau_processes.find(name_proc) != tau_processes.end()))
correction *= tau_ID_correction;
return correction;
}
*/
// --------- final normalizations
// normalization per gen lumi event weight
TH1D* weight_counter = NULL;
// per dtag cross section -- make it a commandline option if you want
bool normalise_per_cross_section = true;
void normalise_final(TH1D* histo, double cross_section, double scale, const TString& name_syst, const TString& name_chan, const TString& name_proc)
{
if (normalise_per_weight)
histo->Scale(1./weight_counter->GetBinContent(2));
if (normalise_per_cross_section)
histo->Scale(cross_section);
/* per-syst/proc/chan systematic corrections
*/
double per_syst_factor = (name_syst == "NOMINAL" || known_normalization_per_syst.find(name_syst) == known_normalization_per_syst.end()) ? known_normalization_per_syst["NOMINAL"] :
(name_syst == "PUUp" || name_syst == "PUDown" ? known_normalization_per_syst[name_syst] : known_normalization_per_syst["NOMINAL"] * known_normalization_per_syst[name_syst]);
double per_proc_factor = known_normalization_per_proc.find(name_proc) == known_normalization_per_proc.end() ?
1. :
known_normalization_per_proc[name_proc];
double per_chan_factor = known_normalization_per_chan.find(name_chan) == known_normalization_per_chan.end() ?
1. :
known_normalization_per_chan[name_chan];
//double rogue_mixed_correction = rogue_mixed_corrections(name_syst, name_chan, name_proc);
histo->Scale(scale * per_syst_factor * per_proc_factor * per_chan_factor /* * rogue_mixed_correction*/);
}
/* --------------------------------------------------------------- */
/** \brief parse char* coma-separated string into vector<TString>
*/
vector<TString> parse_coma_list(char* coma_list)
{
vector<TString> list;
// the input is so simple, we can just substitute , for \0 and set up char* array
// ok, lets parse with strtok and push_back into a vector
char delimeter[] = ",";
char* txt;
char* scratch;
txt = strtok_r(coma_list, delimeter, &scratch);
list.push_back(TString(txt));
while ((txt = strtok_r(NULL, delimeter, &scratch)))
list.push_back(TString(txt));
return list;
}
/** \brief generate a tree with the record histograms from requested systematics, channels, processes, and histograms
\return vector<T_syst_chan_proc_histos>
*/
vector<T_syst_chan_proc_histos> setup_record_histos(
S_dtag_info& main_dtag_info,
vector<TString>& requested_systematics,
vector<TString>& requested_channels ,
vector<TString>& requested_procs ,
vector<TString>& requested_distrs )
{
// the output tree
vector<T_syst_chan_proc_histos> distrs_to_record;
// some info for profiling
int n_systs_made = 0, n_chans_made = 0, n_procs_made = 0, n_distrs_made = 0;
// final state channels
vector<TString> requested_channels_all = {
"el_sel",
"mu_sel",
"el_sel_ss",
"mu_sel_ss",
"el_sel_tauSV3",
"mu_sel_tauSV3",
"el_sel_ss_tauSV3",
"mu_sel_ss_tauSV3",
"tt_elmu",
"tt_elmu_tight",
"dy_mutau",
"dy_mutau_ss",
"dy_eltau",
"dy_eltau_ss",
"dy_mutau_tauSV3",
"dy_mutau_ss_tauSV3",
"dy_eltau_tauSV3",
"dy_eltau_ss_tauSV3",
"dy_elmu",
"dy_elmu_ss",
"dy_mumu",
"dy_elel"};
if (requested_channels[0] == "all")
requested_channels = requested_channels_all;
//const char* requested_channel_names[] = {"tt_elmu", NULL};
//vector<TString> requested_procs = {"all"};
//vector<TString> requested_procs = {"std"};
vector<TString> requested_systematics_test = {"NOMINAL",
"JERUp",
"JERDown",
"JESUp",
"JESDown",
"TESUp",
"TESDown",
"PUUp",
"PUDown",
"bSFUp",
"bSFDown",
"LEPelIDUp",
"LEPelIDDown",
"LEPelTRGUp",
"LEPelTRGDown",
"LEPmuIDUp",
"LEPmuIDDown",
"LEPmuTRGUp",
"LEPmuTRGDown",
};
if (requested_systematics[0] == "test")
requested_systematics = requested_systematics_test;
else if (requested_systematics[0] == "std")
requested_systematics = main_dtag_info.std_systs;
//requested_systematics[0] = "NOMINAL"; requested_systematics[1] = NULL;
//const char* requested_distrs[] = {"Mt_lep_met_c", "leading_lep_pt", NULL};
// set the known processes according to the request: whetehr groups of processes are requested or not
// check if all known processes are requested
map<TString, _F_genproc_def> known_procs;
if (requested_procs[0] == "all")
{
known_procs = main_dtag_info.std_procs.all;
// and reset the requested processes to all known processes for this dtag
requested_procs.clear();
// loop over all known processes
for (const auto& proc: main_dtag_info.std_procs.all)
{
//cout_expr(proc.first);
requested_procs.push_back(proc.first);
}
}
else
{
known_procs = main_dtag_info.std_procs.groups;
//known_procs = main_dtag_info.std_procs.all;
// populate definitions of groups with the fine-grain definitions of all processes
known_procs.insert(main_dtag_info.std_procs.all.begin(), main_dtag_info.std_procs.all.end());
}
// name of the catchall process for the defined dtag
TString procname_catchall = main_dtag_info.std_procs.catchall_name;
map<TString, vector<TString>>& known_std_procs_per_channel = main_dtag_info.std_procs.channel_standard;
// --------------------------------- SETUP RECORD HISTOS for output from the parsed commandline input
for (const auto& systname: requested_systematics)
{
// find the definition of this channel
Stopif(known_systematics.find(systname) == known_systematics.end(), continue, "Do not know a systematic %s", systname.Data());
T_syst_chan_proc_histos systematic = {.name=string(systname.Data()), .syst_def = known_systematics[systname]};
// define channels
for (const auto& channame: requested_channels)
{
// find the definition of this channel
Stopif(known_defs_channels.find(channame) == known_defs_channels.end(), continue, "Do not know the channel %s", channame.Data());
T_chan_proc_histos channel = {
.name = string(channame.Data()),
.chan_def = known_defs_channels[channame],
.procs = {},
.name_catchall_proc = string(procname_catchall.Data())};
// check if standard processes per channels are requested
vector<TString>* process_definitions_to_use = &requested_procs;
if ((*process_definitions_to_use)[0] == "std")
{
// TODO in case of an unknown process set an inclusive definition
Stopif(known_std_procs_per_channel.find(channame) == known_std_procs_per_channel.end(), continue, "Do not know standard processes for the channel %s", channame.Data())
// set the standard processes
process_definitions_to_use = &known_std_procs_per_channel[channame];
}
// loop over requested processes and find their definitions for recording in this channel
//for (const char** requested_proc = requested_procs; *requested_proc != NULL; requested_proc++)
for (const auto& procname: (*process_definitions_to_use))
{
// find the definition of this channel
//TString procname(*requested_proc);
Stopif(known_procs.find(procname) == known_procs.end(), continue, "Do not know the process %s", procname.Data());
T_proc_histos process = {.name=string(procname.Data()), .proc_def=known_procs[procname]};
// define distributions
// create the histograms for all of these definitions
for (const auto& distrname: requested_distrs)
{
Stopif(known_defs_distrs.find(distrname) == known_defs_distrs.end(), continue, "Do not know a distribution %s", distrname.Data());
TH1D_histo a_distr = create_TH1D_histo(known_defs_distrs[distrname], channame + "_" + procname + "_" + systname + "_" + distrname, string(distrname.Data()));
process.histos.push_back(a_distr);
n_distrs_made +=1;
}
channel.procs.push_back(process);
n_procs_made +=1;
}
// setup catchall process
// define distributions
// create the histograms for all of these definitions
for (const auto& distrname: requested_distrs)
{
Stopif(known_defs_distrs.find(distrname) == known_defs_distrs.end(), continue, "Do not know a distribution %s", distrname.Data());
TH1D_histo a_distr = create_TH1D_histo(known_defs_distrs[distrname], channame + "_" + procname_catchall + "_" + systname + "_" + distrname, string(distrname.Data()));
channel.catchall_proc_histos.push_back(a_distr);
n_distrs_made +=1;
n_procs_made +=1;
}
systematic.chans.push_back(channel);
n_chans_made +=1;
}
distrs_to_record.push_back(systematic);
n_systs_made +=1;
}
cerr_expr(n_systs_made << " " << n_chans_made << " " << n_procs_made << " " << n_distrs_made);
return distrs_to_record;
}
// this is a pure hack, but the flexibility allows this:
//extern Int_t NT_nup;
void event_loop(TTree* NT_output_ttree, vector<T_syst_chan_proc_histos>& distrs_to_record,
bool skip_nup5_events, bool isMC)
{
// open the interface to stage2 TTree-s
//#define NTUPLE_INTERFACE_OPEN
//#define OUTNTUPLE NT_output_ttree
//#define NTUPLE_INTERFACE_CONNECT
//#include "stage2_interface.h" // it runs a bunch of branch-connecting commands on TTree* with name OUTNTUPLE
//// this must be done in stage2
//connect_ntuple_interface(NT_output_ttree);
Stopif(connect_ntuple_interface(NT_output_ttree) > 0, exit(55), "could not connect the TTree to the ntuple definitions");
unsigned int n_entries = NT_output_ttree->GetEntries();
//cerr_expr(n_entries);
for (unsigned int ievt = 0; ievt < n_entries; ievt++)
{
NT_output_ttree->GetEntry(ievt);
//if (skip_nup5_events && NT_nup > 5) continue;
//// tests
////cerr_expr(NT_runNumber);
//cerr_expr(NT_event_leptons[0].pt());
//cerr_expr(NT_event_leptons_genmatch[0]);
//Stopif(ievt > 10, break, "reached 10 events, exiting");
// loop over systematics
for (int si=0; si<distrs_to_record.size(); si++)
{
ObjSystematics obj_systematic = distrs_to_record[si].syst_def.obj_sys_id;
// the factor to the NOMINAL_base weight
double event_weight_factor = isMC ? distrs_to_record[si].syst_def.weight_func() : 1.;
// record distributions in all final states where the event passes
vector<T_chan_proc_histos>& channels = distrs_to_record[si].chans;
for (int ci=0; ci<channels.size(); ci++)
{
T_chan_proc_histos& chan = channels[ci];
// check if event passes the channel selection
if (!chan.chan_def.chan_sel(obj_systematic)) continue;
// calculate the NOMINAL_base event weight for the channel
double event_weight = isMC ? chan.chan_def.chan_sel_weight() : 1.;
// and multiply by the systematic factor
event_weight *= event_weight_factor;
// assign the gen process
// loop over procs check if this event passes
// if not get the catchall proc
// set catchall
vector<TH1D_histo>* histos = &(chan.catchall_proc_histos);
// check if any specific channel passes
for (int pi=0; pi<chan.procs.size(); pi++)
{
if (chan.procs[pi].proc_def())
{
histos = &chan.procs[pi].histos;
break;
}
}
// record all distributions with the given event weight
for (int di=0; di<histos->size(); di++)
{
TH1D_histo& histo_torecord = (*histos)[di];
// TODO memoize if possible
double value = histo_torecord.func(obj_systematic);
histo_torecord.histo->Fill(value, event_weight);
//histo_torecord.histo->Fill(value);
}
// <-- I keep the loops with explicit indexes, since the indexes can be used to implement memoization
//for(const auto& histo_torecord: chan.histos)
// {
// double value = histo_torecord.func(obj_systematic);
// histo_torecord.histo->Fill(value, event_weight);
// }
}
}
// end of event loop
}
}
void write_output(const char* output_filename, vector<T_syst_chan_proc_histos>& distrs_to_record,
S_dtag_info& main_dtag_info,
Float_t lumi,
bool isMC, bool save_in_old_order, bool simulate_data)
{
TFile* output_file = (TFile*) new TFile(output_filename, "RECREATE");
output_file->Write();
if (save_in_old_order)
{
for (int si=0; si<distrs_to_record.size(); si++)
{
// merge defined processes and the catchall
TString syst_name(distrs_to_record[si].name.c_str());
vector<T_chan_proc_histos>& all_chans = distrs_to_record[si].chans;
output_file->cd();
//TDirectory* dir_syst = (TDirectory*) output_file->mkdir(syst_name);
//dir_syst->SetDirectory(output_file);
for(const auto& chan: all_chans)
{
//dir_syst->cd();
//TDirectory* dir_chan = (TDirectory*) dir_syst->mkdir(chan.name);
//dir_chan->SetDirectory(dir_syst);
TString chan_name(chan.name.c_str());
for(const auto& proc: chan.procs)
{
//dir_chan->cd();
//TDirectory* dir_proc = (TDirectory*) dir_chan->mkdir(proc.name);
//dir_proc->SetDirectory(dir_chan);
//dir_proc->cd();
TString proc_name(proc.name.c_str());
for(const auto& recorded_histo: proc.histos)
{
// the old order of the path
//TString path = chan.name + "/" + proc.name + "/" + syst_name + "/";
// get or create this path
output_file->cd();
TDirectory* chanpath = output_file->Get(chan_name) ? (TDirectory*) output_file->Get(chan_name) : (TDirectory*) output_file->mkdir(chan_name);
chanpath->cd();
TDirectory* procpath = chanpath->Get(proc_name) ? (TDirectory*) chanpath->Get(proc_name) : (TDirectory*) chanpath->mkdir(proc_name);
procpath->cd();
TDirectory* systpatch = procpath->Get(syst_name) ? (TDirectory*) procpath->Get(syst_name) : (TDirectory*) procpath->mkdir(syst_name);
systpatch->cd();
TString histoname = chan_name + "_" + proc_name + "_" + syst_name + "_" + TString(recorded_histo.main_name);
recorded_histo.histo->SetName(histoname);
// all final normalizations of the histogram
if (isMC)
normalise_final(recorded_histo.histo, main_dtag_info.cross_section, lumi, syst_name, chan_name, proc_name);
recorded_histo.histo->Write();
}
}
// same for catchall
// the old order of the path
//TString path = chan.name + "/" + chan.name_catchall_proc + "/" + syst_name + "/";
//for(const auto& recorded_histo: chan.catchall_proc_histos)
for (unsigned int rec_histo_i = 0; rec_histo_i<chan.catchall_proc_histos.size(); rec_histo_i++)
{
const auto& recorded_histo = chan.catchall_proc_histos[rec_histo_i];
TString chan_name_catchall(chan.name_catchall_proc.c_str());
// get or create this path
output_file->cd();
TDirectory* chanpath = output_file->Get(chan_name) ? (TDirectory*) output_file->Get(chan_name) : (TDirectory*) output_file->mkdir(chan_name);
chanpath->cd();
TDirectory* procpath = chanpath->Get(chan_name_catchall) ? (TDirectory*) chanpath->Get(chan_name_catchall) : (TDirectory*) chanpath->mkdir(chan_name_catchall);
procpath->cd();
TDirectory* systpatch = procpath->Get(syst_name) ? (TDirectory*) procpath->Get(syst_name) : (TDirectory*) procpath->mkdir(syst_name);
systpatch->cd();
TString histoname = chan_name + "_" + chan_name_catchall + "_" + syst_name + "_" + TString(recorded_histo.main_name);
//cerr_expr(histoname);
recorded_histo.histo->SetName(histoname);
if (isMC)
normalise_final(recorded_histo.histo, main_dtag_info.cross_section, lumi, syst_name, chan_name, chan_name_catchall);
recorded_histo.histo->Write();
// data simulation for each recorded distr if requested
if (simulate_data && syst_name == "NOMINAL")
{
output_file->cd();
TDirectory* chanpath = output_file->Get(chan_name) ? (TDirectory*) output_file->Get(chan_name) : (TDirectory*) output_file->mkdir(chan_name);
chanpath->cd();
TDirectory* procpath = chanpath->Get("data") ? (TDirectory*) chanpath->Get("data") : (TDirectory*) chanpath->mkdir("data");
procpath->cd();
TDirectory* systpatch = procpath->Get("NOMINAL") ? (TDirectory*) procpath->Get("NOMINAL") : (TDirectory*) procpath->mkdir("NOMINAL");
systpatch->cd();
TString data_name = chan_name + "_data_NOMINAL_" + recorded_histo.main_name;
if (output_file->Get(chan_name + "/data/NOMINAL/" + data_name)) continue;
TH1D* data_histo = (TH1D*) recorded_histo.histo->Clone();
data_histo->SetDirectory(systpatch);
data_histo->SetName(data_name);
//data_histo->Reset();
//data_histo->Fill(1);
// instead, add histograms from all processes
for(const auto& proc: chan.procs)
{
data_histo->Add(proc.histos[rec_histo_i].histo);
}
data_histo->Write();
}
}
}
}
}
else
{
for (int si=0; si<distrs_to_record.size(); si++)
{
// merge defined processes and the catchall
TString syst_name(distrs_to_record[si].name);
vector<T_chan_proc_histos>& all_chans = distrs_to_record[si].chans;
output_file->cd();
TDirectory* dir_syst = (TDirectory*) output_file->mkdir(syst_name);
//dir_syst->SetDirectory(output_file);
for(const auto& chan: all_chans)
{
TString chan_name(chan.name.c_str());
dir_syst->cd();
TDirectory* dir_chan = (TDirectory*) dir_syst->mkdir(chan_name);
//dir_chan->SetDirectory(dir_syst);
for(const auto& proc: chan.procs)
{
TString proc_name(proc.name.c_str());
dir_chan->cd();
TDirectory* dir_proc = (TDirectory*) dir_chan->mkdir(proc_name);
//dir_proc->SetDirectory(dir_chan);
dir_proc->cd();
for(const auto& recorded_histo: proc.histos)
{
//recorded_histo.histo->Print();
// all final normalizations of the histogram
if (isMC)
normalise_final(recorded_histo.histo, main_dtag_info.cross_section, lumi, syst_name, chan_name, proc_name);
recorded_histo.histo->Write();
}
}
//for(const auto& recorded_histo: chan.catchall_proc_histos)
for (unsigned int rec_histo_i = 0; rec_histo_i<chan.catchall_proc_histos.size(); rec_histo_i++)
{
const auto& recorded_histo = chan.catchall_proc_histos[rec_histo_i];
TString chan_name_catchall_proc(chan.name_catchall_proc.c_str());
// same for catchall
dir_chan->cd();
TDirectory* dir_proc_catchall = dir_chan->Get(chan_name_catchall_proc) ? (TDirectory*) dir_chan->Get(chan_name_catchall_proc) : (TDirectory*) dir_chan->mkdir(chan_name_catchall_proc);
//dir_proc_catchall->SetDirectory(dir_chan);
dir_proc_catchall->cd();
if (isMC)
normalise_final(recorded_histo.histo, main_dtag_info.cross_section, lumi, syst_name, chan_name, chan_name_catchall_proc);
recorded_histo.histo->Write();
// data simulation if requested
if (simulate_data && syst_name == "NOMINAL")
{
dir_syst->cd();
TDirectory* chanpath = dir_syst->Get(chan_name) ? (TDirectory*) dir_syst->Get(chan_name) : (TDirectory*) dir_syst->mkdir(chan_name);
chanpath->cd();
TDirectory* procpath = chanpath->Get("data") ? (TDirectory*) chanpath->Get("data") : (TDirectory*) chanpath->mkdir("data");
procpath->cd();
TString data_name = TString("NOMINAL_") + chan_name + "_data_" + recorded_histo.main_name;
if (procpath->Get(data_name)) continue;
TH1D* data_histo = (TH1D*) recorded_histo.histo->Clone();
data_histo->SetDirectory(procpath);
data_histo->SetName(data_name);
//data_histo->Reset();
//data_histo->Fill(1);
// instead, add histograms from all processes
for(const auto& proc: chan.procs)
{
data_histo->Add(proc.histos[rec_histo_i].histo);
}
data_histo->Write();
}
}
}
}
}
output_file->cd();
if (normalise_per_weight)
weight_counter->Write();
output_file->Close();
}
/** \brief The main program executes user's request over the given list of files, in all found `TTree`s in the files.
It parses the requested channels, systematics and distributions;
prepares the structure of the loop;
loops over all given files and `TTree`s in them,
recording the distributions at the requested systematics;
applies final corrections to the distributions;
and if asked normalizes the distribution to `cross_section/gen_lumi`;
finally all histograms are written out in the standard format `channel/process/systematic/channel_process_systematic_distr`.
The input now: `input_filename [input_filename+]`.
*/
int main (int argc, char *argv[])
{
argc--;
const char* exec_name = argv[0];
argv++;
if (argc < 7)
{
std::cout << "Usage:" << " [0-1]<interface type> 0|1<simulate_data> 0|1<save_in_old_order> 0|1<do_WNJets_stitching> <lumi> <systs coma-separated> <chans> <procs> <distrs> output_filename input_filename [input_filename+]" << std::endl;
exit(1);
}
gROOT->Reset();
/* --- input options --- */
// set to normalize per gen lumi number of events
//bool normalise_per_weight = <user input>;
// a special weird feature:
// produce an output as if it were data
// with NOMINAL systematic
// and data proc name
// histograms are filled with 1
Int_t interface_type = Int_t(atoi(*argv++)) == 1; argc--;
bool simulate_data = Int_t(atoi(*argv++)) == 1; argc--;
bool save_in_old_order = Int_t(atoi(*argv++)) == 1; argc--;
bool do_WNJets_stitching = Int_t(atoi(*argv++)) == 1; argc--;
Float_t lumi(atof(*argv++)); argc--;
// parse commandline coma-separated lists for main parameters of the record
vector<TString> requested_systematics = parse_coma_list(*argv++); argc--;
vector<TString> requested_channels = parse_coma_list(*argv++); argc--;
vector<TString> requested_procs = parse_coma_list(*argv++); argc--;
vector<TString> requested_distrs = parse_coma_list(*argv++); argc--;
const char* output_filename = *argv++; argc--;
if (do_not_overwrite)
Stopif(access(output_filename, F_OK) != -1, exit(2);, "the output file exists %s", output_filename);
cerr_expr(do_WNJets_stitching << " " << output_filename);
/* --------------------- */
// -------------------- set the interface type
string input_path_ttree;
string input_path_weight_counter;
// main record parameters
switch (interface_type)
{
case 0:
known_systematics = create_known_defs_systs_stage2();
known_defs_channels = create_known_defs_channels_stage2();
known_defs_distrs = create_known_defs_distrs_stage2();
known_procs_info = create_known_defs_procs_stage2();
known_normalization_per_syst = create_known_MC_normalization_per_syst_stage2();
known_normalization_per_proc = create_known_MC_normalization_per_proc_stage2();
known_normalization_per_chan = create_known_MC_normalization_per_chan_stage2();
connect_ntuple_interface = &connect_ntuple_interface_stage2;
input_path_ttree = "ttree_out";
input_path_weight_counter = "weight_counter";
break;
case 1:
known_systematics = create_known_defs_systs_ntupler();
known_defs_channels = create_known_defs_channels_ntupler();
known_defs_distrs = create_known_defs_distrs_ntupler();
known_procs_info = create_known_defs_procs_ntupler();
known_normalization_per_syst = create_known_MC_normalization_per_syst_ntupler();
known_normalization_per_proc = create_known_MC_normalization_per_proc_ntupler();
known_normalization_per_chan = create_known_MC_normalization_per_chan_ntupler();
connect_ntuple_interface = &connect_ntuple_interface_ntupler;
input_path_ttree = "ntupler/reduced_ttree";
input_path_weight_counter = "ntupler/weight_counter";
break;
default:
Stopif(interface_type != 0 && interface_type != 1, exit(2);, "the interface type %d is not supported, the valid values are 0 (stage2) and 1 (ntupler)", interface_type);
}
map<TString, S_dtag_info> known_dtags_info = create_known_dtags_info(known_procs_info);
// set the interface type --------------------
//Int_t rebin_factor(atoi(argv[3]));
//TString dir(argv[4]);
//TString dtag1(argv[5]);
/* Here we will parse user's request for figures
* to create the structure filled up in the event loop.
*/
// figure out the dtag of the input files from the first input file
TString first_input_filename(argv[0]);
TString main_dtag("");
// loop over known dtags and find whether any of the matches
map<TString, S_dtag_info>::iterator a_dtag_info = known_dtags_info.begin();
while (a_dtag_info != known_dtags_info.end())
{
// Accessing KEY from element pointed by it.
TString dtag_name = a_dtag_info->first;
if (first_input_filename.Contains(dtag_name))
{
main_dtag = dtag_name;
break;
}
// Increment the Iterator to point to next entry
a_dtag_info++;
}
// test if no dtag was recognized
//Stopif(!main_dtag, ;, "could not recognize any known dtag in %s", first_input_filename.Data());
Stopif(main_dtag.EqualTo(""), ;, "could not recognize any known dtag in %s", first_input_filename.Data());
//if (main_dtag.EqualTo(""))
// {
// cerr_expr();
// }
S_dtag_info main_dtag_info = known_dtags_info[main_dtag];
cerr_expr(main_dtag << " : " << main_dtag_info.cross_section);
bool isMC = main_dtag.Contains("MC");
//if (!isMC) normalise_per_weight = false;
normalise_per_weight &= isMC;
// for WNJets stiching
bool skip_nup5_events = do_WNJets_stitching && isMC && main_dtag.Contains("WJets_madgraph");
//// define histograms for the distributions
//vector<TH1D_histo> distrs;
// define a nested list: list of channels, each containing a list of histograms to record
vector<T_syst_chan_proc_histos> distrs_to_record = setup_record_histos(
main_dtag_info,
requested_systematics ,
requested_channels ,
requested_procs ,
requested_distrs );
// --------------------------------- EVENT LOOP
// process input files
for (unsigned int cur_var = 0; cur_var<argc; cur_var++)
{
TString input_filename(argv[cur_var]);
cerr_expr(cur_var << " " << input_filename);
//cerr_expr(input_filename);
//dtags.push_back(dtag);
//files.push_back(TFile::Open(dir + "/" + dtag + ".root"));
//dtags.push_back(5);
// get input ttree
TFile* input_file = TFile::Open(input_filename);
Stopif(!input_file, continue, "cannot Open TFile in %s, skipping", input_filename.Data());
TTree* NT_output_ttree = (TTree*) input_file->Get(input_path_ttree.c_str());
Stopif(!NT_output_ttree, continue, "cannot Get TTree in file %s, skipping", input_filename.Data());
if (normalise_per_weight)
{
// get weight distribution for the file
TH1D* weight_counter_in_file = (TH1D*) input_file->Get(input_path_weight_counter.c_str());
// if the common weight counter is still not set -- clone
if (!weight_counter)
{
weight_counter = (TH1D*) weight_counter_in_file->Clone();
weight_counter->SetDirectory(0);
}
else
{
weight_counter->Add(weight_counter_in_file);
}
}
// loop over events in the ttree and record the requested histograms
event_loop(NT_output_ttree, distrs_to_record, skip_nup5_events, isMC);
// close the input file
input_file->Close();
}
// if there is still no weight counter when it was requested
// then no files were processed (probably all were skipped)
Stopif(normalise_per_weight && !weight_counter, exit(3), "no weight counter even though it was requested, probably no files were processed, exiting")
/*
for(std::map<TString, double>::iterator it = xsecs.begin(); it != xsecs.end(); ++it)
{
TString dtag = it->first;
double xsec = it->second;
cout << "For dtag " << dtag << " xsec " << xsec << "\n";
}
*/
//std::vector < TString > dtags;
//std::vector < TFile * > files;
//std::vector < TH1D * > histos;
//std::vector < TH1D * > weightflows;
//// nick->summed histo
//std::map<TString, TH1D *> nicknamed_mc_histos;
////vector<int> dtags;
////dtags.reserve();
// make stack of MC, scaling according to ratio = lumi * xsec / weightflow4 (bin5?)
// also nickname the MC....
// per-dtag for now..
// --------------------------------- OUTPUT
write_output(output_filename, distrs_to_record, main_dtag_info, lumi, isMC, save_in_old_order, simulate_data);
}
|
C | #include <stdio.h>
int main (void) {
int x, *p;
x = 100;
p = &x; // Linha corrigida;
printf("O valor de p: %d.\n", *p);
return 0;
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include "include/hialgo.h"
#include "include/test.h"
int IntCmp(const void *a, const void *b)
{
return *(int*)a - *(int*)b;
}
void BsearchTest(void) {
TEST_FUNC_BEGIN();
int a[] = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 };
int num = sizeof(a) / sizeof(a[0]);
int size = sizeof(int);
int c;
void *ret, *left, *right;
c = 5;
ret = HiBsearch(&c, a, num - 1, size, IntCmp, &left, &right);
SHOULD(left == NULL);
SHOULD(ret == NULL);
SHOULD(right = &a[0]);
c = 10;
ret = HiBsearch(&c, a, num - 1, size, IntCmp, &left, &right);
SHOULD(left == NULL);
SHOULD(ret == &a[0]);
SHOULD(right = &a[1]);
c = 11;
ret = HiBsearch(&c, a, num - 1, size, IntCmp, &left, &right);
SHOULD(left == &a[0]);
SHOULD(ret == NULL);
SHOULD(right = &a[1]);
c = 99;
ret = HiBsearch(&c, a, num, size, IntCmp, &left, &right);
SHOULD(*(int*)left == 90);
SHOULD(ret == NULL);
SHOULD(*(int*)right == 100);
c = 100;
ret = HiBsearch(&c, a, num, size, IntCmp, &left, &right);
SHOULD(*(int*)left == 90);
SHOULD(*(int*)ret == 100);
SHOULD(right == NULL);
c = 101;
ret = HiBsearch(&c, a, num, size, IntCmp, &left, &right);
SHOULD(*(int*)left == 100);
SHOULD(ret == NULL);
SHOULD(right == NULL);
TEST_FUNC_END();
}
int main(void)
{
BsearchTest();
system("pause");
return 0;
} |
C | #include <stdio.h>
int main() {
float a,b;
printf("donner l'hauteur' \n");
scanf ("%f",&a);
printf("donner la base \n");
scanf ("%f",&b);
float c=(a*b)/2;
printf ("l'aire du triangle est %f\n",c);
return 0;
}
|
C |
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "images.h"
double* matrix;
unsigned char ascii_gray[] = {32,46,59,42,115,116,73,40,106,117,86,119,98,82,103,64};
double * mat_double_gray; // matrix of double gray
double * mat_resize; // resized matrix
double * h_bright; // bright min & max
double * mat_sobel; // matrix after sobel
unsigned char * mat_ascii; // matrix of unsigned char ascii
char control_signal; // control signal
int stateSig[3] = {255, 255, 255}; // initial state signal (moore)
int lengthx, lengthy;
/*
double * rotateMatrix(int dx, int dy, int x, int y, double * origin_mat){
int i, j;
double * mat = malloc(sizeof(double) * x * y);
for (i = 0; i < x; i++){
for (j = 0; j < y; j++){
mat[i + x * j] = origin_mat[i + x * j];
}
}
if (dx == -1){
// shift left
for (i = 0; i < y; i++){ // which row
double tmp = mat[0 + x * i];
for (j = 0; j < x - 1; j++){
mat[j + x * i] = mat[j + 1 + x * i];
}
mat[x - 1 + x * i] = tmp;
}
}
else if (dx == 1){
// shift right
for (i = 0; i < y; i++){ // which row
double tmp = mat[x - 1 + x * i];
for (j = x - 1; j > 0; j--){
mat[j + x * i] = mat[j - 1 + x * i];
}
mat[0 + x * i] = tmp;
}
}
for (j = 0; j < y; j++){
for (i = 0; i < x; i++){
printf("%d ", mat[i + x * j]);
}
printf("\n");
}
printf("\n");
if (dy == -1){
// shift up
for (i = 0; i < x; i++) { // which column
double tmp = mat[i + x * 0];
for (j = 0; j < y - 1; j++){
mat[i + x * j] = mat[i + x * (j + 1)];
}
mat[i + x * (y - 1)] = tmp;
}
}
else if (dy == 1){
// shift down
for (i = 0; i < x; i++) { // which column
double tmp = mat[i + x * (y - 1)];
for (j = y - 1; j > 0; j--){
mat[i + x * j] = mat[i + x * (j - 1)];
}
mat[i] = tmp;
}
}
return mat;
}
*/
double * sobel(int x, int y, double * origin_mat){
int i, j, m = 0;
//double * origin_mat[8];
double * g;
double gx, gy;
g = malloc(sizeof(double) * (x - 2) * (y - 2));
//gx = malloc(sizeof(double) * x * y);
//gy = malloc(sizeof(double) * x * y);
/*
for (i = -1; i < 2; i++){
for (j = -1; j < 2; j++){
if (!(i == 0 && j == 0)){
origin_mat[m++] = rotateMatrix(i, j, x, y, origin_mat);
}
}
}
*/
for (j = 0; j < y - 2; j++){
for (i = 0; i < x - 2; i++){
//printf("%d, %d\n", i , j);
gx = origin_mat[i + j * x] * (-1) + origin_mat[i + (j + 1) * x] * (-2)
+ origin_mat[i + (j + 2) * x] * (-1) + origin_mat[i + 2 + j * x] * 1
+ origin_mat[i + 2 + (j + 1) * x] * 2 + origin_mat[i + 2 + (j + 2) * x] * 1;
gy = origin_mat[i + j * x] * (-1) + origin_mat[i + 1 + j * x] * (-2)
+ origin_mat[i + 2 + j * x] * (-1) + origin_mat[i + (j + 2) * x] * 1
+ origin_mat[i + 1 + (j + 2) * x] * 2 + origin_mat[i + 2 + (j + 2) * x] * 1;
g[i + j * (x - 2)] = sqrt(gx * gx + gy * gy) / 4;
//printf("%f, %f\n", gx , gy);
}
}
//x -= 2;
//y -= 2;
return g;
}
double * grayscale(int x, int y, unsigned char * origin_mat){
int i, j;
double * gray_m = malloc(sizeof(double) * x * y);
for (j = 0; j < y; j++){
for (i = 0; i < x; i++){
double r, g, b;
r = origin_mat[3 * i + j * x];
g = origin_mat[3 * i + j * x + 1];
b = origin_mat[3 * i + j * x + 2];
gray_m[i + j * x] = r * 0.3125 + g * 0.5625 + b * 0.125;
}
}
return gray_m;
}
double * resize(int x, int y, double * origin_mat){
int i, j;
double * resize_m;
x /= 2;
y /= 2;
resize_m = malloc(sizeof(double) * x * y);
for (j = 0; j < y; j++){
for (i = 0; i < x; i++){
resize_m[i + j * x] = (origin_mat[i * 2 + j * 2 * x]
+ origin_mat[i * 2 + 1 + j * 2 * x] + origin_mat[i * 2 + (j * 2 + 1) * x]
+ origin_mat[i * 2 + 1 + (j * 2 + 1) * x]) / 4;
}
}
return resize_m;
}
double * brightness(int x, int y, double * origin_mat){
int i, j;
double *h = malloc(sizeof(double) * 2); // hmin, hmax
h[0] = origin_mat[0];
h[1] = origin_mat[0];
for (j = 0; j < y; j++)
for (i = 0; i < x; i++){
if (origin_mat[i + j * x] < h[0]) h[0] = origin_mat[i + j * x];
if (origin_mat[i + j * x] > h[1]) h[1] = origin_mat[i + j * x];
}
return h;
}
char moore(double hmin, double hmax, int * stateSig){
// don't know if "inSig" is needed or not, I don't want to
// delay here
int ave;
stateSig[2] = stateSig[1];
stateSig[1] = stateSig[0];
stateSig[0] = hmax - hmin;
ave = (stateSig[0] + stateSig[1] + stateSig[2]) / 3;
if (ave < 128) return 1;
else return 0;
}
void correct(int x, int y, double* origin_mat, char control_sig,
double hmin, double hmax){
// control_sig should be in the task and determine the semephor
int i, j;
if (control_sig == 0) return;
if (hmax - hmin > 127){}
else if (hmax - hmin > 63){
for (j = 0; j < y; j++)
for (i = 0; i < x; i++){
origin_mat[i + j * x] = 2 * (origin_mat[i + j * x] - hmin);
}
}
else if (hmax - hmin > 31){
for (j = 0; j < y; j++)
for (i = 0; i < x; i++){
origin_mat[i + j * x] = 4 * (origin_mat[i + j * x] - hmin);
}
}
else if (hmax - hmin > 15){
for (j = 0; j < y; j++)
for (i = 0; i < x; i++){
origin_mat[i + j * x] = 8 * (origin_mat[i + j * x] - hmin);
}
}
else{
for (j = 0; j < y; j++)
for (i = 0; i < x; i++){
origin_mat[i + j * x] = 16 * (origin_mat[i + j * x] - hmin);
}
}
}
unsigned char * ascii(int x, int y, double * origin_mat){
unsigned char * ascii_m = malloc(sizeof(unsigned char) * x * y);
int i, j, n;
for (j = 0; j < y; j++)
for (i = 0; i < x; i++){
n = (int) origin_mat[i + j * x] / 16;
ascii_m[i + j * x] = ascii_gray[n];
}
return ascii_m;
}
void print_img(int x, int y, unsigned char * mat){
int i, j;
for (j = 0; j < y; j++){
for (i = 0; i < x; i++)
printf("%c", mat[i + j * x]);
printf("\n");
}
}
void print_img_double(int x, int y, double * n){
int i, j;
printf("print-image-double\n");
for (j = 0; j < y; j++){
for (i = 0; i < x; i++){
printf("%.2f ", n[i + x * j]);
}
printf("\n%d,%d\n\n", i, j);
}
printf("\n\n");
}
int main(){
//double* om[3][3] = {'1', '2', '3', '4', '5', '6', '7', '8', '9'};
int x = 4, y = 4;
double om[16] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
12, 13, 14, 15, 16};
int i, j;
/*
double* m = rotateMatrix(-1, 1, x, y, om);
for (j = 0; j < y; j++){
for (i = 0; i < x; i++){
printf("%d ", om[i + x * j]);
}
printf("\n");
}
printf("\n");
for (j = 0; j < y; j++){
for (i = 0; i < x; i++){
printf("%d ", m[i + x * j]);
}
printf("\n");
}
printf("\n");
*/
/*
double* n = sobel(x, y, om);
for (j = 0; j < y - 2; j++){
for (i = 0; i < x - 2; i++){
printf("%.3f ", n[i + (x - 2) * j]);
}
printf("\n");
}
printf("\n");
unsigned char www = 20;
unsigned char w = www * www;
double qq = www * 0.033;
printf("%d\n", w);
*/
i = img1_24_24[0];
j = img1_24_24[1];
printf("before gray\n");
mat_double_gray = grayscale(i, j, img1_24_24 + 3);
printf("before resize\n");
mat_resize = resize(i, j, mat_double_gray);
printf("after resize\n");
i /= 2;
j /= 2;
free(mat_double_gray);
print_img_double(i, j, mat_resize);
printf("before brightness\n");
h_bright = brightness(i, j, mat_resize);
control_signal = moore(h_bright[0], h_bright[1], stateSig);
correct(i, j, mat_resize, stateSig, h_bright[0], h_bright[1]);
mat_sobel = sobel(i, j, mat_resize);
print_img_double(i, j, mat_sobel);
i -= 2;
j -= 2;
free(mat_resize);
printf("before ascii\n");
mat_ascii = ascii(i, j, mat_sobel);
//mat_ascii = ascii(i, j, mat_double_gray);
free(mat_sobel);
print_img(i, j, mat_ascii);
getchar();
}
|
C | #include "pharovm/pharo.h"
#include "pharovm/parameters/parameters.h"
#include "pharovm/debug.h"
#include "pharovm/pathUtilities.h"
#include <assert.h>
typedef VMErrorCode (*vm_parameter_process_function)(const char *argument, VMParameters* params);
typedef struct VMParameterSpec_
{
const char *name;
bool hasArgument;
vm_parameter_process_function function;
} VMParameterSpec;
/*
* Parse a text in the form [anInteger]k|K|m|M|g|G
* Return the number of bytes represented by the text.
* Return VM_ERROR_INVALID_PARAMETER_VALUE in case of error
* (the text is not prefixed by a number or it is negative number)
*
* E.g., 2M => 2 * 1024 * 1024
*/
long long parseByteSize(const char* text){
long long intValue = 0;
int multiplier = 1;
int argumentLength = 0;
char* argument = alloca(255);
strncpy(argument, text, 255);
argument[254] = 0;
if(strlen(argument) > 0){
argumentLength = strlen(argument);
char lastCharacter = argument[argumentLength - 1];
switch(lastCharacter){
case 'k':
case 'K':
multiplier = 1024;
argument[argumentLength - 1] = '\0';
break;
case 'm':
case 'M':
multiplier = 1024 * 1024;
argument[argumentLength - 1] = '\0';
break;
case 'g':
case 'G':
multiplier = 1024 * 1024 * 1024;
argument[argumentLength - 1] = '\0';
break;
default:
break;
}
}
errno = 0;
intValue = strtoll(argument, NULL, 10);
if(errno != 0 || intValue < 0)
{
return VM_ERROR_INVALID_PARAMETER_VALUE;
}
return intValue * multiplier;
}
void vm_printUsageTo(FILE *out);
static VMErrorCode processHelpOption(const char *argument, VMParameters * params);
static VMErrorCode processPrintVersionOption(const char *argument, VMParameters * params);
static VMErrorCode processLogLevelOption(const char *argument, VMParameters * params);
static VMErrorCode processMaxFramesToPrintOption(const char *argument, VMParameters * params);
static VMErrorCode processMaxOldSpaceSizeOption(const char *argument, VMParameters * params);
static VMErrorCode processMaxCodeSpaceSizeOption(const char *argument, VMParameters * params);
static VMErrorCode processEdenSizeOption(const char *argument, VMParameters * params);
static VMErrorCode processWorkerOption(const char *argument, VMParameters * params);
static VMErrorCode processMinPermSpaceSizeOption(const char *argument, VMParameters * params);
static const VMParameterSpec vm_parameters_spec[] =
{
{.name = "headless", .hasArgument = false, .function = NULL},
#ifdef PHARO_VM_IN_WORKER_THREAD
{.name = "worker", .hasArgument = false, .function = processWorkerOption},
#endif
{.name = "interactive", .hasArgument = false, .function = NULL}, // For pharo-ui scripts.
{.name = "vm-display-null", .hasArgument = false, .function = NULL}, // For Smalltalk CI.
{.name = "help", .hasArgument = false, .function = processHelpOption},
{.name = "h", .hasArgument = false, .function = processHelpOption},
{.name = "version", .hasArgument = false, .function = processPrintVersionOption},
{.name = "logLevel", .hasArgument = true, .function = processLogLevelOption},
{.name = "maxFramesToLog", .hasArgument = true, .function = processMaxFramesToPrintOption},
{.name = "maxOldSpaceSize", .hasArgument = true, .function = processMaxOldSpaceSizeOption},
{.name = "codeSize", .hasArgument = true, .function = processMaxCodeSpaceSizeOption},
{.name = "edenSize", .hasArgument = true, .function = processEdenSizeOption},
{.name = "minPermSpaceSize", .hasArgument = true, .function = processMinPermSpaceSizeOption},
#ifdef __APPLE__
// This parameter is passed by the XCode debugger.
{.name = "NSDocumentRevisionsDebugMode", .hasArgument = false, .function = NULL},
#endif
};
// TODO: Turn this array size computation into a macro.
static const size_t vm_parameters_spec_size = sizeof(vm_parameters_spec) / sizeof(vm_parameters_spec[0]);
/**
* Folder search suffixes for finding images.
*/
static const char * const vm_image_search_suffixes[] = {
DEFAULT_IMAGE_NAME,
#ifdef __APPLE__
"../Resources/" DEFAULT_IMAGE_NAME,
"../../../" DEFAULT_IMAGE_NAME,
#endif
};
static const size_t vm_image_search_suffixes_count = sizeof(vm_image_search_suffixes) / sizeof(vm_image_search_suffixes[0]);
static const VMParameterSpec*
findParameterWithName(const char *argumentName, size_t argumentNameSize)
{
for(size_t i = 0; i < vm_parameters_spec_size; ++i) {
const VMParameterSpec *paramSpec = &vm_parameters_spec[i];
if(strlen(paramSpec->name) == argumentNameSize &&
strncmp(paramSpec->name, argumentName, argumentNameSize) == 0) {
return paramSpec;
}
}
return NULL;
}
static int
findParameterArity(const char *parameter)
{
if(*parameter != '-') return 0;
// Ignore the preceding hyphens
++parameter;
if(*parameter == '-')
{
++parameter;
}
// Does the parameter have an equal (=)?
if(strchr(parameter, '=') != NULL) return 0;
// Find the parameter spec.
const VMParameterSpec* spec = findParameterWithName(parameter, strlen(parameter));
if(!spec) return 0;
return spec->hasArgument ? 1 : 0;
}
// FIXME: This should be provided by the client.
static int
isInConsole()
{
#ifdef _WIN32
return GetStdHandle(STD_INPUT_HANDLE) != NULL;
#else
return false;
#endif
}
VMErrorCode
vm_parameters_destroy(VMParameters *parameters)
{
if(!parameters) return VM_ERROR_NULL_POINTER;
free(parameters->imageFileName);
vm_parameter_vector_destroy(¶meters->vmParameters);
vm_parameter_vector_destroy(¶meters->imageParameters);
memset(parameters, 0, sizeof(VMParameters));
return VM_SUCCESS;
}
VMErrorCode
vm_find_startup_image(const char *vmExecutablePath, VMParameters *parameters)
{
char *imagePathBuffer = (char*)calloc(1, FILENAME_MAX+1);
char *vmPathBuffer = (char*)calloc(1, FILENAME_MAX+1);
char *searchPathBuffer = (char*)calloc(1, FILENAME_MAX+1);
if(!imagePathBuffer || !vmPathBuffer || !searchPathBuffer)
{
free(imagePathBuffer);
free(vmPathBuffer);
free(searchPathBuffer);
return VM_ERROR_OUT_OF_MEMORY;
}
// Find the VM absolute directory.
vm_path_make_absolute_into(searchPathBuffer, FILENAME_MAX+1, vmExecutablePath);
if(sqImageFileExists(searchPathBuffer))
{
vm_path_extract_dirname_into(vmPathBuffer, FILENAME_MAX+1, searchPathBuffer);
}
else
{
strncpy(vmPathBuffer, vmExecutablePath, FILENAME_MAX);
vmPathBuffer[FILENAME_MAX] = 0;
}
// Find the image in the different search directory suffixes.
for(size_t i = 0; i < vm_image_search_suffixes_count; ++i)
{
const char *searchSuffix = vm_image_search_suffixes[i];
vm_path_join_into(imagePathBuffer, FILENAME_MAX+1, vmPathBuffer, searchSuffix);
if(sqImageFileExists(imagePathBuffer))
{
parameters->imageFileName = imagePathBuffer;
parameters->isDefaultImage = true;
parameters->defaultImageFound = true;
free(vmPathBuffer);
free(searchPathBuffer);
return VM_SUCCESS;
}
}
// Find the image in the current work directory.
vm_path_get_current_working_dir_into(searchPathBuffer, FILENAME_MAX+1);
vm_path_join_into(imagePathBuffer, FILENAME_MAX+1, searchPathBuffer, DEFAULT_IMAGE_NAME);
free(vmPathBuffer);
free(searchPathBuffer);
if(sqImageFileExists(imagePathBuffer))
{
parameters->imageFileName = imagePathBuffer;
parameters->isDefaultImage = true;
parameters->defaultImageFound = true;
return VM_SUCCESS;
}
free(imagePathBuffer);
parameters->imageFileName = strdup(DEFAULT_IMAGE_NAME);
parameters->isDefaultImage = true;
parameters->defaultImageFound = false;
return VM_SUCCESS;
}
static int
findImageNameIndex(int argc, const char** argv)
{
//The first parameters is the executable name
for(int i=1; i < argc; i ++)
{
const char *argument = argv[i];
// Is this a mark for where the image parameters begins?
if(strcmp(argument, "--") == 0)
{
return i;
}
// Is this an option?
if(*argv[i] == '-') {
i += findParameterArity(argument);
continue;
}
// This must be the first non vmoption argument, so this must be the image.
return i;
}
// I could not find it.
return argc;
}
static VMErrorCode
fillUpImageName(int argc, const char** argv, VMParameters* parameters){
VMErrorCode error;
int imageNameIndex = findImageNameIndex(argc, argv);
// We get the image file name
if(imageNameIndex != argc && strcmp("--", argv[imageNameIndex]) != 0) {
parameters->imageFileName = strdup(argv[imageNameIndex]);
parameters->isDefaultImage = false;
parameters->isInteractiveSession = false;
}
return VM_SUCCESS;
}
static VMErrorCode
splitVMAndImageParameters(int argc, const char** argv, VMParameters* parameters)
{
VMErrorCode error;
int imageNameIndex = findImageNameIndex(argc, argv);
int numberOfVMParameters = imageNameIndex;
int numberOfImageParameters = argc - imageNameIndex - 1;
//If we still have an empty image file, we try the default
if(parameters->imageFileName == NULL){
error = vm_find_startup_image(argv[0], parameters);
if(error) return error;
// Is this an interactive environment?
parameters->isInteractiveSession = !isInConsole() && parameters->isDefaultImage;
}
if(numberOfImageParameters < 0)
numberOfImageParameters = 0;
// Copy image parameters.
error = vm_parameter_vector_insert_from(¶meters->imageParameters, numberOfImageParameters, &argv[imageNameIndex + 1]);
if(error)
{
vm_parameters_destroy(parameters);
return error;
}
// Copy the VM parameters.
error = vm_parameter_vector_insert_from(¶meters->vmParameters, numberOfVMParameters, argv);
if(error)
{
vm_parameters_destroy(parameters);
return error;
}
#if !ALWAYS_INTERACTIVE
// Add additional VM parameters.
const char *extraVMParameters = "--headless";
error = vm_parameter_vector_insert_from(¶meters->vmParameters, 1, &extraVMParameters);
if(error)
{
vm_parameters_destroy(parameters);
return error;
}
#endif
return VM_SUCCESS;
}
static void
logParameterVector(const char* vectorName, const VMParameterVector *vector)
{
logDebug("%s [count = %u]:", vectorName, vector->count);
for(size_t i = 0; i < vector->count; ++i)
{
logDebug(" %s", vector->parameters[i]);
}
}
static void
logParameters(const VMParameters* parameters)
{
logDebug("Image file name: %s", parameters->imageFileName);
logDebug("Is default Image: %s", parameters->isDefaultImage ? "yes" : "no");
logDebug("Is interactive session: %s", parameters->isInteractiveSession ? "yes" : "no");
logParameterVector("vmParameters", ¶meters->vmParameters);
logParameterVector("imageParameters", ¶meters->imageParameters);
}
VMErrorCode
vm_parameters_ensure_interactive_image_parameter(VMParameters* parameters)
{
VMErrorCode error;
const char* interactiveParameter = "--interactive";
if (parameters->isInteractiveSession)
{
if (!vm_parameter_vector_has_element(¶meters->imageParameters, "--interactive"))
{
error = vm_parameter_vector_insert_from(¶meters->imageParameters, 1, &interactiveParameter);
if (error)
return error;
}
}
#if ALWAYS_INTERACTIVE
const char* headlessParameter = "--headless";
/*
* If the macro ALWAYS_INTERACTIVE is set, we invert the logic of headless / interactive
* This is to mimic the old VM behavior
*/
if (!vm_parameter_vector_has_element(¶meters->vmParameters, "--headless") &&
!vm_parameter_vector_has_element(¶meters->imageParameters, "--interactive")){
error = vm_parameter_vector_insert_from(¶meters->imageParameters, 1, &interactiveParameter);
if (error)
return error;
}
/* Ensure we have headless parameter when in interactive mode (the image is expecting it)*/
if (!vm_parameter_vector_has_element(¶meters->vmParameters, "--headless") &&
vm_parameter_vector_has_element(¶meters->imageParameters, "--interactive")) {
error = vm_parameter_vector_insert_from(¶meters->vmParameters, 1, &headlessParameter);
if (error)
return error;
}
#endif
return VM_SUCCESS;
}
void
vm_printUsageTo(FILE *out)
{
fprintf(out,
"Usage: " VM_NAME " [<option>...] [<imageName> [<argument>...]]\n"
" " VM_NAME " [<option>...] -- [<argument>...]\n"
"\n"
"Common <option>s:\n"
" --help Print this help message, then exit\n"
#if ALWAYS_INTERACTIVE
" --headless Run in headless (no window) mode (default: false)\n"
#else
" --headless Run in headless (no window) mode (default: true)\n"
#endif
#ifdef PHARO_VM_IN_WORKER_THREAD
" --worker Run in worker thread (default: false)\n"
#endif
" --logLevel=<level> Sets the log level number (ERROR(1), WARN(2), INFO(3), DEBUG(4), TRACE(5))\n"
" --version Print version information, then exit\n"
" --maxFramesToLog=<cant> Sets the max numbers of Smalltalk frames to log\n"
" --maxOldSpaceSize=<bytes> Sets the max size of the old space. As the other\n"
" spaces are fixed (or calculated from this) with\n"
" this parameter is possible to set the total size.\n"
" It is possible to use k(kB), M(MB) and G(GB).\n"
" --codeSize=<size>[mk] Sets the max size of code zone.\n"
" It is possible to use k(kB), M(MB) and G(GB).\n"
" --edenSize=<size>[mk] Sets the size of eden\n"
" It is possible to use k(kB), M(MB) and G(GB).\n"
" --minPermSpaceSize=<size>[mk] Sets the size of eden\n"
" It is possible to use k(kB), M(MB) and G(GB).\n"
"\n"
"Notes:\n"
"\n"
" <imageName> defaults to `Pharo.image'.\n"
" <argument>s are ignored, but are processed by the Pharo image.\n"
" Precede <arguments> by `--' to use default image.\n");
}
static VMErrorCode
processLogLevelOption(const char* value, VMParameters * params)
{
int intValue = 0;
intValue = strtol(value, NULL, 10);
if(intValue == 0)
{
logError("Invalid option for logLevel: %s\n", value);
vm_printUsageTo(stderr);
return VM_ERROR_INVALID_PARAMETER_VALUE;
}
logLevel(intValue);
return VM_SUCCESS;
}
static VMErrorCode
processMaxFramesToPrintOption(const char* value, VMParameters * params)
{
int intValue = 0;
intValue = strtol(value, NULL, 10);
if(intValue < 0)
{
logError("Invalid option for maxFramesToLog: %s\n", value);
vm_printUsageTo(stderr);
return VM_ERROR_INVALID_PARAMETER_VALUE;
}
params->maxStackFramesToPrint = intValue;
return VM_SUCCESS;
}
static VMErrorCode
processMaxOldSpaceSizeOption(const char* originalArgument, VMParameters * params)
{
long long intValue = parseByteSize(originalArgument);
if(intValue < 0)
{
logError("Invalid option for maxOldSpaceSize: %s\n", originalArgument);
vm_printUsageTo(stderr);
return VM_ERROR_INVALID_PARAMETER_VALUE;
}
params->maxOldSpaceSize = intValue ;
return VM_SUCCESS;
}
static VMErrorCode
processMaxCodeSpaceSizeOption(const char* originalArgument, VMParameters * params)
{
long long intValue = parseByteSize(originalArgument);
if(intValue < 0)
{
logError("Invalid option for codeSize: %s\n", originalArgument);
vm_printUsageTo(stderr);
return VM_ERROR_INVALID_PARAMETER_VALUE;
}
params->maxCodeSize = intValue;
return VM_SUCCESS;
}
static VMErrorCode
processMinPermSpaceSizeOption(const char* originalArgument, VMParameters * params)
{
long long intValue = parseByteSize(originalArgument);
if(intValue < 0)
{
logError("Invalid option for min perm space size: %s\n", originalArgument);
vm_printUsageTo(stderr);
return VM_ERROR_INVALID_PARAMETER_VALUE;
}
params->minPermSpaceSize = intValue;
return VM_SUCCESS;
}
static VMErrorCode
processEdenSizeOption(const char* originalArgument, VMParameters * params)
{
long long intValue = parseByteSize(originalArgument);
if(intValue < 0)
{
logError("Invalid option for eden: %s\n", originalArgument);
vm_printUsageTo(stderr);
return VM_ERROR_INVALID_PARAMETER_VALUE;
}
params->edenSize = intValue;
return VM_SUCCESS;
}
static VMErrorCode
processWorkerOption(const char* argument, VMParameters * params)
{
params->isWorker = true;
return VM_SUCCESS;
}
static VMErrorCode
processHelpOption(const char* argument, VMParameters * params)
{
(void)argument;
vm_printUsageTo(stdout);
return VM_ERROR_EXIT_WITH_SUCCESS;
}
static VMErrorCode
processPrintVersionOption(const char* argument, VMParameters * params)
{
(void)argument;
printf("%s\n", getVMVersion());
printf("Built from: %s\n", getSourceVersion());
return VM_ERROR_EXIT_WITH_SUCCESS;
}
static VMErrorCode
processVMOptions(VMParameters* parameters)
{
VMParameterVector *vector = ¶meters->vmParameters;
for(size_t i = 1; i < vector->count; ++i)
{
const char *param = vector->parameters[i];
if(!param)
{
break;
}
// We only care about specific parameters here.
if(*param != '-')
{
continue;
}
#ifdef __APPLE__
// Ignore the process serial number special argument passed to OS X applications.
if(strncmp(param, "-psn_", 5) == 0)
{
continue;
}
#endif
// Ignore the leading dashes (--)
const char *argumentName = param + 1;
if(*argumentName == '-')
{
++argumentName;
}
// Find the argument value.
const char *argumentValue = strchr(argumentName, '=');
size_t argumentNameSize = strlen(argumentName);
if(argumentValue != NULL)
{
argumentNameSize = argumentValue - argumentName;
++argumentValue;
}
// Find a matching parameter
const VMParameterSpec *paramSpec = findParameterWithName(argumentName, argumentNameSize);
if(!paramSpec)
{
logError("Invalid or unknown VM parameter %s\n", param);
vm_printUsageTo(stderr);
return VM_ERROR_INVALID_PARAMETER;
}
// If the parameter has a required argument, it may be passed as the next parameter in the vector.
if(paramSpec->hasArgument)
{
// Try to fetch the argument from additional means
if(argumentValue == NULL)
{
if(i + 1 < vector->count)
{
argumentValue = vector->parameters[++i];
}
}
// Make sure the argument value is present.
if(argumentValue == NULL)
{
logError("VM parameter %s requires a value\n", param);
vm_printUsageTo(stderr);
return VM_ERROR_INVALID_PARAMETER_VALUE;
}
}
// Invoke the VM parameter processing function.
if(paramSpec->function)
{
VMErrorCode error = paramSpec->function(argumentValue, parameters);
if(error) return error;
}
}
return VM_SUCCESS;
}
EXPORT(VMErrorCode)
vm_parameters_parse(int argc, const char** argv, VMParameters* parameters)
{
char* fullPath;
#ifdef __APPLE__
//If it is OSX I read parameters from the PList
fillParametersFromPList(parameters);
#endif
//We read the arguments from the command line, and override whatever is set before
VMErrorCode error = fillUpImageName(argc, argv, parameters);
if(error) return error;
// Split the argument vector in two separate vectors (If there is no Image, it gives a default one).
error = splitVMAndImageParameters(argc, argv, parameters);
if(error) return error;
// I get the VM location from the argv[0]
char *fullPathBuffer = (char*)calloc(1, FILENAME_MAX);
if(!fullPathBuffer)
{
vm_parameters_destroy(parameters);
return VM_ERROR_OUT_OF_MEMORY;
}
#if _WIN32
WCHAR pathString[MAX_PATH];
char encodedPath[MAX_PATH];
GetModuleFileNameW(NULL, pathString, MAX_PATH);
WideCharToMultiByte(CP_UTF8, 0, pathString, -1, encodedPath, FILENAME_MAX, NULL, 0);
fullPath = getFullPath(encodedPath, fullPathBuffer, FILENAME_MAX);
#else
fullPath = getFullPath(argv[0], fullPathBuffer, FILENAME_MAX);
#endif
setVMPath(fullPath);
free(fullPathBuffer);
error = processVMOptions(parameters);
if(error)
{
vm_parameters_destroy(parameters);
return error;
}
logParameters(parameters);
return VM_SUCCESS;
}
EXPORT(VMErrorCode)
vm_parameters_init(VMParameters *parameters){
parameters->vmParameters.count = 0;
parameters->vmParameters.parameters = NULL;
parameters->imageParameters.count = 0;
parameters->imageParameters.parameters = NULL;
parameters->maxStackFramesToPrint = 0;
parameters->maxCodeSize = 0;
parameters->maxOldSpaceSize = 0;
parameters->edenSize = 0;
parameters->minPermSpaceSize = 0;
parameters->imageFileName = NULL;
parameters->isDefaultImage = false;
parameters->defaultImageFound = false;
parameters->isInteractiveSession = false;
parameters->isWorker = false;
return VM_SUCCESS;
}
|
C | #include<stdio.h>
#include<math.h>
#include<stdlib.h>
int main(void)
{
int op = 0, a = 0, b = 0, temporary = 0, min = 0, max = 0, power = 0;
double var = 0.0, def = 0.0, pi = 3.14159;
printf("enter integer a:\n");
scanf("%i", &a);
printf("enter integer b:\n");
scanf("%i", &b);
printf("enter operation code:\n'");
scanf("%i", &op);
var = ((6 * cos(b * pi)) / (a - 2));
def = (op % abs(a + 1)) + (op % abs(b + 1));
if (op < 0)
{
op = abs(op);
a = temporary;
temporary = b;
a = b;
}
if (a > b)
{
max = a;
}
else
{
max = b;
}
if (a > b)
{
min = b;
}
else
{
min = a;
}
power = pow(a, b);
switch (op)
{
case 0:
printf("a + b = %i\n", a + b);
break;
case 1:
printf("a - b = %i\n", a - b);
break;
case 2:
printf("a * b = %i\n", a * b);
break;
case 3:
printf("a / b = %i\n", a / b);
break;
case 4:
printf("abs(a) = %i\n", abs(a));
break;
case 5:
printf("min(a, b) = %i\n", min);
break;
case 6:
printf("max(a, b) = %i\n", max);
break;
case 7:
case 13:
printf("pow(a, b) = %i\n", power);
break;
case 8:
if (a == 2)
{
printf("Deviding by zero\n");
}
else
{
printf("var(a, b) = %f\n", var);
}
break;
default:
if(a == -1 || b == -1)
{
printf("Deviding by zero\n");
}
else
{
printf("def(a, b) = %f\n", def);
}
}
return 0;
}
|
C | /*
* Add container to existing handler
*/
int wizToolkit_Add_Container(WIZTOOLKIT_INOUT wizToolkitHandler *handler, WIZTOOLKIT_IN wizToolkitObjectContainer *container,
WIZTOOLKIT_OUT long * containerId)
{
long counter;
unsigned char foundHole = 0;
#ifdef _DEBUG
printf("wizToolkit_Add_Container(%p, %p, %p)\n", handler, container, containerId);
#endif
if ( NULL == handler )
{
#ifdef _DEBUG
printf("wizToolkit_Add_Container -> trying to allocate new container on a invalid hanlder (%p)\n", handler);
#endif
return WIZTOOLKIT_ERROR;
}
// find empty container
for (counter = 0; counter < WIZTOOLKIT_MAX_CONTAINERS;counter++)
{
if ( WIZTOOLKIT_CONTAINER_FREE == handler->containers[counter].type)
{
#ifdef _DEBUG
printf("wizToolkit_Add_Container -> free container found at %lu\n", counter);
#endif
foundHole = 1;
break;
}
}
// we found a hole?
if ( foundHole == 0)
{
#ifdef _DEBUG
printf("wizToolkit_Add_Container -> handler full (%p)\n", handler);
#endif
return WIZTOOLKIT_ERROR;
}
*containerId = counter;
handler->containers[counter].type = container->type;
handler->containers[counter].object = container->object;
return WIZTOOLKIT_OK;
}
/*
* Remove container from existing handler
*/
int wizToolkit_Remove_Container(WIZTOOLKIT_INOUT wizToolkitHandler *handler, WIZTOOLKIT_IN long containerId)
{
#ifdef _DEBUG
printf("wizToolkit_Remove_Container(%p, %li)\n", handler, containerId);
#endif
if ( NULL == handler )
{
#ifdef _DEBUG
printf("wizToolkit_Remove_Container -> trying to remove container on a invalid hanlder (%p)\n", handler);
#endif
return WIZTOOLKIT_ERROR;
}
if ( WIZTOOLKIT_MAX_CONTAINERS < containerId )
{
#ifdef _DEBUG
printf("wizToolkit_Remove_Container -> trying to remove container out of bounds (%li) WIZTOOLKIT_MAX_CONTAINERS=%i\n",
containerId, WIZTOOLKIT_MAX_CONTAINERS);
#endif
return WIZTOOLKIT_ERROR;
}
// note: free don't need this, but...
if ( NULL != handler->containers[containerId].object )
{
free(handler->containers[containerId].object);
handler->containers[containerId].object = NULL;
}
handler->containers[containerId].type = WIZTOOLKIT_CONTAINER_FREE;
return WIZTOOLKIT_OK;
}
|
C | #include <stdio.h>
int main ()
{
int n[5];
int i;
n[0]=200;
n[1]=250;
n[2]=350;
n[3]=100;
n[4]=300;
for(i=0; i<5; i++)
{
printf("element ke-%d=%d\n", i, n[i]);
}
return 0;
}
|
C | #include <stdio.h>
int fakt(int n) {
int f;
fot(i=1;1<=n; i++)
f*=i;
return f;
}
int main()
{
int n=5;
printf("%d faktorilis %d\n", n, fakt(n));
}
|
C | int main()
{
int k,a,n,i;
double x[100][1000],sum1,sum2,pj,s;
scanf("%d",&k);
for(a=0;a<k;a++){
sum1=0;pj=0;
scanf("%d",&n);
for(i=0;i<n;i++){
scanf("%lf",&x[a][i]);
sum1+=x[a][i];}
pj=(double)sum1/n;
sum2 = 0;
for(i=0;i<n;i++){
sum2+=(double)(x[a][i]-pj)*(x[a][i]-pj);
}
s=sqrt(sum2/n);
printf("%.5f\n",s);
}
return 0;
}
|
C | #include "analyse.h"
//int sign;
//int sign_x;
//int sign_y;
/**
* @brief analyse
* @param K210/OPEN MV/ݮɵ
* @retval OPEN MV ֱ x=160 y=120ĵΪ(80,60)
*/
void analyse(u8 data)
{
//printf("%s",data);
static u8 RxBuffer[10];
static u8 state = 0;
/*ͨŸʽ 0xAA data0 data1 data2 checkout 0x54*/
/*checkout=(data1+data2)Ͱλ data0 = 0x00,data1=0xe1,data2=0xf3,data1+data2=0x1d4,checkout=0xd4*/
if(state==0&&data==0xAA)
state=1;
else if(state==1)
{
RxBuffer[0]=data; //Ԫر־
state=2;
}
else if(state==2)
{
RxBuffer[1]=data; //x
state=3;
}
else if(state==3)
{
RxBuffer[2]=data; //y
state = 4;
}
else if(state==4)
{
RxBuffer[3]=data;//checkout
state = 5;
}
else if(state==5&&data==0x54)
{
if(RxBuffer[3]==(u8)(RxBuffer[1]+RxBuffer[2]))//Уɹ
{
sign = RxBuffer[0];
sign_x=RxBuffer[1];
sign_y=RxBuffer[2];
}
state = 0;
}
else
state = 0;
}
|
C | //pascal triangle
#include <stdio.h>
//#include <conio.h>
int fact(int n)
{
int i,r=1;
for(i=n;i>0;i--)
{
r+=r*n;
}
return r;
}
int main()
{
int i,k,j,num=4,space=4;
for(i=0;i<num;i++)
{
for(k=space;k>0;k--)
{
printf(" ");
}
space--;
for(j=0;j<=i;j++)
{
printf("%d",fact(i)/(fact(j)*fact(i-j)));
printf(" ");
}
printf("\n");
}
return 0;
}
|
C | /*
* char_count_update.c
*
* Created on: Nov 17, 2019
* Author: SURAJ THITE & Atharv Desai
*/
#include "char_count_update.h"
uint8_t char_count[256];
/*******************************************************************************************************
* Function Name:uint8_t* character_count(uint8_t *char_val)
* Description :This function receives the character and updates its count in the char_count array
* @input: pointer to uint8_t
* @Return : pointer
*******************************************************************************************************/
uint8_t* character_count(uint8_t *char_val)
{
char_count[*char_val] ++; //Increment character value in the char_count global variable
return char_count; //Return pointer to array
}
/*******************************************************************************************************
* Function Name: void generate_report()
* Description : This function generates report to be printed on detection of '.' character
* @input: void
* @Return : void
*******************************************************************************************************/
void generate_report()
{
printf("\n \r");
for (int i=65;i<=90;i++) //Check for A-Z and a-z ascii characters only
{
if(char_count[i]!=0) //If count is not zero , print the value
{
printf("%c-%d,",i,char_count[i]);
}
}
for (int i=97;i<=122;i++)
{
if(char_count[i]!=0)
{
printf("%c-%d,",i,char_count[i]);
}
}
}
|
C | //
// Created by plaut on 3/31/2017.
//
#include "darray.h"
#include <stdlib.h>
struct DArray
{
void **array; //an array of void pointers
int capacity; //total number of slots
int size; //number of filled slots
void (*display)(FILE *,void *); //display function
};
DArray *newDArray(void (*display)(FILE *f, void *d))
{
DArray *d = malloc(sizeof(DArray));
d->array = malloc(sizeof(void*));
d->display = display;
d->capacity = 1;
d->size = 0;
return d;
}
void insertDArray(DArray *a,void *v)
{
a->size++;
if(a->size > a->capacity)
{
a->capacity *= 2;
a->array = realloc(a->array, sizeof(void*) * a->capacity);
}
a->array[a->size-1] = v;
}
void *removeDArray(DArray *a)
{
if(a->size == 0)
{
fprintf(stderr, "ERROR: removing an element from an empty array\n");
exit(-1);
}
void* val = a->array[a->size-1];
a->size--;
a->array[a->size] = NULL;
if(a->capacity > 1 && (a->size < a->capacity/4))
{
a->capacity /= 2;
a->array = realloc(a->array, sizeof(void*) * a->capacity);
}
return val;
}
void *getDArray(DArray *a, int index)
{
void* v;
if(index > a->capacity)
{
fprintf(stdout, "ERROR: accessing an element not in the array\n");
exit(-1);
}
else
{
v = a->array[index];
return v;
}
}
void setDArray(DArray *a, int index, void *value)
{
if(index > (a->capacity))
{
fprintf(stdout, "ERROR: setting an index not in the array\n");
exit(-1);
}
else if(index == (a->size))
insertDArray(a, value);
else
a->array[index] = value;
}
int sizeDArray(DArray *a)
{
return a->size;
}
void displayDArray(FILE *f,DArray *a)
{
fprintf(f, "[");
for(int i = 0; i < a->size; i++)
{
if(i < (a->size-1))
fprintf(f, "%d,", *((int*)a->array[i]));
else
fprintf(f, "%d", *((int*)a->array[i]));
}
fprintf(f, "]");
fprintf(f, "[");
fprintf(f, "%d", (a->capacity - a->size));
fprintf(f, "]");
} |
C | #include <stdio.h>
#include <stdlib.h>
#include "listaEncadeada.h"
int main() {
Lista* lista1 = create();
add(lista1, 6);
add(lista1, 1);
add(lista1, 7);
add(lista1, 2);
add(lista1, 5);
imprimirLista(lista1);
printf ("Elemento 2 esta na posicao: %d\n\n", find(lista1, 2));
pop(lista1, 6);
imprimirLista(lista1);
pop(lista1, 5);
imprimirLista(lista1);
pop(lista1, 7);
imprimirLista(lista1);
lista1 = clear(lista1);
imprimirLista(lista1);
return 0;
}
|
C | #define _CRT_SECURE_NO_WARNINGS 1
//#include<stdio.h>
//int nums(int x[3][3])
//{
// int b[3][3];
// int i, j;
// int m=0, n=0;
// for (i = 0; i < 3; i++)
// {
// for (j = 0; j < 3; j++)
// {
// b[m][n] = x[i][j];
// m++;
// }
// n++;
// }
// return b[m][n];
//}
//int main()
//{
// int a[3][3] = { {1,2,3},{1,2,3},{1,2,3} };
// printf("%d ", nums(a[3][3]));
// return 0;
//}
//#include<stdio.h>
//void nums(char name, int n)
//{
// printf("input teachers name and date:");
// for (int j = 0; j < 10;j++)
// scanf("%c %d", &name, &n);
// for (int i = 0; i < 10; i++);
// printf("%c %d", name, n);
//}
//void sort(int n[10], int m)
//{
// int i,j,k, t;
// for (i = 0; i < 10; i++)
// {
// k = i;
// for (j = i + 1; j < 10; j++)
// if (n[j] < n[k])
// k = j;
// t = n[k];
// n[k] = n[j];
// n[j] = t;
//}
//int main()
//{
// char name = {0};
// int n=0;
// nums(name, n);
// //sort(n[10], m);
// //for (i = 0; i < 10;i++)
// return 0;
//}
//#include<stdio.h>
//int main()
//{
// int a[10];
// int *p, i;
// printf("please enter 10 interger number:");
// for (i = 0; i < 10; i++)
// {
// scanf("%d", &a[i]);
// }
// for (p = a; p < (a + 10); p++)
// {
// printf("%d", *p);
// }
// printf("\n");
// return 0;
//}
//#include<stdio.h>
//int main()
//{
// void inv(int x[], int n);
// int i, a[10] = { 3,7,9,11,0,6,7,5,4,2 };
// printf("The original array:\n");
// for (i = 0; i < 10; i++)
// printf("%d ", a[i]);
// printf("\n");
// inv(a, 10);
// printf("The array has been inverted:\n");
// for (i = 0; i < 10; i++)
// printf("%d ", a[i]);
// printf("\n");
// return 0;
//}
//void inv(int x[], int n)
//{
// int temp, i, j, m = (n - 1) / 2;
// for (i = 0; i <=m; i++)
// {
// j = n - 1 - i;
// temp = x[i];
// x[i] = x[j];
// x[j] = temp;
// }
// return;
//}
//#include<stdio.h>
//void inv(int *x, int n)
//{
// int *p,temp, *i, *j, m = (n - 1) / 2;
// i = x;
// j = x + n - 1;
// p = x + m;
// for (; i <= p; i++, j--)
// {
// temp = *i;
// *i = *j;
// *j = temp;
// }
//}
//int main()
//{
// int i;
// int a[10] = { 3,7,9,1,0,6,7,5,4,2 };
// printf("The original array:\n");
// for (i = 0; i < 10; i++)
// printf("%2d", a[i]);
// printf("\n");
// inv(a, 10);
// printf("The array has been inverted:\n");
// for (i = 0; i < 10; i++)
// printf("%2d", a[i]);
// printf("\n");
// return 0;
//}
//#include<stdio.h>
//void sort(int x[], int n)
//{
// int i, j, k, t;
// for (i = 0; i < n - 1; i++)
// {
// k = i;
// for (j = i + 1; j < n; j++)
// {
// if (x[j] > x[k]) k = j;
// if (k != i)
// {
// t = x[i];
// x[i] = x[k];
// x[k] = t;
// }
// }
// }
//}
//int main()
//{
// int i, *p, a[10];
// p = a;
// printf("please enter 10 integer numbers:");
// for (i = 0; i < 10; i++)
// scanf("%d", p++);
// p = a;
// sort(p, 10);
// for (p = a, i = 0; i < 10; i++)
// {
// printf("%d ", *p);
// p++;
// }
// printf("\n");
// return 0;
//}
//#include<stdio.h>
//int main()
//{
// int a[3][4] = { 1,3,5,7,9,11,13,15,17,19,21,23 };
// int *p;
// for (p = a[0]; p < a[0] + 12; p++)
// {
// if ((p - a[0]) % 4 == 0) printf("\n");
// printf("%4d", *p);
// }
// printf("\n");
// return 0;
//}
//#include<stdio.h>
//int main()
//{
// int a[3][4] = { 1,3,5,7,9,11,13,15,17,19,21,23 };
// int(*p)[4], i, j; //ָpָ4Ԫصһ
// p = a; //pָά0
// printf("please enter row and colun:");
// scanf("%d,%d", &i, &j);
// printf("a[%d,%d]=%d\n", i, j, *(*(p+i)+j)); //a[i][j]ֵ
// return 0;
//}
//#include<stdio.h>
//void search(float(*p)[4], int n)
//{
// int i, j, flag;
// for (j = 0; j < 4; j++)
// {
// flag = 0;
// for (i = 0; i < 4;i++)
// if (*(*(p + j) + i) < 60) flag = 1;
// if (flag == 1)
// {
// printf("No.%d fails,his score are:\n", j + 1);
// for (i = 0; i < 4; i++)
// printf("%5.1f", *(*(p + j) + i));
// printf("\n");
// }
// }
//}
//int main()
//{
// float score[3][4] = { {65,57,70,60},{58,87,90,81},{90,99,100,98} };
// search(score, 3);
// return 0;
//}
//#include<stdio.h>
//int main()
//{
// char a[] = "I am a student.", b[20];
// int i;
// for (i = 0; *(a + i) != '\0'; i++)
// *(b + i) = *(a + i);
// *(b + i) = '\0';
// printf("string a is:%s\n", a);
// printf("string b is:");
// for (i = 0; b[i] != '\0'; i++)
// printf("%c", b[i]);
// printf("\n");
// return 0;
//}
//#include<stdio.h>
//int main()
//{
// char a[] = "I am a boy.", b[20], *p1, *p2;
// p1 = a;
// p2 = b;
// for (; *p1 != '\0'; p1++, p2++)
// *p2 = *p1;
// *p2 = '\0';
// printf("string a is:%s\n", a);
// printf("string b is:%s\n", b);
// return 0;
//}
#include<stdio.h>
int main()
{
int max(int, int);
int(*p)(int, int);
int a, b, c;
p = max;
printf("please enter a and b:");
scanf("%d,%d", &a, &b);
c = (*p)(a,b);
printf("a=%d\nb=%d\nmax=%d\n", a, b, c);
return 0;
}
int max(int x, int y)
{
int z;
if (x > y) z = x;
else z = y;
return(z);
} |
C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LEN 40
int main(int argc , char * argv[])
{
FILE *in, *out; //ָFILEָ
int ch;
char name[LEN]; //ļ
int count = 0;
//
if(argc < 2) //argcûcmdõַС1ʼ
{
fprintf(stderr, "Usage: %s filename\n", argv[0]);
exit(EXIT_FAILURE);
}
//
if((in = fopen(argv[1], "r")) == NULL) //ʹargvĵڶԪ
{
fprintf(stderr, "I couldn't open the file\"%s\"\n", //ļ%s\ n
argv[1]);
exit(EXIT_FAILURE); //쳣ֹ
}
//
strncpy(name, argv[1], LEN - 5); //ļַ
name[LEN - 5] = '\0';
strcat(name, ".red"); //ļ.red
if((out = fopen(name, "w")) == NULL)
{
fprintf(stderr, "Can't create output file.\n"); //ļ
exit(3);
}
//
while((ch = getc(in)) != EOF)
if(count++ % 3 == 0)
putc(ch, out); //ӡ3ַĵһַļ
//β
if(fclose(in) != 0 || fclose(out) != 0)
fprintf(stderr, "Error in closing files\n");
return 0;
}
|
C | #include "monty.h"
/**
* _stack - function that sets the format of the data to a stack (LIFO).
* @h: pointer to the head of the stack
* @times: Number of the current line.
* Return: Nothing it is a void function.
*/
void _stack(stack_t **h, unsigned int times)
{
(void)h;
(void)times;
tools.mode = STACK;
}
/**
* _queue - function that sets the format of the data to a queue (FIFO).
* @h: pointer to the head of the stack
* @times: Number of the current line.
* Return: Nothing it is a void function.
*/
void _queue(stack_t **h, unsigned int times)
{
(void)h;
(void)times;
tools.mode = QUEUE;
}
|
C | #include "mmu.h"
#include <stdlib.h>
#include <stdio.h>
#include "request.h"
#include "inter_alg.h"
#include "process.h"
/**
* vetor que marca, para cada quadro de página, se ele está atualmente atrelado a alguma página virtual,
* isto é, se ele está sendo usado.
* Utiliza a mesma tag PRESENT ou NOT_PRESENT para indicar se está sendo ou usado ou não, respectivamente.
* O tamanho do vetor é constante e é representando por NUMBER_OF_FRAMES.
*/
int *frames_status = NULL;
/**
* O contador global de instruções inicia com 0 e é incrementado automaticamente conforme novas requisições chegam
* (incrementado no arquivo 'request').
* Este contador é utilizado quando o algortimo LRU está habilitado.
*/
int global_instruction_counter = 0;
int get_global_instruction_counter()
{
return global_instruction_counter;
}
void inc_global_instruction_counter()
{
global_instruction_counter++;
}
void initialize_frames()
{
frames_status = malloc(sizeof(int) * NUMBER_OF_FRAMES);
for (int i = 0; i < NUMBER_OF_FRAMES; i++)
{
frames_status[i] = NOT_PRESENT;
}
}
int get_number_of_used_frames()
{
int count = 0;
if (frames_status == NULL)
{
initialize_frames();
return 0;
}
for (int i = 0; i < NUMBER_OF_FRAMES; i++)
{
count += frames_status[i];
}
return count;
}
int get_number_of_free_frames()
{
return NUMBER_OF_FRAMES - get_number_of_used_frames();
}
int *mark_frame(int *frame_number_bits, int status)
{
if (frames_status == NULL)
{
initialize_frames();
}
int frame_number = get_decimal_from_bits(frame_number_bits, FRAME_NUMBER_LEN);
if (frame_number >= 0 && frame_number < NUMBER_OF_FRAMES)
{
frames_status[frame_number] = status;
return frame_number_bits;
}
return NULL;
}
int *get_first_free_frame()
{
if (get_number_of_free_frames() == 0)
{
return NULL;
}
int i = 0;
for (; i < NUMBER_OF_FRAMES; i++)
{
if (frames_status[i] == NOT_PRESENT)
{
break;
}
}
if (i < NUMBER_OF_FRAMES)
{
return get_bits_from_decimal(i, FRAME_NUMBER_LEN);
}
return NULL;
}
PAGES_TABLE *create_and_assign_pages_table()
{
PAGES_TABLE *table = malloc(sizeof(PAGES_TABLE));
table->pages = malloc(sizeof(PAGE) * NUMBER_OF_PAGES);
for (int i = 0; i < NUMBER_OF_PAGES; i++)
{
table->pages[i].frame_number = get_bits_from_decimal(0, FRAME_NUMBER_LEN);
table->pages[i].modified = NOT_MODIFIED;
table->pages[i].present = NOT_PRESENT;
table->pages[i].referenced = 0;
}
return table;
}
ADDRESS *map_to_physical_address(ADDRESS *virtual_address, PAGES_TABLE *table, char op, int **page_number_bits)
{
ADDRESS *physical_address = NULL;
*page_number_bits = malloc(sizeof(int) * PAGE_NUMBER_LEN);
for (int i = 0; i < PAGE_NUMBER_LEN; i++)
{
(*page_number_bits)[i] = virtual_address->bits[i];
}
int page_number = get_decimal_from_bits((*page_number_bits), PAGE_NUMBER_LEN);
if (page_number >= 0 && page_number < NUMBER_OF_PAGES)
{
if (table->pages[page_number].present == PRESENT)
{
int *physical_bits = malloc(sizeof(int) * PHYSICAL_ADDRESS_SIZE);
// copia o número do quadro de página.
for (int i = 0; i < FRAME_NUMBER_LEN; i++)
{
physical_bits[i] = table->pages[page_number].frame_number[i];
}
// copia o valor do deslocamento.
int mov = PAGE_NUMBER_LEN;
for (int i = FRAME_NUMBER_LEN; i < PHYSICAL_ADDRESS_SIZE; i++)
{
physical_bits[i] = virtual_address->bits[mov++];
}
physical_address = get_address_from_bits(physical_bits, PHYSICAL_ADDRESS_SIZE);
// sempre marca como referenciada, nesse caso.
switch (CURRENT_METHOD)
{
case LRU:
table->pages[page_number].referenced = get_global_instruction_counter();
break;
case CLOCK:
table->pages[page_number].referenced = 1;
break;
}
if (op == W)
{
table->pages[page_number].modified = MODIFIED;
}
}
else
{
printf("Falta de Página! Endereço Virtual '%llu' (%s). Página N° '%d'.\n",
virtual_address->decimal,
get_bits_string_address(virtual_address),
page_number);
}
}
else
{
printf("O endereço virtual '%llu' (%s) não pertence ao espaço de endereçamento virtual.\n",
virtual_address->decimal,
get_bits_string_address(virtual_address));
(*page_number_bits) = NULL;
}
return physical_address;
}
int count_mapped_pages(PAGES_TABLE *table)
{
int count = 0;
for (int i = 0; i < NUMBER_OF_PAGES; i++)
{
count += table->pages[i].present;
}
return count;
}
PAGES_TABLE *map_page(PAGES_TABLE *table, PAGE *page)
{
if (page == NULL)
{
return NULL;
}
int *frame_number_bits = get_first_free_frame();
if (frame_number_bits == NULL)
{
return NULL;
}
mark_frame(frame_number_bits, PRESENT);
page->frame_number = frame_number_bits;
page->modified = NOT_MODIFIED;
page->present = PRESENT;
page->referenced = 0;
insert_page(page);
return table;
}
PAGES_TABLE *map_pages_set(PAGES_TABLE *table, PAGE *pages_set, int size)
{
if (size > get_number_of_free_frames())
{
return NULL;
}
for (int i = 0; i < size; i++)
{
if (map_page(table, &pages_set[i]) == NULL)
{
return NULL;
}
}
return table;
}
int *get_first_present_page(PAGES_TABLE *table)
{
for (int i = 0; i < NUMBER_OF_PAGES; i++)
{
if (table->pages[i].present == PRESENT)
{
return get_bits_from_decimal(i, PAGE_NUMBER_LEN);
}
}
return NULL;
}
void unmap_whole_pages_table(PAGES_TABLE *table)
{
for (int i = 0; i < NUMBER_OF_PAGES; i++)
{
table->pages[i].present = NOT_PRESENT;
}
}
void free_pages_table(PAGES_TABLE *table)
{
printf("Liberando tabela de páginas...\n");
if (table != NULL && table->pages != NULL)
{
for (int i = 0; i < NUMBER_OF_PAGES; i++)
{
if (table->pages[i].present == PRESENT)
{
if (remove_page(&table->pages[i]) == NULL)
{
printf("Não foi possível remover a página '%d' (%s) da tabela global de páginas.\n",
i,
get_bits_string_from_decimal(i, PAGE_NUMBER_LEN));
}
mark_frame(table->pages[i].frame_number, NOT_PRESENT);
}
}
free(table->pages);
free(table);
}
}
void print_RAM_situation()
{
printf("Utilização dos quadros de página: %d/%d\n", get_number_of_used_frames(), NUMBER_OF_FRAMES);
}
int *get_page_number_from_page(PAGE *page)
{
PROCESS *process = find_process_from_page(page);
if (process == NULL)
{
return NULL;
}
int i = 0;
for (; i < NUMBER_OF_PAGES; i++)
{
if (&process->pages_table->pages[i] == page)
{
break;
}
}
return get_bits_from_decimal(i, PAGE_NUMBER_LEN);
} |
C | // CEF C API example
// Project website: https://github.com/cztomczak/cefcapi
#pragma once
#include <unistd.h>
#include "include/capi/cef_base_capi.h"
// Set to 1 to check if add_ref() and release()
// are called and to track the total number of calls.
// add_ref will be printed as "+", release as "-".
#define DEBUG_REFERENCE_COUNTING 0
// Print only the first execution of the callback,
// ignore the subsequent.
#define DEBUG_CALLBACK(x) { \
static int first_call = 1; \
if (first_call == 1) { \
first_call = 0; \
printf(x); \
} \
}
// ----------------------------------------------------------------------------
// cef_base_ref_counted_t
// ----------------------------------------------------------------------------
///
// Structure defining the reference count implementation functions.
// All framework structures must include the cef_base_ref_counted_t
// structure first.
///
///
// Increment the reference count.
///
void CEF_CALLBACK add_ref(cef_base_ref_counted_t* self) {
DEBUG_CALLBACK("cef_base_ref_counted_t.add_ref\n");
if (DEBUG_REFERENCE_COUNTING)
printf("+");
}
///
// Decrement the reference count. Delete this object when no references
// remain.
///
int CEF_CALLBACK release(cef_base_ref_counted_t* self) {
DEBUG_CALLBACK("cef_base_ref_counted_t.release\n");
if (DEBUG_REFERENCE_COUNTING)
printf("-");
return 1;
}
///
// Returns the current number of references.
///
int CEF_CALLBACK has_one_ref(cef_base_ref_counted_t* self) {
DEBUG_CALLBACK("cef_base_ref_counted_t.has_one_ref\n");
if (DEBUG_REFERENCE_COUNTING)
printf("=");
return 1;
}
void initialize_cef_base_ref_counted(cef_base_ref_counted_t* base) {
printf("initialize_cef_base_ref_counted\n");
// Check if "size" member was set.
size_t size = base->size;
// Let's print the size in case sizeof was used
// on a pointer instead of a structure. In such
// case the number will be very high.
printf("cef_base_ref_counted_t.size = %lu\n", (unsigned long)size);
if (size <= 0) {
printf("FATAL: initialize_cef_base failed, size member not set\n");
_exit(1);
}
base->add_ref = add_ref;
base->release = release;
base->has_one_ref = has_one_ref;
}
|
C | #include "suffixtrie.h"
struct nodo * insere(char *str, struct nodo *raiz)
{
struct nodo *new;
if(*(str)!='\0')
{
if(raiz==NULL || raiz->caractere != *(str) )
{
if(raiz == NULL || raiz->caractere > *(str) ) //Se não existe o caractere no nivel
{ //cria um novo nodo com o caractere no nivel
if(!(new = malloc( sizeof (struct nodo) )))
{
return raiz;
}
new->caractere = *str;
new->prox = raiz; //insere o proximo valido ou null (que eh a raiz se for o ultimo do nivel)
new->filho = NULL;
str++;
new->filho = insere(str, new->filho);
return new;
}
else
{
raiz->prox = insere(str, raiz->prox); //Verifica se existe o caractere no nivel
return raiz;
}
}
else //o nodo e o caractere coincidem
{
str++;
raiz->filho = insere(str, raiz->filho); //Manda o proximo caractere para o nivel debaixo
return raiz;
}
}
return raiz;
}
struct nodo * busca(struct nodo *raiz, char *str, int *nchar, char *strbuffer, int *maior, struct palindromo *lista)
{
int temp;
if(raiz!=NULL)
{
if(raiz->caractere == *str)
{
strbuffer = realloc(strbuffer,1+(*nchar)*sizeof(char));
strbuffer[*nchar] = raiz->caractere;
(*nchar)++;
str++;
raiz->filho = busca(raiz->filho,str,nchar,strbuffer,maior,lista);
}
else if(raiz->caractere < *str)
{
raiz->prox = busca(raiz->prox,str,nchar,strbuffer,maior,lista);
}
else if(*nchar >= *maior)
{
*maior = *nchar;
strbuffer = realloc(strbuffer,1+(*nchar)*sizeof(char));
strbuffer[*nchar] = '\0';
if(*strbuffer == strbuffer[*nchar-1])
{
lista = inserelista(strbuffer,lista,nchar);
}
}
}
else if(*nchar >= *maior)
{
*maior = *nchar;
strbuffer = realloc(strbuffer,1+(*nchar)*sizeof(char));
strbuffer[*nchar] = '\0';
if(*strbuffer == strbuffer[*nchar-1])
{
lista = inserelista(strbuffer,lista,nchar);
}
}
return raiz;
}
struct palindromo * inserelista(char *str, struct palindromo *first, int *nchar)
{
struct palindromo *new;
//printf("%s\n",str);
if(first==NULL)
{
first = malloc(sizeof(struct palindromo));
first->palavra = NULL;
first->prox = NULL;
first->tamanho = 0;
}
if(first->palavra == NULL)
{
first->tamanho = (int) *nchar;
first->palavra = malloc(*nchar * sizeof(char));
strcpy(first->palavra,str);
}
else
{
first->prox = inserelista(str,first->prox,nchar);
}
return first;
}
struct nodo * printTree(struct nodo *raiz)
{
if(raiz!=NULL)
{
printf("%p - %c - %p - %p\n",raiz, raiz->caractere, raiz->prox, raiz->filho);
if(raiz->filho!=NULL)
{
raiz->filho = printTree(raiz->filho);
}
if(raiz->prox!=NULL)
{
raiz->prox = printTree(raiz->prox);
}
}
return raiz;
}
|
C | #include <stdio.h>
#include <math.h>
#include <x86intrin.h>
#include <mpfr.h>
float
cr_rsqrt (float x)
{
mpfr_t t;
float y;
mpfr_init2 (t, 24);
mpfr_set_flt (t, x, MPFR_RNDN);
mpfr_rec_sqrt (t, t, MPFR_RNDN);
y = mpfr_get_flt (t, MPFR_RNDN);
mpfr_clear (t);
return y;
}
float
rsqrt (float x)
{
float y;
_mm_store_ss( &y, _mm_rsqrt_ss( _mm_load_ss( &x ) ) );
return y;
}
float
ulp_error (float x)
{
float y = rsqrt (x);
float z = cr_rsqrt (x);
float err = fabsf (y - z);
int e;
z = frexpf (z, &e);
/* ulp(z) = 2^(e-24) */
return ldexpf (err, 24 - e);
}
int
main()
{
float x, err, maxerr = 0;
x = 0.0118255867f;
err = ulp_error (x);
printf ("x=%la err=%f\n", x, err);
for (x = 1.0; x < 4.0; x = nextafterf (x, x + x))
{
err = ulp_error (x);
if (err > maxerr)
printf ("x=%la err=%f\n", x, maxerr = err);
}
}
|
C | // To compile this file:
// $ gcc -o filename filename.c -lnfc
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif // HAVE_CONFIG_H
#include <err.h>
#include <nfc/nfc.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_BUF 1024
char* convert_to_hex(const uint8_t *pbtData, const size_t szBytes)
{
size_t szPos;
char* buf_str=(char*) malloc (2*szBytes+1);
char* buf_ptr=buf_str;
for (szPos = 0; szPos < szBytes; szPos++) {
buf_ptr+=sprintf(buf_ptr, "%02x", pbtData[szPos]);
}
*(buf_ptr + 1) = '\0';
return buf_str;
}
int main(int argc, const char *argv[])
{
system("clear");
int fdw, fdr, i;
char buf[MAX_BUF];
char* textInitCon = "Hi";
char* myfifow = "ctopyfifo";
char* myfifor = "pytocfifo";
char* rfidstr;
nfc_device *pnd;
nfc_target nt;
// Allocate only a pointer to nfc_context
nfc_context *context;
// Initialize libnfc and set the nfc_context
nfc_init(&context);
// Display libnfc version
const char *acLibnfcVersion = nfc_version();
printf("%s uses libnfc %s\n", argv[0], acLibnfcVersion);
// Open, using the first available NFC device.
pnd = nfc_open(context, NULL);
if (pnd == NULL) {
warnx("ERROR: %s", "Unable to open NFC device.");
return EXIT_FAILURE;
}
// Set opened NFC device to initiator mode
if (nfc_initiator_init(pnd) < 0) {
nfc_perror(pnd, "nfc_initiator_init");
exit(EXIT_FAILURE);
}
printf("NFC reader: %s opened...\n", nfc_device_get_name(pnd));
/* Create fifos */
mkfifo(myfifow,0666);
mkfifo(myfifor,0666);
/* Send Hi to pipe */
printf("Writing init string TO pipe: >> %s << ...\n", textInitCon);
fdw = open(myfifow, O_WRONLY);
write(fdw, textInitCon, sizeof(textInitCon));
close(fdw);
/* Wait Ok from pipe */
fdr = open(myfifor, O_RDONLY);
read(fdr, buf, MAX_BUF);
printf("Received init string FROM pipe: >> %s << ...\n", buf);
close(fdr);
if (strcmp(buf, "Ok") == 0) {
printf("Init ok, start pushing ...\n\n");
while (strcmp(buf, "Quit") != 0) {
// Poll for a ISO14443A (MIFARE) tag
const nfc_modulation nmMifare = {
.nmt = NMT_ISO14443A,
.nbr = NBR_106,
};
if (nfc_initiator_select_passive_target(pnd, nmMifare, NULL, 0, &nt) > 0) {
rfidstr = convert_to_hex(nt.nti.nai.abtUid, nt.nti.nai.szUidLen);
}
printf("Writing: >> %s << to pipe...\n", rfidstr);
fdw = open(myfifow, O_WRONLY);
write(fdw, rfidstr, strlen(rfidstr));
close(fdw);
fdr = open(myfifor, O_RDONLY);
read(fdr, buf, MAX_BUF);
printf("Received string FROM pipe: >> %s << ...\n", buf);
close(fdr);
}
printf("\nstop pushing ... program terminated!\n\n");
} else {
printf("Init failed, abort!\n");
}
/* Remove fifos */
unlink(myfifow);
unlink(myfifor);
// Close NFC device
nfc_close(pnd);
// Release the context
nfc_exit(context);
return EXIT_SUCCESS;
}
|
C | #include <stdio.h>
int main (void)
{
int cases, temp, match, count, diff;
scanf("%d", &cases);
for (int i = 0; i < cases; i++)
{
scanf("%d", &count);
// Declaring for initial values
temp = 1000005, diff = 0;
while (count--)
{
scanf("%d", &match);
// Only replaces diff if new difference is more
if (match - temp > diff)
diff = match - temp;
/* They do not need consecutive differences.
* say 1 2 4 7 9, Rooney can choose 1 and 9 and show a diff of 8
* So temp has to be replaced with the lower value so that the highest
* diff can be seen
*/
if (temp > match)
temp = match;
}
if (diff > 0)
printf("%d\n", diff);
else
printf("UNFIT\n");
diff = 0;
}
return 0;
} |
C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "defPiece.h"
#include "fct.h"
#include "deplacement.h"
#define clrscr() printf("\033[H\033[2J")
#define couleur(param1, param2) printf("\033[%s;%sm", param1, param2)
#define couleur1(param) printf("\033[%sm", param)
void viderBuffer(){
int c = 0;
while (c != '\n' && c != EOF){
c = getchar();
}
}
int main(int argc, char const *argv[]) {
//Déclaration des variables
piece plateau[SIZE_X][SIZE_Y];
//Déclaration de pièce null
piece vide = {0, 0, 0, "32", ' '};
piece videP = {0, 0, 0, "32", 'X'};
int xInit = 3; //Coordonnée X de la pièce que l'user veut bouger
int yInit = 3; //Coordonnée Y de la pièce que l'user veut bouger
int xDepl = 0; //Coordonnée X de la case ou l'user veut aller
int yDepl = 0; //Coordonnée Y de la case ou l'user veut aller
int echec = 0; //Booleen le roi est en echec
int mat = 0; //Booleen fin de partie
char posInit[3] = "00"; //Coordonnées de la pièce saisie par l'user
char posDepl[3] = "00"; //Coordonnées de la case saisie par l'user
char whoPlay[3] = "34"; //Couleur du joueur qui doit jouer
//Initialisation
initialisation(plateau, vide); //On rempli le plateau avant de commmencer la partie
while(echec == 0){
// if(echec == 0){
//On demande les coordonnées de déplacement à l'utilisateur
while(strcmp(plateau[yInit][xInit].couleur, whoPlay) != 0){
askInit:
aff(plateau, whoPlay);
if(strncmp(whoPlay, "31", 3) == 0){
printf("Joueur Noir: \n");
}else{
printf("Joueur Blanc: \n");
}
//On demande les coordonées de la pièce à déplacer
printf("Coordonnées de la pièce à déplacer:\n");
fgets(posInit, sizeof(posInit), stdin);
printf("Position initiale: (%c;%c)\n", posInit[0], posInit[1]);
//On cast les coordonnées de string en int
xInit = (int) posInit[0] - 48;
yInit = (int) posInit[1] - 48;
printf("%s\n", plateau[yInit][xInit].couleur);
viderBuffer();
}
depPossible(plateau, plateau[yInit][xInit], vide, videP);
do{
aff(plateau, whoPlay);
//On demande les coordonnées où déplacer la pièce
printf("Coordonnées de déplacement:\n");
fgets(posDepl, sizeof(posDepl), stdin);
printf("Positon visé: (%c;%c)\n", posDepl[0], posDepl[1]);
viderBuffer();
//On cast les coordonnées de string en int
xDepl = (int) posDepl[0] - 48;
yDepl = (int) posDepl[1] - 48;
if((yDepl == yInit) && (xDepl == xInit)){
nettoyage(plateau, whoPlay);
goto askInit;
}
}while((plateau[yDepl][xDepl].valeur != 'X') && (strcmp(plateau[yDepl][xDepl].couleur, "35") != 0));
printf("ok\n");
echec = move(plateau, plateau[yInit][xInit], xDepl, yDepl, whoPlay, vide, videP);
// }else{
// printf("Le joueur rouge est en echec!\n");
// echec = 0;
// }
}
printf("Fin de la partie, félicitation au vainqueur\n");
couleur("37","40");
return 0;
}
|
C | #include<stdio.h>
#include<stdlib.h>
#include"my_list.h"
my_bool listIsNullOrEmpty(myList** ppMyList)
{
return !ppMyList || !*ppMyList || !(*ppMyList)->header || !(*ppMyList)->size;
}
my_bool listIsNull(myList** ppMyList)
{
return !ppMyList || !*ppMyList ;
}
my_bool listIsEmpty(myList** ppMyList)
{
return !(*ppMyList)->header || !(*ppMyList)->size;
}
void add(myList** ppMyList, void* p_data, int elemSize)
{
if(!ppMyList)
{
printf("pointer of list is null\n");
return;
}
if(!*ppMyList)
{
// *ppMyList = (myList*)calloc(1, sizeof(int**) + sizeof(int));
*ppMyList = (myList*)calloc(1, elemSize + 2*sizeof(int));
(*ppMyList)->capability = 8;
// (*ppMyList)->header = (int**)calloc((*ppMyList)->capability, sizeof(int*));
(*ppMyList)->header = (char*)calloc((*ppMyList)->capability, elemSize);
}
if((*ppMyList)->size == (*ppMyList)->capability)
{
int capability = (*ppMyList)->capability;
capability += (capability>>1);
char* new_header = (char*)calloc(capability, elemSize);
for(int i=0;i<(*ppMyList)->capability;i++)
{
*(new_header + i*elemSize) = *(char*)((*ppMyList)->header + i*elemSize);
}
free((*ppMyList)->header);
(*ppMyList)->header = new_header;
new_header = '\0';
(*ppMyList)->capability = capability;
}
(*ppMyList)->header + elemSize * (*ppMyList)->size = p_data;
(*ppMyList)->size++;
}
|
C | // Alexander Baekey
// CDA 5106
// Machine Problem 2
//libs
#include<stdlib.h>
#include<stdio.h>
#include<stdbool.h>
#include<math.h>
#include<string.h>
//global counters & flags
//old un-needed
int *countArr;
int B, M2, M1, N, K;
int count;
int *bimodPT;
int bisize;
int *PT;
int gsize;
int *gbh;
int binsum = 0;
bool taken = false;
int *chooser;
int hybsize;
int gpred;
int bipred;
int bicorrect;
int gcorrect;
//Evaluation Metrics
int mispredictions=0;
int predictions=0;
int CPI;
int speedup;
//functions
void smith(int branchPC, char outcome);
void bimodal(int branchPC, char outcome, int M2);
void gshare(int branchPC, char outcome, int M1, int N);
void hybrid(int branchPC, char outcome, int K, int M1, int N, int M2);
int binArr2num(int *gbh, int N);
void smith(int branchPC, char outcome){
predictions++;
int mid = (int)pow(2,(float)B)/2.;
int max = (int)pow(2,(float)B);
if(count < (int)mid){
//predicted not taken
if(outcome == 't'){
mispredictions++;
//updatecounter
if(count<(max-1)){
count++;
}
}
if(outcome == 'n'){
if(count>0){
count--;
}
}
}
else if(count >= (int)mid){
//predicted taken
if(outcome == 'n'){
mispredictions++;
//updatecounter
if(count>0){
count = count - 1;
}
}
if(outcome == 't'){
//updatecounter
if(count<(max-1)){
count = count + 1;
}
}
}
}
void bimodal(int branchPC, char outcome, int M2){
predictions++;
//use bits M+1 to 2 of PC
int cur = (((1<<(M2))-1) & (branchPC>>(2)));
int mid = 4;
int max = 8;
if(bimodPT[cur]<mid){
//predicted not taken
if(outcome == 't'){
mispredictions++;
//updatecounter
if(bimodPT[cur]<(max-1)){
bimodPT[cur] = bimodPT[cur] + 1;
}
}
if(outcome == 'n'){
if(bimodPT[cur]>0){
bimodPT[cur] = bimodPT[cur] - 1;
}
}
}
else if(bimodPT[cur]>=mid){
//predicted taken
if(outcome == 'n'){
mispredictions++;
//updatecounter
if(bimodPT[cur]>0){
bimodPT[cur] = bimodPT[cur] - 1;
}
}
if(outcome == 't'){
//updatecounter
if(bimodPT[cur]<(max-1)){
bimodPT[cur] = bimodPT[cur] + 1;
}
}
}
}
void gshare(int branchPC, char outcome, int M1, int N){
predictions++;
//use bits M+1 to 2 of PC
int test = binArr2num(gbh, N);
int cur = (test ^ (((1<<(M1))-1) & (branchPC>>(2))));
//printf("cur %d\n", cur);
int mid = 4;
int max = 8;
if(PT[cur]<mid){
//predicted not taken
if(outcome == 't'){
mispredictions++;
//updatecounter
if(PT[cur]<(max-1)){
PT[cur] = PT[cur] + 1;
}
taken = true;
}
if(outcome == 'n'){
if(PT[cur]>0){
PT[cur] = PT[cur] - 1;
}
taken = false;
}
}
else if(PT[cur]>=mid){
//predicted taken
if(outcome == 'n'){
mispredictions++;
//updatecounter
if(PT[cur]>0){
PT[cur] = PT[cur] - 1;
}
taken = false;
}
if(outcome == 't'){
//updatecounter
if(PT[cur]<(max-1)){
PT[cur] = PT[cur] + 1;
}
taken = true;
}
}
/* //update global hist*/
//1st shift bits right one
//have to do this descending, otherwise new values spill over
for(int i=(N-1);i>=0;i--){
gbh[i+1]=gbh[i];
}
/* //place result value in MSB*/
//gbh[0] is MSB
if(taken==true){
gbh[0]=1;
}
else if(taken==false){
gbh[0]=0;
}
}
int binArr2num(int *gbh, int N){
binsum=0;
int m=(N-1);
for(int i=0;i<N;i++){
binsum = binsum + (pow(2,m)*gbh[i]);
m--;
}
return binsum;
}
void hybrid(int branchPC, char outcome, int K, int M1, int N, int M2){
predictions++;
//gshare with modification
//use bits M+1 to 2 of PC
int test = binArr2num(gbh, N);
int gcur = (test ^ (((1<<(M1))-1) & (branchPC>>(2))));
int mid = 4;
int max = 8;
if(PT[gcur]<mid){
gpred = 0;
//predicted not taken
if(outcome == 't'){
gcorrect=0;
taken = true;
}
else if(outcome=='n'){
gcorrect=1;
taken=false;
}
}
else if(PT[gcur]>=mid){
gpred = 1;
//predicted taken
if(outcome == 't'){
gcorrect=1;
taken=true;
}
else if(outcome=='n'){
gcorrect=0;
taken=false;
}
}
//bimodal with modification
//use bits M+1 to 2 of PC
int cur = (((1<<(M2))-1) & (branchPC>>(2)));
if(bimodPT[cur]<mid){
bipred = 0;
if(outcome == 't'){
bicorrect=0;
}
else if(outcome=='n'){
bicorrect=1;
}
}
else if(bimodPT[cur]>=mid){
bipred=1;
if(outcome == 't'){
bicorrect=1;
}
else if(outcome=='n'){
bicorrect=0;
}
}
//find index value using bits k+1 to 2 in branchPC
int ccur = (((1<<(K))-1) & (branchPC>>(2)));
//gpred and bipred create the table
if(chooser[ccur]<2){
//bimodal predictor chosen
if(bimodPT[cur]<mid){
//predicted not taken
if(outcome == 't'){
mispredictions++;
//updatecounter
if(bimodPT[cur]<(max-1)){
bimodPT[cur] = bimodPT[cur] + 1;
}
}
if(outcome == 'n'){
if(bimodPT[cur]>0){
bimodPT[cur] = bimodPT[cur] - 1;
}
}
}
else if(bimodPT[cur]>=mid){
//predicted taken
if(outcome == 'n'){
mispredictions++;
//updatecounter
if(bimodPT[cur]>0){
bimodPT[cur] = bimodPT[cur] - 1;
}
}
if(outcome == 't'){
//updatecounter
if(bimodPT[cur]<(max-1)){
bimodPT[cur] = bimodPT[cur] + 1;
}
}
}
}
else if(chooser[ccur]>=2){
//gshare predictor chosen
if(PT[gcur]<mid){
//predicted not taken
if(outcome == 't'){
mispredictions++;
//updatecounter
if(PT[gcur]<(max-1)){
PT[gcur] = PT[gcur] + 1;
}
}
if(outcome == 'n'){
if(PT[gcur]>0){
PT[gcur] = PT[gcur] - 1;
}
}
}
else if(PT[gcur]>=mid){
//predicted taken
if(outcome == 'n'){
mispredictions++;
//updatecounter
if(PT[gcur]>0){
PT[gcur] = PT[gcur] - 1;
}
}
if(outcome == 't'){
//updatecounter
if(PT[gcur]<(max-1)){
PT[gcur] = PT[gcur] + 1;
}
}
}
}
/* //update global hist*/
for(int i=(N-1);i>=0;i--){
gbh[i+1]=gbh[i];
}
/* //place result value in MSB*/
if(taken==true){
gbh[0]=1;
}
else if(taken==false){
gbh[0]=0;
}
// Update chooser
if(bicorrect==1){
if(gcorrect==1){
//do nothing
}
else if(gcorrect==0){
if(chooser[ccur]>0){
chooser[ccur] = chooser[ccur] - 1;
}
}
}
else if(bicorrect==0){
if(gcorrect==0){
//do nothing
}
else if(gcorrect==1){
if(chooser[ccur]<3){
chooser[ccur] = chooser[ccur] + 1;
}
}
}
}
// main execution
void main(int argc, char *argv[]){
char outcome;
int branchPC;
FILE* fp;
char *trace;
char *predictor;
//read in type of branch predictor, loop through file
predictor = argv[1];
if(strcmp("smith", predictor) == 0){
B = strtol(argv[2], NULL, 10);
trace = argv[3];
int x = (int)(pow(2,(float)B)/2.);
count = x;
fp = fopen(trace, "r");
while(!feof(fp)){
fscanf(fp, "%x %c\n", &branchPC, &outcome);
smith(branchPC, outcome);
}
fclose(fp);
printf("COMMAND\n");
printf("./sim %s %d %s\n", predictor, B, trace);
printf("OUTPUT\n");
}
else if(strcmp("bimodal", predictor) == 0){
M2 = strtol(argv[2], NULL, 10);
trace = argv[3];
bisize = (int)(pow(2,(float)M2));
bimodPT = (int *)malloc(sizeof(int)*bisize);
for(int i=0; i<bisize; i++){
bimodPT[i] = 4;
}
fp = fopen(trace, "r");
while(!feof(fp)){
fscanf(fp, "%x %c\n", &branchPC, &outcome);
bimodal(branchPC, outcome, M2);
}
fclose(fp);
printf("COMMAND\n");
printf("./sim %s %d %s\n", predictor, M2, trace);
printf("OUTPUT\n");
}
else if(strcmp("gshare", predictor) == 0){
M1 = strtol(argv[2], NULL, 10);
N = strtol(argv[3], NULL, 10);
trace = argv[4];
gbh = (int *)malloc(sizeof(int)*N);
gsize = (int)(pow(2,(float)M1));
PT = (int *)malloc(sizeof(int)*gsize);
for(int i=0;i<N;i++){
gbh[i]=0;
}
for(int i=0; i<gsize; i++){
PT[i] = 4;
}
fp = fopen(trace, "r");
while(!feof(fp)){
fscanf(fp, "%x %c\n", &branchPC, &outcome);
gshare(branchPC, outcome, M1, N);
}
fclose(fp);
printf("COMMAND\n");
printf("./sim %s %d %d %s\n", predictor, M1, N, trace);
printf("OUTPUT\n");
}
else if(strcmp("hybrid", predictor) == 0){
K = strtol(argv[2], NULL, 10);
M1 = strtol(argv[3], NULL, 10);
N = strtol(argv[4], NULL, 10);
M2 = strtol(argv[5], NULL, 10);
trace = argv[6];
bisize = (int)(pow(2,(float)M2));
bimodPT = (int *)malloc(sizeof(int)*bisize);
for(int i=0; i<bisize; i++){
bimodPT[i] = 4;
}
gbh = (int *)malloc(sizeof(int)*N);
gsize = (int)(pow(2,(float)M1));
PT = (int *)malloc(sizeof(int)*gsize);
for(int i=0;i<N;i++){
gbh[i]=0;
}
for(int i=0; i<gsize; i++){
PT[i] = 4;
}
hybsize = pow(2,K);
chooser = (int *)malloc(sizeof(int)*(hybsize));
for(int i=0;i<hybsize;i++){
chooser[i]=1;
}
fp = fopen(trace, "r");
while(!feof(fp)){
fscanf(fp, "%x %c\n", &branchPC, &outcome);
hybrid(branchPC, outcome, K, M1, N, M2);
}
fclose(fp);
printf("COMMAND\n");
printf("./sim %s %d %d %d %d %s\n", predictor, K, M1, N, M2, trace);
printf("OUTPUT\n");
}
else
printf("%s is not a valid predictor type\n", predictor);
//RESULTS
printf("number of predictions: %d\n", predictions);
printf("number of mispredictions: %d\n", mispredictions);
printf("misprediction rate: %.2f%%\n", (100*(double)mispredictions/(double)predictions));
if(strcmp("smith", predictor) == 0){
printf("FINAL COUNTER CONTENT: ");
printf("%d\n", count);
}
if(strcmp("bimodal", predictor) == 0){
printf("FINAL BIMODAL CONTENTS\n");
for(int i=0;i<bisize;i++){
printf("%d %d\n",i, bimodPT[i]);
}
}
if(strcmp("gshare", predictor) == 0){
printf("FINAL GSHARE CONTENTS\n");
for(int i=0;i<gsize;i++){
printf("%d %d\n",i, PT[i]);
}
}
if(strcmp("hybrid", predictor) == 0){
printf("FINAL CHOOSER CONTENTS\n");
for(int i=0;i<hybsize;i++){
printf("%d %d\n",i, chooser[i]);
}
printf("FINAL GSHARE CONTENTS\n");
for(int i=0;i<gsize;i++){
printf("%d %d\n",i, PT[i]);
}
printf("FINAL BIMODAL CONTENTS\n");
for(int i=0;i<bisize;i++){
printf("%d %d\n",i, bimodPT[i]);
}
}
}
|
C | /* No.10250 ȣ ȣ Ģ ã ϴ */
#include <stdio.h>
int main() {
int testCnt; //testCase
int fCnt, rCnt, num; // , , ° մ
int floor, room;
int count = 0;
scanf("%d", &testCnt);
while (count++ < testCnt) {
scanf("%d %d %d", &fCnt, &rCnt, &num);
floor = (num % fCnt == 0) ? fCnt : num % fCnt;
room = (num%fCnt == 0) ? num / fCnt : num / fCnt + 1;
printf("%d \n", floor * 100 + room);
}
return 0;
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#define MAX_PROCESSES 9
#define PIPE_PATH_IND 1
#define ROW_IND 2
#define FILE_PATH_IND 3
#define N_IND 4
int main(int argc, char *argv[]) {
if(argc != 5){
perror("Wrong number of arguments");
exit(2);
}
printf("Hello, producer!\n");
int pipe;
pipe = open(argv[PIPE_PATH_IND], O_WRONLY);
int file;
file = open(argv[FILE_PATH_IND], O_RDONLY);
int N = (int) strtol(argv[N_IND], NULL, 10);
char tmp[N+1];
char *str = calloc(N+3, sizeof(char));
strcpy(str, argv[ROW_IND]);
int c;
while((c=read(file, tmp, N)) != 0){
tmp[c] = 0;
sleep(1);
strcat(str, ":");
strcat(str, tmp);
printf("PRODUCER PID: %d str: %s\n", getpid(), str);
write(pipe, str, N+2);
strcpy(str, argv[ROW_IND]);
}
close(file);
close(pipe);
free(str);
return 0;
}
|
C | #include <stdio.h>
#include<math.h>
int num_reader(){
int count = 1000;
int sum = 0;
while(count != -999){
sum = sum + count;
count = count -1;
if (count == -999){ break;}
}
printf("sum is %d \n" ,sum);
} |
C | #include <unistd.h>
int ft_strlen(char *str)
{
int i = 0;
i = 0;
while (str[i])
i++;
return (i);
}
int is_tab(char c)
{
return (c == '\t' || c == ' ');
}
void print_reverse(char *str)
{
int first;
int end;
int curr;
|
C | //
// Created by wmurphy on 9/15/2019.
//
#include "Search.h"
int linear_search(double n, double* array) {
int i = 0;
int_func_ptr len = get_array_length_;
while (i < len(array) && *(array + i) != n) {
i++;
}
if (i < len(array)) {
return i;
} else {
return -1;
}
}
|
C | #include <ctype.h>
#include <stdio.h>
#include <sys/isofs.h>
#include <sys/sys.h>
void
isofs_dump_file_id(directory_record_t rec) {
char *s = ((char *) rec) + sizeof(struct directory_record);
if (s[0] == 0) {
printf(".");
return;
}
if (s[0] == 1) {
printf("..");
return;
}
for (int i = 0; i < rec->file_id_len; i++) {
char ch = *(s + i);
if (isprint(ch))
printf("%c", ch);
else
printf("(%02x)", ch);
}
}
void
isofs_dump_record_date(directory_record_t rec) {
uint8_t *rec_date = (uint8_t *) rec->record_date;
printf("%02u:", rec_date[3]);
printf("%02u:", rec_date[4]);
printf("%02u ", rec_date[5]);
printf("%02u-", rec_date[1]);
printf("%02u-", rec_date[2]);
printf("%04u ", rec_date[0] + 1900);
}
void
isofs_dump_flags(directory_record_t rec) {
uint8_t flags = rec->flags;
if (flags & FILE_FLAGS_EXISTENCE) {
printf("EXISTS");
flags &= ~FILE_FLAGS_EXISTENCE;
if (flags == 0)
return;
printf(" ");
}
if (flags & FILE_FLAGS_DIRECTORY) {
printf("DIRECTORY");
flags &= ~FILE_FLAGS_DIRECTORY;
if (flags == 0)
return;
printf(" ");
}
if (flags & FILE_FLAGS_ASSOCIATED_FILE) {
printf("ASSOCIATED-FILE");
flags &= ~FILE_FLAGS_ASSOCIATED_FILE;
if (flags == 0)
return;
printf(" ");
}
if (flags & FILE_FLAGS_RECORD) {
printf("RECORD");
flags &= ~FILE_FLAGS_RECORD;
if (flags == 0)
return;
printf(" ");
}
if (flags & FILE_FLAGS_PROTECTION) {
printf("PROTECTION");
flags &= ~FILE_FLAGS_PROTECTION;
if (flags == 0)
return;
printf(" ");
}
if (flags & FILE_FLAGS_MULTI_EXTENT)
printf("MULTI-EXTENT");
}
void
isofs_dump_primary_volume(primary_volume_descriptor_t pri) {
#if 0
int i;
#endif
printf("ISO9660 primary volume\r\n");
#if 0
printf("system identifier [");
for (i = 0; i < 32; i++)
printf("%c", pri->sys_id[i]);
printf("]\r\n");
printf("volume identifier [");
for (i = 0; i < 32; i++)
printf("%c", pri->vol_id[i]);
printf("]\r\n");
#endif
printf("%u blks (%u MB)\r\n", pri->vol_space_size_le,
pri->vol_space_size_le * ATAPI_SECTOR_SIZE / 0x100000);
printf("logical blk size %u bytes\r\n", pri->logical_blk_size_le);
printf("path table size %u bytes\r\n", pri->path_table_size_le);
printf("path table location blk %u\r\n", pri->path_table_loc_le);
}
static void
isofs_dump_path_table_record(path_table_record_t rec) {
printf("%10u ", rec->dir_id_len);
printf("%15u ", rec->ext_att_rec_len);
printf("%12u ", rec->lba);
printf("%12u ", rec->parent_dirno);
for (int i = 0; i < rec->dir_id_len; i++) {
char *str = ((char *) rec) + sizeof(struct path_table_record);
printf("%c", *(str + i));
}
printf("\r\n");
}
void
isofs_dump_path_table(primary_volume_descriptor_t pri, uint8_t *buf) {
printf("dir_id_len ext_att_rec_len lba ");
printf("parent_dirno path\r\n");
for (int pos = 0; pos < pri->path_table_size_le;) {
path_table_record_t rec = (path_table_record_t) (buf + pos);
isofs_dump_path_table_record(rec);
unsigned reclen = sizeof(struct path_table_record) + rec->dir_id_len;
if (rec->dir_id_len % 2 == 1)
reclen++;
pos += reclen;
}
}
void
isofs_dump_directory(uint8_t *buf, int size) {
directory_record_t rec;
for (int pos = 0; pos < size;) {
rec = (directory_record_t) (buf + pos);
if (rec->dir_rec_len == 0)
break;
/* File id */
isofs_dump_file_id(rec);
printf(" size %u\r\n", rec->size_le);
bufdump((char *) rec, rec->dir_rec_len);
#if _DEBUG
/* File creation time and date */
isofs_dump_record_date(rec);
printf("\r\n");
printf("dir_rec_len %u ", rec->dir_rec_len);
printf("ext_att_rec_len %u ", rec->ext_att_rec_len);
printf("file_id_len %u\r\n", rec->file_id_len);
printf("lba %u ", rec->lba_le);
printf("size %u ", rec->size_le);
printf("flags 0x%02x ", rec->flags);
if (rec->flags > 0) {
printf("(");
isofs_dump_flags(rec);
printf(")");
}
printf("\r\n");
printf("unit_size %u ", rec->unit_size);
printf("interleave_gap_size %u ", rec->interleave_gap_size);
printf("vol_seqno %u\r\n", rec->vol_seqno_le);
#endif
pos += rec->dir_rec_len;
}
}
|
C | #include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
int main(void) {
pid_t return_val;
int x = 100;
return_val = fork();
if (return_val > 0) {
printf("Parent process\n");
printf("Process id: %d\n", getpid());
printf("x = %d\n", x);
printf("Process id of shell: %d\n", getppid());
}
else if (return_val == 0) {
printf("Child process\n");
printf("Process id: %d\n", getpid());
printf("x = %d\n", x);
printf("Process id of parent: %d\n", getppid());
}
else {
fprintf(stderr, "Process creation unsuccessful\n");
exit(1);
}
return 0;
}
|
C | #ifndef _delay_accurate_h
#define _delay_accurate_h
/*
Delay loop with single cycle accuracy.
The actual delay is __cycles + k cycles, with k being about 10.
Does the single cycle fixup using a skip instruction combined with a single
word NOP which needs two cycles to execute (adiw 0). We need to fix 0-3
cycles because the main delay loop is 4 cycles per iteration.
*/
inline static void delay_cycles( uint16_t __cycles )
{
__asm__ volatile (
"1: sbiw %0,4" "\n"
"brsh 1b" "\n"
"sbrc %0,0" "\n"
"adiw %0,0" "\n"
"sbrc %0,1" "\n"
"adiw %0,0" "\n"
"sbrc %0,1" "\n"
"adiw %0,0" "\n"
: "=w" (__cycles)
: "0" (__cycles)
);
}
/* Single cycle NOP. */
#define NOP __asm__ volatile( "clc" )
/* Two cycle NOP. */
#define NOP2 __asm__ volatile( "adiw r24,0" )
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.