language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
|---|---|
C
|
#include "../inc/libmx.h"
void *mx_memccpy(void *restrict dst, const void *restrict src, int c, size_t n) {
unsigned char *p = dst;
const unsigned char *p2 = src;
unsigned char ch = c;
size_t i = 0;
while (i < n) {
p[i] = p2[i];
if (p[i] == ch) {
return p + i + 1;
}
i++;
}
return NULL;
}
|
C
|
/**
* @file cipher.c
* @brief Implements the Kmyth cipher utility library for TPM 2.0.
*/
#include "cipher/cipher.h"
#include <string.h>
#include <openssl/rand.h>
#include <openssl/err.h>
#include "defines.h"
#include "cipher/aes_gcm.h"
#include "cipher/aes_keywrap_3394nopad.h"
#include "cipher/aes_keywrap_5649pad.h"
// Check for supported OpenSSL version
// - OpenSSL v1.1.x required for AES KeyWrap RFC5649 w/ padding
// - OpenSSL v1.1.1 is a LTS version supported until 2023-09-11
// - OpenSSL v1.1.0 is not a supported version after 2019-09-11
// - OpenSSL v1.0.2 is not a supported version after 2019-12-31
#if OPENSSL_VERSION_NUMBER < 0x10101000L
#error OpenSSL version 1.1.1 or newer is required
#endif
// cipher_list[] - array of structs that is used to specify all valid
// (e.g., implemented and supported) symmetric cipher opetions
//
// The cipher names MUST be formatted <Algorithm>/<Mode>/<Padding>/<Key Size>
const cipher_t cipher_list[] = {
{.cipher_name = "AES/GCM/NoPadding/256",
.encrypt_fn = aes_gcm_encrypt,
.decrypt_fn = aes_gcm_decrypt},
{.cipher_name = "AES/GCM/NoPadding/192",
.encrypt_fn = aes_gcm_encrypt,
.decrypt_fn = aes_gcm_decrypt},
{.cipher_name = "AES/GCM/NoPadding/128",
.encrypt_fn = aes_gcm_encrypt,
.decrypt_fn = aes_gcm_decrypt},
{.cipher_name = "AES/KeyWrap/RFC3394NoPadding/256",
.encrypt_fn = aes_keywrap_3394nopad_encrypt,
.decrypt_fn = aes_keywrap_3394nopad_decrypt},
{.cipher_name = "AES/KeyWrap/RFC3394NoPadding/192",
.encrypt_fn = aes_keywrap_3394nopad_encrypt,
.decrypt_fn = aes_keywrap_3394nopad_decrypt},
{.cipher_name = "AES/KeyWrap/RFC3394NoPadding/128",
.encrypt_fn = aes_keywrap_3394nopad_encrypt,
.decrypt_fn = aes_keywrap_3394nopad_decrypt},
{.cipher_name = "AES/KeyWrap/RFC5649Padding/256",
.encrypt_fn = aes_keywrap_5649pad_encrypt,
.decrypt_fn = aes_keywrap_5649pad_decrypt},
{.cipher_name = "AES/KeyWrap/RFC5649Padding/192",
.encrypt_fn = aes_keywrap_5649pad_encrypt,
.decrypt_fn = aes_keywrap_5649pad_decrypt},
{.cipher_name = "AES/KeyWrap/RFC5649Padding/128",
.encrypt_fn = aes_keywrap_5649pad_encrypt,
.decrypt_fn = aes_keywrap_5649pad_decrypt},
{.cipher_name = NULL,
.encrypt_fn = NULL,
.decrypt_fn = NULL},
};
cipher_t kmyth_get_cipher_t_from_string(char *cipher_string)
{
cipher_t cipher = {.cipher_name = NULL,
.encrypt_fn = NULL,
.decrypt_fn = NULL
};
// if input string is NULL, just return initialized cipher_t struct
if (cipher_string == NULL)
{
return cipher;
}
// go through cipher_list looking for user-specified cipher name
size_t i = 0;
while (cipher_list[i].cipher_name != NULL)
{
if (strncmp
(cipher_list[i].cipher_name, cipher_string,
strlen(cipher_list[i].cipher_name) + 1) == 0)
{
// found it, set cipher to this entry in cipher_list and stop looking
cipher = cipher_list[i];
break;
}
i++;
}
return cipher;
}
size_t get_key_len_from_cipher(cipher_t cipher)
{
if (cipher.cipher_name == NULL)
{
return 0;
}
char *key_len_string = NULL;
// The key length string is always after the last delimiter.
key_len_string = strrchr(cipher.cipher_name, '/') + 1;
if (key_len_string == NULL)
{
return 0;
}
int key_len = atoi(key_len_string);
if (key_len <= 0)
{
return 0;
}
return (size_t) key_len;
}
//############################################################################
// kmyth_encrypt_data
//############################################################################
int kmyth_encrypt_data(unsigned char *data,
size_t data_size,
cipher_t cipher_spec,
unsigned char **enc_data,
size_t * enc_data_size,
unsigned char **enc_key, size_t * enc_key_size)
{
if (cipher_spec.cipher_name == NULL)
{
return 1;
}
if (data == NULL || data_size == 0)
{
return 1;
}
if (enc_data == NULL)
{
return 1;
}
if (enc_key == NULL)
{
return 1;
}
if (*enc_key_size == 0)
{
return 1;
}
if(*enc_key_size * sizeof(unsigned char) > INT_MAX)
{
return 1;
}
// create symmetric key (wrapping key) of the desired size
if (!RAND_bytes(*enc_key, (int)(*enc_key_size) * (int)sizeof(unsigned char)))
{
return 1;
}
*enc_data_size = 0;
if (cipher_spec.encrypt_fn(*enc_key,
*enc_key_size,
data, data_size, enc_data, enc_data_size))
{
return 1;
}
return 0;
}
//############################################################################
// kmyth_decrypt_data
//###########################################################################
int kmyth_decrypt_data(unsigned char *enc_data,
size_t enc_data_size,
cipher_t cipher_spec,
unsigned char *key,
size_t key_size,
unsigned char **result, size_t * result_size)
{
if (enc_data == NULL || enc_data_size == 0)
{
return 1;
}
if (cipher_spec.cipher_name == NULL)
{
return 1;
}
if (key == NULL || key_size == 0)
{
return 1;
}
if (result == NULL)
{
return 1;
}
*result_size = 0;
if (cipher_spec.decrypt_fn(key, key_size, enc_data,
enc_data_size, result, result_size))
{
return 1;
}
return 0;
}
|
C
|
// PID.cpp : Defines the entry point for the console application.
//
#include"pid.h"
//PIDȫֱṹ弰ָ
PID PidPar[4]; //{1,1,1,0.3,0.1,0,0,0,5.0,2.0}
PP pid = PidPar;
///PIDʼ
void PID_Initial()
{
int i;
for(i=0;i<4;i++)
{
(pid+i)->T = 1; //ĬϲΪ1s
(pid+i)->Kp = 1; //ĬϱΪ 1
(pid+i)->Ki = 0; //ĬϻΪ 0
(pid+i)->Kd = 0; //ĬΪ 0
(pid+i)->sp = 5.0; //ĬĿֵ5.0
(pid+i)->last_out = 2.0; //u0
}
}
//ȡλPIDֵPIDȫֱ
void PID_SetValue(int ith,float Kp,float Ki, float Kd, float sp)
{
int i = ith;
(pid+i)->Kp = Kp;
(pid+i)->Ki = Ki;
(pid+i)->Kd = Kd;
(pid+i)->sp = sp;
}
//λʽPID㷨ִĵǰ
float PID_Calcu(int ith,float pv)
{
float out;
float err; //ǰƫ e(n)
float term1,term2,term3;
int i = ith;
err = (pid+i)->sp - pv; //e(n)
term1 = (pid+i)->Kp * (err - (pid+i)->last_err);
term2 = (pid+i)->Ki * err;
term3 = (pid+i)->Kd * (err + (pid+i)->prev_err - 2 * (pid+i)->last_err);
out = (pid+i)->last_out + term1 + term2 + term3;
(pid+i)->prev_err = (pid+i)->last_err;
(pid+i)->last_err = err;
(pid+i)->last_out = out;
return out;
}
/*
//û˵Kp,Ki,KdƵ ʱ䳣TiԼʱ䳣Td
void GetTimeConstant()
{
pid->Ti = pid->Kp * pid->T / pid->Ki;
pid->Td = pid->Kd * pid->T / pid->Kp;
}
*/
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_atoi_base.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jiin <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/02/05 14:10:14 by jiin #+# #+# */
/* Updated: 2020/02/06 21:36:10 by jiin ### ########.fr */
/* */
/* ************************************************************************** */
int ft_size(char *base)
{
int i;
int size;
i = 0;
size = 0;
while (base[i] != '\0')
{
i++;
size++;
}
return (size);
}
int is_valid(char *base)
{
int i;
int j;
if (base[0] == '\0' || base[1] == '\0')
return (0);
i = 0;
while (i < ft_size(base) - 1)
{
j = i + 1;
while (j < ft_size(base))
{
if (base[i] == base[j])
return (0);
j++;
}
i++;
}
i = 0;
while (i < ft_size(base))
{
if (base[i] == '+' || base[i] == '-')
return (0);
i++;
}
return (1);
}
int ft_calculate(char *str, char *base, int i, int size)
{
long long result;
int i2;
int j;
int count;
result = 0;
count = 0;
i2 = i;
while (str[i2] != '\0')
{
j = 0;
while (base[j] != '\0')
{
if (str[i2] == base[j])
{
result = (result + j) * size;
count++;
break ;
}
j++;
}
if (count != (++i2 - i))
break ;
}
return (result / size);
}
int ft_atoi_base(char *str, char *base)
{
int i;
int sign;
long long result;
int size;
if (!is_valid(base))
return (0);
i = 0;
while ((base[i] >= 9 && base[i] <= 13) || base[i] == 32)
return (0);
i = 0;
sign = 1;
while ((str[i] >= 9 && str[i] <= 13) || str[i] == 32)
i++;
while ((str[i] == '+') || (str[i] == '-'))
{
if (str[i] == '-')
sign = sign * -1;
i++;
}
size = ft_size(base);
result = ft_calculate(str, base, i, size) * sign;
return ((int)result);
}
|
C
|
#include <stdio.h>
int main() {
const float CAL = 2.54;
float calValue;
printf("Podaj wartosc w calach\n");
scanf("%f", &calValue);
float cmValue = calValue * CAL;
printf("%f cali = %f cm\n", calValue, cmValue);
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
void printSol(int colour[], int V)
{
int i;
for(i=0;i<V;i++)
printf("Colour %d for vertex %d.\n", colour[i],i+1);
}
int isSafe(int v, int **graph, int colour[], int c, int V)
{
//v is vertex which will be marked with colour c, V*V graph, colour array
int i;
for(i=0;i<V;i++)//adjacent vertices same colour return false
if(graph[v][i]!=0 && colour[i]==c)
return 0;//false
return 1;//true
}
//main algo with backtracking
int graphcol(int **graph,int m, int colour[],int v, int V)
{
int c;
if(v==V)
return 1;//solution exists, base case
for(c=1;c<=m;c++)
{
if(isSafe(v,graph,colour,c,V))
{
colour[v]=c;
if(graphcol(graph,m,colour,v+1,V)==1)//recursive backtracking step
return 1;
colour[v]=0;
}
}
return 0;
}
void gcolpossible(int **graph, int m, int V)
{
int i;
int *colour=(int *)malloc(V*sizeof(int));
for(i=0;i<V;i++)
colour[i]=0;
if(graphcol(graph,m,colour,0,V)==0)
printf("Not possible\n");
else
{
printf("Solution is possible.\n");
printSol(colour,V);
}
}
int main()
{
FILE *fp; int **graph,m,V,i,j;
if((fp=fopen("gcol.txt", "r"))==NULL)
{
printf("File not found!\n");
return 0;
}
fscanf(fp,"%d", &m);//take input for number of colours
fscanf(fp,"%d", &V);//no of vertices
graph=(int **)malloc(V*sizeof(int *));//allocate graph
for(i=0;i<V;i++)
graph[i]=(int *)malloc(V*sizeof(int));
for(i=0;i<V;i++)//take input for graph
for(j=0;j<V;j++)
fscanf(fp,"%d", &graph[i][j]);
gcolpossible(graph,m,V);
return 0;
}
|
C
|
/*
程序 12】判断 1010 到 200 之间的素数。
题目:判断 101-200 之间有多少个素数,并输出所有素数。
*/
#include <stdio.h>
#include <math.h>
int leap(int n) {
int temp = sqrt(n + 1);
for (int i = 2; i <= temp; i++) {
if (n % i == 0)
return 0;
}
return 1;
}
int main(void) {
for (int i = 100; i <= 200; i++)
if (leap(i))
printf("%d\t", i);
return 0;
}
|
C
|
#include<stdio.h>
int getArray(int);
int displayArray(int,int);
int main()
{
int arr[1000],limit;
printf("\nEnter array size : ");
scanf("%d",&limit);
arr=getArray(limit);
printf("\n\n\n ");
displayArray("%d",arr[],limit);
}
int getArray(int jk[])
{
int i,array[1000];
printf("\nEnter Array Elements : ");
for(i=0;i<jk;i++)
{
scanf("%d",&array[i]);
}
return array;
}
int displayArray(int a[],int l)
{
int i;
for(i=0;i<l;i++)
{
printf("%d",a[i]);
}
return 0;
}
|
C
|
// Athur: Mohamad Elchami Date: November 6th, 2015 Discription:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
int number, rn, n, spaces;
printf("Enter a number between 2 and 9: ");
scanf("%d", &number);
time_t t;
srand((unsigned) time(&t));
for (; number > 0; number--)
{
rn = rand() % 8 + 2;
if(rn<5)
{
printf("%d:", rn);
for (rn -= 1; rn > 0; --rn)
{
printf("%d", number);
}
printf("\n");
}
else
{
printf("%d:", rn);
for (spaces = rn; spaces > 0; spaces-- )
{
printf(" ");
}
for (n = 10 - rn; n > 0; --n )
{
printf("%d", number);
}
printf("\n");
}
}
return 0;
}
|
C
|
#include <stdio.h>
#include <string.h>
#include "base.h"
char stack[26];
int stackIdx;
char str[27];
void push(char);
char pop();
char peek();
int main(void) {
int strIdx = 0;
char alpha = 'a';
printf("Input : ");
scanf_s("%s", str, 27);
printFirst();
while (1) {
if (strIdx == strlen(str)) {
return 0;
}
if (alpha > 'z') {
printf("Impossible\n");
return -1;
}
if (peek() > str[strIdx]) {
printf("Impossible\n");
return -1;
}
if (peek() == str[strIdx]) {
printf("pop %c\n", str[strIdx]);
pop();
strIdx++;
}
else if (peek() < str[strIdx]) {
printf("push %c\n", alpha);
push(alpha);
alpha++;
}
}
}
void push(char c) {
stack[stackIdx] = c;
stackIdx++;
}
char pop() {
char popRst = stack[stackIdx-1];
stackIdx--;
return popRst;
}
char peek() {
return stack[stackIdx-1];
}
|
C
|
#include<stdio.h>
int main()
{
int n,t,y;
int jiecheng(int x);
printf("请输入正整数n:\n");
scanf("%d",&n);
t=1;
y=0;
while(t<=n)
{y=y+jiecheng(t);
t++;}
printf("结果为:%d\n",y);
return 0;
}
int jiecheng(int x)
{ int s,b;
s=1;
if(x!=0)
{for(b=1;b<=x;b++)
s=s*b;}
return(s);
}
|
C
|
/**
* @file opd_sample_files.h
* Management of sample files
*
* @remark Copyright 2002 OProfile authors
* @remark Read the file COPYING
*
* @author John Levon
* @author Philippe Elie
*/
#ifndef OPD_SAMPLE_FILES_H
#define OPD_SAMPLE_FILES_H
#include "op_list.h"
#include "odb.h"
struct opd_image;
/** one samples file when profiling on a 2.2/2.4 kernel */
struct opd_24_sfile {
/** lru list of sample file */
struct list_head lru_next;
/** the sample file itself */
odb_t sample_file;
};
/**
* sync all samples files
*/
void opd_sync_samples_files(void);
/**
* @param image the image pointer to work on
*
* close all samples files belonging to this image
*/
void opd_close_image_samples_files(struct opd_image * image);
/**
* opd_open_24_sample_file - open an image sample file
* @param image image to open file for
* @param counter counter number
* @param cpu_nr cpu number
*
* Open image sample file for the image, counter
* counter and set up memory mappings for it.
* image->kernel and image->name must have meaningful
* values.
*
* Returns 0 on success.
*/
int opd_open_24_sample_file(struct opd_image * image, int counter, int cpu_nr);
/**
* @param sfile sample file to act on
*
* put sfile at the head of samples files lru list
*/
void opd_24_sfile_lru(struct opd_24_sfile * sfile);
#endif /* OPD_SAMPLE_FILES_H */
|
C
|
#include<stdio.h>
int main()
{
int hours,minutes,seconds;
printf("\n enter seconds:");
scanf("%d",&seconds);
hours = (seconds/60*60);
printf("%d",hours);
minutes = (seconds/60);
printf("%d",minutes);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <mqueue.h>
#include <sys/stat.h>
#include <limits.h>
#include "utils.h"
char *get_customer_queue_name(void){
char *str = calloc(MAX_QNAME_LENGTH, sizeof(char));
strcpy(str, "/");
char tmp[MAX_QNAME_LENGTH];
sprintf(tmp, "%d", getpid());
strcat(str, tmp);
return str;
}
char *get_server_queue_name(void){
char *str = calloc(10, sizeof(char));
strcpy(str, "/server");
return str;
}
int stringToType(char *str){
char *pstr;
if(strcmp(str, "INIT") == 0){
return 4;
}
else if(strcmp(str, "LIST") == 0){
return 3;
}
else if(strcmp(str, "DISCONNECT") == 0){
return 2;
}
else if(strcmp(str, "STOP") == 0){
return 1;
}
else{
pstr = strtok(str, " ");
if(strcmp(pstr, "CONNECT") == 0){
return 5;
}
}
perror("Wrong order type");
return -1;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
/**
* array_range - Create an arrary from min to max numbers.
* @min: Minimum number.
* @max: Maximum number.
*
* Return: The array.
*/
int *array_range(int min, int max)
{
int *tmp;
int size = (max - min) + 1, i;
if (min > max)
{
return (NULL);
}
tmp = malloc(sizeof(int) * ((max - min) + 1));
if (tmp == NULL)
{
return (NULL);
}
for (i = 0; i < size; i++)
{
tmp[i] = min;
min++;
}
return (tmp);
}
|
C
|
/****************************************************************************
* *
* Filename: c1s1.c *
* *
* Purpose : CryptoPals Challenge 1, Set 1. *
* *
* History : Date Reason *
* 01-17-17 Created: CSE Studying *
* *
****************************************************************************/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char bin2b64Char(char*);
char* bin2b64Str_test(char*);
char* hexstr2bin(char*);
int string_compare(char*, char*);
void testSuite(void);
int main(void){
char* hex = "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d";
char* result = "SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t";
//char* hex = "8726f6f6d";
//char* result = "hyb29t";
char* bin;
char* b64;
//testSuite();
printf("Performing Challenge 1 of Set 1 (CryptoPals) ...\n\n");
printf("Length of hex string: %d\n", strlen(hex));
bin = hexstr2bin(hex);
b64 = bin2b64Str_test(bin);
printf("Printing desired conversion: %s\n", result);
printf("Printing your conversion: %s\n\n", b64);
if(string_compare(result,b64)==1)
printf("...Success!\n\n");
else{
printf("...Failure!\n\n");
if(strlen(result)==strlen(b64)){
printf("At least you got the correct number of Base64 symbols:\n");
}else{
printf("You did not even get the correct number of Base64 symbols:\n");
}
printf("The correct number of Base64 symbols after conversion is %d.\n", strlen(result));
printf("The number of Base64 symbols after conversion you have is %d.\n\n", strlen(b64));
}
return 0;
}
|
C
|
/**
* @brief It defines the die test
*
* @file inventory_test.c
* @author Guillermo Hoyo
* @version 1.0
* @date 31-03-2017
* @copyright GNU Public License
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "inventory.h"
#include "inventory_test.h"
#include "test.h"
#define MAX_TESTS 20
/**
* @brief Funcion principal de pruebas para el modulo inventory.
*
* Dos modos de ejecucion:
* 1.-Si se ejecuta sin parametros se ejecutan todas las pruebas
* 2.-Si se ejecuta con un numero entre 1 y el numero de pruebas solo ejecuta
* la prueba indicada
*
*/
int main(int argc, char** argv) {
int test = 0;
int all = 1;
if (argc < 2) {
printf("Running all test for module Inventory:\n");
} else {
test = atoi(argv[1]);
all = 0;
printf("Running test %d:\t", test);
if (test < 1 || test > MAX_TESTS) {
printf("Error: unknown test %d\t", test);
exit(EXIT_SUCCESS);
}
}
if (all || test == 1) test1_inventory_create();
if (all || test == 2) test2_inventory_create();
if (all || test == 3) test1_inventory_set_ids();
if (all || test == 4) test2_inventory_set_ids();
if (all || test == 5) test3_inventory_set_ids();
if (all || test == 6) test4_inventory_set_ids();
if (all || test == 7) test1_inventory_set_max_objects();
if (all || test == 8) test2_inventory_set_max_objects();
if (all || test == 9) test1_inventory_add_id();
if (all || test == 10) test2_inventory_add_id();
if (all || test == 11) test1_inventory_delete_id();
if (all || test == 12) test2_inventory_delete_id();
if (all || test == 13) test1_inventory_get_ids();
if (all || test == 14) test2_inventory_get_ids();
if (all || test == 16) test1_inventory_get_max_objects();
if (all || test == 17) test2_inventory_get_max_objects();
if (all || test == 18) test1_inventory_get_numids();
if (all || test == 19) test2_inventory_get_numids();
if (all || test == 20) test3_inventory_get_numids();
PRINT_PASSED_PERCENTAGE;
return 1;
}
void test1_inventory_create(){
int result = inventory_create(8)!=NULL;
PRINT_TEST_RESULT(result);
}
void test2_inventory_create(){
Inventory *i;
i = inventory_create(8);
PRINT_TEST_RESULT(inventory_get_max_objects(i) == 8);
}
void test1_inventory_set_ids(){
Inventory *i = NULL;
Set * s = NULL;
PRINT_TEST_RESULT(inventory_set_ids(i, s) == ERROR);
}
void test2_inventory_set_ids(){
Inventory *i = inventory_create(8);
Set * s = NULL;
PRINT_TEST_RESULT(inventory_set_ids(i, s) == ERROR);
}
void test3_inventory_set_ids(){
Inventory *i = NULL;
Set * s = set_create();
PRINT_TEST_RESULT(inventory_set_ids(i, s) == ERROR);
}
void test4_inventory_set_ids(){
Inventory *i = inventory_create(8);
Set * s = set_create();
PRINT_TEST_RESULT(inventory_set_ids(i, s) == OK);
}
void test1_inventory_set_max_objects(){
Inventory *i = NULL;
PRINT_TEST_RESULT(inventory_set_max_objects(i, 8) == ERROR);
}
void test2_inventory_set_max_objects(){
Inventory *i = inventory_create(8);
PRINT_TEST_RESULT(inventory_set_max_objects(i, 8) == OK);
}
void test1_inventory_add_id(){
Inventory *i = NULL;
PRINT_TEST_RESULT(inventory_add_id(i, 8) == ERROR);
}
void test2_inventory_add_id(){
Inventory *i = inventory_create(8);
PRINT_TEST_RESULT(inventory_add_id(i, 8) == OK);
}
void test1_inventory_delete_id(){
Inventory *i = NULL;
PRINT_TEST_RESULT(inventory_add_id(i, 8) == ERROR);
}
void test2_inventory_delete_id(){
Inventory *i = inventory_create(8);
PRINT_TEST_RESULT(inventory_add_id(i, 8) == OK);
}
void test1_inventory_get_ids(){
Inventory * i = NULL;
PRINT_TEST_RESULT(inventory_get_ids(i) == NULL);
}
void test2_inventory_get_ids(){
Inventory * i = inventory_create(8);
Set * s = set_create();
inventory_set_ids(i, s);
PRINT_TEST_RESULT(inventory_get_ids(i) != NULL);
}
void test1_inventory_get_max_objects(){
Inventory * i = NULL;
PRINT_TEST_RESULT(inventory_get_max_objects(i) == -1);
}
void test2_inventory_get_max_objects(){
Inventory * i = inventory_create(8);
PRINT_TEST_RESULT(inventory_get_max_objects(i) == 8);
}
void test1_inventory_get_numids(){
Inventory * i = NULL;
PRINT_TEST_RESULT(inventory_get_numids(i) == ERROR);
}
void test2_inventory_get_numids(){
Inventory * i = inventory_create(8);
PRINT_TEST_RESULT(inventory_get_numids(i) == 0);
}
void test3_inventory_get_numids(){
Inventory * i = inventory_create(8);
inventory_add_id(i, 8);
PRINT_TEST_RESULT(inventory_get_numids(i) == 1);
}
|
C
|
#include <stdio.h>
typedef struct BST
{
int data;
struct BST * lchild, * rchild;
} BinaryTreeNode;
BinaryTreeNode* Convert(BinaryTreeNode* pRootOfTree)
{
BinaryTreeNode * pLastNodeInList = NULL;
ConvertNode(pRootOfTree, &pLastNodeInList);
// pLastNodeInList points to the tail of double-linked list,
// but we need to return its head
BinaryTreeNode *pHeadOfList = pLastNodeInList;
while(pHeadOfList != NULL && pHeadOfList->m_pLeft != NULL)
pHeadOfList = pHeadOfList->m_pLeft;
return pHeadOfList;
}
void ConvertNode(BinaryTreeNode* pNode, BinaryTreeNode** pLastNodeInList)
{
if(pNode == NULL)
return;
BinaryTreeNode *pCurrent = pNode;
if (pCurrent->m_pLeft != NULL)
ConvertNode(pCurrent->m_pLeft, pLastNodeInList);
pCurrent->m_pLeft = *pLastNodeInList;
if(*pLastNodeInList != NULL)
(*pLastNodeInList)->m_pRight = pCurrent;
*pLastNodeInList = pCurrent;
if (pCurrent->m_pRight != NULL)
ConvertNode(pCurrent->m_pRight, pLastNodeInList);
}
|
C
|
/*
prog4.c
Richard Coffey
ECE 223
Program #4
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include "functions.h"
#define HSZ 8191
//prototypes
stats_table *parse_file(char *filename, hash_table *hash, int book_num, stats_table *stats);
void print_stats(hash_table *hash, stats_table *stats);
int main(int argc, char **argv) {
hash_table *hash;
char *book1;
char *book2;
int c;
if (argc == 1) {
printf("Please use this format './prog4 -d book1 -f book2'\n");
exit(1);
}
/*checking flags with getopt*/
while ((c = getopt(argc, argv, "d:f:")) != -1) {
switch(c) {
case 'd':
book1 = optarg;
break;
case 'f':
book2 = optarg;
break;
case '?':
printf("\nError using flag\n");
return(1);
default:
abort();
}
}
stats_table *stats = calloc(1, sizeof(stats_table));
//initialize hash table
hash = hash_init();
stats = parse_file(book1, hash, 0, stats);
stats = parse_file(book2, hash, 1, stats);
print_stats(hash, stats);
hash_free(hash);
free(stats);
return 0;
}
stats_table *parse_file(char *filename, hash_table *hash, int book_num, stats_table *stats)
{
FILE *fpt;
char *buf = NULL;
size_t bufsize = 128;
// int hash_val;
book_word *found_word;
book_word *temp_word;
//book_word *inserted_word;
buf = (char *)malloc(bufsize * sizeof(char));
if (buf == NULL) {
printf("\nUnable to allocate buffer\n");
exit(1);
}
if ((fpt = fopen(filename, "r")) == NULL) {
printf("Cannot Read from File \"%s\"\n", filename);
exit (1);
}
//with the file open, we read each word, hash it, place it in tree
while (getline(&buf, &bufsize, fpt) != -1) {
temp_word = (book_word *)malloc(sizeof(book_word));
buf[strcspn(buf, "\r\n")] = 0;
//printf("%s", buf);
//implying that this is a new word
strcpy(temp_word->word, buf); //the key
temp_word->count[0] = 0;
temp_word->count[1] = 0;
temp_word->len = strlen(buf);
// hash_val = h(temp_word->word, HSZ); //index of array
found_word = hash_search(hash, temp_word->word); //search for word
//if the returned pointer is NULL, then the word was not found
if (found_word == NULL) {
//insert the word
temp_word->count[book_num] = 1;
hash_insert(hash, buf, temp_word);
}
//if this word has already been entered
else {
// printf("%s", found_word->word);
found_word->count[book_num]++;
}
//keeping track of book word counts
if (book_num == 0) {
stats->drac_word_count++;
}
else if (book_num == 1) {
stats->frank_word_count++;
}
stats->com_word_count++;
found_word = NULL;
}
fclose(fpt);
return(stats);
}
void print_stats(hash_table *hash, stats_table *stats) {
int count;
int i;
book_word *temp;
book_word *populate = calloc(1, sizeof(book_word));
//populate table
for (i = 0; i < 5; i++) {
stats->drac_large[i] = populate;
stats->frank_large[i] = populate;
stats->com_large[i] = populate;
stats->drac_lfreq[i] = populate;
stats->frank_lfreq[i] = populate;
stats->com_lfreq[i] = populate;
}
for (i = 0; i < 15; i++) {
stats->drac_mfreq[i] = populate;
stats->frank_mfreq[i] = populate;
stats->com_mfreq[i] = populate;
}
for (count = 0; count < (HSZ + 1); count++) {
if ((temp = list_first(hash->table[count])) != NULL) {
// printf("%s", hash->table[count]);
if (temp->count[0] != 0) {
stats_word(temp, stats, 0);
}
if (temp->count[1] != 0) {
stats_word(temp, stats, 1);
}
if (temp->count[1] != 0 && temp->count[0] != 0) {
stats_word(temp, stats, 2);
}
//check for unique words
if ((temp->count[0] == 0) && (temp->count[1] != 0)) {
stats->frank_uni += 1;
}
if ((temp->count[1] == 0) && (temp->count[0] != 0)) {
stats->drac_uni += 1;
// printf("%d\n", stats->drac_uni);
}
if (temp->count[0] != 0 && temp->count[1] != 0) {
stats->com_uni += 1;
}
//putting stuff into array
//word_tables
while((temp = list_next(hash->table[count])) != NULL) {
if (temp->count[0] != 0) {
stats_word(temp, stats, 0);
}
if (temp->count[1] != 0) {
stats_word(temp, stats, 1);
}
if (temp->count[1] != 0 && temp->count[0] != 0) {
stats_word(temp, stats, 2);
}
//check for unique words
if ((temp->count[0] == 0) && (temp->count[1] != 0)) {
stats->frank_uni += 1;
}
if ((temp->count[1] == 0) && (temp->count[0] != 0)) {
stats->drac_uni += 1;
// printf("%d\n", stats->drac_uni);
}
if ((temp->count[0] != 0) && (temp->count[1] != 0)) {
stats->com_uni += 1;
}
}
}
}
//putting stuff into arrays
/*
for the largest you have a array size 21;
You start at the back (I = 19;);
Then while a[i] < word, a[i+1] = a[i];
When you find where the new word fits, insert it.
*/
// Dracula
printf("\nECE2230 Fall 2017 Text Hashing Project\nRichard Coffey\n\n");
printf("Dracula:\n\n");
//printf("Number of lines processed\t %d", linesproc);
printf("Number of words processed:\t %d\n", stats->drac_word_count);
printf("Number of unique words:\t %d\n\n", stats->drac_uni);
printf("5 largest words\n");
printf("%s\t\t%d\n", stats->drac_large[0]->word, stats->drac_large[0]->count[0]);
printf("%s\t\t%d\n", stats->drac_large[1]->word, stats->drac_large[1]->count[0]);
printf("%s\t\t%d\n", stats->drac_large[2]->word, stats->drac_large[2]->count[0]);
printf("%s\t\t%d\n", stats->drac_large[3]->word, stats->drac_large[3]->count[0]);
printf("%s\t\t%d\n\n", stats->drac_large[4]->word, stats->drac_large[4]->count[0]);
printf("15 most frequently used words\n");
printf("%s\t\t%d\n", stats->drac_mfreq[0]->word, stats->drac_mfreq[0]->count[0]);
printf("%s\t\t%d\n", stats->drac_mfreq[1]->word, stats->drac_mfreq[1]->count[0]);
printf("%s\t\t%d\n", stats->drac_mfreq[2]->word, stats->drac_mfreq[2]->count[0]);
printf("%s\t\t%d\n", stats->drac_mfreq[3]->word, stats->drac_mfreq[3]->count[0]);
printf("%s\t\t%d\n", stats->drac_mfreq[4]->word, stats->drac_mfreq[4]->count[0]);
printf("%s\t\t%d\n", stats->drac_mfreq[5]->word, stats->drac_mfreq[5]->count[0]);
printf("%s\t\t%d\n", stats->drac_mfreq[6]->word, stats->drac_mfreq[6]->count[0]);
printf("%s\t\t%d\n", stats->drac_mfreq[7]->word, stats->drac_mfreq[7]->count[0]);
printf("%s\t\t%d\n", stats->drac_mfreq[8]->word, stats->drac_mfreq[8]->count[0]);
printf("%s\t\t%d\n", stats->drac_mfreq[9]->word, stats->drac_mfreq[9]->count[0]);
printf("%s\t\t%d\n", stats->drac_mfreq[10]->word, stats->drac_mfreq[10]->count[0]);
printf("%s\t\t%d\n", stats->drac_mfreq[11]->word, stats->drac_mfreq[11]->count[0]);
printf("%s\t\t%d\n", stats->drac_mfreq[12]->word, stats->drac_mfreq[12]->count[0]);
printf("%s\t\t%d\n", stats->drac_mfreq[13]->word, stats->drac_mfreq[13]->count[0]);
printf("%s\t\t%d\n\n", stats->drac_mfreq[14]->word, stats->drac_mfreq[14]->count[0]);
printf("15 least frequently used words\n");
printf("%s\t\t%d\n", stats->drac_lfreq[0]->word, stats->drac_lfreq[0]->count[0]);
printf("%s\t\t%d\n", stats->drac_lfreq[1]->word, stats->drac_lfreq[1]->count[0]);
printf("%s\t\t%d\n", stats->drac_lfreq[2]->word, stats->drac_lfreq[2]->count[0]);
printf("%s\t\t%d\n", stats->drac_lfreq[3]->word, stats->drac_lfreq[3]->count[0]);
printf("%s\t\t%d\n\n", stats->drac_lfreq[4]->word, stats->drac_lfreq[4]->count[0]);
//Frankenstine
printf("Frankenstine:\n\n");
// printf("Number of lines processed\t %d", linesproc);
printf("Number of words processed:\t %d\n", stats->frank_word_count);
printf("Number of unique words:\t %d\n\n", stats->frank_uni);
printf("5 largest words\n");
printf("%s\t\t%d\n", stats->frank_large[0]->word, stats->frank_large[0]->count[1]);
printf("%s\t\t%d\n", stats->frank_large[1]->word, stats->frank_large[1]->count[1]);
printf("%s\t\t%d\n", stats->frank_large[2]->word, stats->frank_large[2]->count[1]);
printf("%s\t\t%d\n", stats->frank_large[3]->word, stats->frank_large[3]->count[1]);
printf("%s\t\t%d\n\n", stats->frank_large[4]->word, stats->frank_large[4]->count[1]);
printf("15 most frequently used words\n");
printf("%s\t\t%d\n", stats->frank_mfreq[0]->word, stats->frank_mfreq[0]->count[1]);
printf("%s\t\t%d\n", stats->frank_mfreq[1]->word, stats->frank_mfreq[1]->count[1]);
printf("%s\t\t%d\n", stats->frank_mfreq[2]->word, stats->frank_mfreq[2]->count[1]);
printf("%s\t\t%d\n", stats->frank_mfreq[3]->word, stats->frank_mfreq[3]->count[1]);
printf("%s\t\t%d\n", stats->frank_mfreq[4]->word, stats->frank_mfreq[4]->count[1]);
printf("%s\t\t%d\n", stats->frank_mfreq[5]->word, stats->frank_mfreq[5]->count[1]);
printf("%s\t\t%d\n", stats->frank_mfreq[6]->word, stats->frank_mfreq[6]->count[1]);
printf("%s\t\t%d\n", stats->frank_mfreq[7]->word, stats->frank_mfreq[7]->count[1]);
printf("%s\t\t%d\n", stats->frank_mfreq[8]->word, stats->frank_mfreq[8]->count[1]);
printf("%s\t\t%d\n", stats->frank_mfreq[9]->word, stats->frank_mfreq[9]->count[1]);
printf("%s\t\t%d\n", stats->frank_mfreq[10]->word, stats->frank_mfreq[10]->count[1]);
printf("%s\t\t%d\n", stats->frank_mfreq[11]->word, stats->frank_mfreq[11]->count[1]);
printf("%s\t\t%d\n", stats->frank_mfreq[12]->word, stats->frank_mfreq[12]->count[1]);
printf("%s\t\t%d\n", stats->frank_mfreq[13]->word, stats->frank_mfreq[13]->count[1]);
printf("%s\t\t%d\n\n", stats->frank_mfreq[14]->word, stats->frank_mfreq[14]->count[1]);
printf("15 least frequently used words\n");
printf("%s\t\t%d\n", stats->frank_lfreq[0]->word, stats->frank_lfreq[0]->count[1]);
printf("%s\t\t%d\n", stats->frank_lfreq[1]->word, stats->frank_lfreq[1]->count[1]);
printf("%s\t\t%d\n", stats->frank_lfreq[2]->word, stats->frank_lfreq[2]->count[1]);
printf("%s\t\t%d\n", stats->frank_lfreq[3]->word, stats->frank_lfreq[3]->count[1]);
printf("%s\t\t%d\n\n", stats->frank_lfreq[4]->word, stats->frank_lfreq[4]->count[1]);
//Common
printf("Common vocabulary:\n\n");
printf("Number of unique words:\t%d\n\n", stats->com_uni);
printf("5 largest words\n");
printf("%s\t\t%d\n", stats->com_large[0]->word, stats->com_large[0]->count[0]);
printf("%s\t\t%d\n", stats->com_large[1]->word, stats->com_large[1]->count[0]);
printf("%s\t\t%d\n", stats->com_large[2]->word, stats->com_large[2]->count[0]);
printf("%s\t\t%d\n", stats->com_large[3]->word, stats->com_large[3]->count[0]);
printf("%s\t\t%d\n\n", stats->com_large[4]->word, stats->com_large[4]->count[0]);
printf("15 most frequently used words\n");
printf("%s\t\t%d\n", stats->com_mfreq[0]->word, stats->com_mfreq[0]->count[0]);
printf("%s\t\t%d\n", stats->com_mfreq[1]->word, stats->com_mfreq[1]->count[0]);
printf("%s\t\t%d\n", stats->com_mfreq[2]->word, stats->com_mfreq[2]->count[0]);
printf("%s\t\t%d\n", stats->com_mfreq[3]->word, stats->com_mfreq[3]->count[0]);
printf("%s\t\t%d\n", stats->com_mfreq[4]->word, stats->com_mfreq[4]->count[0]);
printf("%s\t\t%d\n", stats->com_mfreq[5]->word, stats->com_mfreq[5]->count[0]);
printf("%s\t\t%d\n", stats->com_mfreq[6]->word, stats->com_mfreq[6]->count[0]);
printf("%s\t\t%d\n", stats->com_mfreq[7]->word, stats->com_mfreq[7]->count[0]);
printf("%s\t\t%d\n", stats->com_mfreq[8]->word, stats->com_mfreq[8]->count[0]);
printf("%s\t\t%d\n", stats->com_mfreq[9]->word, stats->com_mfreq[9]->count[0]);
printf("%s\t\t%d\n", stats->com_mfreq[10]->word, stats->com_mfreq[10]->count[0]);
printf("%s\t\t%d\n", stats->com_mfreq[11]->word, stats->com_mfreq[11]->count[0]);
printf("%s\t\t%d\n", stats->com_mfreq[12]->word, stats->com_mfreq[12]->count[0]);
printf("%s\t\t%d\n", stats->com_mfreq[13]->word, stats->com_mfreq[13]->count[0]);
printf("%s\t\t%d\n\n", stats->com_mfreq[14]->word, stats->com_mfreq[14]->count[0]);
printf("15 least frequently used words\n");
printf("%s\t\t%d\n", stats->com_lfreq[0]->word, stats->com_lfreq[0]->count[0]);
printf("%s\t\t%d\n", stats->com_lfreq[1]->word, stats->com_lfreq[1]->count[0]);
printf("%s\t\t%d\n", stats->com_lfreq[2]->word, stats->com_lfreq[2]->count[0]);
printf("%s\t\t%d\n", stats->com_lfreq[3]->word, stats->com_lfreq[3]->count[0]);
printf("%s\t\t%d\n", stats->com_lfreq[4]->word, stats->com_lfreq[4]->count[0]);
}
|
C
|
#include <stdio.h>
int main()
{
char a[10];int i,l=0;
scanf("%s",&a);
for(i=0;a[i]!='\0';i++)
{
l++;
}
printf("%d",l);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv)
{
int mat1[10][10];
int mat2[10][10];
int arows = 0;
int acols = 0;
int brows = 0;
int bcols = 0;
int xx = 0; int yy = 0;
int space = 0;
char line[1024];
char *line_res;
char **args;
args = malloc(1024 *sizeof(char*));
line_res = malloc(1024 *sizeof(char*));
while(line[0] != '\n' && space < 1)
{
line_res = fgets(line, 1024, stdin);
if(line[0] == '\n')
{
if(space == 0)
{arows = xx;}
else
{brows = xx;}
xx = 0;
space++;
}
//remove the new line character to avoid it being included by strtok
int len = strlen(line);
if( len > 0 && line[len-1] == '\n')
{ line[len-1] = '\0'; }
//use strtok function to split the arguments up
int argc1 = 0;
int argc2 = 0;
char *token;
token = strtok(line," ");
while (token != NULL) {
args[argc1] = token;
token = strtok (NULL," ");
argc1++;
}
if(space == 0)
{acols = argc1;}
else
{bcols = argc1;}
for(yy = 0; yy < argc1; yy++)
{
mat1[xx][yy] = atoi(args[yy]);
}
xx++;
}
printf("arows:%d acols:%d \n", arows, acols);
int counting = 0; int c2 = 0;
for(counting = 0; counting < acols; counting++)
{
for(c2 = 0; c2 < arows; c2++)
{
printf("%d ",mat1[c2][counting]);
}
printf("\n");
}
}
|
C
|
/*
* The information in this file is
* Copyright(c) 2012, Gabriele Colosimo, Andrea Nascetti <gabriele.colosimo, andrea.nascetti>@uniroma1.it
* and is subject to the terms and conditions of the
* GNU Lesser General Public License Version 2.1
* The license text is available from
* http://www.gnu.org/licenses/lgpl.html
*/
/* Programma di Runge-Kutta:
*
* Soluzione di un sistema di due equazioni differenziali del primo ordine
* con il metodo di Runge-Kutta del IV ordine
*
* Funzioni:
* - f(x, y, z)
* - g(x, y, z)
*
* Input:
* - x0, y0, z0: condizione iniziale
* - h: passo di discretizzazione
* - n: numero di passi
*
* Output:
* - xi: nodo i-esimo
* - yi: approssimazione al nodo xi
*
*/
#include <stdio.h>
double f(double x, double y, double z);
double g(double x, double y, double z);
int main()
{
// Allocazione e inizializzazione delle variabili
int n=0, k=0;
double x0=0., y0=0., z0, h=0.;
double xi=0., yi=0., zi=0.;
FILE *OUT = NULL;
// Recupero dei dati dati di input
printf("Inserire il numero n di passi = \n");
scanf("%d", &n);
printf("Inserire il valore di h = \n");
scanf("%lf", &h);
printf("Inserire il valore di x0 = \n");
scanf("%lf", &x0);
printf("Inserire il valore di y0 = \n");
scanf("%lf", &y0);
printf("Inserire il valore di z0 = \n");
scanf("%lf", &z0);
/* Apertura file di output */
OUT = fopen("Runge-Kutta_sistema.txt", "w");
// Controllo apertura file
if(OUT == NULL)
{
printf("Errore nell'apertura del file\n");
printf("Riprovare\n");
return(1);
} /* if */
// Implementazione dell'algoritmo di Runge-Kutta
xi = x0;
yi = y0;
zi = z0;
double k1=0, k2=0, k3=0, k4=0; /* Incrementa funzione y */
double t1=0, t2=0, t3=0, t4=0; /* Incrementa funzione z */
for (k=1; k<=n; k++)
{
k1 = f(xi, yi, zi);
t1 = g(xi, yi, zi);
k2 = f(xi + 0.5*h, yi + 0.5*h*k1, zi + 0.5*h*t1);
t2 = g(xi + 0.5*h, yi + 0.5*h*k1, zi + 0.5*h*t1);
k3 = f(xi + 0.5*h, yi + 0.5*h*k2, zi + 0.5*h*t2);
t3 = g(xi + 0.5*h, yi + 0.5*h*k2, zi + 0.5*h*t2);
k4 = f(xi + h, yi + h*k3, zi + h*t3);
t4 = g(xi + h, yi + h*k3, zi + h*t3);
yi = yi + h*(k1 + 2.0*k2 + 2.0*k3 + k4)/6.0;
zi = zi + h*(t1 + 2.0*t2 + 2.0*t3 + t4)/6.0;
xi = xi + h;
// Stampa dei risultati
fprintf(OUT, "%4d % 14.8lf % 14.8lf % 14.8lf\n", k, xi, yi, zi);
}
fclose(OUT);
return 0;
}
// Implementazione della funzione f(x, y, z) del problema di Cauchy
double f(double x, double y, double z)
{
return z;
}
// Implementazione della funzione g(x, y, z) del problema di Cauchy
double g(double x, double y, double z)
{
return (-2. * 0.1 * z) - y;
}
|
C
|
#include<stdio.h>
int main()
{
int x,y,z;
printf("enter the three numbers");
scanf("%d%d%d",&x,&y,&z);
if(x>y && x>z)
printf("the largest numbers is %d",x);
else if(y>x && y>z)
printf("the largest numbers is %d",y);
else
printf("the largest numbers is %d",z);
return 0;
}
|
C
|
//#pragma once
////#include <d3dx9math.h>
//#include "Vector3.h"
////#include "math.h"
//
//class Quaternion;
//
//static float m4Ident[4][4] =
//{
// { 1.0f, 0.0f, 0.0f, 0.0f },
// { 0.0f, 1.0f, 0.0f, 0.0f },
// { 0.0f, 0.0f, 1.0f, 0.0f },
// { 0.0f, 0.0f, 0.0f, 1.0f }
//};
//
//class Matrix4
//{
//public:
// float matrix[4][4];
//
// Matrix4();
// ~Matrix4();
//
// Matrix4(float inMat[4][4])
// {
// memcpy(matrix, inMat, 16 * sizeof(float));
// }
//
// inline Vector3 GetTranslation() const
// {
// return Vector3(matrix[3][0], matrix[3][1], matrix[3][2]);
// }
//
// inline Vector3 GetScale() const
// {
// Vector3 scaleVec;
// scaleVec.x = Vector3(matrix[0][0], matrix[0][1], matrix[0][2]).Length();
// scaleVec.y = Vector3(matrix[1][0], matrix[1][1], matrix[1][2]).Length();
// scaleVec.z = Vector3(matrix[2][0], matrix[2][1], matrix[2][2]).Length();
// return scaleVec;
// }
//
// static Matrix4 CreateTranslation(const Vector3& trans)
// {
// float temp[4][4] =
// {
// { 1.0f, 0.0f, 0.0f, 0.0f },
// { 0.0f, 1.0f, 0.0f, 0.0f },
// { 0.0f, 0.0f, 1.0f, 0.0f },
// { trans.x, trans.y, trans.z, 1.0f }
// };
// return Matrix4(temp);
// }
//
// inline static Matrix4 CreateScale(float scale)
// {
// float temp[4][4] =
// {
// { scale, 0.0f, 0.0f, 0.0f },
// { 0.0f, scale, 0.0f, 0.0f },
// { 0.0f, 0.0f, scale, 0.0f },
// { 0.0f, 0.0f, 0.0f, 1.0f }
// };
// return Matrix4(temp);
// }
//
// inline static Matrix4 CreateScale(float xScale, float yScale, float zScale)
// {
// float temp[4][4] =
// {
// { xScale, 0.0f, 0.0f, 0.0f },
// { 0.0f, yScale, 0.0f, 0.0f },
// { 0.0f, 0.0f, zScale, 0.0f },
// { 0.0f, 0.0f, 0.0f, 1.0f }
// };
// return Matrix4(temp);
// }
//
// inline static Matrix4 CreateScale(const Vector3& scaleVec)
// {
// return Matrix4::CreateScale(scaleVec.x, scaleVec.y, scaleVec.z);
// }
//
// inline static Matrix4 CreateRotationX(float angleDegrees)
// {
// angleDegrees *= (3.1415926f / 180.0f);
//
// float mat[4][4] =
// {
// {1.0f, 0.0f, 0.0f, 0.0f},
// {0.0f, cosf(angleDegrees), sinf(angleDegrees), 0.0f},
// {0.0f, -sinf(angleDegrees), cosf(angleDegrees), 0.0f},
// {0.0f, 0.0f, 0.0f, 1.0f}
// };
// return Matrix4(mat);
// }
//
// inline static Matrix4 CreateRotationY(float angle)
// {
// angle *= (3.1415926f / 180.0f);
//
// float mat[4][4] =
// {
// { cosf(angle), 0.0f, -sinf(angle), 0.0f },
// { 0.0f, 1.0f, 0.0f, 0.0f },
// { sinf(angle), 0.0f, cosf(angle), 0.0f },
// { 0.0f, 0.0f, 0.0f, 1.0f }
// };
// return Matrix4(mat);
// }
//
// inline static Matrix4 CreateRotationZ(float angle)
// {
// angle *= (3.1415926f / 180.0f);
//
// float mat[4][4] =
// {
// { cosf(angle), sinf(angle), 0.0f, 0.0f },
// { -sinf(angle), cosf(angle), 0.0f, 0.0f },
// { 0.0f, 0.0f, 1.0f, 0.0f },
// { 0.0f, 0.0f, 0.0f, 1.0f }
// };
// return Matrix4(mat);
// }
//
// static Matrix4 CreateFromQuat(const class Quaternion& q);
//
// inline Vector3 GetForward() const
// {
// return GetZAxis();
// }
//
// inline Vector3 GetRight() const
// {
// return GetXAxis();
// }
//
// inline Vector3 GetUp() const
// {
// return GetYAxis();
// }
//
// // Forward
// inline Vector3 GetXAxis() const
// {
// return Vector3(matrix[0][0], matrix[0][1], matrix[0][2]);
// }
//
// // Left
// inline Vector3 GetYAxis() const
// {
// return Vector3(matrix[1][0], matrix[1][1], matrix[1][2]);
// }
//
// // Up
// inline Vector3 GetZAxis() const
// {
// return Vector3(matrix[2][0], matrix[2][1], matrix[2][2]);
// }
//
// static Matrix4 CreateLookAtMatrix(const Vector3& eye, const Vector3& at, const Vector3& up);
//
// static Matrix4 CreateOrtho(float width, float height, float nearVal, float farVal)
// {
// float temp[4][4] =
// {
// { 2.0f / width, 0.0f, 0.0f, 0.0f },
// { 0.0f, 2.0f / height, 0.0f, 0.0f },
// { 0.0f, 0.0f, 1.0f / (farVal - nearVal), 0.0f },
// { 0.0f, 0.0f, nearVal / (nearVal - farVal), 1.0f }
// //{ 0.0f, 0.0f, 0.0f, 1.0f }
// };
// return Matrix4(temp);
// }
//
// static Matrix4 CreatePerspectiveFOV(float fovY, float width, float height, float nearVal, float farVal)
// {
// float yScale = 1.0f / tanf(fovY / 2.0f);
// float xScale = yScale * height / width;
// float temp[4][4] =
// {
// { xScale, 0.0f, 0.0f, 0.0f },
// { 0.0f, yScale, 0.0f, 0.0f },
// { 0.0f, 0.0f, farVal / (farVal - nearVal), 1.0f },
// { 0.0f, 0.0f, -nearVal * farVal / (farVal - nearVal), 0.0f }
// };
// return Matrix4(temp);
// }
//
// static Matrix4 CreateViewMatrix(Vector3& pos, Vector3& target, Vector3&up);
//
// // Matrix multiplication (a * b)
// friend Matrix4 operator*(const Matrix4& a, const Matrix4& b)
// {
// Matrix4 retVal;
// // row 0
// retVal.matrix[0][0] =
// a.matrix[0][0] * b.matrix[0][0] +
// a.matrix[0][1] * b.matrix[1][0] +
// a.matrix[0][2] * b.matrix[2][0] +
// a.matrix[0][3] * b.matrix[3][0];
//
// retVal.matrix[0][1] =
// a.matrix[0][0] * b.matrix[0][1] +
// a.matrix[0][1] * b.matrix[1][1] +
// a.matrix[0][2] * b.matrix[2][1] +
// a.matrix[0][3] * b.matrix[3][1];
//
// retVal.matrix[0][2] =
// a.matrix[0][0] * b.matrix[0][2] +
// a.matrix[0][1] * b.matrix[1][2] +
// a.matrix[0][2] * b.matrix[2][2] +
// a.matrix[0][3] * b.matrix[3][2];
//
// retVal.matrix[0][3] =
// a.matrix[0][0] * b.matrix[0][3] +
// a.matrix[0][1] * b.matrix[1][3] +
// a.matrix[0][2] * b.matrix[2][3] +
// a.matrix[0][3] * b.matrix[3][3];
//
// // row 1
// retVal.matrix[1][0] =
// a.matrix[1][0] * b.matrix[0][0] +
// a.matrix[1][1] * b.matrix[1][0] +
// a.matrix[1][2] * b.matrix[2][0] +
// a.matrix[1][3] * b.matrix[3][0];
//
// retVal.matrix[1][1] =
// a.matrix[1][0] * b.matrix[0][1] +
// a.matrix[1][1] * b.matrix[1][1] +
// a.matrix[1][2] * b.matrix[2][1] +
// a.matrix[1][3] * b.matrix[3][1];
//
// retVal.matrix[1][2] =
// a.matrix[1][0] * b.matrix[0][2] +
// a.matrix[1][1] * b.matrix[1][2] +
// a.matrix[1][2] * b.matrix[2][2] +
// a.matrix[1][3] * b.matrix[3][2];
//
// retVal.matrix[1][3] =
// a.matrix[1][0] * b.matrix[0][3] +
// a.matrix[1][1] * b.matrix[1][3] +
// a.matrix[1][2] * b.matrix[2][3] +
// a.matrix[1][3] * b.matrix[3][3];
//
// // row 2
// retVal.matrix[2][0] =
// a.matrix[2][0] * b.matrix[0][0] +
// a.matrix[2][1] * b.matrix[1][0] +
// a.matrix[2][2] * b.matrix[2][0] +
// a.matrix[2][3] * b.matrix[3][0];
//
// retVal.matrix[2][1] =
// a.matrix[2][0] * b.matrix[0][1] +
// a.matrix[2][1] * b.matrix[1][1] +
// a.matrix[2][2] * b.matrix[2][1] +
// a.matrix[2][3] * b.matrix[3][1];
//
// retVal.matrix[2][2] =
// a.matrix[2][0] * b.matrix[0][2] +
// a.matrix[2][1] * b.matrix[1][2] +
// a.matrix[2][2] * b.matrix[2][2] +
// a.matrix[2][3] * b.matrix[3][2];
//
// retVal.matrix[2][3] =
// a.matrix[2][0] * b.matrix[0][3] +
// a.matrix[2][1] * b.matrix[1][3] +
// a.matrix[2][2] * b.matrix[2][3] +
// a.matrix[2][3] * b.matrix[3][3];
//
// // row 3
// retVal.matrix[3][0] =
// a.matrix[3][0] * b.matrix[0][0] +
// a.matrix[3][1] * b.matrix[1][0] +
// a.matrix[3][2] * b.matrix[2][0] +
// a.matrix[3][3] * b.matrix[3][0];
//
// retVal.matrix[3][1] =
// a.matrix[3][0] * b.matrix[0][1] +
// a.matrix[3][1] * b.matrix[1][1] +
// a.matrix[3][2] * b.matrix[2][1] +
// a.matrix[3][3] * b.matrix[3][1];
//
// retVal.matrix[3][2] =
// a.matrix[3][0] * b.matrix[0][2] +
// a.matrix[3][1] * b.matrix[1][2] +
// a.matrix[3][2] * b.matrix[2][2] +
// a.matrix[3][3] * b.matrix[3][2];
//
// retVal.matrix[3][3] =
// a.matrix[3][0] * b.matrix[0][3] +
// a.matrix[3][1] * b.matrix[1][3] +
// a.matrix[3][2] * b.matrix[2][3] +
// a.matrix[3][3] * b.matrix[3][3];
//
// return retVal;
// }
//
// // Only use for data being uploaded to renderer
// void AdjustCoordinatesForRHS();
//
//private:
//
//};
|
C
|
#include <stdio.h>
void print(int line_no) {
for(int j = 0; j < line_no; j++)
printf("$");
printf("\n");
}
int main(void)
{
const int line = 5;
for(int i = 0; i < line; i++)
{
print(i + 1);
}
return 0;
}
|
C
|
#include <myutils.h>
#include <protocollo.h>
#include <mypthread.h>
#include <mysocket.h>
#include <mypoll.h>
#include <parser_writer.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <fcntl.h>
#include <sys/wait.h>
/** var. globali */
static int pipefd_dir[2]; /* pipe di comunicazione fra signal handler e main */
static int listen_ssfd = -1; /* listen server socket fd */
static int smfd = -1; /* supermercato fd*/
/*****************************************************
* SIGNAL HANDLER SINCRONO
* - aspetta la ricezione di segnali specificati da una maschera
* - gestisce SIGQUIT, SIGHUP e SIGUSR1
* - una volta ricevuto un segnale scrive sulla pipe il segnale ricevuto
*****************************************************/
static void *sync_signal_handler(void *useless) {
int err;
sigset_t mask;
MENO1(sigemptyset(&mask))
MENO1(sigaddset(&mask, SIGQUIT))
MENO1(sigaddset(&mask, SIGHUP))
MENO1(sigaddset(&mask, SIGUSR1))
PTH(err, pthread_sigmask(SIG_SETMASK, &mask, NULL))
int sig_captured; /* conterrà il segnale cattuarato dalla sigwait */
for(;;) {
PTH(err, sigwait(&mask, &sig_captured))
switch(sig_captured) {
case SIGQUIT:
// __attribute__((fallthrough));
case SIGHUP:
MENO1(writen(pipefd_dir[1], &sig_captured, sizeof(int)))
break;
default: /* SIGUSR1 */
return (void *) 0;
}
}
}
inline static void usage(char *str) {
printf("Usage: %s <OPTION>\nOPTION:\n-h\thelp\n\n"
"-c <FILE>\tpassa FILE come file di configurazione per il programma.\n" \
"FILE deve essere del tipo:\n\n" \
"#sono un commento (hashtag ad inizio riga); verrò ignorato \n" \
"#numero clienti, con C=0 non ci sono clienti\n" \
"C = x;\t\t[>=0]\n" \
"#[...] indica il vincolo che il parametro deve rispettare, NON deve essere scritto nel file\n" \
"#numero casse, con K=0 non ci sono casse\n" \
"K = x;\t\t[>=0]\n" \
"#soglia sopra la quale rientrano i clienti, con E=0 non rientrano\n" \
"E = x;\t\t[ IN [0, C] ]\n" \
"#tempo massimo di acquisti [ms]\n" \
"T = x;\t\t[>10]\n" \
"#numero massimo prodotti acquistabili, con P=0 escono tutti senza acquisti\n"\
"P = x;\t\t[>=0]\n" \
"#ampiezza [ms] intervallo di ricerca nuova cassa dei clienti in coda\n"\
"S = x;\t\t[>=10]\n" \
"#tempo di gestione di un prodotto da parte di ogni cassiere\n" \
"L = x;\t\t[>=0]\n" \
"#numero casse aperte inizialmente\n" \
"J = x;\t\t[ IN [0, K] ]\n" \
"#ampiezza [ms] intervallo di comunicazione tra cassiere e direttore\n" \
"A = x;\t\t[>=0]\n" \
"#soglia chiusura casse: definisce il numero di casse con al più un cliente in coda\n" \
"S1 = x;\t\t[>=1]\n" \
"#soglia apertura casse: definisce il numero di clienti in coda in almeno una cassa\n" \
"S2 = x;\t\t[>=1]\n" \
"#nome file di LOG, estensione csv, se esiste lo sovrascrive\n" \
"Z = str.csv\n" \
"NON è necessario che i parametri siano in questo ordine, si devono rispettare le seguenti dipendenze:\n" \
"prima C poi E;\tprima K poi J;\n" \
"è accettato sia K=x; che K = x;\n" \
"Devono essere presenti TUTTI i parametri, NON ripetuti\n\n", str);
}
static void cleanup(void) {
MENO1(unlink(SOCKET_SERVER_NAME))
/*
* provo ad ottenere i flag del fd: se li ottengo vuol dire che il fd è attivo,
* pertanto provvedo a chiuderlo
*/
if(fcntl(listen_ssfd, F_GETFL) >= 0)
MENO1(close(listen_ssfd))
if(fcntl(smfd, F_GETFL) >= 0)
MENO1(close(smfd))
if(fcntl(pipefd_dir[0], F_GETFL) >= 0)
MENO1(close(pipefd_dir[0]))
if(fcntl(pipefd_dir[1], F_GETFL) >= 0)
MENO1(close(pipefd_dir[1]))
}
/***********************************************************************************************
* LOGICA DEL DIRETTORE (del supermercato)
* - forka il processo supermercato
* - gestione segnali
* thread signal handler che scrive sulla pipe per avvisare della ricezione del segnale
* - crea un socket di comunicazione col supermercato e si mette in ascolto su:
* . socket di comunicazione
* . pipe[0]
* - gestisce le casse e le uscite dei clienti con 0 prodotti acquistati
* - quando viene ricevuto un segnale lo reinvia al supermercato
* SIGHUP: rimane in attesa di altre comunicazioni dai cassieri/clienti senza acquisti
* SIGQUIT: gestisce le richieste sospese
* attende la terminazione del supermercato e successivamente termina
************************************************************************************************/
int main(int argc, char *argv[]) {
/***************************************************************************************
* Controllo parametri di ingresso
****************************************************************************************/
if (argc < 2 || argc > 3) {
usage(argv[0]);
exit(EXIT_FAILURE);
}
/** Parametri di configurazione */
param_t par;
if (argv[1][0] == '-' && argv[1][2] == '\0') {
switch (argv[1][1]) {
case 'c':
if(argc != 3) {
usage(argv[0]);
exit(EXIT_FAILURE);
}
MENO1LIB(get_params_from_file(&par, argv[2]), -1)
break;
case 'h':
usage(argv[0]);
exit(EXIT_FAILURE);
break;
default:
printf("Opzione non valida\n");
exit(EXIT_FAILURE);
}
} else {
printf("Opzione non valida\n");
exit(EXIT_FAILURE);
}
/** Variaibili di supporto */
int err,
i;
/***************************************************************************************
* Gestione segnali
* - inizializza la pipe di comunicazione fra signal handler e main
* - thread signal handler, gestirà SIGQUIT e SIGHUP
* maschero tutti i segnali nel thread main
****************************************************************************************/
struct sigaction sa;
MENO1(sigaction(SIGPIPE, NULL, &sa))
sa.sa_handler = SIG_IGN;
MENO1(sigaction(SIGPIPE, &sa, NULL))
sigset_t mask;
MENO1(sigfillset(&mask))
MENO1(sigdelset(&mask, SIGPIPE)) /* voglio ignorarlo */
PTH(err, pthread_sigmask(SIG_SETMASK, &mask, NULL))
/*
* inizializzazione PIPE per TSH
*/
MENO1(pipe(pipefd_dir))
pthread_t tid_tsh;
void *status_tsh;
PTH(err, pthread_create(&tid_tsh, NULL, sync_signal_handler, (void *) NULL))
/***************************************************************************************
* Apertura Supermercato
* - fork del processo supermercato
****************************************************************************************/
pid_t pid_sm = -1; /* pid del supermercato */
int status_sm; /* conterrà il valore di uscita del processo supermercato */
switch ( (pid_sm = fork()) ) {
case 0: /* figlio */
execl(PATH_TO_SUPERMARKET, "supermercato", argv[2], (char *) NULL);
perror("exec");
exit(EXIT_FAILURE);
break;
case -1: /* errore */
perror("fork");
exit(EXIT_FAILURE);
break;
default: /* padre */
break;
}
/***************************************************************************************
* Comunicazione col supermercato: creazione socket di comunicazione
* - SOCKET AF_UNIX per l'instaurazione della connessione
* - creazione SOCKET
* - socket si mette in ascolto
* - attende la richiesta di connessione del supermercato
* - una volta ottenuto il nuovo socket di comunicazione
* chiude il socket iniziale
****************************************************************************************/
SOCKETAF_UNIX(listen_ssfd) /* creo il socket AF_UNIX */
atexit(cleanup); /* elimina l'indirizzo del server e il socket all'uscita */
SOCKETAF_UNIX(listen_ssfd)
struct sockaddr_un serv_addr;
SOCKADDR_UN(serv_addr, SOCKET_SERVER_NAME)
MENO1(bind(listen_ssfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)))
MENO1(listen(listen_ssfd, MAX_BACKLOG))
/***************************************************************************************
* attendo UNA richiesta di connessione dal supermercato
* - inizializzo le strutture per la POLL
* - uso la POLL per attendere una connessione in un certo intervallo
* e monitorare eventuali comunicazione del signal handler
***************************************************************************************/
struct pollfd *pollfd_v; /* array di pollfd */
EQNULL(pollfd_v = start_pollfd())
int polled_fd = 0; /* conterrà il numero di fd che si stanno monitorando */
struct pollfd tmp; /* pollfd di supporto per gli inserimenti */
tmp.fd = listen_ssfd;
tmp.events = POLLIN; /* attende eventi di lettura non con alta priorità */
MENO1LIB(pollfd_add(&pollfd_v, tmp, &polled_fd), -1)
tmp.fd = pipefd_dir[0];
tmp.events = POLLIN;
MENO1LIB(pollfd_add(&pollfd_v, tmp, &polled_fd), -1)
/*
* gestione casse
*/
int *code_casse; /* conterrà le informazioni riguardo le code delle casse */
EQNULL(code_casse = malloc(par.K * sizeof(int)))
for(i = 0; i < par.K; i++)
code_casse[i] = -1; /* -1 indica cassa chiusa */
/***************************************************************************************
* MULTIPLEXING, tramite POLL:
* attendo I/O su più file descriptors
* .smfd
* .pipe[0]
* Inizialmente attende UNA unica richiesta di connessione del supermercato
*
* Può ricevere comunicazioni da:
*
* SIGNAL HANDLER riceve un segnale, lo rimanda al supermercato
*
* CLIENTI in caso di uscita senza acquisti
* li gestisce accettando la loro uscita
*
* CASSE riceve comunicazione riguardo il numero di clienti in coda
*
* MANAGER segnala l'imminente terminazione del supermercato
*
* Quando viene ricevuto un segnale lo reinvia al supermercato
* SIGHUP rimane in attesa di altre comunicazioni dai cassieri/clienti senza acquisti
* SIGQUIT gestisce le richieste sospese
* attende la terminazione del supermercato e successivamente termina
****************************************************************************************/
int sotto_soglia_S1 = 0,
num_casse_aperte = 0;
for(;;) {
/*
* MULTIPLEXING: attendo I/O su vari fd
*/
if(poll(pollfd_v, polled_fd, -1) == -1) { /* aspetta senza timeout, è bloccante */
if(errno == EINTR) {
/*
* in caso di interruzione per segnali non gestiti dall'handler, NON dovrebbe accadere mai
*/
printf("[DIRETTORE] chiusura direttore\n");
break;
} else {
perror("poll");
exit(EXIT_FAILURE);
}
}
/* il cnt di fd monitorati può cambiare durante il ciclo
* => è necessario mantenerlo consistente durante una scansione dell'array
* in caso di chiusure => va decrementato, in caso di aggiunte NO */
int current_pollfd_array_size = polled_fd;
for(i=0; i < current_pollfd_array_size; i++) {
if (pollfd_v[i].revents & POLLIN) { /* fd pronto per la lettura! */
int fd_curr = pollfd_v[i].fd;
if(fd_curr == pipefd_dir[0]) {
/*
* il signal handler ha ricevuto un segnale
*/
int sig_captured;
MENO1(readn(pipefd_dir[0], &sig_captured, sizeof(int)))
/*
* manda il segnale ricevuto al supermercato
*/
MENO1(kill(pid_sm, sig_captured))
}
else if(fd_curr == listen_ssfd) {
/*
* accetto la connessione del supermercato, dopodichè chiudo il socket
*/
MENO1(smfd = accept(listen_ssfd, NULL, 0)) /* socket di comunicazione col supermercato */
tmp.fd = smfd;
tmp.events = POLLIN;
MENO1LIB(pollfd_add(&pollfd_v, tmp, &polled_fd), -1)
MENO1LIB(pollfd_remove(pollfd_v, i, &polled_fd), -1)
current_pollfd_array_size--;
MENO1(shutdown(listen_ssfd, SHUT_RDWR))
MENO1(close(listen_ssfd))
}
else {
/*
* ricevuta comunicazione dal supermercato
*/
sock_msg_code_t type_msg = 0; /* tipo messaggio ricevuto */
int param; /* parametro del messaggio */
MENO1(readn(smfd, &type_msg, sizeof(sock_msg_code_t)))
switch(type_msg) {
case MANAGER_IN_CHIUSURA:
MENO1(waitpid(pid_sm, &status_sm, 0))
goto terminazione_direttore;
case CLIENTE_SENZA_ACQUISTI:
/*
* assumo che il direttore faccia SEMPRE uscire i clienti
* che non effettuano acquisti
* -leggo l'id cliente
*/
MENO1(readn(smfd, ¶m, sizeof(int)))
type_msg = DIRETTORE_PERMESSO_USCITA;
MENO1(writen(smfd, &type_msg, sizeof(sock_msg_code_t)))
MENO1(writen(smfd, ¶m, sizeof(int)))
break;
case CASSIERE_NUM_CLIENTI: {
int ind;
/*
* leggo l'indice della coda e il numero di clienti in coda
*/
MENO1(readn(smfd, &ind, sizeof(int)))
MENO1(readn(smfd, ¶m, sizeof(int)))
/* param >= 0, ind >= 0 */
if(code_casse[ind] < 0) { // era chiusa
num_casse_aperte++;
if(param <= 1)
sotto_soglia_S1++;
} else if(code_casse[ind] <= 1) { // se era APERTA e sotto la soglia S1
if (param > 1)
sotto_soglia_S1--;
} else if(param <= 1) // non era sotto la soglia S1, ora sì
sotto_soglia_S1++;
code_casse[ind] = param;
/*
* es. S1=2: chiude una cassa se ci sono almeno 2 casse che hanno al più un cliente
* es. S2=10: apre una cassa (se possibile) se c’è almeno una cassa con almeno 10 clienti in coda
*/
/*
* decisione APERTURA casse
*/
if(code_casse[ind] >= par.S2) {
type_msg = DIRETTORE_APERTURA_CASSA;
MENO1(writen(smfd, &type_msg, sizeof(sock_msg_code_t)))
}
/*
* decisione CHIUSURA casse
*/
else if(code_casse[ind] <= 1 && num_casse_aperte > 1) {
if(sotto_soglia_S1 >= par.S1) {
type_msg = DIRETTORE_CHIUSURA_CASSA;
MENO1(writen(smfd, &type_msg, sizeof(sock_msg_code_t)))
MENO1(writen(smfd, &ind, sizeof(int)))
code_casse[ind] = -1;
sotto_soglia_S1--;
num_casse_aperte--;
}
}
}
default: ;
}
}
}
}
}
/***************************************************************************************
* Terminazione DIRETTORE
**********************;*****************************************************************/
terminazione_direttore:
free(code_casse);
pollfd_destroy(pollfd_v);
PTH(err, pthread_kill(tid_tsh, SIGUSR1))
PTH(err, pthread_join(tid_tsh, &status_tsh))
PTHJOIN(status_tsh, "Signal Handler Direttore")
return 0;
}
|
C
|
//
// Created by russell on 12.09.16.
//
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <pthread.h>
#include "generator.h"
#include "queue.h"
void *GenerateMessage(void *thrStr) {
int length;
char message[MAXSTRINGSIZE];
threadStr *sharedStr = (threadStr *) thrStr;
for (; ;) {
srand(time(NULL) + pthread_self());
length = (rand() % MAXSTRINGSIZE) + 1;
for (int i = 0; i < length; i++) {
message[i] = 65 + (rand() % 57);
}
/*int letter = rand() % 57;
for (int i = 0; i < length; i++) {
message[i] = 65 + letter;
}*/
message[length] = '\0';
if (put(sharedStr, message) < 0) {
fprintf(stderr, "put() failed\n");
sleep(1);
continue;
}
sleep((rand() % MAXSLEEPTIME) + 1);
}
}
|
C
|
#include <stdio.h>
/* DONE*/
/* RESEMBLES BUBBLE SORT*/
int main()
{
long long int test, count;
int l, i, j, x, temp;
int ar[50];
scanf("%lld", &test);
while(test--){
scanf("%d", &l);
x = 0;
while(l--){
scanf("%d", &ar[x++]);
}
count = 0;
for(i = 1; i < x; i++){
for(j = 1; j < x; j++){
if( ar[j-1] > ar[j]) {
temp = ar[j];
ar[j] = ar[j-1];
ar[j-1] = temp;
count++;
}
}
}
printf("Optimal train swapping takes %ld swaps.\n", count);
}
return 0;
}
|
C
|
#include <stdio.h>
int main(void)
{
int ch;
int cnt = 0;
printf("\nstatic unsigned char module[] = {\n");
while ((ch = getc(stdin)) != EOF) {
if (cnt == 0)
printf("\t\"");
printf("\\x%2.2X", ch);
cnt++;
if (cnt == 16) {
printf("\"\n");
cnt = 0;
}
}
printf("%s};\n", (cnt ? "\"\n" : ""));
return 0;
}
|
C
|
#include "tile.h"
#include <string.h>
#include <stdbool.h>
bool containNeighbors(const tile_t *tiles, int tile_count, int firstNeighbor, int secondNeighbor);
int tiles_is_able_to_chow(tile_t tiles[], int tile_count, tile_t tile)
{
if (containNeighbors(tiles, tile_count, tile + 1, tile + 2) || containNeighbors(tiles, tile_count, tile - 1, tile + 1) ||
containNeighbors(tiles, tile_count, tile - 1, tile - 2)) {
return 1;
}
return 0;
}
bool containNeighbors(const tile_t *tiles, int tile_count, int firstNeighbor, int secondNeighbor) {
return memchr(tiles, firstNeighbor, tile_count) && memchr(tiles, secondNeighbor, tile_count);
}
|
C
|
//---------------------------------------------------------------------------------------
// Smile Programming Language Interpreter
// Copyright 2004-2019 Sean Werkema
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//---------------------------------------------------------------------------------------
#include <smile/gc.h>
#include <smile/string.h>
#include <smile/stringbuilder.h>
#include <smile/crypto/base64.h>
/*
* This code is derived from:
*
* Base64 encoding/decoding (RFC1341)
* Copyright (c) 2005-2011, Jouni Malinen <j@w1.fi>
*
* This software may be distributed under the terms of the BSD license.
* See README for more details.
*
* It's basically Jouni's code, but with some slight revisions to allow the
* return types to match what Smile prefers, and to use GC buffers instead of malloc.
*/
static const unsigned char base64_table[65] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/// <summary>Base-64 encode the given buffer of data.</summary>
/// <param name="src">Data to be encoded.</param>
/// <param name="len">Length of the data to be encoded.</param>
/// <returns>Allocated String of encoded data.</returns>
String Base64Encode(const Byte *src, Int len, Bool wrapLines)
{
String result;
Byte *out, *pos;
const Byte *end, *in;
Int olen;
Int line_len;
olen = len * 4 / 3 + 4; // 3-byte blocks to 4-byte
if (wrapLines)
olen += olen / 72; // line feeds
olen++; // nul termination
if (olen < len)
Smile_Abort_OutOfMemory(); // integer overflow
result = String_CreateInternal(olen);
out = (Byte *)String_GetBytes(result);
if (out == NULL)
return NULL;
end = src + len;
in = src;
pos = out;
line_len = 0;
while (end - in >= 3) {
*pos++ = base64_table[in[0] >> 2];
*pos++ = base64_table[((in[0] & 0x03) << 4) | (in[1] >> 4)];
*pos++ = base64_table[((in[1] & 0x0f) << 2) | (in[2] >> 6)];
*pos++ = base64_table[in[2] & 0x3f];
in += 3;
line_len += 4;
if (wrapLines && line_len >= 72) {
*pos++ = '\n';
line_len = 0;
}
}
if (end - in) {
*pos++ = base64_table[in[0] >> 2];
if (end - in == 1) {
*pos++ = base64_table[(in[0] & 0x03) << 4];
*pos++ = '=';
}
else {
*pos++ = base64_table[((in[0] & 0x03) << 4) |
(in[1] >> 4)];
*pos++ = base64_table[(in[1] & 0x0f) << 2];
}
*pos++ = '=';
line_len += 4;
}
if (wrapLines && line_len)
*pos++ = '\n';
*pos = '\0';
// We likely over-allocated, so set the string's length to the correct count.
result->_opaque.length = (Int)(pos - out);
return result;
}
/// <summary>Base-64 decode the given string of encoded data.</summary>
/// <param name="text">Data to be decoded.</param>
/// <param name="out_len">This will be set to the number of bytes decoded.</param>
/// <returns>Allocated buffer of decoded data, or NULL if the input is invalid.</returns>
Byte *Base64Decode(String text, Int *out_len)
{
Byte dtable[256], *out, *pos, block[4], tmp;
Int i, count, olen;
Int pad = 0;
const Byte *src = String_GetBytes(text);
Int len = String_Length(text);
MemSet(dtable, 0x80, 256);
for (i = 0; i < sizeof(base64_table) - 1; i++)
dtable[base64_table[i]] = (Byte)i;
dtable['='] = 0;
count = 0;
for (i = 0; i < len; i++) {
if (dtable[src[i]] != 0x80)
count++;
}
if (count == 0 || count % 4)
return NULL;
olen = count / 4 * 3;
pos = out = GC_MALLOC_ATOMIC(olen);
if (out == NULL)
Smile_Abort_OutOfMemory();
count = 0;
for (i = 0; i < len; i++) {
tmp = dtable[src[i]];
if (tmp == 0x80)
continue;
if (src[i] == '=')
pad++;
block[count] = tmp;
count++;
if (count == 4) {
*pos++ = (block[0] << 2) | (block[1] >> 4);
*pos++ = (block[1] << 4) | (block[2] >> 2);
*pos++ = (block[2] << 6) | block[3];
count = 0;
if (pad) {
if (pad == 1)
pos--;
else if (pad == 2)
pos -= 2;
else {
// Invalid padding.
return NULL;
}
break;
}
}
}
*out_len = (Int)(pos - out);
return out;
}
|
C
|
#include <ctype.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "C.h"
Node *new_node(NodeKind kind, Node *lhs, Node *rhs) {
Node *node = calloc(1, sizeof(Node));
node->kind = kind;
node->lhs = lhs;
node->rhs = rhs;
return node;
}
Node *new_node_num(int val) {
Node *node = calloc(1, sizeof(Node));
node->kind = ND_NUM;
node->val = val;
return node;
}
Node *code[100];
Node *expr(int gloloc){
Node *node = equality(gloloc);
if(consume("="))
node = new_node(ND_ASSIGN, node, expr(gloloc));
return node;
}
Node *stmt(int gloloc){
Node *node;
if(token->kind == TK_RETURN){
node = calloc(1, sizeof(Node));
node->kind = ND_RETURN;
token = token->next;
node->lhs = expr(gloloc);
}else if(token->kind == TK_IF){
node = calloc(1, sizeof(Node));
node->rhs = calloc(1, sizeof(Node));
node->kind = ND_IF;
token = token->next;
consume("(");
node->lhs = expr(gloloc);
consume(")");
node->rhs->rhs = stmt(gloloc);
if(token->kind == TK_ELSE){
node->kind = ND_IF_ELSE;
token = token->next;
node->rhs->lhs = stmt(gloloc);
}
return node;
}else if(token->kind == TK_WHILE){
node = calloc(1, sizeof(Node));
node->kind = ND_WHILE;
token = token->next;
consume("(");
node->lhs = expr(gloloc);
consume(")");
node->rhs = stmt(gloloc);
return node;
}else if(token->kind == TK_FOR){
node = calloc(1, sizeof(Node));
node->lhs=calloc(1, sizeof(Node));
node->lhs->lhs=calloc(1,sizeof(Node));
node->kind = ND_FOR;
token = token->next;
consume("(");
if(!consume(";")) {
node->lhs->lhs->lhs = expr(gloloc);
consume(";");
}
if(!consume(";")) {
node->lhs->lhs->rhs = expr(gloloc);
consume(";");
}
if(!consume(")")) {
node->lhs->rhs = expr(gloloc);
consume(")");
}
node->rhs = stmt(gloloc);
return node;
}else if(consume("{")){
node = calloc(1, sizeof(Node));
node->kind = ND_BLOCK;
int i=0;
while(!consume("}")){
node->block[i++] = stmt(gloloc);
}
return node;
}else if(token->kind == TK_IDENT &&
!memcmp(token->next->str,"(",1)){
static int glolocloc = 1;
node = calloc(1, sizeof(LVar));
LVar *lvar = calloc(1,sizeof(LVar));
lvar->next = locals[glolocloc];
lvar->name = token->str;
lvar->len = token->len;
lvar->gloloc = glolocloc;
node->offset = lvar->offset;
locals[glolocloc] = lvar;
node->kind = ND_FUNC_DEF;
Token *save = token;
token = token->next->next;
int i = 0;
while(!consume(")")){
node->argu[i++] = primary(glolocloc);
consume(",");
}
if(consume(";")){
token = save;
locals[glolocloc] = locals[glolocloc]->next;
node = expr(glolocloc);
consume(";");
return node;
}
node->rhs = stmt(glolocloc);
node->gloloc = glolocloc;
lvar->def = node->rhs;
gloloc++;
return node;
}else{
node = expr(gloloc);
}
if(!consume(";"))
error("cccc\n");
return node;
}
void *program(){
int i = 0;
while(!at_eof())
code[i++] = stmt(0);
code[i] = NULL;
}
Node *equality(int gloloc) {
Node *node = relational(gloloc);
for (;;) {
if (consume("=="))
node = new_node(ND_equal, node, relational(gloloc));
else if (consume("!="))
node = new_node(ND_nequal, node, relational(gloloc));
else
return node;
}
}
Node *relational(int gloloc){
Node *node = add(gloloc);
if (consume("<"))
node = new_node(ND_big, node, add(gloloc));
else if (consume("<="))
node = new_node(ND_ebig, node, add(gloloc));
else if (consume(">"))
node = new_node(ND_small, node, add(gloloc));
else if (consume(">="))
node = new_node(ND_small, node, add(gloloc));
else
return node;
}
Node *add(int gloloc){
Node *node = mul(gloloc);
for (;;) {
if (consume("+"))
node = new_node(ND_ADD, node, mul(gloloc));
else if (consume("-"))
node = new_node(ND_SUB, node, mul(gloloc));
else
return node;
}
}
Node *mul(int gloloc) {
Node *node = unary(gloloc);
for (;;) {
if (consume("*"))
node = new_node(ND_MUL, node, unary(gloloc));
else if (consume("/"))
node = new_node(ND_DIV, node, unary(gloloc));
else
return node;
}
}
Node *unary(int gloloc) {
if (consume("+"))
return primary(gloloc);
if (consume("-"))
return new_node(ND_SUB, new_node_num(0), primary(0));
return primary(gloloc);
}
Node *primary(int gloloc) {
if (consume("(")) {
Node *node = expr(gloloc);
expect(")");
return node;
}
if(token->kind == TK_IDENT){
Node *node = calloc(1,sizeof(Node));
node->kind = ND_LVAR;
LVar *lvar = find_lvar(token, gloloc);
if(lvar){
node->offset = lvar->offset;
node->gloloc = lvar->gloloc;
}else{
lvar = calloc(1,sizeof(LVar));
lvar->next = locals[gloloc];
lvar->name = token->str;
lvar->len = token->len;
lvar->offset = locals[gloloc]->offset + 8;
lvar->gloloc = gloloc;
node->offset = lvar->offset;
locals[gloloc] = lvar;
}
token = token->next;
if(consume("(")){
node->kind = ND_FUNC;
node->rhs = lvar->def;
int i= 0;
while(!consume(")")){
node->argu[i++] = primary(0);
consume(",");
}
}
return node;
}
// łȂΐl̂͂
return new_node_num(expect_number());
}
LVar *find_lvar(Token *tok,int gloloc){
for (LVar *var = locals[gloloc]; var; var = var->next)
if (var->len == tok->len && gloloc == var->gloloc && !memcmp(tok->str, var->name, var->len))
return var;
return NULL;
}
|
C
|
// Remove all comments from a C program.
//
// "quoted strings" and character constants should also be
// Handled properly...
//
#include <stdio.h>
#define MAX_SIZE 300
int read_line(char input[], int size);
void parse_line(char input[]);
void write_line(char input[], char output[]);
int is_comment(char buffer[]);
int main() { // In-line comments like this one should be removed as well.
int c;
char input[MAX_SIZE];
char output[MAX_SIZE];
while (read_line(input, MAX_SIZE) > 0) {
parse_line(input);
write_line(input, output);
}
}
// read into input the current line. return line size.
int read_line(char input[], int size) {
int i, c;
for (i = 0; i < size - 1 && (c = getchar()) != EOF && c != '\n'; ++i) {
input[i] = c;
}
if (c == '\n') {
input[i] = c;
i++;
}
input[i] = '\0';
return i;
}
// parses out comments in a C file.
void parse_line(char input[]) {
int i;
char buffer[2];
int single_quote, double_quote;
single_quote = 0;
double_quote = 0;
buffer[0] = ' ';
buffer[1] = ' ';
for (i = 0; input[i] != '\0'; ++i) {
buffer[0] = buffer[1];
buffer[1] = input[i];
if (is_comment(buffer) == 1) {
input[i-1] = '\0';
break;
}
}
}
int is_comment(char buffer[]) {
if (buffer[0] == '/' && buffer[1] == '/') {
return 1;
}
return 0;
}
void write_line(char input[], char output[]) {
int i;
i = 0;
while ((output[i] = input[i]) != '\0') {
++i;
}
printf("%s", output);
}
|
C
|
/**
* a simple stream cipher based on RC4
*
* Copyright (C) AlexandrinKS
* https://akscf.me/
**/
#include "cipher.h"
void cipher_init(cipher_ctx_t *ctx, const char* key, size_t key_len) {
int i = 0,j = 0, t=0 ;
uint8_t *sbox_b = (void *) bf_s_box;
/* rc4 */
for(i = 0; i < 256; i++) {
ctx->m[i] = i;
}
for (i = 0, j = 0; i < 256; ++i) {
j = (j + ctx->m[i] + key[i % key_len]) % 256;
t = ctx->m[i];
ctx->m[i] = ctx->m[j];
ctx->m[j] = t;
}
/* init s-boxes */
for(i=0; i <= 3; i++) {
memcpy((uint8_t *)ctx->s[i], (uint8_t *)bf_s_box[i], 1024);
}
ctx->x=0; ctx->y=0;
cipher_update(ctx);
}
void cipher_update(cipher_ctx_t *ctx) {
int idx, i, a, b;
for(idx = 0; idx <= 3; idx++) {
uint8_t *p = (uint8_t *)ctx->s[idx];
for (i = 0; i < 1024; i++) {
a = ctx->m[++ctx->x];
ctx->y += a;
ctx->m[ctx->x] = b = ctx->m[ctx->y];
ctx->m[ctx->y] = a;
p[i] ^= ctx->m[(uint8_t)(a + b)];
}
}
}
void cipher_encrypt(cipher_ctx_t *ctx, uint32_t packet_id, uint8_t *buffer, size_t len) {
uint32_t *p = (void *)buffer;
uint32_t *s = ctx->s[packet_id % 4];
int i, sz = (len / sizeof(int));
if(len % sizeof(int)) { sz--; }
for(i = 0; i < sz; i++) {
p[i] = p[i] ^ s[i % 256];
}
}
void cipher_decrypt(cipher_ctx_t *ctx, uint32_t packet_id, uint8_t *buffer, size_t len) {
uint32_t *p = (void *)buffer;
uint32_t *s = ctx->s[packet_id % 4];
int i, sz = (len / sizeof(int));
if(len % sizeof(int)) { sz--; }
for(i = 0; i < sz; i++) {
p[i] = p[i] ^ s[i % 256];
}
}
|
C
|
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
/* Type definitions */
typedef struct vhost_memory_region {int guest_phys_addr; int memory_size; } const vhost_memory_region ;
struct vhost_memory {int nregions; struct vhost_memory_region const* regions; } ;
typedef int __u64 ;
typedef int /*<<< orphan*/ __u32 ;
/* Variables and functions */
__attribute__((used)) static const struct vhost_memory_region *find_region(struct vhost_memory *mem,
__u64 addr, __u32 len)
{
struct vhost_memory_region *reg;
int i;
/* linear search is not brilliant, but we really have on the order of 6
* regions in practice */
for (i = 0; i < mem->nregions; ++i) {
reg = mem->regions + i;
if (reg->guest_phys_addr <= addr &&
reg->guest_phys_addr + reg->memory_size - 1 >= addr)
return reg;
}
return NULL;
}
|
C
|
#include <stdio.h>
double cf(int);
int main() {
double e = 2 + 1.0 / cf(1);
printf("%f\n", e);
return 0;
}
double cf(int depth) { /*ここにコードを書く*/
if (depth > 10) {
return 1;
}
if ((depth % 3) == 2) {
return 2 * (depth / 3 + 1) + 1.0 / cf(depth+1);
} else {
return 1.0 + 1.0 / cf(depth+1);
}
return 0;
}
|
C
|
/* gen_ref.c : Write a program to implement reflection
along a general line : y=mx+c.*/
#include<stdio.h>
#include<graphics.h>
#include<math.h>
int c,bgcolor;
int a,b,num,den;
int n;
int xm1,ym1,xm2,ym2,xm3,ym3;
void draw_xy();
void bresenham(int x1,int y1,int x2,int y2,int x[],int y[]);
void line_draw(int x1,int y1,int x2,int y2);
void draw_triangle(int x1,int y1,int x2,int y2,int x3,int y3);
void translation(int x1,int y1,int x2,int y2,int x3,int y3,int xa,int ya);
void rotation(int x1,int y1,int x2,int y2,int x3,int y3,float theta);
void reflection(int x1,int y1,int x2,int y2,int x3,int y3,int ch);
void general_reflection(int x1,int y1,int x2,int y2,int x3,int y3);
void plot_line(int x[],int y[],int n);
void main()
{
int x1,y1,x2,y2,x3,y3;
float m;
clrscr();
printf("\nEnter x co-ordinate of Vertex A :");
scanf("%d",&x1);
printf("Enter y co-ordinate of Vertex A :");
scanf("%d",&y1);
printf("Enter x co-ordinate of Vertex B :");
scanf("%d",&x2);
printf("Enter y co-ordinate of Vertex B :");
scanf("%d",&y2);
printf("Enter x co-ordinate of Vertex C :");
scanf("%d",&x3);
printf("Enter y co-ordinate of Vertex C :");
scanf("%d",&y3);
printf("Enter x-translation factor along x-axis(a)=");
scanf("%d",&a);
printf("Enter y-translation factor along y-axis(b)=");
scanf("%d",&b);
printf("Enter numerator of slope(m) :");
scanf("%d",&num);
printf("Enter denominator of slope(m) :");
scanf("%d",&den);
printf("Enter Background Color code(1-14)=");
scanf("%d",&bgcolor);
printf("Enter Color of line(1-14)=");
scanf("%d",&c);
draw_xy();
general_reflection(x1,y1,x2,y2,x3,y3);
getch();
closegraph();
}
/* void general_reflection(int x1,int y1,int x2,int y2,int x3.int y3):
Function to apply reflection along a general straight line.*/
void general_reflection(int x1,int y1,int x2,int y2,int x3,int y3)
{
int xa,yb;
float th1,theta;
int x[700],y[700];
/* To draw Initial triangle */
draw_triangle(x1,y1,x2,y2,x3,y3);
/* General reflection comprises of 5 transformations.
(i) Inverse translation
(ii)Inverse Rotation
(iii) Reflection along x-axis
(iv)Rotation
(v)Translation
*/
/* Inverse translation starts */
xa=-a;
yb=b;
translation(x1,y1,x2,y2,x3,y3,xa,yb);
/*Inverse Rotation Starts */
theta=atan(num/(float)den);
th1=-theta;
/* Copying transformed x,y co-ordinates */
x1=xm1;
y1=ym1;
x2=xm2;
y2=ym2;
x3=xm3;
y3=xm3;
rotation(x1,y1,x2,y2,x3,y3,th1);
/* Reflection along x-axis starts */
/* Copying transformed x,y co-ordinates */
x1=xm1;
y1=ym1;
x2=xm2;
y2=ym2;
x3=xm3;
y3=ym3;
reflection(x1,y1,x2,y2,x3,y3,1); /* Taking reflection along x-axis */
/* Rotation transformation starts */
th1=theta;
/* Copying transformed x,y co-ordinates */
x1=xm1;
y1=ym1;
x2=xm2;
y2=ym2;
x3=xm3;
y3=ym3;
rotation(x1,y1,x2,y2,x3,y3,th1);
/* Translation transformation starts */
xa=a;
yb=b;
x1=xm1;
y1=ym1;
x2=xm2;
y2=ym2;
x3=xm3;
y3=ym3;
translation(x1,y1,x2,y2,x3,y3,xa,yb);
/* Reflection along general axis is over */
draw_triangle(xm1,ym1,xm2,ym2,xm3,ym3);
}
/* void draw_triangle(int x1,int y1,int x2,int y2,int x3,int y3) :
Function to draw a triangle */
void draw_triangle(int x1,int y1,int x2,int y2,int x3,int y3)
{
line_draw(x1,y1,x2,y2);
line_draw(x2,y2,x3,y3);
line_draw(x3,y3,x1,y1);
}
/* void draw_xy() : Function to draw x-axis and y-axis */
void draw_xy()
{
int gd=DETECT,gm;
int i,c1;
c1=15;
initgraph(&gd,&gm,"c://tc//BGI");
setbkcolor(bgcolor); /* To set back ground color */
/* To draw x-axis */
for(i=0;i<640;i++)
{
putpixel(i,240,c1);
delay(2000);
}
/* To draw y-axis */
for(i=0;i<480;i++)
{
putpixel(320,i,c1);
delay(2000);
}
outtextxy(10,245,"-X");
outtextxy(610,245,"+X");
outtextxy(325,20,"+Y");
outtextxy(325,460,"-Y");
outtextxy(325,245,"O(0,0)");
}
/* void line_draw(int x1,int y1,int x2,int y2) : Function
to draw a line from (x1,y1) to (x2,y2) */
void line_draw(int x1,int y1,int x2,int y2)
{
int x[700],y[700];
bresenham(x1,y1,x2,y2,x,y);
plot_line(x,y,n);
}
/* int bresenham(int x1,int y1,int x2,int y2,int x[],int y[]) :
Function to generate all points using Integer generalized
bresenham algorithm */
void bresenham(int x1,int y1,int x2,int y2,int x[],int y[])
{
int delx,dely,s1,s2;
int interchange,temp;
int xx,yy;
int i,e;
delx=abs(x2-x1);
dely=abs(y2-y1);
s1=sign(x2-x1);
s2=sign(y2-y1);
/* To calculate value of interchange */
if(dely>delx)
{
temp=dely;
dely=delx;
delx=temp;
interchange=1;
}
else
interchange=0;
xx=x1;
yy=y1;
e=2*dely-delx;
/* To generate all points */
for(i=0;i<=delx;i++)
{
x[i]=xx;
y[i]=yy;
while(e>=0)
{
if(interchange==1)
xx=xx+s1;
else
yy=yy+s2;
e=e-2*delx;
}
if(interchange==1)
yy=yy+s2;
else
xx=xx+s1;
e=e+2*dely;
}
n=delx;
}
/* int sign(int x) : Function to return sign of x */
int sign(int x)
{
if(x<0)
return -1;
else if(x==0)
return 0;
else
return 1;
}
void plot_line(int x[],int y[],int n)
{
int i;
for(i=0;i<=n;i++)
{
putpixel(320+x[i],240-y[i],c);
delay(2000);
}
}
/* void rotation(int x1,int y1,int x2,int y2,int x3,int y3,float theta) :
Function to implement rotation. */
void rotation(int x1,int y1,int x2,int y2,int x3,int y3,float theta)
{
int obj[3][3];
float obj1[3][3];
float rot[3][3];
int i,j,k;
char a1[80];
/* To initialize Rotation Matrix */
for(i=0;i<3;i++)
for(j=0;j<3;j++)
rot[i][j]=0;
/*
rot[0][0]=1.0/sqrt(1+theta*theta);
rot[0][1]=-theta*rot[0][0];
rot[1][0]=-rot[0][1];
rot[1][1]=rot[0][0]; */
rot[0][0]=cos(theta*3.141593/180);
rot[0][1]=-sin(theta*3.141593/180);
rot[1][0]=sin(theta*3.141593/180);;
rot[1][1]=cos(theta*3.141593/180);
rot[2][2]=1;
/* To construct object matrix */
obj[0][0]=x1;
obj[0][1]=x2;
obj[0][2]=x3;
obj[1][0]=y1;
obj[1][1]=y2;
obj[1][2]=y3;
obj[2][0]=1;
obj[2][1]=1;
obj[2][2]=1;
/* To get co-ordinate of transformed triangle */
for(i=0;i<3;i++)
for(j=0;j<3;j++)
{
obj1[i][j]=0;
for(k=0;k<3;k++)
obj1[i][j]=obj1[i][j]+rot[i][k]*obj[k][j];
}
xm1=obj1[0][0];
xm2=obj1[0][1];
xm3=obj1[0][2];
ym1=obj1[1][0];
ym2=obj1[1][1];
ym3=obj1[1][2];
/* printf("x1=%d y1=%d x2=%d y2=%d x3=%d y3=%d\n",x1,y1,x2,y2,x3,y3);
printf("xr1=%d yr1=%d xr2=%d yr2=%d xr3=%d yr3=%d\n",xm1,ym1,xm2,ym2,xm3,ym3);
getch(); */
/* To draw initial object */
/*
draw_triangle(x1,y1,x2,y2,x3,y3);
sprintf(a1,"A(%d,%d)",x1,y1);
outtextxy(325+x1,245-y1,a1);
sprintf(a1,"B(%d,%d)",x2,y2);
outtextxy(325+x2,245-y2,a1);
sprintf(a1,"C(%d,%d)",x3,y3);
outtextxy(325+x3,245-y3,a1);
outtextxy(360+x3,260-y3,"Before Rotation");
*/
/* To draw modified object */
/*
draw_triangle(xm1,ym1,xm2,ym2,xm3,ym3);
sprintf(a1,"A'(%d,%d)",xm1,ym1);
outtextxy(325+xm1,245-ym1,a1);
sprintf(a1,"B'(%d,%d)",xm2,ym2);
outtextxy(325+xm2,245-ym2,a1);
sprintf(a1,"C'(%d,%d)",xm3,ym3);
outtextxy(325+xm3,245-ym3,a1);
sprintf(a1,"After Rotation by %6.1f degree\n",theta);
outtextxy(360+xm3,260-ym3,a1); */
}
/* void reflection(int x1,int y1,int x2,int y2,int x3,int y3,int ch) :
Function to take reflection about any standard axis. */
void reflection(int x1,int y1,int x2,int y2,int x3,int y3,int ch)
{
int ref[3][3],obj[3][3],obj1[3][3];
int i,j,k;
char a[80];
/* To construct Reflection Matrix */
for(i=0;i<3;i++)
for(j=0;j<3;j++)
ref[i][j]=0;
if(ch==1)
{
ref[0][0]=1;
ref[1][1]=-1;
ref[2][2]=1;
}
else if(ch==2)
{
ref[0][0]=-1;
ref[1][1]=1;
ref[2][2]=1;
}
else if(ch==3)
{
ref[0][1]=1;
ref[1][0]=1;
ref[2][2]=1;
}
else if(ch==4)
{
ref[0][1]=-1;
ref[1][0]=-1;
ref[2][2]=1;
}
/* To construct object matrix */
obj[0][0]=x1;
obj[0][1]=x2;
obj[0][2]=x3;
obj[1][0]=y1;
obj[1][1]=y2;
obj[1][2]=y3;
obj[2][0]=1;
obj[2][1]=1;
obj[2][2]=1;
/* To get co-ordinate of transformed triangle */
for(i=0;i<3;i++)
for(j=0;j<3;j++)
{
obj1[i][j]=0;
for(k=0;k<3;k++)
obj1[i][j]=obj1[i][j]+ref[i][k]*obj[k][j];
}
xm1=obj1[0][0];
xm2=obj1[0][1];
xm3=obj1[0][2];
ym1=obj1[1][0];
ym2=obj1[1][1];
ym3=obj1[1][2];
/* To draw initial object */
/*
draw_triangle(x1,y1,x2,y2,x3,y3);
sprintf(a,"A(%d,%d)",x1,y1);
outtextxy(325+x1,245-y1,a);
sprintf(a,"B(%d,%d)",x2,y2);
outtextxy(325+x2,245-y2,a);
sprintf(a,"C(%d,%d)",x3,y3);
outtextxy(325+x3,245-y3,a);
outtextxy(360+x3,260-y3,"Before Refelection");
*/
/* To draw modified object */
/*
draw_triangle(xm1,ym1,xm2,ym2,xm3,ym3);
sprintf(a,"A'(%d,%d)",xm1,ym1);
outtextxy(325+xm1,245-ym1,a);
sprintf(a,"B'(%d,%d)",xm2,ym2);
outtextxy(325+xm2,245-ym2,a);
sprintf(a,"C'(%d,%d)",xm3,ym3);
outtextxy(325+xm3,245-ym3,a);
outtextxy(360+xm3,260-ym3,"After Refelection");
*/
}
/* void translation(int x1,int y1,int x2,int y2,int x3,int y3,int a,int b) :
Function to implement scaling. */
void translation(int x1,int y1,int x2,int y2,int x3,int y3,int a,int b)
{
int obj[3][3],obj1[3][3];
int tra[3][3];
int i,j,k;
char a1[90];
/* To construct scaling Matrix */
for(i=0;i<3;i++)
for(j=0;j<3;j++)
tra[i][j]=0;
tra[0][2]=a;
tra[1][2]=b;
tra[2][2]=1;
/* 3 lines added below this */
tra[0][0]=1;
tra[1][1]=1;
tra[2][2]=1;
/* To construct object matrix */
obj[0][0]=x1;
obj[0][1]=x2;
obj[0][2]=x3;
obj[1][0]=y1;
obj[1][1]=y2;
obj[1][2]=y3;
obj[2][0]=1;
obj[2][1]=1;
obj[2][2]=1;
/* To get co-ordinate of transformed triangle */
for(i=0;i<3;i++)
for(j=0;j<3;j++)
{
obj1[i][j]=0;
for(k=0;k<3;k++)
obj1[i][j]=obj1[i][j]+tra[i][k]*obj[k][j];
}
xm1=obj1[0][0];
xm2=obj1[0][1];
xm3=obj1[0][2];
ym1=obj1[1][0];
ym2=obj1[1][1];
ym3=obj1[1][2];
/* To draw initial object */
draw_triangle(x1,y1,x2,y2,x3,y3);
/*
sprintf(a1,"A(%d,%d)",x1,y1);
outtextxy(325+x1,245-y1,a1);
sprintf(a1,"B(%d,%d)",x2,y2);
outtextxy(325+x2,245-y2,a1);
sprintf(a1,"C(%d,%d)",x3,y3);
outtextxy(325+x3,245-y3,a1);
outtextxy(360+x3,260-y3,"Before Translation");
*/
/* To draw modified object */
/*getch();*/
draw_triangle(xm1,ym1,xm2,ym2,xm3,ym3);
/*
sprintf(a1,"A'(%d,%d)",xm1,ym1);
outtextxy(325+xm1,245-ym1,a1);
sprintf(a1,"B'(%d,%d)",xm2,ym2);
outtextxy(325+xm2,245-ym2,a1);
sprintf(a1,"C'(%d,%d)",xm3,ym3);
outtextxy(325+xm3,245-ym3,a1);
outtextxy(360+xm3,260-ym3,"After Translation");
*/
}
|
C
|
#include"Heap.h"
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void swap(HPDataType *a, HPDataType *b)
{
HPDataType tmp;
tmp = *a;
*a = *b;
*b = tmp;
}
void DownAdjust(Heap *hp, int n)
{
int cur = n;
while (cur * 2 + 1 < hp->_size)//һѵĽڵûڵ㣬ôҶӣֱ
{
if (hp->_data[cur] < hp->_data[cur * 2 + 1])//УұСҪִн
{
if (cur * 2 + 2 >= hp->_size ||//ҺӲڣֱӽ
hp->_data[cur * 2 + 1] >= hp->_data[cur * 2 + 2])//ӱҺӴôҾӻ
{
swap(&hp->_data[cur], &hp->_data[cur * 2 + 1]);//ֵ
cur = cur * 2 + 1;//λ
}
else//ҺӴұӴôҺӻ
{
swap(&hp->_data[cur], &hp->_data[cur * 2 + 2]);
cur = cur * 2 + 2;
}
}
else if (cur * 2 + 2 < hp->_size&&hp->_data[cur] < hp->_data[cur * 2 + 2])//ӴҺСôҺӽ
{
swap(&hp->_data[cur], &hp->_data[cur * 2 + 2]);
cur = cur * 2 + 2;
}
else
{
break;//ұҺӶôֱ
}
}
}
void HeapInit(Heap *hp, HPDataType *a, int n)
{
int i;
hp->_capacity = MAXSIZE > n ? MAXSIZE : n;
hp->_size = n;
hp->_data = (HPDataType *)malloc(sizeof(HPDataType)*hp->_capacity);
memcpy(hp->_data, a, sizeof(HPDataType)*n);
for (i = n / 2 - 1; i >= 0; i--)
{
DownAdjust(hp, i);
}
}
void HeapDestory(Heap *hp)
{
if (hp->_data)
{
free(hp->_data);
hp->_data = NULL;
hp->_size = hp->_capacity = 0;
}
}
void HeapPush(Heap *hp, HPDataType x)
{
int cur = hp->_size;
if (hp->_size == hp->_capacity)
{
hp->_capacity *= 2;
hp->_data = (HPDataType *)realloc(hp->_data, hp->_capacity*sizeof(HPDataType));
}
hp->_data[hp->_size] = x;
hp->_size++;
while (cur)
{
if (hp->_data[cur] > hp->_data[(cur - 1) / 2])
{
swap(&hp->_data[cur], &hp->_data[(cur - 1) / 2]);
cur = (cur - 1) / 2;
}
else
{
break;
}
}
}
void HeapPop(Heap*hp)
{
swap(hp->_data, hp->_data+hp->_size-1);
hp->_size--;
DownAdjust(hp, 0);
}
HPDataType HeapTop(Heap *hp)
{
if (hp->_size==0)
{
return (HPDataType)0;
}
return hp->_data[0];
}
int HeapSize(Heap *hp)
{
return hp->_size;
}
int HeapEmpty(Heap *hp)
{
return hp->_size == 0;
}
void HeapPrint(Heap *hp)
{
int i;
int tag = 0;
int tmp = 1;
for (i = 0; i < hp->_size; i++)
{
printf("%d", hp->_data[i]);
if (i == tag)
{
putchar('/n');
tmp *= 2;
tag += tmp;
}
}
}
void HeapSort(Heap *hp)
{
int tmp = hp->_size;
while (hp->_size>=1)
{
HeapPop(hp);
}
hp->_size = tmp;
}
|
C
|
#ifndef READDIR_H
#define READDIR_H
/*
* Structures and types used to implement opendir/readdir/closedir
* on Windows 95/NT.
*/
#include <io.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
/* struct dirent - same as Unix */
struct dirent {
long d_ino; /* inode (always 1 in WIN32) */
off_t d_off; /* offset to this dirent */
unsigned short d_reclen; /* length of d_name */
char d_name[_MAX_FNAME + 1]; /* filename (null terminated) */
};
/* typedef DIR - not the same as Unix */
typedef struct {
long handle; /* _findfirst/_findnext handle */
short offset; /* offset into directory */
short finished; /* 1 if there are not more files */
struct _finddata_t fileinfo; /* from _findfirst/_findnext */
char *dir; /* the dir we are reading */
struct dirent dent; /* the dirent to return */
} DIR;
/* Function prototypes */
DIR *opendir(const char *);
struct dirent *readdir(DIR *);
int readdir_r(DIR *, struct dirent *, struct dirent **);
int closedir(DIR *);
int rewinddir(DIR *);
#endif /* READDIR_H */
|
C
|
#include "binary_trees.h"
/**
* binary_tree_depth - check the depth of a tree
* @tree: checking
* Return: depth
*/
size_t binary_tree_depth(const binary_tree_t *tree)
{
size_t size;
if (!tree)
return (0);
else if (tree->parent)
{
size = binary_tree_depth(tree->parent);
return (size + 1);
}
else
return (0);
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_LEN 10
typedef struct treeNode
{
char club[MAX_LEN];
int point;
struct treeNode *left, *right;
} treeNode;
treeNode *search(char club[], treeNode *root)
{
if (root == NULL)
return NULL;
else if (strcmp(root->club, club) == 0)
return root;
else if (strcmp(root->club, club) < 0)
return search(club, root->right);
else
{
return search(club, root->left);
}
}
void insertNode(char club[],int point, treeNode **root)
{
if (*root == NULL)
{
*root = (treeNode *)malloc(sizeof(treeNode));
strcpy((*root)->club, club);
(*root)->point = point;
(*root)->left = NULL;
(*root)->right = NULL;
}
else if (strcmp(club, (*root)->club) < 0)
insertNode(club, point, &(*root)->left);
else if (strcmp(club, (*root)->club) > 0)
insertNode(club, point, &(*root)->right);
}
void makeNullTree(treeNode **treeRoot)
{
(*treeRoot) = NULL;
(*treeRoot)->left = NULL;
(*treeRoot)->right = NULL;
}
int isEmptyTree(treeNode *treeRoot)
{
return treeRoot == NULL;
}
treeNode *leftSubTree(treeNode *node)
{
if (node != NULL)
{
return node->left;
}
return NULL;
}
treeNode *rightSubTree(treeNode *node)
{
if (node != NULL)
{
return node->right;
}
return NULL;
}
void preOrderPrint(treeNode *node)
{
if (node != NULL)
{
printf("%s\t\t%d\n", node->club, node->point);
preOrderPrint(node->left);
preOrderPrint(node->right);
}
}
void freeTree(treeNode *node)
{
if (node == NULL)
return;
freeTree(leftSubTree(node));
freeTree(rightSubTree(node));
free(node);
}
char *deleteMin(treeNode **root)
{
char *k;
if ((*root)->left == NULL)
{
strcpy(k, (*root)->club);
(*root) = (*root)->right;
return k;
}
else
return deleteMin(&(*root)->left);
}
void deleteNode(char ele[], treeNode **root)
{
if (*root != NULL)
{
if (strcmp(ele, (*root)->club) < 0)
{
deleteNode(ele, &(*root)->left);
}
else if (strcmp(ele, (*root)->club) > 0)
{
deleteNode(ele, &(*root)->right);
}
else if ((*root)->left == NULL && (*root)->right == NULL)
{
*root = NULL;
}
else if ((*root)->left == NULL)
{
*root = (*root)->right;
}
else if ((*root)->right == NULL)
{
*root = (*root)->left;
}
else
{
strcpy((*root)->club, deleteMin(&(*root)->right));
}
}
}
void lowerThanField(int key,treeNode *node)
{
if (node != NULL)
{
if(node->point < key){
printf("%s\n",node->club);
}
preOrderPrint(node->left);
preOrderPrint(node->right);
}
}
|
C
|
#include <stdio.h>
#include <string.h>
#include "sfpr_queue.h"
#include "sfpr_string.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
*\file sfpr_queue.c
*\brief SFPRqueue ģ
*\author bijing
*\version 0.1.0
*\date 2012-02-06
*/
struct sfpr_queue_node_s{
unsigned long flag;
void *data; /**< нڵ洢 */
int level; /**< ݵȼ */
struct sfpr_queue_node_s *next; /**< ָ һݽڵ*/
};
/**
*\ingroup queue_struct
*\brief ݲڵ
*/
typedef struct sfpr_queue_operator_s{
sfpr_queue_node_t *node; /**< ָеݽڵ */
sfpr_mutex_t lock; /**< ڵ */
}sfpr_queue_operator_t;
struct sfpr_queue_s{
unsigned long flag;
int length; /**< */
int count;/**< еǰ*/
sfpr_queue_operator_t header; /**< ͷָ */
sfpr_queue_operator_t tailer; /**< βڵָ*/
sfpr_cond_t not_empty_cond; /**< вź*/
sfpr_queue_node_t *node;/**< 㻺 */
sfpr_queue_node_t *tail_node[SFPR_QUEUE_MAX_LEVEL]; /**< βָ */
int tailer_level;
};
sfpr_queue_t *sfpr_queue_create(void)
{
sfpr_queue_t *queue;
#ifdef LOG_DEBUG
printf("sfpr_queue_create() | debug | create a new queue\n");
#endif
queue = (sfpr_queue_t *)malloc(sizeof(sfpr_queue_t));
if (NULL== queue)
{
#ifdef LOG_ERROR
fprintf(stderr,"sfpr_queue_create() | error | malloc queue failed!\n");
#endif
return NULL;
}
memset(queue,0,sizeof(sfpr_queue_t));
queue->count = 0;
return queue ;
}
int sfpr_queue_destroy(sfpr_queue_t *queue)
{
if(NULL==queue)
{
#ifdef LOG_ERROR
fprintf(stderr,"sfpr_queue_destroy() | error | queue is NULL !\n");
#endif
return SFPR_ERROR;
}
#ifdef LOG_DEBUG
printf("sfpr_queue_destroy() | debug | \n");
#endif
if(queue->flag & SFPR_QUEUE_INIT_OK)
{
sfpr_queue_clear(queue);
sfpr_cond_destroy(&queue->not_empty_cond);
sfpr_mutex_destroy(&queue->header.lock);
sfpr_mutex_destroy(&queue->tailer.lock);
free(queue->node);
}
free(queue);
return SFPR_SUCCESS;
}
int sfpr_queue_init(sfpr_queue_t *queue)
{
if(NULL==queue)
{
#ifdef LOG_ERROR
fprintf(stderr,"sfpr_queue_init() | error | queue is NULL !\n");
#endif
return SFPR_ERROR;
}
#ifdef LOG_DEBUG
printf("sfpr_queue_init() | debug | init a queue\n");
#endif
queue->header.node = NULL;
queue->tailer.node = NULL;
if(queue->length <= 0){
queue->length = SFPR_DEFAULT_QUEUE_LENGTH;
}
queue->length = (queue->length>SFPR_MAX_QUEUE_LENGTH)?SFPR_MAX_QUEUE_LENGTH:(queue->length);
queue->node = (sfpr_queue_node_t*)malloc(queue->length * sizeof(sfpr_queue_node_t));
if(!queue->node)
{
#ifdef LOG_ERROR
fprintf(stderr,"sfpr_queue_init() | error | malloc queue node failed!\n");
#endif
return SFPR_ERROR;
}
memset(queue->node,0,queue->length * sizeof(sfpr_queue_node_t));
/**< */
sfpr_cond_create(&queue->not_empty_cond);
sfpr_mutex_create(&queue->header.lock,0);
sfpr_mutex_create(&queue->tailer.lock,0);
queue->flag = SFPR_QUEUE_INIT_OK;
return SFPR_SUCCESS;
}
int sfpr_queue_put(sfpr_queue_t *queue,void *data)
{
sfpr_queue_node_t *node ;
int i;
if (NULL == queue)
{
#ifdef LOG_ERROR
fprintf(stderr,"sfpr_queue_put() | error | queue is NULL !\n");
#endif
return SFPR_ERROR;
}
#ifdef LOG_DEBUG
sfpr_str_hex_print("sfpr_queue_put() | put data",data,16);
#endif
sfpr_mutex_lock(&queue->tailer.lock);
for(i=0;i<queue->length;i++)
{
if(!(queue->node[i].flag & SFPR_QUEUE_NODE_USED))
{
node = &(queue->node[i]);
break;
}
}
if(i == queue->length)
{
#ifdef LOG_ERROR
fprintf(stderr,"sfpr_queue_put() | error | queue is overflow!\n");
#endif
sfpr_mutex_unlock(&queue->tailer.lock);
return SFPR_ERROR;
}
memset(node,0,sizeof(sfpr_queue_node_t));
node->data = data;
node->flag = SFPR_QUEUE_NODE_USED;
node->next =NULL;
/**< ΪʱβݣҪͷָҲָýڵ*/
if (NULL == queue->tailer.node)
{
queue->tailer.node = node;
sfpr_mutex_unlock(&queue->tailer.lock);
sfpr_mutex_lock(&queue->header.lock);
queue->header.node = node;
queue->count++;
sfpr_cond_signal_all(&queue->not_empty_cond);
sfpr_mutex_unlock(&queue->header.lock);
}
else
{
/**< вΪʱֱβڵ*/
queue->tailer.node->next = node;
queue->tailer.node = node;
queue->count++;
sfpr_mutex_unlock(&queue->tailer.lock);
}
return SFPR_SUCCESS ;
}
static sfpr_queue_node_t *get_prep_tail(sfpr_queue_t *queue,int offset)
{
int i = offset - 1;
while(i>=0){
if(queue->tail_node[i]){
return queue->tail_node[i];
}
i--;
}
return NULL;
}
int sfpr_queue_put_with_level(sfpr_queue_t *queue,void *data,int level)
{
sfpr_queue_node_t *node = NULL,*prep = NULL;
int i,offset = 0;
if (NULL == queue){
#ifdef LOG_ERROR
fprintf(stderr,"sfpr_queue_put() | error | queue is NULL !\n");
#endif
return SFPR_ERROR;
}
//level ķΧ1--8
level = (level<0)?0:level;
level = (level>SFPR_QUEUE_MAX_LEVEL-1)?(SFPR_QUEUE_MAX_LEVEL-1):level;
level = (level == 0)?8:level;
//offset ķΧ0--7
offset = level - 1;
#ifdef LOG_NOTICE
fprintf(stderr,"sfpr_queue_put() | node level:%d\n",level);
#endif
sfpr_mutex_lock(&queue->tailer.lock);
for(i=0;i<queue->length;i++){
if(!(queue->node[i].flag & SFPR_QUEUE_NODE_USED)){
node = &(queue->node[i]);
break;
}
}
if(i == queue->length){
#ifdef LOG_ERROR
fprintf(stderr,"sfpr_queue_put() | error | queue is overflow!\n");
#endif
sfpr_mutex_unlock(&queue->tailer.lock);
return SFPR_ERROR;
}
memset(node,0,sizeof(sfpr_queue_node_t));
node->data = data;
node->flag = SFPR_QUEUE_NODE_USED;
node->next = NULL;
/**< ΪʱβݣҪͷָҲָýڵ*/
if (NULL == queue->tailer.node)
{
queue->tailer.node = node;
queue->tail_node[offset] = node;
queue->tailer_level = offset;
sfpr_mutex_unlock(&queue->tailer.lock);
sfpr_mutex_lock(&queue->header.lock);
queue->header.node = node;
queue->count++;
sfpr_cond_signal_all(&queue->not_empty_cond);
sfpr_mutex_unlock(&queue->header.lock);
}
/**< вΪ*/
else
{
/**< û*/
if(!queue->tail_node[offset])
{
queue->tail_node[offset] = node;
prep = get_prep_tail(queue,offset);
if(!prep){
sfpr_mutex_lock(&queue->header.lock);
node->next = queue->header.node;
queue->header.node = queue->tail_node[offset];
sfpr_mutex_unlock(&queue->header.lock);
}else{
node->next = prep->next;
prep->next = queue->tail_node[offset];
}
}
else
{
node->next = queue->tail_node[offset]->next;
queue->tail_node[offset]->next = node;
queue->tail_node[offset] = node;
}
if(offset >= queue->tailer_level)
{
queue->tailer.node->next = node;
queue->tailer.node = node;
queue->tailer_level = offset;
}
queue->count++;
sfpr_mutex_unlock(&queue->tailer.lock);
}
return SFPR_SUCCESS;
}
/**
*\brief ӵǰȡһõĶͬʱȡĶӶɾ
*ǰΪգֱµĶ롣
*/
void *sfpr_queue_get(sfpr_queue_t *queue)
{
void *data = NULL;
sfpr_queue_node_t *node = NULL;
if(NULL== queue)
{
#ifdef LOG_ERROR
fprintf(stderr,"sfpr_queue_get() | error | queue is NULL !\n");
#endif
return NULL;
}
sfpr_mutex_lock(&queue->header.lock);
/**<Ϊʱȴݲź֪ͨ */
while (NULL == queue->header.node)
{
sfpr_cond_wait(&queue->not_empty_cond,&queue->header.lock);
}
node =queue->header.node;
/**<ֻһʱҪͷָβָ뻥 */
if (node == queue->tailer.node)
{
queue->header.node = queue->header.node->next;
sfpr_mutex_lock(&queue->tailer.lock);
if(node == queue->tailer.node)
{
#ifdef LOG_DEBUG
fprintf(stderr,"sfpr_queue_get() | debug | GETGET (tmpnode == queue->tailer.node) \n");
#endif
queue->tailer.node = NULL;
}
sfpr_mutex_unlock(&queue->tailer.lock);
}
/**<жһڵ㣬ֱӴӶͷȥ*/
else
{
queue->header.node = queue->header.node->next;
}
data = node->data;
node->flag = 0;
queue->count--;
sfpr_mutex_unlock(&queue->header.lock);
return data;
}
int sfpr_queue_size(sfpr_queue_t *queue)
{
if (NULL != queue)
{
return queue->count;
}
return -1;
}
/*жϵǰеǷΪգtrueʾգflaseΪǿ*/
int sfpr_queue_is_empty(sfpr_queue_t *queue)
{
int isEmpty;
if (NULL != queue->tailer.node)
return SFPR_FALSE;
sfpr_mutex_lock(&queue->header.lock);
sfpr_mutex_lock(&queue->tailer.lock);
isEmpty = (NULL ==queue->tailer.node);
sfpr_mutex_unlock(&queue->tailer.lock);
sfpr_mutex_unlock(&queue->header.lock);
#ifdef LOG_DEBUG
fprintf(stderr,"sfpr_queue_is_empty() | debug | isEmpty =%d \n",isEmpty);
#endif
return isEmpty;
}
/*նеĶ*/
int sfpr_queue_clear(sfpr_queue_t *queue)
{
sfpr_queue_node_t *node = NULL;
if(NULL== queue)
{
#ifdef LOG_ERROR
fprintf(stderr,"sfpr_queue_get() | error | queue is NULL !\n");
#endif
return -1;
}
sfpr_mutex_lock(&queue->header.lock);
sfpr_mutex_lock(&queue->tailer.lock);
while (NULL != queue->header.node)
{
node = queue->header.node;
queue->header.node = node->next;
memset(node,0,sizeof(sfpr_queue_node_t));
}
queue->tailer.node= NULL;
queue->count = 0;
sfpr_mutex_unlock(&queue->tailer.lock);
sfpr_mutex_unlock(&queue->header.lock);
return SFPR_SUCCESS;
}
int sfpr_queue_enum(sfpr_queue_t *queue)
{
char buffer[256];
sfpr_queue_node_t *node = NULL;
if(NULL== queue)
{
#ifdef LOG_ERROR
fprintf(stderr,"sfpr_queue_get() | error | queue is NULL !\n");
#endif
return -1;
}
sfpr_mutex_lock(&queue->header.lock);
sfpr_mutex_lock(&queue->tailer.lock);
node = queue->header.node;
while (NULL != node)
{
memset(buffer,0,sizeof(buffer));
sprintf(buffer,"sfpr_queue_enum() | node level:%d",node->level);
sfpr_str_hex_print(buffer,node->data,16);
node = node->next;
sfpr_time_msleep(1000);
}
sfpr_mutex_unlock(&queue->tailer.lock);
sfpr_mutex_unlock(&queue->header.lock);
return SFPR_SUCCESS;
}
#ifdef __cplusplus
}
#endif
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
char str[12];
int used[999] = {};
int check[5] = {};
int oks[] = {123, 999, 114, 514, 99};
int main() {
for (size_t k = 0; k < 1000000; k++) {
srand(k);
for (int i = 0; i < 1000; i++) used[i] = 0;
for (int i = 0; i < 5; i++) check[i] = 0;
for (int n = 0; n < 100; n++) {
int i = 0;
while (used[i]) i = rand() % 1000;
used[i] = 1;
}
int ok = 1;
for (int j = 0; j < 5; j++) {
if (!used[oks[j]]) ok = 0;
}
if (ok) {
printf("ok ! %d\n", k);
return 0;
} else {
printf("%d\n", k);
}
}
}
|
C
|
/* ---------------------------------------------------------------------------
** sqlite3-bind: SQLite C API - Parameter binding helper for SQLite.
** ---------------------------------------------------------------------------
** Copyright (c) 2016 by Payton Bissell, payton.bissell@gmail.com
** ---------------------------------------------------------------------------
** This example demonstrats using the sqlite3-bind function to bind parameters
** for a select.
**
** The purpose of this example is to illustrate how the sqlite3-bind function
** can be used as simply as possible.
**
** 1. It does not imply or even demonstrate good programming practices.
** 2. It is NOT designed for high performance.
** 3. It is not defect free, so use with caution.
**
** ---------------------------------------------------------------------------
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sqlite3-bind.h>
/* ---------------------------------------------------------------------------
** Structure of test.db for example...
**
** create table re_trans
** ( re_trans_id integer primary key,
** street text not null default '',
** city text not null default '',
** zip text not null default '',
** state text not null default '',
** beds integer not null default 0,
** baths integer not null default 0,
** sqft integer not null default 0,
** type text not null default '',
** price integer not null default 0,
** latitude double not null default '0.0',
** longitude double not null default '0.0'
** );
** ---------------------------------------------------------------------------
*/
/* ---------------------------------------------------------------------------
** Print each result
*/
static int print_result(void *arg, int argc, char **argv, char **cols)
{ if (argc!=4) return 0;
printf("Result - CITY:%s\tPRICE:%s\tSQFT:%s\tBEDS:%s\n", argv[0], argv[1], argv[2], argv[3]);
return 0;
}
/* ---------------------------------------------------------------------------
** Assumes that the test.db file is present and contains realestate transaction
** data
*/
int main()
{ const char *type="Condo";
int price=80000;
// open and setup the database.
sqlite3 *db=NULL;
if (sqlite3_open("test.db", &db)!=SQLITE_OK) return 0;
// Add each row to the database using the sqlite3-bind function
int r=sqlite3_bind_exec(db, "select city, price, sqft, beds from re_trans where type=? and price<?",
print_result, NULL, SQLITE_BIND_TEXT(type), SQLITE_BIND_INT(price), SQLITE_BIND_END);
// check for errors from the API
if (r!=SQLITE_OK) printf("Query Error: code=%d message=%s\n", r, sqlite3_bind_errmsg(db));
else printf("Query Completed.\n");
if (db) sqlite3_close(db);
return 0;
}
/* EOF */
|
C
|
//
#include "probe.h"
#include "ppoint.h"
#include <stdio.h>
//
//void probe_for_ppoint(uberprobe_t *probe, ppoint_t *ppoint) {
// probe->probe = ppoint;
// probe->start = (size_t (*)(void *)) ppoint_start;
// probe->stop = (size_t (*)(void *, size_t)) ppoint_stop;
//}
typedef struct {
ppoint_t *point;
size_t start;
} throughput_data_t;
typedef struct {
ppoint_t *enter;
ppoint_t *exit;
size_t enter_start;
size_t exit_start;
} latency_data_t;
void uberprobe_start(uberprobe_t *probe) {
probe->start(probe);
}
// interval is nanos
double uberprobe_stop(uberprobe_t *probe, double interval) {
return probe->stop(probe, interval);
}
int uberprobe_less_than(uberprobe_t *probe, double a, double b) {
return probe->less_than(a, b);
}
static void uberprobe_throughput_start(uberprobe_t *probe) {
throughput_data_t *x = (throughput_data_t *)(probe->arg);
x->start = ppoint_start(x->point);
}
// returns ops / sec
static double uberprobe_throughput_stop(uberprobe_t *probe, double interval) {
throughput_data_t *x = (throughput_data_t *)(probe->arg);
return ((double)ppoint_stop(x->point, x->start)) / (interval / (1000 * 1000 * 1000));
}
static int uberprobe_throughput_less_than(double a, double b) {
return a < b;
}
void throughput_probe_init(uberprobe_t *probe, ppoint_t *point) {
throughput_data_t *x = (throughput_data_t *)malloc(sizeof(throughput_data_t));
x->point = point;
probe->arg = x;
probe->start = uberprobe_throughput_start;
probe->stop = uberprobe_throughput_stop;
probe->less_than = uberprobe_throughput_less_than;
}
static void uberprobe_latency_start(uberprobe_t *probe) {
latency_data_t *x = (latency_data_t *)(probe->arg);
x->enter_start = ppoint_start(x->enter);
x->exit_start = ppoint_start(x->exit);
}
// returns sec
static double uberprobe_latency_stop(uberprobe_t *probe, double interval) {
latency_data_t *x = (latency_data_t *)(probe->arg);
size_t enters = ppoint_stop(x->enter, 0);
size_t exits = ppoint_stop(x->exit, 0);
double arrivals_during_interval = enters - x->enter_start;
double arrival_rate = (arrivals_during_interval / interval) * 1000 * 1000 * 1000;
// lam = L/rate
double latency = ((double)(enters - exits)) / arrival_rate;
// printf("# interval=%g enter_start=%lu exter=%lu exits=%lu arrivals=%g arrival_rate=%g latency=%g\n",
// interval/ (1000 * 1000 * 1000),
// x->enter_start,
// enters,
// exits,
// arrivals_during_interval,
// arrival_rate,
// latency);
return latency; // lower latency => return bigger number
}
static int uberprobe_latency_less_than(double a, double b) {
return a > b;
}
void latency_probe_init(uberprobe_t *probe, ppoint_t *enter, ppoint_t *exit) {
latency_data_t *x = (latency_data_t *)malloc(sizeof(latency_data_t));
x->enter = enter;
x->exit = exit;
ppoint_start(x->enter);
ppoint_start(x->exit);
probe->arg = x;
probe->start = uberprobe_latency_start;
probe->stop = uberprobe_latency_stop;
probe->less_than = uberprobe_latency_less_than;
}
void uberprobe_destroy(uberprobe_t *probe) {
free(probe->arg);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "Funciones Matematicas.h"
#include "Funcion pedir numero.h"
int main(){
int opcion;
char seguir='s';
float numeroA;
float numeroB;
float suma;
float resta;
float division;
float producto;
int factorialA;
int factorialB;
int flagDivision=0;
int flagNumeroA=0;
int flagNumeroB=0;
do
{
printf("Elija una opcion\n");
if(flagNumeroA==0)
{
printf("1.Ingresar 1er operando (A=X)\n");
}
else
{
printf("1.Ingresar 1er operando (A=%.2f)\n",numeroA);
}
if(flagNumeroB==0)
{
printf("2.Ingrese 2do operando (B=Y)\n");
}
else
{
printf("2.Ingrese 2do operando (B=%.2f)\n",numeroB);
}
printf("3.Calcular todas las operaciones\n");
printf("4.Informar resultados\n");
printf("5.Salir\n");
opcion=pedirEntero("Ingrese una opcion: ");
switch(opcion)
{
case 1: numeroA=pedirFloat("Ingrese el 1er operando: ");
flagNumeroA=1;
break;
case 2:
numeroB=pedirFloat("Ingrese el 2do operando: ");
if(numeroB==0)
{
flagDivision=1;
}
flagNumeroB=1;
break;
case 3:
printf("Calculando...\n");
suma=sumarNumeros(numeroA,numeroB);
resta=restarNumeros(numeroA,numeroB);
division=dividirNumeros(numeroA,numeroB);
producto=multiplicarNumeros(numeroA,numeroB);
factorialA=factorial(numeroA);
factorialB=factorial(numeroB);
break;
case 4:
printf("La suma es: %.2f\n",suma);
printf("La resta es: %.2f\n",resta);
if(flagDivision==1)
{
printf("No se puede dividir por 0\n");
}
else
{
printf("La division es: %.2f\n",division);
}
printf("El producto es: %.2f\n",producto);
if(numeroA<0||numeroA!=(int)numeroA)
{
printf("No se puede hacer factorial al operando A ingresado\n");
}
else
{
printf("El factorial de A es: %d\n",factorialA);
}
if(numeroB<0||numeroB!=(int)numeroB)
{
printf("No se puede hacer factorial al operando B ingresado\n");
}
else
{
printf("El factorial de B es: %d\n",factorialB);
}
break;
case 5:
printf("Saliendo...\n");
return 0;
default:
printf("No ingreso una opcion correcta\n");
break;
}
system("pause");
system("cls");
fflush(stdin);
}while(seguir=='s');
}
|
C
|
#include "../includes/fractol.h"
void draw_pixel(int x, int y, t_windows *window, int color)
{
int pixel;
int hex;
hex = color;
if(window && x >= 0 && y >= 0 && x < LONGUEUR && y < LARGEUR)
{
pixel = (x * 4) + (4 * LONGUEUR * y);
window->img_str[pixel] = (hex / 64) + 10;
window->img_str[pixel + 1] = (hex / 32) + 10;
window->img_str[pixel + 2] = (hex / 16) + 10;
}
}
void draw_new_map(t_windows *w)
{
int bpp;
int s_l;
int endian;
w->img_ptr = mlx_new_image(w->graph_id, LONGUEUR, LARGEUR);
w->img_str = (unsigned char*)mlx_get_data_addr(w->img_ptr, &bpp, &s_l,
&endian);
//ft_printf("mandelbrot %f, %f , %f , %f, %d", w->m->x1, w->m->x2, w->m->y1, w->m->y2, w->m->i);
mandelbrot(w, w->m);
mlx_put_image_to_window(w->graph_id, w->windows, w->img_ptr, 0, 0);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main()
{
char ch1 = 'g';
char ch2 = 's';
char *ptr;
printf("Char 1 is %c\n", ch1);
printf("Char 2 is %c\n", ch2);
printf("Address of Char 1 is %p\n", &ch1);
printf("Address of Char 2 is %p\n", &ch2);
ptr = &ch1;
ch2 = *ptr;
printf("Char 1 is %c\n", ch1);
printf("Char 2 is %c\n", ch2);
printf("Address of ptr is %p\n", ptr);
printf("The current process %d \n", getpid());
printf("The parent process is %d \n", getppid());
printf("The owner of this process has uid %d \n", getuid());
sleep(1);
int A[] = {1, 2, 3, 4, 5, 6};
int sum = 0, pdt = 1, PID, i;
if ((PID = fork()) == 0)
{
for (i = 0; i < 6; i++)
sum += A[i];
printf("This is child process computed sum %d \n", sum);
}
if (PID < 0)
{
fprintf(stderr, "problem creating a process \n");
}
if (PID > 0)
{
for (i = 0; i < 6; i++)
pdt *= A[i];
printf("The parent process completed the product %d \n", pdt);
}
int child_status, pid, pidwait;
if ((pid = fork()) == 0)
{
printf("This is the child !\n");
}
else
{
pidwait = wait(&child_status);
printf("child % d has terminated\n", pidwait);
}
exit(0);
return 0;
}
|
C
|
#include "vuaes.h"
//#include "vumacro.h"
#include "reg.h"
#include "auth_aes.h"
//#define AES_MODE_START 0x04 // start data encrypt/decrypt
#define AES_MODE_KEYEXPAND 0x10 // start key expanding
#define AES_MODE_KEY_INS 0x02 // key inserted
#define AES_MODE_DATA_INS 0x00 // data inserted
#define AES_SIZE_128 0x00
#define AES_SIZE_192 0x08
#define AES_SIZE_256 0x10
#define AESKEY_LEN 4
static unsigned int s_aestemp[4];
/* const RB dan const Zero digunakan saat proses penghitungan AES CMAC */
static uint8_t const_rb[16] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x87
};
void xor_16byte_array(unsigned int* result, unsigned int* a, unsigned int* b)
{
result[0] = a[0] ^ b[0];
result[1] = a[1] ^ b[1];
result[2] = a[2] ^ b[2];
result[3] = a[3] ^ b[3];
}
static void
XOR_16BYTEARRAY(unsigned char* result,unsigned char* a, unsigned char* b){
unsigned char i;
for(i=0;i<16;i++){
result[i] = a[i]^b[i];
}
}
void AES_CRYPT(unsigned int* out,unsigned int* in)
{
//Input array
AES_DATA_0 = in[3];
AES_DATA_1 = in[2];
AES_DATA_2 = in[1];
AES_DATA_3 = in[0];
while ((AES_CON & 0x01)== 0x00);
//Output array
out[3] = AES_DATA_0;
out[2] = AES_DATA_1;
out[1] = AES_DATA_2;
out[0] = AES_DATA_3;
}
void
vuaes_insertkey16byte(unsigned int * pkey){
// Insert key
AES_KEY_0 = pkey[3];
AES_KEY_1 = pkey[2];
AES_KEY_2 = pkey[1];
AES_KEY_3 = pkey[0];
/* Wait key ready */
while ((AES_CON & 0x02)== 0x00);
}
static
void memcpy_16_byte(unsigned int* dest, unsigned int* src)
{
dest[0x00] = src[0x00];
dest[0x01] = src[0x01];
dest[0x02] = src[0x02];
dest[0x03] = src[0x03];
}
void MEMCPY_16BYTE(uint8_t* dest,uint8_t* src){
dest[0x00] = src[0x00];
dest[0x01] = src[0x01];
dest[0x02] = src[0x02];
dest[0x03] = src[0x03];
dest[0x04] = src[0x04];
dest[0x05] = src[0x05];
dest[0x06] = src[0x06];
dest[0x07] = src[0x07];
dest[0x08] = src[0x08];
dest[0x09] = src[0x09];
dest[0x0A] = src[0x0A];
dest[0x0B] = src[0x0B];
dest[0x0C] = src[0x0C];
dest[0x0D] = src[0x0D];
dest[0x0E] = src[0x0E];
dest[0x0F] = src[0x0F];
}
void
vuaes_process(PINPUTAES pinp){
uint16_t block;
unsigned int* pivbuff;
block = pinp->bufferlen/4;
pivbuff = pinp->piv;
//Enable AES Clock
CLKCON |= 0x10;
if(pinp->mode == AES_MODE_DECRYPT){
AES_CON = AES_MODE_DECRYPT | AES_SIZE_128;
}else{
AES_CON = AES_MODE_ENCRYPT | AES_SIZE_128;
}
vuaes_insertkey16byte(pinp->pkey);
while(block >0){
if(pinp->mode == AES_MODE_DECRYPT){
AES_CRYPT(s_aestemp,pinp->pbuffer);
xor_16byte_array(pinp->presult,pivbuff,s_aestemp);
pivbuff = pinp->pbuffer;
}else{
xor_16byte_array(s_aestemp,pivbuff,pinp->pbuffer);
AES_CRYPT(pinp->presult,s_aestemp);
pivbuff = pinp->presult;
}
pinp->presult+=4;
pinp->pbuffer +=4;
block--;
}
AES_CON = 0x00;
CLKCON &= 0xEF; //Disable AES Clock
}
static void
cmac_leftshift1bit(uint8_t * input, uint8_t * output){
uint8_t idx;
uint8_t overflow = 0;
idx=16;
while(idx){
idx-=1;
output[idx] = input[idx] << 1;
output[idx] |= overflow;
overflow = ((input[idx] & 0x80) !=0) ? 1:0;
}
}
static void
cmac_gen_subkey(uint8_t * key,uint8_t * k1,uint8_t * k2){
static uint8_t input[16] = {
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 };
uint8_t ciphered[16];
uint8_t temp[16];
unsigned int keyint[4];
unsigned int inputint[4];
unsigned int cipheredint[4];
memcpy8to32(keyint,key,16);
memcpy8to32(inputint,input,16);
//AES_INSERTKEY(keyint);
vuaes_insertkey16byte(keyint);
AES_CRYPT(cipheredint,inputint);
memcpy32to8(ciphered,cipheredint,4);
if(( ciphered[0] & 0x80 ) == 0) { /* MSB(L) = 0 then K1 = L << 1 */
cmac_leftshift1bit(ciphered,k1);
}else{ /* K1 = (L<<1) ^ Rb */
cmac_leftshift1bit(ciphered,temp);
XOR_16BYTEARRAY(k1,temp,const_rb);
}
if((k1[0] & 0x80) == 0){
cmac_leftshift1bit(k1,k2);
}else{
cmac_leftshift1bit(k1,temp);
XOR_16BYTEARRAY(k2,temp,const_rb);
}
}
/*
example:
input : C0 FF EE
output: C0 FF EE 80 00 00 00 00 .... 00
*/
static void
cmac_padding(uint8_t * input,uint8_t * padding,uint8_t inputlen){
uint8_t cnt;
/* memcpy */
for(cnt=0;cnt<inputlen;cnt++){
padding[cnt] = input[cnt];
}
padding[inputlen] = 0x80;
/* memset di memory sisanya */
for(cnt = 0;cnt<(15-inputlen);++cnt){
padding[cnt+inputlen+1] = 0x00;
}
}
void
vuaes_cmac(PINPUTAES pinput){
uint8_t subkey_k1[16];
uint8_t subkey_k2[16];
uint8_t key[16];
uint8_t m_last[16];
uint8_t X[16];
uint8_t Y[16];
unsigned int X32[4];
unsigned int Y32[4];
uint8_t padded[16];
uint8_t numround;
uint8_t idx;
uint8_t flagfragment = 0;
uint8_t buffer[64];
uint8_t bufferlen;
uint8_t initvector[16];
//Enable AES Clock
CLKCON |= 0x10;
AES_CON = AES_MODE_ENCRYPT | AES_SIZE_128;
/*only 2 options: 1 or 8 bytes (see veriu security doc)*/
bufferlen = (pinput->bufferlen == 1) ? 1 : pinput->bufferlen * 4;
memcpy32to8(key,pinput->pkey,4);
/* generate 2 subkey */
cmac_gen_subkey(key,subkey_k1,subkey_k2);
/* Tentukan jumlah putaran proses per blok data ( 16 byte ) */
numround = (bufferlen + 15 ) / 16;
if(numround == 0){
numround = 1;
flagfragment = 1;
}else{ /* tentukan apakah butuh padding (16 byte) atau tidak */
flagfragment = ((bufferlen % 16) != 0 ) ? 1 : 0;
}
/* jika panjang data input genap kelipatan 16 byte (tidak terfragment)
maka blok terakhir pada data input di-XOR dengan subkey k1,
hasil dari xor ini akan digunakan pada akhir putaran AES CMAC
*/
memcpy32to8(buffer,pinput->pbuffer,4);
if(!flagfragment){
XOR_16BYTEARRAY(m_last,(&buffer[16*(numround-1)]),subkey_k1);
}else{
cmac_padding(&buffer[16*(numround-1)],padded,bufferlen%16);
XOR_16BYTEARRAY(m_last,padded,subkey_k2);
}
/* Inisialisasi X dengan nilai IV */
memcpy32to8(initvector,pinput->piv,4);
MEMCPY_16BYTE(X,initvector);
/* lakukan loop sebanyak putaran 'numround' */
for(idx=0;idx<numround-1;idx++){
XOR_16BYTEARRAY(Y,((uint8_t *)&pinput->pbuffer[16*idx]),X);
vuaes_insertkey16byte(pinput->pkey);
memcpy8to32(X32,X,16);
memcpy8to32(Y32,Y,16);
AES_CRYPT(X32,Y32); /* X = AES128(Y,key) */
}
/* final process dengan blok terakhir */
XOR_16BYTEARRAY(Y,X,m_last);
memcpy8to32(X32,X,16);
memcpy8to32(Y32,Y,16);
AES_CRYPT(X32,Y32);
/* now put it all to the output */
memcpy_16_byte(pinput->presult,X32);
AES_CON = 0x00;
CLKCON &= 0xEF; //Disable AES Clock
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#define max 5
void disp(int ps[][max+2],int size){
for(int i=0;i<pow(2,size);i++){
printf("\n");
for(int j=0;j<=ps[i][0]+1;j++)
printf("%d\t",ps[i][j]);
}
}
void genpowset(int *set,int size,int ps[][max+2]){
int powsetsize=pow(2,size);
for(int i=0;i<powsetsize;i++)
ps[i][0]=ps[i][1]=0;
//disp(ps,size);
for(int i=0;i<powsetsize;i++){
for(int j=0,k=1;j<size;j++){
if(i & (1<<j)){
//printf("%d\t",set[j]);
ps[i][0]++;
ps[i][1]+=set[j];
ps[i][++k]=set[j];
}
}
//printf("\n");
}
//disp(ps,size);
}
void disp2(int *set1,int *set2){
printf("\nSet 1:\t");
for(int i=2;i-1<=set1[0];i++)
printf("%d\t",set1[i]);
printf("\nSet 2:\t");
for(int i=2;i-1<=set2[0];i++)
printf("%d\t",set2[i]);
printf("\n\n\n\n");
}
void partition(int *set,int size){
int ps[(int)pow(2,max)][max+2];
genpowset(set,size,ps);
//disp(ps,size);
for(int i=0;i<pow(2,size)-1;i++)
for(int j=i+1;j<pow(2,size);j++)
if(ps[i][1]==ps[j][1])
disp2(ps[i],ps[j]);
}
int main(){
int arr[max],size;
printf("Enter size:");
scanf("%d",&size);
printf("Enter elements:");
for(int i=0;i<size;i++)
scanf("%d",&arr[i]);
partition(arr,size);
return 0;
}
|
C
|
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node* next;
}NODE;
typedef struct list
{
NODE* head;
NODE* last;
}LIST;
//Function prototyping
int init(LIST* L);
NODE* create_node(int value);
int is_empty(LIST L);
int append(LIST* L,int value);
void display(LIST L);
void union_list(LIST L1,LIST L2,LIST* L3);
void intersect_list(LIST L1,LIST L2,LIST* L4);
void main()
{
LIST L1,L2,L3,L4;
int value,r,ch;
int d;
NODE* new_node;
NODE* ptr;
int pos,a;
if(init(&L1))
printf("LIST 1 IS INITIALIZED");
else
printf("INITIALIZATION ERROR");
if(init(&L2))
printf("LIST 2 IS INITIALIZED");
else
printf("INITIALIZATION ERROR");
while(1)
{
printf("\nMENU \n1.APPEND \n2.DISPLAY \n3.UNION \n4.INTERSECTION \n5.EXIT \n");
printf("\n ENTER YOUR CHOICE : ");
scanf("%d",&ch);
switch(ch)
{
case 1 :
printf("\n press 0 for list 1 or press 1 for list 2 : ");
scanf("%d",&a);
printf("\n ENTER VALUE TO BE INSERTED : ");
scanf("%d",&value);
if(a==0)
{
if(append(&L1,value))
display(L1);
else
display(L1);
}
else if(a==1)
{
if(append(&L2,value))
display(L2);
else
display(L2);
}
break;
case 2 :
printf("\n press 0 for list 1 or press 1 for list 2 or press 2 for list 3 or press 3 for list 4 : ");
scanf("%d",&a);
printf("\n");
if(a==0)
{
display(L1);
}
else if(a==1)
{
display(L2);
}
else if(a==2)
{
display(L3);
}
else if(a==3)
{
display(L4);
}
break;
case 3 :
init(&L3);
union_list(L1,L2,&L3);
display(L3);
break;
case 4 :
init(&L4);
intersect_list(L1,L2,&L4);
display(L4);
break;
case 5 :
exit(1);
default :
printf("\n WRONG CHOICE \n");
}
}
}
int init(LIST* L)
{
L->head=NULL;
L->last=NULL;
return 1;
}
NODE* create_node(int value)
{
NODE* ptr;
ptr=(NODE*)malloc(sizeof(NODE));
if(ptr!=NULL)
{
ptr->data=value;
ptr->next=NULL;
return ptr;
}
else
return NULL;
}
int is_empty(LIST L)
{
if(L.head==NULL)
return 1;
else
return 0;
}
int append(LIST* L,int value)
{
NODE* new_node,*ptr;
ptr=L->head;
while(ptr!=NULL && ptr->data!=value)
ptr=ptr->next;
if(ptr==NULL)
{
new_node=create_node(value);
if(new_node!=NULL)
{
if(is_empty(*L))
L->last=L->head=new_node;
else
{
L->last->next=new_node;
L->last=new_node;
}
return 1;
}
}
else
return 0;
}
void display(LIST L)
{
NODE* ptr;
ptr=L.head;
while(ptr!=NULL)
{
printf(" %d -> ",ptr->data);
ptr=ptr->next;
}
}
void union_list(LIST L1,LIST L2,LIST* L3)
{
NODE *ptr1,*ptr2;
int value;
ptr1=L1.head;
ptr2=L2.head;
while(ptr1!=NULL)
{
value=ptr1->data;
append(L3,value);
ptr1=ptr1->next;
}
while(ptr2!=NULL)
{
value=ptr2->data;
append(L3,value);
ptr2=ptr2->next;
}
}
void intersect_list(LIST L1,LIST L2,LIST* L4)
{
NODE *ptr1,*ptr2;
int value;
for(ptr1=L1.head;ptr1!=NULL;ptr1=ptr1->next)
{
for(ptr2=L2.head;ptr2!=NULL;ptr2=ptr2->next)
{
if(ptr1->data==ptr2->data)
append(L4,ptr1->data);
}
}
}
|
C
|
#include "Button.h"
#include "DIO.h"
void Button_Initialize(unsigned char portName, unsigned char pinNumber)
{
// Set the direction of the given pin in the given port (direction 0 = input)
DIO_vsetPINDir(portName, pinNumber, 0);
}
unsigned char Button_Read(unsigned char portName, unsigned char pinNumber)
{
unsigned char x;
// Returns 1 if the value of the given pin is high and zero if the value is low
x = DIO_Read_PIN(portName, pinNumber);
return x;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define EPLISON 1.0e-20
#define N_ALPH 256 /* num. of alphabets (EOF is not counted.) */
#define N_SYM (N_ALPH+1) /* num. of all symbol codes including "End-Of-File" code */
/* 8bit 256 alphabets + 1 EOF */
#define N_MAX_SYM_LEN 200
#define N_MAX_NODE ( 2*N_SYM-1 )
#define CMAX 256
#define N_MAX_CODE_LEN 64
typedef struct node NODE;
struct node {
int parent, /* parent node */
child_0, /* child 0 node */
child_1; /* child 1 node */
int code;
double prob;
char sym[ N_MAX_SYM_LEN ]; /* symbol */
};
NODE node[ N_MAX_NODE ];
int find_min_prob_nodes( int max_node, int exclude_node )
{
int id_min = -1;
for ( int i_node = 0; i_node < max_node; i_node++ )
{
if ( i_node != exclude_node && node[i_node].parent == -1 )
{
if ( id_min == -1 ) id_min = i_node;
if ( node[i_node].prob < node[id_min].prob ) id_min = i_node;
}
}
return id_min;
}
void makeHuffmanTree()
{
int left, right;
left = right = -1;
for ( int i_node = N_SYM; i_node < N_MAX_NODE; i_node++ )
{
right = find_min_prob_nodes( i_node, -1 );
left = find_min_prob_nodes( i_node, right );
node[i_node].child_0 = right;
node[i_node].child_1 = left;
node[i_node].prob = node[right].prob + node[left].prob;
strcpy(node[i_node].sym, "\0");
node[right].code = 0;
node[left].code = 1;
node[right].parent = node[left].parent = i_node;
}
}
int main( int argc, char *argv[] )
{
double prob;
double ave_len = 0.0;
char sym[ N_MAX_SYM_LEN ];
int i, i_sym;
FILE *fpr, *fpw;
if( ( fpr = fopen( argv[1], "r" ) ) == NULL )
{
fprintf( stderr, "File open error %s\n", argv[1] );
exit( 1 );
}
for( i=0; i<N_MAX_NODE; i++ )
{
node[i].parent = node[i].child_0 = node[i].child_1 = node[i].code = -1;
}
i = 0;
for (i_sym = 0;i_sym < N_SYM; i_sym++)
{
fscanf( fpr, "%*d%s%*d%lf", sym, &prob );
strcpy( node[i].sym, sym );
if( prob == 0.0) prob = EPLISON;
node[i].prob = prob;
/*
printf( "%s", node[i].sym );
printf( "%9.8f ",node[i].prob );
printf("\n");
*/
i++;
}
makeHuffmanTree();
if( ( fpw = fopen( argv[2], "w" ) ) == NULL )
{
fprintf( stderr, "File open error %s\n", argv[1] );
exit( 1 );
}
for( i=0; i<N_SYM; i++ )
{
char hcode[ N_MAX_CODE_LEN ] = "\0";
hcode[0] = '\0';
int count = i;
// get_hcode
while(1)
{
if( node[count].parent == -1 )break;
char copy[ N_MAX_CODE_LEN ];
strcpy( copy, hcode );
sprintf( hcode, "%d%s", node[count].code, copy );
count = node[count].parent;
}
/*
printf("%d",i);
printf( "%s:", node[i].sym );
printf( "%f:",node[i].prob );
printf("code=%d:",node[i].code );
printf("parent=%d:",node[i].parent );
printf("child0=%d:",node[i].child_0 );
printf("child1=%d:",node[i].child_1 );
printf("%s",hcode);
printf("\n");
*/
int code_len = strlen(hcode);
fprintf( fpw, "# %3d\t%s\t%9.8f\t%3d\t%s\n", i, node[i].sym, node[i].prob, code_len, hcode );
ave_len = ave_len + code_len * node[i].prob;
}
fprintf( fpw, "average code length = %14.8f\n", ave_len);
fprintf( fpw, "compression rate = %14.8f [%%] (ave_len/8)\n", 100 * ave_len / 8.0);
fclose( fpr );
fclose( fpw );
return 0;
}
|
C
|
#include <stdio.h>
int main()
{
int cm = 0;
scanf("%d", &cm);
int foot = cm / 30.48;
int inch = (cm / 30.48 - foot) * 12;
printf("%d %d\n", foot, inch);
return 0;
}
|
C
|
#include "common.h"
#include "linkedlist.h"
#include "thread_pool.h"
List db = {
.name = "db",
.head = NULL,
.tail = NULL,
.count = 0,
.lock = PTHREAD_RWLOCK_INITIALIZER
};
// Thread pool
pthread_t thread_pool[SERVER_BACKLOG];
// Server
int server_init(short port, int backlog);
int server_sendline(Client *, char buffer[], int limit);
int server_recvline(Client *client, char buffer[], int limit);
Client * server_accept_connection(int server_socket);
void server_send_response(Client *, Msg_Type request);
void * server_recv(void *client);
void server_add_client(Client *client);
void server_remove_client(Client *client);
// Client
Client * client_create_node(int socket, char *addr);
void client_get_info(Client *);
bool client_add_friend(Client *client);
int client_remove_friend(Client *client);
// Private chat
int client_friend_chat_setup(Client *client);
int client_friend_chat_thread_create(Client *client);
void * client_friend_chat_thread_handler(void *pclient_pair);
// Group chat
bool client_group_add_member(Client *client);
void * client_group_broadcast_thread_handler(void *pclient);
int client_group_broadcast_thread_create(Client *client);
int client_group_setup(Client *client);
int client_group_create_member_threads(Client *client);
void* client_group_member_thread_handler(void *pclient);
// miscellaneous
void list_print(Client *client, List *list);
void list_send_client_names(Client *);
bool list_does_client_name_exist(char *name, List *list);
Client * list_get_client_by_name(char *name, List *list);
bool list_is_client_in_list(Client *client, List *list);
int main(void)
{
system("clear");
printf("[LOG] Listening @ PORT %d ...\n", SERVER_PORT);
// Initializing server
int server_socket = server_init(SERVER_PORT, SERVER_BACKLOG);
// TODO: Implement Thread_pool
/*for (int i = 0;i < 2; i++)*/
for(;;)
{
// prints all acitve users in a menu
list_print(NULL, &db);
// Accepts incomming connection
Client *client = server_accept_connection(server_socket);
// Creates a server recv thread connection
pthread_t thread1;
if (pthread_create(&thread1, NULL, server_recv, client) != 0)
{
fprintf(stderr, "[ERR] pthread_create: failed to create thread\n");
}
}
// Freeing the client list
ll_free(&db);
}
void client_get_info(Client *client)
{
char recvline[MAXWORD+1];
// Gets user name from client
server_recvline(client, recvline, MAXWORD);
// Checks if the name already exist
while (list_does_client_name_exist(recvline, &db))
{
server_send_response(client, CLIENT_USERNAME_TAKEN);
server_recvline(client, recvline, MAXWORD);
}
server_send_response(client, CLIENT_REGISTERED);
// sets the name to the client struct
strcpy(client->name, recvline);
}
bool list_does_client_name_exist(char *name, struct list_header *list)
{
pthread_rwlock_rdlock(&list->lock);
{
Node *tmp = list->head;
while (tmp)
{
if (strcmp(tmp->client->name, name) == 0)
{
pthread_rwlock_unlock(&list->lock);
return true;
}
tmp = tmp->next;
}
}
pthread_rwlock_unlock(&list->lock);
return false;
}
Client * client_create_node(int socket, char addr[])
{
Client *client = malloc(sizeof(Client));
client->available = true;
client->_friend = NULL;
client->friends_list = (List) {
.name = "Friends",
.head = NULL,
.tail = NULL,
.count = 0,
.lock = PTHREAD_RWLOCK_INITIALIZER
};
client->my_group = (List) {
.name = "Group",
.head = NULL,
.tail = NULL,
.count = 0,
.lock = PTHREAD_RWLOCK_INITIALIZER
};
client->groups_iam_in = (List) {
.name = "Groups i am in",
.head = NULL,
.tail = NULL,
.count = 0,
.lock = PTHREAD_RWLOCK_INITIALIZER
};
// info
client->socket = socket;
snprintf(client->name, MAXWORD, "User%0i", db.count);
strcpy(client->straddr , addr);
// Appends new client to the linked list DS
server_add_client(client);
// Request for the client info (rn only username from the client)
client_get_info(client);
return client;
}
bool client_group_add_member(Client *client)
{
char recvline[MAXWORD+1];
server_recvline(client, recvline, MAXWORD);
Client *member = list_get_client_by_name(recvline, &db);
if (member == NULL)
{
fprintf(stderr, "[ERR] client_group_add_member: member not found\n");
server_send_response(client, CLIENT_NOT_FOUND);
return false;
}
else if (member == client)
{
fprintf(stderr, "[ERR] client_group_add_member: client choose itself\n");
server_send_response(client, CLIENT_CHOOSE_ITSELF);
return false;
}
else if (list_is_client_in_list(member, &client->my_group))
{
fprintf(stderr, "[ERR] client_group_add_member: client already is in group\n");
server_send_response(client, CLIENT_GROUP_MEMBER_EXIST);
return false;
}
pthread_rwlock_wrlock(&db.lock);
{
printf("[LOG] %s added %s to the group\n", client->name, member->name);
if (ll_append(&client->my_group, member) == true)
{
client->my_group.count++;
ll_append(&member->groups_iam_in, client);
member->groups_iam_in.count++;
server_send_response(client, CLIENT_GROUP_MEMBER_ADDED);
}
else
return false;
}
pthread_rwlock_unlock(&db.lock);
list_print(client, &client->my_group);
return true;
}
int client_group_setup(Client *client)
{
Node *tmp = client->my_group.head;
pthread_rwlock_rdlock(&db.lock);
{
if (tmp == NULL)
{
server_send_response(client, CLIENT_GROUP_EMPTY);
pthread_rwlock_unlock(&db.lock);
return -1;
}
client->available = false;
}
pthread_rwlock_unlock(&db.lock);
server_send_response(client, CLIENT_GROUP_CHATROOM_START);
while (tmp) {
if (tmp->client->available)
server_send_response(tmp->client, CLIENT_GROUP_CHATROOM_START);
tmp = tmp->next;
}
return 0;
}
Client * server_accept_connection(int server_socket)
{
int client_socket;
struct sockaddr_in addr;
socklen_t addr_len;
char client_address[MAXLINE+1];
if ((client_socket =
accept(server_socket,(struct sockaddr *)&addr, &addr_len)) < 0)
ERROR_HANDLE();
inet_ntop(AF_INET, &addr, client_address, MAXLINE);
printf("[LOG] Client @ %s connecting ... \n", client_address);
return client_create_node(client_socket, client_address);
}
int server_init(short port, int backlog)
{
int server_socket;
struct sockaddr_in servaddr;
if ((server_socket = socket(AF_INET, SOCK_STREAM, 0)) < 0)
ERROR_HANDLE();
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(port);
if (bind(server_socket, (struct sockaddr *) &servaddr, sizeof(servaddr))
< 0)
ERROR_HANDLE();
if (listen(server_socket, backlog) < 0)
ERROR_HANDLE();
return server_socket;
}
void list_print(Client *client, List *list)
{
Node *node = list->head;
if (client == NULL)
printf("[LOG] DB: ");
else
printf("[LOG] %s`s %s list: ", client->name, list->name);
if (node == NULL)
{
printf("none\n");
return ;
}
pthread_rwlock_rdlock(&list->lock);
{
while (node)
{
printf(" %s ->", node->client->name);
node = node->next;
}
}
pthread_rwlock_unlock(&list->lock);
printf(" NULL\n");
}
void list_send_client_names(Client *client)
{
char buffer[MAXLINE+1];
Node *node = db.head;
int j, k, i = 0;
pthread_rwlock_rdlock(&db.lock);
{
while (node)
{
k = j = 0;
while (node->client->name[k] != '\0')
{
buffer[i++] = node->client->name[k++];
}
buffer[i++] = '\n';
node = node->next;
}
buffer[i-1]= '\0';
}
pthread_rwlock_unlock(&db.lock);
server_sendline(client, buffer, MAXLINE);
}
void * server_recv(void *pclient)
{
Client *client = (Client *)pclient;
char recvline[MAXLINE+1];
while (true)
{
// Recieves the request
switch(server_recvline(client, recvline, MAXLINE))
{
// error
case -1:
// Client disconnected
case -2:
return NULL;
break;
}
Msg_Type request = cstr_as_msg(recvline);
// Handles the request accordingly
printf("[LOG] (%s) messaged server: %s\n", client->name, recvline);
switch (request)
{
case ACTIVE_USERS:
server_send_response(client, ACTIVE_USERS);
list_send_client_names(client);
break;
case CLIENT_USERNAME_TAKEN:
server_send_response(client, CLIENT_USERNAME_TAKEN);
server_recvline(client, recvline, MAXWORD);
break;
case CLIENT_REGISTERED:
server_send_response(client, CLIENT_REGISTERED);
break;
case CLIENT_ADD_FRIEND:
server_send_response(client, CLIENT_ADD_FRIEND);
client_add_friend(client);
break;
case CLIENT_REMOVE_FRIEND:
server_send_response(client, CLIENT_REMOVE_FRIEND);
switch(client_remove_friend(client))
{
case 1:
server_send_response(client, FAILED);
break;
case 0:
server_send_response(client, SUCCESS);
break;
}
break;
case CLIENT_CHAT_SETUP:
switch (client_friend_chat_setup(client))
{
case -1:
server_send_response(client, CLIENT_PARTNER_NULL);
break;
case -2:
server_send_response(client, CLIENT_PARTNERS_PARTNER_NULL);
break;
case -3:
server_send_response(client, CLIENT_UNAVAILABLE);
break;
case -4:
server_send_response(client, FAILED);
break;
case -5:
server_send_response(client, CLIENT_NOT_FOUND);
break;
}
break;
case CLIENT_CHAT_START:
client_friend_chat_thread_create(client);
break;
case CLIENT_GROUP_ADD_MEMBER:
server_send_response(client, CLIENT_GROUP_ADD_MEMBER);
client_group_add_member(client);
break;
case CLIENT_GROUP_CHATROOM_SETUP:
client_group_setup(client);
break;
case CLIENT_GROUP_CHATROOM_START:
client_group_broadcast_thread_create(client);
break;
default:
fprintf(stderr, "[ERR] server_request: request is invalid\n");
break;
}
}
return NULL;
}
int server_sendline(Client *client, char buffer[], int limit)
{
if (buffer[0] == '\0')
{
fprintf(stderr, "[ERR] server_sendline: buffer empty\n") ;
return -2;
}
if (send(client->socket, buffer, limit, 0) < 0)
{
fprintf(stderr, "[ERR] server_sendline: error while sending\n");
server_remove_client(client);
return -1;
}
/*printf("\n---------------------\n");*/
/*printf("* send buffer: %s", buffer);*/
/*printf("\n---------------------\n");*/
return 0;
}
int server_recvline(Client *client, char buffer[], int limit)
{
int n;
memset(buffer, 0, limit);
if ((n = recv(client->socket, buffer, limit, 0)) < 0)
{
PERROR();
server_remove_client(client);
return -1;
}
else if (n == 0)
{
server_remove_client(client);
return -2;
}
/*printf("\n---------------------\n");*/
/*printf("* recv buffer: %s", buffer);*/
/*printf("\n---------------------\n");*/
return 0;
}
void server_send_response(Client *client, Msg_Type request)
{
char *str_msg = msg_as_cstr(request);
server_sendline(client, str_msg, MAXMSG);
printf("[LOG] server messaged %s : %s\n", client->name[0] == 0 ? "UNKOWN":client->name, str_msg);
}
Client * list_get_client_by_name(char *name, List *list)
{
Node *node = list->head;
pthread_rwlock_rdlock(&db.lock);
{
while (node)
{
if (strcmp(node->client->name, name) == 0)
{
pthread_rwlock_unlock(&db.lock);
return node->client;
}
node = node->next;
}
}
pthread_rwlock_unlock(&db.lock);
return NULL;
}
bool client_add_friend(Client *client)
{
char recvline[MAXLINE+1];
server_recvline(client, recvline, MAXWORD);
Client *other_client = list_get_client_by_name(recvline, &db);
if (other_client == NULL)
{
fprintf(stderr, "[ERR] client_add_friend: client choose invalid client\n");
server_send_response(client, CLIENT_NOT_FOUND);
return false;
}
else if (client == other_client)
{
fprintf(stderr, "[ERR] client_add_friend: client choose him/her self\n");
server_send_response(client, CLIENT_CHOOSE_ITSELF);
return false;
}
pthread_rwlock_wrlock(&db.lock);
{
if (ll_append(&client->friends_list, other_client))
client->friends_list.count++;
}
pthread_rwlock_unlock(&db.lock);
list_print(client, &client->friends_list);
server_send_response(client, CLIENT_PARTNER_SELECTED);
return true;
}
int client_friend_chat_setup(Client *client)
{
char recvline[MAXLINE+1];
Client *friend = NULL;
if (client->friends_list.head == NULL)
{
// If the client has not friend
fprintf(stderr, "[ERR] client_friend_chat_setup: clients friend list is empty\n");
return -1;
}
else if (client->friends_list.head != NULL && client->friends_list.head->next == NULL)
{
// If the client has only a single friend
friend = client->friends_list.head->client;
}
else if (client->friends_list.head != NULL)
{
// If the client has more than one friend
server_send_response(client, CLIENT_CHOOSE_FRIEND);
server_recvline(client, recvline, MAXWORD);
friend = list_get_client_by_name(recvline, &client->friends_list);
if (friend == NULL)
{
fprintf(stderr, "[ERR] client_friend_chat_setup: friend not found\n");
return -5;
}
if (friend->friends_list.head == NULL || friend->friends_list.tail == NULL)
{
fprintf(stderr, "[ERR] client_friend_chat_setup: friends friends list is empty\n");
return -2;
}
}
pthread_rwlock_wrlock(&db.lock);
{
// Checking whether the client is in "friend`s" friends list
if (list_is_client_in_list(client, &friend->friends_list) == false)
{
fprintf(stderr, "[LOG] client_friend_chat_setup: client not found in friend`s friends list\n");
pthread_rwlock_unlock(&db.lock);
return -2;
}
else if (friend->available == true)
{
// he/she is available and wants to talk to you
client->available = friend->available = false;
client->_friend = friend;
friend->_friend = client;
}
else if (friend->available == false)
{
fprintf(stderr, "[LOG] client_friend_chat_setup: client is busy\n");
pthread_rwlock_unlock(&db.lock);
return -3;
}
else
{
fprintf(stderr, "[LOG] client_friend_chat_setup: unkown error\n");
return -4;
}
}
pthread_rwlock_unlock(&db.lock);
server_send_response(client, CLIENT_CHAT_START);
server_send_response(friend, CLIENT_CHAT_START);
return 0;
}
int client_friend_chat_thread_create(Client *client)
{
pthread_t tid1;
if (pthread_create(&tid1, NULL, client_friend_chat_thread_handler, client) != 0)
{
fprintf(stderr, "[ERR] client_friend_chat_thread_handler: unable to create thread\n");
return errno;
}
if (pthread_join(tid1, NULL) != 0)
{
fprintf(stderr, "[ERR] client_friend_chat_thread_handler: unable to join client thread\n");
return errno;
}
return 0;
}
int client_group_broadcast_thread_create(Client *client)
{
pthread_t tid1;
if (pthread_create(&tid1, NULL, client_group_broadcast_thread_handler, client) != 0)
{
fprintf(stderr, "[ERR] client_group_broadcast_thread_handler: unable to create thread\n");
return errno;
}
if (pthread_join(tid1, NULL) != 0)
{
fprintf(stderr, "[ERR] client_group_broadcast_thread_handler: unable to join client thread\n");
return errno;
}
return 0;
}
void *client_group_broadcast_thread_handler(void *pclient)
{
char recvline[MAXLINE+1];
char sendline[MAXSND+1];
char mssg[MAXLINE+1];
int recv_output;
Client *client = (Client *)pclient;
Node *node = NULL;
snprintf(mssg, MAXLINE, "%s left\n", client->name);
printf("[LOG] %s initiated group chat\n", client->name);
client_group_create_member_threads(client);
while (client->available == false)
{
// Recieves text from the client
recv_output = recv(client->socket, recvline, MAXLINE, 0 );
if (recv_output == -1)
continue;
else if (recv_output == 0)
break;
// Users wants to quit
if (strcmp(recvline, "CLIENT_CHAT_QUIT") == 0)
break;
// Sends the text to every client members
snprintf(sendline, MAXSND, "%s: %s", client->name, recvline);
node = client->my_group.head;
while (node)
{
if (node->client->available == false)
continue;
if (send(node->client->socket, sendline, MAXLINE, 0) < 0)
{
pthread_rwlock_wrlock(&client->my_group.lock);
{
node->client->available = true;
server_sendline(node->client, mssg, MAXLINE);
server_send_response(client, CLIENT_GROUP_CHATROOM_CLOSE);
}
pthread_rwlock_unlock(&client->my_group.lock);
fprintf(stderr, "[ERR] client2 send error\n");
return NULL;
}
node = node->next;
}
}
return NULL;
}
void *client_friend_chat_thread_handler(void *pclient)
{
char recvline[MAXLINE+1];
char sendline[MAXSND+1];
char user_left_mssg[MAXLINE+1];
int recv_output;
Client *client = (Client *)pclient;
snprintf(user_left_mssg, MAXLINE, "%s left\n", client->name);
printf("[LOG] %s <-> %s chat initiated\n", client->name, client->_friend->name);
while (client->available == false)
{
// get the buffer from the client
recv_output = recv(client->socket, recvline, MAXLINE, 0 );
if(recv_output == -1)
continue;
else if (recv_output == 0)
break;
// if the client quits
if (strcmp(recvline, "CLIENT_CHAT_QUIT") == 0)
break;
snprintf(sendline, MAXSND, "%s: %s", client->name, recvline);
// send the buffer to the other client
if (send(client->_friend->socket, sendline, MAXLINE, 0) < 0)
{
fprintf(stderr, "[ERR] client2 send error\n");
break;
}
}
pthread_rwlock_wrlock(&client->friends_list.lock);
{
server_send_response(client, CLIENT_CHAT_CLOSED);
server_send_response(client->_friend, CLIENT_CHAT_CLOSED);
client->available = true;
client->_friend->available = true;
server_sendline(client->_friend, user_left_mssg, MAXLINE);
client->_friend->_friend = NULL;
client->_friend = NULL;
}
pthread_rwlock_unlock(&client->friends_list.lock);
return NULL;
}
void server_add_client(Client *client)
{
pthread_rwlock_wrlock(&db.lock);
{
ll_append(&db, client);
db.count++;
}
pthread_rwlock_unlock(&db.lock);
list_print(NULL, &db);
}
void server_remove_client(Client *client)
{
fprintf(stderr, "[LOG] Client (%s) disconnected\n", client->name);
close(client->socket);
pthread_rwlock_wrlock(&db.lock);
{
db.count--;
if (client->friends_list.head != NULL)
{
if (client->_friend != NULL) {
client->_friend->available = true;
if (client->_friend->_friend == NULL) {
;
}
else if (client->_friend->_friend == client) {
client->_friend->available = true;
client->_friend->_friend = NULL;
}
}
list_print(client, &client->friends_list);
}
if (client->my_group.head != NULL)
{
Node *memb = client->my_group.head;
while (memb)
{
ll_delete_node(&memb->client->groups_iam_in, client);
memb->client->groups_iam_in.count--;
memb = memb->next;
}
}
switch (ll_delete_node(&db, client))
{
case 0:
fprintf(stderr, "[LOG] ll_delete_node: element deleted\n");
break;
case 1:
fprintf(stderr, "[LOG] ll_delete_node: list empty\n");
break;
case 2:
fprintf(stderr, "[LOG] ll_delete_node: element not found\n");
break;
}
}
pthread_rwlock_unlock(&db.lock);
list_print(NULL, &db);
}
bool list_is_client_in_list(Client *client, List *list)
{
Node *node = list->head;
if (node == NULL)
return false;
if (list->head->client == client || list->tail->client == client)
return true;
while (node)
{
if (node->client == client)
return true;
node = node->next;
}
return false;
}
int client_remove_friend(Client *client)
{
char recvline[MAXLINE+1];
server_recvline(client, recvline, MAXLINE);
Client *friend_node = list_get_client_by_name(recvline, &client->friends_list);
if (friend_node == NULL)
return 1;
pthread_rwlock_wrlock(&db.lock);
{
if (ll_delete_node(&client->friends_list, friend_node))
{
client->friends_list.count++;
}
else
{
pthread_rwlock_unlock(&db.lock);
return 1;
}
}
pthread_rwlock_unlock(&db.lock);
list_print(client, &client->friends_list);
return 0;
}
int client_group_create_member_threads(Client *client)
{
Node *memb = client->my_group.head;
pthread_t tid[client->my_group.count];
if (memb == NULL)
{
fprintf(stderr, "client_group_create_member_threads: memb is null\n");
return errno;
}
for (int i = 0; memb != NULL; i++)
{
memb->client->available = false;
if (pthread_create(&tid[i], NULL, client_group_member_thread_handler, memb->client) != 0)
{
fprintf(stderr, "[ERR] client_group_create_member_threads: unable to create thread\n");
return errno;
}
memb = memb->next;
}
memb = client->my_group.head;
for (int i = 0; memb != NULL; i++)
{
pthread_join(tid[i], NULL);
memb = memb->next;
}
return 0;
}
void* client_group_member_thread_handler(void *pclient)
{
char recvline[MAXLINE+1];
char sendline[MAXSND+1];
char mssg[MAXLINE+1];
int recv_output;
Node *node = NULL;
Client *client = (Client *)pclient;
while (client->available == false)
{
// Recieves text from the client
recv_output = recv(client->socket, recvline, MAXLINE, 0 );
if (recv_output == -1)
continue;
else if (recv_output == 0)
break;
// Users wants to quit
if (strcmp(recvline, "CLIENT_CHAT_QUIT") == 0)
break;
// Sends the text to every client members
snprintf(sendline, MAXSND, "%s: %s", client->name, recvline);
node = client->groups_iam_in.head;
while (node)
{
if (node->client->available == false)
continue;
if (send(node->client->socket, sendline, MAXLINE, 0) < 0)
{
pthread_rwlock_wrlock(&client->my_group.lock);
{
node->client->available = true;
server_sendline(node->client, mssg, MAXLINE);
server_send_response(client, CLIENT_GROUP_CHATROOM_CLOSE);
}
pthread_rwlock_unlock(&client->my_group.lock);
fprintf(stderr, "[ERR] client2 send error\n");
return NULL;
}
node = node->next;
}
}
return NULL;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
#include "gpio.h"
#include "button.h"
#define NUM_OF_BUTTONS_LIMIT 9 // This is a hack - get this from GPIO?
typedef struct _m_tsData
{
bool bPressed;
uint8_t u8Handle;
void (*pvCallback)(void);
} m_tsData;
static m_tsData m_sData[NUM_OF_BUTTONS_LIMIT];
static uint8_t m_u8NumberOfButtons = 0;
bool BUTTON_bInit(void* pvPressedCallback)
{
bool bResult = false;
if (m_u8NumberOfButtons < NUM_OF_BUTTONS_LIMIT)
{
if (GPIO_bRegisterInputPin(&m_sData[m_u8NumberOfButtons].u8Handle))
{
bResult = true;
m_sData[m_u8NumberOfButtons].pvCallback = pvPressedCallback;
m_u8NumberOfButtons++;
}
}
return bResult;
}
void BUTTON_vPoll(void)
{
uint8_t u8Index = 0;
bool bPreviouslyPressed;
for (u8Index = 0; u8Index < m_u8NumberOfButtons; u8Index++)
{
bPreviouslyPressed = m_sData[u8Index].bPressed;
m_sData[u8Index].bPressed = GPIO_bGetInputPinState(m_sData[u8Index].u8Handle);
if (!bPreviouslyPressed && m_sData[u8Index].bPressed)
{
m_sData[u8Index].pvCallback();
}
}
}
|
C
|
#include "hashtable.h"
#include <stdlib.h>
#include <assert.h>
/*
A very simple hash function
*/
int ht_hash(hashtable ht, int id) {
return id % ht->num_buckets;
}
hashtable ht_create(int size_hint)
{
int num_buckets = size_hint;
hashtable ht = (hashtable) malloc(sizeof(ht_table_instance));
assert(ht);
ht->num_buckets = num_buckets;
ht->buckets = (ht_node **) malloc(sizeof(ht_node *) * ht->num_buckets);
assert(ht->buckets);
/* Initialize linked lists to NULL */
for(int i=0; i < ht->num_buckets; i++) {
ht->buckets[i] = NULL;
}
return ht;
}
void ht_insert(hashtable ht, student_info item) {
// what index in the table does it hash to?
int index = ht_hash(ht, item.id);
// empty position
if ( ! ht->buckets[index] ) {
// empty list, just place it there */
ht_node *n = (ht_node *) malloc(sizeof(ht_node));
assert(n);
n->item = item;
n->next = 0;
ht->buckets[index] = n;
return;
}
// collision, insert into the list if not already there
ht_node *cur = ht->buckets[index];
while (cur) {
if ( (cur->item).id == item.id ) {
// already in table, replace it
cur->item = item;
cur = 0;
} else if ( cur->next ) {
// no match, but more to look at, move on
cur = cur->next;
} else {
// no match, at end of list, insert at end
ht_node *n = (ht_node *) malloc(sizeof(ht_node));
assert(n);
cur->next = n;
n->item = item;
n->next = 0;
cur = 0;
}
}
}
int ht_lookup(hashtable ht, int id, student_info *itemp) {
int index = ht_hash(ht, id);
if ( ! ht->buckets[index] ) {
// empty list, not present
return 0;
}
// walk along collision list looking for matching id
ht_node *cur = ht->buckets[index];
while (cur) {
if ( (cur->item).id == id ) {
// found it, return the item and success
*itemp = cur->item;
return 1;
}
// no match, more to look at, move on
cur = cur->next;
}
// could not find it
return 0;
}
void ht_destroy(hashtable ht) {
// free up each bucket
ht_node *cur;
ht_node *next;
for(int i=0; i < ht->num_buckets; i++) {
// star at the head
cur = ht->buckets[i];
while (cur) {
// remember the next node in the list
next = cur->next;
free(cur);
// move to next
cur = next;
}
}
// now clean up the topmost structures
free(ht->buckets);
free(ht);
}
/*
Delete the student info item that matches the given id.
If missing, don't do anything.
*/
void ht_delete(hashtable ht, int id) {
int index = ht_hash(ht, id);
if ( ! ht->buckets[index] ) {
// empty list, not present
return;
}
// check head first looking for matching id
ht_node *cur = ht->buckets[index];
if ( (cur->item).id == id ) {
ht_node *next = cur->next;
ht->buckets[index] = next;
free(cur);
} else {
ht_node *previous = cur;
cur = cur->next;
// walk along collision list looking for matching id
while (cur) {
if ( (cur->item).id == id ) {
previous->next = cur->next;
free(cur);
break;
}
// no match, more to look at, move on
previous = cur;
cur = cur->next;
}
}
}
|
C
|
#include<stdio.h>
int N1,res;
char S;
int main()
{//inico
do{
printf("Programa que te dice si el numero es par o impar\n\n ");
printf("Ingrese su numero:");
scanf("%d",&N1);
res=N1 % 2;
if(res==0)
{
printf("Felicidades es un numero par\n\n");
}
else
{
printf("Felicidades es un numero impar\n\n");
}
do{
printf("Deseas continuar?[s/n]:\n");
fflush(stdin);
scanf("%c",&S);
printf("\n\n");
} while (S=='\n');
} while(S=='s');
printf("Grasias por usar el programa");
}//fin
|
C
|
// Done by - Akhil Raymond George
/*
BANKING SYSTEM PROGRAM WITH PERSISTENCE
BINARY FILE - data.dat used to store user informations
[Program uses structure, functions,file handling]
ADMIN password 123
*/
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>
// Account details structure
struct account_details{
char name[25];
char gender;
char ac_no[15];
char password[10];
float balance;
};
struct account_details s; // Global variable of struct declared
FILE *f; // Global pointer declared for file handling
void display(struct account_details x);
void view_file();
void update_file(struct account_details tmp);
void add_file(struct account_details x);
int login_verification(char ac[15],char pass[10]);
int AC_verification(char ac[15]);
void login_user();
void user_interface();
void withdraw();
void deposit();
void transfer(struct account_details tmp);
void balance_enq(struct account_details tmp);
void create_user();
void admin_interface();
void main_window();
// Function to display the structure
void display(struct account_details x){
printf("\n A/C no: %s",x.ac_no);
printf("\n Name: %s",x.name);
printf("\n Gender: %c",x.gender);
printf("\n Balance: %.2f",x.balance);
}
// View contents of file
void view_file(){
struct account_details x;
f=fopen("data.dat","rb+");
while(fread(&x,sizeof(x),1,f)){
display(x);
printf("\n");
}
}
// Update file with the changed value
void update_file(struct account_details tmp){
struct account_details x;
f=fopen("data.dat","rb+");
while(fread(&x,sizeof(x),1,f)){
if(strcmp(tmp.ac_no,x.ac_no)==0){
fseek(f,ftell(f)-sizeof(s),SEEK_SET);
fwrite(&tmp,sizeof(x),1,f);
break;
}
}
fclose(f);
}
// Appends new user at end of file
void add_file(struct account_details x){
f=fopen("data.dat","ab+");
fwrite(&x,sizeof(x),1,f);
fclose(f);
}
// Login verification checks entered values with values stored in file
int login_verification(char ac[15],char pass[10]){
f=fopen("data.dat","rb+");
while(fread(&s,sizeof(s),1,f)){
if(strcmp(s.ac_no,ac)==0){
if(strcmp(s.password,pass)==0){
return(0);
}
}
}
return(1);
}
// Verifies if A/C no already present in file or not
int AC_verification(char ac[15]){
struct account_details x;
f=fopen("data.dat","rb+");
while(fread(&x,sizeof(x),1,f)){
if(strcmp(x.ac_no,ac)==0){
return(0);
}
}
return(1);
}
// Login interface
void login_user(){
system("cls");
char ac[15];
char pass[10];
int res;
printf("\n ##################################");
printf("\n LOGIN ");
printf("\n ##################################\n");
printf("\n A/C number: ");
gets(ac);
printf("\n Password: ");
gets(pass);
res = login_verification(ac,pass);
if(res==0){
user_interface();
}
else{
printf("\n WRONG CREDENTIALS, TRY AGAIN");
getch();
login_user();
}
}
// Logged in User interface
void user_interface(){
system("cls");
int ch;
printf("\n ##################################");
printf("\n LOGGED IN TO A/C NO: %s",s.ac_no);
printf("\n ##################################");
printf("\n SERVICES");
printf("\n ##################################\n");
printf("\n 1. Withdraw");
printf("\n 2. Deposit");
printf("\n 3. Balance enquiry");
printf("\n 4. Transfer amount");
printf("\n 5. Logout");
printf("\n ENTER CHOICE: ");
scanf("%d",&ch);
switch (ch){
case 1: getchar();
withdraw();
break;
case 2: getchar();
deposit();
break;
case 3: getchar();
balance_enq(s);
break;
case 4: getchar();
transfer(s);
break;
case 5: main_window();
break;
default: printf("\n Wrong choice");
getch();
user_interface();
}
}
// Withdrawal function
void withdraw(){
system("cls");
float amt;
printf("\n ##################################");
printf("\n WITHDRAWAL ");
printf("\n ##################################\n");
printf("\n A/C No: %s",s.ac_no);
printf("\n ENTER AMOUNT TO WITHDRAWN: ");
scanf("%f",&amt);
if(amt<s.balance-1000){
s.balance-=amt;
update_file(s);
printf("\n Updated balance: %.2f",s.balance);
getch();
}
else{
printf("\n Min balance not maintained");
getch();
}
user_interface();
}
// Deposit function
void deposit(){
system("cls");
float amt;
printf("\n ##################################");
printf("\n DEPOSIT ");
printf("\n ##################################\n");
printf("\n A/C No: %s",s.ac_no);
printf("\n ENTER AMOUNT TO DEPOSIT: ");
scanf("%f",&amt);
s.balance+=amt;
update_file(s);
printf("\n Updated balance: %.2f",s.balance);
getch();
user_interface();
}
// Transfer amount from one account to another within the file
void transfer(struct account_details tmp){
int res,amt;
char ac[15];
system("cls");
printf("\n ##################################");
printf("\n ACCOUNT TRANSFER ");
printf("\n ##################################\n");
printf("\n Enter A/C to transfer amount: ");
scanf("%s",&ac);
res=AC_verification(ac);
if(res==0){
printf("\n Enter amount to tranfer: ");
scanf("%d",&amt);
if(amt<tmp.balance-100){
tmp.balance-=amt;
update_file(tmp);
s=tmp;
f=fopen("data.dat","rb+");
while(fread(&tmp,sizeof(tmp),1,f)){
if(strcmp(ac,tmp.ac_no)==0){
break;
}
}
tmp.balance+=amt;
update_file(tmp);
printf("\n Amount Transferred.");
getch();
user_interface();
}
else{
printf("\n Min Balance not maintained. Please try again");
getch();
user_interface();
}
}
else{
printf("\n A/C no: Entered not valid. Please try again");
getch();
user_interface();
}
}
// Displays A/C Details
void balance_enq(struct account_details tmp){
system("cls");
printf("\n ##################################");
printf("\n ACCOUNT DETAILS ");
printf("\n ##################################\n");
display(tmp);
getch();
user_interface();
}
// Creates new user
void create_user(){
system("cls");
int res;
float bal;
printf("\n ##################################");
printf("\n NEW USER ");
printf("\n ##################################\n");
printf("\n A/C No: ");
gets(s.ac_no);
res=AC_verification(s.ac_no);
if(res==0){
printf("\n User already exists. Please Try again");
getch();
main_window();
}
printf("\n Enter name: ");
gets(s.name);
printf("\n Gender(M/F): ");
scanf("%c",&s.gender);
getchar();
printf("\n Enter password: ");
gets(s.password);
bal_rep:
printf("\n Enter deposit amount (min balance-RS.1000)");
scanf("%f",&bal);
if(bal<1000){
printf(" Min balance not satisfied");
goto bal_rep;
}
s.balance=bal;
add_file(s);
printf("\n ##################################");
printf("\n USER ADDED SUCCESSFULLY");
printf("\n ##################################\n");
getch();
main_window();
}
// Admin interface to view file contents
void admin_interface(){
system("cls");
char pass[10];
printf("\n ##################################");
printf("\n ADMIN LOGIN");
printf("\n ##################################\n");
printf("\n Password: ");
scanf("%s",&pass);
if(strcmp(pass,"123")==0){
system("cls");
printf("\n ##################################");
printf("\n FILE CONTENTS (data.dat)");
printf("\n ##################################\n");
view_file();
getch();
main_window();
}
else{
printf("\n Wrong admin password");
getch();
main_window();
}
}
// Main window
void main_window(){
system("cls");
int ch;
printf("\n ##################################");
printf("\n CITY BANK");
printf("\n ##################################\n");
printf("\n 1. LOGIN");
printf("\n 2. CREATE NEW USER");
printf("\n 3. ADMIN LOGIN");
printf("\n 4. EXIT");
printf("\n ENTER CHOICE: ");
scanf("%d",&ch);
switch (ch){
case 1: getchar();
login_user();
break;
case 2: getchar();
create_user();
break;
case 3: getchar();
admin_interface();
break;
case 4: exit(0);
break;
default: printf("\n Wrong choice");
getch();
main_window();
}
}
void main(){
main_window();
}
|
C
|
/* Copyrighted Pixar 1989 */
/* From the RenderMan Companion p. 25 */
/* NOTE: The main() function has been removed and moved to colormain.c */
/* Listing 2.3 Control over viewer and color */
#include <ri.h>
#include <stdio.h>
#define L -.5 /* For x: left side */
#define R .5 /* For x: right side */
#define D -.5 /* For y: down side */
#define U .5 /* For y: upper side */
#define F .5 /* For z: far side */
#define N -.5 /* For z: near side */
/* UnitCube(): define a cube in the graphics environment */
UnitCube()
{
static RtPoint Cube[6][4] = {
{ {L,D,F}, {L,D,N}, {R,D,N}, {R,D,F} }, /* Bottom face */
{ {L,D,F}, {L,U,F}, {L,U,N}, {L,D,N} }, /* Left face */
{ {R,U,N}, {L,U,N}, {L,U,F}, {R,U,F} }, /* Top face */
{ {R,U,N}, {R,U,F}, {R,D,F}, {R,D,N} }, /* Right face */
{ {R,D,F}, {R,U,F}, {L,U,F}, {L,D,F} }, /* Far face */
{ {L,U,N}, {R,U,N}, {R,D,N}, {L,D,N} } /* Near face */
};
int i;
for( i = 0; i < 6; i++) /* Declare the cube */
RiPolygon( (RtInt) 4, RI_P, (RtPointer) Cube[i], RI_NULL);
}
|
C
|
/*
This example code is in the Public Domain (or CC0 licensed, at your option.)
Unless required by applicable law or agreed to in writing, this
software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied.
*/
#pragma once
#include <sdkconfig.h>
#include <esp_err.h>
#define MAX_DEV CONFIG_BT_NIMBLE_MAX_CONNECTIONS
#define SCAN_DURATION_MS (30 * 1000)
#define RESCAN_DURATION_MS (5 * 1000)
typedef esp_err_t (*add_func_t)(void);
typedef struct ble_dev *ble_dev_handle_t;
typedef struct {
/* Name seen in BLE advertisement data */
const char *adv_name;
/* 16-bit BLE Characteristic UUID of the parameter to be controlled */
uint16_t chr_uuid;
/* 16-bit BLE Service UUID of the characteristic */
uint16_t svc_uuid;
/* Function to add device and its parameters to RainMaker */
add_func_t add;
} ble_cfg_t;
/**
* Start BLE framework
*
* This API will start BLE central role and return after scanning for 30 seconds.
* The interval can be changed by configuring SCAN_DURATION_MS. During this time,
* it will find all the registered BLE devices of which are discoverable and add them
* to the RainMaker framework (maximum upto MAX_DEV)
*
* @note This API should be called after esp_rmaker_init() but before esp_rmaker_start()
*/
void app_ble_start(void);
/**
* Create and add RainMaker a device and its parameters for the corresponding BLE device
*
* This API will add a RainMaker device and its parameters as per the functionality
* exposed by the BLE device.
*
* @param[in] cfg BLE configuration of type ble_cfg_t
*
* @return BLE device handle if the device is added successfully.
* @return NULL in case of failures.
*/
ble_dev_handle_t app_ble_add_dev(ble_cfg_t *cfg);
/**
* Update the BLE device parameter
*
* This API will update (write) the parameter (characteristic) value over BLE
*
* @param[in] dev BLE device handle returned from app_ble_add_dev()
* @param[in] data Data to be written
* @param[in] len Length of the data
*
* @return ESP_OK if successful.
* @return error in case of failures.
*
* @note The call to this API should be preceded by mapping the data received from
* RainMaker cloud to the format accepted by the BLE device.
*/
esp_err_t app_ble_update_dev(ble_dev_handle_t dev, uint8_t *data, int len);
|
C
|
/*
* CSI030-2018-01 - Programao de Computadores I
* Nome: Renan Saldanha Linhares
* Matricula: 18.1.5908
* Curso: Engenharia de Computao
* Exercico: Atividade prtica 1, exercicio 03
*/
/* Bibilotecas*/
#include <stdio.h>
#include <locale.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <float.h>
/* O programa gera "n" pares de nmeros inteiros, e para
cada par de nmeros calcular a Funo de Rosenbrock, ao final
ir informa qual a menor constante e qual a maior constante,
a soma e a mdia dos valores calculados*/
int main()
{
setlocale(LC_ALL, "");
srand(time(NULL));
/*declarao de variveis e atribuio de valores*/
int x, y, n, aux;
long int f, maior, menor;
double media, soma, controle;
aux = soma = 0;
controle = DBL_MAX;
printf ("Informe o nmero de pares nmericos a serem gerados: ");
scanf ("%d", &n);
while (aux < n){
/*Estrutura para escolha de x e y aletoriamente*/
x = (rand () % 11 + 5);
y = (rand () % 11 + 5);
f = ((pow((1 - x), 2)) + (100 * (pow((y - (pow(x,2))), 2))));
printf ("F(%d, %d) = %ld\n", x, y, f);
/*Estrutura para descobrir maior e menor valor de f(x,y)*/
if (aux == 0){
menor = maior = f;
}
else if (f > maior){
maior = f;
}
else if (f < menor){
menor = f;
}
soma = (soma + f);
aux++;
}
/*Estrutura para o caso do valor da soma ser maior que o valor suportado pela varivel*/
if (soma > controle){
printf("\7ERRO: Impossvel calcular a soma e a mdia das funes (valor maior que o mximo suportado)\nPorm o maior valor de f(x, y) : %ld;\nO menor valor de f(x, y) : %ld", maior, menor);
}
else{
media = (soma / aux);
printf ("O maior valor de f(x, y) : %ld;\nO menor valor de f(x, y) : %ld;\nA soma de f(x, y) : %.2lf;\nA mdia de f(x, y) : %.2lf.", maior, menor, soma, media);
}
return 0;
}
|
C
|
#include<stdio.h>
#include<math.h>
int main()
{
int num,i;
i=1;
printf("Enter any Number:");
scanf("%d", &num);
printf("Multiplication table of %d= ", num);
while(i <= 10)
{
printf(" %d x %d = %d", num, i, num * i);
i++;
}
return 0;
}
|
C
|
#include <sys/time.h>
int main(){
struct timeval tv;
struct timezone tz;
gettimeofday(&tv, &tz);
printf("%d, %d\n",tv.tv_sec, tv.tv_usec);
}
|
C
|
/*
Author Name :-Shashank Pandora
Organisation :-Emertxe Information Technologies (p) Ltd.
Date :-8 Mar 2020
Description :-Write a program to generate fibbonacci numbers.
Input :-A positive integer say 'N'.
*/
#include<stdio.h>
int main()
{
char c;
do
{
int num, first=0, sec=1, sum, i, sub;
printf("Enter a number: ");
scanf("%d", &num);
printf("fabonicci series for %d is: \n", num);
if(num == 0)
{
printf("%d\n",first);
}
else if (num > 0)
{
printf("%d\n%d\n", first, sec);
sum = first + sec;
while(sum <= num) //loop until sum <= num
{
printf("%d\n", sum); //printing the sum
first = sec; //value of sec is now stored in first
sec = sum; //vlaue of sum is now in sec
sum = first + sec;
}
}
else //for negative number
{
printf("%d\n%d\n",first,sec);
sub = first - sec;
while(-sub >= num && -sub <= -num) //to set range from -ve to +ve value
{
printf("%d\n", sub);
first = sec;
sec = sub;
sub = first - sec;
}
}
printf("Do you want to continue (y/n): ");
scanf("\n%c", &c);
}
while( c == 'y' ); //to re-run the program if user enter y. do while body ending
return 0;
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
int main(){
int s = socket(AF_INET, SOCK_STREAM, 0);
if(s == -1){
perror("socket failed");
exit(2);
}
struct sockaddr_in addr = {
.sin_addr.s_addr = INADDR_ANY,
.sin_family = AF_INET,
.sin_port = htons(4444)
};
if(bind(s, (struct sockaddr*)&addr, sizeof(struct sockaddr_in))) {
perror("bind failed");
exit(2);
}
if(listen(s, 2)) {
perror("listen failed");
exit(2);
}
struct sockaddr_in client_addr;
socklen_t client_addr_length = sizeof(struct sockaddr_in);
int client_socket = accept(s, (struct sockaddr*)&client_addr, &client_addr_length);
if(client_socket == -1) {
perror("accept failed");
exit(2);
}
char* msg = "Hello client.\n";
write(client_socket, msg, strlen(msg));
close(client_socket);
close(s);
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
struct Node {
int data;
struct Node * next;
};
void printNode(struct Node *a){
while( a != NULL)
{
printf("Elements in Nodes are %d \n", a->data);
a = a->next;
}
}
struct Node * GetnewNode(int data){
struct Node * newNode= (struct Node *)malloc (sizeof(struct Node));
newNode->data =data;
newNode->next = NULL;
return newNode;
}
struct Node* head;
void InsertioninLL(int data){
struct Node * newNode = GetnewNode(data);
// if(head == NULL){
// head= newNode;
// return;
// }
newNode->next = head;
head = newNode;
}
int main(){
//allocate through heap
InsertioninLL(33);
InsertioninLL(66);
InsertioninLL(99);
InsertioninLL(22);
printNode(head);
}
|
C
|
/* pf.c */
/* Add by Wuxf 20181202 First version */
#include "pf.h"
#include "array.h"
#include <semaphore.h>
#define MAX_CV_NUM 20
#define MAX_MUTE_NUM 40
#define MAX_SEMA_NUM 20
typedef struct condition_info{
UINT32 state;
pthread_cond_t c;
pthread_mutex_t *m;
}CV_INFO;
typedef struct mute_info{
UINT32 state;
pthread_mutex_t m;
}MUTE_INFO;
typedef struct sema_info{
UINT32 state;
sem_t sem;
}SEMA_INFO;
CV_INFO cv_array[MAX_CV_NUM];
MUTE_INFO mute_arrary[MAX_MUTE_NUM];
SEMA_INFO sema_arrary[MAX_SEMA_NUM];
pthread_condattr_t cvattr;
pthread_mutexattr_t mxattr;
pthread_attr_t thread_attr;
INT32 linux_pt_init(VOID)
{
INT32 ret;
memset(cv_array, 0 , sizeof(cv_array));
memset(mute_arrary, 0, sizeof(mute_arrary));
memset(sema_arrary, 0, sizeof(sema_arrary));
if (pthread_condattr_init(&cvattr) != 0)
{
return (ERROR);
}
/* TODO: check the parameter "CLOCK_MONOTONIC " */
if (pthread_condattr_setclock(&cvattr, CLOCK_MONOTONIC) != 0) {
return (ERROR);
}
if (pthread_mutexattr_init(&mxattr) != 0) {
pthread_condattr_destroy(&cvattr);
return (ERROR);
}
// if this one fails we don't care.
(void) pthread_mutexattr_settype(
&mxattr, PTHREAD_MUTEX_ERRORCHECK);
ret = pthread_attr_init(&thread_attr);
if(ret < 0){
pthread_condattr_destroy(&cvattr);
return ERROR;
}
ret = pthread_attr_setdetachstate(&thread_attr, \
PTHREAD_CREATE_DETACHED);
if(ret < 0){
pthread_condattr_destroy(&cvattr);
return ERROR;
}
return 0;
}
INT32 linux_alloc(INT32 size, VOID **ptr, INT32 option)
{
(VOID)option;
*ptr = malloc(size);
if(!(*ptr))
return ERROR;
return OK;
}
VOID linux_free(VOID * ptr)
{
free(ptr);
}
INT32 linux_pthread_cond_wait(INT32 idx)
{
int rv;
if((idx < 0)||(idx >= MAX_CV_NUM))
return PLATFORM_LAYER_INVALIDE_CV_IDX;
if(STATE_VALIDE != cv_array[idx].state)
{
return PLATFORM_LAYER_CV_NOT_EXIST;
}
pthread_cond_t *c = &cv_array[idx].c;
pthread_mutex_t *m = cv_array[idx].m;
if ((rv = pthread_cond_wait(c, m)) != 0) {
return ERROR;
}
return OK;
}
INT32 linux_pthread_cond_wake(INT32 idx){
INT32 rv;
if((idx < 0)||(idx >= MAX_CV_NUM))
return PLATFORM_LAYER_INVALIDE_CV_IDX;
if(STATE_VALIDE != cv_array[idx].state)
{
return PLATFORM_LAYER_CV_NOT_EXIST;
}
pthread_cond_t *c = &cv_array[idx].c;
if ((rv = pthread_cond_broadcast(c)) != 0) {
return ERROR;
}
return OK;
}
pttime linux_get_cur_clock(VOID)
{
struct timespec ts;
pttime msec;
if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) {
return ERROR;
}
msec = ts.tv_sec;
msec *= 1000;
msec += (ts.tv_nsec / 1000000);
return (msec);
}
int linux_get_pid(void)
{
return getpid();
}
unsigned long linux_get_pthread(VOID){
return pthread_self();
}
INT32 linux_cv_until(INT32 idx, pttime until)
{
struct timespec ts;
INT32 rv;
if((idx < 0)||(idx >= MAX_CV_NUM))
return PLATFORM_LAYER_INVALIDE_CV_IDX;
if(STATE_VALIDE != cv_array[idx].state)
{
return PLATFORM_LAYER_CV_NOT_EXIST;
}
pthread_cond_t *c = &cv_array[idx].c;
pthread_mutex_t *m = cv_array[idx].m;
// Our caller has already guaranteed a sane value for until.
ts.tv_sec = until / 1000;
ts.tv_nsec = (until % 1000) * 1000000;
switch ((rv = pthread_cond_timedwait(c, m, &ts)))
{
case 0:
return (0);
case ETIMEDOUT:
case EAGAIN:
return (LLATFORM_LAYER_TIME_OUT);
}
return (ERROR);
}
INT32 linux_cv_init(INT32* idx, INT32 mute_idx)
{
int cv_idx;
cv_idx = find_array_free((UINT8 *)cv_array, MAX_CV_NUM, sizeof(CV_INFO));
if(cv_idx == ERROR)
return ERROR;
if((mute_idx < 0)||(mute_idx >= MAX_MUTE_NUM))
return PLATFORM_LAYER_INVALIDE_MUTE_IDX;
if(STATE_VALIDE != mute_arrary[mute_idx].state)
{
return PLATFORM_LAYER_MUTE_NOT_EXIST;
}
while (pthread_cond_init(&cv_array[cv_idx].c, &cvattr) != 0)
{
usleep(10000);
}
cv_array[cv_idx].m = &mute_arrary[mute_idx].m;
cv_array[cv_idx].state = STATE_VALIDE;
*idx = cv_idx;
return OK;
}
INT32 linux_mute_init(INT32 * idx, INT32 option)
{
int mute_idx;
(VOID)option;
mute_idx = find_array_free((UINT8 *)mute_arrary, \
MAX_MUTE_NUM, sizeof(MUTE_INFO));
if(mute_idx < 0){
*idx = mute_idx;
return ERROR;
}
while ((pthread_mutex_init(&mute_arrary[mute_idx].m, &mxattr) != 0) &&
(pthread_mutex_init(&mute_arrary[mute_idx].m, NULL) != 0)) {
usleep(10000);
}
mute_arrary[mute_idx].state = STATE_VALIDE;
*idx = mute_idx;
return OK;
}
INT32 linux_mute_lock(INT32 idx)
{
INT32 rv;
if((idx < 0)||(idx >= MAX_MUTE_NUM))
return PLATFORM_LAYER_INVALIDE_MUTE_IDX;
if(STATE_VALIDE != mute_arrary[idx].state)
{
return PLATFORM_LAYER_MUTE_NOT_EXIST;
}
if ((rv = pthread_mutex_lock(&mute_arrary[idx].m)) != 0)
{
return ERROR;
}
return OK;
}
INT32 linux_mute_unlock(INT32 idx)
{
INT32 rv;
if((idx < 0)||(idx >= MAX_MUTE_NUM))
return PLATFORM_LAYER_INVALIDE_MUTE_IDX;
if(STATE_VALIDE != mute_arrary[idx].state)
{
return PLATFORM_LAYER_MUTE_NOT_EXIST;
}
if((rv = pthread_mutex_unlock(&mute_arrary[idx].m)) != 0)
{
return ERROR;
}
return OK;
}
INT32 linux_mute_close(INT32 idx)
{
if((idx < 0)||(idx >= MAX_MUTE_NUM))
return PLATFORM_LAYER_INVALIDE_MUTE_IDX;
if(STATE_VALIDE != mute_arrary[idx].state)
{
return PLATFORM_LAYER_MUTE_NOT_EXIST;
}
(void) pthread_mutex_destroy(&mute_arrary[idx].m);
mute_arrary[idx].state = OK;
return OK;
}
INT32 linux_mute_try_lock(INT32 idx)
{
INT32 rv;
if((idx < 0)||(idx >= MAX_MUTE_NUM))
return PLATFORM_LAYER_INVALIDE_MUTE_IDX;
if(STATE_VALIDE != mute_arrary[idx].state)
{
return PLATFORM_LAYER_MUTE_NOT_EXIST;
}
if ((rv = pthread_mutex_trylock(&mute_arrary[idx].m)) != 0)
{
return ERROR;
}
return OK;
}
INT32 linux_create_thread(ULONG * id, UINT32 option,
VOID *(*routine) (VOID *),
VOID * arg)
{
INT32 ret;
(void)option;
ret = pthread_create(id,&thread_attr,routine,arg);
if(ret)
return ret;
return OK;
}
VOID linux_sleep(INT32 ms)
{
usleep(ms*1000);
}
INT32 linux_sema_init(INT32 value)
{
INT32 ret;
INT32 sema_idx;
sema_idx = find_array_free((UINT8 *)sema_arrary, \
MAX_MUTE_NUM, sizeof(SEMA_INFO));
if(sema_idx == ERROR)
return PLATFORM_LAYER_SEMA_FULL;
ret = sem_init(&sema_arrary[sema_idx].sem, 0, value);
if(ret < 0){
sema_arrary[sema_idx].state = 0;
return ERROR;
}
sema_arrary[sema_idx].state = STATE_VALIDE;
return sema_idx;
}
INT32 linux_sema_close(INT32 idx)
{
if((idx < 0)||(idx >= MAX_SEMA_NUM))
return PLATFORM_LAYER_INVALID_PARA;
if(STATE_VALIDE != sema_arrary[idx].state)
{
return PLATFORM_LAYER_INVALID_PARA;
}
(void)sem_destroy(&sema_arrary[idx].sem);
sema_arrary[idx].state = OK;
return OK;
}
INT32 linux_sema_wait(INT32 idx)
{
INT32 rc;
if((idx < 0)||(idx >= MAX_SEMA_NUM))
return PLATFORM_LAYER_INVALID_PARA;
if(STATE_VALIDE != sema_arrary[idx].state)
{
return PLATFORM_LAYER_INVALID_PARA;
}
do {
rc = sem_wait(&sema_arrary[idx].sem);
} while (rc < 0 && errno == EINTR);
if (rc < 0) {
return ERROR;
}
return OK;
}
INT32 linux_sema_post(INT32 idx)
{
INT32 rc;
if((idx < 0)||(idx >= MAX_SEMA_NUM))
return PLATFORM_LAYER_INVALID_PARA;
if(STATE_VALIDE != sema_arrary[idx].state)
{
return PLATFORM_LAYER_INVALID_PARA;
}
rc = sem_post(&sema_arrary[idx].sem);
if (rc < 0) {
return ERROR;
}
return OK;
}
INT32 linux_socket(INT32 type)
{
INT32 ret;
ret = socket(PF_INET, type, 0);
if (ret >= 0) {
return ERROR;
}
return ret;
}
void linux_socket_set_nonblock(INT32 fd)
{
INT32 f;
f = fcntl(fd, F_GETFL);
fcntl(fd, F_SETFL, f | O_NONBLOCK);
}
/* Rebind ip */
INT32 linux_socket_set_fast_reuse(INT32 fd)
{
INT32 val = 1, ret;
ret = setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
(const INT8 *)&val, sizeof(val));
return ret;
}
/* no nagle */
INT32 linux_socket_set_nodelay(INT32 fd)
{
INT32 value = 1;
return setsockopt(fd, SOL_SOCKET, TCP_NODELAY, &value, sizeof(value));
}
/* out of buffer in line */
INT32 linux_socket_set_oobinline(INT32 fd)
{
INT32 value = 1;
return setsockopt(fd, SOL_SOCKET, SO_OOBINLINE, &value, sizeof(value));
}
INT32 linux_socket_open(INT32 option, UINT8 ip[4], INT32 port, INT32 protocol)
{
INT32 ret;
INT32 fd;
INT32 proto;
UINT16 tmport;
UINT32 tmpip;
(void)option;
tmport = (UINT16)port;
tmpip = *((INT32 *)ip);
struct sockaddr_in addr;
if(protocol == TRANSPORT_TYPE_UDP)
{
proto = SOCK_DGRAM;
}
else if(protocol == TRANSPORT_TYPE_TCP)
{
proto = SOCK_STREAM;
}
else
{
return PLATFORM_LAYER_INVALID_PARA;
}
fd = linux_socket(proto);
if(fd < 0)
return ERROR;
ret = linux_socket_set_fast_reuse(fd);
if(ret < 0){
close(fd);
return ERROR;
}
memset(&addr,0,sizeof(struct sockaddr_in));
addr.sin_family = AF_INET;
addr.sin_port = htons(tmport);
addr.sin_addr.s_addr = htonl(tmpip);
ret = bind(fd,(struct sockaddr *)&addr, sizeof(addr));
if (ret < 0) {
close(fd);
return ERROR;
}
linux_socket_set_nonblock(fd);
if(protocol == TRANSPORT_TYPE_TCP)
linux_socket_set_nodelay(fd);
return fd;
}
#define METHOD_ONE
INT32 linux_socket_send(UINT8 *buf, INT32 len, INT32 option, INT32 socket)
{
#ifdef METHOD_ONE
INT32 ret;
INT32 err;
for(;;)
{
ret = send(socket,buf,len,option);
if(ret < 0)
{
err = errno;
if((err == EINTR))
{
continue;
}
else if((err == EWOULDBLOCK) || (err == EAGAIN))
{
/* no buffer, just wait */
usleep(1000);
continue;
}
else
{
return ERROR;
}
}
else
{
return ret;
}
}
#else
return send(socket,buf,len,option);
#endif
}
INT32 linux_socket_recv(UINT8 *buf, INT32 len, INT32 option, INT32 socket)
{
#ifdef METHOD_ONE
INT32 ret;
INT32 err;
for(;;)
{
ret = recv(socket,buf,len,option);
if(ret < 0)
{
err = errno;
if((err == EINTR))
{
continue;
}
else if((err == EWOULDBLOCK) || (err == EAGAIN))
{
/* no data */
return OK;
}
else
{
return ERROR;
}
}
else
{
return ret;
}
}
#else
return recv(socket,buf,len,option);
#endif
}
INT32 linux_socket_sendto(UINT8 *buf, INT32 len, INT32 option,
INT32 socket, UINT8 ip[4], INT32 port)
{
UINT16 tmport;
UINT32 tmpip;
struct sockaddr_in remote_addr;
tmport = (UINT16)port;
tmpip = *((UINT32 *)ip);
memset(&remote_addr,0,sizeof(struct sockaddr_in));
remote_addr.sin_family = AF_INET;
remote_addr.sin_port = htons(tmport);
remote_addr.sin_addr.s_addr = htonl(tmpip);
#ifdef METHOD_ONE
INT32 ret;
INT32 err;
for(;;)
{
ret = sendto(socket,buf,len,option, \
(struct sockaddr *)&remote_addr,sizeof(remote_addr));
if(ret < 0)
{
err = errno;
if((err == EINTR))
{
continue;
}
else if((err == EWOULDBLOCK) || (err == EAGAIN))
{
/* no buffer, just wait */
usleep(1000);
continue;
}
else
{
return ERROR;
}
}
else
{
return ret;
}
}
#else
return sendto(socket,buf,len,option, \
(struct sockaddr *)&remote_addr,sizeof(remote_addr));
#endif
}
INT32 linux_socket_recvfrom(UINT8 *buf, INT32 len, INT32 option,
INT32 socket, UINT8 ip[4], INT16* port)
{
INT32 ret;
socklen_t length;
struct sockaddr_in remote_addr;
length = sizeof(remote_addr);
#ifdef METHOD_ONE
INT32 err;
for(;;)
{
ret = recvfrom(socket,buf,len,option, \
(struct sockaddr *)&remote_addr,&length);
if(ret < 0)
{
err = errno;
if((err == EINTR))
{
continue;
}
else if((err == EWOULDBLOCK) || (err == EAGAIN))
{
/* no data */
return OK;
}
else
{
return ERROR;
}
}
else
{
break;
}
}
#else
ret = recvfrom(socket,buf,len,option, \
(struct sockaddr *)&remote_addr,&length);
if(ret < 0)
return ret;
#endif
if(ip)
*((UINT32 *)ip) = ntohl(remote_addr.sin_addr.s_addr);
if(port)
*port = ntohs(remote_addr.sin_port);
return ret;
}
INT32 linux_socket_listen(INT32 socket)
{
return listen(socket, 5);
}
INT32 linux_socket_accept(INT32 socket, INT32 option, UINT8 ip[4], INT32* port)
{
struct sockaddr_in remote_addr;
INT32 remote_socket;
socklen_t addrlen;
INT32 ret;
addrlen = sizeof(remote_addr);
memset(&remote_addr,0,sizeof(remote_addr));
(void)option;
#ifdef METHOD_ONE
INT32 err;
for(;;)
{
remote_socket = accept(socket, \
(struct sockaddr *)&remote_addr, &addrlen);
if(remote_socket < 0)
{
err = errno;
if((err == EINTR))
{
continue;
}
else if((err == EWOULDBLOCK) || (err == EAGAIN))
{
return PLATFORM_LAYER_TCP_SOCK_NO_CONN;
}
else
{
return ERROR;
}
}
}
#else
remote_socket = accept(socket, (struct sockaddr *)&remote_addr, &addrlen);
if(remote_socket < 0)
return remote_socket;
#endif
linux_socket_set_nonblock(remote_socket);
ret = linux_socket_set_nodelay(remote_socket);
if(ret)
{
close(remote_socket);
return ERROR;
}
if(ip)
*((UINT32 *)ip) = ntohl(remote_addr.sin_addr.s_addr);
if(port)
*port = ntohs(remote_addr.sin_port);
return remote_socket;
}
INT32 linux_socket_connect(INT32 socket, INT32 option,
UINT8 ip[4], INT32 port)
{
(void)option;
UINT16 tmport;
UINT32 tmpip;
struct sockaddr_in saddr;
tmport = (UINT16)port;
tmpip = *((UINT32 *)ip);
memset(&saddr,0,sizeof(struct sockaddr_in));
saddr.sin_family = AF_INET;
saddr.sin_port = htons(tmport);
saddr.sin_addr.s_addr = htonl(tmpip);
/*
TODO:
Method 1 ,the function will blocked here! no posix return
value can be seen in the top levels;
Method 2 ,do not block the function, top level analysis the return value and do sync
operation use AIO;
*/
#ifdef METHOD_ONE
INT32 err;
INT32 ret;
for(;;)
{
/* will block */
ret = connect(socket, (struct sockaddr *)&saddr, sizeof(saddr));
if(ret < 0)
{
err = errno;
if((err == EINTR)||(err == EWOULDBLOCK))
{
continue;
}
else if(err == EINPROGRESS)
{
return OK;
}
else
{
return ERROR;
}
}
else
{
return OK;
}
}
return ERROR;
#else
return connect(socket, (struct sockaddr *)&saddr, sizeof(saddr));
#endif
}
INT32 linux_socket_close(INT32 socket)
{
return close(socket);
}
INT32 linux_get_core_num(VOID)
{
#ifdef _SC_NPROCESSORS_ONLN
return (sysconf(_SC_NPROCESSORS_ONLN));
#else
return (1);
#endif
}
INT32 linux_sig_block(INT32 sig_num)
{
sigset_t set;
sigemptyset(&set);
sigaddset(&set, sig_num);
(void) pthread_sigmask(SIG_BLOCK, &set, NULL);
return OK;
}
INT32 linux_do_select(INT32* fd, UINT32 operation,
INT32 second,INT32 * ready_fd_list)
{
fd_set tmpfds,rxfds,txfds,errfds;
struct timeval tv;
INT32 ret, i;
INT32 fdd = MAX_FD;
FD_ZERO(&tmpfds);
for(i=0; fd[i] != -1;i++)
{
FD_SET(fd[i], &tmpfds);
if(fdd > fd[i])
fdd = fd[i];
}
tv.tv_sec = second;
tv.tv_usec = 0;
if(operation & DO_SELECT_OPER_RX)
memcpy(&rxfds,&tmpfds,sizeof(fd_set));
if(operation & DO_SELECT_OPER_TX)
memcpy(&txfds,&tmpfds,sizeof(fd_set));
if(operation & DO_SELECT_OPER_ERR)
memcpy(&errfds,&tmpfds,sizeof(fd_set));
ret = select(fdd + 1, &rxfds,&txfds,&errfds,&tv);
if(ret < 0)
{
return ERROR;
}
else if(ret == 0)
{
return PLATFORM_LAYER_SELECT_TIME_OUT;
}
else
{
/* update rx ready_fd_list */
if((ready_fd_list)&&(operation & DO_SELECT_OPER_RX))
{
for(;i>0;i--)
{
FD_ISSET(fd[i-1],&rxfds);
*ready_fd_list++ = fd[i-1];
}
}
return ret;
}
}
INT32 linux_get_ava_len(INT32 fd)
{
INT32 ava_len;
INT32 ret;
ret = ioctl(fd,FIONREAD,&ava_len);
if(ret < 0)
return 0;
return ava_len;
}
PF_OPERA opera = {
.mem_alloc = linux_alloc,
.mem_free = linux_free,
.get_pid = linux_get_pid,
.get_pthread_id = linux_get_pthread,
.cv_wait = linux_pthread_cond_wait,
.cv_wake = linux_pthread_cond_wake,
.get_plat_clock = linux_get_cur_clock,
.cv_until = linux_cv_until,
.cv_init = linux_cv_init,
.mute_init = linux_mute_init,
.mute_lock = linux_mute_lock,
.mute_unlock = linux_mute_unlock,
.mute_close = linux_mute_close,
.mute_try_lock = linux_mute_try_lock,
.init = linux_pt_init,
.create_thread = linux_create_thread,
.sleep = linux_sleep,
.sema_init = linux_sema_init,
.sema_close = linux_sema_close,
.sema_wait = linux_sema_wait,
.sema_post = linux_sema_post,
.socket_open = linux_socket_open,
.socket_send = linux_socket_send,
.socket_recv = linux_socket_recv,
.sock_sendto = linux_socket_sendto,
.sock_recvfrom = linux_socket_recvfrom,
.sock_listen = linux_socket_listen,
.sock_accept = linux_socket_accept,
.sock_connect = linux_socket_connect,
.sock_close = linux_socket_close,
.get_core_num = linux_get_core_num,
.sig_block = linux_sig_block,
.do_select = linux_do_select,
.get_available_len = linux_get_ava_len,
};
PLTF_OBJ linux_pt = {
(INT8*)"linux platform",
&opera,
NULL
};
PLTF_OBJ * pltf_obj_get(void)
{
return &linux_pt;
}
PLTF_OBJ * pt;
INT32 pltf_init(void)
{
pt = pltf_obj_get();
return PT_OPT.init();
}
|
C
|
struct point {
int x, y;
};
struct rectangle {
struct point upper_left, lower_right;
};
struct point center(struct rectangle);
int main(void) {
return 0;
}
struct point center(const struct rectangle r) {
struct point p;
p.x = r.upper_left.x + ((r.lower_right.x - r.upper_left.x) / 2);
p.y = r.lower_right.y + ((r.upper_left.y - r.lower_right.y) / 2);
return p;
}
|
C
|
#include "filelogger.h"
static void _write(File_Logger *this_logger, const char *msg);
File_Logger *CreateFileLogger(int level)
{
File_Logger *logger;
logger = (File_Logger *)malloc(sizeof(File_Logger));
if (logger == NULL)
{
return NULL;
}
memset(logger, 0, sizeof(File_Logger));
do
{
if (CreateLoggerChain(&logger->logger, level) != 0)
{
break;
}
logger->logger.write = (write_func)_write;
return logger;
} while (0);
free(logger);
return NULL;
}
void _write(File_Logger *this_logger, const char *msg)
{
if (this_logger == NULL || msg == NULL)
{
return;
}
printf("File::Logger: %s \n", msg);
}
|
C
|
#include<stdio.h>
int main(void) {
int num, i, a, b,sum[1000];
scanf("%d", &num);
for (i = 0; i <num; i++) {
do {
scanf("%d %d", &a, &b);
} while (a < 0 || a>10 || b < 0 || b>10);
sum[i] = a + b;
}
for (i = 0; i < num; i++) {
printf("Case #%d: %d\n", i + 1, sum[i]);
}
return 0;
}
|
C
|
/*
* Copyright (c) 1992, 1993 by the University of Southern California
*
* For copying and distribution information, please see the file
* <usc-license.h>.
*
* Written by bcn 1991 as part of rdgram.c in Prospero distribution
* Modified by bcn 1/93 modularized and incorporated into new ardp library
*/
#include <usc-license.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include <ardp.h>
#include "ardp__int.h"
#include <perrno.h>
#include <gl_log_msgtypes.h>
int (*ardp_pri_func)() = NULL; /* Function to compare priorities */
int ardp_pri_override = 0; /* If 1, then oveeride value in request */
/*
* ardp_set_queueing_plicy - set function for queueing policy
*
* ardp_set_queuing_policy allows one to provide a function that will set
* priorities for requests. When passed two req structures, r1 and r2, the
* function should return a negative number if r1 should be executed first
* (i.e. r1 has a lower numerical priority) and positive if r2 should be
* executed first. If the function returns 0, it means the two have the
* same priority and should be executed FCFS. If override is non-zero, then
* the priority function is to be applied to all requests. If non-zero,
* it is only applied to those with identical a priori priorities (as
* specified in the datagram itself.
*/
enum ardp_errcode
ardp_set_queuing_policy(int (*pf)(), /* Function to compare priorities */
int override) /* If 1, then override value in request
*/
{
ardp_pri_func = pf;
ardp_pri_override = override;
return(ARDP_SUCCESS);
}
enum ardp_errcode
ardp_set_prvport(int port)
{
ardp_prvport = port;
/* See the documentation of ardp_accept in lib/ardp/ardp_pr_actv.c for an
understanding of why we are doing this form of late binding. */
ardp__accept = ardp_accept;
return(ARDP_SUCCESS);
}
/* Improvement 7/97: Listen on 'default port' if nothing passed. */
/* Something a little bit weird happens here. We need to return both an error
code and a port number. */
/* Change in interface: We now return an error code in perrno if we must. */
int
ardp_bind_port(const char *portname)
{
struct sockaddr_in s_in = {AF_INET};
struct servent *sp;
#if 1
int on = 1;
#endif
int port_no = 0;
/* See the documentation of ardp_accept in lib/ardp/ardp_pr_actv.c for an
understanding of why we are doing this form of late binding. */
ardp__accept = ardp_accept;
if (!portname || !*portname) {
if (ardp_debug) {
rfprintf(stderr, "ardp_bind_port() did not get a valid port name \
as an argument; using the default server port: %d\n",
ardp_config.default_port);
}
s_in.sin_port = htons((u_int16_t) ardp_config.default_port);
} else if(*portname == '#') {
sscanf(portname+1,"%d",&port_no);
if(port_no == 0) {
if (ardp_debug) {
rfprintf(stderr, "ardp_bind_port: cannot bind: \"%s\" is an \
invalid port specifier; port number must follow #\n", portname);
}
return -(perrno = ARDP_PORT_UNKN);
}
s_in.sin_port = htons((ushort) port_no);
}
else if((sp = getservbyname(portname, "udp")) != NULL) {
s_in.sin_port = sp->s_port;
}
else if(strcmp(portname,ardp_config.default_peer) == 0) {
if (ardp_debug) {
rfprintf(stderr,
"ardp_bind_port: udp/%s unknown service - using %d\n",
ardp_config.default_peer, ardp_config.default_port);
}
s_in.sin_port = htons((ushort) ardp_config.default_port);
}
else {
if (ardp_debug) {
rfprintf(stderr, "ardp_bind_port: udp/%s unknown service\n",portname);
return -(perrno = ARDP_PORT_UNKN);
}
}
if ((ardp_srvport = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
ardp__log(L_STATUS,NOREQ,"Startup -- Can't open socket",0);
if (ardp_debug)
rfprintf(stderr, "ardp_bind_port: Can't open socket\n");
return -(perrno = ARDP_UDP_CANT);
}
#if 0
/* This was an attempt to do it more elegantly. It did not work, despite
the promises of the Solaris 2.5 (and SunOS 4.1.3, to be fair) manual
page to the contrary. We got an EINVAL (err # 22) when running this
code under Solaris. -- 8/1/96, sridhar@ISI.EDU, swa@ISI.EDU */
/* We had believed that
passing any non-zero value as the fourth argument to setsockopt() would
be enough to turn on the SO_REUSEADDR option; we believed that it did
not need to point to 'on', an integer with a non-zero value.
There are calls to setsockopt) in lib/pfs/opentcp.c which invoke it with
a zero as the fourth and fifth arguments; no idea why they work (or even
if that code is ever executed). --swa, 8/1/96 */
if (setsockopt(ardp_srvport, SOL_SOCKET, SO_REUSEADDR, (char *) 62065, 0) < 0)
rfprintf(stderr, "dirsrv: setsockopt (SO_REUSEADDR)\n");
#else
/* Old way of doing it: */
if (setsockopt(ardp_srvport, SOL_SOCKET, SO_REUSEADDR, (char *) &on, sizeof(on)) < 0)
rfprintf(stderr, "dirsrv: setsockopt (SO_REUSEADDR): %s; continuing \
as best we can.\n", unixerrstr());
#endif
s_in.sin_addr.s_addr = (u_long) myaddress();
if (bind(ardp_srvport, (struct sockaddr *) &s_in, S_AD_SZ) < 0) {
ardp__log(L_STATUS,NOREQ,"ardp: Startup - Can't bind socket",0);
if (ardp_debug)
rfprintf(stderr, "ardp_bind_port(): Can not bind socket\n");
return -(perrno = ARDP_UDP_CANT);
}
return(ntohs(s_in.sin_port));
}
|
C
|
#include "holberton.h"
/**
* print_square - prints areas.
* @size: specification for the area size.
* Return: print a line.
*/
void print_square(int size)
{
int i;
int s;
if (size > 0) /* \ is 92, space is 32 */
{
for (i = 1; i <= size; i++)
{
for (s = 1; s <= size; s++)
_putchar(35);
_putchar('\n');
}
}
else
{
_putchar('\n');
}
}
|
C
|
#include <stdlib.h>
#include <string.h>
#include <Windows.h>
#ifdef UNICODE
// Convert a null-terminated Wide Character string to a dynamically allocated UTF8 string
LPSTR UTF8_Encode_Dyn( LPCWSTR inStr )
{
LPSTR outStr;
int outSize;
outSize = WideCharToMultiByte(CP_UTF8, 0, inStr, -1, NULL, 0, NULL, NULL);
outStr = (LPSTR)malloc(outSize);
WideCharToMultiByte(CP_UTF8, 0, inStr, -1, outStr, outSize, NULL, NULL);
return outStr;
}
// Convert a null-terminated Wide Character string to a statically allocated UTF8 string
LPSTR UTF8_Encode( LPCWSTR inStr, LPSTR outStr, int outSize )
{
WideCharToMultiByte(CP_UTF8, 0, inStr, -1, outStr, outSize, NULL, NULL);
return outStr;
}
// Convert a null-terminated UTF8 string to a dynamically allocated Wide Character string
LPWSTR UTF8_Decode_Dyn( LPCSTR inStr )
{
LPWSTR outStr;
int outSize;
outSize = MultiByteToWideChar(CP_UTF8, 0, inStr, -1, NULL, 0);
outStr = (LPWSTR)malloc(sizeof(WCHAR) * outSize);
MultiByteToWideChar(CP_UTF8, 0, inStr, -1, outStr, outSize);
return outStr;
}
// Convert a null-terminated UTF8 string to a statically allocated Wide Character string
LPWSTR UTF8_Decode( LPCSTR inStr, LPWSTR outStr, int outSize )
{
MultiByteToWideChar(CP_UTF8, 0, inStr, -1, outStr, outSize);
return outStr;
}
#else
/** These functions included for TCHAR support **/
// Convert a null-terminated ASCII string to a dynamically allocated UTF8 string
LPSTR UTF8_Encode_Dyn( LPCSTR inStr )
{
LPSTR outStr;
outStr = (LPSTR)malloc(strlen(inStr));
strcpy(outStr, inStr);
return outStr;
}
// Convert a null-terminated ASCII string to a statically allocated UTF8 string
LPSTR UTF8_Encode( LPCSTR inStr, LPSTR outStr, int outSize )
{
strncpy(outStr, inStr, outSize);
return outStr;
}
// Convert a null-terminated UTF8 string to a dynamically allocated ASCII string
LPSTR UTF8_Decode_Dyn( LPCSTR inStr )
{
LPSTR outStr;
inSize = strlen(inStr) + 1;
outStr = (LPSTR)malloc(inSize);
for(int i = 0; i < inSize; i++)
{
if(*inStr < 0x80) outStr[i] = *inStr;
if(!*inStr) break;
inStr++;
}
return outStr;
}
// Convert a null-terminated UTF8 string to a statically allocated ASCII string
LPSTR UTF8_Decode( LPCSTR inStr, LPSTR outStr, int outSize )
{
for(int i = 0; i < outSize; i++)
{
if(*inStr < 0x80) outStr[i] = *inStr;
if(!*inStr) break;
inStr++;
}
return outStr;
}
#endif
|
C
|
#include "main.h"
/********************************/
int main()
{
while(1)
{
/* input data */
input_handler(input_data);
}
return 0;
}/********************************/
/* read input string */
void input_handler(char *str)
{
fflush( stdout );
scanf(" %s", str);
if(str[0] == '.')
{
command_handler(str);
}
else
{
data_handler(str);
}
}/********************************/
/* check and execute command */
void command_handler(char *str)
{
if(str[5] == '\0')
{
switch(*(unsigned int*)(str+1))
{
case 0x74697865: // 0x74697865 - .exit
fflush( stdout );
printf("%s\n","Chosen .exit");
fflush( stdout );
printf("%s\n","Bye");
exit(0);
break;
case 0x65657266: // 0x65657266 - .free
fflush( stdout );
printf("%s\n","Chosen .free");
db.cnt = 0;
fflush( stdout );
printf("%s\n","Database is empty");
break;
case 0x776F6873: // 0x776F6873 - .show
fflush( stdout );
printf("%s\n","Chosen .show");
if(db.cnt == 0)
{
fflush( stdout );
printf("%s\n","Database is empty");
}
for(unsigned int k = 0; k < db.cnt; k++)
{
show_data(k);
}
break;
case 0x6F666E69: // 0x6F666E69 - .info
fflush( stdout );
printf("%s\n","Chosen .info");
for(unsigned int i = 0; i < db.cnt; i++)
{
show_data(i);
data_parser (db.items[i].data, i);
}
break;
default:
fflush( stdout );
printf("%s\n",bad_command_message);
}
}
else
{
fflush( stdout );
printf("%s\n",bad_command_message);
}
}/********************************/
/* change data from ascii to hex and store in db */
void data_handler(char *str)
{
db.items[db.cnt].len = strlen(str);
for(unsigned int i = 0, j = 0; i < db.items[db.cnt].len; i+=2, j++)
{
db.items[db.cnt].data[j] = (str[i+1]<='9') ? (str[i+1]-'0') : (str[i+1]-'A'+10) ;
db.items[db.cnt].data[j] += ((str[i]<='9') ? (str[i]-'0') : (str[i]-'A'+10) )* 0x10;
}
db.cnt++;
}/********************************/
/* parsing data */
void data_parser (void *st_ptr, unsigned int a)
{
/* IO nr */
cnt_n1_io = db.items[a].data[36];
cnt_n2_io = db.items[a].data[36 + cnt_n1_io*2 + 1];
cnt_n4_io = db.items[a].data[37 + cnt_n1_io*2 + cnt_n2_io*3 + 1];
cnt_n8_io = db.items[a].data[38 + cnt_n1_io*2 + cnt_n2_io*3 + cnt_n4_io*5 + 1];
typedef struct
{
unsigned char n_io_id[1];
unsigned char n_io_value[1];
} n1_io_ptr;
typedef struct
{
unsigned char n_io_id[1];
unsigned char n_io_value[2];
} n2_io_ptr;
typedef struct
{
unsigned char n_io_id[1];
unsigned char n_io_value[4];
} n4_io_ptr;
typedef struct
{
unsigned char n_io_id[1];
unsigned char n_io_value[8];
} n8_io_ptr;
typedef struct
{
unsigned char event_io_id[1];
unsigned char N_of_total_id[1];
unsigned char N1_of_one_byte_io[1];
n1_io_ptr n1_io[cnt_n1_io];
unsigned char N2_of_two_byte_io[1];
n2_io_ptr n2_io[cnt_n2_io];
unsigned char N4_of_four_byte_io[1];
n4_io_ptr n4_io[cnt_n4_io];
unsigned char N8_of_eight_byte_io[1];
n8_io_ptr n8_io[cnt_n8_io];
} io_element_ptr;
typedef struct
{
unsigned char longitude[4];
unsigned char latitude[4];
unsigned char altitude[2];
unsigned char angle[2];
unsigned char satellites[1];
unsigned char speed[2];
} gps_element_ptr;
typedef struct
{
unsigned char timestamp[8];
unsigned char priority[1];
gps_element_ptr gps_element[1];
io_element_ptr io_element[1];
} avl_data_ptr;
typedef struct
{
unsigned char preamble[4];
unsigned char data_field_lenght[4];
unsigned char codec_id[1];
unsigned char nr_of_data_1[1];
avl_data_ptr avl_data[1];
unsigned char nr_of_data_2[1];
unsigned char crc_16[4];
} stdn;
fflush( stdout );
printf("Name\t\t\t\tSize\t\t\tValue\t\t\tHex Value\n");
printf("Preamble\t\t\t%d\t\t\t", sizeof(((stdn*)st_ptr)->preamble));
printf("%lu\t\t\t", swap_uint32(*(unsigned long*)((stdn*)st_ptr)->preamble));
for(unsigned int i = 0; printf("%02X",((stdn*)st_ptr)->preamble[i]), i < sizeof(((stdn*)st_ptr)->preamble)-1; i++, printf("-"));
printf("\nData Field Lenght\t\t%d\t\t\t", sizeof(((stdn*)st_ptr)->data_field_lenght));
printf("%lu\t\t\t", swap_uint32(*(unsigned long*)((stdn*)st_ptr)->data_field_lenght));
for(unsigned int i = 0; printf("%02X",((stdn*)st_ptr)->data_field_lenght[i]), i < sizeof(((stdn*)st_ptr)->data_field_lenght)-1 ; i++, printf("-"));
printf("\nCodec ID\t\t\t%d\t\t\t", sizeof(((stdn*)st_ptr)->codec_id));
printf("%d\t\t\t", *((stdn*)st_ptr)->codec_id);
for(unsigned int i = 0; printf("%02X",((stdn*)st_ptr)->codec_id[i]), i < sizeof(((stdn*)st_ptr)->codec_id)-1; i++, printf("-"));
printf("\nNr of Data 1\t\t\t%d\t\t\t", sizeof(((stdn*)st_ptr)->nr_of_data_1));
printf("%d\t\t\t", *((stdn*)st_ptr)->nr_of_data_1);
for(unsigned int i = 0; printf("%02X",((stdn*)st_ptr)->nr_of_data_1[i]), i < sizeof(((stdn*)st_ptr)->nr_of_data_1)-1; i++, printf("-"));
printf("\nAVL Data\t\t\t%d", sizeof(((stdn*)st_ptr)->avl_data));
printf("\n Timestamp\t\t\t%d\t\t\t", sizeof(((stdn*)st_ptr)->avl_data->timestamp));
printf("0\t\t\t");
for(unsigned int i = 0; printf("%02X",((stdn*)st_ptr)->avl_data->timestamp[i]), i < sizeof(((stdn*)st_ptr)->avl_data->timestamp)-1; i++, printf("-"));
printf("\n Priority\t\t\t%d\t\t\t", sizeof(((stdn*)st_ptr)->avl_data->priority));
printf("%d\t\t\t", *((stdn*)st_ptr)->avl_data->priority);
for(unsigned int i = 0; printf("%02X",((stdn*)st_ptr)->avl_data->priority[i]), i < sizeof(((stdn*)st_ptr)->avl_data->priority)-1; i++, printf("-"));
printf("\n GPS Element\t\t\t%d", sizeof(((stdn*)st_ptr)->avl_data->gps_element));
printf("\n Longitude\t\t\t%d\t\t\t", sizeof(((stdn*)st_ptr)->avl_data->gps_element->longitude));
printf("%lu\t\t\t", swap_uint32(*(unsigned long*)((stdn*)st_ptr)->avl_data->gps_element->longitude));
for(unsigned int i = 0; printf("%02X",((stdn*)st_ptr)->avl_data->gps_element->longitude[i]), i < sizeof(((stdn*)st_ptr)->avl_data->gps_element->longitude)-1; i++, printf("-"));
printf("\n Latitude\t\t\t%d\t\t\t", sizeof(((stdn*)st_ptr)->avl_data->gps_element->latitude));
printf("%lu\t\t\t", swap_uint32(*(unsigned long*)((stdn*)st_ptr)->avl_data->gps_element->latitude));
for(unsigned int i = 0; printf("%02X",((stdn*)st_ptr)->avl_data->gps_element->latitude[i]), i < sizeof(((stdn*)st_ptr)->avl_data->gps_element->latitude)-1; i++, printf("-"));
printf("\n Altitude\t\t\t%d\t\t\t", sizeof(((stdn*)st_ptr)->avl_data->gps_element->altitude));
printf("%u\t\t\t", swap_uint16(*(unsigned short*)((stdn*)st_ptr)->avl_data->gps_element->altitude));
for(unsigned int i = 0; printf("%02X",((stdn*)st_ptr)->avl_data->gps_element->altitude[i]), i < sizeof(((stdn*)st_ptr)->avl_data->gps_element->altitude)-1; i++, printf("-"));
printf("\n Angle\t\t\t\t%d\t\t\t", sizeof(((stdn*)st_ptr)->avl_data->gps_element->angle));
printf("%u\t\t\t", swap_uint16(*(unsigned short*)((stdn*)st_ptr)->avl_data->gps_element->angle));
for(unsigned int i = 0; printf("%02X",((stdn*)st_ptr)->avl_data->gps_element->angle[i]), i < sizeof(((stdn*)st_ptr)->avl_data->gps_element->angle)-1; i++, printf("-"));
printf("\n Satellites\t\t\t%d\t\t\t", sizeof(((stdn*)st_ptr)->avl_data->gps_element->satellites));
printf("%u\t\t\t", *((stdn*)st_ptr)->avl_data->gps_element->satellites);
for(unsigned int i = 0; printf("%02X",((stdn*)st_ptr)->avl_data->gps_element->satellites[i]), i < sizeof(((stdn*)st_ptr)->avl_data->gps_element->satellites)-1; i++, printf("-"));
printf("\n Speed\t\t\t\t%d\t\t\t", sizeof(((stdn*)st_ptr)->avl_data->gps_element->speed));
printf("%u\t\t\t", swap_uint16(*(unsigned short*)((stdn*)st_ptr)->avl_data->gps_element->speed));
for(unsigned int i = 0; printf("%02X",((stdn*)st_ptr)->avl_data->gps_element->speed[i]), i < sizeof(((stdn*)st_ptr)->avl_data->gps_element->speed)-1; i++, printf("-"));
printf("\n IO Element\t\t\t%d", sizeof(((stdn*)st_ptr)->avl_data->gps_element));
printf("\n Event IO id\t\t\t%d\t\t\t", sizeof(((stdn*)st_ptr)->avl_data->io_element->event_io_id));
printf("%u\t\t\t", *((stdn*)st_ptr)->avl_data->io_element->event_io_id);
for(unsigned int i = 0; printf("%02X",((stdn*)st_ptr)->avl_data->io_element->event_io_id[i]), i < sizeof(((stdn*)st_ptr)->avl_data->io_element->event_io_id)-1; i++, printf("-"));
printf("\n N of total id\t\t\t%d\t\t\t", sizeof(((stdn*)st_ptr)->avl_data->io_element->N_of_total_id));
printf("%u\t\t\t", *((stdn*)st_ptr)->avl_data->io_element->N_of_total_id);
for(unsigned int i = 0; printf("%02X",((stdn*)st_ptr)->avl_data->io_element->N_of_total_id[i]), i < sizeof(((stdn*)st_ptr)->avl_data->io_element->N_of_total_id)-1; i++, printf("-"));
printf("\n N1 of one byte io\t\t%d\t\t\t", sizeof(((stdn*)st_ptr)->avl_data->io_element->N1_of_one_byte_io));
printf("%u\t\t\t", *((stdn*)st_ptr)->avl_data->io_element->N1_of_one_byte_io);
for(unsigned int i = 0; printf("%02X",((stdn*)st_ptr)->avl_data->io_element->N1_of_one_byte_io[i]), i < sizeof(((stdn*)st_ptr)->avl_data->io_element->N1_of_one_byte_io)-1; i++, printf("-"));
for (unsigned int j = 0; j < *((stdn*)st_ptr)->avl_data->io_element->N1_of_one_byte_io; j++)
{
printf("\n N1 IO id\t\t\t%d\t\t\t", sizeof(((stdn*)st_ptr)->avl_data->io_element->n1_io[j].n_io_id));
printf("%u\t\t\t", *((stdn*)st_ptr)->avl_data->io_element->n1_io[j].n_io_id);
for(unsigned int i = 0; printf("%02X",((stdn*)st_ptr)->avl_data->io_element->n1_io[j].n_io_id[i]), i < sizeof(((stdn*)st_ptr)->avl_data->io_element->n1_io[j].n_io_id)-1; i++, printf("-"));
printf("\n N1 value id\t\t\t%d\t\t\t", sizeof(((stdn*)st_ptr)->avl_data->io_element->n1_io[j].n_io_value));
printf("%u\t\t\t", *((stdn*)st_ptr)->avl_data->io_element->n1_io[j].n_io_value);
for(unsigned int i = 0; printf("%02X",((stdn*)st_ptr)->avl_data->io_element->n1_io[j].n_io_value[i]), i < sizeof(((stdn*)st_ptr)->avl_data->io_element->n1_io[j].n_io_value)-1; i++, printf("-"));
}
printf("\n N2 of two byte io\t\t%d\t\t\t", sizeof(((stdn*)st_ptr)->avl_data->io_element->N2_of_two_byte_io));
printf("%u\t\t\t", *((stdn*)st_ptr)->avl_data->io_element->N2_of_two_byte_io);
for(unsigned int i = 0; printf("%02X",((stdn*)st_ptr)->avl_data->io_element->N2_of_two_byte_io[i]), i < sizeof(((stdn*)st_ptr)->avl_data->io_element->N2_of_two_byte_io)-1; i++, printf("-"));
for (unsigned int j = 0; j < *((stdn*)st_ptr)->avl_data->io_element->N2_of_two_byte_io; j++)
{
printf("\n N2 IO id\t\t\t%d\t\t\t", sizeof(((stdn*)st_ptr)->avl_data->io_element->n2_io[j].n_io_id));
printf("%u\t\t\t", *((stdn*)st_ptr)->avl_data->io_element->n2_io[j].n_io_id);
for(unsigned int i = 0; printf("%02X",((stdn*)st_ptr)->avl_data->io_element->n2_io[j].n_io_id[i]), i < sizeof(((stdn*)st_ptr)->avl_data->io_element->n2_io[j].n_io_id)-1; i++, printf("-"));
printf("\n N2 value id\t\t\t%d\t\t\t", sizeof(((stdn*)st_ptr)->avl_data->io_element->n2_io[j].n_io_value));
printf("%u\t\t\t", swap_uint16(*(unsigned short*)((stdn*)st_ptr)->avl_data->io_element->n2_io[j].n_io_value));
for(unsigned int i = 0; printf("%02X",((stdn*)st_ptr)->avl_data->io_element->n2_io[j].n_io_value[i]), i < sizeof(((stdn*)st_ptr)->avl_data->io_element->n2_io[j].n_io_value)-1; i++, printf("-"));
}
printf("\n N4 of four byte io\t\t%d\t\t\t", sizeof(((stdn*)st_ptr)->avl_data->io_element->N4_of_four_byte_io));
printf("%u\t\t\t", *((stdn*)st_ptr)->avl_data->io_element->N4_of_four_byte_io);
for(unsigned int i = 0; printf("%02X",((stdn*)st_ptr)->avl_data->io_element->N4_of_four_byte_io[i]), i < sizeof(((stdn*)st_ptr)->avl_data->io_element->N4_of_four_byte_io)-1; i++, printf("-"));
for (unsigned int j = 0; j < *((stdn*)st_ptr)->avl_data->io_element->N4_of_four_byte_io; j++)
{
printf("\n N4 IO id\t\t\t%d\t\t\t", sizeof(((stdn*)st_ptr)->avl_data->io_element->n4_io[j].n_io_id));
printf("%u\t\t\t", *((stdn*)st_ptr)->avl_data->io_element->n4_io[j].n_io_id);
for(unsigned int i = 0; printf("%02X",((stdn*)st_ptr)->avl_data->io_element->n4_io[j].n_io_id[i]), i < sizeof(((stdn*)st_ptr)->avl_data->io_element->n4_io[j].n_io_id)-1; i++, printf("-"));
printf("\n N4 value id\t\t\t%d\t\t\t", sizeof(((stdn*)st_ptr)->avl_data->io_element->n2_io[j].n_io_value));
printf("%lu\t\t\t", swap_uint32(*(unsigned long*)((stdn*)st_ptr)->avl_data->io_element->n4_io[j].n_io_value));
for(unsigned int i = 0; printf("%02X",((stdn*)st_ptr)->avl_data->io_element->n4_io[j].n_io_value[i]), i < sizeof(((stdn*)st_ptr)->avl_data->io_element->n4_io[j].n_io_value)-1; i++, printf("-"));
}
printf("\n N8 of eight byte io\t\t%d\t\t\t", sizeof(((stdn*)st_ptr)->avl_data->io_element->N8_of_eight_byte_io));
printf("%u\t\t\t", *((stdn*)st_ptr)->avl_data->io_element->N8_of_eight_byte_io);
for(unsigned int i = 0; printf("%02X",((stdn*)st_ptr)->avl_data->io_element->N8_of_eight_byte_io[i]), i < sizeof(((stdn*)st_ptr)->avl_data->io_element->N8_of_eight_byte_io)-1; i++, printf("-"));
for (unsigned int j = 0; j < *((stdn*)st_ptr)->avl_data->io_element->N8_of_eight_byte_io; j++)
{
printf("\n N8 IO id\t\t\t%d\t\t\t", sizeof(((stdn*)st_ptr)->avl_data->io_element->n8_io[j].n_io_id));
printf("%u\t\t\t", *((stdn*)st_ptr)->avl_data->io_element->n8_io[j].n_io_id);
for(unsigned int i = 0; printf("%02X",((stdn*)st_ptr)->avl_data->io_element->n8_io[j].n_io_id[i]), i < sizeof(((stdn*)st_ptr)->avl_data->io_element->n8_io[j].n_io_id)-1; i++, printf("-"));
printf("\n N8 value id\t\t\t%d\t\t\t", sizeof(((stdn*)st_ptr)->avl_data->io_element->n8_io[j].n_io_value));
printf("%lu\t\t\t", swap_uint64(*(unsigned long long*)((stdn*)st_ptr)->avl_data->io_element->n8_io[j].n_io_value));
for(unsigned int i = 0; printf("%02X",((stdn*)st_ptr)->avl_data->io_element->n8_io[j].n_io_value[i]), i < sizeof(((stdn*)st_ptr)->avl_data->io_element->n8_io[j].n_io_value)-1; i++, printf("-"));
}
printf("\nNr of Data 2\t\t\t%d\t\t\t", sizeof(((stdn*)st_ptr)->nr_of_data_2));
printf("%d\t\t\t", *((stdn*)st_ptr)->nr_of_data_2);
for(unsigned int i = 0; printf("%02X",((stdn*)st_ptr)->nr_of_data_2[i]), i < sizeof(((stdn*)st_ptr)->nr_of_data_2)-1; i++, printf("-"));
printf("\nCRC-16\t\t\t\t%d\t\t\t", sizeof(((stdn*)st_ptr)->crc_16));
printf("%lu\t\t\t", swap_uint32(*(unsigned long*)((stdn*)st_ptr)->crc_16));
for(unsigned int i = 0; printf("%02X",((stdn*)st_ptr)->crc_16[i]), i < sizeof(((stdn*)st_ptr)->crc_16)-1; i++, printf("-"));
printf("\n ------------------------------------------------------------------------------------------------ \n");
}/********************************/
/* change data from hex to ascii and show all data in database */
void show_data( unsigned int cnt)
{
char str0[1536];
for(unsigned int i = 0, j = 0; j < db.items[cnt].len; i++, j+=2)
{
if(((db.items[cnt].data[i] >> 4) & 0x0f ) <= 0x9)
{
str0[j] = ((db.items[cnt].data[i] >> 4) & 0x0f ) + '0';
}
else if(((db.items[cnt].data[i] >> 4) & 0x0f ) > 0x9)
{
str0[j] = ((db.items[cnt].data[i] >> 4) & 0x0f ) - 10 + 'A';
}
if(((db.items[cnt].data[i] ) & 0x0f ) <= 0x9)
{
str0[j+1] = (db.items[cnt].data[i] & 0x0f ) + '0';
}
else if(((db.items[cnt].data[i] ) & 0x0f ) > 0x9)
{
str0[j+1] = (db.items[cnt].data[i] & 0x0f ) - 10 + 'A';
}
}
str0[db.items[cnt].len] = 0;
fflush( stdout );
printf("%s\n",str0);
}
//! Byte swap unsigned short
unsigned short swap_uint16( unsigned short val )
{
return (val << 8) | (val >> 8 );
}
//! Byte swap unsigned long
unsigned long swap_uint32( unsigned long val )
{
val = ((val << 8) & 0xFF00FF00 ) | ((val >> 8) & 0xFF00FF );
return (val << 16) | (val >> 16);
}
//! Byte swap unsigned long long
unsigned long long swap_uint64( unsigned long long val )
{
val = ((val << 8) & 0xFF00FF00FF00FF00ULL ) | ((val >> 8) & 0x00FF00FF00FF00FFULL );
val = ((val << 16) & 0xFFFF0000FFFF0000ULL ) | ((val >> 16) & 0x0000FFFF0000FFFFULL );
return (val << 32) | (val >> 32);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ray_tracer_utils.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: fhamel <fhamel@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/04/07 11:23:10 by florianhame #+# #+# */
/* Updated: 2020/10/27 23:40:30 by fhamel ### ########.fr */
/* */
/* ************************************************************************** */
#include "mini_rt.h"
void normalize(t_vec *vec)
{
double len;
len = sqrt(pow(vec->x, 2) + pow(vec->y, 2) + pow(vec->z, 2));
vec->x /= len;
vec->y /= len;
vec->z /= len;
}
double dot_p(t_vec a, t_vec b)
{
double dot_p;
dot_p = (a.x * b.x) + (a.y * b.y) +
(a.z * b.z);
return (dot_p);
}
t_vec cross_p(t_vec a, t_vec b)
{
t_vec c;
c.x = (a.y * b.z) - (a.z * b.y);
c.y = (a.z * b.x) - (a.x * b.z);
c.z = (a.x * b.y) - (a.y * b.x);
return (c);
}
void init_obj(t_obj *obj)
{
obj->id = -1;
obj->x = 0;
obj->y = 0;
obj->z = 0;
obj->len = INFINITY;
obj->ptr = NULL;
}
void fill_obj(t_data *data, t_obj *obj, double t, t_vec cam_ray)
{
obj->x = data->c->x + (t * cam_ray.x);
obj->y = data->c->y + (t * cam_ray.y);
obj->z = data->c->z + (t * cam_ray.z);
obj->len = sqrt(pow(obj->x - data->c->x, 2) +
pow(obj->y - data->c->y, 2) +
pow(obj->z - data->c->z, 2));
}
|
C
|
/*
Example for Temp_Hum_9 Click
Date : Nov 2018.
Author : Aleksandar Paunovic
Test configuration PIC :
MCU : P18F87K22
Dev. Board : EasyPIC PRO v7
PIC Compiler ver : v7.2.0.0
---
Description :
The application is composed of three sections :
- System Initialization - Initializes LOG and I2C
- Application Initialization - Initializes I2C driver and sends SLEEP and WAKEUP dommands
- Application Task - Performs simultaneous temperature and relative humidity measurements and logs both values
*/
#include "Click_Temp_Hum_9_types.h"
#include "Click_Temp_Hum_9_config.h"
char text[50];
float measurementData[2];
void systemInit( )
{
mikrobus_i2cInit( _MIKROBUS1, &_TEMPHUM9_I2C_CFG[0] );
Delay_ms(500);
mikrobus_logInit( _LOG_USBUART, 9600 );
Delay_ms(100);
mikrobus_logWrite( "< < < sys init done > > >", _LOG_LINE );
}
void applicationInit( )
{
temphum9_i2cDriverInit( (T_TEMPHUM9_P)&_MIKROBUS1_GPIO, (T_TEMPHUM9_P)&_MIKROBUS1_I2C, _TEMPHUM9_DEVICE_ADDRESS );
temphum9_sendCommand( _TEMPHUM9_SLEEP );
Delay_ms(500);
temphum9_sendCommand( _TEMPHUM9_WAKEUP );
Delay_ms(100);
mikrobus_logWrite( "< < < app init done > > >", _LOG_LINE );
}
void applicationTask( )
{
mikrobus_logWrite( " ", _LOG_LINE );
temhum9_getTemperatureAndHumidity( _TEMPHUM9_NORMAL_MODE, &measurementData[0] );
FloatToStr( measurementData[0], text );
mikrobus_logWrite( "> > > Temperature : ", _LOG_TEXT );
mikrobus_logWrite( text, _LOG_TEXT );
mikrobus_logWrite( " C", _LOG_LINE );
FloatToStr( measurementData[1], text );
mikrobus_logWrite( "> > > Relative humidity : ", _LOG_TEXT );
mikrobus_logWrite( text, _LOG_TEXT );
mikrobus_logWrite( " %", _LOG_LINE );
mikrobus_logWrite( " ", _LOG_LINE );
Delay_ms(1000);
}
void main( )
{
systemInit( );
applicationInit( );
while (1)
{
applicationTask( );
}
}
|
C
|
#include "apue.h"
#include <ctype.h>
int
main(void)
{
int c;
char str[5] = {'\0', '\0', '\0', '\0', '\0'};
str[4] = '\0';
int i = 0, j;
char tmp;
while ((c = getchar()) != EOF) {
if (islower(c))
c = toupper(c);
if (i >= 4){
tmp = str[0];
for (j = 0; j < 4; j++){
str[j] = str[j + 1];
}
i = 3;
}
if ('\n' != c){
str[i++] = (char)c;
}else{
i = 0;
str[0] = '\0';
}
if (putchar(c) == EOF)
err_sys("output error");
if (c == '\n')
fflush(stdout);
/* puts(str);
fflush(stdout);*/
if (!strcmp(str, "QUIT") || !strcmp(str, "EXIT")){
putchar('\n');
exit(0);
}
}
exit(0);
}
|
C
|
/* $Id: alloc-1.c $ */
/** @file
* Allocate lots of memory, portable ANSI C code.
*/
/*
* Copyright (C) 2007-2017 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* you can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*
* The contents of this file may alternatively be used under the terms
* of the Common Development and Distribution License Version 1.0
* (CDDL) only, as it comes in the "COPYING.CDDL" file of the
* VirtualBox OSE distribution, in which case the provisions of the
* CDDL are applicable instead of those of the GPL.
*
* You may elect to license modified versions of this file under the
* terms and conditions of either the GPL or the CDDL or both.
*/
/*********************************************************************************************************************************
* Header Files *
*********************************************************************************************************************************/
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char **argv)
{
unsigned uPct;
unsigned long cbDone;
unsigned long cMBs = 1024;
unsigned long cb;
/*
* Some quick and dirty argument parsing.
*/
if (argc == 2)
cMBs = strtoul(argv[1], 0, 0);
if (!cMBs || argc > 2)
{
printf("usage: alloc-1 [MBs]\n");
return 1;
}
cb = cMBs * 1024 * 1024;
if (cb / (1024 * 1024) != cMBs)
cb = ~(unsigned long)0 / (1024 * 1024) * (1024 * 1024);
printf("alloc-1: allocating %lu MB (%lu bytes)\n", cb/1024/1024, cb);
/*
* The allocation loop.
*/
printf("alloc-1: 0%%");
fflush(stdout);
cbDone = 0;
uPct = 0;
while (cbDone < cb)
{
unsigned uPctNow;
unsigned long cbThis = cb > 10*1024*1024 ? 10*1024*1024 : cb;
char *pb = malloc(cbThis);
if (!pb)
{
printf("\nalloc-1: calloc failed, cbDone=%lu MB (%lu bytes)\n",
cbDone/1024/1024, cbDone);
return 1;
}
cbDone += cbThis;
/* touch the memory. */
while (cbThis >= 0x1000)
{
*pb = (char)cbThis;
pb += 0x1000;
cbThis -= 0x1000;
}
/* progress */
uPctNow = 100.0 * cbDone / cb;
if (uPctNow != uPct && !(uPctNow & 1))
{
if (!(uPctNow % 10))
printf("%u%%", uPctNow);
else
printf(".");
fflush(stdout);
}
uPct = uPctNow;
}
printf("\nalloc-1: done\n");
return 0;
}
|
C
|
/*
* Lib_Sensor.c
*
* Created on: Mar 11, 2015
* Author: cedric
*/
/*******************************************
* I N C L U D E *
********************************************/
//#include <stdlib.h>
//#include <string.h>
//
//#include "Lib_Sensor_DHT22.h"
//#include "bbb_mmio.h"
///*******************************************
//* D E F I N E *
//********************************************/
//
//// This is the only processor specific magic value, the maximum amount of time to
//// spin in a loop before bailing out and considering the read a timeout. This should
//// be a high value, but if you're running on a much faster platform than a Raspberry
//// Pi or Beaglebone Black then it might need to be increased.
//#define DHT_MAXCOUNT 32000
//
//// Number of bit pulses to expect from the DHT. Note that this is 41 because
//// the first pulse is a constant 50 microsecond pulse, with 40 pulses to represent
//// the data afterwards.
//#define DHT_PULSES 41
//
///*******************************************
//* T Y P E D E F & C O N S T A N T E *
//********************************************/
//
///*******************************************
//* G L O B A L V A R I A B L E S *
//********************************************/
//
///*******************************************
//* F U N C T I O N S *
//********************************************/
///*
// ============================================
// Function : bbb_dht_read()
// Parameter :
// Return Value : int
// Description :
// ============================================
// */
//int bbb_dht_read(int type, int gpio_base, int gpio_number, float* humidity, float* temperature) {
//// Validate humidity and temperature arguments and set them to zero.
//if (humidity == NULL || temperature == NULL) {
//return DHT_ERROR_ARGUMENT;
//}
//*temperature = 0.0f;
//*humidity = 0.0f;
//// Store the count that each DHT bit pulse is low and high.
//// Make sure array is initialized to start at zero.
//int pulseCounts[DHT_PULSES*2] = {0};
//// Get GPIO pin and set it as an output.
//gpio_t pin;
//if (bbb_mmio_get_gpio(gpio_base, gpio_number, &pin) < 0) {
//return DHT_ERROR_GPIO;
//}
//bbb_mmio_set_output(pin);
//// Bump up process priority and change scheduler to try to try to make process more 'real time'.
//set_max_priority();
//// Set pin high for ~500 milliseconds.
//bbb_mmio_set_high(pin);
//sleep_milliseconds(500);
//// The next calls are timing critical and care should be taken
//// to ensure no unnecssary work is done below.
//// Set pin low for ~20 milliseconds.
//bbb_mmio_set_low(pin);
//busy_wait_milliseconds(20);
//
//// Set pin as input.
//bbb_mmio_set_input(pin);
//// Wait for DHT to pull pin low.
//uint32_t count = 0;
//while (bbb_mmio_input(pin)) {
//if (++count >= DHT_MAXCOUNT) {
//// Timeout waiting for response.
//set_default_priority();
//return DHT_ERROR_TIMEOUT;
//}
//}
//// Record pulse widths for the expected result bits.
//int i= 0 ;
//for (i=0; i < DHT_PULSES*2; i+=2) {
//// Count how long pin is low and store in pulseCounts[i]
//while (!bbb_mmio_input(pin)) {
//if (++pulseCounts[i] >= DHT_MAXCOUNT) {
//// Timeout waiting for response.
//set_default_priority();
//return DHT_ERROR_TIMEOUT;
//}
//}
//// Count how long pin is high and store in pulseCounts[i+1]
//while (bbb_mmio_input(pin)) {
//if (++pulseCounts[i+1] >= DHT_MAXCOUNT) {
//// Timeout waiting for response.
//set_default_priority();
//return DHT_ERROR_TIMEOUT;
//}
//}
//}
//// Done with timing critical code, now interpret the results.
//// Drop back to normal priority.
//set_default_priority();
//// Compute the average low pulse width to use as a 50 microsecond reference threshold.
//// Ignore the first two readings because they are a constant 80 microsecond pulse.
//uint32_t threshold = 0;
//for (i=2; i < DHT_PULSES*2; i+=2) {
//threshold += pulseCounts[i];
//}
//threshold /= DHT_PULSES-1;
//// Interpret each high pulse as a 0 or 1 by comparing it to the 50us reference.
//// If the count is less than 50us it must be a ~28us 0 pulse, and if it's higher
//// then it must be a ~70us 1 pulse.
//uint8_t data[5] = {0};
//
//for (i=3; i < DHT_PULSES*2; i+=2) {
//int index = (i-3)/16;
//data[index] <<= 1;
//if (pulseCounts[i] >= threshold) {
//// One bit for long pulse.
//data[index] |= 1;
//}
//// Else zero bit for short pulse.
//}
//// Useful debug info:
////printf("Data: 0x%x 0x%x 0x%x 0x%x 0x%x\n", data[0], data[1], data[2], data[3], data[4]);
//// Verify checksum of received data.
//if (data[4] == ((data[0] + data[1] + data[2] + data[3]) & 0xFF)) {
//if (type == DHT11) {
//// Get humidity and temp for DHT11 sensor.
//*humidity = (float)data[0];
//*temperature = (float)data[2];
//}
//else if (type == DHT22) {
//// Calculate humidity and temp for DHT22 sensor.
//*humidity = (data[0] * 256 + data[1]) / 10.0f;
//*temperature = ((data[2] & 0x7F) * 256 + data[3]) / 10.0f;
//if (data[2] & 0x80) {
//*temperature *= -1.0f;
//}
//}
//return DHT_SUCCESS;
//}
//else {
//return DHT_ERROR_CHECKSUM;
//}
//}
//
//
//void busy_wait_milliseconds(uint32_t millis) {
//// Set delay time period.
//struct timeval deltatime;
//deltatime.tv_sec = millis / 1000;
//deltatime.tv_usec = (millis % 1000) * 1000;
//struct timeval walltime;
//// Get current time and add delay to find end time.
//gettimeofday(&walltime, NULL);
//struct timeval endtime;
//timeradd(&walltime, &deltatime, &endtime);
//// Tight loop to waste time (and CPU) until enough time as elapsed.
//while (timercmp(&walltime, &endtime, <)) {
//gettimeofday(&walltime, NULL);
//}
//}
//void sleep_milliseconds(uint32_t millis) {
//struct timespec sleep;
//sleep.tv_sec = millis / 1000;
//sleep.tv_nsec = (millis % 1000) * 1000000L;
//while (clock_nanosleep(CLOCK_MONOTONIC, 0, &sleep, &sleep) && errno == EINTR);
//}
//void set_max_priority(void) {
//struct sched_param sched;
//memset(&sched, 0, sizeof(sched));
//// Use FIFO scheduler with highest priority for the lowest chance of the kernel context switching.
//sched.sched_priority = sched_get_priority_max(SCHED_FIFO);
//sched_setscheduler(0, SCHED_FIFO, &sched);
//}
//void set_default_priority(void) {
//struct sched_param sched;
//memset(&sched, 0, sizeof(sched));
//// Go back to default scheduler with default 0 priority.
//sched.sched_priority = 0;
//sched_setscheduler(0, SCHED_OTHER, &sched);
//}
//
|
C
|
/*
* ascii.cpp
*
* Created on: 2011/05/03
* Author: mizu
*/
#include "kernel/ctype.h"
#include "kernel/libstr.h"
#include "kernel/basic.h"
int decto10(char* _str)
{
int cnt = 0;
int val = 0;
int magnifi = 1;
// 文字列のケタをカウントする
while(1)
{
if(_str[cnt] == 0x00) // NULLでカウンタ終了
break;
if(!((_str[cnt] >= '0' && _str[cnt] <= '9') || (_str[cnt] >= 'A' && _str[cnt] <= 'F'))) // 16進数チェック
return 0;
cnt++;
}
while(cnt > 0)
{
if(_str[cnt - 1] >= '0' && _str[cnt - 1] <= '9')
{
val += (_str[cnt - 1] - 0x30) * magnifi;
}
else if(_str[cnt - 1] >= 'A' && _str[cnt - 1] <= 'F')
{
val += (_str[cnt - 1] - 0x37) * magnifi;
}
magnifi *= 16;
cnt--;
}
return val;
}
|
C
|
#include<stdio.h>
#define LEN 20
struct names{
char first[LEN];
char last[LEN];
};
struct guys{
struct names handles;
char jobs[LEN];
char favfood[LEN];
float income;
};
int main(void){
struct guys fellow[2]={
{{"aa","bb"},
"student",
"chips",
1000.00
},
{{"cc","dd"},
"teacher",
"patatos",
2000.00
}
};//notice how to initialize......{},
struct guys * him;
printf("fellow 1: %p, fellow 2: %p\n", &fellow[0],&fellow[1]);
him=&fellow[0];
printf("him %p, him+1 %p:\n",him, him+1);
him++;
printf("him.income1 : %f, him.income2: %f:\n", him->income, (*him).income);
printf("him.handle.last: %s, him.job: %s\n", him->handles.last, him->jobs);
return 0;
}
|
C
|
//zoulang7.c
inherit ROOM;
void create()
{
set("short", "");
set("long", @LONG
һȣȶŽķ羰ÿɫӼ
Ҳߵľ룬ɫߣۻɫĵש棬Ѿߡū
ȥæԼ飬һ㵡˻Ⱦܵ
ˣеӵϢңŮӵϢҡ
LONG
);
set("no_fight",1);
set("exits", ([
"west" : __DIR__"zoulang6",
"east" : __DIR__"huilang",
"north" : __DIR__"xxshi1",
"south" : __DIR__"xxshi2",
]));
setup();
}
int valid_leave(object me, string dir)
{
if ((me->query("gender") =="") && dir =="south" )
return notify_fail("ٺ٣͵ŮӵԷ\n");
if ((me->query("gender") == "Ů") && dir == "north")
return notify_fail("ŮӻDzҪȥĺãͲżˡ\n");
return ::valid_leave(me, dir);
}
|
C
|
#ifndef LFR_LEXER_H
#define LFR_LEXER_H
#include <stdbool.h>
/* #include <Data_Structures/darray.h> */
#include <ast/identifier.h>
#include <lexer/tokens.h>
struct inpfile;
struct lexer {
struct {darray(struct token);} tokens;
struct {darray(int);} indices;
unsigned int tok_index;
struct inpfile *file;
struct info_ctx *info;
//! Denotes that the lexer has reached the end of its input
bool at_eof;
};
bool lexer_init(struct lexer *l, struct inpfile *f, struct info_ctx *info);
struct lexer *lexer_create(struct inpfile *f, struct info_ctx *info);
void lexer_deinit(struct lexer *l);
void lexer_destroy(struct lexer *l);
bool lexer_scan(struct lexer *l);
struct token *lexer_next_token(struct lexer *l);
struct token *lexer_lookahead(struct lexer *l, unsigned int num);
struct token *lexer_last_token_valid(struct lexer *l);
/**
* Consumes and returns the next token iff it's a token of @c type
*/
i_INLINE_DECL struct token *lexer_expect_token(struct lexer *l, enum token_type type)
{
struct token *tok = lexer_lookahead(l, 1);
return (tok && tok->type == type && lexer_next_token(l)) ? tok : NULL;
}
i_INLINE_DECL struct inplocation *lexer_last_token_location(struct lexer *l)
{
return &(lexer_last_token_valid(l))->location;
}
i_INLINE_DECL struct inplocation_mark *lexer_last_token_start(struct lexer *l)
{
return &(lexer_last_token_valid(l))->location.start;
}
i_INLINE_DECL struct inplocation_mark *lexer_last_token_end(struct lexer *l)
{
return &(lexer_last_token_valid(l))->location.end;
}
i_INLINE_DECL void lexer_inject_input_file(struct lexer *l, struct inpfile *f)
{
l->file = f;
}
void lexer_push(struct lexer *l);
void lexer_pop(struct lexer *l);
void lexer_rollback(struct lexer *l);
#endif
|
C
|
/*
int _flushbuf(c, stream)
char c;
FILE *stream;
If the standard I/O stream referenced by <stream>
is unbuffered, the character <c> is written
to the stream. Otherwise, the buffer associated
with the stream is flushed to the stream, the
buffer is reinitialized, and the character <c>
is written to the buffer.
To flush a buffer to its associated stream,
use fflush().
Arguments:
c Next character to be written
stream Pointer to stream information
Returns: int
The number of characters written, or EOF if error
Revision History:
06/12/84 kpm - Modified from old TSC _flushbuf()
05/14/85 ljn - Added support for update modes.
06/03/85 ljn - Set FLEOL if stream is a pipe (too).
*/
#include "machine.h"
#include <stdio.h>
int _flushbuf(c, stream)
unsigned char c;
register FILE *stream;
{
REGISTER int i;
char *malloc();
/* Buffered or unbuffered I/O ?? */
if (stream->_flag & _UNBUF)
{
i = 0;
/*
* If were open for append we may have to seek to EOF.
*/
if ((stream->_flag & _APPEND) &&
(!(stream->_flag & _LASTWRITE)))
{
if (!isatty(stream->_fd))
if (lseek(stream->_fd, 0L, 2) == -1)
i = EOF;
}
/* Unbuffered, just write the character */
if (i != EOF)
i = ((write(stream->_fd, &c, 1) == 1) ? c : EOF);
stream->_cnt = 0;
}
else
{
/* Is there a buffer associated with the stream ? */
if (stream->_base == NULL)
{
/* No, try to make one */
if ((stream->_base = malloc(BUFSIZ)) == NULL)
{
/* No buffer available, unbuffered I/O */
stream->_flag |= _UNBUF;
i = 0;
/*
* If were open for append we may have to seek to EOF.
*/
if ((stream->_flag & _APPEND) &&
(!(stream->_flag & _LASTWRITE)))
{
if (!isatty(stream->_fd))
if (lseek(stream->_fd, 0L, 2) == -1)
i = EOF;
}
if (i != EOF)
i = ((write(stream->_fd, &c, 1) == 1) ? c : EOF);
stream->_cnt = 0;
}
else
{
/* Got a buffer. Set up (don't write tho) */
stream->_cnt = BUFSIZ - 1;
stream->_ptr = stream->_base;
*stream->_ptr++ = c;
stream->_flag |= _BIGBUF |
(_termorpipe(stream->_fd)? _FLEOL : 0);
i = (int) c;
}
}
else
{
/*
Buffer already associated with the stream.
Flush it to the file.
If _LASTWRITE is clear, the buffer is empty.
(We either just did a seek or this is the first
operation on a stream that was "setbuf'd")
*/
i = 0;
if (stream->_flag & _LASTWRITE)
{
if (stream->_flag & _APPEND)
{
if (!isatty(stream->_fd))
if (lseek(stream->_fd, 0L, 2) == -1)
i = EOF;
}
if (i != EOF)
{
i = BUFSIZ - ((stream->_cnt > 0) ? stream->_cnt : 0);
if (write(stream->_fd, stream->_base, i) != i)
i = EOF;
else
{
/* Reset buffer and stuff char in it */
stream->_cnt = BUFSIZ - 1;
stream->_ptr = stream->_base;
*stream->_ptr++ = c;
i = c;
}
}
}
else
{
/* Reset buffer and stuff char in it */
stream->_cnt = BUFSIZ - 1;
stream->_ptr = stream->_base;
*stream->_ptr++ = c;
i = c;
}
}
}
return(i);
}
|
C
|
/*
** EPITECH PROJECT, 2018
** zappy
** File description:
** Connect_nbr command related
*/
#include <stdbool.h>
#include "game.h"
#include "entity.h"
bool respond_connect_nbr(game_t *game, player_t *player, char *argument)
{
list_t *tmp = player->entity.team->eggs->head;
int eggs = 0;
(void)game;
if (argument) {
return (false);
}
while (tmp) {
eggs++;
tmp = tmp->next;
}
fprintf(player->stream, "%i\n", (int)player->entity.team->slots + eggs);
return (true);
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE *fp;
char a[10];
printf("Enter Data:\n");
fp=fopen("BMSCE.txt","w");
fgets(a,6,stdin);
fclose(fp);
printf("\n Output\n");
fp = fopen("BMSCE.txt","r");
if(fp == NULL)
{
printf("Error");
exit(1);
}
fgets(a,6,fp);
puts(a);
fclose(fp);
getch();
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
//makro pre jednoduchsiu kontrolu navratovej hodnoty volania funkcie a vypis popisu chyby
#define CHECK( command ) if( ! (command) ) { fprintf(stderr, "Error: '%s' at %s line %d: %s\n", #command, __FILE__, __LINE__, strerror(errno)); exit(EXIT_FAILURE); }
//typ reprezentujuci hodnotu prepinaca (zadany, nezadany)
typedef enum {
UNSET = 0,
SET = 1
} OPTION;
//nastavenia programu (podla vstupnych parametrov)
typedef struct {
OPTION help;
char * outputFile; //cesta ku vystupnemu suboru
} SETTINGS;
//vypis help-u a ukoncenie programu
void printHelpAndExit(FILE * stream, int exitCode) {
fprintf(stream, "Usage: presmerovanie (-h | vystupny_subor)\n");
fprintf(stream, "Program vypise do suboru vystupny_subor procesy pouzivatela\n");
fprintf(stream, "Prepinac -h vypise help\n");
exit(exitCode);
}
//parsovanie vstupnych argumentov programu
void parseArguments(int argc, char*argv[], SETTINGS * settings) {
int opt;
//inicializacia nastaveni na defaultne hodnoty
settings->help = UNSET;
settings->outputFile = NULL;
//parsovanie argumentov zacinajucich pomlckov
do {
opt = getopt(argc, argv, ":h");
switch(opt) {
case 'h':
settings->help = SET;
break;
case ':':
fprintf(stderr, "CHYBA: nezadany argument volby '%c'\n", optopt);
printHelpAndExit(stderr, EXIT_FAILURE);
break;
case '?':
fprintf(stderr, "CHYBA: neznama volba '%c'\n", optopt);
printHelpAndExit(stderr, EXIT_FAILURE);
break;
}
}while(opt != -1);
//parsovanie argumentov bez pomlcky
if( settings->help == UNSET ) {
if( argv[optind] == NULL ) {
fprintf(stderr, "CHYBA: nezadany vystupny subor\n");
printHelpAndExit(stderr, EXIT_FAILURE);
}
if( argv[optind+1] != NULL ) {
fprintf(stderr, "CHYBA: prilis vela parametrov\n");
printHelpAndExit(stderr, EXIT_FAILURE);
}
settings->outputFile = argv[optind];
}
}
int main(int argc, char * argv[]) {
SETTINGS settings;
parseArguments(argc, argv, &settings);
if( settings.help == SET ) {
printHelpAndExit(stdout, EXIT_SUCCESS);
}
//doplnte otovorenie suboru na zapis
int fd;
CHECK( (fd = open(settings.outputFile, O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR )) != -1 );
//zatvorte standardny vystup
CHECK( close(STDOUT_FILENO) != -1 );
//vytvorte kopiu deskriptoru suboru tak, aby bola kopia bola v tabulke otvorenych suborov na pozicii standardneho vystup
CHECK( dup2(fd, STDOUT_FILENO) != -1 );
//zatvorte deskriptor suboru
CHECK( close(fd) != -1);
printf("Zoznam aktualnych procesov:\n");
fflush(stdout);
//doplte nahradenie obrazu aktualneho procesu, obrazom procesu "ps u"
execlp("ps","ps","u",NULL);
perror("Execlp");
return EXIT_FAILURE;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int utn_getString( char *msg,
char *msgError,
int minimo,
int maximo,
int reintentos,
char *resultado);
int utn_isValidNumber(char *str);
int utn_getNumber( char *msg,
char *msgError,
int minimo,
int maximo,
int reintentos,
int* resultado);
int main()
{
}
int utn_getNumber( char *msg,
char *msgError,
int minimo,
int maximo,
int reintentos,
int* resultado)
{
int retorno = -1;
char buffer[18];
int bufferInt;
if(msg != NULL && msgError !=NULL && minimo<maximo && )//FALTA VALIDAR
{
if(utn_getString(msg,msgError,1,16,reintentos,buffer)==0)
{
if(utn_isValidNumber(buffer))
{
bufferInt = atoi(buffer);
if(bufferInt >= minimo && bufferInt <= maximo)
{
*resultado = bufferInt;
retorno = 0;
}
}
}
}
return retorno;
}
int utn_isValidNumber(char *str)
{
return 1;
}
int utn_getString( char *msg,
char *msgError,
int minimo,
int maximo,
int reintentos,
char *resultado)
{
strncpy(resultado, "1234",5);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define beat(x) "\x01\x02\x00"[(x)]
#define unbeat(x) "\x02\x00\x01"[(x)]
#define max(x,y) ((x) > (y) ? (x) : (y))
#define min(x,y) ((x) < (y) ? (x) : (y))
#define throws 100000
#define algos_n 3
#define vals_n 10
#define choose(x,y,z,r,a) (vals_n * vals_n * 2 * 3 * x + vals_n * 2 * 3 * y + 2 * 3 * z + 3 * r + a)
typedef struct {
int (*fx)(int, int, int, int);
int success[vals_n * vals_n * vals_n * 2 * 3];
} alg_t;
char in[100];
int t = 0;
unsigned int hands_a[3] = {0, 0, 0};
unsigned int hands_b[3] = {0, 0, 0};
unsigned int *history_a, *history_b;
alg_t algos[algos_n];
int best_alg = 0;
int best_x = 0, best_y = 0, best_z = 0;
int best_rev = 0, best_ahd = 0;
double alg_freq_t[] = {0, 0.001, 0.01};
int alg_freq_i[] = {0, 1};
int alg_pattern_d[] = {1, 5, 10, 25, 50, 100, 1000, 10000, 50000, 100000};
double alg_pattern_t[] = {0, 0.001, 0.01};
int alg_pattern_w[] = {-1, 0, 1};
int random_throw () {
return random () % 3;
}
int comp_hist (unsigned int a, unsigned int b, unsigned int len, double threshold, int which) {
unsigned int i;
double unmatched = 0;
for (i = 0; i < len; ++i) {
if ((which <= 0 && history_a[a+i] != history_a[b+i]) ||
(which >= 0 && history_b[a+i] != history_b[b+i])) {
++unmatched;
}
if (unmatched / len > threshold) {
return 1;
}
}
return 0;
}
int min_freq (unsigned int *hands, double threshold) {
unsigned int i;
double min = min (min (hands[0], hands[1]), hands[2]);
for (i = 0; i < 3; ++i) {
if (0 == min || abs (min - hands[i]) / min <= threshold) {
return i;
}
}
return random_throw ();
}
int max_freq (unsigned int *hands, double threshold) {
unsigned int i;
double max = max (max (hands[0], hands[1]), hands[2]);
for (i = 0; i < 3; ++i) {
if (0 == max || abs (max - hands[i]) / max <= threshold) {
return i;
}
}
return random_throw ();
}
int alg_freq (int t_x, int i_x, int xyzzz, int rev) {
if (t_x >= 3 || i_x >= 2 || xyzzz)
return -1;
int ret;
if (alg_freq_i[i_x]) {
if (rev) {
ret = min_freq (hands_a, alg_freq_t[t_x]);
} else {
ret = min_freq (hands_b, alg_freq_t[t_x]);
}
} else {
if (rev) {
ret = max_freq (hands_a, alg_freq_t[t_x]);
} else {
ret = max_freq (hands_b, alg_freq_t[t_x]);
}
}
return beat (ret);
}
int alg_pattern (int d_x, int t_x, int w_x, int rev) {
if (d_x >= 10 || t_x >= 3 || w_x >= 3)
return -1;
unsigned int max, len, last = 1;
int ret;
max = min (alg_pattern_d[d_x], t);
for (len = 1; 2 * len <= max; ++len) {
unsigned int x, match = 0;
for (x = max (last, len); len + x <= max; ++x) {
if (0 == comp_hist (0, x, len, alg_pattern_t[t_x], alg_pattern_w[w_x])) {
match = x;
break;
}
}
if (! match)
break;
last = match;
}
if (rev)
ret = history_a[last - 1];
else
ret = history_b[last - 1];
return beat (ret);
}
int alg_random (int xyzzx, int xyzzy, int xyzzz, int rev) {
if (xyzzx || xyzzy || xyzzz || rev)
return -1;
return random_throw ();
}
int throw (int alg, int x, int y, int z, int rev, int ahd) {
int a = algos[alg].fx (x, y, z, rev);
if (0 == ahd)
a = beat (a);
else if (2 == ahd)
a = unbeat (a);
if (rev)
a = beat (a);
return a;
}
void alloc_fail_die () {
if (NULL == history_a || NULL == history_b) {
fprintf (stderr, "I NEED MEMORY!!!\n");
exit (1);
}
}
void grade (int b) {
int i, j, k, l;
int rev, ahd;
best_alg = best_x = best_y = best_z = best_rev = best_ahd = 0;
int best_suc;
int best_suc_undef = 1;
for (i = 0; i < algos_n; ++i) {
for (j = 0; j < vals_n; ++j) {
for (k = 0; k < vals_n; ++k) {
for (l = 0; l < vals_n; ++l) {
for (rev = 0; rev < 2; ++rev) {
for (ahd = 0; ahd < 3; ++ahd) {
int ret = throw (i, j, k, l, rev, ahd);
int* suc = algos[i].success + choose (j, k, l, rev, ahd);
if (ret >= 0) {
if (ret == beat (b)) {
*(suc) += 1;
} else if (b == beat (ret)) {
*(suc) -= 1;
}
}
if (best_suc_undef || *(suc) > best_suc) {
best_suc_undef = 0;
best_alg = i;
best_x = j;
best_y = k;
best_z = l;
best_rev = rev;
best_ahd = ahd;
best_suc = *(suc);
}
}
}
}
}
}
}
}
int fire () {
if (0 == t)
return random_throw ();
return throw (best_alg, best_x, best_y, best_z, best_rev, best_ahd);
}
int main () {
int a, b;
int i, j, k, l;
int rev, ahd;
srand (time (0));
setvbuf (stdin, NULL, _IONBF, 0);
setvbuf (stdout, NULL, _IONBF, 0);
history_a = calloc (throws + 1, sizeof (*history_a));
history_b = calloc (throws + 1, sizeof (*history_b));
alloc_fail_die ();
algos[0].fx = &alg_freq;
algos[1].fx = &alg_pattern;
algos[2].fx = &alg_random;
for (i = 0; i < algos_n; ++i) {
for (j = 0; j < vals_n; ++j) {
for (k = 0; k < vals_n; ++k) {
for (l = 0; l < vals_n; ++l) {
for (rev = 0; rev < 2; ++rev) {
for (ahd = 0; ahd < 3; ++ahd) {
*(algos[i].success + choose (j, k, l, rev, ahd)) = 0;
}
}
}
}
}
}
while (NULL != fgets (in, sizeof (in), stdin)) {
if (0 == strncmp (in, "d", 1)) {
break;
} else if (0 == strncmp (in, "g", 1)) {
printf ("%d\n", fire());
} else if (0 == strncmp (in, "o", 1)) {
in[9] = in[11] = 0;
a = atoi (&in[8]);
b = atoi (&in[10]);
grade (b);
memmove (history_a + 1, history_a, throws * sizeof(*history_a));
memmove (history_b + 1, history_b, throws * sizeof(*history_b));
alloc_fail_die ();
history_a[0] = a;
history_b[0] = b;
++hands_a[a];
++hands_b[b];
if (t < throws) {
++t;
}
}
}
free (history_a);
free (history_b);
history_a = NULL;
history_b = NULL;
return 0;
}
|
C
|
#include <stdio.h>
void sum_array(int *A, int *B, int *C, int size)
{
for (int i = 0; i < size; i++)
*(C + i) = *(A + i) + *(B + i);
}
int main()
{
int n;
int ary[1000];
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
scanf("%d", &ary[i]);
}
sum_array(ary, ary + 1, ary + 1, n - 1);
for (int i = 0; i < n; i++)
{
printf("%d ", ary[i]);
}
printf("\n");
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<string.h>
#include<pthread.h>
#include <sys/time.h>
static inline double get_time()
{
struct timeval t;
gettimeofday(&t, NULL);
return t.tv_sec + t.tv_usec*1e-6;
}
#define B_SIZE 4096
#define N_REP 1000
#define REPETITIONS 50
int rep = N_REP;
typedef struct wait_mutex {
volatile int ready;
pthread_mutex_t mut;
pthread_cond_t snd;
pthread_cond_t rcv;
} wait_mutex_t;
void send(wait_mutex_t * w){
pthread_mutex_lock(&w -> mut);
while (w -> ready) {
pthread_cond_wait(&w -> snd, &w-> mut);
}
w -> ready = 1;
pthread_mutex_unlock(&w -> mut);
pthread_cond_signal(&w -> rcv);
}
void recv(wait_mutex_t * w){
pthread_mutex_lock(&w -> mut);
while (!w -> ready) {
pthread_cond_wait(&w -> rcv, &w-> mut);
}
w -> ready = 0;
pthread_mutex_unlock(&w -> mut);
pthread_cond_signal(&w -> snd);
}
void write_buff(int *b) {
for(int i = 0; i < B_SIZE; i++) {
b[i] = i + 10;
}
}
void compute_buff(int *b) {
for(int i = 0; i < B_SIZE; i++) {
b[i] = log(b[i]);
}
}
void read_buff(int *b) {
int buf[B_SIZE];
memcpy(buf, b, sizeof(int) * B_SIZE);
// for(int i = 0; i < B_SIZE; i++) {
// printf("%d ", b[i]);
// }
// printf("\n");
}
wait_mutex_t srv_rdy_A = {0, PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER, PTHREAD_COND_INITIALIZER};
wait_mutex_t srv_rdy_B = {0, PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER, PTHREAD_COND_INITIALIZER};
wait_mutex_t sink_rdy_A = {0, PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER, PTHREAD_COND_INITIALIZER};
wait_mutex_t sink_rdy_B = {0, PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER, PTHREAD_COND_INITIALIZER};
wait_mutex_t src_cpy_A = {0, PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER, PTHREAD_COND_INITIALIZER};
wait_mutex_t src_cpy_B = {0, PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER, PTHREAD_COND_INITIALIZER};
wait_mutex_t srv_cpy_A = {0, PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER, PTHREAD_COND_INITIALIZER};
wait_mutex_t srv_cpy_B = {0, PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER, PTHREAD_COND_INITIALIZER};
int buffA[B_SIZE];
int buffB[B_SIZE];
void *source(void *arg){
int n_rep = rep;
while(n_rep--){
recv(&srv_rdy_A);
write_buff((int *)buffA);
send(&src_cpy_A);
recv(&srv_rdy_B);
write_buff((int *)buffB);
send(&src_cpy_B);
}
return NULL;
}
void *service(void *arg){
int n_rep = rep;
send(&srv_rdy_A);
send(&srv_rdy_B);
while(n_rep--){
//send(&srv_rdy_A);
recv(&src_cpy_A);
compute_buff((int *)buffA);
recv(&sink_rdy_A);
send(&srv_cpy_A);
send(&srv_rdy_A);
//send(&srv_rdy_B);
recv(&src_cpy_B);
compute_buff((int *)buffB);
recv(&sink_rdy_B);
send(&srv_cpy_B);
send(&srv_rdy_B);
}
return NULL;
}
void *sink(void *arg){
int n_rep = rep;
while(n_rep--){
send(&sink_rdy_A);
recv(&srv_cpy_A);
read_buff((int *)buffA);
send(&sink_rdy_B);
recv(&srv_cpy_B);
read_buff((int *)buffB);
}
return NULL;
}
void reset() {
srv_rdy_A.ready = 0;
srv_rdy_B.ready = 0;
sink_rdy_A.ready = 0;
sink_rdy_B.ready = 0;
src_cpy_A.ready = 0;
src_cpy_B.ready = 0;
srv_cpy_A.ready = 0;
srv_cpy_B.ready = 0;
}
int main(int argc, char * argv[]){
pthread_t p_src, p_srv;
double time = 0;
double time_diff = 0;
double time_old = 0;
double var = 0;
double start = 0;
double end = 0;
for(int i=0; i<REPETITIONS; i++){
reset();
start = get_time();
pthread_create(&p_src, NULL, &source, NULL);
pthread_create(&p_srv, NULL, &service, NULL);
sink(NULL);
pthread_join(p_src, NULL);
pthread_join(p_srv, NULL);
end = get_time();
time_diff = end - start;
time_old = time;
time += (time_diff - time)/(i+1);
var += (time_diff - time) * (time_diff - time_old);
}
printf("mean: %f\n", time);
printf("stddev: %f\n", REPETITIONS<=1? 0: sqrt(var / (REPETITIONS - 1)));
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "fixedXor.h"
int score(char *s);
int main(){
char b[68];
printf("Enter a hex string: ");
fgets(b, 68, stdin);
char output[68]; int max=0;
for(int i=48; i<127; i++){
printf("%s \n", other_hexor(i, b));
if(score(other_hexor(i, b))>max){
max=score(other_hexor(i, b));
strcpy(output, other_hexor(i, b));
}
}
puts(output);
return 0;
}
int score(char *s){
int count=0;
int l=(int) strlen(s);
char freq_chars[]="ULDRHSNIOATE";
for(int i=0; i<l; i++){
for(int j=0; j<12 ;j++){
if(toupper(s[i])==freq_chars[j]){
count+=j;
}
}
}
return count;
}
|
C
|
#include "setsid.h"
int main()
{
if(fork() != 0)
printf("exit success\n");
if(setsid() == -1)
printf("setsid\n");
printf("PID=%ld, PGID = %ld, SID = %ld\n", (long)getpid(),(long)getpgrp(),(long)getsid(0));
if(open("/dev/tty", O_RDWR) == -1)
printf("open /dev/tty\n");
}
|
C
|
/** \file
* \ingroup hqbits
*
* $HopeName: HQNc-standard!export:hqbitvector.h(EBDSDK_P.1) $
*
* Copyright (C) 2008-2014 Global Graphics Software Ltd. All rights reserved.
* This source code contains the confidential and trade secret information of
* Global Graphics Software Ltd. It may not be used, copied or distributed
* for any reason except as set forth in the applicable Global Graphics
* license agreement.
*
* \brief
* Macros implementing bit vectors.
*/
#ifndef __HQBITVECTOR_H__
#define __HQBITVECTOR_H__
/** \brief An unsigned type used to implement bit vectors. */
typedef uint32 bitvector_element_t ;
/** \brief Right shift to convert bit indices to element indices.
The relationship:
(1 << (BITVECTOR_SHIFT_ELEMENTS - 3)) == sizeof(bitvector_element_t)
should always hold. */
#define BITVECTOR_SHIFT_ELEMENTS (3 + 2)
/** \brief Bit vector element size in bits. */
#define BITVECTOR_ELEMENT_BITS (1u << BITVECTOR_SHIFT_ELEMENTS)
/** \brief Mask to extract bit index within element from bit index. */
#define BITVECTOR_ELEMENT_MASK (BITVECTOR_ELEMENT_BITS - 1u)
/** \brief Bitvector element containing all zeros. */
#define BITVECTOR_ELEMENT_ZEROS (bitvector_element_t)0
/** \brief Bitvector element containing all ones. */
#define BITVECTOR_ELEMENT_ONES (bitvector_element_t)(~BITVECTOR_ELEMENT_ZEROS)
/** \brief Size of a bitvector containing \c length_ bits, in elements.
\param length_ Length of the bitvector, in bits.
*/
#define BITVECTOR_SIZE_ELEMENTS(length_) \
(((length_) + BITVECTOR_ELEMENT_BITS - 1u) >> BITVECTOR_SHIFT_ELEMENTS)
/** \brief Size of a bitvector containing \c length_ bits, in bytes.
\param length_ Length of the bitvector, in bits.
*/
#define BITVECTOR_SIZE_BYTES(length_) \
(BITVECTOR_SIZE_ELEMENTS(length_) << 2)
/** \brief Declare a bitvector variable or field.
\param name_ The name of the bitvector name or field.
\param size_ A constant expression, giving the number of bits in the vector.
This macro can be used anywhere that a variable or parameter declaration
can occur.
*/
#define bitvector_t(name_, size_) \
bitvector_element_t name_[BITVECTOR_SIZE_ELEMENTS(size_)]
/** \brief Set all of the bits in a bit vector to a value.
\param vec_ The bitvector to clear.
\param size_ The number of bits in the vector.
\param value_ This should be \c BITVECTOR_ELEMENT_ZEROS to clear the
vector, \c BITVECTOR_ELEMENT_ONES to set the vector.
*/
#define BITVECTOR_SET_ELEMENTS(vec_, size_, value_) MACRO_START \
unsigned int _i_ = BITVECTOR_SIZE_ELEMENTS(size_) ; \
HQASSERT(_i_ > 0, "Bitvector has no elements") ; \
do { \
(vec_)[--_i_] = (value_) ; \
} while ( _i_ > 0 ) ; \
MACRO_END
/** \brief Copy the contents of one bit vector to another, with an optional
exclusive-or operation.
\param dest_ The destination bitvector.
\param src_ The source bitvector.
\param size_ The number of bits in the vector.
\param flip_ A boolean, indicating if the destination should be the inverse
of the source.
*/
#define BITVECTOR_COPY_FLIP(dest_, src_, size_, flip_) MACRO_START \
unsigned int _i_ = BITVECTOR_SIZE_ELEMENTS(size_) ; \
HQASSERT(_i_ > 0, "Bitvector has no elements") ; \
do { \
--_i_ ; \
(dest_)[_i_] = (src_)[_i_] ^ ((bitvector_element_t)!(flip_) - 1u) ; \
} while ( _i_ > 0 ) ; \
MACRO_END
/** \brief Clear a single bit in a bit vector.
\param vec_ The bitvector to modify.
\param bit_ The bit index to clear.
*/
#define BITVECTOR_CLEAR(vec_, bit_) \
(vec_)[(bit_) >> BITVECTOR_SHIFT_ELEMENTS] &= ~((bitvector_element_t)1 << (BITVECTOR_ELEMENT_MASK & (bit_)))
/** \brief Set a single bit in a bit vector.
\param vec_ The bitvector to modify.
\param bit_ The bit index to set.
*/
#define BITVECTOR_SET(vec_, bit_) \
(vec_)[(bit_) >> BITVECTOR_SHIFT_ELEMENTS] |= ((bitvector_element_t)1 << (BITVECTOR_ELEMENT_MASK & (bit_)))
/** \brief Test if a bit in a bit vector is set.
\param vec_ The bitvector to test.
\param bit_ The bit index to test.
*/
#define BITVECTOR_IS_SET(vec_, bit_) \
(((vec_)[(bit_) >> BITVECTOR_SHIFT_ELEMENTS] & ((bitvector_element_t)1 << (BITVECTOR_ELEMENT_MASK & (bit_)))) != 0)
/** \brief Return a mask which can be used to test and isolate a bit in an
identified element.
\param element_ The element index being processed.
\param bit_ The bit index to derive a mask for.
The return value is a mask that is zero if \c bit is not in \c element, or
set to the bit mask within \c element if it is.
This can be used to implement bulk operations in clients, without having
to test if particular bits that should be treated specially are present in
each element. */
#define BITVECTOR_ELEMENT_BIT_MASK(element_, bit_) \
(((element_) == ((bit_) >> BITVECTOR_SHIFT_ELEMENTS)) << ((bit_) & BITVECTOR_ELEMENT_MASK))
/** \brief Iterator structure for walking bit vectors.
This structure is transparent; the element index and the mask can be used
by the client to extract and manipulate words from the bitvector
directly. */
typedef struct bitvector_iterator_t {
int element ; /**< Index of element. Note this must be signed. */
unsigned int bit ; /**< Index of bit (top bit if element iteration). */
bitvector_element_t mask ; /**< Mask to extract bit(s) in iterator. */
} bitvector_iterator_t ;
/** \brief Initialise per-bit iteration over a bit vector using an element,
mask pair.
\param iterator_ A \c bitvector_iterator_t variable to initialise.
\param size_ The size of the bit vector.
This macro is written such that it can be used in a for-loop
initialisation statement. Note that the iteration goes from the highest to
lowest bits. The iterator will be initialised correctly for bitvectors of
size zero or more. The idiom will usually look like this:
\code
bitvector_iterator_t iterator ;
bitvector_t(vector, MAXBITS) ;
for ( BITVECTOR_ITERATE_BITS(iterator, bits_used) ;
BITVECTOR_ITERATE_BITS_MORE(iterator) ;
BITVECTOR_ITERATE_BITS_NEXT(iterator) ) {
if ( (vector[iterator.element] & iterator.mask) != 0 ) {
...bit iterator.bit is set...
}
}
\endcode
\see BITVECTOR_ITERATE_BITS_MORE, BITVECTOR_ITERATE_BITS_NEXT
*/
#define BITVECTOR_ITERATE_BITS(iterator_, size_) \
(iterator_).bit = (size_) - 1, \
(iterator_).element = (int)BITVECTOR_SIZE_ELEMENTS(size_) - 1, \
(iterator_).mask = ((bitvector_element_t)1 << ((iterator_).bit & BITVECTOR_ELEMENT_MASK))
/** \brief Test if per-bit iteration over a bitvector using an element, mask
pair is complete.
\param iterator_ The \c bitvector_iterator_t variable to test.
This macro is written such that it can be used in a for-loop condition
statement. Note that the iteration goes from the highest to lowest bits.
\see BITVECTOR_ITERATE_BITS, BITVECTOR_ITERATE_BITS_NEXT
*/
#define BITVECTOR_ITERATE_BITS_MORE(iterator_) ((iterator_).element >= 0)
/** \brief Continue per-bit iteration over a bit vector using an element, mask
pair.
\param iterator_ The \c bitvector_iterator_t variable to step.
This macro is written such that it can be used in a for-loop continuation
statement. Note that the iteration goes from the highest to lowest bits.
\see BITVECTOR_ITERATE_BITS, BITVECTOR_ITERATE_BITS_MORE
*/
#define BITVECTOR_ITERATE_BITS_NEXT(iterator_) \
(iterator_).bit -= 1, \
(iterator_).element -= (int)((iterator_).mask & 1), \
(iterator_).mask = ((iterator_).mask >> 1) | ((iterator_).mask << (BITVECTOR_ELEMENT_BITS - 1u))
/** \brief Initialise multi-bit iteration over a bit vector using an element,
mask pair.
\param iterator_ A \c bitvector_iterator_t variable to initialise.
\param size_ The size of the bit vector.
\param chunk_ The number of bits to iterate at a time. This should be
a power of 2.
This macro is written such that it can be used in a for-loop
initialisation statement. Note that the iteration goes from the highest to
lowest bits. The iterator will be initialised correctly for bitvectors of
size zero or more. The idiom will usually look like this:
\code
bitvector_iterator_t iterator ;
bitvector_t(vector, MAXLEN * 2) ;
for ( BITVECTOR_ITERATE_BITS_N(iterator, bits_used, 2) ;
BITVECTOR_ITERATE_BITS_MORE(iterator) ;
BITVECTOR_ITERATE_BITS_NEXT_N(iterator, 2) ) {
int chunk = ((vector[iterator.element] & iterator.mask) >> iterator.bit) ;
...
}
\endcode
\see BITVECTOR_ITERATE_BITS_MORE, BITVECTOR_ITERATE_BITS_NEXT_N
*/
#define BITVECTOR_ITERATE_BITS_N(iterator_, size_, chunk_) \
HQASSERT_EXPR(((chunk_) & ((chunk_) - 1)) == 0 && (size_) % (chunk_) == 0, \
"Iteration chunk or size mismatch", \
((iterator_).bit = (size_) - (chunk_), \
(iterator_).element = (int)BITVECTOR_SIZE_ELEMENTS(size_) - 1, \
(iterator_).mask = ((bitvector_element_t)((1 << (chunk_)) - 1) << ((iterator_).bit & BITVECTOR_ELEMENT_MASK))))
/** \brief Continue multi-bit iteration over a bit vector using an element,
mask pair.
\param iterator_ The \c bitvector_iterator_t variable to step.
\param chunk_ The number of bits to iterate at a time. This should be
a power of 2.
This macro is written such that it can be used in a for-loop continuation
statement. Note that the iteration goes from the highest to lowest bits.
\see BITVECTOR_ITERATE_BITS_MORE, BITVECTOR_ITERATE_BITS_N
*/
#define BITVECTOR_ITERATE_BITS_NEXT_N(iterator_, chunk_) \
HQASSERT_EXPR(((chunk_) & ((chunk_) - 1)) == 0 && (iterator_).bit % (chunk_) == 0, \
"Iteration chunk or size mismatch", \
((iterator_).bit -= (chunk_), \
(iterator_).element -= (int)((iterator_).mask & 1), \
(iterator_).mask = (((iterator_).mask >> (chunk_)) | \
((iterator_).mask << (BITVECTOR_ELEMENT_BITS - (chunk_))))))
/** \brief Initialise per-element iteration over a bit vector using an
element, mask pair.
\param iterator_ The \c bitvector_iterator_t variable to initialise.
\param size_ The size of the bit vector.
This macro is written such that it can be used in a for-loop
initialisation statement. Note that the iteration goes from the highest to
lowest element. The iterator will be initialised correctly for bitvectors of
size zero or more. The iteration idiom will usually look like this:
\code
bitvector_iterator_t iterator ;
bitvector_t(vector, MAXBITS) ;
for ( BITVECTOR_ITERATE_ELEMENTS(iterator, bits_used) ;
BITVECTOR_ITERATE_ELEMENTS_MORE(iterator) ;
BITVECTOR_ITERATE_ELEMENTS_NEXT(iterator) ) {
if ( (vector[iterator.element] & iterator.mask) == iterator.mask ) {
...all bits set...
} else if ( (vector[iterator.element] & iterator.mask) == 0 ) {
...no bits set...
} ...etc...
}
\endcode
\see BITVECTOR_ITERATE_ELEMENTS_MORE, BITVECTOR_ITERATE_ELEMENTS_NEXT
*/
#define BITVECTOR_ITERATE_ELEMENTS(iterator_, size_) \
(iterator_).bit = ((size_) - 1), \
(iterator_).element = (int)BITVECTOR_SIZE_ELEMENTS(size_) - 1, \
(iterator_).mask = (BITVECTOR_ELEMENT_ONES >> ((BITVECTOR_ELEMENT_BITS - (size_)) & BITVECTOR_ELEMENT_MASK))
/** \brief Test if per-element iteration over a bitvector using an element,
mask pair is complete.
\param iterator_ The \c bitvector_iterator_t variable to test.
The bits index to test. This macro is written such that it can be used in
a for-loop condition statement. Note that the iteration goes from the
highest to lowest element.
\see BITVECTOR_ITERATE_ELEMENTS, BITVECTOR_ITERATE_ELEMENTS_NEXT
*/
#define BITVECTOR_ITERATE_ELEMENTS_MORE(iterator_) ((iterator_).element >= 0)
/** \brief Continue per-element iteration over a bit vector using an element,
mask pair.
\param iterator_ The \c bitvector_iterator_t variable to step.
This macro is written such that it can be used in a for-loop continuation
statement. Note that the iteration goes from the highest to lowest
element.
\see BITVECTOR_ITERATE_ELEMENTS, BITVECTOR_ITERATE_ELEMENTS_MORE
*/
#define BITVECTOR_ITERATE_ELEMENTS_NEXT(iterator_) \
(iterator_).bit = ((iterator_).bit & ~BITVECTOR_ELEMENT_MASK) - 1, \
(iterator_).element -= 1, (iterator_).mask = BITVECTOR_ELEMENT_ONES
#endif /* __BITVECTOR_H__ */
|
C
|
/* Ofront+ 0.9 -xtspkae */
#include "SYSTEM.h"
#include "Platform.h"
static CHAR Console_line[128];
static INTEGER Console_pos;
export void Console_Bool (BOOLEAN b);
export void Console_Char (CHAR ch);
export void Console_Flush (void);
export void Console_Hex (INTEGER i);
export void Console_Int (INTEGER i, INTEGER n);
export void Console_Ln (void);
export void Console_LongHex (LONGINT i);
export void Console_LongInt (LONGINT i, INTEGER n);
export void Console_Read (CHAR *ch);
export void Console_ReadLine (CHAR *line, INTEGER line__len);
export void Console_String (CHAR *s, INTEGER s__len);
/*============================================================================*/
void Console_Flush (void)
{
INTEGER error;
error = Platform_Write(1, (Platform_MemAdr)((LONGINT)Console_line), Console_pos);
Console_pos = 0;
}
/*----------------------------------------------------------------------------*/
void Console_Char (CHAR ch)
{
if (Console_pos == 128) {
Console_Flush();
}
Console_line[__X(Console_pos, 128)] = ch;
Console_pos += 1;
if (ch == 0x0a) {
Console_Flush();
}
}
/*----------------------------------------------------------------------------*/
void Console_String (CHAR *s, INTEGER s__len)
{
INTEGER i;
__DUP(s, s__len);
i = 0;
while (s[__X(i, s__len)] != 0x00) {
Console_Char(s[__X(i, s__len)]);
i += 1;
}
__DEL(s);
}
/*----------------------------------------------------------------------------*/
void Console_Int (INTEGER i, INTEGER n)
{
CHAR s[16];
INTEGER i1, k;
if (i == __LSHL((INTEGER)1, 31, INTEGER)) {
__MOVE("8463847412", s, 11);
k = 10;
} else {
i1 = __ABS(i);
s[0] = (CHAR)((INTEGER)__MOD(i1, 10) + 48);
i1 = __DIV(i1, 10);
k = 1;
while (i1 > 0) {
s[__X(k, 16)] = (CHAR)((INTEGER)__MOD(i1, 10) + 48);
i1 = __DIV(i1, 10);
k += 1;
}
}
if (i < 0) {
s[__X(k, 16)] = '-';
k += 1;
}
while (n > k) {
Console_Char(' ');
n -= 1;
}
while (k > 0) {
k -= 1;
Console_Char(s[__X(k, 16)]);
}
}
/*----------------------------------------------------------------------------*/
void Console_LongInt (LONGINT i, INTEGER n)
{
CHAR s[24];
LONGINT i1;
INTEGER k;
if (i == __LSHL((LONGINT)1, 63, LONGINT)) {
__MOVE("8085774586302733229", s, 20);
k = 19;
} else {
i1 = __ABS(i);
s[0] = (CHAR)(__MOD(i1, 10) + 48);
i1 = __DIV(i1, 10);
k = 1;
while (i1 > 0) {
s[__X(k, 24)] = (CHAR)(__MOD(i1, 10) + 48);
i1 = __DIV(i1, 10);
k += 1;
}
}
if (i < 0) {
s[__X(k, 24)] = '-';
k += 1;
}
while (n > k) {
Console_Char(' ');
n -= 1;
}
while (k > 0) {
k -= 1;
Console_Char(s[__X(k, 24)]);
}
}
/*----------------------------------------------------------------------------*/
void Console_Ln (void)
{
Console_String(Platform_newLine, 2);
}
/*----------------------------------------------------------------------------*/
void Console_Bool (BOOLEAN b)
{
if (b) {
Console_String((CHAR*)"TRUE", 5);
} else {
Console_String((CHAR*)"FALSE", 6);
}
}
/*----------------------------------------------------------------------------*/
void Console_Hex (INTEGER i)
{
INTEGER k, n;
k = -28;
while (k <= 0) {
n = __MASK(__ASH(i, k, INTEGER), -16);
if (n <= 9) {
Console_Char((CHAR)(48 + n));
} else {
Console_Char((CHAR)(55 + n));
}
k += 4;
}
}
/*----------------------------------------------------------------------------*/
void Console_LongHex (LONGINT i)
{
INTEGER k, n;
k = -60;
while (k <= 0) {
n = __MASK((INTEGER)__ASH(i, k, LONGINT), -16);
if (n <= 9) {
Console_Char((CHAR)(48 + n));
} else {
Console_Char((CHAR)(55 + n));
}
k += 4;
}
}
/*----------------------------------------------------------------------------*/
void Console_Read (CHAR *ch)
{
INTEGER n, error;
Console_Flush();
error = Platform_ReadBuf(0, (BYTE*)(void*)&*ch, 1, &n);
if (n != 1) {
*ch = 0x00;
}
}
/*----------------------------------------------------------------------------*/
void Console_ReadLine (CHAR *line, INTEGER line__len)
{
INTEGER i;
CHAR ch;
Console_Flush();
i = 0;
Console_Read(&ch);
while ((i < line__len - 1 && ch != 0x0a) && ch != 0x00) {
line[__X(i, line__len)] = ch;
i += 1;
Console_Read(&ch);
}
line[__X(i, line__len)] = 0x00;
}
/*----------------------------------------------------------------------------*/
export void *Console__init(void)
{
__DEFMOD;
__IMPORT(Platform__init);
__REGMOD("Console", 0);
__REGCMD("Flush", Console_Flush);
__REGCMD("Ln", Console_Ln);
/* BEGIN */
Console_pos = 0;
__ENDMOD;
}
|
C
|
#define _GNU_SOURCE
#include <stdio.h> // perror
#include <stdlib.h> // exit, EXIT_*
#include <syscall.h> // SYS_pivot_root
#include <unistd.h> // syscall, chdir, execv
int
main(int argc, char *argv[])
{
argc = argc;
if (syscall(SYS_pivot_root, "rootfs-target", "rootfs-target/.oldroot"))
{
perror("pivot root");
exit(EXIT_FAILURE);
}
chdir("/");
if (execv(argv[1], argv + 1))
{
perror("exec under new root");
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
|
C
|
//Includes
#include<sys/socket.h>
#include<netdb.h>
#include<ifaddrs.h>
#include<stdio.h>
#include<stdlib.h>
int main() {
//declare pointer addresses
struct ifaddrs *addresses;
//getifaddrs allocates the memory for addresses, and gives a linked list of addresses to addresses
//Also checks if it works
if (getifaddrs(&addresses) == -1) {
printf("getifaddrs call faliled\n");
return -1;
}
//declare new pointer address, and initalize it with addresses(used to cycle through)
struct ifaddrs *address = addresses;
//prints out the names of the sockets, and their addresess
while (address) {
//get address family
int family = address->ifa_addr->sa_family;
//check if it's not IPv4 or IPv6
if (family == AF_INET || family == AF_INET6) {
//print socket name
printf("%s\t", address->ifa_name);
//print address type
printf("%s\t", family == AF_INET ? "IPv4" : "IPv6");
//declare char array ap for storing the address
char ap[100];
//gets address type size
const int family_size = family == AF_INET ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6);
//gets the actual address and stores it in ap
getnameinfo(address->ifa_addr, family_size, ap, sizeof(ap), 0, 0, NI_NUMERICHOST);
//print address
printf("\t%s\n", ap);
}
//cycle to the next socket
address = address->ifa_next;
}
//End the program
freeifaddrs(addresses);
return 0;
}
|
C
|
/*
* COMP20007 Design of Algorithms
* Semester 1 2016
*
* David Murges
* 657384
*
* This module provides all the topological sorting functionality.
*
*/
#ifndef TOPOSORT_H
#define TOPOSORT_H
#include "graph.h"
/* Returns a list of topologically sorted vertices using the DFS method */
extern List dfs_sort(Graph graph);
/*visit the nodes of the graph push node into new_list if it reaches leaf*/
extern int visit1(List* vertices,bool temporary[],bool permanent[],int numsorted,Vertex vertex);
/*setting false as default value of items in array*/
extern void populatearrays(bool* permanent,bool* temporary,Graph graph);
/*setting items in array to false*/
extern void initializearray(bool *alreadyVisited,Graph graph);
/* Returns a list of topologically sorted vertices using the Kahn method */
extern List kahn_sort(Graph graph);
/* Uses graph to verify vertices are topologically sorted */
extern bool verify(Graph graph, List list);
#endif
|
C
|
#include <stdio.h>
//#include<Fraction.h>
struct Fraction
{
int numerator;
int denominator;
};
void enter(struct Fraction*far);
void simplify(struct Fraction*);
void display(const struct Fraction*);
int main(void)
{
struct Fraction f; //abc
//int num;
printf("Fraction Simplifier\n");
printf("===================\n");
enter(&f);
simplify(&f);
display(&f);
return 0;
}
void enter(struct Fraction* f){
//int numerator, denominatore;
printf("Enter Numerator :");
scanf_s("%d", (&f->numerator));// avi rite
printf("\nEnter denominators:");
scanf_s("%d", (&f->denominator));
}
void simplify(struct Fraction* f){
int i,gcd;
for (i = 1; i <= (f->numerator) && i <= (f->denominator); ++i) //http://www.programiz.com/c-programming/examples/hcf-gcd
{
// Checks if i is factor of both integers
if ((f->numerator) % i == 0 && (f->denominator) % i == 0)
gcd = i;
}
// Find Fraction
f->numerator = (f -> numerator) / gcd;
f->denominator = (f -> denominator) / gcd;
}
void display(const struct Fraction* f){
printf("\n\n%d/%d", f->numerator, f->denominator);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.