language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
|---|---|
C
|
/* Program that simulates the game "Game of Life".
* First, takes 3 inputs, rows, columns and number of steps/generations
* Then takes the initial board state
* Returns the board state of the final generation/step
*/
#include <stdio.h>
#include <stdlib.h>
/*
* Constants for alive and dead cells, can be changed
*/
#define ALIVE 'X'
#define DEAD '.'
/*
* Initialises the board with the user input
* Takes the number of rows and columns as well as the board pointer
* Sets the board position to be user's input if it passes a conditional statement
*/
void initialiseBoard(int rows, int cols, char **board) {
char tempChar;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
scanf(" %c", &tempChar);
/* Checks to see if the user input format is correct before assigning to board
* closes the program if not
* */
if (tempChar == ALIVE || tempChar == DEAD) {
board[i][j] = tempChar;
} else {
printf("Error. Board value must be '%c' or '%c'.\n", ALIVE, DEAD);
exit(1);
}
}
}
}
/*
* Method used to check a cell's value
* Takes the working row and column, total rows and columns as well as the board
* Returns 0 if the cell is dead or out of bounds
* Returns 1 if the cell is alive
*/
int getNeighbourValue(int row, int col, int rows, int cols, char **board) {
if (row < 0 || row >= rows || col < 0 || col >= cols || board[row][col] != ALIVE) {
return 0;
}
else {
return 1;
}
}
/*
* Method that counts the number of alive neighbouring cells
* Takes the working row and column, total rows and columns as well as the board
* Returns the total count
*/
int getNeighbourCount(int row, int col, int rows, int cols, char **board) {
int count = 0;
/* Statements used to check each surrounding cell and then adding the value to the counter */
count += getNeighbourValue(row - 1, col - 1, rows, cols, &*board);
count += getNeighbourValue(row - 1, col, rows, cols, &*board);
count += getNeighbourValue(row - 1, col + 1, rows, cols, &*board);
count += getNeighbourValue(row, col - 1, rows, cols, &*board);
count += getNeighbourValue(row, col + 1, rows, cols, &*board);
count += getNeighbourValue(row + 1, col - 1, rows, cols, &*board);
count += getNeighbourValue(row + 1, col, rows, cols, &*board);
count += getNeighbourValue(row + 1, col + 1, rows, cols, &*board);
return count;
}
/*
* Method that writes the new generated board to the original
* Takes the total rows and cols as well as the original and new boards.
*/
void writeNewGen(int rows, int cols, char **board, char **newBoard) {
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
board[row][col] = newBoard[row][col];
}
}
}
/* Prints the results
* Takes the number of rows and columns as well as board as a char
* Loop through the board treating it like a matrix and print the content of each cell
* as a char
*/
void printResult(int rows, int cols, char **board) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%c", board[i][j]);
}
printf("\n");
}
}
/*
* Method used to run the simulation
* Takes the total rows and columns, the number of steps desired and the board
*/
void runSimulation(int rows, int cols, int steps, char **board) {
/* Dynamically allocate a new array of pointers to pointers that will be used for new generations*/
char **newBoard;
newBoard = (char **)malloc(rows * sizeof(char *));
for (int i = 0; i < rows; i++) {
newBoard[i] = (char *)malloc(cols * sizeof(char));
}
if (newBoard == NULL) {
printf("Error. Not enough space available.\n");
exit(1);
}
/* Loop used to simulate passing generations */
for(int gen = 0; gen < steps; gen++) {
int r, c;
for(r = 0; r < rows; r++) {
for(c = 0; c < cols; c++) {
/* Variable used to call the function that counts the total number of alive neighbours and stores it */
int neighbourCount = getNeighbourCount(r, c, rows, cols, &*board);
/* Check the count with the rules of the game and set the value on the new board*/
if(neighbourCount == 3) {
newBoard[r][c] = ALIVE;
} else if(neighbourCount == 2 && board[r][c] == ALIVE) {
newBoard[r][c] = ALIVE;
} else {
newBoard[r][c] = DEAD;
}
}
}
/* Write the new board state to the original after a generation passes */
writeNewGen(rows, cols, &*board, &*newBoard);
}
/* Free the memory space used for the new board */
free(newBoard);
}
/* Main function to take input and call the simulation and printing */
int main() {
/* Taking the initial input line */
int rows, cols, steps;
scanf("%d %d %d", &rows, &cols, &steps);
if (rows <= 0 || cols <= 0) {
printf("Error. Rows and columns must be larger than 0.\n");
exit(1);
}
/* Dynamically allocate an array of pointers to pointers that will be used as the game board*/
char **board;
board = (char **)malloc(rows * sizeof(char *));
for (int i = 0; i < rows; i++) {
board[i] = (char *)malloc(cols * sizeof(char));
}
/* Check to see if memory space was given, if not then exist */
if (board == NULL) {
printf("Error. Not enough space available.\n");
exit(1);
}
/* Calls for the functions responsible for the initialisation, simulation and priting */
initialiseBoard(rows, cols, &*board);
runSimulation(rows, cols, steps, &*board);
printResult(rows, cols, &*board);
/* Free the memory space used for the board */
free(board);
return 0;
}
|
C
|
#include <stdio.h>
#define LENGTH 6;
int binsearch(int i, int j[], int q);
int main () {
int x, n, i;
x = 3;
n = LENGTH;
int v[n];
for (i = 0; i < n; i++) {
v[i] = i + 1;
printf("%d \n", v[i]);
}
printf("index: %d \n", binsearch(x,v,n));
}
int binsearch(int x, int v[], int n) {
int low, high, mid;
low = 0;
high = n-1;
mid = (low + high) / 2;
while (low <= high && x != v[mid]) {
if (x < v[mid]) {
high = mid - 1;
} else {
low = mid + 1;
}
mid = (low + high) / 2;
}
if (x == v[mid]) {
return mid;
} else {
return -1;
}
}
|
C
|
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
/* Type definitions */
typedef int /*<<< orphan*/ Oid ;
/* Variables and functions */
int /*<<< orphan*/ InvalidOid ;
scalar_t__ nextTempTableSpace ;
scalar_t__ numTempTableSpaces ;
int /*<<< orphan*/ * tempTableSpaces ;
Oid
GetNextTempTableSpace(void)
{
if (numTempTableSpaces > 0)
{
/* Advance nextTempTableSpace counter with wraparound */
if (++nextTempTableSpace >= numTempTableSpaces)
nextTempTableSpace = 0;
return tempTableSpaces[nextTempTableSpace];
}
return InvalidOid;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <time.h>
#include "headers.h"
int main(int argc, char * argv[]){
welcomeScreen();
char * name = getName();
char * player = playerSelection(name);
char ** winLose; // first is winner, second is loser
if (strcmp(player, "A") == 0){
hiAnswerer();
char * category = getCategory();
char * object = getObject(category);
confirmSelection(category, object);
winLose = setupServer(name, category, object);
free(winLose);
}
else if (strcmp(player, "Q") == 0) {
srand(time(NULL));
hiQuestioner();
setupClient(name);
}
// int playAgainA = endScreenA();
// int playAgainQ = endScreenQ();
//
// if (playAgainA == 0){
// printScoreboardA(winLose);
// //printf("Thanks for playing! \n");
// }
// if (playAgainQ == 0){
// printScoreboardQ(winLose);
// //printf("Thanks for playing! \n");
// }
// if (playAgainA == 1){
// char * category = getCategory();
// char * object = getObject(category);
// confirmSelection(category, object);
// winLose = setupServer(name, category, object);
// }
// if (playAgainQ == 1){
// hiQuestioner();
// setupClient(name);
// }
printf("\n----------------------------------\n\n\n");
printf("THANKS FOR PLAYING! \n");
printf("\n\n\n----------------------------------\n\n\n");
free(name);
free(player);
return 0;
}
//******************************************
void welcomeScreen(){
printf("\n\n\n\n");
printf("----------------------------------\n\n\n");
printf("WELCOME TO 20 QUESTIONS!\n\n");
printf("By Christina Tan and Stephanie Liu\n\n\n");
printf("----------------------------------\n\n\n");
sleep(1);
}
char * getName() {
char * name = malloc(20);
printf("Enter your name: ");
fgets(name, 20, stdin);
name[strlen(name) - 1] = 0;
return name;
}
char * playerSelection(char * name){
char * player = malloc(10);
printf("\nWelcome %s!\n\n", name);
sleep(1);
while (! (strcmp(player, "A") == 0 || strcmp(player, "Q") == 0)) {
printf("Would you like to be an answerer or questioner? (A / Q): ");
fgets(player, 10, stdin);
player[strlen(player)-1] = 0;
printf("\n");
}
printf("\n----------------------------------\n\n\n");
return player;
}
//
// int endScreen(){
// printf("----------------------------------\n\n\n");
// printf("THANKS FOR PLAYING!\n\n");
// char *next = malloc (10);
// while (! (strcmp(next, "Y") == 0 || strcmp(next, "N") == 0)) {
// printf("\n\n Play Again? (Y/N) ");
// fgets(next, 2, stdin);
// }
// if (strcmp(next, "Y") == 0){
// return 1;
// } if (strcmp(next, "N") == 0){
// return 0;
// }
// return -1;
// }
// void printScoreboard(char * winner, char * loser){
// printf("----------------------------------\n\n\n");
// printf("Scoreboard: \n");
// printf("%-10s\t\t %-10d\n", winner, 1);
// printf("%-10s\t\t %-10d\n\n\n", loser, 0);
// printf("----------------------------------\n\n\n");
// }
|
C
|
#include "linkqueue.h"
#include "BFS.h"
int visit[N] = {0};
graph_t * graph_create(){
graph_t *g = (graph_t *)malloc(sizeof(graph_t));
int i = 0;
for (i = 0; i < N; ++i)
{
g->V[i] = i;
}
return g;
}
int graph_input(graph_t * g)
{
int i,j;
while(scanf("%d %d", &i, &j) == 2)
{
//while( getchar() != '\n');
getchar();
// g->A[i][j] = 1;
g->A[i][j] = g->A[j][i] = 1;
}
return 0;
}
int graph_output(graph_t * g)
{
int i,j;
printf(" V0 V1 V2 V3 V4 \n");
for (i = 0; i < N; ++i)
{
printf("V%d ", i);
for (j = 0; j < N; ++j)
{
printf(" %d ", g->A[i][j]);
}
putchar(10);
}
return 0;
}
int adj_first(graph_t * g, int v)
{
int i;
for (i = 0; i < N; ++i)
{
if ( 1 == g->A[v][i])
{
return i;
}
}
return -1;
}
int adj_next(graph_t * g, int v, int u)
{
int i;
for (i = u + 1; i < N; ++i)
{
if ( 1 == g->A[v][i])
{
return i;
}
}
return -1;
}
int DFS(graph_t *g, int v)
{
int u;
printf("%d ", v);
visit[v] = 1;
//printf(" pppppppp ");
//getchar();
u = adj_first(g, v);
while( u >= 0 )
{
if ( visit[u] == 0 )
{
DFS(g, u);
}
u = adj_next(g, v, u);
}
return 0;
}
int BFS(graph_t *g, int v)
{
int u;
//创建一个队列
linkqueue_t *lq = linkqueue_create();
//将根结点入队
linkqueue_input(lq, v);
visit[v] = 1;
//循环出队,
while(!linkqueue_empty(lq))
{
v = linkqueue_output_undel(lq);
printf("v = %d ", v);
u = adj_first(g, v);
while( u >= 0)
{
if (visit[u] == 0)
{
visit[u] = 1;
linkqueue_input(lq, u);
}
u = adj_next(g, v, u);
}
}
return 0;
}
int main(int argc, char const *argv[])
{
graph_t *g;
int j;
g = graph_create();
graph_input(g);
graph_output(g);
DFS(g, 0);
putchar(10);
for (j = 0; j < N; ++j)
{
visit[j] = 0;
}
BFS(g, 1);
putchar(10);
return 0;
}
|
C
|
/*Write a program to implement Singly Linked lists of integers.
1.Write function insert_end() to insert an element at end of linked list. Take Linked List pointer and integer as two arguments.
2.Write function insert_beg() to insert at beginning of linked list. Take Linked List pointer and integer as two arguments.
3.Write function delete_beg() & delete_end() to delete element from linked list. Take Linked List pointer only as single argument.
4.Write function search() to search as element in Linked list and return node address. Return NULL for failed search.
5.Write function insert_after() to insert an element after above search() function. Insert element at end for failed search().
6.Write function display() to print the elements of linked list. Take Linked List pointer only as single argument.*/
#include<stdio.h>
#include<stdlib.h>
struct node{
int val;
struct node *next;
};
struct node* insert_beg(struct node *head, int val)
{
struct node *temp = (struct node* )malloc(sizeof(struct node));
temp->val = val;
temp->next = NULL;
if(head == NULL)
{
head = temp;
return head;
}
temp->next = head;
head = temp;
return head;
}
struct node* insert_end(struct node *head, int val)
{
struct node *temp = (struct node* )malloc(sizeof(struct node));
struct node *t_head;
temp->val = val;
temp->next = NULL;
if(head == NULL)
{
head = temp;
return head;
}
t_head = head;
while(t_head->next != NULL)
t_head = t_head->next;
t_head->next = temp;
return head;
}
struct node* delete_beg(struct node *head)
{
struct node *temp;
int val;
if(head == NULL)
{
printf("\nList is empty\n");
return head;
}
val = head->val;
temp = head;
head = head->next;
free(temp);
return head;
}
struct node* delete_end(struct node *head)
{
struct node *temp, *thead;
if(head == NULL)
{
printf("\nList is empty\n");
return head;
}
thead = head;
while(thead->next != NULL)
{
temp = thead;
thead = thead->next;
}
free(temp->next);
temp->next = NULL;
return head;
}
struct node* insert_after(struct node *head, int pos, int val)
{
struct node *temp, *newNode;
newNode = (struct node*)malloc(sizeof(struct node));
if(head == NULL)
{
printf("\nList is empty\n");
return head;
}
temp = head;
while(temp != NULL)
{
if(temp->val == pos)
{
newNode->val = val;
newNode->next = temp->next;
temp->next = newNode;
return head;
}
temp = temp->next;
}
printf("\nValue %d is not in the list \n", val);
return head;
}
void display(struct node *head)
{
if(head == NULL)
printf("\nList is empty\n");
printf("\nValue is ");
while(head != NULL)
{
printf("%d\t", head->val);
head = head->next;
}
}
struct node* search(struct node *head, int val)
{
struct node *temp;
temp = head;
while(temp != NULL)
{
if(temp->val == val)
{
printf("\nElement %d is found in the list \n", val);
return head;
}
temp = temp->next;
}
printf("\nElement %d is not found in the list \n", val);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* parser_heredoc.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: llecoq <llecoq@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/08/17 12:55:03 by llecoq #+# #+# */
/* Updated: 2021/09/17 17:46:18 by llecoq ### ########.fr */
/* */
/* ************************************************************************** */
#include "minishell.h"
static void interpret_and_write_into_fd(int fd, char *input, t_shell *shell)
{
replace_token_with_var(&input, shell);
write(fd, input, ft_strlen(input));
write(fd, "\n", 1);
}
static void heredoc_prompt(t_shell *shell, char *limiter, int fd)
{
char *input;
while (1)
{
input = readline("> ");
if (input)
{
if (ft_strncmp(input, limiter, ft_strlen(limiter) + 1) == 0)
{
free(input);
return ;
}
interpret_and_write_into_fd(fd, input, shell);
}
else if (input == NULL)
return ;
}
}
static void search_for_heredoc(t_token *token_list, t_cmd *cmd, char **limiter)
{
t_token *token;
token = token_list;
while (token)
{
if (token->redir == HEREDOC)
{
cmd->redir.from_heredoc = EXISTENT;
(*limiter) = token->next->word;
return ;
}
token = token->next;
}
return ;
}
void create_heredoc(t_shell *shell, t_token **cmd_array, t_cmd *cmds_list)
{
char *limiter;
int pipefd[2];
int i;
t_cmd *cmd;
cmd = cmds_list;
i = 0;
while (cmd_array[i] != NULL)
{
search_for_heredoc(cmd_array[i], cmd, &limiter);
if (cmd->redir.from_heredoc == EXISTENT)
{
if (pipe(pipefd) == FAILED)
error_quit(shell, SYSCALL_ERROR, NULL);
heredoc_prompt(shell, limiter, pipefd[1]);
close(pipefd[1]);
cmd->redir.from_heredoc = pipefd[0];
}
cmd = cmd->next;
i++;
}
}
|
C
|
/* PROTO-SHELL CRIADO POR CAMILO LIRA SIDOU
* para a matéria de Sistemas Operacionais
* ministrada pelo prof. André Carvalho
* Engenharia de Software - iComp - UFAM
* 01/09/2019
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
// INPUT_DELIM: caracteres a serem retirados pelo strtok;
// INPUT_SIZE: tamanho max de um input do user;
// MAX_ARG: num max. de argumentos que podem ser passados;
// NUM_INT_FUNC: numero de funcoes internas do shell.
#define INPUT_DELIM " \n"
#define INPUT_SIZE 128
#define MAX_ARG 10
#define NUM_INT_FUNC 3
// array de funções nativas do shell
// PS: 'exit' teve implementação particular
char* int_func[] = {"help", "pwd", "cd"};
// declarações antecipadas das funções internas do shell:
int int_help(char** args);
int int_pwd(char** args);
int int_cd(char** args);
// função-ponteiro que executa as funções nativas do shell:
int (*int_func_exec[]) (char** args) = {
&int_help,
&int_pwd,
&int_cd
};
// declarações antecipadas das funções utilizadas:
int cout_intro();
int read_input(char* usr_input);
int parse_input(char* usr_input, char** parsd_input);
int parse_input_piped(char* usr_input, char** usr_input_piped);
int exec_prog(char** args);
int exec_prog_piped(char** args1, char** args2);
// desativei essa função pois estava dando erro:
// free(): double free detected in tcache2
// irei investigar a causa
int clear_buff(char** array, int col);
int main() {
char *usr_input; // input do user
char** usr_input_piped; // input do user dividido se houver pipe
char** parsd_input; // input depois do parse
char** parsd_input_2; // input depois do parse do 2º comando
char *buf; // bufer utilizado para o strtok;
int status = 1; // 1 = programa rodando / 0 = fim do programa
int p_pid, wid; // guardam os retornos do fork e wait, respectiv.
// alocações dinâmicas dos arrays declarados acima:
usr_input = malloc(INPUT_SIZE * sizeof(char));
usr_input_piped = malloc(MAX_ARG * sizeof(char*));
for (int i = 0; i < MAX_ARG; i++) {
usr_input_piped[i] = malloc(INPUT_SIZE * sizeof(char));
}
parsd_input = malloc(MAX_ARG * sizeof(char*));
for (int i = 0; i < MAX_ARG; i++) {
parsd_input[i] = malloc(INPUT_SIZE * sizeof(char));
}
parsd_input_2 = malloc(MAX_ARG * sizeof(char*));
for (int i = 0; i < MAX_ARG; i++) {
parsd_input_2[i] = malloc(INPUT_SIZE * sizeof(char));
}
// imprime a intro. na tela:
cout_intro();
// loop principal de execução do programa:
while (status) {
printf("> ");
read_input(usr_input);
parse_input_piped(usr_input, usr_input_piped);
parse_input(usr_input_piped[0], parsd_input);
// verif. do comando 'exit':
if (parsd_input[0] != NULL) {
if (!strcmp(parsd_input[0], "exit")) {
status = 0;
free(usr_input);
//clear_buff(parsd_input, MAX_ARG);
exit(0);
}
}
// verif. se o comando é piped:
if (usr_input_piped[1] != NULL) {
parse_input(usr_input_piped[1], parsd_input_2);
exec_prog_piped(parsd_input, parsd_input_2);
}
// senao é piped, roda o comando unico:
else if (parsd_input[0] != NULL)
exec_prog(parsd_input);
}
return 0;
}
// funcao que imprime a intro. do shell:
int cout_intro() {
printf("==================================================\n");
printf("TERMINAL ALPHA VERSÃO 0.1 INICIALIZADO\n");
printf("criado por Camilo Lira Sidou para a materia de SO\n");
printf("2 de Setembro de 2019\n");
printf("==================================================\n");
printf("\n");
printf("Digite 'help' para listar os comandos disponiveis!\n");
printf("\n");
return 1;
}
// funcao que lê o input do user e guarda na var. usr_input
int read_input(char* usr_input) {
fgets(usr_input, INPUT_SIZE, stdin);
return 1;
}
// faz o parse (divisao) do input e salva em parsd_input
int parse_input(char* usr_input, char** parsd_input) {
char* buf;
int i = 0;
buf = strtok(usr_input, INPUT_DELIM);
while (buf != NULL) {
parsd_input[i++] = buf;
buf = strtok(NULL, INPUT_DELIM);
}
while (i < MAX_ARG) parsd_input[i++] = NULL;
return 1;
}
/* divide o input do user de acordo com o pipe, por exemplo:
* input: pipe1 | pipe2
* pipe1 sera guardado no indice 0 de usr_input_piped
* pipe2 sera guardado no indice 1 de usr_input_piped
*/
int parse_input_piped(char* usr_input, char** usr_input_piped) {
int p_pid = -1;
int exec_r = -1;
int i = 0;
char* buf;
usr_input_piped[1] = NULL;
buf = strtok(usr_input, "|");
while (buf != NULL) {
usr_input_piped[i++] = buf;
buf = strtok(NULL, "|");
}
while (i < MAX_ARG) usr_input_piped[i++] = NULL;
if (usr_input_piped[1] == NULL) return 0;
return 1;
}
// executa um programa se nao houver pipe:
int exec_prog(char** args) {
int p_pid = -1;
int exec_r;
int in, out;
// checa se é uma funcao interna do shell e a executa se o for:
for (int i = 0; i < NUM_INT_FUNC; i++) {
if (strstr(args[0], int_func[i]) != 0) {
return (*int_func_exec[i])(args);
}
}
p_pid = fork();
if (p_pid < 0) {
printf("\n>> ERRO: O fork falhou. Abortando.\n\n");
exit(1);
}
else if (p_pid == 0) {
// checa se existe redirecionamento de input/output e abre
// os streams de in e out, bem como os arquivos, de acordo
// com o caso:
if (args[1] != NULL) {
if (!strcmp(args[1], "<")) {
in = open(args[2], O_RDONLY);
if (in < 0) {
printf("\n>>ERRO: arquivo nao encontrado\n\n");
close(in);
exit(1);
}
dup2(in, 0);
close(in);
}
if (!strcmp(args[1], ">")) {
out = open(args[2], O_WRONLY | O_CREAT, 0666);
if (out < 0) {
printf("\n>>ERRO: nao foi possivel criar o arquivo\n\n");
close(out);
exit(1);
}
dup2(out, 1);
close(out);
}
}
// execucao de fato do programa:
exec_r = execvp(args[0], args);
if (exec_r < 0 ) {
printf("\n>> ERRO: comando desconhecido\n\n");
exit(1);
}
}
else wait(NULL);
return 1;
}
// faz a execucao dos comandos caso haja pipe, onde
// args1 e args2 são vetores de *strings*, cada um
// contendo as linhas de comando divididas, com cada
// parametro em um índice:
int exec_prog_piped(char** args1, char** args2) {
int pipe_io[2];
int p_pid1, p_pid2;
// checa se é uma funcao interna do shell e a executa se o for:
for (int i = 0; i < NUM_INT_FUNC; i++) {
if (strstr(args1[0], int_func[i]) != 0) {
return (*int_func_exec[i])(args1);
}
}
// inicializa o pipe:
if (pipe(pipe_io) < 0) {
printf("\n>> ERRO: pipe nao executado\n\n");
}
// fork do primeiro processo (pipe1):
p_pid1 = fork();
if (p_pid1 < 0) {
printf("\n>> ERRO: O fork falhou. Abortando.\n\n");
return -1;
}
// fecha o input do filho pipe1, mantendo o output
// processo 1: escreve
if (p_pid1 == 0) {
close(pipe_io[0]);
dup2(pipe_io[1], 1);
close(pipe_io[1]);
if (execvp(args1[0], args1) < 0) {
printf("\n>> ERRO: argumento <pipe1> invalido\n");
exit(1);
}
}
else {
// fork do segundo processo (pipe2):
p_pid2 = fork();
if (p_pid2 < 0) {
printf("\n>> ERRO: O fork falhou. Abortando.\n\n");
return -1;
}
// fecha o output do filho pipe2, mantendo o input
// processo 2: lê
if (p_pid2 == 0) {
close(pipe_io[1]);
dup2(pipe_io[0], 0);
close(pipe_io[0]);
if (execvp(args2[0], args2) < 0) {
printf("\n>> ERRO: argumento <pipe2> invalido\n\n");
exit(1);
}
}
else {
// processo pai: aguarda a finalização de ambos os filhos
wait(NULL);
wait(NULL);
}
}
return 1;
}
// função que imprime os comandos nativos do shell:
int int_help(char** args) {
printf("\n");
printf(">> Comandos nativos do shell:\n");
printf("\n");
printf(" exit\n");
for (int i = 0; i < NUM_INT_FUNC; i++) {
printf(" %s\n", int_func[i]);
}
printf("\n");
return 1;
}
// função que mostra o diretorio corrente:
int int_pwd(char** args) {
char current_dir[300];
getcwd(current_dir, 300);
printf("\n");
printf("%s\n", current_dir);
printf("\n");
return 1;
}
// função para mudar o diretorio corrente:
int int_cd(char** args) {
int chdir_r;
if (args[1] == NULL) {
printf("\n>> ERRO: sintaxe do comando: cd <diretorio>\n\n");
return -1;
}
strtok(args[1], "\n");
chdir_r = chdir(args[1]);
if (chdir_r < 0) {
printf("\n>> ERRO: diretorio invalido\n\n");
}
else {
printf("\n>> Novo diretorio:");
int_pwd(NULL);
}
return 1;
}
// esse comando serviria para desalocar as arrays alocadas dinamicamente
// utilizando a função free(), porém ocorreu o seguinte erro:
// free(): double free detected in tcache2
// não achei informação sobre esse erro na internet, e chequei
// se não estava dando free duas vezes nas arrays, portanto deixarei
// desativada até entender exatamente qual foi o erro
int clear_buff(char** array, int lin) {
for (int i = 0; i < lin; i++) free(array[i]);
return 1;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
main () {
setlocale (LC_ALL, "portuguese");
int quantidadeMinima, quantidadeMaxima;
float estoqueMedio;
printf ("\n Digite o estoque Mínimo: ");
scanf ("%d", &quantidadeMinima);
printf ("\n Digite o estoque Máximo: ");
scanf ("%d", &quantidadeMaxima);
estoqueMedio = (quantidadeMinima + quantidadeMaxima) / 2;
printf ("\n Quantidade Média do estoque: %.2f", estoqueMedio);
system ("pause");
return 0;
}
|
C
|
#include "holberton.h"
/**
* select_function - structured list to work with it
* @format: string with operators
* @list: list of arguments to print
* Return: numbers of char printed
*/
int select_function(char format, va_list list)
{
unsigned int i = 0, result = 0;
f_type operator[] = {
{'c', print_char},
{'s', print_str},
{'d', print_int},
{'i', print_int},
{'u', print_unsigned},
{'o', print_octal},
{'x', print_hex},
{'X', print_HEX},
{'b', print_bin},
{'S', print_Str_Ascii},
{'r', print_rev_str},
{'R', print_rot13},
{'\0', NULL}};
while (operator[i].c)
{
if (format == operator[i].c)
{
result += operator[i].f(list);
break;
}
i++;
}
if (result == 0)
return (0);
return (result);
}
|
C
|
/*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "cjson/cJSON.h"
#include "cjson/cJSON_ex.h"
#include "types.h"
#include "list.h"
struct list_head NodeListHead[HASHLISTLENTGH];
/**
* @brief init list hash table head.
*
* @returns none.
*
*/
void init_listtable(void)
{
int headpos = 0;
/*init list head*/
for(headpos = 0; headpos < HASHLISTLENTGH;headpos++)
{
INIT_LIST_HEAD(&NodeListHead[headpos]);
}
}
/**
* @brief 根据字符串计算hash值.
* @input
* @returns hash值.
*
*/
int GetHash(char *string)
{
int hash = 0;
int flag = 0;
char *p = NULL;
int data16 = 0;
p = string;
while(*p != '\0')
{
if(flag)
{
data16 |= (*p++)<<8;
}
else
{
data16 = (*p++);
}
hash ^= 0x9e3779b9 + (data16<<6) + (data16>>2);
flag ^= 1;
}
hash = abs(hash);
hash = hash % HASHLISTLENTGH;
return hash;
}
/**
* @brief : add member to hash table list.
*
* @returns 0:ok -1:error.
*
*/
int NodeAdd(NODE node,struct list_head *head)
{
NODE *pnode = NULL;
struct list_head *listhead = NULL;
struct list_head *listpos = NULL;
listhead = head;
listpos = listhead->next;
while(listpos != listhead)
{
pnode = list_entry(listpos, NODE, list);
if(0 == strcmp(pnode->name,node.name))
{
printf(" %s already exist\n",pnode->name);
return -1;
}
listpos = listpos->next;
}
pnode = malloc(sizeof(NODE));
if(pnode == NULL)
{
return -1;
}
strcpy(pnode->name, node.name);
strcpy(pnode->id, node.id);
list_add_tail(&pnode->list,head);
return 0;
}
/**
* @brief : remove listmember from list.
* @input : delete which list member from which list
* @returns 0:ok -1:error.
*
*/
int NodeDel(struct list_head *listpos,struct list_head *head)
{
NODE *pnode;
if(list_empty_careful(head))
{
printf("error : empty list \n");
return -1;
}
list_del(listpos);
pnode = list_entry(listpos, NODE, list);
free(pnode);
pnode = NULL;
return 0;
}
/**
* @brief : delete and free memory from a list.
* @input : delete which list,the head point of list
* @returns 0:ok .
*
*/
int DelAllNode(struct list_head *head)
{
struct list_head *listhead = NULL;
struct list_head *listpos = NULL;
listhead = head;
listpos = listhead->next;
while(listpos != listhead)
{
listpos = listpos->next;
NodeDel(listpos->prev,head);
}
return 0;
}
/**
* @brief : delete and free memory from tablelist.
* @input : none
* @returns 0:ok .
*
*/
int DelTableNode(void)
{
int cnt;
for(cnt = 0;cnt < HASHLISTLENTGH;cnt++)
{
DelAllNode(&NodeListHead[cnt]);
}
return 0;
}
int loadfile(void)
{
char indata[1000];
int errname,errid;
FILE * pFile;
cJSON *root_json =NULL;
char name[100];
char id[30];
NODE node;
int pos;
pFile = fopen ("./indata" , "r");
if (pFile == NULL)
{
return -1;
}
memset(indata, '\0', sizeof(indata));
while(NULL != fgets (indata , 1000 , pFile))
{
root_json = cJSON_Parse(indata);
if(root_json == NULL)
{
fprintf(stderr, "Parse Json Config Error before: [%s]\n", cJSON_GetErrorPtr());
fprintf(stderr, "[%s]\n", indata);
continue;
}
errname = getItemString(root_json,"name",name);
errid = getItemString(root_json,"id",id);
if(!errname && !errid)
{
strcpy(node.name,name);
strcpy(node.id,id);
pos = GetHash(node.name);
NodeAdd(node, &NodeListHead[pos]);
}
}
printf("load file end \n");
fclose(pFile);
unlink("./indata");
return 0;
}
/**
* @brief : print info of table list.
* @input : none
* @returns NONE .
*
*/
void PrintInfo(void)
{
NODE *pnode = NULL;
struct list_head *listhead = NULL;
struct list_head *listpos = NULL;
int hashval = 0;
for(hashval = 0;hashval < HASHLISTLENTGH;hashval++)
{
listhead = &NodeListHead[hashval];
listpos = listhead->next;
while(listpos != listhead)
{
pnode = list_entry(listpos, NODE, list);
printf(" hashval:%d id:%s name : %s \n",hashval,pnode->id,pnode->name);
listpos = listpos->next;
}
}
}
/**
* @brief : entry of program.
* @input : none
* @returns 0 .
*
*/
int main(int argc, char *argv[])
{
init_listtable();
while(1)
{
if(0 == loadfile())
{
printf("add \n");
PrintInfo();
DelTableNode();
printf("del \n");
PrintInfo();
}
sleep(5);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int comp(const void *a, const void *b)
{
return *(int*)a-*(int*)b;
}
int main()
{
int i = 0;
int *array;
int n;
printf("输入排序个数:\n");
scanf("%d", &n);
array = (int*)malloc(n*sizeof(int));
for(;i<n;i++)
{
scanf("%d", (array+i));
}
qsort(array, n, sizeof(int), comp);
printf("排序后的结果为:\n");
for(i=0; i<n; i++)
{
printf("%d\t", array[i]);
}
return 0;
}
|
C
|
/*古典问题(兔子生崽):有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少?(输出前40个月即可)*/
#include "stdio.h"
int main()
{
int month,num;
int f(int n);
for(month=1;month<=40;month++)
{
num=f(month);
printf("The amount of rabits in the %dth month is:%d.\n",month,num);
}
return 0;
}
int f(int n)
{
int m;
if(n==1||n==2)
m=1;
else
m=f(n-1)+f(n-2);
return m;
}
|
C
|
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
struct TreeNode* createNode(int* nums, int left, int right){
if(left > right) return NULL;
int x = (left+right)/2;
struct TreeNode* node = (struct TreeNode*) malloc(sizeof(struct TreeNode));
node->val = nums[x];
node->left = createNode(nums, left, x-1);
node->right = createNode(nums, x+1, right);
return node;
}
struct TreeNode* sortedArrayToBST(int* nums, int numsSize){
return createNode(nums, 0, numsSize-1);
}
|
C
|
/*************************************************************************
> File Name: server.c
> Author: hosts
> Mail: hosts@gsxio.com
> Created Time: Sun 02 Jul 2017 09:12:03 AM CST
************************************************************************/
#include "apue.h"
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
static void usage(char *proc)
{
printf("Usage:%s, [client_ip], [client_port]\n", proc);
}
int startup(char* _ip, int _port)
{
int sock = socket(AF_INET, SOCK_STREAM, 0);
if(sock < 0)
{
perror("socket");
exit(1);
}
struct sockaddr_in local;
local.sin_family = AF_INET;
local.sin_port = htons(_port);
local.sin_addr.s_addr = inet_addr(_ip);
if(bind(sock, (struct sockaddr*)&local, sizeof(local)) < 0)
{
perror("bind");
exit(2);
}
if(listen(sock, 5) < 0)
{
perror("listen");
exit(3);
}
return sock;
}
void *thread_run(void *arg)
{
int sock = *((int *) arg);
char buf[1024];
while(1)
{
ssize_t s = read(sock, buf, sizeof(buf) - 1);
if(s < 0)
{
perror("read");
}
else if(s > 0)
{
buf[s] = 0;
printf("client: %s\n", buf);
write(sock, "汶洋草泥马\n", sizeof("汶洋草泥马\n") - 1);
}
else
{
printf("client is quiet\n");
close(sock);
break;
}
}
close(sock);
}
int main(int argc, char* argv[])
{
if(argc != 3)
{
usage(argv[0]);
return 1;
}
int listen_sock = startup(argv[1], atoi(argv[2]));
struct sockaddr_in remote;
socklen_t len = sizeof(remote);
while(1)
{
int newsock = accept(listen_sock, (struct sockaddr*)&remote, &len);
if(newsock < 0)
{
perror("accept");
continue;
}
pthread_t tid;
int ret = printf("client: ip:%s, port:%d\n", inet_ntoa(remote.sin_addr), ntohs(remote.sin_port));
pthread_create(&tid, NULL, thread_run, &newsock);
if(ret < 0)
{
perror("pthread_create");
exit(4);
}
pthread_detach(tid);
}
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
int main()
{
char c;
int isVowel(char);
scanf("%c",&c);
if (isVowel(c)==1)
{
printf("V\n");
}
else{
printf("C\n");
}
return 0;
}
int isVowel(char c){
switch(c){
case 'a':case 'o':case 'i':case 'e':case 'u':
case 'A':case 'O':case 'I':case 'E':case 'U': return 1;
}
return 0;
}
|
C
|
/*
* File: ResTableEntry.h
* Author : angelToms
*
*/
#ifndef RESTABLEENTRY_H
#define RESTABLEENTRY_H
#include <stdint.h>
#include "ResStringPoolHeader.h"
#include "ResStringPoolRef.h"
/**
* This is the beginning of information about an entry in the resource
* table. It holds the reference to the name of this entry, and is
* immediately followed by one of:
* * A Res_value structure, if FLAG_COMPLEX is -not- set.
* * An array of ResTable_map structures, if FLAG_COMPLEX is set.
* These supply a set of name/value mappings of data.
*/
struct ResTable_entry
{
// Number of bytes in this structure.
uint16_t size;
enum {
// If set, this is a complex entry, holding a set of name/value
// mappings. It is followed by an array of ResTable_map structures.
FLAG_COMPLEX = 0x0001,
// If set, this resource has been declared public, so libraries
// are allowed to reference it.
FLAG_PUBLIC = 0x0002
};
uint16_t flags;
// Reference into ResTable_package::keyStrings identifying this entry.
struct ResStringPool_ref key;
};
extern "C" {
__inline__ void printResTableEntry(const ResTable_entry* entry) {
const char* type = (entry->flags & ResTable_entry::FLAG_COMPLEX) ? "ResTable_map_entry" : "Res_value";
const char* isPub = (entry->flags & ResTable_entry::FLAG_PUBLIC) ? "Public" : "Not Public";
QUP_LOGI("[*] ResTable_entry :\n"
"[+] size = %d\n"
"[+] flags = 0x%08x\n"
"[+] ResStringPool_ref index = %d\n"
"[+] entry type = %s-%s",
entry->size,
entry->flags,
entry->key.index,
isPub,
type);
}
}
#endif /* RESTABLEENTRY_H */
|
C
|
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,ans;
char ch;
clrscr();
printf("\n Enter a=addition,s=substraction,m=multiplication: ");
scanf("%c",&ch);
printf("\n Enter A \n");
scanf("%d",&a);
printf("\n Enter B \n");
scanf("%d",&b);
switch(ch)
{
case 'a':
ans=a+b;
printf("\nAddition is %d",ans);
break;
case 's':
ans=a-b;
printf("\nSubstraction is %d",ans);
break;
case 'm':
ans=a*b;
printf("\nMultiplication is %d",ans);
break;
default:
printf("wrong value");
break;
}
getch();
}
|
C
|
#ifndef INTERNALEEPROM_H
#define INTERNALEEPROM_H
static sensorConfig_eprom_t epromRecords[NUMBER_OF_HARDWARE_ADDRESSES] __attribute__((section(".eeprom")));
sensorConfig_eprom_t eepromRead(int myAddress)
{
sensorConfig_eprom_t myRecord;
myRecord.sensorConfig.hardwareAddress =
eeprom_read_byte(&(epromRecords[myAddress].sensorConfig.hardwareAddress));
myRecord.sensorConfig.measurementName =
eeprom_read_byte(&(epromRecords[myAddress].sensorConfig.measurementName));
myRecord.sensorConfig.sensorType =
eeprom_read_byte(&(epromRecords[myAddress].sensorConfig.sensorType));
myRecord.sensorConfig.channelParameter =
eeprom_read_byte(&(epromRecords[myAddress].sensorConfig.channelParameter));
myRecord.sensor_Attached_Flag =
eeprom_read_byte(&(epromRecords[myAddress].sensor_Attached_Flag));
return myRecord;
}
result_t eepromWrite(sensorConfig_eprom_t myRecord)
{
uint8_t myIndex;
myIndex = myRecord.sensorConfig.hardwareAddress;
eeprom_write_byte(&(epromRecords[myIndex].sensorConfig.hardwareAddress),myRecord.sensorConfig.hardwareAddress);
eeprom_write_byte(&(epromRecords[myIndex].sensorConfig.measurementName),myRecord.sensorConfig.measurementName);
eeprom_write_byte(&(epromRecords[myIndex].sensorConfig.sensorType),myRecord.sensorConfig.sensorType);
eeprom_write_byte(&(epromRecords[myIndex].sensorConfig.channelParameter),myRecord.sensorConfig.channelParameter);
eeprom_write_byte(&(epromRecords[myIndex].sensor_Attached_Flag),myRecord.sensor_Attached_Flag);
return SUCCESS;
}
result_t eepromErasemyMeasurementName(uint8_t myMeasurementName)
{
uint8_t i;
for( i=0; i < NUMBER_OF_HARDWARE_ADDRESSES ; i++)
{
if(eeprom_read_byte(&(epromRecords[i].sensorConfig.measurementName))== myMeasurementName)
eeprom_write_byte(&(epromRecords[i].sensor_Attached_Flag),INVALID_SENSOR_RECORD);
}
return SUCCESS;
}
sensorConfig_eprom_t eepromGetMeasurementName(uint8_t myMeasurementName)
{
uint8_t i;
sensorConfig_eprom_t myRecord;
//setting void in the return if in the loop nothing found.
myRecord.sensorConfig.measurementName = myMeasurementName;
myRecord.sensorConfig.channelParameter = 0x00;
myRecord.sensorConfig.sensorType = 0x00;
myRecord.sensorConfig.hardwareAddress = NO_HARDWARE_ADDRESS;
myRecord.sensor_Attached_Flag = INVALID_SENSOR_RECORD;
for( i=0; i < NUMBER_OF_HARDWARE_ADDRESSES ; i++) {
if( ((eeprom_read_byte(&(epromRecords[i].sensorConfig.measurementName)))== myMeasurementName) &
((eeprom_read_byte(&(epromRecords[i].sensor_Attached_Flag))==VALID_SENSOR_RECORD)))
{
myRecord.sensorConfig.hardwareAddress =
eeprom_read_byte(&(epromRecords[i].sensorConfig.hardwareAddress));
myRecord.sensorConfig.measurementName =
eeprom_read_byte(&(epromRecords[i].sensorConfig.measurementName));
myRecord.sensorConfig.sensorType =
eeprom_read_byte(&(epromRecords[i].sensorConfig.sensorType));
myRecord.sensorConfig.channelParameter =
eeprom_read_byte(&(epromRecords[i].sensorConfig.channelParameter));
myRecord.sensor_Attached_Flag =
eeprom_read_byte(&(epromRecords[i].sensor_Attached_Flag));
return myRecord;
}
}
return myRecord;
}
sensorConfig_eprom_t eepromGetHardwareAddress(uint8_t hardwareAddress)
{
uint8_t i = hardwareAddress;
sensorConfig_eprom_t myRecord;
//setting void in the return if in the loop nothing found.
myRecord.sensorConfig.measurementName = 0;
myRecord.sensorConfig.channelParameter = 0x00;
myRecord.sensorConfig.sensorType = 0x00;
myRecord.sensorConfig.hardwareAddress = hardwareAddress;
myRecord.sensor_Attached_Flag = INVALID_SENSOR_RECORD;
if( eeprom_read_byte(&(epromRecords[i].sensor_Attached_Flag))==VALID_SENSOR_RECORD )
{
myRecord.sensorConfig.hardwareAddress =
eeprom_read_byte(&(epromRecords[i].sensorConfig.hardwareAddress));
myRecord.sensorConfig.measurementName =
eeprom_read_byte(&(epromRecords[i].sensorConfig.measurementName));
myRecord.sensorConfig.sensorType =
eeprom_read_byte(&(epromRecords[i].sensorConfig.sensorType));
myRecord.sensorConfig.channelParameter =
eeprom_read_byte(&(epromRecords[i].sensorConfig.channelParameter));
myRecord.sensor_Attached_Flag =
eeprom_read_byte(&(epromRecords[i].sensor_Attached_Flag));
}
return myRecord;
}
#endif
|
C
|
/* 5) Apresentar os números primos entre 1 e 100. */
#include <stdio.h>
int main(void)
{
int i, j;
int qtde;
printf("Monstrar os numeros primos entre 1 e 100:\n\n");
for (i = 1; i < 101; i++) // gerar os primos de 1 a 100.
{
qtde = 0;
for (j = 2; j <= i / 2; j++) // testar o numero para ver se é primo
{
if (i % j == 0)
{
qtde++;
break; //ou j = i
}
}
if (qtde == 0)
{
printf("%d\t", i);
}
}
return 0;
}
|
C
|
/*
2019最新个人所得税免征额提高到5000,5001~8000部分税率3%,
8001~17000部分税率10%,17001~30000部分税率20%,30001~40000部分税率25%,
0001~60000部分税率30%,
60001~85000部分税率35%,85000部分以上45%。输入当月工资额,计算应交个税。
*/
#include<stdio.h>
int main()
{
double salary;
printf("请输入当月工资:\n");
scanf("%lf",&salary);
if(salary>5000&&salary<=8000)
printf("应交个人所得税%f\n",salary*3/100 );
}
|
C
|
#include <stdio.h>
void set_matrix (int i, int j, int n, char c, int matrix[][10], int columns[])
{
if (i < n)
{
if (j < 10 && c == ',')
{
scanf("%d%c", &matrix[i][j], &c);
return set_matrix(i, j + 1, n, c, matrix, columns);
}
columns[i] = j;
return set_matrix(i + 1, 0, n, ',', matrix, columns);
}
}
void set_array (int i, int array[])
{
if (i < 6)
{
scanf("%d", &array[i]);
set_array(i + 1, array);
}
}
int mega_sena_round(int i, int j, int columns, int matrix[][10], int number)
{
if (j < columns)
{
if(matrix[i][j] == number)
{
return 1;
}
return mega_sena_round (i, j + 1, columns, matrix, number);
}
return 0;
}
int count_winners(int i, int j, int n, int game[], int matrix[][10], int columns[])
{
if (i < n)
{
if (j < 6)
{
if (mega_sena_round(i, 0, columns[i], matrix, game[j]))
{
return count_winners(i, j + 1, n, game, matrix, columns);
}
else
{
return count_winners(i + 1, 0, n, game, matrix, columns);
}
}
if (j == 6)
{
return 1 + count_winners(i + 1, 0, n, game, matrix, columns);
}
else
{
return count_winners(i + 1, 0, n, game, matrix, columns);
}
}
return 0;
}
int main ()
{
int n;
scanf("%d", &n);
int matrix[n][10], columns[n];
set_matrix(0, 0, n, ',', matrix, columns);
int game[6];
set_array(0, game);
printf("Total de ganhadores: %d\n", count_winners(0, 0, n, game, matrix, columns));
return 0;
}
|
C
|
//character frequency
#include <stdio.h>
#include <string.h>
int main()
{
char str[10],ch;
int c = 0;
printf("Enter a string: ");
gets(str);
printf("Enter a character to find its frequency:");
scanf("%c",&ch);
for (int i=0;str[i]!='\0';++i)
{
if (ch==str[i])
++c;
}
printf("Frequency of %c=%d",ch,c);
return 0;
}
|
C
|
/*
** cut_str.c for cut_spaces_tab in /home/DoWdoX/PROJECT/PSU/clone2
**
** Made by DORIAN DEBOUT
** Login <DoWdoX@epitech.net>
**
** Started on Sat Jan 21 15:39:56 2017 DORIAN DEBOUT
** Last update Sun Jan 22 15:05:03 2017 DORIAN DEBOUT
*/
#include "./include/my.h"
int cut_begin(char *str)
{
int i;
i = 0;
if (str[i] == ' ' || str[i] == '\t')
{
while (str[i] != '\0' && (str[i] == ' ' || str[i] == '\t'))
i = i + 1;
}
return i;
}
int cut_end(char *str)
{
int i;
i = my_strlen(str) - 1;
if (str[i] == ' ' || str[i] == '\t')
{
while (i > 0 && (str[i] == ' ' || str[i] == '\t'))
i = i - 1;
}
i = i + 1;
return i;
}
char *cut_str(char *str)
{
int i;
int j;
int k;
char *str2;
k = 0;
if (verif(str) == 0)
{
i = cut_begin(str);
j = cut_end(str);
if ((str2 = malloc(sizeof(char) * (my_strlen(str) + 1))) == NULL)
return NULL;
while (i != j)
{
str2[k] = str[i];
k = k + 1;
i = i + 1;
}
return str2;
}
else
return NULL;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_isexec.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: vroche <vroche@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2015/02/17 14:32:12 by vroche #+# #+# */
/* Updated: 2015/10/14 16:49:05 by vroche ### ########.fr */
/* */
/* ************************************************************************** */
/*
** fonction to detect if file is Mach-O binary-64 with magic number
** open file, read 4 first bytes, compare and close.
** CA FE BA BE Java class file, Mach-O Fat Binary
** BE BA FE CA Java class file, Mach-O Fat Binary (reverse)
** FE ED FA CF Mach-O binary (64-bit)
** CF FA ED FE Mach-O binary (reverse byte ordering scheme, 64-bit)
** Thanks wiki !
*/
#include "minishell.h"
#include "stdio.h"
int ft_isexec(char *str)
{
int fd;
unsigned int buf;
int rtn;
char *scr;
rtn = 0;
if ((fd = open(str, O_RDONLY)) == -1)
rtn = -1;
if (rtn == 0 && read(fd, &buf, sizeof(unsigned int)) \
!= sizeof(unsigned int))
rtn = -2;
if (rtn == 0 && !(buf == 0xCFFAEDFE || buf == 0xFEEDFACF \
|| buf == 0xCAFEBABE || buf == 0xBEBAFECA))
rtn = -3;
scr = (char *)&buf;
if (rtn == -3 && *scr == '#' && *(scr + 1) == '!')
rtn = 0;
close(fd);
return (rtn);
}
|
C
|
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <wait.h>
#include <limits.h>
#include <fcntl.h>
#include <time.h>
#include <pthread.h>
#include <inttypes.h>
#include <math.h>
#include <errno.h>
#include <semaphore.h>
struct performer{ // structure containing the information about the performer on the stage be it singer or musician
char* name;
char code;
int arrival_time;
struct performer *partner; // variable stores the information if some singer joined the musician's performance
pthread_t id;
}**stage;
typedef struct performer performer;
int total,acoustic,electric,crd,t1,t2,max_wait;
int bufsiz = 256;
sem_t acoustic_sem; // semaphore which keeps track of the acoustic stages which are free
sem_t electric_sem; // semaphore which keeps track of the electric stages which are free
sem_t total_sem; // semaphore which keeps track of the total stages which are free
sem_t singer_sem;
sem_t coordinators;
void swap(int* a,int *b) {
int *temp = (int*)malloc(sizeof(int));
*temp = *a;
*a = *b;
*b = *temp;
}
void shufflearray(int *arr,int n) { // function to shuffle the contents of an array
for (int i = n - 1; i > 0; i--)
{
int j = rand() % (i + 1);
swap(&arr[i], &arr[j]);
}
}
void* music(void* input) {
performer *in = (performer*)input;
sleep(in->arrival_time); // sleep for the time the performer takes to arrive
printf("\033[1;32m");
printf("%s %c arrived\n",in->name,in->code);
int inacoustic = 1;
int inelectric = 1;
if(in->code == 'v')
inelectric = 0;
if(in->code == 'b')
inacoustic = 0;
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
ts.tv_sec += max_wait;
int duration = rand() % (t2 - t1 + 1) + t1; // duration for which the musician will play
int *arr,size;
if(!inacoustic) {
arr = (int *)malloc(sizeof(int) * electric);
size = electric;
for(int i = 0 ; i < electric ; i++)
arr[i] = i;
}
else if(!inelectric) {
arr = (int *)malloc(sizeof(int) * acoustic);
size = acoustic;
for(int i = 0 ; i < acoustic ; i++)
arr[i] = electric + i;
}
else {
arr = (int *)malloc(sizeof(int) * (acoustic + electric));
size = acoustic + electric;
for(int i = 0 ; i < acoustic + electric ; i++)
arr[i] = i;
}
if(!inacoustic) { // if the musician plays only on electric stage
if(sem_timedwait(&electric_sem,&ts) == -1 && errno == ETIMEDOUT) { // check for the maximum waiting time for a electric stage to get free
printf("\033[1;32m");
printf("%s %c left because of impatience\n",in->name,in->code);
return NULL;
}
}
else if(!inelectric) {
if(sem_timedwait(&acoustic_sem,&ts) == -1 && errno == ETIMEDOUT) {
printf("\033[0;31m");
printf("%s %c left because of impatience\n",in->name,in->code);
return NULL;
}
}
else {
if(sem_timedwait(&total_sem,&ts) == -1 && errno == ETIMEDOUT) {
printf("\033[0;31m");
printf("%s %c left because of impatience\n",in->name,in->code);
return NULL;
}
}
shufflearray(arr,size);
for(int i = 0 ; i < size ; i++) {
int stgno = arr[i];
if(stage[stgno] != NULL)
continue;
stage[stgno] = in;
if(stgno < electric) {
if(!inacoustic) {
if(sem_trywait(&total_sem))
continue;
}
else {
if(sem_wait(&electric_sem))
continue;
}
printf("\033[1;34m");
printf("%s performing %c at electric stage, stage number %d for %d sec\n",in->name,in->code,stgno + 1,duration);
sleep(duration);
if(in->partner != NULL) {
sleep(2);
stage[stgno] = NULL;
sem_post(&electric_sem);
sem_post(&singer_sem);
}
else {
stage[stgno] = NULL;
sem_post(&electric_sem);
}
sem_post(&total_sem);
printf("\033[1;33m");
printf("%s performance at electric stage, stage number %d ended\n",in->name,stgno + 1);
}
else {
if(!inelectric) {
if(sem_trywait(&total_sem))
continue;
}
else {
if(sem_trywait(&acoustic_sem))
continue;
}
printf("\033[1;34m");
printf("%s performing %c at acoustic stage, stage number %d for %d sec\n",in->name,in->code,stgno + 1,duration);
sleep(duration);
if(in->partner != NULL) {
sleep(2);
stage[stgno] = NULL;
sem_post(&acoustic_sem);
sem_post(&singer_sem);
}
else {
stage[stgno] = NULL;
sem_post(&acoustic_sem);
}
sem_post(&total_sem);
printf("\033[01;33m");
printf("%s performance at acoustic stage, stage number %d ended\n",in->name,stgno + 1);
}
break;
}
sem_wait(&coordinators);
printf("\033[0;35m");
if(in->partner == NULL)
printf("%s collecting T-shirt\n",in->name);
else
printf("%s and their partner %s collecting T-shirt\n",in->name,in->partner->name);
sleep(2);
sem_post(&coordinators);
return NULL;
}
void* sing(void* input) {
performer *in = (performer*)input;
sleep(in->arrival_time);
printf("\033[1;36m");
printf("%s s arrived\n",in->name);
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
ts.tv_sec += max_wait;
if(sem_timedwait(&singer_sem,&ts) == -1 && errno == ETIMEDOUT) {
printf("\033[0;31m");
printf("%s %c left because of impatience\n",in->name,in->code);
return NULL;
}
int duration = rand() % (t2 - t1 + 1) + t1;
int *arr = (int *)malloc(sizeof(int) * (acoustic + electric));
int size = acoustic + electric;
for(int i = 0 ; i < acoustic + electric ; i++)
arr[i] = i;
shufflearray(arr,size);
for(int i = 0 ; i < acoustic + electric ; i++) {
int stgno = arr[i];
if(stage[stgno] != NULL && (stage[stgno]->code == 's' || stage[stgno]->partner != NULL))
continue;
if(stage[stgno] != NULL) {
stage[stgno]->partner = in;
printf("\033[0;35m");
printf("%s joined %s's performance, performance extended by 2 sec\n",in->name,stage[stgno]->name);
return NULL;
}
else {
if(stgno < electric && sem_trywait(&electric_sem) == 0) {
sem_wait(&total_sem);
stage[stgno] = in;
printf("\033[1;34m");
printf("%s performing %c at electric stage, stage number %d for %d sec\n",in->name,in->code,stgno + 1,duration);
sleep(duration);
printf("\033[1;33m");
printf("%s performance at electric stage, stage number %d ended\n",in->name,stgno + 1);
sem_post(&electric_sem);
sem_post(&total_sem);
sem_post(&singer_sem);
stage[stgno] = NULL;
break;
}
else if(stgno >= electric && sem_trywait(&acoustic_sem) == 0) {
sem_wait(&total_sem);
stage[stgno] = in;
printf("\033[1;34m");
printf("%s performing %c at acoustic stage, stage number %d for %d sec\n",in->name,in->code,stgno + 1,duration);
sleep(duration);
printf("\033[1;33m");
printf("%s performance at acoustic stage, stage number %d ended\n",in->name,stgno + 1);
sem_post(&acoustic_sem);
sem_post(&total_sem);
sem_post(&singer_sem);
stage[stgno] = NULL;
break;
}
}
}
sem_wait(&coordinators);
printf("\033[0;35m");
printf("%s collecting T-shirt\n",in->name);
sleep(2);
sem_post(&coordinators);
return NULL;
}
int main() {
srand(time(NULL));
scanf("%d %d %d %d %d %d %d",&total,&acoustic,&electric,&crd,&t1,&t2,&max_wait);
sem_init(&acoustic_sem,0,acoustic);
sem_init(&electric_sem,0,electric);
sem_init(&total_sem,0,acoustic + electric);
sem_init(&singer_sem,0,acoustic + electric);
sem_init(&coordinators,0,crd);
stage = (performer**)malloc(sizeof(performer*) * (acoustic + electric));
for(int i = 0 ; i < acoustic + electric ; i++) {
stage[i] = (performer*)malloc(sizeof(performer));
stage[i] = NULL;
}
char* type = (char*)malloc(sizeof(char) * total);
int* arvt = (int*)malloc(sizeof(int) * total);
char** name = (char**)malloc(sizeof(char*) * total);
for(int i = 0 ; i < total ; i++) {
name[i] = (char*)malloc(sizeof(char) * bufsiz);
scanf("%s %c %d",name[i],&type[i],&arvt[i]);
}
performer* temp = (performer*)malloc(sizeof(performer) * total);
for(int i = 0 ; i < total ; i++) {
temp[i].name = name[i];
temp[i].code = type[i];
temp[i].partner = NULL;
temp[i].arrival_time = arvt[i];
if(type[i] != 's') {
pthread_create(&temp[i].id,NULL,music,&temp[i]);
}
else
pthread_create(&temp[i].id,NULL,sing,&temp[i]);
usleep(50);
}
for(int i = 0 ; i < total ; i++) {
pthread_join(temp[i].id,NULL);
}
printf("\033[1;31m");
printf("Finished\n");
return 0;
}
|
C
|
/* $Revision: 1.1.6.6 $ */
/* shrlibsample.c
*
* Sample C shared library for use with MATLAB Shared
* Library Calling (CALLLIB)
* Copyright 2002-2008 The MathWorks, Inc.
*
*/
#include <stdlib.h>
#include <mex.h> /* only needed because of mexFunction below and mexPrintf */
/*#include "windows.h"*/
#define EXPORT_FCNS
#include "shrhelp.h"
#include "shrlibsample.h"
EXPORTED_FUNCTION void multDoubleArray(double *x,int size)
{
/* Multiple each element of the array by 3 */
int i;
for (i=0;i<size;i++)
*x++ *= 3;
}
EXPORTED_FUNCTION double addMixedTypes(short x,int y,double z)
{
return (x + y + z);
}
EXPORTED_FUNCTION double addDoubleRef(double x,double *y,double z)
{
return (x + *y + z);
}
EXPORTED_FUNCTION char* stringToUpper(char *input)
{
char *p = input;
if (p!=NULL)
{
while (*p!=0)
{
*p = toupper(*p);
p++;
}
} else {
input="Null pointer passed to stringToUpper.";
}
return input;
}
EXPORTED_FUNCTION char* readEnum(TEnum1 val)
{
switch (val) {
case en1: return "You chose en1";
case en2: return "You chose en2";
case en4: return "You chose en4";
default : return "enum not defined";
}
return "ERROR";
}
EXPORTED_FUNCTION double addStructFields(struct c_struct st)
{
double t = st.p1 + st.p2 + st.p3;
return t;
}
EXPORTED_FUNCTION double *multDoubleRef(double *x)
{
*x *= 5;
return x;
}
EXPORTED_FUNCTION double addStructByRef(struct c_struct *st)
{
double t = st->p1+st->p2+st->p3;
st->p1=5.5;
st->p2=1234;
st->p3=12345678;
return t;
}
EXPORTED_FUNCTION void allocateStruct(struct c_struct** val)
{
/* allocate zeroed space for 5 copies of c_struct */
struct c_struct* local=(struct c_struct*) calloc(sizeof(struct c_struct),5);
*val=local; /* assign val to the first set of values */
local->p1 = 12.4;
local->p2 = 222;
local->p3 = 333333;
local++;
local->p1 = 2.1;
local->p2 = 22;
local->p3 = 23;
}
EXPORTED_FUNCTION void deallocateStruct(void *ptr)
{
free(ptr);
}
EXPORTED_FUNCTION void multiplyShort(short *x, int size)
{
int i;
for (i=0; i<size; i++)
*x++ *= i;
}
EXPORTED_FUNCTION void print2darray(double my2d[][3],int len)
{
int indxi,indxj;
for(indxi=0;indxi<len;++indxi)
{
for(indxj=0;indxj<3;++indxj)
{
mexPrintf("%10g",my2d[indxi][indxj]);
}
mexPrintf("\n");
}
}
EXPORTED_FUNCTION const char ** getListOfStrings(void)
{
static const char *strings[5];
strings[0]="String 1";
strings[1]="String Two";
strings[2]=""; /* empty string */
strings[3]="Last string";
strings[4]=NULL;
return strings;
}
double exportedDoubleValue=10.0; /* this is not a function, it is an exported variable*/
EXPORTED_FUNCTION void printExportedDoubleValue(void)
/* this function allows independent verification of exportedDoubleValue */
{
mexPrintf("The value of exportedDoubleValue is %f.\n",exportedDoubleValue);
}
/* this function exists so that mex may be used to compile the library
it is not otherwise needed */
void mexFunction( int nlhs, mxArray *plhs[],
int nrhs, const mxArray*prhs[] )
{
}
|
C
|
#include <stdio.h>
#include<stdlib.h>
struct Term
{
int coeff;
int exp;
};
struct poly
{
int n;
struct Term *terms;
};
void create(struct poly *p)
{
int i;
printf("Number of terms?");
scanf("%d",&p->n);
p->terms=(struct Term*)malloc(p->n*sizeof(struct Term));
printf("Enter terms\n");
for(i=0;i<p->n;i++)
scanf("%d%d",&p->terms[i].coeff,&p->terms[i].exp);
}
void display(struct poly p)
{
int i;
for(i=0;i<(p.n-1);i++)
printf("%dx%d+",p.terms[i].coeff,p.terms[i].exp);
printf("%dx%d",p.terms[i].coeff,p.terms[i].exp);
printf("\n");
}
int main()
{
struct poly p1;
create(&p1);
display(p1);
return 0;
}
|
C
|
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
/* Type definitions */
typedef int /*<<< orphan*/ FILE ;
/* Variables and functions */
size_t BUFSIZ ;
int errno ;
int /*<<< orphan*/ * fgets (char*,size_t,int /*<<< orphan*/ *) ;
int /*<<< orphan*/ free (char*) ;
char* malloc (size_t) ;
char* realloc (char*,size_t) ;
char* strchr (char*,char) ;
size_t strlen (char*) ;
char *
fgetln(FILE *fp, size_t *len)
{
static char *buf = NULL;
static size_t bufsiz = 0;
char *ptr;
if (buf == NULL) {
bufsiz = BUFSIZ;
if ((buf = malloc(bufsiz)) == NULL)
return NULL;
}
if (fgets(buf, bufsiz, fp) == NULL)
return NULL;
*len = 0;
while ((ptr = strchr(&buf[*len], '\n')) == NULL) {
size_t nbufsiz = bufsiz + BUFSIZ;
char *nbuf = realloc(buf, nbufsiz);
if (nbuf == NULL) {
int oerrno = errno;
free(buf);
errno = oerrno;
buf = NULL;
return NULL;
} else
buf = nbuf;
if (fgets(&buf[bufsiz], BUFSIZ, fp) == NULL) {
buf[bufsiz] = '\0';
*len = strlen(buf);
return buf;
}
*len = bufsiz;
bufsiz = nbufsiz;
}
*len = (ptr - buf) + 1;
return buf;
}
|
C
|
#include <stdio.h>
#include <math.h>
int fees(int starthrs,int startmin,int endhrs,int endmin){
int hrs = 0, min = 0;
int fees=0;
if( startmin>endmin ){
endhrs -= 1;
endmin += 60;
}
hrs = endhrs-starthrs;
min = endmin-startmin+(hrs*60);
if( min<=120 )
fees = (min/30)*30;
else if( min<=240){
fees = 120 + ceil((min-120)*1.0/30)*40 ;
}
else
{
fees = 120+160+ceil((min-240)*1.0/30)*60 ;
}
return fees;
}
int main(){
int starthrs,startmin,endhrs,endmin;
char colon;
int feesvalue[3]={0};
int x,i,j;
for( i=0;i<3;i++ ){
scanf("%d:%d",&starthrs,&startmin);
scanf("%d:%d",&endhrs,&endmin);
if( starthrs<0 || starthrs>=25 || startmin <0 || startmin >60 ||endhrs<0 || endhrs>=25 || endmin <0 || endmin >60){
feesvalue[i]=-1;
continue;
}
feesvalue[i] = fees(starthrs,startmin,endhrs,endmin);
}
for(j = 0; j < i; j++){
if(feesvalue[j] == -1)
printf("error\n");
else
printf("%d\n",feesvalue[j]);
}
return 0;
}
|
C
|
#include "uart.h"
void uart0_init()
{
unsigned int * gphcon = GPHCON,*gphup=GPHUP,*ulcon=ULCON0,*ucon=UCON0,*ubrdiv0 = UBRDIV0;
*gphcon &= ~(3<<4|3<<6);
*gphcon |= 2<<4|2<<6;
*gphup &= ~(1<<2|1<<3);
*ulcon = 3;
*ucon = 5;
*ubrdiv0 = 26;
}
int getchar(void)
{
unsigned int * uartstat = UARTSTAT0;
while(!(*uartstat&1));
return *(unsigned char*) URXH0;
}
void putchar(char c)
{
unsigned int *uartstat = UARTSTAT0;
while(!(*uartstat&1<<2));
*(unsigned char*)UTXH0 = c;
if(c=='\n'){
while(!(*uartstat&1<<2));
*(unsigned char*)UTXH0 = '\r';
}
if(c=='\r'){
while(!(*uartstat&1<<2));
*(unsigned char*)UTXH0 = '\n';
}
}
char* puts(char *s)
{
char *p = s;
while(*s)
{
putchar(*s);
s++;
}
putchar('\n');
return p;
}
void putHex(unsigned int a)
{
int i;
unsigned char b[8];
for(i=0;i<8;i++)
{
b[i]=a&0xf;
a>>=4;
}
putchar('0');putchar('X');
for(i=7;i>=0;i--)
{
if(b[i]>=0&&b[i]<=9)
{
putchar(b[i]+'0');
}
else
{
putchar(b[i]-0xA+'A');
}
}
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
void *my_alloc(size_t count)
{
return malloc(count);
}
void my_free(void *ptr)
{
printf("NATIVE freeing: %p\n", ptr);
free(ptr);
}
|
C
|
#include <stdio.h>
#include <string.h>
#define TARGET_SPEED 100
#define PID_CNT 100
typedef struct pid_info {
float kp;
float ki;
float kd;
float set_speed;
float actual_speed;
float err;
float err_last1;
float err_last2;
float err_total;
} pid_info_s;
int pid_init(pid_info_s *pid)
{
if (NULL == pid) {
printf("error: pid is NULL\n");
return -1;
}
pid->kp = 0.1;
pid->ki = 0.2;
pid->kd = 0.1;
pid->set_speed = 0.0;
pid->actual_speed = 0.0;
pid->err = 0.0;
pid->err_last1 = 0.0;
pid->err_last2 = 0.0;
pid->err_total = 0.0;
return 0;
}
float pid_pos_calc(pid_info_s *pid, float speed)
{
if ((NULL == pid) || (speed < 0)) {
printf("error: pid is NULL\n");
return -1;
}
pid->set_speed = speed;
pid->err = pid->set_speed - pid->actual_speed;
pid->err_total += pid->err;
pid->actual_speed = pid->kp * pid->err + pid->ki * pid->err_total + pid->kd * (pid->err - pid->err_last1);
pid->err_last2 = pid->err_last1;
pid->err_last1 = pid->err;
return pid->actual_speed;
}
float pid_inc_calc(pid_info_s *pid, float speed)
{
float increat_speed = 0.0;
if ((NULL == pid) || (speed < 0)) {
printf("error: pid is NULL\n");
return -1;
}
pid->set_speed = speed;
pid->err = pid->set_speed - pid->actual_speed;
increat_speed = pid->kp * (pid->err - pid->err_last1)+ pid->ki * pid->err + pid->kd * (pid->err - 2 * pid->err_last1 + pid->err_last2);
pid->actual_speed += increat_speed;
pid->err_last2 = pid->err_last1;
pid->err_last1 = pid->err;
return pid->actual_speed;
}
int main(void)
{
int count = 0;
float speed = 0.0;
pid_info_s pid;
memset(&pid, 0, sizeof(pid_info_s));
pid_init(&pid);
for (count = 0; count < PID_CNT; count++) {
#if 0
speed = pid_pos_calc(&pid, TARGET_SPEED);
#else
speed = pid_inc_calc(&pid, TARGET_SPEED);
#endif
printf("count: %d, speed: %f\n", count, speed);
}
return 0;
}
|
C
|
#include "osdcore.h"
#include "sound/wavwrite.h"
struct _wav_file
{
FILE *file;
UINT32 total_offs;
UINT32 data_offs;
};
wav_file *wav_open(const char *filename, int sample_rate, int channels)
{
wav_file *wav;
UINT32 bps, temp32;
UINT16 align, temp16;
/* allocate memory for the wav struct */
wav = (wav_file *) osd_malloc(sizeof(struct _wav_file));
if (!wav)
return NULL;
/* create the file */
wav->file = fopen(filename, "wb");
if (!wav->file)
{
osd_free(wav);
return NULL;
}
/* write the 'RIFF' header */
fwrite("RIFF", 1, 4, wav->file);
/* write the total size */
temp32 = 0;
wav->total_offs = ftell(wav->file);
fwrite(&temp32, 1, 4, wav->file);
/* write the 'WAVE' type */
fwrite("WAVE", 1, 4, wav->file);
/* write the 'fmt ' tag */
fwrite("fmt ", 1, 4, wav->file);
/* write the format length */
temp32 = LITTLE_ENDIANIZE_INT32(16);
fwrite(&temp32, 1, 4, wav->file);
/* write the format (PCM) */
temp16 = LITTLE_ENDIANIZE_INT16(1);
fwrite(&temp16, 1, 2, wav->file);
/* write the channels */
temp16 = LITTLE_ENDIANIZE_INT16(channels);
fwrite(&temp16, 1, 2, wav->file);
/* write the sample rate */
temp32 = LITTLE_ENDIANIZE_INT32(sample_rate);
fwrite(&temp32, 1, 4, wav->file);
/* write the bytes/second */
bps = sample_rate * 2 * channels;
temp32 = LITTLE_ENDIANIZE_INT32(bps);
fwrite(&temp32, 1, 4, wav->file);
/* write the block align */
align = 2 * channels;
temp16 = LITTLE_ENDIANIZE_INT16(align);
fwrite(&temp16, 1, 2, wav->file);
/* write the bits/sample */
temp16 = LITTLE_ENDIANIZE_INT16(16);
fwrite(&temp16, 1, 2, wav->file);
/* write the 'data' tag */
fwrite("data", 1, 4, wav->file);
/* write the data length */
temp32 = 0;
wav->data_offs = ftell(wav->file);
fwrite(&temp32, 1, 4, wav->file);
return wav;
}
void wav_close(wav_file *wav)
{
UINT32 total;
UINT32 temp32;
if (!wav) return;
total = ftell(wav->file);
/* update the total file size */
fseek(wav->file, wav->total_offs, SEEK_SET);
temp32 = total - (wav->total_offs + 4);
temp32 = LITTLE_ENDIANIZE_INT32(temp32);
fwrite(&temp32, 1, 4, wav->file);
/* update the data size */
fseek(wav->file, wav->data_offs, SEEK_SET);
temp32 = total - (wav->data_offs + 4);
temp32 = LITTLE_ENDIANIZE_INT32(temp32);
fwrite(&temp32, 1, 4, wav->file);
fclose(wav->file);
osd_free(wav);
}
void wav_add_data_16(wav_file *wav, INT16 *data, int samples)
{
if (!wav) return;
/* just write and flush the data */
fwrite(data, 2, samples, wav->file);
fflush(wav->file);
}
void wav_add_data_32(wav_file *wav, INT32 *data, int samples, int shift)
{
INT16 *temp;
int i;
if (!wav) return;
/* allocate temp memory */
temp = (INT16 *)osd_malloc_array(samples * sizeof(temp[0]));
if (!temp)
return;
/* clamp */
for (i = 0; i < samples; i++)
{
int val = data[i] >> shift;
temp[i] = (val < -32768) ? -32768 : (val > 32767) ? 32767 : val;
}
/* write and flush */
fwrite(temp, 2, samples, wav->file);
fflush(wav->file);
/* free memory */
osd_free(temp);
}
void wav_add_data_16lr(wav_file *wav, INT16 *left, INT16 *right, int samples)
{
INT16 *temp;
int i;
if (!wav) return;
/* allocate temp memory */
temp = (INT16 *)osd_malloc_array(samples * 2 * sizeof(temp[0]));
if (!temp)
return;
/* interleave */
for (i = 0; i < samples * 2; i++)
temp[i] = (i & 1) ? right[i / 2] : left[i / 2];
/* write and flush */
fwrite(temp, 4, samples, wav->file);
fflush(wav->file);
/* free memory */
osd_free(temp);
}
void wav_add_data_32lr(wav_file *wav, INT32 *left, INT32 *right, int samples, int shift)
{
INT16 *temp;
int i;
if (!wav) return;
/* allocate temp memory */
temp = (INT16 *)osd_malloc_array(samples * 2 * sizeof(temp[0]));
if (!temp)
return;
/* interleave */
for (i = 0; i < samples * 2; i++)
{
int val = (i & 1) ? right[i / 2] : left[i / 2];
val >>= shift;
temp[i] = (val < -32768) ? -32768 : (val > 32767) ? 32767 : val;
}
/* write and flush */
fwrite(temp, 4, samples, wav->file);
fflush(wav->file);
/* free memory */
osd_free(temp);
}
|
C
|
#include <stdlib.h>
#include "c-sum.h"
int sum_abs_(int *in, int *num, int *out) {
int i;
for (i=0; i < *num; ++i) {
*out += abs(in[i]);
}
}
|
C
|
#include <stdio.h>
void delete_char(char* arr,char ch);
int main()
{
char arr[10],ch;
scanf("%s\n",arr);
scanf("%c",&ch);
delete_char(arr,ch);
return 0;
}
void delete_char(char* arr,char ch)
{
for(int i=0;i<10;i++)
{
if(ch==*(arr+i))
{
for(int j=i;j<10;j++)
{
*(arr+j)=*(arr+j+1);
}
printf("%s\n",arr);
break;
}
if(i==9)
printf("Not Found\n");
}
}
|
C
|
#include "LynxSD.h"
////////////////////////////////////////////////////////////////////////////////
//
// Microcontroller communication constants
//
////////////////////////////////////////////////////////////////////////////////
typedef enum
{
ECommandByte_OpenDir = 0,
ECommandByte_ReadDir,
ECommandByte_OpenFile,
ECommandByte_GetSize,
ECommandByte_Seek,
ECommandByte_Read,
ECommandByte_Write,
ECommandByte_Close,
ECommandByte_ProgramFile,
ECommandByte_ClearBlocks,
ECommandByte_LowPowerMode
} ECommandByte;
#define IO_TIMEOUT 30000
////////////////////////////////////////////////////////////////////////////////
//
// Lynx registers
//
////////////////////////////////////////////////////////////////////////////////
const unsigned char AUXMASK = 16;
#define IODAT ((volatile unsigned char *) 0xFD8B)
#define IODIR ((volatile unsigned char *) 0xFD8A)
#define CART1 ((volatile unsigned char *) 0xFCB3)
#define CART0 ((volatile unsigned char *) 0xFCB2)
////////////////////////////////////////////////////////////////////////////////
//
// Support functions to read and write bytes to the cartridge microcontroller
//
////////////////////////////////////////////////////////////////////////////////
static void __fastcall__ WriteByte(unsigned char byte)
{
while (*IODAT & AUXMASK); // make sure the cart isnt blocking the write
*CART1 = byte;
}
static void __fastcall__ WriteBytes(unsigned char *pBuf, unsigned int nSize)
{
while (nSize--)
{
WriteByte(*pBuf++);
}
}
static void __fastcall__ WriteWord(unsigned int word)
{
WriteBytes((unsigned char*) &word, 2);
}
static void __fastcall__ WriteDword(unsigned long dword)
{
WriteBytes((unsigned char*) &dword, 4);
}
static unsigned char ReadByte()
{
while (!(*IODAT & AUXMASK)); // wait for data in read FIFO
return *CART0; // read byte
}
static void __fastcall__ ReadBytes(unsigned char *pOut, unsigned int size)
{
while (size--)
{
*pOut++ = ReadByte();
}
}
static unsigned long ReadDword()
{
unsigned long nDword;
ReadBytes((unsigned char*) &nDword, 4);
return nDword;
}
static void __fastcall__ WriteString(const char *pStr)
{
char c;
do
{
c = *pStr++;
WriteByte(c);
} while (c);
}
////////////////////////////////////////////////////////////////////////////////
//
// Microcontroller commands
//
////////////////////////////////////////////////////////////////////////////////
void LynxSD_Init()
{
*IODIR = 0; // all input
*CART1 = 0xaa; // initialise cart comms
}
void LynxSD_LowPowerMode()
{
WriteByte(ECommandByte_LowPowerMode); // turn of sd card and enter low power state
}
FRESULT __fastcall__ LynxSD_OpenDir(const char *pDir)
{
WriteByte(ECommandByte_OpenDir); // open dir command
WriteString(pDir);
return (FRESULT) ReadByte(); // read the response
}
FRESULT __fastcall__ LynxSD_ReadDir(SFileInfo *pInfo)
{
FRESULT res;
WriteByte(ECommandByte_ReadDir);
res = (FRESULT) ReadByte();
if (res == FR_OK)
{
ReadBytes((unsigned char *) pInfo, sizeof(SFileInfo));
}
return res;
}
FRESULT __fastcall__ LynxSD_OpenFile(const char *pFile)
{
WriteByte(ECommandByte_OpenFile); // open file command
WriteString(pFile);
return (FRESULT) ReadByte(); // read the response
}
FRESULT __fastcall__ LynxSD_ReadFile(void *pBuffer, unsigned int nSize)
{
WriteByte(ECommandByte_Read);
WriteWord(nSize);
ReadBytes((unsigned char *) pBuffer, nSize);
return (FRESULT) ReadByte(); // final byte is status for read
}
FRESULT __fastcall__ LynxSD_WriteFile(void *pBuffer, unsigned int nSize)
{
WriteByte(ECommandByte_Write);
WriteWord(nSize);
WriteBytes((unsigned char *) pBuffer, nSize);
return (FRESULT) ReadByte(); // final byte is status for write
}
FRESULT LynxSD_CloseFile()
{
WriteByte(ECommandByte_Close);
return (FRESULT) ReadByte(); // status for close
}
FRESULT __fastcall__ LynxSD_SeekFile(unsigned long nSeekPos)
{
WriteByte(ECommandByte_Seek);
WriteDword(nSeekPos);
return (FRESULT) ReadByte(); // seek result
}
unsigned long LynxSD_GetFileSize()
{
WriteByte(ECommandByte_GetSize);
return ReadDword(); // size of open file
}
FRESULT __fastcall__ LynxSD_ProgramROMFromFile(unsigned int nStartBlock, unsigned char nBlockSize, unsigned int nBlockCount, unsigned char b512BlockCard)
{
if (b512BlockCard)
{
nBlockSize |= 0x10;
}
WriteByte(ECommandByte_ProgramFile);
WriteWord(nStartBlock); // start block from 0-511 (>255 with 512 block card bit set)
WriteByte(nBlockSize); // or with 0x10 for 512 block card (a19 controlled by aux pin)
WriteWord(nBlockCount); // blocks to write
return (FRESULT) ReadByte(); // waits for programming to end and gets result
}
FRESULT __fastcall__ LynxSD_ClearROMBlocks(unsigned int nStartBlock, unsigned int nBlocks, unsigned char b512BlockCard)
{
if (b512BlockCard)
{
nBlocks |= 0x8000;
}
WriteByte(ECommandByte_ClearBlocks);
WriteWord(nStartBlock); // start block from 0-511 (>255 with 512 block card bit set)
WriteWord(nBlocks); // or with 0x8000 for 512 block card (a19 controlled by aux pin)
return (FRESULT) ReadByte(); // waits for clearing to end and gets result
}
FRESULT __fastcall__ LynxSD_OpenFileTimeout(void *pBuffer)
{
unsigned int count=0;
while ((*IODAT & AUXMASK) && (count++<IO_TIMEOUT));
if (count>=IO_TIMEOUT)
return FR_DISK_ERR;
*CART1 = ECommandByte_OpenFile;
WriteString(pBuffer);
count=0;
while (!(*IODAT & AUXMASK) && (count++<IO_TIMEOUT)); // wait for data in read FIFO or timeout
if (count<IO_TIMEOUT)
{
return *CART0;
}
else
return FR_DISK_ERR;
}
|
C
|
/*************************************************************/
/* imcop_types.h */
/* DM350 IMCOP type definitions */
/* ------------------------------------------------------ */
/* 09/02/2005 First release by */
/*************************************************************/
#ifndef __IMCOP_TYPES_H__
#define __IMCOP_TYPES_H__
/*********************************************************/
/* Utility macros */
/*********************************************************/
/* Array size */
#define ARRAY_LENGTH(X) (sizeof(X)/sizeof(X[0]))
/* Register size */
#define REG_SIZE(sReg) (sizeof(sReg)/sizeof(IMCOP_Reg))
/* Unsigned Bit Extraction */
#define BITEXT(value, bitLoc, bitNum) /*(U##bitNum)*/(((value) >> (bitLoc)) & ((1 << (bitNum)) - 1))
/* Signed Bit Extraction */
#define BITEXTS(value, bitLoc, bitNum) /*(S##bitNum)*/((((S32)(value) << (32-(bitNum)-(bitLoc))) >> (32-(bitNum))))
/* Bit Field Writing */
#define WRITE_FIELD(variable, bitLoc, bitNum, value) {variable &= ~(((1 << (bitNum)) -1) << (bitLoc)); variable |= (((value) & ((1 << (bitNum)) -1))<< (bitLoc));}
/*********************************************************/
/* Type definitions */
/*********************************************************/
/* BOOL type */
#if 0
typedef enum _BOOL {
FALSE = 0,
TRUE = 1
} BOOL;
#endif
typedef int BOOL;
#ifndef TRUE
#define TRUE 1
#define FALSE 0
#endif
/* data types for MS VC++ */
#ifdef _MSC_VER
typedef signed _int8 S8;
typedef unsigned _int8 U8;
typedef signed _int16 S16;
typedef unsigned _int16 U16;
typedef signed _int32 S32;
typedef unsigned _int32 U32;
typedef signed _int64 S64;
typedef unsigned _int64 U64;
#endif /* _MSC_VER */
typedef signed char S8;
typedef unsigned char U8;
typedef signed short S16;
typedef unsigned short U16;
typedef signed int S32;
typedef unsigned int U32;
typedef signed long long S64;
typedef unsigned long long U64;
/* integer types with bit-width not equal to a multiple of 8 */
/* unsigned 1 to 7 bit */
typedef U8 U1;
typedef U8 U2;
typedef U8 U3;
typedef U8 U4;
typedef U8 U5;
typedef U8 U6;
typedef U8 U7;
/* signed 1 to 7 bit */
typedef S8 S1;
typedef S8 S2;
typedef S8 S3;
typedef S8 S4;
typedef S8 S5;
typedef S8 S6;
typedef S8 S7;
/* unsigned 9 to 15 bit */
typedef U16 U9;
typedef U16 U10;
typedef U16 U11;
typedef U16 U12;
typedef U16 U13;
typedef U16 U14;
typedef U16 U15;
/* unsigned 9 to 15 bit */
typedef S16 S9;
typedef S16 S10;
typedef S16 S11;
typedef S16 S12;
typedef S16 S13;
typedef S16 S14;
typedef S16 S15;
typedef U32 U17;
typedef U32 U18;
typedef U32 U19;
typedef U32 U20;
typedef U32 U21;
typedef U32 U22;
typedef U32 U23;
typedef U32 U24;
typedef U32 U25;
typedef U32 U26;
typedef U32 U27;
typedef U32 U28;
typedef U32 U29;
typedef U32 U30;
typedef U32 U31;
typedef U64 U48;
typedef S32 S17;
typedef S32 S18;
typedef S32 S19;
typedef S32 S20;
typedef S32 S21;
typedef S32 S22;
typedef S32 S23;
typedef S32 S24;
typedef S32 S25;
typedef S32 S26;
typedef S32 S27;
typedef S32 S28;
typedef S32 S29;
typedef S32 S30;
typedef S32 S31;
/* IMCOP configuration register */
typedef volatile unsigned short IMCOP_Reg;
typedef volatile unsigned int IMCOP_Reg32;
/* IMCOP memories */
typedef signed char IMCOP_Mem;
typedef signed char IMCOP_Mem8;
typedef signed short IMCOP_Mem16;
typedef signed int IMCOP_Mem32;
#endif // #ifndef __IMCOP_TYPES_H__
|
C
|
#include <stdio.h>
#include <stdlib.h>
int putData(int**, int, int);
void printData(int**, int, int);
int main(void)
{
int n, m;
int i;
scanf("%d %d", &n, &m);
int** arr = (int**)malloc(sizeof(int*) * n);
if (arr == NULL) exit(EXIT_FAILURE);
for (i = 0; i < n; i++) // 주의: 'n번' 할당해야 한다. Caution: Allocate spaces for n times
{
arr[i] = (int*)malloc(sizeof(int) * m); // Allocate (m * int) size space
if (arr[i] == NULL) exit(EXIT_FAILURE);
}
putData(arr, n, m);
printData(arr, n, m);
for (i = 0; i < n; i++)
free(arr[i]);
free(arr);
return 0;
}
int putData(int** target, int n, int m)
{
int x = 0, i = 0, y = 0, j = 0;
int num = 1;
const int max = n * m;
target[0][0] = num++;
while (num <= max)
{
if (y < m - 1)
y++;
else
x++;
j = y;
i = x;
while (j >= 0 && i < n)
target[i++][j--] = num++;
}
}
void printData(int** target, int n, int m) {
int i, j;
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++)
printf(" %d", target[i][j]);
putchar('\n');
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int get_positive_int() {
char buffer[80];
char *ret, *tail;
long n;
do {
printf("Height: ");
ret = fgets(buffer, 80, stdin);
n = strtol(buffer, &tail, 10);
} while (n < 1 || n > 8 || ret == NULL || *tail != 0x0a);
return n;
}
int main(void) {
int height = get_positive_int();
for (int row = 1; row <= height; row++) {
for (int i = 0; i < height - row; i++) {
printf(" ");
}
for (int i = 0; i < row; i++) {
printf("#");
}
printf(" ");
for (int i = 0; i < row; i++) {
printf("#");
}
printf("\n");
}
}
|
C
|
#include <stdio.h>
#include <ucontext.h>
#include <stdlib.h>
#include <string.h>
typedef struct TCB_t
{
int thread_id;
ucontext_t context;
struct TCB_t *next;
struct TCB_t *prev;
} TCB_t;
void init_TCB (TCB_t *tcb, void *function, void *stackP, int stack_size)
{
memset(tcb, '\0', sizeof(TCB_t));
getcontext(&tcb->context);
tcb->context.uc_stack.ss_sp = stackP;
tcb->context.uc_stack.ss_size = (size_t) stack_size;
makecontext(&tcb->context, function, 0);
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
int main()
{
char prenom[100];
printf("Veuillez entrer votre nom:\n>>> ");
scanf("%s", prenom);
printf("Bonjour Monsieur %s !", prenom);
return 0;
}
|
C
|
#include <ng_vector.h>
#include<stdlib.h>
#include<string.h>
// constructors
ng_vector_t* ng_vector_new(const size_t fruit_size, const int max)
{
const size_t size = sizeof(ng_vector_t) + fruit_size*max;
ng_vector_t* self = (ng_vector_t*)malloc(size);
return ng_vector_init(self, fruit_size, max);
}
ng_vector_t* ng_vector_init(ng_vector_t* self,
const size_t
fruit_size,
const int max)
{
self->max_ = max;
self->numb_ = 0;
return self;
}
ng_vector_t* ng_vector_enlarge(ng_vector_t** selfp,
const size_t fruit_size,
void*(*fruit_cp_init)(const void*,
void*),
void(*fruit_deinit)(void*))
{
// cache the old one
ng_vector_t* self = *selfp;
// calculate new size needed
const int new_max = self->max_*2;
const size_t new_size = sizeof(ng_vector_t) + new_max*fruit_size;
if(0x0==fruit_cp_init){
*selfp = (ng_vector_t*)realloc(self, new_size);
(*selfp)->max_ = new_max;
return *selfp;
} else {
// allocate new blank stuffs
*selfp = (ng_vector_t*)malloc(new_size);
// copy over the old stuffs
for(int i=0;i<self->numb_;i++){
const int delta = fruit_size*i;
void *old_fruit = (void*)(self->fruits_ + delta);
void *new_fruit = (void*)((*selfp)->fruits_ + delta);
fruit_cp_init(old_fruit,new_fruit);
}
// copy over size parameters
(*selfp)->max_ = new_max;
(*selfp)->numb_ = self->numb_;
}
if(0x0==fruit_deinit){
for(int i=0;i<self->numb_;i++){
void *fruit = (void*)(self->fruits_ + fruit_size*i);
fruit_deinit(fruit);
}
}
// deallocate old space
free(self);
// return new
return *selfp;
}
// destructors
void ng_vector_delete(ng_vector_t** selfp, const int fruit_size, void(*fruit_uninit)(void*))
{
ng_vector_uninit(*selfp, fruit_size, fruit_uninit);
free(*selfp);
*selfp = 0x0;
}
void ng_vector_uninit(ng_vector_t* self, const int fruit_size, void(*fruit_uninit)(void*))
{
if(0x0 != fruit_uninit){
for(int i=0;i<self->numb_*fruit_size;i+=fruit_size){
fruit_uninit((void*)(self->fruits_ + i));
}
}
self->numb_=0;
}
// accesss
// just for convenience
bool ng_vector_empty(const ng_vector_t* self){
return 0==self->numb_;
}
// get a pointer to an elment in the vector
void* ng_vector_at(ng_vector_t* self, const int index, const int fruit_size)
{
return (void*)(self->fruits_+index*fruit_size);
}
// returns the back ("top") of th stack...
void* ng_vector_back(ng_vector_t* self, const int fruit_size)
{
return ng_vector_at(self, self->numb_-1, fruit_size);
}
// add an element to the end of the vector
void
ng_vector_push_back(ng_vector_t** selfp,
const int fruit_size, const void* fruit,
void*(*fruit_cp_init)(const void*,
void*),
void(*fruit_deinit)(void*))
{
// see if we need teo expand or not
ng_vector_t* self = *selfp;
if(self->numb_== self->max_){
self = ng_vector_enlarge(selfp, fruit_size, fruit_cp_init, fruit_deinit);
}
// calculate place to put new fruit
void* place = (void*)(self->fruits_ + self->numb_*fruit_size);
// if we don't have a copy-initializer, just bitcopy
if(0x0 == fruit_cp_init){
memcpy(place, fruit, fruit_size);
} else {
fruit_cp_init(fruit, place);
}
// bump up the pointer
self->numb_+=1;
}
// remove an element from the end of the vector
void
ng_vector_pop_back(ng_vector_t* self,
const int fruit_size,
void(*fruit_deinit)(void*))
{
// one less element in here
self->numb_ -= 1;
if(0x0 != fruit_deinit){
const int position = fruit_size*self->numb_;
fruit_deinit((void*)(self->fruits_+position));
}
}
// binary search. Equivalent to lower_bound in c++ STL
int ng_vector_binary_search_upper_bound(const ng_vector_t* v,
const int l, const int h,
const int fruit_size, const void* fruit,
int(*fruit_compare)(const void*,
const void*))
{
// initalize the low we use to the low supplied
int low[2];
low[0] = l;
int size = (h-l);
while(size>0){
const int half = size/2;
low[1] = low[0]+size-half;
size = half;
const void* probe = (void*)(v->fruits_ + fruit_size*(low[0]+half));
const bool cmp = fruit_compare(fruit, probe) > 0;
low[0] = low[cmp];
}
return low[0];
}
// binary search. Equivalent to lower_bound in c++ STL
int ng_vector_binary_search_lower_bound(const ng_vector_t* v,
const int l, const int h,
const int fruit_size, const void* fruit,
int(*fruit_compare)(const void*,
const void*))
{
// initalize the low we use to the low supplied
int low[2];
low[0] = l;
int size = (h-l);
while(size>0){
const int half = size/2;
low[1] = low[0]+size-half;
size = half;
const void* probe = (void*)(v->fruits_ + fruit_size*(low[0]+half));
const bool cmp = fruit_compare(fruit, probe) >= 0;
low[0] = low[cmp];
}
return low[0];
}
|
C
|
#include <stdio.h>
unsigned int bit_set(unsigned int value, int n)
{
value = value | 1 << (n - 1);
return value;
}
int bitpat_search(unsigned int source, unsigned int pattern, int n)
{
int int_size = 32, i, j, k = 1;
unsigned int compare, movePattern, move, temp = 1, theMove = 0;
for (i = 1; i <= n; i++)
theMove = bit_set(theMove, i);
movePattern = theMove & pattern;
while (temp != 0)
{
temp = source >> k;
k++;
}
for (j = k - 1 - n; j >= 0; j--)
{
move = (source >> j) & theMove;
if (move == movePattern)
return (k - 1 - j - n);
}
return -1;
}
int main(void)
{
int bitpat_search(unsigned int source, unsigned int pattern, int n);
unsigned int s = 0xe1f4u, p = 0x8u;
printf("%i\n", bitpat_search(s, p, 4));
return 0;
}
|
C
|
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/sem.h>
#include<sys/shm.h>
#include <sys/stat.h>
#include<fcntl.h>
static struct sembuf buf;
void podnies (int semid, int semnum)
{
buf.sem_num = semnum;
buf.sem_op = 1;
buf.sem_flg = 0;
if(semop(semid, &buf, 1) == -1)
{
printf("blad przy podnoszeniu semafora\n");
exit(1);
}
}
void opusc (int semid, int semnum)
{
buf.sem_num = semnum;
buf.sem_op = -1;
buf.sem_flg = 0;
if(semop(semid, &buf, 1) == -1)
{
printf("blad przy opuszczaniu semafora\n");
exit(1);
}
}
int main()
{
int NR_semafora, NR_pamieci, NR_sem2;
int semid, shmid, pid, pid2, semid2,i,lproc;
FILE *fp1;
char *buf_shm, tab[120];
struct semid_ds buf3;
struct shmid_ds buf4;
//========tworzenie semafora========
NR_semafora=ftok(".", 'G');
semid = semget(NR_semafora, 2, IPC_CREAT|0666);
if(semid==-1)
{
printf("err semafor projekt\n");
exit(2);
}
lproc=semctl(semid,1,GETNCNT,0);
if(semctl(semid, 0, SETVAL, lproc)== -1)
{
printf("blad nadania wartosci projekt\n");
exit(3);
}
if(semctl(semid, 1, SETVAL, 0)== -1)
{
printf("blad nadania wartosci projekt\n");
exit(3);
}
//========koniec tworzenia semafora
//========tworzenie pamieci wspoldzielonej====
NR_pamieci=ftok(".", 'P');
shmid = shmget(NR_pamieci, 120, IPC_CREAT|0666);
buf_shm=(char*)shmat(shmid, NULL, 0);
//========koniec tworzenia pamieci wspoldzielonej====
if((fp1=fopen("matyjek_pisarz2.c","r"))==NULL)
{
printf("cos nie teges\n");
exit(1);
}
lproc=semctl(semid,1,GETNCNT,0);
//printf("%d\n",lproc);
while((fgets(tab,120,fp1))!=NULL)
{i=0;
while(i<lproc)
{
opusc(semid,0);
i++;
}
strncpy(buf_shm, (char*)tab, 120);
while(i)
{
podnies(semid,1);
i--;
}
usleep(50000);
}
while(semctl(semid,0,GETVAL,0))
{
opusc(semid,0);
i++;
}
buf_shm[0]='\0';
while(i)
{
podnies(semid,1);
i--;
}
usleep(300000);
semctl(semid, 0, IPC_RMID, &buf3);
semctl(semid2, 0, IPC_RMID, &buf3);
shmctl(shmid, IPC_RMID, &buf4);
printf("Koncze prace\n");
return 0;
}
|
C
|
/*
Este programa crea dos hilos. Cada hilo hace exactamente lo mismo, incrementar una variable
global un numero de veces "NITER". El resultado final debe ser el doble del numero de veces que se
incrementa la variable, ya que cada hilo la incrementa el mismo número de veces.
Si no hubiera semáforo general, el resultado podría ser inconsistente.
*/
#include <pthread.h>
#include <semaphore.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h> //Para la funcion strerror(), que permite describir el valor de errno como cadena.
#define NITER 100
int count = 0; //Recurso compartido
sem_t mutex; //Semaforo general
void * ThreadAdd(void *a)
{
int i, tmp,p;
for(i = 0; i < NITER; i++)
{
p = sem_wait(&mutex); //Chequeo para ver si el semáforo está abierto despues de decrementar.
if (p !=0)
{
printf("sem_wait error...\n");
printf("errno value= %d definido como %s\n", errno, strerror(errno));
pthread_exit(NULL);
}
/*
¿ Por que no poner count++ ?
Es para simular que el simple incremento de una variable podría estar compuesto a nivel ensamblador
de varias instrucciones e incluso involucrar a la ALU, por lo que el hilo se podria ver interrumpido
o sacado de la CPU antes de realizar todas las instrucciones que dieran lugar al incremento.
En este caso podriamos suponer que el proceso puede salir despues de la sentencia tmp = count;
con lo que el valor de count podria ser inconsistente en count = tmp; si algún otro hilo modifica
mientras el actual esta fuera de la CPU.
*/
tmp = count; //Seccion Critica
tmp = tmp+1; //Seccion Critica
count = tmp; //Seccion Critica
p = sem_post(&mutex); //Se comprueba el valor del semáforo al incrementarlo. Si hay algun proceso en cola pasa a estado Listo.
if (p !=0)
{
printf("sem_post error...\n");
printf("errno value= %d definido como %s\n", errno, strerror(errno));
pthread_exit(NULL);
}
}
pthread_exit(NULL);
}
int main(int argc, char * argv[])
{
pthread_t tid1, tid2;
int p;
//Inicializamos nuestro semáforo a 1
//y el cero indica que el semáforo solo
//estara disponible para este main() y sus hilos().
p = sem_init(&mutex, 0, 1);
if (p !=0)
{
printf("sem_init error...\n");
printf("errno value= %d definido como %s\n", errno, strerror(errno));
exit(EXIT_FAILURE);
}
//Note que podría hacer lo siguiente con un bucle for() en vez de repetir codigo. Modifiquelo.
if(pthread_create(&tid1, NULL, ThreadAdd, NULL))
{
printf("\n ERROR creating thread 1");
exit(EXIT_FAILURE);
}
if(pthread_create(&tid2, NULL, ThreadAdd, NULL))
{
printf("\n ERROR creating thread 2");
exit(EXIT_FAILURE);
}
//Note que podría hacer esto con un bucle for(). Modifiquelo.
if(pthread_join(tid1, NULL)) /* wait for the thread 1 to finish */
{
printf("\n ERROR joining thread");
exit(EXIT_FAILURE);
}
if(pthread_join(tid2, NULL)) /* wait for the thread 2 to finish */
{
printf("\n ERROR joining thread");
exit(EXIT_FAILURE);
}
//Se comprueba si el valor del recurso compartido es menor o mayor del doble, que es lo que se espera.
//Nunca entrara en el primer if al haber utilizado un semaforo para evitar inconsistencia de datos.
if ( (count< (2 * NITER)) || (count>(2 * NITER)) )
printf("\nBOOM! count is [%d], should be %d\n", count, 2*NITER);
else
printf("\nOK! count is [%d] \n", count);
exit(EXIT_SUCCESS);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#if 0 //chri
#include <getopt.h>
#include <linux/soundcard.h>
#include <sys/resource.h>
#include <linux/config.h>
#endif
#include <math.h>
#include "faad.h"
#include "audio.h"
audio_file *open_audio_file(char *infile, int samplerate, int channels,
int outputFormat, int fileType, long channelMask)
{
//int freq = 44100;
//int stereo = 1;
audio_file *aufile = malloc(sizeof(audio_file));
aufile->outputFormat = outputFormat;
aufile->samplerate = samplerate;
aufile->channels = channels;
aufile->total_samples = 0;
aufile->fileType = fileType;
aufile->channelMask = channelMask;
switch (outputFormat)
{
case FAAD_FMT_16BIT:
aufile->bits_per_sample = 16;
break;
case FAAD_FMT_24BIT:
aufile->bits_per_sample = 24;
break;
default:
if (aufile) free(aufile);
return NULL;
}
if(infile[0] == '-')
{
aufile->sndfile = stdout;
} else {
aufile->sndfile = (FILE *)open(infile, (O_WRONLY | O_CREAT | O_TRUNC), 0660);
}
if(infile[0] == '/' && infile[1] == 'd')
{
/* //chri
if (ioctl(aufile->sndfile, SNDCTL_DSP_SPEED, &freq) < 0)
{
printf("sampling frequency fail\n\n");
return (0);
}
if (ioctl(aufile->sndfile, SNDCTL_DSP_STEREO, &stereo) < 0)
{
printf("stereo fail\n\n");
return (0);
}
*/
}
else { //chri : already decided
aufile->fileType = OUTPUT_WAV;
}
if (aufile->sndfile == NULL)
{
if (aufile) free(aufile);
return NULL;
}
if (aufile->fileType == OUTPUT_WAV)
{
if (aufile->channelMask)
write_wav_extensible_header(aufile, aufile->channelMask);
else
write_wav_header(aufile);
}
return aufile;
}
#if 0
int write_audio_file(audio_file *aufile, void *sample_buffer, int samples, int offset)
{
char *buf = (char *)sample_buffer;
switch (aufile->outputFormat)
{
case FAAD_FMT_16BIT:
return write_audio_16bit(aufile, buf + offset*2, samples);
case FAAD_FMT_24BIT:
//return write_audio_24bit(aufile, buf + offset*4, samples);
default:
return 0;
}
return 0;
}
#else
//Shawn 2004.8.27
int write_audio_file(audio_file *aufile, void *sample_buffer, int samples, int offset)
{
char *buf = (char *)sample_buffer;
switch (aufile->outputFormat)
{
case FAAD_FMT_16BIT:
aufile->total_samples += samples;
return (write(aufile->sndfile, (buf + offset*2), samples*2));
case FAAD_FMT_24BIT:
//return write_audio_24bit(aufile, buf + offset*4, samples);
aufile->total_samples += samples;
return (write(aufile->sndfile, (buf + offset*4), samples*4));
default:
return 0;
}
return 0;
}
#endif
void close_audio_file(audio_file *aufile)
{
if (aufile->fileType == OUTPUT_WAV)
{
lseek(aufile->sndfile, 0, SEEK_SET);
if (aufile->channelMask)
write_wav_extensible_header(aufile, aufile->channelMask);
else
write_wav_header(aufile);
}
if (aufile->sndfile)
close(aufile->sndfile);
if (aufile) free(aufile);
}
static int write_wav_header(audio_file *aufile)
{
unsigned char header[44];
unsigned char* p = header;
unsigned int bytes = (aufile->bits_per_sample + 7) / 8;
float data_size = (float)bytes * aufile->total_samples;
unsigned long word32;
*p++ = 'R'; *p++ = 'I'; *p++ = 'F'; *p++ = 'F';
word32 = (data_size + (44 - 8) < (float)MAXWAVESIZE) ?
(unsigned long)data_size + (44 - 8) : (unsigned long)MAXWAVESIZE;
*p++ = (unsigned char)(word32 >> 0);
*p++ = (unsigned char)(word32 >> 8);
*p++ = (unsigned char)(word32 >> 16);
*p++ = (unsigned char)(word32 >> 24);
*p++ = 'W'; *p++ = 'A'; *p++ = 'V'; *p++ = 'E';
*p++ = 'f'; *p++ = 'm'; *p++ = 't'; *p++ = ' ';
*p++ = 0x10; *p++ = 0x00; *p++ = 0x00; *p++ = 0x00;
if (aufile->outputFormat == FAAD_FMT_FLOAT)
{
*p++ = 0x03; *p++ = 0x00;
} else {
*p++ = 0x01; *p++ = 0x00;
}
*p++ = (unsigned char)(aufile->channels >> 0);
*p++ = (unsigned char)(aufile->channels >> 8);
word32 = (unsigned long)(aufile->samplerate + 0.5);
*p++ = (unsigned char)(word32 >> 0);
*p++ = (unsigned char)(word32 >> 8);
*p++ = (unsigned char)(word32 >> 16);
*p++ = (unsigned char)(word32 >> 24);
word32 = aufile->samplerate * bytes * aufile->channels;
*p++ = (unsigned char)(word32 >> 0);
*p++ = (unsigned char)(word32 >> 8);
*p++ = (unsigned char)(word32 >> 16);
*p++ = (unsigned char)(word32 >> 24);
word32 = bytes * aufile->channels;
*p++ = (unsigned char)(word32 >> 0);
*p++ = (unsigned char)(word32 >> 8);
*p++ = (unsigned char)(aufile->bits_per_sample >> 0);
*p++ = (unsigned char)(aufile->bits_per_sample >> 8);
*p++ = 'd'; *p++ = 'a'; *p++ = 't'; *p++ = 'a';
word32 = data_size < MAXWAVESIZE ?
(unsigned long)data_size : (unsigned long)MAXWAVESIZE;
*p++ = (unsigned char)(word32 >> 0);
*p++ = (unsigned char)(word32 >> 8);
*p++ = (unsigned char)(word32 >> 16);
*p++ = (unsigned char)(word32 >> 24);
return write(aufile->sndfile, header, sizeof(header));
}
static int write_wav_extensible_header(audio_file *aufile, long channelMask)
{
unsigned char header[68];
unsigned char* p = header;
unsigned int bytes = (aufile->bits_per_sample + 7) / 8;
float data_size = (float)bytes * aufile->total_samples;
unsigned long word32;
*p++ = 'R'; *p++ = 'I'; *p++ = 'F'; *p++ = 'F';
word32 = (data_size + (68 - 8) < (float)MAXWAVESIZE) ?
(unsigned long)data_size + (68 - 8) : (unsigned long)MAXWAVESIZE;
*p++ = (unsigned char)(word32 >> 0);
*p++ = (unsigned char)(word32 >> 8);
*p++ = (unsigned char)(word32 >> 16);
*p++ = (unsigned char)(word32 >> 24);
*p++ = 'W'; *p++ = 'A'; *p++ = 'V'; *p++ = 'E';
*p++ = 'f'; *p++ = 'm'; *p++ = 't'; *p++ = ' ';
*p++ = /*0x10*/0x28; *p++ = 0x00; *p++ = 0x00; *p++ = 0x00;
/* WAVE_FORMAT_EXTENSIBLE */
*p++ = 0xFE; *p++ = 0xFF;
*p++ = (unsigned char)(aufile->channels >> 0);
*p++ = (unsigned char)(aufile->channels >> 8);
word32 = (unsigned long)(aufile->samplerate + 0.5);
*p++ = (unsigned char)(word32 >> 0);
*p++ = (unsigned char)(word32 >> 8);
*p++ = (unsigned char)(word32 >> 16);
*p++ = (unsigned char)(word32 >> 24);
word32 = aufile->samplerate * bytes * aufile->channels;
*p++ = (unsigned char)(word32 >> 0);
*p++ = (unsigned char)(word32 >> 8);
*p++ = (unsigned char)(word32 >> 16);
*p++ = (unsigned char)(word32 >> 24);
word32 = bytes * aufile->channels;
*p++ = (unsigned char)(word32 >> 0);
*p++ = (unsigned char)(word32 >> 8);
*p++ = (unsigned char)(aufile->bits_per_sample >> 0);
*p++ = (unsigned char)(aufile->bits_per_sample >> 8);
/* cbSize */
*p++ = (unsigned char)(22);
*p++ = (unsigned char)(0);
/* WAVEFORMATEXTENSIBLE */
/* wValidBitsPerSample */
*p++ = (unsigned char)(aufile->bits_per_sample >> 0);
*p++ = (unsigned char)(aufile->bits_per_sample >> 8);
/* dwChannelMask */
word32 = channelMask;
*p++ = (unsigned char)(word32 >> 0);
*p++ = (unsigned char)(word32 >> 8);
*p++ = (unsigned char)(word32 >> 16);
*p++ = (unsigned char)(word32 >> 24);
/* SubFormat */
if (aufile->outputFormat == FAAD_FMT_FLOAT)
{
/* KSDATAFORMAT_SUBTYPE_IEEE_FLOAT: 00000003-0000-0010-8000-00aa00389b71 */
*p++ = 0x03;
*p++ = 0x00;
*p++ = 0x00;
*p++ = 0x00;
*p++ = 0x00; *p++ = 0x00; *p++ = 0x10; *p++ = 0x00; *p++ = 0x80; *p++ = 0x00;
*p++ = 0x00; *p++ = 0xaa; *p++ = 0x00; *p++ = 0x38; *p++ = 0x9b; *p++ = 0x71;
} else {
/* KSDATAFORMAT_SUBTYPE_PCM: 00000001-0000-0010-8000-00aa00389b71 */
*p++ = 0x01;
*p++ = 0x00;
*p++ = 0x00;
*p++ = 0x00;
*p++ = 0x00; *p++ = 0x00; *p++ = 0x10; *p++ = 0x00; *p++ = 0x80; *p++ = 0x00;
*p++ = 0x00; *p++ = 0xaa; *p++ = 0x00; *p++ = 0x38; *p++ = 0x9b; *p++ = 0x71;
}
/* end WAVEFORMATEXTENSIBLE */
*p++ = 'd'; *p++ = 'a'; *p++ = 't'; *p++ = 'a';
word32 = data_size < MAXWAVESIZE ?
(unsigned long)data_size : (unsigned long)MAXWAVESIZE;
*p++ = (unsigned char)(word32 >> 0);
*p++ = (unsigned char)(word32 >> 8);
*p++ = (unsigned char)(word32 >> 16);
*p++ = (unsigned char)(word32 >> 24);
return write(aufile->sndfile, header, sizeof(header));
}
#if 0
static int write_audio_16bit(audio_file *aufile, void *sample_buffer,
unsigned int samples)
{
int ret;
unsigned int i;
short *sample_buffer16 = (short*)sample_buffer;
char *data = malloc(samples*aufile->bits_per_sample*sizeof(char)/8);
aufile->total_samples += samples;
if (aufile->channels == 6 && aufile->channelMask)
{
for (i = 0; i < samples; i += aufile->channels)
{
short r1, r2, r3, r4, r5, r6;
r1 = sample_buffer16[i];
r2 = sample_buffer16[i+1];
r3 = sample_buffer16[i+2];
r4 = sample_buffer16[i+3];
r5 = sample_buffer16[i+4];
r6 = sample_buffer16[i+5];
sample_buffer16[i] = r2;
sample_buffer16[i+1] = r3;
sample_buffer16[i+2] = r1;
sample_buffer16[i+3] = r6;
sample_buffer16[i+4] = r4;
sample_buffer16[i+5] = r5;
}
}
for (i = 0; i < samples; i++)
{
data[i*2] = (char)(sample_buffer16[i] & 0xFF);
data[i*2+1] = (char)((sample_buffer16[i] >> 8) & 0xFF);
}
ret = write(aufile->sndfile, data, samples);
if (data) free(data);
return ret;
}
#else
//Shawn 2004.8.27
static int write_audio_16bit(audio_file *aufile, void *sample_buffer,
unsigned int samples)
{
int ret;
aufile->total_samples += samples;
ret = write(aufile->sndfile, sample_buffer, samples);
return ret;
}
#endif
/*
static int write_audio_24bit(audio_file *aufile, void *sample_buffer,
unsigned int samples)
{
int ret;
unsigned int i;
long *sample_buffer24 = (long*)sample_buffer;
char *data = malloc(samples*aufile->bits_per_sample*sizeof(char)/8);
aufile->total_samples += samples;
if (aufile->channels == 6 && aufile->channelMask)
{
for (i = 0; i < samples; i += aufile->channels)
{
long r1, r2, r3, r4, r5, r6;
r1 = sample_buffer24[i];
r2 = sample_buffer24[i+1];
r3 = sample_buffer24[i+2];
r4 = sample_buffer24[i+3];
r5 = sample_buffer24[i+4];
r6 = sample_buffer24[i+5];
sample_buffer24[i] = r2;
sample_buffer24[i+1] = r3;
sample_buffer24[i+2] = r1;
sample_buffer24[i+3] = r6;
sample_buffer24[i+4] = r4;
sample_buffer24[i+5] = r5;
}
}
for (i = 0; i < samples; i++)
{
data[i*3] = (char)(sample_buffer24[i] & 0xFF);
data[i*3+1] = (char)((sample_buffer24[i] >> 8) & 0xFF);
data[i*3+2] = (char)((sample_buffer24[i] >> 16) & 0xFF);
}
ret = write(aufile->sndfile, data, samples);
if (data) free(data);
return ret;
}
*/
|
C
|
#include"../inc/cmd.h"
int
run(int argc, char* argv[])
{
// No input file path, Print HELP
if(argc == 1){
printf("%s",help_info);
return 0;
}
// Initial static global variables
algo = 0, mode = 0, k_flag = 0, total_bytes = 0;
in_path = argv[1];
fp = NULL; out_path = NULL;
// read from in_path
fp = fopen(in_path, "rb");
isError(fp == NULL, "Open in_file failed:%s",in_path);
// Read byte-by-byte
total_bytes = fread(in_buff, 1, MAX_BUFF_SIZE, fp);
fclose(fp);
isError(total_bytes >= MAX_BUFF_SIZE, "Read file failed(Maximum support is 10MB)",NULL)
// command parsing, get algo, mode, keys...
CommandParsing(argc,argv);
// If no out_path, choose deafalt out_file,
// encoded/in_file_name or decoded/in_file_name
if(out_path == NULL) {
out_path = (char*)malloc(512);
if(mode == MODE_DECODE)
sprintf(out_path,"./decoded/%s",getFileName(in_path));
if(mode == MODE_ENCODE)
sprintf(out_path,"./encoded/%s",getFileName(in_path));
}
// Call program and calculate running time
Counter(Des(out_buff,in_buff, bit_keys, total_bytes, algo, mode);)
// Write the results
fp = fopen(out_path,"wb+");
isError(fp == NULL, "Open out_file failed:%s",out_path);
if(header)
fwrite(header,1,80,fp);
fwrite(out_buff,1,total_bytes-(total_bytes%8)+8*(!!(total_bytes%8)),fp);
fclose(fp);
// If you randomly generate a set of simple alphanumeric keys,
// output the keys to the file 'randomkeys.txt'
OutLog();
// B/ms
return total_bytes/(int)(run_time/1000);
}
static void
OutLog()
{
// get current time
getCurrentTime();
// Print log
if(log_path == NULL)
fp = fopen("des-log.txt","a");
else fp = fopen(log_path,"w+");
fprintf(fp,"time:\t%s\n",curtime);
if(mode == MODE_ENCODE)
fprintf(fp,"Type:\tENCODE\nAlgo:\t%d\n",algo);
if(mode == MODE_DECODE)
fprintf(fp,"Type:\tDECODE\nAlgo:\t%d\n",algo);
fprintf(fp,"Input:\t%s\n",in_path);
fprintf(fp,"Output:\t%s\n\n",out_path);
for(int i = 0; i < AKM[algo]; i++) {
fprintf(fp,"key %d:%llu\n", i+1, bit_keys[i]);
}
fprintf(fp,"\nFile size:\t%dKB\n",total_bytes >> 10);
fprintf(fp,"Run time:\t%fus\n",run_time);
fprintf(fp,"Operating speed:\t%dB/ms\n",total_bytes/(int)(run_time/1000));
fputs("-----------------------------------------\n",fp);
fclose(fp);
}
static void
CommandParsing(int argc, char* argv[])
{
int k_flag = 0;
header = log_path = NULL;
for(int i = 2; i < argc; i++)
{
if(argv[i] != NULL)
switch (argv[i][0])
{
case '0':
break;
case '1':
algo = ALGO_DESEEE3;
break;
case '2':
algo = ALGO_DESEDE3;
break;
case '3':
algo = ALGO_DESEEE2;
break;
case '4':
algo = ALGO_DESEDE2;
break;
case 'e':
mode = MODE_ENCODE;
break;
case 'd':
mode = MODE_DECODE;
break;
case '=':
out_path = argv[++i];
break;
case '-':
if(strcmp(argv[i], "--dec") == 0)
bit_keys[k_flag++] = Str2Bit64(argv[++i]);
else if(strcmp(argv[i], "--head") == 0)
header = argv[++i];
else if(strcmp(argv[i], "--log") == 0)
log_path = argv[++i];
break;
default:
break;
}
}
if(mode == MODE_ENCODE && k_flag == 0) {
KeyGenerator();
k_flag = AKM[algo];
}
isError(k_flag < AKM[algo],"No enough Keys!", NULL);
}
static void
KeyGenerator()
{
srand(time(NULL));
while(k_flag < AKM[algo]){
for(int i = 0; i < 64 ;i++)
{
if(rand() % 2)
bit_set_1(&bit_keys[k_flag] ,i);
else bit_set_0(&bit_keys[k_flag] ,i);
}
k_flag++;
}
}
static bit64
Str2Bit64(char * str)
{
if(str == NULL)
return 0;
bit64 ret = 0;
for(int i = 0; i < 20 && str[i] != '\0'; i++)
{
ret *= 10;
ret += str[i] - '0';
}
return ret;
}
static void
getCurrentTime()
{
time_t tmpcal_ptr;
struct tm *tmp_ptr = NULL;
time(&tmpcal_ptr);
tmp_ptr = gmtime(&tmpcal_ptr);
tmp_ptr = localtime(&tmpcal_ptr);
sprintf (curtime, "%d.%d.%d-%d:%d:%d",
(1900+tmp_ptr->tm_year), (1+tmp_ptr->tm_mon),
tmp_ptr->tm_mday, tmp_ptr->tm_hour,
tmp_ptr->tm_min, tmp_ptr->tm_sec);
}
static char*
getFileName(char *p)
{
int i = 0;
while (p[i] != '\0') i++;
while (i >= 0 && (p[i] != '\\' && p[i] != '/')) i--;
return p + i + 1;
}
|
C
|
#include "holberton.h"
/**
* _abs - determine the absolute value of an integer
* @i: variable to determine the absolute value of an integer
* Return: i if succesful
*/
int _abs(int i)
{
if (i < 0)
i *= -1;
return (i);
}
|
C
|
/*
* DE1-SoC LT24 Example
*
* Displays a test pattern on the LT24
* LCD using the LT24 bare metal driver.
*
* Created on: 09 Feb 2018
*/
#include "DE1SoC_LT24/DE1SoC_LT24.h"
#include "HPS_Watchdog/HPS_Watchdog.h"
#include "HPS_usleep/HPS_usleep.h"
#include "seven_seg/seven_seg.h"
#include <math.h>
volatile int *seg1_ptr = (int *) 0xFF200020;
volatile int *seg2_ptr = (int *) 0xFF200030;
volatile unsigned int *private_timer_load = (unsigned int *) 0xFFFEC600;
// ARM A9 Private Timer Value
volatile unsigned int *private_timer_value = (unsigned int *) 0xFFFEC604;
// ARM A9 Private Timer Control
volatile unsigned int *private_timer_control = (unsigned int *) 0xFFFEC608;
// ARM A9 Private Timer Interrupt
volatile unsigned int *private_timer_interrupt = (unsigned int *) 0xFFFEC60C;
//Array Length Helper
#define ARRAY_LEN(arr) (sizeof(arr)/sizeof(arr[0]))
//Debugging Function (same as last lab)
#include <stdlib.h>
void exitOnFail(signed int status, signed int successStatus){
if (status != successStatus) {
exit((int)status); //Add breakpoint here to catch failure
}
}
// frame rate with bit-bang mode is 6.6 per second
// with hardware optimisation enabled frame rate is 20 per second !
// speed increased by 20/6.6 = 303%
// the previous calc. was at optimization level of -O0 and Total RO Size (Code + RO Data 6.54kB
// at leve -o1 Total RO Size (Code + RO Data) 5.53kB ,frame rate same as -O0 ,o1 better memory
// at level O2 Total RO Size (Code + RO Datav 5.24kB) a little better size than o1
// frame-rate variable optimised away
//at o3 level max ,deafult for size the Total RO Size (Code + RO Datav 5.23kB) almost same as o2 and the frame rate is a little it better almost 21
// o3 with time ,code size is 6.20 kb ,and frame rate is 32 /s ,the fastest ever!
// Main Function
// =============
int main(void) {
//Variables
unsigned short colours[6] = {LT24_RED,LT24_YELLOW,LT24_GREEN,LT24_CYAN,LT24_BLUE,LT24_MAGENTA};
volatile unsigned int t_init=0;
volatile unsigned int t_final=0;
volatile unsigned int t_diff=0;
unsigned int colourIdx = 0;
//unsigned int f=225; // timer freq = 225mhz ,225 milion tick in 1 sec
volatile double tick_period=0.0044; // period of timer tick in nano sec
volatile double time_color_s=0;
volatile double time_color_ns=0;
unsigned long frame_rate=0;
*private_timer_load = 225000000;
//Initialise the LCD Display.
exitOnFail(
LT24_initialise(0xFF200060,0xFF200080), //Initialise LCD
LT24_SUCCESS); //Exit if not successful
HPS_ResetWatchdog();
//Display Internal Test Pattern
exitOnFail(
LT24_testPattern(), //Generate test pattern
LT24_SUCCESS); //Exit if not successful
HPS_ResetWatchdog();
//Wait a moment
usleep(500000);
HPS_ResetWatchdog();
*private_timer_control = (0<< 8) | (0 << 2) | (1 << 1) | (1 << 0); //auto ,start
//Main Run Loop
while (1) {
//Set display to solid colour
t_init=*private_timer_value;
LT24_clearDisplay(colours[colourIdx]);
//Update Colour Index
colourIdx++;
if (colourIdx >= ARRAY_LEN(colours)) {
colourIdx = 0;
}
t_final=*private_timer_value;
t_diff=t_init-t_final; // number of ticks
time_color_ns=t_diff * tick_period; // in nano sec
time_color_s=time_color_ns/1000000; // in sec
frame_rate=1/time_color_s;
seg_dec(frame_rate,1,seg1_ptr);
//Finally reset the watchdog.
HPS_ResetWatchdog();
}
}
|
C
|
#include <gtk/gtk.h>
#define BUFSIZE 256
/* Create the list of "messages" */
static GtkWidget *create_list( void )
{
GtkWidget *scrolled_window;
GtkWidget *textView;
/* Create a new scrolled window, with scrollbars only if needed */
textView= gtk_text_view_new();
scrolled_window = gtk_scrolled_window_new (NULL, NULL);
gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (scrolled_window),
GTK_POLICY_AUTOMATIC,
GTK_POLICY_AUTOMATIC);
{
char buffer[BUFSIZE];
size_t length;
FILE *in= fopen("test.txt", "r");
g_print("aaa1\n");
GtkTextBuffer *textBuffer= gtk_text_view_get_buffer(GTK_TEXT_VIEW(textView));
while ((length= fread (buffer, 1, BUFSIZE, in)) > 0) {
g_print(buffer);
gtk_text_buffer_insert_at_cursor(textBuffer, buffer, length);
}
fclose(in);
}
gtk_container_add (GTK_CONTAINER (scrolled_window), textView);
return scrolled_window;
}
int main( int argc,
char *argv[] )
{
GtkWidget *window;
GtkWidget *vpaned;
GtkWidget *hpaned;
GtkWidget *button;
GtkWidget *list;
gtk_init (&argc, &argv);
window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
gtk_window_set_title (GTK_WINDOW (window), "Paned Windows");
g_signal_connect (window, "destroy",
G_CALLBACK (gtk_main_quit), NULL);
gtk_container_set_border_width (GTK_CONTAINER (window), 10);
gtk_widget_set_size_request (GTK_WIDGET (window), 450, 400);
vpaned = gtk_vpaned_new ();
gtk_container_add (GTK_CONTAINER (window), vpaned);
gtk_widget_show (vpaned);
hpaned = gtk_hpaned_new ();
gtk_paned_add1 (GTK_PANED (vpaned), hpaned);
gtk_widget_show (hpaned);
list = create_list ();
gtk_paned_add1 (GTK_PANED (hpaned), list);
list = create_list ();
gtk_paned_add2 (GTK_PANED (hpaned), list);
button = gtk_button_new_with_label ("Hello World2");
gtk_paned_add2 (GTK_PANED (vpaned), button);
gtk_widget_show (button);
gtk_widget_show (window);
gtk_widget_show_all(window);
gtk_main ();
return 0;
}
|
C
|
#include <stdio.h>
int main(){
int cont=0,N=0,m;
scanf("%d",&N);
while (cont<=10000){
cont++;
if(cont%N==2){
printf("%d\n",cont);
}
}
return 0;
}
|
C
|
#include <stdio.h>
char *findFirstOcc(char c, char str[]) {
int i;
for(i = 0; str[i]; ++i) {
if(str[i] == c) {
return str + i;
}
}
return NULL;
}
int main(void) {
int cdt;
char str[256];
scanf("%d", &cdt);
while(cdt--) {
scanf(" %[^\n]%*c", str);
printf("('a') => %s\n", findFirstOcc('a', str));
}
return 0;
}
|
C
|
/**
\file myDebug.c
\brief Implementation file for custom debugging functions.
\date Dec 5, 2014
\author Luis M. Gallegos C.
*/
/******************************************************************************
* INCLUDE FILES *
******************************************************************************/
#include <stdint.h>
#include <stdio.h>
#include "platform.h"
#include "myDebug.h"
/******************************************************************************
* FUNCTION IMPLEMENTATIONS *
******************************************************************************/
void myDebug_init (void) {
/* Set debugging pins to output mode. */
PORTE.PDR.BIT.B5 = 1;
PORTE.PDR.BIT.B6 = 1;
/* Set debugging pins to low. */
PORTE.PODR.BIT.B5 = 0;
PORTE.PODR.BIT.B6 = 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <string.h>
//input:seconds,path,args
int pid;
void alarmAction (int signum)
{
printf("ALARM\n");
kill(pid,SIGKILL);
}
int main (int arc, char **argv, char **env)
{
if (arc <= 1)
printf("There are not any args\n");
else if (arc == 2)
printf("There must be 2 args at least:seconds and path\n");
else
{
int sec = atoi(argv[1]);
printf("sec is %d\n", sec);
printf("path is %s\n",argv[2]);
char **a = argv+2;
alarm(sec);
if ( (pid = fork()) == -1)
{
printf("fork error\n");
return 1;
}
else
if (pid == 0)
{
if(execv(argv[2], a) != -1);
else
{
printf("Evecv error\n");
return 1;
}
}
else
{
struct sigaction act;
act.sa_handler = alarmAction;
if (sigaction(SIGALRM, &act, NULL) != 0)
{
printf("sigaction error\n");
}
}
waitpid(pid, NULL, NULL);
}
return 0;
}
|
C
|
#include "trickle.h"
#include "positioning.h"
// PhoenixLL
#include "mayfly.h"
#include "debug.h"
// other
#include <string.h>
#include "SEGGER_RTT.h"
#define APP_ID 0x8070
#define KEY_LEN 14
/* Application "positioning"
* Key structure: (uint16_t app_id, uint8_t addr1[6], uint8_t addr2[6])
* Value: 1 byte RSSI
*/
// Structures, helper functions and interface for trickle
static uint8_t values[N_TRICKLE_NODES][N_TRICKLE_NODES];
// Memory for trickle instances
static uint8_t instances[N_TRICKLE_NODES][N_TRICKLE_NODES][TRICKLE_T_SIZE];
static uint8_t addresses[N_TRICKLE_NODES][6];
static uint32_t n_addresses = 0;
extern uint8_t dev_addr[6];
void
positioning_init(void) {
trickle_init((struct trickle_t*)instances, N_TRICKLE_NODES * N_TRICKLE_NODES);
// Start first instance - a meaningless self<->self RSSI just to give other nodes some packets
uint8_t key_data[KEY_LEN];
write_uint16(key_data, APP_ID);
memcpy(key_data+2, dev_addr, 6);
memcpy(key_data+8, dev_addr, 6);
slice_t key = new_slice(key_data, KEY_LEN);
uint8_t val_data = 0;
slice_t val = new_slice(&val_data, 1);
struct trickle_t *instance = positioning_get_instance(key);
ASSERT(instance);
trickle_value_write(instance, key, val, MAYFLY_CALL_ID_PROGRAM);
}
/* Translation from address to index. If address isn't yet indexed, give it an index.
Note: In this application, a key consists of two 6-byte addresses.
*/
uint32_t
get_index(uint8_t *address) {
for (int i = 0; i < n_addresses; i ++) {
if (memcmp(addresses[i], address, 6) == 0) {
return i;
}
}
// The address is not found. Give it an index.
uint32_t new_index = n_addresses++;
if (new_index >= N_TRICKLE_NODES) {
// Max number of addresses reached
return ~0;
}
memcpy(addresses[new_index], address, 6);
return new_index;
}
void
get_double_index(uint8_t *instance, uint32_t *i, uint32_t *j) {
uint32_t index = (instance - (uint8_t*)instances) / TRICKLE_T_SIZE;
// Convert from index to (i, j) index into 2D array
*i = index / N_TRICKLE_NODES;
*j = index % N_TRICKLE_NODES;
}
uint8_t
make_key(uint8_t *dest, uint8_t *addr1, uint8_t *addr2) {
write_uint16(dest, APP_ID);
memcpy(dest+2, addr1, 6);
memcpy(dest+8, addr2, 6);
return KEY_LEN;
}
///////////////
// Interface //
///////////////
// Generate key based on the index of the trickle instance in the `instances` array
// Return number of bytes written do `dest`
uint8_t
positioning_get_key(uint8_t *instance, uint8_t *dest) {
uint32_t i, j;
get_double_index(instance, &i, &j);
return make_key(dest, addresses[i], addresses[j]);
}
slice_t
positioning_get_val(uint8_t *instance) {
uint32_t i, j;
get_double_index(instance, &i, &j);
ASSERT(i < N_TRICKLE_NODES);
ASSERT(j < N_TRICKLE_NODES);
{
// For logic test - can be removed (TODO)
// Assuming 3 nodes, 9 indices.. just write to lines 11-14 a kind of instance 'id'
uint32_t id = ((i & 0b11) << 2) | (j & 0b11);
NRF_GPIO->OUTSET = (id << 11);
NRF_GPIO->OUTCLR = ((~id & 0b1111) << 11);
int a = 0;
}
return new_slice(&values[i][j], 1);
}
struct trickle_t*
positioning_get_instance(slice_t key) {
// Check that the key is for this application
if (read_uint16(key.ptr) != APP_ID || key.len != KEY_LEN) {
return 0;
}
// Want to register the address even if the next IF is true.
// (note that `get_index` inserts address into `addresses`)
uint32_t i = get_index(key.ptr + 2);
// Prohibit access to instances that reflect RSSI between a single device
if (memcmp(key.ptr+2, key.ptr+8, 6) == 0
// .... except self <-> self. It's used just for other nodes to get RSSI
&& memcmp(key.ptr+2, dev_addr, 6) != 0) {
return 0;
}
uint32_t j = get_index(key.ptr + 8);
if (i == ~0 || j == ~0) {
// Max number of addresses reached
return 0;
}
return (struct trickle_t *) &instances[i][j];
}
void
positioning_register_rssi(uint8_t rssi, uint8_t *other_dev_addr) {
uint8_t key_data[KEY_LEN];
make_key(key_data, dev_addr, other_dev_addr);
slice_t key = new_slice(key_data, sizeof(key_data));
struct trickle_t *instance = positioning_get_instance(key);
if (instance) {
slice_t val = new_slice(&rssi, 1);
trickle_value_write(instance, key, val, MAYFLY_CALL_ID_PROGRAM);
}
}
uint8_t
is_positioning_node(uint8_t *address) {
for (int i = 0; i < n_addresses; i ++) {
if (memcmp(addresses[i], address, 6) == 0) {
return 1;
}
}
return 0;
}
void
positioning_print(void) {
printf("\n =Registered addresses=\n\n");
// Print addresses
for (uint32_t i = 0; i < n_addresses; i ++) {
for (uint8_t j = 0; j < 6; j ++) {
printf("%x", addresses[i][j]);
if (!(i == n_addresses-1 && j == 5)) {
printf(", ");
}
}
printf("\n");
}
printf("\n =Trickle data=\n\n");
// Print matrix of values
for (uint32_t row = 0; row < n_addresses; row ++) {
for (uint32_t col = 0; col < n_addresses; col ++) {
printf("%d", values[row][col]);
if (col != n_addresses-1) {
printf(", ");
}
}
printf("\n");
}
printf("\n");
}
|
C
|
#include <stdio.h>
#include <cs50.h>
#include <math.h>
int getCoin(int n);
int main(void)
{
int counter = 0;
float change = -1;
int cents = 0;
while (change < 0)
{
printf("How much is the change?\n");
change = get_float();
cents = roundf(change * 100);
}
while (cents != 0)
{
cents -= getCoin(cents);
counter++;
}
printf("%i\n", counter);
}
int getCoin(int n)
{
int result=0;
if (n >= 25) {
result = 25;
} else if (n >= 10) {
result = 10;
} else if (n >= 5) {
result = 5;
} else if (n >= 1) {
result = 1;
}
return result;
}
|
C
|
/*
* Layout.h
*
* Created on: Jan 26, 2020
* Author: Kenny Rhodes
*
*/
#ifndef LAYOUT_H_
#define LAYOUT_H_
#include <stdio.h>
#include <stdlib.h>
#include "room.h"
typedef struct{
//A graph of rooms in the house
Room roomList;
}Layout;
int nRooms(void);
Room firstRoom(void);
void open(Room aRoom);
#endif /* LAYOUT_H_ */
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char vet[200];
char * str1;
int tam;
scanf("%[^\n]%*c", vet);
tam = strlen(vet);
str1 = (char *)malloc(sizeof(char) * tam);
for(int i = 0; i < tam; i++) {
str1[i] = vet[tam - 1 - i];
}
str1[tam] = '\0';
for(int i = 0; i < tam; i++) {
printf("%c", vet[i]);
}
printf("\n");
for(int i = 0; i < tam; i++) {
printf("%c", str1[i]);
}
return 0;
}
|
C
|
/*
Input one character and print that character.
*/
#include<stdio.h>
int main()
{
char w[20];
scanf("%s", &w);
printf("%s\n", w);
return 0;
}
|
C
|
#include "trie.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/**
* @brief Adding fake documentation to keep playing with github.
*
* @param trie
* @param word
*
* @return
*/
int add_word(trieNode* trie, char* word){
int i, j, length = strlen(word);
if(trie->letter){
printf("add_word should only be passed the root of a trie\n");
return 0;
}
for(i=0;i<length;i++){
if(trie->list[word[i] - 'a'])
trie = trie->list[word[i] - 'a'];
else{
trie = trie->list[word[i] - 'a'] = malloc(sizeof(trieNode));
init_node(trie);
trie->letter = word[i];
trie->depth = i+1;
}
}
trie->full_word = malloc(strlen(word));
strcpy(trie->full_word,word);
return 1;
}
int init_node(trieNode* trie){
int i;
for(i = 0; i<26;i++) trie->list[i] = NULL;
trie->letter = 0;
trie->full_word = NULL;
return 1;
}
trieNode* init_trie(char* dictionary){
FILE* dict;
if(!(dict = fopen(dictionary, "r"))) {
printf("Error opening dictionary\n");
exit(0);
}
char word[MAX_WORD];
trieNode* trie = malloc(sizeof(trieNode));
init_node(trie);
while(fscanf(dict, "%s\n",word) != EOF)
add_word(trie,word);
return trie;
}
int find_word(trieNode* trie, char* word){
printf("find_word should only be passed the root of a trie\n");
return 0;
}
for(i=0;i<length;i++){
if(trie->list[word[i] - 'a'])
trie = trie->list[word[i] - 'a'];
else return 0;
}
if(trie->full_word) return 1;
return 0;
}
|
C
|
//
// instruction.h
// desassembleur
//
// Created by Hubert Godfroy on 23/03/12.
// Copyright (c) 2012 Mines de Nancy. All rights reserved.
//
// Cette classe a pour but de faire de la POO en C..
//
/*!
* @file instruction.h
*/
#ifndef desassembleur_instruction_h
#define desassembleur_instruction_h
#include "macro.h"
#include "variable.h"
#include "processeur.h"
/*!
* Cette structure donne toutes les informations permettant de réaliser une
* instruction assembleur. Chacune des méthodes doivent également tenir compte du
* fait que certain de leurs paamètres peuvent être indéterminés.
*/
typedef struct _instruction{
/*!
* Cette méthode indique comment doit être réglé le drapeau d'overflow
* @param a
* @param b
* @param c
* @return La méthode renvoie un élément de armement_flag
*/
int(* of_aux)(const Variable a, const Variable b, const Variable c);
/*!
* Cette méthode indique comment doit être réglé le drapeau CF
*/
int(* cf_aux)(const Variable a, const Variable b, const Variable c);
/*!
* Cette méthode indique comment doit être réglé le drapeau CF
*/
int(* af_aux)(const Variable a, const Variable b, const Variable c);
int zf_aux; /*!<UNLOKED si l'instruction modifie ZF*/
int pf_aux; /*!<UNLOKED si l'instruction modifie PF*/
int sf_aux; /*!<UNLOKED si l'instruction modifie SF*/
/*!
* f renvoie un pointeur sur la Variable qu'il
* ne modifie par la Variable de flags
* par contre il doit modifier la Variable IP.
*/
Variable (*f)(Variable a, Variable b, Variable c, Processeur*p, int len);
}Instruction;
/*!
* Execute l'instruction virtuelement si possible et ses conséquentes sur les
* divers flags. Enregistre le changement d'état
* dans un processeur virtuel
* @param Instruction à executer
* @param Variable concernée
* @param Variable concernée
* @param Variable concernée
* @param Taille de l'instruction en octet
* @param Processeur virtuel
*/
Variable do_instr(Instruction*, Variable, Variable, Variable, int, Processeur*);
/*!
* Crée une instruction
* Il vaut mieux ne pas utiliser directement cette fonction dans le cadre de
* l'utilisation pour le désassemblage. En effet, il vaut mieux utiliser des
* fonctions d'initialisation déjà préparée qui simplifie la création d'une
* instruction
* @param of Fonction qui agit sur le flag d'overflow
* @param cf Fonction qui agit sur le flag de retenue
* @param af Fonction qui agit sur le flag d'ajustement
* @param zf 1 si le flag de zéro peut être modifié, 0 sinon
* @param pf 1 si le flag de parité peut être modifié, 0 sinon
* @param sf 1 si le flag de signe peut être modifié, 0 sinon
*/
Instruction* newInstruction(
int of(const Variable,
const Variable,
const Variable),
int cf(const Variable,
const Variable,
const Variable),
int af(const Variable,
const Variable,
const Variable),
int zf,
int pf,
int sf,
Variable f(Variable,
Variable,
Variable,
Processeur*, int)
);
/*!
* Efface de la mémoire une Instruction.
* @param Instruction à effacer
*/
void terminateInstruction(Instruction*);
/*-------------------------------------------------------------------*/
typedef struct _test{
int (*f)(int);
}test;
int do_test(test*, int);
test* newTest(int f(int));
#endif
|
C
|
#include <stdio.h>
/*
* print Fahrenheit-Celsius table for fahr = 0, 20, ..., 300
*/
float fahr_to_cel(int fahr);
float fahr_to_cel(int fahr)
{
return (5.0 / 9.0) * (fahr - 32.0);
}
main()
{
/*
* Declarations: <type> <variable name>
*/
float fahr, celsius;
int lower, upper, step;
/*
* Assignment statements
*/
lower = 0; // lower limit of temperature table
upper = 300; // upper limit
step = 20; // step size
fahr = lower;
printf("Convering Fahrenheit to Celsius\n%3c\t%6c\n%s", 'F', 'C', "---------------\n");
while (fahr <= upper) {
// decimal point in constant indicates floating point
/*
* If an arithmetic operator has integer operands, an integer operation is performed
* If an arithmetic operator has one floating-point operand and one integer operand, the integer
* operand will be converted to a floating-point before the operation is done.
*/
celsius = fahr_to_cel(fahr); //function call fahr_to_cel(fahr)
// print fahr in a field that is 3 digits wide, celsisu in a field that is 6 digits wide
printf("%3.0f\t%6.1f\n", fahr, celsius); //printf is not actually part of the C language, ANSI standard defines this
fahr = fahr + step;
}
}
|
C
|
#include <stdio.h>
int main()
{
int a[6] = {1, 2, 3, 4, 5, 6};
for (int i = 0; i < 6; i++)
{
if (i == 4)
break;
printf("\nAddress of array index elements %d is %x.", a[i], &a[i]);
}
return 0;
}
|
C
|
//
// Created by gianluca on 23/11/19.
//
#include <stdio.h>
#define MAXD 7
int maj(int *v, int n);
int main()
{
int vet[MAXD] = {3, 3, 9, 4, 3, 5, 3};
int ris = maj(vet, MAXD);
printf("%d\n", ris);
return 0;
}
int maj(int *v, int n)
{
if(n==1) return *v; //Il vettore unitario ha il suo unico elemento come maggioritario
//Calcolo maggioritario di sinistra
int ms = maj(v, n/2); // v contiente l'indirizzo prima cella vettore originale (prima cella vettore sx)
int md = maj(v+(n/2), n/2); //v+(n/2) contiene l'ndirizzo della *cellam successiva a quella di mezzo (prima cella vettore dx)
if (ms==-1 && md==-1) return -1; //se entrambi i vettori non hanno l'elemento è inutile cercare
if (ms == md) return ms; //se i valori sono uguali ovviamente l'elemento sarà un maj
int cs = 0, cd=0;
// conta contemporanea di maj sx e dx all'interno del vettore originale
for (int i = 0; i < n; i++) {
if (v[i]==ms) cs++;
if (v[i]==md) cd++;
}
if (cs>n/2) return ms; // !!In caso di parità torna sempre il vincitore di sinistra
if (cd>n/2) return md;
else return -1;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#define MAXN 999999999
#define MAXV 100
int M[MAXV][MAXV],X[MAXV],n;
int flag=0;//ǿ֧ͨ
/* +(X)ǷΪ? :0;:1*/
int Phi_plus() {
int i,j;
for(i=1;i<=n;i++)
for (j=1;j<=n;j++)
if ((i!=j)&&(X[i]==-1)&&(X[j]==0)&&(M[i][j])) return(1);
return(0);
}
void prim1() {
int i,j;
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
if ((i!=j)&&(X[i]==-1)&&(X[j]==0)&&(M[i][j])) {
X[j]=-1;
X[0]++;
}
}
/* -(X)ǷΪ? :0;:1*/
int Phi_minus() {
int i,j;
for(i=1;i<=n;i++)
for (j=1;j<=n;j++)
if ((i!=j)&&(X[i]==flag)&&(X[j]==-1)&&(M[j][i])) return(1);
return(0);
}
void prim2() {
int i,j;
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
if ((i!=j)&&(X[i]==flag)&&(X[j]==-1)&&(M[j][i])) {
X[j]=flag;
X[0]++;
}
}
void SCC() {
int i=1,j;
int visited;
//еδʱ
while (X[0]<n) {
while (X[i]>0) i++;
flag++;
X[i]=-1;
X[0]++;
visited=X[0];
while ( (X[0]<n) && Phi_plus()) prim1();
X[0]=visited;
X[i]=flag;
while ( (X[0]<n) && Phi_minus()) prim2();
for (j=i;j<=n;j++)
if (X[j]==flag) printf("%d ",j);
else if (X[j]==-1) X[j]=0;
printf("\n");
}
printf("%dǿ֧ͨ\n",flag);
}
void main() {
int i,j;
freopen("SCC.in", "r", stdin);
printf("DĶn=");
scanf("%d",&n);
printf("DڽӾ:\n");
for (i=1;i<=n;i++)
for (j=1;j<=n;j++)
scanf("%d",&M[i][j]);
printf("ǿ֧ͨΪ:\n");
SCC();
if (flag==1) printf("Dǿͨͼ\n");
else printf("Dǿͨͼ\n");
getch();
}
|
C
|
/*
* File: main.c
* Author: bryan
*
* Created on 18 de julio de 2018, 11:55 AM
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*
* Argumentos principales argc para el contador de parametros ingresados en la ejecucion
* argv para el puntero que hace referencia a los parametros ingresados
*/
int main(int argc, char** argv) {
char nombre[50];
char mensaje[50]="Bienvenido al programa: ";
if(argc==1){
printf("Que nombre de personaje desea tener? ");
//se delimita la entrada nombre para no lanzar warnings en la compilacion
fgets(nombre,40,stdin);
}else{
int contador=0;
for(int i=1;i<argc;i++){// empieza el contador en 1 porque el primer parametro argv[0] es el nombre del ejecutable
int longParam=strlen(argv[i]); //longitud del parametro en turno
char temporal[longParam]; //se crea un arreglo para almacenar el contenido del parametro en turno
strcpy(temporal,argv[i]); //traspaso de arreglos, parametro a temporal
for(int j=0;j<longParam;j++){
nombre[contador]=temporal[j]; //concatenando cadena nombre con cada parametro temporal
contador++;
}
nombre[contador]=' '; //almacenando espacio entre parametros
contador++;
}
}
printf("%s %s",mensaje,nombre); //se imprimen los parametros
printf("\n");
char expresion='s';
while (expresion=='r'||expresion=='R') {
printf("Hola Mundo");
}
do{
printf("Hola Mundo");
expresion='s';
}while(expresion=='r'||expresion=='R');
switch(expresion){
case 'r':{
printf("Hola Mundo");
break;
}
case 't':{
printf("Hola Mundo");
break;
}
case 's':{
printf("Hola Mundo");
break;
}
default :{
printf("Hola Mundo");
break;
}
}
return (EXIT_SUCCESS);//fin de proceso
}
|
C
|
#include <stdio.h>
int strlen1(char *s);
int main(void)
{
char str[] = "hogefoobar";
printf("length of str:%d\n", strlen1(str));
return 0;
}
int strlen1(char *s)
{
int len = 0;
for (; s[len] != '\0'; len++);
return len;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(void)
{
int arr[2][2][2] = {1, 2, 3, 4, 5, 6, 7, 8};
printf("%d \n", arr[1][0][1]);
printf("1°: %d \n", *(*(*(arr+1)+0)+1));
printf("2°: %d \n", *(*(arr[1]+0)+1));
printf("3°: %d \n", *(arr[1][0]+1));
printf("4°: %d \n", (*(arr+1))[0][1]);
printf("4°(): %d \n", *(arr+1)[0][1]);
printf("5°: %d \n", (*(arr[1]+0))[1]);
printf("5°(): %d \n", *(arr[1]+0)[1]);
printf("6°: %d \n", (*(*(arr+1)+0))[1]);
// arr[1][0][1] ִ 5 ̻
/*
1. *(*(*(arr+1)+0)+1)
2. *(*(arr[1]+0)+1)
3. *(arr[1][0]+1)
4. (*(arr+1))[0][1]
5. (*(arr[1]+0))[1]
6. (*(*(arr+1)+0))[1]
*(dereference) [](Array subscript) 켱
1. 4°
*(arr+1)[0][1] *((arr+1)[0][1]) ؼ ǰ ϳ Ǯ Ẹ
*((arr+1)[0][1])
*(*(arr+1+0)[1])
*(arr[1][1])
*(arr[1][1]+0)
arr[1][1][0] = 7 ̴
2. 5°
*(arr[1]+0)[1]
*((arr[1]+0)[1])
*((arr[1])[1])
*(arr[1][1])
arr[1][1][0]
*/
return 0;
}
|
C
|
/*գҪıйص䡣
һ looptimes (0<looptimes<10) looptimes 㣺
ʮơ˽ƺʮʽÿʮơ˽ƺʮʽ
ʾ˵
룺
1 (looptimes=1)
31 11 1a (ʮ31˽11ʮ1a)
The decimal is 31, the octal is 37, the hexadecimal is 1f. (ʮ31ʮơ˽ƺʮʽ31, 37, 1f)
The decimal is 9, the octal is 11, the hexadecimal is 9. ˽11ʮơ˽ƺʮʽ9, 11, 9)
The decimal is 26, the octal is 32, the hexadecimal is 1a. ʮ1aʮơ˽ƺʮʽ26, 32, 1a)
*/
#include <stdio.h>
int main(void)
{
int decimal, octal, hexadecimal;
int looptimes, ri;
scanf("%d", &looptimes);
for(ri = 1; ri <= looptimes; ri++){
scanf("%d%o%x", &decimal, &octal, &hexadecimal);
printf("The decimal is %d, the octal is %o, the hexadecimal is %x.\n",decimal,decimal,decimal);
printf("The decimal is %d, the octal is %o, the hexadecimal is %x.\n",octal,octal,octal);
printf("The decimal is %d, the octal is %o, the hexadecimal is %x.\n",hexadecimal,hexadecimal,hexadecimal);
}
}
|
C
|
//
// main.c
// TwoFloats
//
// Created by Josiah Mory on 4/7/17.
// Copyright © 2017 kickinbahk Productions. All rights reserved.
//
#include <stdio.h>
int main(int argc, const char * argv[]) {
float firstNum;
float secondNum;
double combinedNums;
firstNum = 3.14;
secondNum = 82.25;
combinedNums = firstNum + secondNum;
printf("The combination of the numbers %f and %f is %f.\n", firstNum, secondNum, combinedNums);
return 0;
}
|
C
|
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "lib_util.h"
#include "stringsorting.h"
void createStringElementsArray(StringElementsArray * si, int N)
{
si->N = N;
si->str = (char **) malloc(sizeof(char *) * N);
si->len = (int *) malloc(sizeof(int) * N);
return;
}
void freeStringElementsArray(StringElementsArray * si)
{
free(si->str);
free(si->len);
return;
}
///PARA NIF
void createStringElementsArrayAndFillNif(StringElementsArray * a, int N, pessoa * pessoas)
{
int i;
createStringElementsArray(a, N);
for (i = 0; i < N; i++)
{
a->str[i] = pessoas[i].nif;
a->len[i] = (int) strlen(pessoas[i].nif);
}
return;
}
///PARA NOME
void createStringElementsArrayAndFillNome(StringElementsArray * a, int N, pessoa * pessoas)
{
int i;
createStringElementsArray(a, N);
for (i = 0; i < N; i++)
{
a->str[i] = pessoas[i].nome;
a->len[i] = (int) strlen(pessoas[i].nome);
}
return;
}
///PARA DATA
void createStringElementsArrayAndFillData(StringElementsArray * a, int N, pessoa * pessoas)
{
int i;
createStringElementsArray(a, N);
for (i = 0; i < N; i++)
{
a->str[i] = pessoas[i].datanascimento;
a->len[i] = (int) strlen(pessoas[i].datanascimento);
}
return;
}
///PARA CODIGO POSTAL
void createStringElementsArrayAndFillCodpostal(StringElementsArray * a, int N, pessoa * pessoas)
{
int i;
createStringElementsArray(a, N);
for (i = 0; i < N; i++)
{
a->str[i] = pessoas[i].cod_postal;
a->len[i] = (int) strlen(pessoas[i].cod_postal);
}
return;
}
///PARA FREGUESIA
void createStringElementsArrayAndFillFreguesia(StringElementsArray * a, int N, pessoa * pessoas)
{
int i;
createStringElementsArray(a, N);
for (i = 0; i < N; i++)
{
a->str[i] = pessoas[i].freguesia;
a->len[i] = (int) strlen(pessoas[i].freguesia);
}
return;
}
/*************************************************************************
* LSD Radix Sort
************************************************************************/
void lsd_sort(StringElementsArray * a, int N, int W, int R)
{
int i, r, d, c;
int * count = newIntArray(R + 1);
StringElementsArray aux; // aux Array
createStringElementsArray(&aux, N); // create aux array
for (d = W - 1; d >= 0; d--)
{
// reset count[] array
for (i = 0; i < R + 1; i++)
count[i] = 0;
// compute frequency counts
for (i = 0; i < N; i++)
count[a->str[i][d] + 1]++;
// transform counts to indicies
for (r = 0; r < R; r++)
count[r + 1] += count[r];
// distribute
for (i = 0; i < N; i++)
{
c = a->str[i][d];
aux.str[count[c]] = a->str[i];
aux.len[count[c]] = a->len[i];
count[c]++;
}
// copy back
for (i = 0; i < N; i++)
{
a->str[i] = aux.str[i];
a->len[i] = aux.len[i];
}
}
freeStringElementsArray(&aux);
}
/*************************************************************************
* MSD Radix Sort (without cutoff)
************************************************************************/
void msd_sort_whithout_cutoff(StringElementsArray *a, StringElementsArray *aux, int lo, int hi, int d, int R)
{
int i, r, c;
int * count = newIntArray(R + 2);
// reset count[] array
for (i = 0; i < R + 2; i++)
count[i] = 0;
if (hi <= lo)
return;
// compute frequency counts
for (i = lo; i <= hi; i++)
{
c = (d < a->len[i]) ? (a->str[i][d]) : -1;
count[c + 2]++;
}
// transform counts to indicies
for (r = 0; r < R + 1; r++)
count[r + 1] += count[r];
// distribute
for (i = lo; i <= hi; i++)
{
c = (d < a->len[i]) ? (a->str[i][d]) : -1;
aux->str[count[c + 1]] = a->str[i];
aux->len[count[c + 1]] = a->len[i];
count[c + 1]++;
}
// copy back
for (i = lo; i <= hi; i++)
{
a->str[i] = aux->str[i - lo];
a->len[i] = aux->len[i - lo];
}
// recursively sort for each character
for (r = 0; r < R; r++)
msd_sort_whithout_cutoff(a, aux, lo + count[r], lo + count[r + 1] - 1, d + 1, R);
free(count);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include "linkedHead.h"
struct Song_node * insert_front(struct Song_node *nody, char *artist, char *name){
struct Song_node *newSong = malloc(sizeof(struct Song_node));
strcpy(newSong->name, name);
strcpy(newSong->artist, artist);
newSong->next = nody;
return newSong;
}
int song_cmp(struct Song_node *one, struct Song_node *two){
if(! strcmp(one->artist,two->artist)){
return strcmp(one->name,two->name);
}
return strcmp(one->artist,two->artist);
}
struct Song_node * insert_ordered(struct Song_node *front,char *artist, char *name){
struct Song_node *newSong = malloc(sizeof(struct Song_node));
strcpy(newSong->name, name);
strcpy(newSong->artist, artist);
newSong->next = 0;
if(! front){
return newSong;
}
if(song_cmp(front,newSong)>=0){
newSong->next = front;
return newSong;
}
//newSong->name = newNode->name;
//newSong->artist = newNode->artist;
//newSong->next = newNode->next;
struct Song_node *currentSong_node = front;
while(currentSong_node->next){
if(song_cmp(currentSong_node->next,newSong)>=0){
newSong->next = currentSong_node->next;
currentSong_node->next = newSong;
return front;
}
currentSong_node = currentSong_node->next;
}
currentSong_node->next = newSong;
return front;
}
struct Song_node *remove_Song_node(struct Song_node *front, struct Song_node *soon_dead_node){
if(! soon_dead_node){
printf("Song not found\n");
return front;
}
if(! song_cmp(front,soon_dead_node)){
struct Song_node *returner = front->next;
free(front);
return returner;
}
struct Song_node *currentSong_node = front;
while(currentSong_node->next){
if(! song_cmp(currentSong_node->next,soon_dead_node)){
struct Song_node *deadSong_node = currentSong_node->next;
if(currentSong_node->next->next)
currentSong_node->next = currentSong_node->next->next;
else
currentSong_node->next = NULL;
free(deadSong_node);
return front;
}
currentSong_node = currentSong_node->next;
}
printf("Song not found");
return front;
}
struct Song_node * free_list(struct Song_node *list){
while(list != NULL){
printf("freeing Song_node: ");
print_node(list);
printf("\n");
list = remove_Song_node(list,list);
}
return list;
}
void print_list(struct Song_node *nody){
if(nody != NULL){
while(nody->next){
print_node(nody);
printf(" | ");
nody = nody->next;
}
print_node(nody);
printf(" |\n\n");
}
else
printf("NO SONGS!\n");
}
void print_node(struct Song_node *nody){
if(! nody){
printf("SONG NOT HERE");
return ;
}
printf("%s: %s", nody->artist, nody->name);
}
struct Song_node *find_unique(struct Song_node *list, char *artist, char*name){
struct Song_node *currentSong_node = list;
while(currentSong_node){
if(! strcmp(currentSong_node->artist,artist) && ! strcmp(currentSong_node->name,name)){
return currentSong_node;
}
currentSong_node = currentSong_node->next;
}
return NULL;
}
struct Song_node *find_artist(struct Song_node *front, char *artist){
struct Song_node *currentSong_node = front;
while(currentSong_node){
if(! strcmp(currentSong_node->artist,artist)){
return currentSong_node;
}
currentSong_node = currentSong_node->next;
}
return NULL;
}
struct Song_node *find_random(struct Song_node *front){
if(! front){
return NULL;
}
int total = countSongs(front);
int index = rand() %total;
int i = 0;
struct Song_node *currentSong_node = front;
while(i!=index){
currentSong_node = currentSong_node->next;
i++;
}
return currentSong_node;
}
int countSongs(struct Song_node *front){
int total = 0;
struct Song_node *currentSong_node = front;
while(currentSong_node){
total++;
currentSong_node = currentSong_node->next;
}
return total;
}
|
C
|
/**
*\file dwenguinoLumberjack.h
*\brief This file contains all the functions that are made specifically for the game.
*
*Almost all changes happen by changing the variables in the \a Game struct.
*\author Antoine, Sebastiaan
*/
#ifndef DWENGUINO_LUMBERJACK_H
#define DWENGUINO_LUMBERJACK_H
#include <stdlib.h>
#include "dwenguinoAccelerometer.h"
#define PITCH_POINT 10
#define MENU 0
#define ALIVE 1
#define DEAD 2
/*!
* \brief Struct containing all game variables.
*/
struct Game {
/**
\brief Array containing the approximate positions of the branches in the tree.
This variable is a 2D array consisting of two 1D arrays of length 8: they represent the left side and the right side of the tree.\n
These arrays are used to store the approximate positions of the branches in the tree. One element in the array contains 5 positions in the tree.\n
There can only be one branch in the total of the 5 positions. The exact position is stored in \a counter .
*/
int** tree;
int side_jack; /**<\brief Keeps track of the side of the player (left or right). */
int score; /**<\brief Keeps track of the score. */
int counter; /**<\brief Gives the exact position of the branch (1 to 5).*/
int difficulty; /**<\brief Defines the rate at which an LED goes off. */
int state; /**<\brief Gives the game state: ALIVE, DEAD or MENU*/
int tilt; /**<\brief Determines the speed at which the branches fall down*/
int speed; /**<\brief Rolling counter of the game. \detailed Caps at 29999, after that it goes back to 0 to prevent overflow.*/
};
typedef struct Game Game;
/*!
* \brief Allocates space to the \a Game struct and the tree array and assigns the right values to the variables of the \a Game struct.
*
* This function needs to be called before using any of the functions in this file.
*\return Pointer to the address of the \a Game struct.
*/
Game* InitGame();
/*!
* \brief Frees up the space allocated to the game.
*\param game Pointer to the \a Game struct.
*\return Void
*/
void DeleteGame(Game* game);
/*!
* \brief Updates the branches of the tree.
*
* This function generates new branches at the right time and updates the existing branches to fall one position.
*\param game Pointer to the \a Game struct.
*\return Void
*/
void UpdateTree(Game* game);
/*!
* \brief Updates the side on which Jack is standing, depending on the roll angle of the accelerometer.
*\param game Pointer to the \a Game struct.
*\return Void
*/
void UpdateSide(Game* game);
/*!
* \brief Changes the \a tilt variable depending on the pitch of the accelerometer
*\param game Pointer to the \a Game struct.
*\return Void
*/
void UpdateTilt(Game* game);
/*!
* \brief Sets the \a difficulty of the game.
*\param game Pointer to the \a Game struct.
*\param difficulty New difficulty to be set.
*\return Void
*/
void setDifficulty(Game* game, int difficulty);
/*!
* \brief Verifies if a branch is colliding with Jack and changes the game \a state and LEDs accordingly.
*\param game Pointer to the \a Game struct.
*\return Void
*/
void CheckCollision(Game* game);
/*!
* \brief Verifies the state of the LEDs and the \a state of the game for a "Game Over" and changes the \a Game struct accordingly.
*\return Void
*
*In case of a "Game-Over", the tree array is emptied, the LEDs are all turned off and game state is set to \a DEAD.
*\param game Pointer to the \a Game struct.
*\return Void
*/
void CheckGameOver(Game* game);
#endif //DWENGUINO_LUMBERJACK_H
|
C
|
/*Jinoo Hong*/
/*Take in 3 user-input numbers and print “numbers are equal” if all 3 numbers are equal, and “not equal”, followed by the largest number, if the numbers are not equal. Then print out the sum of the 3 numbers.*/
#include <stdio.h>
int main() {
int num1, num2, num3, total;
printf("Please enter a number: ");
scanf("%d", &num1);
printf("\nPlease enter another number: ");
scanf("%d", &num2);
printf("\nPlease enter a third number: ");
scanf("%d", &num3);
if (num1==num2&&num1==num3) {
printf("\nNumbers are equal");
total=num1*3;
}
else {
printf("\nNot equal");
int largest = num1;
if (num1<num2) {
largest = num2;
}
if (largest<num3) {
largest = num3;
}
printf("\n The largest number is %d", largest);
total=num1+num2+num3;
}
printf("\nThe sum of the numbers is %d \n", total);
}
|
C
|
#include<stdio.h>
int main()
{
char c;
int islowercasevowel,isuppercasevowel;
printf("enter an alphabets:");
scanf("%c",&c);
if(is lowercase vowel)
printf("%c is a vowel");
else
printf("%c is a consonants");
}
|
C
|
#include<stdio.h>
int main()
{
int arr[25],i,positive=0,negative=0,odd=0,even=0;
for(i=0;i<25;i++)
{
printf("\n enter the no = ");
scanf("%d",&arr[i]);
}
for(i=0;i<25;i++)
{
if (arr[i]>0)
positive++;
if (arr[i]<0)
negative++;
if (arr[i]%2==0)
even++;
else
odd++;
}
printf("\n %d positive no are",positive);
printf("\n %d negative no are",negative);
printf("\n %d even no are",even);
printf("\n %d odd no are",odd);
}
|
C
|
/*
* readability.c
* index = 0.0588 * L - 0.296 * S - 15.8
* L is the average number of letters per 100 words in the text
* S is the average number of sentences per 100 words in the text
* Ask user to input a string, count the number of letters (a-z, A-Z)
* Calculate grade
* Print as output "Grade X" where X is the grade level
*
* Created on: 17-Aug-2020
* Author: dc
*/
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <cs50.h> //CS50 header
#include <math.h>
int letterCount(string text); //func to count letters
int wordCount(string text); //func to count words
int senCount(string text); //func to count sentences
int main(void)
{
string input = get_string("Text: "); //text to be graded
int letters = letterCount(input);
int words = wordCount(input);
int sen = senCount(input);
int l = (letters * 100) / words; //calculate letters per 100 words
int s = (sen * 100) / words; //calculate sentences per 100 words
int grade = round(0.0588 * l - 0.296 * s - 15.8); //calculate grade
if (grade < 1)
{
printf("Before Grade 1\n");
}
else if (grade > 16)
{
printf("Grade 16+\n");
}
else
{
printf("Grade %d\n", grade);
}
}
int letterCount(string text)
{
int ctr = 0, len = strlen(text);
for (int i = 0; i < len; i++)
{
if (isalpha(text[i]) != 0) //count the alphabets
{
ctr++;
}
}
return ctr;
}
int wordCount(string text)
{
int ctr = 1, len = strlen(text); //ctr set at 1 coz 1 word will have 0 space, 2 words will have 1 space
for (int i = 0; i < len; i++)
{
if (text[i] == ' ') //assuming words are separated by space only
{
ctr++;
}
}
return ctr;
}
int senCount(string text)
{
int ctr = 0, len = strlen(text);
for (int i = 0; i < len; i++)
{
if (text[i] == '.' || text[i] == '?' || text[i] == '!') //assuming these are the sentence terminators
{
ctr++;
}
}
return ctr;
}
|
C
|
// Exercise 5-4. Write the function strend(s,t), which returns 1 of the string
// t occurs at the end of the string s, and zero otherwise.
#include <stdio.h>
int strend(char*, char*);
int main()
{
char a[] = "This is one string.";
char b[] = "one string.";
printf("%d\n", strend(a, b));
return 0;
}
int strend(char *s, char *t)
{
int i = strlen(s) - 1;
int j = strlen(t) - 1;
for (; (&t[j] != t || &s[i] != s) && s[i] == t[j]; i--, j--)
;
return &t[j+1] == t ? 1 : 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
struct queue{
int* data;
int head;
int tail;
int cap;
int count;
};
void initqueue(int n, struct queue* q){
q->data = (int*)malloc(n*sizeof(int));
q->cap = n;
q->count = 0;
q->head = 0;
q->tail = 0;
}
void relocation(struct queue* q){
int a[q->cap], i;
for (i = 0; i < q->cap; i++) a[i] = q->data[i];
free(q->data);
q->data = (int*)malloc(2*q->cap*sizeof(int));
for(i = 0; i<2*q->cap; i++) q->data[i] = 666;
if (q->tail>q->head){
for (i = 0; i < q->cap; i++) q->data[i] = a[i];
}
else{
for(i = 0; i<q->tail; i++) q->data[i] = a[i];
for(i = q->head; i<=q->cap-1; i++) q->data[i+q->cap] = a[i];
q->head +=q->cap;
}
q->cap = 2*q->cap;
}
int empty(struct queue* q){
return q->count == 0? 1 : 0;
}
void enqueue(int x, struct queue* q){
if(q->count==q->cap) relocation(q);
q->data[q->tail] = x;
q->tail++;
if(q->tail == q->cap) q->tail = 0;
q->count++;
}
int dequeue(struct queue* q){
int x = q->data[q->head];
q->head++;
if(q->head == q->cap) q->head = 0;
q->count--;
printf("%d\n", x);
return x;
}
int main(int argc, const char * argv[]) {
int n, i, n1;
scanf("%d", &n);
char cmd[5];
struct queue que;
struct queue* q = &que;
initqueue(4, q);
for(i = 0; i<n; i++){
scanf("%s", cmd);
if((cmd[0]=='E')&&(cmd[1]=='N')){
scanf("%d", &n1);
enqueue(n1, q);
}
if(cmd[0]=='D'){
n1 = dequeue(q);
}
if((cmd[0]=='E')&&(cmd[1]=='M')){
if(empty(q)) printf("true\n");
else printf("false\n");
}
}
free(q->data);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "linked_list.h"
// function to convert a linked list to an array
sized_arr convert_list_array(Node *list) {
sized_arr sized_array;
int size_list = get_size(list);
double *array = NULL;
array = malloc(sizeof(double) * size_list);
Node *temp = list;
int i;
for (i = 0; i < size_list; i++) {
array[i] = temp->data;
temp = temp->next;
}
sized_array.values = array;
sized_array.length = size_list;
return sized_array;
}
// functions to work with linked lists containing double data
void insert_begin(double x, Node **head) {
Node *n;
n = (Node*) malloc(sizeof(Node));
if (*head == NULL) {
n->data = x;
n->next = NULL;
*head = n;
return;
}
n->data = x;
n->next = *head;
*head = n;
}
void insert_end(double x, Node **head) {
Node *n, *temp;
n = (Node*) malloc(sizeof(Node));
if (*head == NULL) {
n->data = x;
n->next = NULL;
*head = n;
return;
}
temp = *head;
while (temp->next != NULL)
temp = temp->next;
temp->next = n;
n->data = x;
n->next = NULL;
}
void traverse(Node *head) {
Node *n;
n = head;
if (n == NULL) {
printf("Linked list is empty.\n");
return;
}
while (n->next != NULL) {
printf("%.3f, ", n->data);
n = n->next;
}
printf("%.3f\n", n->data);
}
int get_size(Node *head) {
Node *n;
n = head;
if (n == NULL)
return 0;
int c = 1;
while (n->next != NULL) {
c++;
n = n->next;
}
return c;
}
void delete_begin(Node **head) {
Node *n;
if (*head == NULL) {
printf("Linked list is already empty.\n");
}
n = (*head)->next;
free(*head);
*head = n;
}
void delete_end(Node **head) {
Node *n, *m;
if (*head == NULL) {
printf("Linked list is already empty.\n");
}
if ((*head)->next == NULL) {
free(*head);
*head = NULL;
}
n = *head;
while (n->next != NULL) {
m = n;
n = n->next;
}
m->next = NULL;
free(n);
}
// functions to work with linked lists containing
// other linked lists
void insert_begin_l(Node *data, Node_l **head) {
Node_l *n;
n = (Node_l*) malloc(sizeof(Node_l));
if (*head == NULL) {
n->data = data;
n->next = NULL;
*head = n;
return;
}
n->data = data;
n->next = *head;
*head = n;
}
void insert_end_l(Node *data, Node_l **head) {
Node_l *n, *temp;
n = (Node_l*) malloc(sizeof(Node_l));
if (*head == NULL) {
n->data = data;
n->next = NULL;
*head = n;
return;
}
temp = *head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = n;
n->data = data;
n->next = NULL;
}
void traverse_l(Node_l *head) {
Node_l *n;
n = head;
if (n == NULL) {
printf("Linked list is empty.\n");
return;
}
int i = 1;
while (n->next != NULL) {
printf("Row %d : ", i);
traverse(n->data);
n = n->next;
i++;
}
printf("Row %d : ", i);
traverse(n->data);
}
int get_size_l(Node_l *head) {
Node_l *n;
n = head;
if (n == NULL)
return 0;
int c = 1;
while (n->next != NULL) {
c++;
n = n->next;
}
return c;
}
void delete_begin_l(Node_l **head) {
Node_l *n;
if ((*head) == NULL) {
printf("Linked list is already empty.\n");
return;
}
n = (*head)->next;
free(*head);
*head = n;
}
void delete_end_l(Node_l **head) {
Node_l *n, *m;
if (*head == NULL) {
printf("Linked list is already empty.\n");
return;
}
if ((*head)->next == NULL) {
free(*head);
head = NULL;
return;
}
n = *head;
while (n->next != NULL) {
m = n;
n = n->next;
}
m->next = NULL;
free(n);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
#include <math.h>
float hipcalc(float a, float b);
/*2) Escrever uma funo para retornar o valor da hipotenusa de um tringulo retngulo dado os valores dos catetos.*/
int main()
{
setlocale(LC_ALL, "portuguese");
float op, adj, hipotenusa;
printf("Hipotenusa: %f\n",hipcalc(op,adj));
}
float hipcalc(float a,float b){
float hip;
printf("Digite o valor do cateto oposto do triangulo:");
scanf("%f",&a);
printf("Digite o valor do cateto adjacente do triangulo:");
scanf("%f",&b);
hip= sqrt( (pow(a,2) + pow(b,2)) );
return hip;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int *fill_arr(int count){
srand(time(NULL));
int *arr = (int*)malloc(count * sizeof(int));
for(int i = 0;i < count;i++){
*(arr + i*sizeof(int)) = rand() % 10;
}
return arr;
}
void print_arr(int *arr,int count){
for(int i = 0;i < count;i++){
printf("%d ",*(arr + i*sizeof(int)));
}
printf("\n");
}
int *delete_els(int *arr,int count,int start,int c_del){
int c = 0;
int temp[count - c_del];
for(int i = 0;i < count;i++){
if(i == start){
c = 1;
}
temp[i] = *(arr + (i + c_del*c)*sizeof(int));
}
if((arr = realloc(arr,(count - c_del)*sizeof(int))) == NULL){
return NULL;
}
for(int i = 0;i < count -c_del;i++){
*(arr + i*sizeof(int)) = temp[i];
}
return arr;
}
int *add_element(int *arr,int count,int key,int el){
int temp[count + 1];
int c = 0;
for(int i = 0;i < count;i++){
if(key == i){
temp[i] = el;
c=1;
}
temp[i + 1*c] = *(arr + i*sizeof(int));
}
if((arr = realloc(arr,(count + 1)*sizeof(int))) == NULL){
return NULL;
}
for(int i = 0;i < count + 1;i++){
*(arr + i*sizeof(int)) = temp[i];
}
return arr;
}
int main(){
int count,id,temp;
printf("Put count of elements:");scanf("%d",&count);
int *arr = fill_arr(count);
print_arr(arr,count);
printf("Put first element`s id to delete:");scanf("%d",&id);
printf("Put count of elements to delete:");scanf("%d",&temp);
arr = delete_els(arr,count,id,temp);
count -= temp;
print_arr(arr,count);
printf("Put id to add element:");scanf("%d",&id);
printf("Put value of element to add:");scanf("%d",&temp);
arr = add_element(arr,count,id,temp);
count += 1;
print_arr(arr,count);
free(arr);
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_printf.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: krios-fu <krios-fu@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/02/14 14:51:14 by krios-fu #+# #+# */
/* Updated: 2020/02/29 19:09:30 by krios-fu ### ########.fr */
/* */
/* ************************************************************************** */
#include "printf.h"
void ft_setformat_(t_printf *p)
{
if (ft_isdigit(*p->str) && *p->str != '0'
&& p->width == 0 && p->dot != '1')
p->width = ft_atoi(p->str);
if (*p->str == '.')
{
p->dot = '1';
p->str++;
if (*p->str == '*')
p->precision = va_arg(p->ap, int);
if (ft_isdigit(*p->str))
p->precision = ft_atoi(p->str);
}
}
void ft_setformat(t_printf *p, int nb)
{
p->precision = 0;
p->width = 0;
p->zero_space = ' ';
p->tab = ' ';
p->dot = '0';
while (!ft_isalpha(*p->str))
{
++p->str;
if (*p->str == '-')
p->tab = '-';
if (*p->str == '0' && p->tab != '-' && p->width == 0)
p->zero_space = '0';
if (*p->str == '*')
{
nb = va_arg(p->ap, int);
p->width = (nb < 0) ? (nb * -1) : nb;
p->tab = (nb < 0) ? '-' : p->tab;
}
ft_setformat_(p);
if (*p->str == '%')
break ;
}
}
void ft_getformat(t_printf *p)
{
if (p->type == 'd' || p->type == 'i')
ft_print_di(p, va_arg(p->ap, int));
if (p->type == 's')
ft_print_str(p, va_arg(p->ap, char *));
if (p->type == 'c')
ft_print_char(p, va_arg(p->ap, int));
if (p->type == 'u')
ft_print_u(p, va_arg(p->ap, int));
if (p->type == 'x')
ft_print_x(p, va_arg(p->ap, unsigned int));
if (p->type == 'X')
ft_print_xup(p, va_arg(p->ap, unsigned int));
if (p->type == 'p')
ft_print_p(p, va_arg(p->ap, char *));
if (p->type == '%')
ft_print_char(p, 37);
}
void ft_format_printf(t_printf *p)
{
p->len_str = 0;
while (*p->str)
{
if (*p->str == '%')
{
ft_setformat(p, 0);
p->zero_space = (p->precision >= 0 && p->zero_space == '0'
&& p->type == 'd') ? ' ' : p->zero_space;
p->type = *p->str;
ft_getformat(p);
}
else
p->len_str += write(1, p->str, 1);
++p->str;
}
}
int ft_printf(const char *str, ...)
{
t_printf pformat;
pformat.str = (char *)str;
va_start(pformat.ap, str);
ft_format_printf(&pformat);
va_end(pformat.ap);
return (pformat.len_str);
}
|
C
|
#include "LPmatrx.h"
int iSum(int n,int *v)
{
int i,r=0;
for (i=0; i<n; i++)
r+=v[i];
return (r);
} /* iSum */
int getPos(int n,
int i,
int *v)
{
int j;
for(j=0; j<n && i!=v[j]; ++j);
return (j);
} /* getPos */
void iZero(int n,
int *x,
int *sub)
{
int i;
if (sub) {
for(i=0; i<n; ++i)
x[sub[i]]=0;
}
else
memset(x,0,n*sizeof(n));
} /* iZero */
void iSet(int n,
int a,
int *x,
int *s)
{
int i;
if (!s)
for(i=0; i<n; ++i)
x[i]=a;
else
for(i=0; i<n; ++i)
x[s[i]]=a;
} /* iSet */
void iSwap(int i1,
int i2,
int *v)
{
int temp;
if ( i1<0 || i2<0 ) {
printf(" negative index.\n");
ShutDown();
exit(0);
}
temp = v[i1];
v[i1] = v[i2];
v[i2] = temp;
} /* iSwap */
void iCopy(int n,
int *x,
int *y)
{
memcpy(y,x,n*sizeof(int));
} /* iCopy */
void fSort(int num,
int maxi,
int *val,
int *fir,
int *link)
{
int k,v;
iSet(maxi+1,num,fir,NULL);
for(k=0; k<num; ++k) {
v = val[k];
if (v<=maxi) {
link[k] = fir[v];
fir[v] = k;
}
}
} /* fSort */
void dCopy(int n,
double *s,
double *d)
{
memcpy(d,s,sizeof(double)*n);
} /* dCopy */
double dSums(int nnz,
double x[],
int indx[])
{
double r=0.0;
int i;
if (indx) {
for(i=0; i<nnz; ++i)
r += x[indx[i]]*x[indx[i]];
}
else {
for(i=0; i<nnz; ++i)
r += x[i]*x[i];
}
return ( r );
} /* dSums */
void dZero(int n,
double x[],
int ind[])
{
int i;
if (!ind) {
memset(x,0,sizeof(double)*n);
}
else {
for(i=0; i<n; ++i)
x[ind[i]]=0.0;
}
} /* dZero */
void dSwap(int i,
int j,
double *x)
{
double temp;
temp=x[i];
x[i]=x[j];
x[j]=temp;
} /* dSwap */
double dNorm0(int n,
double x[],
int indx[])
{
int i;
double r=0.0;
if (!indx)
for(i=0; i<n; ++i)
r=max(r,fabs(x[i]));
else
for(i=0; i<n; ++i)
r=max(r,fabs(x[indx[i]]));
return (r);
} /* dNorm0 */
double dNorm1(int n,
double *x)
{
int i;
double r=0.0;
if (n) {
for(i=0; i<n; ++i)
r+=fabs(x[i]);
}
return ( r );
} /* dNorm1 */
double dNorm2(int n,
double *x)
{
int i;
double r=0.0;
for (i=0; i<n; i++)
r+=x[i]*x[i];
return (sqrt(fabs(r)));
} /* dNorm2 */
void addVect(int n,
double alf,
double *x,
int *s,
double *y)
{
int i;
if (n<=0||alf==0.0)
return;
if (!s) {
if (alf==1.0) {
for (i=0; i<n; i++)
y[i]+=x[i];
}
else if (alf==-1.0) {
for (i=0; i<n; i++)
y[i]-=x[i];
}
else {
for (i=0; i<n; i++)
y[i]+=alf*x[i];
}
}
else {
if (alf==1.0) {
for (i=0; i<n; i++)
y[s[i]]+=x[i];
}
else if (alf==-1.0) {
for (i=0; i<n; i++)
y[s[i]]-=x[i];
}
else {
for (i=0; i<n; i++)
y[s[i]]+=alf*x[i];
}
}
} /* addVect */
double svDot(array *x,
double *y)
{
int i;
double r=0.0;
for(i=0; i<x->nn0; ++i)
r+=x->an[i]*y[x->ja[i]];
return ( r );
} /* svDot */
void setArray(double alf,
array *x,
double *y)
{
int k;
if (x->nn0<=0||alf==0.0)
return;
if (alf==1.0) {
for (k=0; k<x->nn0; k++)
y[x->ja[k]]+=x->an[k];
}
else if (alf==-1.0) {
for (k=0; k<x->nn0; k++)
y[x->ja[k]]-=x->an[k];
}
else {
for (k=0; k<x->nn0; k++)
y[x->ja[k]]+=alf*x->an[k];
}
} /* setArray */
|
C
|
#include <stdio.h>
#include <stdlib.h>
void read(char *filename, FILE *rfp, FILE *wfp);
void write(char * filename, char c, FILE *wfp);
int main(void) {
char file[30];
printf("Enter the css file name you want to format with: (include the .css) ");
scanf("%s", file);
//char file[] = "app.min.css";
FILE *rfp;
FILE *wfp;
read(file, rfp, wfp);
return 0;
}
void read(char *filename, FILE* rfp, FILE *wfp) {
char c;
printf("Opening the file in read mode \n");
rfp = fopen(filename, "r");
wfp = fopen("formatted.css","w");
if (rfp == NULL) {
printf("Could not open file \n");
return;
}
printf("Reading the file \n");
while (1) {
c = fgetc(rfp);
if (c == EOF) {
break;
}
write("format.css", c, wfp);
//printf ( "%c", c ) ;
}
printf("Closing the file test.c \n") ;
fclose(rfp);
fclose(wfp);
}
void write(char *filename, char c, FILE *wfp) {
if (c == '{') {
fputc('\n', wfp);
fputc(c, wfp);
fputc('\n', wfp);
fputc('\t', wfp);
}
else if (c == '}') {
fputc('\n', wfp);
fputc(c, wfp);
fputc('\n', wfp);
}
else if (c == ';') {
fputc(c, wfp);
fputc('\n', wfp);
fputc('\t', wfp);
}
else {
fputc(c, wfp);
}
}
|
C
|
/**************************************************************************
* cryptofile.c *
* 4096/B7B720D6 "Kyle Isom <coder@kylesiom.net>" *
* 2011-01-08 *
* *
* cryptographic file functions *
**************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <gcrypt.h>
#include "config.h"
#include "crypto.h"
#include "cryptofile.h"
#include "debug.h"
crypto_key_return_t crypto_wipe_file(const char *filename, size_t passes) {
crypto_key_return_t result = KEY_FAILURE;
FILE *kf = NULL;
struct stat kf_stat;
unsigned char *rdata = NULL; /* random data buffer */
size_t file_size = 0;
size_t wipe_buf_size = 0; /* amount of random chars to gen each round */
size_t rounds = 1; /* needed to handle secure mem */
size_t i = 0, j = 0; /* loop counters */
/* use stat to get file size */
TRACEOUT_1("[+] stat'ing %s...\n", filename);
if (-1 == stat(filename, &kf_stat)) {
#ifdef DEBUG
perror("[!] stat");
#endif
return result;
}
LOG("[+] stat complete!\n");
/* compute number of rounds and the size of the random data buffer
* that will be written to the file */
file_size = (size_t) kf_stat.st_size;
#if SECURE_MEM != 0
rounds = (file_size / (SECURE_MEM / 5)) + 1;
wipe_buf_size = (SECURE_MEM / 5);
#else
wipe_buf_size = file_size;
#endif
/* for debugging purposes, print out some wipe data */
#ifdef DEBUG
printf("[+] wipe data:\n");
printf(" wipe size: %u\n passes: %u\n rounds: %u\n",
(unsigned int) wipe_buf_size, (unsigned int) passes,
(unsigned int) rounds);
#endif
/* top-level loop to write to the file passes number of times */
for (i = 0; i < passes; ++i) {
#ifdef DEBUG
printf("[+] wipe pass number %u\n", (unsigned int) i);
#endif
kf = fopen(filename, "w");
/* error checking */
if (NULL == kf) {
#ifdef DEBUG
fprintf(stderr, "[!] %s does not exist!\n", filename);
#endif
return result;
} else if (0 != ferror(kf)) {
#ifdef DEBUG
fprintf(stderr, "[!] encountered an error opening %s!\n",
filename);
perror("fopen");
#endif
return result;
}
/* inner loop to write the buffer to the file */
for (j = 0; j < rounds; ++j) {
size_t written = 0;
#ifdef DEBUG
printf("\twipe round %u\n", (unsigned int) j);
#endif
rdata = CRYPTO_MALLOC( wipe_buf_size, sizeof rdata );
gcry_create_nonce(rdata, wipe_buf_size);
/* write and check for errors */
written = fwrite(rdata, sizeof *rdata, wipe_buf_size, kf);
/* sanity check to make sure we wrote as many bytes as we
* wanted to */
if (written != wipe_buf_size) {
#ifdef DEBUG
fprintf(stderr, "[!] did not write expected number of ");
fprintf(stderr, "bytes (expected %u bytes, wrote %u bytes",
(unsigned int) wipe_buf_size, (unsigned int) written);
fprintf(stderr, "\nto file: %s\n", filename);
#endif
result = INCONSISTENT_STATE;
return result;
}
gcry_free(rdata);
} /* end of wiping round */
/* close and check for errors */
if (0 != fclose(kf)) {
#ifdef DEBUG
fprintf(stderr, "[!] error encountered closing %s!\n", filename);
perror("fclose");
#endif
return result;
}
} /* end of write pass */
/* finally remove the file from the file system */
if (0 != unlink(filename)) {
#ifdef DEBUG
fprintf(stderr, "error unlinking file!\n");
#endif
} else {
result = KEY_SUCCESS; /* making it this far means wiping
* was successful */
}
return result;
}
|
C
|
#include "holberton.h"
/**
* _puts - prints a string then a line feed
* @s: the string to print
*/
void _puts(char *s)
{
char *sub;
for (sub = s; *sub; sub++)
_putchar(*sub);
_putchar('\n');
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* find_alias.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: hhuhtane <hhuhtane@student.hive.fi> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/09/11 16:43:03 by hhuhtane #+# #+# */
/* Updated: 2021/09/11 16:43:33 by hhuhtane ### ########.fr */
/* */
/* ************************************************************************** */
#include "builtins.h"
/*
** FIND_ALIAS_NAMED_NAME function finds alias value for the alias NAME.
** if no alias NAME is found, it returns NULL. Return string is const so
** it shouldn't be freed. make a copy from the return value if needed.!
*/
t_alias *find_alias_with_name(const char *name, t_alias *alias)
{
int i;
i = 0;
while (i < ALIAS_SIZE && alias[i].name)
{
if (ft_strequ(alias[i].name, name))
return (&alias[i]);
i++;
}
return (NULL);
}
const char *find_alias_named_name(const char *name, t_alias *alias)
{
int i;
i = 0;
while (i < ALIAS_SIZE && alias[i].name)
{
if (ft_strequ(alias[i].name, name))
return (alias[i].value);
i++;
}
return (NULL);
}
|
C
|
#include "../include/shell.h"
// filedes[0] предназначен для чтения, а filedes[1] предназначен для записи.
static int check_redir(char **args, int f)
{
int i;
i = -1;
while (args[++i])
{
if (equals(args[i], ">") || equals(args[i], ">>"))
{
g_gl.flagf = 1;
return (0);
}
else if (equals(args[i], "<"))
{
if (f)
make_redirection(args);
return (0);
}
}
return (1);
}
static void check_redir_bred(t_shell *sh, int size)
{
char **res;
int i;
i = -1;
while (sh->args_of_shell[++i])
if (equals(sh->args_of_shell[i], "<")
|| equals(sh->args_of_shell[i], ">")
|| equals(sh->args_of_shell[i], ">>"))
size++;
res = malloc(sizeof(char *) * (arr_size(sh->args_of_shell) - size + 1));
i = -1;
size = 0;
while (sh->args_of_shell[++i])
{
if (!(equals(sh->args_of_shell[i], "<")
|| equals(sh->args_of_shell[i], ">")
|| equals(sh->args_of_shell[i], ">>")))
res[i - size] = ft_strdup(sh->args_of_shell[i]);
else
size++;
}
res[i - size] = NULL;
ft_split_free(sh->args_of_shell);
sh->args_of_shell = res;
}
void its_pipe_childe(t_shell *sh, int pid, int f)
{
if (!pid && !f)
{
close(g_gl.fdp[0]);
dup2(g_gl.fdp[1], 1);
if (check_redir(sh->args_of_shell, 1))
commands(sh->args_of_shell);
exit(0);
}
close(g_gl.fdp[0]);
dup2(g_gl.fdp[1], 1);
close(g_gl.fd_in);
dup2(g_gl.fd_out, 0);
check_redir_bred(sh, 0);
commands(sh->args_of_shell);
exit(0);
}
int its_pipe(t_shell *sh, int f)
{
pid_t pid;
pipe(g_gl.fdp);
pid = fork();
if (!pid)
its_pipe_childe(sh, pid, f);
close(g_gl.fdp[1]);
if (f || g_gl.flagf == 1)
close(g_gl.fd_out);
check_redir(sh->args_of_shell, 0);
t_global a = g_gl;
g_gl.fd_out = g_gl.fdp[0];
g_gl.fd_in = g_gl.fdp[1];
a = g_gl;
return (0);
}
int its_last_pipe(char **sh)
{
int a;
pid_t pid;
pid = fork();
if (!pid)
{
close(g_gl.fd_in);
dup2(g_gl.fd_out, 0);
if (!g_gl.flagf)
commands(sh);
else
{
pipe(g_gl.fdp);
write(g_gl.fdp[1], "", 1);
dup2(g_gl.fdp[0], 0);
close(g_gl.fdp[1]);
commands(sh);
}
exit(atoi(g_gl.error_code));
}
close(g_gl.fd_out);
close(g_gl.fdp[1]);
waitpid(pid, &a, 0);
arg_itoa(a);
g_gl.fd_out = 1;
g_gl.fd_in = 0;
return (0);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include "poly_mul.h"
extern void polymul_asm(uint16_t *r, const uint16_t *a, const uint16_t *b);
void pol_mul(uint16_t* a, uint16_t* b, uint16_t* res, uint16_t p, uint32_t n)
{
uint32_t i;
uint16_t c[2*n - 1];
polymul_asm(c, a, b);
for (i = n; i < 2*n-1; i++){
res[i - n] += (c[i - n] - c[i]);// & (p - 1);
}
res[n - 1] += c[n - 1];
}
void pol_mul_sch(uint16_t* a, uint8_t* b, uint16_t* res)
{
uint32_t i,n=256;
uint16_t c[2*n - 1],d[n];
for(i=0;i<(n/4);i++)
{
d[4*i] = ((b[i]& 0x03) ^ 0x2 ) - 0x2;
d[4*i+1] = (((b[i]>>2) & 0x03) ^ 0x2 ) - 0x2;
d[4*i+2] = (((b[i]>>4) & 0x03) ^ 0x2 ) - 0x2;
d[4*i+3] = (((b[i]>>6) & 0x03) ^ 0x2 ) - 0x2;
}
toom_cook_4way_mem_asm(c,a,d);
/*polymul_asm(c,a,d);
for (i = n; i < 2*n-1; i++){
res[i - n] += (c[i - n] - c[i]);// & (p - 1);
}
res[n - 1] += c[n - 1];
*/
}
|
C
|
//#include <stdio.h>
//
//int main()
//{
// int i1;
// printf("%lu\n", sizeof(i1));
// i1 = 2147483647;//2^31-1
// printf("%d\n", i1);
//
// short int i2;
// printf("%lu\n", sizeof(i2));
// i2 = 32767;//2^15-1
// printf("%hd\n", i2);
//
// long int i3;
// printf("%lu\n", sizeof(i3));
// i3 = 1234;
// printf("%ld\n", i3);
//
// long long int i4;
// printf("%lu\n", sizeof(i4));
// i4 = 1234;
// printf("%lld\n", i4);
//
// unsigned int i5;
// printf("%lu\n", sizeof(i5));
// i5 = 4294967295;
// printf("%u\n", i5);
//
// unsigned short int i6;
// printf("%lu\n", sizeof(i6));
// i6 = 65535;
// printf("%hu\n", i6);
//
// unsigned long int i7;
// printf("%lu\n", sizeof(i7));
// i7 = 1234;
// printf("%lu\n", i7);
//
// unsigned long long int i8;
// printf("%lu\n", sizeof(i8));
// i8 = 1234;
// printf("%llu\n", i8);
//
// return 0;
//}
|
C
|
#include <stdio.h>
void main()
{
int i,j,sayi;
printf("Sayi giriniz ");
scanf("%d",&sayi);
for(i=1;i<=sayi;i++)
{
printf("%d\t",i);
for(j=1;j<=i;j++)
{
printf("%d",i);
}
printf("\n");
}
getch();
}
|
C
|
#include "task_lib.h"
tcb_t tcb[MAX_TASKS];
/**
* @brief Scheduler update
* @param void
* @retval void
*/
void sch_update(void)
{
uint8_t index;
for (index = 0; index < MAX_TASKS; index++)
{
/* Check if there is a task at this location */
if (tcb[index].p_tack_cb)
{
if (tcb[index].delay == 0)
{
/* The task is duo to run */
if (tcb[index].co_op)
{
/* If it is a co-operative task, increment the RunMe flag */
tcb[index].run_me += 1;
}
else
{
/* If it is a pre-emptive task, run it IMMEDIATELY */
tcb[index].p_tack_cb();
if (tcb[index].period == 0)
{
tcb[index].p_tack_cb = 0;
}
}
if (tcb[index].period)
{
/* Schedule this periodic task to run again */
tcb[index].delay = tcb[index].period;
}
}
else
{
tcb[index].delay -= 1;
}
}
}
}
/**
* @brief Dispathch tasks
* @param void
* @retval void
*/
void dispathch_tasks(void)
{
uint8_t index;
/* Dispatches (runs) the next task (if one is ready) */
for (index = 0; index < MAX_TASKS; index++)
{
/* Only dispatching co_operative tasks */
if (tcb[index].co_op && tcb[index].run_me > 0)
{
tcb[index].p_tack_cb();
tcb[index].run_me -= 1;
/* Periodic tasks will automatically run again,if this is a one shot' task, remove it from the array*/
if (tcb[index].period == 0)
{
tcb[index].p_tack_cb = 0;
}
}
}
}
/**
* @brief Add task
* @param del : Delay time
* @param per : Period
* @param co_op : co_operative
* @retval -1 : failed index : success
*/
int8_t add_task(void (*p_func)(void),
uint16_t del,
uint16_t per,
uint8_t co_op)
{
uint8_t index = 0;
/* First find a gap in the array (if there is one) */
while ((tcb[index].p_tack_cb != 0) && (index < MAX_TASKS))
{
index++;
}
if (index == MAX_TASKS)
{
/* We reached the end of the list */
return -1;
}
tcb[index].p_tack_cb = p_func;
tcb[index].delay = del;
tcb[index].period = per;
tcb[index].co_op = co_op;
tcb[index].run_me = 0;
return index;
}
#if (EN_DELETE_TASK != 0)
/**
* @brief Delete task
* @param index : Task index
* @retval -1 : failed index : success
*/
int8_t delete_task(uint8_t index)
{
if (tcb[index].p_tack_cb == 0)
{
/* No task at this location... */
return -1;
}
/* Delete the success */
tcb[index].p_tack_cb = 0;
tcb[index].delay = 0;
tcb[index].period = 0;
tcb[index].run_me = 0;
return 0;
}
#endif
|
C
|
/* Casting data types */
#include <stdio.h>
#include <stdlib.h>
void main (void)
{
int a = 1;
/* one data type can be cast as another using (new type)variable */
printf("Print integer as float: %f\n", (float)a);
/*
Output:
=> Print integer as float: 1.000000
*/
exit(0);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int valorMaximo(int* arr){
int valorMax = 0;
int valorActual = *(arr);
if( *(arr) != 0){
valorMax = valorMaximo(arr+1);
if(valorMax == 0){
return valorActual;
}
if(valorActual > valorMax){
return valorActual;
}
else{
return valorMax;
}
}
else{
return 0;
}
}
int* dirMemoriaValorMaximo(int* arr){
int* dirMemMax = NULL;
int* dirMemActual = arr;
if (*(arr) != 0){
dirMemMax = dirMemoriaValorMaximo(arr+1);
if(dirMemMax == NULL){
return dirMemActual;
}
if(*(dirMemActual) > *(dirMemMax)){
return dirMemActual;
}
else{
return dirMemMax;
}
}
else{
return NULL;
}
}
int main(){
int arreglo[] = {1,5,6,-2,11,0};
printf("Valor maximo del arreglo es: %d\n",valorMaximo(arreglo));
printf("Y su direccion de memoria es: %p",dirMemoriaValorMaximo(arreglo));
return 0;
}
|
C
|
// ------------------------------------------------------------------------------------------------
// string.h
// ------------------------------------------------------------------------------------------------
#pragma once
#include "stdlib/types.h"
void *memset(void *s, int c, size_t n);
void *memcpy(void *dst, const void *src, size_t n);
void *memmove(void *dst, const void *src, size_t n);
void *memchr(const void *buf, int c, size_t n);
int memcmp(const void *s1, const void *s2, size_t n);
size_t strlen(const char *str);
char *strcpy(char *dst, const char *src);
char *strncpy(char *dst, const char *src, size_t n);
int strcmp(const char *s1, const char *s2);
char *strcpy_safe(char *dst, const char *src, size_t dstSize);
|
C
|
#include<stdio.h>
int main ()
{
int a[]={10,2,4,15,35,46,85};
int value,pos=-1,i;
printf("Enter the value:");
scanf("%d",&value);
for(i=0; i<7; i++)
{
if(value==a[i])
{
pos=i+1;
break;
}
}
if(pos==-1)
{
printf("Item is not found");
}
else
printf("The value is found %d position:",pos);
getch();
}
|
C
|
#include<stdio.h>
#include<math.h>
int main()
{
int start, first, second, end;
while (scanf("%d%d%d%d", &start, &first, &second, &end) != EOF){
int degree = 1080, scale = 9;
if (start == 0 && first == 0 && second == 0 && end == 0){
break;
}
else{
degree = degree + ((40 + (start - first)) % 40) * 9;
degree = degree + ((40 + (second - first)) % 40) * 9;
degree = degree + ((40 + (second - end)) % 40) * 9;
}
printf("%d\n", degree);
}
return 0;
}
|
C
|
// Author: Robert H. Lee
// Created: Fall 2015
// Here we use allgatherv to fill only part of the blocks corresponding to each
// process. This is useful when we want to overlap computation and
// communication. If computation is required to produce the block of data that
// needs to be allgathered, we can compute a small part of the block, then
// initiate allgatherv on the small part, then continue computation and
// allgathering successive chunks. The allgatherv and computation can be
// performed in parallel by the use of threads.
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <omp.h>
#include <mpi.h>
#include <sys/time.h>
int main(int argc, char** argv)
{
// Initialize MPI threads and check provided support levels.
int provided_support = -1;
MPI_Init_thread(&argc, &argv, MPI_THREAD_FUNNELED, &provided_support);
int processors = -1;
MPI_Comm_size(MPI_COMM_WORLD, &processors);
int rank = -1;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
if(rank == 0)
{
fprintf(stdout, "Total processors, rank: %d, %d\n", processors, rank);
fprintf(stdout, "Support levels: %d, %d, %d, %d\n", MPI_THREAD_SINGLE,
MPI_THREAD_FUNNELED, MPI_THREAD_SERIALIZED, MPI_THREAD_MULTIPLE);
fprintf(stdout, "Requested, provided support: %d, %d\n",
MPI_THREAD_FUNNELED, provided_support);
}
// Setup allgather environment.
int steps = 3;
int size_per_step = 5;
int size_per_processor = size_per_step * steps;
int total_size = processors*size_per_processor;
int *global_data = (int*) malloc(total_size*sizeof(int));
int i = 0;
for(i = 0; i < total_size; ++i) global_data[i] = -1;
int offset = size_per_processor*rank;
int *local_data = global_data + offset;
for(i = 0; i < size_per_processor; ++i) local_data[i] = i+offset;
// Compute displs and recvcounts.
int* displs = (int*) malloc(processors*sizeof(int));
int* recvcounts = (int*) malloc(processors*sizeof(int));
for(i = 0; i < processors; ++i)
{
displs[i] = i * size_per_processor;
recvcounts[i] = size_per_step;
}
// If the send size differs, allgather hangs.
for(i = 0; i < steps; ++i)
{
int block = size_per_step;//(rank & 1) ? 0: size_per_step;
fprintf(stdout, "Rank: %d, send count: %d\n", rank, block);
MPI_Allgatherv(
local_data,
block,
MPI_INT,
global_data,
recvcounts, // replaces recvcount
displs, // addition for allgatherv
MPI_INT,
MPI_COMM_WORLD
);
// update locations
local_data += size_per_step;
int j;
for(j = 0; j < processors; ++j) displs[j] += size_per_step;
}
// Print list.
fprintf(stdout, "Rank %d:\n", rank);
for(i = 0; i < total_size; ++i)
{
fprintf(stdout, "%d ", global_data[i]);
}
fprintf(stdout, "\n");
// Clean up.
free(global_data);
free(displs);
free(recvcounts);
MPI_Finalize();
return EXIT_SUCCESS;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.