language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdbool.h>
#include <string.h>
char* sub_exp(char * expression, int i);
int fork_num(char* temp_str);
int parse_and_calc(char * expression);
int fork_expr(char* subexpr);
int find_operands(char * expression);
char* sub_exp(char * expression, int i) //Takes the full expression and outputs the subexpression starting at index i for forking
{
int paren = 0; //for counting parentheses
int j = i;
char * temp_str = calloc(20, sizeof(char));
strcpy(temp_str, ""); //Clears out temp_str
char temp_c = (char) expression[i];
while ( (!((temp_c == ')') && (paren == 0))) && (temp_c != '\0') )
{
temp_c = (char) expression[j];
if( temp_c == '(' )
{
paren++;
}
else if( temp_c == ')' )
{
paren--;
}
/*Counts the number of open paren minus number of closed paren.
A full expression only ends on a ')' and when the number of each type of paren are equal, to account for nesting.*/
j++;
}
if (temp_c == '\0')
{
//Will also return error if the end of the string is reached before full subexpression found.
printf("Parentheses mismatch; exiting\n");
exit(EXIT_FAILURE);
}
//Get rid of of paren on each side:
strncpy( temp_str, &(expression[i+1]), j-i-2 );
temp_str[j-1] = '\0';//Manually re-adds null terminator
/*This is where forking stuff happens*/
return temp_str;
}
int fork_num(char* temp_str) //Forks if just a number
{
pid_t pid;
int operand = 0;
int p[2]; /* array to hold the two pipe (file) descriptors:
p[0] is the read end of the pipe
p[1] is the write end of the pipe */
int rc = pipe( p );
if ( rc == -1 )
{
puts( "pipe() failed" );
fflush(NULL);
exit(EXIT_FAILURE);
}
pid = fork();
fflush(NULL);
if (pid == 0) //If in child
{
close( p[0] ); /* close the read end of the pipe */
p[0] = -1; /* this should avoid human error.... */
/* write some data to the pipe */
operand = atof(temp_str); //This is proof of the use of pipes; parent doesn't know this value unless passed
printf("PID %d: My expression is \"%d\"\n", getpid(), operand);
fflush(NULL);
printf("PID %d: Sending \"%d\" on pipe to parent\n", getpid(), operand);
fflush(NULL);
write( p[1], &(operand), sizeof(int) );
exit(EXIT_SUCCESS); //Terminates child once done
}
else //If in parent
{
close( p[1] ); /* close the write end of the pipe */
p[1] = -1; /* this should avoid human error.... */
read( p[0], &(operand), sizeof(int) ); /* BLOCKING CALL */
return operand;
}
}
int find_operands(char * expression) //Gives the number of operands in an expression
{
int num_operands = 0;
int paren = 0;
int i = 0;
for (i = 2; i <= (int) strlen(expression); i++) //Skips the inital operation
{
if ((((char) expression[i] == ' ') || ((char) expression[i] == '\0')) && ((char) expression[i-1] != ')'))//End of argument
{
if (paren == 0)
{
num_operands++;
}
}
else if( (char) expression[i] == '(' )//Start of new parenthetical expression. Time to ignore operands within.
{
if (paren == 0) // If not in subexpression
{
num_operands++;
}
paren++;
}
else if ((char) expression[i] == ')')
{
if (paren == 0) // If not in subexpression
{
num_operands++;
}
paren--;
}
}
return num_operands;
}
int parse_and_calc(char * expression) //Parses the expression and gives the operator and operands
{
int i = 0; //for loop index
char* temp_str = calloc(10, sizeof(char)); //Used for all sorts of stuff
char temp_c; //Because C is silly, making an intermediate for (char) expression[i] is easier
int operand_size = 8;
int val = 0; //final answer for this fork
const pid_t pid = getpid(); //Original Process ID; compared to see if in child or parent
char* operation = calloc(10, sizeof(char)); //the operation for the expression; must be a string to capture invalid operations
int* operands = (int*) calloc(operand_size, sizeof(int));
int num_operands = find_operands(expression); //number of operands
int ops_count = 0; //Keeps track of where to put numbers in operands
strcpy(temp_str, ""); //Clears out temp_str
sscanf (expression,"%s",operation);
printf("PID %d: My expression is \"(%s)\"\n", pid, expression); //Expression lacks the parentheses, therefore I add them back in for printing
fflush(NULL);
if (((int) strlen(operation) > 1) ||
(((char) operation[0] != '+') && ((char) operation[0] != '-') && ((char) operation[0] != '*') && ((char) operation[0] != '/'))) //If invalid operator
{
printf("PID %d: ERROR: unknown \"%s\" operator; exiting\n", pid, operation);
exit(EXIT_FAILURE);
}
printf("PID %d: Starting \"%c\" operation\n", pid, operation[0]);
fflush(NULL);
//printf("There are %d operands\n", num_operands);
fflush(NULL);
for (i = 2; i <= (int) strlen(expression); i++) //Skips the inital operation
{
temp_c = (char) expression[i];
if (((temp_c == ' ') || (temp_c == '\0')) && ((char) expression[i-1] != ')'))//End of argument
{
//Assume it's a numeric argument
if (num_operands < 2) //Why is this here? Allows one fork, then checks if enough operands, to match Submitty.
{
printf("PID %d: ERROR: not enough operands; exiting\n", pid);
fflush(NULL);
}
if (((char) operation[0] == '/') && (atoi(temp_str) == 0)) //Same here
{
printf("PID %d: ERROR: division by zero is not allowed; exiting\n", pid);
fflush(NULL);
exit(EXIT_FAILURE);
}
operands[ops_count] = fork_num(temp_str);
if (num_operands < 2) //The error is thrown before the fork, but doesn't exit until after...ask Goldschmidt
{
exit(EXIT_FAILURE);
}
ops_count++;
strcpy(temp_str, ""); //Clears out temp_str
//printf("i is %d\n", i);
}
else if( temp_c == '(' )//Start of new parenthetical expression. Time to fork!
{
temp_str = sub_exp(expression, i);
operands[ops_count] = fork_expr(temp_str); //Note the parent in fork_expr is original
if (operands[ops_count] == 0)
{
printf("PID %d: ERROR: division by zero is not allowed; exiting\n", pid);
exit(EXIT_FAILURE);
}
ops_count++;
i += (int) strlen(temp_str)+2; //Skips the subexpression in original process so it's not read again
}
else //Continuation of previous argument
{
strncat(temp_str, &temp_c, 1);
}
}
if (operation[0] == '+') //Addition
{
val = operands[0];
for(i = 1; i < num_operands; i++)
{
val += operands[i];
}
}
else if (operation[0] == '-')
{
val = operands[0];
for(i = 1; i < num_operands; i++)
{
val -= operands[i];
}
}
else if (operation[0] == '*')
{
val = operands[0];
for(i = 1; i < num_operands; i++)
{
val *= operands[i];
}
}
else if (operation[0] == '/')
{
val = operands[0];
for(i = 1; i < num_operands; i++)
{
val /= operands[i];
}
}
return val;
}
int fork_expr(char* subexpr) //Forks if a new subexpression
{
pid_t pid;
int operand = 0;
int p[2]; /* array to hold the two pipe (file) descriptors:
p[0] is the read end of the pipe
p[1] is the write end of the pipe */
int rc = pipe( p );
if ( rc == -1 )
{
printf( "pipe() failed\n" );
exit(EXIT_FAILURE);
}
pid = fork();
fflush(NULL);
if (pid == 0) //If in child
{
close( p[0] ); /* close the read end of the pipe */
p[0] = -1; /* this should avoid human error.... */
/* write some data to the pipe */
operand = parse_and_calc(subexpr);
printf("PID %d: Processed \"(%s)\"; sending \"%d\" on pipe to parent\n", getpid(), subexpr, operand);
fflush(NULL);
write( p[1], &(operand), sizeof(int) );
exit(EXIT_SUCCESS); //Terminates child once done
}
else //If in parent
{
close( p[1] ); /* close the write end of the pipe */
p[1] = -1; /* this should avoid human error.... */
read( p[0], &(operand), sizeof(int) ); /* BLOCKING CALL */
return operand;
}
}
int main(int argc, char *argv[]){
FILE * file = fopen(argv[1], "r");
int expression_size = 30;
char * expression = (char*) calloc(expression_size, sizeof(char));
char * temp_str; //Used for all sorts of stuff
pid_t pid = getpid(); //Process ID
if (file == NULL)
{
printf("File not found\n");
return EXIT_FAILURE;
}
char temp_char = fgetc(file); //For iterating through file
while (( temp_char != '(' ) && ( temp_char != EOF )) //Find the start of the expression, or end of the file, whichever comes first
{
temp_char = fgetc(file);
}
if (temp_char == EOF) //If no parentheses, there is no expression
{
printf("No expression found\n");
return EXIT_FAILURE;
}
while ( (fgets (expression, 30, file)) != NULL ) //Read the expression into the variable. Purposely skips the '(' to help parsing.
{
if ( (bool) (expression[expression_size - 1]) ) //If the array is full, reallocate
{
expression_size *= 2;
expression = (char*) realloc (expression, expression_size * sizeof(char));
}
}
fclose(file);
//All this to get rid of trailing ')':
temp_str = (char*) calloc(expression_size, sizeof(char));
strncpy( temp_str, expression, (int) strlen(expression)-2 );
temp_str = strcat (temp_str, "\0"); //Manually re-adds null terminator
expression = temp_str;
if (pid) //Only put out final answer if in original process
{
printf("PID %d: Processed \"(%s)\"; final answer is \"%d\"\n", pid, expression, parse_and_calc(expression));
fflush(NULL);
free(expression);
exit (EXIT_SUCCESS);
}
free(expression);
exit (EXIT_FAILURE);
}
|
C
|
/* Given a string, find the first non-repeating character in it and return it's
* index. If it doesn't exist, return -1.
*
* Examples:
*
* s = "leetcode"
* return 0.
*
* s = "loveleetcode",
* return 2.
*
* Note: You may assume the string contain only lowercase letters.
*
**/
int firstUniqChar(char* s) {
int counter[26] = {0};
char *p = s;
while(*p != '\0') {
counter[*p++ - 97]++;
}
int index = 0;
while(*s != '\0') {
if(counter[*s++ - 97] == 1) {
return index;
}
index++;
}
return -1;
}
|
C
|
#include <stdio.h>
#include <math.h>
int main(void) {
int Chomem = 0, Cmulher = 0, i, mani = 0;
float salario, sh = 0, maior = 0, total = 0;
char sexo[1], mc[1];
for(i = 0; i < 10; i++){
scanf("%f\n%c", &salario, &sexo[0]);
total += salario;
switch(sexo[0]){
case 'm':
Chomem++;
sh += salario;
if(salario > maior){
mc[0] = 'm';
maior = salario;
}
break;
case 'f':
Cmulher++;
if(salario > maior){
mc[0] = 'f';
maior = salario;
}
break;
}
}
printf("%d\n%d\n", Chomem, Cmulher);
total /= 10.0;
mani = round(total*100);
if(mani%10==0)printf("%.1f\n%c\n", total, mc[0]);
else printf("%.2f\n%c\n", total, mc[0]);
sh /= Chomem*1.0;
mani = round(sh*100.0);
if(mani%10==0) printf("%.1f", sh);
else printf("%.2f", sh);
return 0;
}
|
C
|
/*
** EPITECH PROJECT, 2021
** my_defender
** File description:
** handle_events
*/
#include "defender.h"
void handle_game_event(all_t *all)
{
sfEvent event;
sfVector2i mvector = sfMouse_getPositionRenderWindow(all->window);
if (all->game->once == true) {
all->game[3].tower = malloc(sizeof(game_object_t) * 1000);
all->game->once = false;
}
while (sfRenderWindow_pollEvent(all->window, &event)) {
handle_escape_key(all, event);
show_settings(all, event);
handle_fps_events(all, event);
if (all->game->show_settings == false) {
handle_towers(all, event, mvector);
accelerate_button_mouse(all, event, mvector);
play_button_mouse(all, event, mvector);
}
}
}
int handle_menu_event(all_t *all)
{
sfEvent event;
while (sfRenderWindow_pollEvent(all->window, &event)) {
if (event.type == sfEvtKeyPressed && event.key.code == sfKeyEscape) {
all->status = quit;
sfRenderWindow_close(all->window);
}
handle_fps_events(all, event);
if (all->status == menu)
menu_mouse(all, event);
if (all->status == option)
if (option_mouse(all, event) == -1)
return (-1);
}
return (0);
}
|
C
|
#include "Graph.h"
#include <malloc.h>
#include <string.h>
#include <stdio.h>
Edge *New_Edge(Vertex ep1, Vertex ep2, int weight)
{
Edge *edge = 0;
edge = (Edge *)malloc(sizeof(Edge));
edge->ep1 = ep1;
edge->ep2 = ep2;
edge->weight = weight;
return edge;
}
Vertex Edge_AnOther(Edge *edge, Vertex pt)
{
if (strcmp(edge->ep1, pt) == 0)
{
return edge->ep2;
}
if (strcmp(edge->ep2, pt) == 0)
{
return edge->ep1;
}
return "";
}
int Edge_Include(Edge *edge, Vertex pt)
{
return (strcmp(edge->ep1, pt) == 0) || (strcmp(edge->ep2, pt) == 0);
}
Graph *New_Graph()
{
Graph *graph = 0;
graph = (Graph *)malloc(sizeof(Graph));
graph->vertexs = New_Array();
graph->edges = New_Array();
return graph;
}
void Delete_Graph(Graph *graph)
{
Iterator seek = 0, end = 0;
Edge *edge = 0;
seek = Array_Begin(graph->edges);
end = Array_End(graph->edges);
for (seek = seek; seek != end; ++seek)
{
edge = (Edge *)(*seek);
free(edge);
}
Delete_Array(graph->vertexs);
Delete_Array(graph->edges);
free(graph);
}
int Graph_AddVertex(Graph *graph, Vertex pt)
{
if (Graph_ExistVertex(graph, pt))
{
return 0;
}
Array_PushBack(graph->vertexs, (Element)pt);
return 1;
}
int Graph_AddEdge(Graph *graph, Vertex ep1, Vertex ep2, int weight)
{
if (Graph_ExistVertex(graph, ep1) && Graph_ExistVertex(graph, ep2))
{
Edge *edge = 0;
if (Graph_ExistEdge(graph, ep1, ep2))
{
return 0;
}
edge = New_Edge(ep1, ep2, weight);
Array_PushBack(graph->edges, edge);
return 1;
}
return 0;
}
int Graph_ExistVertex(Graph *graph, Vertex pt)
{
Iterator seek = 0, end = 0;
Vertex stored_pt = 0;
seek = Array_Begin(graph->vertexs);
end = Array_End(graph->vertexs);
for (seek = seek; seek != end; ++seek)
{
stored_pt = (Vertex)(*seek);
if (strcmp(stored_pt, pt) == 0)
{
return 1;
}
}
return 0;
}
int Graph_ExistEdge(Graph *graph, Vertex ep1, Vertex ep2)
{
Iterator seek = 0, end = 0;
Edge *stored_eg = 0;
seek = Array_Begin(graph->edges);
end = Array_End(graph->edges);
for (seek = seek; seek != end; ++seek)
{
stored_eg = (Edge *)(*seek);
if (Edge_Include(stored_eg, ep1) && Edge_Include(stored_eg, ep2))
{
return 1;
}
}
return 0;
}
void Graph_View(Graph *graph)
{
Graph_ViewVertexs(graph);
Graph_ViewEdges(graph);
}
void Graph_ViewVertexs(Graph *graph)
{
Iterator seek = 0, end = 0;
Vertex pt = 0;
printf(" :%d\n", graph->vertexs->usage);
seek = Array_Begin(graph->vertexs);
end = Array_End(graph->vertexs);
for (seek = seek; seek != end; ++seek)
{
pt = (Vertex)(*seek);
printf("%s\n", pt);
}
}
void Graph_ViewEdges(Graph *graph)
{
Iterator seek = 0, end = 0;
Edge *edge = 0;
printf(" :%d\n", graph->edges->usage);
seek = Array_Begin(graph->edges);
end = Array_End(graph->edges);
for (seek = seek; seek != end; ++seek)
{
edge = (Edge *)(*seek);
printf("(%s ,%s):%d\n", edge->ep1, edge->ep2, edge->weight);
}
}
void Graph_FindNeighvor(Graph *graph, Vertex ep, Array *neighvor)
{
Iterator seek = 0, end = 0;
Edge *edge = 0;
seek = Array_Begin(graph->edges);
end = Array_End(graph->edges);
for (seek = seek; seek != end; ++seek)
{
edge = (Edge *)(*seek);
if (Edge_Include(edge, ep))
{
Vertex opt;
opt = Edge_AnOther(edge, ep);
Array_PushBack(neighvor, (Element)opt);
}
}
}
int Graph_GetWeight(Graph *graph, Vertex ep1, Vertex ep2)
{
Iterator seek = 0, end = 0;
Edge *edge = 0;
seek = Array_Begin(graph->edges);
end = Array_End(graph->edges);
for (seek = seek; seek != end; ++seek)
{
edge = (Edge *)(*seek);
if (Edge_Include(edge, ep1) && Edge_Include(edge, ep2))
{
return edge->weight;
}
}
return -1;
}
|
C
|
#include <stdio.h>
struct person {
char *name;
int age;
char *work;
void (*printf_info)(struct person *per); //函数指针
};
void printf_info(struct person *per)
{
printf("name = %6s, age = %2d, work = %s\n", per->name, per->age, per->work);
}
int main(int argc, char **argv)
{
struct person person[] = {
{"hceng", 23, "Embedded engineer", printf_info},
{"jack", 21, "Graphic Designer", printf_info}
};
person[0].printf_info(&person[0]);
person[1].printf_info(&person[1]);
return 0;
}
|
C
|
/*Աʵ*/
#include "JosephRing.h"
JosephRing* createRing(){
JosephRing* pList;
pList = (JosephRing*)malloc(sizeof(JosephRing));
init(pList);
return pList;
}
//ʼΪ0
void init(JosephRing* pList){
pList->head = NULL;
pList->len = 0;
}
//һڵ
Node* createNode(int number){
Node *p = (Node*)malloc(sizeof(Node));
p->value = number;
p->next = NULL;
return p;
}
//سn
int getLength(JosephRing* pList){
return pList->len;
}
//ӡбԪ
void printAll(JosephRing* pList){
Node* t = NULL;
int i = 0;
t = pList->head;
while (i < getLength(pList)){
printf("element[%d] = %d\n", i++, t->value);
t = t->next;
}
printf("\n");
}
//ɾָĽڵ
Node* delNode(JosephRing* pList, Node* del){
Node* pNext = NULL;
if (del){//ɾ
pNext = del->next;
if(pNext == pList->head)
pList->head = del;
del->value = pNext->value;
del->next = pNext->next;
pList->len--;
free(pNext);
}
return del;
}
//IJ뷽
void insert(JosephRing* pList, int x){
Node* newNode = NULL;
if (pList->len == 0){//ǿձ
newNode = createNode(x);
newNode->index = 0;
newNode->next = newNode;//ɻ;
} else {
newNode = createNode(pList->head->value);
newNode->index = pList->head->index;
newNode->next = pList->head->next;
pList->head->value = x;
pList->head->index = pList->len;
pList->head->next = newNode;
}
pList->head = newNode;
pList->len++;
}
int getNumber(JosephRing* pList, int k, int m) {
int ret = 0;
int i = 0;
Node* p = pList->head;
while (k--) p = p->next;
while (pList->len != 1) {
for (i = 0; i < m - 1; i++) p = p->next;
#ifdef _DEBUG_
printf("del %d\n", p->value);
#endif // _DEBUG_
p = delNode(pList, p);
#ifdef _DEBUG_
printAll(pList);
#endif // _DEBUG_
}
ret = pList->head->value;
return ret;
}
int newGetNumber(JosephRing* pList, int k) {
int ret = 0;
int i = 0;
int m;
Node* p = pList->head;
while (k--) p = p->next;
m = p->value;
while (pList->len != 1) {
for (i = 0; i < m - 1; i++) p = p->next;
m = p->value;
#ifdef _DEBUG_
printf("del %d\n", p->value);
#endif // _DEBUG_
p = delNode(pList, p);
#ifdef _DEBUG_
printAll(pList);
#endif // _DEBUG_
}
ret = pList->head->value;
return ret;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
void quicksort(int arr[], int start , int end);
int partition(int arr[], int start , int end);
int partition(int arr[], int start , int end)
{
int pivot = arr[end];
int i =0;
int temp =0 ;
int pindex = start;
for(i = start ; i < end ; i++)
{
if(arr[i] < pivot)
{
temp = arr[i];
arr[i] = arr[pindex];
arr[pindex] = temp;
pindex++;
}
}
temp = arr[pindex];
arr[pindex] = arr[end];
arr[end] = temp;
return pindex;
}
void quicksort(int arr[], int start , int end)
{
int pindex = 0;
if(start < end)
{
pindex = partition(arr , start , end);
quicksort(arr , start , pindex-1);
quicksort(arr , pindex + 1 , end);
}
}
void main()
{
int arr[10] = { 20 , 22 , 24, 8 ,10 , 15 , 25 , 60 , 2 , 17};
int i = 0;
quicksort( arr , 0 , 9);
for(i =0 ;i < 10; i++)
{
printf("Element : %d \r\n", arr[i]);
}
}
|
C
|
#include "tim5.h"
void timer5_init()
{
init_pa2_timer();
// Enable TIM5 in the APB1 clock enable register 1
RCC->APB1ENR1 |= RCC_APB1ENR1_TIM5EN;
TIM5->PSC = 80; // Set prescaler value for TIM5
TIM5->EGR |= TIM_EGR_UG; // Trigger an update event for timer 5
TIM5->CCER &= ~(TIM_CCER_CC3E); // Disable channel 3 output
TIM5->CCER &= ~(0xA00); // Clear CC3NP and CC3P
TIM5->CCER |= 0xA00; // Set CC3NP and CC3P to rising edge trigger
// Set up CCMRx
TIM5->CCMR2 &= ~(0xFF);
TIM5->CCMR2 |= 0x01; // Set CC3 channel as input, IC3 mapped on TI3
TIM5->CCER |= TIM_CCER_CC3E; // Turn on output enable for capture input
}
void timer5_start()
{
TIM5->CR1 |= 0x1;
}
void timer5_stop()
{
TIM5->CR1 &= ~(0x01);
}
uint32_t timer5_count()
{
return TIM5->CNT; // Timer 2
}
uint32_t timer5_capture()
{
return TIM5->CCR3; // Timer 2 Channel 2
}
uint32_t timer5_event()
{
return (TIM5->SR & 0x8);
}
uint32_t get_timer5_elapsed(uint32_t start_time)
{
// Get current timer count
uint32_t current_time = timer5_count();
// Check if the timer has wrapped around
if (current_time < start_time)
current_time += 200;
// Return time elapsed between start and current times.
return current_time - start_time;
}
|
C
|
/**
A gpio library for easier usage of GPIO ports
Refreshed in F4 by Rex Cheng
*/
#include "gpio.h"
const GPIO
/*** GPIOA ***/
PA0 = {GPIOA, GPIO_Pin_0},
PA1 = {GPIOA, GPIO_Pin_1},
PA2 = {GPIOA, GPIO_Pin_2},
PA3 = {GPIOA, GPIO_Pin_3},
PA4 = {GPIOA, GPIO_Pin_4},
PA5 = {GPIOA, GPIO_Pin_5},
PA6 = {GPIOA, GPIO_Pin_6},
PA7 = {GPIOA, GPIO_Pin_7},
PA8 = {GPIOA, GPIO_Pin_8},
PA9 = {GPIOA, GPIO_Pin_9},
PA10 = {GPIOA, GPIO_Pin_10},
PA11 = {GPIOA, GPIO_Pin_11},
PA12 = {GPIOA, GPIO_Pin_12},
PA13 = {GPIOA, GPIO_Pin_13},
PA14 = {GPIOA, GPIO_Pin_14},
PA15 = {GPIOA, GPIO_Pin_15},
/*** GPIOB ***/
PB0 = {GPIOB, GPIO_Pin_0},
PB1 = {GPIOB, GPIO_Pin_1},
PB2 = {GPIOB, GPIO_Pin_2},
PB3 = {GPIOB, GPIO_Pin_3},
PB4 = {GPIOB, GPIO_Pin_4},
PB5 = {GPIOB, GPIO_Pin_5},
PB6 = {GPIOB, GPIO_Pin_6},
PB7 = {GPIOB, GPIO_Pin_7},
PB8 = {GPIOB, GPIO_Pin_8},
PB9 = {GPIOB, GPIO_Pin_9},
PB10 = {GPIOB, GPIO_Pin_10},
PB11 = {GPIOB, GPIO_Pin_11},
PB12 = {GPIOB, GPIO_Pin_12},
PB13 = {GPIOB, GPIO_Pin_13},
PB14 = {GPIOB, GPIO_Pin_14},
PB15 = {GPIOB, GPIO_Pin_15},
/*** GPIOC ***/
PC0 = {GPIOC, GPIO_Pin_0},
PC1 = {GPIOC, GPIO_Pin_1},
PC2 = {GPIOC, GPIO_Pin_2},
PC3 = {GPIOC, GPIO_Pin_3},
PC4 = {GPIOC, GPIO_Pin_4},
PC5 = {GPIOC, GPIO_Pin_5},
PC6 = {GPIOC, GPIO_Pin_6},
PC7 = {GPIOC, GPIO_Pin_7},
PC8 = {GPIOC, GPIO_Pin_8},
PC9 = {GPIOC, GPIO_Pin_9},
PC10 = {GPIOC, GPIO_Pin_10},
PC11 = {GPIOC, GPIO_Pin_11},
PC12 = {GPIOC, GPIO_Pin_12},
PC13 = {GPIOC, GPIO_Pin_13},
PC14 = {GPIOC, GPIO_Pin_14},
PC15 = {GPIOC, GPIO_Pin_15},
/*** GPIOD ***/
PD0 = {GPIOD, GPIO_Pin_0},
PD1 = {GPIOD, GPIO_Pin_1},
PD2 = {GPIOD, GPIO_Pin_2},
PD3 = {GPIOD, GPIO_Pin_3},
PD4 = {GPIOD, GPIO_Pin_4},
PD5 = {GPIOD, GPIO_Pin_5},
PD6 = {GPIOD, GPIO_Pin_6},
PD7 = {GPIOD, GPIO_Pin_7},
PD8 = {GPIOD, GPIO_Pin_8},
PD9 = {GPIOD, GPIO_Pin_9},
PD10 = {GPIOD, GPIO_Pin_10},
PD11 = {GPIOD, GPIO_Pin_11},
PD12 = {GPIOD, GPIO_Pin_12},
PD13 = {GPIOD, GPIO_Pin_13},
PD14 = {GPIOD, GPIO_Pin_14},
PD15 = {GPIOD, GPIO_Pin_15},
/*** GPIOE ***/
PE0 = {GPIOE, GPIO_Pin_0},
PE1 = {GPIOE, GPIO_Pin_1},
PE2 = {GPIOE, GPIO_Pin_2},
PE3 = {GPIOE, GPIO_Pin_3},
PE4 = {GPIOE, GPIO_Pin_4},
PE5 = {GPIOE, GPIO_Pin_5},
PE6 = {GPIOE, GPIO_Pin_6},
PE7 = {GPIOE, GPIO_Pin_7},
PE8 = {GPIOE, GPIO_Pin_8},
PE9 = {GPIOE, GPIO_Pin_9},
PE10 = {GPIOE, GPIO_Pin_10},
PE11 = {GPIOE, GPIO_Pin_11},
PE12 = {GPIOE, GPIO_Pin_12},
PE13 = {GPIOE, GPIO_Pin_13},
PE14 = {GPIOE, GPIO_Pin_14},
PE15 = {GPIOE, GPIO_Pin_15},
/*** GPIOF ***/
PF0 = {GPIOF, GPIO_Pin_0},
PF1 = {GPIOF, GPIO_Pin_1},
PF2 = {GPIOF, GPIO_Pin_2},
PF3 = {GPIOF, GPIO_Pin_3},
PF4 = {GPIOF, GPIO_Pin_4},
PF5 = {GPIOF, GPIO_Pin_5},
PF6 = {GPIOF, GPIO_Pin_6},
PF7 = {GPIOF, GPIO_Pin_7},
PF8 = {GPIOF, GPIO_Pin_8},
PF9 = {GPIOF, GPIO_Pin_9},
PF10 = {GPIOF, GPIO_Pin_10},
PF11 = {GPIOF, GPIO_Pin_11},
PF12 = {GPIOF, GPIO_Pin_12},
PF13 = {GPIOF, GPIO_Pin_13},
PF14 = {GPIOF, GPIO_Pin_14},
PF15 = {GPIOF, GPIO_Pin_15},
/*** GPIOG ***/
PG0 = {GPIOG, GPIO_Pin_0},
PG1 = {GPIOG, GPIO_Pin_1},
PG2 = {GPIOG, GPIO_Pin_2},
PG3 = {GPIOG, GPIO_Pin_3},
PG4 = {GPIOG, GPIO_Pin_4},
PG5 = {GPIOG, GPIO_Pin_5},
PG6 = {GPIOG, GPIO_Pin_6},
PG7 = {GPIOG, GPIO_Pin_7},
PG8 = {GPIOG, GPIO_Pin_8},
PG9 = {GPIOG, GPIO_Pin_9},
PG10 = {GPIOG, GPIO_Pin_10},
PG11 = {GPIOG, GPIO_Pin_11},
PG12 = {GPIOG, GPIO_Pin_12},
PG13 = {GPIOG, GPIO_Pin_13},
PG14 = {GPIOG, GPIO_Pin_14},
PG15 = {GPIOG, GPIO_Pin_15}
;
//EXTI0_IRQHandler
//EXTI1_IRQHandler
//EXTI2_IRQHandler
//EXTI3_IRQHandler
//EXTI4_IRQHandler
__weak void EXTI5_IRQHandler(void) {}
__weak void EXTI6_IRQHandler(void) {}
__weak void EXTI7_IRQHandler(void) {}
__weak void EXTI8_IRQHandler(void) {}
__weak void EXTI9_IRQHandler(void) {}
__weak void EXTI10_IRQHandler(void) {}
__weak void EXTI11_IRQHandler(void) {}
__weak void EXTI12_IRQHandler(void) {}
__weak void EXTI13_IRQHandler(void) {}
__weak void EXTI14_IRQHandler(void) {}
__weak void EXTI15_IRQHandler(void) {}
static inline IRQn_Type get_exti_group(u16 pin) {
switch (pin) {
case GPIO_Pin_0: return EXTI0_IRQn;
case GPIO_Pin_1: return EXTI1_IRQn;
case GPIO_Pin_2: return EXTI2_IRQn;
case GPIO_Pin_3: return EXTI3_IRQn;
case GPIO_Pin_4: return EXTI4_IRQn;
case GPIO_Pin_5:
case GPIO_Pin_6:
case GPIO_Pin_7:
case GPIO_Pin_8:
case GPIO_Pin_9: return EXTI9_5_IRQn;
case GPIO_Pin_10:
case GPIO_Pin_11:
case GPIO_Pin_12:
case GPIO_Pin_13:
case GPIO_Pin_14:
case GPIO_Pin_15: return EXTI15_10_IRQn;
};
}
static inline u8 get_port_source(GPIO_TypeDef* port) {
switch ((u32) port) {
case GPIOA_BASE: return EXTI_PortSourceGPIOA;
case GPIOB_BASE: return EXTI_PortSourceGPIOB;
case GPIOC_BASE: return EXTI_PortSourceGPIOC;
case GPIOD_BASE: return EXTI_PortSourceGPIOD;
};
}
static inline u16 get_pin_source(u16 pin) {
u8 pin_source = 0;
do {
if (pin & 0x01) break;
pin >>=1;
pin_source++;
} while (1);
return pin_source;
}
void gpio_exti_init(const GPIO* gpio, EXTITrigger_TypeDef trigger) {
IRQn_Type exti_grp = get_exti_group(gpio->pin);
u8 port_source = get_port_source(gpio->port);
u8 pin_source = get_pin_source(gpio->pin);
// NVIC
NVIC_InitTypeDef NVIC_InitStructure;
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);
NVIC_InitStructure.NVIC_IRQChannel = exti_grp;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
// EXTI
SYSCFG_EXTILineConfig(port_source, pin_source);
EXTI_InitTypeDef EXTI_InitStructure;
EXTI_InitStructure.EXTI_Line = gpio->pin;
EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;
EXTI_InitStructure.EXTI_Trigger = trigger;
EXTI_InitStructure.EXTI_LineCmd = ENABLE;
EXTI_Init(&EXTI_InitStructure);
}
void gpio_af_init(const GPIO* gpio, GPIOOType_TypeDef otype, GPIOPuPd_TypeDef pupd, u8 af) {
gpio_init(gpio, GPIO_Mode_AF, otype, pupd);
GPIO_PinAFConfig(gpio->port, get_pin_source(gpio->pin), af);
}
void EXTI9_5_IRQHandler(void) {
if ((EXTI->PR & EXTI_Line5) != RESET)
{
EXTI5_IRQHandler();
EXTI_ClearITPendingBit(EXTI_Line5);
}
if ((EXTI->PR & EXTI_Line6) != RESET)
{
EXTI6_IRQHandler();
EXTI_ClearITPendingBit(EXTI_Line6);
}
if ((EXTI->PR & EXTI_Line7) != RESET)
{
EXTI7_IRQHandler();
EXTI_ClearITPendingBit(EXTI_Line7);
}
if ((EXTI->PR & EXTI_Line8) != RESET)
{
EXTI8_IRQHandler();
EXTI_ClearITPendingBit(EXTI_Line8);
}
if ((EXTI->PR & EXTI_Line9) != RESET)
{
EXTI9_IRQHandler();
EXTI_ClearITPendingBit(EXTI_Line9);
}
if ((EXTI->PR & EXTI_Line10) != RESET)
{
EXTI10_IRQHandler();
EXTI_ClearITPendingBit(EXTI_Line10);
}
if ((EXTI->PR & EXTI_Line11) != RESET)
{
EXTI11_IRQHandler();
EXTI_ClearITPendingBit(EXTI_Line11);
}
}
void EXTI15_10_IRQHandler(void)
{
if ((EXTI->PR & EXTI_Line12) != RESET)
{
EXTI12_IRQHandler();
EXTI_ClearITPendingBit(EXTI_Line12);
}
if ((EXTI->PR & EXTI_Line13) != RESET)
{
EXTI13_IRQHandler();
EXTI_ClearITPendingBit(EXTI_Line13);
}
if ((EXTI->PR & EXTI_Line14) != RESET)
{
EXTI14_IRQHandler();
EXTI_ClearITPendingBit(EXTI_Line14);
}
if ((EXTI->PR & EXTI_Line15) != RESET)
{
EXTI15_IRQHandler();
EXTI_ClearITPendingBit(EXTI_Line15);
}
}
/**
General input GPIO initailizer
Usage: @ref gpio_init
Output type and speed does not matter to input gpio
*/
void gpio_input_init(const GPIO* gpio, GPIOPuPd_TypeDef pp_type){
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_StructInit(&GPIO_InitStructure);
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN;
GPIO_InitStructure.GPIO_Pin = gpio->pin;
GPIO_InitStructure.GPIO_PuPd = pp_type;
GPIO_Init(gpio->port, &GPIO_InitStructure);
}
/**
General output GPIO initailizer
Usage: @ref gpio_init
Speed is fixed to GPIO_Medium_Speed which should be sufficient.
*/
void gpio_output_init(const GPIO* gpio, GPIOOType_TypeDef output_type, GPIOPuPd_TypeDef pp_type){
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_StructInit(&GPIO_InitStructure);
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
GPIO_InitStructure.GPIO_Speed = GPIO_High_Speed;
GPIO_InitStructure.GPIO_Pin = gpio->pin;
GPIO_InitStructure.GPIO_OType = output_type;
GPIO_InitStructure.GPIO_PuPd = pp_type;
GPIO_Init(gpio->port, &GPIO_InitStructure);
}
/**
Initilize RCC clock for all GPIO ports
*/
void gpio_rcc_init_all(){
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE);
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOB, ENABLE);
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOC, ENABLE);
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOD, ENABLE);
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOE, ENABLE);
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOF, ENABLE);
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOG, ENABLE);
}
/**
* @brief GPIO Real-time Clock Initialization
* @param GPIO pointer
*/
void gpio_rcc_init(const GPIO* gpio){
switch ((uint32_t) gpio->port) {
case ((uint32_t)GPIOA):
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE);
break;
case ((uint32_t)GPIOB):
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOB, ENABLE);
break;
case ((uint32_t)GPIOC):
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOC, ENABLE);
break;
case ((uint32_t)GPIOD):
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOD, ENABLE);
break;
case ((uint32_t)GPIOE):
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOE, ENABLE);
break;
case ((uint32_t)GPIOF):
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOF, ENABLE);
break;
case ((uint32_t)GPIOG):
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOG, ENABLE);
break;
}
}
uint16_t getPinSource(const GPIO* gpio){
switch(gpio->pin){
case GPIO_Pin_0:
return GPIO_PinSource0;
case GPIO_Pin_1:
return GPIO_PinSource1;
case GPIO_Pin_2:
return GPIO_PinSource2;
case GPIO_Pin_3:
return GPIO_PinSource3;
case GPIO_Pin_4:
return GPIO_PinSource4;
case GPIO_Pin_5:
return GPIO_PinSource5;
case GPIO_Pin_6:
return GPIO_PinSource6;
case GPIO_Pin_7:
return GPIO_PinSource7;
case GPIO_Pin_8:
return GPIO_PinSource8;
case GPIO_Pin_9:
return GPIO_PinSource9;
case GPIO_Pin_10:
return GPIO_PinSource10;
case GPIO_Pin_11:
return GPIO_PinSource11;
case GPIO_Pin_12:
return GPIO_PinSource12;
case GPIO_Pin_13:
return GPIO_PinSource13;
case GPIO_Pin_14:
return GPIO_PinSource14;
default:
return GPIO_PinSource15;
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
#include <ctype.h>
#include "inputs.h"
#include "Referi.h"
//0-MENU
void mostrarMenuR()
{
printf("-----Elija una opcion-----\n\n");
printf("1-Dar de alta\n");
printf("2-Dar de baja\n");
printf("3-Modificar\n");
printf("4-Listar\n");
printf("5-Salir\n");
}
void printModificationMenuR()
{
printf("-----ELIJA QUE MODIFICAR-----\n\n");
printf("1-Nombre\n");
printf("2-Apellido\n");
printf("3-Sexo\n");
printf("4-eMail\n");
printf("5-Fecha\n");
printf("6-Salir\n");
}
//1-INICIALIZAR
int inicializarReferis(eReferi* referis, int len)
{
int i;
int retorno=-1;
if(referis!=NULL && len>0)
{
for (i=0; i<len; i++)
{
referis[i].isEmpty = FREE;
}
retorno=0;
}
return retorno;
}
int getFreeR(eReferi* referis,int len) //TERMINADA
{
int i;
int index = -1;//DEFINIMOS VALOR
for (i=0;i<len;i++)
{
if (referis[i].isEmpty == FREE)
{
index = i;
break;//SI DEVUELVE -1 NO HAY ESPACIO
}
}
return index;
}
int buscarReferiPorCodigo(eReferi* referi, int len, int codigo)
{
int i;
int retorno = -1;
if(referi!=NULL && len>0)
{
for(i=0; i<len; i++)
{
if(referi[i].codigo==codigo && referi[i].isEmpty==NOTFREE)
{
retorno = i;
break;
}
}
}
return retorno;
}
//2-ALTAS/BAJAS/MODIFICACION
int agregarReferis(eReferi* referis,int len,int codigo)
{
int i;
char diaAux[3];
char mesAux[3];
char anioAux[5];
char fechaAux[12];
char codigoRAux[10];
char nombreAux[32];
char apellidoAux[32];
char emailAux[32];
char auxSexo;
int dia;
int mes;
int anio;
int codigoAux;
int codigoE;
int retorno= -1;
i=getFreeR(referis, len);
if(i>=0)
{
getString("\nIngrese el nombre: ",nombreAux);//Pido
//VALIDACION
while(isOnlyLetters(nombreAux) == 0)
{
getString("\nPOR FAVOR SOLO INGRESE LETRAS\nIngrese el nombre nuevamente: ",nombreAux);//Valido
}
stringToUpper(nombreAux);//Paso primer caracter a Mayuscula
getString("\nIngrese el apellido: ",apellidoAux);//Pido
//VALIDACION
while(isOnlyLetters(apellidoAux) == 0)
{
getString("\nPOR FAVOR SOLO INGRESE LETRAS\nIngrese el apellido nuevamente: ",apellidoAux);//Valido
}
stringToUpper(apellidoAux);//Paso primer caracter a Mayuscula
fflush(stdin);
auxSexo=getChar("\nIngrese el sexo: ");//Pido
auxSexo=toupper(auxSexo);
//VALIDACION
while(auxSexo!= 'M' && auxSexo!= 'F')
{
auxSexo=getChar("\nERROR, SOLO INGRESE f/m Ingrese el sexo: ");//Valido
auxSexo=toupper(auxSexo);
}
getString("\nIngrese el eMail: ",emailAux);//Pido
//VALIDACION
/*while(//Funcion que valide mail (email) == 0)
{
getString("\nPOR FAVOR INGRESE UN EMAIL VALIDO\nIngrese el eMail nuevamente: ",email);//Valido
}
*/
getString("\nIngrese la fecha de nacimiento: ",fechaAux);//Pido
//VALIDACION
while(isADate(fechaAux) == 0)
{
getString("\nPOR FAVOR INGRESE UNA FECHA VALIDA \nIngrese la fecha nuevamente: ",fechaAux);//Valido
}
//VALIDACION YA QUE EN FUNCION DA ERROR
for(i=0;i<3;i++)///DA
{
if(fechaAux[1]!='/')
{
diaAux[0]=fechaAux[0];
diaAux[1]=fechaAux[1];
break;
}
else
{
diaAux[0]=fechaAux[0];
}
}
for(i=2;i<10;i++)///MES Y ANIO
{
if(fechaAux[2]!='/' && fechaAux[3]!= '/')
{
mesAux[0]=fechaAux[2];
mesAux[1]=fechaAux[3];
anioAux[0]=fechaAux[5];
anioAux[1]=fechaAux[6];
anioAux[2]=fechaAux[7];
anioAux[3]=fechaAux[8];
break;
}
if(fechaAux[3]!='/' && fechaAux[4]!= '/')
{
mesAux[0]=fechaAux[3];
mesAux[1]=fechaAux[4];
anioAux[0]=fechaAux[6];
anioAux[1]=fechaAux[7];
anioAux[2]=fechaAux[8];
anioAux[3]=fechaAux[9];
break;
}
if(fechaAux[2]!='/' && fechaAux[3]=='/')
{
mesAux[0]=fechaAux[2];
anioAux[0]=fechaAux[4];
anioAux[1]=fechaAux[5];
anioAux[2]=fechaAux[6];
anioAux[3]=fechaAux[7];
}
if(fechaAux[3]!='/' && fechaAux[4]=='/')
{
mesAux[0]=fechaAux[3];
anioAux[0]=fechaAux[5];
anioAux[1]=fechaAux[6];
anioAux[2]=fechaAux[7];
anioAux[3]=fechaAux[8];
}
}
dia=atoi(diaAux);
mes=atoi(mesAux);
anio=atoi(anioAux);
//FIN
if(dia>31 || dia<=0 && mes>12 || mes<=0 && anio>2050 || anio<=1900)
{
printf("\nLA FECHA NO ES VALIDA");
return -1;
}
else
{
referis[i].fechaNac.dia=dia;
referis[i].fechaNac.mes=mes;
referis[i].fechaNac.anio=anio;
}
strcpy(referis[i].nombre,nombreAux);
strcpy(referis[i].apellido,apellidoAux);
referis[i].sexo=auxSexo;
strcpy(referis[i].eMail,emailAux);
referis[i].isEmpty=NOTFREE;
referis[i].codigo=codigo;
retorno =0;
printf("\nCarga exitosa.\n");//Se pudo cargar el usuario
}
else
{
printf("\nNo hay espacio disponible.\n");//No hay mas espacio
}
return retorno;
}
int modificarReferis(eReferi* referis,int len)
{
int id;
int i;
int index;
int opcion;
int sector;
char auxNombre[32];
char auxApellido[32];
char auxEmail[32];
char auxId[10];
char auxSexo;
char auxFecha[12];
char diaAux[3];
char mesAux[3];
char anioAux[5];
char respuesta;
int dia;
int mes;
int anio;
int retorno;
if(len >0 && referis!= NULL)
{
retorno=0;
printReferi(referis,len);
getString("\nIngrese el codigo del referi: ",auxId);
while(isNumeric(auxId)==0)
{
getString("\nPOR FAVOR INGRESE SOLO NUMEROS\nIngrese codigo nuevamente: ",auxId);
}
id=atoi(auxId);
index=buscarReferiPorCodigo(referis, len, id);
if(index>=0)
{
printModificationMenuR();
opcion=getInt("Su opcion: ");
switch(opcion)
{
case 1:
getString("\nIngrese un nuevo nombre para el referi: ",auxNombre);
while(isOnlyLetters(auxNombre)==0)
{
getString("\nPOR FAVOR SOLO INGRESE SOLO LETRAS \nIngrese nuevamente el nuevo referi: ",auxNombre);
}
stringToUpper(auxNombre);
strcpy(referis[index].nombre, auxNombre);
break;
case 2:
getString("\nIngrese un nuevo apellido para el referi: ",auxApellido);
while(isOnlyLetters(auxApellido)==0)
{
getString("\nPOR FAVOR SOLO INGRESE SOLO LETRAS \nIngrese nuevamente el nuevo apellido: ",auxApellido);
}
stringToUpper(auxApellido);
strcpy(referis[index].apellido, auxApellido);
break;
case 3:
printf("\nDesea cambiar el sexo por el sexo opuesto? s/n");
fflush(stdin);
respuesta=getche();
respuesta=tolower(respuesta);
while(respuesta!='s' && respuesta!='n')
{
printf("\nPOR FAVOR, SOLO INGRESE s/n");
fflush(stdin);
respuesta=getche();
respuesta=tolower(respuesta);
}
if(respuesta=='s')
{
if(referis[index].sexo == 'M')
{
referis[index].sexo = 'F';
}
else
{
referis[index].sexo = 'M';
}
}
else
{
retorno=-3;//SE CANCELO LA ACCION
}
break;
case 4:
getString("\nIngrese un nuevo eMail para el referi: ",auxEmail);
while(isOnlyLetters(auxEmail)==0)
{
getString("\nPOR FAVOR SOLO INGRESE SOLO LETRAS \nIngrese nuevamente el nuevo eMail: ",auxEmail);
}
strcpy(referis[index].eMail, auxEmail);
break;
case 5:
getString("\nIngrese la nueva fecha de nacimiento: ",auxFecha);//Pido
//VALIDACION
while(isADate(auxFecha) == 0)
{
getString("\nPOR FAVOR INGRESE UNA FECHA VALIDA \nIngrese la fecha nuevamente: ",auxFecha);//Valido
}
//VALIDACION YA QUE EN FUNCION DA ERROR
for(i=0;i<3;i++)///DA
{
if(auxFecha[1]!='/')
{
diaAux[0]=auxFecha[0];
diaAux[1]=auxFecha[1];
break;
}
else
{
diaAux[0]=auxFecha[0];
}
}
for(i=2;i<10;i++)///MES Y ANIO
{
if(auxFecha[2]!='/' && auxFecha[3]!= '/')
{
mesAux[0]=auxFecha[2];
mesAux[1]=auxFecha[3];
anioAux[0]=auxFecha[5];
anioAux[1]=auxFecha[6];
anioAux[2]=auxFecha[7];
anioAux[3]=auxFecha[8];
break;
}
if(auxFecha[3]!='/' && auxFecha[4]!= '/')
{
mesAux[0]=auxFecha[3];
mesAux[1]=auxFecha[4];
anioAux[0]=auxFecha[6];
anioAux[1]=auxFecha[7];
anioAux[2]=auxFecha[8];
anioAux[3]=auxFecha[9];
break;
}
if(auxFecha[2]!='/' && auxFecha[3]=='/')
{
mesAux[0]=auxFecha[2];
anioAux[0]=auxFecha[4];
anioAux[1]=auxFecha[5];
anioAux[2]=auxFecha[6];
anioAux[3]=auxFecha[7];
}
if(auxFecha[3]!='/' && auxFecha[4]=='/')
{
mesAux[0]=auxFecha[3];
anioAux[0]=auxFecha[5];
anioAux[1]=auxFecha[6];
anioAux[2]=auxFecha[7];
anioAux[3]=auxFecha[8];
}
}
dia=atoi(diaAux);
mes=atoi(mesAux);
anio=atoi(anioAux);
//FIN
if(dia>31 || dia<=0 && mes>12 || mes<=0 && anio>2050 || anio<=1900)
{
printf("\nLA FECHA NO ES VALIDA");
return -4;
}
else
{
referis[i].fechaNac.dia=dia;
referis[i].fechaNac.mes=mes;
referis[i].fechaNac.anio=anio;
}
break;
case 6:
retorno=-2;//-2 PARA SALIR
break;
default:
printf("\nError. No se ha ingresado una opcion valida.\n");
break;
}
}
else
{
retorno=-1;
}
return retorno;
}
}
int bajaReferis(eReferi* referis,int len,int id)
{
//Hacer baja Lgica
int retorno =-1;
int index;
char respuesta;
if (referis!=NULL && len>0)
{
printReferi(referis,len);
index = buscarReferiPorCodigo(referis,len,id);
if(index!=-1) //CAMBIAMOS EL ESTADO DEL EQUIPO A LIBRE
{
if (referis[index].isEmpty==FREE)
{
}
else
{
printf("\n\n\nDar de baja a:");
printf("\n%s %s",referis[index].nombre,referis[index].apellido);
printf("\n\nEsta seguro de eliminar el dato s/n: ");
respuesta = getche();
}
if (respuesta=='s')
{
referis[index].isEmpty = FREE;
retorno=0;//ACEPTO ACCION
}
else
{
if (referis[index].isEmpty==FREE)
{
retorno=2;//EL DATO YA SE ELIMINO
}
else
{
retorno =1;//CANCELO ACCION
}
}
}
}
return retorno;//SI RETORNA -1 NO FUNCIONO
}
//3-ORDENAR
int ordenarReferisNombreyApellido(eReferi* referis, int len, int order)
{
int i;
int j;
int retorno=-1;
eReferi aux[1];
if(referis!=NULL||len<0||order<0||order>1)
{
for(i=0; i<len-1; i++)
{
for(j=1; j<len; j++)
{
switch(order)
{
case 0:
if (stricmp(referis[i].apellido,referis[j].apellido)>0)
{
aux[0]=referis[i];
referis[i]=referis[j];
referis[j]=aux[0];
}
if((stricmp(referis[i].apellido,referis[j].apellido)==0) && (stricmp(referis[i].nombre,referis[j].nombre)>0))
{
aux[0]=referis[i];
referis[i]=referis[j];
referis[j]=aux[0];
}
break;
case 1:
if (stricmp(referis[i].apellido,referis[j].apellido)<0)
{
aux[0]=referis[i];
referis[i]=referis[j];
referis[j]=aux[0];
}
if((stricmp(referis[i].apellido,referis[j].apellido)==0) && (stricmp(referis[i].nombre,referis[j].nombre)<0))
{
aux[0]=referis[i];
referis[i]=referis[j];
referis[j]=aux[0];
}
break;
}
}
}
retorno=0;
}
return retorno;
}
//4-MOSTRAR
int printReferi(eReferi* referis,int len)
{
int i;
int index;
char sexo[20];
printf("Codigo Nombre Apellido Sexo Fecha de Nacimiento Email\n");
for(i=0; i<len; i++)
{
if(referis[i].sexo=='M')
{
strcpy(sexo,"Masculino");
}
else
{
strcpy(sexo,"Femenino");
}
if(referis[i].isEmpty==NOTFREE)
{
printf("%d-- %10s %7s %5s %7d/%d/%d %12s\n",referis[i].codigo,referis[i].nombre,referis[i].apellido,sexo,referis[i].fechaNac.dia,referis[i].fechaNac.mes,referis[i].fechaNac.anio,referis[i].eMail);
}
}
return 0;
}
//5-EXTRAS
void hardcodeoReferis(eReferi* referis)
{
int i;
char nombre[4][32]={"Pablo","Nestor","German","Patricia"};
char apellido[4][32]={"Lunati","Pitana","Delfino","Vazquez"};
char eMail[4][32]={"[email protected]","[email protected]","[email protected]","[email protected]"};
int dia[4]={5,17,8,9};
int mes[4]={6,6,5,11};
int anio[4]={1967,1975,1989,1969};
for(i=0;i<4;i++)
{
referis[i].codigo=i+1;
strcpy(referis[i].nombre,nombre[i]);
strcpy(referis[i].apellido,apellido[i]);
strcpy(referis[i].eMail,eMail[i]);
if(i<3)
{
referis[i].sexo='M';
}
else
{
referis[i].sexo='F';
}
referis[i].fechaNac.dia=dia[i];
referis[i].fechaNac.mes=mes[i];
referis[i].fechaNac.anio=anio[i];
referis[i].isEmpty=NOTFREE;
}
}
int cantidadReferisOcupados(eReferi* referis, int len)
{
int i;
int cantidadReferis=0;
for (i=0;i<len;i++)
{
if (referis[i].isEmpty == NOTFREE)
{
cantidadReferis++;
//break;//SI DEVUELVE -1 NO HAY ESPACIO
}
}
return cantidadReferis;
}
|
C
|
/*
* A wrapper around printf. Not thread-safe due to the global variable
* DEBUG.
*/
#include <stdio.h>
#include <stdarg.h>
#include <stdbool.h>
bool DEBUG = false;
void debug_enable(bool enable)
{
DEBUG = enable;
}
int debug_printf(char *format, ...)
{
if (!DEBUG)
{
return 0;
}
va_list args;
va_start(args, format);
return printf(format, args);
}
|
C
|
#include <unistd.h>
#include <stdio.h>
#include <string.h>
/*
Given a filename, retrieve its extension (everything after the last '.')
*/
char* get_extension(char* str)
{
char* file = strrchr(str, '/');
if (!file)
file = str;
else
file += 1;
char* ext = strrchr(file, '.');
if (!ext)
return 0;
return ext+1;
}
/*
Given a file descriptor, figure out what MIME type correlates best with the
file. In essence, all it does is look at the filename extension and map
that extension to a known MIME type.
*/
void deduce_mime_type(int fd, char* buf)
{
// Witchcraft to extract filename from file descriptor
char filename[101];
char procpath[50];
sprintf(procpath, "/proc/self/fd/%d", fd);
size_t n = readlink(procpath, filename, 100);
filename[n] = 0;
// Retrieve the extension of the filename
char* ext = get_extension(filename);
// If not extension, default to binary
if (!ext)
ext = "bin";
// Extension to MIME mapping
char* MIME[][2] = {
{"html", "text/html"},
{"bin", "application/octet-stream"},
{"gif", "image/gif"},
{"png", "image/png"},
{"jpg", "image/jpeg"},
{"jpeg", "image/jpeg"},
{"txt", "text/plain"},
{"js", "application/javascript"},
{"css", "text/css"},
{"pdf", "application/pdf"},
{"xml", "application/xml"},
{"mp3", "audio/mpeg"},
{"ogg", "audio/ogg"},
{"json", "application/json"},
{"zip", "application/zip"},
{"avi", "video/avi"},
{"mp4", "video/mp4"}
};
int types = sizeof(MIME) / sizeof(MIME[0]);
int i;
for (i = 0; i < types; i++) {
if (strcmp(ext, MIME[i][0]) == 0) {
strcpy(buf, MIME[i][1]);
break;
}
}
if (i == types)
strcpy(buf, "application/octet-stream");
}
|
C
|
#include <foo.h>
#include <stdio.h>
int
main (int argc, char * argv[])
{
int value = power_level ();
if (value < 9000) {
printf ("Power level is %i\n", value);
return 1;
}
printf ("IT'S OVER 9000!!!\n");
return 0;
}
|
C
|
#include <stdio.h>
#include <math.h>
int main() {
int n,i;
float x[1000], total=0, rata, rata_2=0, sd;
printf ("jumlah data (maksimum 1000 buah) : ");
scanf("%d",&n);
printf("\n");
for (i=0;i<n;i++){
printf("nilai data ke %d ? ",i+1);
scanf("%f", &x[i]);
total = total + x[i];
}
rata = total /n;
for (i=0;i<n;i++)
{rata_2+=((x[i]-rata)*(x[i]-rata));}
sd= sqrt(rata_2/n);
printf("\n");
printf("jumlah data = %d\n",n);
printf("total nilai = %.2f\n",total);
printf("rata-rata nilai = %.2f\n",rata);
printf("deviasi standart = %.2f\n",sd);
return 0;
}
|
C
|
/*
* Leonardo Wistuba de França <[email protected]>
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "quickSort.h"
/*
* O Quicksort é o algoritmo mais eficiente para uma grande variedade de situações.
* Entretanto, é um método bastante frágil no sentido de que qualquer erro de implementação pode ser difícil de ser detectado.
* O algoritmo é recursivo, o que demanda uma pequena quantidade de memória adicional.
* Além disso, seu desempenho é da ordem de O(n²) operações no pior caso.
*
* Retirado do livro Projeto de Algoritmos do Nivio Ziviani
*/
void particionar(int esquerda, int direita, int* i, int* j, int* A) {
int x, w;
*i = esquerda;
*j = direita;
x = A[(*i + *j) / 2]; // obtém o pivô x
do {
while (x > A[*i])
(*i)++;
while (x < A[*j])
(*j)--;
if (*i <= *j) {
w = A[*i];
A[*i] = A[*j];
A[*j] = w;
(*i)++;
(*j)--;
}
} while (*i <= *j);
}
void ordenar(int esquerda, int direita, int* A) {
int i, j;
particionar(esquerda, direita, &i, &j, A);
if (esquerda < j) ordenar(esquerda, j, A);
if (i < direita) ordenar(i, direita, A);
}
void quickSort(int* A, int* n) {
ordenar(0, *n - 1, A);
}
|
C
|
#include<stdio.h>
#include<string.h>
int find(char str[100][100],char st[50],int lr);
int find(char str[100][100],char st[50],int lr)
{
char sup[50];
int flag=0;
for(int i=0;i<lr;i++)
{
for(int j=0;j<strlen(st);j++)
sup[j]=str[i][j];
if(strcmp(st,sup)==0)
{
flag++;
}
for(int j=0;j<strlen(st);j++)
sup[j]='\0';
}
return flag==3?strlen(st):0;
return 0;
}
int main()
{
char arr[100][100];
char sup[50];
int l,low,pos,max=0;
printf("please enter number of words you want to input\n");
scanf("%d",&l);
printf("plese enter %d words\n",l);
for(int i=0;i<l;i++)
scanf("%s",arr[i]);
low=strlen(arr[0]);
for(int i=0;i<l;i++)
{
if(low>=strlen(arr[i]))
{
low=strlen(arr[i]);
pos=i;
}
}
//printf("%s",arr[pos]);
for(int i=0;i<strlen(arr[pos]);i++)
{
sup[i]=arr[pos][i];
int len=find(arr,sup,l);
if(len>max)
{
max=len;
}
}
if(max==0)
printf("no common prefix\n");
else
{
printf("the commom prefix is:-");
for(int i=0;i<max;i++)
{
printf("%c",arr[pos][i]);
}
}
return 0;
}
|
C
|
/***************************************************************************
* Manipulando Imagens TIFF (Tag Image File Format)
* autoras: Lissa Pesci
* Miriam Yumi Peixoto
* compile: gcc -o ex_imagem ex_imagem.c imagem.c -lm -ltiff
**************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include "imagem.h"
int IMAGE_WIDTH = 512;
int IMAGE_HEIGHT = 512;
int NFRAMES;
int main (int argc, char *argv[]) {
struct Image * image1, * image2;
struct ComprImage compr_image;
unsigned int fator = 5;
if (argc == 2) {
image1 = ReadTiffImage(argv[1]);
compr_image = comprime(image1, fator);
//compr_image = aplica_dct(image);
//image = quantizacao(compr_image, 3);
image2 = descomprime(compr_image, fator);
SaveTiffImage("imagens/anothertest.tif", image2);
} else {
printf("Usage: ex_imagem filename.tiff\n");
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include "ssu_employee.h"
int main(int argc, char *argv[]) {
struct ssu_employee record;
int fd;
//shell에서 파일을 입력받음
if(argc < 2) {
fprintf(stderr, "usage : %s file\n", argv[0]);
exit(1);
}
//쓰기 전용 모드로 파일을 open
//파일이 없을 경우 0644 모드로 생성 후 쓰기 전용 모드로 파일을 open
if((fd = open(argv[1], O_WRONLY | O_CREAT | O_EXCL, 0640)) < 0) {
fprintf(stderr, "open error for %s\n", argv[1]);
exit(1);
}
while(1) {
printf("Enter employee name <SPACE> salary: ");
scanf("%s", record.name);
if(record.name[0] == '.')
break;
scanf("%d", &record.salary);
record.pid = getpid();
//record에 저장된 정보를 argv[1] 파일에 write하기
write(fd, (char *)&record, sizeof(record));
}
close(fd);
exit(0);
}
|
C
|
/* Check whether the tree is complete or not
For this, check if a tree has either 0 or 2 nodes. If a tree has one child for any of the nodes, then the tree is not complete!
*/
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *left, *right;
};
struct node * createNode(int data)
{
struct node *new=(struct node *)malloc(sizeof(struct node));
new->data=data;
new->left=NULL;
new->right=NULL;
return new;
}
void insert_key(struct node **root,int data)
{
if(!*root)
{
*root=createNode(data);
return;
}
struct node *ptr=*root;
//RECURSIVE VERSION
if(data < ptr->data)
insert_key(&(ptr->left),data);
if(data > ptr->data)
insert_key(&(ptr->right),data);
}
struct node *find_min(struct node *root)
{
struct node *result;
if(!root)
return;
if(root->left)
{
result= find_min(root->left);
}
else
result=root;
return result;
}
struct node *find_max(struct node *root)
{
struct node *result;
if(!root)
return root;
if(root->right)
{
result= find_max(root->right);
}
else
result=root;
return result;
}
struct node* delete_key(struct node *root,int data)
{
// base case
if(!root)
return root;
// If the key to be deleted is smaller than the root's key,
// then it lies in left subtree
if(data<root->data)
root->left=delete_key(root->left,data);
// If the key to be deleted is greater than the root's key,
// then it lies in right subtree
else if(data>root->data)
root->right=delete_key(root->right,data);
//if root is same as key to be deleted, then delete this
else
{
//perform deletion according to the type of this key
struct node *temp;
// node with only right child or no child
if(!root->left)
{
temp=root->right;
free(root);
return temp;
}
// node with only left child or no child
else if(!root->right)
{
temp=root->left;
free(root);
return temp;
}
//node with two children: get inorder successor (smallest in RST)
temp=find_min(root->right);
root->data=temp->data;
root->right=delete_key(root->right,temp->data);
}
return root;
}
void preorder(struct node *root)
{
if(root)
{
printf("%d ",root->data);
preorder(root->left);
preorder(root->right);
}
}
void inorder(struct node *root)
{
if(root)
{
inorder(root->left);
printf("%d ",root->data);
inorder(root->right);
}
}
void postorder(struct node *root)
{
if(root)
{
postorder(root->left);
postorder(root->right);
printf("%d ",root->data);
}
}
int isComplete(struct node *root)
{
//if node is null
if(!root)
return 1;
//if node is a leaf
if(!root->left && !root->right)
{
return 1;
}
//if it has 2 children
else if(root->left && root->right)
return(isComplete(root->left) && isComplete(root->right));
//node having one children
else
return 0;
}
int main()
{
struct node *root=NULL;
int choice,index,key,num;
printf("\n1. Insert key\t2. Delete Key\n");
printf("3. Find min\t4. Inorder traversal\n");
printf("5. Find max\t6. Is the BST complete?\t7. Exit\n");
printf("Enter your choice:");
scanf("%d", &choice);
struct node *res;
while(choice!=7)
{
switch (choice)
{
case 1:
printf("Enter the key to be inserted.\n");
scanf("%d",&key);
printf("key: %d\n",key);
insert_key(&root,key);
break;
case 2:
printf("Enter the key to be deleted.\n");
scanf("%d",&key);
printf("key: %d\n",key);
// res=find_min(root);
// printf("Min is:%d",res->data);
delete_key(root,key);
break;
case 3:
res=find_min(root);
printf("Min is:%d\n",res->data);
break;
case 4:
printf("Inorder traversal is:\n");
inorder(root);
break;
case 5:
res=find_max(root);
printf("Max is:%d\n",res->data);
break;
case 6:
num=isComplete(root);
if(num)
printf("Yes\n");
else
printf("No\n");
break;
case 7:
printf("BYE");
exit(0);
break;
default:
printf("Wrong option!!\n");
break;
}
printf("Enter your choice:");
scanf("%d", &choice);
}
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* asm_helper_2.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: fpetras <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/04/17 11:57:53 by fpetras #+# #+# */
/* Updated: 2018/04/19 10:17:54 by fpetras ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_asm.h"
static int ft_inside_quotes(char *line, int j)
{
int i;
int quotes;
int inside;
i = 0;
quotes = 0;
inside = 0;
while (line[i])
{
if (line[i] == '\"')
quotes++;
if (i == j && quotes == 1)
inside = 1;
i++;
}
if (quotes == 2 && inside == 1)
return (1);
return (0);
}
void ft_handle_comments(char **file)
{
int i;
int j;
i = 0;
while (file[i])
{
j = 0;
while (file[i][j])
{
if (file[i][j] == COMMENT_CHAR || file[i][j] == ';')
{
if ((ft_strstr(file[i], NAME_CMD_STRING) ||
ft_strstr(file[i], COMMENT_CMD_STRING)) &&
ft_inside_quotes(file[i], j))
;
else
file[i][j] = '\0';
}
j++;
}
i++;
}
}
/*
** Does not trim lines within multi-line name or comment
*/
static int ft_skip_header(char **file)
{
int i;
int j;
int quotes;
char *tmp;
i = -1;
quotes = 0;
while (file[++i])
{
j = -1;
if (ft_strstr(file[i], NAME_CMD_STRING) ||
ft_strstr(file[i], COMMENT_CMD_STRING))
{
tmp = ft_strdup(ft_strchr(file[i], '.'));
free(file[i]);
file[i] = tmp;
}
while (file[i][++j])
(file[i][j] == '\"') ? quotes++ : 0;
if (quotes == 4)
return (i + 1);
}
return (0);
}
void ft_trim_file(char **file)
{
int i;
char *tmp;
i = ft_skip_header(file);
while (file[i])
{
tmp = ft_strtrim(file[i]);
free(file[i]);
file[i] = ft_strdup(tmp);
free(tmp);
i++;
}
}
|
C
|
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
#include "runtime.h"
#include "stack.h"
enum {
maxround = sizeof(uintptr),
};
uint32 runtime·panicking;
void (*runtime·destroylock)(Lock*);
/*
* We assume that all architectures turn faults and the like
* into apparent calls to runtime.sigpanic. If we see a "call"
* to runtime.sigpanic, we do not back up the PC to find the
* line number of the CALL instruction, because there is no CALL.
*/
void runtime·sigpanic(void);
int32
runtime·gotraceback(void)
{
byte *p;
p = runtime·getenv("GOTRACEBACK");
if(p == nil || p[0] == '\0')
return 1; // default is on
return runtime·atoi(p);
}
static Lock paniclk;
void
runtime·startpanic(void)
{
if(m->dying) {
runtime·printf("panic during panic\n");
runtime·exit(3);
}
m->dying = 1;
runtime·xadd(&runtime·panicking, 1);
runtime·lock(&paniclk);
}
void
runtime·dopanic(int32 unused)
{
static bool didothers;
if(g->sig != 0)
runtime·printf("[signal %x code=%p addr=%p pc=%p]\n",
g->sig, g->sigcode0, g->sigcode1, g->sigpc);
if(runtime·gotraceback()){
if(g != m->g0) {
runtime·printf("\n");
runtime·goroutineheader(g);
runtime·traceback(runtime·getcallerpc(&unused), runtime·getcallersp(&unused), 0, g);
}
if(!didothers) {
didothers = true;
runtime·tracebackothers(g);
}
}
runtime·unlock(&paniclk);
if(runtime·xadd(&runtime·panicking, -1) != 0) {
// Some other m is panicking too.
// Let it print what it needs to print.
// Wait forever without chewing up cpu.
// It will exit when it's done.
static Lock deadlock;
runtime·lock(&deadlock);
runtime·lock(&deadlock);
}
runtime·exit(2);
}
void
runtime·panicindex(void)
{
runtime·panicstring("index out of range");
}
void
runtime·panicslice(void)
{
runtime·panicstring("slice bounds out of range");
}
void
runtime·throwreturn(void)
{
// can only happen if compiler is broken
runtime·throw("no return at end of a typed function - compiler is broken");
}
void
runtime·throwinit(void)
{
// can only happen with linker skew
runtime·throw("recursive call during initialization - linker skew");
}
void
runtime·throw(int8 *s)
{
runtime·startpanic();
runtime·printf("throw: %s\n", s);
runtime·dopanic(0);
*(int32*)0 = 0; // not reached
runtime·exit(1); // even more not reached
}
void
runtime·panicstring(int8 *s)
{
Eface err;
if(m->gcing) {
runtime·printf("panic: %s\n", s);
runtime·throw("panic during gc");
}
runtime·newErrorString(runtime·gostringnocopy((byte*)s), &err);
runtime·panic(err);
}
int32
runtime·mcmp(byte *s1, byte *s2, uint32 n)
{
uint32 i;
byte c1, c2;
for(i=0; i<n; i++) {
c1 = s1[i];
c2 = s2[i];
if(c1 < c2)
return -1;
if(c1 > c2)
return +1;
}
return 0;
}
byte*
runtime·mchr(byte *p, byte c, byte *ep)
{
for(; p < ep; p++)
if(*p == c)
return p;
return nil;
}
uint32
runtime·rnd(uint32 n, uint32 m)
{
uint32 r;
if(m > maxround)
m = maxround;
r = n % m;
if(r)
n += m-r;
return n;
}
static int32 argc;
static uint8** argv;
Slice os·Args;
Slice syscall·envs;
void
runtime·args(int32 c, uint8 **v)
{
argc = c;
argv = v;
}
int32 runtime·isplan9;
int32 runtime·iswindows;
void
runtime·goargs(void)
{
String *s;
int32 i;
// for windows implementation see "os" package
if(Windows)
return;
s = runtime·malloc(argc*sizeof s[0]);
for(i=0; i<argc; i++)
s[i] = runtime·gostringnocopy(argv[i]);
os·Args.array = (byte*)s;
os·Args.len = argc;
os·Args.cap = argc;
}
void
runtime·goenvs_unix(void)
{
String *s;
int32 i, n;
for(n=0; argv[argc+1+n] != 0; n++)
;
s = runtime·malloc(n*sizeof s[0]);
for(i=0; i<n; i++)
s[i] = runtime·gostringnocopy(argv[argc+1+i]);
syscall·envs.array = (byte*)s;
syscall·envs.len = n;
syscall·envs.cap = n;
}
byte*
runtime·getenv(int8 *s)
{
int32 i, j, len;
byte *v, *bs;
String* envv;
int32 envc;
bs = (byte*)s;
len = runtime·findnull(bs);
envv = (String*)syscall·envs.array;
envc = syscall·envs.len;
for(i=0; i<envc; i++){
if(envv[i].len <= len)
continue;
v = envv[i].str;
for(j=0; j<len; j++)
if(bs[j] != v[j])
goto nomatch;
if(v[len] != '=')
goto nomatch;
return v+len+1;
nomatch:;
}
return nil;
}
void
runtime·getgoroot(String out)
{
byte *p;
p = runtime·getenv("GOROOT");
out = runtime·gostringnocopy(p);
FLUSH(&out);
}
int32
runtime·atoi(byte *p)
{
int32 n;
n = 0;
while('0' <= *p && *p <= '9')
n = n*10 + *p++ - '0';
return n;
}
void
runtime·check(void)
{
int8 a;
uint8 b;
int16 c;
uint16 d;
int32 e;
uint32 f;
int64 g;
uint64 h;
float32 i, i1;
float64 j, j1;
void* k;
uint16* l;
struct x1 {
byte x;
};
struct y1 {
struct x1 x1;
byte y;
};
if(sizeof(a) != 1) runtime·throw("bad a");
if(sizeof(b) != 1) runtime·throw("bad b");
if(sizeof(c) != 2) runtime·throw("bad c");
if(sizeof(d) != 2) runtime·throw("bad d");
if(sizeof(e) != 4) runtime·throw("bad e");
if(sizeof(f) != 4) runtime·throw("bad f");
if(sizeof(g) != 8) runtime·throw("bad g");
if(sizeof(h) != 8) runtime·throw("bad h");
if(sizeof(i) != 4) runtime·throw("bad i");
if(sizeof(j) != 8) runtime·throw("bad j");
if(sizeof(k) != sizeof(uintptr)) runtime·throw("bad k");
if(sizeof(l) != sizeof(uintptr)) runtime·throw("bad l");
if(sizeof(struct x1) != 1) runtime·throw("bad sizeof x1");
if(offsetof(struct y1, y) != 1) runtime·throw("bad offsetof y1.y");
if(sizeof(struct y1) != 2) runtime·throw("bad sizeof y1");
uint32 z;
z = 1;
if(!runtime·cas(&z, 1, 2))
runtime·throw("cas1");
if(z != 2)
runtime·throw("cas2");
z = 4;
if(runtime·cas(&z, 5, 6))
runtime·throw("cas3");
if(z != 4)
runtime·throw("cas4");
*(uint64*)&j = ~0ULL;
if(j == j)
runtime·throw("float64nan");
if(!(j != j))
runtime·throw("float64nan1");
*(uint64*)&j1 = ~1ULL;
if(j == j1)
runtime·throw("float64nan2");
if(!(j != j1))
runtime·throw("float64nan3");
*(uint32*)&i = ~0UL;
if(i == i)
runtime·throw("float32nan");
if(!(i != i))
runtime·throw("float32nan1");
*(uint32*)&i1 = ~1UL;
if(i == i1)
runtime·throw("float32nan2");
if(!(i != i1))
runtime·throw("float32nan3");
runtime·initsig(0);
}
void
runtime·Caller(int32 skip, uintptr retpc, String retfile, int32 retline, bool retbool)
{
Func *f, *g;
uintptr pc;
uintptr rpc[2];
/*
* Ask for two PCs: the one we were asked for
* and what it called, so that we can see if it
* "called" sigpanic.
*/
retpc = 0;
if(runtime·callers(1+skip-1, rpc, 2) < 2) {
retfile = runtime·emptystring;
retline = 0;
retbool = false;
} else if((f = runtime·findfunc(rpc[1])) == nil) {
retfile = runtime·emptystring;
retline = 0;
retbool = true; // have retpc at least
} else {
retpc = rpc[1];
retfile = f->src;
pc = retpc;
g = runtime·findfunc(rpc[0]);
if(pc > f->entry && (g == nil || g->entry != (uintptr)runtime·sigpanic))
pc--;
retline = runtime·funcline(f, pc);
retbool = true;
}
FLUSH(&retpc);
FLUSH(&retfile);
FLUSH(&retline);
FLUSH(&retbool);
}
void
runtime·Callers(int32 skip, Slice pc, int32 retn)
{
// runtime.callers uses pc.array==nil as a signal
// to print a stack trace. Pick off 0-length pc here
// so that we don't let a nil pc slice get to it.
if(pc.len == 0)
retn = 0;
else
retn = runtime·callers(skip, (uintptr*)pc.array, pc.len);
FLUSH(&retn);
}
void
runtime·FuncForPC(uintptr pc, void *retf)
{
retf = runtime·findfunc(pc);
FLUSH(&retf);
}
uint32
runtime·fastrand1(void)
{
uint32 x;
x = m->fastrand;
x += x;
if(x & 0x80000000L)
x ^= 0x88888eefUL;
m->fastrand = x;
return x;
}
|
C
|
#ifndef SQL_H
#define SQL_H
#define CREA_JUGADORES "CREATE TABLE jugadores ("\
"nombre VARCHAR(12) NOT NULL,"\
"passwd VARCHAR(12) NOT NULL,"\
"email VARCHAR(150) NOT NULL,"\
"codreg CHAR(13) NOT NULL,"\
"estado INT NOT NULL DEFAULT 0,"\
"INDEX login (nombre, passwd),"\
"CONSTRAINT pk_nombre_jugadores PRIMARY KEY (nombre)"\
") TYPE=InnoDB;"
#define CREA_GRUPOS "CREATE TABLE grupos ("\
"gid INT NOT NULL AUTO_INCREMENT,"\
"grupo VARCHAR(12) NOT NULL UNIQUE,"\
"INDEX gid_ind (gid),"\
"CONSTRAINT pk_gid_grupos PRIMARY KEY (gid)"\
") TYPE=InnoDB;"
#define CREA_RANGOS "CREATE TABLE rangos ("\
"rango VARCHAR(25) NOT NULL,"\
"nivel INT NOT NULL UNIQUE,"\
"INDEX rango_ind (rango),"\
"INDEX nivel_ind (nivel),"\
"CONSTRAINT pk_rango_rangos PRIMARY KEY (rango),"\
"CONSTRAINT fk_rango_rangos FOREIGN KEY (rango) REFERENCES grupos(grupo) ON DELETE CASCADE"\
") TYPE=InnoDB;"
#define CREA_INMORTALES "CREATE TABLE inmortales ("\
"uid INT NOT NULL AUTO_INCREMENT,"\
"nombre VARCHAR(12) NOT NULL UNIQUE,"\
"rango VARCHAR(12) NOT NULL,"\
"INDEX uid_ind (uid),"\
"INDEX nombre_ind (nombre),"\
"INDEX rango_ind (rango),"\
"CONSTRAINT pk_uid_inmortales PRIMARY KEY (uid),"\
"CONSTRAINT fk_nombre_inmortales FOREIGN KEY (nombre) REFERENCES jugadores(nombre) ON DELETE CASCADE,"\
"CONSTRAINT fk_rango_inmortales FOREIGN KEY (rango) REFERENCES rangos(rango) ON DELETE CASCADE"\
") TYPE=InnoDB;"
#define CREA_MIEMBROS "CREATE TABLE miembros ("\
"nombre VARCHAR(12) NOT NULL,"\
"grupo VARCHAR(12) NOT NULL,"\
"INDEX nombre_ind(nombre),"\
"INDEX grupo_ind(grupo),"\
"CONSTRAINT pk_nombre_grupo_miembros PRIMARY KEY (nombre, grupo),"\
"CONSTRAINT fk_nombre_miembros FOREIGN KEY (nombre) REFERENCES inmortales(nombre) ON DELETE CASCADE,"\
"CONSTRAINT fk_grupo_miembros FOREIGN KEY (grupo) REFERENCES grupos(grupo) ON DELETE CASCADE"\
") TYPE=InnoDB;"
#define CREA_CANALES "CREATE TABLE canales ("\
"cid INT NOT NULL AUTO_INCREMENT,"\
"canal VARCHAR(12) NOT NULL UNIQUE,"\
"tipo INT NOT NULL,"\
"CONSTRAINT pk_canales PRIMARY KEY (cid)"\
") TYPE=InnoDB;"
#define CREA_MAP ([ "jugadores":CREA_JUGADORES, "grupos":CREA_GRUPOS, "rangos":CREA_RANGOS, "inmortales":CREA_INMORTALES, "miembros":CREA_MIEMBROS, "canales":CREA_CANALES ])
#define CREA_ORDEN ({ "jugadores", "grupos", "rangos", "inmortales", "miembros", "canales" });
#endif /* SQL_H */
|
C
|
#ifndef KRR_util_h_
#define KRR_util_h_
#include <SDL2/SDL_rwops.h>
#ifdef __cplusplus
extern "C" {
#endif
///
/// Print callstack up to this point of calling this function.
/// Stack size is 32.
///
/// Only supported on Linux, Unix, and macOS. It will be no-op for Windows and other platforms.
///
extern void KRR_util_print_callstack();
/*
* Equivalent to fgets() but operate on string instead of file.
*
* It will read string up to `dst_size` or stop reading whenever find newline character, then return string so far as read via `dist_str`.
*
* It will finally stop whenever it has read all the bytes from the `input_str`.
*
* Be careful if you dynamically allocate input string, you have to save original pointer somewhere in order to free it later. Calling this function will modify input string's starting location thus you cannot use it to free any further unless you save original pointer to do so.
*
* \param dst_str destination string as output
* \param dst_size up to number of bytes to read for destination string
* \param input_str input string to read. When this function returns, this input string's location will be updated to point to the
* \return string as read starting from the current location of input string to newline character but with maximum limit up to `dst_size`. It returns NULL when all of `input_str`'s bytes has been read and no more string can be found.
*/
extern char* KRR_util_sgets(char* dst_str, int dst_size, char** input_str);
/*
* Read line from SDL_RWops and output to `dst_str` upto `dst_size`. Its reading location will be updated thus this function can be called repetitively to get each line from SDL_RWops.
*
* Note that output string doesn't include newline character.
*
* \param file input SDL_RWops
* \param dst_str destination string to get a line of text to
* \param dst_size maximum size in bytes to read into output string.
* \return pointer to destination string, this just return `dst_str`.
*/
extern char* KRR_util_rwopsgets(SDL_RWops* file, char* dst_str, int dst_size);
#ifdef __cplusplus
}
#endif
#endif
|
C
|
#include <stdio.h>
void add(char*, char*);
void add1(char*, char*);
void add2(char*,char*);
int main(int argc, char *argv[])
{
char inp1[20], inp2[20];
printf("\nEnter the 1st number :");
scanf("%s", inp1);
printf("\nEnter the 2nd number :");
scanf("%s", inp2);
printf("\n");
add2(inp1, inp2);
}
void add2(char inp1[20],char inp2[20])
{
char res[10];
int i=0,i2=0,j=0,j2=0,temp,n1,n2,ind=0,carry;
while(inp1[i]!='\0'&&inp2[i]!='\0')
{
n1=inp1[i]-'0';
n2=inp2[i]-'0';
temp=n1+n2;
i++;
//printf("\n temp %d",temp);
if(temp<=9)
{
res[ind]=temp+'0';
ind++;
j=i;
}
printf("\ntemp %d",temp);
if(temp>9)
{
res[i]=temp%10;
carry=temp/10;
while(j<i)
{
res[j]='0';
j++;
}
res[j]=carry+'0';
//break;
}
}
res[j]='\0';
printf("\nResult : ");
for(i=0;res[i]!='\0';i++)
{
printf("%c",res[i]);
}
}
void add(char inp1[20], char inp2[20])
{
char res[30];
int temp,len1,len2,ind=0,i,n1,n2,j;
int carry = 0;
for (len1 = 0; inp1[len1] != '\0'; len1++);
for (len2 = 0; inp2[len2] != '\0'; len2++);
while (len1 >= 0 || len2 >= 0)
{
//if (len1 >= 0 && len2 >= 0)
if (len1 >= 0)
n1 = inp1[len1] - '0';
else
n1 = 0;
if (len2 >= 0)
n2 = inp2[len2] - '0';
else
n2 = 0;
// temp = (inp1[len1] - '0') + (inp2[len2] - '0') + carry;
temp = n1 + n2 + carry;
carry = 0;
if (temp>9)
{
//printf("\nTemp %d", temp);
carry = temp / 10;
//printf("\ncarry %d", carry);
res[ind] = (temp % 10);
// ind++;
}
else
{
//printf("\nTemp %d", temp);
res[ind] = temp;
}
// if(len1!=0)
len1--;
//if(len2!=0)
len2--;
ind++;
//printf("\n len1 %d \n len2 %d",len1,len2);
//printf("\ninp1[len1]=%d",inp1[len1]-'0');
//printf("\ninp2[len2]=%d",inp2[len2]-'0');
}
res[ind+1] = '\0';
for (j = 0; res[j] != '\0'; j++);
int d;
i = 0;
printf("\nRes : ");
//for (i = 0; res[i] != '\0'; i++)
for (i = ind-1; i >= 1;i--)
printf("%d", res[i]);
printf("\n");
}
void add1(char inp1[20], char inp2[20])
{
int n1 = 0, n2 = 0, res, i;
for (i = 0; inp1[i] != '\0'; i++)
n1 = n1 * 10 + inp1[i] - '0';
for (i = 0; inp2[i] != '\0'; i++)
n2 = n2 * 10 + inp2[i] - '0';
printf("\nnum1 = %d \n num 2 = %d ", n1, n2);
res = n1 + n2;
printf("\nSum is %d", res);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <windows.h>
int main(int argc, char const *argv[]) {
clock_t t_start, t_end;
t_start = clock();
int second = 0, minite = 0;
while (1) {
int s, m;
t_end = clock();
s = (t_end - t_start) / CLOCKS_PER_SEC;
m = s / 60;
s %= 60;
if (s != second) {
second = s;
minite = m;
system("cls");
// 输出,可以自定义样式,但是受限于窗口大小,自行调整
printf("duration=====> %02d:%02d\n", m, s);
// 假睡眠过渡,减少cpu消耗
Sleep(997);
}
if ((m - 1 == 0) && (s - 0 == 0)) {
printf("计时结束\n");
return 0;
}
}
return 0;
}
|
C
|
#include"stack.h"
void greate_memory(int **p)
{
*p= malloc(SIZE*sizeof(int));
if(NULL==*p)
{
printf("sorry malloc fail\n");
exit -1;
}
}
void init_stack(pStack pS)
{
greate_memory(&pS->bottom);
pS->top=0;
}
int push(pStack ps,int mod)
{
if(ps->top==50)
{
printf("FULL\n");
return FULL;
}
ps->bottom[ps->top] = mod;
ps->top++;
return SUC;
}
int pop(pStack ps,int *pop_data)
{
if(ps->top==0)
{
return EMPTY;
}
ps->top--;
*pop_data=ps->bottom[ps->top];
return SUC;
}
|
C
|
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct linkedlist *initialize();
void add(struct linkedlist* list, int value);
void print_list(struct linkedlist *list);
struct node{
int data;
struct node *next;
};
struct linkedlist{
int size;
struct node *head;
};
struct linkedlist *initialize(){
struct linkedlist* list = malloc(sizeof(struct linkedlist));
list->size = 0;
list->head = NULL;
return list;
}
void add(struct linkedlist* list, int value)
{
//Code to add an element to a LinkedList
}
void print_list(struct linkedlist *list)
{
//Code to print a LinkedList
}
void print_reverse(struct linkedlist *list)
{
//Code to print a LinkedList in reverse
}
int main()
{
}
|
C
|
#include<stdio.h>
int sum(int num);
int main(int argc, char const *argv[])
{
int n, result;
printf("Enter range of how many natural number sum you want");
scanf("%d",&n);
result=sum(n);
printf("sum=%d",result);
return 0;
}
int sum(int n)
{
if(n!=0)
return (n+ sum(n-1));
else
return n;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "LinkedList.h"
#include "Controller.h"
#include "Employee.h"
#include "menu.h"
/****************************************************
Menu:
1. Cargar los datos de los empleados desde el archivo data.csv (modo texto).
2. Cargar los datos de los empleados desde el archivo data.bin (modo binario).
3. Alta de empleado
4. Modificar datos de empleado
5. Baja de empleado
6. Listar empleados
7. Ordenar empleados
8. Guardar los datos de los empleados en el archivo data.csv (modo texto).
9. Guardar los datos de los empleados en el archivo data.bin (modo binario).
10. Salir
*****************************************************/
int main()
{
char seguir='s';
int flagLoadBin=0;
int flagLoadText=0;
int flagAdd=0;
LinkedList* listaEmpleados = ll_newLinkedList();
do
{
system("cls");
switch(menu())
{
case 1: //CARGA DE ARCHIVO DE TEXTO
system("cls");
if(!controller_loadFromText("data.csv",listaEmpleados))
{
printf("Archivo de texto cargado con exito\n");
flagLoadText=1;
}
system("pause");
break;
case 2://CARGA DE ARCHIVO BINARIO
system("cls");
if(!controller_loadFromBinary("data.bin",listaEmpleados))
{
printf("Archivo binario cargado con exito!\n");
flagLoadBin=1;
}
system("pause");
break;
case 3://ALTA DE EMPLEADO
system("cls");
if(!controller_addEmployee(listaEmpleados))
{
printf("Empleado cargado con exito!\n");
flagAdd=1;
}
system("pause");
break;
case 4://EDICION DE EMPLEADOS
system("cls");
if(flagAdd || flagLoadBin || flagLoadText)
{
if(!controller_editEmployee(listaEmpleados))
{
printf("Empleado editado con exito!\n");
}
}
else
{
printf("Cargar un empleado si desea editar\n");
}
system("pause");
break;
case 5://REMOVER EMPLEADO
system("cls");
if(flagAdd || flagLoadBin || flagLoadText)
{
if(!controller_removeEmployee(listaEmpleados))
{
printf("Empleado eliminado con exito!\n");
}
}else
{
printf("Cargar un empleado si desea remover\n");
}
system("pause");
break;
case 6://LISTA DE EMPLEADOS
system("cls");
if(flagAdd || flagLoadBin || flagLoadText)
{
controller_ListEmployee(listaEmpleados);
}else
{
printf("Cargar un empleado si desea listar\n");
}
system("pause");
break;
case 7://ORDENAMIENTO DE EMPLEADOS
system("cls");
if(flagAdd || flagLoadBin || flagLoadText)
{
if(!controller_sortEmployee(listaEmpleados))
{
printf("ordenamiento exitoso!\n");
}
}else
{
printf("Cargar un empleado si desea ordenar\n");
}
system("pause");
break;
case 8://SALVAR COMO TEXTO
system("cls");
if(flagAdd || flagLoadBin || flagLoadText)
{
if(!controller_saveAsText("data.csv",listaEmpleados))
{
printf("Guardado como texto con exito!\n");
}
}else
{
printf("Cargar empleados si desea guardar en archivo csv\n");
}
system("pause");
break;
case 9://SALVAR COMO BINARIO
system("cls");
if(flagAdd || flagLoadBin || flagLoadText)
{
if(!controller_saveAsBinary("data.bin",listaEmpleados))
{
printf("Guardado como binario con exito!\n");
}
}else
{
printf("Cargar empleados si desea guardar en archivo binario\n");
}
system("pause");
break;
case 10: //SALIR
system("cls");
seguir='n';
break;
}
}
while(seguir == 's');
return 0;
}
|
C
|
#include "statistic_descriptive.h"
// Variation
/*
* Variation = xi - Av
*
*/
void variation (double *vector_data, double *vector_freq, double *vector_variation, int lenght) { // Require average_ari_pond
int i; // For Loop Variable
double Av; // Average Of Vector_Data's Elements
Av = average_ari_pond (vector_data,vector_freq,lenght);
#pragma omp parallel for private(i)
for (i = 0; i < lenght; i++) {
vector_variation[i] = vector_data[i] - Av;
}
}
// Variance
/*
* Variance = sum(variation(i)*variation(i)*freq(i))
*
*/
double variance (double *vector_data, double *vector_freq, int lenght) { // Require vector_vector_mult && vector_el_sum && variation
double vector_variation[lenght]; // variation[i]
double vector_variation_quad[lenght]; // variation[i]*variation[i]
double vector_result[lenght]; // variation[i]*variation[i]*freq[i]
double result;
variation (vector_data,vector_freq,vector_variation,lenght); // Vector Variation Calculation
vector_vector_mult (vector_variation,vector_variation,vector_variation_quad,lenght); // Vector Variation*Variation Calculation
vector_vector_mult (vector_variation_quad,vector_freq,vector_result,lenght); // Vector Variation*Variation*Freq Calculation
result = vector_el_sum (vector_result,lenght); // Sum Vector Result Elements
return result;
}
// Standard Deviation
/*
* Sd = sqrt(variance)
*
*/
double standard_deviation (double *vector_data, double *vector_freq, int lenght) { // Require variance
double result;
result = sqrt (variance (vector_data, vector_freq, lenght));
return result;
}
// Absolute Mean Value
/*
* Abs_Mean_VAL = sum(abs(x[i] - X_av)
*
*/
double mean_abs (double *vector_data, double *vector_freq, int lenght) {
double average = 0.0;
double result = 0.0;
int i = 0;
average = average_ari (vector_data, lenght);
#pragma omp parallel for private(i) reduction(+: result)
for (i = 0; i < lenght; i++) {
result += abs(vector_data[i] - average);
}
return result;
}
// Coefficient Of Variation
/*
* cv = standard_deviation/average_pond
*
*/
double cv (double *vector_data, double *vector_freq, int lenght) { // Require variance
double result;
double stand_deviation;
double avg_pond;
// Standard Deviation And Ponderate Average Calculation
#pragma omp parallel sections
{
// Standard Deviation
#pragma omp section
{
stand_deviation = standard_deviation (vector_data, vector_freq, lenght);
}
// Ponderate Average
#pragma omp section
{
avg_pond = average_ari_pond (vector_data, vector_freq, lenght);
}
}
result = stand_deviation / avg_pond;
return result;
}
|
C
|
/*
* 合并两个有序的数组,使之成位一个有序的数组
*/
#include <stdio.h>
void merge_array(int *a, size_t a_len, int *b, size_t b_len, int *c)
{
while ((a_len != 0) && (b_len != 0))
{
if (*a < *b)
{
*c++ = *a++;
a_len--;
}
else
{
*c++ = *b++;
b_len--;
}
if (a_len == 0 && b_len != 0)
{
while (b_len)
{
*c++ = *b++;
b_len--;
}
}
if (b_len == 0 && a_len != 0)
{
while (a_len)
{
*c++ = *a++;
a_len--;
}
}
}
}
int main(int argc, char **argv)
{
int a[] = {12, 56, 465};
int b[] = {1, 13, 45};
int c[6];
int i;
merge_array(a, 3, b, 3, c);
printf("c = a + c\n");
for (i = 0; i < 6; i++)
{
printf("%d\t", c[i]);
}
printf("\n");
return 0;
}
|
C
|
#include <stdio.h>
int main(void){
int a,i,b=1;
scanf("%d",&a);
for(i=1;i<=a;i++){
b*=i;
}
printf("%d ",b);
return 0;
}
|
C
|
#include <time.h>
#include <stdio.h>
int main()
{
clock_t t1, t2;
t1 = clock();
int i;
for(i=0; i<1000000; i++)
printf("");
t2 = clock();
double f = (double)(t2 - t1);
printf("%lf\n", f);
return 0;
}
|
C
|
/*
* ڰ 2014 ܿб
* Ǵ 2009190021 UIC а
*
* 2015 1 3 Ͽ Visual Studio 2010 ۼϿϴ.
* α ΰ : X, Y (Y 0 ƴ) a, s, m, d ϳ ڸ argument
* double · ݴϴ.
* ڰ a Է X + Y ,
* ڰ s Է X - Y ,
* ڰ m Է X * Y ,
* ڰ d Է X / Y ְ ˴ϴ.
*
* Է ÿ Բ α ˴ϴ.
* X, Y ƴ Է α ˴ϴ.
*/
#include <stdio.h> // ̺귯 Լ Ÿ
#include <math.h>
double add (int x, int y);
double subtract (int x, int y);
double multiply (int x, int y);
double divide (int x, int y);
double print_result (double z);
int main(void) // Լ
{
//
int x, y, invalid=0;
char comp;
double result;
// Է
printf("You need to type two integers X, Y and a character\n"
"First, decide which operation to conduct by choosing one of the following characters:\n"
"If you type \"a\", then we will compute X + Y \n"
"If you type \"s\", then we will compute X - Y \n"
"If you type \"m\", then we will compute X * Y \n"
"If you type \"d\", then we will compute X / Y \n");
printf("What is your choice?> ");
scanf("%c", &comp);
printf("\nNow, give us the first integer X> ");
scanf("%d", &x);
if (comp=='d'){ // ڿ d ִ 0 ƴ Էϵ ȳ
printf("Type the second \"NONZERO\" integer Y> ");
}
else{
printf("Type the second integer Y> ");
}
scanf("%d", &y);
// Է ڷḦ Լ ̿
if (comp=='a'){
result=add(x,y);
}
else if (comp=='s'){
result=subtract(x,y);
}
else if (comp=='m'){
result=multiply(x,y);
}
else if (comp=='d'){
if(y==0){
printf("\nIf you choose to divide, Y must be a nonzero integer"); // ڰ 0
invalid=1; // invalid Ͽ Ʒ Է° ߸Ǿٴ Բ
}
else{
result=divide(x,y); // ڰ 0 ƴ
}
}
else{
invalid=1;
}
if (invalid==1){ // Էµ ڰ a, s, m, d ϳ ƴ ,
printf("\nYou did not follow the input directions properly,\n"
"Please run the program again.\n"); // Լ
}
else{
print_result(result); // Էµ ڿ ̻ Լ ̿
printf("\n\nThank you for using this program.\nSee you next time ^.^\n\n"); // Լ
}
// Լ
return 0;
}
// ʿ Լ
double add (int x, int y){
return (double) (x+y);
}
double subtract (int x, int y){
return (double) (x-y);
}
double multiply (int x, int y){
return (double) (x*y);
}
double divide (int x, int y){
return (double)x / (double)y;
}
double print_result (double z){
printf("\n>>>> The result of the operation is: %.4lf", z); // Լ Ǹ
return 0.0; // 0.0 ϰ ȭ鿡 ǥõ ̸, ܼ ߱
}
|
C
|
#include<stdio.h>
#define SIZE 50
void string(char str[]);
int sum_number(int a, int b);
int ymnozh(int k,int l);
int cube(int x);
int main()
{
int res_sum,a,b;
int res_ymnozh;
int k;
int l;
int cu;
int x;
printf("You can add two numbers and our function will count sum value\n");
scanf("%d%d", &a, &b);
char str[SIZE]="I am function string\n";
string(str);
res_sum = sum_number(a,b);
fprintf(stdout, "Result sum_number = %d\n",res_sum);
printf("You can add two numbers and our function will multiply your value\n");
scanf("%d%d",&k,&l);
res_ymnozh = ymnozh(k,l);
fprintf(stdout,"Result multiply function - %d\n",res_ymnozh);
scanf("%d",&x);
cu = cube(x);
fprintf(stdout, "Result cube function - %d\n",cu);
}
void string(char str[])
{
fprintf(stdout,"Func string: %s",str);
}
int sum_number(int a, int b)
{
return a + b;
}
int ymnozh(int k, int l)
{
return k * l;
}
int cube(int x)
{
return (x * x) * x;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <netdb.h> // for getnameinfo()
// Usual socket headers
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "response.h"
#include "request.h"
#define IP_ADDR "0.0.0.0"
#define PORT_ADDR 1234
#define SIZE 1024
#define BACKLOG 10 // Passed to listen()
#define COLOR_GREEN "\033[0;32m"
#define COLOR_RED "\033[0;31m"
#define COLOR_RESET "\033[0m"
void report(struct sockaddr_in *serverAddress);
int main(void)
{
char response[65536];
char request[4096];
// Socket setup: creates an endpoint for communication, returns a descriptor
// -----------------------------------------------------------------------------------------------------------------
int serverSocket = socket(
AF_INET, // Domain: specifies protocol family
SOCK_STREAM, // Type: specifies communication semantics
0 // Protocol: 0 because there is a single protocol for the specified family
);
// Construct local address structure
// -----------------------------------------------------------------------------------------------------------------
struct sockaddr_in serverAddress;
serverAddress.sin_family = AF_INET;
serverAddress.sin_port = htons(1235);
serverAddress.sin_addr.s_addr = inet_addr(IP_ADDR); //htonl(INADDR_LOOPBACK);
// Bind socket to local address
// -----------------------------------------------------------------------------------------------------------------
// bind() assigns the address specified by serverAddress to the socket
// referred to by the file descriptor serverSocket.
bind(
serverSocket, // file descriptor referring to a socket
(struct sockaddr *) &serverAddress, // Address to be assigned to the socket
sizeof(serverAddress) // Size (bytes) of the address structure
);
// Mark socket to listen for incoming connections
// -----------------------------------------------------------------------------------------------------------------
int listening = listen(serverSocket, BACKLOG);
if (listening < 0) {
printf("Error: The server is not listening.\n");
return 1;
}
report(&serverAddress); // Custom report function
readImage("download.jpg",response);
int clientSocket;
ssize_t valread;
// Wait for a connection, create a connected socket if a connection is pending
// -----------------------------------------------------------------------------------------------------------------
while(1) {
clientSocket = accept(serverSocket, NULL, NULL);
valread = read(clientSocket , request, 4096);
getHead(request);
//printf("%sRequest from blabla%s\n%s\n\n",COLOR_GREEN,COLOR_RESET,request);
send(clientSocket, response, sizeof(response), 0);
close(clientSocket);
}
return 0;
}
void report(struct sockaddr_in *serverAddress)
{
char hostBuffer[INET6_ADDRSTRLEN];
char serviceBuffer[NI_MAXSERV]; // defined in `<netdb.h>`
socklen_t addr_len = sizeof(*serverAddress);
int err = getnameinfo(
(struct sockaddr *) serverAddress,
addr_len,
hostBuffer,
sizeof(hostBuffer),
serviceBuffer,
sizeof(serviceBuffer),
NI_NUMERICHOST
);
if (err != 0) {
printf("It's not working!!\n");
}
printf("\n\n\tServer listening on http://%s:%s\n", hostBuffer, serviceBuffer);
}
|
C
|
/**
* @file
* @brief servo/motor information
*/
#ifndef __SERVOS_H__
#define __SERVOS_H__
/**
* @brief choose whether to use fuzzy logic or use hardset values
*/
#define MOTORCTRL_FUZZY
/**
* @brief defines the largest value a motor can have
*
* This is the maximum value that a motor can get,
* i.e. forward*resolution.
*/
#define MOTORCTRL_MAX_SUM 1024
/**
* @brief the max percentage that the motor will be set to
*/
#define MOTORCTRL_PERC_MAX 100
/**
* @brief defines the max number of chars to use for fuzzy logic
*/
#define MOTORCTRL_MAX_RES 8
/**
* @brief minimum absolute value to send to motors
*/
#define MOTORCTRL_MIN_THESH 20
/**
* @brief how much weight is given to a single increment
* (call to forward or backward)
*/
#define MOTORCTRL_FULL_STEP (MOTORCTRL_MAX_SUM / MOTORCTRL_MAX_RES)
/**
* @brief how much weight is given for a half-increment
*/
#define MOTORCTRL_HALF_STEP (MOTORCTRL_FULL_STEP / 2)
/**
* @brief defines which system is being used currently
*/
typedef enum arm_motor_e
{
CTRL_MOTOR, //!< control the motor
CTRL_ARM, //!< control the arm
} arm_motor_e;
/**
* @brief what system is currently being controlled.
* @note internal to this file. Use associated functions
* to change this instead
*/
static arm_motor_e CURR_SYSTEM = CTRL_MOTOR;
/**
* @brief control the motor
*/
void ctrl_use_motor(void)
{
CURR_SYSTEM = CTRL_MOTOR;
}
/**
* @brief control the arm
*/
void ctrl_use_arm(void)
{
CURR_SYSTEM = CTRL_ARM;
}
/**
* @brief return which system is currently being used
*/
arm_motor_e ctrl_using_which(void)
{
return CURR_SYSTEM;
}
/**
* @brief control structure used in boolean functions
*/
typedef struct motorctrl_t
{
// motors
int motor_left; //!< left motor power
int motor_right; //!< right motor power
// servos
int servo_hand; //!< hand servo control
int servo_thumb; //!< thumb servo control
int servo_fingers; //!< finger servo control
int servo_wrist; //!< wrist servo control
int servo_shoulder; //!< shoulder servo control
int servo_5; //!< extra servo
int servo_6; //!< extra servo
} motorctrl_t;
void motorctrl_forward(int *currval);
void motorctrl_backward(int *currval);
int motorctrl_bound_value(int motor_val);
int motorctrl_motor_left(const motorctrl_t& m);
int motorctrl_motor_right(const motorctrl_t& m);
/**
* @brief initialize a motorctrl_t structure
*/
void motorctrl_init(motorctrl_t *m_ptr)
{
memset(m_ptr, 0x0, sizeof(motorctrl_t));
}
/**
* @brief updates a motorctrl_t structure with new motor magnitude specs
* @param str char array returned from a bluetooth read
* @returns
* Returns 0 on success, positive when stop signal received,
* negative on error
*/
int motorctrl_update(motorctrl_t *m_ptr, ubyte *str)
{
int index = 0;
if (NULL == m_ptr) ErrorFatal("NULL m_ptr");
motorctrl_init(m_ptr);
if (NULL == str)
return 0;
while (*str != '\0')
{
index++;
const ubyte motor_spec = *str;
if ('k' == motor_spec)
{
// stop command
return 1;
}
else if (ctrl_using_which() == CTRL_MOTOR)
{
// motor commands
if ('s' == motor_spec)
{
// switch to arm
LogMsg("--> Arm");
ctrl_use_arm();
}
else if ('t' == motor_spec)
{
}
else if ('f' == motor_spec)
{
motorctrl_forward(&(m_ptr->motor_left));
motorctrl_forward(&(m_ptr->motor_right));
}
else if ('b' == motor_spec)
{
motorctrl_backward(&m_ptr->motor_left);
motorctrl_backward(&m_ptr->motor_right);
}
else if ('l' == motor_spec)
{
//m_ptr->motor_left += 0;
motorctrl_forward(&m_ptr->motor_right);
}
else if ('r' == motor_spec)
{
motorctrl_forward(&m_ptr->motor_left);
//m_ptr->motor_right += 0;
}
}
else if (ctrl_using_which() == CTRL_ARM)
{
// arm commands
switch (motor_spec)
{
case 's':
// switch to motor
LogMsg("--> Motor");
ctrl_use_motor();
break;
case 'a':
// move hand
m_ptr->servo_hand = 100;
break;
case 'e':
// move hand
m_ptr->servo_hand = -100;
break;
case 'd':
// move wrist
m_ptr->servo_wrist = 10;
break;
case 'g':
// move wrist
m_ptr->servo_wrist = -10;
break;
}
}
str++;
}
if (0 == index)
return -1;
else
return 0;
}
/**
* @brief increment motor value. Doesn't apply bounding.
* @param currval current motor value
*/
void motorctrl_forward(int *currval)
{
*currval = *currval + MOTORCTRL_FULL_STEP;
}
/**
* @brief decrement motor value. Doesn't apply bounding.
* @param currval current motor value
*/
void motorctrl_backward(int *currval)
{
*currval = *currval - MOTORCTRL_FULL_STEP;
}
/**
* @brief ensure motor_val is between -100 and 100
*/
int motorctrl_bound_value(int motor_val)
{
#ifdef MOTORCTRL_FUZZY
// take the mean*(max%) of the motor value.
// This will produce a value between -max% .. max%
motor_val = (motor_val * MOTORCTRL_PERC_MAX) / MOTORCTRL_MAX_SUM;
#endif
// final bounding checks
if (motor_val < -MOTORCTRL_PERC_MAX)
return -MOTORCTRL_PERC_MAX;
else if (motor_val > MOTORCTRL_PERC_MAX)
return MOTORCTRL_PERC_MAX;
else
return motor_val;
}
/**
* @brief return the motor value for motorD
*/
int motorctrl_motor_left(const motorctrl_t& m)
{
return m.motor_left;
}
/**
* @brief return the motor value for motorE
*/
int motorctrl_motor_right(const motorctrl_t& m)
{
return m.motor_right;
}
#endif
|
C
|
/* 1. Prompt by using CS50 library fx: get_int()
2. Validate that User Input is bw 0-23 by using a do-while loop
3. Draw the half pyramid.*/
#include <cs50.h>
#include <stdio.h>
int main(void)
{
int h = 0;
do
{
printf("Height (1-23): ");
h = get_int();
if (h == 0)
{
exit(0);
}
}
while (h < 1 || h > 23);
int max = h + 1;
// outer loop to iterate through rows, printing a new line on each iteration
for (int i = 2; i <= max; i++)
{
int blanks = max - i;
// loop to output spaces for each row
for (int j = 0; j < blanks; j++)
{
printf(" ");
}
// loop to output hashes for each row
for (int k = 0; k < i; k++)
{
printf("#");
}
printf("\n");
}
}
|
C
|
#include "../../Permutation/ascon.h"
#include "../../kat.h"
#include "../crypto_aead.h"
#define RATE (64 / 8)
#define PA_ROUNDS 12
#define PB_ROUNDS 6
#define IV \
((u64)(8 * (CRYPTO_KEYBYTES)) << 56 | (u64)(8 * (RATE)) << 48 | \
(u64)(PA_ROUNDS) << 40 | (u64)(PB_ROUNDS) << 32)
#define P12(s) (ascon_inlined((s), 0xf0))
#define P6(s) (ascon_inlined((s), 0x96))
inline static void __attribute__((always_inline))
sbox(uint32_t *s0, uint32_t *s1, uint32_t *s2, uint32_t *s3, uint32_t *s4,
uint32_t *r0) {
uint32_t t0, t1, t2;
t0 = *s1 ^ *s2;
t1 = *s0 ^ *s4;
t2 = *s3 ^ *s4;
*s4 = ((~*s4) | *s3) ^ t0;
*s3 = ((*s3 ^ *s1) | t0) ^ t1;
*s2 = ((*s2 ^ t1) | *s1) ^ t2;
*s1 = (*s1 & ~t1) ^ t2;
*s0 = *s0 | t2;
*r0 = *s0 ^ t0;
};
inline static void __attribute__((always_inline))
xorror(uint32_t *dl, uint32_t *dh, const uint32_t *sl, const uint32_t *sh,
const uint32_t *sl0, const uint32_t *sh0, const int r0,
const uint32_t *sl1, const uint32_t *sh1, const int r1) {
uint32_t t0, t1;
t0 = *sl0 << (32 - r0);
t0 ^= *sh0 >> r0;
t0 ^= *sl1 << (32 - r1);
t0 ^= *sh1 >> r1;
t1 = *sh0 << (32 - r0);
t1 ^= *sl0 >> r0;
t1 ^= *sh1 << (32 - r1);
t1 ^= *sl1 >> r1;
*dl = *sl ^ t1;
*dh = *sh ^ t0;
}
inline static void __attribute__((always_inline))
ascon_inlined(state *p, int round_constant) {
uint32_t x0, x1, x2, x3, x4;
uint32_t y0, y1, y2, y3, y4;
uint32_t t3, t4;
uint32_t *state_32 = (uint32_t *)p;
// x0-x4 lower halves of state
// y0-y4 upper halves of state
x0 = state_32[0];
y0 = state_32[1];
x1 = state_32[2];
y1 = state_32[3];
x2 = state_32[4];
y2 = state_32[5];
x3 = state_32[6];
y3 = state_32[7];
x4 = state_32[8];
y4 = state_32[9];
do {
// Addition of round constant
x2 ^= round_constant;
// Substitution layer
sbox(&x0, &x1, &x2, &x3, &x4, &t3);
sbox(&y0, &y1, &y2, &y3, &y4, &t4);
// Linear diffusion layer
xorror(&x0, &y0, &x2, &y2, &x2, &y2, 19, &x2, &y2, 28);
xorror(&x2, &y2, &x4, &y4, &x4, &y4, 1, &x4, &y4, 6);
xorror(&x4, &y4, &x1, &y1, &x1, &y1, 7, &y1, &x1, 9);
xorror(&x1, &y1, &x3, &y3, &y3, &x3, 29, &y3, &x3, 7);
xorror(&x3, &y3, &t3, &t4, &t3, &t4, 10, &t3, &t4, 17);
// Compute next round constant
round_constant -= 15;
} while (60 != round_constant);
state_32[0] = x0;
state_32[1] = y0;
state_32[2] = x1;
state_32[3] = y1;
state_32[4] = x2;
state_32[5] = y2;
state_32[6] = x3;
state_32[7] = y3;
state_32[8] = x4;
state_32[9] = y4;
};
int crypto_aead_encrypt_ref_c(unsigned char *c, unsigned long long *clen,
const unsigned char *m, unsigned long long mlen,
const unsigned char *ad, unsigned long long adlen,
const unsigned char *nsec,
const unsigned char *npub,
const unsigned char *k) {
const u64 K0 = BYTES_TO_U64(k, 8);
const u64 K1 = BYTES_TO_U64(k + 8, 8);
const u64 N0 = BYTES_TO_U64(npub, 8);
const u64 N1 = BYTES_TO_U64(npub + 8, 8);
state s;
(void)nsec;
// set ciphertext size
*clen = mlen + CRYPTO_ABYTES;
// initialization
s.x0 = IV;
s.x1 = K0;
s.x2 = K1;
s.x3 = N0;
s.x4 = N1;
P12(&s);
s.x3 ^= K0;
s.x4 ^= K1;
// process associated data
if (adlen) {
while (adlen >= RATE) {
s.x0 ^= BYTES_TO_U64(ad, 8);
P6(&s);
adlen -= RATE;
ad += RATE;
}
s.x0 ^= BYTES_TO_U64(ad, adlen);
s.x0 ^= 0x80ull << (56 - 8 * adlen);
P6(&s);
}
s.x4 ^= 1;
// process plaintext
while (mlen >= RATE) {
s.x0 ^= BYTES_TO_U64(m, 8);
U64_TO_BYTES(c, s.x0, 8);
P6(&s);
mlen -= RATE;
m += RATE;
c += RATE;
}
s.x0 ^= BYTES_TO_U64(m, mlen);
s.x0 ^= 0x80ull << (56 - 8 * mlen);
U64_TO_BYTES(c, s.x0, mlen);
c += mlen;
// finalization
s.x1 ^= K0;
s.x2 ^= K1;
P12(&s);
s.x3 ^= K0;
s.x4 ^= K1;
// set tag
U64_TO_BYTES(c, s.x3, 8);
U64_TO_BYTES(c + 8, s.x4, 8);
return 0;
}
int crypto_aead_decrypt_ref_c(unsigned char *m, unsigned long long *mlen,
unsigned char *nsec, const unsigned char *c,
unsigned long long clen, const unsigned char *ad,
unsigned long long adlen,
const unsigned char *npub,
const unsigned char *k) {
if (clen < CRYPTO_ABYTES) {
*mlen = 0;
return -1;
}
const u64 K0 = BYTES_TO_U64(k, 8);
const u64 K1 = BYTES_TO_U64(k + 8, 8);
const u64 N0 = BYTES_TO_U64(npub, 8);
const u64 N1 = BYTES_TO_U64(npub + 8, 8);
state s;
u64 c0;
(void)nsec;
// set plaintext size
*mlen = clen - CRYPTO_ABYTES;
// initialization
s.x0 = IV;
s.x1 = K0;
s.x2 = K1;
s.x3 = N0;
s.x4 = N1;
P12(&s);
s.x3 ^= K0;
s.x4 ^= K1;
// process associated data
if (adlen) {
while (adlen >= RATE) {
s.x0 ^= BYTES_TO_U64(ad, 8);
P6(&s);
adlen -= RATE;
ad += RATE;
}
s.x0 ^= BYTES_TO_U64(ad, adlen);
s.x0 ^= 0x80ull << (56 - 8 * adlen);
P6(&s);
}
s.x4 ^= 1;
// process plaintext
clen -= CRYPTO_ABYTES;
while (clen >= RATE) {
c0 = BYTES_TO_U64(c, 8);
U64_TO_BYTES(m, s.x0 ^ c0, 8);
s.x0 = c0;
P6(&s);
clen -= RATE;
m += RATE;
c += RATE;
}
c0 = BYTES_TO_U64(c, clen);
U64_TO_BYTES(m, s.x0 ^ c0, clen);
s.x0 &= ~BYTE_MASK(clen);
s.x0 |= c0;
s.x0 ^= 0x80ull << (56 - 8 * clen);
c += clen;
// finalization
s.x1 ^= K0;
s.x2 ^= K1;
P12(&s);
s.x3 ^= K0;
s.x4 ^= K1;
// verify tag (should be constant time, check compiler output)
if (((s.x3 ^ BYTES_TO_U64(c, 8)) | (s.x4 ^ BYTES_TO_U64(c + 8, 8))) != 0) {
*mlen = 0;
return -1;
}
return 0;
}
|
C
|
/*
\file classic_mode.c
\brief This source file contains the implementation for the frequency guessing game.
\authors: César Villarreal Hernández, ie707560
Luís Fernando Rodríguez Gutiérrez, ie705694
\date 03/05/2019
*/
#include "classic_mode.h"
static uint8_t buffer_sequence[BUFFER_SIZE];
static boolean_t sequence_complete_g;
static uint8_t sequence_number;
static boolean_t timeout_status_flag;
static NoteBuffer_t current_state;
static volatile uint8_t seconds_g;
static volatile uint8_t time_g;
static const sequence_map_t sequence_map[SEQUENCE_SIZE] =
{
{SEQUENCE_ZERO, {C, D, E, G, A}},
{SEQUENCE_ONE, {D, G, A, C, C}},
{SEQUENCE_TWO, {A, G, B, C, D}},
{SEQUENCE_THREE, {D, G, D, C, A}},
{SEQUENCE_FOUR, {A, B, A, B, C}},
{SEQUENCE_FIVE, {D, B, E, G, A}},
{SEQUENCE_SIX, {A, D, A, G, A}},
{SEQUENCE_SEVEN, {C, A, G, A, D}}
};
static const FSM_SS_t FSM_Buffer[BUFFER_SIZE]=
{
{&buffer_sequence[ZERO], {buffer_S2, buffer_S3, buffer_S4, buffer_S5, buffer_S1}},
{&buffer_sequence[ONE], {buffer_S3, buffer_S4, buffer_S5, buffer_S1, buffer_S2}},
{&buffer_sequence[TWO], {buffer_S4, buffer_S5, buffer_S1, buffer_S2, buffer_S3}},
{&buffer_sequence[THREE], {buffer_S5, buffer_S1, buffer_S2, buffer_S3, buffer_S4}},
{&buffer_sequence[FOUR], {buffer_S1, buffer_S2, buffer_S3, buffer_S4, buffer_S5}}
};
void CM_generate_sequence_buffer(void)
{
/* get random sequence number (0-8)*/
sequence_number = FTM_get_counter_reg();
/* set that the sequence is not complete yet*/
sequence_complete_g = FALSE;
/* Update current global buffer */
CM_get_sequence(sequence_number);
}
void CM_get_sequence(uint8_t sequence_index)
{
uint8_t i;
for(i = ZERO; BUFFER_SIZE > i ; i++)
{
/* update buffer sequence to global buffer */
buffer_sequence[i] = sequence_map[sequence_index].sequence_buffer[i];
}
/* Displays on LCD screen corresponding note in music pentagram */
LCD_set_pentagram_sequence(sequence_number, buffer_S1);
}
void CM_handle_time_interrupt(void)
{
boolean_t victory_flag; //this flag indicates if the user has won or lost the game
boolean_t note_found_flag; //this flag indicates if a note has been found
/* Sets current state corresponding buffer value to the frequency converter module */
LM2907_update_current_note(*FSM_Buffer[current_state].key_number);
/* get note found flag status */
note_found_flag = LM2907_get_note_found_flag();
if(note_found_flag)
{
/* send victory message to SPI */
terminal_correct_msg();
/* Displays on LCD screen corresponding note in music pentagram */
LCD_set_pentagram_sequence(sequence_number, *FSM_Buffer[current_state].key_number);
/* get game's next state status */
current_state = FSM_Buffer[current_state].next[ZERO];
/* reset seconds */
seconds_g = ZERO;
/* verify if the user has completed all the sequence */
if(current_state == buffer_S1)
{
/* indicate that the user has won */
victory_flag = TRUE;
}
else
{
/* indicate that the user has not won yet */
victory_flag = FALSE;
}
}
else
{
/* indicate that the user has lost */
victory_flag = FALSE;
}
if((TRUE == victory_flag) && (FALSE == timeout_status_flag))
{
/* send victory message to SPI */
terminal_victory_msg();
/* Disable PIT for adc sampling @ 2kHz */
PIT_disable_interrupt(PIT_2);
/* Disable PIT for time interrupt handler */
PIT_disable_interrupt(PIT_3);
/* Capture user initials */
terminal_enter_your_initials();
/* Store the user's time score */
system_user_record_capture(time_g);
}
else if((FALSE == victory_flag) && (TRUE == timeout_status_flag))
{
/* send losing message to SPI */
terminal_game_over_msg();
/* start PIT for adc sampling @ 2kHz */
PIT_disable_interrupt(PIT_2);
/* start pit for time interrupt handler */
PIT_disable_interrupt(PIT_3);
GPIO_set_playerboard_flag();
terminal_enter_your_initials();
system_user_record_capture(time_g);
}
else
{
/* increase current seconds and total time */
CM_increase_time();
/* Verify if a time out has ocurred */
CM_update_timeout_status();
}
}
void CM_update_timeout_status(void)
{
/* Verify if the current seconds has reached the time limit */
if(TIME_LIMIT == seconds_g)
{
/* indicate time out if it reached its limit */
timeout_status_flag = TRUE;
}
else
{
/* indicate time has not run out */
timeout_status_flag = FALSE;
}
}
uint8_t CM_get_time_g(void)
{
/* return in total time count */
return time_g;
}
void CM_reset_game(void)
{
uint8_t i;
/* restart seconds count */
seconds_g = ZERO;
/* restart in total time count */
time_g = ZERO;
/* restart timeout flag */
timeout_status_flag = FALSE;
/* Set initial state */
current_state = buffer_S1;
for(i = ZERO; BUFFER_SIZE > i; i++)
{
buffer_sequence[i] = ZERO;
}
}
void CM_increase_time(void)
{
/* total seconds */
time_g++;
/* increment sequence state seconds */
seconds_g++;
}
|
C
|
#include <stdio.h> //Biblioteca de tratamento de entrada/sada.
#include <stdlib.h> //Biblioteca de implementao de Funes para diversas operaes.
#include <locale.h> //Biblioteca que especifica constantes de acordo com a localizao especfica, como moeda, data, etc.
int main()//Incio da funo int main ().
{
setlocale(LC_ALL, "Portuguese"); //LC_ALL Faz referncia todos os aspectos de localizao.
|
C
|
/*
* Here are all the Data Structures needed in the project
* @author : Ebrahim Gomaa (HmanA6399)
*/
#pragma once
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include "safeExit.h"
/**
* Enumerating process state
*/
typedef enum pstate {
RUNNING,
STOPPED,
FINISHED,
RESUMED,
STARTED,
IDLE
} pstate;
//========= begin basic DS ===========
typedef struct Pair
{
int lower_bound;
int upper_bound;
} Pair;
Pair Pair__create(int lower_bound,int upper_bound)
{
Pair p;
p.lower_bound = lower_bound;
p.upper_bound = upper_bound;
return p;
}
void Pair__print(Pair p) {
printf("(%d, %d)\n", p.lower_bound, p.upper_bound);
}
//========= e n d basic DS ===========
//========== begin ProcessData =================
/*
* Represents Process data read from file
*/
typedef struct ProcessData
{
int pid;
int t_arrival;
int t_running;
int priority;
} ProcessData;
/**
* Creates new ProcessData pointer
*
* @param pid ID of the process
* @param t_arr Arrival Time
* @param t_run Running Time
* @param prior Priority index
* @return Pointer to the created ProcessData Instance
*/
ProcessData* ProcessData__create(int pid, int t_arr, int t_run, int prior) {
ProcessData* pd = (ProcessData*) malloc(sizeof(ProcessData));
pd->pid = pid;
pd->t_arrival = t_arr;
pd->t_running = t_run;
pd->priority = -1 * prior;
return pd;
}
/**
* Print ProcessData
*
* @param pd Pointer to ProcessData
*/
void ProcessData__print(ProcessData* pd) {
printf("%d\t%d\t%d\t%d\n", pd->pid, pd->t_arrival, pd->t_running, pd->priority);
}
/**
* Free the allocated memory for given ProcessData pointer
*
* @param pd Pointer to ProcessData memory location
*/
void ProcessData__destroy(ProcessData* pd) {
if (pd != (ProcessData*) -1 && pd != NULL)
free(pd);
}
ProcessData NULL_PROCESS_DATA() {
ProcessData pd;
pd.pid = -1;
return pd;
}
//========== end ProcessData =================
//========== begin PCB ======================
/**
* Representation of the process in the scheduler module
*/
typedef struct PCB
{
ProcessData p_data;
int t_remaining;
int t_ta; // Turn-around time
int t_w; // Waiting time
int t_st;
int actual_pid;
pstate state;
} PCB;
/**
* Creates new PCB pointer
*
* @param p_data Pointer to the process data instance
* @param t_r Initial Remaining Time
* @param t_ta Initial Turnaround time
* @param t_w Initial waiting Time
* @param state Process State
* @param actual_pid Pid of process
* @param t_st frist clock in run
* @return Pointer to the created PCB Instance
*/
PCB *PCB__create(ProcessData p_data, int t_r, int t_w, int t_ta, pstate state, int actual_pid, int t_st)
{
PCB *pcb = (PCB *)malloc(sizeof(PCB));
pcb->p_data = p_data;
pcb->t_remaining = t_r;
pcb->t_ta = t_ta;
pcb->t_w = t_w;
pcb->state = state;
pcb->t_st = t_st;
pcb->actual_pid = actual_pid;
return pcb;
}
/**
* Free the allocated memory for given PCB pointer
*
* @param pcb Pointer to PCB memory location
*/
void PCB__destroy(PCB* pcb) {
if (pcb != (PCB*) -1 && pcb != NULL)
free(pcb);
}
//======= end PCB =========================
//======= begin FIFOQueue =========================
/**
* Node of a linkedlist
*/
typedef struct Node {
void* val;
struct Node* next;
} Node;
/**
* Linkedlist-implemented FIFOQueue
*/
typedef struct FIFOQueue {
Node* head;
Node* tail;
} FIFOQueue;
/**
* Creates a new FIFOQueue. Initializes head and tail with NULL
*
* @return pointer to FIFOQueue Instance
*/
FIFOQueue* FIFOQueue__create() {
FIFOQueue* fq = (FIFOQueue*) malloc(sizeof(FIFOQueue));
fq->head = NULL;
fq->tail = NULL;
return fq;
}
/**
* Returns pointer to the value of the `head` of the Queue without removal
*
* @param fq Pointer to FIFOQueue instance to peak
* @return pointer to val
*/
void* FIFOQueue__peek(FIFOQueue* fq) {
if (fq->head == NULL) return NULL;
return fq->head->val;
}
/**
* Returns pointer to the value of the `head` of the Queue WITH removal. Update head and tail
*
* @param fq Pointer to FIFOQueue instance to peak
* @return pointer to val
*/
void* FIFOQueue__pop(FIFOQueue* fq) {
// Case 0 : Empty LL
if (fq->head == NULL) return NULL;
void* val = fq->head->val;
// Case 1 : last element
if (fq->head == fq->tail) {
free(fq->head);
fq->head = NULL;
fq->tail = NULL;
return val;
}
// Ordinary Case
Node* tmp = fq->head;
fq->head = fq->head->next;
free(tmp);
return val;
}
/**
* Create Node of val and insert it to the queue. Update tail and head
*
* @param fq Pointer to FIFOQueue instance to peak
* @param val pointer to new val
*/
void FIFOQueue__push(FIFOQueue* fq, void* val) {
Node* nd = (Node*) malloc(sizeof(Node));
nd->val = val;
nd->next = NULL;
if (fq->tail != NULL) fq->tail->next = nd;
fq->tail = nd;
// If the Queue is initially empty
if (fq->head == NULL) fq->head = nd;
}
/**
* Return whether the queue is empty
*/
ushort FIFOQueue__isEmpty(FIFOQueue* fq) {
return (fq->head == NULL);
}
//======= end FIFOQueue ===========================
//======= begin PriorityQueue =========================
static inline int parent(int i) { return i>>1; }
static inline int leftChild(int i) { return (i<<1); }
static inline int rightChild(int i) { return (i<<1)+1; }
static inline ushort isLeaf(int idx, int sz) { return ((leftChild(idx) > sz)); }
typedef struct PriorityItem {
void* val;
long long priority;
} PriorityItem;
void PriorityItem__swap(PriorityItem* pit1, PriorityItem* pit2) {
PriorityItem* pit_tmp = (PriorityItem*) malloc(sizeof(PriorityItem));
memcpy(pit_tmp, pit1, sizeof(PriorityItem));
pit1->val = pit2->val;
pit1->priority = pit2->priority;
pit2->val = pit_tmp->val;
pit2->priority = pit_tmp->priority;
free(pit_tmp);
}
typedef struct PriorityQueue {
struct PriorityItem** heap;
int size;
} PriorityQueue;
void __maxHeapify(PriorityQueue* pq, int idx) {
if (isLeaf(idx, pq->size)) return;
PriorityItem *cur = pq->heap[idx], *left = pq->heap[leftChild(idx)], *right = (rightChild(idx) <= pq->size) ? pq->heap[rightChild(idx)] : NULL;
if (
cur->priority < left->priority ||
(right != NULL && cur->priority < right->priority)
) {
// Choose the greater for swapping
PriorityItem* grtr = (right != NULL && (right->priority > left->priority)) ? right : left;
int grtr_idx = (right != NULL && (right->priority > left->priority)) ? rightChild(idx) : leftChild(idx);
// Swap and recurse
PriorityItem__swap(cur, grtr);
__maxHeapify(pq, grtr_idx);
}
}
PriorityQueue* PriorityQueue__create(int max_sz) {
PriorityQueue* pq = (PriorityQueue*) malloc(sizeof(PriorityQueue));
pq->heap = (PriorityItem**) malloc(sizeof(PriorityItem*) * (max_sz + 5));
pq->heap[0] = (PriorityItem*) malloc(sizeof(PriorityItem));
pq->heap[0]->val = NULL; pq->heap[0]->priority = __INT64_MAX__;
pq->size = 0;
return pq;
}
void ____printHeap(PriorityQueue* pq) {
printf("\n");
for (int i = 1; i <= pq->size; ++i) printf("%lld ", pq->heap[i]->priority);
printf("\n");
}
void PriorityQueue__push(PriorityQueue* pq, void* val, long long prior) {
// Create the node
PriorityItem* pit = (PriorityItem*) malloc(sizeof(PriorityItem));
pit->val = val;
pit->priority = prior;
// Place it to the end of the heap
pq->heap[++pq->size] = pit;
// Fix max heap
int cur_idx = pq->size;
while (pq->heap[cur_idx]->priority > pq->heap[parent(cur_idx)]->priority) {
PriorityItem__swap(pq->heap[cur_idx], pq->heap[parent(cur_idx)]);
cur_idx = parent(cur_idx);
}
// ____printHeap(pq);
}
void* PriorityQueue__peek(PriorityQueue* pq) {
return pq->heap[1]->val;
}
void* PriorityQueue__pop(PriorityQueue* pq) {
void* retval = pq->heap[1]->val;
// Swap head and tail
pq->heap[1]->val = pq->heap[pq->size]->val;
pq->heap[1]->priority = pq->heap[pq->size]->priority;
// Remove tail (old head)
free(pq->heap[pq->size]);
pq->size--;
// Fix heap
if (pq->size) __maxHeapify(pq, 1);
return retval;
}
ushort PriorityQueue__isEmpty(PriorityQueue* pq) {
return pq->size == 0;
}
void PriorityQueue__destroy(PriorityQueue* pq) {
for (int i = 0; i < pq->size; ++i) { free(pq->heap[i]->val); free(pq->heap[i]); }
free(pq->heap);
free(pq);
}
//======= end PriorityQueue ===========================
|
C
|
#include <msp430.h>
//By Bryan Regn
//Last updated 10/7/17
/**
* main.c
*/
int main(void)
{
WDTCTL = WDTPW | WDTHOLD; // stop watchdog timer
//needed when using msp430 processors used to reset device to previous state
unsigned int i=0;
P1SEL = 0x00; //sets P1 to GPIO
P4SEL = 0x00; //sets P4 to GPIO
P1DIR = BIT0; //P1DIR is the register used to control the direction of other pins (I/O)
//the above code sets P1.0 '1' making it an output
P4DIR = BIT7; //sets P4 to an output for the second led
P1OUT = 0x00; //initializes led
P4OUT = 0x00; //initializes led
for(;;){ //infinite loop
for(i=0; i<20000; i++);
if(i%1000==0){
P4OUT^= BIT7; // uses xor to toggle P4.7 (Second LED)
}
if(i%2000==0){
P1OUT ^= BIT0; //uses xor to toggle P1.0 (first LED)
}
}
return 0;
}
|
C
|
#include <stdio.h>
#define NUM 5
char cData[NUM] = {0x11, 0x22, 0x33, 0x44 ,0x55};
short sData[NUM] = {0x1111, 0x2222, 0x3333, 0x4444, 0x5555};
long lData[NUM] = {0x11111111, 0x22222222, 0x33333333, 0x44444444, 0x55555555};
int main(void)
{
char *pc;
short *sc;
long *lc;
pc = cData;
sc = sData;
lc = lData;
puts("<Char type>");
for (int i = 0; i < NUM; i++)
{
printf("%08X [%02X]\n", pc, *pc);
pc++;
}
puts("<Short type>");
for (int i = 0; i < NUM; i++)
{
printf("%08X [%02X]\n", sc, *sc);
sc++;
}
puts("<Long type>");
for (int i = 0; i < NUM; i++)
{
printf("%08X [%02X]\n", lc, *lc);
lc++;
}
}
|
C
|
#include <stdio.h>
#include <string.h>
#include "MEM.h"
#include "DBG.h"
#include "diksamc.h"
static DKC_Compiler *st_current_compiler;
DKC_Compiler *
dkc_get_current_compiler(void)
{
return st_current_compiler;
}
void
dkc_set_current_compiler(DKC_Compiler *compiler)
{
st_current_compiler = compiler;
}
void *
dkc_malloc(size_t size)
{
void *p;
DKC_Compiler *compiler;
compiler = dkc_get_current_compiler();
p = MEM_storage_malloc(compiler->compile_storage, size);
return p;
}
char *
dkc_strdup(char *src)
{
char *p;
DKC_Compiler *compiler;
compiler = dkc_get_current_compiler();
p = MEM_storage_malloc(compiler->compile_storage, strlen(src)+1);
strcpy(p, src);
return p;
}
TypeSpecifier *
dkc_alloc_type_specifier(DVM_BasicType type)
{
TypeSpecifier *ts = dkc_malloc(sizeof(TypeSpecifier));
ts->basic_type = type;
ts->derive = NULL;
return ts;
}
TypeDerive *
dkc_alloc_type_derive(DeriveTag derive_tag)
{
TypeDerive *td = dkc_malloc(sizeof(TypeDerive));
td->tag = derive_tag;
td->next = NULL;
return td;
}
DVM_Boolean
dkc_compare_parameter(ParameterList *param1, ParameterList *param2)
{
ParameterList *pos1;
ParameterList *pos2;
for (pos1 = param1, pos2 = param2; pos1 && pos2;
pos1 = pos1->next, pos2 = pos2->next) {
if (strcmp(pos1->name, pos2->name) != 0) {
return DVM_FALSE;
}
if (!dkc_compare_type(pos1->type, pos2->type)) {
return DVM_FALSE;
}
}
if (pos1 || pos2) {
return DVM_FALSE;
}
return DVM_TRUE;
}
DVM_Boolean
dkc_compare_type(TypeSpecifier *type1, TypeSpecifier *type2)
{
TypeDerive *d1;
TypeDerive *d2;
if (type1->basic_type != type2->basic_type) {
return DVM_FALSE;
}
for (d1 = type1->derive, d2 = type2->derive;
d1 && d2; d1 = d1->next, d2 = d2->next) {
if (d1->tag != d2->tag) {
return DVM_FALSE;
}
if (d1->tag == FUNCTION_DERIVE) {
if (!dkc_compare_parameter(d1->u.function_d.parameter_list,
d2->u.function_d.parameter_list)) {
return DVM_FALSE;
}
}
}
if (d1 || d2) {
return DVM_FALSE;
}
return DVM_TRUE;
}
FunctionDefinition *
dkc_search_function(char *name)
{
DKC_Compiler *compiler;
FunctionDefinition *pos;
compiler = dkc_get_current_compiler();
for (pos = compiler->function_list; pos; pos = pos->next) {
if (!strcmp(pos->name, name))
break;
}
return pos;
}
Declaration *
dkc_search_declaration(char *identifier, Block *block)
{
Block *b_pos;
DeclarationList *d_pos;
DKC_Compiler *compiler;
for (b_pos = block; b_pos; b_pos = b_pos->outer_block) {
for (d_pos = b_pos->declaration_list; d_pos; d_pos = d_pos->next) {
if (!strcmp(identifier, d_pos->declaration->name)) {
return d_pos->declaration;
}
}
}
compiler = dkc_get_current_compiler();
for (d_pos = compiler->declaration_list; d_pos; d_pos = d_pos->next) {
if (!strcmp(identifier, d_pos->declaration->name)) {
return d_pos->declaration;
}
}
return NULL;
}
void
dkc_vstr_clear(VString *v)
{
v->string = NULL;
}
static int
my_strlen(char *str)
{
if (str == NULL) {
return 0;
}
return strlen(str);
}
void
dkc_vstr_append_string(VString *v, char *str)
{
int new_size;
int old_len;
old_len = my_strlen(v->string);
new_size = old_len + strlen(str) + 1;
v->string = MEM_realloc(v->string, new_size);
strcpy(&v->string[old_len], str);
}
void
dkc_vstr_append_character(VString *v, int ch)
{
int current_len;
current_len = my_strlen(v->string);
v->string = MEM_realloc(v->string, current_len + 2);
v->string[current_len] = ch;
v->string[current_len+1] = '\0';
}
void
dkc_vwstr_clear(VWString *v)
{
v->string = NULL;
}
static int
my_wcslen(DVM_Char *str)
{
if (str == NULL) {
return 0;
}
return dvm_wcslen(str);
}
void
dkc_vwstr_append_string(VWString *v, DVM_Char *str)
{
int new_size;
int old_len;
old_len = my_wcslen(v->string);
new_size = sizeof(DVM_Char) * (old_len + dvm_wcslen(str) + 1);
v->string = MEM_realloc(v->string, new_size);
dvm_wcscpy(&v->string[old_len], str);
}
void
dkc_vwstr_append_character(VWString *v, int ch)
{
int current_len;
current_len = my_wcslen(v->string);
v->string = MEM_realloc(v->string,sizeof(DVM_Char) * (current_len + 2));
v->string[current_len] = ch;
v->string[current_len+1] = L'\0';
}
char *
dkc_get_basic_type_name(DVM_BasicType type)
{
switch (type) {
case DVM_BOOLEAN_TYPE:
return "boolean";
break;
case DVM_INT_TYPE:
return "int";
break;
case DVM_DOUBLE_TYPE:
return "double";
break;
case DVM_STRING_TYPE:
return "string";
break;
case DVM_NULL_TYPE:
return "null";
break;
default:
DBG_assert(0, ("bad case. type..%d\n", type));
}
return NULL;
}
char *
dkc_get_type_name(TypeSpecifier *type)
{
VString vstr;
TypeDerive *derive_pos;
dkc_vstr_clear(&vstr);
dkc_vstr_append_string(&vstr, dkc_get_basic_type_name(type->basic_type));
for (derive_pos = type->derive; derive_pos;
derive_pos = derive_pos->next) {
switch (derive_pos->tag) {
case FUNCTION_DERIVE:
DBG_assert(0, ("derive_tag..%d\n", derive_pos->tag));
break;
case ARRAY_DERIVE:
dkc_vstr_append_string(&vstr, "[]");
break;
default:
DBG_assert(0, ("derive_tag..%d\n", derive_pos->tag));
}
}
return vstr.string;
}
DVM_Char *
dkc_expression_to_string(Expression *expr)
{
char buf[LINE_BUF_SIZE];
DVM_Char wc_buf[LINE_BUF_SIZE];
int len;
DVM_Char *new_str;
if (expr->kind == BOOLEAN_EXPRESSION) {
if (expr->u.boolean_value) {
dvm_mbstowcs("true", wc_buf);
} else {
dvm_mbstowcs("false", wc_buf);
}
} else if (expr->kind == INT_EXPRESSION) {
sprintf(buf, "%d", expr->u.int_value);
dvm_mbstowcs(buf, wc_buf);
} else if (expr->kind == DOUBLE_EXPRESSION) {
sprintf(buf, "%f", expr->u.double_value);
dvm_mbstowcs(buf, wc_buf);
} else if (expr->kind == STRING_EXPRESSION) {
return expr->u.string_value;
} else {
return NULL;
}
len = dvm_wcslen(wc_buf);
new_str = MEM_malloc(sizeof(DVM_Char) * (len + 1));
dvm_wcscpy(new_str, wc_buf);
return new_str;
}
|
C
|
#include<stdio.h>
int main()
{
int ara[100];
int i,j,n,max,min;
printf("Enter the element number of array : ");
scanf("%d", &n);
printf("\nEnter the elements :\n");
for(i=0; i<n; i++)
scanf("%d", &ara[i]);
for(i=0; i<n-1; i++)
{
if(ara[i]>ara[i+1])
{
max = ara[i];
ara[i+1] = ara[i];
}
else max = ara[i+1];
}
for(i=0; i<n-1; i++)
{
if(ara[i]<ara[i+1])
{
min = ara[i];
ara[i+1] = ara[i];
}
else min = ara[i+1];
}
printf("\nLargest Number Is : %d\n",max);
printf("\nSmallest Number Is : %d\n",min);
return 0;
}
|
C
|
#include<stdio.h>
#include "conio.h"
void mergesort(int x[],int y[],int m,int n);
void accept(int x[],int n);
void print(int x[],int n);
main()
{
int m,n,a[10],i,b[10],k,c[20];
clrscr();
printf("\nHow many numbers in first array :");
scanf("%d",&m);
accept(a,m);
print(a,m);
printf("\nHow many numbers in second array :");
scanf("%d",&n);
accept(b,n);
print(b,n);
mergesort(a,b,m,n);
printf("\n");
getch();
}
void accept(int x[],int n)
{
int i;
printf("\nEnter the elements:====>\t");
for(i=0;i<n;i++)
{
scanf("%d",&x[i]);
}
}
void print(int x[],int n)
{
int i;
printf("\n\tThe elements are===>:");
for(i=0;i<n;i++)
{
printf(" %d ",x[i]);
}
printf("\n");
}
void selection(int x[],int n)
{
int indx,j,large,i;
for(i=n-1;i>0;i--)
{
large=x[0];
indx=0;
for(j=1;j<=i;j++)
if(x[j] > large)
{
large=x[j];
indx=j;
}
x[indx]=x[i];
x[i]=large;
}
}
void mergesort(int x[],int y[],int m,int n)
{
int k,c[20],j=0,t=m+n,i,temp;
for(k=0;k<m;k++)
{
c[k]=x[k];
}
for(;k<t;k++,j++)
{
c[k]=y[j];
}
printf("\nThe Elements after Merging are....\n");
print(c,t);
for(i=0;i<t;i++)
{
for(j=0;j<t;j++)
{
if(c[i]<c[j])
{
temp=c[i];
c[i]=c[j];
c[j]=temp;
}
}
}
printf("\nThe elements after sorting are:\n\n");
print(c,t);
}
|
C
|
#include "mach0.h"
int main(int argc, char **argv)
{
if (argc != 2){
printf("Usage: %s <n_iterations>\n", argv[0]);
}
int n = atoi(argv[1]);
double result = mach0(n);
printf("Result: %.17f\n", result);
}
|
C
|
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "time.h"
int main()
{
clock_t start, finish;
start = clock();
char *p = (char *)malloc(sizeof(char)*10);
char *q;
int i = 0;
strcpy(p,"hello");
for(; i<100000; i++)
{
q = (char *)malloc(sizeof(char)*4096);
q = p;
strcpy(q,"hello");
sprintf(q,"%d", i);
}
strcat(p,"world");
finish = clock();
printf("%f seconds\n", (double)(finish - start) / CLOCKS_PER_SEC);
return 0;
}
|
C
|
/*--@̺--*/
/*--2017/12/25--*/
/*--ң۰--*/
#include<stdio.h>
#include<stdlib.h>
#define MAXSIZE 100
typedef int KeyType;
typedef int FieldType;
/*--źԱ--*/
typedef struct Record
{
KeyType key;
FieldType others;
}Record;
Record* Create_Array(Record *array)
{
int i;
array = (Record*)malloc(MAXSIZE*sizeof(Record));
if(!array)
exit(-1);
for(i=0;i<=10;i++)
{
array[i].key = i*2;
}
return array;
}
/*--۰--*/
int Binary_Search(KeyType key,int last,Record *array)
{
int mid,low,high;
high = last;
low = 1;
while(low<=high)
{
mid = (low+high)/2;
if(key>array[mid].key)
low = mid + 1;
else if(key<array[mid].key)
high = mid - 1;
else
return mid;
}
return 0;
}
int main()
{
int ret;
Record *Array1;
Array1 = Create_Array(Array1);
ret = Binary_Search(14,10,Array1);
printf("۰ҽ%d\n",ret);
return 0;
}
|
C
|
#include <stdio.h>
int main() {
printf("hello, world\n");
printf("carriage return demo\n");
printf("Beethoven is my favorite composer\rMozart\n");
printf("Multiple\nlines\nwith\ncarriage\nreturn\n\r\r\r\r1\n2\n3\n4\n");
printf("%d", gety())
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "netlist.h"
#include "entree_sortie.h"
int main(int argc, char** argv){
Netlist* n = NULL;
char s1[100];
char s2[15] = ".balayAVL.int";
if ( argc != 2) {
printf ( "Erreur format: %s <NomFichier>\n", argv[0]);
return 1;
}
printf("Lecture de la Netlist en cours...\n");
n = lecture_netlist(argv[1], n);
strcpy(s1, argv[1]);
strcat(s1, s2);
printf("recherche des intersections (avec AVL) de la Netlist en cours...\n");
n = intersect_balayage_AVL(n);
printf("sauvegarde des intersections de la Netlist en cours...\n");
sauvegarde_intersection(s1, n);
printf("sauvegarde effectuée dans le fichier '%s' avec succès.\n", s1);
supprimer_netlist(n);
return 0;
}
|
C
|
#pragma once
//Enum specifying the kind of title a card has.
enum CardTitleType {
//The normal title position
NormalTitle = 1,
//The card is split an as such has the titles on the side.
SplitCardTitle = 2,
//The card is an Amonkhet split card, with one title in the regular place and one title in a split card half.
AkhSplitCardTitle = 3,
//The card has been transformed.
TransformedTitle = 4,
//The card has the design indicating a "future" card.
FutureSightTitle = 5,
//The card comes form the Amonkhet Invocations set and has the title in the regular place, written in semi-hieroglyphs.
AmonkhetInvocationsTitle = 6,
//The card is an emblem card.
Emblem = 7,
//The card is a token card.
Token = 8,
//The card is a normal transformed card, i.e the backside of the card.
Backside = 9,
//The card is a commercial card, only containing advertising.
Commercial = 10
};
|
C
|
#include "trie.h"
#include "code.h"
#include <stdio.h>
#include <stdlib.h>
// Constructor for a TrieNode ADT
//
TrieNode *trie_node_create(uint16_t code) {
TrieNode *n = malloc(sizeof(TrieNode));
if (!n) {
return NULL;
}
n->code = code;
for (int sym = 0; sym < ALPHABET; sym++) {
n->children[sym] = NULL;
}
return n;
}
// Destructor for a TrieNode
//
void trie_node_delete(TrieNode *n) {
if (n) {
free(n);
}
}
// Constructor for the root trie node of a trie
//
TrieNode *trie_create(void) {
TrieNode *root = trie_node_create(EMPTY_CODE);
if (!root) {
return NULL;
}
return root;
}
// resets a trie structure starting at the root
//
void trie_reset(TrieNode *root) {
for (int sym = 0; sym < ALPHABET; sym++) {
trie_delete(root->children[sym]);
root->children[sym] = NULL;
}
}
// Destructor for a sub-trie
//
void trie_delete(TrieNode *n) {
if (n) {
for (int sym = 0; sym < ALPHABET; sym++) {
if (n->children[sym] != NULL) {
trie_delete(n->children[sym]);
}
}
trie_node_delete(n);
}
}
// if sym is a valid ASCII character, returns a pointer to the
// Node that represents that sym
//
TrieNode *trie_step(TrieNode *n, uint8_t sym) {
return n->children[sym];
}
|
C
|
//calculates a broker's commission
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
int main()
{float commission,value;
printf("enter value of trade\n");
scanf("%f",&value);
if (value<2500.00f)
commission=30.00f+(value*.017f);
else if (value<6250.00f)
commission=56+(value*.0066f);
else if (value<20000.00f)
commission=76+(value*.0034f);
else if (value<50000.00f)
commission=100+(value*.0022f);
else if (value<500000.00f)
commission=155+(value*.0011f);
else commission=255+(value*.0009f);
if (commission<39.00f)
commission=39.00f;
printf("commission: Tk.%.2f\n",commission);
getch();
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "carta.h"
#include "cartas.h"
#include "jugador.h"
#include "jugadores.h"
#include "jugada.h"
#include "jugadas.h"
#include "partida.h"
#include "preguntas.h"
#include "colores.h"
/*
*conf==TRUE-->Muestra la carta c.
*conf==FALSE-->Muestra |UNO|.
*/
void mostrar_carta(tcarta c, int conf)
{
printf("|");
if (conf==TRUE)
{
cambiar_color_fondo(c.color);
if (c.fig<=9)
printf(" %d ", c.fig);
else if (c.fig==10)
printf("+2 ");
else if (c.fig==11)
printf(" R ");
else if (c.fig==12)
printf(" S ");
else if (c.fig==13)
{
cambiar_color_letra(BLACK);
printf(" W ");
}
else
{
cambiar_color_letra(BLACK);
printf("W+4");
}
}
else
{
cambiar_color_fondo(WHITE);
cambiar_color_letra(RED);
printf("UNO");
}
default_attributes();
}
|
C
|
#include <stdio.h>
int main()
{
int data[68][5]={0};
int n,i,j,s,d,da;
while(1)
{
printf("Enter 1 to insert sales figure\nEnter 2 to update sales figure\nEnter 3 to delete sales figure\nEnter 4 to display the data base\nEnter 5 to Close Programme\n");
scanf("%d",&n);
if(n==1||n==2)
{
if(n==1)
printf("Enter STORE NO.(1-68), DEPARTMENT NO.(1-5) and DATA in Format \" STORE_NO. DEPARTMENT_NO. DATA \" to insert sales figure DATA\n");
else
printf("Enter STORE NO.(1-68), DEPARTMENT NO.(1-5) and DATA in Format \" STORE_NO. DEPARTMENT_NO. DATA \" to update sales figure DATA\n");
scanf("%d %d %d",&s,&d,&da);
data[s-1][d-1]=da;
}
else if(n==3)
{
printf("Enter STORE NO.(1-68) and DEPARTMENT NO.(1-5) in Format \" STORE_NO. DEPARTMENT_NO.\" to delete sales figure\n");
scanf("%d %d",&s,&d);
data[s-1][d-1]=0;
}
else if(n==4)
{
printf("DEPARTMENTS ");
for(i=0;i<5;i++)
{
printf("%10d ",i+1);
}
printf("\n");
for(i=0;i<68;i++)
{
printf(" STORE %3d ",i+1);
for(j=0;j<5;j++)
{
printf("%10d ",data[i][j]);
}
printf("\n");
}
}
else if(n==5)
return 0;
else
{
printf("Choose a valid operation");
}
}
}
|
C
|
//
// problem32.c
// LeetCode
//
// Created by apoptoxin on 2018/8/5.
// Copyright © 2018年 micronil.com. All rights reserved.
//
#include "problem32.h"
#include "bool_define.h"
int longestValidParentheses(char* s) {
int length = strlen(s);
int total = 0;
int *a = malloc(sizeof(int) * length);
//用a来记录从第i个元素开始最长的有效括号长度
//a[i]就等于:
//1.如果s[i]为')',则a[i]=0
//int tmp = 0
//2.计算a[i+2]开始最长+s[i]和s[i+1],得到长度l1,然后累加上a[i+l1]得到l1;
//3.计算a[i+1]开始最长,为l2,加上s[i]和s[i+l2],结果存在l2,然后累加上a[i+l2]得到l2;
//a[i]=l1和l2最大的
//从length-2开始,因为最后一位一定是0
for (int i = length-1; i >= 0; i--) {
//如果是')'就没必要计算了,结果就是0
if (i < length -1 && s[i] == '(') {
//step1,计算i+2开始的值
int l1 = 0;
if (s[i+1] == ')') {
l1 = 2;
if (i+l1 < length) {
l1 = a[i+l1] + l1;
}
}
//step2,计算i+1
int l2 = 0;
if (i+1+a[i+1] < length && s[i+1+a[i+1]] == ')') {
l2 = a[i+1] + 2;
if (i+l2 < length) {
l2 = a[i+l2]+l2;
}
}
//比较l1和l2,取大的
a[i] = l1>l2?l1:l2;
total = total > a[i] ?total:a[i];
} else {
a[i] = 0;
}
}
return total;
}
|
C
|
/** @file */
/**
* \file
* \brief API of the libparanut.
*/
/**
* \mainpage libparanut Documentation
*
* \section ParaNut Software Library Documentation
* Welcome to the libparanut documentation! This is a hardware abstraction
* library you can use to program a ParaNut processor without having to stare at
* Assembly Code. This documentation is meant as reference to developers interested in
* - Developing software for a ParaNut processor.
* - Using the special concepts of parallelity in a ParaNut processor.
* - Improving the libparanut.
*
* The main docoumentation containing the definition of the ParaNut architecture and design rules
* can be found in the [*ParaNut Manual*](../../doc/paranut-manual.pdf). If you want to work with
* the SystemC ParaNut model (simulation) take a look at the libparanutsim documentation
* [*libparanutsim Documentation*](../../doc/libparanutsim/index.html).
*
* \section modules Modules of the libparanut
*
* The libparanut serves several functions to you on a silver
* platter. These are grouped into the \ref mo :
*
* 1. The \ref ba contains functions for getting general information
* about the ParaNut, like the number of cores and such. There's also some
* functions for halting cores.
* 2. The \ref li contains functions for stopping and starting Linked
* Mode execution. Don't know what that is? Check \ref ms or the fine
* ParaNut Manual.
* 3. The \ref th contains functions for stopping and starting Threaded
* Mode execution. Same advice goes.
* 4. The \ref ca contains functions for controlling the ParaNut cache and
* getting information about it.
* 5. The \ref ex contains functions for controlling Interrupts and
* Exceptions.
* 6. The \ref sp is an implementation of a spinlock so you can properly
* protect and synchronize your stuff in Threaded Mode.
*
* \section System Overview
*
* The following picture shows a system overview. It might be a little confusing
* at first. Don't worry about that, just read some more documentation and it
* will probably all fall into place.
*
* \todo Add English Version and fix format
*
* \image html aufbau.png "Overview of the libparanut" width=800px
* \image latex aufbau.eps "Overview of the libparanut" width=0.8\textwidth
*
* \section HOWTO
*
* \todo Add documentation here in case other compilers/ISAs are used someday.
*
* \todo The \ref Makefile might not be compliant with any other tool than GNU
* make.
*
* How to make libparanut run with our in-house ParaNut implementation:
* You will need GNU make and the RISC-V GNU Toolchain for that (see Appendix A
* in ParaNut Manual). Also, you may need to have Python on your system (so far,
* no restrictions on the version are known). This assumes you already got the
* ParaNut up and running!
*
* 1. Open up the wonderful \ref Makefile in the libparanut directory. This
* is the place where all your wishes come true. Right at the start,
* there's the section "System Configuration" where you can set a few
* things to tweek your libparanut. Check out the \ref co to see what
* those values mean. The default should be fine at first.
* 2. Onto the section "Compiler Configuration".
* See the "PN_ISA" in the \ref Makefile? This is the Instruction Set
* Architecture. The very nice \ref Makefile tree will chose all the right
* assembly source code files for the libparanut if this variable is set
* correctly. Currently, our ParaNut implements RISCV ISA, which is why
* this value says RV32I. This means you don't have to touch it.
* 3. The \ref Makefile also lets you chose the compiler. If you want another
* compiler than GCC, you will also need to add some if-else logic in the
* section "Compiler and Assembler Flags".
* 4. To reduce the code size of the libparanut, you could set "PN_DEBUG" to
* 0. This means that the libparanut will not be compiled with debug
* symbols. It should be fine to compile it with debug symbols at first,
* though.
* 7. Want everything compiled now? Say \code gmake all \endcode and the
* magic is done. All the modules are compiled and statically linked into
* "libparanut.a". You can find it in the newly generated directory named
* "INSTALL". Do not forget to call clean beforehand if you changed
* something in the Makefile.
* 8. Include paranut.h in your application. Set your include-path to
* the INSTALL directory while compiling:
* \code -I/path/to/libparanut/INSTALL/include \endcode
* 9. Link libparanut.a into your application. To do that in GCC,
* you can just put \code -L/path/to/libparanut/INSTALL/lib -lparanut \endcode
* at the end of your linker/compilation command.
*
* I hope the following example can explain what I mean:
*
* \todo Prettier example, explain Link Module and Spinlock Module.
*
* \code
* cd /path/to/libparanut
* gmake all
* cd /path/to/my_application.c
* my_gcc -c my_compiler_options -I/path/to/libparanut/INSTALL/include my_application.c
* my_gcc my_link_options my_object.o -L/path/to/libparanut/INSTALL/lib-lparanut
* \endcode
*
* Do not forget to also compile in the startup code. To see a full example of
* what you need to do, check the Makefiles in the other sw/ subdirectories in
* the repository.
*
* \section expectations Expectations to the application
*
* Here is a list of things that the libparanut expects you to have done before using it:
*
* 1. The \ref ca expects you to have called \ref pn_cache_init() before
* using any of its other functions. Behaviour of the other functions is
* undefined if not.
* 2. The \ref ex expects you to have called \ref pn_exception_init() before
* calling \ref pn_exception_set_handler(). I mean, you can set your own
* exception handler beforehand, but it will not be called if the
* exception occurs.
* The \ref pn_interrupt_enable(), \ref pn_interrupt_disable(), and \ref
* pn_progress_mepc() functions will work with no problem, though.
* 3. The \ref th is the complicated one. It's a little tricky because of its
* workflow. The CePU internally sets a few needed variables which
* indicate a status to the CoPU. After a CoPU is woken up, they start
* executing code at the reset address. This means that the end of the
* startup code for the CoPUs also needs to be their entrance point to the
* \ref th, where they can read the internal variables and figure out what
* they are supposed to do with them. This entrance point is
* \ref pn_thread_entry(), and it needs to be called in the startup code
* on all CoPUs. Our in-house startup code does this for you, but I'm
* leaving that here just in case you want to know.
* 5. The \ref th has one more expectation. The state of the CePU and its
* memory need to be shared with all cores. That means that there has
* to be a shared memory section that has to be as big as the memory for
* the individual cores. The start adress of this area has to be put into
* a globally known location called shared_mem_start, and the size has
* to be put into shared_mem_size. This also happens in our build-in
* startup code, so you do not need to worry about it.
*
* Also, here's some general advice: If you want your startup code to be
* compatible with many versions of the libparanut, you can check if a certain
* module is available. The file \ref pn_config.h, which is created during
* compilation time, has some defines set for every module that is enabled.
* Check out the \ref pn_config.h documentation to find out more!
*
* \internal
* \section future Future Ideas for libparanut
*
* 1. In the \ref ca, split \ref pn_cache_enable() and
* \ref pn_cache_disable() into seperate functions for data and
* instruction cache.
* 2. In the \ref th, build in POSIX style thread functions.
* 3. Build a state machine for every core that tracks wether a core is used
* in linked mode, threaded mode, or doing POSIX threads. Enable the user
* of the libparanut to use threaded and linked mode in a mixed way.
* 4. In \ref ex, provide a function to hang in a "raw" exception handler
* (basically change mtvec).
* 5. Implement a possibility to check wether or not a module has been
* initialized already. Also implement a pn_init() function which
* checks for all modules if the module is already initialized, and if it
* is not, initializes them (provided the module was compiled in).
* 6. Concerning the init() functions: If a function in a module is used
* despite of the module not being initialized, throw an exception
* (use \ref pn_ecall()).
* 7. Implement a pn_strerror() function which takes an error value and
* prints what the error means.
* 8. Implement a global checkable error variable.
* 9. For threaded and linked mode, implement the possibility to pass a stack
* size that shall be copied. It should also be able to tell these
* functions that only the stack from the top function shall be copied.
* 10. Implement a pn_atomic_increment() and pn_atomic_decrement() function.
* 11. Implement pn_printf() which can be used in linked mode.
* 12. In the Makefile, copy the libparanut to the place where the RISCV
* toolchain is installed. This would make it easier for applications to
* compile.
*
* \section Copyright
*
* Copyright 2019-2020 Anna Pfuetzner (<[email protected]>)
* Alexander Bahle (<[email protected]>)
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
/**
* \internal
* \defgroup as Internal Assembly Calls
*
* \brief Calls from the architecture independent implementation to the
* architecture specific assembly code.
*
* \todo If there ever is a new ParaNut with a different ISA,
* documentation for the new .S files has to be added in the
* respective directories.
*/
/**
* \file Makefile
* \brief Makefile of the libparanut.
*
* This Makefile is supposed to make (ha!) the compilation of libparanut more
* handy. To check out exactly how this works, see the section \ref HOWTO in the
* mainpage!
*
* \internal
* \todo The Makefile might not be compliant with any other tool than GNU make.
* Compatibility with other tools should be tested and listed (maybe in
* the mainpage). The \ref HOWTO section needs to be changed, then.
*
* \attention Why am I calling a Python Skript when I'm building
* pn_cache_RV32I_nnn.S (example: \ref pn_cache_RV32I_auto.S) instead of just
* writing the file myself? And why does that cache target exist?
* Click \ref pn_cache_RV32I_buildscript.py to find out!
* \endinternal
*
* \includelineno Makefile
*/
/*Includes*********************************************************************/
#ifndef PARANUT_H
#define PARANUT_H
#include <stdint.h>
#include <stdlib.h>
#include "pn_config.h"
/*Typedefs*********************************************************************/
/**
* \defgroup he libparanut Helpers
* \brief Typedefs and defines of libparanut which can also be used in your
* application.
*/
/**
* \addtogroup he
* @{
*/
/**
* \defgroup ty Typedefs
* \brief Needed typedefs.
*
* Please note that there are several typedefs for differing register widths of
* the ParaNut. Which ones are used depend on how you set \ref PN_RWIDTH while
* compiling (pn_config.h). Doxygen can only document one of them, so here you
* are, stuck with the 32-bit version. Check source code of paranut.h,
* section Typedefs, if you want to see the others.
*/
/**
* \addtogroup ty
* @{
*/
/**
* \typedef _pn_spinlock
* \brief Renaming of struct \ref __pn_spinlock for your convenience.
*
* Check documentation of \ref __pn_spinlock to get more information.
*/
/**
* @{
*/
/**
* \typedef PN_CID
* \brief Signed type that can be used to address any core in this
* architecture.
*
* See documentation of \ref PN_NUMC to understand why we use only the actual
* register width and not more.
*/
/**
* \typedef PN_NUMC
* \brief Signed type that can hold the maximum number of cores in this
* architecture.
*
* Let's say your ParaNut has a group register width of 32 bits. This means that
* there are 4.294.967.296 potential groups. Every group has 32 bits to
* represent different cores. That means there are 137.438.953.472 cores that
* can be adressed.
*
* This does, in theory, mean that we need 64 bit to represent the possible
* number of cores. However, it is deemed to be pretty unrealistic that there
* will be a ParaNut version with more than 4.294.967.296 cores anytime soon.
* So, for optimization purposes, we just use 32 bit here. Even half of that is
* probably not possible in my lifetime, which is why we are not even using
* unsigned (also because some compilers could throw errors when mixing signed
* and unsigned types, e.g. in a for loop). One more plus is that we can use
* these values to signal errors when they are returned by a function.
*
* Same explaination goes in all other register widths. If you really need more,
* feel free to double the bits.
*/
/**
* \typedef PN_CMSK
* \brief Unsigned type that can act as a core mask.
*
* This is, of course, the same as the register width of the ParaNut. Unsigned
* because it direcetly represents a register.
*/
/**
* \typedef PN_NUMG
* \brief Signed type that can be used to address any group in this
* architecture.
*
* This is, of course, the same as the register width of the ParaNut.
*/
#if PN_RWIDTH == 8
typedef int8_t PN_CID;
typedef int8_t PN_NUMC;
typedef uint8_t PN_CMSK;
typedef int8_t PN_NUMG;
#elif PN_RWIDTH == 16
typedef int16_t PN_CID;
typedef int16_t PN_NUMC;
typedef uint16_t PN_CMSK;
typedef int16_t PN_NUMG;
#elif PN_RWIDTH == 32
typedef int32_t PN_CID;
typedef int32_t PN_NUMC;
typedef uint32_t PN_CMSK;
typedef int32_t PN_NUMG;
#elif PN_RWIDTH == 64
typedef int64_t PN_CID;
typedef int64_t PN_NUMC;
typedef uint64_t PN_CMSK;
typedef int64_t PN_NUMG;
#elif PN_RWIDTH == 128
typedef int128_t PN_CID;
typedef int128_t PN_NUMC;
typedef uint128_t PN_CMSK;
typedef int128_t PN_NUMG;
#else
#error Your ParaNut has a very exotic register width that was not considered\
when libparanut was written. Check paranut.h, section Typedefs, and add \
your funky register width there.
#endif
/**
* @}
*/
/**
* @}
*/
/*Error Codes******************************************************************/
/**
* \defgroup er Error Codes
* \brief Error codes returned by the functions in this library.
*/
/**
* \addtogroup er
* @{
*/
/**
* @{
*/
/**
* \def PN_SUCCESS
* \brief Successful execution.
*
* Implies that a function finished successfully.
*/
#define PN_SUCCESS 0
/**
* \def PN_ERR_PARAM
* \brief Parameter error.
*
* The parameters given to a function were wrong (i.e. out of range).
*/
#define PN_ERR_PARAM (-1)
/**
* \def PN_ERR_NOIMP
* \brief Function not implemented.
*
* The libparanut function is not yet implemented.
*/
#define PN_ERR_NOIMP (-2)
/**
* \def PN_ERR_COPU
* \brief CoPU error.
*
* Function that isn't allowed on CoPU was being executed on CoPU.
*/
#define PN_ERR_COPU (-3)
/**
* \def PN_ERR_MATCH
* \brief Mode begin and end matching error.
*
* Functions for beginning and ending linked and threaded mode have to be
* matched. Linked and threaded mode shall not be mixed.
*/
#define PN_ERR_MATCH (-4)
/**
* \def PN_ERR_LOCKOCC
* \brief Lock occupied error.
*
* Can occur if you tried destroying an occupied lock or used the trylock
* function on an occupied lock.
*/
#define PN_ERR_LOCKOCC (-5)
/**
* \def PN_ERR_CACHE_LINESIZE
* \brief Weird cache line size error.
*
* Can occur if libparanut is supposed to run on an architecture that has a
* cache line size which is not either 32, 64, 128, 256, 512, 1024 or 2048 bit.
* Should be more of a development error instead of a normal usage error.
*
* In other words, it should not occur if you are just developing middle end
* stuff while using the libparanut on a deployed ParaNut. Contact
* the maintainers about this if it still does.
*
* \internal
*
* The following steps would be necessary to introduce a new cache line size on
* RV32I libparanut:
* - Go to the top of \ref pn_cache_RV32I_buildscript.py and add the new
* cache line size in bits to "cache_line_size_list".
* - Go to the \ref Makefile and take a look at the target "cache". Add a new
* call to the buildscript for your size.
* - Go into \ref pn_cache.c and look at "Assembly Functions". Add your
* references to the others.
* - Also look at the function \ref pn_cache_init(). You will see that there
* is a switch that decides what functions to use. Add a new
* case there (before the default, of course!) and put in your newly
* added functions.
* - After a \code make clean all \endcode your new cache line size should be
* ready to use.
* - Change the places in the documentation where the linesizes are listed
* (should only be here and at the top of
* \ref pn_cache_RV32I_buildscript.py). Add your
* new assembly file to the GIT repo and push that stuff.
*
* \todo This description should change if other ParaNut architectures or cache
* line sizes are introduced.
*
* \endinternal
*/
#define PN_ERR_CACHE_LINESIZE (-6)
/**
* \def PN_ERR_EXC
* \brief Exception code not implemented error.
*
* You tried callin \ref pn_exception_set_handler() with an invalid exception
* code.
*/
#define PN_ERR_EXC (-8)
/**
* @}
*/
/**
* @}
*/
/*Modes************************************************************************/
/**
* \defgroup ms Modes
*
* \brief Modes of the ParaNut Cores.
*
* The CePU can only ever operate in Mode 3 (autonomous). It is still shown as
* capable of Mode 2 (threaded Mode) because Mode 3 is an extension in
* functionality in comparison to Mode 2. Mode 2 cores do not handle their own
* interrupts/exceptions, which a Mode 3 core does.
*
* It can also be set into Mode 0, which does not break hardware debugging
* support.
*
* The CePU is the only core capable of changing other cores Modes.
*
* The CoPUs are never capable of Mode 3. They may be capable of Mode 2, which
* means they are able to fetch their own instructions and are therefore able
* to do different work in parallel to the CePU. They are, at minimum, capable
* of Mode 1 (linked Mode), which means it will execute the same instructions as
* the CePU on different data. This does not start until the CePU is also told
* to now start executing in linked mode, though.
*
* \internal
* \todo The information above may change some day.
* \endinternal
*
* Which Mode the CoPUs are in after system reset is an implementation detail of
* the ParaNut itself and the startup code.
*
* For further information, check ParaNut Manual.
*/
/**
* \addtogroup ms
* @{
*/
/**
* @{
*/
/**
* \def PN_M0
* \brief Mode 0 (halted Mode).
*/
#define PN_M0 0x0U
/**
* \def PN_M1
* \brief Mode 1 (linked Mode).
*/
#define PN_M1 0x1U
/**
* \def PN_M2
* \brief Mode 2 (unlinked or threaded Mode).
*/
#define PN_M2 0x2U
/**
* \def PN_M3
* \brief Mode 3 (autonomous Mode).
*/
#define PN_M3 0x3U
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/*Base Module******************************************************************/
/**
* \defgroup mo libparanut Modules
*
* \brief Modules of libparanut.
*/
/**
* \addtogroup mo
* @{
*/
/**
* \defgroup ba Base Module
*
* \brief Functions for getting the status of your ParaNut and halting
* cores.
*
* Concerning the _g functions: If your ParaNut implementation has more cores
* than what is the standard register size on your system (i.e. register size is
* 32, but you got more than 32 cores including the CePU), you have to chose the
* group of cores that you want to talk to. For that, most functions in this
* section have a group version (suffix _g) which has an additional group
* parameter.
*
* This works the following way: If your register size is 32, than the CePU is
* in group 0 (0x00000000) and is always represented by the first bit in the
* coremasks (0x00000001). The first CoPU is also in group 0 and represented by
* the second bit (0x00000002). After that comes the second CoPU, represented by
* 0x00000004. And so on until CoPU 30. The 31st CoPU is then represented by
* group 1 (0x00000001) and the first bit (0x00000001). The 63rd CoPU is
* represented by group 2 (0x00000002) and the first bit (0x00000001). The 95th
* CoPU is represented by group 3 (0x00000003) and the first bit (0x00000001).
* This information may become untrue if a big-endian version of the ParaNut is
* ever released.
*
* For further information on this topic, you should check the ParaNut Manual
* itself. Also, the documentation on the ParaNut \ref ms that is included in
* here could clear some things up.
*
* \internal
* The base module also contains functions that are used in other modules as
* well.
* \todo Currently (Oct. 2019), there is no ParaNut implementation that actually
* has to use more than one group, which is why the group functions are only
* implemented as stubs right now.
* \endinternal
*/
/**
* \addtogroup ba
* @{
*/
/**
* @{
*/
/**
* \fn PN_NUMC pn_numcores(void)
* \brief Get the number of cores in your system.
*
* Cannot be called from CoPU.
*
* \return The number of cores in your ParaNut implementation or \ref
* PN_ERR_COPU.
*/
PN_NUMC pn_numcores(void);
/**
* \fn PN_CMSK pn_m2cap(void)
* \brief Check which cores are capable of Mode 2 operation.
*
* See documentation of \ref ms for more information.
*
* Cannot be called from CoPU.
*
* \return A bitmask representing your ParaNut cores or \ref PN_ERR_COPU.
* If a bit is set to 1, it means that the core is capable of
* operating in Mode 2.
*/
PN_CMSK pn_m2cap(void);
/**
* \fn PN_CMSK pn_m2cap_g(PN_NUMG groupnum)
* \brief Check which cores are capable of Mode 2 operation.
*
* \todo Currently only a stub. Will therefore always return either
* \ref PN_ERR_COPU or \ref PN_ERR_NOIMP if executed on CePU.
*
* See documentation of \ref ms for more information.
*
* Cannot be called from CoPU.
*
* \param[in] groupnum is the group of cores you want to know about.
* \return A bitmask representing your ParaNut cores or \ref PN_ERR_COPU. If
* a bit is set to 1, it means that the core is capable of operating
* in Mode 2.
*/
PN_CMSK pn_m2cap_g(PN_NUMG groupnum);
/**
* \fn PN_CMSK pn_m3cap(void)
* \brief Check which cores are capable of Mode 3 operation.
*
* \attention This function will, in the current ParaNut implementation, return
* a hard coded 1 or \ref PN_ERR_COPU if executed on CoPU. The reason for this
* is that only the CePU is capable of Mode 3.
*
* See documentation of \ref ms for more information.
*
* Cannot be called from CoPU.
*
* \return A bitmask representing your ParaNut cores or \ref PN_ERR_COPU. If
* a bit is set to 1, it means that the core is capable of operating
* in Mode 3.
*/
PN_CMSK pn_m3cap(void);
/**
* \fn PN_CMSK pn_m3cap_g(PN_NUMG groupnum)
* \brief Check which cores are capable of Mode 3 operation.
*
* \todo Currently only a stub. Will therefore always return either
* \ref PN_ERR_COPU or \ref PN_ERR_NOIMP if executed on CePU.
*
* See documentation of \ref ms for more information.
*
* Cannot be called from CoPU.
*
* \param[in] groupnum is the group of cores you want to know about.
* \return A bitmask representing your ParaNut cores or \ref PN_ERR_COPU. If
* a bit is set to 1, it means that the core is capable of operating
* in Mode 3.
*/
PN_CMSK pn_m3cap_g(PN_NUMG groupnum);
/**
* \fn PN_CID pn_coreid(void)
* \brief Get the ID of the core that this function is executed on.
*
* \return The core ID. Starts with 0 for CePU. Can not return an error.
*/
PN_CID pn_coreid(void);
/**
* \fn PN_CID pn_coreid_g(PN_NUMG *groupnum)
* \brief Get the ID and group number of the core that this code is running
* on.
*
* \todo Currently only a stub. Will therefore always return \ref PN_ERR_NOIMP.
*
* \param[out] groupnum is a reference to be filled with the group number of
* the core.
* \return The core ID. Starts with 0 for CePU. Does not start again when in
* another group than group 0. Can not return an error.
*/
PN_CID pn_coreid_g(PN_NUMG *groupnum);
/**
* \fn void pn_halt(void)
* \brief Halt whatever core the function is executed on.
*
* If executed on a core, it will be set to Mode 0 and stop operation. Causes
* reset of program counter to reset address on a Mode 2 capable CPU.
*
* If executed on CePU, also halts all other CoPUs on system.
*
* See documentation of \ref ms for more information.
*
* This function returns nothing because it should not be possible for any core
* to leave this state on its own.
*/
void pn_halt(void);
/**
* \fn int pn_halt_CoPU(PN_CID coreid)
* \brief Halts a CoPU.
*
* Sets the CoPU with the given ID into a halted state (Mode 0).
*
* See documentation of \ref ms for more information.
*
* Cannot be executed on CoPU.
*
* Halting an already halted core results in failure (\ref PN_ERR_PARAM) to aid
* debugging.
*
* \todo Not yet implemented for given core IDs outside of group 0. Will return
* \ref PN_ERR_NOIMP in this case.
*
* \param[in] coreid is the ID of the CoPUs you want to halt. Since ID 0
* represents the CePU, this function will throw an error when given
* 0 to aid debugging. If you want the CePU to halt, use function
* \ref pn_halt().
* \return Either \ref PN_SUCCESS, \ref PN_ERR_PARAM or \ref PN_ERR_COPU.
*/
int pn_halt_CoPU(PN_CID coreid);
/**
* \fn int pn_halt_CoPU_m(PN_CMSK coremask)
* \brief Halts one or more CoPUs.
*
* Sets the CoPUs represented in the bitmask into a halted state (Mode 0).
*
* See documentation of \ref ms for more information.
*
* Cannot be executed on CoPU.
*
* Halting an already halted core results in failure (\ref PN_ERR_PARAM) to aid
* debugging.
*
* \param[in] coremask is the bitmask representing the CoPUs you want to halt.
* When all bits are set to 0, this function will return an error
* (\ref PN_ERR_PARAM) to aid debugging. Also, setting the first bit
* to 1 will return an error (\ref PN_ERR_PARAM) since it represents
* the CePU, which should be halted with \ref pn_halt().
* \return Either \ref PN_SUCCESS, \ref PN_ERR_PARAM or \ref PN_ERR_COPU.
*/
int pn_halt_CoPU_m(PN_CMSK coremask);
/**
* \fn int pn_halt_CoPU_gm(PN_CMSK *coremask_array, PN_NUMG array_size)
* \brief Halts the CoPUs specified in the coremask_array.
*
* \todo Currently only a stub. Will therefore always return either
* \ref PN_ERR_COPU or \ref PN_ERR_NOIMP if executed on CePU.
*
* Sets the CoPUs represented by bitmask and their position in the array (=
* their group number) into a halted state (Mode 0).
*
* See documentation of \ref ms for more information.
*
* Cannot be executed on CoPU.
*
* Halting an already halted core results in failure (\ref PN_ERR_PARAM) to aid
* debugging.
*
* \param[in] coremask_array is a pointer to the start of a coremask array. The
* position of the mask in the array represents the group number of
* the cores. When all bits are set to 0, this function will return
* an error (\ref PN_ERR_PARAM) to aid debugging. Also, setting the
* first bit to 1 will return an error (\ref PN_ERR_PARAM) since it
* represents the CePU, which should be halted with \ref pn_halt().
* \param[in] array_size is the number of entries in the coremask_array.
* \return Either \ref PN_SUCCESS, \ref PN_ERR_PARAM or \ref PN_ERR_COPU.
*/
int pn_halt_CoPU_gm(PN_CMSK *coremask_array, PN_NUMG array_size);
/**
* \fn unsigned int pn_clock_freq(void)
* \brief Returns system clock frequency in Hz.
*
* Returns the value of the paranut pnclockinfo register which should contain
* the current system clock frequency in Hz. If this value is not what you would
* expect check your implementation.
*
* \return System clock frequency in Hz.
*/
unsigned int pn_clock_freq(void);
/**
* \fn unsigned int pn_timebase_us(void)
* \brief Returns machine timer timebase in us.
*
* Returns the value of the paranut pntimebase register which should contain
* the current machine timer timebase in us.
*
* \return Machine timer timebase in us.
*/
unsigned int pn_timebase_us(void);
/**
* \fn int64_t pn_time_ns(void)
* \brief Returns system time in ns. Does not care for overflow.
*
* Cannot be executed on CoPU.
*
* The first time executing this function takes the longest time since it has
* to initialize the frequency and an internal conversion factor. So if you want
* to use it for time measurement, you can call the function once before
* actual measurement to make the values more comparable.
*
* When testing on my ParaNut, this made a difference of around 2000 ticks.
*
* \return System time in ns or \ref PN_ERR_COPU.
*/
int64_t pn_time_ns(void);
/**
* \fn void pn_usleep(int64_t useconds);
* \brief waits for atleast useconds in microseconds
*
* Cannot be executed on CoPU.
*
* Activaly waits until atleast the time in useconds is over for this it uses the pn_time_ns function
*
*
* \return void
*/
void pn_usleep(int64_t useconds);
/**
* \fn int pn_simulation(void)
* \brief Checks if we run in simulation instead of real hardware.
*
* \warning This function is a thing that only works with our specific
* ParaNut simulation. If the simulation changes, this needs to be changed, too.
*
* \return Zero if we run on hardware, non-zero if we run in simulation.
*/
int pn_simulation(void);
/**
* @}
*/
/**
* @}
*/
/*Linked Module****************************************************************/
/**
* \defgroup li Link Module
*
* \brief Functions for using the linked mode.
*
* Also see \ref ms.
*
* \warning
* If you want to use the Linked Module on RISC-V ParaNut, your ParaNut has to
* support the M Extension and you have to compile your application with the
* flag mabi=rv32im. The libparanut \ref Makefile sets this flag automatically
* when you chose the \ref li or one of the Modules that has \ref li as a
* dependency.
*/
/**
* \addtogroup li
* @{
*/
/**
* @{
*/
/**
* \fn PN_CID pn_begin_linked(PN_NUMC numcores, void *frame_adr)
* \brief Links a given number of CoPUs to the CePU.
*
* \internal
* \todo This functions specification depends a lot on ParaNut hardware design.
* In later implementations, using linked and threaded mode in a mixed way might
* be possible. The documentation and implementation will have to be changed,
* then.
* \endinternal
*
* \todo Not yet implemented for more cores than what is available in one group.
* Will return \ref PN_ERR_NOIMP when called with more cores.
*
* Sets numcores-1 CoPUs to Mode 1 (linked Mode) so they start executing the
* instruction stream fetched by the CePU. This function will return an error
* (\ref PN_ERR_MATCH) if the CoPUs are not all halted.
*
* The frame_adr is used to determine the stack we need to synchronize
* between the CePU and CoPUs. The \ref PN_BEGIN_LINKED macro uses the gcc
* specific built-in function __builtin_frame_address() to do this automatically.
* The value given will be checked and \ref PN_ERR_PARAM is returned on a value
* that is not inside the CePUs stack frame. If the value NULL is supplied the
* entire stack will be coppied, which in some cases can slow down the execution.
*
* See documentation of \ref ms for more information.
*
* Cannot be executed on CoPU. Cannot be mixed with threaded mode or other
* linked mode functions, until \ref pn_end_linked() is called.
*
* \attention All data that you want to preserve after \ref pn_end_linked()
* was called can not be stored on stack. You can make it static or global.
*
* \warning There is no guarantee that the execution of code actually happens at
* the same time on CePUs and CoPUs.
*
* \param[in] numcores is the number of cores that shall be linked together.
* A value of 0 or 1 will return an error (\ref PN_ERR_PARAM) to aid
* debugging.
* \param[in] frame_adr is the address where the callers stack is
* starting.
* A value outside of the CePu stack will return an error
* (\ref PN_ERR_PARAM) to aid debugging.
* The value __NULL__ will not return an error and the entire stack
* will be coppied.
* \param[in] flags may be used to further configure the linked mode execution.
* Currently only one flag is implemented: 1. This flag beeing set
* indicates that the saved register s0 is currently beeing used as
* frame pointer and must thus be altered according to the CoPUs stack
* address. Further flags may be added in future.
* \return The ID of the core, or \ref PN_ERR_MATCH, \ref PN_ERR_PARAM, or
* \ref PN_ERR_COPU.
*/
PN_CID pn_begin_linked(PN_NUMC numcores, void *frame_adr, char flags);
/**
* \def PN_BEGIN_LINKED(NUMCORES)
* \brief Call pn_begin_linked with the __buitlin_frame_address(0).
*
* Calls pn_begin_linked with the gcc built-in function __buitlin_frame_address(0)
* to copy only the current stack frame.
*/
#define PN_BEGIN_LINKED(NUMCORES) ({ \
char flags = 0; \
void *frame_addr = __builtin_frame_address(0); \
void *fp = NULL; \
asm volatile("mv %0, s0" : "=r" (fp)); \
if(fp == frame_addr){ \
flags = 1; \
} \
pn_begin_linked(NUMCORES, __builtin_frame_address(0), flags);})
/**
* \fn PN_CID pn_begin_linked_m(PN_CMSK coremask, void *frame_adr)
* \brief Links the CPUs specified in the coremask.
*
* \internal
* \todo This functions specification depends a lot on ParaNut hardware design.
* In later implementations, using linked and threaded mode in a mixed way might
* be possible. The documentation and implementation will have to be changed,
* then.
* \endinternal
*
* Sets the CoPUs represented by the bitmask to Mode 1 (linked Mode) so they
* start executing the instruction stream fetched by the CePU. This function
* will return an error (\ref PN_ERR_MATCH) if the CoPUs are not all halted.
*
* The frame_adr is used to determine the stack we need to synchronize
* between the CePU and CoPUs. The \ref PN_BEGIN_LINKED_M macro uses the gcc
* specific built-in function __builtin_frame_address() to do this automatically.
* The value given will be checked and \ref PN_ERR_PARAM is returned on a value
* that is not inside the CePUs stack frame. If the value NULL is supplied the
* entire stack will be coppied, which in some cases can slow down the execution.
*
* See documentation of \ref ms for more information.
*
* Cannot be executed on CoPU. Cannot be mixed with threaded mode or other
* linked mode functions, until \ref pn_end_linked() is called.
*
* \attention All data that you want to preserve after \ref pn_end_linked()
* was called can not be stored on stack. You can make it static or global.
*
* \warning There is no guarantee that the execution of code actually happens at
* the same time on CePUs and CoPUs.
*
* \param[in] coremask is the bitmask representing the CoPUs you want to link.
* When all bits are set to 0, this function will return an error
* (\ref PN_ERR_PARAM) to aid debugging. Also, not setting the first
* bit to 1 will return an error (\ref PN_ERR_PARAM) since it
* represents the CePU (which needs to be linked, too).
* \param[in] frame_adr is the address where the callers stack is
* starting.
* A value outside of the CePu stack will return an error
* (\ref PN_ERR_PARAM) to aid debugging.
* The value __NULL__ will not return an error and the entire stack
* will be coppied.
* \param[in] flags may be used to further configure the linked mode execution.
* Currently only one flag is implemented: 1. This flag beeing set
* indicates that the saved register s0 is currently beeing used as
* frame pointer and must thus be altered according to the CoPUs stack
* address. Further flags may be added in future.
* \return The ID of the core, or \ref PN_ERR_MATCH, \ref PN_ERR_PARAM, or
* \ref PN_ERR_COPU.
*/
PN_CID pn_begin_linked_m(PN_CMSK coremask, void *frame_adr, char flags);
/**
* \def PN_BEGIN_LINKED_M(NUMCORES)
* \brief Call pn_begin_linked_m with the __buitlin_frame_address(0).
*
* Calls pn_begin_linked_m with the gcc built-in function __buitlin_frame_address(0)
* to copy only the current stack frame.
*/
#define PN_BEGIN_LINKED_M(COREMASK) \
char flags = 0; \
void *frame_addr = __builtin_frame_address(0); \
void *fp = NULL; \
asm volatile("mv %0, s0" : "=r" (fp)); \
if(fp == frame_addr){ \
flags = 1; \
} \
pn_begin_linked_m(COREMASK, __builtin_frame_address(0), flags)
/**
* \fn PN_CID pn_begin_linked_gm(PN_CMSK *coremask_array,
* PN_NUMG array_size)
* \brief Links the CPUs specified in the coremask_array.
*
* \internal
* \todo This functions specification depends a lot on ParaNut hardware design.
* In later implementations, using linked and threaded mode in a mixed way might
* be possible. The documentation and implementation will have to be changed,
* then.
* \endinternal
*
* \todo Currently only a stub. Will therefore always return \ref PN_ERR_NOIMP.
*
* Sets the CoPUs represented by bitmask and their position in the array (=
* their group number) to Mode 1 (linked Mode) so they start executing the
* instruction stream fetched by the CePU. This function will return an error
* (\ref PN_ERR_MATCH) if the CoPUs are not all halted.
*
* See documentation of \ref ms for more information.
*
* Cannot be executed on CoPU. Cannot be mixed with threaded mode or other
* linked mode functions, until \ref pn_end_linked() is called.
*
* \attention All data that you want to preserve after \ref pn_end_linked()
* was called can not be stored on stack. You can make it static or global.
*
* \warning There is no guarantee that the execution of code actually happens at
* the same time on CePUs and CoPUs.
*
* \param[in] coremask_array is a pointer to the start of a coremask array. The
* position of the mask in the array represents the group number of
* the cores. When all bits are set to 0, this function will return
* an error (\ref PN_ERR_PARAM) to aid debugging. Also, not setting
* the first bit to 1 will return an error (\ref PN_ERR_PARAM) since
* it represents the CePU (which needs to be linked, too).
* \param[in] array_size is the number of entries in the coremask_array.
* \return The ID of the core, or \ref PN_ERR_MATCH, \ref PN_ERR_PARAM, or
* \ref PN_ERR_COPU.
*/
PN_CID pn_begin_linked_gm(PN_CMSK *coremask_array, PN_NUMG array_size, char flags);
/**
* \fn int pn_end_linked(void)
* \brief Ends linked execution.
*
* Halts all CoPUs that are currently linked together, effectively ending the
* linked execution. Will fail if there are no cores linked together.
*
* See documentation of \ref ms for more information.
*
* Can be executed on CoPU, but will do nothing then.
*
* \return Either \ref PN_SUCCESS or \ref PN_ERR_MATCH.
*/
int pn_end_linked(void);
/**
* \def PN_END_LINKED()
* \brief Call pn_end_linked.
*
* Calls pn_end_linked. Is only defined to have aesthetically matching pair with
* the \ref PN_BEGIN_LINKED and \ref PN_BEGIN_LINKED_M macros.
*/
#define PN_END_LINKED() pn_end_linked()
/**
* \fn PN_CID pn_run_linked(PN_NUMC numcores, void (*func)(), void *args)
* \brief Starts a given function in linked mode.
*
* \internal
* \todo This functions specification depends a lot on ParaNut hardware design.
* In later implementations, using linked and threaded mode in a mixed way might
* be possible. The documentation and implementation will have to be changed,
* then.
* \endinternal
*
* \todo Not yet implemented for more cores than what is available in one group.
* Will return \ref PN_ERR_NOIMP when called with more cores.
*
* Sets numcores-1 CoPUs to Mode 1 (linked Mode) and runs the given function.
* After completing the function will return 0 in case of success. This function
* will return an error (\ref PN_ERR_MATCH) if the CoPUs are not all halted.
* The referenced function should have two attributes: void *args, PN_CID cid.
* Argument 1 is defined by the user, while argument 2 "cid" contains the ID of
* the executing Core.
*
* Cannot be executed on CoPU. Cannot be mixed with threaded mode or other
* linked mode functions, until \ref pn_end_linked() is called.
*
* \attention All data that you want to preserve after \ref completing the function
* has returned can not be stored on stack. You can make it static or global.
*
* \warning There is no guarantee that the execution of code actually happens at
* the same time on CePUs and CoPUs.
*
* \param[in] numcores is the number of cores that shall be linked together.
* A value of 0 or 1 will return an error (\ref PN_ERR_PARAM) to aid
* debugging.
* \param[in] func functionpointer to the function to be executed in linked mode.
* The function may expect a single argument in the form of a void pointer.
* Will return PN_ERR_PARAM if NULL.
* \param[in] args contains the void pointer to be handed to the function. May also
* be NULL.
* \return \ref PN_SUCCESS, \ref PN_ERR_MATCH, \ref PN_ERR_PARAM, or
* \ref PN_ERR_COPU.
*/
PN_CID pn_run_linked(PN_NUMC numcores, void (*func)(void *args, PN_CID cid), void *args);
/**
* \fn PN_CID pn_run_linked_m(PN_CMSK coremask, void *function, void *args);
* \brief Starts a given function in linked mode using a specific set of CoPUs.
*
* \internal
* \todo This functions specification depends a lot on ParaNut hardware design.
* In later implementations, using linked and threaded mode in a mixed way might
* be possible. The documentation and implementation will have to be changed,
* then.
* \endinternal
*
* \todo Not yet implemented for more cores than what is available in one group.
* Will return \ref PN_ERR_NOIMP when called with more cores.
*
* Sets the CoPUs defined by coremask to Mode 1 (linked Mode)and runs the given function.
* After completing the function will return 0 in case of success. This function
* will return an error (\ref PN_ERR_MATCH) if the CoPUs are not all halted.
* The referenced function should have two attributes: void *args, PN_CID cid.
* Argument 1 is defined by the user, while argument 2 "cid" contains the ID of
* the executing Core.
*
*
* Cannot be executed on CoPU. Cannot be mixed with threaded mode or other
* linked mode functions, until \ref pn_end_linked() is called.
*
* \attention All data that you want to preserve after \ref completing the function
* has returned can not be stored on stack. You can make it static or global.
*
* \warning There is no guarantee that the execution of code actually happens at
* the same time on CePUs and CoPUs.
*
* \param[in] coremask is the bitmask representing the CoPUs you want to link.
* When all bits are set to 0, this function will return an error
* (\ref PN_ERR_PARAM) to aid debugging. Also, not setting the first
* bit to 1 will return an error (\ref PN_ERR_PARAM) since it
* represents the CePU (which needs to be linked, too).
* \param[in] func functionpointer to the function to be executed in linked mode.
* The function may expect a single argument in the form of a void pointer.
* Will return PN_ERR_PARAM if NULL.
* \param[in] args contains the void pointer to be handed to the function. May also
* be NULL.
* \return \ref PN_SUCCESS, \ref PN_ERR_MATCH, \ref PN_ERR_PARAM, or
* \ref PN_ERR_COPU.
*/
PN_CID pn_run_linked_m(PN_CMSK coremask, void (*func)(), void *args);
/**
* \fn pn_run_linked_gm(PN_CMSK *coremask_array, PN_NUMG array_size,
* void *function, void *args)
* \brief NOT IMPLEMENTED YET, run a function in linked mode using group mask.
*
*
* \todo Currently only a stub. Will therefore always return \ref PN_ERR_NOIMP.
*/
PN_CID pn_run_linked_gm(PN_CMSK *coremask_array, PN_NUMG array_size, void *function, void *args);
/**
* @}
*/
/**
* @}
*/
/*Threaded Module**************************************************************/
/**
* \defgroup th Thread Module
*
* \brief Functions for using the threaded mode.
*
* Also see \ref ms.
*/
/**
* \addtogroup th
* @{
*/
/**
* @{
*/
/**
* \fn void pn_thread_entry(void)
* \brief Function that has to be called for CoPUs at the end of the
* startup code.
*
* Marks the entry point of CoPUs into the \ref th. Necessary for threaded Mode.
*
* The CoPUs are set up to work correctly in threaded Mode.
*
* Execution is only effective on CoPU. Can be executed on CePU, will do nothing
* then.
*
* Should not be called in a normal application at all. Left in here for
* startup code writers convenience.
*
* \attention What comes after this part in the startup code is irrelevant,
* since the CoPUs that landed there are either put into threaded mode or
* halted. The function can therefore not return any errors.
*
*/
void pn_thread_entry(void);
/**
* \fn PN_CID pn_begin_threaded(PN_NUMC numcores)
* \brief Puts numcores CPUs in threaded mode.
*
* \internal
* \todo This functions specification depends a lot on ParaNut hardware design.
* In later implementations, using linked and threaded mode in a mixed way might
* be possible. The documentation and implementation will have to be changed,
* then.
* \endinternal
*
* \todo Not yet implemented for more cores than what is available in one group.
* Will return \ref PN_ERR_NOIMP when called with more cores.
*
* Sets numcores-1 CoPUs to Mode 2 (unlinked Mode) so they start executing the
* following code in parallel. This function will return an error
* (\ref PN_ERR_MATCH) if the CoPUs are not all halted.
*
* See documentation of \ref ms for more information.
*
* Cannot be executed on CoPU. Cannot be mixed with linked mode or other
* begin threaded functions, until \ref pn_end_threaded() is called.
*
* \attention All data that you want to preserve after \ref pn_end_threaded()
* was called can not be stored on stack. You can make it static or global.
*
* \warning There is no guarantee that the execution of code actually happens at
* the same time on CePUs and CoPUs.
*
* \param[in] numcores is the number of cores that shall run threaded.
* A value of 0 or 1 will return an error (\ref PN_ERR_PARAM) to aid
* debugging.
* \return The ID of the core, or \ref PN_ERR_MATCH, \ref PN_ERR_PARAM, or
* \ref PN_ERR_COPU.
*/
PN_CID pn_begin_threaded(PN_NUMC numcores);
/**
* \fn PN_CID pn_begin_threaded_m(PN_CMSK coremask)
* \brief Puts the CPUs specified in the coremask in threaded mode.
*
* \internal
* \todo This functions specification depends a lot on ParaNut hardware design.
* In later implementations, using linked and threaded mode in a mixed way might
* be possible. The documentation and implementation will have to be changed,
* then.
* \endinternal
*
* Sets the CoPUs represented by the bitmask to Mode 2 (unlinked Mode) so they
* start executing the following code in parallel. This function
* will return an error (\ref PN_ERR_MATCH) if the CoPUs are not all halted.
*
* See documentation of \ref ms for more information.
*
* Cannot be executed on CoPU. Cannot be mixed with linked mode or other
* begin threaded functions, until \ref pn_end_threaded() is called.
*
* \attention All data that you want to preserve after \ref pn_end_threaded()
* was called can not be stored on stack. You can make it static or global.
*
* \warning There is no guarantee that the execution of code actually happens at
* the same time on CePUs and CoPUs.
*
* \param[in] coremask is the bitmask representing the CoPUs you want to run
* threaded. When all bits are set to 0, this function will return
* an error (\ref PN_ERR_PARAM) to aid debugging. Also, not setting
* the first bit to 1 will return an error (\ref PN_ERR_PARAM) since
* it represents the CePU (which needs to run threaded, too).
* \return The ID of the core, or \ref PN_ERR_MATCH, \ref PN_ERR_PARAM, or
* \ref PN_ERR_COPU.
*/
PN_CID pn_begin_threaded_m(PN_CMSK coremask);
/**
* \fn PN_CID pn_begin_threaded_gm(PN_CMSK *coremask_array,
* PN_NUMG array_size)
* \brief Puts the CPUs specified in the coremask_array in threaded mode.
*
* \internal
* \todo This functions specification depends a lot on ParaNut hardware design.
* In later implementations, using linked and threaded mode in a mixed way might
* be possible. The documentation and implementation will have to be changed,
* then.
* \endinternal
*
* \todo Currently only a stub. Will therefore always return \ref PN_ERR_NOIMP.
*
* Sets the CoPUs represented by bitmask and their position in the array (=
* their group number) to Mode 2 (unlinked Mode) so they start executing the
* following code in parallel. This function will return an error
* (\ref PN_ERR_MATCH) if the CoPUs are not all halted.
*
* See documentation of \ref ms for more information.
*
* Cannot be executed on CoPU. Cannot be mixed with linked mode or other
* begin threaded functions, until \ref pn_end_threaded() is called.
*
* \attention All data that you want to preserve after \ref pn_end_threaded()
* was called can not be stored on stack. You can make it static or global.
*
* \warning There is no guarantee that the execution of code actually happens at
* the same time on CePUs and CoPUs.
*
* \param[in] coremask_array is a pointer to the start of a coremask array. The
* position of the mask in the array represents the group number of
* the cores. When all bits are set to 0, this function will return
* an error (\ref PN_ERR_PARAM) to aid debugging. Also, not setting
* the first bit to 1 will return an error (\ref PN_ERR_PARAM) since
* it represents the CePU (which needs to run threaded, too).
* \param[in] array_size is the number of entries in the coremask_array.
* \return The ID of the core, or \ref PN_ERR_MATCH, \ref PN_ERR_PARAM, or
* \ref PN_ERR_COPU.
*/
PN_CID pn_begin_threaded_gm(PN_CMSK *coremask_array, PN_NUMG array_size);
/**
* \fn int pn_end_threaded(void)
* \brief Ends threaded execution.
*
* On CoPU, halts the core. On CePU, waits until all other cores are halted.
* This ends the threaded mode.
*
* See documentation of \ref ms for more information.
*
* \return Either \ref PN_SUCCESS or \ref PN_ERR_MATCH.
*/
int pn_end_threaded(void);
/**
* \fn PN_CID pn_run_threaded(PN_NUMC numcores, void (*function)(void *args, PN_CID cid), void *args)
* \brief Excutes a given function on the CoPUs specified in numcores
*
* \internal
* \todo This functions specification depends a lot on ParaNut hardware design.
* In later implementations, using linked and threaded mode in a mixed way might
* be possible. The documentation and implementation will have to be changed,
* then.
* \endinternal
*
* Sets numcores-1 CoPUs to Mode 2 (unlinked Mode) they then
* start execting the function provided and halt once completed. This function
* will return an error (\ref PN_ERR_MATCH) if the CoPUs are not all halted.
*
* See documentation of \ref ms for more information.
*
* Cannot be executed on CoPU. Cannot be mixed with linked mode or other
* begin threaded functions. The calling CePU is not informed when the function
* has finished execution. This can be accomplished by monitoring the state of
* CePUs marked in the numcores
*
* \attention All data that you want to preserve can not be stored on stack.
* You can make it static or global.
*
* \warning There is no guarantee that the execution of code actually happens at
* the same time on CePUs and CoPUs.
*
* \param[in] numcores is the number of cores that shall run the function.
* A value of 0 or 1 will return an error (\ref PN_ERR_PARAM) to aid
* debugging.
* \param[in] function pointer to a function, which will be used as entrypoint
* for the started CoPUs. The function must define two parameters:
* void *args - void pointer to hand arguments to the function
* PN_CID cid - core id of the core executing the function
* \param[in] args pointer of type void, that may be used to add arguments to
* the function called. This parameter may be of value NULL.
* \return A mask representing the CePUs started by this functioncall
**/
PN_CMSK pn_run_threaded(PN_NUMC numcores, void (*function)(void *args, PN_CID cid), void *args);
/**
* \fn pn_run_threaded(PN_CMSK coremask, void (*function)(void *args, PN_CID cid), void *argsn)
* \brief Excutes a given function on the CoPUs specified in numcores
*
* \internal
* \todo This functions specification depends a lot on ParaNut hardware design.
* In later implementations, using linked and threaded mode in a mixed way might
* be possible. The documentation and implementation will have to be changed,
* then.
* \endinternal
*
* Sets the CoPUs represented by the bitmask to Mode 2 (unlinked Mode) they then
* start execting the function provided and halt once completed. This function
* will return an error (\ref PN_ERR_MATCH) if the CoPUs are not all halted.
*
* See documentation of \ref ms for more information.
*
* Cannot be executed on CoPU. Cannot be mixed with linked mode or other
* begin threaded functions. The calling CePU is not informed when the function
* has finished execution. This can be accomplished by monitoring the state of
* CePUs marked in the numcores
*
* \attention All data that you want to preserve can not be stored on stack.
* You can make it static or global.
*
* \warning There is no guarantee that the execution of code actually happens at
* the same time on CePUs and CoPUs.
*
* \param[in] coremask is the bitmask representing the CoPUs you want to run
* threaded. When all bits are set to 0, this function will return
* an error (\ref PN_ERR_PARAM) to aid debugging. Also, not setting
* the first bit to 1 will return an error (\ref PN_ERR_PARAM) since
* it represents the CePU (which needs to run threaded, too).
* \param[in] function pointer to a function, which will be used as entrypoint
* for the started CoPUs. The function must define two parameters:
* void *args - void pointer to hand arguments to the function
* PN_CID cid - core id of the core executing the function
.
* \param[in] args pointer of type void, that may be used to add arguments to
* the function called. This parameter may be of value NULL.
* \return The ID of the core, or \ref PN_ERR_MATCH, \ref PN_ERR_PARAM, or
* \ref PN_ERR_COPU.
*/
PN_CMSK pn_run_threaded_m(PN_CMSK coremask, void (*function)(void *args, PN_CID cid), void *args);
/**
* \fn pn_join_thread_m(PN_CMSK coremask, uint32_t timeout)
* \brief Waits until a specified set of CePUs is stopped
*
* \internal
* \todo This functions specification depends a lot on ParaNut hardware design.
* In later implementations, using linked and threaded mode in a mixed way might
* be possible. The documentation and implementation will have to be changed,
* then.
* \endinternal
*
* Wait a maximum of timeout ms for CePUs defined in coremask to be stopped.
* If the timeout is exceeded, the CePUs ARE NOT FORCED TO STOP. If this behaviour
* is desired, it must be implemented in the calling function (e.g. add a
* pn_end_threaded) to the next line. Timeout may be 0, meaning the function
* will run indefinatly
*
* \attention This is a blocking function. It is strongly advised always
* to specify a timeout.
*
* \warning There is no guarantee that the execution of code actually happens at
* the same time on CePUs and CoPUs.
*
* \param[in] coremask is the bitmask representing the CoPUs you want to run
* threaded. When all bits are set to 0, this function will return
* an error (\ref PN_ERR_PARAM) to aid debugging. Also, not setting
* the first bit to 1 will return an error (\ref PN_ERR_PARAM) since
* it represents the CePU (which needs to run threaded, too).
* \return The ID of the core(s) stopped, or PN_ERR_COPU.
*/
PN_CMSK pn_join_thread_m(PN_CMSK coremask, uint32_t timeout);
/**
* @}
*/
/**
* @}
*/
/*Cache Module*****************************************************************/
/**
* \defgroup ca Cache Module
*
* \brief Special functions for controlling the shared ParaNut cache.
*
* \internal
*
* If you want to see how to add a new cache line size, check
* \ref PN_ERR_CACHE_LINESIZE.
*
* \todo May need some changes in the future when ParaNut cores get some cache
* on their own or a proper cache controller is implemented.
* \todo Virtual addressing is not implemented in the current ParaNut
* implementation, but may be featured later on. When the day comes, put in a
* physical address calculation in the implementation of these functions.
* \endinternal
*/
/**
* \addtogroup ca
* @{
*/
/**
* @{
*/
/**
* \fn int pn_cache_init(void)
* \brief Function that has to be called in the main function before any
* of the functions in the \ref ca can be called. Initializes some
* internal data and enables the cache.
*
* Can only be used on CePU.
*
* \return Either \ref PN_SUCCESS, \ref PN_ERR_COPU, or
* \ref PN_CACHE_LINESIZE.
*/
int pn_cache_init(void);
/**
* \fn int pn_cache_enable(void)
* \brief Enables instruction and data cache. When changing this, make sure
* that the \ref pn_cache_init() function is still correct!
*
* \attention Careful here: ParaNut Cache is flushed completely before
* disabling.
*
* Can only be used on CePU.
*
* \return Either \ref PN_SUCCESS or \ref PN_ERR_COPU.
*/
int pn_cache_enable(void);
/**
* \fn int pn_cache_disable(void)
* \brief Disables instruction and data cache.
*
* \attention Careful here: ParaNut Cache is flushed completely before
* disabling.
*
* \warning Atomic memory operations (\ref sp) are not possible on a disabled
* cache.
*
* Can only be used on CePU.
*
* \return Either \ref PN_SUCCESS or \ref PN_ERR_COPU.
*/
int pn_cache_disable(void);
/**
* \fn unsigned long pn_cache_linesize(void)
* \brief Returns the cache line size in bit.
*
* \return The cache line size in bit. Can not return an error.
*/
unsigned long pn_cache_linesize(void);
/**
* \fn unsigned long pn_cache_size(void)
* \brief Returns the cache size in Byte.
*
* \return The cache size in byte. Can not return an error.
*/
unsigned long pn_cache_size(void);
/**
* \fn int pn_cache_invalidate(void *addr, unsigned long size)
* \brief Invalidates the cache entries containing the given address range.
*
* \param[in] addr is the (virtual) start address of the memory you want to
* invalidate.
* \param[in] size is the size of the address range you want to invalidate in
* byte. The size will always be aligned to the cache line size.
* \return Either \ref PN_SUCCESS or \ref PN_ERR_PARAM if given size is
* bigger than memory size.
*/
int pn_cache_invalidate(void *addr, unsigned long size);
/**
* \fn int pn_cache_invalidate_all(void)
* \brief Invalidates the whole cache. When changing this, make sure that
* the \ref pn_cache_init() function is still correct!
* \return Can only return \ref PN_SUCCESS, is not made void for the sake of
* making the internal implementation more similar for cache
* functions.
*/
int pn_cache_invalidate_all(void);
/**
* \fn int pn_cache_writeback(void *addr, unsigned long size)
* \brief Writes back the cache lines that cached the given address range.
*
* \param[in] addr is the (virtual) start address of the memory you want
* written back.
* \param[in] size is the size of the address range you want written back in
* byte. The size will always be aligned to the cache line size.
* \return Either \ref PN_SUCCESS or \ref PN_ERR_PARAM if given size is
* bigger than memory size.
*/
int pn_cache_writeback(void *addr, unsigned long size);
/**
* \fn int pn_cache_writeback_all(void)
* \brief Writes whole cache back.
* \return Can only return \ref PN_SUCCESS, is not made void for the sake of
* making the internal implementation more similar for cache
* functions.
*/
int pn_cache_writeback_all(void);
/**
* \fn int pn_cache_flush(void *addr, unsigned long size)
* \brief Combination of \ref pn_cache_invalidate() and \ref
* pn_cache_writeback().
*
* \param[in] addr is the (virtual)start address of the memory you want
* flushed.
* \param[in] size is the size of the address range you want flushed in
* byte. The size will always be aligned to the cache line size.
* \return Either \ref PN_SUCCESS or \ref PN_ERR_PARAM if given size is
* bigger than memory size.
*/
int pn_cache_flush(void *addr, unsigned long size);
/**
* \fn int pn_cache_flush_all(void)
* \brief Flushes the whole cache.
* \return Can only return \ref PN_SUCCESS, is not made void for the sake of
* making the internal implementation more similar for cache
* functions.
*/
int pn_cache_flush_all(void);
/**
* @}
*/
/**
* @}
*/
/*Exception Module*************************************************************/
/**
* \defgroup ex Exception Module
*
* \brief Functions for controlling the handling of interrupts/exceptions.
*
* Why are we calling this exceptions, even though most people would call this
* an interrupt? Historic reasons. The libparanut was first written for the
* RISCV implementation of the ParaNut, and the RISCV specification refers to
* both interrupts and exceptions as exceptions.
*
* \internal
* \todo All of these functions may be too RISCV specific to ever use them on
* another architecture. I have not done more research on this topic yet. If
* that's the case, we might even need to add architecture specific .c files
* for this module. I would name them pn_cache_RV32I.c, pn_cache_RV64I.c, and so
* on. The Makefile and Documentation will probably need some changes then.
*
* Also, when the ParaNut has a more advanced mstatus register, the
* API implementation of the \ref pn_interrupt_enable() and
* \ref pn_interrupt_disable() functions has to change.
* \endinternal
*/
/**
* \addtogroup ex
* @{
*/
/**
* @{
*/
/**
* \fn void pn_exception_init(void)
* \brief Initializes libparanut internal exception handling. Interrupts
* (not exceptions in general!) are disabled after. Should be
* called before using \ref pn_exception_set_handler().
*/
void pn_exception_init(void);
/**
* \fn int pn_exception_set_handler(
* void (*handler)(
* unsigned int cause,
* unsigned int program_counter,
* unsigned int mtval),
* unsigned int exception_code
* )
* \brief Set your own exception handler.
*
* Can be called without using \ref pn_exception_init() first, will not work
* though.
*
* Already does the work of saving away registers, setting program counter etc.
* for you. You can just hang in what you want to do.
*
* \attention For exceptions, the register that contains the adress where
* execution resumes is set to the faulty instruction that threw the exception.
* For interrupts, it already points to the instruction where execution should
* resume. Consider this in your handler. If you need to, use
* \ref pn_progress_mepc.
*
* \param[in] handler is a function pointer to your exception handler. Will
* return an error (\ref PN_ERR_PARAM) if NULL is given.
* \param[in] exception_code is the number that your exception has. You can
* look up the exception codes in the ParaNut Manual. For
* interrupts, the value of the most significant bit of the
* exception code has to be 1. For synchronous exceptions, it has
* to be 0. This function will return an error (\ref PN_ERR_EXC) if
* a non implemented value for cause is given.
* \return Either \ref PN_SUCCESS, \ref PN_ERR_EXC, or \ref PN_ERR_PARAM.
*/
int pn_exception_set_handler(
void (*handler)(
unsigned int cause,
unsigned int program_counter,
unsigned int mtval),
unsigned int exception_code
);
/**
* \fn void pn_ecall(void)
* \brief Raises an environment call exception.
*
* Can be called without using \ref pn_exception_init() first.
*/
void pn_ecall(void);
/**
* \fn void pn_interrupt_enable(void)
* \brief Enables interrupts only.
*
* Can be called without using \ref pn_exception_init() first.
*/
void pn_interrupt_enable(void);
/**
* \fn void pn_interrupt_disable(void)
* \brief Disables interrupts only.
*
* Can be called without using \ref pn_exception_init() first.
*/
void pn_interrupt_disable(void);
/**
* \fn void pn_progress_mepc(void)
* \brief Sets program counter of the register which keeps the exception
* return adress to next instruction.
*
* Can be called without using \ref pn_exception_init() first.
*/
void pn_progress_mepc(void);
/**
* @}
*/
/**
* @}
*/
/*Spinlock Module**************************************************************/
/**
* \defgroup sp Spinlock Module
* \brief Functions and structure used for synchronizing memory access.
*
* \warning
* The functions in here are really kinda performance critical, since it is
* always important to do as little as possible when you have reserved a
* memory area. This means that the functions will do extremly little security
* checks, which means you have to use them the way they are described.
* Read the detailed descriptions of the functions carefully. Or don't. I'm not
* the coding police.
*
* \warning
* Using the spinlock functions in linked Mode (see \ref li and \ref ms) results
* in undefined behaviour.
*
* \warning
* If you want to use the Spinlock Module on RISC-V ParaNut, your ParaNut has to
* support the A Extension and you have to compile your application with the
* flag mabi=rv32ia. The libparanut \ref Makefile sets this flag automatically
* when you chose the \ref sp or one of the Modules that has \ref sp as a
* dependency.
*
* Return value of functions is always error code, except when stated otherwise
* in the description of the function.
*/
/**
* \addtogroup sp
* @{
*/
/**
* \struct __pn_spinlock
* \brief A synchronization primitive. Use \ref _pn_spinlock instead of
* this.
*
* A simple implementation of a synchronization primitive. Might be used for
* implementing POSIX Threads later on.
*
* \warning
* You are not supposed to touch anything in this struct, which is why you can't
* see anything about the members in this documentation.
*
* \attention I highly recommend to not put locks on stack. The reason is that
* the stack (or at least a part of it) will be copied when putting the ParaNut
* into threaded Mode (see \ref pn_begin_threaded()). In other words, if you
* put a lock on stack, it will be copied, and the new instances of the lock
* will be available per core. You should make it static, global or get
* the memory by allocation.
*
* \warning Atomic memory operations are not possible on a disabled cache.
*
* \internal Note for other architectures: Check your ABI on how structs are
* aligned and what data size integer type has. On RV32I GCC, I have no problems
* with this, since int size is 4 bytes, PN_CID is just int32 (also 4 bytes),
* and ABI convention says that int is aligned at 4 bytes. I assume that GCC
* uses the convention, but switching to an obscure compiler could destroy that.
* So the stuff in here for GCC can just be treated as lying right behind each
* other in 4 bytes of memory, which is convenient for me. It should work on
* all other compilers using the ABI convention, but I just didn't want this to
* go unsaid.
*/
typedef struct __pn_spinlock
{
PN_CID owner_ID; /**< \internal ID of the CPU that owns me. Can also be
* negative to represent statuses free (not
* locked by anyone) or dead (not initialized).
*/
} _pn_spinlock;
/**
* @{
*/
/**
* \fn int pn_spinlock_init(_pn_spinlock *spinlock)
* \brief Creates a lock.
*
* You allocate the space for the spinlock. Really don't care where you get it
* from (check \ref __pn_spinlock for a recommendation). You pass a reference to
* this function, and the function initializes it for you. And you shall never
* touch what's in it.
*
* Afterwards, you can use the other functions in this module on the same lock.
* Behaviour will always be undefined if you don't call this function first.
*
* The function does not care if your lock was already initialized. It will fail
* if the CPU did not get the memory reservation (\ref PN_ERR_LOCKOCC), which
* should never happen. This is a very good indicator that something is very
* wrong with your program.
*
* After initialization, the lock is free. It will not be automatically owned by
* the hart that initialized it.
*
* \param spinlock is a pointer to the lock. The function will return
* \ref PN_ERR_PARAM if NULL is passed.
* \return Either \ref PN_SUCCESS, \ref PN_ERR_PARAM, or
* \ref PN_ERR_LOCKOCC. If something internally went very wrong, the
* function is also theoretically able to return \ref PN_ERR_NOIMP.
*/
int pn_spinlock_init(_pn_spinlock *spinlock);
/**
* \fn int pn_spinlock_lock(_pn_spinlock *spinlock)
* \brief Waits for a lock. Forever, if it must. Use with caution.
*
* Behaviour of this function is undefined if the lock wasn't initialized by
* \ref pn_spinlock_init().
*
* \warning
* The function will be stuck in eternity if the lock is already in the current
* harts posession, or if someone else owns the lock and forgot to unlock it, or
* if the lock was destroyed.
*
* \param spinlock is a pointer to a lock that we want to aquire. The
* function will return \ref PN_ERR_PARAM if NULL is passed.
* \return Either \ref PN_SUCCESS or \ref PN_ERR_PARAM.
*/
int pn_spinlock_lock(_pn_spinlock *spinlock);
/**
* \fn int pn_spinlock_trylock(_pn_spinlock *spinlock);
* \brief Tries to acquire a lock. Nonblocking.
*
* Behaviour of this function is undefined if the lock wasn't initialized by
* \ref pn_spinlock_init().
*
* Will fail if lock is already owned (no matter by whom), another CPU got the
* memory reservation, or if lock was destroyed.
*
* \param spinlock is a pointer to a lock that we want to aquire. The
* function will return \ref PN_ERR_PARAM if NULL is passed.
* \return Either \ref PN_SUCCESS, \ref PN_ERR_LOCKOCC or \ref PN_ERR_PARAM.
* If something internally went very wrong, the
* function is also theoretically able to return \ref PN_ERR_NOIMP.
*/
int pn_spinlock_trylock(_pn_spinlock *spinlock);
/**
* \fn int pn_spinlock_unlock(_pn_spinlock *spinlock)
* \brief Unlocks a lock.
*
* Behaviour of this function is undefined if the lock wasn't initialized by
* \ref pn_spinlock_init().
*
* Will fail is lock is not owned by current hart (\ref PN_ERR_PARAM).
*
* \param spinlock is a pointer to a lock that we want to unlock. The
* function will return \ref PN_ERR_PARAM if NULL is passed.
* \return Either \ref PN_SUCCESS or \ref PN_ERR_PARAM.
* If something internally went very wrong, the
* function is also theoretically able to return \ref PN_ERR_NOIMP.
*/
int pn_spinlock_unlock(_pn_spinlock *spinlock);
/**
* \fn int pn_spinlock_destroy(_pn_spinlock *spinlock)
* \brief Destroys a lock.
*
* Behaviour of this function is undefined if the lock wasn't initialized by
* \ref pn_spinlock_init().
*
* A destroyed lock can be re-initialized by using \ref pn_spinlock_init().
*
* The lock can either be owned by current hart or unlocked, else the function
* will fail.
*
* \param spinlock is a pointer to a lock that we want to destroy. The
* function will return \ref PN_ERR_PARAM if NULL is passed.
* \return Either \ref PN_SUCCESS, \ref PN_ERR_LOCKOCC or \ref PN_ERR_PARAM.
* If something internally went very wrong, the
* function is also theoretically able to return \ref PN_ERR_NOIMP.
*/
int pn_spinlock_destroy(_pn_spinlock *spinlock);
/**
* \internal
* \var sp_loc
* \brief Stack Pointer location, used by \ref set_linked_as() and
* \ref set_threaded_as().
*/
extern int sp_loc;
/**
* \internal
* \var tp_loc
* \brief Thread Pointer location, used in \ref th.
*/
extern int tp_loc;
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#endif //#endif PARANUT_H
/*EOF**************************************************************************/
|
C
|
#include <stdio.h>
// global var
int g;
int scopeDemo() {
// local var
int a, b;
a = 10;
b = 20;
g = a + b;
// int g = 50; if local var and global var has a same name, local var is preferred
printf("Value of a = %d, b = %d and g = %d\n", a, b, g);
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* precision_width.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: lazrossi <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/06/25 09:13:25 by lazrossi #+# #+# */
/* Updated: 2018/07/24 18:56:29 by lazrossi ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
void apply_flag_padding(t_printf *argument_specs, t_str *argument_str)
{
char fill;
fill = (argument_specs->precision < argument_specs->width &&
argument_specs->precision != -1) ? ' ' : '0';
if (argument_specs->arg_len >= argument_specs->width)
return ;
if (!((*argument_specs).left_align_output))
{
if (ft_strchr("dDioOuUxX", argument_specs->type) &&
argument_specs->sign[0] && fill == '0')
{
update_str(argument_str, (void*)&argument_specs->sign[0], 1);
update_str(argument_str, (void*)&fill, 1);
return ;
}
update_str(argument_str, (void*)&fill, 1);
update_str(argument_str, (void*)&argument_specs->sign[0], 1);
}
}
void apply_plus_minus_flags(t_printf *argument_specs, t_str *argument_str)
{
if (!(argument_specs->type))
return ;
if (ft_strchr("cCsOouS", argument_specs->type))
return ;
update_str(argument_str, (void*)&argument_specs->show_sign, 1);
}
void apply_precision(t_printf *argument_specs, t_str *argument_str)
{
char fill;
int i;
fill = '0';
i = 0;
if (!(argument_specs->type))
return ;
if (argument_specs->precision && argument_specs->type == 'o'
&& argument_specs->sharp && argument_specs->arg_len)
argument_specs->precision--;
if (argument_specs->precision <= argument_specs->arg_len)
return ;
while (i++ < argument_specs->precision - argument_specs->arg_len)
update_str(argument_str, (void*)&fill, 1);
}
void apply_sharp(t_printf *argument_specs, t_str *argument_str)
{
char fill;
fill = '0';
if (ft_strchr("cCsC", argument_specs->type))
return ;
if (!argument_specs->type)
return ;
update_str(argument_str, (void*)&fill, 1);
if (ft_strchr("xXp", argument_specs->type))
{
fill = (argument_specs->type == 'X') ? 'X' : 'x';
update_str(argument_str, (void*)&fill, 1);
}
}
|
C
|
#include <stdio.h>
int sumArray(int * array, int size)
{
int sum = 0;
int i;
for(i=0;i<size;i++)
{
sum += *(array+i);
}
return sum;
}
void block(int n, char a, char b)
{
char current = a;
int height;
int row;
for(height = 0; height<n;height++)
{
for(row=0;row<n;row++)
{
printf("%c",current);
}
if(current==b)
{
current=a;
}
else
{
current = b;
}
for(row=0;row<n;row++)
{
printf("%c",current);
}
printf("\n");
}
}
int main(int argc, char *argv[])
{
int a[] = {1,2,3};
int ans = sumArray(a,3);
//printf("%d", ans);
block(10,'@','$');
}
|
C
|
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <sys/sysmacros.h>
#define KEYPAD_MAJOR_NUMBER 505
#define KEYPAD_MINOR_NUMBER 105
#define KEYPAD_DEV_PATH_NAME "/dev/keypad_dev"
int output0 =-1;
int output1 =-1;
int output2 =-1;
int output3 =-1;
int main(void)
{
dev_t keypad_dev;
int fd;
int line;
int index = -1;
char characters[13] = {'0',};
int result=0;
keypad_dev = makedev(KEYPAD_MAJOR_NUMBER, KEYPAD_MINOR_NUMBER);
mknod(KEYPAD_DEV_PATH_NAME, S_IFCHR|0666, keypad_dev);
fd = open(KEYPAD_DEV_PATH_NAME, O_RDWR);
if(fd < 0) {
printf("fail to open keypad\n");
return -1;
}
while(1) {
line = 2;
write(fd, &line, sizeof(int));
read(fd, &index, sizeof(int));
if(index != -1) {
if(index !=output0){
characters[0] = '1';
characters[1] = '2';
characters[2] = '3';
printf("line 2 : %c\n", characters[index]);
result = result*10+(characters[index]-'0');
printf("%d\n",result);
output0 = index;
}
}
sleep(0.5);
line = 7;
write(fd, &line, sizeof(int));
read(fd, &index, sizeof(int));
if(index != -1) {
if(index !=output1){
characters[3] = '4';
characters[4] = '5';
characters[5] = '6';
printf("line 7 :%c\n", characters[index+3]);
result = result*10+(characters[index+3]-'0');
printf("%d\n",result);
output1 = index;
}
}
sleep(0.5);
line = 6;
write(fd, &line, sizeof(int));
read(fd, &index, sizeof(int));
if(index != -1) {
if(index !=output2){
characters[6] = '7';
characters[7] = '8';
characters[8] = '9';
printf("line 6 : %c\n", characters[index+6]);
result = result*10+(characters[index+6]-'0');
printf("%d\n",result);
output2 = index;
}
}
sleep(0.5);
line = 4;
write(fd, &line, sizeof(int));
read(fd, &index, sizeof(int));
if(index != -1) {
if(index !=output3){
characters[9] = '*';
characters[10] = '0';
characters[11] = '#';
printf("line 4 : %c\n", characters[index+9]);
result = result*10+(characters[index+9]-'0');
printf("%d\n",result);
output3 = index;
}
}
sleep(0.5);
}
close(fd);
return 0;
}
|
C
|
#include <complex.h>
#include <stdio.h>
int main(void){
double complex z = 0.5 + 0.5I;
double complex w = 0.5 - 0.5I;
double complex s = z + w;
double complex p = z * w;
double complex q = z / w;
fprintf(stderr, " z = %f + %fi\n", creal(z), cimag(z));
fprintf(stderr, "|z| = %f\n", cabs(z));
fprintf(stderr, " w = %f + %fi\n", creal(w), cimag(w));
fprintf(stderr, " s = %f + %fi\n", creal(s), cimag(s));
fprintf(stderr, " p = %f + %fi\n", creal(p), cimag(p));
fprintf(stderr, " q = %f + %fi\n", creal(q), cimag(q));
return 0;
}
|
C
|
#include <iostream>
using namespace std;
int main(){
float aloha[10], coisas[10][5], *pf, value = 2.2;
int i=3;
aloha[2] = value;
scanf("%f", &aloha);
aloha = "value"; // Erro de tipo, enquanto aloha é um número flutuante "value" é uma string do tipo char.
printf("%f", aloha);
coisas[4][4] = aloha[3];
coisas[5] = aloha; // Erro de semântica INVÁLIDO
pf = value; //Erro de tipo, enquanto 'pf' é um ponteiro, 'value' é um float.
pf = aloha;
}
|
C
|
#include <avr/io.h>
#include <avr/interrupt.h>
//256 count = 64 us >> 4 count for each us so we need 4*13 = 52 for 13us
// global variable to count the number of overflows
volatile uint8_t tot_overflow;
// initialize timer, interrupt and variable
void timer0_init()
{
// set up timer with prescaler = 1
TCCR0 |= (1 << CS00);
// initialize counter
TCNT0 = 204;
// enable overflow interrupt
TIMSK |= (1 << TOIE0);
// enable global interrupts
sei();
// initialize overflow counter variable
tot_overflow = 0;
}
// TIMER0 overflow interrupt service routine
// called whenever TCNT0 overflows
ISR(TIMER0_OVF_vect)
{
// keep a track of number of overflows
//tot_overflow++;
PORTB ^= (1 << 0); // toggles the led
TCNT0 = 204; // reset counter
}
int main(void)
{
// connect led to pin PB0
DDRB |= (1 << 0);
// initialize timer
timer0_init();
// loop forever
while(1)
{
/* // check if no. of overflows = 12
if (tot_overflow >= 12) // NOTE: '>=' is used
{
// check if the timer count reaches 53
if (TCNT0 >= 53)
{
PORTC ^= (1 << 0); // toggles the led
TCNT0 = 0; // reset counter
tot_overflow = 0; // reset overflow counter
}
} */
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <unistd.h>
#define BUFSIZE 1024
int main(int argc, char* argv[]){
fd_set fds;
int i;
//コマンドライン引数の個数の検査と説明
if (argc != 4)
{
printf("Usage : %s [IPv4_Addr] [port] [your username]\n", argv[0]);
exit(1);
}
printf("executed command: ");
for(i = 0; i < argc; i++){
printf("%s ", argv[i]);
}
printf("\n");
// -------------------
// TCPソケットの作成
// -------------------
int s;
// ソケットの作成および生成の成否確認
// sはソケット識別番号>0
if ((s = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
fprintf(stderr, "[ ! ] Failed to create socket.\n");
exit(1);
}
printf("[ + ] Socket created successfully : %d\n", s);
// -----------------------------
// コネクションの確立および成否確認
// -----------------------------
char *address = argv[1];
struct sockaddr_in server_addr;
memset((char *)&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = inet_addr(address);
//port番号の設定および検査
int port;
port = atoi(argv[2]);
if (port <= 0 && port > 65535)
{
printf("[ ! ] Irregal port number : \"%s\"\n", argv[2]);
exit(1);
}
server_addr.sin_port = htons(port);
int n;
//コネクションの確立と失敗時の対応
if (connect(s, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0)
{
fprintf(stderr, "[ ! ] Failed to establish connection to %s:%d.\n", argv[1], port);
exit(1);
}
printf("[ + ] Connection established to %s:%d successfully.\n", argv[1], port);
//ニックネーム送信と失敗時の対応
char nickname[BUFSIZE];
strcpy(nickname, argv[3]);
int nickname_len = strlen(nickname);
if((n = send(s, nickname, nickname_len, 0)) != nickname_len){
fprintf(stderr, "[ ! ] Failed to send a message of your nickname: \"%s\"\n", nickname);
exit(1);
}
printf("[ + ] Sended a message of your nickname successfully: \"%s\"\n", nickname);
printf("[ + ] Now you can write and send arbitrary message here!\n");
char readbuf[BUFSIZE];
char stdinbuf[BUFSIZE];
int ret;
bool is_restricted_in;
while(1){
FD_ZERO(&fds);
FD_SET(s, &fds);
FD_SET(0, &fds);
//監視対象のfdに受信があるまで待機
if((n = select(FD_SETSIZE, &fds, NULL, NULL, NULL)) == -1){
perror("select"); fprintf(stderr, "select() error\n"); exit(1);
}
//自分のソケット用fdに受信があった (他サーバからチャットメッセージを受け取った) 場合
if(FD_ISSET(s, &fds)){
bzero(readbuf, sizeof(readbuf));
ret = read(s, readbuf, BUFSIZE);
printf("%s", readbuf);
}
//標準入力があった場合, 読み込む
if(FD_ISSET(0, &fds)){
bzero(stdinbuf, sizeof(stdinbuf));
fgets(stdinbuf, BUFSIZE, stdin);
write(s, stdinbuf, BUFSIZE);
}
}
return 0;
}
|
C
|
#include <stdio.h>
#include <unistd.h>
int my_strlen2(char const *str)
{
int len = 0;
while((*str++))
{
len++;
}
return len;
}
int my_compute_power_rec(int nb, int p)
{
int res;
if (p==0)
res = 1;
if (p < 0)
res = 0;
if (p > 0)
{
res = my_compute_power_rec(nb,p-1)*nb;
}
return res;
}
int my_putchar(char);
int my_getnbr_base(char const *str , char const *base)
{
int n = my_strlen2(base);
int i;
int j = my_strlen2(str);
long c = 0;
int flag = 1;
int a = 0;
if(str == NULL || base == NULL || n == 0 || j == 0)
{
return 0;
}
for(i = 0; base[i] != '\0'; i++)
{
int f = 1;
for(int k = 0; k < i; k++)
{
if(base[i] == base[k])
{
return 0;
}
}
}
while(str[a] == '-' || str[a] == '+')
{
if(str[a] == '-')
flag = flag * -1;
a++;
}
if(flag == -1)
my_putchar("-");
for(i = j - 1, j = 0; i >= a; i--, j++)
{
int tmp;
if(str[i] >= '0' && str[i] <= '9')
tmp = (str[i]-'0');
else
tmp = (str[i]-'A')+10;
c=c+(long)(tmp *my_compute_power_rec(n ,j));
}
if(c < -2147483648 || c > 2147483647)
{
return 0;
}
return c;
}
|
C
|
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include "spn.h"
const unsigned int crackKey = 0x3a94d63f;
typedef struct {
char x[sNum], y[sNum];
int keyNum;
int pairNum;
double bias;
spn_Text in;
}chain;
char approxTable[16][16];
char bitXor(char num);
int printb(int value, int quadbit);
void calcApprox();
void printApprox();
chain findChain_linear();
void findKey_linear(chain linear_chain);
int keyCracker(spn_Text *p1, spn_Text *p2, int n);
int main()
{
int i;
char op;
chain linear_chain;
spn_Text *pp, *cp;
spn_Text plain, cypher;
spn_Init();
spn_SetKey(crackKey);
calcApprox();
while (1) {
system("cls");
printApprox();
linear_chain = findChain_linear();
printf("Run linear analysis. (y/n) :");
scanf("%c", &op);
getchar();
switch (op) {
case 'y': case 'Y':
findKey_linear(linear_chain);
pp = (spn_Text*)malloc(sizeof(spn_Text) * 5);
cp = (spn_Text*)malloc(sizeof(spn_Text) * 5);
for (i = 0; i < 5; i++) {
plain = rand();
cypher = spn_Encrypt_raw(&plain, &cypher);
pp[i] = plain;
cp[i] = cypher;
}
printf("Brute force crack >>>\n");
keyCracker(pp, cp, 5);
break;
case 'n': case 'N':
break;
}
getchar();
}
}
int keyCracker(spn_Text *p1, spn_Text *p2, int num)
{
clock_t t1, t2;
int i, j, mark;
MainKey key;
spn_Text temp;
t1 = clock();
for (i = (int)pow(2, 24); i >= 0; i--) {
key = ((i & 0xf) << 4) ^ ((i >> 4) << 12) ^ 0x60f;
spn_SetKey(key);
for (j = 0; j < num; j++) {
spn_Encrypt_raw(p1 + j, &temp);
if (temp == *(p2 + j)) {
mark = 1;
continue;
}
else {
mark = 0;
break;
}
}
if (mark)
break;
}
t2 = clock();
printf("Key : %x\n", key);
printf("time consumed : %ld ms", t2 - t1);
getchar();
}
void calcApprox()
{
char a, b;
char x, y;
for (a = 0; a < pow(2, sBits); a++)
for (b = 0; b < pow(2, sBits); b++)
approxTable[a][b] = 0;
for (a = 0; a < pow(2, sBits); a++)
for (b = 0; b < pow(2, sBits); b++)
for (x = 0; x < pow(2, sBits); x++)
{
y = SBox(x, spn_Sub);
if (bitXor(a & x) == bitXor(b & y))
approxTable[a][b]++;
}
}
void printApprox()
{
char a, b;
printf("Linear Approximation Table:\n");
printf("\na\\b|");
for (b = 0; b < pow(2, sBits); b++)
printf("%3X", b);
printf("\n");
for (b = 0; b < 3 * pow(2, sBits) + 4; b++)
{
if (b == 3)
{
printf("|");
continue;
}
printf("-");
}
printf("\n");
for (a = 0; a < pow(2, sBits); a++)
{
printf("%3X|", a);
for (b = 0; b < pow(2, sBits); b++)
{
printf("%3d", approxTable[a][b]);
}
printf("\n");
}
}
char bitXor(char num)
{
return (num & 0x1) ^ ((num & 0x2) >> 1) ^ ((num & 0x4) >> 2) ^ ((num & 0x8) >> 3) ^
(num & 0x10) ^ ((num & 0x20) >> 4) ^ ((num & 0x40) >> 5) ^ ((num & 0x80) >> 6);
}
int printb(int value, int quadbit)
{
int i;
for (i = 0; i < 4 * quadbit; i++) {
if ((i % 4 == 0) && (i != 0))
printf(" | ");
printf("%d", (value >> (4 * quadbit - i - 1)) & 0x1);
}
printf("\n");
return 0;
}
chain findChain_linear()
{
int sId; //1234
int r;
int c;
double bias;
char smark[sNum];
spn_Text u, v, x, y;
spn_Text sIn[RoundNum - 1][sNum], sOut[RoundNum - 1][sNum];
chain linear_chain;
printf("Select an Initial Input : ");
scanf("%hx", &x);
getchar();
u = x;
bias = 1;
//逐轮搜索找到最大spn逼近
for (r = 0; r < RoundNum - 1; r++) {
printf("\nRound %d\n", r + 1);
printf("Probability bias now is : %lf\n", bias / 2);
printf("--------------------------------\n");
printf("...In Vectors : ");
printb(u, 4);
//标记活动的s盒
printf("...Active S-Box : ");
for (sId = sNum - 1; sId >= 0; sId--) {
sIn[r][sId] = (u >> sId * 4) & 0xf; //对u进行拆分 3210
if ((u & (0xf << (sId * 4))) != 0) {
smark[sId] = 1;
printf("| S%d |", 4 - sId); //转换为大端显示
}
else
smark[sId] = 0;
}
printf("\n");
//对活动的s盒寻找最大线性逼近
v = 0;
for (sId = sNum - 1; sId >= 0; sId--) {
if (smark[sId] == 0) {
sOut[r][sId] = 0; //3210
continue;
}
else {
printf("......Select Out Vector for S%d: ", 4 - sId);
scanf("%hx", &sOut[r][sId]);
getchar();
v = v ^ (sOut[r][sId] << sId * 4);
bias = 2 * bias * (approxTable[sIn[r][sId]][sOut[r][sId]] - 8) / 16; //线性链的概率偏差
}
}
//根据选择的s盒输出P置换得到下一轮的随机变量输入
u = Permutation(v, spn_Per);
printf("...Out Vectors : ");
printb(v, 4);
printf("...Next Round In: ");
printb(u, 4);
printf("--------------------------------\n");
}
y = u;
c = 0;
for (sId = 0; sId < sNum; sId++) {
linear_chain.x[sId] = sIn[0][sId];
linear_chain.y[sId] = (y >> sId * 4) & 0xf;
if (u & (0xf << 4 * sId))
c++; //统计影响的密钥比特
}
linear_chain.bias = bias / 2;
linear_chain.keyNum = c;
linear_chain.pairNum = 1000 + (double)linear_chain.keyNum * 4 * pow(linear_chain.bias, -2);
printf("Linear Approximation Chain : \n");
printf("--------------------------------\n");
printf("In : ");
printb(x, 4);
printf("Out : ");
printb(y, 4);
printf("Probability Bias : %lf\n", linear_chain.bias);
printf("Affected Key Bits : %d bit\n", linear_chain.keyNum * 4);
printf("Known Plain/Cypher sample required : %d pairs", linear_chain.pairNum);
getchar();
return linear_chain;
}
void findKey_linear(chain linear_chain)
{
int i, j;
int *counter; //候选密钥计数器指针
int key, maxcount, maxkey;
char *u, *v;
char *mark;
char z;
clock_t t1, t2;
spn_Text plain, cypher;
u = (char*)malloc(sizeof(char) * linear_chain.keyNum);
v = (char*)malloc(sizeof(char) * linear_chain.keyNum);
mark = (char*)malloc(sizeof(char) * linear_chain.keyNum);
counter = (int*)malloc(sizeof(int) * pow(2, 4 * linear_chain.keyNum));
//分配并初始化密钥计数器
for (i = 0; i < pow(2, 4 * linear_chain.keyNum); i++)
counter[i] = 0;
//v/u下标与实际位置的关系
for (i = 0, j = 0; i < sNum; i++)
if (linear_chain.y[i] != 0)
mark[j++] = i; //3210
srand(time(0));
//测试pairNum个明密文对
t1 = clock();
for (i = 0; i < linear_chain.pairNum; i++) {
plain = rand() % 0xffff; //生成16bit的随机明文
spn_Encrypt_raw(&plain, &cypher);
//测试候选密钥
for (key = 0; key < pow(2, 4 * linear_chain.keyNum); key++) {
z = 0;
for (j = 0; j < linear_chain.keyNum; j++) {
v[j] = ((cypher >> 4 * mark[j]) ^ (key >> 4 * j)) & 0xf;
u[j] = SBox(v[j], spn_rSub);
z = z ^ bitXor(u[j] & linear_chain.y[mark[j]]);
}
for (j = 0; j < sNum; j++)
z = z ^ bitXor(linear_chain.x[j] & (plain >> (4 * j)));
if (z == 0)
counter[key]++;
}
}
//遍历计数器寻找T/2最大偏移量
maxcount = 0;
for (key = 0; key < pow(2, 4 * linear_chain.keyNum); key++) {
counter[key] = abs(counter[key] - linear_chain.pairNum / 2);
if (counter[key] > maxcount)
{
maxcount = counter[key];
maxkey = key;
}
}
t2 = clock();
for (i = 0; i <= RoundNum; i++)
printf("...roundKey[%d] = %#x\n", i + 1, spn_Key->roundKey[i]);
for (i = linear_chain.keyNum - 1; i >= 0; i--) {
printf("k%d = %x\t", 4 - mark[i], (maxkey >> i * 4) & 0xf);
}
printf("\ntime consumed : %ld ms", t2 -t1);
getchar();
}
|
C
|
#include "stdc.h"
void *memset(void *str, int c, size_t n){
unsigned char* buffer = (unsigned char *) str;
for (size_t i = 0; i < n; i++){
buffer[i] = c;
}
return buffer;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
int main()
{
char *arg_list[] = { /* ~{ѼƦC (tXr v) */
"ls", /* argv[0] Y{W */
"-l",
"/tmp",
NULL }; /* H NULL */
execvp("ls", arg_list); /* b PATH |M~{ */
printf("The end of the program.\n");
}
|
C
|
/* This program removes wtmp entries by name or tty number */
#include <utmp.h>
#include <stdio.h>
#include <sys/file.h>
#include <sys/fcntl.h>
#define WTMP_PATH "/var/log/wtmp"
void usage(name)
char *name;
{
printf("Usage: %s [ user | tty ]\n", name);
exit(1);
}
void main (argc, argv)
int argc;
char *argv[];
{
struct utmp utmp;
int size, fd, lastone = 0;
int match, tty = 0, x = 0;
if (argc > 3 || argc < 2)
usage(argv[0]);
if (strlen(argv[1]) < 2)
{
printf("Error: Length of user\n");
exit(1);
}
if (argc == 3)
if (argv[2][0] == 'l')
lastone = 1;
if (!strncmp(argv[1], "tty", 3))
tty++;
if ((fd = open(WTMP_PATH, O_RDWR)) == -1)
{
printf("Error: Open on %s\n", WTMP_PATH);
exit(1);
}
printf("[Searching for %s]: ", argv[1]);
if (fd >= 0)
{
size = read(fd, &utmp, sizeof(struct utmp));
while ( size == sizeof(struct utmp) )
{
if ( tty ? ( !strcmp(utmp.ut_line, argv[1]) ) : ( !strncmp(utmp.ut_name, argv[1], strlen(argv[1])) ) && lastone != 1)
{
if (x == 10)
printf("\b%d", x);
else
if (x > 9 && x != 10)
printf("\b\b%d", x);
else
printf("\b%d", x);
lseek( fd, -sizeof(struct utmp), L_INCR );
bzero( &utmp, sizeof(struct utmp) );
write( fd, &utmp, sizeof(struct utmp) );
x++;
}
size = read( fd, &utmp, sizeof(struct utmp) );
}
}
if (!x)
printf("No entries found.");
else
printf(" entries removed.");
printf("\n");
close(fd);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: rfelicio <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/06/02 20:37:05 by rfelicio #+# #+# */
/* Updated: 2021/06/04 10:26:58 by rfelicio ### ########.fr */
/* */
/* ************************************************************************** */
#include <unistd.h>
void ft_putchar(char c);
void ft_is_negative(int n);
int main(void)
{
int nb_1;
int nb_2;
int nb_3;
char newline;
nb_1 = 42;
nb_2 = -42;
nb_3 = 0;
newline = '\n';
ft_is_negative(nb_1);
ft_putchar(newline);
ft_is_negative(nb_2);
ft_putchar(newline);
ft_is_negative(nb_3);
ft_putchar(newline);
return (0);
}
void ft_putchar(char c)
{
write(1, &c, 1);
}
void ft_is_negative(int n)
{
char positive;
char negative;
positive = 'P';
negative = 'N';
if (n >= 0)
ft_putchar(positive);
if (n < 0)
ft_putchar(negative);
}
|
C
|
/*
* prob7.c -- Problem 7 of column 9
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <assert.h>
int bits(unsigned char byte)
{
int count = 0;
while (byte) {
++count;
byte &= byte-1;
}
return count;
}
int countbits(const unsigned char *p, int n)
{
static int ones[256], isinit;
if (!isinit) {
for (int i = 0; i < 256; i++)
ones[i] = bits((unsigned char) i);
isinit = 1;
}
if (p == NULL)
return 0;
int count = 0;
for (int i = 0; i < n; i++) {
count += ones[*p++];
}
return count;
}
int countbits2(const unsigned char *p, int n)
{
int count = 0;
for (int i = 0; i < n; i++)
count += bits(*p++);
return count;
}
#define MAXN 100000000
unsigned char x[MAXN];
int main()
{
srand(time(NULL));
for (int i = 0; i < MAXN; i++)
x[i] = (unsigned char) (rand() % 256);
int algnum, n;
while (scanf("%d %d", &algnum, &n) != EOF) {
if (n > MAXN) {
printf("n should be no more than %d\n", MAXN);
continue;
}
clock_t start, ticks;
int thisans, chkans;
start = clock();
switch (algnum) {
case 1:
thisans = countbits(x, n);
break;
case 2:
thisans = countbits2(x, n);
break;
default:
break;
}
ticks = clock() - start;
printf("alg: %d, n: %d, ticks: %d, sec: %.2f\n",
algnum, n, (int) ticks, (float) ticks / CLOCKS_PER_SEC);
chkans = countbits2(x, n);
if (thisans != chkans)
printf("error: mismatch with countbits2(): %d\n", chkans);
}
return 0;
}
|
C
|
//waitpid函数的使用
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main(void)
{
//创建2个子进程
pid_t pid = fork();
if(-1 == pid)
{
perror("fork"),exit(-1);
}
pid_t pid2;
if(0 != pid)//父进程
{
pid2 = fork();
}
if(0 == pid) //子进程1
{
printf("子进程一开始运行,PID = %d\n",getpid());
sleep(3);
printf("子进程一结束运行\n");
exit(100); //子进程结束
}
if(0 == pid2) //子进程2
{
printf("子进程二开始运行,PID = %d\n",getpid());
sleep(5);
printf("子进程二结束运行\n");
exit(200); //子进程结束
}
//父进程
printf("父进程开始等待...\n");
int status = 0;
//等待任意一个子进程结束
int res = wait(&status);
//表示等待任意一个子进程结束
//int res = waitpid(-1,&status,0);
//等待子进程二结束
//int res = waitpid(pid2,&status,0);
//等待子进程一结束,与等待任意一个子进程的效果相同
//int res = waitpid(pid,&status,0);
if(-1 == res)
{
perror("waitpid"),exit(-1);
}
if(WIFEXITED(status))
{
printf("进程%d总算结束了,退出状态信息是:%d\n",res,WEXITSTATUS(status));
}
return 0;
}
|
C
|
/* LMINIM.C - Calculate the minimum intensity for an input image.
Author: Mike Wall
Date: 9/14/2017
Version: 1.
*/
#include<mwmask.h>
int lminim(DIFFIMAGE *imdiff)
{
size_t
r,
c,
n=0,
index = 0;
IMAGE_DATA_TYPE
minval;
struct rccoords rvec;
minval = imdiff->ignore_tag;
for(r = 0; r < imdiff->vpixels; r++) {
for(c = 0; c < imdiff->hpixels; c++) {
if ((imdiff->image[index] != imdiff->overload_tag) &&
(imdiff->image[index] != imdiff->ignore_tag)) {
if (minval > imdiff->image[index] ||
minval == imdiff->ignore_tag) {
minval = imdiff->image[index];
rvec.r=r;
rvec.c=c;
}
}
index++;
}
}
imdiff->min_pixel_value = minval;
// printf("Minimum value of %d at position %d,%d\n",minval,rvec.r,rvec.c);
}
|
C
|
typedef struct node_st {
int external;
struct node_st *bparent;
int rank;
int weight; //external nodes only
//wt(v) = size(v) if no solid edge enters v (ergo, bparent(v) == null)
// size(v) - size(w) if the solid edge (w,v) enters v
//internal nodes only
//prolly should be in a separate structure but I'm so lazy...
struct node_st *bleft, *bright, *bhead, *btail;
int reversed;
int netcost;
int netmin;
//vertex data
struct node_st *dparent; //originally vertex_st
double dcost;
} Node;
/* #define Path Node */
/* #define Vertex Node */
typedef Node Path;
typedef Node Vertex;
typedef struct quadruple_st{
Path *p, *q;
double x, y;
} Quadruple;
//nodes
int grosscost(Vertex *v);
int grossmin(Vertex *v);
Path* splice(Path *p);
Path* expose(Vertex *v);
//paths
Path *path(Vertex *v);
Vertex *head(Path *p);
Vertex *tail(Path *p);
Vertex *before(Vertex *v);
Vertex *after(Vertex *v);
int pcost(Vertex *v);
Vertex *pmincost(Path *p);
void pupdate(Path *p, double x);
void reverse(Path *p);
Path *concatenate(Path *p, Path *q, double x);
Quadruple *split(Vertex *v);
//requirements for concatenate and split
Node *construct(Node *v, Node *w, double x);
Quadruple *destroy(Node *u);
void rotate_left(Node *v);
void rotate_right(Node *v);
//auxiliar functions
Vertex* find_deepest_right_child(Vertex *v);
Vertex* find_deepest_left_child(Vertex *v);
int is_right_child(Vertex *v);
int is_left_child(Vertex *v);
int size(Vertex *v);
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
FILE *file;
typedef struct tower_seg
{
int size;
struct tower_seg *seg_under;
}Tower;
Tower* create_tower(int seg_amount)
{
Tower *hanoi_first,*hanoi_last;
hanoi_first=(Tower*)malloc(sizeof(Tower));
int i=1; //first seg
hanoi_first->size=i;
hanoi_last=hanoi_first;
while(i++<seg_amount)
{
//segments 2nd to pre last
hanoi_last->seg_under=(Tower*)malloc(sizeof(Tower));
hanoi_last=hanoi_last->seg_under;
hanoi_last->size=i;
}
//last segment
hanoi_last->seg_under=NULL;
return hanoi_first;
}
int USRinput_seg_amount()
{
char c;
int seg_amount=0;
while(seg_amount<1)
{
printf("Podaj wielkosc wiezy!\n");
if(scanf("%d",&seg_amount)==0)
{
do {
c = getchar();
}
while (!isdigit(c));
ungetc(c, stdin);
}
}
return seg_amount;
}
int can_be_moved(Tower *top1,Tower *top2, Tower *top3, int *target)
{
if(top1!=NULL)
{
if(top1->size!=1)
{
if(top2!=NULL)
{
if(top1->size < top2->size)
{
*target=2; return 1;
}
}else {*target=2; return 1;}
if(top3!=NULL)
{
if(top1->size < top3->size)
{
*target=3; return 1;
}
}else {*target=3; return 1;}
}
}
if(top2!=NULL)
{
if(top2->size!=1)
{
if(top1!=NULL)
{
if(top2->size < top1->size)
{
*target=1; return 2;
}
}else {*target=1; return 2;}
if(top3!=NULL)
{
if(top2->size < top3->size)
{
*target=3; return 2;
}
}else {*target=3; return 2;}
}
}
if(top3!=NULL)
{
if(top3->size!=1)
{
if(top1!=NULL)
{
if(top3->size < top1->size)
{
*target=1; return 3;
}
}else {*target=1; return 3;}
if(top2!=NULL)
{
if(top3->size < top2->size)
{
*target=2; return 3;
}
}else {*target=2; return 3;}
}
}
if(1)
printf("very bad");
}
int count(Tower *tow)
{
int amount=0;
while(tow)
{
amount++;
tow=tow->seg_under;
}
return amount;
}
void swap(Tower **from, Tower **to)
{
if(*from!=NULL)
{
Tower *tmp;
tmp=(*from)->seg_under;
(*from)->seg_under=*to;
(*to)=(*from);
(*from)=tmp;
}
}
void print_towers(Tower *top1,Tower *top2,Tower *top3)
{
system("cls"); //clears screen
printf("I\tII\tIII\n\n");
while(top1!=NULL || top2!=NULL || top3!=NULL)
{
if(top1!=NULL)
{printf("%d\t",top1->size);top1=top1->seg_under;}else printf("\t");
if(top2!=NULL)
{printf("%d\t",top2->size);top2=top2->seg_under;}else printf("\t");
if(top3!=NULL)
{printf("%d\n",top3->size);top3=top3->seg_under;}else printf("\n");
}
}
void print_toFile(Tower *top1,Tower *top2,Tower *top3, FILE *file)
{
fprintf(file,"I\tII\tIII\n\n");
while(top1!=NULL || top2!=NULL || top3!=NULL)
{
if(top1!=NULL)
{fprintf(file,"%d\t",top1->size);
top1=top1->seg_under;
}else fprintf(file,"\t");
if(top2!=NULL)
{fprintf(file,"%d\t",top2->size);
top2=top2->seg_under;
}else fprintf(file,"\t");
if(top3!=NULL)
{fprintf(file,"%d\n",top3->size);
top3=top3->seg_under;
}else fprintf(file,"\n");
} fprintf(file,"\n");
}
void move(Tower **top1, Tower **top2, Tower **top3,int selected, int target)
{
if(selected==1)
{
if(target==2) // top2 and top3 can be both null
{
swap(top1,top2);
}else swap(top1,top3);
}else if(selected==2)
{
if(target==1)
{
swap(top2,top1);
}else swap(top2,top3);
}else if(target==1)
{
swap(top3,top1);
}else swap(top3,top2);
}
void user_solve(Tower *hanoi_first, int seg_amount)
{
Tower *top1,*top2=NULL,*top3=NULL, *being_moved, *to;
top1=hanoi_first;
int segs_top3,selected,target,valid_move,moves_counter=0;
char c;
while(segs_top3!=seg_amount)
{
print_towers(top1,top2,top3);
print_toFile(top1,top2,top3,file);
while(selected<1 || selected>3 || target<1 || target>3 || selected==target || valid_move!=1)
{
valid_move=1;
printf("\nPodaj nr stosu z ktorego przesunac: ");
if(scanf("%d",&selected)==0)
{
do{
c=getchar();
}while(!isdigit(c));
ungetc(c,stdin);
}
printf("\nPodaj nr stosu bedacy celem: "); scanf("%d",&target);
if(selected==1)
{
being_moved=top1;
}else if(selected==2)
{
being_moved=top2;
}else if(selected==3)
{
being_moved=top3;
}
if(target==1)
{
to=top1;
}else if(target==2)
{
to=top2;
}else if(target==3)
{
to=top3;
}
if(being_moved==NULL)
{
valid_move=0;
}
if(selected<1 ||selected>3 || target<1 || target>3)
{
valid_move=0;
}else
if(to!=NULL && being_moved!=NULL)
{
if(being_moved->size > to->size)
valid_move=0;
}
if(valid_move==0)
{
printf("\nNiedozwolony ruch!");
}
}valid_move=0;
move(&top1,&top2,&top3,selected,target);moves_counter++;
segs_top3=count(top3);
}
print_towers(top1,top2,top3);
print_toFile(top1,top2,top3,file);
printf("Liczba ruchow: %d\nNacisnij dowolny klawisz by kontynuowac",moves_counter);getch();
}
int solve_hanoi(Tower *hanoi_first,int seg_amount)
{
int wait, segs_top3=0, from,to,mode=-1;
char c;
printf("0 - Kolejne ruchy odbeda sie po podanej przez ciebie liczbie milisekund\n1 - Kolejne ruchy odbeda sie po kliknieci dowolnego przycisku\n");
while(mode!=0 && mode!=1)
{
if(scanf("%d",&mode)==0)
{
do{
c=getchar();
}while(!isdigit(c));
ungetc(c,stdin);
}
}
if(mode==0)
{printf("Podaj opoznienie miedzy kolejnymi ruchami: ");scanf("%d",&wait);system("cls");}
if(seg_amount<1)
return -1;
Tower *top1, *top2=NULL, *top3=NULL;
top1=hanoi_first;
print_towers(top1,top2,top3); print_toFile(top1,top2,top3,file);
if(mode==0)Sleep(wait);else {getch();}
while(segs_top3!=seg_amount)
{
segs_top3=0;
if(top1!=NULL)
{if(top1->size==1 && segs_top3!=seg_amount) //moving smallest seg to the next tower
{
if(seg_amount%2==0)
swap(&top1,&top2);else swap(&top1,&top3);
segs_top3=count(top3);
print_towers(top1,top2,top3); print_toFile(top1,top2,top3,file);
if(mode==0)Sleep(wait);else {getch();}
if(segs_top3!= seg_amount)
{
from=can_be_moved(top1,top2,top3,&to);
move(&top1,&top2,&top3,from,to);
segs_top3=count(top3);
print_towers(top1,top2,top3); print_toFile(top1,top2,top3,file);
if(mode==0)Sleep(wait);else {getch();}
}
}
}
if(top2!=NULL)
{if(top2->size==1 && segs_top3!=seg_amount) //moving smallest seg to the next tower
{
if(seg_amount%2==0)
swap(&top2,&top3);else swap(&top2,&top1);
segs_top3=count(top3);
print_towers(top1,top2,top3); print_toFile(top1,top2,top3,file);
if(mode==0)Sleep(wait);else {getch();}
if(segs_top3!= seg_amount)
{
from=can_be_moved(top1,top2,top3,&to);
move(&top1,&top2,&top3,from,to);
segs_top3=count(top3);
print_towers(top1,top2,top3); print_toFile(top1,top2,top3,file);
if(mode==0)Sleep(wait);else {getch();}
}
}
}
if(top3!=NULL)
{if(top3->size==1 && segs_top3!=seg_amount) //moving smallest seg to the next tower
{
if(seg_amount%2==0)
swap(&top3,&top1);else swap(&top3,&top2);
segs_top3=count(top3);
print_towers(top1,top2,top3); print_toFile(top1,top2,top3,file);
if(mode==0)Sleep(wait);else {getch();}
if(segs_top3!= seg_amount)
{
from=can_be_moved(top1,top2,top3,&to);
move(&top1,&top2,&top3,from,to);
segs_top3=count(top3);
print_towers(top1,top2,top3); print_toFile(top1,top2,top3,file);
if(mode==0)Sleep(wait);else {getch();}
}
}
}
}
return 0;
}
int main()
{
file=fopen("hanoi.txt","w");
int amount, select=1;
char c;
while(select!=0)
{
amount=USRinput_seg_amount();
Tower *top1=create_tower(amount );
system("cls");
printf("0 Koniec programu\n1 Zobacz rozwiazanie\n2 Sprobuj rozwiazac\nPodaj numer: ");
if(scanf("%d",&select)==0)
{
do{
c=getchar();
}while(!isdigit(c));
ungetc(c,stdin);
}
if(select==1)
{system("cls");solve_hanoi(top1,amount);system("cls");fprintf(file,"\n////////////////////\n\n");}
if(select==2)
{system("cls");user_solve(top1,amount);system("cls");fprintf(file,"\n////////////////////\n\n");}
}
close(file);
return 0;
}
|
C
|
#include "Notify.h"
void notify(char* PATH_CONFIG)
{
int length;
int i = 0;
char buffer[BUF_LEN];
int fileToWatch = inotify_init();
if( fileToWatch < 0)
{
logError("[NOTIFY/MEMORIA]: Error al iniciar el notifier.");
return;
}
int watchDescriptor = inotify_add_watch(fileToWatch, PATH_CONFIG, IN_CREATE | IN_MODIFY | IN_DELETE | IN_DELETE_SELF);
length = read(fileToWatch, buffer, BUF_LEN);
if(length < 0)
{
logError("[NOTIFY/MEMORIA]: Error al tratar de acceder al archivo a vigilar.");
return;
}
while(i < length)
{
struct inotify_event* event = (struct inotify_event*) &buffer[i];
if(event->mask & IN_MODIFY)
{
sleep(2);
logInfo("[NOTIFY/MEMORIA]: se ha modificado el archivo de configuración, actualizando valores.");
t_config* ConfigMain = config_create(PATH_CONFIG);
info_memoria.retardo_fs = config_get_int_value(ConfigMain, "RETARDO_FS");
info_memoria.retardo_mp = config_get_int_value(ConfigMain, "RETARDO_MEM");
info_memoria.tiempo_goss = config_get_int_value(ConfigMain, "RETARDO_GOSSIPING");
info_memoria.tiempo_jour = config_get_int_value(ConfigMain, "RETARDO_JOURNAL");
config_destroy(ConfigMain);
logInfo("[NOTIFY/MEMORIA]: valores actualizados.");
puts("Al detectarse un cambio en el archivo de configuración, se actualizaron los valores de Memoria.");
}
else if(event->mask & IN_DELETE_SELF)
{
logInfo("[NOTIFY/MEMORIA]: Se ha detectado que el archivo de config ha sido eliminado. Terminando sistema.");
puts("Memoria está siendo desconectado ya que el archivo de configuración fue destruido.");
break;
}
else if(event->mask & IN_CREATE)
{
logInfo("[NOTIFY/MEMORIA]: Se ha detectado el archivo de configuración");
}
length = read(fileToWatch, buffer, BUF_LEN);
}
(void) inotify_rm_watch(fileToWatch, watchDescriptor);
(void) close(fileToWatch);
}
|
C
|
/*
* dv_ext_irq.c
*
* Created: 11/14/2019 11:25:45 AM
* Author: liu
*/
#include <asf.h>
#include "dv_ext_irq.h"
/**
* \brief De-assert start pin when shutdown pin is asserted
*/
static void handler_shdn(long unsigned int unused0, long unsigned int unused1)
{
/* Disable front-end DC-DC converter on PoEM board */
DV_unused(unused0);
DV_unused(unused1);
gpio_set_pin_high(NSTART);
DV_info("Shutdown pin asserted, powering down tool...");
}
/**
* \brief Initialize external interrupt for nSHDN pin (PA18)
*/
void init_shdn_ext_irq(void)
{
/* Configure PA26 as input with pull-up and debouncing */
pio_set_input(PIN_SHDN_PIO, PIN_SHDN_PIO_MASK, PIO_INPUT | PIO_PULLUP | PIO_DEBOUNCE);
/* Configure debounce filter at 25Hz */
pio_set_debounce_filter(PIN_SHDN_PIO, PIN_SHDN_PIO_MASK, 25);
/* Configure external interrupt on falling edge of PA26 */
pio_handler_set(PIN_SHDN_PIO, PIN_SHDN_PIO_ID, PIN_SHDN_PIO_MASK, PIN_SHDN_ATTR, handler_shdn);
/* Clear interrupt status */
pio_get_interrupt_status(PIN_SHDN_PIO);
/* Enable PIO line interrupts. */
pio_enable_interrupt(PIN_SHDN_PIO, PIN_SHDN_PIO_MASK);
/* Configure external interrupt in NVIC */
NVIC_EnableIRQ((IRQn_Type)PIN_SHDN_PIO_ID);
}
|
C
|
#include"list.h"
int main() {
char** head_node = NULL;
StringListInit(&head_node, "First");
StringListPrint(head_node);
StringListInit(&head_node, "Second");
StringListAdd(head_node, "hello");
StringListAdd(head_node, "hello2");
StringListAdd(head_node, "hello");
StringListAdd(head_node, "world");
StringListAdd(head_node, "Last");
StringListPrint(head_node);
printf("\n> Size of list: %d", StringListSize(head_node));
printf("\n> Index of <hello2>: %d \n\n", StringListIndexOf(head_node, "hello2"));
StringListPrint(head_node);
printf("---> Remove <First> : ");
StringListRemove(&head_node, "First");
StringListPrint(head_node);
printf("---> Remove <hello2> : ");
StringListRemove(&head_node, "hello2");
StringListPrint(head_node);
printf("---> Remove <Error> : ");
StringListRemove(&head_node, "Error");
StringListPrint(head_node);
printf("---> Remove <Last> : ");
StringListRemove(&head_node, "Last");
StringListPrint(head_node);
printf("---> Replace <hello> to <bye> : ");
StringListReplaceInStrings(head_node, "hello", "bye");
StringListPrint(head_node);
printf("---> Destroy List : ");
StringListDestroy(&head_node);
StringListPrint(head_node);
printf("\n");
char** head_node2 = NULL;
StringListInit(&head_node2, "b");
StringListAdd(head_node2, "d");
StringListAdd(head_node2, "a");
StringListAdd(head_node2, "b");
StringListAdd(head_node2, "c");
StringListAdd(head_node2, "b");
StringListAdd(head_node2, "e");
StringListAdd(head_node2, "c");
StringListPrint(head_node2);
printf("---> Sorting : ");
StringListSort(&head_node2);
StringListPrint(head_node2);
printf("---> Remove Duplicates : ");
StringListRemoveDuplicates(head_node2);
StringListPrint(head_node2);
printf("---> Destroy List : ");
StringListDestroy(&head_node2);
StringListPrint(head_node2);
return 0;
}
|
C
|
#include <cstdio>
#include <cstdlib>
typedef int val_t;
typedef val_t * val_array;
typedef int index_t;
typedef struct {
val_array data;
int size;
int data_length;
} heap_t;
typedef heap_t * heap;
heap build_max_heap (val_array A, int size);
void max_heapify (heap h, index_t i);
void destroy_heap (heap h);
val_t get (heap h, index_t i);
void set (heap h, index_t i, val_t val);
val_t heap_extract_max (heap h);
void max_heap_insert (heap h, val_t v);
void heap_increase_key (heap h, index_t i, val_t v);
void swap (val_t * l, val_t * r);
int size (heap h);
void print_heap (heap h);
index_t parent (index_t i);
index_t left (index_t i);
index_t right (index_t i);
|
C
|
#include <sys/types.h>
#include <sys/event.h>
#include <sys/time.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include "mruby.h"
#include "mruby/compile.h"
#include "mruby/string.h"
// gcc `mruby/bin/mruby-config --cflags --ldflags --libs --ldflags-before-libs` watchFile.c
//
// File.dirname(File.realpath("./myfile.rb"))
// mrb_load_string_cxt
// Dir.open(File.dirname(File.realpath("./myfile.rb"))).each{|f| p f}
int checkFile(mrb_state *mrb, mrbc_context *cxt, char *filepath)
{
mrb_value val;
val = mrb_funcall(mrb, mrb_top_self(mrb), "checkFile", 1,
mrb_str_new_cstr(mrb, filepath));
return mrb_bool(val);
}
void watchFile(mrb_state *mrb, mrbc_context *cxt, char *filepath)
{
int fd, dfd, kq;
struct kevent kev[2], kev_r;
int isFileWatching;
char *dirpath;
mrb_value val;
fd = open(filepath,O_RDONLY);
// dirpath = File.dirname(File.realpath("./myfile.rb"))
val = mrb_funcall(mrb, mrb_obj_value(mrb_class_get(mrb, "File")), "realpath", 1,
mrb_str_new_cstr(mrb, filepath));
val = mrb_funcall(mrb, mrb_obj_value(mrb_class_get(mrb, "File")), "dirname", 1,
val);
dirpath = mrb_string_value_ptr(mrb, val);
dfd = open(dirpath,O_RDONLY);
kq = kqueue();
EV_SET(&kev[0], fd, EVFILT_VNODE, EV_ADD | EV_ENABLE | EV_CLEAR, NOTE_DELETE | NOTE_WRITE, 0, NULL);
EV_SET(&kev[1], dfd, EVFILT_VNODE, EV_ADD | EV_ENABLE | EV_CLEAR, NOTE_WRITE, 0, NULL);
if (kevent(kq, kev, 2, NULL, 0, NULL) == -1) {
perror("oops");
printf("kevent error\n");
exit(0);
}
isFileWatching = 1;
while (1) {
if (isFileWatching) {
// ディレクトリとファイルを監視
if (kevent(kq, kev, 2, &kev_r, 1, NULL) == -1) {
printf("kevent_r error\n");
exit(0);
}
} else {
// ディレクトリのみ監視
if (kevent(kq, &kev[1], 1, &kev_r, 1, NULL) == -1) {
printf("kevent_r error\n");
exit(0);
}
}
if (isFileWatching == 1) {
if (kev_r.ident == fd) {
if (kev_r.fflags & NOTE_WRITE) {
printf("file was updated!\n");
} else if (kev_r.fflags & NOTE_DELETE) {
printf("file was deleted!\n");
isFileWatching = 0;
}
}
} else {
if (kev_r.fflags & NOTE_WRITE) {
printf("%s\n","update dir");
if (checkFile(mrb, cxt, filepath) == 1) {
printf("%s\n","add file!");
// チェック対象だったら、fdを再取得して、これを監視対象にする。
fd = open(filepath, O_RDONLY);
EV_SET(&kev[0], fd, EVFILT_VNODE, EV_ADD | EV_ENABLE | EV_CLEAR, NOTE_DELETE | NOTE_WRITE, 0, NULL);
isFileWatching = 1;
}
}
}
}
}
int main(int argc, char **argv)
{
FILE* f;
mrb_state *mrb;
mrbc_context *cxt;
mrb_value val;
char *filepath = "./foo.txt";
mrb = mrb_open();
cxt = mrbc_context_new(mrb);
f = fopen("checkFile.rb", "r");
mrb_load_file(mrb, f);
fclose(f);
// File.realpath("./myfile.rb"))
val = mrb_funcall(mrb, mrb_obj_value(mrb_class_get(mrb, "File")), "realpath", 1,
mrb_str_new_cstr(mrb, filepath));
char *fullpath = mrb_string_value_ptr(mrb, val);
printf("%s\n", fullpath);
watchFile(mrb, cxt, fullpath);
mrb_close(mrb);
exit(0);
}
|
C
|
#include<GL/gl.h>
#include<GL/glut.h>
#define width 640
#define height 480 // Fixing the height and width of the screen.
#include<stdio.h>
#include<math.h>
const char* ch; // Input arguments are saved in this character pointer.
float xi,xf,yi,yf,xt,yt; // Six global variables : xi,xf,yi,yf -> used in lines drawing algorithm && xi,xf,yi,yf,xt,yt -> used in triangle drawing algorithm.
float r[3] = {-1,-1,-1},g[3] = {-1,-1,-1}, b[3] = {-1,-1,-1},a[3] = {-1,-1,-1}; // Color for each vertex of triangle and also for each end point of line segment.(in line drawing case, third element has -1 as its value(as we need only two indices only).)
float red,green,blue,alpha; // Finally acheived colors by calculating using ratios formula.
//########### Color Calculation ###########//
void color(float t) // t is the ratio in which two vertices are divided by.
{
red = r[0] + t*(r[1]-r[0]); // Using: line -> (x1,y1)------(x2,y2) , a point p in between divides this line with t:(1-t).
green = g[0] + t*(g[1]-g[0]);
blue = b[0] + t*(b[1]-b[0]);
alpha = a[0] + t*(a[1]-a[0]);
}
//---------------------------------------------------------------------------//
//########### Bresenham Algorithm for drawing pixel per pixel line ##########//
void bresenham(void)
{
float slope; // Variable to store slope of the line with sign.
float dx,dy,x,y; // Variables to store change in end points x,y values.
dx = xf-xi;
dy = yf-yi;
if(dx!=0)
slope = dy/dx;
else
slope = 99999999;
x = xi;
y = yi;
glPointSize(1.0f); // Setting point size to be one to assure a pixel draw.
glBegin(GL_POINTS);
float t = 0;
if (dx ==0) // If change in x is zero slope -> infinity, only y needs to be incremented.
{
while(y!=yf)
{
color(fabs((y-yi)/(yf-yi))); //Calling Color function for color calculation.
glColor4f(red/255.0,green/255.0,blue/255.0,alpha/255.0); //Choosing color as calculated.
if(yf>yi) // If yf > yi => y needs increment positively.
glVertex3f(x,y++,1.0f);
else
glVertex3f(x,y--,1.0f); // else y needs negative increment.
}
}
else if(fabs(slope)<=1) // If slope is between -1 and 1.
{
while(xf!=x){ // Since, slope is not steep, therefore, while xf is not reached keeps on incrementing x(positively or negatively).
if(xf>xi)
x = x +1;
else
x = x - 1;
if(yf>yi) // If yf > yi => y needs to be positively incremented.
{
if(y+0.5 <= yi + slope*(x-xi)) // if midpoint of the next and its above pixel is less than corresponding value of line for this x, then y needs positive increment else no increment required.
y = y+1;
}
else
{
if(y-0.5 >= yi + slope*(x-xi)) // if midpoint of the next and its below pixel is greator than corresponding value of line for this x, then y needs negative increment else no increment required.
y = y-1;
}
color(fabs((x-xi)/(xf-xi))); // Calling Color function for color calculation.
glColor4f(red/255.0,green/255.0,blue/255.0,alpha/255.0); // Choosing color as calculated.
glVertex3f(x,y,1.0f);
}
}
else // If slope is out of the limits of -1 and 1, then this else statement gets executed.
{
while(yf!=y) // Since, slope is steep, therefore, while yf is not reached keeps on incrementing y(positively or negatively).
{
if(yf>yi) // if yf > yi => increment y positively
y++;
else // Else increment y negatively.
y--;
if(xf>xi) // if xf > xi => x needs positive increment
{
if(x+0.5<= xi+((y-yi)/slope)) // if midpoint of the left and its right pixel is less than corresponding value of line for this y, then x needs positive increment else no increment required.
x++;
}
else
{
if(x-0.5>= xi+((y-yi)/slope)) // if midpoint of the left and its right pixel is greator than corresponding value of line for this y, then x needs negative increment else no increment required.
x--;
}
color(fabs((y-yi)/(yf-yi))); // Calling the color function for calculating the corresponding colors.
glColor4f(red/255.0,green/255.0,blue/255.0,alpha/255.0);
glVertex3f(x,y,1.0f);
}
}
glEnd();
glFlush(); // Flushing the buffer for synchronizing drawing.
}
//-------------------------------------------------------------//
//############### Area of Triangle ##################//
float area()
{
float s = (sqrt((xf-xi)*(xf-xi) + (yf-yi)*(yf-yi)) + sqrt((xt-xi)*(xt-xi) + (yt-yi)*(yt-yi)) + sqrt((xf-xt)*(xf-xt) + (yf-yt)*(yf-yt))) /2;
return sqrt(s*(s-(sqrt((xf-xi)*(xf-xi) + (yf-yi)*(yf-yi))))*(s-(sqrt((xt-xi)*(xt-xi) + (yt-yi)*(yt-yi))))*(s-(sqrt((xf-xt)*(xf-xt) + (yf-yt)*(yf-yt)))));
}
//-------------------------------------------------------------------------//
//############## Area w.r.t point (x,y),(xf,yf),(xt,yt) ###################//
float areaone(float x, float y)
{
float s = (sqrt((xf-x)*(xf-x) + (yf-y)*(yf-y)) + sqrt((xt-x)*(xt-x) + (yt-y)*(yt-y)) + sqrt((xf-xt)*(xf-xt) + (yf-yt)*(yf-yt))) /2;
return sqrt(s*(s-(sqrt((xf-x)*(xf-x) + (yf-y)*(yf-y))))*(s-(sqrt((xt-x)*(xt-x) + (yt-y)*(yt-y))))*(s-(sqrt((xf-xt)*(xf-xt) + (yf-yt)*(yf-yt)))));
}
//-------------------------------------------------------------------------//
//############## Area w.r.t point (x,y),(xi,yi),(xt,yt) ###################//
float areatwo(float x,float y)
{
float s = (sqrt((x-xi)*(x-xi) + (y-yi)*(y-yi)) + sqrt((xt-xi)*(xt-xi) + (yt-yi)*(yt-yi)) + sqrt((x-xt)*(x-xt) + (y-yt)*(y-yt))) /2;
return sqrt(s*(s-(sqrt((x-xi)*(x-xi) + (y-yi)*(y-yi))))*(s-(sqrt((xt-xi)*(xt-xi) + (yt-yi)*(yt-yi))))*(s-(sqrt((x-xt)*(x-xt) + (y-yt)*(y-yt)))));
}
//-------------------------------------------------------------------------//
//############## Area w.r.t point (x,y),(xf,yf),(xi,yi) ###################//
float areathree(float x,float y)
{
float s = (sqrt((xf-xi)*(xf-xi) + (yf-yi)*(yf-yi)) + sqrt((x-xi)*(x-xi) + (y-yi)*(y-yi)) + sqrt((xf-x)*(xf-x) + (yf-y)*(yf-y))) /2;
return sqrt(s*(s-(sqrt((xf-xi)*(xf-xi) + (yf-yi)*(yf-yi))))*(s-(sqrt((x-xi)*(x-xi) + (y-yi)*(y-yi))))*(s-(sqrt((xf-x)*(xf-x) + (yf-y)*(yf-y)))));
}
//-------------------------------------------------------------------------//
//############## Check for Point to lie within Triangle ###################//
bool PointInTriangle(float x,float y)
{
float slope = (yf-yi)/(xf-xi);
if(((y-yi)-slope*(x-xi))*((yt-yi)-slope*(xt-xi))>0)
{
slope = (yt-yi)/(xt-xi);
if(((y-yi)-slope*(x-xi))*((yf-yi)-slope*(xf-xi))>0)
{
slope = (yt-yf)/(xt-xf);
if(((y-yf)-slope*(x-xf))*((yi-yf)-slope*(xi-xf))>0)
return true;
}
}
return false;
}
//--------------------------------------------------------------------//
//################# Triangle Drawing Algorithm #######################//
void triangles(void)
{
float maxx;
maxx = xi > xf ? xi : xf;
maxx = xt >maxx ? xt : maxx; // Getting the max of x values.
float maxy = yi > yf ? yi : yf;
maxy = yt >maxy ? yt : maxy; // Getting the max of y values.
float miny = yi > yf ? yf : yi;
miny = yt > miny ? miny : yt; // Getting the min of y values.
float minx = xi > xf ? xf : xi;
minx = xt > minx ? minx : xt; // Getting the min of x values.
float i,j;
glBegin(GL_POINTS);
for(i = minx; i<=maxx;i++) // Running the two nested 'for' loops and if the any point lie in the triangle, then drawing it, leaving out the rest.
{
for(j = miny; j <= maxy; j++)
{
if(PointInTriangle(i,j)) // Calling the function PointInTriangle for check regarding point lying inside.
{
// Calculating the color for pixels by taking the ratios of the areas of the area formed by point with each of the vertices.
red = ((areaone(i,j) * r[0] + areatwo(i,j) * r[1] + areathree(i,j) * r[2]) / area() ) / 255.0;
green = ((areaone(i,j) * g[0] + areatwo(i,j) * g[1] + areathree(i,j) * g[2]) / area() ) / 255.0;
blue = ((areaone(i,j) * b[0] + areatwo(i,j) * b[1] + areathree(i,j) * b[2]) / area() ) / 255.0;
alpha = ((areaone(i,j) * a[0] + areatwo(i,j) * a[1] + areathree(i,j) * a[2]) / area() ) / 255.0;
glColor4f(red,green,blue,alpha);
glVertex3f(i,j,1.0f);
}
}
}
glEnd();
glFlush(); // Flushing the buffer for synchronizing drawing.
}
//-----------------------------------------------------------------------------------------//
//################### Calling the display function ################//
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
int numoflines;
FILE* in = fopen(ch,"r+"); // File opening and inputting the values ....
fscanf(in,"%d",&numoflines);
while(numoflines!=0){
fscanf(in,"%f",&xi);
fscanf(in,"%f",&yi);
fscanf(in,"%f",&r[0]);
fscanf(in,"%f",&g[0]);
fscanf(in,"%f",&b[0]);
fscanf(in,"%f",&a[0]);
fscanf(in,"%f",&xf);
fscanf(in,"%f",&yf);
fscanf(in,"%f",&r[1]);
fscanf(in,"%f",&g[1]);
fscanf(in,"%f",&b[1]);
fscanf(in,"%f",&a[1]);
bresenham(); // Calling the bresenham algorithm from here.
numoflines--;
}
int numoftriangles = 0;
fscanf(in,"%d",&numoftriangles);
while(numoftriangles!=0){
fscanf(in,"%f",&xi);
fscanf(in,"%f",&yi);
fscanf(in,"%f",&r[0]);
fscanf(in,"%f",&g[0]);
fscanf(in,"%f",&b[0]);
fscanf(in,"%f",&a[0]);
fscanf(in,"%f",&xf);
fscanf(in,"%f",&yf);
fscanf(in,"%f",&r[1]);
fscanf(in,"%f",&g[1]);
fscanf(in,"%f",&b[1]);
fscanf(in,"%f",&a[1]);
fscanf(in,"%f",&xt);
fscanf(in,"%f",&yt);
fscanf(in,"%f",&r[2]);
fscanf(in,"%f",&g[2]);
fscanf(in,"%f",&b[2]);
fscanf(in,"%f",&a[2]);
triangles(); // Calling the triangle algorithm from here.
numoftriangles--;
}
}
//------------------------------------------------------------------------------------//
//#################### Initializing Function #######################//
void init()
{
glClearColor(0.0,0.0,0.0,1.0); // Setting the background as : black.
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-320,320,-240,240,-1.0f,1.0f); // Setting the coordinates as : x-axis-> -320 to 320, y-axis-> -240 to 240, z-axis-> -1 to 1.
}
//-----------------------------------------------------------------------------------//
//################################ The Main Function ######################################//
int main(int argc,char** argv) // Ready to take arguments.
{
glutInit(&argc,argv);
if(argc>=2) // If argument does not have input.txt file, then ask for it ....
ch = argv[1];
else{
printf("\nPlease execute as : './rasterize input.txt'\n");
return 0;}
glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE); // Using only Single Buffer for drawing.
glutInitWindowSize(width,height);
glutInitWindowPosition(100,100);
glutCreateWindow("Test");
init(); // Initializing with line endpoints.
glutDisplayFunc(display);
glutMainLoop();
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int integer = 0, i = 0, intchange = 0, ii = 0, k = 0;
int j = 1, sum = 0, rem = 0, sign = -1;
int remm = 0, summ = 0;
printf("Enter an integer >= 0: ");
while(scanf("%d", &integer) != EOF)
{
//****** Upper
intchange = integer;
for(i = 1 ; intchange >= 10; i *= 10)
{
intchange /= 10;
}
printf("%d", integer);
sum = integer;
k = i;
for( ii = 10 , j = 1 ; ii <= i ; j++ , ii *= 10 )
{
rem = integer / ii;
if ( j % 2 ) printf(" - ");
else printf(" + ");
printf("%d", rem);
}
for( k = 10 ; k <= i ; k *= 10)
{
sum += sign * (integer / k);
sign *= -1;
}
printf(" = %d\n", sum);
//****** Lower
printf("%d", integer / i);
summ = integer / i;
for( ii = i / 10 ; ii >= 1 ; ii /= 10)
{
remm = integer / ii;
printf(" + ");
printf("%d", remm);
summ += remm;
}
printf(" = %d\n", summ);
printf("\n");
printf("Enter an integer >= 0: ");
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
//ַѹ
//磺"xxxyyyyz"ѹַΪ"3x4yz"
//"yyyyyyy"ѹΪ"7y"
//һŻ
//ʱֻ1-99
void CutStringP(char* str){
assert(str);
char* p1 = str;
char* p2 = str;
while (*p2){
int count = 1;
if (*p2 == *(p2 + 1)){
while (*p2 == *(p2 + 1)){
count++;
p2++;
}
if (count <= 9){
*p1 = count + '0';
p1++;
*p1 = *p2;
p1++;
p2++;
*p1 = *p2;
}
else {
*p1 = count / 10 + '0';
p1++;
*p1 = count % 10 + '0';
p1++;
*p1 = *p2;
p1++;
p2++;
*p1 = *p2;
}
}
else {
p1++;
p2++;
*p1 = *p2;
}
}
p1++;
*p1 = '\0';
}
int main(){
//char str[] = "xxxyyyyz";
char str[] = "xxxxxxxxxxxxxxxzyyyyyyyyyyyyyyyyyyyyyyyyyyyyz";
CutStringP(str);
puts(str);
system("pause");
return 0;
}
|
C
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Wang Jian
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <string.h>
#include "st_log.h"
#include "st_stack.h"
void st_stack_destroy(st_stack_t *stack)
{
if (stack == NULL) {
return;
}
if(stack->data_arr) {
safe_free(stack->data_arr);
}
}
st_stack_t* st_stack_create(st_stack_id_t capacity)
{
st_stack_t* st_stack = NULL;
ST_CHECK_PARAM(capacity <= 0, NULL);
st_stack = (st_stack_t*)malloc(sizeof(st_stack_t));
if(NULL == st_stack)
{
ST_WARNING("alloc memory for st_stack failed");
return NULL;
}
memset(st_stack, 0, sizeof(st_stack_t));
st_stack->capacity = capacity;
st_stack->top = 0;
st_stack->data_arr = (void **)malloc(sizeof(void *)*capacity);
if(NULL == st_stack->data_arr)
{
ST_WARNING("alloc memory for data_arr failed");
goto ERR;
}
memset(st_stack->data_arr, 0, sizeof(void*)*capacity);
return st_stack;
ERR:
safe_st_stack_destroy(st_stack);
return NULL;
}
int st_stack_push(st_stack_t* st_stack, void* obj)
{
if(st_stack->top == st_stack->capacity)
{
ST_WARNING("st_stack overflow");
return ST_STACK_FULL;
}
st_stack->data_arr[st_stack->top++] = obj;
return ST_STACK_OK;
}
int st_stack_pop(st_stack_t* st_stack, void** obj)
{
if(st_stack->top == 0)
{
ST_WARNING("st_stack empty");
return ST_STACK_EMPTY;
}
*obj = st_stack->data_arr[--st_stack->top];
return ST_STACK_OK;
}
int st_stack_clear(st_stack_t* st_stack)
{
st_stack->top = 0;
return ST_STACK_OK;
}
bool st_stack_empty(st_stack_t* st_stack)
{
return (st_stack->top == 0);
}
st_stack_id_t st_stack_size(st_stack_t* st_stack)
{
return st_stack->top;
}
int st_stack_top(st_stack_t* st_stack, void** obj)
{
if(st_stack->top == 0)
{
return ST_STACK_EMPTY;
}
*obj = st_stack->data_arr[st_stack->top-1];
return ST_STACK_OK;
}
int st_stack_topn(st_stack_t* st_stack, st_stack_id_t n, void** obj)
{
if(st_stack->top <= n - 1)
{
ST_WARNING("st_stack empty");
return ST_STACK_EMPTY;
}
*obj = st_stack->data_arr[st_stack->top-n];
return ST_STACK_OK;
}
|
C
|
#include <stdio.h>
int main()
{
int A[10];
int B[10];
int C[10];
printf("Preecha o vetor A[10].\n");
for (int i = 0; i < 10; i++)
{
printf("Digite o %d° valor: ", i + 1);
scanf("%d", &A[i]);
}
printf("Preencha o vetor B[10].\n");
for (int j = 0; j < 10; j++)
{
printf("Digite o %d° valor: ", j + 1);
scanf("%d", &B[j]);
}
printf("Um vetor c[10] foi criado a partir da diferença dos elementos de A e B.\n");
for (int k = 0; k < 10; k++)
{
C[k] = A[k] - B[k];
printf("%d\t", C[k]);
}
printf("\n");
return (0);
}
|
C
|
#include<stdio.h>
#include<string.h>
#include"digit.c"
#include"orerator.c"
int main()
{
int i,j=0;
char str[100],ch;
printf("Enter the string to be test :");
scanf("%s" ,str);
for(i=j;str[j]!='\0';i++)
if(str[i]>='0'&& str[i]<='9')
{
j=digit(str,j);}
else if(str[j]=='+'|| str[j]== '=')
{
j=operator(str,j);
}
else
{
printf("not a valid operator chose only '+' ,'++' or '+=' ");
break;}
printf("\n");
return 0;
}
|
C
|
//
// main.c
// client
//
// Created by 고상원 on 2020/04/21.
// Copyright © 2020 고상원. All rights reserved.
//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h>
#define BUFF_SIZE 1024
int main(int argc, const char * argv[]) {
int client_socket;
struct ifreq ifr;
struct sockaddr_in server_addr;
char buff[BUFF_SIZE];
char message[BUFF_SIZE];
char totalMessage[BUFF_SIZE];
char ip_buf[BUFF_SIZE];
while(1){
client_socket = socket(PF_INET, SOCK_STREAM, 0);
strncpy(ifr.ifr_name, "enp0s3", IFNAMSIZ);
ioctl(client_socket, SIOCGIFADDR, &ifr);
if(-1 == client_socket){
printf("socket 생성 실패\n");
exit(1);
}
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(4000);
server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
if(-1 == connect(client_socket, (struct sockaddr*)&server_addr, sizeof(server_addr))){
printf("접속 실패\n");
exit(1);
}
//strcpy(ip_buf, inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr));
strcpy(ip_buf, "192.168.10.2"); //Hard Coding of Client IP
//쓰기
printf("[%s -> send] ", ip_buf);
scanf("%s", message);
strcpy(totalMessage, "[");
strcat(totalMessage, ip_buf);
strcat(totalMessage, " -> rcv] ");
strcat(totalMessage, message);
if(!strcmp(message, "bye"))
break;
write(client_socket, totalMessage, strlen(totalMessage) + 1);
//읽기
read(client_socket, buff, BUFF_SIZE);
printf("%s\n", buff);
}
close(client_socket);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#define N 5 /* !!!!!! Düğüm sayısı burada elle değiştirilmeli. !!!!!*/
int n,m;
int cal[100],indis=0;
struct Queue
{
int front, rear, size;
unsigned capacity;
int* array;
};
struct Queue* createQueue(unsigned capacity)
{
struct Queue* queue = (struct Queue*) malloc(sizeof(struct Queue));
queue->capacity = capacity;
queue->front = queue->size = 0;
queue->rear = capacity - 1;
queue->array = (int*) malloc(queue->capacity * sizeof(int));
return queue;
}
struct Node {
int dest,distance;
struct Node* next;
};
struct Edge {
int src, dest, distance;
};
struct Graph {
struct Node* head[N];
};
// adjacency list oluşturuyor
struct Graph* createGraph(struct Edge edges[], int n)
{
unsigned i;
struct Graph* graph = (struct Graph*)malloc(sizeof(struct Graph));
for (i = 0; i < n; i++)
graph->head[i] = NULL;
for (i = 0; i < m; i++)
{
int src = edges[i].src;
int dest = edges[i].dest;
int dist = edges[i].distance;
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->dest = dest;
newNode->distance = dist;
newNode->next = graph->head[src];
graph->head[src] = newNode;
}
return graph;
}
// adjacency list yazdırıyor
int printGraph(struct Graph* graph)
{
int i,max,neighboor;
max = 0;
printf("\n");
for (i = 0; i < N; i++)
{
printf("%d | ",i);
struct Node* ptr = graph->head[i];
neighboor = 0;
while (ptr != NULL)
{
printf("(%d -> %d) distance:%d ",i, ptr->dest,ptr->distance);
ptr = ptr->next;
neighboor++;
}
if(neighboor > max)
max = neighboor;
printf("\n");
}
return max;
}
void BFS(struct Graph* graph,int source,int dest){
int marked[N],prior[N];
int i,curr;
for(i=0;i<N;i++){
marked[i] = prior[i] = -1;
}
struct Queue* queue = createQueue(1000);
marked[source] = 1; //visited
enqueue(queue,source);
i = 0;
while(isEmpty(queue) != 0){
curr = dequeue(queue);
if(curr == dest){
printf("\npath is : ");
printPath(graph,prior,dest,0);
printf("\nMinimum Distance beetwen %d and %d is %d\n",source,dest,calcu(graph,cal,source,0));
}
struct Node* ptr = graph->head[curr];
while (ptr != NULL)
{
if(marked[ptr->dest] == -1){
marked[ptr->dest] = 1;
enqueue(queue,ptr->dest);
prior[ptr->dest] = curr;
}
ptr = ptr->next;
}
i++;
}
}
//en kısa yolu yazdırıyor
int printPath(struct Graph* graph,int prior[],int v,int dist){
int cost;
cal[indis] = v;
indis++;
if(v >= 0){
cost = printPath(graph,prior,prior[v],dist);
struct Node* ptr = graph->head[v];
if(v < N){
printf("%d ",v);
}
}
return dist;
}
// source ve dest dugumlerı arasındakı mesafeyı hesaplıyor
int calcu(struct Graph* graph,int cal[],int v,int dist){
indis = indis - 2;
while(indis >= 1){
struct Node* ptr = graph->head[cal[indis]];
while(ptr->dest != cal[indis-1]){
ptr = ptr->next;
}
dist = dist + ptr->distance;
indis--;
}
return dist;
}
// kuyruk dolu mu kontrolu
int isFull(struct Queue* queue)
{ return (queue->size == queue->capacity); }
// kuyruk bos mu kontrolu
int isEmpty(struct Queue* queue)
{
if(queue->size == 0)
return 0;
}
//kuyruğa eleman eklıyor
void enqueue(struct Queue* queue, int item)
{
if (isFull(queue))
return;
queue->rear = (queue->rear + 1)%queue->capacity;
queue->array[queue->rear] = item;
queue->size = queue->size + 1;
//printf("%d enqueued to queue\n", item);
}
/*
kuyruktan eleman siliyor
*/
int dequeue(struct Queue* queue)
{
if (isEmpty(queue) == 0)
return -1;
int item = queue->array[queue->front];
queue->front = (queue->front + 1)%queue->capacity;
queue->size = queue->size - 1;
//printf("%d dequeued to queue\n", item);
return item;
}
int main(){
FILE *fp;
int inf[100];
int i,j,source,dest;
int max;
fp = fopen("Graf2.txt","r");
if(fp == NULL)
printf("File couldn't open.");
i = 0;
while(!feof(fp)){
fscanf(fp,"%d",&inf[i]); /* dosyadan bir kelime okuyalim */
i++;
}
n = inf[0]; // düðüm sayýsý
m = inf[1]; // baðlantý sayýsý
source = inf[2]; // baþlangýç düðümü
dest = inf[3]; // varýþ düðümü
printf("n=%d m=%d source=%d dest=%d\n",n,m,source,dest);
struct Edge edges[m*3];
j = 0;
for(i=4;i<m*3+4;i=i+3){
edges[j].src = inf[i];
edges[j].dest = inf[i+1];
edges[j].distance = inf[i+2];
printf("%d %d %d ",edges[j].src,edges[j].dest,edges[j].distance);
j++;
}
struct Graph *graph = createGraph(edges, n);
max = printGraph(graph);
printf("\n\n\n");
BFS(graph,source,dest);
printf("\nMaximum neigboor count is :%d\n",max);
return 0;
}
|
C
|
#include "virtual_machine.h"
#include "instructions_info.h"
// 00 - HALT - Parada
void halt(){
if(DEBUG_MODE)
printf("HALT\n");
exit(0);
}
// 01 - LOAD R M - Carrega Registrador
void load(int r, int m){
if(DEBUG_MODE)
printf("LOAD %d %d\n", r, m);
GENERAL_REGISTERS[r] = MEMORY[m + PC];
}
// 02 - STORE R M - Armazena Registrador
void store(int r, int m){
if(DEBUG_MODE)
printf("STORE %d %d\n", r, m);
MEMORY[m + PC] = GENERAL_REGISTERS[r];
}
// 03 - READ R - Le valor para registrador
void read(int r){
if(DEBUG_MODE)
printf("READ %d\n", r);
scanf("%d", &GENERAL_REGISTERS[r]);
}
// 04 - WRITE R - Escreve conteudo do registrador
void write(int r){
if(DEBUG_MODE)
printf("WRITE %d\n", r);
printf("%d\n", GENERAL_REGISTERS[r]);
}
// 05 - COPY R1 R2 - Copia Registrador
void copy (int r1, int r2){
if(DEBUG_MODE)
printf("COPY %d %d\n", r1, r2);
GENERAL_REGISTERS[r1] = GENERAL_REGISTERS[r2];
updatePEP(GENERAL_REGISTERS[r1]);
}
// 06 - PUSH R - Empilha valor do registrador
void push(int r){
if(DEBUG_MODE)
printf("PUSH %d\n", r);
AP -= 1;
MEMORY[AP] = GENERAL_REGISTERS[r];
}
// 07 - POP R - Desempilha valor no registrador
void pop(int r){
if(DEBUG_MODE)
printf("PUSH %d\n", r);
GENERAL_REGISTERS[r] = MEMORY[AP];
AP += 1;
}
// 08 - JUMP M - Desvio incondicional
void jump(int m){
if(DEBUG_MODE)
printf("JUMP %d\n", m);
PC += m;
}
// 09 - JZ M - Desvia se zero
void jz(int m){
if(DEBUG_MODE)
printf("JZ %d\n", m);
if((PEP & B10) == B10){
PC += m;
}
}
// 10 - JNZ M - Desvia se não zero
void jnz(int m){
if(DEBUG_MODE)
printf("JNZ %d\n", m);
if((PEP & B10) == B00){
PC += m;
}
}
// 11 - JN M - Desvia se negativo
void jumpn(int m){
if(DEBUG_MODE)
printf("JN %d\n", m);
if((PEP & B01) == B01){
PC += m;
}
}
// 12 - JNN M - Desvia se não negativo
void jnn(int m){
if(DEBUG_MODE)
printf("JNN %d\n", m);
if((PEP & B01) == B00){
PC += m;
}
}
// 13 - CALL M - Chamada de subrotina
void call(int m){
if(DEBUG_MODE)
printf("CALL %d\n", m);
AP -= 1;
MEMORY[AP] = PC;
PC = PC + m;
}
// 14 - RET - Retorno de subrotina
void ret(){
if(DEBUG_MODE)
printf("RET\n");
PC = MEMORY[AP];
AP += 1;
}
// 15 - AND R1 R2 - AND (bit a bit) de dois registradores
void and(int r1, int r2){
if(DEBUG_MODE)
printf("AND %d %d\n", r1, r2);
GENERAL_REGISTERS[r1] = GENERAL_REGISTERS[r1] & GENERAL_REGISTERS[r2];
updatePEP(GENERAL_REGISTERS[r1]);
}
// 16 - OR R1 R2 - OR (bit a bit) de dois registradores
void or(int r1, int r2){
if(DEBUG_MODE)
printf("OR %d %d\n", r1, r2);
GENERAL_REGISTERS[r1] = GENERAL_REGISTERS[r1] | GENERAL_REGISTERS[r2];
updatePEP(GENERAL_REGISTERS[r1]);
}
// 17 - NOT R1 - NOT (bit a bit) de um registrador
void not(int r1){
if(DEBUG_MODE)
printf("NOT %d\n", r1);
GENERAL_REGISTERS[r1] = ~ GENERAL_REGISTERS[r1];
updatePEP(GENERAL_REGISTERS[r1]);
}
// 18 - XOR R1 R2 - XOR (bit a bit) de dois registradores
void xor(int r1, int r2){
if(DEBUG_MODE)
printf("XOR %d %d\n", r1, r2);
GENERAL_REGISTERS[r1] = GENERAL_REGISTERS[r1] ^ GENERAL_REGISTERS[r2];
updatePEP(GENERAL_REGISTERS[r1]);
}
// 19 - ADD R1 R2 - Soma dois registradores
void add(int r1, int r2){
if(DEBUG_MODE)
printf("ADD %d %d\n", r1, r2);
GENERAL_REGISTERS[r1] += GENERAL_REGISTERS[r2];
updatePEP(GENERAL_REGISTERS[r1]);
}
// 20 - SUB R1 R2 - Subtrai dois registradores
void sub(int r1, int r2){
if(DEBUG_MODE)
printf("SUB %d %d\n", r1, r2);
GENERAL_REGISTERS[r1] -= GENERAL_REGISTERS[r2];
updatePEP(GENERAL_REGISTERS[r1]);
}
// 21 - MUL R1 R2 - Multiplica dois registradores
void mul(int r1, int r2){
if(DEBUG_MODE)
printf("MUL %d %d\n", r1, r2);
GENERAL_REGISTERS[r1] *= GENERAL_REGISTERS[r2];
updatePEP(GENERAL_REGISTERS[r1]);
}
// 22 - DIV R1 R2 - Dividendo entre dois registradores
void division(int r1, int r2){
if(DEBUG_MODE)
printf("DIV %d %d\n", r1, r2);
GENERAL_REGISTERS[r1] /= GENERAL_REGISTERS[r2];
updatePEP(GENERAL_REGISTERS[r1]);
}
// 23 - MOD R1 R2 - Resto entre dois registradores
void mod(int r1, int r2){
if(DEBUG_MODE)
printf("MOD %d %d\n", r1, r2);
GENERAL_REGISTERS[r1] %= GENERAL_REGISTERS[r2];
updatePEP(GENERAL_REGISTERS[r1]);
}
// 24 - CMP R1 R2 - Compara dois registradores
void cmp(int r1, int r2){
if(DEBUG_MODE)
printf("CMP %d %d\n", r1, r2);
updatePEP(GENERAL_REGISTERS[r1] - GENERAL_REGISTERS[r2]);
}
// 25 - TST R1 R2 - Testa dois registradores
void tst(int r1, int r2){
if(DEBUG_MODE)
printf("TST %d %d\n", r1, r2);
updatePEP(GENERAL_REGISTERS[r1] & GENERAL_REGISTERS[r2]);
}
void updatePEP(int result){
PEP = B00;
if(result == 0){
PEP = B10;
}
else if(result < 0){
PEP = B01;
}
}
void dumpRegisters(){
printf("-- REGISTERS --\n");
printf("PC:%d\nAP:%d\nPEP:%d\n", PC, AP, PEP);
int i;
for(i=0;i<4;i++){
printf("REG %d: %d\n", i, GENERAL_REGISTERS[i]);
}
printf("--- --- ---\n\n");
}
void execute(int code, int* operands){
switch(code){
case HALT:
halt();
break;
case LOAD:
load(operands[0], operands[1]);
break;
case STORE:
store(operands[0], operands[1]);
break;
case READ:
read(operands[0]);
break;
case WRITE:
write(operands[0]);
break;
case COPY:
copy (operands[0], operands[1]);
break;
case PUSH:
push(operands[0]);
break;
case POP:
pop(operands[0]);
break;
case JUMP:
jump(operands[0]);
break;
case JZ:
jz(operands[0]);
break;
case JNZ:
jnz(operands[0]);
break;
case JN:
jumpn(operands[0]);
break;
case JNN:
jnn(operands[0]);
break;
case CALL:
call(operands[0]);
break;
case RET:
ret();
break;
case AND:
and(operands[0], operands[1]);
break;
case OR:
or(operands[0], operands[1]);
break;
case NOT:
not(operands[0]);
break;
case XOR:
xor(operands[0], operands[1]);
break;
case ADD:
add(operands[0], operands[1]);
break;
case SUB:
sub(operands[0], operands[1]);
break;
case MUL:
mul(operands[0], operands[1]);
break;
case DIV:
division(operands[0], operands[1]);
break;
case MOD:
mod(operands[0], operands[1]);
break;
case CMP:
cmp(operands[0], operands[1]);
break;
case TST:
tst(operands[0], operands[1]);
break;
}
if(DEBUG_MODE)
dumpRegisters();
}
|
C
|
#include "shoveler/component/tilemap_sprite.h"
#include "shoveler/component/material.h"
#include "shoveler/component/tilemap.h"
#include "shoveler/component.h"
#include "shoveler/sprite/tilemap.h"
const char *const shovelerComponentTypeIdTilemapSprite = "tilemap_sprite";
static void *activateTilemapSpriteComponent(ShovelerComponent *component);
static void deactivateTilemapSpriteComponent(ShovelerComponent *component);
ShovelerComponentType *shovelerComponentCreateTilemapSpriteType()
{
ShovelerComponentTypeConfigurationOption configurationOptions[2];
configurationOptions[SHOVELER_COMPONENT_TILEMAP_SPRITE_OPTION_ID_MATERIAL] = shovelerComponentTypeConfigurationOptionDependency("material", shovelerComponentTypeIdMaterial, /* isArray */ false, /* isOptional */ false, /* liveUpdate */ NULL, /* liveUpdateDependency */ NULL);
configurationOptions[SHOVELER_COMPONENT_TILEMAP_SPRITE_OPTION_ID_TILEMAP] = shovelerComponentTypeConfigurationOptionDependency("tilemap", shovelerComponentTypeIdTilemap, /* isArray */ false, /* isOptional */ false, /* liveUpdate */ NULL, /* liveUpdateDependency */ NULL);
return shovelerComponentTypeCreate(shovelerComponentTypeIdTilemapSprite, activateTilemapSpriteComponent, /* update */ NULL, deactivateTilemapSpriteComponent, /* requiresAuthority */ false, sizeof(configurationOptions) / sizeof(configurationOptions[0]), configurationOptions);
}
ShovelerSprite *shovelerComponentGetTilemapSprite(ShovelerComponent *component)
{
assert(component->type->id == shovelerComponentTypeIdTilemapSprite);
return component->data;
}
static void *activateTilemapSpriteComponent(ShovelerComponent *component)
{
ShovelerComponent *materialComponent = shovelerComponentGetDependency(component, SHOVELER_COMPONENT_TILEMAP_SPRITE_OPTION_ID_MATERIAL);
assert(materialComponent != NULL);
ShovelerMaterial *material = shovelerComponentGetMaterial(materialComponent);
assert(material != NULL);
ShovelerComponent *tilemapComponent = shovelerComponentGetDependency(component, SHOVELER_COMPONENT_TILEMAP_SPRITE_OPTION_ID_TILEMAP);
assert(tilemapComponent != NULL);
ShovelerTilemap *tilemap = shovelerComponentGetTilemap(tilemapComponent);
assert(tilemap != NULL);
ShovelerSprite *tileSprite = shovelerSpriteTilemapCreate(material, tilemap);
return tileSprite;
}
static void deactivateTilemapSpriteComponent(ShovelerComponent *component)
{
ShovelerSprite *tileSprite = (ShovelerSprite *) component->data;
assert(tileSprite != NULL);
shovelerSpriteFree(tileSprite);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
typedef struct locality{
float latitude;
float longitude;
float elevation;
char* sitename;
int siteID;
} locality;
union coord_point {
float flt_x;
int int_x;
};//allows type flexibility, works similar to struct but cant simultaneously assign
void record_locality(struct locality* loc){
//... illustrates passing pointer to struct in function
}
int main (void){
locality loc1;
locality loc2;
locality loc3;
locality loc4;
loc1.latitude = 10.30;
loc1.longitude = -10.0;
float latitude = 0.0;
latitude = loc1.latitude;
return 0;
}
|
C
|
include <stdio.h>
int main()
{
int Number, Sum = 0;
printf("\n Please Enter any positive integer \n");
scanf(" %d",&Number);
Sum = (Number * (Number + 1) * (2 * Number + 1 )) / 6;
printf("\n The Sum of Series for %d = %d ",Number, Sum);
}
|
C
|
//Referred various sites for socket programming and then came up with this code.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>
#include <pthread.h>
#define LOOPS 100000
//Defining Thread Structure.....
struct thread_struct
{
int sock;
int value_buffer;
};
//UDP server receiving data.....
void *udpConnect(void *arg)
{
struct thread_struct *thread_arg = (struct thread_struct *)arg;
struct sockaddr_in client_addr;
char * buffer = (char *)malloc(sizeof(char) * thread_arg -> value_buffer);
int size_sockaddr = sizeof(struct sockaddr_in);
memset(buffer, 0, sizeof(char) * thread_arg -> value_buffer);
int i = 0;
while (i < LOOPS) {
recvfrom(thread_arg -> sock, buffer, thread_arg -> value_buffer, 0, (struct sockaddr *)&client_addr, &size_sockaddr);
}
i++;
printf("UDP server receiving Data....\n" );
}
//UDP server Functioning....
void udpServer(int value_buffer, int thread_num)
{
int sock_server, s_bind;
struct sockaddr_in server_addr;
if (value_buffer == 65000)
{
value_buffer = 64500;
}
char * buffer = (char *)malloc(sizeof(char) * value_buffer);
memset(buffer, 0, sizeof(char) * value_buffer);
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
server_addr.sin_port = htons(4567);
//Createing socket...
sock_server = socket(AF_INET, SOCK_DGRAM, 0);
if(sock_server == -1)
{
exit(-1);
}
//Bind socket....
s_bind = bind(sock_server, (struct sockaddr *)&server_addr, sizeof(struct sockaddr));
if(s_bind == -1)
{
exit(-1);
}
pthread_t threads[thread_num];
int i = 0;
struct thread_struct * thread_arg = (struct thread_struct *)malloc(sizeof(struct thread_struct));
thread_arg -> sock = sock_server;
thread_arg -> value_buffer = value_buffer;
//Create many threads to process.
for (i = 0; i < thread_num; ++i)
{
pthread_create(&threads[i], NULL, udpConnect, thread_arg);
}
for (i = 0; i < thread_num; ++i)
{
pthread_join(threads[i], NULL);
}
close(sock_server);
}
//TCP Server receiving data....
void *tcpConnect(void *arg)
{
struct thread_struct *thread_arg = (struct thread_struct *)arg;
char * buffer = (char *)malloc(sizeof(char) * thread_arg -> value_buffer);
memset(buffer, 0, sizeof(char) * thread_arg -> value_buffer);
int i = 0;
for (i = 0; i < LOOPS; ++i)
{
recv(thread_arg -> sock, buffer, thread_arg -> value_buffer, 0);
}
free(buffer);
return NULL;
}
//TCP Server functioninf.....
void tcpServer(int value_buffer, int thread_num)
{
int sock_server, sock_client, s_bind;
struct sockaddr_in myserver_address;
struct sockaddr_in client_addr;
if (value_buffer == 65000)
{
value_buffer = 64500;
}
memset(&myserver_address, 0, sizeof(myserver_address));
myserver_address.sin_family = AF_INET;
myserver_address.sin_addr.s_addr = inet_addr("127.0.0.1");
myserver_address.sin_port = htons(4567);
//create socket.
sock_server = socket(AF_INET, SOCK_STREAM, 0);
s_bind = bind(sock_server, (struct sockaddr *)&myserver_address, sizeof(struct sockaddr));
if(s_bind == -1)
{
exit(-1);
}
//Begin listening.
listen(sock_server, 10);
printf("Server is listening....\n", );
int size_sockaddr = sizeof(struct sockaddr_in);
pthread_t threads[thread_num];
//Create many threads to process.
int i = 0;
while(i < thread_num)
{
sock_client = accept(sock_server, (struct sockaddr *)&client_addr, &size_sockaddr);
if(sock_client == -1)
{
exit(-1);
}
struct thread_struct * thread_arg = (struct thread_struct *)malloc(sizeof(struct thread_struct));
thread_arg -> sock = sock_client;
thread_arg -> value_buffer = value_buffer;
pthread_create(&threads[i], NULL, tcpConnect, thread_arg);
pthread_join(threads[i], NULL);
i++;
}
close(sock_client);
close(sock_server);
}
//Main function, select protocol according to the input.
int main(int argc, char *argv[])
{
int value_buffer = atoi(argv[2]);
int thread_num = atoi(argv[3]);
if (strcmp(argv[1], "UDP") == 0)
{
udpServer(value_buffer, thread_num);
} else {
tcpServer(value_buffer, thread_num);
}
if (argc != 4)
{
printf("Input three arguments: Connection type, buffer size and number of threads\n");
return 1;
}
return 0;
}
|
C
|
#include "t_token.h"
#include "exec.h"
#include <stdio.h>
struct s_token_to_prompt g_token_to_prompt[] =
{
{TK_PIPE,"pipe"},
{TK_AND_IF,"cmdand"},
{TK_OR_IF,"cmdor"},
{TK_IF, "if"},
{TK_THEN,"then"},
{TK_ELSE,"else"},
{TK_ELIF,"elif"},
{TK_CASE,"case"},
{TK_WHILE,"while"},
{TK_UNTIL,"until"},
{TK_FOR,"for"},
{TK_LBRACE,"cursh"},
{TK_LPAREN,"subsh"},
{-1, NULL},
};
char *token_to_prompt(int token_id)
{
int i = 0;
while (g_token_to_prompt[i].string)
{
if (token_id == g_token_to_prompt[i].id)
return (g_token_to_prompt[i].string);
i++;
}
return (NULL);
}
char *parser_construct_prompt(t_ast_lst *ast_stack)
{
int token_id;
int token_next_id;
char *prompt;
char *token_prompt;
t_ast_lst *tmp;
prompt = NULL;
tmp = ast_stack;
while (tmp)
{
token_id = -1;
// printf("\n-----\n");
if (tmp->ast->token)
{
token_id = tmp->ast->token->id;
// debug_token(tmp->ast->token);
}
if (tmp->next && tmp->next->ast->token)
{
token_next_id = tmp->next->ast->token->id;
// debug_token(tmp->next->ast->token);
}
if (token_id == TK_RPAREN && token_next_id == TK_LPAREN)
{
token_prompt = "function";
tmp = tmp->next;
}
else
token_prompt = token_to_prompt(token_id);
if (token_prompt)
{
if (!prompt)
prompt = ft_strdup(token_prompt);
else
prompt = ft_strjoin3_free(token_prompt, " ", prompt, 1);
}
tmp = tmp->next;
}
// printf("prompt: %s\n", prompt);
return (prompt);
}
|
C
|
/*==============================================================================================================*/
/* Nom : lecture.c */
/* Auteur : Joseph CAILLET */
/* Desc : Lit des donnes depuis un fichier pour simuler la carte. */
/*==============================================================================================================*/
#include <ctype.h>
#include "lecture.h"
//Macro servant a :
//- quitter la fonction de lecture si une fin de fichier est rencontré
//- relancer une nouvelle aquisition si une trame est incorecte.
#define RETURN_IF_EOF_OR_READING_ERROR() res = checkErrors(res, etat, pf); \
if(res == -1) \
{ \
return absorb;\
} \
else if(res == 1) \
{ \
return lecture(pf, etat); \
}
/*------------------------------------------------------------------------------*/
/* Fonction : readSequence */
/* Params : FILE* pf, float* nb */
/* Retour : -1 si EOF, 1 si erreur, char caractere sinon. */
/* Desc : La fonction lit une sequence de 4 char ds pf */
/*------------------------------------------------------------------------------*/
int readSequence(FILE* pf, float* nb)
{
char tab[LONG_ELM_TRAME];
int i;
char res;
for(i = 0; i < LONG_ELM_TRAME; i++)
{
res = fgetc(pf);//lecture des 4 char
if(res == EOF)
{
return -1;//si fin fichier
}
else if(!isdigit(res))
{
return 1;//si erreur de lecture
}
tab[i] = res - 48;//transformaton du char ascii en nb
}
*nb = (tab[0] ) * 1000 + (tab[1] ) * 100 + (tab[2] ) * 10 + (tab[3] );//calcul du nombre
return 0;
}
/*------------------------------------------------------------------------------*/
/* Fonction : isSeparatorValid */
/* Params : FILE* pf, float* nb */
/* Retour : -1 si EOF, 1 si erreur, char caractere sinon. */
/* Desc : La fonction lit un char dan pf et vérifie suivant le mode si */
/* le separateur est bien valide */
/*------------------------------------------------------------------------------*/
int isSeparatorValid(FILE* pf, int mode)
{
char c1;
char c2;
if(mode == 0)//si separateur de nombre en cour de trame
{
c1 = fgetc(pf);
if(c1 == EOF)
{
return -1;//si fin fichier
}
else if(c1 != ',')
{
return 1;//si separarteur n'est pas une virgule
}
return 0;//separateur ok
}
else if(mode == 1)
{
c1 = fgetc(pf);
c2 = fgetc(pf);
if(c1 == EOF || c2 == EOF)
{
return -1;//si fin de fichier
}
else if(c1 != '\n' || c2 != '\r')
{
return 1;//si séparateur n'est pas LFCR
}
return 0;//separateur ok
}
return -1;//erreur mode incorect
}
/*------------------------------------------------------------------------------*/
/* Fonction : checkErrors */
/* Params : int res, int* eof, FILE* pf */
/* Retour : -1 si EOF, 1 si erreur, 0 sinon. */
/* Desc : La fonction verifie si il y a de erreurs: rerourne -1 si eof, */
/* 1 si erreur de lecture et trame de pf stabilise, 0 sinon. */
/*------------------------------------------------------------------------------*/
int checkErrors(int res, int* eof, FILE* pf)
{
if(res == -1)
{
*eof = EOF;
return -1;//fin de fichier
}
else if(res == 1)
{
if(waitForValidTrame(pf) == -1)//on passe a latrame suivante
{
*eof = EOF;
return -1;//fin de fichier
}
return 1;//la trame comportait une erreur, et le fichier à été remis ds un état valide.
}
else
{
return 0;//pas d'erreur
}
}
/*------------------------------------------------------------------------------*/
/* Fonction : waitForValidTrame */
/* Params : FILE* pf */
/* Retour : -1 si EOF, 1 si erreur, 0 sinon. */
/* Desc : La fonction stabilise la trame a un etat connu : rerourne -1 */
/* si eof, 1 si erreur de lecture et trame stabilise, 0 sinon. */
/*------------------------------------------------------------------------------*/
int waitForValidTrame(FILE* pf)
{
char c1, c2;
int continuer = 1;
while(continuer)//on lit des caracter tant que l'on est pas revenu a un etat stable, connu, celui de fin de trame.
{
c1 = c2;
c2 = fgetc(pf);
if(c1 == '\n' && c2 == '\r')//si fin de trame
{
continuer = 0;//on est revenu a un etat connu
}
else if(c1 == EOF || c2 == EOF)
{
return -1;// si fin de fichier
}
}
return 0;
}
/*------------------------------------------------------------------------------*/
/* Fonction : lecture */
/* Params : FILE* pf, int* etat */
/* Retour : absor. */
/* Desc : La fonction lit dan le fichier pf, et retourne une struc absorb */
/* avec les valeurs lues. etat est mis a EOF si fin du fichier */
/* rencontrée */
/*------------------------------------------------------------------------------*/
absorp lecture(FILE* pf, int* etat)
{
absorp absorb;
int res;
//memorisaton de acr
res = readSequence(pf, &absorb.acr);
RETURN_IF_EOF_OR_READING_ERROR()
//verification separateur ,
res = isSeparatorValid(pf, 0);
RETURN_IF_EOF_OR_READING_ERROR()
//memorisaton de dcr
res = readSequence(pf, &absorb.dcr);
RETURN_IF_EOF_OR_READING_ERROR()
//verification separateur ,
res = isSeparatorValid(pf, 0);
RETURN_IF_EOF_OR_READING_ERROR()
//memorisaton de acir
res = readSequence(pf, &absorb.acir);
RETURN_IF_EOF_OR_READING_ERROR()
//verification separateur ,
res = isSeparatorValid(pf, 0);
RETURN_IF_EOF_OR_READING_ERROR()
//memorisaton de dcir
res = readSequence(pf, &absorb.dcir);
RETURN_IF_EOF_OR_READING_ERROR()
//verification separateur LF CR
res = isSeparatorValid(pf, 1);
RETURN_IF_EOF_OR_READING_ERROR()
//supression de l'offset, retablissement de l'origine a zero
absorb.acr -= 2048;
absorb.acir -= 2048;
return absorb;
}
|
C
|
/*
* \brief MTZ model with lazy constraints.
* \authors Francesco Cazzaro, Marco Cieno
*/
#include <errno.h>
#include <limits.h>
#include <math.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <cplex.h>
#include "tsp_solvers.h"
#include "logging.h"
#include "tsp.h"
#include "tspconf.h"
/*!
* \brief Get the position of variable x(i,j) in CPLEX internal state.
*
*
* \param i
* i in x(i,j)
*
* \param j
* j in x(i,j)
*
* \param problem
* Pointer to the instance structure.
*/
size_t
_LazyMTZ_xpos ( size_t i, size_t j, const instance *problem )
{
if ( i == j ) {
log_fatal( "i == j" );
exit( EXIT_FAILURE );
}
return i * ( problem->nnodes - 1UL ) + j - ( j > i ? 1UL : 0UL );
}
/*!
* \brief Get the position of variable u(i) in MTZ model. 0-indexed.
*
*
* \param i
* i in u(i)
*
* \param problem
* Pointer to the instance structure.
*/
size_t
_LazyMTZ_upos ( size_t i, const instance *problem )
{
return problem->nnodes * ( problem->nnodes - 1UL ) + i - 1UL;
}
/*!
* \brief Add MTZ constraints to the problem.
*
*
* \param problem
* Pointer to the instance structure.
*
* \param env
* CPLEX environment.
*
* \param lp
* CPLEX problem.
*/
void
_add_constraints_LazyMTZ ( const instance *problem, CPXENVptr env, CPXLPptr lp )
{
char ctype = CPX_BINARY;
double lb = 0.0;
double ub = 1.0;
double obj;
double rhs;
char sense;
size_t lastrow;
char *cname = calloc( CPX_STR_PARAM_MAX, sizeof( *cname ) );
// add binary vars x(i,j) for all i, j
for ( size_t i = 0; i < problem->nnodes; ++i )
{
for ( size_t j = 0; j < problem->nnodes; ++j )
{
if( i == j ) continue;
snprintf( cname, CPX_STR_PARAM_MAX, "x(%zu,%zu)", i + 1, j + 1 );
obj = _euclidean_distance(
problem->xcoord[i],
problem->ycoord[i],
problem->xcoord[j],
problem->ycoord[j]
);
if ( CPXnewcols( env, lp, 1, &obj, &lb, &ub, &ctype, &cname ) ) {
log_fatal( "CPXnewcols [%s]", cname );
exit( EXIT_FAILURE );
}
if ( CPXgetnumcols( env, lp ) - 1 != _LazyMTZ_xpos( i, j, problem ) ) {
log_fatal( "CPXgetnumcols [%s: x(%zu, %zu)]",
cname, i + 1, j + 1 );
exit( EXIT_FAILURE );
}
}
}
// add degree constraints
rhs = 1.0;
sense = 'E';
// Sum[ x(i,h) ]_{i | i != h} = 1 for all h
for ( size_t h = 0; h < problem->nnodes; ++h )
{
snprintf( cname, CPX_STR_PARAM_MAX, "degree(%zu)", h + 1 );
if ( CPXnewrows( env, lp, 1, &rhs, &sense, NULL, &cname ) ) {
log_fatal( "CPXnewrows [%s]", cname );
exit( EXIT_FAILURE );
}
lastrow = CPXgetnumrows( env, lp ) - 1;
for ( size_t i = 0; i < problem->nnodes; ++i )
{
if ( i == h ) continue;
if ( CPXchgcoef( env, lp, lastrow, _LazyMTZ_xpos( i, h, problem ), 1.0 ) ) {
log_fatal( "CPXchgcoef [%s: x(%zu, %zu)]",
cname, i + 1, h + 1 );
exit( EXIT_FAILURE );
}
}
}
// Sum[ x(h,i) ]_{i | i != h} = 1 for all h
for ( size_t h = 0; h < problem->nnodes; ++h )
{
snprintf( cname, CPX_STR_PARAM_MAX, "degree(%zu)", h + 1 );
if ( CPXnewrows( env, lp, 1, &rhs, &sense, NULL, &cname ) ) {
log_fatal( "CPXnewrows [%s]", cname );
exit( EXIT_FAILURE );
}
lastrow = CPXgetnumrows( env, lp ) - 1;
for ( size_t i = 0; i < problem->nnodes; ++i )
{
if ( i == h ) continue;
if ( CPXchgcoef( env, lp, lastrow, _LazyMTZ_xpos( h, i, problem ), 1.0 ) ) {
log_fatal( "CPXchgcoef [%s: x(%zu, %zu)]",
cname, h + 1, i + 1 );
exit( EXIT_FAILURE );
}
}
}
// add sequences vars u(i)
ctype = CPX_CONTINUOUS;
lb = 2.0;
ub = problem->nnodes;
obj = 0.;
for ( size_t i = 1; i < problem->nnodes; ++i )
{
snprintf( cname, CPX_STR_PARAM_MAX, "u(%zu)", i + 1 );
if( CPXnewcols( env, lp, 1, &obj, &lb, &ub, &ctype, &cname ) ) {
log_fatal( "CPXnewcols [%s]", cname );
exit( EXIT_FAILURE );
}
if ( CPXgetnumcols( env, lp ) - 1 != _LazyMTZ_upos( i, problem ) ) {
log_fatal( "CPXgetnumcols [%s]", cname );
exit( EXIT_FAILURE );
}
}
// Lazy constraints
int rmatbeg = 0;
int *rmatind = malloc( CPXgetnumcols( env, lp ) * sizeof( *rmatind ) );
double *rmatval = malloc( CPXgetnumcols( env, lp ) * sizeof( *rmatval ) );
if ( rmatind == NULL || rmatval == NULL ) {
log_fatal( "Out of memory." );
exit( EXIT_FAILURE );
}
// u(i) - u(j) + n x(i,j) <= n - 1 for all i, j | i != j, i != 0, j != 0
rhs = problem->nnodes - 1;
sense = 'L';
for ( size_t j = 1; j < problem->nnodes; ++j )
{
for ( size_t i = 1; i < problem->nnodes; ++i )
{
if ( i == j ) continue;
snprintf( cname, CPX_STR_PARAM_MAX, "sequence(%zu)", j + 1 );
rmatind[0] = (int) _LazyMTZ_upos( i, problem );
rmatval[0] = +1.0;
rmatind[1] = (int) _LazyMTZ_upos( j, problem );
rmatval[1] = -1.0;
rmatind[2] = (int) _LazyMTZ_xpos( i, j, problem );
rmatval[2] = (double) problem->nnodes;
if ( CPXaddlazyconstraints( env, lp, 1, 3, &rhs, &sense, &rmatbeg, rmatind, rmatval, &cname ) ) {
log_fatal( "CPXaddlazyconstraints [%s]", cname );
exit( EXIT_FAILURE );
}
}
}
free( rmatind );
free( rmatval );
free( cname );
}
void
LazyMTZ_model ( instance *problem )
{
int error;
CPXENVptr env = CPXopenCPLEX( &error );
CPXLPptr lp = CPXcreateprob( env, &error, problem->name ? problem->name : "TSP" );
/* BUILD MODEL */
log_info( "Adding constraints to the model." );
_add_constraints_LazyMTZ( problem, env, lp );
/* CPLEX PARAMETERS */
tspconf_apply( env );
struct timespec start, end;
clock_gettime( CLOCK_MONOTONIC, &start );
log_info( "Starting solver." );
if ( CPXmipopt( env, lp ) ) {
log_fatal( "CPXmipopt error." );
exit( EXIT_FAILURE );
}
clock_gettime( CLOCK_MONOTONIC, &end );
log_info( "Retrieving final solution." );
double *xopt = malloc( CPXgetnumcols( env, lp ) * sizeof( *xopt ) );
if ( xopt == NULL ) {
log_fatal( "Out of memory." );
exit( EXIT_FAILURE );
}
CPXsolution( env, lp, NULL, NULL, xopt, NULL, NULL, NULL );
_xopt2solution( xopt, problem, &_LazyMTZ_xpos );
free( xopt );
problem->elapsedtime = ( end.tv_sec - start.tv_sec ) + ( end.tv_nsec - start.tv_nsec ) / 1000000000.;
problem->visitednodes = CPXgetnodecnt( env, lp );
problem->solcost = compute_solution_cost( problem );
CPXfreeprob( env, &lp );
CPXcloseCPLEX( &env );
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.