language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C
|
#include <stdio.h>
#include <string.h>
void showprompt(void); /*prototype*/
int main()
{
char input [64];
do
{
showprompt(); /*call the function*/
gets(input);
puts("Someday I must implement that function..");
}
while((strcasecmp)("quit" , input));
/* while 1
`strcasecmp returneaza 0 atunci cand elementele sunt identice
(fara a tine cont de majuscule)
*/
puts("Oh! Apparently I did!");
return 0;
}
void showprompt(void)
{
printf("What is thy bidding?");
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
void MatrixSearch(double **a, double*pMax, double*pMin,int n)
{
int i,j;
*pMax=*pMin=*(*(a+0)+0);
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(*(*(a+i)+j)>*pMax)
*pMax=*(*(a+i)+j);
if(*(*(a+i)+j)<*pMin)
*pMin=*(*(a+i)+j);
}
}
}
int main()
{
int i,j;
double max,min;
int n;
double **a=(double**)malloc(100*sizeof(double*));
scanf("%d",&n);
for(i=0;i<n;i++)
{
*(a+i)=malloc(100*sizeof(double));
for(j=0;j<n;j++)
{
scanf("%lf",*(a+i)+j);
}
}
MatrixSearch(a,&max,&min,n);
printf("max=%.2lf,min=%.2lf \n",max,min);
for(i=0;i<n;i++)
{
free(*(a+i));
}
free(a);
return 0;
}
|
C
|
/*
Exercise 1-20. Write a program detab that replaces tabs in the input with the proper number of blanks to space to
the next tab stop. Assume a fixed set of tab stops, say every n columns. Should n be a variable or a symbolic
parameter?
*/
#include <stdio.h>
#define MAX_LINE_LEN 1025
#define TAB_SIZE 8
int Getline(char line[], int max);
void detab(char line[],int len);
int main(void)
{
int lineLen=0;
char lineArray[MAX_LINE_LEN];
while ((lineLen=Getline(lineArray,MAX_LINE_LEN))!=0)
{
//length= lenLen-1 to ignore the '\n' char
detab(lineArray, lineLen);
//printf("Reversed===>> %s",lineArray);
}
return 0;
}
void detab(char line[],int len)
{
int curPos = 0;
for (int i =0; i<len;i++)
{
int sCount;
switch (line[i])
{
case '\t':
sCount = TAB_SIZE - (curPos % TAB_SIZE);
for (int j=0;j<sCount;j++)
{
putchar(' ');
curPos++;
}
break;
default:
putchar(line[i]);
curPos++;
break;
}
}
}
int Getline(char line[], int max)
{
int i = 0;
int c = 0;
for (i = 0; ((c = getchar()) != EOF) && c != '\n' && i < max - 1; ++i)
line[i] = c;
if (c == '\n')
line[i++] = c;
line[i] = '\0';
return i;
}
|
C
|
//
// filterWords.c
// Lab1
//
// Created by Amanda Rosén on 2014-12-26.
// Copyright (c) 2014 Amanda Rosén. All rights reserved.
//
#include "filterWords.h"
int filterWords(char (*array_importantwords)[60],StackAddress strStack,int array_length) {
int i;
for (i=0; i<=array_length; i++) {
if (existsStrStack(strStack,array_importantwords[i])!=0) {
removeFromArray(array_importantwords,array_length,i);
array_length--;
}
}
return array_length;
}
|
C
|
inherit ROOM;
#include <dirs.h>
#include <std.h>
#include "/wizards/shanus/defs/tara.h"
void init() {
::init();
add_action("read", "read");
}
void create() {
::create();
set_property("light",2);
set_property("night light",2);
set_property("indoors", 1);
set_short("Tara's Tavern");
set("day long", @DAY
The building looks bigger from the outside. It if packed full
of sweaty drunk halfling bodies, everyone crowded as close to the bar
as they can get. Although it is crowed, the people seem to be
having a good time, eating, drinking, singing, and just relaxing
while they are not out working. Bergin keeps his place clean,
the bar is spotless, and the tables close to it. Pretty halfling
serving wenches bring food and drink to those waiting.
DAY
);
set("night long", @NIGHT
The tavern is well lit with torches, Bergin making sure not
to scare off his late customers with darkness. The tavern
is not as crowded as it is during the day, but there are enough customers
to make it worth while to Bergin to keep it open at night. Some
of the hard core alcoholics lie slumped down against the bar,
prefering to pass out here then their own homes. Most of the
wenches have gone to bed, leaving Bergin to tend the bar alone.
NIGHT
);
add_item("menu","Try reading it.");
add_item("halflings","They sit here drinking and eating.");
add_item("bar","The bar is clean and shiny, many halflings sit "+
"next to it.");
add_item("building","One of the few buildings not built into the "+
"hillside, it looks much bigger from the outside.");
add_item("wenches","Pretty well filled out halfling wenches, "+
"who's job is not only to serve food, but attract customers.");
add_item("tables","Many tables for halflings to enjoy there "+
"food and drink.");
add_item("torches","Bergin pays for torches to keep the inside "+
"and outside of the tavern well lit all night.");
add_item("alcoholics","People who enjoy life more then you.");
set_smell("default","The air smells of ale and stew.");
set_listen("default","The sound of a bustline Tavern fills the air.");
add_exit(TARAROOMS+"rm5", "west");
}
void reset() {
::reset();
if(!present("bergin"))
new(TARAMON+"bergin")->move(this_object());
}
int read(string str) {
object ob;
int i;
if(!str) return 0;
if(lower_case(str) != "menu") return notify_fail("There is no '"+str+"' here.\n");
ob = present("bergin");
if(!ob) {
write("That's not a menu. That's Bergin's will!");
return 1;
}
write("Bergin serves the following beverages and foods.");
write("-----------------------------------------------------------");
write(sprintf("%30s %d silver", "A bowl of stew",
(int)ob->get_price("stew")));
write(sprintf("%30s %d silver", "A mug of ale",
(int)ob->get_price("ale")));
write(sprintf("%30s %d silver", "A glass of wine",
(int)ob->get_price("wine")));
write(sprintf("%30s %d silver", "A large portion of beef",
(int)ob->get_price("beef")));
write(sprintf("%30s %d silver", "A shot of tequila",
(int)ob->get_price("tequila")));
write(sprintf("%30s %d silver", "A chunk of cheese",
(int)ob->get_price("cheese")));
write("-----------------------------------------------------------");
write("<buy item> gets you the food or drink.");
return 1;
}
|
C
|
/* A LAN Risk Server
* -----------------
* Usage ./server PORT_NUMBER
*
* If no port number given, uses DEFAULT PORT
*
* Author: Ewan McCartney
*/
#include "Server.h"
/* Small function to print out errors over stderr.
* Program terminates once message printed */
void error(const char *msg)
{
perror(msg);
exit(1);
}
/* Globals */
int Serverfd = 0; //Server File Descriptor
int PortNo = DEFAULT_PORT; //Port Number of Server
int main(int argc, char *argv[])
{
//File Descriptors for the server socket and client socket, allowing use of read() and write()
int newsockfd;
char buffer[256]; //Buffer for storing output messages
int n; //Return codes for socket functions
printf("> Starting up...\nMSG> Version: %s\n", VERSION);
//Checking to see if we have a port number given as CLI args
if (argc == 2) { PortNo = atoi(argv[1]); }
else { printf("> No port given. Using default: %d\n",DEFAULT_PORT); }
//Run Setup of server. Incase of error, we exit
if (Serv_Setup() <0) { printf("NOTICE> Exiting...\n"); exit(1); }
//Once setup has been run, enter client connection stage.
//EDIT: Perhaps put this in a loop?
AcceptClients(Serverfd);
//Once we're done, tell user we're exiting, cause this is only debug!
printf("NOTICE> Shutting down...\n");
CloseAllClients();
close(Serverfd);
exit(0);
//UNREACHABLE CURRENTLY
//Reads in data from the client that's connected
bzero(buffer,256);
n = read(newsockfd,buffer,255);
if (n < 0)
{
error("ERROR reading from socket");
}
//Prints out what it got, and sends a confirmation to the client.
printf("Here is the message: %s\n",buffer);
n = write(newsockfd,"I got your message",18);
if (n < 0)
{
error("ERROR writing to socket");
}
//Closes both server and client sockets, IN CORRECT ORDER
close(newsockfd);
close(Serverfd);
return 0;
}
/* Setup
* Creates Server socket and performs bind() and listen()
* Allows server to startup
*
* Returns -1 if fails
*/
int Serv_Setup()
{
struct sockaddr_in serv_addr;
Serverfd = socket(AF_INET, SOCK_STREAM, 0);
if (Serverfd < 0)
{
printf("ERROR> Couldn't start network coms.\n");
return -1;
}
//Sets everything in the serv_addrs to 0
bzero((char *) &serv_addr, sizeof(serv_addr));
//Setup serv_addr struct with right values
serv_addr.sin_family = AF_INET; //Should always be AF_INET (I assume AF_UNIX for pipe)
serv_addr.sin_addr.s_addr = INADDR_ANY; //Sets the address of the Server. Should always be the IP of machine INADDR_ANY = IP of machine
serv_addr.sin_port = htons(PortNo); //Sets port of server. Requires to ne in Network byte order, so use Htons
/* Binds the Socket to the address.
* Bind(FILE DES, ADDRESS, SIZE)
* FILE DES is the value returned from socket()
* ADDRESS is our addr struct, but requires to be cast to sockaddr for function
* SIZE of the address of socket
*
* Returns -1 if failed. Perhaps the socket is already in use.
*/
if (bind(Serverfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
{
printf("ERROR> Unable to associate server with network socket.\n");
return -1;
}
//Listens for connections. accept maximum of 5 connections in queue while processing responce. Standard size for systems
listen(Serverfd,5);
printf("MSG> I'm broadcasting on: 127.0.0.1 and your computer's IP address.\n");
return 0;
}
|
C
|
/*
** EPITECH PROJECT, 2017
** my_fill_str
** File description:
** fill a str with '\0s'
*/
char *my_fill_str(char *to_fill, int len)
{
int index = 0;
while (index < len)
{
to_fill[index] = '\0';
index++;
}
return (to_fill);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int BinaryConversion (int User_Input)
{
int Original = User_Input, Remainder, arr[10], count =0, i;
while(User_Input>0){
Remainder = User_Input%2;
User_Input = User_Input/2;
arr[count++] = Remainder;
}
printf("\n Binary of number %d is : ",Original);
for (i=count-1; i>=0; i--)
{
printf("%d",arr[i]);
}
return 0;
}
int main()
{
printf("*********** Decimal To Binary Conversion ******************* \n")
int User_Input=0 ;
printf("Please enter the number to convert into Binary : ");
scanf("%d",&User_Input);
BinaryConversion(User_Input);
printf("\n *********** End of program ******************* \n")
}
|
C
|
/*Faa um programa em C que leia um vetor contendo n valores no intervalo [0,9], sendo n fornecido pelo usurio. Aps obter o vetor, faa com que o seu vetor apresente a sada conforme abaixo:
vetor de entrada: [9,2,3,4,5]
sada esperada:
81, 18, 27, 36, 45,
18, 4, 6, 8, 10,
27, 6, 9, 12, 15,
36, 8, 12, 16, 20,
45, 10, 15, 20, 25,
Para que a avaliao automatizada funcione, siga as instrues abaixo:
para ler o tamanho do vetor apresente a mensagem abaixo e na sequencia leia o valor usando scanf
printf("Informe o tamanho do vetor:\n");
para ler os valores para o vetor, apresente a mensagem abaixo e na sequencia leia os valores usando scanf
printf("Informe os valores para o vetor (1 em cada linha):\n");
a sada deve ter o formato apresentado acima
## inicio sada (exemplo para o vetor do enunciado) - ignore esta linha
81, 18, 27, 36, 45,
18, 4, 6, 8, 10,
27, 6, 9, 12, 15,
36, 8, 12, 16, 20,
45, 10, 15, 20, 25,
## fim sada - ignore esta linha*/
#include<stdio.h>
int main(){
int n, i, j;
printf("Informe o tamanho do vetor:\n");
scanf("%d", &n);
int v[n];
printf("Informe os valores para o vetor (1 em cada linha):\n");
for(i=0; i<n; i++){
scanf("%d", &v[i]);
}
for(i=0; i<n; i++){
for(j=0; j<n; j++){
printf("%d, ", v[i]*v[j]);
}
printf("\n");
}
}
|
C
|
#include "dependency_analysis.h"
#include "inst_list.h"
#include "graph.h"
reg_map_t *compute_dependencies(single_list_t *list) {
reg_map_t *map = newMap(xed_reg_enum_t_last());
xed_decoded_inst_t *instructions = list->array;
xed_decoded_inst_t xedd;
for (size_t i = 0; i < list->size; i++) {
xedd = instructions[i];
const xed_inst_t *xi = xed_decoded_inst_inst(&xedd);
if (xed_inst_noperands(xi) > 0)
compute_instruction(map, &xedd, xi, i);
}
order_map(map);
return map;
}
void compute_instruction(reg_map_t *map, xed_decoded_inst_t *xedd,
const xed_inst_t *xi, int line) {
for (size_t i = 0; i < xed_inst_noperands(xi); i++) {
const xed_operand_t *op = xed_inst_operand(xi, i);
put_operand_in_map(op, xedd, map, line);
}
}
void put_operand_in_map(const xed_operand_t *op, xed_decoded_inst_t *xedd,
reg_map_t *map, int line) {
xed_operand_enum_t op_name = xed_operand_name(op);
switch (op_name) {
case XED_OPERAND_AGEN:
case XED_OPERAND_MEM0: {
if (xed3_operand_get_base0(xedd) != XED_REG_INVALID)
add_to_map(map, xed3_operand_get_base0(xedd), line, READ);
if (xed3_operand_get_seg0(xedd) != XED_REG_INVALID)
add_to_map(map, xed3_operand_get_seg0(xedd), line, READ);
if (xed3_operand_get_index(xedd) != XED_REG_INVALID)
add_to_map(map, xed3_operand_get_index(xedd), line, READ);
break;
}
case XED_OPERAND_MEM1: {
if (xed3_operand_get_base0(xedd) != XED_REG_INVALID)
add_to_map(map, xed3_operand_get_base0(xedd), line, READ);
if (xed3_operand_get_seg0(xedd) != XED_REG_INVALID)
add_to_map(map, xed3_operand_get_seg0(xedd), line, READ);
break;
}
default: {
xed_reg_enum_t reg;
if (!xed_operand_is_register(op_name)) break;
xed3_get_generic_operand(xedd, op_name, ®);
if (xed_operand_read(op))
add_to_map(map, reg, line, READ);
if (xed_operand_written(op))
add_to_map(map, reg, line, WRITE);
}
}
}
graph_t *build_controlflowgraph(single_list_t *instructions) {
graph_t *graph = newGraph(instructions->size);
for (size_t i = 0; i < instructions->size; i++) {
if (is_branch_instruction(&instructions->array[i]))
compute_branch_flow(instructions, graph, i);
else
add_graph_dependency(i, i + 1, graph, XED_REG_INVALID);
}
return graph;
}
void compute_branch_flow(single_list_t *instructions, graph_t *graph, int line) {
xed_decoded_inst_t *xedd = &instructions->array[line];
xed_iform_enum_t iform = xed_decoded_inst_get_iform_enum(xedd);
if (!branch_is_unconditional(iform))
add_graph_dependency(line, line + 1, graph, XED_REG_INVALID);
int displacement = xed_decoded_inst_get_branch_displacement(xedd);
//for backbranches
int toLine = displacement > 0 ? line + 1 : line;
if (displacement < 0) {
while (displacement < 0 && toLine >= 0) {
displacement += xed_decoded_inst_get_length(&instructions->array[toLine--]);
}
displacement == 0 ? toLine++ : 0;
}
//normal branches
else {
while (displacement > 0 && toLine < graph->size) {
displacement -= xed_decoded_inst_get_length(&instructions->array[toLine++]);
}
}
add_graph_dependency(line, toLine, graph, XED_REG_INVALID);
}
int branch_is_unconditional(xed_iform_enum_t iform) {
return iform >= 636 && iform <= 638 || iform >= 656 && iform <= 658;
}
graph_t *build_dependencygraph(reg_map_t *map, graph_t *flowgraph) {
graph_t *dep_graph = newGraph(flowgraph->size);
access_t *cur;
for (size_t i = 0; i < map->size; i++) {
cur = map->map[i];
if (cur != NULL && i != XED_REG_RIP)
build_single_depency(cur, flowgraph, dep_graph);
}
return dep_graph;
}
void build_single_depency(access_t *first, graph_t *flowgraph, graph_t *dep_graph) {
int fromLine;
access_t *back = NULL;
while (first != NULL) {
if (first->read_write == WRITE) {
fromLine = first->line;
first = first->next;
while (1) {
if (first == NULL) break;
if (first->read_write == WRITE) {
if (is_successor(fromLine, first->line, flowgraph)) break;
if (back == NULL) back = first;
}
if (is_successor(fromLine, first->line, flowgraph))
add_graph_dependency(fromLine, first->line, dep_graph, first->used_reg);
first = first->next;
}
if (back != NULL) {
first = back;
back = NULL;
}
} else
first = first->next;
}
}
graph_t *build_dependencygraph_cfg(single_list_t *instructions, graph_t *cfg) {
graph_t *dg = newGraph(instructions->size);
int write_ops[xed_reg_enum_t_last()];
int write_flags[xed_flag_enum_t_last()];
for (int i = 0; i < xed_reg_enum_t_last(); ++i) {
write_ops[i] = -1;
}
for (int i = 0; i < xed_flag_enum_t_last(); ++i) {
write_flags[i] = -1;
}
branch_analysis_root(dg, instructions, cfg, write_ops, write_flags, 0);
return dg;
}
void branch_analysis_root(graph_t *dg, single_list_t *instructions, graph_t *cfg, int *write_ops, int *write_flags, int start) {
node_t *cur_node = cfg->nodes[start];
int cur_line = start;
while (true) {
add_all_dependencies(dg, cur_line, write_ops, write_flags, &instructions->array[cur_line]);
if (cur_node->num_successors > 1) {
int write_ops_single[xed_reg_enum_t_last()];
int write_flags_single[xed_flag_enum_t_last()];
for (int i = 0; i < cur_node->num_successors; ++i) {
if (cur_line >= cur_node->successors[i].line) {
continue;
}
for (int j = 0; j < xed_reg_enum_t_last(); ++j) {
write_ops_single[j] = write_ops[j];
}
for (int j = 0; j < xed_flag_enum_t_last(); ++j) {
write_flags_single[j] = write_flags[j];
}
branch_analysis_root(dg, instructions, cfg, write_ops_single, write_flags_single, cur_node->successors[i].line);
}
return;
} else if (cur_node->num_successors == 0) {
return;
} else {
int child_line = cur_node->successors[0].line;
if (cur_line >= child_line) {
return;
}
cur_node = cfg->nodes[child_line];
cur_line = child_line;
}
}
}
void add_all_dependencies(graph_t *dg, int toline, int *write_ops, int *write_flags, xed_decoded_inst_t *xedd) {
// flags
if (xed_decoded_inst_uses_rflags(xedd)) {
const xed_simple_flag_t *simple_flag = xed_decoded_inst_get_rflags_info(xedd);
const xed_flag_action_t *flag_action;
xed_flag_enum_t name;
for (unsigned int i = 0; i < xed_simple_flag_get_nflags(simple_flag); ++i) {
flag_action = xed_simple_flag_get_flag_action(simple_flag, i);
name = xed_flag_action_get_flag_name(flag_action);
if (write_flags[name] != -1 && xed_flag_action_read_flag(flag_action)) {
bool exists = false;
for (int j = 0; j < dg->nodes[toline]->num_fathers; ++j) {
// check if the same dependence from the same father already exists
if (dg->nodes[toline]->fathers[j].line == write_flags[name] && dg->nodes[toline]->fathers[j].flag == name) {
exists = true;
break;
}
}
if (!exists)
add_graph_dependency_flag(write_flags[name], toline, dg, name);
} else if (xed_flag_action_writes_flag(flag_action)) {
write_flags[name] = toline;
}
}
}
// registers
const xed_inst_t *xi = xed_decoded_inst_inst(xedd);
int num_writen = 0;
int num_read = 0;
xed_reg_enum_t writen[xed_inst_noperands(xi)];
xed_reg_enum_t read[xed_inst_noperands(xi)];
for (size_t i = 0; i < xed_inst_noperands(xi); i++) {
const xed_operand_t *op = xed_inst_operand(xi, i);
xed_operand_enum_t op_name = xed_operand_name(op);
switch (op_name) {
case XED_OPERAND_AGEN:
case XED_OPERAND_MEM0: {
if (xed3_operand_get_base0(xedd) != XED_REG_INVALID)
read[num_read++] = xed3_operand_get_base0(xedd);
if (xed3_operand_get_seg0(xedd) != XED_REG_INVALID)
read[num_read++] = xed3_operand_get_seg0(xedd);
if (xed3_operand_get_index(xedd) != XED_REG_INVALID)
read[num_read++] = xed3_operand_get_index(xedd);
break;
}
case XED_OPERAND_MEM1: {
if (xed3_operand_get_base0(xedd) != XED_REG_INVALID)
read[num_read++] = xed3_operand_get_base0(xedd);
if (xed3_operand_get_seg0(xedd) != XED_REG_INVALID)
read[num_read++] = xed3_operand_get_seg0(xedd);
break;
}
default: {
xed_reg_enum_t reg;
if (!xed_operand_is_register(op_name)) break;
xed3_get_generic_operand(xedd, op_name, ®);
if (reg == XED_REG_RFLAGS) break;
if (xed_operand_read(op))
read[num_read++] = reg;
if (xed_operand_written(op) && reg != XED_REG_RIP)
writen[num_writen++] = compute_register(reg);
}
}
}
int fromLine;
for (int i = 0; i < num_read; ++i) {
fromLine = write_ops[compute_register(read[i])];
if (fromLine != -1) {
// check if edge already exists, we only want it once
bool exists = false;
for (int j = 0; j < dg->nodes[toline]->num_fathers; ++j) {
// check if the same dependence from the same father already exists
if (dg->nodes[toline]->fathers[j].line == fromLine && dg->nodes[toline]->fathers[j].reg == read[i]) {
exists = true;
break;
}
}
if (!exists)
add_graph_dependency(fromLine, toline, dg, read[i]);
}
}
for (int i = 0; i < num_writen; ++i) {
write_ops[writen[i]] = toline;
}
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<time.h>
#include<sys/ipc.h>
#include<sys/msg.h>
#include<sys/wait.h>
#include<sys/errno.h>
extern int errno; // error NO.
#define PIDFILE "/var/run/smsd.pid" // PID file
#define MSGPERM 0600 // msg queue permission
#define MSGTXTLEN 1024 // msg text length
#define MSGPHONELEN 15 // msg phone length
int msgqid, rc;
int done;
struct msg_buf{
long mtype;
char mphone[MSGPHONELEN];
char mtext[MSGTXTLEN];
} msg;
int main(int argc,char **argv){
// create a message queue. If here you get a invalid msgid and use it in msgsnd() or msgrcg(), an Invalid Argument error will be returned.
if(geteuid() != 0){
printf("run program as root\n");
exit(1);
}
if(argc<3){
printf("USAGE: msg_send NUMBER MESSAGE");
return 1;
}else{
// message to send
msg.mtype = 1; // set the type of message
sprintf (msg.mphone, "%s", argv[1]); // set the phone of sms
sprintf (msg.mtext, "%s", argv[2]); /* setting the right time format by means of ctime() */
}
if( access( PIDFILE, F_OK ) == -1 ){
printf("smsd daemon isn't running\n");
system("./smsd");
printf("trying to start daemon\n");
sleep(1);
if( access( PIDFILE, F_OK ) == -1 ){
printf("no, it doesn't want. sry :(\n");
exit(1);
}
}
key_t key = ftok("/var/run/smsd.pid",1);
if(key<0){
perror(strerror(errno));
printf("failed to create a key\n");
return 1;
}
msgqid = msgget(key, MSGPERM);
if(msgqid==ENOENT){
perror(strerror(errno));
printf("message queue doesn't exist\nis the daemon running?\n");
return 1;
}else if(msgqid < 0){
perror(strerror(errno));
printf("failed to connect to message queue with msgqid = %d\n", msgqid);
return 1;
}
// send the message to queue
rc = msgsnd(msgqid, &msg, sizeof(msg)-sizeof(long), 0); // the last param can be: 0, IPC_NOWAIT, MSG_NOERROR, or IPC_NOWAIT|MSG_NOERROR.
if (rc < 0) {
perror( strerror(errno) );
printf("msgsnd failed, rc = %d\n", rc);
return 1;
}
printf("msg sent to daemon\n");
return 0;
}
|
C
|
#include<stdio.h>
int arr[10]={9,8,0,1,7,5,2,3,6};
int size=10;
int print(){
int i=0;
for(i=0;i<size;i++){
printf("%d | %d \n",i,arr[i]);
}
}
int liner(int val){
int i=0;
printf("%d is the value of index is:",i);
for(i=0;i<size;i++){
if(arr[i]==val){
printf("%d",val);
}
}
return -1;
}
int main(){
print();
int val=3;
liner(5);
}
|
C
|
/*
*LED blink using PIN 13 (connect positive side of led), 220 ohm resistor (stops led from overloading and burning out!!!), GND.
*/
//Set up function of LED pin 13.
//int: Integers are whole numbers in the C language.
int led = 13;
void setup() {
pinMode(13, OUTPUT);
}
//Set up LED on pin 13, with loop and delay.
//HIGH pulls the volatage high and LOW drops/zeros out the voltage. 1000ms equals to 1 second.
// C language write to the hardware.
void loop() {
digitalWrite(13, HIGH);
dealy(1000);
digitalWrite(13, LOW);
delay(1000);
}
|
C
|
/*
Database "epinions_1" contains tables:
item
review
trust
useracct
*/
#ifndef EPINIONS_1
#define EPINIONS_1
struct T_item {
double item_id;
char title[12];
};
struct T_review {
double a_id;
double user_id; // --> useracct.user_id
double item_id; // --> item.item_id
double rating;
double rank;
};
struct T_trust {
double source_user_id; // --> useracct.user_id
double target_user_id; // --> useracct.user_id
double trust;
};
struct T_useracct {
double user_id;
char name[6];
};
struct T_item
item[] = {
{ 0, "pear" },
{ 1, "orange" },
{ 2, "apple" },
{ 3, "shampoo" },
{ 4, "avocado" },
{ 5, "comb" },
{ 6, "blue hoodie" },
{ 7, "cup" }
};
struct T_review
review[] = {
{ 1, 1, 1, 10, 1 },
{ 2, 2, 1, 5, 2 },
{ 3, 1, 4, 7, 3 },
{ 4, 2, 7, 10, 7 },
{ 5, 2, 5, 7, 4 },
{ 6, 1, 3, 5, 5 },
{ 7, 2, 7, 6, 6 }
};
struct T_trust
trust[] = {
{ 1, 2, 10 },
{ 1, 3, 6 },
{ 2, 4, 8 },
{ 3, 6, 10 },
{ 7, 2, 3 },
{ 7, 5, 2 },
{ 7, 3, 4 },
{ 6, 2, 1 },
{ 1, 5, 7 }
};
struct T_useracct
useracct[] = {
{ 1, "Helen" },
{ 2, "Mark" },
{ 3, "Terry" },
{ 4, "Nancy" },
{ 5, "Rosie" },
{ 6, "Roxi" },
{ 7, "Emily" }
};
#endif
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* check_map.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: dheredat <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/12/23 15:36:13 by dheredat #+# #+# */
/* Updated: 2019/12/23 16:57:19 by dheredat ### ########.fr */
/* */
/* ************************************************************************** */
#include "../inc/fdf.h"
void free_strsplit(char ***str)
{
int i;
i = 0;
while ((*str)[i])
{
free((*str)[i]);
(*str)[i] = NULL;
i++;
}
free(*str);
*str = NULL;
}
void check_hex(char *str)
{
int i;
i = 1;
if (str[0] != '0' || str[1] != 'x')
error_display("Bad colour");
while (str[++i])
if (!((str[i] >= 48 && str[i] <= 57)
|| (str[i] >= 65 && str[i] <= 70)
|| (str[i] >= 97 && str[i] <= 102)))
error_display("Bad colour");
}
void word_check(char *str)
{
char **point;
int i;
if (!(point = ft_strsplit(str, ',')))
error_display("Split malloc error");
i = -1;
while (point[0][++i])
if (!(ft_isdigit(point[0][i])))
error_display("Bad map content error");
if (point[1] == NULL)
{
free_strsplit(&point);
return ;
}
else
check_hex(point[1]);
if (point[2] != NULL)
{
free_strsplit(&point);
error_display("Bad map content error");
}
free_strsplit(&point);
}
void check_line(char *line)
{
int i;
char **words;
if (!(words = ft_strsplit(line, ' ')))
error_display("Split malloc error");
i = 0;
while (words[i])
{
word_check(words[i]);
i++;
}
if (t_map.max_x == 0)
t_map.max_x = i;
else if (t_map.max_x != i)
error_display("Wrong map size");
free_strsplit(&words);
}
void check_map(char *buff)
{
char **lines;
int i;
if (!(lines = ft_strsplit(buff, '\n')))
error_display("Split malloc error");
i = 0;
while (lines[i])
{
check_line(lines[i]);
i++;
}
t_map.max_y = i;
free_strsplit(&lines);
}
|
C
|
/* REFERENCE: http://preshing.com/20120305/implementing-a-recursive-mutex/ */
#if defined(ZEROMTX) && !defined(PTHREAD)
#include <stdlib.h>
#include <zero/asm.h>
#include <zero/thr.h>
#include <zero/mtx.h>
zeromtxatr *
zeroallocmtxatr(void)
{
zeromtxatr *atr = malloc(sizeof(zeromtxatr));
if (atr) {
atr->flg = __ZEROMTXATR_DYNAMIC;
}
return atr;
}
int
zerofreemtxatr(zeromtxatr *atr)
{
int ret = 0;
if (atr->flg & __ZEROMTXATR_DYNAMIC) {
free(atr);
} else {
ret = ZEROMTXATR_NOTDYNAMIC;
}
return ret;
}
int
zeroinitmtxatr(zeromtxatr *atr)
{
long dynflg = atr->flg & __ZEROMTXATR_DYNAMIC;
if (!atr) {
return -1;
}
atr->flg |= __ZEROMTXATR_INIT | dynflg;
return 0;
}
long
zerotrylkmtx(zeromtx *mtx)
{
volatile long res = 0;
long thr;
if (!(mtx->atr.flg & ZEROMTX_RECURSIVE)) {
/* non-recursive mutex */
res = mtxtrylk(&mtx->val);
} else {
/* recursive mutex */
thr = thrid();
if (mtx->val == thr) {
m_atominc(&mtx->cnt);
} else if (!m_cmpswap(&mtx->cnt, 0, 1)) {
mtx->val = thr;
} else {
return 0;
}
res = thr;
mtx->rec++;
}
return res;
}
void
zerolkmtx(zeromtx *mtx)
{
volatile long res = -1;
long thr;
if (!(mtx->atr.flg & ZEROMTX_RECURSIVE)) {
/* non-recursive mutex */
mtxlk(&mtx->val);
} else {
/* recursive mutex */
thr = thrid();
res = m_fetchadd(&mtx->cnt, 1);
if (res) {
if (mtx->val != thr) {
do {
res = mtxtrylk(&mtx->lk);
if (!res) {
thryield();
}
} while (!res);
}
}
mtx->val = thr;
mtx->rec++;
}
return;
}
void
zerounlkmtx(zeromtx *mtx)
{
volatile long res;
long thr;
if (!(mtx->atr.flg & ZEROMTX_RECURSIVE)) {
/* non-recursive mutex */
mtxunlk(&mtx->val);
} else {
/* recursive mutex */
thr = thrid();
if (mtx->val == thr) {
mtx->rec--;
if (!mtx->rec) {
mtx->val = ZEROMTX_FREE;
}
res = m_fetchadd(&mtx->cnt, -1);
if (res > 1) {
if (!mtx->rec) {
mtxunlk(&mtx->lk);
}
}
}
}
return;
}
#endif /* defined(ZEROMTX) && !defined(PTHREAD) */
|
C
|
printf("\nEnter the direct path distance between node %d and %d: ", i, j);
|
C
|
/*--------------------------------------------------------++
|| Operate Left Port ||
++--------------------------------------------------------*/
// HAVE TO KEEP COMPONENTS RUNNING INDEPENDENTLY (ON / OFF)
// ORDER OF THIS MATTERS!! IF NOT IN THE FOLLOWING ORDER, nosepoke will NOT trigger solenoid on...
// idk WHY...
void activate_right_led (){
static unsigned long led_on_time = 0;
static unsigned long led_off_time = 0;
static unsigned long ITI_start_time = 0;
static int time_index = 0;
if (start_ITI_R == false){
if (led_state_R == LOW) {
led_state_R = HIGH;
led_on_time = millis();
digitalWrite(port_led_R, led_state_R);
Serial.print(F("9171:"));
Serial.println(led_on_time);
}
if((led_state_R = HIGH) && (millis() - led_on_time > led_on_duration)) {
led_state_R = LOW;
start_ITI_R = true;
ITI_start_time = millis();
led_off_time = millis();
digitalWrite(port_led_R, led_state_R);
Serial.print(F("9170:"));
Serial.println(led_off_time);
}
}
if (start_ITI_R) {
// start_ITI_R = false;
// ^changing state here will enable the following if clause Just ONCE
// because duration is involved, need to check the if clause multiple times!! (due to nature of microprocessors)
if ((millis() - ITI_start_time) >= wait_interval_R[time_index]) {
start_ITI_R= false;
time_index += 1;
if (time_index >= NUM_TIMES) {
time_index = 0;
}
activate_random_gen = true;
select_port = random_generator();
}
}
}
void activate_right_solenoid(){
static unsigned long solenoid_on_time = 0;
static unsigned long solenoid_off_time = 0;
// valid poke is when mouse responds while LED is turned on
if (led_state_R == HIGH) {
if (poke_in_R && valid_input_R) { // if valid_input is true
sol_state_R = HIGH;
valid_input_R = false;
solenoid_on_time = millis();
digitalWrite(port_solenoid_R, sol_state_R);
Serial.print(F("9271:"));
Serial.println(solenoid_on_time);
}
if ((sol_state_R == HIGH) && (millis() - solenoid_on_time > solenoid_on_duration)) {
sol_state_R = LOW;
solenoid_off_time = millis();
digitalWrite(port_solenoid_R, sol_state_R);
Serial.print(F("9270:"));
Serial.println(solenoid_off_time);
}
if (poke_in_R == false){ //later change to ! after logic works
valid_input_R = true;
}
}
// WITHOUT else if CLAUSE BELOW, FOLLOWING BUG OCCURS:
// when mouse pokes its head just before the led turns off and the solenoid turns on to dispense water,
// if the solenoid duration goes over the point of time at which LED turns off,
// then the solenoid is kept at HIGH indefinitely until the port LED turns on again
// (b/c the solenoid only turns off when LED is on) ^ check if conditional logic above
// ** (led_on_time + solenoid_duration > led_off_time) **
// experiment this by changing the duration of the solenoid reward (increase to see more effect) &
// poking your finger just before the LED turns off
else if (led_state_R == LOW) {
if (sol_state_R == HIGH){
sol_state_R = LOW;
solenoid_off_time = millis();
digitalWrite(port_solenoid_R, sol_state_R);
Serial.print(F("9270:"));
Serial.println(solenoid_off_time);
}
// 09/15/19 EDIT:
// If valid_input_L is trapped as FALSE state because poke out didn't occur within the "LED on window",
// toggle to TRUE once head pokes out!
if (poke_in_R == false){
valid_input_R = true;
}
}
}
|
C
|
#include <stdio.h>
#include <locale.h>
#include <glib.h>
#include <glib/gstdio.h>
// gcc -o permutacje-par permutacje-par.c `pkg-config --libs --cflags glib-2.0`
gchar* duza(const gchar* param)
{
gchar *name;
int i,len;
glong dlug;
g_return_val_if_fail(param != NULL, NULL);
name = g_strdup(param);
/* capitalize first letter */
// name[0] = g_ascii_toupper(name[0]);
name[0] = g_unichar_toupper(name[0]);
dlug = g_utf8_strlen(name,-1);
len = (int)(dlug);
for (i = 0; i<len; ++i)
{
if (name[i] == '-')
{
name[i] = ' ';
if (i+1 < len)
{
/* capitalize first letter of each word */
name[i+1] = g_unichar_toupper(name[i+1]);
}
}
}
return name;
}
int main(int argc, char** argv)
{
setlocale(LC_ALL, "pl_PL.utf8");
int licznik,dokonca,licznikkombinacji;
int ile_kombinacji,numerargumentu;
gint ile_slow;
ile_slow=argc-2;
// g_print("Liczba slow: %i\n", ile_slow);
licznik=atoi(argv[argc-1]);
// g_print("Licznik: %i\n", licznik);
ile_kombinacji=ile_slow-licznik+1;
for (licznikkombinacji=1;licznikkombinacji<=ile_kombinacji;licznikkombinacji++)
{
//g_print(" %izestaw: ",licznikkombinacji);
for (dokonca=1; dokonca<=licznik; dokonca++)
{
// g_print("%s|",tablica_slow[dokonca+licznikkombinacji-2]);
g_print("%s",argv[dokonca+licznikkombinacji-1]);
if (dokonca!=licznik) {g_print("_");}
}
g_print("|");
for (dokonca=1; dokonca<=licznik; dokonca++)
{
// g_print("%s|",tablica_slow[dokonca+licznikkombinacji-2]);
g_print("%s",duza(argv[dokonca+licznikkombinacji-1]));
if (dokonca!=licznik) {g_print("_");}
}
g_print("|");
}
return 0;
}
|
C
|
/*
** EPITECH PROJECT, 2020
** command
** File description:
** cmd
*/
#include "../include/my.h"
int my_command(char *str)
{
my_putstr(str);
str = get_next_line(0);
if (detect_stop_car(str) == 1)
return (1);
return (0);
}
int detect_stop_car(char *str)
{
int i = my_strlen(str) - 1, j = 0;
char *new;
new = malloc(sizeof(char *) * my_strlen(str));
if (new == NULL)
return (-1);
while (str[i] != ':' && str[i] != 0)
i -= 1;
i -= 1;
while (str[i] != ':' && str[i] != 0)
i -= 1;
i += 1;
while (str[i] != ':' && str[i] != 0)
new[j++] = str[i++];
new[j] = 0;
if (my_strcmp("Track Cleared", new) == 0) {
free(new);
my_command("STOP_SIMULATION\n");
return (1); }
free(new);
return (0);
}
|
C
|
#include "stack.h"
void SInitP (tStackP *S)
/* ------
** Inicializace zásobníku.
**/
{
S->top = 0;
}
void SPushP (tStackP *S, int a )
/* ------
** Vloží hodnotu na vrchol zásobníku.
**/
{
/* Při implementaci v poli může dojít k přetečení zásobníku. */
if (S->top==90)
printf("Chyba: Došlo k přetečení zásobníku s ukazateli!\n");
else {
S->top++;
S->a[S->top]=a;
}
}
int STopPopP (tStackP *S)
/* --------
** Odstraní prvek z vrcholu zásobníku a současně vrátí jeho hodnotu.
**/
{
/* Operace nad prázdným zásobníkem způsobí chybu. */
if (S->top==0) {
printf("Chyba: Došlo k podtečení zásobníku s ukazateli!\n");
return(NULL);
}
else {
return (S->a[S->top--]);
}
}
int STopP (tStackP *S)
/* --------
** Vrátí hodnotu prvku na vrcholu zásobníku
**/
{
/* Operace nad prázdným zásobníkem způsobí chybu. */
if (S->top==0) {
printf("Chyba: Došlo k podtečení zásobníku s ukazateli!\n");
return(NULL);
}
else {
return (S->a[S->top]);
}
}
void SPopP (tStackP *S)
/* --------
** Odstraní prvek z vrcholu zásobníku
**/
{
/* Operace nad prázdným zásobníkem způsobí chybu. */
if (S->top==0) {
printf("Chyba: Došlo k podtečení zásobníku s ukazateli!\n");
}
else {
S->top--;
}
}
int SSizeP (tStackP *S) {
/* -------
** Vrátí počet prvků v zásobníku
**/
return(S->top);
}
bool SEmptyP (tStackP *S)
/* -------
** Je-li zásobník prázdný, vrátí hodnotu true.
**/
{
return(S->top==0);
}
|
C
|
#include <stdio.h>
int main() {
double i, sum, x = 0;
while (scanf("%lf", &x) == 1) {
sum += x;
i++;
printf("Total=%f Average=%f\n", sum, sum / i);
};
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
typedef short TKey;
typedef struct _Node{
TKey key;
struct _Node *left, *right, *top;
}Node;
void insertNode(Node **root, TKey n);
void removeNode(Node **root, TKey n);
void listPreOrder(Node *Root);
int High(Node *n);
int FB(Node *n);
void RSD(Node *n1, Node *n2);
void RSE(Node *n1, Node *n2);
void bal(Node *n);
int main(){
Node **tree;
Node *t;
t = NULL;
tree = &t;
insertNode(tree, 1);
insertNode(tree, 5);
insertNode(tree, 10);
listPreOrder(*tree);
bal(*tree);
printf("\n");
listPreOrder(*tree);
return 0;
}
int FB(Node *n){
if(n == NULL)
return 0;
return High((*n).left) - High((*n).right);
}
int High(Node *n){
if(n == NULL)
return 0;
int esq = 0, dir = 0;
esq = High((*n).left);
dir = High((*n).right);
if(esq > dir)
return esq + 1;
else
return dir + 1;
}
void bal(Node *n){
int v = FB((*n).left) - FB((*n).right);
printf("\nDEBUG: %d\n", v);
if(v >= 1){
RSD(n, (*n).left);
}else if(v <= -1){
RSE(n, (*n).right);
}
}
void RSD(Node *n1, Node *n2){
(*n1).top = n2;
(*n1).left = NULL;
(*n2).right = n1;
}
void RSE(Node *n1, Node *n2){
(*n1).top = n2;
(*n1).right = NULL;
(*n2).left = n1;
}
void removeNode(Node **root, TKey n){
if(*root == NULL){
printf("Not Found!");
return;
}
}
void insertNode(Node **root, TKey n){
if(*root == NULL){
Node *aux = malloc(sizeof(Node));
(*aux).key = n;
(*aux).left = NULL;
(*aux).right = NULL;
(*aux).top = NULL;
*root = aux;
return;
}
if(n < (**root).key){ // insere a esquerda
if((**root).left != NULL){
insertNode(&(**root).left, n);
}else{
Node *aux = malloc(sizeof(Node));
(*aux).key = n;
(*aux).left = NULL;
(*aux).right = NULL;
(*aux).top = *root;
(**root).left = aux;
}
}else{ // insere a direita
if((**root).right != NULL){
insertNode(&(**root).right, n);
}else{
Node *aux = malloc(sizeof(Node));
(*aux).key = n;
(*aux).left = NULL;
(*aux).right = NULL;
(*aux).top = *root;
(**root).right = aux;
}
}
}
void listPreOrder(Node *Root){
if(Root == NULL) return;
printf(" ( ");
printf(" %hi [%d]", (*Root).key, FB(Root));
listPreOrder((*Root).left);
printf(" ");
listPreOrder((*Root).right);
printf(" ) ");
}
|
C
|
/*
* del_test.c
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include"adflib.h"
void MyVer(char *msg)
{
fprintf(stderr,"Verbose [%s]\n",msg);
}
/*
*
*
*/
int main(int argc, char *argv[])
{
struct Device *hd;
struct Volume *vol;
struct List *list;
SECTNUM nSect;
adfEnvInitDefault();
/* mount existing device */
hd = adfMountDev( argv[1],FALSE );
if (!hd) {
fprintf(stderr, "can't mount device\n");
adfEnvCleanUp(); exit(1);
}
vol = adfMount(hd, 0, FALSE);
if (!vol) {
adfUnMountDev(hd);
fprintf(stderr, "can't mount volume\n");
adfEnvCleanUp(); exit(1);
}
adfVolumeInfo(vol);
list = adfGetDirEnt(vol,vol->curDirPtr);
while(list) {
printEntry(list->content);
adfFreeEntry(list->content);
list = list->next;
}
freeList(list);
putchar('\n');
/* cd dir_2 */
nSect = adfChangeDir(vol, "same_hash");
list = adfGetDirEnt(vol,vol->curDirPtr);
while(list) {
printEntry(list->content);
adfFreeEntry(list->content);
list = list->next;
}
freeList(list);
putchar('\n');
/* not empty */
adfRemoveEntry(vol, vol->curDirPtr, "dir_2");
/* first in same hash linked list */
adfRemoveEntry(vol, vol->curDirPtr, "file_3a");
/* second */
adfRemoveEntry(vol, vol->curDirPtr, "dir_3");
/* last */
adfRemoveEntry(vol, vol->curDirPtr, "dir_1a");
list = adfGetDirEnt(vol,vol->curDirPtr);
while(list) {
printEntry(list->content);
adfFreeEntry(list->content);
list = list->next;
}
freeList(list);
putchar('\n');
adfParentDir(vol);
adfRemoveEntry(vol, vol->curDirPtr, "mod.And.DistantCall");
list = adfGetDirEnt(vol,vol->curDirPtr);
while(list) {
printEntry(list->content);
adfFreeEntry(list->content);
list = list->next;
}
freeList(list);
putchar('\n');
adfVolumeInfo(vol);
adfUnMount(vol);
adfUnMountDev(hd);
adfEnvCleanUp();
return 0;
}
|
C
|
// fsplit.cpp : Defines the entry point for the console application.
//
#include <stdlib.h>
#include "stdafx.h"
#include <string.h>
#define MAX_SPLIT 100
char *itoa(int, char *, int);
int main(int argc, char* argv[]) {
if ((argc < 3) || (argc > (MAX_SPLIT + 2)))
{
printf("File splitter by TS-Labs\n");
printf("Usage: fsplit <input> <piece 1 size> .. <piece N size>\n");
return 1;
}
FILE* f_in = fopen (argv[1], "rb");
if (!f_in)
{
printf ("Input file error!");
return 1;
}
struct stat st;
stat(argv[1], &st);
int sz = st.st_size;
void *buf = malloc(sz);
if (!buf)
{
printf ("Memory alloc error!");
return 3;
}
int ssz[MAX_SPLIT];
int n = (argc - 2);
for (int i = 0; i < n; i++)
{
ssz[i] = min(sz, atoi(argv[i + 2]));
sz -= ssz[i];
if (!sz)
break;
}
if (sz)
ssz[n++] = sz;
for (int i = 0; i < n; i++)
{
char fout[256];
char t[256];
strcpy(fout, argv[1]);
strcat(fout, ".");
strcat(fout, itoa(i, t, 10));
FILE *f_out = fopen(fout, "wb");
if (!f_out)
{
printf ("Output file error!");
return 2;
}
if (fread(buf, 1, ssz[i], f_in) != ssz[i])
{
printf ("Read file error!");
return 4;
}
if (fwrite(buf, 1, ssz[i], f_out) != ssz[i])
{
printf ("Write file error!");
return 5;
}
fclose(f_out);
}
fclose(f_in);
printf("DONE!\n");
return 0;
}
|
C
|
#include<stdio.h>
int main(){
int v,n,i,t;
scanf("%d%d",&v,&n);
for(i=0;i<n;i++){
scanf("%d",&t);
if(t==v)
printf("%d",i);
}
}
|
C
|
/********************************************************
** Authors: Alessandro Di Stanislao, [email protected]
** Carlo Caini (project supervisor), [email protected]
**
**
** Copyright (c) 2018, Alma Mater Studiorum, University of Bologna
** All rights reserved.
********************************************************/
#ifndef ERASURE_LAYER_H_
#define ERASURE_LAYER_H_
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "zfec/fec.h"
struct fec_encoded_data{
int M;
int K;
int block_size;
unsigned char **primary_blocks;
unsigned char **secondary_blocks;
unsigned int *secondary_blocks_numbers;
};
typedef struct fec_encoded_data fec_encoded_data;
struct fec_received_data{
int M;
int K;
int block_size;
unsigned char **input_blocks;
unsigned char **output_blocks;
unsigned int *index_blocks;
};
typedef struct fec_received_data fec_received_data;
/* This functions creates N blocks of a message data: K information blocks i.e. primary blocks.
M redundancy blocks i.e. secondary blocks.
N is the total number of blocks.
K blocks are needed for reconstruct the message.
Returns: a fec_encoded_data structure which contains primary and secondary blocks. */
fec_encoded_data* el_encode_blocks(int K,int N, const unsigned char *message,int message_length);
/* This functions recreates a complete message from K blocks of data
* Parameters: a fec_received_data that contains information and redundancy blocks.
* each information blocks must be stored in its index position.
* redundancy blocks can be placed everywhere.
* Returns: a char pointer with the decoded message. */
int el_decode_blocks(fec_received_data *data,unsigned char* message);
#endif
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* pf_wctoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: laleta <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/06/21 04:24:38 by laleta #+# #+# */
/* Updated: 2019/06/24 02:02:49 by laleta ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
void ft_conv_char(uint32_t wc, char *conv)
{
if (wc <= 0x7F)
conv[0] = wc;
else if (wc <= 0x7FF)
{
conv[0] = ((wc >> 6) + 0xC0);
conv[1] = ((wc & 0x3F) + 0x80);
}
else if (wc <= 0xFFFF)
{
conv[0] = ((wc >> 12) + 0xE0);
conv[1] = (((wc >> 6) & 0x3F) + 0x80);
conv[2] = ((wc & 0x3F) + 0x80);
}
else if (wc <= 0x10FFFF)
{
conv[0] = ((wc >> 18) + 0xF0);
conv[1] = (((wc >> 12) & 0x3F) + 0x80);
conv[2] = (((wc >> 6) & 0x3F) + 0x80);
conv[3] = ((wc & 0x3F) + 0x80);
}
}
int32_t ft_wcharlen(uint32_t wc)
{
if (wc <= 0x7F)
return (1);
else if (wc <= 0x7FF)
return (2);
else if (wc <= 0xFFFF)
return (3);
else if (wc <= 0x10FFFF)
return (4);
return (0);
}
static inline void ft_wctoa_c(t_prnf *pf, uint32_t *wc, char *conv)
{
ft_conv_char(*wc, conv);
pf->n1 = ft_wcharlen(*wc);
ft_memcpy(pf->s, conv, pf->n1);
}
void ft_wctoa(t_prnf *pf, uint32_t *wc, char type)
{
char conv[4];
int16_t wc_len;
int16_t l;
l = 0;
if (type == 'C' || type == 'c')
ft_wctoa_c(pf, wc, conv);
else
{
while (*wc != L'\0')
{
ft_conv_char(*wc, conv);
wc_len = ft_wcharlen(*wc);
if (pf->prec >= l + wc_len || pf->prec < 0)
{
ft_memcpy(pf->s + l, conv, wc_len);
l += wc_len;
}
else
break ;
++wc;
}
pf->n1 = l;
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void arraySum (int A[], int n){
int s=0;
for(int i=0;i<n;i++)
{
s=s+A[i];
}
printf("%d",s);
}
int main()
{
int n,i;
int a[n];
printf("Enter the number of elements\n");
scanf("%d",&n);
printf("Enter the elements of array\n");
for(int i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
arraySum(a,n);
/*for(i=0;i<n;i++)
{
s = s + a[i];
}
printf("%d",s);*/
return 0;
}
|
C
|
/*
** crack.c guesses the password (max 5 characters) when given a hash
** Dani van Enk, 11823526
*/
// including the used libraries
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define _XOPEN_SOURCE
#include <unistd.h>
#include <crypt.h>
#include <string.h>
// predefining the used functions
char next_letter(char current_letter);
int no_of_z(char string[], int length);
/*
** main loop with the possibility of parameters
*/
int main(int argc, char *argv[])
{
// only accepting 1 parameter when executing the code
if (argc == 2)
{
/*
** defining size, position of least significant digit
** length, userdefined has, password, last password and salt.
*/
int size = 6;
int least_bit_pos = 0;
int length = 1;
char *hash = argv[1];
char password[size];
char lastpass[size];
char salt[3] = {hash[0], hash[1]};
// filling password and lastpass with zeros
for (int i = 0; i < size; i++)
{
password[i] = '\0';
lastpass[i] = '\0';
}
// looping for each try
while (1)
{
// copy password onto lastpass
for (int char1 = 0; char1 < size; char1++)
{
lastpass[char1] = password[char1];
}
/*
** if z is reached and the number of z is equal to length
** add a new character
*/
if (lastpass[0] == 'z' && lastpass[least_bit_pos + 1] == '\0' &&
no_of_z(lastpass, length) == length)
{
least_bit_pos++;
length++;
for (int char2 = least_bit_pos - 1; char2 >= 0; char2--)
{
password[char2] = next_letter(lastpass[char2]);
}
}
/*
** if z is reached and no new character is needed (no_of_z < length)
** set next letter for the more significant letter
*/
if (lastpass[least_bit_pos] == 'z')
{
for (int char3 = length - 1; char3 >= 0; char3--)
{
/*
** for the next letter to be set, the less significant
** letters must all be z, else break
*/
if (lastpass[char3] == 'z')
{
password[char3 - 1] = next_letter(lastpass[char3 - 1]);
}
else
{
break;
}
}
}
// next letter, least significant letter is on the right
password[least_bit_pos] = next_letter(lastpass[least_bit_pos]);
/*
** if the hash gotten from the guessed password is equal to
** the userdefined hash, correct password has been found
*/
if (strcmp(hash, crypt(password, salt)) == 0)
{
printf("Found: %s\n", password);
return 0;
}
// exit for an password larger than 5 characters
else if (length > 5)
{
printf("Not Found 404\n");
return 1;
}
}
}
// error message for not enough parameters
else
{
printf("Usage: ./crack hash\n");
return 1;
}
// end program
return 0;
}
/*
** next_letter() returns the next leter to the given letter
*/
char next_letter(char current_letter)
{
// define current letter
int i = (int) current_letter;
// if Z is reached set letter to a
if (i == 90)
{
i += 7;
}
// if z is reached set letter to A
else if (i == 122 || i == 0)
{
i = 65;
}
// else just set to next letter
else
{
i++;
}
// return character
return (char) i;
}
/*
** no_of_z() returns the number of z in a string when given a string and length
*/
int no_of_z(char string[], int length)
{
// begin with 0 z
int no_z = 0;
// loop over the characters of the string
for (int i = 0; i < length; i++)
{
// if z is found increase no_z
if (string[i] == 'z')
{
no_z++;
}
}
// return the number of z
return no_z;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
/**
Given a sorted array of n integers where each integer is in the range from 0 to m-1 and m > n. Find the smallest number that is missing from the array.
Examples
Input: {0, 1, 2, 6, 9}, n = 5, m = 10
Output: 3
Input: {4, 5, 10, 11}, n = 4, m = 12
Output: 0
Input: {0, 1, 2, 3}, n = 4, m = 5
Output: 4
Input: {0, 1, 2, 3, 4, 5, 6, 7, 10}, n = 9, m = 11
Output: 8
*/
void setArray(int *N, int size){
int i; // counter
for(i=0; i<size; i++){
scanf("%d", N+i);
}
}
void getArray(int *N, int size){
int i; // counter
for(i=0; i<size; i++){
printf("%d ", *(N+i));
}
printf("\n");
}
int missing(int *N, int size){
int i=-1, res=1; // counter
while(res!=-1){
++i;
res = binarySearch(N, 0, size-1, i);
printf("Search result for %d is %d\n", i, res);
}
return i;
}
int binarySearch(int *N, int st, int end, int key){
int mid = st + (end-st+1)/2;
if(end<st){
return -1;
}
if(*(N+mid)==key){
return mid;
}
if(key > *(N+mid)){
return binarySearch(N, mid+1, end, key);
}else{
return binarySearch(N, st, mid-1, key);
}
}
int main(){
int T;
int *N;
int missing_element;
printf("Enter the size of array");
scanf("%d", &T);
N = (int*) malloc(sizeof(int)*T);
setArray(N, T);
missing_element = missing(N,T);
getArray(N, T);
printf("Missing Element %d\n", missing_element);
return 1;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define max 50
#define long_alfabeto 26
#define inicio_ascii_mayusculas 65
#define inicio_ascii_minusculas 97
const char *alfMinusculas = "abcdefghijklmnopqrstuvwxyz",
*alfMayusculas = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
void importarDiccionario(char* nomArchivo);
void importarTexto(char* nomArchivo);
void encriptar(char *mensaje, char *resultado);
int main(){
char nomDiccionario[max], nomTexto[max];
printf("********************* Kate The Ripper ********************\n");
system("ls\n\n");
printf("Ingresar nombre de diccionario: \n");
fgets(nomDiccionario, max, stdin);
strtok(nomDiccionario, "\n");
printf("Ingresar nombre de archivo con texto: \n");
fgets(nomTexto, max, stdin);
strtok(nomTexto, "\n");
importarDiccionario(nomDiccionario);
//importarTexto(nomTexto);
return 0;
}
//********************** FUNCION IMPORTAR DICCIONARIO DE DATOS ******************************
void importarDiccionario(char* nomArchivo){
char texto[max], encriptada[max], textoACrackear[max];
/*printf("Ingresar el texto a crackear: \n");
fgets(textoACrackear, max, stdin);
strtok(textoACrackear, "\n");*/
importarTexto(texto);
FILE *archivo;
archivo = fopen ( nomArchivo, "r" );
if (archivo==NULL) {
fprintf(stderr, "** Error de archivo del diccionario **\n");
exit(0);
}
while(1){
if(fgets(texto, max, archivo) == NULL) break;
encriptar(texto, encriptada);
strtok(encriptada, "\n");
strtok(texto, "\n");
if(strcmp(textoACrackear, encriptada) == 0){
printf("\n\nLa contraseña es: %s", texto);
fclose (archivo);
exit(0);
}else {
printf(".");
continue;
}
while(getchar() != '\n');
}
printf("\n\n * Contraseña no encontrada *");
fclose (archivo);
}
//********************** FUNCION LEER ARCHIVO CON TEXTO CIFRADO *****************************
void importarTexto(char* nomArchivo){
FILE *archivo;
archivo = fopen ( nomArchivo, "r" );
if (archivo==NULL) {
fprintf(stderr, "** Error de archivo de texto encriptado **\n");
exit(0);
}
while(1){
if(fgets(nomArchivo, max, archivo) == NULL) break;
strtok(nomArchivo, "\n");
}
fclose(archivo);
}
//******************************** FUNCION ENCRIPTAR *****************************************
void encriptar(char *mensaje, char *resultado) {
int i = 0, saltos = 3; //definir el numero de saltos.
while (mensaje[i]) {
char caracterActual = mensaje[i];
int posicionOriginalAscii = (caracterActual);
if (!isalpha(caracterActual)) {
resultado[i] = caracterActual;
i++;
continue;
}
if (isupper(caracterActual)) {
resultado[i] = alfMayusculas[(posicionOriginalAscii - inicio_ascii_mayusculas + saltos) % long_alfabeto];
}
else if (islower(caracterActual)) {
resultado[i] = alfMinusculas[(posicionOriginalAscii - inicio_ascii_minusculas + saltos) % long_alfabeto];
}
i++;
}
}
|
C
|
#include<stdio.h>
int main()
{
char str[100];
countSpecialChar;
int counter;
countDigits=countSpecialChar;
printf("Enter a string: ");
scanf("%c",str);
for(counter=0;str[counter]!=NULL;counter++)
{
if( countSpecialChar++)
}
printf("\nDigits: %d \nSpecial Characters: %d",countSpecialChar);
return 0;
|
C
|
#include <stdio.h>
void main()
{
char str1[100];
char str2[100];
int i = 0, m = 0;
int j = 0;
int count = 0;
int k = 0, choice;
printf("Please Enter the first string ");
// scanf("%s",str);
// gets(str);
fgets(str1, sizeof(str1), stdin);
printf("Please Enter the second string ");
fgets(str2, sizeof(str2), stdin);
printf("Please Enter the how many character want to add from second string ");
scanf("%d", &choice);
// printf(str);
while (str1[i] != '\n')
{
i++;
}
while (str2[j] != '\n')
{
str1[i] = str2[j];
count += 1;
if (count == choice)
{
i++;
break;
}
i++;
j++;
}
str1[i] = '\0'; //for iterating
printf("after concatination string is \n");
while (str1[k] != '\0')
{
printf("%c", str1[k]);
k++;
}
}
|
C
|
#include "hash_tables.h"
/**
* hash_table_create - a function that creates a hash table.
* @size : side of the hash table
* Return: a pointer to the newly created hash table
*/
hash_table_t *hash_table_create(unsigned long int size)
{
hash_table_t *table;
table = malloc(sizeof(hash_table_t));
if (table == NULL)
return (NULL);
table->size = size;
table->array = malloc(sizeof(table->array) * size);
if (table->array == NULL)
return (NULL);
return (table);
}
|
C
|
#include <stdio.h>
main(){
int i,v[10],cont=0,conti=0;
for(i=0;i<10;i++){
printf("digite os valores: ");
scanf("%d",&v[i]);
}
for(i=0;i<10;i++)
{
if(v[i]>0){
cont++;
}
else{
cont=cont;
}
if(v[i]%2!=0){
conti++;
}
else{
conti=conti;
}
}
printf("a quantidade de valores positivos sao: %d e a quantidade de valores impares sao: %d",cont,conti);
}
|
C
|
#include <stdio.h>
#include <lab0.h>
extern unsigned long etext, edata, end;
void printsegaddress() {
kprintf("void printsegaddress()\n");
kprintf("\nCurrent: etext[0x%08x]=0x%08x, edata[0x%08x]=0x%08x, ebss[0x%08x]=0x%08x", &etext, etext, &edata, edata, &end, end);
kprintf("\nPreceding: etext[0x%08x]=0x%08x, edata[0x%08x]=0x%08x, ebss[0x%08x]=0x%08x", (&etext - 1), *(&etext - 1), (&edata - 1), *(&edata - 1), (&end - 1), *(&end - 1));
kprintf("\nAfter: etext[0x%08x]=0x%08x, edata[0x%08x]=0x%08x, ebss[0x%08x]=0x%08x", (&etext + 1), *(&etext + 1), (&edata + 1), *(&edata + 1), (&end + 1), *(&end + 1));
}
|
C
|
int main() {
int i;
for i=0; i < 3; i++){
printf("i: %d", &i);
}
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* remove_backslash.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mboivin <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/01/02 01:11:11 by mboivin #+# #+# */
/* Updated: 2021/01/02 13:27:53 by mboivin ### ########.fr */
/* */
/* ************************************************************************** */
#include <stdbool.h>
#include "libft_str.h"
#include "sh_subsystems.h"
/*
** The backslash retains its special meaning only when followed by one of the
** following characters: ‘$’, ‘`’, ‘"’, ‘\’, or newline. Within double quotes,
** backslashes that are followed by one of these characters are removed.
** Backslashes preceding characters without a special meaning are left
** unmodified. A double quote may be quoted within double quotes by preceding
** it with a backslash.
*/
static bool is_followed_by_special(char *tok_word, size_t i)
{
i++;
if (tok_word[i])
{
return ((tok_word[i] == DOLLAR_SIGN) || (tok_word[i] == STRONG_QUOTE)
|| (tok_word[i] == WEAK_QUOTE) || (tok_word[i] == BACKSLASH));
}
return (false);
}
void remove_backslash(
char **result, char *tok_word, size_t *i, bool check_special)
{
if (check_special)
{
if (is_followed_by_special(tok_word, *i))
(*i)++;
}
else
(*i)++;
*result = ft_append_char(*result, tok_word + *i, true);
}
|
C
|
#include<stdio.h>
void main()
{
char ch;
printf("\n enter the character");
scanf("%c",&ch);
printf(" ASCII value is %d",ch);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* msh_parsing2.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ede-thom <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/02/20 15:32:04 by agoodwin #+# #+# */
/* Updated: 2021/05/27 14:39:51 by ede-thom ### ########.fr */
/* */
/* ************************************************************************** */
#include "minishell.h"
void add_el(t_list **lst, char *str, int type)
{
t_list *new;
if (!str || str[0] == '\0')
return ;
new = ft_lstnew(new_el(str, type));
if (!new)
error_exit(MALLOC_FAIL_ERROR);
ft_lstadd_back(lst, new);
}
int check_syntax_quote(char *line, int *j, int *i, t_command cmd)
{
while (line[++(*j)] != line[*i])
{
if (!line[*j])
{
shell_error(SYNTAX_ERROR, cmd.num);
return (0);
}
}
return (1);
}
static int quote_loop_logic(char *line, t_command cmd, int i,
t_list **elements)
{
char *str;
char *tmp;
int quote;
int j;
j = i;
quote = line[i];
if (!check_syntax_quote(line, &j, &i, cmd))
return (-5);
tmp = ft_substr(line, i + 1, j - i - 1);
if (!tmp)
error_exit(MALLOC_FAIL_ERROR);
if (quote == '"')
{
str = place_vars(tmp);
add_el(elements, str, TEXT);
free(str);
}
else
add_el(elements, tmp, TEXT);
free(tmp);
return (j);
}
void add_substr_el(char *line, int start, int end, t_list **elements)
{
char *tmp;
tmp = ft_substr(line, start, end);
if (!tmp)
error_exit(MALLOC_FAIL_ERROR);
add_el(elements, tmp, UNPARSED);
free(tmp);
}
t_list *parse_quotes(char *line, t_command cmd)
{
t_list *elements;
int i;
int start;
i = -1;
start = 0;
elements = NULL;
while (line[++i])
{
if (line[i] == '\'' || line[i] == '"')
{
add_substr_el(line, start, i - start, &elements);
start = quote_loop_logic(line, cmd, i, &elements) + 1;
if (start < 0)
{
ft_lstclear(&elements, del_element);
return (NULL);
}
i = start - 1;
}
}
add_substr_el(line, start, i - start, &elements);
return (elements);
}
|
C
|
/* File: mesinkata.h */
/* Definisi Mesin Kata: Model Akuisisi Versi I */
#ifndef __MESINKATA_H__
#define __MESINKATA_H__
#include "boolean.h"
#include "mesinkar.h"
#define NMax 50
#define BLANK ' '
typedef struct {
char *TabKata;
int Length;
} Kata;
/* State Mesin Kata */
extern boolean EndKata;
extern Kata CKata;
extern int list_of_input[99999];
extern int maxindex;
extern int baris[99999];
int IsSymbol();
/* Check if CC is symbol */
int IsTitikKoma();
/* Check if CC is semi-colon */
int IsAngka();
/* Check if CC is bracket */
int IsKurung();
/* Check if CC is newline */
int IsNewline();
/* Check if CC is number */
void IgnoreBlank();
/* Skip whitespace */
void STARTKATA();
/* Start parse text */
void ADVKATA();
/* Read next word */
void SalinSimbol();
/* Copy symbol */
void SalinAngka();
/* Copy number */
void SalinKata();
/* Copy words */
int CompareKata(Kata Kata1, Kata Kata2);
/* Compare words */
int KataToIndex(Kata K);
/* Change word to token (int) */
void printkata(Kata C);
/* Show word */
void init_token(char *filename);
/* parse external file contain strings and fill into array as tokens */
char* IndexToToken(int x);
/* Change token (int) to string */
#endif
|
C
|
#include <stdlib.h>
#include <math.h>
#include "Vector3.h"
Vector3 plusEquals(Vector3 *v1, Vector3 v2){
v1->x += v2.x;
v1->y += v2.y;
v1->z += v2.z;
return *v1;
}
Vector3 minusEquals(Vector3 *v1, Vector3 v2){
v1->x -= v2.x;
v1->y -= v2.y;
v1->z -= v2.z;
return *v1;
}
Vector3 multiply(Vector3 v, float a){
v.x *= a;
v.y *= a;
v.z *= a;
return v;
}
Vector3 crossProduct(const Vector3 v1, const Vector3 v2){
Vector3 crp;
crp.x = v1.y*v2.z - v1.z*v2.y;
crp.y = -v1.x*v2.z + v1.z*v2.x;
crp.z = v1.x*v2.y - v1.y*v2.x;
return crp;
}
float dotProduct(const Vector3 v1, const Vector3 v2){
return v1.x * v2.x + v1.y * v2.y + v1.z * v2.z;
}
float magnitude(Vector3 v){
return sqrt( v.x*v.x + v.y*v.y + v.z*v.z);
}
void normalize(Vector3 *v){
float mag = magnitude(*v);
v->x /= mag;
v->y /= mag;
v->z /= mag;
}
|
C
|
#include <stdio.h>
int main(void)
{
int test_case, T, i, len, dec, dec1, need, temp;
char str[1002];
freopen("1_input.txt", "r", stdin);
scanf(" %d", &T);
for (test_case = 1; test_case <= T; ++test_case)
{
for (i = 0; i < 1002; i++)
{
str[i] = NULL;
}
scanf("%s", str);
dec = str[0] - '0';
need = 0;
len = 0;
while (str[++len]);
for (i = 1; i < len; i++)
{
dec1 = str[i] - 48;
if (dec < i)
{
temp = i - dec;
need += temp;
dec += temp;
}
dec += dec1;
}
printf("#%d %d\n", test_case, need);
}
return 0; // ݵ 0 ؾ մϴ.
}
|
C
|
#include <stdio.h>
#include <assert.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <time.h>
int main() {
int ptoc[2];
int ctop[2];
pipe(ptoc);
pipe(ctop);
pid_t child;
int count = 0;
clock_t start = clock();
if ((child = fork()) == 0) {
close(0);
dup(ptoc[0]);
while ((clock() - start) < (start + 5 * CLOCKS_PER_SEC)) {
// === rcv char from parent
char buf = 0;
read(0, &buf, 1);
assert(buf == 0x42);
// ==== send char to parent
char buf_send = 1;
write(ctop[1], &buf_send, 1);
}
// End of loop, send kill signal
char buf_send = 0xff;
write(ctop[1], &buf_send, 1);
} else {
close(ptoc[0]);
while (1) {
// send char to child
char send = 0x42;
write(ptoc[1], &send, 1);
// ==== receive char from child
char rcv_buf;
read(ctop[0], &rcv_buf, 1);
if (rcv_buf == -1) {
break;
}
assert(rcv_buf == 1);
count++;
}
int wstatus;
wait(&wstatus);
printf("exchanges per second: %d\n", count / 5);
}
return 0;
}
|
C
|
#include "global.h"
#include "md4.h"
#define MD 4
#define MD_CTX MD4_CTX
#define MDInit MD4Init
#define MDUpdate MD4Update
#define MDFinal MD4Final
static void MDPrint (digest)
unsigned char digest[16];
{
unsigned int i;
for (i = 0; i < 16; i++)
printf ("%02x", digest[i]);
}
static void MDString (char *string)
{
MD4_CTX context;
unsigned char digest[16];
unsigned int len = strlen (string);
MD4Init (&context);
MD4Update (&context, string, len);
MD4Final (digest, &context);
printf ("MD%d (\"%s\") = ", MD, string);
MDPrint (digest);
printf ("\n");
}
int main(int argc, char *argv[])
{
MDString("qwe123");
}
|
C
|
/********************************************************
* Author: Shawn Guo *
* Date : 2013/2/15 *
* Last : 2013/2/15 *
* Project: LCD高精度时钟 *
* 插入LCD1602, P1 | JP5(0 1 ... A B) *
* K1: 功能键 K5: 返回键 K2: 增加键 K6:减少键 K3:闹铃键*
* P3^0 | BEEP *
********************************************************/
#include "LCD.h"
#include "key.h"
#include "time.h"
extern char YEAR1, YEAR2, MONTH, DAY, WEEK, HOUR, MINUTE, SECOND;
void Delayms(unsigned int xms);
int main()
{
// Time_Save(); // 第一次使用时,初始化ds1302内存
Time_Init();
LCD_Init();
while(1)
Key_Wait();
return 0;
}
void Delayms(unsigned int xms)
{
unsigned char i;
while(xms--)
{
for(i = 0; i < 110; i++)
;
}
}
|
C
|
#include "stdlib.h"
#include "stdio.h"
#include "string.h"
int main ()
{
char *str = "American";
char *str_temp = malloc (strlen (str) + 1);
strlcpy (str_temp, str, strlen (str) + 1);
char cur_char;
char *temp = str_temp + (strlen (str_temp) * sizeof (char) - sizeof (char));
cur_char = *temp;
while (*str != NULL)
{
printf("current char is : %c, and str is : %c\n", cur_char, *str);
if (cur_char != *str)
{
printf ("failed like a motherfucker!\n");
return 0;
}
temp--;
cur_char = *temp;
str++;
}
printf ("ISSA PALINDROME!\n");
return 1;
}
|
C
|
#include <stdio.h>
int main()
{
int i,n,m,p=0,j;
printf("Enter the size:");
scanf("%d",&n);
int a[99][99]={0};
a[0][(n-1)/2]=1;
j=(n-1)/2;
for(i=2;i<=n*n;i++)
{
p--;
j++;
if(p>=0) ;
else p+=n;
if(j<=n-1) ;
else j+=(-n);
if(a[p][j]==0)
a[p][j]=i;
else
a[++p][j]=i;
}
for(i=0;i<n;i++){
printf("\n");
for(m=0;m<n;m++)
printf("%3d ",a[i][m]);
}
printf("\n");
}
|
C
|
/* Here are the special operators that psipp recognizes which are
* not handled in parse.y.
*/
#include <stdio.h>
#include <stdlib.h>
#include "global.h"
/* This returns true if the value of the two names are the same. If
* one (or both) of the names is quoted, then the string with the
* quotes removed is used in the comparison.
*/
int
streq(name1,name2)
char *name1,*name2;
{
int result;
char *val1,*val2;
val1 = name_to_val(name1);
val2 = name_to_val(name2);
result = !strcmp(val1,val2);
free(val1);
free(val2);
return(result);
}
char *
name_to_val(name)
char *name;
{
char *result,*tmp;
if (name[0]=='"') {
if (name[strlen(name)-1]!='"') {
syntax_error("Yikes! Couldn't find the closing quote on a string.");
}
result = (char *) malloc(strlen(name));
strcpy(result,&name[1]);
result[strlen(result)-1] = '\0';
}
else {
tmp = eval_name_to_str(name);
result = (char *) malloc(sizeof(tmp)+1);
strcpy(result,tmp);
}
return(result);
}
|
C
|
#include<stdio.h>
void main(){
char str[10];
clrscr();
printf("Enter a string: ");
scanf("%s", &str);
if(str[0] == 'a'){
if(str[1] == 'b'){
printf("String is valid");
}
else{
printf("String is invalid");
}
}
else{
printf("String is invalid");
}
getch();
}
|
C
|
#include <stdio.h>
#include <limits.h>
struct {
const char *str;
const int base;
const long result;
} tests[] = {
{" 0", 10, 0},
{"0101", 2, 5},
{"ffff", 16, 0xffff}
};
int main(int argc, const char **argv) {
for (int i = 0; i < (sizeof(tests) / sizeof(tests[0])); i++) {
printf("\"%s\" base %i: ", tests[i].str, tests[i].base);
char *str_end;
long v = strtol(tests[i].str, &str_end, tests[i].base);
if (v != tests[i].result)
fprintf(stderr, "fail. Expected %i, got %i\n", tests[i].result, v);
else
printf("pass\n");
}
}
|
C
|
#ifndef SPIMAGEDATA_H_
#define SPIMAGEDATA_H_
#include "../SPPoint.h"
#include <stdbool.h>
/** A type used for defining an ImageData item**/
typedef struct sp_image_data {
int index;
int numOfFeatures;
SPPoint* featuresArray;
} sp_image_data;
/** A type used for defining an ImageData item as a pointer**/
typedef struct sp_image_data* SPImageData;
/*
* The method creates a new image data, with a given index
* @param index - the image index
*
* @returns
* NULL in case of memory allocation failure
* otherwise an ImageData item with the given index
*
* @logger - the method logs allocation errors if needed
*/
SPImageData createImageData(int index);
/*
* Deallocates a number of features from a given features array
* pre assumptions - numOfFeatures >= 0
*
* @param features - the features array
* @param numOfFeatures - the number of features
*
* @logger - prints a warning if images data is null
*/
void freeFeatures(SPPoint* features, int numOfFeatures);
/*
* Deallocates an image data item
*
* @param imageData - the image data to destroy
* @param suppressFeaturesArrayWarning - indicates if imageData->features = NULL should cause a warning
* @param freeInternalFeatures - indicates if the internal features (SPPoints) should be destroyed too
*
* @logger - prints a warning if image data is null
*/
void freeImageData(SPImageData imageData, bool suppressFeaturesArrayWarning, bool freeInternalFeatures);
/*
* Deallocates an images data items array
*
* pre-assumptions - size >=0
*
* @param imagesData - the images data array that should be destryed
* @param size - the size of the array
* @param freeInternalFeatures - indicates if the internal features (SPPoints) should be destroyed too
*
*
* @logger - prints a warning if images data is null
*/
void freeAllImagesData(SPImageData* imagesData, int size, bool freeInternalFeatures);
/*
* Resets an image data, free's its features and sets its number of features to 0.
*
* @param image - the image to reset
*
* @logger - reports warning if image is null
*/
void resetImageData(SPImageData image);
#endif /* SPIMAGEDATA_H_ */
|
C
|
#include "sort.h"
/**
* bubble_sort - sort an array with the bubble method
* @array: <-
* @size: array size
*
* Return: none
*/
void bubble_sort(int *array, size_t size)
{
size_t i, j;
int aux, tmp;
if (!array)
return;
else if (size <= 1)
return;
for (i = 0; i < size - 1; i++)
{
aux = array[0];
for (j = 0; j < size; j++)
{
if (aux > array[j])
{
tmp = array[j];
array[j] = aux;
array[j - 1] = tmp;
print_array(array, size);
}
else if (aux < array[j])
aux = array[j];
}
}
}
|
C
|
// testing4.c
#include <stdio.h>
#include "gfx4.h"
int main()
{
int wid = 600, ht = 500;
char c;
char *thefont = "-misc-fixed-bold-r-normal--13-120-75-75-c-70-iso8859-1";
char *mytext = "Notre Dame Fighting Irish";
int x_winctr, y_winctr; // window's center
int pxl_w, pxl_h, x_txt, y_txt; // text string's parameters
int x_r, y_r, rect_wid, rect_ht; // rectangle's parameters
int pad = 10; // padding for the rectangle
gfx_open(wid, ht, "My window");
gfx_color(255,255,255);
gfx_changefont(thefont);
while(1) {
if(gfx_event_waiting()) {
c = gfx_wait();
if (c == 'q') break;
}
// find the window's center point coordinates
x_winctr = gfx_windowwidth()/2;
y_winctr = gfx_windowheight()/2;
// determine the text string's width and height in pixels
pxl_w = gfx_textpixelwidth(mytext,thefont);
pxl_h = gfx_textpixelheight(mytext,thefont);
// display the text dead center, by determining its lower left corner
x_txt = x_winctr - pxl_w/2;
y_txt = y_winctr + pxl_h/2;
gfx_text(x_txt, y_txt, mytext);
// draw a rectangle around the text, dead center, with a given padding
// first determine its top left corner's x,y coordinates
x_r = x_txt - pad;
y_r = y_txt - pxl_h - pad;
// now compute its width and height
rect_wid = pxl_w + 2*pad;
rect_ht = pxl_h + 2*pad;
gfx_rectangle(x_r, y_r, rect_wid, rect_ht);
gfx_flush();
}
return 0;
}
|
C
|
#ifndef SIMPLE_HASHTABLE_HEADER
#define SIMPLE_HASHTABLE_HEADER
#include <stddef.h>
#include <stdint.h>
typedef void * (* alloc_fn)(size_t size);
typedef void (* free_fn)(void * ptr);
typedef uint32_t (* hash_fn) (void * data, size_t datalen);
/* simple table of linked-lists */
struct sht;
struct sht * sht_create_custom(int size, alloc_fn _alloc, free_fn _free,
hash_fn _hash);
void sht_destroy(struct sht * h);
#define sht_create(size) sht_create_custom(size, NULL, NULL, NULL)
int sht_insert(struct sht * h, void * key, size_t keylen, void * value);
void * sht_lookup(struct sht * h, void * key, size_t keylen);
void * sht_lookup_insert(struct sht * h, void * key, size_t keylen,
void * value);
int sht_remove(struct sht * h, void * key, size_t keylen);
int sht_gc(struct sht * h, int max_gc_num);
void sht_dump_stats(struct sht const * h);
#endif /* SIMPLE_HASHTABLE_HEADER */
|
C
|
#include<stdio.h>
#include<conio.h>
main()
{
int a;
//char one,two,three,four,five,six,seven,eight,nine,ten;
clrscr();
printf("Enter the number:");
scanf("%d",&a);
//if(a>=1)&&(a<=10)
if(a==1)
printf("\none");
else if(a==2)
printf("\ntwo");
else if(a==3)
printf("\nthree");
else if(a==4)
printf("\nFour");
else if(a==5)
printf("\nfive");
else if(a==6)
printf("\nsix");
else if(a==7)
printf("\nSeven");
else if(a==8)
printf("\nEight");
else if(a==9)
printf("\nNine");
else if(a==10)
printf("\nTen");
else
printf("\nEnter the number from 1 to 10" );
getch();
}
|
C
|
#include "holberton.h"
int main(void)
{
char c[10] = "Holberton";
int i;
for (i = 0; i < 10; i++)
putchar (c[i]);
putchar('\n');
return (0);
}
|
C
|
/**
* @file
* @brief Implementation by students of usefull function for the system project.
* @todo Change the SU_removeFile to use exec instead of system.
*/
#include "system_utils.h"
/**
* @brief Maximum length (in character) for a command line.
**/
#define SU_MAXLINESIZE (1024*8)
/********************** File managment ************/
void SU_removeFile(const char * file){
pid_t pid_fils = -1;
pid_fils = fork(); //Création d'un fils
if (pid_fils==-1) {
fprintf(stderr,"Erreur du fork");
}
else if (pid_fils==0) { //Exécuté par le fils
char buffer[SU_MAXLINESIZE-3];
snprintf(buffer, SU_MAXLINESIZE-3, "%s",file); //On met dans buffer les paramètres de la commande "rm"
fprintf(stderr, "%s\n", buffer);
if (execl("/bin/rm","rm",buffer,NULL)==-1) { //Suppression du fichier grâce à l'utilisation de execl
fprintf(stderr,"Erreur de execl");
exit(EXIT_FAILURE);
}
}
else { wait(NULL); } //Le père attend son fils
}
|
C
|
/*
* @file: T02_InvertSequencesRGB_White_Layered.c
* @company: ITESO
* @Engineer Team: D.F.R. / R.G.P.
*/
#include <stdio.h>
#include <stdint.h>
#include "MK64F12.h"
#include <bits.h> // se añadió .h vClass
#include <GPIO.h> // se añadió .h vClass - tiene propio .c vClass
int main(void) {
GPIO_clock_gating( GPIO_A); // sw3
GPIO_clock_gating( GPIO_B); // led azul y rojo
GPIO_clock_gating( GPIO_C); // sw2
GPIO_clock_gating( GPIO_E); // led verde
gpio_pin_control_register_t led_config = GPIO_MUX1; // 100
gpio_pin_control_register_t sw_config = GPIO_MUX1 |GPIO_PE | GPIO_PS; // 103
GPIO_pin_control_register( GPIO_A, bit_4, &sw_config ); // sw3 - pin 4
GPIO_pin_control_register( GPIO_B, bit_21, &led_config); // ledBlue - pin 21
GPIO_pin_control_register( GPIO_B, bit_22, &led_config); // ledRed - pin 22
GPIO_pin_control_register( GPIO_C, bit_6, &sw_config ); // sw2 - pin 6
GPIO_pin_control_register( GPIO_E, bit_26, &led_config); // ledGreen - pin 26
GPIO_set_pin( GPIO_B, bit_22); // OFF - 1 RED
GPIO_set_pin( GPIO_E, bit_26); // OFF - 1 GREEN
GPIO_set_pin( GPIO_B, bit_21); // OFF - 1 BLUE
GPIO_data_direction_pin(GPIO_B, GPIO_OUTPUT, bit_22); // OUTPUT - 1 RED
GPIO_data_direction_pin(GPIO_E, GPIO_OUTPUT, bit_26); // OUTPUT - 1 GREEN
GPIO_data_direction_pin(GPIO_B, GPIO_OUTPUT, bit_21); // OUTPUT - 1 BLUE
while (1) {
GPIO_clear_pin(GPIO_E, bit_26); // ON - 0 GREEN
//GPIO_clear_pin(GPIO_B, bit_21); // ON - 0 BLUE
//GPIO_clear_pin(GPIO_B, bit_22); // ON - 0 RED
}
return 0 ;
}
|
C
|
#include <stdio.h>
#include "ft_printf.h"
int main(void)
{
unsigned long a;
unsigned long b;
//a = 5;
//b = 5;
a = -42;
b = -42;
//a = 4294967295;
//b = 4294967295;
/*All with unsigned ints: 11 symbols and 1*/
printf("original: %u\n", a);
ft_printf("our : %u\n\n", b);
//flags
printf("FLAGS\n");
printf("original: %0lu\n", a);
ft_printf("our : %0lu\n\n", b);
printf("original: %-luA\n", a);
ft_printf("our : %-luA\n\n", b);
//precision
printf("PRECISION\n");
printf("original: %.14u\n", a);
ft_printf("our : %.14u\n\n", b);
printf("original: %.1u\n", a);
ft_printf("our : %.1u\n\n", b);
//width
printf("WIDTH\n");
printf("original: %17u\n", a);
ft_printf("our : %17u\n\n", b);
printf("original: %2u\n", a);
ft_printf("our : %2u\n\n", b);
//precision and flags
printf("PRECISION AND FLAGS\n");
printf("original: %0.16u\n", a);
ft_printf("our : %0.16u\n\n", b);
printf("original: %-.20uA\n", a);
ft_printf("our : %-.20uA\n\n", b);
//width and flags
printf("WIDTH AND FLAGS\n");
printf("original: %-13uAA\n", a);
ft_printf("our : %-13uAA\n\n", b);
printf("original: %025u\n", a);
ft_printf("our : %025u\n\n", b);
printf("original: %01u\n", a);
ft_printf("our : %01u\n\n", b);
//precision, width and flags
printf("PRECISION, WIDTH AND FLAGS\n");
printf("original: %-15.17uA\n", a);
ft_printf("our : %-15.17uA\n\n", b);
printf("original: %-20.5uA\n", a);
ft_printf("our : %-20.5uA\n\n", b);
printf("original: %018.12u\n", a);
ft_printf("our : %018.12u\n\n", b);
printf("original: %011.12u\n", a);
ft_printf("our : %011.12u\n\n", b);
//precision, width and double flags
printf("PRECISION, WIDTH AND DOUBLE FLAGS\n");
printf("original: %-019.12uAA\n", a);
ft_printf("our : %-019.12uAA\n\n", b);
printf("original: %- 15.20uAA\n", a);
ft_printf("our : %- 15.20uAA\n\n", b);
return (0);
}
|
C
|
double arithmetic(double a, double b, char *s) {
if (s[0]=='a') return a+b;
else if (s[0]=='s') return a-b;
if (s[0]=='m') return a*b;
else if (s[0]=='d') return a/b;
}
|
C
|
/*
* mm-naive.c - The fastest, least memory-efficient malloc package.
* In this naive approach, a block is allocated by simply incrementing
* the brk pointer. A block is pure payload. There are no headers or
* footers. Blocks are never coalesced or reused. Realloc is
* implemented directly using mm_malloc and mm_free.
*
* NOTE TO STUDENTS: Replace this header comment with your own header
* comment that gives a high level description of your solution.
*/
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <unistd.h>
#include <string.h>
#include "mm.h"
#include "memlib.h"
/*********************************************************
* NOTE TO STUDENTS: Before you do anything else, please
* provide your team information in the following struct.
********************************************************/
/* single word (4) or double word (8) alignment */
#define WSIZE 4 /* Word and header/footer size (bytes) */
#define DSIZE 8 /* Double word size (bytes) */
#define CHUNKSIZE (1<<12) /* Extend heap by this amount (bytes) */
#define ALIGNMENT 8
/* rounds up to the nearest multiple of ALIGNMENT */
#define ALIGN(size) (((size) + (ALIGNMENT-1)) & ~0x7)
#define SIZE_T_SIZE (ALIGN(sizeof(size_t)))
#define MAX(x, y) ((x) > (y) ? (x) : (y))
// Pack a size and allocated bit into a word
#define PACK(size, alloc) ((size) | (alloc))
// Read and write a word at address p
#define GET(p) (*(unsigned int *)(p))
#define PUT(p, val) (*(unsigned int *)(p) = (val))
// Read the size and allocation bit from address p
#define GET_SIZE(p) (GET(p) & ~0x7)
#define GET_ALLOC(p) (GET(p) & 0x1)
// Address of block's header and footer
#define HDRP(bp) ((char *)(bp) - WSIZE)
#define FTRP(bp) ((char *)(bp) + GET_SIZE(HDRP(bp)) - DSIZE)
// Address of next and previous blocks
#define NEXT_BLKP(bp) ((char *)(bp) + GET_SIZE((char *)(bp) - WSIZE))
#define PREV_BLKP(bp) ((char *)(bp) - GET_SIZE((char *)(bp) - DSIZE))
/* private variables */
static char *heap_listp;
/* function prototypes for internal helper routines */
static void *extend_heap(size_t words);
static void place(void *bp, size_t asize);
static void *find_fit(size_t asize);
static void *coalesce(void *bp);
static void printblock(void *bp);
static void checkblock(void *bp);
/*
* mm_init - Initialize the memory manager
*/
int mm_init(void)
{
/* create the initial empty heap */
if ((heap_listp = mem_sbrk(4*WSIZE)) == NULL)
return -1;
PUT(heap_listp, 0); /* alignment padding */
PUT(heap_listp+WSIZE, PACK(DSIZE, 1)); /* prologue header */
PUT(heap_listp+DSIZE, PACK(DSIZE, 1)); /* prologue footer */
PUT(heap_listp+WSIZE+DSIZE, PACK(0, 1)); /* epilogue header */
heap_listp += DSIZE;
/* Extend the empty heap with a free block of CHUNKSIZE bytes */
if (extend_heap(CHUNKSIZE/WSIZE) == NULL)
return -1;
return 0;
}
/*
* mm_malloc - Allocate a block with at least size bytes of payload
*/
void *mm_malloc(size_t size)
{
size_t asize; /* adjusted block size */
size_t extendsize; /* amount to extend heap if no fit */
char *bp;
/* Ignore spurious requests */
if (size <= 0)
return NULL;
/* Adjust block size to include overhead and alignment reqs. */
// if (size <= DSIZE)
// asize = DSIZE + OVERHEAD;
// else
// asize = DSIZE * ((size + (OVERHEAD) + (DSIZE-1)) / DSIZE);
asize = ALIGN(size + SIZE_T_SIZE);
/* Search the free list for a fit */
if ((bp = find_fit(asize)) != NULL) {
place(bp, asize);
return bp;
}
/* No fit found. Get more memory and place the block */
extendsize = MAX(asize,CHUNKSIZE);
if ((bp = extend_heap(extendsize/WSIZE)) == NULL)
return NULL;
place(bp, asize);
return bp;
}
/*
* mm_free - Free a block
*/
void mm_free(void *bp)
{
if (!bp)
return;
size_t size = GET_SIZE(HDRP(bp));
PUT(HDRP(bp), PACK(size, 0));
PUT(FTRP(bp), PACK(size, 0));
coalesce(bp);
return;
}
/* Not implemented. For consistency with 15-213 malloc driver */
void *mm_realloc(void *oldptr, size_t size)
{
size_t oldsize;
void *newptr;
/* If size == 0 then this is just free, and we return NULL. */
if (size == 0) {
mm_free(oldptr);
return NULL;
}
/* If oldptr is NULL, then this is just malloc. */
if (oldptr == NULL) {
return mm_malloc(size);
}
newptr = mm_malloc(size);
/* If realloc() fails the original block is left untouched */
if(!newptr) {
return NULL;
}
/* Copy the old data. */
oldsize = GET_SIZE(HDRP(oldptr));
if (size < oldsize)
oldsize = size;
memcpy(newptr, oldptr, oldsize);
/* Free the old block. */
mm_free(oldptr);
return newptr;
}
/*
* mm_checkheap - Check the heap for consistency
*/
void mm_checkheap(int verbose)
{
char *bp = heap_listp;
if (verbose)
printf("Heap (%p):\n", heap_listp);
if ((GET_SIZE(HDRP(heap_listp)) != DSIZE) || !GET_ALLOC(HDRP(heap_listp)))
printf("Bad prologue header\n");
checkblock(heap_listp);
for (bp = heap_listp; GET_SIZE(HDRP(bp)) > 0; bp = NEXT_BLKP(bp)) {
if (verbose)
printblock(bp);
checkblock(bp);
}
if (verbose)
printblock(bp);
if ((GET_SIZE(HDRP(bp)) != 0) || !(GET_ALLOC(HDRP(bp))))
printf("Bad epilogue header\n");
}
/* The remaining routines are internal helper routines */
/*
* extend_heap - Extend heap with free block and return its block pointer
*/
static void *extend_heap(size_t words)
{
void *bp;
size_t size;
/* Allocate an even number of words to maintain alignment */
size = (words % 2) ? (words+1) * WSIZE : words * WSIZE;
if ((bp = mem_sbrk(size)) == (void *) -1)
return NULL;
/* Initialize free block header/footer and the epilogue header */
PUT(HDRP(bp), PACK(size, 0)); /* free block header */
PUT(FTRP(bp), PACK(size, 0)); /* free block footer */
PUT(HDRP(NEXT_BLKP(bp)), PACK(0, 1)); /* new epilogue header */
/* Coalesce if the previous block was free */
return coalesce(bp);
}
/*
* place - Place block of asize bytes at start of free block bp
* and split if remainder would be at least minimum block size
*/
static void place(void *bp, size_t asize)
{
size_t csize = GET_SIZE(HDRP(bp));
if ((csize - asize) >= (2*DSIZE)) {
PUT(HDRP(bp), PACK(asize, 1));
PUT(FTRP(bp), PACK(asize, 1));
bp = NEXT_BLKP(bp);
PUT(HDRP(bp), PACK(csize-asize, 0));
PUT(FTRP(bp), PACK(csize-asize, 0));
}
else {
PUT(HDRP(bp), PACK(csize, 1));
PUT(FTRP(bp), PACK(csize, 1));
}
}
/*
* find_fit - Find a fit for a block with asize bytes
*/
static void *find_fit(size_t asize)
{
void *bp;
/* first fit search */
for (bp = heap_listp; GET_SIZE(HDRP(bp)) > 0; bp = NEXT_BLKP(bp)) {
if (!GET_ALLOC(HDRP(bp)) && (asize <= GET_SIZE(HDRP(bp)))) {
return bp;
}
}
return NULL; /* no fit */
}
/*
* coalesce - boundary tag coalescing. Return ptr to coalesced block
*/
static void *coalesce(void *bp)
{
size_t prev_alloc = GET_ALLOC(FTRP(PREV_BLKP(bp)));
size_t next_alloc = GET_ALLOC(HDRP(NEXT_BLKP(bp)));
size_t size = GET_SIZE(HDRP(bp));
if (prev_alloc && next_alloc) { /* Case 1 */
return bp;
}
else if (prev_alloc && !next_alloc) { /* Case 2 */
size += GET_SIZE(HDRP(NEXT_BLKP(bp)));
PUT(HDRP(bp), PACK(size, 0));
PUT(FTRP(bp), PACK(size,0));
return(bp);
}
else if (!prev_alloc && next_alloc) { /* Case 3 */
size += GET_SIZE(HDRP(PREV_BLKP(bp)));
PUT(FTRP(bp), PACK(size, 0));
PUT(HDRP(PREV_BLKP(bp)), PACK(size, 0));
return(PREV_BLKP(bp));
}
else { /* Case 4 */
size += GET_SIZE(HDRP(PREV_BLKP(bp))) +
GET_SIZE(FTRP(NEXT_BLKP(bp)));
PUT(HDRP(PREV_BLKP(bp)), PACK(size, 0));
PUT(FTRP(NEXT_BLKP(bp)), PACK(size, 0));
return(PREV_BLKP(bp));
}
}
static void printblock(void *bp)
{
size_t hsize, halloc, fsize, falloc;
hsize = GET_SIZE(HDRP(bp));
halloc = GET_ALLOC(HDRP(bp));
fsize = GET_SIZE(FTRP(bp));
falloc = GET_ALLOC(FTRP(bp));
if (hsize == 0) {
printf("%p: EOL\n", bp);
return;
}
printf("%p: header: [%d:%c] footer: [%d:%c]\n", bp,
(int)hsize, (halloc ? 'a' : 'f'),
(int)fsize, (falloc ? 'a' : 'f'));
}
static void checkblock(void *bp)
{
if ((size_t)bp % 8)
printf("Error: %p is not doubleword aligned\n", bp);
if (GET(HDRP(bp)) != GET(FTRP(bp)))
printf("Error: header does not match footer\n");
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <pthread.h>
#include <sys/ioctl.h>
#define X 80
#define Y 80
#define DEAD '.'
#define ALIVE '0'
#define mb() asm volatile("mfence":::"memory")
#define true 1
#define false 0
int size_x, size_y;
char MAP[X][Y];
volatile char LOCK = 0;
volatile char flag[2] = { false, false };
volatile char turn = 0;
static void *life( /*void *d*/ ) {
//int *p = (int *) d;
FILE *fh = fopen("map.txt", "r");
fscanf( fh, "%d", &size_x );
fscanf( fh, "%d", &size_y );
++size_x; ++size_y;
char counter, get;
int x, y, dx, dy;
for ( x = 0; x < X; ++x )
for ( y = 0; y < Y; ++y )
MAP[x][y] = 0;
for ( x = 1; x <= size_x; ++x )
for ( y = 1; y <= size_y; ++y )
fscanf( fh, "%c", &MAP[x][y] );
fclose(fh);
int self = 0;
int other = 1;
while( 1 ) {
// Dekker lock
flag[self] = true;
mb();
while( flag[other] == true ) {
if( turn != self ) {
flag[self] = false;
while( turn != self );
flag[self] = true;
}
}
// Critical section
// mark
for ( x = 1; x <= size_x; ++x )
for ( y = 1; y <= size_y; ++y ) {
counter = 0;
for ( dx = -1; dx < 2; ++dx )
for ( dy = -1; dy < 2; ++dy )
if ( !(dx == 0 && dy == 0) && (MAP[x + dx][y + dy] == ALIVE || MAP[x + dx][y + dy] == 3) ) ++counter;
if ( MAP[x][y] == DEAD && counter == 3 ) MAP[x][y] = 2; // alive
if ( MAP[x][y] == ALIVE && !(counter == 3 || counter == 2) ) MAP[x][y] = 3; // die
}
// rebuild
for ( x = 1; x <= size_x; ++x )
for ( y = 1; y <= size_y; ++y ) {
if ( MAP[x][y] == 2 ) MAP[x][y] = ALIVE;
if ( MAP[x][y] == 3 ) MAP[x][y] = DEAD;
}
// Dekker unlock
turn = other;
flag[self] = false;
sleep(1);
}
}
static void *print( /*void *d*/ ) {
//int *p = (int *) d;
char c;
int size, x, y;
int self = 1;
int other = 0;
while( scanf("%c", &c) ) {
// Dekker lock
flag[self] = true;
mb();
while( flag[other] == true ) {
if( turn != self ) {
flag[self] = false;
while( turn != self );
flag[self] = true;
}
}
// Critical section
for ( x = 1; x <= size_x; ++x )
for ( y = 1; y <= size_y; ++y )
printf( "%c", MAP[x][y] );
// Dekker unlock
turn = other;
flag[self] = false;
}
}
int main() {
//int p[4];
pthread_t thread[2];
//if ( pipe(p) == -1 || pipe(p + 2) == -1 ) {
// fprintf( stderr, "Pipe init failed!\n" );
// return 1;
//}
pthread_create(&thread[0], NULL, &life, NULL);
pthread_create(&thread[1], NULL, &print, NULL);
// wait threads
pthread_join(thread[0], NULL);
pthread_join(thread[1], NULL);
//int i;
//
//for ( i = 0; i < 4; ++i ) close(p[i]);
return 0;
}
|
C
|
/* sttrampoline.c: this is an optional helper file to link into Stata plugins which provides infrastructure plugins to define subcommands. */
/* This lets a single plugin operate in multiple steps which is necessary sometimes to work around the limited Stata API, */
/* and it lets a single plugin provide multiple services, if that makes sense. */
#include <string.h>
#include "sttrampoline.h"
/* Stata only lets an extension module export a single function (which I guess is modelled after each .ado file being a single function, a tradition Matlab embraced as well)
* to support multiple routines the proper way we would have to build multiple DLLs, and to pass variables between them we'd have to figure out
* instead of fighting with that, I'm using a tried and true method: indirection:
* the single function we export is a trampoline, and the subcommands array the list of places it can go.
*
* This file can be included by any plugin which wants to use a trampoline.
*/
ST_retcode sttrampoline(int argc, char* argv[]) {
for (int i = 0; i < argc; i++) {
stdebug("\targv[%d]=%s\n", i, argv[i]);
}
stdebug("Total dataset size: %dx%d. We have been asked operate on [%d:%d,%d].\n",
SF_nobs(), SF_nvar(), SF_in1(), SF_in2(), SF_nvars());
if (argc < 1) {
sterror("no subcommand specified\n");
return (1);
}
char *command = argv[0];
argc--;
argv++; //shift off the first arg before passing argv to the subcommand
int i = 0;
while (subcommands[i].name) {
if (strncmp(command, subcommands[i].name, SUBCOMMAND_MAX) == 0) {
return subcommands[i].func(argc, argv);
}
i++;
}
sterror("unrecognized subcommand '%s'\n", command);
return 1;
}
|
C
|
#include <stdio.h>
int main()
{
float number;
printf("How much money you made last year: ");
scanf("%f",&number);
number = number*0.7;
printf("After taxes: $%.2f\n", number);
if (number < 0)
{
printf("invalid input\n");
}
else if (number >= 0 && number <= 20000)
{
printf("broke\n");
}
else if (number >= 20001 && number <= 60000)
{
printf("not bad\n");
}
else
{
printf("Ballin\n");
}
return 0;
}
|
C
|
#include <stdio.h>
int main(void) {
// your code goes here
int s,q,num;
scanf("%d %d",&s,&q);
for(num=s;num<=q;num++)
{
if(num%2==1)
printf("%d ",num);
}
return 0;
}
|
C
|
// //
// Author: T.Warburton //
// Design: T.Warburton && S.Sherwin //
// Date : 12/4/96 //
// //
// Copyright notice: This code shall not be replicated or used without //
// the permission of the author. //
// //
/**************************************************************************/
#include <stdarg.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
#include <polylib.h>
#include "veclib.h"
#include "hotel.h"
#include <stdio.h>
using namespace polylib;
#define TOL_BLEND 1.0e-8
#define TANTOL 1e-10
/* new atan2 function to stop Nan on atan(0,0)*/
static double atan2_proof (double x, double y)
{
if (fabs(x) + fabs(y) > TANTOL) return (atan2(x,y));
else return (0.);
}
#define atan2 atan2_proof
typedef struct point { /* A 2-D point */
double x,y; /* coordinate */
} Point;
double find_spiral_theta(Curve *curve, double x0, double y0, double z0);
void genCylinder(Curve *curve, double *x, double *y, double *z, int q){
register int i;
double *f,theta,phi,cp,sp,ct,st;
f = dvector(0,q-1);
/* translate co-ordinates so that given point is origin */
dsadd(q, -curve->info.cyl.xc, x, 1, x, 1);
dsadd(q, -curve->info.cyl.yc, y, 1, y, 1);
dsadd(q, -curve->info.cyl.zc, z, 1, z, 1);
/* rotate co-ordinates so that cylinder axis is aligned with z axis */
phi = atan2(curve->info.cyl.ay, curve->info.cyl.ax);
cp = cos(phi); sp = sin(phi);
drot(1,&curve->info.cyl.ax,1,&curve->info.cyl.ay,1,cp,sp);
theta = atan2(curve->info.cyl.ax,curve->info.cyl.az);
ct = cos(theta); st = sin(theta);
drot(q,x,1,y,1,cp,sp);
drot(q,z,1,x,1,ct,st);
/* move co-ordinate out to surface value */
for(i = 0; i < q; ++i){
theta = atan2(y[i],x[i]);
x[i] = curve->info.cyl.radius*cos(theta);
y[i] = curve->info.cyl.radius*sin(theta);
}
/* rotate back */
drot(q,z,1,x,1,ct,-st);
drot(q,x,1,y,1,cp,-sp);
/* translate co-ordinates back to original position */
dsadd(q, curve->info.cyl.xc, x, 1, x, 1);
dsadd(q, curve->info.cyl.yc, y, 1, y, 1);
dsadd(q, curve->info.cyl.zc, z, 1, z, 1);
free(f);
}
void genCone(Curve *curve, double *x, double *y, double *z, int q){
register int i;
double *f,theta,phi,cp,sp,ct,st;
f = dvector(0,q-1);
/* translate co-ordinates so that apex is at origin */
dsadd(q, -curve->info.cone.xc, x, 1, x, 1);
dsadd(q, -curve->info.cone.yc, y, 1, y, 1);
dsadd(q, -curve->info.cone.zc, z, 1, z, 1);
/* rotate co-ordinates so that cone axis is aligned with z axis */
phi = atan2(curve->info.cone.ay, curve->info.cone.ax);
cp = cos(phi); sp = sin(phi);
drot(1,&curve->info.cone.ax,1,&curve->info.cone.ay,1,cp,sp);
theta = atan2(curve->info.cone.ax,curve->info.cone.az);
ct = cos(theta); st = sin(theta);
drot(q,x,1,y,1,cp,sp);
drot(q,z,1,x,1,ct,st);
/* move co-ordinate out to surface value */
for(i = 0; i < q; ++i){
theta = atan2(y[i],x[i]);
x[i] = fabs(z[i])*curve->info.cone.alpha*cos(theta);
y[i] = fabs(z[i])*curve->info.cone.alpha*sin(theta);
}
/* rotate back */
drot(q,z,1,x,1,ct,-st);
drot(q,x,1,y,1,cp,-sp);
/* translate co-ordinates back to original position */
dsadd(q, curve->info.cone.xc, x, 1, x, 1);
dsadd(q, curve->info.cone.yc, y, 1, y, 1);
dsadd(q, curve->info.cone.zc, z, 1, z, 1);
free(f);
}
void genSphere(Curve *curve, double *x, double *y, double *z, int q){
register int i;
double *f,theta,phi;
f = dvector(0,q-1);
/* translate co-ordinates so that apex is at origin */
dsadd(q, -curve->info.sph.xc, x, 1, x, 1);
dsadd(q, -curve->info.sph.yc, y, 1, y, 1);
dsadd(q, -curve->info.sph.zc, z, 1, z, 1);
/* move co-ordinate out to surface value */
for(i = 0; i < q; ++i){
phi = atan(z[i]/sqrt(x[i]*x[i]+y[i]*y[i]));
theta = atan2(y[i],x[i]);
z[i] = curve->info.sph.radius*sin(phi);
x[i] = y[i] = curve->info.sph.radius*cos(phi);
x[i] *= cos(theta);
y[i] *= sin(theta);
}
/* translate co-ordinates back to original position */
dsadd(q, curve->info.sph.xc, x, 1, x, 1);
dsadd(q, curve->info.sph.yc, y, 1, y, 1);
dsadd(q, curve->info.sph.zc, z, 1, z, 1);
free(f);
}
void genSheet(Curve *curve, double *x, double *y, double *z, int q){
register int i;
double *f,theta,phi,cp,sp,ct,st,rtmp;
f = dvector(0,q-1);
/* translate co-ordinates so that given point is origin */
dsadd(q, -curve->info.she.xc, x, 1, x, 1);
dsadd(q, -curve->info.she.yc, y, 1, y, 1);
dsadd(q, -curve->info.she.zc, z, 1, z, 1);
/* rotate co-ordinates so that cylinder axis is aligned with z axis */
phi = atan2(curve->info.she.ay, curve->info.she.ax);
cp = cos(phi); sp = sin(phi);
drot(1,&curve->info.she.ax,1,&curve->info.she.ay,1,cp,sp);
theta = atan2(curve->info.she.ax,curve->info.she.az);
ct = cos(theta); st = sin(theta);
drot(q,x,1,y,1,cp,sp);
drot(q,z,1,x,1,ct,st);
/* move co-ordinate out to surface value */
for(i = 0; i < q; ++i){
theta = z[i]*curve->info.she.twist+curve->info.she.zerotwistz;
rtmp = sqrt(x[i]*x[i]+y[i]*y[i]);
x[i] = rtmp*cos(theta);
y[i] = rtmp*sin(theta);
}
/* rotate back */
drot(q,z,1,x,1,ct,-st);
drot(q,x,1,y,1,cp,-sp);
/* translate co-ordinates back to original position */
dsadd(q, curve->info.she.xc, x, 1, x, 1);
dsadd(q, curve->info.she.yc, y, 1, y, 1);
dsadd(q, curve->info.she.zc, z, 1, z, 1);
free(f);
}
#ifdef OLDHELIX
void genSpiral(Curve *curve, double *x, double *y, double *z, int q){
register int i;
double *f,theta,phi,cp,sp,ct,st,rtmp;
f = dvector(0,q-1);
/* translate co-ordinates so that given point is origin */
dsadd(q, -curve->info.spi.xc, x, 1, x, 1);
dsadd(q, -curve->info.spi.yc, y, 1, y, 1);
dsadd(q, -curve->info.spi.zc, z, 1, z, 1);
/* rotate co-ordinates so that cylinder axis is aligned with z axis */
phi = atan2(curve->info.spi.ay, curve->info.spi.ax);
cp = cos(phi); sp = sin(phi);
drot(1,&curve->info.spi.ax,1,&curve->info.spi.ay,1,cp,sp);
theta = atan2(curve->info.spi.ax,curve->info.spi.az);
ct = cos(theta); st = sin(theta);
drot(q,x,1,y,1,cp,sp);
drot(q,z,1,x,1,ct,st);
/* move co-ordinate out to surface value */
for(i = 0; i < q; ++i){
theta = z[i]*curve->info.spi.twist+curve->info.spi.zerotwistz;
rtmp = curve->info.spi.axialradius;
x[i] -= rtmp*cos(theta);
y[i] -= rtmp*sin(theta);
phi = atan2(y[i],x[i]);
x[i] = curve->info.spi.piperadius*cos(phi);
y[i] = curve->info.spi.piperadius*sin(phi);
x[i] += rtmp*cos(theta);
y[i] += rtmp*sin(theta);
}
/* rotate back */
drot(q,z,1,x,1,ct,-st);
drot(q,x,1,y,1,cp,-sp);
/* translate co-ordinates back to original position */
dsadd(q, curve->info.spi.xc, x, 1, x, 1);
dsadd(q, curve->info.spi.yc, y, 1, y, 1);
dsadd(q, curve->info.spi.zc, z, 1, z, 1);
free(f);
}
#else
void genSpiral(Curve *curve, double *x, double *y, double *z, int q){
register int i;
double *f,theta,theta0,phi,cp,sp,ct,st;
double axialrad,pitch,piperad;
double cx,cy,cz;
f = dvector(0,q-1);
/* translate co-ordinates so that given point is origin */
dsadd(q, -curve->info.spi.xc, x, 1, x, 1);
dsadd(q, -curve->info.spi.yc, y, 1, y, 1);
dsadd(q, -curve->info.spi.zc, z, 1, z, 1);
/* rotate co-ordinates so that cylinder axis is aligned with z axis */
phi = atan2(curve->info.spi.ay, curve->info.spi.ax);
cp = cos(phi); sp = sin(phi);
drot(1,&curve->info.spi.ax,1,&curve->info.spi.ay,1,cp,sp);
theta = atan2(curve->info.spi.ax,curve->info.spi.az);
ct = cos(theta); st = sin(theta);
drot(q,x,1,y,1,cp,sp);
drot(q,z,1,x,1,ct,st);
phi = 0.5*M_PI -
atan(curve->info.spi.pitch/(2*M_PI*curve->info.spi.axialradius));
piperad = curve->info.spi.piperadius;
axialrad = curve->info.spi.axialradius;
pitch = curve->info.spi.pitch;
/* move co-ordinate out to surface value */
for(i = 0; i < q; ++i){
/* intially find theta0 assuming in first winding */
theta0 = find_spiral_theta(curve,x[i],y[i],z[i]);
cz = 0.0;
/* if theta0 gives a helix point which is outside pipe radius */
/* assume that we are in the next winding and so re-calculate */
while(fabs(z[i] - cz - pitch*theta0/(2*M_PI)) > piperad){
cz += pitch;
theta0 = find_spiral_theta(curve,x[i],y[i],z[i]-cz);
}
cx = axialrad*cos(theta0);
cy = axialrad*sin(theta0);
cz += pitch*theta0/(2*M_PI);
/* move section centre to origin */
x[i] -= cx;
y[i] -= cy;
z[i] -= cz;
/* rotate theta about z axis */
drot(1,x+i,1,y+i,1,cos(theta0),sin(theta0));
/* rotate -phi about x axis */
drot(1,y+i,1,z+i,1,cos(-phi),sin(-phi));
theta = atan2(y[i],x[i]);
x[i] = curve->info.spi.piperadius*cos(theta);
y[i] = curve->info.spi.piperadius*sin(theta);
/* rotate phi about x axis */
drot(1,y+i,1,z+i,1,cos(phi),sin(phi));
/* rotate theta about z axis */
drot(1,x+i,1,y+i,1,cos(-theta0),sin(-theta0));
/* move section centre back */
x[i] += cx;
y[i] += cy;
z[i] += cz;
}
/* rotate back */
drot(q,z,1,x,1,ct,-st);
drot(q,x,1,y,1,cp,-sp);
/* translate co-ordinates back to original position */
dsadd(q, curve->info.spi.xc, x, 1, x, 1);
dsadd(q, curve->info.spi.yc, y, 1, y, 1);
dsadd(q, curve->info.spi.zc, z, 1, z, 1);
free(f);
}
#define TOLTHETA 1e-10
#define ITERTHETA 100
/* find the angle corresponding to the intersection of the helix and the plane
containing the points x0,y0,z0 */
double find_spiral_theta(Curve *curve, double x0, double y0, double z0){
register int count = 0;
double dt;
double theta, theta0;
double pitch = curve->info.spi.pitch;
double rad = curve->info.spi.axialradius;
double A,B;
theta = theta0 = atan2(y0,x0);
/* correct for negative value of theta0 */
theta0 += (fabs(z0 - pitch*theta0/(2*M_PI)) < rad)? 0:2*M_PI;
theta = theta0;
A = pitch*pitch/(4*M_PI*M_PI*rad);
B = -x0*sin(theta0) + y0*cos(theta0) + z0*pitch/(2*M_PI*rad);
dt = (-A*theta + B)/(rad+A);
while((fabs(dt) > TOLTHETA)&&(count++ < ITERTHETA)){
theta += dt;
dt = (rad*sin(theta0 - theta) - A*theta + B)/(rad*cos(theta0-theta)+A);
}
if(count == ITERTHETA)
fprintf(stderr,"Iterations failed to converge in spiral_theta\n");
return theta;
}
#endif
void genTaurus(Curve *curve, double *x, double *y, double *z, int q){
register int i;
double *f,theta,phi,cp,sp,ct,st,rtmp,xtmp,ytmp;
f = dvector(0,q-1);
/* translate co-ordinates so that given point is origin */
dsadd(q, -curve->info.tau.xc, x, 1, x, 1);
dsadd(q, -curve->info.tau.yc, y, 1, y, 1);
dsadd(q, -curve->info.tau.zc, z, 1, z, 1);
/* rotate co-ordinates so that tauinder axis is aligned with z axis */
phi = atan2(curve->info.tau.ay, curve->info.tau.ax);
cp = cos(phi); sp = sin(phi);
drot(1,&curve->info.tau.ax,1,&curve->info.tau.ay,1,cp,sp);
theta = atan2(curve->info.tau.ax,curve->info.tau.az);
ct = cos(theta); st = sin(theta);
drot(q,x,1,y,1,cp,sp);
drot(q,z,1,x,1,ct,st);
/* move co-ordinate out to surface value */
for(i = 0; i < q; ++i){
theta = atan2(y[i],x[i]);
rtmp = curve->info.tau.axialradius;
xtmp = x[i];
ytmp = y[i];
x[i] = xtmp*cos(theta)+ytmp*sin(theta)-rtmp;
y[i] = -xtmp*sin(theta)+ytmp*cos(theta);
phi = atan2(z[i],x[i]);
x[i] = curve->info.tau.piperadius*cos(phi)+rtmp;
z[i] = curve->info.tau.piperadius*sin(phi);
xtmp = x[i];
ytmp = y[i];
x[i] = xtmp*cos(theta)-ytmp*sin(theta);
y[i] = xtmp*sin(theta)+ytmp*cos(theta);
}
/* rotate back */
drot(q,z,1,x,1,ct,-st);
drot(q,x,1,y,1,cp,-sp);
/* translate co-ordinates back to original position */
dsadd(q, curve->info.tau.xc, x, 1, x, 1);
dsadd(q, curve->info.tau.yc, y, 1, y, 1);
dsadd(q, curve->info.tau.zc, z, 1, z, 1);
free(f);
}
void trans_coords(Coord *o, Coord *t, Coord *n, Coord *b,
Coord *x, Coord *newx, int np, int dir){
int i;
// to (t,n,b)
if(dir == 1){
dcopy(np, x->x, 1, newx->x, 1);
dcopy(np, x->y, 1, newx->y, 1);
dcopy(np, x->z, 1, newx->z, 1);
dsadd(np, -o->x[0], newx->x, 1, newx->x, 1);
dsadd(np, -o->y[0], newx->y, 1, newx->y, 1);
dsadd(np, -o->z[0], newx->z, 1, newx->z, 1);
for(i=0;i<np;++i){
newx->x[i] = t->x[0]*x->x[i] + t->y[0]*x->y[i] + t->z[0]*x->z[i];
newx->y[i] = n->x[0]*x->x[i] + n->y[0]*x->y[i] + n->z[0]*x->z[i];
newx->z[i] = b->x[0]*x->x[i] + b->y[0]*x->y[i] + b->z[0]*x->z[i];
}
}
else{
for(i=0;i<np;++i){
newx->x[i] = t->x[0]*x->x[i] + n->x[0]*x->y[i] + b->x[0]*x->z[i];
newx->y[i] = t->y[0]*x->x[i] + n->y[0]*x->y[i] + b->y[0]*x->z[i];
newx->z[i] = t->z[0]*x->x[i] + n->z[0]*x->y[i] + b->z[0]*x->z[i];
}
/* translate co-ordinates back to original position */
dsadd(np, o->x[0], newx->x, 1, newx->x, 1);
dsadd(np, o->y[0], newx->y, 1, newx->y, 1);
dsadd(np, o->z[0], newx->z, 1, newx->z, 1);
}
}
#define c1 ( 0.29690)
#define c2 (-0.12600)
#define c3 (-0.35160)
#define c4 ( 0.28430)
#define c5 (-0.10360)
/* naca profile -- usage: naca t x returns points on naca 00 aerofoil of
thickness t at position x */
static double naca(double L, double x, double t){
x = x/L;
if(L==0.)
return 0.;
// return 5.*t*L*(c1*sqrt(x)+ x*(c2 + x*(c3 + x*(c4 + c5*x))));
return 5.*t*L*(c1*sqrt(x)+ x*(c2 + x*(c3 + x*(c4 + c5*x))));
}
#undef c1
#undef c2
#undef c3
#undef c4
#undef c5
void genNaca3d(Curve *curve, double *x, double *y, double *z, int q){
register int i;
Coord X,newX;
double sg;
X.x = x;
X.y = y;
X.z = z;
newX.x = dvector(0, q-1);
newX.y = dvector(0, q-1);
newX.z = dvector(0, q-1);
trans_coords(curve->info.nac3d.origin,
curve->info.nac3d.axis,
curve->info.nac3d.lead,
curve->info.nac3d.locz,
&X,&newX,q,1); // transform to aligned coord.s
/* move co-ordinate out to surface value */
for(i = 0; i < q; ++i){
sg = (newX.z[i]<0) ? -1. : 1.;
if(newX.x[i] < 0. || newX.x[i] > curve->info.nac3d.length)
fprintf(stderr, "X: %lf\n", newX.x[i]);
newX.z[i] = sg*naca(curve->info.nac3d.length,
newX.x[i],
curve->info.nac3d.thickness);
}
trans_coords(curve->info.nac3d.origin,
curve->info.nac3d.axis,
curve->info.nac3d.lead,
curve->info.nac3d.locz,
&newX,&X,q,-1); // transform to aligned coord.s
free(newX.x);
free(newX.y);
free(newX.z);
}
void Quad_Face_JacProj(Bndry *B){
Element *E = B->elmt;
int face = B->face;
const int qa = E->qa, qb = E->qb;
Coord S;
double **da,**db,**dc,**dt;
double **D, *x, *y, *z, *xr, *xs, *yr, *ys, *zr, *zs;
D = dmatrix(0,9,0,QGmax*QGmax-1);
xr = D[0]; xs = D[1];
yr = D[2]; ys = D[3];
zr = D[4]; zs = D[5];
S.x = D[0]; x = D[6];
S.y = D[1]; y = D[7];
S.z = D[2]; z = D[8];
E->GetFaceCoord(face,&S);
E->InterpToFace1(face,S.x,x);
E->InterpToFace1(face,S.y,y);
E->InterpToFace1(face,S.z,z);
// db->da
/* calculate derivatives */
E->getD(&da,&dt,&db,&dt,&dc,&dt);
/* calculate dx/dr */
dgemm('T','N',qa,qb,qa,1.0,*da,qa,x,qa,0.0,xr,qa);
/* calculate dx/ds */
dgemm('N','N',qa,qb,qb,1.0,x,qa,*da,qb,0.0,xs,qa);
/* calculate dy/dr */
dgemm('T','N',qa,qb,qa,1.0,*da,qa,y,qa,0.0,yr,qa);
/* calculate dy/ds */
dgemm('N','N',qa,qb,qb,1.0,y,qa,*da,qb,0.0,ys,qa);
/* calculate dz/dr */
dgemm('T','N',qa,qb,qa,1.0,*da,qa,z,qa,0.0,zr,qa);
/* calculate dz/ds */
dgemm('N','N',qa,qb,qb,1.0,z,qa,*da,qb,0.0,zs,qa);
/* x = yr*zs - zr*ys*/
dvmul (qa*qb,yr,1,zs,1,x,1);
dvvtvm(qa*qb,zr,1,ys,1,x,1,x,1);
/* y = zr*xs - xr*zs*/
dvmul (qa*qb,zr,1,xs,1,y,1);
dvvtvm(qa*qb,xr,1,zs,1,y,1,y,1);
/* z = xr*ys - xs*yr*/
dvmul (qa*qb,xr,1,ys,1,z,1);
dvvtvm(qa*qb,xs,1,yr,1,z,1,z,1);
/* Surface Jacobea = sqrt(x^2 + y^2 + z^2) */
dvmul (qa*qb,x,1,x,1,B->sjac.p,1);
dvvtvp(qa*qb,y,1,y,1,B->sjac.p,1,B->sjac.p,1);
dvvtvp(qa*qb,z,1,z,1,B->sjac.p,1,B->sjac.p,1);
dvsqrt(qa*qb,B->sjac.p,1,B->sjac.p,1);
free_dmatrix(D,0,0);
}
/* calculate the surface jacobian which is defined for as 2D surface in
a 3D space as:
Surface Jac = sqrt(Nx^2 + Ny^2 + Nz^2)
where [Nx,Ny,Nz] is the vector normal to the surface given by the
cross product of the two tangent vectors in the r and s direction,
i.e.
Nx = y_r z_s - z_r y_s
Ny = z_r x_s - x_r z_s
Nz = x_r y_s - y_r x_s
*/
/* this function is defined with qa and qc to be compatible with the
prism and pyramid triangular faces */
void Tri_Face_JacProj(Bndry *B){
register int i;
Element *E = B->elmt;
int face = B->face;
const int qa = E->qa, qb = E->qb, qc = E->qc;
Coord S;
double **da,**db,**dc,**dt;
double **D, *x, *y, *z, *xr, *xs, *yr, *ys, *zr, *zs;
Mode *v = E->getbasis()->vert;
D = dmatrix(0,9,0,QGmax*QGmax-1);
xr = D[0]; xs = D[1];
yr = D[2]; ys = D[3];
zr = D[4]; zs = D[5];
S.x = D[0]; x = D[6];
S.y = D[1]; y = D[7];
S.z = D[2]; z = D[8];
E->GetFaceCoord(face,&S);
E->InterpToFace1(face,S.x,x);
E->InterpToFace1(face,S.y,y);
E->InterpToFace1(face,S.z,z);
/* calculate derivatives */
E->getD(&da,&dt,&db,&dt,&dc,&dt);
/* calculate dx/dr */
dgemm('T','N',qa,qc,qa,1.0,*da,qa,x,qa,0.0,xr,qa);
for(i = 0; i < qc; ++i) dsmul(qa,1/v->c[i],xr+i*qa,1,xr+i*qa,1);
/* calculate dx/ds */
for(i = 0; i < qc; ++i) dvmul(qa,v[1].a,1,xr+i*qa,1,xs+i*qa,1);
dgemm('N','N',qa,qc,qc,1.0,x,qa,*dc,qc,1.0,xs,qa);
/* calculate dy/dr */
dgemm('T','N',qa,qc,qa,1.0,*da,qa,y,qa,0.0,yr,qa);
for(i = 0; i < qc; ++i) dsmul(qa,1/v->c[i],yr+i*qa,1,yr+i*qa,1);
/* calculate dy/ds */
for(i = 0; i < qc; ++i) dvmul(qa,v[1].a,1,yr+i*qa,1,ys+i*qa,1);
dgemm('N','N',qa,qc,qc,1.0,y,qa,*dc,qc,1.0,ys,qa);
/* calculate dz/dr */
dgemm('T','N',qa,qc,qa,1.0,*da,qa,z,qa,0.0,zr,qa);
for(i = 0; i < qc; ++i) dsmul(qa,1/v->c[i],zr+i*qa,1,zr+i*qa,1);
/* calculate dz/ds */
for(i = 0; i < qc; ++i) dvmul(qa,v[1].a,1,zr+i*qa,1,zs+i*qa,1);
dgemm('N','N',qa,qc,qc,1.0,z,qa,*dc,qc,1.0,zs,qa);
/* x = yr*zs - zr*ys*/
dvmul (qa*qc,yr,1,zs,1,x,1);
dvvtvm(qa*qc,zr,1,ys,1,x,1,x,1);
/* y = zr*xs - xr*zs*/
dvmul (qa*qc,zr,1,xs,1,y,1);
dvvtvm(qa*qc,xr,1,zs,1,y,1,y,1);
/* z = xr*ys - xs*yr*/
dvmul (qa*qc,xr,1,ys,1,z,1);
dvvtvm(qa*qc,xs,1,yr,1,z,1,z,1);
/* Surface Jacobean = sqrt(x^2 + y^2 + z^2) */
dvmul (qa*qc,x,1,x,1,B->sjac.p,1);
dvvtvp(qa*qc,y,1,y,1,B->sjac.p,1,B->sjac.p,1);
dvvtvp(qa*qc,z,1,z,1,B->sjac.p,1,B->sjac.p,1);
dvsqrt(qa*qc,B->sjac.p,1,B->sjac.p,1);
free_dmatrix(D,0,0);
}
#if 0
// only needed for explicit codes -- generate normals at Gauss points 'g'x'h'
void gen_face_normals(Element *E){
int i;
Bndry *Bc; // temporary bc
Bc = (Bndry*) calloc(1,sizeof(Bndry));
Bc->elmt = E;
for(i=0;i<E->Nfaces;++i){
Bc->face = i;
E->Surface_geofac(Bc);
if(Bc->sjac.p){
// need to fix for variable order
E->face[i].sjac.p = dvector(0, E->lmax*E->lmax-1);
E->InterpToGaussFace(0, Bc->sjac.p, E->lmax, E->lmax, E->face[i].sjac.p);
free(Bc->sjac.p);
Bc->sjac.p = NULL;
E->face[i].nx.p = dvector(0, E->lmax*E->lmax-1);
E->InterpToGaussFace(0, Bc->nx.p, E->lmax, E->lmax, E->face[i].nx.p);
free(Bc->nx.p);
Bc->nx.p = NULL;
E->face[i].ny.p = dvector(0, E->lmax*E->lmax-1);
E->InterpToGaussFace(0, Bc->ny.p, E->lmax, E->lmax, E->face[i].ny.p);
free(Bc->ny.p);
Bc->ny.p = NULL;
E->face[i].nz.p = dvector(0, E->lmax*E->lmax-1);
E->InterpToGaussFace(0, Bc->nz.p, E->lmax, E->lmax, E->face[i].nz.p);
free(Bc->nz.p);
Bc->nz.p = NULL;
}
else{
E->face[i].sjac.d = Bc->sjac.d;
E->face[i].nx.d = Bc->nx.d;
E->face[i].ny.d = Bc->ny.d;
E->face[i].nz.d = Bc->nz.d;
}
}
}
#endif
void gen_ellipse(Element *E, Curve *cur, double *x, double *y){
int i;
double x0 = cur->info.ellipse.xo;
double y0 = cur->info.ellipse.yo;
double rmin = cur->info.ellipse.rmin;
double rmaj = cur->info.ellipse.rmaj;
Coord X;
X.x = dvector(0, QGmax-1);
X.y = dvector(0, QGmax-1);
double *xa = dvector(0, QGmax-1);
double *ya = dvector(0, QGmax-1);
E->straight_edge(&X, cur->face);
E->InterpToFace1(cur->face, X.x, xa);
E->InterpToFace1(cur->face, X.y, ya);
double t0=0., t1=0.;
#if 1
t0 = atan2((ya[0]-y0)*rmin, (xa[0]-x0)*rmaj);
t1 = atan2((ya[E->qa-1]-y0)*rmin, (xa[E->qa-1]-x0)*rmaj);
if(E->id == 162 || E->id == 387 || E->id == 445)
fprintf(stderr, "id: %d t0: %lf t1: %lf\n", E->id+1,t0, t1);
#endif
double t;
double *z, *w;
getzw(E->qa, &z, &w, 'a');
if(t0 > 0 && t1 < 0){
for(i=0;i<E->qa;++i){
t = 0.5*(1-z[i])*t0 + 0.5*(1+z[i])*(t1+2.*M_PI);
x[i] = x0 + rmaj*cos(t);
y[i] = y0 + rmin*sin(t);
if(E->id == 162 || E->id == 387 || E->id == 445)
fprintf(stderr, "id: %d t: %lf x[%lf],y[%lf]\n", E->id+1, t, x[i] , y[i]);
}
}
else if(t0 < 0 && t1 > 0){
for(i=0;i<E->qa;++i){
t = 0.5*(1-z[i])*(t0+2.*M_PI) + 0.5*(1+z[i])*t1;
x[i] = x0 + rmaj*cos(t);
y[i] = y0 + rmin*sin(t);
if(E->id == 162 || E->id == 387 || E->id == 445)
fprintf(stderr, "id: %d t: %lf x[%lf],y[%lf]\n", E->id+1, t, x[i] , y[i]);
}
}
else{
for(i=0;i<E->qa;++i){
t = 0.5*(1-z[i])*t0 + 0.5*(1+z[i])*t1;
x[i] = x0 + rmaj*cos(t);
y[i] = y0 + rmin*sin(t);
if(E->id == 162 || E->id == 387 || E->id == 445)
fprintf(stderr, "id: %d t: %lf x[%lf],y[%lf]\n", E->id+1,t, x[i] , y[i]);
}
}
free(xa); free(ya);
free(X.x); free(X.y);
return;
}
void gen_sin(Element *E, Curve *cur, double *x, double *y){
int i;
double x0 = cur->info.sin.xo;
double y0 = cur->info.sin.yo;
double A = cur->info.sin.amp;
double lambda = cur->info.sin.wavelength;
Coord X;
double *xa = dvector(0, QGmax-1);
double *ya = dvector(0, QGmax-1);
X.x = xa; X.y =ya;
E->straight_edge(&X, cur->face);
E->InterpToFace1(cur->face, X.x, x);
for(i=0;i<E->qa;++i)
y[i] = y0+A*sin(2.*M_PI*(x[i]-x0)/lambda);
free(xa); free(ya);
return;
}
/*******************************************************************/
void fillM(double **coord, double **d_dv, double **d_dw, double **d_dvdw, int i,int j, double **M);
void genFree(Curve *curve, double *x, double *y, double *z, char dir1, char dir2, int qa, int qb){
//first 3 members of x,y,z contains coordinates of vertises
int nvc,nwc,nvert,vert,i,j;
double *xyz_vert, **vw;
double *za,*zb,*w; // quadrature points
double xs,ys; // local standard coordinate system
double nu1,nu2; // collapsed coordinate system
double vq,wq; // coordinates in parametric space
double delta_1,delta_2;
nvc = curve->info.free.nvc;
nwc = curve->info.free.nwc;
nvert = 3; // assume triangle
if (nvert == 4){ //modify it later - nvert should be a parameter
printf("projection of quadratic face on curved boundary is not implemented \n");
exit(-1);
}
xyz_vert = dvector(0,nvert-1);
vw = dmatrix(0,2,0,1);
// get coordinates of vertices in parametric coordinate system
for (vert = 0; vert < nvert; vert++){
xyz_vert[0] = x[vert];
xyz_vert[1] = y[vert];
xyz_vert[2] = z[vert];
curve->info.free.get_vw_safe(xyz_vert,vw[vert]);
}
/* in a case of periodic boundary - fix elements that
are crossed by periodic interface */
if (curve->info.free.Vperiodic == 1){
delta_1 = fabs(vw[0][0]-vw[1][0]);
delta_2 = fabs(vw[1][0]-vw[2][0]);
delta_1 = ( (delta_1 > delta_2) ? delta_1 : delta_2 );
if (delta_1 > (0.5*nwc) ){
for (i = 0; i < 3; i++){
if ( vw[i][0] < (0.5*nwc))
vw[i][0] = vw[i][0]+(-1.0+nwc);
}
}
}
if (curve->info.free.Wperiodic == 1){
delta_1 = fabs(vw[0][1]-vw[1][1]);
delta_2 = fabs(vw[1][1]-vw[2][1]);
delta_1 = ( (delta_1 > delta_2) ? delta_1 : delta_2 );
if (delta_1 > (0.5*nvc) ){
for (i = 0; i < 3; i++){
if ( vw[i][1] < (0.5*nvc))
vw[i][1] = vw[i][1]+(-1.0+nvc);
}
}
}
//project all quadrature points on the face
switch (dir1){
case 'a':
getzw(qa,&za,&w,'a');
break;
case 'b':
getzw(qa,&za,&w,'b');
break;
case 'c':
getzw(qa,&za,&w,'c');
break;
}
switch (dir2){
case 'a':
getzw(qb,&zb,&w,'a');
break;
case 'b':
getzw(qb,&zb,&w,'b');
break;
case 'c':
getzw(qb,&zb,&w,'c');
break;
}
for (j = 0; j < qb; j++){
nu2 = zb[j];
for (i = 0; i < qa; i++){
nu1 = za[i];
//transform from collapsed coordinate system to original xy
//step 1
//transform from collapsed coordinate system to standard element coord.
xs = 0.5*(nu1+1.0)*(1.0-nu2)-1.0;
ys = nu2;
//step 2
//transforms from standard element coordinate sysstem to original xy
wq = vw[0][1]*(-ys-xs)+vw[1][1]*(1.0+xs)+vw[2][1]*(1.0+ys);
wq *= 0.5;
vq = vw[0][0]*(-ys-xs)+vw[1][0]*(1.0+xs)+vw[2][0]*(1.0+ys);
vq *= 0.5;
curve->info.free.interpolate2d(vq,wq,xyz_vert); // temporary use of array xyz_vert
x[i+qa*j] = xyz_vert[0];
y[i+qa*j] = xyz_vert[1];
z[i+qa*j] = xyz_vert[2];
}
}
free(xyz_vert);
free_dmatrix(vw,0,0);
return;
}
void C_Free::get_vw_safe(double *xyz,double *vw){
int return_flag = 0, iter, MAX_iter_vw = 30;
double Tol_vw = 1.0e-8;
double delta_vw = 0.95;
double error;
int Npoints1d = 6;
/* start from 2D Newton-Raphson */
return_flag = get_vw(xyz,vw);
if (return_flag == 0) return;
/* 2D Newton-Raphson failed to converge */
/* find v,w by 2D refining */
for (iter = 0; iter < MAX_iter_vw; ++iter){
return_flag = get_vw(xyz,vw,delta_vw,Npoints1d,&error);
if (return_flag == 0 && error < Tol_vw) break;
delta_vw *= 0.55;
}
//fprintf(stderr,"iter = %d error = %e\n",iter,error);
}
int C_Free::get_vw(double *xyz,double *vw){
/* projects point(x,y,z) onto surface and
returns vw coordinates and new x,y,z coordinate */
double Tol = 1.0e-8;
int i,j,Imin,Jmin;
double *xyz_0,*xyz_1;
double t;
double dx,dy,dz,dr;
double dnvc_m1,dnwc_m1;
dnvc_m1 = (double) nvc - 1.0;
dnwc_m1 = (double) nwc - 1.0;
xyz_0 = dvector(0,2);
xyz_1 = dvector(0,2);
/* first guess */
for (i = 0; i < 3; i++)
xyz_0[i] = xyz[i];
/* find closest point point from coordXYZ */
t = 1000000.0;
for (i = 0; i < nvc; i++){
for (j = 0; j < nwc; j++){
dx = xyz[0]-coordX[i][j];
dy = xyz[1]-coordY[i][j];
dz = xyz[2]-coordZ[i][j];
dr = sqrt(dx*dx+dy*dy+dz*dz);
if (dr < t){
Imin = i;
Jmin = j;
t = dr;
/* if closest point that defines the surface coinsides
with xyz - exit */
if (dr < Tol){
vw[0] = 1.0*j;
vw[1] = 1.0*i;
free(xyz_0);
free(xyz_1);
return 0;
}
}
}
}
if (Jmin == (nwc-1) )
Jmin--;
if (Imin == (nvc-1) )
Imin--;
/* Newton Rapson */
int iter;
double *vw_closest_pnt,*vw_0,*vw_n,**Jac,**invJac,*F_0;
double *dXvw,*dYvw,*dZvw;
double vw_first_closest_pnt[2];
double error,error_save,error_save_closest_pnt;
vw_closest_pnt = dvector(0,1);
vw_0 = dvector(0,1);
vw_n = dvector(0,1);
dXvw = dvector(0,1);
dYvw = dvector(0,1);
dZvw = dvector(0,1);
F_0 = dvector(0,1);
Jac = dmatrix(0,1,0,1);
invJac = dmatrix(0,1,0,1);
/* first guesses */
vw_0[0] = (double) Jmin; vw_0[1] = (double) Imin;
vw[0] = vw_0[0];
vw[1] = vw_0[1];
vw_first_closest_pnt[0] = vw[0];
vw_first_closest_pnt[1] = vw[1];
interpolate_dvw_2d(vw_0[0],vw_0[1], xyz_1, dXvw, dYvw, dZvw);
dx = xyz_1[0]-xyz_0[0];
dy = xyz_1[1]-xyz_0[1];
dz = xyz_1[2]-xyz_0[2];
if (fabs(dx) < 0.1*Tol)
dx = 0.1*Tol;
if (fabs(dy) < 0.1*Tol)
dy = 0.1*Tol;
if (fabs(dz) < 0.1*Tol)
dz = 0.1*Tol;
// F_0[0] = dx*dx+dy*dy;
// F_0[1] = dy*dy+dz*dz;
for (i = 0; i < 2; i++)
F_0[i] = (xyz_1[i]-xyz_0[i])*(xyz_1[i]-xyz_0[i])+(xyz_1[i+1]-xyz_0[i+1])*(xyz_1[i+1]-xyz_0[i+1]);
error = sqrt(0.5*(F_0[0]*F_0[0]+F_0[1]*F_0[1]));
if (error < Tol){
vw[0] = vw_0[0];
vw[1] = vw_0[1];
error_save = error;
goto clean_and_return;
}
error_save_closest_pnt = error;
//printf("error_save_closest_pnt = %e \n",error);
//printf("vw_0[0] = %f vw_0[1] = %f \n",vw_0[0],vw_0[1]);
//printf("xyz_1[0] = %f xyz_1[1] = %f xyz_1[2] = %f \n",xyz_1[0],xyz_1[1],xyz_1[2]);
vw_closest_pnt[0] = vw_0[0];
vw_closest_pnt[1] = vw_0[1];
error_save = 1000000.0;
for (iter = 0; iter < 20; iter++){
//printf("iteration = %d \n",iter);
/* fill Jacobian */
dx = xyz_1[0]-xyz_0[0];
dy = xyz_1[1]-xyz_0[1];
dz = xyz_1[2]-xyz_0[2];
/*
if (fabs(dx) < 0.1*Tol)
dx = 0.1*Tol;
if (fabs(dy) < 0.1*Tol)
dy = 0.1*Tol;
if (fabs(dz) < 0.1*Tol)
dz = 0.1*Tol;
*/
#if 0
Jac[0][0] = 2.0*dx*dXvw[0]+2.0*dy*dYvw[0];
Jac[0][1] = 2.0*dx*dXvw[1]+2.0*dy*dYvw[1];
Jac[1][0] = 2.0*dy*dYvw[0]+2.0*dz*dZvw[0];
Jac[1][1] = 2.0*dy*dYvw[1]+2.0*dz*dZvw[1];
#else
Jac[0][0] = 2.0*(xyz_1[0]-xyz_0[0])*dXvw[0]+2.0*(xyz_1[1]-xyz_0[1])*dYvw[0];
Jac[0][1] = 2.0*(xyz_1[0]-xyz_0[0])*dXvw[1]+2.0*(xyz_1[1]-xyz_0[1])*dYvw[1];
Jac[1][0] = 2.0*(xyz_1[1]-xyz_0[1])*dYvw[0]+2.0*(xyz_1[2]-xyz_0[2])*dZvw[0];
Jac[1][1] = 2.0*(xyz_1[1]-xyz_0[1])*dYvw[1]+2.0*(xyz_1[2]-xyz_0[2])*dZvw[1];
#endif
//printf("dXvw: %f %f \n ",dXvw[0],dXvw[1]);
//printf("dYvw: %f %f \n ",dYvw[0],dYvw[1]);
//printf("dZvw: %f %f \n ",dZvw[0],dZvw[1]);
//printf("Jac[(0,0) (0,1)]: %f %f \n ",Jac[0][0],Jac[0][1]);
//printf("Jac[(1,0) (1,1)]: %f %f \n ",Jac[1][0],Jac[1][1]);
/* invert Jacobian */
#if 0
error = (Jac[0][0]*Jac[1][1]-Jac[1][0]*Jac[0][1]); // temporary use of var. error
if (fabs(error) < 1.0e-12)
error = 1.0e-12;
error = 1.0/error;
#else
error = (Jac[0][0]*Jac[1][1]-Jac[1][0]*Jac[0][1]); // temporary use of var. error
if (fabs(error) < 1.0e-12){
error_save = 10000.0;
//fprintf(stderr,"get_vw: det|Jac| is close to zero \n");
vw_0[0] = vw[0] = vw_first_closest_pnt[0];
vw_0[1] = vw[1] = vw_first_closest_pnt[1];
goto clean_and_return;
}
else
error = 1.0/error; // temporary use of var. error
#endif
invJac[0][0] = error*Jac[1][1];
invJac[0][1] = -error*Jac[0][1];
invJac[1][0] = -error*Jac[1][0];
invJac[1][1] = error*Jac[0][0];
vw_n[0] = invJac[0][0]*F_0[0]+invJac[0][1]*F_0[1];
vw_n[1] = invJac[1][0]*F_0[0]+invJac[1][1]*F_0[1];
//printf("vw_n[0] = %f vw_n[1] = %f \n",vw_n[0],vw_n[1]);
/* update previous result */
for (i = 0; i < 2; i++)
vw_0[i] = vw_0[i]-vw_n[i];
/* keep v and w inside the domain */
if (Vperiodic == 0){
vw_0[0] = ( (vw_0[0] > 0.0) ? vw_0[0] : 0.0); //MAX(vw[0],0.0);
vw_0[0] = ( (vw_0[0] < dnwc_m1) ? vw_0[0] : dnwc_m1); //MIN(vw_0[0],dnvc_m1);
}
else{
while (vw_0[0] < 0.0 || vw_0[0] > dnwc_m1){
if (vw_0[0] < 0.0)
vw_0[0] = dnwc_m1+vw_0[0];
if (vw_0[0] > dnwc_m1)
vw_0[0] = vw_0[0]- dnwc_m1;
// printf("Vperiodic: vw_0[0] = %e \n",vw_0[0]);
}
}
if (Wperiodic == 0){
vw_0[1] = ( (vw_0[1] > 0.0) ? vw_0[1] : 0.0); //MAX(vw[1],0.0);
vw_0[1] = ( (vw_0[1] < dnvc_m1) ? vw_0[1] : dnvc_m1); //MIN(vw_0[1],dnwc_m1);
}
else{
while (vw_0[1] < 0.0 || vw_0[1] > dnvc_m1){
if (vw_0[1] < 0.0)
vw_0[1] = dnvc_m1+vw_0[1];
if (vw_0[1] > dnvc_m1)
vw_0[1] = vw_0[1]- dnvc_m1;
printf("Wperiodic: vw_0[1] = %e \n",vw_0[1]);
}
}
//printf("vw_0[0] = %f vw_0[1] = %f \n",vw_0[0],vw_0[1]);
interpolate_dvw_2d(vw_0[0],vw_0[1], xyz_1, dXvw, dYvw, dZvw);
//printf("xyz_1[0] = %f xyz_1[1] = %f xyz_1[2] = %f \n",xyz_1[0],xyz_1[1],xyz_1[2]);
for (i = 0; i < 2; i++)
F_0[i] = (xyz_1[i]-xyz_0[i])*(xyz_1[i]-xyz_0[i])+(xyz_1[i+1]-xyz_0[i+1])*(xyz_1[i+1]-xyz_0[i+1]);
/* estimate error */
error = sqrt(0.5*(F_0[0]*F_0[0]+F_0[1]*F_0[1]));
// printf("error = %e \n",error);
/* save the best result */
if (error_save > error){
for (i = 0; i < 3; i++)
xyz[i] = xyz_1[i];
vw[0] = vw_0[0];
vw[1] = vw_0[1];
error_save = error;
}
if (error < Tol)
break;
}
/* analyze error */
if (error_save > 3.0e-1){
if (error_save_closest_pnt < error_save){
vw[0] = vw_closest_pnt[0];
vw[1] = vw_closest_pnt[1];
error_save = error_save_closest_pnt;
interpolate_dvw_2d(vw[0],vw[1], xyz, dXvw, dYvw, dZvw);
}
}
clean_and_return:
//printf("error_save = %e vw = [%e %e]\n",error_save,vw[0],vw[1]);
free(vw_closest_pnt);
free(vw_0);
free(vw_n);
free(dXvw);
free(dYvw);
free(dZvw);
free_dmatrix(Jac,0,0);
free_dmatrix(invJac,0,0);
if (error_save < 10.0*Tol)
return 0;
else{
xyz[0] = xyz_0[0];
xyz[1] = xyz_0[1];
xyz[2] = xyz_0[2];
return 1;
}
}
int C_Free::get_vw(double *xyz,double *vw, double range, int Npoints, double *error){
int i,j;
double *v,*w,*xyz_temp,*xyz_save;
double error_ref,error_init,dx,dy,dz;
double dnvc_m1,dnwc_m1;
dnvc_m1 = (double) nvc - 1.0;
dnwc_m1 = (double) nwc - 1.0;
v = new double[Npoints*2];
w = v+Npoints;
xyz_temp = new double[6];
xyz_save = xyz_temp+3;
v[0] = vw[0]-range;
v[Npoints-1] = vw[0]+range;
if ( Vperiodic == 0){
v[0] = ( (v[0] > 0.0) ? v[0] : 0.0); //MAX(vw[0],0.0);
v[0] = ( (v[0] < dnwc_m1) ? v[0] : dnwc_m1); //MIN(vw_0[0],dnwc_m1);
v[Npoints-1] = ( (v[Npoints-1] > 0.0) ? v[Npoints-1] : 0.0); //MAX(vw[0],0.0);
v[Npoints-1] = ( (v[Npoints-1] < dnwc_m1) ? v[Npoints-1] : dnwc_m1); //MIN(vw_0[0],dnwc_m1);
}
w[0] = vw[1]-range;
w[Npoints-1] = vw[1]+range;
if (Wperiodic == 0){
w[0] = ( (w[0] > 0.0) ? w[0] : 0.0); //MAX(vw[0],0.0);
w[0] = ( (w[0] < dnvc_m1) ? w[0] : dnvc_m1); //MIN(vw_0[0],dnvc_m1);
w[Npoints-1] = ( (w[Npoints-1] > 0.0) ? w[Npoints-1] : 0.0); //MAX(vw[0],0.0);
w[Npoints-1] = ( (w[Npoints-1] < dnvc_m1) ? w[Npoints-1] : dnvc_m1); //MIN(vw_0[0],dnvc_m1);
}
dx = (v[Npoints-1]-v[0])/(-1.0+Npoints);
for (i = 1; i < Npoints; ++i)
v[i] = v[0]+dx*i;
dx = (w[Npoints-1]-w[0])/(-1.0+Npoints);
for (i = 1; i < Npoints; ++i)
w[i] = w[0]+dx*i;
//fprintf(stderr,"vw = [%f %f], range v = [%f %f],range w = [%f %f]\n", vw[0],vw[1],v[0],v[Npoints-1],w[0],w[Npoints-1]);
interpolate2d(vw[0],vw[1],xyz_temp);
dx = xyz_temp[0]-xyz[0];
dy = xyz_temp[1]-xyz[1];
dz = xyz_temp[2]-xyz[2];
error_ref = sqrt(dx*dx+dy*dy+dz*dz);
error_init = error_ref;
for (i = 0; i < Npoints; ++i){
for (j = 0; j < Npoints; ++j){
interpolate2d(v[i],w[j],xyz_temp);
dx = xyz_temp[0]-xyz[0];
dy = xyz_temp[1]-xyz[1];
dz = xyz_temp[2]-xyz[2];
error[0] = sqrt(dx*dx+dy*dy+dz*dz);
//fprintf(stderr,"v = %f w = %f error = %f \n",v[i],w[j],error[0]);
if (error[0] < error_ref){
vw[0] = v[i];
vw[1] = w[j];
error_ref=error[0];
}
}
}
delete[] v;
delete[] xyz_temp;
//fprintf(stderr,"error_init = %e, error_refin = %e \n",error_init,error[0]);
if (error[0] < error_init)
return 0;
else
return 1;
}
void C_Free::interpolate_dvw_2d(double v1, double w1, double *xyz, double *dXvw, double *dYvw, double *dZvw){
/* r(v,w) = [1 v v^2 v^3]*C*M*CT*[1 w w^2 w^3]' */
int i,j;
double *ANS1, *ANS2, **Mtemp;
ANS1 = dvector(0,3);
ANS2 = dvector(0,3);
Mtemp = dmatrix(0,3,0,3);
/* global coordinates */
vg = v1;
wg = w1;
/* cell number */
i = (int) wg;
j = (int) vg;
if (i >= (nvc-1) )
i--;
if (j >= (nwc-1) )
j--;
/* if CMCT was computed for different cell than recompute it */
/* else - do nothing - use existing CMCT */
//if (i==Icell && j==Jcell)
// i=i;
//else{
if (i != Icell || j != Jcell){
fillM(coordX,dx_dv,dx_dw,dx_dvdw,i,j,M);
dgemm('T', 'T', 4, 4, 4, 1.0, *C, 4, *M, 4, 0.0, *Mtemp, 4);
dgemm('N', 'T', 4, 4, 4, 1.0, *CT, 4, *Mtemp, 4, 0.0, *CMCTx, 4);
;
fillM(coordY,dy_dv,dy_dw,dy_dvdw,i,j,M);
dgemm('T', 'T', 4, 4, 4, 1.0, *C, 4, *M, 4, 0.0, *Mtemp, 4);
dgemm('N', 'T', 4, 4, 4, 1.0, *CT, 4, *Mtemp, 4, 0.0, *CMCTy, 4);
fillM(coordZ,dz_dv,dz_dw,dz_dvdw,i,j,M);
dgemm('T', 'T', 4, 4, 4, 1.0, *C, 4, *M, 4, 0.0, *Mtemp, 4);
dgemm('N', 'T', 4, 4, 4, 1.0, *CT, 4, *Mtemp, 4, 0.0, *CMCTz, 4);
Icell = i;
Jcell = j;
}
/* local coordinates */
vl = vg - ( (double) j);
wl = wg - ( (double) i);
V[0] = 1.0; V[1] = vl; V[2] = vl*vl; V[3] = vl*vl*vl;
W[0] = 1.0; W[1] = wl; W[2] = wl*wl; W[3] = wl*wl*wl;
/* compute coordinates x,y,z */
dgemv('T',4,4,1.0,*CMCTx,4,W,1,0.0,ANS1,1);
xyz[0] = ddot(4,V,1,ANS1,1);
dgemv('T',4,4,1.0,*CMCTy,4,W,1,0.0,ANS1,1);
xyz[1] = ddot(4,V,1,ANS1,1);
dgemv('T',4,4,1.0,*CMCTz,4,W,1,0.0,ANS1,1);
xyz[2] = ddot(4,V,1,ANS1,1);
/* compute partial derivatives */
/* d / dv */
V[0] = 0.0; V[1] = 1.0; V[2] = 2.0*vl; V[3] = 3.0*vl*vl;
dgemv('T',4,4,1.0,*CMCTx,4,W,1,0.0,ANS1,1);
dXvw[0] = ddot(4,V,1,ANS1,1);
dgemv('T',4,4,1.0,*CMCTy,4,W,1,0.0,ANS1,1);
dYvw[0] = ddot(4,V,1,ANS1,1);
dgemv('T',4,4,1.0,*CMCTz,4,W,1,0.0,ANS1,1);
dZvw[0] = ddot(4,V,1,ANS1,1);
/* d / dw */
V[0] = 1.0; V[1] = vl; V[2] = vl*vl; V[3] = vl*vl*vl;
W[0] = 0.0; W[1] = 1.0; W[2] = 2.0*wl; W[3] = 3.0*wl*wl;
dgemv('T',4,4,1.0,*CMCTx,4,W,1,0.0,ANS1,1);
dXvw[1] = ddot(4,V,1,ANS1,1);
dgemv('T',4,4,1.0,*CMCTy,4,W,1,0.0,ANS1,1);
dYvw[1] = ddot(4,V,1,ANS1,1);
dgemv('T',4,4,1.0,*CMCTz,4,W,1,0.0,ANS1,1);
dZvw[1] = ddot(4,V,1,ANS1,1);
free(ANS1);
free(ANS2);
}
void C_Free::interpolate2d(double v1, double w1, double *xyz){
/* r(v,w) = [1 v v^2 v^3]*C*M*CT*[1 w w^2 w^3]' */
int i,j;
double *ANS1, *ANS2;
double dnvc_m1 = -1.0+nvc;
double dnwc_m1 = -1.0+nwc;
ANS1 = dvector(0,3);
ANS2 = dvector(0,3);
/* global coordinates */
vg = v1;
wg = w1;
/* keep v and w inside the domain */
if (Vperiodic == 0){
vg = ( (vg > 0.0) ? vg : 0.0); //MAX(vw[0],0.0);
vg = ( (vg < dnwc_m1) ? vg : dnwc_m1); //MIN(vw_0[0],dnvc_m1);
}
else{
if (vg < 0.0)
vg = dnwc_m1+vg;
if (vg > dnwc_m1)
vg = vg-dnwc_m1;
}
if (Wperiodic == 0){
wg = ( (wg > 0.0) ? wg : 0.0); //MAX(vw[1],0.0);
wg = ( (wg < dnvc_m1) ? wg : dnvc_m1); //MIN(vw_0[1],dnwc_m1);
}
else{
if (wg < 0.0)
wg = dnvc_m1+wg;
if (wg > dnvc_m1)
wg = wg- dnvc_m1;
}
/* cell number */
i = (int) wg;
j = (int) vg;
if (i >= (nvc-1) )
i--;
if (j >= (nwc-1) )
j--;
/* local coordinates */
vl = vg - ( (double) j);
wl = wg - ( (double) i);
V[0] = 1.0; V[1] = vl; V[2] = vl*vl; V[3] = vl*vl*vl;
W[0] = 1.0; W[1] = wl; W[2] = wl*wl; W[3] = wl*wl*wl;
fillM(coordX,dx_dv,dx_dw,dx_dvdw,i,j,M);
dgemv('T',4,4,1.0,*CT,4,W,1,0.0,ANS1,1);
dgemv('T',4,4,1.0,*M,4,ANS1,1,0.0,ANS2,1);
dgemv('T',4,4,1.0,*C,4,ANS2,1,0.0,ANS1,1);
xyz[0] = ddot(4,V,1,ANS1,1);
fillM(coordY,dy_dv,dy_dw,dy_dvdw,i,j,M);
dgemv('T',4,4,1.0,*CT,4,W,1,0.0,ANS1,1);
dgemv('T',4,4,1.0,*M,4,ANS1,1,0.0,ANS2,1);
dgemv('T',4,4,1.0,*C,4,ANS2,1,0.0,ANS1,1);
xyz[1] = ddot(4,V,1,ANS1,1);
fillM(coordZ,dz_dv,dz_dw,dz_dvdw,i,j,M);
dgemv('T',4,4,1.0,*CT,4,W,1,0.0,ANS1,1);
dgemv('T',4,4,1.0,*M,4,ANS1,1,0.0,ANS2,1);
dgemv('T',4,4,1.0,*C,4,ANS2,1,0.0,ANS1,1);
xyz[2] = ddot(4,V,1,ANS1,1);
free(ANS1);
free(ANS2);
}
void fillM(double **coord, double **d_dv, double **d_dw, double **d_dvdw, int i,int j, double **M){
M[0][0] = coord[i][j]; M[0][1] = coord[i+1][j]; M[0][2] = d_dw[i][j]; M[0][3] = d_dw[i+1][j];
M[1][0] = coord[i][j+1]; M[1][1] = coord[i+1][j+1]; M[1][2] = d_dw[i][j+1]; M[1][3] = d_dw[i+1][j+1];
M[2][0] = d_dv[i][j]; M[2][1] = d_dv[i+1][j]; M[2][2] = d_dvdw[i][j]; M[2][3] = d_dvdw[i+1][j];
M[3][0] = d_dv[i][j+1], M[3][1] = d_dv[i+1][j+1]; M[3][2] = d_dvdw[i][j+1]; M[3][3] = d_dvdw[i+1][j+1];
}
/*******************************************************************/
double crossprodmag(double *a, double *b)
{
double mag, c[3];
c[0] = a[1]*b[2] - a[2]*b[1];
c[1] = a[2]*b[0] - a[0]*b[2];
c[2] = a[0]*b[1] - a[1]*b[0];
mag = sqrt(c[0]*c[0] + c[1]*c[1] + c[2]*c[2]);
return mag;
}
void crossprod(double *a, double *b, double *c)
{
c[0] = a[1]*b[2] - a[2]*b[1];
c[1] = a[2]*b[0] - a[0]*b[2];
c[2] = a[0]*b[1] - a[1]*b[0];
return;
}
void unitcrossprod(double *a, double *b, double *c){
double inv_mag;
c[0] = a[1]*b[2] - a[2]*b[1];
c[1] = a[2]*b[0] - a[0]*b[2];
c[2] = a[0]*b[1] - a[1]*b[0];
inv_mag = 1.0/sqrt(c[0]*c[0] + c[1]*c[1] + c[2]*c[2]);
c[0] = c[0]*inv_mag;
c[1] = c[1]*inv_mag;
c[2] = c[2]*inv_mag;
return;
}
double blend(double r){
return r*r;
}
void superblend(double *ri, double **Q, double *P, double *r_blend ){
int i;
double rn, v0_Qi_P_s, v1_Qi_P_s, v2_Qi_P_s;
rn = 1.0-TOL_BLEND;
r_blend[0] = r_blend[1] = r_blend[2] = 0.0;
for ( i = 0; i < 3; ++i)
if ( ri[i] > rn ){
r_blend[i] = 1.0;
return;
}
v0_Qi_P_s = (Q[0][0]-P[0])*(Q[0][0]-P[0]) +
(Q[0][1]-P[1])*(Q[0][1]-P[1]) +
(Q[0][2]-P[2])*(Q[0][2]-P[2]);
v1_Qi_P_s = (Q[1][0]-P[0])*(Q[1][0]-P[0]) +
(Q[1][1]-P[1])*(Q[1][1]-P[1]) +
(Q[1][2]-P[2])*(Q[1][2]-P[2]);
v2_Qi_P_s = (Q[2][0]-P[0])*(Q[2][0]-P[0]) +
(Q[2][1]-P[1])*(Q[2][1]-P[1]) +
(Q[2][2]-P[2])*(Q[2][2]-P[2]);
if (ri[0] > TOL_BLEND)
r_blend[0] = ri[0]*ri[0] * ( ri[2]*ri[2]* v2_Qi_P_s/(v2_Qi_P_s+v0_Qi_P_s) + ri[1]*ri[1]*v1_Qi_P_s/(v1_Qi_P_s+v0_Qi_P_s) );
if (ri[1] > TOL_BLEND)
r_blend[1] = ri[1]*ri[1] * ( ri[0]*ri[0]* v0_Qi_P_s/(v0_Qi_P_s+v1_Qi_P_s) + ri[2]*ri[2]*v2_Qi_P_s/(v2_Qi_P_s+v1_Qi_P_s) );
if (ri[2] > TOL_BLEND)
r_blend[2] = ri[2]*ri[2] * ( ri[1]*ri[1]* v1_Qi_P_s/(v1_Qi_P_s+v2_Qi_P_s) + ri[0]*ri[0]*v0_Qi_P_s/(v0_Qi_P_s+v2_Qi_P_s) );
rn = 1.0/sqrt(r_blend[0] + r_blend[1] + r_blend[2]);
r_blend[0] *= rn;
r_blend[1] *= rn;
r_blend[2] *= rn;
}
void genRecon(Curve *curve, double *va, double *vb, double *vc, double *x, double *y, double *z, int q){
int i;
double ra, rb, rc, *vna, *vnb, *vnc, ta[3], tb[3], a[3],b[3],c[3];
double A, ma, mb, mc, blenda, blendb, blendc, totalblend, inv_totalblend;
double conta, contb, contc, tha, thb, thc;
double Nx, Ny, Nz , ka[3], kb[3], kc[3];
double qa[3], qb[3], qc[3];
double *P,*r_blend,*ri;
double **Q = dmatrix(0,2,0,2);
double MAXANGLE = dparam("DMAXANGLESUR");
P = dvector(0,8);
r_blend = P+3;
ri = P+6;
double N[3];
vna = curve->info.recon.vn0;
vnb = curve->info.recon.vn1;
vnc = curve->info.recon.vn2;
ta[0] = vb[0] - va[0];
ta[1] = vb[1] - va[1];
ta[2] = vb[2] - va[2];
tb[0] = vc[0] - va[0];
tb[1] = vc[1] - va[1];
tb[2] = vc[2] - va[2];
unitcrossprod(tb, ta, N);
tha = fabs(asin(crossprodmag(N, vna)));
thb = fabs(asin(crossprodmag(N, vnb)));
thc = fabs(asin(crossprodmag(N, vnc)));
if( (tha>MAXANGLE) || (thb >MAXANGLE) || (thc>MAXANGLE) )
{
ROOTONLY fprintf(stderr, "This may cause problem Angle(degree) between face normal and averaged normals %lf %lf %lf \n",
tha*180.0/M_PI, thb*180/M_PI, thc*180.0/M_PI);
return;
}
A = crossprodmag(ta, tb);
for(i=0;i<q; i++)
{
a[0] = x[i]-va[0];
a[1] = y[i]-va[1];
a[2] = z[i]-va[2];
b[0] = x[i]-vb[0];
b[1] = y[i]-vb[1];
b[2] = z[i]-vb[2];
c[0] = x[i]-vc[0];
c[1] = y[i]-vc[1];
c[2] = z[i]-vc[2];
ra = crossprodmag(b,c);
ra = ra/A;
rb = crossprodmag(c,a);
rb = rb/A;
rc = crossprodmag(a,b);
rc = rc/A;
Nx = vna[0]*ra + vnb[0]*rb + vnc[0]*rc;
Ny = vna[1]*ra + vnb[1]*rb + vnc[1]*rc;
Nz = vna[2]*ra + vnb[2]*rb + vnc[2]*rc;
conta = (va[0]-x[i])*Nx + (va[1]-y[i])*Ny + (va[2]-z[i])*Nz;
contb = (vb[0]-x[i])*Nx + (vb[1]-y[i])*Ny + (vb[2]-z[i])*Nz;
contc = (vc[0]-x[i])*Nx + (vc[1]-y[i])*Ny + (vc[2]-z[i])*Nz;
ka[0] = x[i] + conta*Nx;
ka[1] = y[i] + conta*Ny;
ka[2] = z[i] + conta*Nz;
kb[0] = x[i] + contb*Nx;
kb[1] = y[i] + contb*Ny;
kb[2] = z[i] + contb*Nz;
kc[0] = x[i] + contc*Nx;
kc[1] = y[i] + contc*Ny;
kc[2] = z[i] + contc*Nz;
conta = (va[0]-ka[0])*vna[0] + (va[1]-ka[1])*vna[1] + (va[2]-ka[2])*vna[2];
contb = (vb[0]-kb[0])*vnb[0] + (vb[1]-kb[1])*vnb[1] + (vb[2]-kb[2])*vnb[2];
contc = (vc[0]-kc[0])*vnc[0] + (vc[1]-kc[1])*vnc[1] + (vc[2]-kc[2])*vnc[2];
ma = conta/(1. + Nx*vna[0] + Ny*vna[1] + Nz*vna[2]) ;
mb = contb/(1. + Nx*vnb[0] + Ny*vnb[1] + Nz*vnb[2]) ;
mc = contc/(1. + Nx*vnc[0] + Ny*vnc[1] + Nz*vnc[2]) ;
qa[0] = ka[0] + ma*Nx;
qa[1] = ka[1] + ma*Ny;
qa[2] = ka[2] + ma*Nz;
qb[0] = kb[0] + mb*Nx;
qb[1] = kb[1] + mb*Ny;
qb[2] = kb[2] + mb*Nz;
qc[0] = kc[0] + mc*Nx;
qc[1] = kc[1] + mc*Ny;
qc[2] = kc[2] + mc*Nz;
blenda = blend(ra);
blendb = blend(rb);
blendc = blend(rc);
totalblend = blenda + blendb + blendc;
inv_totalblend = 1.0/totalblend;
#if 0
ri[0] = ra;
ri[1] = rb;
ri[2] = rc;
P[0] = x[i];
P[1] = y[i];
P[2] = z[i];
conta = (va[0]-x[i])*Nx + (va[1]-y[i])*Ny + (va[2]-z[i])*Nz;
contb = (vb[0]-x[i])*Nx + (vb[1]-y[i])*Ny + (vb[2]-z[i])*Nz;
contc = (vc[0]-x[i])*Nx + (vc[1]-y[i])*Ny + (vc[2]-z[i])*Nz;
Q[0][0] = va[0]-conta*Nx;
Q[0][1] = va[1]-conta*Ny;
Q[0][2] = va[2]-conta*Nz;
Q[1][0] = vb[0]-contb*Nx;
Q[1][1] = vb[1]-contb*Ny;
Q[1][2] = vb[2]-contb*Nz;
Q[2][0] = vc[0]-contc*Nx;
Q[2][1] = vc[1]-contc*Ny;
Q[2][2] = vc[2]-contc*Nz;
superblend(ri, Q, P, r_blend);
x[i] = r_blend[0]*qa[0] + r_blend[1]*qb[0] + r_blend[2]*qc[0];
y[i] = r_blend[0]*qa[1] + r_blend[1]*qb[1] + r_blend[2]*qc[1];
z[i] = r_blend[0]*qa[2] + r_blend[1]*qb[2] + r_blend[2]*qc[2];
// x[i] = r_blend[0]*Q[0][0] + r_blend[1]*Q[1][0] + r_blend[2]*Q[2][0];
// y[i] = r_blend[0]*Q[0][1] + r_blend[1]*Q[1][1] + r_blend[2]*Q[2][1];
// z[i] = r_blend[0]*Q[0][2] + r_blend[1]*Q[1][2] + r_blend[2]*Q[2][2];
#else
x[i] = (blenda*qa[0] + blendb*qb[0] + blendc*qc[0])*inv_totalblend;
y[i] = (blenda*qa[1] + blendb*qb[1] + blendc*qc[1])*inv_totalblend;
z[i] = (blenda*qa[2] + blendb*qb[2] + blendc*qc[2])*inv_totalblend;
#endif
}
free(P);
free_dmatrix(Q,0,0);
return;
}
/*******************************************************************/
#define c1 ( 0.29690)
#define c2 (-0.12600)
#define c3 (-0.35160)
#define c4 ( 0.28430)
#define c5 (-0.10360)
/* naca profile -- usage: naca t x returns points on naca 00 aerofoil of
thickness t at position x
to compile
cc -o naca naca.c -lm
*/
double Tri_naca(double L, double x, double t){
x = x/L;
if(L==0.)
return 0.;
// return 5.*t*L*(c1*sqrt(x)+ x*(c2 + x*(c3 + x*(c4 + c5*x))));
return 5.*t*L*(c1*sqrt(x)+ x*(c2 + x*(c3 + x*(c4 + c5*x))));
}
#undef c1
#undef c2
#undef c3
#undef c4
#undef c5
void Tri_genNaca(Element *E, Curve *curve, double *x, double *y){
int i;
Coord X;
X.x = dvector(0, QGmax-1);
X.y = dvector(0, QGmax-1);
E->GetFaceCoord(curve->face, &X);
dcopy(E->qa, X.x, 1, x, 1);
for(i=0;i<E->qa;++i){
y[i] = Tri_naca(curve->info.nac2d.length,
X.x[i]-curve->info.nac2d.xo,
curve->info.nac2d.thickness);
if(X.y[i] < curve->info.nac2d.yo)
y[i] = curve->info.nac2d.yo-y[i];
else
y[i] = curve->info.nac2d.yo+y[i];
}
free(X.x);
free(X.y);
}
#define distance(p1,p2) (sqrt((p2.x-p1.x)*(p2.x-p1.x)+(p2.y-p1.y)*(p2.y-p1.y)))
#define ITERNACA 1000
#define TOLNACA 1e-5
#define c1 ( 0.29690)
#define c2 (-0.12600)
#define c3 (-0.35160)
#define c4 ( 0.28430)
// #define c5 (-0.10150)
#define c5 (-0.10360)
/*all that follows is to set up a spline fitting routine from a data file*/
typedef struct geomf { /* Curve defined in a file */
int npts ; /* number of points */
int pos ; /* last confirmed position */
char *name ; /* File/curve name */
double *x, *y ; /* coordinates */
double *sx,*sy; /* spline coefficients */
double *arclen; /* arclen along the curve */
struct geomf *next ; /* link to the next */
} Geometry;
typedef struct vector { /* A 2-D vector */
double x, y ; /* components */
double length ; /* length */
} Vector;
#define _MAX_NC 1024 /* Points describing a curved side */
static int closest (Point p, Geometry *g);
static void bracket (double s[], double f[], Geometry *g, Point a,
Vector ap);
static Vector setVector (Point p1, Point p2);
static double searchGeom (Point a, Point p, Geometry *g),
brent (double s[], Geometry *g, Point a, Vector ap,
double tol);
static Geometry *lookupGeom (char *name),
*loadGeom (char *name);
static Geometry *geomlist;
static Point setPoint (double x, double y)
{
Point p;
p.x = x;
p.y = y;
return p;
}
static Vector setVector (Point p1, Point p2)
{
Vector v;
v.x = p2.x - p1.x;
v.y = p2.y - p1.y;
v.length = sqrt (v.x*v.x + v.y*v.y);
return v;
}
/* Compute the angle between the vector ap and the vector from a to
* a point s on the curv. Uses the small-angle approximation */
static double getAngle (double s, Geometry *g, Point a, Vector ap)
{
Point c;
Vector ac;
c = setPoint (splint(g->npts, s, g->arclen, g->x, g->sx),
splint(g->npts, s, g->arclen, g->y, g->sy));
ac = setVector(a, c);
return 1. - ((ap.x * ac.x + ap.y * ac.y) / (ap.length * ac.length));
}
/* Search for the named Geometry */
static Geometry *lookupGeom (char *name)
{
Geometry *g = geomlist;
while (g) {
if (strcmp(name, g->name) == 0)
return g;
g = g->next;
}
return (Geometry *) NULL;
}
/* Load a geometry file */
static Geometry *loadGeom (char *name){
const int verbose = option("verbose");
Geometry *g = (Geometry *) calloc (1, sizeof(Geometry));
char buf [BUFSIZ];
double tmp[_MAX_NC];
Point p1, p2, p3, p4;
FILE *fp;
register int i;
double xscal = dparam("XSCALE");
double yscal = dparam("YSCALE");
double xmove = dparam("XMOVE");
double ymove = dparam("YMOVE");
if (verbose > 1)
printf ("Loading geometry file %s...", name);
if ((fp = fopen(name, "r")) == (FILE *) NULL) {
fprintf (stderr, "couldn't find the curved-side file %s", name);
exit (-1);
}
while (fgets (buf, BUFSIZ, fp)) /* Read past the comments */
if (*buf != '#') break;
/* Allocate space for the coordinates */
g -> x = (double*) calloc (_MAX_NC, sizeof(double));
g -> y = (double*) calloc (_MAX_NC, sizeof(double));
strcpy (g->name = (char *) malloc (strlen(name)+1), name);
/* Read the coordinates. The first line is already in *
* the input buffer from the comment loop above. */
i = 0;
while (i <= _MAX_NC && sscanf (buf,"%lf%lf", g->x + i, g->y + i) == 2) {
i++;
if (!fgets(buf, BUFSIZ, fp)) break;
}
g->npts = i;
if(xmove) dsadd(g->npts,xmove,g->x,1,g->x,1);
if(ymove) dsadd(g->npts,ymove,g->y,1,g->y,1);
if(xscal) dscal(g->npts,xscal,g->x,1);
if(yscal) dscal(g->npts,yscal,g->y,1);
if (i < 2 ) error_msg (geometry file does not have enough points);
if (i > _MAX_NC) error_msg (geometry file has too many points);
if (verbose > 1) printf ("%d points", g->npts);
/* Allocate memory for the other quantities */
g->sx = (double*) calloc (g->npts, sizeof(double));
g->sy = (double*) calloc (g->npts, sizeof(double));
g->arclen = (double*) calloc (g->npts, sizeof(double));
/* Compute spline information for the (x,y)-coordinates. The vector "tmp"
is a dummy independent variable for the function x(eta), y(eta). */
tmp[0] = 0.;
tmp[1] = 1.;
dramp (g->npts, tmp, tmp + 1, tmp, 1);
spline (g->npts, 1.e30, 1.e30, tmp, g->x, g->sx);
spline (g->npts, 1.e30, 1.e30, tmp, g->y, g->sy);
/* Compute the arclength of the curve using 4 points per segment */
for (i = 0; i < (*g).npts-1; i++) {
p1 = setPoint (g->x[i], g->y[i] );
p2 = setPoint (splint (g->npts, i+.25, tmp, g->x, g->sx),
splint (g->npts, i+.25, tmp, g->y, g->sy));
p3 = setPoint (splint (g->npts, i+.75, tmp, g->x, g->sx),
splint (g->npts, i+.75, tmp, g->y, g->sy));
p4 = setPoint (g->x[i+1], g->y[i+1]);
g->arclen [i+1] = g->arclen[i] + distance (p1, p2) + distance (p2, p3) +
distance (p3, p4);
}
/* Now that we have the arclength, compute x(s), y(s) */
spline (g->npts, 1.e30, 1.e30, g->arclen, g->x, g->sx);
spline (g->npts, 1.e30, 1.e30, g->arclen, g->y, g->sy);
if (verbose > 1)
printf (", arclength = %f\n", g->arclen[i]);
/* add to the list of geometries */
g ->next = geomlist;
geomlist = g;
fclose (fp);
return g;
}
/*
* Find the point at which a line passing from the anchor point "a"
* through the search point "p" intersects the curve defined by "g".
* Always searches from the last point found to the end of the curve.
*/
static double searchGeom (Point a, Point p, Geometry *g)
{
Vector ap;
double tol = dparam("TOLCURV"), s[3], f[3];
register int ip;
/* start the search at the closest point */
ap = setVector (a, p);
s[0] = g -> arclen[ip = closest (p, g)];
s[1] = g -> arclen[ip + 1];
bracket (s, f, g, a, ap);
if (fabs(f[1]) > tol)
brent (s, g, a, ap, tol);
return s[1];
}
int id_min(int n, double *d, int skip);
/* --------------- Bracketing and Searching routines --------------- */
static int closest (Point p, Geometry *g)
{
const
double *x = g->x + g->pos,
*y = g->y + g->pos;
const int n = g->npts - g->pos;
double len[_MAX_NC];
register int i;
for (i = 0; i < n; i++)
len[i] = sqrt (pow(p.x - x[i],2.) + pow(p.y - y[i],2.));
i = id_min (n, len, 1) + g->pos;
i = min(i, g->npts-2);
/* If we found the same position and it's not the very first *
* one, start the search over at the beginning again. The *
* test for i > 0 makes sure we only do the recursion once. */
if (i && i == g->pos) { g->pos = 0; i = closest (p, g); }
return g->pos = i;
}
#define GOLD 1.618034
#define CGOLD 0.3819660
#define GLIMIT 100.
#define TINY 1.e-20
#define ZEPS 1.0e-10
#define ITMAX 100
#define SIGN(a,b) ((b) > 0. ? fabs(a) : -fabs(a))
#define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d);
#define SHFT2(a,b,c) (a)=(b);(b)=(c);
#define fa f[0]
#define fb f[1]
#define fc f[2]
#define xa s[0]
#define xb s[1]
#define xc s[2]
static void bracket (double s[], double f[], Geometry *g, Point a, Vector ap)
{
double ulim, u, r, q, fu;
fa = getAngle (xa, g, a, ap);
fb = getAngle (xb, g, a, ap);
if (fb > fa) { SHFT (u, xa, xb, u); SHFT (fu, fb, fa, fu); }
xc = xb + GOLD*(xb - xa);
fc = getAngle (xc, g, a, ap);
while (fb > fc) {
r = (xb - xa) * (fb - fc);
q = (xb - xc) * (fb - fa);
u = xb - ((xb - xc) * q - (xb - xa) * r) /
(2.*SIGN(max(fabs(q-r),TINY),q-r));
ulim = xb * GLIMIT * (xc - xb);
if ((xb - u)*(u - xc) > 0.) { /* Parabolic u is bewteen b and c */
fu = getAngle (u, g, a, ap);
if (fu < fc) { /* Got a minimum between b and c */
SHFT2 (xa,xb, u);
SHFT2 (fa,fb,fu);
return;
} else if (fu > fb) { /* Got a minimum between a and u */
xc = u;
fc = fu;
return;
}
u = xc + GOLD*(xc - xb); /* Parabolic fit was no good. Use the */
fu = getAngle (u, g, a, ap); /* default magnification. */
} else if ((xc-u)*(u-ulim) > 0.) { /* Parabolic fit is bewteen c */
fu = getAngle (u, g, a, ap); /* and ulim */
if (fu < fc) {
SHFT (xb, xc, u, xc + GOLD*(xc - xb));
SHFT (fb, fc, fu, getAngle(u, g, a, ap));
}
} else if ((u-ulim)*(ulim-xc) >= 0.) { /* Limit parabolic u to the */
u = ulim; /* maximum allowed value */
fu = getAngle (u, g, a, ap);
} else { /* Reject parabolic u */
u = xc + GOLD * (xc - xb);
fu = getAngle (u, g, a, ap);
}
SHFT (xa, xb, xc, u); /* Eliminate the oldest point & continue */
SHFT (fa, fb, fc, fu);
}
return;
}
/* Brent's algorithm for parabolic minimization */
static double brent (double s[], Geometry *g, Point ap, Vector app, double tol)
{
int iter;
double a,b,d,etemp,fu,fv,fw,fx,p,q,r,tol1,tol2,u,v,w,x,xm;
double e=0.0;
a = min (xa, xc); /* a and b must be in decending order */
b = max (xa, xc);
d = 1.;
x = w = v = xb;
fw = fv = fx = getAngle (x, g, ap, app);
for (iter = 1; iter <= ITMAX; iter++) { /* ....... Main Loop ...... */
xm = 0.5*(a+b);
tol2 = 2.0*(tol1 = tol*fabs(x)+ZEPS);
if (fabs(x-xm) <= (tol2-0.5*(b-a))) { /* Completion test */
xb = x;
return fx;
}
if (fabs(e) > tol1) { /* Construct a trial parabolic fit */
r = (x-w) * (fx-fv);
q = (x-v) * (fx-fw);
p = (x-v) * q-(x-w) * r;
q = (q-r) * 2.;
if (q > 0.) p = -p;
q = fabs(q);
etemp=e;
e = d;
/* The following conditions determine the acceptability of the */
/* parabolic fit. Following we take either the golden section */
/* step or the parabolic step. */
if (fabs(p) >= fabs(.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x))
d = CGOLD * (e = (x >= xm ? a-x : b-x));
else {
d = p / q;
u = x + d;
if (u-a < tol2 || b-u < tol2)
d = SIGN(tol1,xm-x);
}
} else
d = CGOLD * (e = (x >= xm ? a-x : b-x));
u = (fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d));
fu = getAngle(u,g,ap,app);
/* That was the one function evaluation per step. Housekeeping... */
if (fu <= fx) {
if (u >= x) a = x; else b = x;
SHFT(v ,w ,x ,u );
SHFT(fv,fw,fx,fu)
} else {
if (u < x) a=u; else b=u;
if (fu <= fw || w == x) {
v = w;
w = u;
fv = fw;
fw = fu;
} else if (fu <= fv || v == x || v == w) {
v = u;
fv = fu;
}
}
} /* .......... End of the Main Loop .......... */
error_msg(too many iterations in brent());
xb = x;
return fx;
}
#undef ITMAX
#undef CGOLD
#undef ZEPS
#undef SIGN
#undef fa
#undef fb
#undef fc
#undef xa
#undef xb
#undef xc
|
C
|
/*
You're going on a trip with some students and it's up to you to keep track of how much money each Student has. A student is defined like this:
#define NAMELIM 0x8
struct student {
char name[NAMELIM + 1];
unsigned fives;
unsigned tens;
unsigned twenties;
};
As you can tell, each Student has some fives, tens, and twenties. Your job is to return the name of the student with the most money. If every student has the same amount, then return "all".
Notes:
Each student will have a unique name
There will always be a clear winner: either one person has the most, or everyone has the same amount
If there is only one student, then that student has the most money
*/
#include <stdio.h>
#include <stddef.h>
#define NAMELIM 0x8
struct student
{
char name[NAMELIM+1];
unsigned fives;
unsigned tens;
unsigned twenties;
};
const char *most_money(const struct student *v, size_t n)
{
if (n == 1)
{
return v->name;
}
int maxMoneyIndex = 0;
unsigned maxMoney = 0;
unsigned currentMoney = 0;
unsigned countEqual = 1;
for (int i = 0; i < n; i++)
{
currentMoney = 5 * v[i].fives + 10 * v[i].tens + 20 * v[i].twenties;
if (currentMoney > maxMoney)
{
maxMoney = currentMoney;
maxMoneyIndex = i;
}
else if (currentMoney == maxMoney)
{
countEqual++;
}
else
{
// NOP
}
}
return (n == countEqual) ? "all" : v[maxMoneyIndex].name;
}
int main (int argv, char **argc)
{
const struct student guys[] =
{
{"Cameron",2,2,0},
{"Geoff",0,3,0},
{"Phil",2,2,1}
};
const struct student guys2[] =
{
{"Cameron",2,2,0},
{"Geoff",0,3,0},
};
const struct student guys3[] =
{
{"Phil",2,2,1}
};
const struct student guys4[] =
{
{ "Qzhs", 6, 7, 7 },
{ "Ghr", 3, 6, 7 },
{ "Sujosohn", 2, 7, 4 },
{ "Xqymhk", 7, 7, 0 },
{ "Hh", 1, 4, 5 },
{ "Waouhe", 0, 4, 3 },
{ "Lha", 2, 1, 7 },
{ "Efx", 2, 8, 5 },
{ "Dvwdfft", 3, 4, 0 },
{ "Qlsoffq", 0, 1, 1 },
{ "Kxjeidfm", 0, 0, 1 },
{ "Kfi", 2, 0, 4 },
{ "Tqzfh", 2, 1, 1 },
{ "Aff", 3, 6, 3 },
{ "Lrfd", 9, 0, 8 },
{ "Fa", 3, 4, 6 },
{ "Tedz", 5, 0, 6 },
{ "Xqddx", 7, 2, 4 },
{ "Cbrdv", 7, 1, 4 }
};
/*
printf("%s\n", most_money(guys, sizeof(guys) / sizeof(guys[0])));
printf("%s\n", most_money(guys2, sizeof(guys2) / sizeof(guys2[0])));
printf("%s\n", most_money(guys3, sizeof(guys3) / sizeof(guys3[0])));
printf("%s\n", most_money(guys4, sizeof(guys4) / sizeof(guys4[0])));
*/
struct student *p_guys = guys4;
printf("%s %u\n", p_guys->name, p_guys->fives);
printf("%s %u\n", (p_guys + 1)->name, (p_guys + 1)->fives);
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* helper.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: hben-yah <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/02/02 21:46:07 by hben-yah #+# #+# */
/* Updated: 2019/02/03 16:29:28 by hben-yah ### ########.fr */
/* */
/* ************************************************************************** */
#include "minitalk.h"
int
count_occurence(char *s)
{
char c;
int occ;
occ = 0;
c = s[occ++];
while (s[occ] && c == s[occ])
++occ;
occ = (occ < 256 ? occ : 255);
return (occ);
}
int
count_only_one_occurence(char *s)
{
int nb;
int occ;
nb = 0;
while (*s && nb < 256)
{
occ = count_occurence(s);
if (occ > 3)
return ((nb < 256 ? nb : 255));
nb += occ;
s += occ;
}
nb = (nb < 256 ? nb : 255);
return (nb);
}
size_t
encoded_text_length(char *s)
{
size_t len;
size_t sublen;
char mode;
size_t i;
len = 0;
mode = 0;
i = 0;
while (s[i])
{
mode = s[i++];
sublen = (unsigned char)s[i++];
i += (mode == 2 ? 1 : sublen);
len += sublen;
}
return (len);
}
t_sdata
*get_sdata(void)
{
static t_sdata *sdata;
if (!sdata)
try_m(sdata = (t_sdata *)ft_memalloc(sizeof(t_sdata)));
return (sdata);
}
t_connect
*get_connection(t_sdata *sdata, int pid)
{
t_connect *con;
con = sdata->con;
while (con && con->pid != pid)
con = con->next;
return (con);
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
char* retirarEspacos(char frase[]){
for(int i=0; frase[i] != '\0'; i++){
if (frase[i] == 32){
frase[i] = '\a';
}
}
return frase;
}
int main(){
char frase[256];
printf("Digite uma frase:\n");
fgets(frase, 255, stdin);
printf("\nFrase alterada:\n%s", retirarEspacos(frase));
return 0;
}
|
C
|
#include <stdio.h>
void reverse_string(char* string)
{
if (*string != 0)
{
reverse_string(string + 1);
}
//ȥ\0
string--;
printf("%c", *string);
}
int main()
{
char arr[] = "student";
int n;
reverse_string(arr);
return 0;
}
|
C
|
#include "../Ref/api.h"
#include "../Ref/params.h"
#include "stdio.h"
#include "stdint.h"
#include "string.h"
int main() {
int i;
uint8_t sk[NTRU_SECRETKEYBYTES];
uint8_t c[NTRU_CIPHERTEXTBYTES];
uint8_t k2[NTRU_SHAREDKEYBYTES];
unsigned int a;
char buffer[100];
char hex[2];
char name[64];
printf("---------------------------------ntruhrss701---------------------------------\n");
printf("Decapsulating ...\n");
FILE* fp = fopen("../report/secret_key.txt","r");
if (fp==NULL)
{
printf("Catching errors with secret_key.txt\n");
return(-1);
}
while(feof(fp) == 0)
{ /*read some data, lets process it.*/
/*extract individual values from the buffer*/
fgets(buffer, 100, fp);
sscanf(buffer, "%s", name);
if (strcmp(name, "Secret_key:") == 0) {
for (i = 0; i < NTRU_SECRETKEYBYTES; i++) {
fgets(hex, 3, fp);
sscanf(hex, "%02X", &a);
sk[i] = (uint8_t)a;
}
break;
}
}
fclose(fp);
FILE* ct_file_en = fopen("../report/SV_encaps.txt","r");
// FILE* ct_file_en = fopen("../report/ciphertext_after_encaps.txt","r");
if (ct_file_en==NULL)
{
printf("Catching errors with SV_encaps.txt\n");
return(-1);
}
while(feof(ct_file_en) == 0)
{ /*read some data, lets process it.*/
/*extract individual values from the buffer*/
fgets(buffer, 101, ct_file_en);
sscanf(buffer, "%s", name);
if (strcmp(name, "Ciphertext:") == 0) {
for (i = 0; i<NTRU_CIPHERTEXTBYTES; i++) {
fgets(hex, 3, fp);
sscanf(hex, "%02X", &a);
c[i] = (uint8_t)a;
}
break;
}
}
fclose(ct_file_en);
PQCLEAN_NTRUHRSS701_CLEAN_crypto_kem_dec(k2, c, sk);
FILE *ct_file_de = fopen("../report/ciphertext_before_decaps.txt", "w");
fprintf(ct_file_de,"Secret_key:\n");
for (i = 0; i < NTRU_SECRETKEYBYTES; i++) {
fprintf(ct_file_de,"%02X", sk[i]);
}
fprintf(ct_file_de,"\n______________________________________________________________________________________________________________________________________________________________________________________________\n\n");
fprintf(ct_file_de,"Ciphertext:\n");
for (i = 0; i < NTRU_CIPHERTEXTBYTES; i++) {
fprintf(ct_file_de,"%02X", c[i]);
}
fclose(ct_file_de);
FILE *shk_file = fopen("../report/shared_key_after_decaps.txt", "w");
fprintf(shk_file,"Shared_key:\n");
for (i = 0; i < NTRU_SHAREDKEYBYTES;i++) {
fprintf(shk_file,"%02X", k2[i]);
}
fprintf(shk_file,"\n");
fclose(shk_file);
printf("Done.\n");
}
|
C
|
/******************************************************************************/
#ifndef MEMORY_H
#include "MEMORY.h"
#endif
/******************************************************************************/
#ifndef GPIO_H
#include "GPIO.h"
#endif
/******************************************************************************/
#define PORT_ERROR 0X00
/******************************************************************************/
/* -------- Micro-controller C/C's ------- */
typedef enum{
PIN_OUTPUT = 0,
PIN_INPUT
}Pin_Direction_State_t;
typedef enum{
PIN_LOW = 0,
PIN_HIGH
}Pin_Value_State_t;
typedef enum{
PORT_OUTPUT = 0X00,
PORT_INPUT = 0XFF
}Port_Direction_State_t;
typedef struct{
Pin_Direction_State_t Pin0 : 1;
Pin_Direction_State_t Pin1 : 1;
Pin_Direction_State_t Pin2 : 1;
Pin_Direction_State_t Pin3 : 1;
Pin_Direction_State_t Pin4 : 1;
Pin_Direction_State_t Pin5 : 1;
Pin_Direction_State_t Pin6 : 1;
Pin_Direction_State_t Pin7 : 1;
}Pin_Direction_t;
typedef struct{
Pin_Value_State_t Pin0 : 1;
Pin_Value_State_t Pin1 : 1;
Pin_Value_State_t Pin2 : 1;
Pin_Value_State_t Pin3 : 1;
Pin_Value_State_t Pin4 : 1;
Pin_Value_State_t Pin5 : 1;
Pin_Value_State_t Pin6 : 1;
Pin_Value_State_t Pin7 : 1;
}Pin_Value_t;
/******************************************************************************/
void GPIO_SetPinDirection(const GPIO_Port_ID_t GPIO_PORT_ID,
const GPIO_Pin_ID_t GPIO_PIN_ID,
const GPIO_Direction_t GPIO_PIN_DIRECTION){
volatile Pin_Direction_t* Pin_Direction_Ptr;
switch(GPIO_PORT_ID){
case GPIO_PORTA:
Pin_Direction_Ptr = (volatile Pin_Direction_t*)PORTA_DIRECTION_ADDRESS;
break;
case GPIO_PORTB:
Pin_Direction_Ptr = (volatile Pin_Direction_t*)PORTB_DIRECTION_ADDRESS;
break;
case GPIO_PORTC:
Pin_Direction_Ptr = (volatile Pin_Direction_t*)PORTC_DIRECTION_ADDRESS;
break;
case GPIO_PORTD:
Pin_Direction_Ptr = (volatile Pin_Direction_t*)PORTD_DIRECTION_ADDRESS;
break;
case GPIO_PORTE:
Pin_Direction_Ptr = (volatile Pin_Direction_t*)PORTE_DIRECTION_ADDRESS;
break;
default:
/* Error: Undefined Port */
return;
}
switch(GPIO_PIN_ID){
case GPIO_PIN0:
if(GPIO_OUTPUT == GPIO_PIN_DIRECTION){
Pin_Direction_Ptr->Pin0 = PIN_OUTPUT;
}else if(GPIO_INPUT == GPIO_PIN_DIRECTION){
Pin_Direction_Ptr->Pin0 = PIN_INPUT;
}else{
/* Error : Undefined Direction */
Pin_Direction_Ptr->Pin0 = PIN_INPUT;
}
break;
case GPIO_PIN1:
if(GPIO_OUTPUT == GPIO_PIN_DIRECTION){
Pin_Direction_Ptr->Pin1 = PIN_OUTPUT;
}else if(GPIO_INPUT == GPIO_PIN_DIRECTION){
Pin_Direction_Ptr->Pin1 = PIN_INPUT;
}else{
/* Error : Undefined Direction */
Pin_Direction_Ptr->Pin1 = PIN_INPUT;
}
break;
case GPIO_PIN2:
if(GPIO_OUTPUT == GPIO_PIN_DIRECTION){
Pin_Direction_Ptr->Pin2 = PIN_OUTPUT;
}else if(GPIO_INPUT == GPIO_PIN_DIRECTION){
Pin_Direction_Ptr->Pin2 = PIN_INPUT;
}else{
/* Error : Undefined Direction */
Pin_Direction_Ptr->Pin2 = PIN_INPUT;
}
break;
case GPIO_PIN3:
if(GPIO_OUTPUT == GPIO_PIN_DIRECTION){
Pin_Direction_Ptr->Pin3 = PIN_OUTPUT;
}else if(GPIO_INPUT == GPIO_PIN_DIRECTION){
Pin_Direction_Ptr->Pin3 = PIN_INPUT;
}else{
/* Error : Undefined Direction */
Pin_Direction_Ptr->Pin3 = PIN_INPUT;
}
break;
case GPIO_PIN4:
if(GPIO_OUTPUT == GPIO_PIN_DIRECTION){
Pin_Direction_Ptr->Pin4 = PIN_OUTPUT;
}else if(GPIO_INPUT == GPIO_PIN_DIRECTION){
Pin_Direction_Ptr->Pin4 = PIN_INPUT;
}else{
/* Error : Undefined Direction */
Pin_Direction_Ptr->Pin4 = PIN_INPUT;
}
break;
case GPIO_PIN5:
if(GPIO_OUTPUT == GPIO_PIN_DIRECTION){
Pin_Direction_Ptr->Pin5 = PIN_OUTPUT;
}else if(GPIO_INPUT == GPIO_PIN_DIRECTION){
Pin_Direction_Ptr->Pin5 = PIN_INPUT;
}else{
/* Error : Undefined Direction */
Pin_Direction_Ptr->Pin5 = PIN_INPUT;
}
break;
case GPIO_PIN6:
if(GPIO_OUTPUT == GPIO_PIN_DIRECTION){
Pin_Direction_Ptr->Pin6 = PIN_OUTPUT;
}else if(GPIO_INPUT == GPIO_PIN_DIRECTION){
Pin_Direction_Ptr->Pin6 = PIN_INPUT;
}else{
/* Error : Undefined Direction */
Pin_Direction_Ptr->Pin6 = PIN_INPUT;
}
break;
case GPIO_PIN7:
if(GPIO_OUTPUT == GPIO_PIN_DIRECTION){
Pin_Direction_Ptr->Pin7 = PIN_OUTPUT;
}else if(GPIO_INPUT == GPIO_PIN_DIRECTION){
Pin_Direction_Ptr->Pin7 = PIN_INPUT;
}else{
/* Error : Undefined Direction */
Pin_Direction_Ptr->Pin7 = PIN_INPUT;
}
break;
default:
/* Error: Undefined Pin */
break;
}
}
void GPIO_SetPinValue(const GPIO_Port_ID_t GPIO_PORT_ID,
const GPIO_Pin_ID_t GPIO_PIN_ID,
const GPIO_PinValue_t GPIO_PIN_VALUE){
volatile Pin_Value_t* Pin_Value_Ptr;
switch(GPIO_PORT_ID){
case GPIO_PORTA:
Pin_Value_Ptr = (volatile Pin_Value_t*)PORTA_WRITE_ADDRESS;
break;
case GPIO_PORTB:
Pin_Value_Ptr = (volatile Pin_Value_t*)PORTB_WRITE_ADDRESS;
break;
case GPIO_PORTC:
Pin_Value_Ptr = (volatile Pin_Value_t*)PORTC_WRITE_ADDRESS;
break;
case GPIO_PORTD:
Pin_Value_Ptr = (volatile Pin_Value_t*)PORTD_WRITE_ADDRESS;
break;
case GPIO_PORTE:
Pin_Value_Ptr = (volatile Pin_Value_t*)PORTE_WRITE_ADDRESS;
break;
default:
/* Error: Undefined Port */
return;
}
switch(GPIO_PIN_ID){
case GPIO_PIN0:
if(GPIO_HIGH == GPIO_PIN_VALUE){
Pin_Value_Ptr->Pin0 = PIN_HIGH;
}else if(GPIO_LOW == GPIO_PIN_VALUE){
Pin_Value_Ptr->Pin0 = PIN_LOW;
}else{
/* Error: Undefined Value */
Pin_Value_Ptr->Pin0 = PIN_LOW;
}
break;
case GPIO_PIN1:
if(GPIO_HIGH == GPIO_PIN_VALUE){
Pin_Value_Ptr->Pin1 = PIN_HIGH;
}else if(GPIO_LOW == GPIO_PIN_VALUE){
Pin_Value_Ptr->Pin1 = PIN_LOW;
}else{
/* Error: Undefined Value */
Pin_Value_Ptr->Pin1 = PIN_LOW;
}
break;
case GPIO_PIN2:
if(GPIO_HIGH == GPIO_PIN_VALUE){
Pin_Value_Ptr->Pin2 = PIN_HIGH;
}else if(GPIO_LOW == GPIO_PIN_VALUE){
Pin_Value_Ptr->Pin2 = PIN_LOW;
}else{
/* Error: Undefined Value */
Pin_Value_Ptr->Pin2 = PIN_LOW;
}
break;
case GPIO_PIN3:
if(GPIO_HIGH == GPIO_PIN_VALUE){
Pin_Value_Ptr->Pin3 = PIN_HIGH;
}else if(GPIO_LOW == GPIO_PIN_VALUE){
Pin_Value_Ptr->Pin3 = PIN_LOW;
}else{
/* Error: Undefined Value */
Pin_Value_Ptr->Pin3 = PIN_LOW;
}
break;
case GPIO_PIN4:
if(GPIO_HIGH == GPIO_PIN_VALUE){
Pin_Value_Ptr->Pin4 = PIN_HIGH;
}else if(GPIO_LOW == GPIO_PIN_VALUE){
Pin_Value_Ptr->Pin4 = PIN_LOW;
}else{
/* Error: Undefined Value */
Pin_Value_Ptr->Pin4 = PIN_LOW;
}
break;
case GPIO_PIN5:
if(GPIO_HIGH == GPIO_PIN_VALUE){
Pin_Value_Ptr->Pin5 = PIN_HIGH;
}else if(GPIO_LOW == GPIO_PIN_VALUE){
Pin_Value_Ptr->Pin5 = PIN_LOW;
}else{
/* Error: Undefined Value */
Pin_Value_Ptr->Pin5 = PIN_LOW;
}
break;
case GPIO_PIN6:
if(GPIO_HIGH == GPIO_PIN_VALUE){
Pin_Value_Ptr->Pin6 = PIN_HIGH;
}else if(GPIO_LOW == GPIO_PIN_VALUE){
Pin_Value_Ptr->Pin6 = PIN_LOW;
}else{
/* Error: Undefined Value */
Pin_Value_Ptr->Pin6 = PIN_LOW;
}
break;
case GPIO_PIN7:
if(GPIO_HIGH == GPIO_PIN_VALUE){
Pin_Value_Ptr->Pin7 = PIN_HIGH;
}else if(GPIO_LOW == GPIO_PIN_VALUE){
Pin_Value_Ptr->Pin7 = PIN_LOW;
}else{
/* Error: Undefined Value */
Pin_Value_Ptr->Pin7 = PIN_LOW;
}
break;
default:
/* Error: Undefined Pin */
break;
}
}
GPIO_PinValue_t GPIO_ReadPinValue(const GPIO_Port_ID_t GPIO_PORT_ID,
const GPIO_Pin_ID_t GPIO_PIN_ID){
volatile Pin_Value_t* Pin_Value_Ptr;
GPIO_PinValue_t GPIO_PinValue = GPIO_HIGH;
switch(GPIO_PORT_ID){
case GPIO_PORTA:
Pin_Value_Ptr = (volatile Pin_Value_t*)PORTA_READ_ADDRESS;
break;
case GPIO_PORTB:
Pin_Value_Ptr = (volatile Pin_Value_t*)PORTB_READ_ADDRESS;
break;
case GPIO_PORTC:
Pin_Value_Ptr = (volatile Pin_Value_t*)PORTC_READ_ADDRESS;
break;
case GPIO_PORTD:
Pin_Value_Ptr = (volatile Pin_Value_t*)PORTD_READ_ADDRESS;
break;
case GPIO_PORTE:
Pin_Value_Ptr = (volatile Pin_Value_t*)PORTE_READ_ADDRESS;
break;
default:
/* Error: Undefined Port */
GPIO_PinValue = GPIO_LOW;
break;
}
if(GPIO_HIGH == GPIO_PinValue){
switch(GPIO_PIN_ID){
case GPIO_PIN0:
if(PIN_HIGH == Pin_Value_Ptr->Pin0){
GPIO_PinValue = GPIO_HIGH;
}else{
GPIO_PinValue = GPIO_LOW;
}
break;
case GPIO_PIN1:
if(PIN_HIGH == Pin_Value_Ptr->Pin1){
GPIO_PinValue = GPIO_HIGH;
}else{
GPIO_PinValue = GPIO_LOW;
}
break;
case GPIO_PIN2:
if(PIN_HIGH == Pin_Value_Ptr->Pin2){
GPIO_PinValue = GPIO_HIGH;
}else{
GPIO_PinValue = GPIO_LOW;
}
break;
case GPIO_PIN3:
if(PIN_HIGH == Pin_Value_Ptr->Pin3){
GPIO_PinValue = GPIO_HIGH;
}else{
GPIO_PinValue = GPIO_LOW;
}
break;
case GPIO_PIN4:
if(PIN_HIGH == Pin_Value_Ptr->Pin4){
GPIO_PinValue = GPIO_HIGH;
}else{
GPIO_PinValue = GPIO_LOW;
}
break;
case GPIO_PIN5:
if(PIN_HIGH == Pin_Value_Ptr->Pin5){
GPIO_PinValue = GPIO_HIGH;
}else{
GPIO_PinValue = GPIO_LOW;
}
break;
case GPIO_PIN6:
if(PIN_HIGH == Pin_Value_Ptr->Pin6){
GPIO_PinValue = GPIO_HIGH;
}else{
GPIO_PinValue = GPIO_LOW;
}
break;
case GPIO_PIN7:
if(PIN_HIGH == Pin_Value_Ptr->Pin7){
GPIO_PinValue = GPIO_HIGH;
}else{
GPIO_PinValue = GPIO_LOW;
}
break;
default:
/* Error: Undefined Pin */
GPIO_PinValue = GPIO_LOW;
break;
}
}
return GPIO_PinValue;
}
void GPIO_SetPortDirection(const GPIO_Port_ID_t GPIO_PORT_ID,
const GPIO_Direction_t GPIO_PORT_DIRECTION){
volatile Port_Direction_State_t* Port_Direction_Ptr;
switch(GPIO_PORT_ID){
case GPIO_PORTA:
Port_Direction_Ptr = (volatile Port_Direction_State_t*)PORTA_DIRECTION_ADDRESS;
break;
case GPIO_PORTB:
Port_Direction_Ptr = (volatile Port_Direction_State_t*)PORTB_DIRECTION_ADDRESS;
break;
case GPIO_PORTC:
Port_Direction_Ptr = (volatile Port_Direction_State_t*)PORTC_DIRECTION_ADDRESS;
break;
case GPIO_PORTD:
Port_Direction_Ptr = (volatile Port_Direction_State_t*)PORTD_DIRECTION_ADDRESS;
break;
case GPIO_PORTE:
Port_Direction_Ptr = (volatile Port_Direction_State_t*)PORTE_DIRECTION_ADDRESS;
break;
default:
/* Error: Undefined Port */
return;
}
if(GPIO_OUTPUT == GPIO_PORT_DIRECTION){
*Port_Direction_Ptr = PORT_OUTPUT;
}else if(GPIO_INPUT == GPIO_PORT_DIRECTION){
*Port_Direction_Ptr = PORT_INPUT;
}else{
/* Error: Undefined Direction */
*Port_Direction_Ptr = PORT_INPUT;
}
}
void GPIO_SetPortValue(const GPIO_Port_ID_t GPIO_PORT_ID,
const u8_t GPIO_PORT_VLAUE){
volatile u8_t* Port_Value_Ptr;
switch(GPIO_PORT_ID){
case GPIO_PORTA:
Port_Value_Ptr = (volatile u8_t*)PORTA_WRITE_ADDRESS;
break;
case GPIO_PORTB:
Port_Value_Ptr = (volatile u8_t*)PORTB_WRITE_ADDRESS;
break;
case GPIO_PORTC:
Port_Value_Ptr = (volatile u8_t*)PORTC_WRITE_ADDRESS;
break;
case GPIO_PORTD:
Port_Value_Ptr = (volatile u8_t*)PORTD_WRITE_ADDRESS;
break;
case GPIO_PORTE:
Port_Value_Ptr = (volatile u8_t*)PORTE_WRITE_ADDRESS;
break;
default:
/* Error: Undefined Port */
return;
}
*Port_Value_Ptr = GPIO_PORT_VLAUE;
}
u8_t GPIO_ReadPortValue(const GPIO_Port_ID_t GPIO_PORT_ID){
volatile u8_t* Port_Value_Ptr;
switch(GPIO_PORT_ID){
case GPIO_PORTA:
Port_Value_Ptr = (volatile u8_t*)PORTA_READ_ADDRESS;
break;
case GPIO_PORTB:
Port_Value_Ptr = (volatile u8_t*)PORTB_READ_ADDRESS;
break;
case GPIO_PORTC:
Port_Value_Ptr = (volatile u8_t*)PORTC_READ_ADDRESS;
break;
case GPIO_PORTD:
Port_Value_Ptr = (volatile u8_t*)PORTD_READ_ADDRESS;
break;
case GPIO_PORTE:
Port_Value_Ptr = (volatile u8_t*)PORTE_READ_ADDRESS;
break;
default:
/* Error: Undefined Port */
return PORT_ERROR;
}
return *Port_Value_Ptr;
}
void GPIO_Init(void){
ADCON1 = 0X06; /* No Analog Channels */
}
|
C
|
#include <stdio.h>
#include <math.h>
void main() {
int k;
long double Sum,a,x,y;
//series vizualizacijas bloks;
printf("\n\n\t 500 \n"); // ar \t taulaciju nocentre
printf("\t -------- \n");
printf("\t \\ (k+1) k (2k-1)\n"); //pakapes
printf("\t \\ (-1)^ *x^ *2^\n"); //dalas augsa
printf(" f(x) =\t | ---------------------------- = (sin(sqrt(x)))^2\n"); //dalas vidus
printf(" \t /\t (2*k)!"); //dalas apaksa
printf("\n\t /\n"); //
printf("\t -------- \n");
printf("\t k=1\n\n");
// x ievadisana
printf("Ievadiet x vertibu, kurai velaties iegut (sin(sqrt(x)))^2: ");
scanf("%Lg",&x);
y = sin(sqrt(x))*sin(sqrt(x));
printf("\nIzmantojot math: f(%.5Lg)=(sin(sqrt(%.5Lg)))^2=%.5Lg\n",x,x,y); //izvada y izmantojot math
printf("\n");
//SERIES SUM bloks
a=x;
Sum = a;
k=1; //k sakas no 1
printf("Izmantojot series summu: \n\n");
while(k<501)
{
k++;
a = a* (-4)*x /((2*k)*(2*k-1)); //a*R
Sum = Sum + a; //SUM
if (k==499||k==500)
{
printf("%d. | X=%.5Lg\t|\ta=%.5Lg\t|\tS=%.5Lg\t\n", k, x, a, Sum);
}
}
printf("\nRekurences reizinatajs:\n\n");
//REKURENCES reizinataja vizualizacijas bloks
printf(" (-4)*x\n");
printf(" R = -------------------- \n");
printf(" (2*k)*(2*k-1)\n");
printf("\n");
}
|
C
|
#include "klib.h"
#if !defined(__ISA_NATIVE__) || defined(__NATIVE_USE_KLIB__)
size_t strlen(const char *s) {
int i = 0;
while (s[i++]);
return --i;
}
char *strcpy(char* dst,const char* src) {
int i = 0;
while (1) {
dst[i] = src[i];
if (!src[i]) break;
i++;
}
return dst;
}
char* strncpy(char* dst, const char* src, size_t n) {
for (int i = 0 ; i < n ; ++i) {
dst[i] = src[i];
}
return dst;
}
char* strcat(char* dst, const char* src) {
int i = 0, j = 0;
while (dst[j]) j++;
while (src[i]) dst[j++] = src[i++];
dst[j++] = '\0';
return dst;
}
int strcmp(const char* s1, const char* s2) {
int i = 0;
while (s1[i] && s2[i]) {
if (s1[i] != s2[i]) return s1[i] - s2[i];
i++;
}
return 0;
}
int strncmp(const char* s1, const char* s2, size_t n) {
for (int i = 0 ; i < n ; ++i) {
if (s1[i] != s2[i]) return s1[i] - s2[i];
}
return 0;
}
void* memset(void* v,int c,size_t n) {
for (int i = 0 ; i < n ; ++i) {
*(char *)(v + i) = c;
}
return v;
}
void* memcpy(void* out, const void* in, size_t n) {
unsigned char *src = (unsigned char *) in;
unsigned char *dst = (unsigned char *) out;
for (int i = 0 ; i < n ; ++i) {
*(dst + i) = *(src + i);
}
return out;
}
int memcmp(const void* s1, const void* s2, size_t n){
if (!n) return 0;
int i;
unsigned char *us1 = (unsigned char *) s1;
unsigned char *us2 = (unsigned char *) s2;
for (i = 0 ; i < n; ++i) {
if (*(us1 + i) != *(us2 + i)) return *(us1 + i) - *(us2 + i);
}
return 0;
}
#endif
|
C
|
#include<stdio.h>
int main(void) {
int ways = 0;
int i, j, k;
int testCases, value;
scanf("%d\n", &testCases);
for (i = 1; i <= testCases; i++) {
scanf("%d\n", &value);
ways = 0;
printf("Case #%d: %d", i, value);
for (j = 2; j <= value / j; j++) {
k = value / j;
if (j * k == value) {
printf(" = %d * %d", j, k);
ways++;
if (ways == 2) {
printf("\n");
break;
}
}
}
}
return 0;
}
|
C
|
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
#define THREADS_NO 4
int main()
{
int i;
omp_set_num_threads(THREADS_NO);
#pragma omp parallel
{
for(i = 0; i <= 5; i++)
printf("[%d] Hello World, i = %d\n", omp_get_thread_num(), i);
}
return EXIT_SUCCESS;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <sys/socket.h>
#include <sys/select.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
void usage() {
printf("Usage: hw1 <URL>\n");
exit(1);
}
int main(int argc, char** argv)
{
if(argc<2) usage();
/* grab the host and path from the URL */
char host[100], path[100], file[100];
memset(path,0,sizeof(path));
int scanned=sscanf(argv[1],"http://%[^/]/%s",host,path);
/* parse out a nice filename to use */
char *filepart=strrchr(path,'/');
if(filepart && strlen(filepart+1)) // the strlen call checks if there's a filename after the slash
strcpy(file,filepart+1);
else
strcpy(file,"index.html");
/* resolve the host name to an IP address */
struct addrinfo hints;
memset(&hints,0,sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
struct addrinfo* addrinfo;
int lookup_result=getaddrinfo(host,"http",&hints,&addrinfo);
if(lookup_result!=0) {
printf("Error: no such host %s\n",host);
perror(gai_strerror(lookup_result));
exit(1);
}
printf("Connecting to host %s (%s) to retrieve document %s. \n",
host,
inet_ntoa( ((struct sockaddr_in*)addrinfo->ai_addr)->sin_addr),
path);
/* create a new socket for talking to remote host */
int sock = socket(AF_INET, SOCK_STREAM, 0);
if(sock < 0) {
perror("Creating socket failed: ");
exit(1);
}
/* connect to the remote host */
int res = connect(sock,
(struct sockaddr*)addrinfo->ai_addr,
sizeof(struct sockaddr_in));
if(res < 0) {
perror("Error connecting.");
exit(1);
}
freeaddrinfo(addrinfo);
/* formulate and send the request */
char request[255];
sprintf(request,"GET /%s HTTP/1.0\r\nHost: %s\r\n\r\n",path,host);
send(sock,request,strlen(request),0);
/* start receiving the response */
const int MAX_HDR = 1024*1024;
char buf[MAX_HDR]; // expect headers to be no more than a megabyte!
memset(buf,0,MAX_HDR);
int recv_total = 0;
int recv_count = 0;
// keep receiving request until empty line is encountered. This way we don't
// have to worry about packet boundaries in the parsing.
while(!strstr(buf,"\r\n\r\n")) {
recv_count = recv(sock, buf+recv_total, sizeof(buf)-1-recv_total, 0);
if(recv_count==0) {
printf("receiving request failed\n");
exit(1);
}
recv_total+=recv_count;
}
// now parse the contents
int code;
sscanf(buf,"HTTP/1.%*[01] %d ",&code);
if(code==200)
printf("Receiving file.\n");
else {
printf("Got error code %d\n",code);
char errorline[100];
sscanf(buf,"%[^\r]",errorline);
printf("%s\n",errorline);
exit(1);
}
// skip to the empty line in the response, then start writing data to file
char *end_of_headers;
if(end_of_headers=strstr(buf, "\r\n\r\n")) {
printf("Saving to file %s\n",file);
int bytes_left=recv_total-((end_of_headers-buf)+4);
FILE *outfile=fopen(file,"w+");
fwrite(end_of_headers+4,1,bytes_left,outfile);
while((recv_count=recv(sock,buf,10000,0))!=0) {
fwrite(buf,recv_count,1,outfile);
}
fclose(outfile);
}
else {
printf("Could not find end of headers. Quitting.\n");
}
shutdown(sock,SHUT_RDWR);
}
|
C
|
//Implementacao de um TAD Lista
//Feito por: Leonardo Fonseca Pinheiro
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "lista.h"
struct item_{
int indice;
int peso;
int dist;
item* prox;
};
struct lista_ {
item* ini;
item* fim;
int tamanho;
};
//Cria uma lista
//Nao tem parametros e Retorna a lista
LISTA* lista_criar(void){
LISTA* l = malloc(sizeof(LISTA));
if(l != NULL){
l->ini = NULL;
l->fim = NULL;
l->tamanho = 0;
}
return l;
}
//Apaga uma lista, recebida por parametro
//Retorno void
void lista_apagar(LISTA **l){
if (*l == NULL)
return;
item* aux = (*l)->ini;
for(int i = 0; i < (*l)->tamanho; i++){
if (aux != NULL){
item* aux1;
aux1 = aux->prox;
aux->prox = NULL;
free(aux);
aux = aux1;
}
}
free(*l);
}
//Insere um elemento v, recebido por parametro, na lista l,
//que tambem e um parametro. Retorno void.
void inserir_lista(LISTA* l, int v){
if(l == NULL){
return;
}
item* aux = malloc(sizeof(item));
aux->indice = v;
aux->dist = 1;
aux->peso = 1;
aux->prox = NULL;
if(l->ini == NULL){
l->ini = aux;
}
if(l->fim != NULL){
l->fim->prox = aux;
}
l->fim = aux;
l->tamanho++;
return;
}
/* Insere um elemento v, com peso p e distancia d, recebidos por parametro,
* na lista l, que tambem e um parametro. Retorno void. */
void inserir_lista_com_peso(LISTA* l, int v, int p, int d){
if(l == NULL){
return;
}
item* aux = malloc(sizeof(item));
aux->indice = v;
aux->dist = d;
aux->peso = p;
aux->prox = NULL;
if(l->ini == NULL){
l->ini = aux;
}
if(l->fim != NULL){
l->fim->prox = aux;
}
l->fim = aux;
l->tamanho++;
return;
}
//Remove um elemento v, recebido por parametro, da lista l,
//que tambem e um parametro. Retorno void.
void remover_lista(LISTA* l, int v){
if(l == NULL){
return;
}
if(l->ini->indice == v){
l->ini = l->ini->prox;
}
item* p = l->ini;
item* aux = NULL;
while(p != NULL){
if(p->indice == v){
aux->prox = p->prox;
break;
}
else{
aux = p;
p = p->prox;
}
}
if(p == l->fim){
l->fim = aux;
}
l->tamanho--;
return;
}
//Remove o primeiro elemento da lista l, recebida por parametro.
//Retorno void
void remover_primeiro_lista(LISTA* l){
if(l == NULL){
return;
}
l->ini = l->ini->prox;
return;
}
//Busca um elemento v, recebido por parametro, na lista l,
//que tambem e um parametro. Retorno booleano.
boolean lista_busca(LISTA* l, int v){
if(l == NULL){
return false;
}
item* aux = l->ini;
while(aux != NULL){
if(aux->indice == v){
return true;
}
else{
aux = aux->prox;
}
}
return false;
}
//Imprime uma lista l, recebida por parametro. Retorno void.
void lista_imprimir(LISTA* l){
if(l != NULL){
if(l->tamanho == 0){
return;
}
else{
item* p = l->ini;
while(p != NULL){
printf("%d ", p->indice);
p = p->prox;
}
}
}
return;
}
//Funcao para passar o tamanho da lista
int lista_tamanho(LISTA* l){
return l->tamanho;
}
//Retorna o indice do item na posicao P
int indice_lista(LISTA* l, int p){
if(p > l->tamanho){
return -1;
}
if(p == l->tamanho){
return l->fim->indice;
}
item* aux = l->ini;
for(int i = 0; i < p; i++){
aux = aux->prox;
}
return aux->indice;
}
item* ponteiro_lista(LISTA*l, item* p){
if(p == NULL){
return l->ini;
}
else{
return p->prox;
}
}
int indice_item(item* i){
return (i->indice);
}
//Retorna a distancia do item na posicao P
int lista_getDist(LISTA* l, int p){
if(p > l->tamanho){
return -1;
}
if(p == l->tamanho){
return l->fim->indice;
}
item* aux = l->ini;
for(int i = 0; i < p; i++){
aux = aux->prox;
}
return aux->dist;
}
//Retorna o peso do item v
int lista_getPeso(LISTA* l, int v){
if(l == NULL){
return -1;
}
item* aux = l->ini;
while(aux != NULL){
if(aux->indice == v){
break;
}
else{
aux = aux->prox;
}
}
if(aux != NULL){
return aux->peso;
}
return -1;
}
|
C
|
#include<stdio.h>
float squareroot(int n)
{
float sqr,temp;
sqr=n/2;
temp=0;
while(sqr!=temp)
{
temp=sqr;
sqr=(n/temp+temp)/2;
}
return sqr;
}
int main()
{
int n;
float sqr;
printf("Enter a number\n");
scanf("%d",&n);
sqr=squareroot(n);
printf("The square root of %d is %.2f",n,sqr);
return 0;
}
|
C
|
#include <stdio.h>
main(){
int A,B,R;
printf("Donner deux entiers A et B positifs");
do{
scanf("%d", &A);
scanf("%d", &B);
} while (A>0 && B>0);
while (R>0){
R=R-B;
}
if(R=0)
printf("%d est est divisible par %d",A,B);
else
printf("%d est n’’est pas divisible par %d",A,B);
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <limits.h>
#include <linux/sched.h>
#include <time.h>
#define LEN 200
struct Borders {
int start;
int end;
};
// int array[] = {4, 2, 3, 1, 5};
int array[LEN];
void prepareArray() {
srand(time(0));
int i;
for (i = 0; i < LEN; i++) {
array[i] = rand()%1000;
}
}
// does actual sorting
void *mergeConc(void* bord) {
struct Borders borders = *((struct Borders *) bord);
int center = (borders.start + borders.end) / 2;
int leftIt = borders.start;
int rightIt = center + 1;
int currentPos = 0;
int tmpTab[LEN];
while (leftIt <= center && rightIt <= borders.end) {
if (array[leftIt] < array[rightIt]) {
tmpTab[currentPos] = array[leftIt];
leftIt++;
currentPos++;
} else {
tmpTab[currentPos] = array[rightIt];
rightIt++;
currentPos++;
}
}
if (leftIt <= center) {
while (leftIt <= center) {
tmpTab[currentPos] = array[leftIt];
leftIt++; currentPos++;
}
} else if (rightIt <= borders.end) {
while (rightIt <= borders.end) {
tmpTab[currentPos] = array[rightIt];
rightIt++; currentPos++;
}
}
currentPos = 0;
int i;
for (i = borders.start; i <= borders.end; i++) {
array[i] = tmpTab[currentPos];
currentPos++;
}
}
// doesn't care about array, only divide
void *mergeSortConc(void* bord) {
struct Borders borders = *((struct Borders *) bord);
struct Borders left, right;
pthread_t leftTid;
pthread_t rightTid;
left.start = borders.start;
left.end = (borders.start + borders.end) / 2;
right.start = left.end + 1;
right.end = borders.end;
if (borders.start < borders.end) {
pthread_create(&leftTid, NULL, mergeSortConc, &left);
pthread_create(&rightTid, NULL, mergeSortConc, &right);
pthread_join(leftTid, NULL);
pthread_join(rightTid, NULL);
mergeConc(&borders);
}
}
// does actual sorting
void merge(struct Borders *borders) {
int center = (borders->start + borders->end) / 2;
int leftIt = borders->start;
int rightIt = center + 1;
int currentPos = 0;
int tmpTab[LEN];
while (leftIt <= center && rightIt <= borders->end) {
if (array[leftIt] < array[rightIt]) {
tmpTab[currentPos] = array[leftIt];
leftIt++;
currentPos++;
} else {
tmpTab[currentPos] = array[rightIt];
rightIt++;
currentPos++;
}
}
if (leftIt <= center) {
while (leftIt <= center) {
tmpTab[currentPos] = array[leftIt];
leftIt++; currentPos++;
}
} else if (rightIt <= borders->end) {
while (rightIt <= borders->end) {
tmpTab[currentPos] = array[rightIt];
rightIt++; currentPos++;
}
}
currentPos = 0;
int i;
for (i = borders->start; i <= borders->end; i++) {
array[i] = tmpTab[currentPos];
currentPos++;
}
}
// doesn't care about array, only divide
void mergeSort(struct Borders *borders) {
struct Borders left, right;
left.start = borders->start;
left.end = (borders->start + borders->end) / 2;
right.start = left.end + 1;
right.end = borders->end;
if (borders->start < borders->end) {
mergeSort(&left);
mergeSort(&right);
merge(borders);
}
}
int main() {
struct Borders borders;
borders.start = 0;
borders.end = (sizeof array / sizeof *array) - 1;
prepareArray();
int j = 0;
for (j = 1; j <= LEN; j++) {
printf("%d \t", array[j-1]);
if (j % 10 == 0) printf("\n");
}
printf("\n\n\n");
clock_t start = clock();
mergeSort(&borders);
clock_t end = clock();
int i;
for (i = 1; i <= LEN; i++) {
printf("%d \t", array[i-1]);
if (i % 10 == 0) printf("\n");
}
printf("\n\n");
printf("Czas wykonywania dla asynchronicznego: %lu ms\n", end-start);
// CONCURRENT
prepareArray();
for (j = 1; j <= LEN; j++) {
printf("%d \t", array[j-1]);
if (j % 10 == 0) printf("\n");
}
printf("\n\n\n");
clock_t start2 = clock();
mergeSortConc(&borders);
clock_t end2 = clock();
for (i = 1; i <= LEN; i++) {
printf("%d \t", array[i-1]);
if (i % 10 == 0) printf("\n");
}
printf("\n\n");
printf("Czas wykonywania dla asynchronicznego: %lu ms\n", end2-start);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int a;
int b;
int c;
int wynik;
scanf("%d", &a);
scanf("%d", &b);
scanf("%d", &c);
wynik = a + b + c;
printf("%d\n", wynik);
return EXIT_SUCCESS;
}
|
C
|
/*
Byte queue library, implemented on single buffer
Copyright © 2017 Eugene Mihailenco <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "queue.h"
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <memory.h>
#include <limits.h>
#include <stddef.h>
/*
## Base ideas
Queues are implemented as single-linked lists, each node is 8 bytes;
Buffer of size 2048 allows to allocate 256 nodes
Node with index 0 is used for allocator, freelist index is stored
in free mem, so effectively we have 255 queues and index 0 may
be used as null pointer, while having 8 bit size;
Normal node has 7 bytes payload and 1 next node index
Tail node doest need next intex, so it has 8 bytes payload
Root nodes have 5 bytes payload, head/tail indexes and counters
used to check how many payload slots used in head, in tail and
in root itself;
Capacity depends on case, couple examples:
(worst) created 63 empty queues and one full - 1343 = (255 - 64 - 1)*7 + 8 + 5
created 64 all equally full - 1721 = (255 - 64 - 64)*7 + 64*8 + 64*5
(best) created 1 full queue - 1784
## Why not 16-byte nodes?
I was considering alternative solution where nodes are 16 bytes too.
Its ratio of user-data to service-data is bigger, there will be 127 nodes
payloads: root - 13 bytes, node - 15 and tail node 16
but capacity cases will be worse on edge cases when many empty queues exist
(worst) created 63 empty queues and one full - 959 = (127 - 64 - 1)*15 + 13 + 16
created 64 all equally full - not possible, not enough nodes for equual - only 13*64 bytes each
(best) created 1 full queue - 1903
with variation where root nodes stored in separate index and have no data we will
get even worse, in case when 64 nodes created, 63 pushed 1 element (so 16 bit block is allocated)
and will almost nothig will be left for last one 64th queue
## Performance
enqueueByte/dequeueByte/createQueue - worst case linear
destroyQueue is linear on element count in that queue
printQueue is linear on element count in that queue
## Memory
Only memory in buffer used, layout:
[pfree|node|node|...|node]
Structure of node bit fields:
Root node:
XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX
[ data ] [ data ] [ data ] [ data ] [ data ] [ head ] [ tail ] [ cntr ]
data = 8x5 bit payload
head = 8 bit index of head of queue
tail = 8 bit index of tail of queue
cntr = 8 bit counters - interpreted differently:
if head == NULL - 8 bits is number of used payload slots in root
if head != NULL - 4 bits - head, 4 bits - tail - nr of slots used in them
Normal node:
XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX
[ data ] [ data ] [ data ] [ data ] [ data ] [ data ] [ data ] [ next ]
data = 8x7 bit payload data
next = 8 bit index of next node
Tail node:
XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX
[ data ] [ data ] [ data ] [ data ] [ data ] [ data ] [ data ] [ data ]
data = 8x8 bit payload data
## Some conventions and naming
Node types:
root node - used as handle returned to client,
and also has payload, stores
indexes for head and tail and countres.
1st data field represents "to be dequeued" element.
normal node - for data only, has 7 payload byte fields
and index for next element
Root node states:
empty - state when queue was just created head == tail == NULL, cntr == 0
single - has some payload, head == head == NULL, cntr != 0
full - has full payload, head != NULL uses head and tail counters
Normal node states:
normal - not all payload slots filled yet
full - all slots used
## Allocation/Deallocation:
Generic node allocator with free nodes list implemented in free storage
used. pfree index always points to free region that will be returned by
allocate_node() call. deallocate() stores previous pfree value in free
memory region to recover pfree after subsequent allocations/deallocations.
Both functions work in constant time. Allocator returns zeroed out node.
Enqueue:
use Q handle as pointer to node, read root node.
if its not full - set data, wire nxt and prw to self, return;
if its single - goto make new node
take prew node
if prew node is normal - add data B, swap B<->A, return;
make new node, set its data A and nxt to root
link new node: prew->nxt = new, root->prw = new
Dequeue:
use Q handle as pointer to node, read root node.
If its empty - raise error, return null;
if its single - set empty, return old data;
take next node;
if its full - return B, make it normal, copy B to root, return old root data;
if its normal - copy A to root. deallocate it, return old root data;
List as FIFO semantic:
Oueue:
1 2 3 ... N , where 1 is last come and N is first to out
[root N] --head-> [N-1] -> [N-2] -> ... [3] -> [2] -> [1]
| ^
| |
`----tail-------------------------------------------′
*/
// ========================================================================== //
#define ROOT_PAYLOAD 5
#define NODE_PAYLOAD 7
#define TAIL_PAYLOAD 8
// 64 bit bit-filed node struct to access data and indexes, unioned so same
// node_t can be seen: as_root, as_node, as_tail and as_pfree.
typedef union
{
struct
{
unsigned char data[NODE_PAYLOAD] ;
unsigned char next;
} as_node;
struct
{
unsigned char data[TAIL_PAYLOAD] ;
} as_tail;
struct
{
unsigned char data[ROOT_PAYLOAD] ;
unsigned char head;
unsigned char tail;
unsigned char cnth : 4 ;
unsigned char cntt : 4 ;
} as_root;
unsigned long int as_pfree;
unsigned int as_ints[2];
} __attribute__((packed)) node_t;
// TODO: how abount like uint64_t ?
static_assert(sizeof(unsigned long int) == 8, "Algorithm relies on 8 byte longs");
static_assert(sizeof(unsigned int) == 4, "Algorithm relies on 4 byte ints");
static_assert(sizeof(node_t) == 8, "Algorithm relies on 4 byte nodes");
static_assert(sizeof(char) == 1, "In case C standard violated by compiler");
static_assert(CHAR_BIT == 8, "In case platform is weird");
#define NODE_COUNT 256
// Static buffer for data - can be set from outside
// with initQueues() call, and its len. No other data used.
static node_t* buffer;
static int buffer_len;
// Callbacks
static onOutOfMem_cb_t onOutOfMemory;
static onIllegalOperation_cb_t onIllegalOperation;
// ========================================================================== //
// helper, returns true if pointer is withit [buffer, buffer + MA
static inline bool bounds_check(node_t* node);
// Get queue root
static inline node_t* get_queue_root(Q* q);
// get node's index
static inline unsigned char node_to_index(node_t* node);
// get node by index
static inline node_t* index_to_node(unsigned char index);
// single root has no head and tail
static inline bool is_single_root(node_t* root);
// empty root is single root that has no no data
static inline bool is_empty_root(node_t* root);
// checks if single root has more extra slots for data
static inline bool is_full_root(node_t* root);
// checks if root has tail node with all slots filled
static inline bool is_full_tail(node_t* root);
// checks if root has emtpy head (i.e head exists but has no data)
static inline bool is_empty_head(node_t* root);
// checks if root has emtpy tail (i.e tail exists but has no data)
static inline bool is_empty_tail(node_t* root);
// root that has head and tail the same values
static inline bool is_headtail_root(node_t* root);
// getters settors for head/tail
static inline node_t* get_root_head(node_t* root);
static inline node_t* get_root_tail(node_t* root);
static inline void set_root_head(node_t* root, node_t* head, unsigned char cnt);
static inline void set_root_tail(node_t* root, node_t* tail, unsigned char cnt);
// gets byte from single root
static inline unsigned char pop_single_root_data(node_t* root);
// sets byte info single root
static inline void push_single_root_data(node_t* root, unsigned char b);
// gets byte from root, needs input byte to shift data,
// non-single root must be full filled, function rotates
// bytes of root's payload to make it FIFO
static inline unsigned char shift_root_data(node_t* root, unsigned char in);
// gets byte from next node, decrements cnth
static inline unsigned char pop_head_data(node_t* root);
// gets byte from prew node, decrements cnth and cntt
// only used when head==tail
static inline unsigned char pop_tail_data(node_t* root);
// gets last byte of full tail, so it can became normal node,
// also sets nodes next index to given value
static inline unsigned char swap_tail(node_t* root, node_t* newtail);
// adds data to roots tail node
static inline void push_tail_data(node_t* root, unsigned char b);
// makes root single
static inline void make_root_single(node_t* root);
// gettters/setters for node's next node
static inline node_t* get_node_next(node_t* node);
static inline void set_node_next(node_t* node, node_t* next);
// Allocates a node, returns it all zeroed
static node_t* alloc_node();
// Deallocates node, should not be used after free
static void free_node(node_t* node);
// ========================================================================== //
// Core functions
static inline node_t* get_queue_root(Q* q)
{
node_t* root = (node_t*)q;
assert(bounds_check(root));
return root;
}
static inline bool bounds_check(node_t* node)
{
return (node != NULL) && (buffer < node && node < buffer + NODE_COUNT);
}
static inline unsigned char node_to_index(node_t* node)
{
assert(bounds_check(node));
return node - buffer;
}
static inline node_t* index_to_node(unsigned char index)
{
return buffer + index;
}
// Root nodes related fuctions
static inline bool is_single_root(node_t* root)
{
assert(bounds_check(root));
return root->as_root.head == 0 ;
}
static inline bool is_empty_root(node_t* root)
{
assert(bounds_check(root));
return is_single_root(root) && root->as_root.cntt == 0;
}
static inline bool is_full_root(node_t* root)
{
assert(bounds_check(root));
assert(is_single_root(root));
return root->as_root.cntt == ROOT_PAYLOAD;
}
static inline bool is_full_tail(node_t* root)
{
assert(bounds_check(root));
assert(!is_single_root(root));
return root->as_root.cntt == TAIL_PAYLOAD;
}
static inline bool is_empty_head(node_t* root)
{
assert(bounds_check(root));
assert(!is_single_root(root));
return root->as_root.cnth == 0;
}
static inline bool is_empty_tail(node_t* root)
{
assert(bounds_check(root));
assert(!is_single_root(root));
return root->as_root.cntt == 0;
}
static inline bool is_headtail_root(node_t* root)
{
assert(bounds_check(root));
return !is_single_root(root) && root->as_root.head == root->as_root.tail;
}
static inline node_t* get_root_head(node_t* root)
{
assert(bounds_check(root));
assert(!is_empty_root(root));
assert(!is_single_root(root));
node_t* h = index_to_node(root->as_root.head);
assert(h != root);
return h;
}
static inline node_t* get_root_tail(node_t* root)
{
assert(bounds_check(root));
assert(!is_empty_root(root));
assert(!is_single_root(root));
node_t* t = index_to_node(root->as_root.tail);
assert(t != root);
return t;
}
static inline void set_root_head(node_t* root, node_t* head, unsigned char cnt)
{
assert(bounds_check(root));
assert(bounds_check(head));
assert(cnt <= NODE_PAYLOAD);
root->as_root.head = node_to_index(head);
root->as_root.cnth = cnt;
}
static inline void set_root_tail(node_t* root, node_t* tail, unsigned char cnt)
{
assert(bounds_check(root));
assert(bounds_check(tail));
assert(cnt <= TAIL_PAYLOAD);
root->as_root.tail = node_to_index(tail);
root->as_root.cntt = cnt;
}
static inline unsigned char pop_single_root_data(node_t* root)
{
assert(bounds_check(root));
assert(!is_empty_root(root));
assert(is_single_root(root));
unsigned char cnt = root->as_root.cntt;
assert(cnt > 0 && cnt <= ROOT_PAYLOAD);
unsigned char* d = root->as_root.data;
unsigned char p = d[0];
// a bit hacky but fast - lets shift entire thing ;)
unsigned long int root_d = root->as_pfree;
root_d >>= 8;
root->as_pfree = root_d;
// recover and update data
root->as_root.cntt = cnt - 1;
root->as_root.head = 0;
root->as_root.tail = 0;
return p;
}
static inline void push_single_root_data(node_t* root, unsigned char b)
{
assert(bounds_check(root));
assert(is_single_root(root));
unsigned char cnt = root->as_root.cntt;
assert(cnt < ROOT_PAYLOAD);
unsigned char* d = root->as_root.data;
d[cnt] = b;
root->as_root.cntt = cnt + 1;
}
static inline unsigned char shift_root_data(node_t* root, unsigned char new)
{
assert(bounds_check(root));
assert(!is_single_root(root));
unsigned char* d = root->as_root.data;
unsigned char p = d[0];
// a bit hacky but fast - lets shift entire thing ;)
unsigned int root_d = root->as_ints[0];
root_d >>= 8;
root->as_ints[0] = root_d;
d[3] = d[4];
d[4] = new;
return p;
}
static inline unsigned char pop_head_data(node_t* root)
{
assert(bounds_check(root));
assert(!is_single_root(root));
assert(!is_headtail_root(root));
node_t* head = get_root_head(root);
unsigned char cnt = root->as_root.cnth;
/* printf("cnt = %d \n", cnt); */
assert(cnt > 0 && cnt <= NODE_PAYLOAD);
unsigned char* d = head->as_node.data;
unsigned char p = d[0];
// a bit hacky but fast - lets shift entire thing ;)
// will have to recover next field though
unsigned char next = head->as_node.next;
unsigned long int head_d = head->as_pfree;
head_d >>= 8;
head->as_pfree = head_d;
head->as_node.next = next;
// recover and update data
root->as_root.cnth = cnt - 1;
return p;
}
static inline unsigned char pop_tail_data(node_t* root)
{
assert(bounds_check(root));
assert(!is_single_root(root));
assert(is_headtail_root(root));
node_t* tail = get_root_tail(root);
unsigned char cnt = root->as_root.cntt;
assert(cnt > 0 && cnt <= TAIL_PAYLOAD);
unsigned char* d = tail->as_tail.data;
unsigned char p = d[0];
unsigned long int tail_d = tail->as_pfree;
tail_d >>= 8;
tail->as_pfree = tail_d;
root->as_root.cntt = cnt - 1;
root->as_root.cnth = cnt - 1;
return p;
}
static inline unsigned char swap_tail(node_t* root, node_t* newtail)
{
assert(bounds_check(root));
assert(bounds_check(newtail));
assert(!is_single_root(root));
assert(root->as_root.cntt == TAIL_PAYLOAD);
node_t* tail = get_root_tail(root);
unsigned char* d = tail->as_node.data + TAIL_PAYLOAD - 1;
unsigned char p = *d;
*d = node_to_index(newtail);
if(is_headtail_root(root)) // if its first time we expand
{
root->as_root.cnth = NODE_PAYLOAD;
}
set_root_tail(root, newtail, 0);
return p;
}
static inline void push_tail_data(node_t* root, unsigned char b)
{
assert(bounds_check(root));
assert(!is_single_root(root));
node_t* tail = get_root_tail(root);
// increment, write to tail
unsigned char cnt = root->as_root.cntt;
assert(cnt < TAIL_PAYLOAD);
unsigned char* d = tail->as_root.data;
d[cnt] = b;
root->as_root.cntt = cnt + 1;
}
static inline void push_tail_data2(node_t* root, unsigned char b, unsigned char a)
{
assert(bounds_check(root));
assert(!is_single_root(root));
node_t* tail = get_root_tail(root);
// increment, write to tail
unsigned char cnt = root->as_root.cntt;
assert(cnt < TAIL_PAYLOAD);
unsigned char* d = tail->as_root.data;
d[cnt++] = b;
d[cnt] = a;
root->as_root.cntt = cnt + 1;
}
static inline void make_root_single(node_t* root)
{
assert(bounds_check(root));
assert(!is_single_root(root));
root->as_root.cntt = ROOT_PAYLOAD;
root->as_root.cnth = 0;
root->as_root.head = 0;
root->as_root.tail = 0;
}
// Simple node related
static inline node_t* get_node_next(node_t* node)
{
assert(bounds_check(node));
return index_to_node(node->as_node.next);
}
static inline void set_node_next(node_t* node, node_t* next)
{
assert(bounds_check(node));
assert(bounds_check(next));
node->as_node.next = node_to_index(next);
}
// ========================================================================== //
static node_t* alloc_node()
{
assert(buffer->as_pfree != 0);
if (buffer->as_pfree >= NODE_COUNT)
{
onOutOfMemory();
return NULL;
}
node_t* ret = index_to_node(buffer->as_pfree);
if (ret->as_pfree == 0)
{
buffer->as_pfree += 1;
}
else
{
buffer->as_pfree = ret->as_pfree;
ret->as_pfree = 0;
}
return ret;
}
static void free_node(node_t* node)
{
assert(bounds_check(node));
node->as_pfree = buffer->as_pfree;
buffer->as_pfree = node_to_index(node);
}
// ========================================================================== //
queueMetrics_t initQueues(unsigned char* buf, unsigned int len)
{
assert(buf != NULL);
assert(len == 2048);
memset(buf, 0, len);
buffer = (node_t*) buf;
buffer_len = len;
buffer->as_pfree = 1;
queueMetrics_t ret;
ret.name = "Eugene's impl";
ret.max_empty_queues = 255;
ret.max_nonempty_queues = 255;
ret.max_els_in_single = 1784;
ret.max_els_in_16even = 1769;
ret.max_els_in_64even = 1721;
ret.max_els_in_max_even_queues = 5;
ret.max_els_in_single_with_63_empty = 1343;
return ret;
}
Q* createQueue()
{
// create new empty root node and return it as handle
return (Q*) alloc_node();
}
void destroyQueue(Q* q)
{
node_t* root = get_queue_root(q);
if (is_single_root(root)) // if its only one node - just free it
{
free_node(root);
return;
}
node_t* t = get_root_tail(root);
node_t* p = get_root_head(root);
free_node(root);
if (t == p) // if its two nodes - free both
{
free_node(t);
return;
}
while (p != t) // walk through the chain and free them all
{
node_t* pp = get_node_next(p);
free_node(p);
p = pp;
}
free_node(t);
}
void enqueueByte(Q* q, unsigned char b)
{
node_t* root = get_queue_root(q);
if (is_single_root(root))
{
if (!is_full_root(root))
{
push_single_root_data(root, b);
}
else
{
node_t* newman = alloc_node();
if (newman == NULL) return;
set_root_tail(root, newman, 0);
set_root_head(root, newman, 0);
push_tail_data(root, b);
}
return;
}
if (is_full_tail(root))
{
// we run out fo tail data
node_t* newman = alloc_node();
if (newman == NULL) return;
char old_b = swap_tail(root, newman);
push_tail_data2(root, old_b, b);
return;
}
push_tail_data(root, b);
}
unsigned char dequeueByte(Q* q)
{
node_t* root = get_queue_root(q);
if (is_empty_root(root))
{
onIllegalOperation();
return 0;
}
if (is_single_root(root))
{
return pop_single_root_data(root);
}
if (is_headtail_root(root))
{
unsigned char tail_ret = pop_tail_data(root); // pops from 8 data field
unsigned char ret = shift_root_data(root, tail_ret);
if (is_empty_tail(root))
{
free_node(get_root_tail(root));
make_root_single(root);
}
return ret;
}
unsigned char head_ret = pop_head_data(root);
unsigned char ret = shift_root_data(root, head_ret);
if (is_empty_head(root))
{
node_t* head = get_root_head(root);
set_root_head(root, get_node_next(head), NODE_PAYLOAD);
free_node(head);
return ret;
}
return ret;
}
void printQueue(Q* q)
{
node_t* root = (node_t*)q;
if (is_empty_root(root))
{
printf("[empty] - 1 node\n");
return;
}
printf("[non empty =) ] - N nodes\n");
// TODO: count elements, nodes, print nicely
/*printf("[");
node_t* p;
while ((p = get_nxt(root)) != root)
{
printf("%d ", p->data);
}
printf("%d]\n", root->data );*/
}
void setOutOfMemoryCallback(onOutOfMem_cb_t cb)
{
assert(cb != NULL);
onOutOfMemory = cb;
}
void setIllegalOperationCallback(onIllegalOperation_cb_t cb)
{
assert(cb != NULL);
onIllegalOperation = cb;
}
|
C
|
/* Thomas Schultz
* Lab: LAB4
* SECTION: CS1050C
* Pawprint: TJS6F2
* TA: Dheeraj
*/
#include <stdio.h>
//prototype functions
int checkEven(int x);
int errorCheck(int y);
int checkPrime(int z);
int addDigits(int a);
void printMizzou(int b);
int main (void) {
int num;//delcaring variables
int numtwo;
printf("Enter a positive number: ");
scanf("%d", &num);
while(errorCheck(num)==1) {//call to function--error checker
printf("Error! Enter a positive number only: ");
scanf("%d", &num);
}
if(checkEven(num)==1)//call to function--odd or even
printf("\n%d is an even number\n", num);
else
printf
("\n%d is an odd number\n", num);
if(checkPrime(num)==1)//call to prime function
printf("%d is a prime number\n", num);
else
printf("%d is not a prime number\n", num);
printf("The sumd of digits in %d is %d\n", num, addDigits(num));//call to addDigits function
printf("\nEnter the second positive number: ");
scanf("%d", &numtwo);
while(errorCheck(numtwo)==1) {//error checker function call
printf("Error! Enter a positive number only: ");
scanf("%d", &numtwo);
}
printf("\nCalling the MIZZOU function, the output is:\n\n");
printMizzou(numtwo);//calling printMizzou function
return 0;
}
int errorCheck(int y) {//positive # error checker
if(y<=0)
return 1;
return 0;
}
int checkEven(int x) {//odd or even function
int z;
z=2;
if(x%z==0)//even or odd?
return 1;
return 0;
}
int checkPrime(int z) {//prime function
int a;
for(a=2; a<= z/2; a++) {//prime or not prime
if (z%a==0){
return 0;
break;
}
}
return 1;
}
int addDigits(int a) {//add em up
if(a!=0) {
return(a%10 + addDigits(a/10));
}
return 0;
}
void printMizzou(int b) {//Mizzou function
int i;
for(i=1; i<=b; i++) {
if(i%15==0)
printf("MIZZOU ");
else if(i%3==0)
printf("MIZ ");
else if(i%5==0)
printf("ZOU ");
else if((i%3!=0) && (i%5!=0))
printf("%d ", i);
}
printf("\n");
}
|
C
|
/* Tipos Triangulos */
#include <stdio.h>
#define MAX 1000
int main (void) {
float A,B,C;
int tmp;
scanf("%f", &A);
scanf("%f", &B);
scanf("%f", &C);
if (A < B) {
tmp = A;
A = B;
B = tmp; }
if (A < C) {
tmp = A;
A = C;
C = tmp; }
if (B < C) {
tmp = B;
B = C;
C = tmp; }
if (A >= B + C)
printf("NAO FORMA TRIANGULO\n");
else {
if ((A*A) == (B*B) + (C*C))
printf("TRIANGULO RETANGULO\n");
if ((A*A) > (B*B) + (C*C))
printf("TRIANGULO OBTUSANGULO\n");
if ((A*A) < (B*B) + (C*C))
printf("TRIANGULO ACUTANGULO\n");
if ((A == B) && (B == C) && (A == C))
printf("TRIANGULO EQUILATERO\n");
else if (A == B ||
A == C ||
B == C )
printf("TRIANGULO ISOSCELES\n");
}
return 0;
}
|
C
|
#include"projet.h"
int main(){
ImageCouleur *imageLena;
ImageCouleur *imageMire;
imageLena = chargerImage("C:/Users/AYOUB LABIDI/Desktop/Lena.ppm");
imageMire = chargerImage("C:/Users/AYOUB LABIDI/Desktop/Mire.ppm");
ImageGris *image1 = creerImageGris(imageLena->h,imageLena->l);
image1->pixels = changerCouleurGris(imageLena->pixels,imageLena->h*imageLena->l);
ImageCouleur *image2 = creerImageCouleur(imageLena->h,imageLena->l);
image2->pixels= fusionImages(imageLena->pixels,imageMire->pixels,imageLena->h*imageLena->l);
ImageCouleur *image3 = creerImageCouleur(imageLena->h,imageLena->l);
image3->pixels = inversionCouleur(imageLena->pixels,imageLena->h*imageLena->l);
sauvgarderImageGris("gris.ppm",image1);
sauvgarderImage("fusion.ppm",image2);
sauvgarderImage("inversion.ppm",image3);
int* histogramme;
histogramme = calculHistogramme(image1->pixels,image1->h*image1->l);
afficherHistogramme(histogramme);
printf("...");
getchar();
}
ImageCouleur *chargerImage(const char *fichier)
{
char format[10];
ImageCouleur *img;
FILE *f;
int max_pix,commentaire;
//ouvrir le fichier de l'image
f = fopen(fichier, "rb");
if (!f) {
fprintf(stderr, "Erreur lors de l'ouverture du fichier '%s'\n", fichier);
exit(1);
}
//lire le format de l'image
if (!fgets(format, sizeof(format), f)) {
perror(fichier);
exit(1);
}
//Verifier le format de l'image
if (format[0] != 'P' || format[1] != '6') {
fprintf(stderr, "Format de l'image est invalide\n");
exit(1);
}
//allocation de l'image
img = (ImageCouleur *)malloc(sizeof(ImageCouleur));
//enlever les commentaires
commentaire = getc(f);
while (commentaire == '#') {
while (getc(f) != '\n') ;
commentaire = getc(f);
}
ungetc(commentaire,f);
//lire les dimensions de l'image
if (fscanf(f, "%d %d", &img->h, &img->l) != 2) {
fprintf(stderr, "Les dimensions de l'image sont invalides\n");
exit(1);
}
//lire la valeur max d'un pixel
if (fscanf(f, "%d", &max_pix) != 1) {
fprintf(stderr, "La valeur maximal d'un pixel est invalide\n");
exit(1);
}
//vrifier la valeur max d'un pixel
if (max_pix != MAX_PIXEL) {
fprintf(stderr, "Format de l'image est invalide\n");
exit(1);
}
//supprimer l'espace vide
while (fgetc(f) != '\n') ;
//allocation des pixels
img->pixels = (Pixel*)malloc(img->h * img->l * sizeof(Pixel));
//lecture des pixels
if (fread(img->pixels, 3 * img->h, img->l, f) != img->l) {
fprintf(stderr, "Erreur lors de la chargement de l'image '%s'\n", fichier);
exit(1);
}
fclose(f);
return img;
}
void sauvgarderImage(const char *fichier, ImageCouleur *img)
{
FILE *f;
//ouverture du fichier
f = fopen(fichier, "wb");
if (!f) {
fprintf(stderr, "Erreur lors de l'ouverture du fichier '%s'\n", fichier);
exit(1);
}
//ecriture de l'entete:
//format de l'image
fprintf(f, "P6\n");
//dimensions de l'image
fprintf(f, "%d %d\n",img->h,img->l);
//valeur max d'un pixel
fprintf(f, "%d\n",MAX_PIXEL);
//ecriture des pixels
fwrite(img->pixels, 3 * img->h, img->l, f);
fclose(f);
}
void sauvgarderImageGris(const char *fichier, ImageGris *img)
{
FILE *f;
int i;
//ouverture du fichier
f = fopen(fichier, "wb");
if (!f) {
fprintf(stderr, "Erreur lors de l'ouverture du fichier '%s'\n", fichier);
exit(1);
}
//ecriture de l'entete
//format de l'image
fprintf(f, "P2\n");
//dimensions de l'image
fprintf(f, "%d %d\n",img->h,img->l);
//valeur max d'un pixel
fprintf(f, "%d\n",MAX_PIXEL);
//ecriture des pixels
for(i=0;i<img->h*img->l;i++){
fprintf(f, "%d ",img->pixels[i].g);
}
fclose(f);
}
Pixel* inversionCouleur(Pixel *pixels,int taille)
{
int i;
if(pixels){
//parcour du tableau et soustraction des valeurs de chaque pixel de la valeur max que peut prendre un pixel (255)
for(i=0;i<taille;i++){
pixels[i].r=MAX_PIXEL-pixels[i].r;
pixels[i].v=MAX_PIXEL-pixels[i].v;
pixels[i].b=MAX_PIXEL-pixels[i].b;
}
}
return pixels;
}
PixelGris* changerCouleurGris(Pixel *pixels,int taille)
{
int i;
if(pixels){
//parcour du tableau et remplissage des valeurs des pixels gris par la moyenne des pixels de l'image d'origine
PixelGris *pixelsGris =(PixelGris*)malloc(taille * sizeof(PixelGris));
for(i=0;i<taille;i++){
pixelsGris[i].g =(pixels[i].r+pixels[i].v+pixels[i].b)/3;
}
return pixelsGris;
}
}
int * calculHistogramme(PixelGris* pixels,int taille)
{
//allocation du tableau d'histogramme
int* histogramme = (int*)malloc(256*sizeof(int));
int i,j;
//parcour des cases de l'histogramme
for(i=0;i<256;i++)
{
//initialisation de la case par 0
histogramme[i]=0;
//parcour du tableau des pixels et calcul d'occurence
for(j=0;j<taille;j++){
if(pixels[j].g == i)
histogramme[i]=histogramme[i]+1;
}
}
return histogramme;
}
Pixel * fusionImages(Pixel *pixels1,Pixel *pixels2,int taille)
{
int i;
//allocation du tableau des pixels de l'image du fusion
Pixel *fusion=(Pixel*)malloc(taille * sizeof(Pixel));
if(pixels1){
//parcour du tableau et remlissage des valeurs par la moyenne des pixels des deux images fusionner
for(i=0;i<taille;i++){
fusion[i].r=(pixels1[i].r+pixels2[i].r)/2;
fusion[i].v=(pixels1[i].v+pixels2[i].v)/2;
fusion[i].b=(pixels1[i].b+pixels2[i].b)/2;
}
return fusion;
}
}
ImageGris * creerImageGris(int h,int l)
{
//allocation de l'image
ImageGris* img = (ImageGris*)malloc(sizeof(ImageGris));
img->h=h;
img->l=l;
return img;
}
ImageCouleur * creerImageCouleur(int h,int l)
{
//allocation de l'image
ImageCouleur* img = (ImageCouleur*)malloc(sizeof(ImageCouleur));
img->h=h;
img->l=l;
return img;
}
void afficherHistogramme(int* histogramme)
{
int i;
for(i=0;i<256;i++){
printf("%d ",histogramme[i]);
}
printf("\n");
}
|
C
|
#ifndef PIXEL_H
#define PIXEL_H
#include <stdlib.h>
typedef struct PIXEL
{
int column;
int r, g, b;
struct PIXEL *pnext;
struct PIXEL *pprev;
}Pixel;
/*
* Funo make_vector(int n)
* ----------------------------
* TV: n de elementos que o vetor tera
*
* retorno: vetor com n elementos
*/
Pixel* *make_vector(int TV);
/*
* Funo make_pixel(int column, int r, int g, int b)
* ----------------------------
* column: coluna do pixel
* r: codigo do vermelho do pixel
* g: codigo do verde do pixel
* b: codigo do azul do pixel
*
* retorno: pixel com os atributos de entrada
*/
Pixel* make_pixel(int column, int r, int g, int b);
/*
* Funo insert_last(Pixel *L, Pixel *new_pixel)
* ----------------------------
* L: Lista a introduzir o pixel
* new_pixel: pixel para introduzir na lista
*
* retorno: lista com o pixel adicionado na ultima posicao
*/
Pixel* insert_last(Pixel *L, Pixel *new_pixel);
/*
* Funo free_list(Pixel *L)
* ----------------------------
* L: Lista para libertar
* TV: tamanho do vetor
*/
void free_image(Pixel* *L, int TV);
/*
* Funo free_list(Pixel *L)
* ----------------------------
* L: Lista para libertar
*/
void free_list(Pixel *L);
#endif /*PIXEL_H*/
|
C
|
int maiorSufixo(char s1[], char s2[])
{
int i = strlen(s1) - 1, j = strlen(s2) - 1, conta = 0;
while (s1[i] == s2[j])
{
conta++;
i--;
j--;
}
return conta;
}
|
C
|
//This code is used with the AlarmClockMp3 project
//it is called when incrementing the time manually and
//it ensures the time values stay within the bounds of a 12 hour clock
#include "timeKeeping.h"
void timeHourCheck(void)
{
//9 rolls over to 0
if((myclockTimeStruct.RTC_Hours & 0x0F) >= 0xA)
{
myclockTimeStruct.RTC_Hours = (myclockTimeStruct.RTC_Hours & 0x30 ) + 0x10;
}
//if incrementing passes 12 -> toggles am/pm
if(myclockTimeStruct.RTC_Hours == 0x12 )
{
myclockTimeStruct.RTC_H12 ^= 0x40;
}
//if incrementing hits hour 13, sets to 1 oclock
if(myclockTimeStruct.RTC_Hours >= 0x13 )
{
myclockTimeStruct.RTC_Hours = 0x01;
}
}
void timeMinuteCheck(void)
{
//allows 9 to roll over to 0 and 60 to 0
if((myclockTimeStruct.RTC_Minutes & 0x0F) >= 0xA)
{
myclockTimeStruct.RTC_Minutes = (myclockTimeStruct.RTC_Minutes & 0x70 ) + 0x10;
if((myclockTimeStruct.RTC_Minutes & 0x70 ) >= 0x60 )
{
myclockTimeStruct.RTC_Minutes = 0x00;
}
}
}
void alarmHourCheck(void)
{
//9 rolls over to 0
if((AlarmStruct.RTC_AlarmTime.RTC_Hours & 0x0F) >= 0xA)
{
AlarmStruct.RTC_AlarmTime.RTC_Hours = (AlarmStruct.RTC_AlarmTime.RTC_Hours & 0x30 ) + 0x10;
}
//if incrementing passes 12 -> toggles am/pm
if(AlarmStruct.RTC_AlarmTime.RTC_Hours == 0x12 )
{
AlarmStruct.RTC_AlarmTime.RTC_H12 ^= 0x40;
}
//if incrementing hits hour 13, sets to 1 oclock
if(AlarmStruct.RTC_AlarmTime.RTC_Hours >= 0x13 )
{
AlarmStruct.RTC_AlarmTime.RTC_Hours = 0x01;
}
}
void alarmMinuteCheck(void)
{
//allows 9 to roll over to 0 and 60 to 0
if((AlarmStruct.RTC_AlarmTime.RTC_Minutes & 0x0F) >= 0xA)
{
AlarmStruct.RTC_AlarmTime.RTC_Minutes = (AlarmStruct.RTC_AlarmTime.RTC_Minutes & 0x70 ) + 0x10;
if((AlarmStruct.RTC_AlarmTime.RTC_Minutes & 0x70 ) >= 0x60 )
{
AlarmStruct.RTC_AlarmTime.RTC_Minutes = 0x00;
}
}
}
|
C
|
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#define SOCKET_ERROR -1
#define BUFFER_SIZE 100
#define HOST_NAME_SIZE 255
using namespace std;
int main(int argc, char* argv[])
{
int hSocket; /* handle to socket */
struct hostent* pHostInfo; /* holds info about a machine */
struct sockaddr_in Address; /* Internet socket address stuct */
long nHostAddress;
char pBuffer[BUFFER_SIZE];
unsigned nReadAmount;
char strHostName[HOST_NAME_SIZE];
int nHostPort;
/*
if(argc < 3)
{
printf("\nUsage: download host-name host-port host-path \n");
return 0;
}
else
{
strcpy(strHostName,argv[1]);
nHostPort=atoi(argv[2]);
}
*/
extern char *optarg;
int c, times_to_download = 1, err = 0;
bool debug = false;
while( (c = getopt( argc, argv, "c:d" ) ) != -1){
switch(c){
case 'c':
times_to_download = atoi( optarg );
break;
case 'd':
debug = true;
break;
case '?':
err = 1;
break;
}
}
string path = argv[ optind + 2 ];
string host = argv[ optind ];
int port = atoi( argv[ optind + 1 ] );
printf("\nMaking a socket");
/* make a socket */
hSocket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(hSocket == SOCKET_ERROR)
{
printf("\nCould not make a socket\n");
return 0;
}
printf("\nmade 1");
/* get IP address from name */
pHostInfo=gethostbyname(host.c_str());
printf("\nmade 2");
/* copy address into long */
memcpy(&nHostAddress,pHostInfo->h_addr,pHostInfo->h_length);
/* fill address struct */
Address.sin_addr.s_addr=nHostAddress;
Address.sin_port=htons(port);
Address.sin_family=AF_INET;
/* connect to host */
if(connect(hSocket,(struct sockaddr*)&Address,sizeof(Address))
== SOCKET_ERROR)
{
printf("\nCould not connect to host\n");
return 0;
}
printf("\nmade 3");
string request = "GET / HTTP/1.1 \r\nHost: mclement.us\r\n\r\n";
printf("\nmade 4");
printf("\nWriting:\n%s",request.c_str());
printf("\nmade 5");
write(hSocket,request.c_str(),request.length());
/* read from socket into buffer
** number returned by read() and write() is the number of bytes
** read or written, with -1 being that an error occured */
nReadAmount=read(hSocket,pBuffer,BUFFER_SIZE);
printf("\nReceived \"%s\" from server\n",pBuffer);
/* write what we received back to the server */
printf("\nClosing socket\n");
/* close socket */
if(close(hSocket) == SOCKET_ERROR)
{
printf("\nCould not close socket\n");
return 0;
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
int main(void) {
int p1,p2,p3,p4,p5;
while ((p1=fork())==-1);
if (!p1) {
printf("p1 pid %d, ppid %d.\n",getpid(),getppid());
while ((p2=fork())==-1);
if (!p2) {
printf("p2 pid %d, ppid %d.\n",getpid(),getppid());
while((p4=fork())==-1);
if(!p4){
printf("p4 pid %d, ppid %d.\n",getpid(),getppid());
exit(0);
}
else
wait(0);
while((p5=fork())==-1);
if(!p5){
printf("p5 pid %d, ppid %d.\n",getpid(),getppid());
exit(0);
}
else
wait(0);
exit(0);
}
else
wait(0);
while ((p3=fork())==-1);
if (!p3) {
printf("p3 pid %d, ppid %d.\n",getpid(),getppid());
exit(0);
}
else
wait(0);
exit(0);
}
else
wait(0);
return 0;
}
|
C
|
#include<unistd.h>
#include<fcntl.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
int fdisp,nbytes;
fdisp=open("file1.txt",O_RDONLY);
if(fdisp<0)
{
perr("open");
exit(1);
}
int length=135;
char buffer[length];
nbytes=read(fdisp,buffer,length);
if(nbytes<0)
{
perr("read");
exit(2);
}
buffer[length]='\0';
printf("%s\n",buffer);
close(fdisp);
}
|
C
|
#include <stdio.h>
int main(void){
int original, i = 0;
int invertido[4];
scanf("%d", &original);
do{
invertido[i] = original%10;
i++;
original = (original - original%10)/10;
}while(original != 0);
for(i = 0; i < 4; i++){
printf("%d", invertido[i]);
}
printf("\n");
return 0;
}
|
C
|
#include "unity.h"
#include "string.h"
#include <stdlib.h>
void setUp (void) {}
void tearDown (void) {}
/**
* Test if empty string returns 0.
*/
void test_empty_string(void) {
char* test_string = "";
int length = get_string_length(test_string);
TEST_ASSERT_EQUAL(0, length);
}
/**
* Test if string of length 1 works
*/
void test_one_char(void) {
char* test_string = "A";
int length = get_string_length(test_string);
TEST_ASSERT_EQUAL(1, length);
}
/**
* Test if string of length 2 works
*/
void test_two_chars(void) {
char* test_string = "ab";
int length = get_string_length(test_string);
TEST_ASSERT_EQUAL(length, 2);
}
/**
* Test if string with special characters work
*/
void test_special_chars(void) {
char* test_string = "... ;;;";
int length = get_string_length(test_string);
TEST_ASSERT_EQUAL(length, 7);
}
/**
* Test if string with a "hole" inside still returns
* the proper length
*/
void test_hole(void) {
char* test_string = "AB\0DEFG";
int length = get_string_length(test_string);
TEST_ASSERT_EQUAL(length, 2);
}
/**
* Test if NULL argument returns -1 properly
*/
void test_null_string(void) {
char* null_string = NULL;
int length = get_string_length(null_string);
TEST_ASSERT_EQUAL(-1, length);
}
/**
* The main function for this unit test runner
*/
int main(void) {
UNITY_BEGIN();
RUN_TEST(test_empty_string);
RUN_TEST(test_one_char);
RUN_TEST(test_two_chars);
RUN_TEST(test_special_chars);
RUN_TEST(test_hole);
RUN_TEST(test_null_string);
return UNITY_END();
}
|
C
|
#include<stdio.h>
int main(int argc,char **argv)
{
if(argc<2)
{
printf("Usage...");
}
FILE* fp=NULL;
fp=fopen(argv[1],"r");
if(NULL==fp)
{
printf("fopen()error\n");
return -1;
}
char ch;
while(1)
{
ch=fgetc(fp);
if(EOF==ch)
{
printf("over");
break;
}
printf("%c",ch);
}
fclose(fp);
return 0;
}
|
C
|
#include "hash.h"
static int count_params(char* query_string, int len)
{
int count = 1;
while(*query_string)
{
if (*query_string++ == '&')
{
count++;
}
}
return count;
}
static Entry new_entry(char* arg)
{
Entry e;
e.key = strtok(arg,"=");
e.value = strtok(NULL,"=");
dd( "entry: (%s|%s)", e.key, e.value );
return e;
}
static Hash* parse_query_string(void* (*allocator)(size_t), char* args, int len)
{
int args_count = count_params(args,len);
Entry* entries = (Entry *) allocator(args_count*sizeof(Entry));
int i;
int index = 0;
for(i=0; i<args_count; i++)
{
char* pos = strchr(args, '&');
if(pos == NULL)
{
index = len;
}
else
{
index = pos - args;
}
dd( "index: %d", index );
char * arg = allocator((index + 1) * sizeof(char) );
strncpy(arg, args, index );
arg[index] = '\0';
entries[i] = new_entry(arg);
args += index + 1;
len -= index + 1;
}
Hash *hash = new_hash(allocator);
hash->entries = entries;
hash->size = args_count;
return hash;
}
static Hash* get_params(ngx_http_request_t *r)
{
char *key = malloc(r->args.len*sizeof(char));
memcpy(key,r->args.data, r->args.len);
return parse_query_string(&malloc, key, r->args.len);
}
static char* command(ngx_http_request_t *r)
{
char* path = (char *) r->uri.data;
char* pos = strchr(path, '?');
int size = pos - path;
char* command = malloc(size * sizeof(char));
strncpy(command, path+1, size-1);
command[size] = '\0';
return command;
}
|
C
|
#include <stdio.h>
// GDB will stop here
int divide_by_zero(int num) {
int result;
int zero = 0;
result = num / zero;
return result;
}
int main() {
int ret;
printf("Start to calculate\n");
ret = divide_by_zero(1);
return 0;
}
|
C
|
#include <stdio.h>
int main()
{
int year;
printf("Enter ur birthday year to check its is leap year or not?");
scanf("%d", &year);
if(year%4 == 0){
if (year%100 ==0)
{
if(year%400 == 0)
printf("%d is a leap year",year);
else
printf("%d is not a leap year",year);
}
else
printf("%d is a leap year",year);
}
else
printf("%d is not a leap year",year);
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.