language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
|---|---|
C
|
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
char** expr;
void swap(int* arr, int i, int j) {
int x = arr[i];
arr[i] = arr[j];
arr[j] = x;
}
void swap_str(char** arr, int i, int j) {
char* x = arr[i];
arr[i] = arr[j];
arr[j] = x;
}
void solve24pt(int* arr, int start, int end, int target) {
int i,j;
// printf("start = %d, end = %d\n", start, end);
/*for(i = start; i < 4; i++) {*/
/*printf("%d ", arr[i]);*/
/*}*/
/*printf("\n");*/
if(start == end) {
if(target == arr[start]) {
printf("%s\n", expr[start]);
}
return;
}
for(i = start; i < end; i++) {
for(j = i+1; j<=end; j++) {
int var_1 = arr[i];
int var_2 = arr[j];
char expr1[50];
char expr2[50];
strcpy(expr1, expr[i]);
strcpy(expr2, expr[j]);
swap(arr,j,end);
swap_str(expr, j, end);
arr[i] = var_1+var_2;
sprintf(expr[i],"(%s + %s)", expr1, expr2);
solve24pt(arr, start, end-1, target);
arr[i] = var_1*var_2;
sprintf(expr[i],"(%s * %s)",expr1, expr2);
solve24pt(arr, start, end-1, target);
arr[i] = var_1-var_2;
sprintf(expr[i],"(%s - %s)",expr1, expr2);
solve24pt(arr, start, end-1, target);
if(var_2!=0) {
arr[i] = var_1/var_2;
sprintf(expr[i],"(%s / %s)",expr1, expr2);
solve24pt(arr, start, end-1, target);
}
arr[i] = var_1;
swap(arr, j,end);
swap_str(expr, j, end);
strcpy(expr[i], expr1);
}
}
}
int main() {
int n = 4;
int arr[] = {11,8,3,5};
expr = malloc(sizeof(char*)*n);
int i;
for(i = 0; i < n; i++) {
expr[i] = malloc(sizeof(char)*50);
sprintf(expr[i], "%d",arr[i]);
}
solve24pt(arr, 0, 3, 24);
for(i = 0; i < n; i++) {
free(expr[i]);
}
free(expr);
}
|
C
|
/*
EMS - file_length.c
POSIX Style text file length search
Copyright (C) 2021 Naive-C <naive.c.cell@gmail.com>
*/
#include <sys/stat.h>
size_t file_length(const int fd)
{
struct stat st;
fstat(fd, &st);
size_t size = st.st_size;
return size;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
void lerVetor(int *, int);
void construirMinHeap (int *, int);
void descer (int *, int, int);
void mostrar(int *, int);
int main() {
int n, *v;
v = (int *)malloc(sizeof(int));
scanf("%d", &n);
while (n != 0) {
v = (int *)realloc(v, n * sizeof(int));
lerVetor(v, n);
construirMinHeap(v, n);
mostrar(v, n);
scanf("%d", &n);
}
return 0;
}
void lerVetor(int *v, int n) {
int i = 0;
while (i < n) {
scanf("%d", &v[i]);
i++;
}
}
void construirMinHeap (int *v, int n) {
int i = (n / 2) - 1;
while (i >= 0) {
descer(v, n, i);
i--;
}
}
void descer(int *v, int n, int i) {
int esq, dir, maior, aux;
esq = (2 * i) + 1;
dir = (2 * i) + 2;
if (dir < n && v[dir] < v[i]) {
maior = dir;
} else {
maior = i;
}
if (esq < n && v[esq] < v[maior]) {
maior = esq;
}
if (maior != i) {
aux = v[i];
v[i] = v[maior];
v[maior] = aux;
descer(v, n, maior);
}
}
void mostrar(int *v, int n) {
int i = 0;
while (i < n) {
printf("%d%s", v[i], i + 1 < n ? " " : "\n");
i++;
}
}
|
C
|
#ifndef FALLING_LETTER
#define FALLING_LETTER
#include "Computer.h"
#include "fonts.h"
struct FallingLetter : public ScreenElement
{
int sign;
float rotation_angle;
FallingLetter(float _x1, float _y1, float _x2, float _y2, string _name) : ScreenElement(_x1, _y1, _x2, _y2, _name)
{
sign = 2;
}
void draw(TextureManager* texture_manager)
{
draw_string(texture_manager, 32, name, x1, y1);
}
};
#endif
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXLINE 1000
int except = 0;
int number = 0;
void findpattern(char *fname, char *pattern);
void handlematch(FILE *fp, char *fname, char *pattern);
int main(int argc, char *argv[])
{
char line[MAXLINE];
char *prog = argv[0];
int c;
while (--argc > 0 && (*++argv)[0] == '-') {
while ((c = *++argv[0])) {
switch(c) {
case 'x':
except = 1;
break;
case 'n':
number = 1;
break;
default:
fprintf(stderr, "%s: illegal option %c\n", prog, c);
argc = 0;
break;
}
}
}
if (argc == 1) {
findpattern("", *argv); /* no file for reading in */
} else if (argc > 1) { /* at least has one input file */
char *pattern = *argv;
while (--argc > 0) {
findpattern(*++argv, pattern);
}
} else {
fprintf(stderr, "Usage: %s [-x] [-n] pattern [file...]\n", prog);
exit(2);
}
return 0;
}
void findpattern(char *fname, char *pattern) {
FILE *fp;
if (strlen(fname) == 0) {
handlematch(stdin, fname, pattern);
} else if ((fp = fopen(fname, "r")) == NULL) {
fprintf(stderr, "can't open %s\n", fname);
exit(1);
} else {
handlematch(fp, fname, pattern);
fclose(fp);
}
}
void handlematch(FILE *fp, char *fname, char *pattern) {
char line[MAXLINE];
int lineno = 0;
while (fgets(line, MAXLINE, fp) != NULL) {
lineno++;
if ((strstr(line, pattern) != NULL) != except) {
if (strlen(fname) != 0)
printf("[%s] ", fname);
if (number)
printf("%3d: ", lineno);
printf("%s", line);
}
}
}
|
C
|
#include<stdio.h>
#include<math.h>
main()
{
long long int i,t,j,k,l,cnt=0,p,A,B,C,D,x,y,m,n,a[100][2];
scanf("%lld",&t);
for(i=0;i<t;i++)
{
cnt=0;
scanf("%lld %lld %lld %lld %lld %lld %lld %lld",&n,&A,&B,&C,&D,&x,&y,&m);
a[0][0]=x;
a[0][1]=y;
for(j=1;j<n;j++)
{x=(A*x+B)%m;
y=(C*y+D)%m;
a[j][0]=x;
a[j][1]=y;
}
for(k=0;k<n;k++)
for(l=k+1;l<n;l++)
for(p=l+1;p<n;p++)
if(((a[k][0]+a[l][0]+a[p][0])%3==0)&&((a[k][1]+a[l][1]+a[p][1])%3==0))
cnt++;
printf("Case #%lld: %lld\n",i+1,cnt);
}
}
|
C
|
//==============================================================================
/* MBUG-2151 interface implementation
Mostly identical to mbug_2165.c, but without carrier modulation.
Any changes in this file should also be applied in mbug_2165.c.
*/
//==============================================================================
#include <stdlib.h>
#include <string.h>
#include <ctype.h> // toupper()
#include "mbug_2151.h"
//------------------------------------------------------------------------------
// Parameter numbers (keep private, may change in future revisions)
enum mbug_2151_param {
PARAM_START = 0x10,
PARAM_RESET = 0xFF,
PARAM_ITER = 0x01,
PARAM_CLOCK_DIV = 0x02,
PARAM_BASE_CLOCK = 0x05,
PARAM_BUSY = 0x70,
PARAM_SEQ_LEN = 0x71
};
//------------------------------------------------------------------------------
// Get a list of all available mbug-2151 devices.
const mbug_device_list mbug_2151_list( void )
{
return mbug_get_device_list(2151);
}
//------------------------------------------------------------------------------
// Device base clock. This is assumed to be identical for
// all mbug-2151 devices and only read the very first time a device is opened.
// Currently, _base_clock = _mod_clock = 4 MHz.
static int base_clock = 0;
//------------------------------------------------------------------------------
// Open a device specified by it's serial number (as int,
// last digits of the serial number are matched only).
mbug_device mbug_2151_open( int serial_num )
{
mbug_device dev = mbug_open_int(2151, serial_num);
if ( (dev != NULL) && (base_clock == 0) )
{
base_clock = mbug_2151_get_base_clock( dev );
}
return dev;
}
//------------------------------------------------------------------------------
// Open a device specified by it's id string, as returned
// by mbug_2151_list()
mbug_device mbug_2151_open_str( const char *id )
{
mbug_device dev;
unsigned int type = mbug_type_from_id( id );
if (type != 2151) return NULL;
dev = mbug_open_str( id );
if ( (dev != NULL) && (base_clock == 0) )
{
base_clock = mbug_2151_get_base_clock( dev );
}
return dev;
}
//------------------------------------------------------------------------------
// Close a previously opened device.
void mbug_2151_close( mbug_device dev )
{
mbug_close(dev);
}
//------------------------------------------------------------------------------
// Private helper function:
// Generic I/O command: Send cmd, receive integer parameter
// Return values <0 indicate errors.
static int io( mbug_device dev, unsigned char* out, size_t size )
{
unsigned char in[8] = {0};
short status = 0;
int value = 0, ret = 0;
ret = mbug_write( dev, out, size );
if (ret<0) return -1;
ret = mbug_read( dev, in, sizeof(in) );
if (ret<0) return -1;
// First 2 bytes contain the return status (signed 16 bit)
status = *(short*) in;
// Next 4 bytes contain the returned output value
value = *(int*) (in+2);
if (status<0) return status;
else return value;
}
//------------------------------------------------------------------------------
// Private helper function:
// Set parameter value.
static int set_param( mbug_device dev, enum mbug_2151_param param, unsigned int value )
{
unsigned char out[8] = {0xB0, param, 0, 0, 0, 0, 0, 0};
memcpy( out+2, (void*)&value, 4 );
return io( dev, out, 6);
}
//------------------------------------------------------------------------------
// Private helper function:
// Get parameter value.
static int get_param( mbug_device dev, enum mbug_2151_param param )
{
unsigned char out[2] = {0xC0, param};
return io( dev, out, 2);
}
//------------------------------------------------------------------------------
// Set transmission sequence (max 255 bytes, selectable transmission mode)
int mbug_2151_set_sequence( mbug_device dev, unsigned char* data, size_t nbytes, mbug_2151_tx_mode tx_mode )
{
unsigned char out[64] = {0xB0, 0};
unsigned char* pd = data;
size_t s, smax;
if (nbytes>255) nbytes=255;
if (tx_mode > TX_MODE_TIMED_16)
tx_mode = TX_MODE_BITSTREAM;
smax = 64 - 4; // Maximum data length per packet
// First packet: Set sequence
// Command format: {0xB0, 0, mode<<4, len, data[:] }
s = nbytes>smax ? smax : nbytes;
out[2] = tx_mode<<4; out[3] = s;
memcpy( out+4, pd, s );
nbytes -= s; pd += s;
if (io( dev, out, s+4 ) <0)
return -1;
// Subsequent packages: Append sequence
// Command format: {0xB0, 0, 0x01, len, data[] }
while (nbytes>0)
{
s = nbytes>smax ? smax : nbytes;
out[2] = 0x01; out[3] = s;
memcpy( out+4, pd, s );
nbytes -= s; pd += s;
if (io( dev, out, s+4 ) <0)
return -1;
}
return 0;
}
//------------------------------------------------------------------------------
// Set transmission sequence in bitstream mode (max 255 bytes)
int mbug_2151_set_seq_bitstream( mbug_device dev, unsigned char* data, size_t nbytes )
{
return mbug_2151_set_sequence( dev, data, nbytes, TX_MODE_BITSTREAM );
}
//------------------------------------------------------------------------------
// Set transmission sequence in 8-bit time mode (max 255 bytes)
int mbug_2151_set_seq_times_8bit( mbug_device dev, unsigned char* data, size_t nbytes )
{
return mbug_2151_set_sequence( dev, data, nbytes, TX_MODE_TIMED_8 );
}
//------------------------------------------------------------------------------
// Set transmission sequence in 16-bit time mode (max 127 items)
int mbug_2151_set_seq_times_16bit( mbug_device dev, unsigned short* data, size_t nitems )
{
return mbug_2151_set_sequence( dev, (unsigned char*)data, nitems*2, TX_MODE_TIMED_16 );
}
//------------------------------------------------------------------------------
// Get the size (in bytes) of the currently set sequence
int mbug_2151_get_seq_length( mbug_device dev )
{
return get_param( dev, PARAM_SEQ_LEN );
}
//------------------------------------------------------------------------------
// Set number of transmission sequence iterations,
// 0: infinite, Maximum: 2**16-1
int mbug_2151_set_iterations( mbug_device dev, unsigned int niter )
{
if (niter >= 1<<16 ) niter = (1<<16)-1;
return set_param( dev, PARAM_ITER, niter );
}
//------------------------------------------------------------------------------
// Get the currently set number of transmission sequence iterations,
// 0: infinite
int mbug_2151_get_iterations( mbug_device dev )
{
return get_param( dev, PARAM_ITER );
}
//------------------------------------------------------------------------------
// Get the devices base transmission clock frequency in Hz
int mbug_2151_get_base_clock( mbug_device dev )
{
return get_param( dev, PARAM_BASE_CLOCK );
}
//------------------------------------------------------------------------------
// Set clock divider. => Bitrate = base_clock/div
// Minimum div is 10 for bitstream mode, 1 for timed modes,
// Maximum div is 2**16-1 (65535).
int mbug_2151_set_clock_div( mbug_device dev, unsigned int div )
{
if (div == 0) div = 1;
if (div >= 1<<16 ) div = (1<<16)-1;
return set_param( dev, PARAM_CLOCK_DIV, div );
}
//------------------------------------------------------------------------------
// Get the currently set transmission clock divider.
int mbug_2151_get_clock_div( mbug_device dev )
{
return get_param( dev, PARAM_CLOCK_DIV );
}
//------------------------------------------------------------------------------
// Set the transmission rate (via clock div).
// Minimum rate is 61sec.
// Maximum rate is 400kHz for bitstream mode, 4Mhz for timed modes.
// Returns the actually set bitrate or <0 in case of an error.
double mbug_2151_set_bitrate( mbug_device dev, double freq )
{
int div;
div = (int)(0.5 + 1.0*base_clock/freq);
if (div >= 1<<16) div = (1<<16)-1;
if( mbug_2151_set_clock_div( dev, div ) < 0)
return -1;
return (int)(0.5 + 1.0*base_clock/div);
}
//------------------------------------------------------------------------------
// Set the transmission time base (in seconds, via clock div).
// Minimum timebase is 2.5us for bitstream mode, 0.25us for timed modes.
// Maximum timebase is 16.38375ms.
// Resolution is 0.25us.
// Returns the actually set timebase or <0 in case of an error.
double mbug_2151_set_timebase( mbug_device dev, double interval )
{
int div;
div = (int)(0.5 + 1.0*interval*base_clock);
if (div >= 1<<16) div = (1<<16)-1;
if( mbug_2151_set_clock_div( dev, div ) < 0)
return -1;
return (int)(0.5 + 1.0*div/base_clock);
}
//------------------------------------------------------------------------------
// Start transmission.
int mbug_2151_start( mbug_device dev )
{
return set_param( dev, PARAM_START, 0x0001 );
}
//------------------------------------------------------------------------------
// Stop transmission
// force = 0: Stop gracefully after ongoing iteration
// force = 1: Stop instantly
int mbug_2151_stop( mbug_device dev, int force )
{
return set_param( dev, PARAM_START, force ? 0x0100 : 0x0000 );
}
//------------------------------------------------------------------------------
// Stop transmission gracefully, i.e. after the current iteration.
int mbug_2151_stop_gracefully( mbug_device dev )
{
return set_param( dev, PARAM_START, 0x0000 );
}
//------------------------------------------------------------------------------
// Stop transmission instantly.
int mbug_2151_stop_immediately( mbug_device dev )
{
return set_param( dev, PARAM_START, 0x0100 );
}
//------------------------------------------------------------------------------
// Reset transmission and all parameters
int mbug_2151_reset( mbug_device dev )
{
return set_param( dev, PARAM_RESET, 0 );
}
//------------------------------------------------------------------------------
// Get busy state. >0 if transmission is in progress
int mbug_2151_get_busy( mbug_device dev )
{
return get_param( dev, PARAM_BUSY );
}
//------------------------------------------------------------------------------
int mbug_2151_ab440s_str_to_addr( const char *str ) {
int addr = 0;
int i = 0;
for(i = 0; str[i]; i++) {
if(str[i] >= '1' && str[i] <= '5') {
addr |= 1<<(9-str[i]+'1');
} else if(toupper(str[i]) >= 'A' && toupper(str[i]) <= 'E') {
addr |= 1<<(4-toupper(str[i])+'A');
}
}
return addr;
}
int mbug_2151_ab440s_switch_addr( mbug_device dev, int addr, int state ) {
unsigned char seq[16];
int i;
if(mbug_2151_set_bitrate(dev, 3125) == -1) {
return -1;
}
if(mbug_2151_set_iterations(dev, 3) == -1) {
return -1;
}
for(i = 0; i < 12; i++) {
seq[i] = 0x71;
}
if(state == 1) {
seq[10] = 0x11;
} else {
seq[11] = 0x11;
}
seq[12] = 1;
seq[13] = seq[14] = seq[15] = 0;
for(i = 0; i < 10; i++) {
seq[9-i] = (addr & (1<<i)) ? 0x11 : 0x71;
}
if(mbug_2151_set_sequence(dev, seq, 16, TX_MODE_BITSTREAM) == -1) {
return -1;
}
return mbug_2151_start(dev);
}
int mbug_2151_ab440s_switch_str( mbug_device dev, const char *addr, int state ) {
return mbug_2151_ab440s_switch_addr(dev,
mbug_2151_ab440s_str_to_addr(addr),
state);
}
int mbug_2151_dmv7008_cmd_addr(mbug_device dev, int syscode, int channel, int cmd) {
int i;
unsigned char seq[118] = {0};
int bits;
int iter = 4;
const unsigned char cmdbits[5][4] = {
//ON OFF INC DEC
{ 0xE1, 0xF0, 0xEB, 0xFA }, // CH 1
{ 0x00, 0x11, 0x0A, 0x1B }, // CH 2
{ 0x82, 0x93, 0x88, 0x99 }, // CH 3
{ 0x41, 0x50, 0x4B, 0x5A }, // CH 4
{ 0xC3, 0xD2, 0xC9, 0xD8 } // ALL
};
syscode = syscode & 0xFFF;
if(channel < 0 || channel > 4) {
return -1;
}
bits = (1 << 20) | (syscode << 8) | (cmdbits[channel][cmd] << 0);
for(i = 0; i < 21; i++) {
if ((bits >> (20-i)) & 1) { // Approximate 1/3 pulse width
seq[2*i] = 0x00; seq[2*i+1] = 0xF8; // 0b1111100000000000
} else {
seq[2*i] = 0xE0; seq[2*i+1] = 0xFF; // 0b1111111111100000
}
}
if(mbug_2151_set_bitrate(dev, 8333) == -1) {
return -1;
}
if (cmd==2 || cmd==3) // :TODO: Use command definitions from mbug_2151_targets.h
iter = 1;
if(mbug_2151_set_iterations(dev, iter) == -1) {
return -1;
}
if(mbug_2151_set_sequence(dev, seq, 118, TX_MODE_BITSTREAM) == -1) {
return -1;
}
return mbug_2151_start(dev);
}
int mbug_2151_dmv7008_cmd_str(mbug_device dev, const char *addr, int cmd) {
static int syscode = 0;
int channel;
const char *colon = strchr(addr, ':');
if(colon != NULL) {
syscode = atoi(addr);
channel = atoi(colon+1);
} else {
channel = atoi(addr);
}
return mbug_2151_dmv7008_cmd_addr(dev, syscode, channel, cmd);
}
int mbug_2151_rs200_cmd_addr(mbug_device dev, int syscode, int channel, int cmd) {
int i;
unsigned short seq[26*2];
unsigned int data;
if(syscode < 0 || syscode > 255) {
return -1;
}
if(channel < 0 || channel == 4 || channel > 5) {
return -1;
}
data = (channel << 4) | (cmd << 7) | ((1^cmd) << 2);
if(channel == 1 || channel == 2) {
data ^= 1<<7;
}
data = (0x19 << 20)
| (syscode << 12)
| (data << 4)
| (0x9 + syscode + (syscode>>4) + data + (data>>4)) & 0x0F;
for(i = 0; i < 26; i++) {
if(data & (1<<(25-i))) {
seq[2*i+0] = 600;
seq[2*i+1] = 3400;
} else {
seq[2*i+0] = 1300;
seq[2*i+1] = 3400;
}
}
seq[26*2-1] += 30000;
if(mbug_2151_set_timebase(dev, 1e-6) == -1) {
return -1;
}
if(mbug_2151_set_iterations(dev, 4) == -1) {
return -1;
}
if(mbug_2151_set_seq_times_16bit(dev, seq, 26*2) == -1) {
return -1;
}
return mbug_2151_start(dev);
}
int mbug_2151_rs200_cmd_str(mbug_device dev, char *addr, int cmd) {
static int syscode = 0;
int channel;
char *colon = strchr(addr, ':');
char *chanptr;
if(colon != NULL) {
syscode = atoi(addr);
chanptr = colon+1;
} else {
chanptr = addr;
}
if(toupper(*chanptr) == 'A'
|| toupper(*chanptr) == 'M') {
channel = 5;
} else {
channel = atoi(chanptr) - 1;
}
return mbug_2151_rs200_cmd_addr(dev, syscode, channel, cmd);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static unsigned int CHARACTERS_ASCII = 91;
typedef struct TMyStruct {
unsigned char key[7];
unsigned long long value;
} TMap;
void RadixSort(TMap *source, unsigned long int size) {
TMap *tmp;
int i;
unsigned int j;
unsigned long long count[CHARACTERS_ASCII];
unsigned long long sum;
unsigned long long bubble;
i = 5;
tmp = NULL;
tmp = (TMap*)malloc(sizeof(TMap) * size);
if (!tmp) {
return ;
}
if (size > 0) {
while (i >= 0) {
sum = 0;
bubble = 0;
j = 0;
while (j < CHARACTERS_ASCII)
count[j++] = 0;
j = 0;
while (j < size) {
count[source[j].key[i]]++;
j++;
}
j = 0;
while (j < CHARACTERS_ASCII) {
bubble = count[j];
count[j] = sum;
sum += bubble;
j++;
}
j = 0;
while (j < size) {
tmp[count[source[j].key[i]]] = source[j];
count[source[j].key[i]]++;
j++;
}
i--;
memcpy(source, tmp, sizeof(TMap) * size);
}
}
free(tmp);
}
int main(void)
{
TMap *kvalue;
char c;
int uselessVar;
unsigned long long count;
unsigned long long size;
count = 0;
size = 1;
kvalue = (TMap*)malloc((sizeof(TMap)));
while((c = getchar()) != EOF) {
if (c != '\n') {
TMap tmp;
if (size == count) {
kvalue = (TMap*)realloc(kvalue, sizeof(TMap) * 2 * size);
if (!kvalue) {
return (0);
}
size *= 2;
}
tmp.key[0] = c;
c = getchar();
c = getchar();
tmp.key[1] = c;
c = getchar();
tmp.key[2] = c;
c = getchar();
tmp.key[3] = c;
c = getchar();
c = getchar();
tmp.key[4] = c;
c = getchar();
tmp.key[5] = c;
tmp.key[6] = '\0';
c = getchar();
uselessVar = scanf("%llu", &tmp.value);
kvalue[count] = tmp;
c = getchar();
count++;
if (!uselessVar) {
;
}
}
}
RadixSort(kvalue, count);
size = 0;
printf("\n");
while (size != count) {
printf("%c %c%c%c %c%c\t%llu\n", kvalue[size].key[0], kvalue[size].key[1],
kvalue[size].key[2], kvalue[size].key[3], kvalue[size].key[4], kvalue[size].key[5],
kvalue[size].value);
size++;
}
free(kvalue);
return (0);
}
|
C
|
// Name of coder : Mangesh Chandrawanshi
// Roll No : 1801CS16
// Date created : 26th Mar 2019
// Brief objective of the program : Complete task given in Assignment 8
#include <stdio.h>
// Structure Definition
typedef struct student{
int roll_number;
char grades[6];
float CGPA;
}student;
// Function I to sort in increasing order of roll numbers
void sort_by_roll_number(student l[], int n)
{
int swap=-1,i,j;
while(swap != 0)
{
swap=0;
for(i=0;i<n-1;i++)
{
if(l[i+1].roll_number<l[i].roll_number)
{
student temp;
temp = l[i];
l[i] = l[i+1];
l[i+1] = temp;
swap++;
}
}
}
printf("\nList sorted by roll no\n");
for(i=0;i<n;i++)
{
printf("%d ", l[i].roll_number);
for(j=0;j<6;j++)
{
printf("%c ", l[i].grades[j]);
}
printf("%.2f\n",l[i].CGPA);
}
}
// Function II to sort in decreasing order of CGPA
void sort_by_CGPA(student l[], int n)
{
int swap=-1,i,j;
while(swap != 0)
{
swap=0;
for(i=0;i<n-1;i++)
{
if(l[i+1].CGPA>l[i].CGPA)
{
student temp;
temp = l[i];
l[i] = l[i+1];
l[i+1] = temp;
swap++;
}
}
}
printf("\nList sorted by CGPA\n");
for(i=0;i<n;i++)
{
printf("%d ", l[i].roll_number);
for(j=0;j<6;j++)
{
printf("%c ", l[i].grades[j]);
}
printf("%.2f\n",l[i].CGPA);
}
}
// Main
int main()
{
int n,i,j;
scanf("%d",&n);
student a[n];
// Input
for(i=0;i<n;i++)
{
scanf("%d", &a[i].roll_number);
for(j=0;j<6;j++)
{
char q;
scanf("%c",&q);
if(q != ' ')
{
a[i].grades[j]=q;
}
else
{
j--;
}
}
// CGPA calculation
int x[6]={0};
for(j=0;j<6;j++)
{
if(a[i].grades[j]=='E')x[j]=10;
else if(a[i].grades[j]=='A')x[j]=9;
else if(a[i].grades[j]=='B')x[j]=8;
else if(a[i].grades[j]=='C')x[j]=7;
else if(a[i].grades[j]=='D')x[j]=6;
else if(a[i].grades[j]=='P')x[j]=5;
else if(a[i].grades[j]=='F')x[j]=0;
}
float ans = (4*x[0]+5*x[1]+3*x[2]+4*x[3]+3*x[4]+1*x[5])/(float)20;
a[i].CGPA = ans;
}
// Call to function I
sort_by_roll_number(a,n);
// Call to function II
sort_by_CGPA(a,n);
return 0;
}
|
C
|
#include<stdio.h>
#include<conio.h>
int main(void)
{
int X[10][10],n,i,j,flag;
printf("How many columns and rows?\n");
scanf("%d",&n);
printf("Enter the elements\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&X[i][j]);
}
}
flag=1;
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if((X[i][j]-X[j][i]!=0))
{
flag=0;
break;
}
}
}
if(flag==1)
printf("Symmetric matrix");
else
printf("Not a symmetric matrix");
}
|
C
|
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/msg.h>
#include <ctype.h>
#include <time.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/mman.h>
#include <semaphore.h>
#include <fcntl.h>
#include <sys/stat.h>
#include "my_queue.h"
void help(){
printf("Two arguments required (number of clients, number of cuts).\n");
exit(1);
}
void sigint_hr(int signo){
exit(2);
}
void cl_queue_init();
void semaphores_init();
void signals_mask_init();
void detach_and_close(void);
int enter_barber_shop();
void get_cut(int number_of_cuts);
my_queue* m_queue = NULL;
sem_t* barber_semaphore;
sem_t* queue_semaphore;
sem_t* check_semaphore;
sem_t* wait_semaphore;
struct timespec time_value;
volatile int cuts_already = 0;
sigset_t fullMask;
void sigrtmin_handler(int signo){
cuts_already++;
}
int main(int argc, char** argv){
if(argc != 3) {
help();
}
if(atexit(detach_and_close) == -1) {
print_error("Error while setting atexit.\n");
}
if(signal(SIGINT, sigint_hr) == SIG_ERR) {
print_error("Error while setting sigint handler.\n");
}
if(signal(SIGRTMIN, sigrtmin_handler) == SIG_ERR) {
print_error("Error while setting sigrtmin handler.\n");
}
int number_of_clients = atoi(argv[1]);
if(number_of_clients < 1 || number_of_clients > 500) {
print_error("Too few or too many clients");
}
int number_of_cuts = atoi(argv[2]);
if (number_of_cuts < 1 || number_of_cuts > 15) {
print_error("Too few or too many cuts");
}
cl_queue_init();
semaphores_init();
signals_mask_init();
sigset_t mask;
if(sigemptyset(&mask) == -1) {
print_error("Error while setting empty set.\n");
}
if(sigaddset(&mask, SIGRTMIN) == -1) {
print_error("Error while adding SIGRTMIN set.\n");
}
if(sigprocmask(SIG_BLOCK, &mask, NULL) == -1) {
print_error("Error while sigprocmask");
}
for(int i=0; i<number_of_clients; i++){
pid_t child_pid = fork();
if(child_pid == -1) {
print_error("Error while forking.\n");
}
if(child_pid == 0){
get_cut(number_of_cuts);
return 0;
}
}
printf("All clients cut.\n");
while(1){
wait(NULL);
if (errno == ECHILD) break;
}
return 0;
}
void get_cut(int number_of_cuts){
while(cuts_already < number_of_cuts){
if(sem_wait(check_semaphore) == -1) {
print_error("Error while decrementing check semaphore");
}
if(sem_wait(queue_semaphore) == -1) {
print_error("Error while decrementing queue semaphore");
}
int res = enter_barber_shop();
if(sem_post(queue_semaphore) == -1) {
print_error("Error while incrementing queue semaphore");
}
if(sem_post(check_semaphore) == -1) {
print_error("Error while incrementing check semaphore");
}
if(res != -1){
sigsuspend(&fullMask);
clock_gettime(CLOCK_MONOTONIC, &time_value);
printf("%li.%lis >>> Client %d just got cut \n",time_value.tv_sec,time_value.tv_nsec/1000,getpid());
fflush(stdout);
}
}
}
int enter_barber_shop(){
int barber_state;
if(sem_getvalue(barber_semaphore, &barber_state) == -1){
print_error("Error while getting barber semaphore value.\n");
}
pid_t my_pid = getpid();
if(barber_state == 0){
if(sem_post(barber_semaphore) == -1) {
print_error("Error while waking barber up.\n");
}
clock_gettime(CLOCK_MONOTONIC, &time_value);
printf("%li.%lis >>> Client %d woke barber up.\n",time_value.tv_sec,time_value.tv_nsec/1000,getpid());
if(sem_wait(wait_semaphore) == -1) {
print_error("Error while decrementing wait semaphore");
}
m_queue->chair = my_pid;
return 1;
} else {
int tmp = my_queue_push(m_queue, my_pid);
if(tmp == -1){
clock_gettime(CLOCK_MONOTONIC, &time_value);
printf("%li.%lis >>> No place in queue for client %d \n",time_value.tv_sec,time_value.tv_nsec/1000,my_pid);
fflush(stdout);
return -1;
} else {
clock_gettime(CLOCK_MONOTONIC, &time_value);
printf("%li.%lis >>> Client %d is in the queue \n",time_value.tv_sec,time_value.tv_nsec/1000,my_pid);
fflush(stdout);
return 0;
}
}
}
void cl_queue_init(){
int shared_m_id = shm_open("/shm", O_RDWR, 0666);
if(shared_m_id == -1) {
print_error("Error while opening shared memory.\n");
}
void* tmp = mmap(NULL, sizeof(my_queue), PROT_READ | PROT_WRITE, MAP_SHARED, shared_m_id, 0);
if(tmp == (void*)(-1)) {
print_error("Error while mapping shared memory.\n");
}
m_queue = (my_queue*) tmp;
}
void semaphores_init(){
barber_semaphore = sem_open("/barber", O_RDWR);
queue_semaphore = sem_open("/queue", O_RDWR);
check_semaphore = sem_open("/check", O_RDWR);
wait_semaphore = sem_open("/wait", O_RDWR);
if(barber_semaphore == SEM_FAILED) {
print_error("Error while opening barber semaphore");
}
if(queue_semaphore == SEM_FAILED) {
print_error("Error while opening queue semaphore");
}
if(check_semaphore == SEM_FAILED) {
print_error("Error while opening check semaphore");
}
if(wait_semaphore == SEM_FAILED) {
print_error("Error while opening wait semaphore");
}
}
void signals_mask_init(){
sigfillset(&fullMask);
sigdelset(&fullMask, SIGRTMIN);
sigdelset(&fullMask, SIGINT);
}
void detach_and_close(void){
int error = 0;
if(munmap(m_queue, sizeof(m_queue)) == -1) {
printf("Error while munmap queue.\n");
error = 1;
}
if(sem_close(barber_semaphore) == -1) {
printf("Error while closing barber semaphore.\n");
error = 1;
}
if(sem_close(queue_semaphore) == -1) {
printf("Error while closing queue semaphore.\n");
error = 1;
}
if(sem_close(check_semaphore) == -1) {
printf("Error while closing check semaphore.\n");
error = 1;
}
if(sem_close(wait_semaphore) == -1) {
printf("Error while closing wait semaphore.\n");
error = 1;
}
if (!error) {
printf("Detach and close has been succesfully completed.\n");
}
}
|
C
|
#pragma once
typedef int BTDataType;
typedef struct BinaryTreeNode
{
struct BinaryTreeNode* _left;
struct BinaryTreeNode* _right;
BTDataType _data;
}BTNode;
#include "Queue.h"
#include "Stack.h"
BTNode* BuyBTNode(BTDataType x);
//
BTNode* CreateBTree(BTDataType* a, size_t* pIndex, BTDataType invalid);
void BTreePrevOrder(BTNode* root);
void BTreeInOrder(BTNode* root);
void BTreePostOrder(BTNode* root);
size_t BTreeSize(BTNode* root);
size_t BTreeLeafSize(BTNode* root);
size_t BTreeKLevelSize(BTNode* root, size_t k);
size_t BTreeDepth(BTNode* root);
BTNode* BTreeFind(BTNode* root, BTDataType x);
void BTreeLevelOrder(BTNode* root);
// жȫ
int IsCompleteBTree(BTNode* root);
int IsCompleteBTree1(BTNode* root);// flagķʽж
// ǵݹ
void BTreePrevOrderNonR(BTNode* root);
void BTreeInOrderNonR(BTNode* root);
void BTreePostOrderNonR(BTNode* root);
BTNode* BuyBTNode(BTDataType x)
{
BTNode* node = (BTNode*)malloc(sizeof(BTNode));
assert(node);
node->_data = x;
node->_left = NULL;
node->_right = NULL;
return node;
}
BTNode* CreateBTree(BTDataType* a, size_t* pIndex, BTDataType invalid)
{
assert(a);
BTNode*tree=NULL;
if (a[*pIndex] == invalid)
tree=NULL;
else
{
tree = BuyBTNode(a[*pIndex]);
(*pIndex)++;
tree->_left = CreateBTree(a, pIndex, invalid);
(*pIndex)++;
tree->_right = CreateBTree(a, pIndex, invalid);
}
return tree;
}
void BTreePrevOrder(BTNode* root)
{
if (root == NULL)
return;
printf("%d ", root->_data);
BTreePrevOrder(root->_left);
BTreePrevOrder(root->_right);
}
void BTreeInOrder(BTNode* root)
{
if (root == NULL)
return;
BTreeInOrder(root->_left);
printf("%d ", root->_data);
BTreeInOrder(root->_right);
}
void BTreePostOrder(BTNode* root)
{
if (root == NULL)
return;
BTreePostOrder(root->_left);
BTreePostOrder(root->_right);
printf("%d ", root->_data);
}
size_t BTreeSize(BTNode* root)
{
if (root == NULL)
return 0;
else
return 1+BTreeSize(root->_left) + BTreeSize(root->_right);
}
size_t BTreeLeafSize(BTNode* root)
{
if (root == NULL)
return 0;
else if (root->_left == NULL&&root->_right == NULL)
return 1;
else
return BTreeLeafSize(root->_left) + BTreeLeafSize(root->_right);
}
size_t BTreeKLevelSize(BTNode* root, size_t k)
{
if (root == NULL)
return 0;
else if (k == 1)
return 1;
else
return BTreeKLevelSize(root->_left, k - 1) + BTreeKLevelSize(root->_right, k - 1);
}
size_t BTreeDepth(BTNode* root)
{
size_t depthleft = 0, depthright = 0;
if (root == NULL)
return 0;
depthleft = BTreeDepth(root->_left);
depthright = BTreeDepth(root->_right);
return depthleft > depthright ? (1+depthleft):(1+depthright);
}
BTNode* BTreeFind(BTNode* root, BTDataType x)
{
BTNode*key = NULL;
if (root == NULL)
return NULL;
if (root->_data == x)
key=root;
else
{
key = BTreeFind(root->_left, x);
if (key==NULL)
key = BTreeFind(root->_right, x);
}
return key;
}
void BTreeLevelOrder(BTNode* root)
{
Queue q;
BTNode*cur = root;
QueueInit(&q);
if (cur != NULL)
{
QueuePush(&q, cur);
}
while (QueueEmpty(&q))
{
cur = QueueFront(&q);
printf("%d ", cur->_data);
QueuePop(&q);
if (cur->_left)
QueuePush(&q, cur->_left);
if (cur->_right)
QueuePush(&q, cur->_right);
}
printf("\n");
}
int IsCompleteBTree(BTNode* root)
{
Queue q;
BTNode*cur = root;
QueueInit(&q);
if (cur != NULL)
{
QueuePush(&q, cur);
}
while (QueueEmpty(&q))
{
cur = QueueFront(&q);
QueuePop(&q);
if (cur == NULL)
break;
else
{
QueuePush(&q, cur->_left);
QueuePush(&q, cur->_right);
}
}
while (QueueEmpty(&q))
{
cur = QueueFront(&q);
if (cur != NULL)
return -1;
QueuePop(&q);
}
return 0;
}
int IsCompleteBTree1(BTNode* root)// flagķʽж
{
Queue q;
int flag = 0;
BTNode*cur = root;
QueueInit(&q);
if (cur != NULL)
QueuePush(&q, cur);
while (QueueEmpty(&q))
{
cur = QueueFront(&q);
QueuePop(&q);
if (cur == NULL)
break;
else
{
if (cur->_left == NULL)
flag = -1;
else
QueuePush(&q, cur->_left);
if (cur->_right == NULL)
flag = -1;
else
{
if (flag != 0)
return -1;
QueuePush(&q, cur->_left);
}
}
}
return 0;
}
void BTreePrevOrderNonR(BTNode* root)
{
BTNode*cur = root;
Stack s;
StackInit(&s, 10);
if (root == NULL)
return;
//
while (cur || StackEmpty(&s))
{
while (cur)
{
printf("%d ", cur->_data);
StackPush(&s, cur);
cur = cur->_left;
}
BTNode* top = StackTop(&s);
StackPop(&s);
//
cur = top->_right;
}
printf("\n");
}
void BTreeInOrderNonR(BTNode* root)
{
BTNode*cur = root;
Stack s;
StackInit(&s, 10);
if (root == NULL)
return;
while (cur || StackEmpty(&s))
{
while (cur)
{
StackPush(&s, cur);
cur = cur->_left;
}
BTNode*top = StackTop(&s);
printf("%d ", top->_data);//ʸڵ㣬Ѿˡ
StackPop(&s);
//
cur = top->_right;
}
printf("\n");
}
void BTreePostOrderNonR(BTNode* root)
{
BTNode*cur = root;
BTNode*prev = NULL;
Stack s;
StackInit(&s,10);
while (cur || StackEmpty(&s))
{
while (cur)
{
StackPush(&s, cur);
cur = cur->_left;
}
BTNode*top = StackTop(&s);
if (top->_right == NULL||top->_right==prev)
{
printf("%d ", top->_data);
StackPop(&s);
prev = top;
}
else
{
cur = top->_right;
}
}
printf("\n");
}
|
C
|
#ifndef FL_RANGE_H
#define FL_RANGE_H
#include "FuzzyLib.h"
#include "Real.h"
#include <stdlib.h>
struct FL_EXPORT Range
{
Range(Real a = NotANumber, Real b = NotANumber) { this->a = a; this->b = b; }
Range(const Range& o ) { *this = o; }
Range& operator = (const Range& o ){ this->a = o.a; this->b = o.b; return *this; }
Real a;
Real b;
inline bool contains(const Real val) const { return (val >= a) && (val <= b);}
inline bool contains(const Range& o) const { return contains(o.a) && contains(o.b); }
inline Range moved(const Real d) const { return Range(a + d, b + d); }
inline void move(const Real d) { *this = moved(d); }
inline Real length() const { return b - a; }
struct RangeIterator
{
RangeIterator(const Range& range, Real dx = RealEpsilon) { this->range = ⦥ this->dx = dx; this->val = this->range->a; }
RangeIterator(const RangeIterator& o ) { *this = o; }
RangeIterator& operator = (const RangeIterator& o) { this->range = o.range; this->dx = o.dx; this->val = o.val; c(); return *this; }
inline Real value() const { c(); return val; }
inline Real operator *() const { return value(); }
inline operator Real () const { return value(); }
inline bool operator < (const RangeIterator& o) const { c(); return val < o.val - dx; }
inline bool operator != (const RangeIterator& o) const { return !(*this == o); }
inline bool operator == (const RangeIterator& o) const { c(); return abs(val - o.val) <= RealEpsilon; }
inline Real operator ++ (int) { Real ret = val; val += dx; c(); return ret; }
inline Real operator ++ () { val += dx; c(); return val; }
inline Real operator += (int times) { val += times * dx; c(); return val; }
inline Real operator -- (int) { Real ret = val; val -= dx; c(); return ret; }
inline Real operator -- () { val -= dx; c(); return val; }
inline Real operator -= (int times) { val -= times * dx; c(); return val; }
inline RangeIterator end() { return RangeIterator(Range(range->b, range->b), 0.);}
Real dx;
const Range* range;
protected:
Real val;
friend struct Range;
private:
void c() const {
if(range == 0 || val - range->a < -dx || val - range->b > dx)
throw "RangeIterator: Out if range";
}
};
RangeIterator begin(const Real dx = RealEpsilon) const;
RangeIterator end() const;
};
typedef Range::RangeIterator RangeIterator;
#endif // FL_RANGE_H
|
C
|
/* Program 7.8 Getting the values in a two-dimensional array */
/* Jedi Chou - 20130812-1407 */
#include <stdio.h>
int main(void)
{
long board[3][3] = {
{'1', '2', '3'},
{'4', '5', '6'},
{'7', '8', '9'}
};
/* List all elements of the array */
for(int i=0; i<9; i++) {
printf("Board: %c\n", *(*board+i));
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main(){
int num, num2 ;
num = 20;
num2 = 5;
int soma = num + num2;
printf("A soma eh igual a : %i\n", soma);
int subtracao = num - num2;
printf("O valor da subtracao eh igual a : %i\n", subtracao);
int divisao = num / num2;
printf("O valor da divisao eh igual a : %i\n", divisao);
int multiplicacao = num * num2;
printf("O resultado da multiplicacao eh igual a : %i\n", multiplicacao);
return 0;
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <float.h>
#include <sys/timeb.h>
/* WordRank - by Greg Scaffidi
This program finds the "rank" of a given word compared to other words
that can be made by re-arranging the letters of the given word. Any unique
combination of letters will be considered a different word, even if those
words do not appear in a dictionary (ie "BAT" and "TAB" are words, but so
are "ATB" and "BTA"). If all possible words that can be created from a set
of letters are listed alphabetically, the first word in the list will have
rank #1, the next word will have rank #2, and the last word will have the
highest rank. For example, consider the following words with their ranks:
Word Rank
----- ----
ABC 1
ACB 2
BAC 3
BCA 4
CAB 5
CBA 6
It is helpful to first understand how to determine the total number of unique
words that can be made out of a set of letters.
This total can be expressed in terms of n, where n is the number of
letters in the set. If no letters are repeated, the solution is found by
taking n! (n factorial), where n is the total number of letters in the word.
In the example above, n=3. So, the rank of the last word in the list is:
3! = 3 x 2 x 1 = 6.
The calculation to find the rank of the last word in the list when letters
are repeated is slightly more complex. To do it, we take n! and divide it
by x, where x expresses the number of times a letter is repeated. Consider
the following list:
Word Rank
----- ----
AAAB 1
AABA 2
ABAA 3
BAAA 4
To find the highest rank, we take "(the total number of letters)!" and divide
by "(the total number of times each letter is repeated)!". In this case we have
4 total letters, and 3 repeats. So,
4!/3! = 24/6 = 4
This solution appears simple because only 1 letter is repeated, but it is
easily extended to the case where more than 1 letter repeats. In this case, we
take the product of "(the total number of times each letter is repeated)!" for
each letter in the word. We could have written the expression above as:
4!/3! x 1! to get the same answer. So, consider the following example with
multiple repeated letters:
Word Rank
----- ----
AABB 1
ABAB 2
ABBA 3
BAAB 4
BABA 5
BBAA 6
4!/2! * 2! = 24/(2x2) = 24/4 = 6
To find the rank of a particular word in the list, say 'BCA', we first start
by alphabetizing the letters and comparing each letter in the alphabetized
word to the first letter in the word we are trying to rank. Each time a letter
doesn't match, we penalize the word by adding (n-i-1)! to it's rank, where 'i' is
the number of the letters in the alphabetized word that we have matched so far.
In this case we just subtract 1 from n, because we haven't matched any letters yet
(i=0). B!=A, so the total penalty for 'BCA' increases by:
(n-i-1)! = (3-0-1)! = 2! = 2x1 = 2.
Next, we look at the second letter of the alphabetized word and again compare it
to the first letter in 'BCA'. It matches (B=B). We do not penalize the word
in this case. Instead, we remove the letter that we matched from the alphabetized
word. The alphabetized word becomes 'AC' and 'i' becomes 1. Then, we start again
by comparing the first letter in the alphabetized word, 'A' to the second letter in
'BCA', 'C'. It doesn't match so the penalty increases by,
(n-i-1)! = (3-1-1)! = 1! = 1x1 = 1.
The total penalty is now 2+1 = 3.
Now, we compare the second letter in the alphabetized word, 'C' to the second letter
of 'BCA' and they match. We don't assign a penalty. The alphabetized word becomes
just 'A'. We compare this to the next letter in 'BCA' and they also match. We don't
assign a penalty and we are done. When we started out, the total penalty (rank) was 0.
Since we decided that the best (lowest) rank in our scheme is #1, we have to add 1 to
the total penalty to get a rank of #4.
The same process is used to find the rank of a word when letters are repeated, except
that the number of repeated letters has to be tracked in addition to the number of total
letters, and the total penalty has to be divided by:
"(the total number of times each letter is repeated)! for each letter in the word"
If we are looking for the rank of the word, BOOKKEEPER:
Let R = "(the total number of times each letter is repeated)!"
R = rB x rO x rK x rE x rP x rR
R = 1! x 2! x 2! x 3! x 1! x 1!
R = 1 x 2 x 2 x 6 x 1 x 1
R = 24
BOOKKEEPER has 10 letters. So,
n = 10
BEEEKKOOPR is the alphabetized version of the word.
i = 0, since we are just starting and haven't found any matches yet.
Starting with the first letter of the word, we examine each letter in the word and add
a penalty according to the formula, ((n-i-1)!/R) when the letters do not match. Once
we match the letter, we update i and R, then start over by comparing the next letter
against the alphabetized word. But, whenever we find a match, we remove that letter from
the alphabetized word and don't consider it again. When we find a letter that matches in
the same position in both words, we don't assign a penalty at all:
B = 0, i = 1, rB = 0! = 1, R = 24
E = (n-i-1)!/R = (10 -1 -1)!/24 = 8!/24 = 40320/24 = 1680
E = (n-i-1)!/R = (10 -1 -1)!/24 = 8!/24 = 40320/24 = 1680
E = (n-i-1)!/R = (10 -1 -1)!/24 = 8!/24 = 40320/24 = 1680
K = (n-i-1)!/R = (10 -1 -1)!/24 = 8!/24 = 40320/24 = 1680
K = (n-i-1)!/R = (10 -1 -1)!/24 = 8!/24 = 40320/24 = 1680
O = 1680 x 5 = 8400, i = 2, rO = 1! = 1, R = 12
E = (n-i-1)!/R = (10 -2 -1)!/12 = 7!/12 = 5040/12 = 420
E = (n-i-1)!/R = (10 -2 -1)!/12 = 7!/12 = 5040/12 = 420
E = (n-i-1)!/R = (10 -2 -1)!/12 = 7!/12 = 5040/12 = 420
K = (n-i-1)!/R = (10 -2 -1)!/12 = 7!/12 = 5040/12 = 420
K = (n-i-1)!/R = (10 -2 -1)!/12 = 7!/12 = 5040/12 = 420
O = 420 x 5 = 2100, i = 3, rO = 0! = 1, R = 12
E = (n-i-1)!/R = (10 -3 -1)!/12 = 6!/12 = 720/12 = 60
E = (n-i-1)!/R = (10 -3 -1)!/12 = 6!/12 = 720/12 = 60
E = (n-i-1)!/R = (10 -3 -1)!/12 = 6!/12 = 720/12 = 60
K = 60 x 3 = 180, i = 4, rK = 1! = 1, R = 6
E = (n-i-1)!/R = (10 -4 -1)!/6 = 5!/6 = 120/6 = 20
E = (n-i-1)!/R = (10 -4 -1)!/6 = 5!/6 = 120/6 = 20
E = (n-i-1)!/R = (10 -4 -1)!/6 = 5!/6 = 120/6 = 20
K = 20 x 3 = 60, i = 5, rK = 0! = 1, R = 6
E = 0, i = 6, rE = 2! = 2, R = 2
E = 0, i = 7, rE = 1! = 1, R = 1
E = (n-i-1)!/R = (10 -7 -1)!/1 = 2!/1 = 2/1 = 2
P = 2, i = 8, rP = 0! = 1, R = 1
E = 0, i = 9, rE = 0! = 1, R = 1
R = 0, i = 10, rR = 0! = 1, R = 1
After totalling-up the penalties found for each letter, we get 10742. Because
our ranking scheme starts with 1 (not 0) we have to add 1 to find the rank of
the word, BOOKKEEPER: 10742 + 1 = 10743.
The program below accepts a given word as as an argument. If the argument is found to be
valid input (a word consisting of 1-25 capital letters), the total number of times each
letter appears in the word is stored in an array. Another array stores a copy of the word
that has had it's letters re-arranged in alphabetical order. These two arrays are used
along with the algorithm outlined above to find the given word's rank.
*/
// error conditions
#define ERR_TOO_MANY_WORDS 0x01
#define ERR_TOO_MANY_LETTERS 0x02
#define ERR_TOO_FEW_LETTERS 0x04
#define ERR_TOO_FEW_WORDS 0x08
#define ERR_NOT_ALL_CAPS 0x10
unsigned char err;
unsigned int wordLength;
// array to store the number of times
// each letter is repeated in the word
char counts[26] = {0};
// used to easily asses whether repeated
// letters still need to be accounted for
unsigned char repeatsTrue = 0;
// the alphabetized version of the word
// ie - the word with rank #1
char alphaWord[26] = {0};
// used to build the penalty as letters in
// the word are compared to letters in the
// alphabetized word, as described above
unsigned long long penalty = 0;
// for keeping a sum total of the word's rank
// set to 1, b/c rank starts at #1
unsigned long long totalPenalty = 1;
// capitalized letters in alphabetical order
// are used for comparison
const char upper[26] = {
'A','B','C','D','E',
'F','G','H','I','J',
'K','L','M','N','O',
'P','Q','R','S','T',
'U','V','W','X','Y',
'Z'
};
// variables for storing what's leftover
// from integer division
unsigned long long remainder = 0;
double extraSum = 0.0;
// for reference, the first 27 factorials
// 0! 1
// 1! 1
// 2! 2
// 3! 6
// 4! 24
// 5! 120
// 6! 720
// 7! 5040
// 8! 40320
// 9! 362880
// 10! 3628800
// 11! 39916800
// 12! 479001600
// 13! 6227020800
// 14! 87178291200
// 15! 1307674368000
// 16! 20922789888000
// 17! 355687428096000
// 18! 6402373705728000
// 19! 121645100408832000
// 20! 2432902008176640000
// 21! 51090942171709440000
// 22! 1124000727777607680000
// 23! 25852016738884976640000
// 24! 620448401733239439360000
// 25! 15511210043330985984000000
// 26! 403291461126605635584000000
// use these pre-calculated factorials instead of
// computing them at run-time, where possible
unsigned long long factorials [26] = {
1,
1,
2,
6,
24,
120,
720,
5040,
40320,
362880,
3628800,
39916800,
479001600,
6227020800,
87178291200,
1307674368000,
20922789888000,
355687428096000,
6402373705728000,
121645100408832000,
2432902008176640000,
1, // since input should not generate
1, // a rank greater than what can be
1, // stored in a 64bit integer, these
1, // factorials should not be needed.
1 // set to 1, to provide predictable
}; // behavior if the program attempts
// to access them.
// Checks that a word is composed of valid characters.
// Alphabetizes the word and provides information
// about the number of characters and repeated characters
//
int checkWord(char word[]) {
unsigned char i = 0;
unsigned char j = 0;
unsigned char letterCount = 0;
printf("\nChecking word: '%s'",word);
// for each letter in the word
for(i=0;i<wordLength;++i) {
if(word[i] >= 'A' && word[i] <= 'Z') {
++counts[word[i] - 'A'];
}
else {
printf("\n'%c' is not a valid character.",word[i]);
return ERR_NOT_ALL_CAPS;
}
}
// build the alphabetized word
for(j=0;j<26;++j) {
for(i=0;i<counts[j];++i) {
alphaWord[letterCount] = upper[j];
++letterCount;
}
}
return 0;
}
// Removes a letter from a string.
// --------------------------------------------------------
// arguments:
// 0 : the word to shrink
// 1 : the character to remove
// 2 : a buffer that will contain the new shrunken word
//
char * shrinkWord (char word[], char letter, char newWord[]) {
int position = 0;
// get a pointer to the character in the string
char *letterPos = strchr(word, letter);
if(letterPos == NULL)
{
printf("\nshrinkWord() ERROR!"); // report error
return newWord;
}
position = letterPos - word;
// copy word up until the character
memcpy(newWord, word, position);
// append the rest of the word after the character
strcat(newWord + position, word + position + 1);
return newWord;
}
unsigned char checkCounts() {
unsigned char k = 0;
for(k=0;k<26;++k) {
if(counts[k] > 1) {
return 1;
}
}
return 0;
}
// This function attempts to work around the limitation of the maximum size of
// a 64bit integer. Though the program isn't expected to output an answer with
// a value greater than the capacity of a 64bit integer, the calculations
// involved in arriving at that answer could involve values that are too large.
// This function attempts to cancel-out values in the numerator and denominator
// prior to performing the division.
// --------------------------------------------------------
// arguments:
// 0 : the numerator factorial
// 1 : an array containing the denominator factorials
//
unsigned long long divFactorials (unsigned char numerator, char denominators[]) {
// arrays to store the "exploded" factorials
unsigned char numerPieces[26] = {0};
unsigned char denomPieces[26] = {0};
// used for iterating through the arrays
unsigned char i = 0;
unsigned char j = 0;
unsigned char numTemp = 0;
unsigned char denomTemp = 0;
// the "whole" part leftover from the integer division of the
// numerator and denominator
unsigned long long result = 1;
// sum values used to perform the division
unsigned long long numSum = 1;
unsigned long long demSum = 1;
// the remainder from the integer division
unsigned long long remain = 0;
// decimal value of the remainder found by
// dividing 'remain' by 'demSum'
double exBit = 0.0;
// explode the factorial into an array of the
// integers that are multiplied together to form it.
numTemp = numerator;
for(i=0;i<26;++i) {
if(denominators[i]>1) {
denomPieces[denomTemp] = denominators[i];
for(j=1;j<denominators[i];++j) {
denomPieces[denomTemp+j] = denominators[i]-j;
}
denomTemp+=(denominators[i]-1);
}
if(numTemp) {
numerPieces[i] = numTemp;
--numTemp;
}
}
// go through the exploded numerator factorial components
for (i=0; i < numerator; ++i) {
// go through the exploded denominator factorial components
for(j=0;j<denomTemp;++j) {
// if there is no remainder when the numerator component
// is divided by the denominator component it is easy to
// cancel something out.
if (!(numerPieces[i] % denomPieces[j])) {
// they cancel out perfectly!
if((numerPieces[i] / denomPieces[j]) == 1) {
numerPieces[i] = denomPieces[j] = 1;
++i;
break;
}
// the denominator component cancels out completely
// but the numerator component is just reduced
else if((numerPieces[i] / denomPieces[j]) < numerPieces[i]) {
numerPieces[i] = (numerPieces[i] / denomPieces[j]);
denomPieces[j] = 1;
++i;
break;
}
}
}
}
// total up the numerator
for(i=0;i<numerator;++i) {
if(numerPieces[i]>1) {
numSum *=numerPieces[i];
}
}
// ... and the denominator
for(i=0;i<denomTemp;++i) {
if(denomPieces[i]>1) {
demSum *=denomPieces[i];
}
}
// perform the integer division
result = numSum / demSum;
// get the remainder
remain = numSum % demSum;
// ... if there is one, convert it to a decimal value
if(remain) {
exBit = (double) remain / (double) demSum;
}
// keep a running total of the remainder values
extraSum += exBit;
return result;
}
// Converts a word to its number. Called recursively.
// --------------------------------------------------------
// arguments:
// 0 : the word to find the number of
// 1 : the alphabetized version of the word
// 2 : length of alphabetized word
// 3 : a value reflecting the number of times the function has been called
//
int wordToNumber(char word[],char newAlpha[], int alphaLength, unsigned char reit ){
// chars should be safe to use, given the restraints on the problem
// that words are <= 25 letters, and rank will fit into 64bit integer
unsigned char i = 0;
unsigned char j = 0;
unsigned char k = 0;
// some buffers for storing the word after it has
// been manipulated by different functions
char newWord[26] ={0};
char newWord1[26] ={0};
// for each letter in the word
for(i=reit;i<wordLength;++i) {
// for each letter in the alphabetized word
for(j=0;j<alphaLength;++j) {
// if the letter we are looking at in the word to be ranked
// does not match the letter at the corresponding position
// in the alphabetized word, we need to assign a penalty
if(newAlpha[j]!=word[i])
{
// here we need to be concerned with using values too large
// for a 64bit integer.
// ie, finding the rank of a word like BBBBBBBBBBBBBBBBBBBAAAAAA
// involves dividing 25! by 19! x 5!
if(repeatsTrue) {
penalty += divFactorials(strlen(word) - reit - 1,counts);
}
// if we don't need to do a division, we can just add the
// pre-calculated factorial value to the rank
else {
penalty += (unsigned long long) (factorials[strlen(word) - reit - 1]);
}
}
else {
for(k=0;k<26;++k) {
// if the letter is repeated, make sure we reduce the count
if((upper[k] == newAlpha[j]) && counts[k] > 1) {
--counts[k];
// update the repeatsTrue flag
repeatsTrue = checkCounts();
break;
}
}
// ... remove that letter from the word
strcpy(newWord1, shrinkWord(newAlpha,newAlpha[j],newWord));
// ... track the total penalty
totalPenalty += (penalty);
// ... before resetting penalty
penalty = 0;
// ... and call this function to check again
// using the remaining letters
wordToNumber(word,newWord1,strlen(newWord1),i+1);
return 0;
}
}
}
// need to cast to float first.......
printf("\n\nRank # %llu ",(unsigned long long)totalPenalty + (unsigned long long)(float)extraSum);
return 0;
}
int printErr(unsigned char num) {
if(!num) {
printf("\nNo errors detected in input.");
return 0;
}
printf("\n");
if(num & ERR_TOO_MANY_WORDS)
printf("\nYou entered too many words.");
if(num & ERR_TOO_MANY_LETTERS)
printf("\nYou entered too many letters.");
if(num & ERR_TOO_FEW_LETTERS)
printf("\nYou entered too few letters.");
if(num & ERR_TOO_FEW_WORDS)
printf("\nYou entered too few words.");
if(num & ERR_NOT_ALL_CAPS)
printf("\nYou entered lower case letters.");
printf("\nPlease enter just one word consisting of 1-25 capital letters.\n");
return -1;
}
int main(int argc, char **argv)
{
struct timeb tstart, tstop;
ftime(&tstart);
err = 0;
wordLength = 0;
// check for valid input
if(argc < 2) {
err |= ERR_TOO_FEW_WORDS;
}
else if(argc > 2) {
err |= ERR_TOO_MANY_WORDS;
}
else {
wordLength = strlen(argv[1]);
if (wordLength < 1) {
err |= ERR_TOO_FEW_LETTERS;
}
else if (wordLength > 25) {
err |= ERR_TOO_MANY_LETTERS;
}
// finish checking for letters.
// total up the counts for each letter.
// build an alphabetized word to compare against.
err |= checkWord(argv[1]);
}
if(!printErr(err)) {
// remember if there are repeated letters.
repeatsTrue = checkCounts();
wordToNumber(argv[1], alphaWord, wordLength,0);
printf("found for word: %s\n", argv[1]);
ftime(&tstop);
printf("\nelapsed time: %d ms\n",
(int) (1000.0 * (tstop.time - tstart.time) +
(tstop.millitm - tstart.millitm)));
return 0;
}
else
return err;
}
|
C
|
#include "util.h"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
void heap_adjust(int* a, int s, int n) {
int tmp = a[s];
for (int i = s << 1; i <= n; i <<= 1) {
if(i < n && a[i] < a[i + 1])
i ++;
if(a[i] <= tmp) break;
a[s] = a[i];
s = i;
}
a[s] = tmp;
}
void heap_sort(int* a, int useless, int n) {
for(int i = n >> 1; i > 0; i --)
heap_adjust(a, i, n);
for(int i = n; i > 0; i --) {
a[i] ^= a[1];
a[1] ^= a[i];
a[i] ^= a[1];
heap_adjust(a, 1, i - 1);
}
}
int main() {
/*int *a = read_data(basename(__FILE__));
clock_t start = clock();
heap_sort(a, N);
printf("heap sort cost time %.2lf, N %d\n", (clock() - start) * 1.0 / CLOCKS_PER_SEC, N);
assert(check(a));*/
sort(heap_sort, basename(__FILE__));
return 0;
}
|
C
|
#include <timeutils.h>
void addmsec(int32_t *year, int32_t *day, int32_t *msec, int32_t delta)
{
int16_t year1, day1;
double sec1, unixTime;
unixTime = yds2unix(*year, *day, *msec/1000.0) + delta/1000.0;
unix2yds(unixTime, &year1, &day1, &sec1);
*year = year1;
*day = day1;
*msec = sec1*1000.0;
}
|
C
|
/**
* This file, alder_thread_argument.c, is part of alder-thread.
*
* Copyright 2013 by Sang Chul Choi
*
* alder-thread is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* alder-thread 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 alder-thread. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdio.h>
#include <pthread.h>
#include "alder_thread_argument.h"
#define NUM_THREADS 5
struct thread_data{
int thread_id;
int sum;
char *message;
};
struct thread_data thread_data_array[NUM_THREADS];
void *PrintHello(void *threadarg)
{
struct thread_data *my_data = (struct thread_data *) threadarg;
int tid = my_data->thread_id;
int sum = my_data->sum;
printf("Hello World! It's me, thread #%d - sum %d!\n", tid, sum);
pthread_exit(NULL);
}
int alder_thread_argument()
{
pthread_t threads[NUM_THREADS];
int rc;
int t;
for(t=0; t<NUM_THREADS; t++){
printf("In main: creating thread %d\n", t);
thread_data_array[t].thread_id = t;
thread_data_array[t].sum = t + 10;
rc = pthread_create(&threads[t], NULL, PrintHello, (void *) &thread_data_array[t]);
if (rc){
printf("ERROR; return code from pthread_create() is %d\n", rc);
return(-1);
}
}
return 0;
}
|
C
|
#include "Record.h"
#include <stdlib.h>
#include <string.h>
Record * create_record (const char * phone, const char * lastname, const char * firstname,const char * town, float amount)
{
Record *record = (Record *) malloc(sizeof(Record));
if(record == NULL)
return NULL ;
memset(record->phone,'\0',strlen(phone) + 1);
memset(record->lastname,'\0',strlen(lastname) + 1);
memset(record->firstname,'\0',strlen(firstname) + 1);
memset(record->town,'\0',strlen(town) + 1);
strcpy(record->phone, phone);
strcpy(record->lastname, lastname);
strcpy(record->firstname, firstname);
strcpy(record->town,town);
record->amount =amount;
return record;
}
void delete_record(Record * record){
free(record);
}
|
C
|
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <string.h>
#include <unistd.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#define BUFFER_SIZE 1500 //maximum tcp packet size
#define BACKLOG 5 // quantidade de requests até trocar os logs
#define not_blacklisted 1
struct addrinfo hints, *serv_info, host_addr;
struct sockaddr_storage their_addr;
FILE *fd;
/* int verifyWhiteAndBlackList(const char *buffer)
- Retorna um inteiro indicando se está na blacklist (-1), se está na whitelist(1), ou em nenhuma das listas (0)
- Buffer da dados será comparado ao arquivo de blacklst e whitelist
*/
int verifyWhiteAndBlackList(const char *buffer)
{
//Returns 1 case in whitelist
//Returns -1 case in blacklist
//0 otherwise
char *buffer_new = (char *)calloc(BUFFER_SIZE, sizeof(char));
memcpy(buffer_new, buffer, BUFFER_SIZE);
char *url = strstr(buffer_new, "GET ");
if (url != NULL)
{
url += sizeof("GET ") - 1;
char *end = strstr(url, "HTTP") - 1;
url[end - url] = '\0';
}
else
{
printf("url==NULL and buffer_new=%s\n", buffer_new);
return 0;
}
FILE *white_file;
FILE *black_file;
black_file = fopen("blacklist.txt", "r");
white_file = fopen("whitelist.txt", "r");
char line[256];
if (white_file == NULL)
{ //arquivo nao existe
printf("Cant found whitelist.txt\n");
}
else
{ //verifica white list
while (fgets(line, sizeof(line), white_file))
{
int size = strlen(line);
line[size - 1] = '\0';
if (strstr(url, line))
{ //terms is in whitelist
printf("Term (whitelist): %s\n", line);
whiteLogWrite(buffer);
free(buffer_new);
return 1;
}
}
fclose(white_file);
}
if (black_file == NULL)
{
printf("Cant found blacklist.tx\n");
}
else
{
while (fgets(line, sizeof(line), black_file))
{
int size = strlen(line);
line[size - 1] = '\0';
if (strstr(url, line))
{
printf("Term (blacklist): %s\n", line);
blackLogtWrite(buffer);
free(buffer_new);
return -1;
}
}
}
free(buffer_new);
return 1;
}
/* int verifyDenyTerm(const char *buffer)
- Retorna um inteiro indicando se o buffer contém um deny term
- Buffer da dados será comparado ao arquivo de deny terms
*/
int verifyDenyTerm(const char *buffer)
{
//returns -1 if found a deny term
// returns 1 otherwise
FILE *file_terms = NULL;
file_terms = fopen("C:/Users/Bruno/Desktop/UnB/UnB - 2 2017/Teleinformática e redes 2/Trab/websocket/src/denyTerms.txt", "r");
char term[256];
if (!file_terms)
{ //arquivo nao existe
printf("File denyTerms.txt not found\n");
}
else
{
while (fgets(term, sizeof(term), file_terms))
{
int size = strlen(term);
term[size - 1] = '\0';
if (strstr(buffer, term))
{ //termo do arquvo encontrado no buffer
printf("Deny Term found: %s\n", term);
deniedLogWrite(fgets(term, sizeof(term), file_terms));
return -1;
}
}
fclose(file_terms);
}
printf("No deny terms found\n");
return 1;
}
/*void deniedLogWrite(char* term)
- Cria e escreve um arquivo de log com os denied terms
- Denied term a ser escrito no arquivo de log
*/
void deniedLogWrite(char* term)
{
FILE* denied_log;
denied_log = fopen ("websocket/denied_log.txt", "a");
if (denied_log == NULL)
{
printf("Error in denied_log file\n");
} else
{
fprintf(denied_log, "Contains denied term: %s\n",term );
fclose(denied_log);
}
}
/* void blackLogtWrite(const char* buffer)
- Cria e escreve um arquivo de log com as url blacklisted
- Buffer contém a URL da blacklist
*/
void blackLogtWrite(const char* buffer)
{
FILE* black_log;
black_log = fopen ("websocket/black_log.txt", "a");
if (black_log == NULL)
{
printf("Error in black_log file\n");
} else
{
fprintf(black_log, "Tried to request url from blacklist: %s", buffer);
fclose(black_log);
}
}
/*void whiteLogWrite(const char* buffer)
- Cria e escreve um arquivo de log com as url da white list
- Buffer contém a URL da whitelist
*/
void whiteLogWrite(const char* buffer)
{
FILE* log_white;
log_white = fopen ("websocket/white_log.txt", "a");
if (log_white == NULL)
{
printf("Error in white_log file\n");
} else
{
fprintf(log_white, "Tried to request url from blacklist: %s", buffer);
fclose(log_white);
}
}
/* Função de passagem de endereços na socket */
void *get_in_addr(struct sockaddr *sa)
{
if (sa->sa_family == AF_INET)
{
return &(((struct sockaddr_in *)sa)->sin_addr);
}
return &(((struct sockaddr_in6 *)sa)->sin6_addr);
}
int directory(char *host, char *path)
/* Essa função cria os diretórios para o proxy cache. Optou-se por fazer dessa forma ao invés
de salvar apenas as URLs em txt para efeitos de controle se a página já foi ou não acessada
e se está gravada em memória, e verificação dos cabeçalhos. A saída fornece uma flag se a página
está em cache (já foi acessada) ou não (primeira vez de acesso). */
{
struct stat st = {0};
char *temporary = NULL;
char cwd[1024];
if (getcwd(cwd, sizeof(cwd)) != NULL)
printf("..........\n");
else
perror("getcwd() error");
mkdir("cache", 0700);
chdir("cache");
mkdir(host, 0700);
chdir(host);
temporary = strtok(path, "/");
char *extension;
int flag = 0;
while (temporary != NULL)
{
if ((stat(temporary, &st) == -1) && (temporary != NULL))
{
mkdir(temporary, 0700);
flag = 1;
}
chdir(temporary);
extension = temporary;
temporary = strtok(NULL, "/");
}
if (temporary == NULL)
{
if (stat("Homepage", &st) == -1)
{
flag = 1;
}
fd = fopen("Homepage", "a+");
}
else
{
if (stat(extension, &st) == -1)
{
flag = 1;
}
fd = fopen(extension, "a+");
}
return flag;
}
/*! \fn void connect_host(char *host, char *port, char *path, char *v, int newsockfd)
\brief Responsável por fazer a conexão com o host, setando seus parametros
\param host Host passado como parametro ("from host")
\param port Porta passada como parametro inicial (argc)
\param path
\param v
\param newsockfd Socket que recebe os dados de volta
*/
void connect_host(char *host, char *port, char *path, char *v, int newsockfd)
{
struct addrinfo *p;
int newsocket1, sockfd1, n;
memset(&host_addr, 0, sizeof(host_addr));
host_addr.ai_family = AF_UNSPEC;
host_addr.ai_socktype = SOCK_STREAM;
char s[INET6_ADDRSTRLEN];
char buffer[1024];
int rv;
if ((rv = getaddrinfo(host, port, &host_addr, &serv_info)) != 0)
{
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
return 1;
}
for (p = serv_info; p != NULL; p = p->ai_next)
{
//addrinfo->ainext : ponteiro para o prox addrinfo
if ((sockfd1 = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1)
{
perror("client: socket");
continue;
}
if (connect(sockfd1, p->ai_addr, p->ai_addrlen) == -1)
{
//second parameter: addrinfo
// se o status da conexao for 0, ok. se for -1, alguma parte nao pode conectar apropriadamente, close
close(sockfd1);
perror("client: connect");
continue;
}
break;
}
if (p == NULL)
{
fprintf(stderr, "client: failed to connect\n");
return;
}
inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr), s, sizeof s);
sprintf(buffer, "\nConnected to %s IP - %s\n", host, s);
if (not_blacklisted == verifyDenyTerm(host))
{
if (path != NULL)
sprintf(buffer, "GET /%s %s\r\nHost: %s\r\nConnection: close\r\n\r\n", path, v, host);
else
sprintf(buffer, "GET / %s\r\nHost: %s\r\nConnection: close\r\n\r\n", v, host);
// sending:
n = send(sockfd1, buffer, strlen(buffer), 0);
printf("\n%s\n", buffer);
if (n < 0)
perror("Error writing to socket");
else
{
do
{
bzero((char *)buffer, 500);
//receive data froms server and store at buffer
n = recv(sockfd1, buffer, 500, 0);
fprintf(fd, "%s", buffer);
if (n < 0)
perror("Error reading from socket");
else
send(newsockfd, buffer, strlen(buffer), 0);
} while (n > 0);
}
}
}
void cache(char *buffer)
/*Carrega o buffer de armazenamento temporariamente para o cache*/
{
char temporary[128];
while (1)
{
if ((fgets(temporary, 128, fd)) == NULL)
break;
strcat(buffer, temporary);
}
return;
}
int send_file(char *host, char *port, char *path, char *v, int newsockfd)
/* Passagem de arquivos para montagem de novo cabeçalho */
{
struct addrinfo host_addr, *servinfo;
struct addrinfo *p;
int newsocket1, sockfd1, n;
memset(&host_addr, 0, sizeof(host_addr));
host_addr.ai_family = AF_UNSPEC;
host_addr.ai_socktype = SOCK_STREAM;
char s[INET6_ADDRSTRLEN];
char buffer[1024];
int rv;
bzero((char *)buffer, 1024);
cache(buffer);
send(newsockfd, buffer, strlen(buffer), 0);
}
// t1= verbo http, t2 = url, t3 = versão do protocolo
void request(int newsockfd)
/* trabalha nas requisições de servidor, armazenamento em buffer pro cache de acordo com os requisitos de rede e filtragem. Deve
retornar um HTML. */
{
char s[INET6_ADDRSTRLEN];
char buffer[BUFFER_SIZE];
int flag = 0, n, i;
char t1[512], t2[512], t3[16];
char *temporary = NULL;
char *port;
bzero(buffer, BUFFER_SIZE);
recv(newsockfd, buffer, BUFFER_SIZE, 0);
sscanf(buffer, "%s %s %s", t1, t2, t3);
//TODO: verify if blacklisted
if (verifyWhiteAndBlackList(buffer) == not_blacklisted)
{
if (((strncmp(t1, "GET", 3) == 0)) && ((strncmp(t3, "HTTP/1.1", 8) == 0) || (strncmp(t3, "HTTP/1.0", 8) == 0)) && (strncmp(t2, "http://", 7) == 0))
{
strcpy(t1, t2);
flag = 0;
for (i = 7; i < strlen(t2); i++)
{
if (t2[i] == ':')
{
flag = 1;
break;
}
}
temporary = strtok(t2, "//");
if (flag == 0)
{
port = "80";
temporary = strtok(NULL, "/");
}
else
{
temporary = strtok(NULL, ":");
}
sprintf(t2, "%s", temporary);
printf("host = %s", t2);
if (flag == 1)
{
temporary = strtok(NULL, "/");
port = temporary;
}
strcat(t1, "^]");
temporary = strtok(t1, "//");
temporary = strtok(NULL, "/");
if (temporary != NULL)
temporary = strtok(NULL, "^]");
printf("\npath = %s\nPort = %s\n", temporary, port);
i = directory(t2, temporary);
if (i == 1)
{
printf("From Host\n");
connect_host(t2, port, temporary, t3, newsockfd);
}
else
{
printf("From cache\n");
send_file(t2, port, temporary, t3, newsockfd);
}
}
else
{
send(newsockfd, "400 : BAD REQUEST\nONLY HTTP REQUESTS ALLOWED", 44, 0);
}
}
else
{
//TODO url blacklisted. Show html?
}
}
/*! \fn int start_server(int sockfd)
\brief Responsável por iniciar o socket. Retorna o inteiro retornado pela função accept
\param sockfd Socket que será iniciado pela função
*/
int start_server(int sockfd)
{
printf("Server Start Running.........\n");
char s[INET6_ADDRSTRLEN];
socklen_t sin_size;
int newsockfd, pid;
while (1)
{
sin_size = sizeof their_addr;
newsockfd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size);
if (newsockfd == -1)
{
perror("accept");
continue;
}
inet_ntop(their_addr.ss_family, get_in_addr((struct sockaddr *)&their_addr), s, sizeof s);
printf("Connected client:\n");
printf("server:got connection from %s\n", s);
pid = fork();
if (pid == 0)
break;
}
return newsockfd;
}
int set_server(const char *Host, const char *service)
/*Configura o servidor chamanado as funções declaradas anteriormente, bem como algumas da biblioteca socket.h
Utiliza como base Socket API */
{
struct addrinfo *p;
int sim = 1;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
int sockfd;
int i;
int n;
n = getaddrinfo(Host, service, &hints, &serv_info);
if (n != 0)
{
fprintf(stderr, "getaddrinfo %s\n", gai_strerror(n));
return 1;
}
for (p = serv_info; p != NULL; p = p->ai_next)
{
if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1)
{
perror("server:socket\n");
continue;
}
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &sim, sizeof(int)) == -1)
{
perror("setsockopt");
exit(1);
}
if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1)
{
close(sockfd);
perror("server:bind");
continue;
}
break;
}
if (p == NULL)
{
fprintf(stderr, "server: falha ao ligar\n");
return 2;
}
freeaddrinfo(serv_info);
if (listen(sockfd, BACKLOG) == -1)
{
perror("listen");
exit(1);
}
return sockfd;
}
int main(int argc, char **argv)
{
int sockfd, newsockfd;
if (argc < 2)
{
fprintf(stderr, "Indique a porta para o proxy!!!!\n");
exit(1);
}
sockfd = set_server(NULL, argv[1]);
newsockfd = start_server(sockfd);
request(newsockfd);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
r
int spellCheck(char word[],FILE* open){
//fseek(open,0,SEEK_SET); // words belongs the mains threads, i want each thread to start at the beginning
char compare[20];
fgets(compare,sizeof(compare),open);
while(compare != NULL){
if(strcmp(compare,word)==0){
printf("happened\n");
return 0;
}
fgets(compare,sizeof(compare),open);
if(feof(open)){
return 1;
}
}
}
int main(){
char test[20];
printf("gimme a word?\n");
scanf("%s",&test);
strcat(test,"\n");
// it's easier to add the newline terminator to the test word
// that it is to take it away from the fgets i read from words
FILE* open=fopen("words","r");
if(open == NULL){
printf("words not open");
return -1;
}
//int pthread_create(*worker,&spellCheck);
int result = spellCheck(test,open);
if(result == 0){
printf("Spelt correct\n");
printf("%s\n",test);
} else {
printf("Spelt incorrect\n");
printf("%s\n",test);
}
}
|
C
|
/*
* PROJECT 5: NEH Algorithm on Flow Shop Functions
Author: Holly Strauch
CS 471
Project 5
May 31, 2019
This program runs the NEH algorithm on three functions: Flow Shop Scheduling (FSS),
Flow Shop with Blocking (FSB), and Flow Shop with No Wait (FSNW). It is a
combinatorial algorithm which attempts to find the ordering n jobs being
processed in m machines that will results in the minimum amount of total time.
*/
#include "Schedule.h"
#include "Input.h"
#include "Util.h"
#include <stdlib.h>
/** \brief Allocates memory for the Schedule Struct
*
* @param machines Number of machines
* @param jobs Number of jobs
* @return Initialized Schedule strucct
*/
Schedule * initSched(int machines, int jobs){
Schedule *sched = (Schedule *)calloc(1, sizeof(Schedule));
sched->processTime = matrixGenInt(machines, jobs);
sched->schedule = matrixGenInt(machines, jobs);
sched->makespan = 0;
sched->flowTime = 0;
return sched;
}
/** \brief Creates a matrix which is a subset of the complete processing times read in from a file. It is made by
* inserting job into a specified point in an existing permutation of jobs.
*
* @param numJobs The new job being inserted into the existing permutation
* @param index The index at which to insert the new job
* @param perm Int array representing the current permutation
* @param in Input struct with algorithm data
* @return
*/
Schedule *create_sched(int numJobs, int index, int *perm, Input *in){
int i=0, j=0;
Schedule *sched = initSched(in->machines, numJobs);
for(j = numJobs - 1; j >= 0; j--){
for(i = 0; i < in->machines; i++) {
if(j > index){
sched->processTime[i][j] = in->processTimeComplete[i][perm[j-1]];
}else if(j == index){
sched->processTime[i][j] = in->processTimeComplete[i][in->order[numJobs-1]];
}else if(j < index){
sched->processTime[i][j] = in->processTimeComplete[i][perm[j]];
}
}
}
return sched;
}
/** \brief Calculates flow time for FS No Wait by summing all the departure values for the final machine
*
* @param machines The number of machines
* @param jobs Number of jobs
* @param sched The Schedule struct with the departure times and where the flowTime is being set
*/
void setFlowTime(int machines, int jobs, Schedule *sched){
int i = 0;
for (i = 0; i < jobs; i++){
sched->flowTime += sched->schedule[machines-1][i];
}
}
/** \brief Frees the memory for a Schedule struct
*
* @param machines The number of machines in the schedule
* @param sched The Schedule struct being freed
*/
void freeSchedule(int machines, Schedule *sched){
freematrix(machines, sched->schedule);
freematrix(machines, sched->processTime);
free(sched);
}
|
C
|
/*
* rgb color convert:
* ---> hex 00 00 00 ~ ff ff ff
* ---> hsl hue(0~360) saturation(0~1) lightness(0-1)
* ---> hsb/hsv hue(0~360) saturation(0~1) value/brightness(0-1)
* ---> cmyk cyan(0-1) magenta(0-1) yellow(0-1) black(0-1)
*/
#include <stdio.h>
#include <string.h>
typedef struct RGBvalue {
int r;
int g;
int b;
}RGB_t;
void rgb2hex(RGB_t rgb)
{
char hex[7];
sprintf(hex,"%02x%02x%02x",rgb.r,rgb.g,rgb.b);
printf("#%s\n",hex);
}
void rgb2hsv(RGB_t rgb)
{
int r = rgb.r;
int g = rgb.g;
int b = rgb.b;
int max = (r > g) ? (r > b ? r : b) : (g > b ? g : b);
int min = (r < g) ? (r < b ? r : b) : (g < b ? g : b);
int pan = max - min;
int h;
if (pan == 0){
h = 0;
}
else if(max == r){
if( g >= b ){
h = 60*(g-b)/pan;
}
else{
h = 60*(g-b)/pan+360;
}
}
else if(max == g){
h = 60*(b-r)/pan+120;
}
else if(max == b){
h = 60*(r-g)/pan+240;
}
float s = max ? pan*1.0/max : 0;
float v = max*1.0/255;
printf("h:%dD s:%g%% v:%g%%\n",h,s*100,v*100);
}
void rgb2hsl(RGB_t rgb)
{
int r = rgb.r;
int g = rgb.g;
int b = rgb.b;
int max = (r > g) ? (r > b ? r : b) : (g > b ? g : b);
int min = (r < g) ? (r < b ? r : b) : (g < b ? g : b);
int pan = max - min;
int uni = max + min;
int h;
if (pan == 0){
h = 0;
}
else if(max == r){
if( g >= b ){
h = 60*(g-b)/pan;
}
else{
h = 60*(g-b)/pan+360;
}
}
else if(max == g){
h = 60*(b-r)/pan+120;
}
else if(max == b){
h = 60*(r-g)/pan+240;
}
float s;
if(pan == 0 || uni == 0){
s = 0;
}
else if(uni <= 128){
s = pan*1.0/uni;
}
else{
s = pan*1.0/(510-uni);
}
float l = uni*1.0/510;
printf("h:%dD s:%g%% l:%g%%\n",h,s*100,l*100);
}
void rgb2cmyk(RGB_t rgb)
{
int r = rgb.r;
int g = rgb.g;
int b = rgb.b;
int max = (r > g) ? (r > b ? r : b) : (g > b ? g : b);
int min = (r < g) ? (r < b ? r : b) : (g < b ? g : b);
float C = 1-r*1.0/255;
float M = 1-g*1.0/255;
float Y = 1-b*1.0/255;
float k = (C < M) ? (C < Y ? C : Y) : (M < Y ? M : Y);
if(k == 1.0f){
puts("c:0 m:0 y:0 k:1");
}
else if(k > 0.0f){
float c = (C-k)/(1-k);
float m = (M-k)/(1-k);
float y = (Y-k)/(1-k);
printf("c:%g m:%g y:%g k:%g\n",c,m,y,k);
}
}
void rgb2cmy(RGB_t rgb)
{
int r = rgb.r;
int g = rgb.g;
int b = rgb.b;
float c = (1-r*1.0/255);
float m = (1-g*1.0/255);
float y = (1-b*1.0/255);
printf("c:%g%% m:%g%% y:%g%%\n",c*100,m*100,y*100);
}
int ch2i(char c)
{
if (c >= 'a' && c <= 'f'){
c = c - 'a' + 10;
}
else if (c >= 'A' && c <= 'F'){
c = c - 'A' + 10;
}
else if(c >='0' && c <= '9'){
c = c - '0';
}
else{
return 0;
}
return c;
}
void hex2rgb(char* hex)
{
int r=0, g=0, b=0;
r = ch2i(hex[0]) * 16 + ch2i(hex[1]);
g = ch2i(hex[2]) * 16 + ch2i(hex[3]);
b = ch2i(hex[4]) * 16 + ch2i(hex[5]);
printf("r:%d g:%d b:%d\n", r, g, b);
}
int main(int argc, const char* argv[])
{
// RGB_t rgb = {0,2,10};
// rgb2hex(rgb);
// rgb2hsv(rgb);
// rgb2hsl(rgb);
// rgb2cmyk(rgb);
// rgb2cmy(rgb);
hex2rgb("Ff0aaa");
return 0;
}
|
C
|
// Unit Test Framework Includes
#include "atf.h"
// File To Test
#include <stdc.h>
#include <bstree.h>
typedef struct {
bstree_node_t node;
int val;
} int_node_t;
int compare(bstree_node_t* a, bstree_node_t* b)
{
int_node_t* nodea = container_of(a, int_node_t, node);
int_node_t* nodeb = container_of(b, int_node_t, node);
return (nodea->val < nodeb->val) ? -1 : (nodea->val > nodeb->val) ? 1 : 0;
}
//-----------------------------------------------------------------------------
// Begin Unit Tests
//-----------------------------------------------------------------------------
TEST_SUITE(BSTree) {
//-------------------------------------------------------------------------
// bstree_init
//-------------------------------------------------------------------------
TEST(Verify_bstree_init_should_init_the_tree)
{
bstree_t tree;
bstree_init(&tree, NULL, true);
CHECK(tree.root == NULL);
CHECK(tree.cmpfn == NULL);
CHECK(tree.allow_dups == true);
}
//-------------------------------------------------------------------------
// bstree_empty
//-------------------------------------------------------------------------
TEST(Verify_bstree_empty_should_return_true_if_the_tree_is_empty)
{
bstree_t tree = { 0, 0, 0 };
CHECK(bstree_empty(&tree));
}
TEST(Verify_bstree_empty_should_return_false_if_the_tree_is_not_empty)
{
bstree_t tree = { (bstree_node_t*)0x1234, NULL, false };
CHECK(!bstree_empty(&tree));
}
//-------------------------------------------------------------------------
// bstree_size
//-------------------------------------------------------------------------
TEST(Verify_bstree_size_should_return_0_for_empty_tree)
{
bstree_t tree = { 0, 0, 0 };
CHECK(0 == bstree_size(&tree));
}
TEST(Verify_bstree_size_should_return_1)
{
bstree_node_t node1 = { NULL, NULL };
bstree_t tree = { &node1, NULL, false };
CHECK(1 == bstree_size(&tree));
}
TEST(Verify_bstree_size_should_return_2)
{
bstree_node_t node2 = { NULL, NULL };
bstree_node_t node1 = { &node2, NULL };
bstree_t tree = { &node1, NULL, false };
CHECK(2 == bstree_size(&tree));
}
TEST(Verify_bstree_size_should_return_3)
{
bstree_node_t node3 = { NULL, NULL };
bstree_node_t node2 = { NULL, NULL };
bstree_node_t node1 = { &node2, &node3 };
bstree_t tree = { &node1, NULL, false };
CHECK(3 == bstree_size(&tree));
}
//-------------------------------------------------------------------------
// bstree_insert
//-------------------------------------------------------------------------
TEST(Verify_bstree_insert_should_insert_into_empty_tree)
{
int_node_t node = { {0,0}, 42 };
bstree_t tree = { NULL, compare, false };
bstree_insert(&tree, &(node.node));
CHECK(tree.root = &(node.node));
}
TEST(Verify_bstree_insert_should_insert_to_the_left)
{
int_node_t node1 = { {0,0}, 42 };
int_node_t node2 = { {0,0}, 41 };
bstree_t tree = { &(node1.node), compare, false };
bstree_insert(&tree, &(node2.node));
CHECK(tree.root->left = &(node2.node));
}
TEST(Verify_bstree_insert_should_insert_to_the_right)
{
int_node_t node1 = { {0,0}, 42 };
int_node_t node2 = { {0,0}, 43 };
bstree_t tree = { &(node1.node), compare, false };
bstree_insert(&tree, &(node2.node));
CHECK(tree.root->right = &(node2.node));
}
//-------------------------------------------------------------------------
// bstree_lookup
//-------------------------------------------------------------------------
TEST(Verify_bstree_lookup_should_not_find_the_item_in_an_empty_tree)
{
int_node_t node1 = { {0,0}, 42 };
bstree_t tree = { NULL, compare, false };
CHECK(bstree_lookup(&tree, &(node1.node)) == NULL);
}
TEST(Verify_bstree_lookup_should_find_the_item_at_the_root)
{
int_node_t node1 = { {0,0}, 42 };
bstree_t tree = { &(node1.node), compare, false };
CHECK(bstree_lookup(&tree, &(node1.node)) == &(node1.node));
}
TEST(Verify_bstree_lookup_should_find_the_item_to_the_left)
{
int_node_t node2 = { {0,0}, 41 };
int_node_t node1 = { {&(node2.node),0}, 42 };
bstree_t tree = { &(node1.node), compare, false };
CHECK(bstree_lookup(&tree, &(node2.node)) == &(node2.node));
}
TEST(Verify_bstree_lookup_should_find_the_item_to_the_right)
{
int_node_t node2 = { {0,0}, 43 };
int_node_t node1 = { {0,&(node2.node)}, 42 };
bstree_t tree = { &(node1.node), compare, false };
CHECK(bstree_lookup(&tree, &(node2.node)) == &(node2.node));
}
}
|
C
|
#include <bits/stdc++.h>
using namespace std;
#define MOD 1000000007
long long dp[100005];
long long power(long long N, long long expo)
{
long long ans = 1;
cout << "came inside power with n="<< n<< " and expo ="<< expo<< endl;
while(expo)
{
cout << "came inside while with expo ="<< expo<< endl;
if(expo%2)
ans = ans*N%MOD;
cout << "ans ="<< ans<< endl;
N = N*N%MOD;
expo/= 2;
}
return ans;
}
int main(){
int n;
cin >> n;
dp[2] = 2;
for(int i=3; i<=5; i++)
dp[i] = dp[i-1]*i%MOD*i%MOD*power(i-1, MOD-2)%MOD;
cout << dp[n] << endl;
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "LinkedList.h"
#include "envios.h"
#include "parser.h"
#include "validaciones.h"
//int idMaxArray(LinkedList* pArrayLibros);
/** \brief Carga los datos desde el archivo data.csv (modo texto).
*
* \param path char*
* \param pArrayListEmployee LinkedList*
* \return int
*
*/
int controller_loadFromText(char* path, LinkedList* pArrayListEnvios)
{
int retorno = -1;
FILE* fAux=NULL;
if(path != NULL && pArrayListEnvios != NULL)
{
fAux = fopen(path, "r");
if(fAux != NULL)
{
if(!parser_EnviosFromText(fAux,pArrayListEnvios))
{
printf("El archivo se cargo existosamente en modo texto!");
retorno = 0;
}
}
//fclose(fAux);
}
return retorno;
}
/** \brief Carga los datos de los empleados desde el archivo data.csv (modo binario).
*
* \param path char*
* \param pArrayListEmployee LinkedList*
* \return int
*
*/
/*int controller_loadFromBinary(char* path, LinkedList* pArrayListEmployee)
{
int retorno = -1;
FILE* pFile = NULL;
if(path != NULL && pArrayListEmployee != NULL)
{
pFile = fopen(path, "rb");
if(pFile != NULL && !parser_EmployeeFromBinary(pFile,pArrayListEmployee))
{
printf("El archivo se cargo existosamente en modo binario!");
retorno = 0;
}
}
return retorno;
}*/
/** \brief Alta de empleados
*
* \param path char*
* \param pArrayListEmployee LinkedList*
* \return int
*
*/
/*int controller_addEmployee(LinkedList* pArrayListEmployee)
{
char nombre[50];
char horasTrabajadas[20];
char sueldo[20];
char idTex[20];
int id;
int retorno=-1;
Employee* pAuxiliar;
if(pArrayListEmployee!=NULL)
{
id=idMaxArray(pArrayListEmployee)+1;
sprintf(idTex,"%d",id);
if( !getName("\n Ingrese nombre de empleado: ", "\n Error",1,50,1,nombre) &&
!getInt("\n Ingrese horas trabajadas: ", "\n Error",1,21,1,horasTrabajadas) &&
!getInt("\n Ingrese sueldo: ", "\n Error",1,21,1,sueldo))
{
pAuxiliar= employee_newParametros(idTex,nombre,horasTrabajadas,sueldo);
if(pAuxiliar != NULL)
{
ll_add(pArrayListEmployee,pAuxiliar);
retorno = 0;
}
}
}
return retorno;
}*/
/*int idMaxArray(LinkedList* pArrayLibros)
{
int retorno = -1;
eLibros* pAux;
int idAux;
int idMax = -1;
if(pArrayLibros != NULL)
{
for(int i = 0; i<ll_len(pArrayLibros); i++)
{
pAux = ll_get(pArrayLibros,i);
libros_getId(pAux, &idAux);
if(idAux>idMax)
{
idMax = idAux;
}
}
}
retorno = idMax;
return retorno;
}*/
/*int buscarPorId(LinkedList* pArrayEmpleado, int id)
{
int i;
int retorno = -1;
Employee* auxEmployee = NULL;
int idEmployee;
if (pArrayEmpleado!=NULL && id>=0)
{
for(i=0; i<ll_len(pArrayEmpleado); i++)
{
auxEmployee = ll_get(pArrayEmpleado,i);
if(auxEmployee != NULL)
{
employee_getId(auxEmployee,&idEmployee);
if(idEmployee == id)
{
retorno=i;
break;
}
}
}
}
return retorno;
}*/
/** \brief Listar empleados
*
* \param path char*
* \param pArrayListEmployee LinkedList*
* \return int
*
*/
int controller_ListEnvios(LinkedList* pArrayListEnvios)
{
int retorno = -1;
int id;
char nombre[51];
int kilometros;
int tipoDeEntregas;
Envios* pAux;
//printf("entro aca");
if(pArrayListEnvios != NULL)
{
for(int i =0; i<ll_len(pArrayListEnvios); i++)
{
//printf("entro aca");
//printf("I:%d - ",i);
pAux=ll_get(pArrayListEnvios,i);
//llamadas_getIdProblema(pArrayListLLamadas,pAux);
if(pAux != NULL)
{
envios_getId(pAux,&id);
envios_getNombre(pAux,nombre);
envios_getKilometros(pAux,&kilometros);
envios_getTipoDeEntrega(pAux,&tipoDeEntregas);
switch(tipoDeEntregas)
{
case 1:
printf("%d --",id);
printf("%s --",nombre);
printf("%d --",kilometros);
printf("normal\n\n");
break;
case 2:
printf("%d --",id);
printf("%s --",nombre);
printf("%d --",kilometros);
printf("express\n\n");
break;
case 3:
printf("%d --",id);
printf("%s --",nombre);
printf("%d --",kilometros);
printf("Segun disponibilidad\n\n");
}
}
}
retorno = 0;
}
return retorno;
}
//printf("Menu 6 -----
/** \brief Modificar datos de empleado
*
* \param path char*
* \param pArrayListEmployee LinkedList*
* \return int
*
*/
/*int controller_editEmployee(LinkedList* pArrayListEmployee)
{
int retorno=-1;
int posEmployee=-1;
int idEmployee;
int opcion;
Employee* auxEmployee;
char nombre[51];
char horasTrabajadas[51];
char sueldo[51];
if(pArrayListEmployee != NULL)
{
controller_ListEmployee(pArrayListEmployee);
if(!getEntero("Ingrese el ID a modificar","ID invalido",0,ll_len(pArrayListEmployee),1,&idEmployee))
{
posEmployee=buscarPorId(pArrayListEmployee,idEmployee);
auxEmployee = ll_get(pArrayListEmployee,posEmployee);
getEntero("1)Modificar Nombre\n2)Modificar horas trabajadas\n3)Modificar sueldo\n","Opcion invalida!\n",1,3,1,&opcion);
switch(opcion)
{
case 1:
if(!getName("Ingrese nuevo nombre:","nombre invalido",2,51,3,nombre))
{
if(!employee_setNombre(auxEmployee,nombre))
{
printf("Nombre modificado correctamente");
}
}
break;
case 2:
if(!getInt("Ingrese nuevo horas trabajadas:\n","Horas invalidas",1,5,3,horasTrabajadas))
{
employee_setHorasTrabajadas(auxEmployee,atoi(horasTrabajadas));
printf("Horas modificadas correctamente");
}
break;
case 3:
if(!getInt("Ingrese nuevo sueldo:\n","Sueldo invalido",1,8,3,sueldo))
{
employee_setSueldo(auxEmployee,atoi(sueldo));
printf("Sueldo modificado correctamente");
}
break;
}
retorno = 0;
}
}
return retorno;
}*/
/** \brief Baja de empleado
*
* \param path char*
* \param pArrayListEmployee LinkedList*
* \return int
*
*/
/*int controller_removeEmployee(LinkedList* pArrayListEmployee)
{
int retorno = -1;
int IDABorrar;
int posIDABorrar;
Employee* auxEmployee;
if(pArrayListEmployee != NULL)
{
controller_ListEmployee(pArrayListEmployee);
getEntero("Ingrese ID a borrar: \n","ID no encontrado",0,ll_len(pArrayListEmployee),1,&IDABorrar);
posIDABorrar = buscarPorId(pArrayListEmployee,IDABorrar);
auxEmployee = ll_pop(pArrayListEmployee,posIDABorrar);
if(auxEmployee != NULL)
{
employee_delete(auxEmployee);
printf("Empleado eliminado correctamente");
retorno = 0;
}
}
return retorno;
}*/
/** \brief Ordenar empleados
*
* \param path char*
* \param pArrayListEmployee LinkedList*
* \return int
*
*/
/*int controller_sortEmployee(LinkedList* pArrayListEmployee)
{
int retorno = -1;
if(pArrayListEmployee != NULL)
{
ll_sort(pArrayListEmployee,employee_comparacionNombre,0);
retorno = 0;
}
return retorno;
}*/
/** \brief Guarda los datos de los empleados en el archivo data.csv (modo texto).
*
* \param path char*
* \param pArrayListEmployee LinkedList*
* \return int
*
*/
int controller_saveAsText(char* path, LinkedList* pArrayListEnvios)
{
int retorno = -1;
Envios* auxEnvios;
FILE* pFile;
int i;
int id;
char nombre[51];
int kilometros;
int tipoDeEntrega;
float precio;
int costo;
if(path != NULL && pArrayListEnvios != NULL)
{
pFile = fopen(path,"w");
if(pFile != NULL)
{
for(i=0; i<ll_len(pArrayListEnvios); i++)
{
auxEnvios = ll_get(pArrayListEnvios,i);
if(auxEnvios != NULL)
{
envios_getId(auxEnvios, &id);
envios_getNombre(auxEnvios,nombre);
envios_getKilometros(auxEnvios,&kilometros);
envios_getTipoDeEntrega(auxEnvios, &tipoDeEntrega);
envios_getPrecio(auxEnvios,&precio);
envios_getCosto(auxEnvios,&costo);
fprintf(pFile,"%d,%s,%d,%d,%.2f,%d\n",id,nombre,kilometros,tipoDeEntrega,precio,costo);
}
}
retorno = 0;
fclose(pFile);
}
}
return retorno;
}
int controller_costoTipoEntrega(void* p)
{
int tipo;
int costo;
if(p!=NULL)
{
envios_getTipoDeEntrega((Envios*)p,&tipo);
envios_getCosto(p,&costo);
if(tipo==1)
{
costo=330;
}else if(tipo==2)
{
costo = 560;
}else if(tipo==3){
costo =80;
}
envios_setCosto((Envios*)p,costo);
}
return 1;
}
int controller_aumentoPorKilometros(void* p)
{
float precio=0;
int kilometros;
if(p!=NULL)
{
envios_getPrecio((Envios*)p,&precio);
envios_getKilometros(p,&kilometros);
if(kilometros<=50)
{
precio=67;
precio=precio*kilometros;
}else if(kilometros>50)
{
precio = 80;
precio=precio*kilometros;
}
envios_setPrecio((Envios*)p,precio);
}
return 1;
}
|
C
|
#ifndef VARIADIC_FUNCTIONS_H
#define VARIADIC_FUNCTIONS_H
#include <stdarg.h>
/**
* struct op - points to list of args in op_t
* @op: operator points to column 0 opt_t
* @f: points to functions in coumn 1 op_t
*
*/
typedef struct op
{
char *op;
void (*f)();
} op_t;
void print_all(const char * const format, ...);
int sum_them_all(const unsigned int n, ...);
void print_numbers(const char *separator, const unsigned int n, ...);
void print_strings(const char *separator, const unsigned int n, ...);
void _putchar(char);
#endif
|
C
|
/*
Luke Winker
22 January 2019
Software Engineering
*/
#include <stdio.h>
int main()
{
printf("The size of int is %1u \n", sizeof(int));
printf("The size of char is %1u \n", sizeof(char));
printf("The size of long is %1u \n", sizeof(long));
printf("The size of float is %1u \n", sizeof(float));
printf("The size of double is %1u \n", sizeof(double));
printf("The size of unsigned int is %1u \n", sizeof(unsigned));
printf("The size of unsigned char is %1u \n", sizeof(unsigned char));
printf("The size of unsigned long is %lu \n", sizeof(unsigned long));
printf("The size of int * is %1u \n", sizeof(int *));
printf("The size of char * is %1u \n", sizeof(char *));
printf("The size of long * is %1u \n", sizeof(long *));
}
|
C
|
// FUNCTIONS TO CORRECTLY READ THE CONFIGURATION FILE
#define CONFIG "datarepo.conf" //name of the configuration file
#define COMMENT '#' //character that defines a comment line
#define MAX_ARGS 2 //every line is structured as lhs=rhs, so the tokenize array only needs 2 fields
void readConfig (short unsigned int* serv_port) {
int tmp = *serv_port;
char* buf = (char*)malloc(BUF_SIZE * sizeof(char));
char** args = (char**)malloc(MAX_ARGS);
size_t len;
FILE* fp;
// Open and check if the file exists
if ((fp = fopen(CONFIG, "r")) == NULL) return;
// Read the conf file line per line
while (getline(&buf, &len, fp) != -1) {
buf[strlen(buf)-1] = '\0';
printf("[-] Reading line. Content: \"%s\"\n", buf);
//If the first line is a comment, skip it
if (buf[0] == '#') continue;
//Tokenize the line
tokenize(buf, &args);
printf("[-] tokenized: \"%s\", \"%s\"\n", args[0], args[1]);
//Look at args[0] to see the left hand side of the assignment
if (!strcmp(args[0], "port")) {
printf("%s\n", args[1]);
*serv_port = atoi(args[1]);
}
}
free(buf);
free(args);
fclose(fp);
return;
}
|
C
|
#include<stdio.h>
#include<math.h>
#define szer 50
#define wys 40
#define dol_x -0.9
#define gora_x 8
#define dol_y -2.5
#define gora_y 2.5
float funkcja_a (float x) {
return x*x*x/27 - x*x*2/9 + x/3 + 2;
}
float funkcja_b (float x) {
// return ((x-2)*x-1)*x+2;
return log(x+1);
}
char rysunek[szer][wys];
void rysuj(int x, int y, char znak) {
if (0<=x && x<szer && 0<=y && y<wys)
rysunek[x][y] = znak;
}
int interpoluj (float x, float a, float b, int n) {
return floor((x-a)*n/(b-a));
}
int f_a (int x) {
return interpoluj(funkcja_a((gora_x-dol_x)/szer*x+dol_x), dol_y,
gora_y, wys);
}
int f_b (int x) {
return interpoluj(funkcja_b((gora_x-dol_x)/szer*x+dol_x), dol_y,
gora_y, wys);
}
main () {
int x,y, poziom, pion;
printf("\nWYKRES FUNKCJI:\n\n ");
for (x=0; x<szer; x=x+1)
for (y=0; y<wys; y=y+1)
rysuj(x, y, ' ');
pion = interpoluj(0, dol_x, gora_x, szer);
for(y=0; y<wys; y=y+1)
rysuj(pion, y, '|');
poziom = interpoluj(0, dol_y, gora_y, wys);
for(x=0; x<szer; x=x+1)
rysuj(x, poziom, '-');
rysuj(pion, poziom, '+');
for (x=0; x<szer; x=x+1)
rysuj(x, f_b(x), '*');
for (x=0; x<szer; x=x+1)
rysuj(x, f_a(x), 'o');
for (y=wys-1; y>=0; y=y-1) {
for (x=0; x<szer; x=x+1)
printf("%c", rysunek[x][y]);
printf("\n ");
}
printf("\n\n");
}
|
C
|
#include <stdio.h>
int linearRecursive(int arr[], int el, int i, int end)
{
if (i < end)
{
if (arr[i] == el)
return i;
else
return linearRecursive(arr, el, i + 1, end);
}
return -1;
}
void main()
{
int x[] = {9, 6, 4, 24, 56, 34, 23, 6, 7, 34, 23};
int term, length = 11;
printf("Enter search term: ");
scanf("%d", &term);
int index = linearRecursive(x, term, 0, length - 1);
if (index != -1)
printf("Found %d at position %d", term, index + 1);
else
printf("%d is not there in the entered array", term);
}
|
C
|
/** @brief: Este programa configura el BCM_GPIO 17 usando la libreria wiringPi
* El GPIO 17 corresponde con el pin 0 en wiring Pi
* Se debe compilar con: gcc gpio.c -o gpio -lwiringpi
*
*
* gcc gpio.c -o gpio -lwiringPi
*
*
*/
#include<stdio.h>
#include<unistd.h>
#include<wiringPi.h>
int main( )
{
//Se inicializa la libreria wiring Pi
wiringPiSetup();
//Se configura el GPIO 17 como salida
pinMode( 0, OUTPUT );
pinMode( 2, OUTPUT );
//Se escribe un valor digital al GPIO
while( 1 )
{
digitalWrite( 0,0 );
digitalWrite( 2,0 );
printf("\nReele se cierra en cero \n");
sleep(4);
printf("\nReele se abre en uno\n");
digitalWrite( 0, 1 );
digitalWrite( 2, 1 );
sleep(4);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define dim 3
#define size_dim 129
#define size (size_dim*size_dim*size_dim)
void read_turbulence(double **turb_array)
{
printf("Reading grid turbulence file\n");
FILE *turb_in = fopen("turbulence19.txt", "r"); /// file generated by the turbulence_generator.py
double dummy1, dummy2, dummy3;
int i;
for (i=0;i<size; i++)
{
fscanf(turb_in, "%lf %lf %lf %lf %lf %lf\n", &dummy1, &dummy2, &dummy3, &turb_array[0][i], &turb_array[1][i], &turb_array[2][i]) ;
}
fclose(turb_in);
}
void normalize_turbulence(double **turb_array, double **normal_turb )
{
printf("Normalizing energy of velocity field\n");
int i;
double Z=0;
for (i=0;i<size; i++)
{
Z = Z + (0.5*( pow(turb_array[0][i],2.0) + pow(turb_array[1][i],2.0) + pow(turb_array[2][i],2.0) ) );
}
int j; double z0=0;
for (j=0;j<size;j++)
{
normal_turb[0][j] = turb_array[0][j] / sqrt(Z);
normal_turb[1][j] = turb_array[1][j] / sqrt(Z);
normal_turb[2][j] = turb_array[2][j] / sqrt(Z);
z0 = z0 + (0.5*( pow(normal_turb[0][j],2.0) + pow(normal_turb[1][j],2.0) + pow(normal_turb[2][j],2.0) ));
}
printf("\tNormalization = %f\n", z0);
}
void write_turbulence(double **v_b)
{
printf("Writing normalized turbulence\n");
FILE *write = fopen("t19_vn_grid.txt", "w"); //// name of the file to be written
int j;
for (j=0;j<size; j++)
{
fprintf(write, "%e %e %e\n", v_b[0][j], v_b[1][j], v_b[2][j]) ;
}
fclose(write);
}
void freeArray(double **a) {
int i;
for (i = 0; i < dim; i++) {
free(a[i]);
}
free(a);
}
int main()
{
printf("Commencing calculation\n");
///-----------------------------------------------///
///////////////////Define arrays////////////////////
double **v;
double **v_normal;
v = malloc(dim * sizeof(double *));
v_normal = malloc(dim * sizeof(double *));
if(v == NULL)
{
fprintf(stderr, "out of memory--v\n");
}
else if(v_normal == NULL)
{
fprintf(stderr, "out of memory--v_normal\n");
}
int i;
for(i = 0; i < dim; i++)
{
v[i] = malloc(size * sizeof(double));
v_normal[i] = malloc(size * sizeof(double));
if( v[i] == NULL || v_normal[i] == NULL)
{
fprintf(stderr, "out of memory----\n");
}
}
///-----------------------------------------------///
///-----------------------------------------------///
read_turbulence(v); //read turbulence file
normalize_turbulence(v, v_normal); ///normalize turbulence
write_turbulence(v_normal); // write turbulence
///-----------------------------------------------///
freeArray(v);
freeArray(v_normal);
printf("Calculation complete\n");
return 0;
}
|
C
|
//SINGLY LINKED LIST IMPLEMENTATION IN C LANGUAGE:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
struct node{
int data;
struct node * next;
}*head=NULL;
void insertbegin(int x);
void insertmid(int x);
void insertlast(int x);
int deletebegin();
int deletelast( );
int deletemid();
int getsize();
void displaylist();
int main(){
int pos,x,s=1;
while(s!=9){
printf("Select your choice:\n");
printf("1.Insert at the beginning of the list\n");
printf("2.Insert at the middle of the list\n");
printf("3.Insert at the end of the list\n");
printf("4.Delete at the beginning of the list\n");
printf("5.Delete at the middle of the list\n");
printf("6.Delete at the end of the list\n");
printf("7.Get the length of the list\n");
printf("8.Display the list\n");
printf("9.Exit\n");
scanf("%d",&s);
switch(s){
case 1: printf("Enter the number that you want to insert:\n");
scanf("%d",&x);
insertbegin(x);
break;
case 2:printf("Enter the number that you want to insert:\n");
scanf("%d",&x);
insertmid(x);
break;
case 3:printf("Enter the number that you want to insert:\n");
scanf("%d",&x);
insertlast(x);
break;
case 4:deletebegin();
break;
case 5:deletemid();
break;
case 6:deletelast();
break;
case 7:printf("The size of the list is %d\n",getlength());
break;
case 8:displaylist();
break;
case 9: printf("Thanks!\n");
break;
default:printf("Please enter a valid choice\n");
break;
}
}
return 0;
}
//FUNCTION TO INSERT AN ELEMENT IN THE BEGINNING OF THE LIST
void insertbegin(int x){
struct node *newnode;
newnode = (struct node * )malloc(sizeof(struct node));
newnode->data=x;
if(head==NULL){
newnode->next=NULL;
head=newnode;
}
else{
newnode->next=head;
head=newnode;
}
}
//FUNCTION TO INSERT AN ELEMENT IN THE MIDDLE OF THE LIST
void insertmid(int x){
struct node *newnode;
newnode=(struct node *)malloc(sizeof(struct node));
newnode->data=x;
if(head==NULL){
printf("The linked list is empty so the element will be added at the beginning\n");
newnode->next=NULL;
head=newnode;
}
else{
int pos;
printf("Enter the position at which you want to insert your number:\n");
scanf("%d",&pos);
if (pos==1){
newnode->next=head;
head=newnode;
}
else{
struct node *traverser=head;
int i=0;
for(i=0;i<pos-2;i++){
traverser=traverser->next;
}
newnode->next=traverser->next;
traverser->next=newnode;
}
}
}
//FUNCTION TO INSERT AN ELEMENT AT THE LAST OF THE LIST
void insertlast(int x){
struct node *newnode;
newnode=(struct node *)malloc(sizeof(struct node ));
newnode->data=x;
if(head==NULL){
newnode->next=NULL;
head=newnode;
}
else{
struct node *traverser=head;
while(traverser->next!=NULL){
traverser=traverser->next;
}
traverser->next=newnode;
newnode->next=NULL;
}
}
//FUNCTION TO DELETE THE FIRST ELEMENT FROM THE LIST
int deletebegin(){
if(head==NULL){
printf("The linked list is empty\n");
}
else{
struct node *temp=head;
head=temp->next;
printf("The removed element is :%d\n",temp->data);
free(temp);
}
}
//FUNCTION TO DELETE THE LAST ELEMENT OF THE LIST
int deletelast(){
if(head==NULL){
printf("The linked list is empty\n");
}
else if(getlength()==1){
struct node *temp=head;
head=temp->next;
printf("The removed element is :%d\n",temp->data);
free(temp);
}
else{
struct node *traverser=head;
struct node *temp;
while(traverser->next->next!=NULL){
traverser=traverser->next;
}
temp=traverser->next;
traverser->next=NULL;
printf("The removed element is :%d\n",temp->data);
free(temp);
}
}
//FUNCTION TO DELETE AN ELEMENT FROM THE LIST WHICH IS IN THE MIDDLE
int deletemid(){
if(head==NULL){
printf("The linked list is empty\n");
}
else{
int pos;
printf("Enter the position at which you want the element to be deleted:\n");
scanf("%d",&pos);
if(pos==1){
struct node *temp=head;
head=temp->next;
printf("The removed element is :%d\n",temp->data);
free(temp);
}
else{
struct node *temp=head;
int i=0;
for(i=0;i<pos-2;i++){
temp=temp->next;
}
struct node *temp2=temp->next;
temp->next=temp2->next;
printf("The removed element is :%d\n",temp2->data);
free(temp2);
}
}
}
//FUNCTION TO GET THE LENGTH OF THE LINKED LIST
int getlength(){
int size=0; //VARIABLE TO STORE THE SIZE OF THE LIST
struct node *traverser=head;
while(traverser!=NULL){
traverser=traverser->next;
size++;
}
return size;
}
//FUNCTION TO DISPLAY THE LIST
void displaylist(){
if(head==NULL){
printf("The linked list is empty\n");
}
else{
printf("The linked list is : ");
struct node *traverser=head;
while(traverser!=NULL){
printf("%d ",traverser->data);
traverser=traverser->next;
}
printf("\n");
}
}
|
C
|
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include "E_Ofono.h"
static void
_method_success_check(void *data, DBusMessage *msg __UNUSED__, DBusError *error)
{
const char *name = data;
if ((!error) || (!dbus_error_is_set(error)))
{
printf("SUCCESS: method %s() finished successfully.\n", name);
return;
}
printf("FAILURE: method %s() finished with error: %s %s\n",
name, error->name, error->message);
dbus_error_free(error);
}
static void
_elements_print(E_Ofono_Element **elements, unsigned int count)
{
unsigned int i;
for (i = 0; i < count; i++)
{
printf("--- element %d:\n", i);
e_ofono_element_print(stdout, elements[i]);
}
free(elements);
printf("END: all elements count = %u\n", count);
}
static Eina_Bool
_on_element_add(void *data __UNUSED__, int type __UNUSED__, void *info)
{
E_Ofono_Element *element = info;
printf(">>> %s %s\n", element->path, element->interface);
return EINA_TRUE;
}
static Eina_Bool
_on_element_del(void *data __UNUSED__, int type __UNUSED__, void *info)
{
E_Ofono_Element *element = info;
printf("<<< %s %s\n", element->path, element->interface);
return EINA_TRUE;
}
static Eina_Bool
_on_element_updated(void *data __UNUSED__, int type __UNUSED__, void *info)
{
E_Ofono_Element *element = info;
printf("!!! %s %s\n", element->path, element->interface);
e_ofono_element_print(stderr, element);
return EINA_TRUE;
}
static Eina_Bool
_on_cmd_quit(char *cmd __UNUSED__, char *args __UNUSED__)
{
fputs("Bye!\n", stderr);
ecore_main_loop_quit();
return EINA_FALSE;
}
static Eina_Bool
_on_cmd_sync(char *cmd __UNUSED__, char *args __UNUSED__)
{
e_ofono_manager_sync_elements();
return EINA_TRUE;
}
static char *
_tok(char *p)
{
p = strchr(p, ' ');
if (!p)
return NULL;
*p = '\0';
p++;
while (isspace(*p))
p++;
if (*p == '\0')
return NULL;
return p;
}
static Eina_Bool
_on_cmd_get_all(char *cmd __UNUSED__, char *args)
{
E_Ofono_Element **elements;
char *type;
unsigned int count;
Eina_Bool ret;
if (!args)
type = NULL;
else
type = args;
if (type)
ret = e_ofono_elements_get_all_type(type, &count, &elements);
else
ret = e_ofono_elements_get_all(&count, &elements);
if (!ret)
fputs("ERROR: could not get elements\n", stderr);
else
{
printf("BEG: all elements type=%s count = %d\n", type, count);
_elements_print(elements, count);
}
return EINA_TRUE;
}
static E_Ofono_Element *
_element_from_args(char *interface, char *args, char **next_args)
{
E_Ofono_Element *element;
if (!args)
{
fputs("ERROR: missing element path\n", stderr);
*next_args = NULL;
return NULL;
}
if (!interface)
{
interface = _tok(args);
*next_args = _tok(interface);
}
else
*next_args = _tok(args);
element = e_ofono_element_get(args, interface);
if (!element)
fprintf(stderr, "ERROR: no element called \"%s %s\".\n", args, interface);
return element;
}
static Eina_Bool
_on_cmd_print(char *cmd __UNUSED__, char *args)
{
char *next_args;
E_Ofono_Element *element = _element_from_args(NULL, args, &next_args);
if (element)
e_ofono_element_print(stdout, element);
return EINA_TRUE;
}
static Eina_Bool
_on_cmd_get_properties(char *cmd __UNUSED__, char *args)
{
char *next_args;
E_Ofono_Element *element = _element_from_args(NULL, args, &next_args);
if (element)
e_ofono_element_properties_sync(element);
return EINA_TRUE;
}
static Eina_Bool
_on_cmd_property_set(char *cmd __UNUSED__, char *args)
{
char *next_args, *name, *p;
E_Ofono_Element *element = _element_from_args(NULL, args, &next_args);
void *value;
long vlong;
unsigned short vu16;
unsigned int vu32;
int type;
if (!element)
return EINA_TRUE;
if (!next_args)
{
fputs("ERROR: missing parameters name, type and value.\n", stderr);
return EINA_TRUE;
}
name = next_args;
p = _tok(name);
if (!p)
{
fputs("ERROR: missing parameters type and value.\n", stderr);
return EINA_TRUE;
}
next_args = _tok(p);
if (!next_args)
{
fputs("ERROR: missing parameter value.\n", stderr);
return EINA_TRUE;
}
type = p[0];
switch (type)
{
case DBUS_TYPE_BOOLEAN:
vlong = !!atol(next_args);
value = &vlong;
fprintf(stderr, "DBG: boolean is: %ld\n", vlong);
break;
case DBUS_TYPE_UINT16:
vu16 = strtol(next_args, &p, 0);
if (p == next_args)
{
fprintf(stderr, "ERROR: invalid number \"%s\".\n", next_args);
return EINA_TRUE;
}
value = &vu16;
fprintf(stderr, "DBG: u16 is: %hu\n", vu16);
break;
case DBUS_TYPE_UINT32:
vu32 = strtol(next_args, &p, 0);
if (p == next_args)
{
fprintf(stderr, "ERROR: invalid number \"%s\".\n", next_args);
return EINA_TRUE;
}
value = &vu32;
fprintf(stderr, "DBG: u16 is: %u\n", vu32);
break;
case DBUS_TYPE_STRING:
case DBUS_TYPE_OBJECT_PATH:
p = next_args + strlen(next_args);
if (p > next_args)
p--;
while (p > next_args && isspace(*p))
p--;
if (p <= next_args)
{
fprintf(stderr, "ERROR: invalid string \"%s\".\n", next_args);
}
p[1] = '\0';
value = next_args;
fprintf(stderr, "DBG: string is: \"%s\"\n", next_args);
break;
default:
fprintf(stderr, "ERROR: don't know how to parse type '%c' (%d)\n",
type, type);
return EINA_TRUE;
}
fprintf(stderr, "set_property %s [%p] %s %c %p...\n",
args, element, name, type, value);
if (!e_ofono_element_property_set(element, name, type, value))
fputs("ERROR: error setting property.\n", stderr);
return EINA_TRUE;
}
/* Manager Commands */
static Eina_Bool
_on_cmd_manager_get(char *cmd __UNUSED__, char *args __UNUSED__)
{
E_Ofono_Element *element;
element = e_ofono_manager_get();
e_ofono_element_print(stderr, element);
return EINA_TRUE;
}
static Eina_Bool
_on_cmd_manager_modems_get(char *cmd __UNUSED__, char *args __UNUSED__)
{
char *path;
Eina_Array_Iterator iterator;
unsigned int i;
Eina_Array *modems = NULL;
if(e_ofono_manager_modems_get(&modems))
{
printf("[");
if (modems)
EINA_ARRAY_ITER_NEXT(modems, i, path, iterator)
printf(" %s", path);
printf(" ]\n");
}
return EINA_TRUE;
}
/* Modem Commands */
static Eina_Bool
_on_cmd_modem_set_powered(char *cmd __UNUSED__, char *args)
{
char *next_args;
Eina_Bool powered;
E_Ofono_Element *element = _element_from_args("org.ofono.Modem", args, &next_args);
if (!element)
return EINA_TRUE;
if (!args)
{
fputs("ERROR: missing the powered value\n", stderr);
return EINA_TRUE;
}
powered = !!atol(next_args);
if (e_ofono_modem_powered_set
(element, powered, _method_success_check, "modem_set_powered"))
printf(":::Modem %s Powered set to %hhu\n", element->path, powered);
else
fputs("ERROR: can't set Modem Powered\n", stderr);
return EINA_TRUE;
}
/* SMS Commands */
static Eina_Bool
_on_cmd_sms_sca_set(char *cmd __UNUSED__, char *args)
{
char *next_args, *sca;
E_Ofono_Element *element = _element_from_args("org.ofono.SmsManager", args,
&next_args);
if (!element)
return EINA_TRUE;
if (!args)
{
fputs("ERROR: missing service center address\n", stderr);
return EINA_TRUE;
}
sca = next_args;
if (e_ofono_sms_sca_set(element, sca, _method_success_check,
"sms_sca_set"))
printf(":::Service Center Address on modem %s set to %s\n",
element->path, sca);
else
fputs("ERROR: couldn't change Service Center Address\n", stderr);
return EINA_TRUE;
}
static Eina_Bool
_on_cmd_sms_send_message(char *cmd __UNUSED__, char *args)
{
char *next_args, *number, *message;
E_Ofono_Element *element = _element_from_args("org.ofono.SmsManager", args,
&next_args);
if (!element)
return EINA_TRUE;
number = next_args;
if (!number)
{
fputs("ERROR: missing recipient number and message text.\n", stderr);
return EINA_TRUE;
}
message = _tok(number);
if (!message)
{
fputs("ERROR: missing message text.\n", stderr);
return EINA_TRUE;
}
if (!e_ofono_sms_send_message(element, number, message,
_method_success_check, "sms_send_message"))
fputs("ERROR: error setting property.\n", stderr);
return EINA_TRUE;
}
static Eina_Bool
_on_input(void *data __UNUSED__, Ecore_Fd_Handler *fd_handler)
{
char buf[256];
char *cmd, *args;
const struct {
const char *cmd;
Eina_Bool (*cb)(char *cmd, char *args);
} *itr, maps[] = {
{"quit", _on_cmd_quit},
{"sync", _on_cmd_sync},
{"get_all", _on_cmd_get_all},
{"print", _on_cmd_print},
{"get_properties", _on_cmd_get_properties},
{"set_property", _on_cmd_property_set},
{"manager_get", _on_cmd_manager_get},
{"manager_modems_get", _on_cmd_manager_modems_get},
{"modem_set_powered", _on_cmd_modem_set_powered},
{"sms_sca_set", _on_cmd_sms_sca_set},
{"sms_send_message", _on_cmd_sms_send_message},
{NULL, NULL}
};
if (ecore_main_fd_handler_active_get(fd_handler, ECORE_FD_ERROR))
{
fputs("ERROR: reading from stdin, exit\n", stderr);
return EINA_FALSE;
}
if (!ecore_main_fd_handler_active_get(fd_handler, ECORE_FD_READ))
{
fputs("ERROR: nothing to read?\n", stderr);
return EINA_FALSE;
}
if (!fgets(buf, sizeof(buf), stdin))
{
fprintf(stderr, "ERROR: could not read command: %s\n", strerror(errno));
ecore_main_loop_quit();
return EINA_FALSE;
}
cmd = buf;
while (isspace(*cmd))
cmd++;
args = strchr(cmd, ' ');
if (args)
{
char *p;
*args = '\0';
args++;
while (isspace(*args))
args++;
p = args + strlen(args) - 1;
if (*p == '\n')
*p = '\0';
}
else
{
char *p;
p = cmd + strlen(cmd) - 1;
if (*p == '\n')
*p = '\0';
}
if (strcmp(cmd, "help") == 0)
{
if (args)
{
printf("Commands with '%s' in the name:\n", args);
for (itr = maps; itr->cmd; itr++)
if (strstr(itr->cmd, args))
printf("\t%s\n", itr->cmd);
}
else
{
fputs("Commands:\n", stdout);
for (itr = maps; itr->cmd; itr++)
printf("\t%s\n", itr->cmd);
}
fputc('\n', stdout);
return EINA_TRUE;
}
for (itr = maps; itr->cmd; itr++)
if (strcmp(itr->cmd, cmd) == 0)
return itr->cb(cmd, args);
printf("unknown command \"%s\", args=%s\n", cmd, args);
return EINA_TRUE;
}
int
main(int argc __UNUSED__, char *argv[] __UNUSED__)
{
E_DBus_Connection *c;
ecore_init();
e_dbus_init();
eina_init();
c = e_dbus_bus_get(DBUS_BUS_SYSTEM);
if (!c) {
printf("ERROR: can't connect to system session\n");
return -1;
}
e_ofono_system_init(c);
ecore_event_handler_add(E_OFONO_EVENT_ELEMENT_ADD, _on_element_add, NULL);
ecore_event_handler_add(E_OFONO_EVENT_ELEMENT_DEL, _on_element_del, NULL);
ecore_event_handler_add(E_OFONO_EVENT_ELEMENT_UPDATED,
_on_element_updated, NULL);
ecore_main_fd_handler_add
(0, ECORE_FD_READ | ECORE_FD_ERROR, _on_input, NULL, NULL, NULL);
ecore_main_loop_begin();
e_ofono_system_shutdown();
e_dbus_connection_close(c);
eina_shutdown();
e_dbus_shutdown();
ecore_shutdown();
fputs("DBG: clean exit.\n", stderr);
return 0;
}
|
C
|
void L06_TF1(){
//canvas 1
TCanvas * c1 = new TCanvas();
//first method to define a fucntion
TF1 * f1 = new TF1("f1","sin(x)/x", 0,3);
f1->Draw();
double x0 = 0.001;
double fx0 = f1->Eval(0.001);//Evaluate the value of f1 in point x0
printf("The value of f1 at point x0 is: f1(%lg) = %lg \n",x0,fx0);
double integrated =f1->Integral(0,2);//Integrate f1 from 0 to 2
printf("The integral of f1 between 0 and 2 = %lg\n", integrated);
//canvas 2
TCanvas * c2 = new TCanvas();
//second method to define a fucntion
TF1 * f2 = new TF1("f2","[0]*x + [1]", 0,3);
f2->SetParName(0,"slope");//set the name of [0] parameter to slope
f2->SetParameter("slope",2);
f2->SetParameter(1,5);//set the value of [1] parameter to 5
f2->Draw();
//canvas 3
TCanvas * c3 = new TCanvas();
//third method to define a function
TF1 * f3 = new TF1("f3","TMath::Log(x)",1,2);
f3->Draw();
}
|
C
|
//
// Created by Greg Postnikoff
//
#ifndef ONEGINBRAT_FUNCTION_H
#define ONEGINBRAT_FUNCTION_H
int StrcmpReverse( const void * str1, const void * str2 ) {
Text * s1 = (Text *) str1;
Text * s2 = (Text *) str2;
int leng = 0;
int FirstPunct1 = 0, FirstPunct2 = 0;
while (ispunct(s1->str[s1->len - 2 - FirstPunct1]))
FirstPunct1++;
while (ispunct(s2->str[s2->len - 2 - FirstPunct2]))
FirstPunct2++;
if ( s1->len < s2->len ) {
leng = s1->len;
for (int i = 0; i < leng - FirstPunct1; i++) {
if (s1->str[leng - FirstPunct1 - (2 + i)] > s2->str[s2->len - FirstPunct2 - (2 + i)])
return 1;
if (s1->str[leng - FirstPunct1 - (2 + i)] < s2->str[s2->len - FirstPunct2 - (2 + i)])
return -1;
}
}
else {
leng = s2->len;
for ( int i = 0; i < leng - FirstPunct2; i++ ) {
if ( s1->str[s1->len - FirstPunct1 - (2 + i)] > s2->str[leng - FirstPunct2 - (2 + i)] )
return 1;
if ( s1->str[s1->len - FirstPunct1 - (2 + i)] < s2->str[leng - FirstPunct2 - (2 + i)] )
return -1;
}
}
if ( s1->len < s2->len )
return -1;
if ( s1->len > s2->len )
return 1;
if ( s1->len == s2->len )
return 0;
}
int OpenFile(FILE ** FileIn, const char * filename) {
*FileIn = fopen(filename, "r");
if (!*FileIn) {
return ERROR_OPEN_FILE;
}
return SUCCESS_OPEN_FILE;
}
int StringQuan( const char * buffer, const int size) {
int strquan = 1;
for (int i = 0; i < size; i++)
if (buffer[i] == '\n')
strquan++;
return strquan;
}
void Devide(char * buffer, struct Text * text, const int size) {
text[0].str = buffer;
int current = 1;
for (int i = 1; i < size; i++, text[current - 1].len++ )
if (buffer[i] == '\n') {
text[current].str = &buffer[i + 1];
current++;
buffer[i] = '\0';
}
}
char * ReadFILE(FILE * FileIn, const int size) {
char * buffer = (char *) calloc(size, sizeof(char));
fread( buffer, sizeof(char), size , FileIn);
return buffer;
}
int Strcmp( const void * str1, const void * str2 ) {
struct Text * s1 = (struct Text *) str1;
struct Text * s2 = (struct Text *) str2;
int j = 0, m = 0;
while (ispunct(s1->str[j]))
j++;
while (ispunct(s2->str[m]))
m++;
return strcmp( &s1->str[j], &s2->str[m] );
}
void CreateBuffer( char * filename, FILE * FileIn, struct DevidedBuffer * devided_buffer) {
const int Result = OpenFile(&FileIn, filename);
assert(Result == SUCCESS_OPEN_FILE);
struct stat st = {};
stat(filename, &st);
char *buffer = ReadFILE(FileIn, st.st_size + 1);
buffer[st.st_size] = '\n';
const int strquan = StringQuan(buffer, st.st_size);
struct Text * text = (struct Text *) calloc(strquan, sizeof(Text));
Devide(buffer, text, st.st_size);
devided_buffer->text = text;
devided_buffer->strquan = strquan;
}
void PrintBuf(struct DevidedBuffer * devided_buffer) {
for (int i = 0; i < devided_buffer->strquan; i++)
if (devided_buffer->text[i].len > 2)
printf("'%s'\n", devided_buffer->text[i].str);
}
#endif //ONEGINBRAT_FUNCTION_H
|
C
|
#include <stdio.h>
#include <stdlib.h>
char destChar[3];
char srcChar[3];
int width;
int height;
int startX, startY;
int endX, endY;
char fileName[128] = {0};
char buf[1024] = {0};
void readConf()
{
printf("ļ:");
memset(fileName, 0, sizeof(fileName));
scanf("%s", fileName);
printf(" (width), (height):");
scanf("%d%d", &width, &height);
printf("ʼx1, y1:");
scanf("%d%d", &startX, &startY);
printf("ֹx2, y2:");
scanf("%d%d", &endX, &endY);
}
/***
*λת
*/
int postion(int x, int y, int fileSize)
{
int pos = y * width + x;
if (pos < 0) return 0;
if (pos >= fileSize) pos = fileSize - 1;
return pos;
}
int hex2dec(char *s)
{
int i = 0;
int len = strlen(s);
int dec = 0;
char c;
if (NULL == s) return 0;
while (i < len)
{
c = s[i];
dec *= 16;
dec += (int)(c - '0');
i++;
}
return dec;
}
int doReplace()
{
char p;
int fileSize, start, end;
int i;
int ret, count = 0;
char hex[3] = {0};
char r = hex2dec(destChar);
printf("r = %d\n", r);
FILE *fp = fopen(fileName, "rb+");
if (NULL == fp) {
printf("ļʧ.\n");
return -1;
}
fseek(fp, 0L, SEEK_END);
fileSize = ftell(fp);
printf("file size = %d\n", fileSize);
start = postion(startX, startY, fileSize);
end = postion(endX, endY, fileSize);
printf("start=%d, end=%d\n", start, end);
rewind(fp);
fseek(fp, (long)start, SEEK_SET);
/**ļв滻**/
i = start;
while (i <= end)
{
if (1 != fread(&p, 1, 1, fp))
{
fclose(fp);
return -1;
}
sprintf(hex, "%02x", p);
hex[2] = '\0';
//printf("hex=%s\n", hex);
if (0 == strcmp(hex, srcChar)) {
printf("Found %s at %d, Begin to Replace.\n", hex, i);
fseek(fp, i, SEEK_SET);
fwrite(&r, 1, 1, fp);
fseek(fp, i+1, SEEK_SET);
count++;
}
i++;
}
fclose(fp);
return count;
}
int main()
{
int num = 0;
readConf();
do {
printf("Ҫ滻ַ01(-1˳:");
scanf("%s", srcChar);
srcChar[2] = '\0';
if (strcmp(srcChar, "-1") == 0) break;
printf("滻ַ67:");
scanf("%s", destChar);
destChar[2] = '\0';
num = doReplace();
if (num > 0)
printf("滻%d\n", num);
} while(1);
return 0;
}
|
C
|
#ifndef __TREE_H__
#define __TREE_H__
#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct Node_ {
struct Node_ *left;
struct Node_ *right;
int data;
} Node;
typedef struct {
Node *root;
} Tree;
Tree *tree_create(int val);
void tree_elem_add(Node *node, int val);
Node *node_create(int val);
void tree_elem_delete(Tree *tree, Node *del);
Node* tree_find_parent(Node* node, Node *del);
Node* tree_find_elem(Node* node, int val);
Node* find_min(Node* node);
void tree_print(Node *node, int lvl);
// bool detour(Node *node, int l, int r);
// bool lie_in_area(int value, int l, int r);
// void bords_insert(int *left, int *right);
void tree_free(Node *node);
void tree_destroy(Tree **tree);
#endif
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* print_instructions.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: lcompagn <lcompagn@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/10/15 13:46:45 by lcompagn #+# #+# */
/* Updated: 2018/10/15 13:47:18 by lcompagn ### ########.fr */
/* */
/* ************************************************************************** */
#include "vm.h"
void ft_print_instructions(void)
{
attron(A_UNDERLINE);
mvprintw(INSTRUCTION_LINE, 2, "Usage");
attroff(A_UNDERLINE);
mvprintw(INSTRUCTION_LINE + 1, 2, "\t- (Un)pause :\t[Space]");
mvprintw(INSTRUCTION_LINE + 2, 2, "\t- Next step :\t[%c]", KEY_STEP);
mvprintw(INSTRUCTION_LINE + 3, 2, "\t- Faster :\t[%c]", KEY_SLEEP_DOWN);
mvprintw(INSTRUCTION_LINE + 4, 2, "\t- Slower :\t[%c]", KEY_SLEEP_UP);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "store.h"
store *createStore(void *datas, void(*prPtr)(void* info)){
store *ptr = malloc(sizeof(store));
ptr->printPtr = prPtr;
ptr->data = datas;
return ptr;
}
void displayStore( store* s ){
s->printPtr(s->data);
}
|
C
|
#include<stdio.h>
int MulDigit(int iNo)
{
int iDigit=0, iMul=1;
while(iNo != 0)
{
iDigit = iNo % 10;
if(iDigit %2 != 0)
{
iMul = iMul * iDigit;
}
else
{
iMul = 1;
}
iNo = iNo/10;
}
return iMul;
}
int main()
{
int ino =0,iRet=0;
printf("Enter the number:");
scanf("%d",&ino);
iRet = MulDigit(ino);
printf("%d \n",iRet);
return 0;
}
|
C
|
/*
* @file list.c
*
*/
#include <stdlib.h>
#include "wge100_camera/list.h"
#include "wge100_camera/host_netutil.h"
/**
* Initializes a new camera list using macros from list.h
*
* @param ipCamList Pointer to an IpCamList list element
*
* @return Always returns zero.
*/
int wge100CamListInit( IpCamList *ipCamList ) {
INIT_LIST_HEAD(&ipCamList->list);
return 0;
}
/**
* Adds a new camera to camera list ipCamList if that serial number is not
* already in the list.
*
* @param ipCamList Pointer to the IpCamList head
* @param newItem Pointer to an IpCamList structure that describes the new camera
*
* @return Returns CAMLIST_ADD_OK if the camera was added to the list, or CAMLIST_ADD_DUP if it was a duplicate.
*/
int wge100CamListAdd( IpCamList *ipCamList, IpCamList *newItem) {
IpCamList *listIterator;
int isInList = 0;
// Scan through the list, looking for a serial number that matches the one we're trying to add
list_for_each_entry(listIterator, &(ipCamList->list), list) {
if( newItem->serial == listIterator->serial) {
// This camera is already in the list
isInList = 1;
break;
}
}
if(isInList == 1) {
debug("Serial number %d already exists in list, dropping.\n", newItem->serial);
return CAMLIST_ADD_DUP;
} else {
debug("Serial number %d is new, adding to list.\n", newItem->serial);
list_add_tail( &(newItem->list), &(ipCamList->list) );
return CAMLIST_ADD_OK;
}
}
/**
* Utility function to locate a camera with a particular serial number in a list.
* @param ipCamList Pointer to the list head
* @param serial Serial number (not including product ID) to look for
* @return Returns the index of the camera, or -1 if not found
*/
int wge100CamListFind( IpCamList *ipCamList, uint32_t serial ) {
int count;
IpCamList *listIterator;
count = 0;
list_for_each_entry(listIterator, &(ipCamList->list), list) {
if(listIterator->serial == serial) {
return count;
}
count++;
}
return -1;
}
/**
* Utility function to return a specific element number from the camera list.
*
* @pre index must be less than the value returned by wge100CamListNumEntries().
* If it is greater, then the last element in the list will be returned.
*
* @param ipCamList Pointer to the camera list head
* @param index Number of the list element to returna (0..max)
*
* @return Returns a pointer to the requested list element
*/
IpCamList *wge100CamListGetEntry( const IpCamList *ipCamList, int index ) {
IpCamList *listIterator;
// Iterate through the list until we have counted off 'index' entries
list_for_each_entry(listIterator, &(ipCamList->list), list) {
if(index-- == 0) {
break;
}
}
return listIterator;
}
/**
* Utility function to remove a specific element number from the camera list.
*
* @pre index must be less than the value returned by wge100CamListNumEntries().
*
* @param ipCamList Pointer to the camera list head
* @param index Number of the list element to remove (0..max)
*
* @return Returns 0 if successful, -1 if index was invalid
*/
int wge100CamListDelEntry( IpCamList *ipCamList, int index ) {
int count;
IpCamList *tmpListItem;
struct list_head *pos, *q;
count = 0;
list_for_each_safe(pos, q,&(ipCamList->list)) {
if(count++ == index) {
tmpListItem = list_entry(pos, IpCamList, list);
list_del(pos);
free(tmpListItem);
return 0;
}
}
return -1;
}
/**
* Utility function to determine the number of entries in an IpCamlist
*
* @param ipCamList Pointer to the list head to count.
*
* @return Returns the number of elements in the list
*/
int wge100CamListNumEntries( const IpCamList *ipCamList ) {
int count;
IpCamList *listIterator;
count = 0;
list_for_each_entry(listIterator, &(ipCamList->list), list) {
count++;
}
return count;
}
/**
* Utility function to remove all entries from a camera list.
*
* @param ipCamList Pointer to the camera list head
*
* @return Returns 0 if successful.
*/
void wge100CamListDelAll( IpCamList *ipCamList ) {
int count;
IpCamList *tmpListItem;
struct list_head *pos, *q;
count = 0;
list_for_each_safe(pos, q,&(ipCamList->list)) {
tmpListItem = list_entry(pos, IpCamList, list);
list_del(pos);
free(tmpListItem);
}
}
|
C
|
/*
============================================================================
Name : TP2_1_1.c
Author :
Version :
Copyright : Your copyright notice
Description : Hello World in C, Ansi-style
============================================================================
*/
#include <stdio.h>
#include <stdlib.h>
#define N 4
#define M 5
int main(void){
int f,c;
double mt[N][M];
setvbuf(stdout, NULL, _IONBF, 0);
for(f=0;f<N;f++){
for(c=0;c<M;c++){
printf("Ingrese un numero para mt[%d][%d]: ",f,c);
scanf("%lf", &mt[f][c]);
}
}
for(f=0;f<N;f++){
for(c=0;c<M;c++){
printf("%lf", mt[f][c]);
}
printf("\n");
}
return 0;
}
|
C
|
/// Динамическая память: malloc / free
/// ----------------------------------
#include <stdio.h>
#include <stdlib.h>
int intStatic[100]; // Статическая память
int main() {
static int intStatic2[100]; // Статическая память
int intStack[100]; // Стек
//-->
int stackArray[100]; // Массив в стеке
int* intArray; // Стек
intArray = 10; // Стек
// Получение области динамической памяти
intArray = malloc(100); // Отводим память - 100 байт
intArray = malloc(70 * sizeof(int)); // 70 целых чисел
if(intArray == NULL) { // Памяти не хватило
printf("No memory :(");
return;
}
// Пользуемся как обычным массивом
intArray[0] = 10;
// Освобождение памяти
free(intArray);
intArray = NULL;
//<--
// Сумма элементов массива
int N, i;
printf("N = ");
scanf("%d", &N);
// Заводим в динамической памяти массив целых
// чисел размером N
int* A = malloc(N * sizeof(int));
// Вводим элементы массива с клавиатуры
for(i = 0; i < N; i++) {
scanf("%d", &A[i]);
//scanf("%d", A+i );
}
// Считаем сумму
int sum = 0;
for(i = 0; i < N; i++)
sum += A[i];
printf("sum = %d\n", sum);
// Освобождаем память
free(A);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include<time.h>
int intcomp(const void* x, const void* y){
int* xx = (int*)x;
int* yy = (int*)y;
return *xx - *yy;
}
//int floatcomp(const void* x, const void* y){
// float* xx = (float*)x;
// float* yy = (float*)y;
//
// return *xx - *yy < 0? -1: *xx - *yy > 0 ? 1:0;
//}
void swap(int w[], int a, int b)
{
int temp = 0;
temp = w[a];
w[a] = w[b];
w[b] = temp;
}
void myqsort(int w[], int start, int end)
{
int x = w[start];
int p = start + 1;
int q = end;
//printf("xxx %d %d\n", start, end);
if(start < end){
while (p < q) {
while (w[p] <= x && p < end){
p++;
}
while (w[q] > x){
q--;
}
if (p < q)
swap(w, p, q);
}
if (w[start]>w[q])
swap(w, start, q);
//printf("%d %d\n", p, q);
myqsort(w, start, q - 1);
myqsort(w, q+1, end);
}
}
main()
{
int w[] = { 83,86,77,15,93,35,86,92,49,21 };
int n = sizeof(w) / sizeof(w[0]);
int i;
myqsort(w, 0, n - 1);
for(i = 0; i < n; i++){
printf("%d\n", w[i]);
}
printf("\n");
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <assert.h>
#include <sys/time.h>
#include <time.h>
#define MAX_LEVELS 20
static int max_table;
struct trans_thread {
void **curr_table;
int offset[MAX_LEVELS];
int curr;
int max;
};
int translate_cpu(struct trans_thread *trans) {
void **c = trans->curr_table;
while(trans->curr < trans->max-1) {
trans->curr_table = (void **) trans->curr_table[trans->offset[trans->curr]];
trans->curr++;
// fprintf(stderr, "offset: %d\n", trans->offset[trans->curr]);
}
return (int) *(trans->curr_table + trans->offset[trans->curr]); // ((void *) trans->curr_table + trans->offset[trans->max-1]);
}
float cpu_run_time(struct trans_thread *trans, int addresses) {
int i;
struct timeval start_time, stop_time;
gettimeofday(&start_time, NULL);
for(i = 0; i < addresses; i++) {
translate_cpu(&trans[i]);
}
gettimeofday(&stop_time, NULL);
long time_diff = (stop_time.tv_usec)
-(start_time.tv_usec);
return time_diff;
}
struct trans_thread *gen_addresses(int num_addr, int levels, int *level_sizes,
void **pgd)
{
int i,j;
struct trans_thread *new_threads = (struct trans_thread *)
malloc(sizeof(struct trans_thread) * num_addr);
if (!new_threads){
fprintf(stderr, "malloc failed: %d\n", strerror(errno));
exit(1);
}
for(i = 0; i < num_addr; i++)
{
new_threads[i].curr_table = pgd;
new_threads[i].max = levels;
new_threads[i].curr = 0;
for(j = 0; j < levels; j++) {
new_threads[i].offset[j] =
rand() % level_sizes[j];
}
}
return new_threads;
}
int construct_table(void *table, int *levels, int num_levels) {
int i, j, level_size = 1;
void **table_ptr = (void **) table,
**level_ptr;
// set intermediate addresses of table
for(i = 0; i < num_levels-1; i++)
{
level_size *= levels[i];
// hideous but best way I could find to get next level
level_ptr = (void **) table + (level_size)+ (((void *)table_ptr - table)/(sizeof(void*)));
// helpufl check: fprintf(stderr, "level_size: %d, level_ptr: %d, table_ptr: %d\n", level_size, (level_ptr- (void **) table) / sizeof(void *), table_ptr - (void **) table);
for(j = 0; j < level_size; j++) {
table_ptr[j] = level_ptr + ((j)*levels[i+1]);
}
table_ptr += level_size;
}
assert((void *) table_ptr - table < max_table);
// set last level of page table to garbage; for our purposes
// it doesn't matter
for(i = 0; i < level_size * levels[num_levels-1]; i++) {
*table_ptr = (void *) i;
table_ptr++;
}
assert((void *) table_ptr - table == max_table);
// return number of entries at the lowest level of the
// page table
return levels[num_levels-1] * level_size;
}
int main(int argc, char** argv) {
void **pg_table;
int i, j, table_size = 0, level_size = 1,
total_addresses, table_lowest_addresses,
levels = argc-3;
int level_sizes[levels];
struct trans_thread *sample;
struct trans_thread *run_threads;
srand(time(NULL));
// get number of pointers in contiguous page table
for(i = 1, j =0; i < argc; i++) {
if ( !strcmp(argv[i], "-n")) {
total_addresses = atoi(argv[++i]);
continue;
}
level_size *= atoi(argv[i]);
level_sizes[j++] = atoi(argv[i]);
table_size += level_size;
}
max_table = table_size * sizeof(void *);
pg_table = (void *) malloc(sizeof(void *) * table_size);
if (!pg_table) {
fprintf(stderr, "malloc failed: %d\n", strerror(errno));
exit(1);
}
table_lowest_addresses = construct_table(pg_table, level_sizes,
levels);
/*for(i = 0; i < table_size; i++) {
fprintf(stderr, "address number: %d, address intermediate value: %d, final value: %d, address: %d\n", i, ((void **) pg_table[i] - pg_table) / sizeof(void *), pg_table[i], pg_table+i);
}
for (i = 0; i < table_size - table_lowest_addresses; i++)
{
fprintf(stderr, "address %d, points to %d\n", pg_table + i, pg_table[i]);
}*/
fprintf(stderr, "number of translatable addresses: %d\n", table_lowest_addresses);
fprintf(stderr, "total size of page table: %d\n", max_table);
/*sample = (struct trans_thread *) malloc(sizeof(struct trans_thread));
sample->curr_table = pg_table;
sample->offset[0] = 1;
sample->offset[1] = 0;
sample->offset[2] = 0;
sample->offset[3] = 0;
sample->curr = 0;
sample->max = 4;
int sample_test = translate_cpu(sample);
fprintf(stderr, "translated address: %d\n", sample_test );*/
run_threads = gen_addresses(total_addresses, levels, level_sizes,
pg_table);
long time_taken = cpu_run_time(run_threads, total_addresses);
fprintf(stderr, "The CPU took %lu microseconds to compute %d addresses. "
"For a table of depth %d.\n",
time_taken, total_addresses, levels);
return 0;
}
|
C
|
/*
* Simple program showing 2 threads with a mutex to access a shared counter variable.
* IMPORTANT: Use the script "compile_with_pthreads" to build this example. gcc seems
* picky about the order in whinc the input, output and libpthread arguments appear!
* Enhanced to show two threads and two mutex variables that can cause a deadlock.
$Author$: Kalyan Subramanian
$email$: kalyan dot sub at gmail
$Date$: Sep 17, 2014
*/
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *function1();
void *function2();
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER;
int counter1 = 0;
int counter2 = 0;
int main(int argc, char* argv[])
{
int rc1, rc2;
pthread_t thread1, thread2;
/* Create independent threads each of which will execute function1 and 2*/
if( (rc1=pthread_create( &thread1, NULL, &function1, NULL)) )
{
printf("Thread creation failed: %d\n", rc1);
}
if( (rc2=pthread_create( &thread2, NULL, &function2, NULL)) )
{
printf("Thread creation failed: %d\n", rc2);
}
/* Wait till threads are complete before main continues. Unless we */
/* wait we run the risk of executing an exit which will terminate */
/* the process and all threads before the threads have completed. */
pthread_join( thread1, NULL);
pthread_join( thread2, NULL);
exit(0);
}
void *function1()
{
pthread_t tid;
tid = pthread_self();
printf("### In thread function1, with thread ID: 0x%x\n", (int)tid);
pthread_mutex_lock( &mutex1 );
printf("### Thread1, locked mutex1\n");
counter1++;
printf("\t ### Counter 1 value: %d\n",counter1);
pthread_mutex_lock( &mutex2 );
printf("\t ### Thread1, locked mutex2\n");
counter2--;
counter1++;
printf("\t ### Counter 2 value: %d\n",counter2);
printf("\t ### Counter 1 value: %d\n",counter1);
pthread_mutex_unlock( &mutex2 );
printf("\t ### Thread1, UNlocked mutex2\n");
pthread_mutex_unlock( &mutex1 );
printf("### Thread1, UNlocked mutex1\n");
}
void *function2()
{
pthread_t tid;
tid = pthread_self();
printf("@@@ In thread function2, with thread ID: 0x%x\n", (int)tid);
pthread_mutex_lock( &mutex2 );
printf("@@@ Thread2, locked mutex2\n");
counter2++;
printf("\t @@@ Counter 2 value: %d\n",counter2);
pthread_mutex_lock( &mutex1 );
printf("\t @@@ Thread2, locked mutex1\n");
counter1--;
counter2++;
printf("\t @@@ Counter 1 value: %d\n",counter1);
printf("\t @@@ Counter 2 value: %d\n",counter1);
pthread_mutex_unlock( &mutex1 );
printf("\t @@@ Thread2, UNlocked mutex1\n");
pthread_mutex_unlock( &mutex2 );
printf("@@@ Thread2, UNlocked mutex2\n");
}
|
C
|
#include <stdio.h>
void classifyPoints(int x, int y) {
if(x > 0 && y > 0)
printf("primeiro\n");
else if(x < 0 && y > 0)
printf("segundo\n");
else if(y < 0 && x < 0)
printf("terceiro\n");
else if(x > 0 && y < 0)
printf("quarto\n");
}
int main(int argc, char const *argv[]) {
int x, y;
while(scanf("%d%d", &x, &y) && x != 0 && y != 0)
classifyPoints(x, y);
return 0;
}
|
C
|
/* hash.h - Foundation library - Public Domain - 2013 Mattias Jansson
*
* This library provides a cross-platform foundation library in C11 providing basic support
* data types and functions to write applications and games in a platform-independent fashion.
* The latest source code is always available at
*
* https://github.com/mjansson/foundation_lib
*
* This library is put in the public domain; you can redistribute it and/or modify it without
* any restrictions.
*/
#pragma once
/*! \file hash.h
\brief Murmur3 hash
Murmur3 hash from http://code.google.com/p/smhasher/
Wrapper macros around predefined static hashed strings. See hashify utility for
creating static hashes */
#include <foundation/platform.h>
#include <foundation/types.h>
#include <foundation/assert.h>
#if BUILD_ENABLE_STATIC_HASH_DEBUG
#include <foundation/string.h>
#endif
/*! Hash data memory blob. Pointer must be aligned to 8 bytes
\param key Key to hash
\param len Length of key in bytes
\return Hash of key */
FOUNDATION_API FOUNDATION_PURECALL hash_t
hash(const void* key, size_t len);
/*! Reverse hash lookup. Only available if #BUILD_ENABLE_STATIC_HASH_DEBUG is
enabled, otherwise if will always return an empty string
\param value Hash value
\return String matching hash value, or empty string if not found */
FOUNDATION_API string_const_t
hash_to_string(hash_t value);
#if BUILD_ENABLE_STATIC_HASH_DEBUG
static FOUNDATION_FORCEINLINE hash_t
static_hash(const void* key, size_t len, hash_t value);
#else
#define static_hash(key, len, value) ((void)sizeof(key), (void)sizeof(len), (hash_t)(value))
#define hash_to_string(value) ((void)sizeof(value), (const char*)0)
#endif
/*! Declare a statically hashed string. If #BUILD_ENABLE_STATIC_HASH_DEBUG is enabled
in the build config this will allow the string to be reverse looked up with hash_to_string.
Static hash strings are usually defined by using the hashify tool on a declaration file,
see the hashstrings.txt and corresponding hashstrings.h header
\param key Key string
\param len Length of key in bytes
\param value Hash value */
#define static_hash_string(key, len, value) static_hash(key, len, (hash_t)value)
#if BUILD_ENABLE_STATIC_HASH_DEBUG
FOUNDATION_API void
static_hash_store(const void* key, size_t len, hash_t value);
static FOUNDATION_FORCEINLINE hash_t
static_hash(const void* key, size_t len, hash_t value) {
hash_t ref = hash(key, len);
FOUNDATION_ASSERT_MSGFORMAT(!value || (ref == value), "Static hash fail: %s -> 0x%" PRIx64 ", expected 0x%" PRIx64,
(const char*)key, ref, value);
static_hash_store(key, len, ref);
return ref;
}
#endif
/*! Hash of an empty/null string (length 0) */
#define HASH_EMPTY_STRING 0xC2D00F032E25E509ULL
/*! Null hash value */
#define HASH_NULL 0ULL
|
C
|
#pragma once
#define TEMPLATE_SPECIALIZATION template <\
typename _Object\
>
#define CStateAbstract CState<_Object>
TEMPLATE_SPECIALIZATION
CStateAbstract::CState(_Object *obj, void *data)
{
reset ();
object = obj;
_data = data;
}
TEMPLATE_SPECIALIZATION
CStateAbstract::~CState()
{
free_mem();
}
TEMPLATE_SPECIALIZATION
void CStateAbstract::reinit()
{
if (current_substate != u32(-1)) get_state_current()->critical_finalize();
for (STATE_MAP_IT it = substates.begin(); it != substates.end(); it++)
it->second->reinit();
reset();
}
TEMPLATE_SPECIALIZATION
void CStateAbstract::initialize()
{
time_state_started = Device.dwTimeGlobal;
current_substate = u32(-1); // means need reselect state
prev_substate = u32(-1);
}
TEMPLATE_SPECIALIZATION
void CStateAbstract::execute()
{
// проверить внешние условия изменения состояния
check_force_state();
// если состояние не выбрано, перевыбрать
if (current_substate == u32(-1)) {
reselect_state();
VERIFY(current_substate != u32(-1));
}
// выполнить текущее состояние
CSState *state = get_state(current_substate);
state->execute();
// сохранить текущее состояние
prev_substate = current_substate;
// проверить на завершение текущего состояния
if (state->check_completion()) {
state->finalize();
current_substate = u32(-1);
}
}
TEMPLATE_SPECIALIZATION
void CStateAbstract::finalize()
{
reset();
}
TEMPLATE_SPECIALIZATION
void CStateAbstract::critical_finalize()
{
if (current_substate != u32(-1)) get_state_current()->critical_finalize();
reset();
}
TEMPLATE_SPECIALIZATION
void CStateAbstract::reset()
{
current_substate = u32(-1);
prev_substate = u32(-1);
time_state_started = 0;
}
TEMPLATE_SPECIALIZATION
void CStateAbstract::select_state(u32 new_state_id)
{
if (current_substate == new_state_id) return;
CSState *state;
// если предыдущее состояние активно, завершить его
if (current_substate != u32(-1)) {
state = get_state(current_substate);
state->critical_finalize();
}
// установить новое состояние
state = get_state(current_substate = new_state_id);
// инициализировать новое состояние
setup_substates();
state->initialize();
}
TEMPLATE_SPECIALIZATION
CStateAbstract* CStateAbstract::get_state(u32 state_id)
{
STATE_MAP_IT it = substates.find(state_id);
VERIFY(it != substates.end());
return it->second;
}
TEMPLATE_SPECIALIZATION
void CStateAbstract::add_state(u32 state_id, CSState *s)
{
substates.insert(mk_pair(state_id, s));
}
TEMPLATE_SPECIALIZATION
void CStateAbstract::free_mem()
{
for (STATE_MAP_IT it = substates.begin(); it != substates.end(); it++) xr_delete(it->second);
}
TEMPLATE_SPECIALIZATION
void CStateAbstract::fill_data_with (void *ptr_src, u32 size)
{
VERIFY(ptr_src);
VERIFY(_data);
CopyMemory(_data, ptr_src, size);
}
TEMPLATE_SPECIALIZATION
CStateAbstract *CStateAbstract::get_state_current()
{
if (substates.empty() || (current_substate == u32(-1))) return 0;
STATE_MAP_IT it = substates.find(current_substate);
VERIFY(it != substates.end());
return it->second;
}
TEMPLATE_SPECIALIZATION
EMonsterState CStateAbstract::get_state_type()
{
if (substates.empty() || (current_substate == u32(-1))) return eStateUnknown;
EMonsterState state = get_state_current()->get_state_type();
return ( (state == eStateUnknown) ? EMonsterState(current_substate) : state);
}
TEMPLATE_SPECIALIZATION
void CStateAbstract::remove_links (CObject* object)
{
for ( auto& it : substates )
it.second->remove_links (object);
}
#undef TEMPLATE_SPECIALIZATION
|
C
|
#include <getopt.h>
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include "lb_config.h"
#include "nf-util.h"
#include "nf-log.h"
#define PARSE_ERROR(format, ...) \
nf_config_usage(); \
fprintf(stderr, format, ##__VA_ARGS__); \
exit(EXIT_FAILURE);
void nf_config_init(int argc, char **argv) {
// Init
uint16_t nb_devices = rte_eth_dev_count_avail();
struct option long_options[] = {
{ "flow-expiration", required_argument, NULL, 'x' },
{ "flow-capacity", required_argument, NULL, 'f' },
{ "backend-capacity", required_argument, NULL, 's' },
{ "cht-height", required_argument, NULL, 'h' },
{ "backend-expiration", required_argument, NULL, 't' },
{ "wan", required_argument, NULL, 'w' },
{ NULL, 0, NULL, 0 }
};
int opt;
while ((opt = getopt_long(argc, argv, "b:x:f:", long_options, NULL)) != EOF) {
switch (opt) {
case 'x':
config.flow_expiration_time =
nf_util_parse_int(optarg, "flow-expiration", 10, '\0');
if (config.flow_expiration_time == 0) {
PARSE_ERROR("Flow expiration time must be strictly positive.\n");
}
break;
case 'f':
config.flow_capacity =
nf_util_parse_int(optarg, "flow-capacity", 10, '\0');
if (config.flow_capacity <= 0) {
PARSE_ERROR("Flow capacity must be strictly positive.\n");
}
break;
case 's':
config.backend_capacity =
nf_util_parse_int(optarg, "backend-capacity", 10, '\0');
if (config.backend_capacity <= 0) {
PARSE_ERROR("Backend capacity must be strictly positive.\n");
}
break;
case 'h':
config.cht_height = nf_util_parse_int(optarg, "cht-height", 10, '\0');
if (config.cht_height <= 0) {
PARSE_ERROR("CHT height must be strictly positive.\n");
}
break;
case 't':
config.backend_expiration_time =
nf_util_parse_int(optarg, "backend-expiration", 10, '\0');
if (config.backend_expiration_time == 0) {
PARSE_ERROR("Backend expiration time must be strictly positive.\n");
}
break;
case 'w':
config.wan_device = nf_util_parse_int(optarg, "wan-dev", 10, '\0');
if (config.wan_device >= nb_devices) {
PARSE_ERROR("WAN device does not exist.\n");
}
break;
default:
PARSE_ERROR("Unknown option.\n");
break;
}
}
// Reset getopt
optind = 1;
// Fill in the mac addresses
config.device_macs = malloc(sizeof(struct rte_ether_addr) * rte_eth_dev_count_avail());
for (int i = 0; i < rte_eth_dev_count_avail(); ++i) {
rte_eth_macaddr_get(i, &config.device_macs[i]);
}
}
void nf_config_usage(void) {
NF_INFO("Usage:\n"
"[DPDK EAL options] --\n"
"\t--flow-expiration <time>: flow expiration time (us).\n"
"\t--flow-capacity <n>: flow table capacity.\n"
"\t--backend-capacity <n>: backend table capacity.\n"
"\t--cht-height <n>: consistent hashing table height: bigger <n> "
"generates more smooth distribution.\n"
"\t--backend-expiration <time>: backend expiration time (us).\n"
"\t--wan <device>: set device to be the external one.\n");
}
void nf_config_print(void) {
// FIXME why are we giving 20 backends and 3 devs for verif when the config
// assumes #backends == #devs?
#ifndef KLEE_VERIFICATION
NF_INFO("\n--- LoadBalancer Config ---\n");
NF_INFO("WAN device: %" PRIu16, config.wan_device);
for (uint16_t b = 0; b < config.backend_count; b++) {
char *dev_mac_str = nf_mac_to_str(&(config.device_macs[b]));
NF_INFO("Backend device %" PRIu16 " own-mac: %s", b, dev_mac_str);
free(dev_mac_str);
}
NF_INFO("Flow expiration time: %" PRIu32 "us", config.flow_expiration_time);
NF_INFO("Flow capacity: %" PRIu32, config.flow_capacity);
NF_INFO("Backend expiration time: %" PRIu32 "us",
config.backend_expiration_time);
NF_INFO("Backend capacity: %" PRIu32, config.backend_capacity);
NF_INFO("\n--- --- ------ ---\n");
#endif
}
|
C
|
#include<stdio.h>
int main()
{
FILE *fp;
char f[25],e[25];
int i,j,fc,fo=0,fo_a[256],fe=0,fe_a[256],df_counter=0;;
float ch_sq_a[256],ch_sq=0.0;
printf("\nEnter the name of the source file(with extension) : ");
scanf("%s",f);
for(i=0;i<=255;i++)
fe_a[i]=0;
fp=fopen(f,"r+");
for(i=0;(fc=fgetc(fp))!=EOF;i++)
fe_a[fc]=fe_a[fc]+1;
fclose(fp);
printf("\nEnter the name of the encrypted file(with extension) : ");
scanf("%s",e);
for(i=0;i<=255;i++)
fo_a[i]=0;
fp=fopen(e,"r+");
for(i=0;(fc=fgetc(fp))!=EOF;i++)
fo_a[fc]=fo_a[fc]+1;
fclose(fp);
for(i=0;i<=255;i++)
{
if(fe_a[i]!=0)
ch_sq_a[i]=(fo_a[i]-fe_a[i])*(fo_a[i]-fe_a[i])/fe_a[i];
}
for(i=0;i<=255;i++)
ch_sq=ch_sq+ch_sq_a[i];
printf("Chi-square value= %f",ch_sq);
for(i=0;i<=255;i++)
{
if(fe_a[i]!=0 && fo_a[i]!=0)
df_counter=df_counter+1;
else if(fe_a[i]!=0 && fo_a[i]==0)
df_counter=df_counter+1;
else if(fe_a[i]==0 && fo_a[i]!=0)
df_counter=df_counter+1;
else
df_counter=df_counter+0;
}
printf("\nDegree of Freedom= %d",df_counter-1);
return 0;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <float.h>
#include <gsl/gsl_fit.h>
#include <gsl/gsl_multifit.h>
#include "jsd_fit.h"
#include "nrfit.h"
#include "nrutil.h"
#define LOOP_COUNT_MAX 20
void jsd_minmax(double A[], int n, double *pmin, double *pmax)
{
int i;
double min, max;
if (n <= 0) {
*pmin = *pmax = 0.0;
return;
}
min = max = A[0];
for (i=1; i<n; i++) {
double val = A[i];
if (isless(val, min))
min = val;
else if (isgreater(val, max))
max = val;
}
*pmin = min;
*pmax = max;
}
void jsd_normalize(double A[], int n, double min, double max)
{
int i;
for (i=0; i<n; i++) {
A[i] = NORMALIZE(A[i], min, max);
}
}
void jsd_denormalize(double A[], int n, double min, double max)
{
int i;
for (i=0; i<n; i++) {
A[i] = DENORMALIZE(A[i], min, max);
}
}
/* order - the order of the polynomial
* C - the coefficients (must be of size order+1) [0..order]
* x - the value to evaluate for
*/
double jsd_poly_eval(double x, double C[], int order)
{
int i;
float val;
val = C[order];
for (i=order-1; i>=0; i--) {
val = val * x + C[i];
}
return val;
}
double jsd_linear_eval(double x, double C[])
{
return C[0] + C[1]*x;
}
/* order - the order of the polynomial
* C - the coefficients (must be of size order+1) [0..order]
* x - the value to evaluate for
*/
float jsd_fpoly_eval(float x, float C[], int order)
{
int i;
float val;
val = C[order];
for (i=order-1; i>=0; i--) {
val = val * x + C[i];
}
return val;
}
/*
void jsd_linear_fit(double X[], double Y[], int size, float nsigma, double C[], double *chisq)
{
double c0, c1, cov00, cov01, cov11;
double sigma;
int outlier;
double mean;
double *eval;
int i;
eval = malloc(sizeof(double) * size);
do
{
if (size <= 1) {
C[0] = Y[0];
C[1] = 0;
return;
}
gsl_fit_linear (X, 1, Y, 1, size, &c0, &c1, &cov00, &cov01, &cov11, chisq);
if (isnan(c0+c1)) {
C[0] = 0.0;
C[1] = 0.0;
return;
}
// do the evaluations
mean = 0.0;
for (i=0; i<size; i++) {
eval[i] = c0+c1*X[i];
mean += Y[i];
}
mean /= size;
// calc sigma
sigma = 0.0;
for (i=0; i<size; i++) {
sigma += SQR(Y[i]-mean);
}
sigma = sqrt(sigma/size);
// determine outliers
outlier = 0;
for (i=0; i<size; i++) {
if (fabs(mean-Y[i]) > nsigma*sigma) {
outlier = 1;
//printf("outlier=%g: (size=%i mean=%g sigma=%g nsigma=%g)\n",
// Y[i], size, mean, sigma, nsigma);
size = size-1;
Y[i] = Y[size];
X[i] = X[size];
}
}
} while (outlier && size > 1);
C[0] = c0;
C[1] = c1;
free(eval);
}
*/
void jsd_print_poly(FILE *file, double C[], int order)
{
int i;
fprintf(file, "f%i(x) = ", order);
for (i=0; i<order; i++) {
fprintf(file, "%g*x**%i + ", C[i], i);
}
fprintf(file, "%g*x**%i\n", C[i], i);
}
int jsd_poly_fit(double X[], double Y[], int size, float nsigma, double C[], int order, double *chisq)
{
int i;
int terms = order+1;
double *x,*y,*sig,*a,*w,**cvm,**u,**v;
double sigma;
int outlier;
double mean;
double *diff, *eval;
int err = 0; //assume no error
if (nsigma < 1.0) {
printf("ERROR: nsigma less than 1.0\n");
return -2;
}
if(size < order+1)
{
for (i=1;i<=terms;i++)
C[i-1] = 0.0;
return -1;
}
diff = malloc(sizeof(double) * size+1);
eval = malloc(sizeof(double) * size+1);
x=dvector(1,size);
y=dvector(1,size);
sig=dvector(1,size);
a=dvector(1,terms);
w=dvector(1,terms);
cvm=dmatrix(1,terms,1,terms);
u=dmatrix(1,size,1,terms);
v=dmatrix(1,terms,1,terms);
for (i=1;i<=size;i++) { //nr fortran style indexing
x[i]=X[i-1];
y[i]=Y[i-1];
sig[i]=1.0;
}
do {
/* for (i=1;i<=size;i++) { //nr fortran style indexing
x[i]=X[i-1];
y[i]=Y[i-1];
sig[i]=1.0;
}
*/
err = svdfit(x,y,sig,size,a,terms,u,v,w,chisq,fpoly);
if (err || !isfinite(a[1])) {
//printf("ERROR: svdfit curve fit failed! %d\n",size);
for (i=1;i<=terms;i++)
C[i-1] = 0.0;
err = -1;
break;
}
for (i=1;i<=terms;i++)
C[i-1] = a[i];
// do the evaluations
mean = 0.0;
// for (i=0; i<size; i++) { //normal indexing
for (i=1; i<=size; i++) { //nr indexing
eval[i] = jsd_poly_eval(x[i], C, order);
diff[i] = eval[i] - y[i];
mean += diff[i];
}
mean /= size;
// calc sigma
sigma = 0.0;
//<<<<<<< jsd_fit.c
// for (i=0; i<size; i++) {
// for (i=1; i<=size; i++) {
// sigma += (diff[i]-mean)*(diff[i]-mean);
//=======
for (i=0; i<size; i++) {
sigma += SQR(diff[i]-mean);
//>>>>>>> 1.4
}
sigma = sqrt(sigma/size);
// determine outliers
outlier = 0;
for (i=1; i<=size; i++) {
//for (i=0; i<size; i++) {
if (fabs(diff[i] - mean) > nsigma*sigma) {
outlier = 1;
//printf("outlier=%g: (size=%i mean=%g sigma=%g nsigma=%g)\n",
// Y[i], size, mean, sigma, nsigma);
//Y[i] = eval[i];
//size = size-1;
x[i] = x[size];
y[i] = y[size];
size = size-1;
}
}
} while (outlier && size > order+1);
free(eval);
free(diff);
free_dmatrix(v,1,terms,1,terms);
free_dmatrix(u,1,size,1,terms);
free_dmatrix(cvm,1,terms,1,terms);
free_dvector(w,1,terms);
free_dvector(a,1,terms);
free_dvector(sig,1,size);
free_dvector(y,1,size);
free_dvector(x,1,size);
return err;
}
/*int jsd_poly_fit(double X[], double Y[], int size, float nsigma,double C[], int order, double *chisq)
{
int i, j;
gsl_matrix *x, *cov;
gsl_vector *y, *c;
int terms = order + 1;
//allocate memory
gsl_multifit_linear_workspace * work = gsl_multifit_linear_alloc (size, terms);
x = gsl_matrix_alloc (size, terms);
y = gsl_vector_alloc (size);
c = gsl_vector_alloc (terms);
cov = gsl_matrix_alloc (terms, terms);
//prepare the fit start conditions
for (i = 0; i < size; i++)
{
double mv = 1.0;
for (j=0; j<terms; j++) {
gsl_matrix_set (x, i, j, mv);
mv *= X[i];
}
gsl_vector_set (y, i, Y[i]);
}
//perform the fit
gsl_multifit_linear (x, y, c, cov, chisq, work);
//store the results in the output array
for (i=0; i<terms; i++) {
C[i] = gsl_vector_get (c, i);
}
//cleanup memory
gsl_multifit_linear_free (work);
gsl_matrix_free(x);
gsl_vector_free(y);
gsl_vector_free(c);
gsl_matrix_free(cov);
return 1;
}
*/
/* a - array of coefficients 1..ma
* X is normalized on return of this function
*/
/*
void jsd_iterative_fpoly_fit(float X[], float Y[], float sig[], int size, float C[], int order, float *chisq)
{
int i;
int outlierFound;
double sigma;
float *eval;
int nsigma = 3; //TODO: parameterize this or somthing
int count;
int ndata = size;
int ma = order+1;
float **U, **V, *W; //workspaces for svdfit
U = matrix(1, ndata, 1, ma);
V = matrix(1, ma, 1, ma);
W = vector(1, ma);
eval = vector(1, size);
for (i=0; i<size; i++) {
sig[i] = 1.0;
}
count = 0;
do {
sigma = 0;
outlierFound = 0;
//do the fit
jsd_normalize(X, size);
nr_svdfit(X-1, Y-1, sig-1, ndata, C-1, ma, U, V, W, chisq, fpoly);
//calculate the difference between the function evaluation and Y
//and also calculate sigma using the function evaluation as the mean
for (i=0; i<size; i++) {
eval[i] = jsd_fpoly_eval(X[i], C, order);
sigma += SQR(Y[i] - eval[i]);
}
sigma = sqrt(sigma/(size-1));
//reject outliers by making the value equal to the function
for (i=0; i<size; i++) {
if (fabs(eval[i] - Y[i]) > nsigma*sigma*sig[i]) {
outlierFound = 1;
sig[i] = INFINITY;
//printf("outlier at (%f, %f)\n", X[i], Y[i]);
}
}
//fprintf(stdout, "%c(x) = ", 'f'+count);
//for (i=0; i<=order; i++) fprintf(stdout, "%+.6g*x**%i ", C[i], i);
//fprintf(stdout, "\n");
count++;
//repeat until there are no more outliers
} while (outlierFound && count < LOOP_COUNT_MAX);
printf("curve fit iterations: %i\n", count);
free_vector(eval, 1, size);
free_vector(W, 1, ma);
free_matrix(V, 1, ma, 1, ma);
free_matrix(U, 1, ndata, 1, ma);
}
*/
|
C
|
#include<stdio.h>
#include<conio.h>
int _strlen(char *p){
if(*p=='\0')
return(0);
else
return(1+_strlen(p++));
}
void main(){
char str1[100];
int len;
clrscr();
printf("\nEnter a String:");
fflush(stdin);
gets(str1);
len=_strlen(str1);
printf("\nLingth of the given string %s=%d",str1,len);
getch();
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* libft.h :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: dzheng <dzheng@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/11/23 16:49:40 by dzheng #+# #+# */
/* Updated: 2017/02/17 14:41:55 by dzheng ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef LIBFT_H
# define LIBFT_H
# include <string.h>
# include <unistd.h>
# include <stdlib.h>
# include "../libft/libft.h"
# include <stdarg.h>
# include <stdio.h>
# include <wchar.h>
# include <sys/types.h>
# include <sys/stat.h>
# include <fcntl.h>
# include <stdint.h>
/*
** LIBFT
*/
typedef struct s_list
{
void *content;
size_t content_size;
struct s_list *next;
} t_list;
void ft_putchar(char c);
void ft_putstr(char const *s);
int ft_atoi(const char *str);
int ft_strcmp(const char *s1, const char *s2);
char *ft_strcpy(char *dst, const char *src);
char *ft_strdup(const char *str);
size_t ft_strlen(const char *s);
int ft_strncmp(const char *s1, const char *s2, size_t n);
char *ft_strncpy(char *dst, const char *src, size_t len);
int ft_isspace(int c);
char *ft_strcat(char *s1, const char *s2);
char *ft_strncat(char *s1, const char *s2, size_t n);
int ft_isalpha(int c);
int ft_isdigit(int c);
int ft_isalnum(int c);
int ft_isascii(int c);
int ft_isprint(int c);
int ft_ishex(int c);
int ft_toupper(int c);
int ft_tolower(int c);
void ft_putchar_fd(char c, int fd);
void ft_putstr_fd(char const *str, int fd);
void ft_putnbr(int n);
void ft_putnbr_fd(int n, int fd);
void ft_strclr(char *s);
void ft_striter(char *s, void (*f)(char *));
void ft_striteri(char *s, void (*f)(unsigned int, char *));
void ft_putendl(char const *s);
void ft_putendl_fd(char const *s, int fd);
char *ft_strchr(const char *s, int c);
char *ft_strrchr(const char *s, int c);
char *ft_strstr(const char *big, const char *little);
char *ft_strnstr(const char *a, const char *b, size_t len);
size_t ft_strlcat(char *dst, const char *src, size_t size);
void *ft_memset(void *b, int c, size_t len);
void ft_bzero(void *s, size_t n);
void *ft_memcpy(void *dst, const void *src, size_t n);
void *ft_memccpy(void *dst, const void *src, int c, size_t n);
void *ft_memmove(void *dst, const void *src, size_t len);
void *ft_memchr(const void *s, int c, size_t n);
int ft_memcmp(const void *s1, const void *s2, size_t n);
void *ft_memalloc(size_t size);
void ft_memdel(void **ap);
char *ft_strnew(size_t size);
void ft_strdel(char **as);
char *ft_strmap(char const *s, char (*f)(char));
char *ft_strmapi(char const *s, char (*f)(unsigned int, char));
int ft_strequ(char const *s1, char const *s2);
int ft_strnequ(char const *s1, char const *s2, size_t n);
char *ft_strsub(char const *s, unsigned int start, size_t len);
char *ft_strjoin(char const *s1, char const *s2);
char *ft_strnjoin(int n, ...);
char *ft_strtrim(char const *s);
char **ft_strsplit(char const *s, char c);
char *ft_itoa(int n);
t_list *ft_lstnew(void const *content, size_t content_size);
void ft_lstdelone(t_list **alst, void (*del)(void *, size_t));
void ft_lstdel(t_list **alst, void (*del)(void *, size_t));
void ft_lstadd(t_list **alst, t_list *new);
void ft_lstiter(t_list *lst, void (*f)(t_list *elem));
t_list *ft_lstmap(t_list *lst, t_list *(*f)(t_list *elem));
void ft_swap(int *a, int *b);
int ft_isblank(int c);
char *ft_strrev(char *str);
int ft_ispunct(int c);
char *ft_strchar(char c, size_t size);
void ft_write_null(void);
int ft_intlen(int n);
long long ft_abs(long long n);
void ft_lstaddend(t_list **alst, t_list *new);
t_list *ft_lstselectsort(t_list *lst, int (*cmp)(void*, void*));
int ft_lstsize(t_list *lst);
void ft_print_tab(int **tab, int line, int column);
void ft_print_grid(char **str);
/*
** FT_PRINTF
*/
typedef struct s_flags
{
int left_justify;
int fill_w_zero;
int pos_nul;
int is_blank;
int is_sharp;
int size_lenght;
int size_prec;
int which_letter;
int h;
int l;
int j;
int z;
} t_flags;
int ft_printf(const char *format, ...);
int ft_check_letter(va_list ap, char c, t_flags flaggs);
int ft_check_there_is_letter(char c);
t_flags get_width(int *i, t_flags b, va_list ap);
t_flags get_precision(const char *s, int *i, t_flags b, va_list ap);
char *ft_strchar(char c, size_t size);
int ft_printf_c(va_list ap, t_flags flaggs);
int ft_printf_c_maj(va_list ap, t_flags flaggs);
int ft_printf_i(va_list ap, t_flags flaggs, char c);
int ft_printf_s(va_list ap, t_flags flaggs);
int ft_printf_s_maj(va_list ap, t_flags flaggs);
int ft_printf_u(va_list ap, t_flags flaggs, char c);
int ft_printf_o(va_list ap, t_flags flaggs, char c);
int ft_printf_x(va_list ap, t_flags flaggs);
int ft_printf_x_maj(va_list ap, t_flags flaggs);
int ft_printf_p(va_list ap, t_flags flaggs);
int ft_print_per_cent(t_flags flaggs);
char *ft_check_if_flags_str(t_flags flaggs, char *str);
char *ft_check_if_flags_int(t_flags flaggs, char *str);
char *ft_size_lenght(t_flags flaggs, char *str);
char *ft_size_lenght_int(t_flags flaggs, char *str);
char *ft_size_prec(t_flags flaggs, char *str);
char *ft_size_prec_int(t_flags flaggs, char *str, int negative);
char *ft_is_blank(t_flags flaggs, char *str, int negative);
char *ft_is_pos_nul(t_flags flaggs, char *str, int negative);
char *convert_int_to_octal(uintmax_t i);
char *convert_int_to_hex(uintmax_t i);
char *convert_int_to_hex_maj(uintmax_t i);
char *ft_itoa_intmax_t(intmax_t n);
char *ft_itoa_uintmax_t(uintmax_t n);
int ft_atoi_intmax_t(const char *str);
intmax_t arg_signed_modifier(va_list ap, t_flags b);
uintmax_t arg_unsigned_modifier(va_list ap, t_flags b);
char *ft_unicode(wchar_t c);
int ft_free_return(char **str);
void ft_lenght_c(t_flags *b, char **str);
int ft_check_strong_bite(char byte);
int ft_apply_width(t_flags b, char c);
int ft_is_flags(char c);
char *ftf_join_flags(char *str, t_flags b, char *tmp);
char *ft_join_unicode(char *out_unicode, wchar_t *str);
char *ft_convert_octal(char *str, uintmax_t i, t_flags b);
int ft_free_flags_return(char **str, t_flags b);
char *ft_join_flags_int(t_flags b, char *str);
char *ft_join_lenght_int(t_flags b, char *tmp, char *str);
/*
** GET_NET_LINE
*/
# define BUFF_SIZE 1000
typedef struct s_fd
{
int n_fd;
char *str;
struct s_fd *next;
} t_fd;
int get_next_line(const int fd, char **line);
#endif
|
C
|
//
// Created by yyh on 18-7-30.
//
#include "client_fun.h"
#include "mySocket.h"
#include "login.h"
#include "Initialization.h"
/************************************************************************
函数名称: void *client_fun(void *arg)
函数功能: 线程函数,处理客户信息
函数参数: 已连接套接字
函数返回: 无
************************************************************************/
void *client_fun(void *arg)
{
int sock = (int)arg; // 传入的已连接套接字
int flag = 0;
while (flag != STOP_LOOP){
if ((flag = getFlag(sock)) != -4){
}
switch (flag) {
case RECV_MAIL:
servRecvMail(sock);
break;
case CHECK_MAIL:
checkMail();
break;
case SEND_MAIL:
sendMail(sock);
break;
case DEL_MAIL:
delMail();
break;
case START_MAIL:
startMail();
break;
case MODIFY_CONTACT:
modifyContect(sock);
break;
case MODIFY_BLACK_LIST:
modifyBlackList();
break;
case STOP_LOOP:
break;
case LOGIN:
servLogin(sock);
break;
case SINGUP:
servSignUp(sock);
break;
case LOGOUT:
servLogOut(sock);
break;
default:
break;
}
}
printf("client closed!\n");
close(sock); //关闭已连接套接字
return NULL;
}
int getFlag(int socket){
char id[FLAG_SIZE] = {0};
char pass[FLAG_SIZE] = {0};
int flag = 0;
char type;
if(myRecvMsg(socket, &flag, &type) <= 0){
return STOP_LOOP;
}
myRecvMsg(socket, id, &type);
myRecvMsg(socket, pass, &type);
if (flag == LOGOUT){
mySendMsg(socket, &flag, sizeof(flag), MY_MSG);
return flag;
}
int check = login(id, pass);
if (check == -4 && flag == 8) {
return DO_NOTHING;
}
else {
mySendMsg(socket, &flag, sizeof(flag), MY_MSG);
}
return flag;
}
int checkMail(){
}
int sendMail(int sock){
int flag = 0;
char fileName[FILE_NAME_MAX_SIZE] = {0};
myRecvFile(sock, "server/TemporaryStorage/", sizeof("server/TemporaryStorage/"), fileName);
flag = sfRecieve(fileName);
mySendMsg(sock, &flag, sizeof(flag), MY_MSG);
return flag;
}
int delMail() {
}
int startMail() {
}
int modifyContect(int sock) {
char type;
char id[12];
char buf[FILE_NAME_MAX_SIZE];
myRecvMsg(sock, id, &type);
char path[FILE_NAME_MAX_SIZE];
strcat(path, "server/");
strcat(path, id);
strcat(path, "/mailBox/");
myRecvFile(sock, path, strlen(path) + 1, buf);
}
int modifyBlackList() {
}
int servLogin(int sock) {
char id[FLAG_SIZE] = {0};
char pass[FLAG_SIZE] = {0};
char type;
myRecvMsg(sock, id, &type);
myRecvMsg(sock, pass, &type);
int flag = login(id, pass);
mySendMsg(sock, &flag, sizeof(flag), MY_MSG);
return flag;
}
int servLogOut(int sock){
char id[FLAG_SIZE] = {0};
char type;
myRecvMsg(sock, id, &type);
logout(id);
mySendMsg(sock, "OK", sizeof("OK"), MY_MSG);
return 0;
}
int servSignUp(int sock) {
char id[FLAG_SIZE] = {0};
char pass[FLAG_SIZE] = {0};
char type;
myRecvMsg(sock, id, &type);
myRecvMsg(sock, pass, &type);
int flag = selfInitiallization(id, pass);
mySendMsg(sock, &flag, sizeof(flag), MY_MSG);
return flag;
}
int servRecvMail(int sock) {
char id[FLAG_SIZE];
int flag = RECV_MAIL;
char type;
myRecvMsg(sock, id, &type);
char path[FILE_NAME_MAX_SIZE] = {0};
strcat(path, "server/");
strcat(path, id);
strcat(path,"/mailBox/mailNumber.txt");
FILE* fp = fopen(path, "r");
if (fp){
mySendFile(sock, "mailNumber.txt", sizeof("mailNumber.txt"), fp);
fclose(fp);
}
else {
flag = -1;
}
bzero(path, sizeof(path));
strcat(path, "server/");
strcat(path, id);
strcat(path,"/mailBox/list.txt");
fp = fopen(path, "r");
if (fp) {
mySendFile(sock, "list.txt", sizeof("list.txt"), fp);
fclose(fp);
}
else {
flag = -1;
}
mySendMsg(sock, &flag, sizeof(flag), MY_MSG);
return flag;
}
|
C
|
static inline
bool mutexInit(pthread_mutex_t *mutex)
{
pthread_mutexattr_t mutexattr;
return
ASSERT((errno = pthread_mutexattr_init(&mutexattr)) == 0) ||
ASSERT((errno = pthread_mutexattr_settype(&mutexattr,
PTHREAD_MUTEX_FAST_NP)) == 0) ||
ASSERT((errno = pthread_mutex_init(mutex, &mutexattr)) == 0) ||
ASSERT((errno = pthread_mutexattr_destroy(&mutexattr)) == 0);
}
static inline
bool _mutexTryLock(pthread_mutex_t *mutex)
{
errno = pthread_mutex_trylock(mutex);
switch(errno)
{
case 0:
return true; // we have the lock
case EBUSY:
return false; // we do NOT have the lock
default:
VASSERT(0, "pthread_mutex_trylock() failed");
}
return false; // oh shit
}
static inline
bool _mutexLock(pthread_mutex_t *mutex)
{
while((errno = pthread_mutex_lock(mutex)) != 0)
{
if(errno != EINTR)
return VASSERT(0, "pthread_mutex_lock() failed");
WARN("pthread_mutex_lock() was interrupted by a signal");
}
return false;
}
#ifdef PO_PTHREADMUTEX_DEBUG
static inline bool
_MutexTryLock(pthread_mutex_t *mutex, const char *file, int line)
{
bool ret = _mutexTryLock(mutex);
if(!ret)
ERROR("%s:%d:%s() failed", file, line, __func__);
return ret;
}
static inline bool
_MutexLock(pthread_mutex_t *mutex, const char *file, int line)
{
if(!_mutexTryLock(mutex))
{
ERROR("%s:%d:%s() blocked", file, line, __func__);
return _mutexLock(mutex);
}
return false;
}
# define mutexTryLock(x) _MutexTryLock((x), __BASE_FILE__, __LINE__)
# define mutexLock(x) _MutexLock((x), __BASE_FILE__, __LINE__)
#else
# define mutexTryLock(x) _mutexTryLock(x)
# define mutexLock(x) _mutexLock(x)
#endif
static inline
bool mutexUnlock(pthread_mutex_t *mutex)
{
return ASSERT((errno = pthread_mutex_unlock(mutex)) == 0);
}
static inline
bool condInit(pthread_cond_t *cond)
{
return ASSERT((errno = pthread_cond_init(cond, NULL)) == 0);
}
static inline
bool mutexDestroy(pthread_mutex_t *mutex)
{
return ASSERT((errno = pthread_mutex_destroy(mutex)) == 0);
}
static inline
bool condDestroy(pthread_cond_t *cond)
{
return ASSERT((errno = pthread_cond_destroy(cond)) == 0);
}
static inline
bool condWait(pthread_cond_t *cond, pthread_mutex_t *mutex)
{
errno = 0;
if((errno = pthread_cond_wait(cond, mutex)) != 0)
{
if(errno != EINTR)
return VASSERT(0, "pthread_cond_wait() failed");
WARN("pthread_cond_wait() was interrupted by a signal\n");
}
return false;
}
static inline
int condTimedWait(pthread_cond_t *cond, pthread_mutex_t *mutex,
uint32_t timeOut /*milli-seconds = 1/1000 sec*/)
{
struct timeval now;
struct timespec timeout;
ASSERT(gettimeofday(&now, 0) == 0);
timeout.tv_sec = now.tv_sec + timeOut/1000;
// tv_nsec is in nano seconds = 10^(-9) seconds
// tv_usec is in microseconds = 10^(-6) seconds
// timeOut in in milliseconds = 10^(-3) seconds
timeout.tv_nsec = now.tv_usec*1000 + (timeOut%1000)*1000000;
if(timeout.tv_nsec > 1000000000)
{
uint64_t extraSecs;
extraSecs = timeout.tv_nsec/1000000000;
timeout.tv_sec += extraSecs;
timeout.tv_nsec -= extraSecs * 1000000000;
}
errno = 0;
if((errno = pthread_cond_timedwait(cond, mutex, &timeout)) != 0)
{
if(errno != EINTR && errno != ETIMEDOUT)
{
VASSERT(0, "pthread_cond_timedwait() failed");
return errno;
}
else if(errno == EINTR)
WARN("pthread_cond_timedwait() was interrupted by a signal\n");
// errno == ETIMEDOUT is the time expired case that will be
// common.
//else if(errno == ETIMEDOUT)
// WARN("pthread_cond_timedwait() time expired");
}
return errno;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
double y ;
for(y=1;y!=10;y++){
printf("%lf\n",y/10);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
void swap(int*, int, int);
void imprimir_lista(int*, int);
int main() {
int i = 0;
int j = 0;
int n = 0;
int* lista;
printf("Cantidad de datos: ");
scanf("%d", &n);
lista = malloc(n*sizeof(int));
for(i = 0; i < n; i++){
scanf("%d", &lista[i]);
}
imprimir_lista(lista, n);
int minimo = 0;
int minimovalor = 0;
for(i = 0; i < n; i++) {
minimovalor = lista[i];
minimo = i;
for(j = i; j < n; j++) {
if(lista[j] < minimovalor) {
minimovalor = lista[j];
minimo = j;
}
}
swap(lista, i, minimo);
}
imprimir_lista(lista, n);
return 0;
}
void swap(int* lista, int i, int j){
int tmp = lista[i];
lista[i] = lista[j];
lista[j] = tmp;
return;
}
void imprimir_lista(int* lista, int n){
for(int i = 0; i < n; i++) {
printf("%d\t", lista[i]);
}
printf("\n");
return;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
struct node {
int data;
int status; struct node *next;
};
struct node *root=NULL;
void createGraph(struct node *adj[10],int n) {
struct node *last;
int m,val,d;
for(int i=0; i<n; i++) {
printf("Enter the neighbours for %d :",i);
scanf("%d",&m);
for(int j=0; j<m; j++) {
scanf("%d",&val);
struct node *temp= malloc(sizeof(struct node));
temp->data=val;
temp->next=NULL;
if(adj[i]==NULL) {
adj[i]=temp;
} else {
last->next=temp;
}
last=temp;
}
}
}
void Display(struct node *adj[10],int n) {
for(int i=0; i<n; i++) {
struct node *temp; temp=adj[i];
printf("Node %d = ",i); while(temp!=NULL)
{
printf("%d->",temp->data); temp=temp->next;
}
printf("NULL\n");
}
}
void bfs(struct node *adj[10],int n,int *parent) {
int queue[n];
int visited[n];
for(int i=0; i<n; i++) {
visited[i]=0;
}
int front,rear;
front=rear=-1;
queue[rear++]=0;
visited[0]=1;
parent[0]=-1;
while(rear!=front) {
int x=queue[front++];
printf("%d ",x);
struct node *temp=adj[x];
while(temp!=NULL) {
if(visited[temp->data]==0) {
queue[rear++]=temp->data;
visited[temp->data]=1;
parent[temp->data]=x;
}
temp=temp->next;
}
}
printf("\n");
}
void dfs(struct node *adj[10],int n,int *visited) {
struct node *temp;
visited[n]=1;
printf("%d ",n);
temp=adj[n];
while(temp!=NULL) {
if(visited[temp->data]==0) {
dfs(adj,temp->data,visited);
}
else {
temp=temp->next;
}
}
}
int main() {
int v;
printf("Enter the number of nodes : ");
scanf("%d",&v);
struct node *adj[10];
for(int i=0; i<v; i++) {
adj[i]=NULL;
}
createGraph(adj,v);
int p[v];
Display(adj,v);
printf("\nBFS Traversal : ");
bfs(adj,v,p);
int visited[10]= {0};
printf("\n");
printf("DFS Traversal : ");
dfs(adj,0,visited);
return 0;
}
|
C
|
/*Atividade 2.5 - Consumo de combustvel*/
#include <stdio.h>
#include <locale.h>
int main() {
system("cls");
setlocale(LC_ALL, "Portuguese");
float distancia, litros, consumo;
printf("\n\n -------*Programa calcula o consumo mdio de combustvel*-------\n");
printf("\n Digite a distncia em quilmetros: ");
scanf("%f", &distancia);
printf("\n Digite o total de combustvel gasto em litros: ");
scanf("%f", &litros);
consumo = litros / distancia;
printf("\n O consumo mdio %.2f l/km \n", consumo);
system("pause");
return 0;
}
|
C
|
/*
* PID.c
*
* Created on: Feb 27, 2015
* Author: Erik Johnson
*/
#include "derivative.h"
#include "PID.h"
#include "AK8963.h"
#include "math.h"
int Calculate_Error_Mag (AK8963_Data sensordata) // To be implemented**** (Erik)
{
// Compute current direction vector using the equation:
// theta = arctan ( Y / X )
/*
Y
^ X
| XXXXXX
| XXXXX
| XXXXXX
| XXXXX
| XXXXXXX
| XXXXXXX
| XXXXXXXX
| XXXXXXXXX
| XXXXXXXX XX theta
| XXXXXXX X
XX-----------------------X-----------------------------------> X
*/
double theta = atan2((double)sensordata.HY, (double)sensordata.HX); // Signed angle in radians (-PI, PI)
theta = theta * (180.0/(atan(1)*4.0)); // Convert to signed degrees (-180, 180) (uses ghetto pi)
return (int)theta; // Return signed angle from X axis (corresponds to setpoint of aligning X axis)
}
int Calculate_Correction (int errorvalue, int* last_i_term, int* last_d_term, double KP, double KI, double KD)
{
int P_Term; // Holds the calculated Proportional value
int I_Term; // Holds the calculated Integral value
int D_Term; // Holds the calculated Differential value
// This calculates Proportional value, Kp is multiplied with errValue and the result is assigned to P_Term
P_Term = KP * errorvalue;
// Prepare Integral value, add the current error value to the integral value and assign the total to i_Temp
*last_i_term = *last_i_term + errorvalue;
// Prevents integral wind-up, limits i_Temp from getting too positive or negative
if (*last_i_term > IMAX)
*last_i_term = IMAX;
else if (*last_i_term < IMIN)
*last_i_term = IMIN;
// Calculates the Integral value, Ki is multiplied with i_Temp and the result is assigned to I_Term
I_Term = KI * (*last_i_term);
// Calculates Differential value, Kd is multiplied with (d_Temp minus newMagValue) and the result is assigned to D_Term
// The newMagValue will become the old ADC value on the next function call, this is assigned to d_Temp so it can be used
D_Term = KD * ((*last_d_term) - errorvalue);
*last_d_term = errorvalue;
// We now have all the terms, return the correction to be made
return (P_Term + I_Term + D_Term);
}
|
C
|
/* Erich WOo & Boxian Wang
* 26 October 2020
* Kernel Context Switching. See cswitch.h for detailed documentation
*/
#include "cswitch.h"
// THE proc table
extern proc_table_t *procs;
// THE global kernel page tables
extern kernel_global_pt_t kernel_pt;
/********************* FUNCTION DECLARATIONS ***********************/
/* Switches Kernel Context and kernel stack pages
* from the specified current process, to the specified next.
* A copy of the KernelContext is stored into the current process so that when the
* current process resumes at some later time, it will return from the KCS call.
* The kc* of the next process is returned, so that the kernel teleports to the next.
*
* @param kc_in the Kernel Context pointer of the caller
* @param curr_pcb_p the current process' pcb pointer
* @param next_pcb_p the next process' pcb pointer
* @return the KernelContext pointer of the next process
*/
KernelContext* KCSwitch(KernelContext *kc_in, void *curr_pcb_p, void *next_pcb_p);
/* From the Yalnix Manual:
* - KCCopy will simply copy the kernel context from *kc_in into the new pcb,
* and copy the contents of the current kernel stack
* into the frames that have been allocated for the new process’s kernel stack.
* However, it will then return kc in.
*
* new_pcb_p must be an initialized/copied pcb_t* before calling KCCopy
*
* @param kc_in the Kernel Context pointer of the caller
* @param new_pcb_p the child's pcb pointer
* @param not_used an unused parameter
* @return the KernelContext pointer both parent and child return from
*/
KernelContext* KCCopy(KernelContext *kc_in, void *new_pcb_p, void *not_used);
/********************* FUNCTIONS ***********************/
void save_uc(UserContext *uc) {
pcb_t *curr = procs->running->data;
curr->uc = *uc;
}
void restore_uc(UserContext *uc) {
pcb_t *curr = procs->running->data;
*uc = curr->uc;
}
void add_return_val(int r) {
pcb_t *curr = procs->running->data;
curr->uc.regs[0] = r;
}
void switch_proc(node_t *from, node_t *to) {
KernelContextSwitch(KCSwitch, from->data, to->data);
}
void copy_kernel(node_t *child) {
KernelContextSwitch(KCCopy, child->data, NULL);
}
KernelContext* KCSwitch(KernelContext *kc_in, void *curr_pcb_p, void *next_pcb_p) {
pcb_t *curr_pcb = (pcb_t *) curr_pcb_p, *next_pcb = (pcb_t *) next_pcb_p;
curr_pcb->kc = *kc_in;
// switching kernel stack
for (int vpn = BASE_PAGE_KSTACK; vpn < LIM_PAGE_KSTACK; vpn++) {
kernel_pt.pt[vpn - BASE_PAGE_0] = next_pcb->kstack->pt[vpn - BASE_PAGE_KSTACK];
}
WriteRegister(REG_TLB_FLUSH, TLB_FLUSH_KSTACK);
WriteRegister(REG_PTBR1, (unsigned int) next_pcb->userpt->pt);
WriteRegister(REG_TLB_FLUSH, TLB_FLUSH_1);
return &next_pcb->kc; // teleport to next
}
KernelContext* KCCopy(KernelContext *kc_in, void *new_pcb_p, void *not_used) {
pcb_t *new_pcb = (pcb_t *) new_pcb_p;
new_pcb->kc = *kc_in;
// copy kernel stack; has to be done in a magical stack!
int dummy = BASE_PAGE_KSTACK - 1;
for (int vpn = BASE_PAGE_KSTACK; vpn < LIM_PAGE_KSTACK; vpn++) {
set_pte(&kernel_pt.pt[dummy - BASE_PAGE_0], 1, get_frame(NONE, AUTO), PROT_READ|PROT_WRITE);
WriteRegister(REG_TLB_FLUSH, dummy << PAGESHIFT); // must flush after use!
memcpy((void*) (dummy << PAGESHIFT), (void*) (vpn << PAGESHIFT), PAGESIZE);
new_pcb->kstack->pt[vpn - BASE_PAGE_KSTACK] = kernel_pt.pt[dummy - BASE_PAGE_0];
}
set_pte(&kernel_pt.pt[dummy - BASE_PAGE_0], 0, NONE, NONE);
WriteRegister(REG_TLB_FLUSH, dummy << PAGESHIFT);
return kc_in; // go back
}
|
C
|
#include<stdio.h>
//Reading input from user
int read_int(void)
{
int i=0;
char num[20];
scanf("%s",num);
//Clear buffer
while(getchar() != '\n');
//Check if the first character is integer or alphabet;if true return
if(num[0]<48 || num[0]>57)
{
printf("The entered character is not integer.\n");
return 0;
}
//Check for all characters entered by user and print only integer number
while(num[i] != '\0')
{
//Check if the number is in the range of ASCII value 48 to 57
if(num[i]>47 && num[i] <58)
printf("The number is: %c\n",num[i]);
else
printf("The entered character is not integer.\n");
//Increment the index
i++;
}
return 0;
}
//Main function
int main()
{
char ch;
while(1)
{
//Prompt user for input
printf("Enter the number:");
read_int();
//Ask user for options
printf("\nDo you want to continue(Y/N):");
ch=getchar();
while(getchar() != '\n');
if(!(ch == 'Y' || ch == 'y'))
{
break;
}
}
return 0;
}
|
C
|
/*
* synchronized I/O
*/
#include <stdio.h>
#include <fcntl.h>
#include <sys/stat.h>
char wbuf[] = {"12CDEFGHIJKLMNOP"};
int main()
{
int fd;
int nw;
int arg=0;
unsigned int fl;
fd = open("myfile.txt", O_RDONLY);
printf("fd = %d\n", fd);
fl=fcntl(fd, F_GETFL, arg);
printf("fl = %x\n", fl);
fcntl(fd, F_SETFL, O_RDWR);
fl=fcntl(fd, F_GETFL, arg);
printf("fl = %x\n", fl);
write(fd, wbuf, 16);
close(fd);
return 0;
}
|
C
|
/**
*@file quectel_tts_client.c
*@date 2017-08-24
*@author running.qian
*@brief Quecte TTS client
*/
#include "ql_oe.h"
#include "ql_tts_client_api.h"
#define QL_TTS_LOG(format, ...) fprintf(stderr, "[QL_TTS_E][%d]:"format, __LINE__, ##__VA_ARGS__)
void user_callback(ql_tts_client_event_e_type evt, char *infostr)
{
QL_TTS_LOG("user_callback Got evt:%d, %s\n\r", evt, infostr);
}
int main(int argc, char *argv[])
{
int i, value;
char ucs_demo[] = {"6B228FCE4F7F752879FB8FDC6A215757"};
QL_TTS_LOG("cmd: %s %s\n\r", argv[1], argv[2]);
QL_TTS_client_init(user_callback);
if (strcmp(argv[1], "p1") == 0) {
QL_TTS_client_play(QL_TTS_PLAY_MODE_NORMAL, QL_TTS_DATA_MODE_ASCII, argv[2], strlen(argv[2]));
}
else if (strcmp(argv[1], "p2") == 0) {
QL_TTS_client_play(QL_TTS_PLAY_MODE_NORMAL, QL_TTS_DATA_MODE_UCS, argv[2], strlen(argv[2]));
}
else if (strcmp(argv[1], "st") == 0) {
QL_TTS_client_stop();
}
else if (strcmp(argv[1], "sv") == 0) {
value = atoi(argv[2]);
QL_TTS_client_volume_set(value);
}
else if (strcmp(argv[1], "gv") == 0) {
value = QL_TTS_client_volume_get();
QL_TTS_LOG("Get Volume Vaule is %d\n",value);
}
else if (strcmp(argv[1], "ss") == 0) {
value = atoi(argv[2]);
QL_TTS_client_speed_set(value);
}
else if (strcmp(argv[1], "gs") == 0) {
value = QL_TTS_client_speed_get();
QL_TTS_LOG("Get Speed Value is %d\n\r",value);
}
else {
QL_TTS_LOG("unkonwn test cmd\n\r");
QL_TTS_client_deinit();
return 0;
}
while (1) {
sleep(1);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <string.h>
// (1) string is a group of characters
// how to store a string in char array?
// size of char array must be >= num of characters + 1
// + 1 is for '\0'
// (2) Arrays and pointers are different types that are used in similar manner
// (3) Arrays are always passed to function by reference
void charPtrVsArray()
{
char c1[] = "Hello";
char* c2;
int i;
printf("c1 = %s\n", c1);
c2 = c1; // valid
// c1 = c2; is invalid -> compilation error
printf("c2[1] = %c\n", c2[1]);
c2[0] = 'A';
printf("c1 = %s\n", c1);
for(i=0; i<strlen(c2); i++)
{
printf(" c2[%d] = %c\n", i, c2[i]);
printf(" *(c2+%d) = %c\n", i, *(c2+i));
}
}
int test()
{
char str[] = "john"; // '\0' is auto added
int str_len = sizeof(str);
int i;
printf("str = %s\n", str);
int len = strlen(str);
int size = sizeof(str);
printf(" len of C = %d\n", len);
printf(" sizeof C = %d\n", size);
for (i=0; i<str_len; i++)
{
// printf( "c[%d] = %c\n", i, str[%i]);
}
return 0;
}
// arg is c[] which is treated as pointer to the 1st char of string
// c++ is move one char at a time
void myPrintStr(char* c)
{
printf("%s\n", c);
int i=0;
while (*(c+i) != '\0')
{
printf("%c-", c[i]);
i++;
}
printf("\n");
while(*c != '\0')
{
printf("%c#", *c);
c++;
}
printf("\n");
}
int myStrCmp(char *s1, char *s2)
{
//while ((*s1!='\0') && (*s2!='\0') && (*s1 == *s2)) // work, but need to check if *s2 is '\0'
while ((*s1!='\0') && (*s1 == *s2))
// while (*s1 == *s2) // doesn't work with '\0' vs '\0'
{
s1++;
s2++;
}
return (*s1 - *s2);
}
int main()
{
char C[20];
C[0] = 'J';
C[1] = 'O';
C[2] = 'H';
C[3] = 'N';
C[4] = '!';
// C[5] = '\0';
int len = strlen(C);
int size = sizeof(C);
printf("C = %s\n", C);
printf(" len of C = %d\n", len);
printf(" sizeof C = %d because we defined 'char C[%d]'\n", size, size);
test();
charPtrVsArray();
printf("Test myPrintStr()\n");
myPrintStr("abcdefg");
printf("%d\n", myStrCmp("", ""));
printf("%d\n", myStrCmp("AB", "ABC"));
printf("%d\n", myStrCmp("ABC", "AB"));
printf("%d\n", myStrCmp("ABC", "ABC"));
}
|
C
|
#include "vm_pool.H"
#define MB * (0x1 << 20)
#define KB * (0x1 << 10)
#define KERNEL_POOL_START_FRAME ((2 MB) / FRAME_SIZE)
#define KERNEL_POOL_SIZE ((2 MB) / FRAME_SIZE)
#define PROCESS_POOL_START_FRAME ((4 MB) / FRAME_SIZE)
#define PROCESS_POOL_SIZE ((28 MB) / FRAME_SIZE)
/* definition of the kernel and process memory pools */
#define MEM_HOLE_START_FRAME ((15 MB) / FRAME_SIZE)
#define MEM_HOLE_SIZE ((1 MB) / FRAME_SIZE)
/* we have a 1 MB hole in physical memory starting at address 15 MB */
#define KERNEL_BASE_ADDR (2 MB)
#define PROCESS_BASE_ADDR (4 MB)
/* definition of base addresses for the kernel and process pools*/
#define FRAME_SIZE (4 KB)
/* definition of the frame size */
#define PAGE_TABLE_SIZE (0x1 << 10)
/* definition of the number of entries on a page table */
const unsigned int VMPool::_MAX_NO_REGIONS;
/* Static variables definition */
VMPool::VMPool(unsigned long _base_address, unsigned long _size, FramePool *_frame_pool, PageTable *_page_table){
/*store all the necessary properties*/
base_address = _base_address;
size = _size;
framePool = _frame_pool;
pageTable = _page_table;
region_index = 0;
_page_table->register_vmpool(this); //register the VM Pool on the page table
regions[0].base_address = _base_address;
regions[0].size = _size;
regions[0].available = TRUE;
/*Initialize the allocated regions array with a single element representing the entire vm pool as available*/
}
unsigned long VMPool::allocate(unsigned long _size){
unsigned long base_addr = 0;
unsigned long remainingSize = 0;
unsigned long sizeToAllocate = _size % PageTable::PAGE_SIZE > 0 ? ((_size / PageTable::PAGE_SIZE) + 1) * PageTable::PAGE_SIZE : _size; //computes the size of the region, rounding to the next multiple of page size
int i;
for (i = 0; i < region_index; ++i) //iterate over the allocated regions to look if any of the previously allocate ones is available now
{
if(regions[i].available == TRUE && regions[i].size >= sizeToAllocate){ //found a region that was released
base_addr = regions[i].base_address;
if(i < _MAX_NO_REGIONS - 1){ //there is still room to split this region in two if size needed is less than the current size of the region
remainingSize = regions[i].size - sizeToAllocate; //compute the remaining size when allocating just the size needed
regions[i].size = sizeToAllocate;
regions[i].available = FALSE;
if(remainingSize > 0){ //creates a new available region with the remaining size computed
for(int j = region_index; j > i; j--){ //shift all allocated regions one space to the right to make room for the newly created region
regions[j].base_address = regions[j-1].base_address;
regions[j].size = regions[j-1].size;
regions[j].available = regions[j-1].available;
}
regions[i+1].base_address = regions[region_index].base_address + regions[region_index].size;
regions[i+1].size = remainingSize;
regions[i+1].available = TRUE;
/* creates the new available region and set it to available*/
region_index++;
}
break;
}
else{ //allocated regions array is already full and thus no split is possible, simply mark the region as unavailable
regions[i].available = FALSE;
break;
}
}
}
if(i == region_index){ //reached the last region allocated without finding any available spot
if(regions[region_index].available == TRUE && regions[i].size >= sizeToAllocate){ //check if the last allocated region is available and if it has enough size to accommodate the request
base_addr = regions[region_index].base_address;
if(region_index < _MAX_NO_REGIONS - 1){ //there is still room to split this region in two if size needed is less than the current size of the region
regions[(region_index+1)].available = TRUE;
regions[(region_index+1)].base_address = regions[region_index].base_address + sizeToAllocate;
remainingSize = regions[region_index].size - sizeToAllocate;
regions[(region_index+1)].size = remainingSize;
/*creates a new region with the remaining size and set it to available*/
regions[region_index].size = sizeToAllocate;
regions[region_index].available = FALSE;
regions[region_index].base_address = base_addr;
region_index++;
/*mark the region with the proper size and set available to false*/
}
else{ //allocated regions array is already full and thus no split is possible, simply mark the region as unavailable
regions[region_index].available = FALSE;
}
}
else{ //no region available to allocate
Console::puts("Error when allocating the region!\n");
return 0;
}
}
return base_addr;
}
void VMPool::release(unsigned long _start_address){
int index = -1;
for (int i = 0; i < region_index; ++i) //search for the region that is going to be released and store the index of it
{
if(regions[i].base_address == _start_address){
index = i;
break;
}
}
if(index != -1) {
for (int i = _start_address; i < regions[i].base_address + regions[i].size; i += PageTable::PAGE_SIZE) //free all the pages within that region
{
pageTable->free_page(_start_address / PageTable::PAGE_SIZE);
}
regions[index].available = TRUE; //mark the region as available
pageTable->load(); //flush the TLB
}
}
BOOLEAN VMPool::is_legitimate(unsigned long _address){
for (int i = 0; i < _MAX_NO_REGIONS; ++i) //iterate over the allocated regions to look if the address is valid
{
if(_address >= regions[i].base_address && _address < (regions[i].base_address + regions[i].size) && regions[i].available == FALSE){ //_address is within the region and region is not available
return TRUE;
}
}
return FALSE;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<dlfcn.h>
#include<string.h>
#include <sys/types.h>
#include <unistd.h>
#include "handlers.h"
char *so_array[300];
char filename[100];
char soname[100];
char so_name[300];
int init_handlers(){
static int i=0,j=1;
FILE *fp;
void *soptr;
fp=fopen("./config.txt","r");
if(fp==NULL){
printf("config.txt not found \n");
return FALSE;
}
fgets(so_name,300,fp);
while(!feof(fp)){
so_name[strlen(so_name)-1]='\0';
printf("%d.Loading .. %s\n",j,so_name);
j++;
soptr=dlopen(so_name,RTLD_NOW);
so_array[i]=soptr;
i++;
if(soptr == NULL){
printf("failed to load library\n");
return FALSE;
}
fgets(so_name,300,fp);
}
return TRUE;
}
void handleMenuEvent(int choice)
{
switch (choice){
case 1:
printf("Enter file name :");
scanf("%s",filename);
vdrawimage(filename);
break;
case 2:
printf("Enter file name :");
scanf("%s",filename);
vsavefile(filename);
break;
case 4:
printf("enter the name of so file that you want to remove:\n");
scanf("%s",soname);
unreg_handler(soname);
}
printf("---------------------\n");
}
void displayMenu()
{
int choice;
while(1){
printf("1: show image \n");
printf("2: save image \n");
printf("3: exit \n");
printf("4: you want to remove any so file\n");
printf("choice:");
scanf("%d",&choice);
if(choice == 3)
exit(0);
handleMenuEvent(choice);
}
}
int main()
{
start = (struct node *) malloc(sizeof(struct node));
ptr=start;
printf("start : %p\n",start);
init_handlers();
displayMenu();
return 0;
}
|
C
|
#include <assert.h>
#include <stdint.h>
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include "minimalloc.h"
/* 4 is not enough for 64 bit arches */
#define MIN_ORDER 5
/* #define MAX_ORDER 24 */
#define CHUNKS_COUNT 5
/*
* Chunked blob is split into contiguous power of 2 chunks. Up to
* CHUNKS_COUNT chunks.
*
* 'size' determines chunks count and sizes (via
* value_size_to_block_sizes). Biggest chunk -> smallest chunk. Chunk
* 0 (biggest one) starts right after end of chunked_blob structure
*/
struct chunked_blob {
unsigned size;
void *other_chunks[CHUNKS_COUNT-1];
};
/* We need to find at most CHUNKS_COUNT powers of two that cover size
* + all required metadata (chunked_blob, block headers) with minimal
* total size. This can be greatly improved, but for now it can remain
* suboptimal. Unused orders array positions are set to -1. */
static
void value_size_to_block_sizes(unsigned size, int orders[CHUNKS_COUNT])
{
unsigned original_size = size;
(void) original_size;
unsigned thing;
int i;
/* we'll need exactly one chunked_blob struct header */
size += sizeof(struct chunked_blob);
if (size <= (2U << MIN_ORDER)) {
if (size <= (1U << MIN_ORDER)) {
thing = (1U << MIN_ORDER);
goto skip_upper_bound;
}
thing = (2U << MIN_ORDER);
goto skip_upper_bound;
}
i = CHUNKS_COUNT;
thing = 0;
while (--i >= 0 && thing != size) {
/* count leading zeros of remaining difference and
* find highest set bit of it */
int order = sizeof(unsigned) * 8 - __builtin_clz(size - thing) - 1;
if (order < MIN_ORDER) {
thing += (1U << MIN_ORDER);
goto skip_upper_bound;
}
thing |= (1U << order);
}
/* size is still smaller then thing. Add into smallest set bit
* of thing to make it larger then size. */
if (thing != size)
thing += (1U << __builtin_ctz(thing));
skip_upper_bound:
i = 0;
double prop = (double)(thing-size)/thing;
/* printf("thing/original_size: %f, %d\n", (double)(thing - original_size) / thing, original_size); */
assert(prop >= 0 && prop < 1.0);
while (thing) {
int order = sizeof(unsigned) * 8 - __builtin_clz(thing) - 1;
orders[i++] = order;
thing -= (1U << order);
}
for (;i < CHUNKS_COUNT; i++)
orders[i] = -1;
}
static struct mini_state *ms;
static size_t total_allocated;
static
void *mi_mallocer(size_t size)
{
void *rv = malloc(size);
if (!rv) {
abort();
}
total_allocated += size;
return rv;
}
static
void *xmalloc(size_t size)
{
if (!ms) {
ms = mini_init(mi_mallocer, 0);
if (!ms) {
abort();
}
}
void *rv = mini_malloc(ms, size);
return rv;
}
static
void xfree(void *p)
{
assert(ms);
mini_free(ms, p);
}
struct chunked_blob *allocate_blob(unsigned size)
{
int i;
int orders[CHUNKS_COUNT];
struct chunked_blob *blob;
value_size_to_block_sizes(size, orders);
unsigned allocated;
unsigned subsize;
unsigned char filler;
blob = xmalloc(subsize = (1U << (orders[0])));
allocated = subsize;
blob->size = size;
filler = (uintptr_t)blob % 251;
memset(blob + 1, filler, subsize - sizeof(struct chunked_blob));
for (i = 1; i < CHUNKS_COUNT && orders[i] >= 0; i++) {
subsize = 1U << orders[i];
void *ptr = blob->other_chunks[i-1] = xmalloc(subsize);
allocated += subsize;
memset(ptr, filler, subsize);
}
assert(allocated > size);
return blob;
}
static
void memchk(void *_p, unsigned char value, size_t orig_len)
{
char *p = _p;
assert(((uintptr_t)p & 3) == 0);
assert((orig_len & 3) == 0);
size_t len = orig_len / 4;
uint32_t acc = 0;
uint32_t val = value | (value << 8) | (value << 16) | (value << 24);
for (size_t i = 0; i < len; i++) {
uint32_t v = ((volatile uint32_t *)p)[i];
acc |= v ^ val;
}
assert(acc == 0);
if (acc != 0) {
abort();
}
memset(p, 0xff, orig_len);
}
void free_blob(struct chunked_blob *blob, size_t _unused)
{
int i;
int orders[CHUNKS_COUNT];
value_size_to_block_sizes(blob->size, orders);
unsigned char filler = (uintptr_t)blob % 251;
for (i = CHUNKS_COUNT-1; i > 0; i--) {
if (orders[i] < 0)
continue;
memchk(blob->other_chunks[i-1], filler, 1U << orders[i]);
xfree(blob->other_chunks[i-1]);
}
memchk(blob + 1, filler, (1U << orders[0]) - sizeof(*blob));
xfree(blob);
}
size_t get_total_allocated_size(void)
{
return total_allocated;
}
|
C
|
//
// GameInitializations.h
// BlockBreaker
//
// Created by Shuyang Sun on 4/29/13.
// Copyright (c) 2013 Shuyang Sun. All rights reserved.
//
#ifndef BlockBreaker_GameInitializations_h
#define BlockBreaker_GameInitializations_h
/**
* Defining some game data, can be changed later.
* The function "int areValidSymbols(void)" will determin whether there are overlaped symbols.
*/
#define MAX(a,b) ((a) > (b) ? (a):(b)) // Macro for MAX
#define LINE_NUMBER_OF_BLOCKS (4) // Line number of bricks.
#define GAME_WINDOW_WIDTH (27) // Width of whole game window.
#define SPACE_BETWEEN_LAST_LINE_OF_BRICKS_AND_BOTTOM_EDGE (8) // Space between the last line of bricks and the bottom edge
#define BOARD_WIDTH (3) // Width of board.
#define SYMBOL_FOR_LEFT_AND_RIGHT_EDGE ('|') // Symbol to represent left and right edge of window.
#define SYMBOL_FOR_TOP_AND_BOTTOM_EDGE ('X') // Symbol to represent top and bottom edge of window.
#define SYMBOL_FOR_BOARD ('T') // Symbol for board. (will be multiplied by BOARD_WIDTH later)
#define SYMBOL_FOR_BALL ('O') // Symbol for ball.
#define SYMBOL_FOR_BLOCK ('=') // Symbol for block.
#define SYMBOL_FOR_SPACE (' ') // Symbol for space.
#define SYMBOL_FOR_TRACE_OF_BALL_SLASH ('/') // Symbol for ball tracing (left to right).
#define SYMBOL_FOR_TRACE_OF_BALL_BACK_SLASH ('\\') // Symbol for ball tracing (right to left).
/******|| Redefine symbols for trace if game window width is one. ||******/
#if (GAME_WINDOW_WIDTH == 1)
#undef SYMBOL_FOR_TRACE_OF_BALL_SLASH
#undef SYMBOL_FOR_TRACE_OF_BALL_BACK_SLASH
#define SYMBOL_FOR_TRACE_OF_BALL_SLASH ('|') // Symbol for ball tracing.
#define SYMBOL_FOR_TRACE_OF_BALL_BACK_SLASH ('|') // Symbol for ball tracing.
#endif
/******|| Redefine symbols for trace if game window width is one. ||******/
/******|| Constant Values ||******/
/* Calculate the row and colum needed for the whole array. */
// The extra 3 rows are for holding top, bottom edge and board.
const short int totalRow = LINE_NUMBER_OF_BLOCKS + SPACE_BETWEEN_LAST_LINE_OF_BRICKS_AND_BOTTOM_EDGE + 3;
// The extra 3 colums are for holding left, right edges and the new line character '\n'.
const short int totalColum = GAME_WINDOW_WIDTH + 3;
/******|| Constant Values ||******/
/******|| Enums ||******/
/**
* Typedefed enum to mark the current direction of ball.
* If the ball hit the Left edge, direction += 1.
* If the ball hit the Right edge, direction -= 1.
* If the ball hit the Top edge, direction += 2.
* If the ball hit the Board, direction -= 2.
*/
typedef enum{
None = 0,
Up_Left = 1,
Up_Right = 2,
Down_Left = 3,
Down_Right = 4,
} Direction;
// // Typedefed enum to indicate the status of game.
typedef enum{
Game_Over = 0,
Game_Playing = 1,
} GameStatus;
/******|| Enums ||******/
/******|| Structures ||******/
// Structure indicating a point, contain two parameters: x, y.
typedef struct {
int x;
int y;
} Point;
/******|| Structures ||******/
/******|| Function to determine wether the game will be able to play. (There may be symbol conflicts.) ||******/
short int areValidSymbols(void)
{
// If there are overlaped symbols, the function will not be able to run.
int result;
result = // All the conditions for areValidSymbols:
(SYMBOL_FOR_BOARD != SYMBOL_FOR_BLOCK)&& // Board != Block
(SYMBOL_FOR_BOARD != SYMBOL_FOR_BALL)&& // Board != Ball
(SYMBOL_FOR_BLOCK != SYMBOL_FOR_BALL)&& // Block != Ball
// SYMBOL_FOR_LEFT_AND_RIGHT_EDGE doesn't equal to the other three:
(SYMBOL_FOR_LEFT_AND_RIGHT_EDGE != SYMBOL_FOR_BALL)&&
(SYMBOL_FOR_LEFT_AND_RIGHT_EDGE != SYMBOL_FOR_BLOCK)&&
(SYMBOL_FOR_LEFT_AND_RIGHT_EDGE != SYMBOL_FOR_BOARD)&&
// SYMBOL_FOR_TOP_AND_BOTTOM_EDGE doesn't equal to the other three:
(SYMBOL_FOR_TOP_AND_BOTTOM_EDGE != SYMBOL_FOR_BALL)&&
(SYMBOL_FOR_TOP_AND_BOTTOM_EDGE != SYMBOL_FOR_BLOCK)&&
(SYMBOL_FOR_TOP_AND_BOTTOM_EDGE != SYMBOL_FOR_BOARD)&&
// SYMBOL_FOR_SPACE doesn't equal to all of them.
(SYMBOL_FOR_SPACE != SYMBOL_FOR_BALL)&&
(SYMBOL_FOR_SPACE != SYMBOL_FOR_BLOCK)&&
(SYMBOL_FOR_SPACE != SYMBOL_FOR_BOARD)&&
(SYMBOL_FOR_SPACE != SYMBOL_FOR_LEFT_AND_RIGHT_EDGE)&&
(SYMBOL_FOR_SPACE != SYMBOL_FOR_TOP_AND_BOTTOM_EDGE)&&
// SYMBOL_FOR_TRACE_OF_BALL_SLASH doesn't equal to all of them.
(SYMBOL_FOR_TRACE_OF_BALL_SLASH != SYMBOL_FOR_BALL)&&
(SYMBOL_FOR_TRACE_OF_BALL_SLASH != SYMBOL_FOR_BLOCK)&&
(SYMBOL_FOR_TRACE_OF_BALL_SLASH != SYMBOL_FOR_BOARD)&&
(SYMBOL_FOR_TRACE_OF_BALL_SLASH != SYMBOL_FOR_LEFT_AND_RIGHT_EDGE)&&
(SYMBOL_FOR_TRACE_OF_BALL_SLASH != SYMBOL_FOR_TOP_AND_BOTTOM_EDGE)&&
// #define SYMBOL_FOR_TRACE_OF_BALL_BACK_SLASH doesn't equal to all of them.
(SYMBOL_FOR_TRACE_OF_BALL_BACK_SLASH != SYMBOL_FOR_BALL)&&
(SYMBOL_FOR_TRACE_OF_BALL_BACK_SLASH != SYMBOL_FOR_BLOCK)&&
(SYMBOL_FOR_TRACE_OF_BALL_BACK_SLASH != SYMBOL_FOR_BOARD)&&
(SYMBOL_FOR_TRACE_OF_BALL_BACK_SLASH != SYMBOL_FOR_LEFT_AND_RIGHT_EDGE)&&
(SYMBOL_FOR_TRACE_OF_BALL_BACK_SLASH != SYMBOL_FOR_TOP_AND_BOTTOM_EDGE)&&
// Game window width must more or equal than one.
(GAME_WINDOW_WIDTH >= 1)&&
// Board width must be more than 0, and less or equal than game window width.
(BOARD_WIDTH >= 1)&&
(BOARD_WIDTH <= GAME_WINDOW_WIDTH);
return result;
}
// Function make a point.
Point PointMake(int x, int y)
{
Point res = {x, y};
return res;
}
// Function to print array.
void printArr(char arr[totalRow][totalColum]){
// Static variable to determin how many time this function is called.
static int timeCalled = 0;
// If this is not the first time function is called, delete characters printed out last time.
if (timeCalled != 0){
int numberOfEscapeCharacterB = (totalColum+1)*totalRow+2;
for (int i = 0; i < numberOfEscapeCharacterB; ++i)
putchar('\b');
} else {
++timeCalled;
}
// Print out the array.
for (short int row = 0; row < totalRow - 1; ++row)
for (short int colum = 0; colum < totalColum; ++colum)
putchar(arr[row][colum]);
}
#endif
|
C
|
//
// Created by nicol on 29/09/2021.
//
#include "exercice.h"
#include <stdio.h>
#include "fonctions.h"
void exercice1()
{
int a = saisissezEntier();
int b = saisissezEntier();
printf(getMax(a, b));
return;
}
void exercice3()
{
//int longueur = saisirLongueur();
//int largeur = saisirLargeur();
//printf(calculPerimetre(longueur, largeur), calculAire(longueur, largeur));
//return;
// consigne mal lues, je me suis embeté pour rien..
int longueur = saisissezEntier();
int largeur = saisissezEntier();
printf(calculPerimetre(longueur, largeur), calculAire(longueur, largeur));
return;
}
void exercice4()
{
int i = saisissezEntier();
int j= saisissezEntier();
printf(multiple(i, j ));
return;
}
void exercice5()
{
float note1= saisissezEntier();
float note2= saisissezEntier();
float note3= saisissezEntier();
return moyenne(note1, note2, note3);
}
|
C
|
/*******************************************************************************
*
* window_ncurses.c
*
* author: AC Pretorius
* date : 01/04/2021
*
*******************************************************************************/
#include <stdio.h>
#include <string.h>
#include <malloc.h>
#include <ncurses.h>
#include "window_ncurses.h"
struct Window {
uint64_t id;
};
/*******************************************************************************
*
* function
*
*******************************************************************************/
bool window_create(window_t** window)
{
if (*window) {
fprintf(stderr, "invalid handle!\n");
return false;
}
*window = malloc(sizeof **window);
if (!*window) {
fprintf(stderr, "could not allocate memory for window!\n");
return false;
}
if (!memset(*window, 0, sizeof **window)) {
fprintf(stderr, "could not initialise memory for window!\n");
return false;
}
initscr();
cbreak();
noecho();
curs_set(FALSE);
keypad(stdscr, TRUE);
timeout(25);
return true;
}
/*******************************************************************************
*
* function
*
*******************************************************************************/
bool window_delete(window_t** window)
{
if (!*window) {
fprintf(stderr, "invalid handle!\n");
return false;
}
endwin();
free(*window);
*window = 0;
return true;
}
/*******************************************************************************
*
* function
*
*******************************************************************************/
bool ncurses_render(bool(*engine_render)(void*), void* context)
{
clear();
engine_render(context);
refresh();
return true;
}
/*******************************************************************************
*
* function
*
*******************************************************************************/
bool ncurses_input(bool(*engine_input)(void*, int16_t), void* context)
{
return engine_input(context, getch());
}
/*******************************************************************************
*
* function
*
*******************************************************************************/
bool ncurses_draw(int16_t ch, int pox_x, int pos_y)
{
move(pos_y, pox_x);
addch(ch);
return true;
}
/*******************************************************************************
*
* function
*
*******************************************************************************/
bool ncurses_string(int pox_x, int pos_y, char* string, int num_chars)
{
mvaddnstr(pos_y, pox_x, string, num_chars);
return true;
}
/*******************************************************************************
*
* END window_ncurses.c
*
*******************************************************************************/
|
C
|
/*
* ferror.c
*
* Copyright 1987, 1992 by Sierra Systems. All rights reserved.
*/
#include <stdio.h>
/*---------------------------------- ferror() ------------------------------*/
/*
* ferror tests the error indicator for the stream pointed to by fp.
* ferror() returns non-zero if and only if the error indicator is set for
* the stream pointed to by fp.
*/
int (ferror)(FILE *fp)
{
return(ferror(fp));
}
|
C
|
/* gpio.c
*/
#include <stdint.h>
#include "pico/stdlib.h"
#include "tool.h"
#include "driver_config.h"
#include "gpio.h"
void gpio_Init(void){
gpios_init();
}
void gpios_init(void){
// Enable pins
gpio_init(PICO_DEFAULT_I2C_SCL_PIN);
gpio_init(PICO_DEFAULT_I2C_SDA_PIN);
gpio_init(PIN_VEN);
gpio_init(PIN_IRQ);
/*** I2C ***/
gpio_set_input_enabled(PICO_DEFAULT_I2C_SCL_PIN, true); // Enable input
gpio_set_input_enabled(PICO_DEFAULT_I2C_SCL_PIN, true); // Enable input
gpio_set_function(PICO_DEFAULT_I2C_SDA_PIN, GPIO_FUNC_I2C); // Set pin 6 (GPIO4) to I2C SDA
gpio_set_function(PICO_DEFAULT_I2C_SCL_PIN, GPIO_FUNC_I2C); // Set pin 7 (GPIO5) to I2C SCL
gpio_pull_up(PICO_DEFAULT_I2C_SDA_PIN); // Enable pull-up on SDA pin
gpio_pull_up(PICO_DEFAULT_I2C_SCL_PIN); // Enable pull-up on SCL pin
/*** NFC ***/
// NFC VEN PIN
gpio_set_dir(PIN_VEN, true); // Set to output
// NFC IRQ PIN
gpio_set_input_enabled(PIN_IRQ, true); // Enable input
gpio_set_dir(PIN_IRQ, false); // Set to input
#ifdef DEBUG
printf("GPIO: VEN pin direction = %d\n", gpio_get_dir(PIN_VEN));
printf("GPIO: IRQ status = %d", gpio_get(PIN_IRQ));
#endif // DEBUG
}
void gpio_SetValue( uint32_t bitPosi, uint32_t bitVal )
{
//Chip_GPIO_SetPinState(LPC_GPIO, portNum, bitPosi, bitVal);
gpio_put(bitPosi, bitVal);
}
uint8_t gpio_GetValue( uint32_t bitPosi)
{
//return Chip_GPIO_GetPinState(LPC_GPIO, portNum, bitPosi);
return gpio_get(bitPosi);
}
void gpio_SetDir( uint32_t bitPosi, uint32_t dir )
{
//Chip_GPIO_SetDir(LPC_GPIO, portNum, 1<<bitPosi, dir);
gpio_set_dir(bitPosi, dir);
}
|
C
|
#include <stdio.h>
int xgets(char a[100]);
int xputs(char a[100]);
int main()
{
char s[100];
printf("\nEnter a String:\t ");
xgets(s);
xputs(s);
printf("\n");
}
int xgets(char a[100])
{
scanf("%[^\n]s", a);
}
int xputs(char a[100])
{
printf("%s", a);
}
|
C
|
#include "../LinkedList/linkedList.h"
#include "mediaDeTodosOsNumeros.h"
#include <stdio.h>
int main()
{
LinkedList *listaUlong = createLinkedList(sizeof(u_long));
for (size_t i = 0; i < 10; i++)
appendLinkedList(listaUlong, &i);
printf("%f\n", mediaDeTodosOsNumeros(listaUlong));
destroyLinkedList(listaUlong);
return 0;
}
|
C
|
#ifndef B3_AABB_H
#define B3_AABB_H
#include "Bullet3Common/shared/b3Float4.h"
#include "Bullet3Common/shared/b3Mat3x3.h"
typedef struct b3Aabb b3Aabb_t;
struct b3Aabb
{
union
{
float m_min[4];
b3Float4 m_minVec;
int m_minIndices[4];
};
union
{
float m_max[4];
b3Float4 m_maxVec;
int m_signedMaxIndices[4];
};
};
inline void b3TransformAabb2(b3Float4ConstArg localAabbMin,b3Float4ConstArg localAabbMax, float margin,
b3Float4ConstArg pos,
b3QuatConstArg orn,
b3Float4* aabbMinOut,b3Float4* aabbMaxOut)
{
b3Float4 localHalfExtents = 0.5f*(localAabbMax-localAabbMin);
localHalfExtents+=b3MakeFloat4(margin,margin,margin,0.f);
b3Float4 localCenter = 0.5f*(localAabbMax+localAabbMin);
b3Mat3x3 m;
m = b3QuatGetRotationMatrix(orn);
b3Mat3x3 abs_b = b3AbsoluteMat3x3(m);
b3Float4 center = b3TransformPoint(localCenter,pos,orn);
b3Float4 extent = b3MakeFloat4(b3Dot3F4(localHalfExtents,b3GetRow(abs_b,0)),
b3Dot3F4(localHalfExtents,b3GetRow(abs_b,1)),
b3Dot3F4(localHalfExtents,b3GetRow(abs_b,2)),
0.f);
*aabbMinOut = center-extent;
*aabbMaxOut = center+extent;
}
/// conservative test for overlap between two aabbs
inline bool b3TestAabbAgainstAabb(b3Float4ConstArg aabbMin1,b3Float4ConstArg aabbMax1,
b3Float4ConstArg aabbMin2, b3Float4ConstArg aabbMax2)
{
bool overlap = true;
overlap = (aabbMin1.x > aabbMax2.x || aabbMax1.x < aabbMin2.x) ? false : overlap;
overlap = (aabbMin1.z > aabbMax2.z || aabbMax1.z < aabbMin2.z) ? false : overlap;
overlap = (aabbMin1.y > aabbMax2.y || aabbMax1.y < aabbMin2.y) ? false : overlap;
return overlap;
}
#endif //B3_AABB_H
|
C
|
#ifndef __VECTOR_2F_H__
#define __VECTOR_2F_H__
#include <math.h>
struct Vec2f
{
float x;
float y;
Vec2f() : x(0.0f), y(0.0f)
{;}
Vec2f(float x, float y)
{
this->x = x;
this->y = y;
}
Vec2f(const Vec2f& vec)
{
this->x = vec.x;
this->y = vec.y;
}
Vec2f(float size)
{
this->x = size;
this->y = size;
}
Vec2f& operator+= (const Vec2f& vec)
{
this->x += vec.x;
this->y += vec.y;
return *this;
}
Vec2f& operator-= (const Vec2f& vec)
{
this->x -= vec.x;
this->y -= vec.y;
return *this;
}
// @todo: not optimaized!
void normalize()
{
float length = this->length();
x /= length;
y /= length;
}
float length()
{
return sqrtf(x * x + y * y);
}
void length(float length)
{
normalize();
x *= length;
y *= length;
}
};
Vec2f operator+ (const Vec2f& vec_1, const Vec2f& vec_2);
Vec2f operator- (const Vec2f& vec_1, const Vec2f& vec_2);
Vec2f operator* (const Vec2f& vec, float coeff);
Vec2f operator* (float coeff, const Vec2f& vec);
float quad_distance(const Vec2f& point_1, const Vec2f& point_2);
float distance(const Vec2f& point_1, const Vec2f& point_2);
#endif //__VECTOR_2F_H__
|
C
|
int printf(const char *s, ...);
int main()
{
int foo;
foo = 3;
int bar;
bar = 7;
printf("foo - bar = %d, foo = %d, bar = %d\n", foo - bar, foo, bar);
return 0;
}
|
C
|
//
// Created by helisi on 2021/7/31.
//
#include <stdio.h>
/**
* this program calculate summary from 0 to 9
* @param argc parameter count
* @param argv parameters
* @return 0
* */
int main(int argc, char **argv) {
int sum = 0;
int i = 0;
for (; i < 10; ++i) {
sum = sum + i;
}
printf("%d\n", sum);
return 0;
}
|
C
|
#include "holberton.h"
/**
* _puts - returns the length of a string.
* @s : pointer to char
* Return: void
* On error, -1 is returned, and errno is set appropriately.
*/
void _puts(char *s)
{
int k = 0;
while (*(s + k) != '\0')
{
_putchar(*(s + k));
k++;
}
_putchar('\n');
}
|
C
|
#pragma once
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <math.h>
#include "LRU/K_hash.h"
/**
* A list.
*/
struct List {
int page; /**< a page of data */
struct node *value; /**< an adress of data. */
struct List *next; /**< a pointer to the next element of the list*/
};
/**
* A struct which tell us about existence of element in hash table
*/
struct Exist {
short int True; /**< a sign of existence*/
struct node *value; /**< an adress*/
}
/**
* Deletion of the list
* @param head a double pointer to the head of the list
*/
void free_list(struct List **head);
/**
* This function prints all element in the one list
* @param head a pointer to the head of the list
*/
void print_list(struct List *head);
/**
* This function adds a new element in the list
* @param page a page of data which we add to the list
* @param value an adress of data
*/
void set_list(struct List **head, int page, struct node *value);
/**
* Deleting the element in the list
* @param page a page of data which we delete
* @param head a double pointer to the head of the list
*/
void del_in_list(struct List **head, int page);
/**
* This function looks for an element in the list
* @param page a page of data which we look for
* @param head a pointer to the head of the list
*/
struct Exist exist_in_list(struct List *head, int page);
|
C
|
#include <stdio.h>
int main(void){
int i,j,k,n;
double a[100][100]={0},m;
printf("n=");
scanf("%d",&n);
for(i=0;i<n;i++){
for(j=0;j<n;j++){
printf("(%d)X%d=",i+1,j+1);
scanf("%lf",&a[i][j]);
}
}
for(i=0;i<n;i++)
a[i][n+i]=1;
for(i=0;i<n-1;i++){
for(j=i+1;j<n;j++){
m=a[j][i]/a[i][i];
for(k=i;k<n*2;k++)
a[j][k]-=m*a[i][k];
}
}
for(i=n-1;i>0;i--){
for(j=i-1;j>=0;j--){
m=a[j][i]/a[i][i];
for(k=i;k<n*2;k++)
a[j][k]-=m*a[i][k];
}
}
for(i=0;i<n;i++){
m=a[i][i];
for(j=0;j<n*2;j++)
a[i][j]/=m;
}
for(i=0;i<n;i++){
for(j=n;j<n*2;j++)
printf("%.2f\t",a[i][j]);
printf("\n");
}
//getch();
return 0;
}
|
C
|
#include<stdio.h>
#include<string.h>
int main()
{
char ch;
while(ch!=EOF)
{
ch=getchar();
if(ch=='W')
printf("Q");
else if(ch=='E')
printf("W");
else if(ch=='R')
printf("E");
else if(ch=='T')
printf("R");
else if(ch=='Y')
printf("T");
else if(ch=='U')
printf("Y");
else if(ch=='I')
printf("U");
else if(ch=='O')
printf("I");
else if(ch=='P')
printf("O");
else if(ch=='[')
printf("P");
else if(ch=='S')
printf("A");
else if(ch=='D')
printf("S");
else if(ch=='F')
printf("D");
else if(ch=='G')
printf("F");
else if(ch=='H')
printf("G");
else if(ch=='J')
printf("H");
else if(ch=='K')
printf("J");
else if(ch=='L')
printf("K");
else if(ch==';')
printf("L");
else if(ch=='X')
printf("Z");
else if(ch=='C')
printf("X");
else if(ch=='V')
printf("C");
else if(ch=='B')
printf("V");
else if(ch=='N')
printf("B");
else if(ch=='M')
printf("N");
else if(ch==',')
printf("M");
else if(ch=='\\')
printf("]");
else if(ch==']')
printf("[");
else if(ch=='/')
printf(".");
else if(ch=='.')
printf(",");
else if(ch==39)
printf(";");
else if(ch=='1')
printf("`");
else if(ch=='2')
printf("1");
else if(ch=='3')
printf("2");
else if(ch=='4')
printf("3");
else if(ch=='5')
printf("4");
else if(ch=='6')
printf("5");
else if(ch=='7')
printf("6");
else if(ch=='8')
printf("7");
else if(ch=='9')
printf("8");
else if(ch=='0')
printf("9");
else if(ch=='=')
printf("-");
else if(ch=='-')
printf("0");
else if(ch==' ')
printf(" ");
if(ch=='\n')
printf("\n");
}
return 0;
}
|
C
|
#include<stdio.h>
#include <stdlib.h>
typedef int ElemType; //еĴ洢
typedef struct QNode// н
{
ElemType data;
struct QNode *next;
} QNode;
typedef struct //
{
QNode *front; // ͷָ
QNode *rear; // βָ
} LinkQueue;
//նӣɹ1ʧܣ0
int InitQueue(LinkQueue *Q)
{
Q->front = Q->rear =(QNode *)malloc(sizeof(QNode));
if (Q->front==NULL)return 0; //洢ʧ
Q->front->next = NULL;
return 1;
}
// ԪeΪQµĶβԪ ,ɹ1ʧܣ0
int EnQueue (LinkQueue *Q, ElemType e)
{
QNode *p=(QNode *)malloc(sizeof(QNode));
if (p==NULL)return 0; //洢ʧ
p->data = e;
p->next = NULL;
Q->rear->next = p; //p뵽β
Q->rear = p; //βΪp
return 1;
}
//вգɾQĶͷԪأeֵNULL
ElemType DeQueue (LinkQueue *Q)
{
QNode *p;
ElemType e;
if(Q->front==Q->rear)return 0;//Ϊ
p=Q->front->next; //pָͷ
e=p->data;
Q->front->next=p->next; //frontnextָͷĺһ
if (Q->rear==p)Q->rear = Q->front; //ֻһ㣬ɾΪ
free (p);
return e;
}
//ջգeضͷԪأNULL
ElemType GetFront(LinkQueue Q)
{
if (Q.front == Q.rear) return NULL; //Ϊ
return Q.front->next->data;
}
//Ϊջ10
int QueueEmpty(LinkQueue Q)//ջǿ
{
if(Q.front == Q.rear)return 1; //Ϊ
else return 0;
}
int main()
{
LinkQueue q ;
ElemType e;
system("title 3 ");
InitQueue(&q); //ʼ
EnQueue(&q,3);EnQueue(&q,4);EnQueue(&q,5);EnQueue(&q,6); //ν3456
e=DeQueue(&q);printf("ӵԪΪ:%d\n",e); //ջӡͷԪ
EnQueue(&q,7);//7
e=DeQueue(&q);//
EnQueue(&q,8);//8
printf("Ԫγջ:");
while((e=DeQueue(&q))!=NULL)//ԪγӲӡ
{
printf("%3d",e);
}
printf("\n");;
return 0;
}
|
C
|
/**************************************/
/* */
/* Code from the book C Unleashed */
/* Macmillan, 2000 */
/* Chapter 6: Data Files */
/* Steve Summit 2000-03-17 */
/* */
/**************************************/
#define TRUE 1
#define FALSE 0
#include <stddef.h>
int csvburst(char *line, char *arr[], int narr)
{
char *p;
int na = 0;
char prevc = ','; /* force recognizing first field */
char *dp = NULL;
int inquote = FALSE;
for(p = line; *p != '\0'; prevc = *p, p++) {
if(prevc == ',' && !inquote) {
/*
* start new field
*/
if(dp != NULL)
*dp = '\0'; /*terminate prev */
if(na >= narr)
return na;
arr[na++] = p;
dp = p;
if(*p == '"') {
inquote = TRUE;
continue; /* skip quote */
}
}
if(inquote && *p == '"') {
/*
* doubled quote goes to one quote;
*/
/*
* otherwise quote ends quote mode
*/
if(*(p + 1) != '"')
inquote = FALSE;
p++; /* skip first quote */
}
if(*p != ',' || inquote)
*dp++ = *p;
}
if(dp != NULL)
*dp = '\0';
if(na < narr)
arr[na] = NULL;
return na;
}
|
C
|
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <sys/un.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
void print_error(const char* s) {
printf("%s, errno: %d, message: %s.\n", s, errno, sys_errlist[errno]);
}
void confirm_continue() {
printf("Press any key to continue:");
getchar();
}
int main()
{
int sockfd;
int len;
struct sockaddr_un address;
sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
address.sun_family = AF_UNIX;
strcpy(address.sun_path, "server_socket");
len = sizeof(address);
int ret = connect(sockfd, (struct sockaddr *)&address, len);
if(ret < 0) {
print_error("Connect to server failed");
exit(1);
}
char* buffer = malloc(100);
memset(buffer, 'a', 99);
buffer[99] = '\0';
ret = write(sockfd, buffer, 100);
if (ret >= 0) {
printf("%d bytes written to server.\n", ret);
}
else {
print_error("Write data failed");
}
close(sockfd);
}
|
C
|
<!DOCTYPE html>
<title>Canvas test: 2d.composite.uncovered.pattern.destination-atop</title>
<script src="../tests.js"></script>
<link rel="stylesheet" href="../tests.css">
<body>
<p id="passtext">Pass</p>
<p id="failtext">Fail</p>
<p class="output">These images should be identical:</p>
<canvas id="c" class="output" width="100" height="50"><p class="fallback">FAIL (fallback content)</p></canvas>
<p class="output expectedtext">Expected output:<p><img src="2d.composite.uncovered.pattern.destination-atop.png" class="output expected" id="expected" alt="">
<ul id="d"></ul>
<script>
_addTest(function(canvas, ctx) {
ctx.fillStyle = 'rgba(0, 255, 255, 0.5)';
ctx.fillRect(0, 0, 100, 50);
ctx.globalCompositeOperation = 'destination-atop';
ctx.fillStyle = ctx.createPattern(document.getElementById('yellow.png'), 'no-repeat');
ctx.fillRect(0, 50, 100, 50);
_assertPixelApprox(canvas, 50,25, 0,0,0,0, "50,25", "0,0,0,0", 5);
});
</script>
<img src="../images/yellow.png" id="yellow.png" class="resource">
|
C
|
#define FIXED_DIM 10
#include <stdio.h>
#include <stdlib.h>
#include "item.h"
#include "stack.h"
struct stack {
Item arr[FIXED_DIM];
int riemp;
};
Stack newStack() {
Stack stack = malloc(sizeof(struct stack));
stack->riemp = 0;
return stack;
}
int isEmptyStack(Stack stack) { return !stack->riemp; }
int push(Stack stack, Item item) {
if(stack->riemp == FIXED_DIM) {
printf("Reached maximum dimesion of the stack!\n");
return 0;
} else
stack->arr[stack->riemp++] = item;
return 1;
}
int pop(Stack stack) { free(stack->arr[stack->riemp--]); }
Item top(Stack stack) {
if(isEmptyStack(stack)) {
printf("Empty stack!");
} else
return stack->arr[stack->riemp];
}
void printStack(Stack stack) {
if(isEmptyStack(stack)) {
printf("Empty stack!");
} else {
for(int i = stack->riemp - 1; i >= 0; i--) out_item(stack->arr[i]);
printf("\n");
}
}
|
C
|
#include <systemd/sd-daemon.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
int create_xml(const char* device, const char* filename);
int attach_device(const char* device, const char* vm);
int detach_device(const char* device, const char* vm);
//create XML for "virsh attach-device"
//device must be in this format "0000:0000"
int
create_xml(const char* device, const char* filename)
{
char xml[108] = "<hostdev mode='subsystem' type='usb'><source><vendor id='0x0000'/><product id='0x0000'/></source></hostdev>";
//put device into XML
{
int pos1 = 59, pos2 = 81;
strncpy(&xml[pos1], device, 4); //vendor
strncpy(&xml[pos2], &device[5], 4); //product
}
//save XML
{
FILE* output;
output = fopen(filename, "w+");
if (output)
{
fprintf(output, "%s",xml);
fclose(output);
}
else
{
fprintf(stderr, SD_ERR "[VM-HID] Failed to open %s. ERROR %d: %s.\n", filename, errno, strerror(errno));
return 0;
}
}
return 1;
}
//check if file exists and can be read
int
get_xml(const char* device, const char* filename)
{
if (access(filename, R_OK) != -1)
return 1;
else
return create_xml(device, filename);
}
int
call_virsh(const char* action, const char* vm, const char* device)
{
char filename[20] = "/tmp/d0000:0000.xml";
//put device into filename
strncpy(&filename[6], device, 9);
if (get_xml(device,filename))
{
char call[256] = "virsh ";
strcat(call, action);
strcat(call, " ");
strcat(call, vm);
strcat(call, " ");
strcat(call, filename);
return (system(call)+1);
}
else
{
fprintf(stderr, SD_ERR "[VM-HID] Failed to %s %s in %s.\n", action, device, vm);
return 0;
}
}
int
turn_off_video()
{
return system("xset -display :0.0 dpms force off");
}
|
C
|
#include <uproc.h>
#include <stdint.h>
#include <float.h>
#include <limits.h>
#include <string.h>
#include <errno.h>
#include <stdio.h>
static int __uchar_read_proc(uproc_buf_t *buf, int *done, off_t fileoff, void *private_data) {
unsigned char *v = (unsigned char *)private_data;
int n = snprintf(buf->mem, buf->size, "%c", *v);
if (n > 0) {
if (n >= buf->size){
buf->mem[buf->size - 1] = '\n';
} else {
buf->mem[n] = '\n';
++n;
}
}
*done = 1;
return n;
}
static int __ushort_read_proc(uproc_buf_t *buf, int *done, off_t fileoff, void *private_data) {
unsigned short *v = (unsigned short *)private_data;
int n = snprintf(buf->mem, buf->size, "%u", *v);
if (n > 0) {
if (n >= buf->size){
buf->mem[buf->size - 1] = '\n';
} else {
buf->mem[n] = '\n';
++n;
}
}
*done = 1;
return n;
}
static int __uint_read_proc(uproc_buf_t *buf, int *done, off_t fileoff, void *private_data) {
unsigned int *v = (unsigned int *)private_data;
int n = snprintf(buf->mem, buf->size, "%u", *v);
if (n > 0) {
if (n >= buf->size){
buf->mem[buf->size - 1] = '\n';
} else {
buf->mem[n] = '\n';
++n;
}
}
*done = 1;
return n;
}
static int __ulong_read_proc(uproc_buf_t *buf, int *done, off_t fileoff, void *private_data) {
unsigned long *v = (unsigned long *)private_data;
int n = snprintf(buf->mem, buf->size, "%lu", *v);
if (n > 0) {
if (n >= buf->size){
buf->mem[buf->size - 1] = '\n';
} else {
buf->mem[n] = '\n';
++n;
}
}
*done = 1;
return n;
}
static int __ullong_read_proc(uproc_buf_t *buf, int *done, off_t fileoff, void *private_data) {
unsigned long long*v = (unsigned long long *)private_data;
int n = snprintf(buf->mem, buf->size, "%llu", *v);
if (n > 0) {
if (n >= buf->size){
buf->mem[buf->size - 1] = '\n';
} else {
buf->mem[n] = '\n';
++n;
}
}
*done = 1;
return n;
}
static int __uint16_read_proc(uproc_buf_t *buf, int *done, off_t fileoff, void *private_data) {
uint16_t *v = (uint16_t *)private_data;
int n = snprintf(buf->mem, buf->size, "%u", (unsigned int)*v);
if (n > 0) {
if (n >= buf->size){
buf->mem[buf->size - 1] = '\n';
} else {
buf->mem[n] = '\n';
++n;
}
}
*done = 1;
return n;
}
static int __uint32_read_proc(uproc_buf_t *buf, int *done, off_t fileoff, void *private_data) {
uint32_t *v = (uint32_t *)private_data;
int n = snprintf(buf->mem, buf->size, "%lu", (unsigned long)*v);
if (n > 0) {
if (n >= buf->size){
buf->mem[buf->size - 1] = '\n';
} else {
buf->mem[n] = '\n';
++n;
}
}
*done = 1;
return n;
}
static int __uint64_read_proc(uproc_buf_t *buf, int *done, off_t fileoff, void *private_data) {
uint64_t *v = (uint64_t *)private_data;
int n = snprintf(buf->mem, buf->size, "%llu", (unsigned long long)*v);
if (n > 0) {
if (n >= buf->size){
buf->mem[buf->size - 1] = '\n';
} else {
buf->mem[n] = '\n';
++n;
}
}
*done = 1;
return n;
}
static int __char_read_proc(uproc_buf_t *buf, int *done, off_t fileoff, void *private_data) {
return __uchar_read_proc(buf, done, fileoff, private_data);
}
static int __short_read_proc(uproc_buf_t *buf, int *done, off_t fileoff, void *private_data) {
short *v = (short *)private_data;
int n = snprintf(buf->mem, buf->size, "%d", *v);
if (n > 0) {
if (n >= buf->size){
buf->mem[buf->size - 1] = '\n';
} else {
buf->mem[n] = '\n';
++n;
}
}
*done = 1;
return n;
}
static int __int_read_proc(uproc_buf_t *buf, int *done, off_t fileoff, void *private_data) {
int *v = (int *)private_data;
int n = snprintf(buf->mem, buf->size, "%d", *v);
if (n > 0) {
if (n >= buf->size){
buf->mem[buf->size - 1] = '\n';
} else {
buf->mem[n] = '\n';
++n;
}
}
*done = 1;
return n;
}
static int __long_read_proc(uproc_buf_t *buf, int *done, off_t fileoff, void *private_data) {
long *v = (long *)private_data;
int n = snprintf(buf->mem, buf->size, "%ld", *v);
if (n > 0) {
if (n >= buf->size){
buf->mem[buf->size - 1] = '\n';
} else {
buf->mem[n] = '\n';
++n;
}
}
*done = 1;
return n;
}
static int __llong_read_proc(uproc_buf_t *buf, int *done, off_t fileoff, void *private_data) {
long long *v = (long long *)private_data;
int n = snprintf(buf->mem, buf->size, "%lld", *v);
if (n > 0) {
if (n >= buf->size){
buf->mem[buf->size - 1] = '\n';
} else {
buf->mem[n] = '\n';
++n;
}
}
*done = 1;
return n;
}
static int __float_read_proc(uproc_buf_t *buf, int *done, off_t fileoff, void *private_data) {
float *v = (float *)private_data;
int n = snprintf(buf->mem, buf->size, "%f", *v);
if (n > 0) {
if (n >= buf->size){
buf->mem[buf->size - 1] = '\n';
} else {
buf->mem[n] = '\n';
++n;
}
}
*done = 1;
return n;
}
static int __double_read_proc(uproc_buf_t *buf, int *done, off_t fileoff, void *private_data) {
double *v = (double *)private_data;
int n = snprintf(buf->mem, buf->size, "%f", *v);
if (n > 0) {
if (n >= buf->size){
buf->mem[buf->size - 1] = '\n';
} else {
buf->mem[n] = '\n';
++n;
}
}
*done = 1;
return n;
}
static int __ldouble_read_proc(uproc_buf_t *buf, int *done, off_t fileoff, void *private_data) {
long double *v = (long double *)private_data;
int n = snprintf(buf->mem, buf->size, "%Lf", *v);
if (n > 0) {
if (n >= buf->size){
buf->mem[buf->size - 1] = '\n';
} else {
buf->mem[n] = '\n';
++n;
}
}
*done = 1;
return n;
}
static int __int16_read_proc(uproc_buf_t *buf, int *done, off_t fileoff, void *private_data) {
int16_t *v = (int16_t *)private_data;
int n = snprintf(buf->mem, buf->size, "%d", (int)*v);
if (n > 0) {
if (n >= buf->size){
buf->mem[buf->size - 1] = '\n';
} else {
buf->mem[n] = '\n';
++n;
}
}
*done = 1;
return n;
}
static int __int32_read_proc(uproc_buf_t *buf, int *done, off_t fileoff, void *private_data) {
int32_t *v = (int32_t *)private_data;
int n = snprintf(buf->mem, buf->size, "%ld", (long)*v);
if (n > 0) {
if (n >= buf->size){
buf->mem[buf->size - 1] = '\n';
} else {
buf->mem[n] = '\n';
++n;
}
}
*done = 1;
return n;
}
static int __int64_read_proc(uproc_buf_t *buf, int *done, off_t fileoff, void *private_data) {
int64_t *v = (int64_t *)private_data;
int n = snprintf(buf->mem, buf->size, "%lld", (long long)*v);
if (n > 0) {
if (n >= buf->size){
buf->mem[buf->size - 1] = '\n';
} else {
buf->mem[n] = '\n';
++n;
}
}
*done = 1;
return n;
}
static int __cstring_read_proc(uproc_buf_t *buf, int *done, off_t fileoff, void *private_data) {
const char *v = (const char *)private_data;
size_t len;
size_t size = (buf->entry->size > buf->size ? buf->size : buf->entry->size);
fprintf(stderr, "__cstring_read_proc: %s, size: %lu\n", v, size);
*done = 1;
if (size <= 1) {
return 0;
}
len = strlen(v);
if (len < size) {
size = len;
}
memcpy(buf->mem, v, len);
buf->mem[size] = '\n';
return size + 1;
}
#define __WRITE_BUF_SIZE 5000
// buffer for making uproc_buf_t into a null-terminated string.
static char __write_buf[__WRITE_BUF_SIZE];
static inline void __copy_to_write_buf(uproc_buf_t *buf) {
uproc_dentry_t *entry = buf->entry;
size_t size = buf->size > entry->size ? entry->size : buf->size;
if (size > __WRITE_BUF_SIZE - 1) {
size = __WRITE_BUF_SIZE - 1;
}
memcpy(__write_buf, buf->mem, size);
__write_buf[size] = '\0';
}
static int __uchar_write_proc(uproc_buf_t *buf, int *done, off_t fileoff, void *private_data) {
int n = 0;
unsigned char *v = (unsigned char *)private_data;
*done = 1;
if (buf->size > 0) {
*v = buf->mem[0];
n = 1;
}
return n;
}
static int __ushort_write_proc(uproc_buf_t *buf, int *done, off_t fileoff, void *private_data) {
int n = buf->size;
unsigned short *v = (unsigned short *)private_data;
unsigned long int x;
char *endptr;
__copy_to_write_buf(buf);
*done = 1;
x = strtoul(__write_buf, &endptr, 10);
if (errno == ERANGE || x > USHRT_MAX) {
n = -ERANGE;
} else if (endptr == __write_buf) {
n = -EINVAL;
} else {
*v = x;
}
return n;
}
static int __uint_write_proc(uproc_buf_t *buf, int *done, off_t fileoff, void *private_data) {
int n = buf->size;
unsigned int *v = (unsigned int *)private_data;
unsigned long long int x;
char *endptr;
__copy_to_write_buf(buf);
*done = 1;
x = strtoull(__write_buf, &endptr, 10);
if (errno == ERANGE || x > UINT_MAX) {
n = -ERANGE;
} else if (endptr == __write_buf) {
n = -EINVAL;
} else {
*v = x;
}
return n;
}
static int __ulong_write_proc(uproc_buf_t *buf, int *done, off_t fileoff, void *private_data) {
int n = buf->size;
unsigned long *v = (unsigned long *)private_data;
unsigned long long int x;
char *endptr;
__copy_to_write_buf(buf);
*done = 1;
x = strtoull(__write_buf, &endptr, 10);
if (errno == ERANGE || x > ULONG_MAX) {
n = -ERANGE;
} else if (endptr == __write_buf) {
n = -EINVAL;
} else {
*v = x;
}
return n;
}
static int __ullong_write_proc(uproc_buf_t *buf, int *done, off_t fileoff, void *private_data) {
int n = buf->size;
unsigned long long *v = (unsigned long long *)private_data;
unsigned long long int x;
char *endptr;
__copy_to_write_buf(buf);
*done = 1;
x = strtoull(__write_buf, &endptr, 10);
if (errno == ERANGE) {
n = -ERANGE;
} else if (endptr == __write_buf) {
n = -EINVAL;
} else {
*v = x;
}
return n;
}
static int __uint16_write_proc(uproc_buf_t *buf, int *done, off_t fileoff, void *private_data) {
int n = buf->size;
uint16_t *v = (uint16_t *)private_data;
unsigned long int x;
char *endptr;
__copy_to_write_buf(buf);
*done = 1;
x = strtoul(__write_buf, &endptr, 10);
if (errno == ERANGE || x > UINT16_MAX) {
n = -ERANGE;
} else if (endptr == __write_buf) {
n = -EINVAL;
} else {
*v = x;
}
return n;
}
static int __uint32_write_proc(uproc_buf_t *buf, int *done, off_t fileoff, void *private_data) {
int n = buf->size;
uint32_t *v = (uint32_t *)private_data;
unsigned long long int x;
char *endptr;
__copy_to_write_buf(buf);
*done = 1;
x = strtoull(__write_buf, &endptr, 10);
if (errno == ERANGE || x > UINT32_MAX) {
n = -ERANGE;
} else if (endptr == __write_buf) {
n = -EINVAL;
} else {
*v = x;
}
return n;
}
static int __uint64_write_proc(uproc_buf_t *buf, int *done, off_t fileoff, void *private_data) {
int n = buf->size;
uint64_t *v = (uint64_t *)private_data;
unsigned long long int x;
char *endptr;
__copy_to_write_buf(buf);
*done = 1;
x = strtoull(__write_buf, &endptr, 10);
if (errno == ERANGE || x > UINT64_MAX) {
n = -ERANGE;
} else if (endptr == __write_buf) {
n = -EINVAL;
} else {
*v = x;
}
return n;
}
static int __char_write_proc(uproc_buf_t *buf, int *done, off_t fileoff, void *private_data) {
return __uchar_write_proc(buf, done, fileoff, private_data);
}
static int __short_write_proc(uproc_buf_t *buf, int *done, off_t fileoff, void *private_data) {
int n = buf->size;
short *v = (short *)private_data;
long int x;
char *endptr;
__copy_to_write_buf(buf);
*done = 1;
x = strtol(__write_buf, &endptr, 10);
if (errno == ERANGE || x > SHRT_MAX || x < SHRT_MIN) {
n = -ERANGE;
} else if (endptr == __write_buf) {
n = -EINVAL;
} else {
*v = x;
}
return n;
}
static int __int_write_proc(uproc_buf_t *buf, int *done, off_t fileoff, void *private_data) {
int n = buf->size;
int *v = (int *)private_data;
long long int x;
char *endptr;
__copy_to_write_buf(buf);
*done = 1;
x = strtoll(__write_buf, &endptr, 10);
if (errno == ERANGE || x > INT_MAX || x < INT_MIN) {
n = -ERANGE;
} else if (endptr == __write_buf) {
n = -EINVAL;
} else {
*v = x;
}
return n;
}
static int __long_write_proc(uproc_buf_t *buf, int *done, off_t fileoff, void *private_data) {
int n = buf->size;
long *v = (long *)private_data;
long long int x;
char *endptr;
__copy_to_write_buf(buf);
*done = 1;
x = strtoll(__write_buf, &endptr, 10);
if (errno == ERANGE || x > LONG_MAX || x < LONG_MIN) {
n = -ERANGE;
} else if (endptr == __write_buf) {
n = -EINVAL;
} else {
*v = x;
}
return n;
}
static int __llong_write_proc(uproc_buf_t *buf, int *done, off_t fileoff, void *private_data) {
int n = buf->size;
long long *v = (long long *)private_data;
long long int x;
char *endptr;
__copy_to_write_buf(buf);
*done = 1;
x = strtoll(__write_buf, &endptr, 10);
if (errno == ERANGE) {
n = -ERANGE;
} else if (endptr == __write_buf) {
n = -EINVAL;
} else {
*v = x;
}
return n;
}
static int __float_write_proc(uproc_buf_t *buf, int *done, off_t fileoff, void *private_data) {
int n = buf->size;
float *v = (float *)private_data;
float x;
char *endptr;
__copy_to_write_buf(buf);
*done = 1;
x = strtof(__write_buf, &endptr);
if (errno == ERANGE) {
n = -ERANGE;
} else if (endptr == __write_buf) {
n = -EINVAL;
} else {
*v = x;
}
return n;
}
static int __double_write_proc(uproc_buf_t *buf, int *done, off_t fileoff, void *private_data) {
int n = buf->size;
double *v = (double *)private_data;
double x;
char *endptr;
__copy_to_write_buf(buf);
*done = 1;
x = strtod(__write_buf, &endptr);
if (errno == ERANGE) {
n = -ERANGE;
} else if (endptr == __write_buf) {
n = -EINVAL;
} else {
*v = x;
}
return n;
}
static int __ldouble_write_proc(uproc_buf_t *buf, int *done, off_t fileoff, void *private_data) {
int n = buf->size;
long double *v = (long double *)private_data;
long double x;
char *endptr;
__copy_to_write_buf(buf);
*done = 1;
x = strtold(__write_buf, &endptr);
if (errno == ERANGE) {
n = -ERANGE;
} else if (endptr == __write_buf) {
n = -EINVAL;
} else {
*v = x;
}
return n;
}
static int __int16_write_proc(uproc_buf_t *buf, int *done, off_t fileoff, void *private_data) {
int n = buf->size;
int16_t *v = (int16_t *)private_data;
long int x;
char *endptr;
__copy_to_write_buf(buf);
*done = 1;
x = strtol(__write_buf, &endptr, 10);
if (errno == ERANGE || x > INT16_MAX || x < INT16_MIN) {
n = -ERANGE;
} else if (endptr == __write_buf) {
n = -EINVAL;
} else {
*v = x;
}
return n;
}
static int __int32_write_proc(uproc_buf_t *buf, int *done, off_t fileoff, void *private_data) {
int n = buf->size;
int32_t *v = (int32_t *)private_data;
long long int x;
char *endptr;
__copy_to_write_buf(buf);
*done = 1;
x = strtoll(__write_buf, &endptr, 10);
if (errno == ERANGE || x > INT32_MAX || x < INT32_MIN) {
n = -ERANGE;
} else if (endptr == __write_buf) {
n = -EINVAL;
} else {
*v = x;
}
return n;
}
static int __int64_write_proc(uproc_buf_t *buf, int *done, off_t fileoff, void *private_data) {
int n = buf->size;
int64_t *v = (int64_t *)private_data;
long long int x;
char *endptr;
__copy_to_write_buf(buf);
*done = 1;
x = strtoll(__write_buf, &endptr, 10);
if (errno == ERANGE) {
n = -ERANGE;
} else if (endptr == __write_buf) {
n = -EINVAL;
} else {
*v = x;
}
return n;
}
static int __string_write_proc(uproc_buf_t *buf, int *done, off_t fileoff, void *private_data) {
char *v = (char *)private_data;
size_t size = (buf->entry->size - 1 > buf->size ? buf->size : buf->entry->size - 1);
*done = 1;
memcpy(v, buf->mem , size);
v[size] = '\0';
return size;
}
static uproc_dentry_t* __uproc_utility_create_internal(uproc_ctx_t *ctx,
const char *name, // name of the entry
mode_t mode, // permissions
size_t size,
uproc_dentry_t* parent,
int readonly,
uproc_read_proc_t read_proc,
uproc_write_proc_t write_proc,
void *private_data) {
if (size == 0)
size = 4096;
if (readonly)
write_proc = NULL;
return uproc_create_entry(ctx, name, mode, size, parent, read_proc, write_proc, private_data);
}
/*
* Wrappers for primitive types.
* @readonly: if set, only the default read hanlder will be installed.
*/
uproc_dentry_t* uproc_create_entry_uchar(uproc_ctx_t *ctx,
const char *name, // name of the entry
mode_t mode, // permissions
uproc_dentry_t* parent,
int readonly,
unsigned char *v
) {
return __uproc_utility_create_internal(ctx, name, mode, 0, parent, readonly,
__uchar_read_proc, __uchar_write_proc, (void*)v);
}
uproc_dentry_t* uproc_create_entry_ushort(uproc_ctx_t *ctx,
const char *name, // name of the entry
mode_t mode, // permissions
uproc_dentry_t* parent,
int readonly,
unsigned short *v
) {
return __uproc_utility_create_internal(ctx, name, mode, 0, parent, readonly,
__ushort_read_proc, __ushort_write_proc, (void*)v);
}
uproc_dentry_t* uproc_create_entry_uint(uproc_ctx_t *ctx,
const char *name, // name of the entry
mode_t mode, // permissions
uproc_dentry_t* parent,
int readonly,
unsigned int *v
) {
return __uproc_utility_create_internal(ctx, name, mode, 0, parent, readonly,
__uint_read_proc, __uint_write_proc, (void*)v);
}
uproc_dentry_t* uproc_create_entry_ulong(uproc_ctx_t *ctx,
const char *name, // name of the entry
mode_t mode, // permissions
uproc_dentry_t* parent,
int readonly,
unsigned long *v
) {
return __uproc_utility_create_internal(ctx, name, mode, 0, parent, readonly,
__ulong_read_proc, __ulong_write_proc, (void*)v);
}
uproc_dentry_t* uproc_create_entry_ullong(uproc_ctx_t *ctx,
const char *name, // name of the entry
mode_t mode, // permissions
uproc_dentry_t* parent,
int readonly,
unsigned long long *v
) {
return __uproc_utility_create_internal(ctx, name, mode, 0, parent, readonly,
__ullong_read_proc, __ullong_write_proc, (void*)v);
}
uproc_dentry_t* uproc_create_entry_uint16(uproc_ctx_t *ctx,
const char *name, // name of the entry
mode_t mode, // permissions
uproc_dentry_t* parent,
int readonly,
uint16_t *v
) {
return __uproc_utility_create_internal(ctx, name, mode, 0, parent, readonly,
__uint16_read_proc, __uint16_write_proc, (void*)v);
}
uproc_dentry_t* uproc_create_entry_uint32(uproc_ctx_t *ctx,
const char *name, // name of the entry
mode_t mode, // permissions
uproc_dentry_t* parent,
int readonly,
uint32_t *v
) {
return __uproc_utility_create_internal(ctx, name, mode, 0, parent, readonly,
__uint32_read_proc, __uint32_write_proc, (void*)v);
}
uproc_dentry_t* uproc_create_entry_uint64(uproc_ctx_t *ctx,
const char *name, // name of the entry
mode_t mode, // permissions
uproc_dentry_t* parent,
int readonly,
uint64_t *v
) {
return __uproc_utility_create_internal(ctx, name, mode, 0, parent, readonly,
__uint64_read_proc, __uint64_write_proc, (void*)v);
}
uproc_dentry_t* uproc_create_entry_char(uproc_ctx_t *ctx,
const char *name, // name of the entry
mode_t mode, // permissions
uproc_dentry_t* parent,
int readonly,
char *v
) {
return __uproc_utility_create_internal(ctx, name, mode, 0, parent, readonly,
__char_read_proc, __char_write_proc, (void*)v);
}
uproc_dentry_t* uproc_create_entry_short(uproc_ctx_t *ctx,
const char *name, // name of the entry
mode_t mode, // permissions
uproc_dentry_t* parent,
int readonly,
short *v
) {
return __uproc_utility_create_internal(ctx, name, mode, 0, parent, readonly,
__short_read_proc, __short_write_proc, (void*)v);
}
uproc_dentry_t* uproc_create_entry_int(uproc_ctx_t *ctx,
const char *name, // name of the entry
mode_t mode, // permissions
uproc_dentry_t* parent,
int readonly,
int *v
) {
return __uproc_utility_create_internal(ctx, name, mode, 0, parent, readonly,
__int_read_proc, __int_write_proc, (void*)v);
}
uproc_dentry_t* uproc_create_entry_long(uproc_ctx_t *ctx,
const char *name, // name of the entry
mode_t mode, // permissions
uproc_dentry_t* parent,
int readonly,
long *v
) {
return __uproc_utility_create_internal(ctx, name, mode, 0, parent, readonly,
__long_read_proc, __long_write_proc, (void*)v);
}
uproc_dentry_t* uproc_create_entry_llong(uproc_ctx_t *ctx,
const char *name, // name of the entry
mode_t mode, // permissions
uproc_dentry_t* parent,
int readonly,
long long *v
) {
return __uproc_utility_create_internal(ctx, name, mode, 0, parent, readonly,
__llong_read_proc, __llong_write_proc, (void*)v);
}
uproc_dentry_t* uproc_create_entry_float(uproc_ctx_t *ctx,
const char *name, // name of the entry
mode_t mode, // permissions
uproc_dentry_t* parent,
int readonly,
float *v
) {
return __uproc_utility_create_internal(ctx, name, mode, 0, parent, readonly,
__float_read_proc, __float_write_proc, (void*)v);
}
uproc_dentry_t* uproc_create_entry_double(uproc_ctx_t *ctx,
const char *name, // name of the entry
mode_t mode, // permissions
uproc_dentry_t* parent,
int readonly,
double *v
) {
return __uproc_utility_create_internal(ctx, name, mode, 0, parent, readonly,
__double_read_proc, __double_write_proc, (void*)v);
}
uproc_dentry_t* uproc_create_entry_ldouble(uproc_ctx_t *ctx,
const char *name, // name of the entry
mode_t mode, // permissions
uproc_dentry_t* parent,
int readonly,
long double *v
) {
return __uproc_utility_create_internal(ctx, name, mode, 0, parent, readonly,
__ldouble_read_proc, __ldouble_write_proc, (void*)v);
}
uproc_dentry_t* uproc_create_entry_int16(uproc_ctx_t *ctx,
const char *name, // name of the entry
mode_t mode, // permissions
uproc_dentry_t* parent,
int readonly,
int16_t *v
) {
return __uproc_utility_create_internal(ctx, name, mode, 0, parent, readonly,
__int16_read_proc, __int16_write_proc, (void*)v);
}
uproc_dentry_t* uproc_create_entry_int32(uproc_ctx_t *ctx,
const char *name, // name of the entry
mode_t mode, // permissions
uproc_dentry_t* parent,
int readonly,
int32_t *v
) {
return __uproc_utility_create_internal(ctx, name, mode, 0, parent, readonly,
__int32_read_proc, __int32_write_proc, (void*)v);
}
uproc_dentry_t* uproc_create_entry_int64(uproc_ctx_t *ctx,
const char *name, // name of the entry
mode_t mode, // permissions
uproc_dentry_t* parent,
int readonly,
int64_t *v
) {
return __uproc_utility_create_internal(ctx, name, mode, 0, parent, readonly,
__int64_read_proc, __int64_write_proc, (void*)v);
}
// wrapper for const char *, it's readonly by definition.
uproc_dentry_t* uproc_create_entry_cstring(uproc_ctx_t *ctx,
const char *name, // name of the entry
mode_t mode, // permissions
uproc_dentry_t* parent,
size_t size, // maximum size of content the entry could hold, content wil be trauncated if exceeds this limit
const char *v
) {
return __uproc_utility_create_internal(ctx, name, mode, 0, parent, /* readonly */ 1,
__cstring_read_proc, /* write_proc */ NULL, (void*)v);
}
// wrapper for char *.
// Note: when writing to the entry, uproc honors the @size variable.
// Specifically,uproc overrides the content of the char arry
// pointed by @v and puts '\0' at the end of the string.
uproc_dentry_t* uproc_create_entry_string(uproc_ctx_t *ctx,
const char *name, // name of the entry
mode_t mode, // permissions
uproc_dentry_t* parent,
size_t size, // maximum size of content the entry could hold, content wil be trauncated if exceeds this limit
int readonly,
char *v
) {
return __uproc_utility_create_internal(ctx, name, mode, 0, parent, readonly,
__cstring_read_proc, __string_write_proc, (void*)v);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
srand(time(NULL)); /* With this we make the random number different each time we execute the program */
char PossibleColors[][16] = {
"blue",
"green",
"red",
"yellow",
"white",
"black"
};
int RandomColor = rand() % 6; /* We divide by 6 to get a number between 0 to 5 so it selects the color */
int NumberOfLives = 5;
int CorrectAnswers = 0;
int OldCorrectAnswer = 0;
int LengthOfColor = strlen(PossibleColors[RandomColor]);
int LetterGuessed[7] = { 0, 0, 0, 0, 0, 0, 0 }; /*These will be 1 when the participant selects right word */
int LoopIndex = 0;
int quit = 0;
char guess[16]; /* User imput */
char LetterEntered;
while (CorrectAnswers < LengthOfColor)
{
printf ("\nNew Turn. Use it wisely...\nHangman Word:");
for (LoopIndex = 0; LoopIndex < LengthOfColor; LoopIndex++)
{
if (LetterGuessed[LoopIndex] == 1)
{
printf ("%c", PossibleColors[RandomColor][LoopIndex]);
}
else
{
printf ("_ ");
}
}
printf ("\n");
printf ("Number of correct letters so far: %d\n", CorrectAnswers);
printf ("\nTry a letter:");
fgets (guess, 10, stdin); /*It reads a line from the stream and stores it into the string pointed to by guess*/
if (strncmp(guess, "quit", 4) == 0)
{
quit = 1; /* This will work as a flag when decide to quit the game */
break;
}
LetterEntered = guess[0];
OldCorrectAnswer = CorrectAnswers; /* This is used to keep the number of lives moving */
for (LoopIndex = 0; LoopIndex < LengthOfColor; LoopIndex++)
{
if (LetterGuessed[LoopIndex] == 1)
{
continue;
}
if (LetterEntered == PossibleColors[RandomColor][LoopIndex])
{
LetterGuessed[LoopIndex] = 1;
CorrectAnswers++;
}
}
if (OldCorrectAnswer == CorrectAnswers)
{
NumberOfLives--;
printf ("\nNop. Wrong answer. Keep trying!\n");
if (NumberOfLives == 0)
{
break;
}
}
else
{
printf ("\nYES! Right answer. Keep going!\n");
}
}
if (quit == 1)
{
printf ("\nYou decided this was too much for you\n");
}
else if (NumberOfLives == 0)
{
printf ("\nAnd by the way... GAME OVER. The right answer was: %s\n", PossibleColors[RandomColor]);
}
else
{
printf ("\nYES!! You just won! Congratulations!\n");
}
return (0);
}
|
C
|
/*
DESCRIPCIÓN: Programa que evalúa y valida una expresión infija
COMPILACIÓN:
Crear objeto gcc TADpila[D].c -c
Ejecucion dinamica gcc TADpila[D].c Parentesis.c -o Par
*/
//LIBRERIAS
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "TADpila[D].h" //Libreria que contiene TAD Pila Dinamica
//PROGRAMA PRINCIPAL
int main(void)
{
pila A;
elemento E, Ultimo;
char c, *ecuacion, UCaracter;
int i, n=0, x;
//Se reserva espacio en la memoria para la ecuación a resolver
ecuacion = (char*)malloc(1*sizeof(char));
//Inicialización de la pila "A"
initialize(&A);
printf("Ingrese una ecuacion: \n\n" );
do
{
c = getchar(); //Guardar la cadena que se ingresa
ecuacion[n] = c;
n++;
ecuacion = (char*)realloc(ecuacion,(n+1)*sizeof(char));
}while(c != '\n');
ecuacion[n-1] = '\0'; //Carácter que finaliza una cadena
n--; c = '0';
//VALIDACIÓN DE PARENTESIS CORRECTOS
for(i=0;i<n;i++)
{
E.x = ecuacion[i];
//Si encuentra un parentesis que abre en la expresión entonces lo empila
if(E.x == '(' || E.x == '{' || E.x == '[')
push(E,&A);
else
{
// putchar(UCaracter); printf(" COMPARA"); putchar(E.x); printf("\n");
if((UCaracter == '(' ) && (E.x == ')') || (UCaracter == '{' ) && (E.x == '}') || (UCaracter == '[' ) && (E.x == ']'))
{
if(empty(&A) == TRUE) //Y si la pila esta vacía
{
//Marca el tipo de error 1
printf("\n>>>>>>Error 1, un parentesis intenta cerrar y no ha sido abierto<<<<<\n");
exit(1); //Sale porque la evaluación ya no tendría caso
break;
}
else
E=pop(&A); //y en la pila hay algun elemento, desempila el elemento
}
else
{
printf("ERROR, Los parentesis no estan bien acomodados\n");
exit(1); break; // Ya no se sigue evaluando
}
}
if(empty(&A) != TRUE)
{
Ultimo = top(&A);
UCaracter = Ultimo.x;
// putchar(UCaracter); printf(" ULTIMO en la pila \n");
}
}
// Si la pila A no está vacía indica que la expresión es incorrecta
if(empty(&A) == FALSE)
{
printf("\n>>>>>Error 2, un parentesis esta abierto y no ha sido cerrado<<<<<\n");
exit(1); //Sale del programa
}
else //Si la pila esta vacía entonces la ecuación es correcta
printf("\n>>>>>Tu ecuacion es correcta<<<<<\n\n");
destroy(&A); //Destruimos la pila "A"
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
typedef struct AdjListNode{
int dest;
struct AdjListNode* next;
}AdjListNode;
typedef struct AdjList
{
struct AdjListNode* head;
}AdjList;
typedef struct Graph
{
int V;
struct AdjList* array;
int type;
}Graph;
Graph* createGraph(int V, int type)
{
Graph *graph = malloc(sizeof(Graph));
graph->V = V;
graph->type = type;
graph->array = malloc(V*sizeof(AdjList)); // 创建 array of AdjList
int i;
for(int i=0; i<V; i++){
graph->array[i].head = NULL;
}
return graph;
};
AdjListNode* newAdjListNode(int dest)
{
AdjListNode* node = malloc(sizeof(AdjListNode));
node->dest = dest;
node->next = NULL;
return node;
};
void addEdge(Graph *graph, int src, int dest){
if(graph->type == 1){ // directed graph
AdjListNode* newNode = newAdjListNode(dest);
newNode->next = graph->array[src].head;
graph->array[src].head = newNode;
}else{
AdjListNode* newNode = newAdjListNode(dest);
newNode->next = graph->array[src].head;
graph->array[src].head = newNode;
newNode = newAdjListNode(src);
newNode->next = graph->array[dest].head;
graph->array[dest].head = newNode;
}
};
void printGraph(Graph *graph){
for(int i=0; i<graph->V; i++){
printf("\n Adjacency list of vertex %d\n head ", i);
AdjListNode *head = graph->array[i].head;
while(head){
printf("-> %d", head->dest);
head = head->next;
}
printf("\n");
}
};
|
C
|
#include<stdio.h>
#define SIZE 2
void MM(int A[SIZE][SIZE],int B[SIZE][SIZE],int C[SIZE][SIZE],int n)
{
int P,Q,R,S,T,U,V;
// if(n<=2)
// {
P=(A[0][0]+A[1][1])*(B[0][0]+B[1][1]);
Q=(A[1][0]+A[1][1])*B[0][0];
R=A[0][0]*(B[0][1]-B[1][1]);
S=(A[1][1])*(B[1][0]-B[0][0]);
T=(A[0][0]+A[0][1])*B[1][1];
U=(A[1][0]-A[0][0])*(B[0][0]+B[0][1]);
V=(A[0][1]-A[1][1])*(A[1][0]+B[1][1]);
}
// else
// {
// MM(A,(*B)[0],(*C)[0],n/2) + MM(A,B,C,n/2);
// MM(A,B,C,n/2) + MM(A,B,C,n/2);
// MM(A,B,C,n/2) + MM(A,B,C,n/2);
// }
C[0][0]=(P+S-T+V);
C[0][1]=(R+T);
C[1][0]=(Q+S);
C[1][1]=(P+R-Q+U);
}
int main()
{
int i,j,k;
int a[SIZE][SIZE];
int b[SIZE][SIZE];
int c[SIZE][SIZE];
printf("Enter the 4 elements of first matrix: ");
for(i = 0;i < SIZE; i++)
for(j = 0;j < SIZE; j++)
scanf("%d", &a[i][j]);
printf("Enter the 4 elements of second matrix: ");
for(i = 0; i < SIZE; i++)
for(j = 0;j < SIZE; j++)
scanf("%d", &b[i][j]);
printf("\nThe first matrix is\n");
for(i = 0; i < SIZE; i++){
printf("\n");
for(j = 0; j < SIZE; j++)
printf("%d\t", a[i][j]);
}
printf("\nThe second matrix is\n");
for(i = 0;i < SIZE; i++){
printf("\n");
for(j = 0;j < SIZE; j++)
printf("%d\t", b[i][j]);
}
MM(a,b,c,SIZE);
printf("\n Multiplication \n");
for(i = 0;i < SIZE; i++){
printf("\n");
for(j = 0;j < SIZE; j++)
printf("%d\t", c[i][j]);
}
return 0;
}
|
C
|
//άԪڴеĴ洢λ
//ά1010,±0ʼ
#include "stdio.h"
main()
{
int loc_a00;//Ԫռڴһάַ
int num;//ÿԪռõĴ洢Ԫ
int loc_aij;
int i,j;
printf("Ԫռڴһάַ:");
scanf("%d",&loc_a00);
printf("ÿԪռõĴ洢Ԫ:");
scanf("%d",&num);
printf("άкźк:");
scanf("%d,%d",&i,&j);
loc_aij=loc_a00+(i*10+j)*num;//
printf("ȶάa%d%dڴеַΪ:%d\n",i,j,loc_aij);
loc_aij=loc_a00+(j*10+i)*num;//
printf("ȶάa%d%dڴеַΪ:%d\n",i,j,loc_aij);
}
|
C
|
#include <stdio.h>
int main(void) {
int i, j, n, a, b, sum = 1;
scanf("%d", &n);
for (i = 0; i < n; i++) {
scanf("%d %d", &a, &b);
for (j = 0; j < b; j++) {
sum *= a;
while (sum - 10 > 0) sum %= 10;
}
if (sum == 0) printf("%d\n", 10);
else printf("%d\n", sum);
sum = 1;
}
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.