language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C | #include "circularList.h"
//Node *last = NULL;
Node *create(int data)
{
Node *temp = (Node *)calloc(1,sizeof(*temp));
temp->data = data;
temp->next = NULL;
return temp;
}
Node *addAtBeginning(Node *last, int data)
{
Node *new;
//Node *temp = last->next;
if(last == NULL)
{
printf("List is empty\n");
new = create(data);
new->next = new;
last = new;
return last;
}
new = create(data);
new->next = last->next;
last->next = new;
return last;
}
Node *addAtEnd(Node *last, int data)
{
Node *new;
if(last == NULL)
{
printf("List is empty\n");
new = create(data);
new->next = new;
last = new;
return last;
}
new = create(data);
new->next = last->next;
last->next = new;
last = new;
return last;
}
int getNodeCount(Node *last)
{
Node *start;
if(last == NULL)
{
return 0;
}
int count = 0;
start = last->next;
// ++count;
//
// while(start != last->next)
// {
// ++count;
// }
do
{
++count;
start = start->next;
}while(start != last->next);
return count;
}
Node *addAtPos(Node *last, int data, int pos)
{
int count = getNodeCount(last);
if(count < pos || last == NULL)
{
printf("Invalid Pos:%d\n", pos);
return last;
}
Node *new, *nodeItr;
if(pos == 1)
{
new = create(data);
new->next = last->next;
last->next = new;
return last;
}
nodeItr = last->next; // pointer to start node
// itreating until the nodeItr points to (pos -1)th node
for(int itr = 1; itr < pos -1 && nodeItr->next != last->next; ++itr)
{
nodeItr = nodeItr->next;
}
// check for nodeItr is pointing to the 1st node again!!
if(nodeItr != last->next)
{
new = create(data);
new->next = nodeItr->next;
nodeItr->next = new;
}
else
{
printf("Invalid Pos:%d\n",pos);
}
return last;
}
Node *delete(Node *last, int data)
{
if(last == NULL)
{
printf("List empty\n");
return last;
}
Node *temp, *itr;
itr = last->next;
if(itr->data == data)
{
if(itr->next == itr)
{
temp = itr;
free(temp);
last = NULL;
return last;
}
temp = itr;
last->next = temp->next;
free(temp);
return last;
}
while(itr->next != last->next)
{
if(itr->next->data == data)
{
temp = itr->next;
itr->next = temp->next;
free(temp);
return last;
}
itr = itr->next;
}
}
void display(Node *last)
{
if(last == NULL)
{
printf("List is empty\n");
return;
}
Node *start = last->next;
int itr = 1;
do
{
printf("Node[%d]: add:%p data:%d\n",itr++,start,start->data);
start = start->next;
} while(start != last->next);
}
|
C | #include <math.h>
#include "config.h"
#include <stdio.h>
extern double Temperature[ROWS+2][COLUMNS+2];
extern double Temperature_last[ROWS+2][COLUMNS+2];
double jacobi_loop( int row, double* Temp, double* Temp_last ) {
double dt = 0.0;
if ( row == 1000 ) printf( "Temperature[%d][1000] = %5.2f, Temperature_last[%d][1000] = %5.2f\n", row, Temperature[row][1000], row, Temperature_last[row][1000] );
for( int j=1; j <= COLUMNS; j++ ) {
Temperature[row][j] = 0.25 * ( Temperature_last[row][j-1] + Temperature_last[row][j+1] +
Temperature_last[row-1][j] + Temperature_last[row+1][j] );
// dt = fmax( dt, fabs( Temperature[row][j] - Temperature_last[row][j] ) );
}
return dt;
}
|
C | /* http://www.yolinux.com/TUTORIALS/LinuxTutorialPosixThreads.html */
/* conditional variable example */
/*
* A condition variable is a variable of type pthread_cond_t and is
* used with the appropriate functions for waiting and later, process
* continuation.
*
* The condition variable mechanism allows threads to suspend execution
* and relinquish the processor until some condition is true.
* A condition variable must always be associated with a mutex to
* avoid a race condition created by one thread preparing to wait
* and another thread which may signal the condition before the
* first thread actually waits on it resulting in a deadlock.
* The thread will be perpetually waiting for a signal that is
* never sent. Any mutex can be used, there is no explicit link
* between the mutex and the condition variable.
Man pages of functions used in conjunction with the condition variable:
Creating/Destroying:
pthread_cond_init
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
pthread_cond_destroy
Waiting on condition:
pthread_cond_wait - unlocks the mutex and waits for the condition variable cond to be signaled.
pthread_cond_timedwait - place limit on how long it will block.
Waking thread based on condition:
pthread_cond_signal - restarts one of the threads that are waiting on the condition variable cond.
pthread_cond_broadcast - wake up all threads blocked by the specified condition variable.
*/
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condition_var = PTHREAD_COND_INITIALIZER;
void *functionCount1();
void *functionCount2();
int count = 0;
#define COUNT_DONE 10
#define COUNT_HALT1 3
#define COUNT_HALT2 6
int main() {
pthread_t thread1, thread2;
pthread_create( &thread1, NULL, &functionCount1, NULL);
pthread_create( &thread2, NULL, &functionCount2, NULL);
pthread_join( thread1, NULL);
pthread_join( thread2, NULL);
printf("Final count: %d\n",count);
exit(0);
}
// Write numbers 1-3 and 8-10 as permitted by functionCount2()
void *functionCount1() {
for(;;) {
// Lock mutex and then wait for signal to relase mutex
pthread_mutex_lock( &count_mutex );
// Wait while functionCount2() operates on count
// mutex unlocked if condition varialbe in functionCount2() signaled.
pthread_cond_wait( &condition_var, &count_mutex );
count++;
printf("Counter value functionCount1: %d\n",count);
pthread_mutex_unlock( &count_mutex );
if (count >= COUNT_DONE) return(NULL);
}
}
// Write numbers 4-7
void *functionCount2() {
for(;;) {
pthread_mutex_lock( &count_mutex );
if( count < COUNT_HALT1 || count > COUNT_HALT2 ) {
// Condition of if statement has been met.
// Signal to free waiting thread by freeing the mutex.
// Note: functionCount1() is now permitted to modify "count".
pthread_cond_signal( &condition_var );
} else {
count++;
printf("Counter value functionCount2: %d\n",count);
}
pthread_mutex_unlock( &count_mutex );
if(count >= COUNT_DONE) return(NULL);
}
}
|
C | #include<stdio.h>
int Multip_Rec();
int main(int argc, char const *argv[]){
int n1 = 7, n2 = 7, p = 0, valor = 0;
valor = Multip_Rec(n1,n2,p);
printf("\n");
printf("%d\n", valor);
return 0;
}
int Multip_Rec(int a, int b, int p){
int v;
if (p==b)
return 0;
else{
p++;
v = a + Multip_Rec(a,b,p);
}
return v;
} |
C | // Contactor.h
/**
* Sets Contactor on or off
* Checks if flag is high or low. If high, return 1, if low, return 0.
* @author Manolo Alvarez
* @lastRevised 11/21/2018
*/
#ifndef CONTACTOR_H__
#define CONTACTOR_H__
// Initiliazes GPIOA_Pin_6
void Contactor_Init(void);
// Closes contactor, GPIO_Pin_6 = 1
void Contactor_On(void);
//Opens contactor, GPIO_Pin_6 = 0
void Contactor_Off(void);
//Outputs: flag status (0 or 1)
uint32_t Contactor_Flag(void);
#endif
|
C | #include<stdio.h>
#include<stdlib.h>
#include<omp.h>
#include<time.h>
#include<math.h>
#include<float.h>
#define K 4
int num_threads;
long num_points,cluster_count[K];
long datapoints[100][2];
int cluster[K][2]={{75,25},{25,25},{25,75},{75,75}};
void populate_points(){
long i;
#pragma omp parallel
for(i=0;i<num_points;i++){
datapoints[i][0]=rand()%100;
datapoints[i][1]=rand()%100;
printf("%ld\t%ld\n",datapoints[i][0],datapoints[i][1]);
}
for(i=0;i<4;i++)
cluster_count[i]=0;
}
double get_distance(int x1, int y1, int x2, int y2) {
int dx=x2-x1,dy=y2-y1;
return ((double)sqrt(dx*dx+dy*dy));
}
void classify_points() {
long i; int j, cluster_index; double cur_dist=0, min_dist=999;
#pragma omp parallel for private(cluster_index, j , i, cur_dist, min_dist)
for(i=0;i<num_points;i++){
cluster_index=-1;
cur_dist=0,min_dist=999;
for(j=0;j<K;j++){
cur_dist=get_distance(datapoints[i][0],datapoints[i][1],cluster[j][0],cluster[j][1]);
if(cur_dist<min_dist){
min_dist=cur_dist;
cluster_index=j;
}
}
printf("%ld %ld belongs to %d %d \n", datapoints[i][0],datapoints[i][1],cluster[cluster_index][0],cluster[cluster_index][1]);
cluster_count[cluster_index]++;
}
}
void main(){
printf("Max threads:%d\n",omp_get_max_threads());
printf("Enter number of points:");
scanf("%ld",&num_points);
populate_points();
double t1=omp_get_wtime();
classify_points();
double t2=omp_get_wtime();
printf("Time taken %lf\n",t2-t1);
int i=0;
printf("Counts\n");
while(i<4)
printf("%d->%ld\n",i,cluster_count[i++]);
}
|
C | /* This is Floyd Algorithm with time complexity of O(N log_2 P / sqrt(P))
This parallel Algorithm breaks the bigger adjacency matrix into smaller grids.
The grids are of size n/sqrt(p)*n/sqrt(p) .
Where n*n is the size of the bigger adjacency matrix and p is the total number of processes.
And finally , the computation is done on grids parallely by different processes.
*/
#include <stdio.h>
#include <mpi.h>
#include <limits.h>
#include <math.h>
#include <omp.h>
MPI_Status status;
int ROWS_IN_ORIGINAL_ARRAY=4;
int COLS_IN_ORIGINAL_ARRAY=4;
int min(int,int);
int add(int,int);
int main (int argc, char **argv)
{
int rank, size;
MPI_Init (&argc, &argv); /* starts MPI */
MPI_Comm_rank (MPI_COMM_WORLD, &rank); /* get current process id */
MPI_Comm_size (MPI_COMM_WORLD, &size); /* get number of processes */
//size = p =total number of processes
//ROWS_IN_ORIGINAL_ARRAY = n = total number of rows in the adjacency matrix
if(rank == 0)//Master Process code starts
{
//------Process to break the big matrix into grid chunks STARTS
int size_of_grid_chunk=ROWS_IN_ORIGINAL_ARRAY / (sqrt((int)size)); // g = n/sqrt(p)
//Initializing the Adjacency Matrix in the Master Process
int originalArray_W0[ROWS_IN_ORIGINAL_ARRAY][COLS_IN_ORIGINAL_ARRAY]; //Initializing the original Array
//Populating the original Adjacency Array in the Master Process
originalArray_W0[0][0]=0;
originalArray_W0[0][1]=INT_MAX;
originalArray_W0[0][2]=3;
originalArray_W0[0][3]=0;
originalArray_W0[1][0]=-2;
originalArray_W0[1][1]=0;
originalArray_W0[1][2]=INT_MAX;
originalArray_W0[1][3]=1;
originalArray_W0[2][0]=INT_MAX;
originalArray_W0[2][1]=INT_MAX;
originalArray_W0[2][2]=0;
originalArray_W0[2][3]=5;
originalArray_W0[3][0]=INT_MAX;
originalArray_W0[3][1]=4;
originalArray_W0[3][2]=INT_MAX;
originalArray_W0[3][3]=0;
int counter=0;
int i=0;
int j=0;
int k=0;
int g=size_of_grid_chunk; //g is the size of grid chunk
//sending the array chunks(grids) to the slave processes
for( i=0;i<g;i++)
{
for( j=0;j<g;j++)
{
for( k=0;k<g;k++)
{
MPI_Send(&originalArray_W0[(i*g)+k][j*g],g,MPI_INT,counter,k,MPI_COMM_WORLD);
}//end of k loop
counter=counter+1;
}//end of j loop
}//end of i loop
k=0;
//receiving the Master's chunk(grid)
int original_chunk[g][g];
for(i=0;i<g;i++)
{
MPI_Status status;
MPI_Recv(&original_chunk[i][0],2,MPI_INT,0,i,MPI_COMM_WORLD,&status);
}
//-----Process to break the big matrix into grid chunks ENDS
//MAIN LOOP (in master) which runs k times where k is the number of vertices in the graph
for(k=0;k<ROWS_IN_ORIGINAL_ARRAY;k++)
{
//Sending the i rows
for(i=0;i<size;i++)
{
int i_by_g=i/g;
for(j=i_by_g*g;j<(i_by_g*g)+g;j++)
{
MPI_Send(&originalArray_W0[j][0],COLS_IN_ORIGINAL_ARRAY,MPI_INT,i,(j-(i_by_g*g)),MPI_COMM_WORLD);//This will run g times for each process
} //end of j loop
}//end of i loop
//Receiving the i rows
int i_rows_chunk[g][COLS_IN_ORIGINAL_ARRAY];
i=0;
for(i=0;i<g;i++)
{
MPI_Status status;
MPI_Recv(&i_rows_chunk[i][0],COLS_IN_ORIGINAL_ARRAY,MPI_INT,0,i,MPI_COMM_WORLD,&status);
}
//Sending the k row
for(i=0;i<size;i++)
{
MPI_Send(&originalArray_W0[k][0],COLS_IN_ORIGINAL_ARRAY,MPI_INT,i,k,MPI_COMM_WORLD);//tag is k
}
//Receiving k the row
int k_row[COLS_IN_ORIGINAL_ARRAY];
MPI_Status status1;
MPI_Recv(&k_row,COLS_IN_ORIGINAL_ARRAY,MPI_INT,0,k,MPI_COMM_WORLD,&status1);
//Computation starts using MULTI THREADING
omp_set_num_threads(g);
#pragma omp parallel
{
int ID = omp_get_thread_num();j=0;
for(j=0;j<g;j++)
{
int absolute_i= (((int)rank/g)*g)+ID;
int absolute_j= ((rank%g)*g)+j;
original_chunk[ID][j]=min(original_chunk[ID][j], add(i_rows_chunk[ID][k],k_row[absolute_j]) ) ;
}
}
//Sending the results to master to update
for(i=0;i<g;i++)
{
MPI_Send(&original_chunk[i][0],g,MPI_INT,0,i,MPI_COMM_WORLD);
}//end of i loop
//Receiving from slave processes and updating the original array
for(i=0;i<size;i++)//i represents the process from which we receive
{
int start_i= ((int)i/g)*g;
int start_j= (i%g)*g;
for(j=start_i;j<start_i+g;j++)
{
MPI_Status status;
MPI_Recv(&originalArray_W0[j][start_j],g,MPI_INT,i,(start_i-j),MPI_COMM_WORLD,&status);
}//end of j loop
}//end of i loop
} //MAIN k loop ends
printf("\n After the computation, the values of grid in process %d are - \n",rank);
for(i=0;i<g;i++)
{
for(j=0;j<g;j++)
{
printf(" %d ",original_chunk[i][j]);
}
printf("\n");
}
printf("\n\n");
}//end of Master Process
//******************************************************************************************************************
else //Slave Process
{
int size_of_grid_chunk=ROWS_IN_ORIGINAL_ARRAY / (sqrt((int)size)); // g = n/sqrt(p)
int g=size_of_grid_chunk;
//receiving the grid chunk from master
int original_chunk[g][g];
int i=0;int j=0;
for(i=0;i<g;i++)
{
MPI_Status status;
MPI_Recv(&original_chunk[i][0],2,MPI_INT,0,i,MPI_COMM_WORLD,&status);
}
int k=0;
//MAIN LOOP (in slave) which runs k times where k is the number of vertices in the graph
for(k=0;k<ROWS_IN_ORIGINAL_ARRAY;k++)
{
//Receiving the i rows from master
int i_rows_chunk[g][COLS_IN_ORIGINAL_ARRAY];
i=0;
for(i=0;i<g;i++)
{
MPI_Status status;
MPI_Recv(&i_rows_chunk[i][0],COLS_IN_ORIGINAL_ARRAY,MPI_INT,0,i,MPI_COMM_WORLD,&status);
}
//Receiving k the row
int k_row[COLS_IN_ORIGINAL_ARRAY];
MPI_Status status1;
MPI_Recv(&k_row,COLS_IN_ORIGINAL_ARRAY,MPI_INT,0,k,MPI_COMM_WORLD,&status1);
//Computation starts using MULTI THREADING
omp_set_num_threads(g);
#pragma omp parallel
{
int ID = omp_get_thread_num();j=0;
for(j=0;j<g;j++)
{
int absolute_i= (((int)rank/g)*g)+ID;
int absolute_j= ((rank%g)*g)+j;
original_chunk[ID][j]=min(original_chunk[ID][j], add(i_rows_chunk[ID][k],k_row[absolute_j]) ) ;
}
}
//Sending the results to master to update
for(i=0;i<g;i++)
{
MPI_Send(&original_chunk[i][0],g,MPI_INT,0,i,MPI_COMM_WORLD);
}//end of i loop
} //MAIN k loop ends
printf("\n After the computation, the values of grid in process %d are - \n",rank);
for(i=0;i<g;i++)
{
for(j=0;j<g;j++)
{
printf(" %d ",original_chunk[i][j]);
}
printf("\n");
}
printf("\n\n");
}//End of Slave Process
MPI_Finalize();
return 0;
}
//This function returns the minimum of 2 numbers
int min(int a,int b)
{
if(a<b) return a;
else return b;
}
//This function returns the sum of 2 numbers. This also handles the cases where the input is infinity.
int add(int a,int b)
{
if(a==INT_MAX && b==INT_MAX) return INT_MAX;
if(a==INT_MAX || b==INT_MAX) return INT_MAX;
return a+b;
} |
C | #include <memory.h>
#include <printk.h>
#include <string.h>
#include <x86.h>
#define PHYSICAL_POOL_PAGES 64
#define PHYSICAL_POOL_BYTES (PHYSICAL_POOL_PAGES << 12)
#define BITSET_SIZE (PHYSICAL_POOL_PAGES >> 6)
#define ADDRMASK 0xFFF0000000000FFF
#define OFFSMASK 0x1FF
#define PAGESIZE 4096
#define PAGE_SIZE PAGESIZE
#define PAGE_MASK ADDRMASK
#define STACKSTART 0x2000000000
#define STACKEND 0x40000000
extern __attribute__((noreturn)) void die(void);
static uint64_t bitset[BITSET_SIZE];
static uint8_t pool[PHYSICAL_POOL_BYTES] __attribute__((aligned(0x1000)));
paddr_t alloc_page(void)
{
size_t i, j;
uint64_t v;
for (i = 0; i < BITSET_SIZE; i++) {
if (bitset[i] == 0xffffffffffffffff)
continue;
for (j = 0; j < 64; j++) {
v = 1ul << j;
if (bitset[i] & v)
continue;
bitset[i] |= v;
return (((64 * i) + j) << 12) + ((paddr_t) &pool);
}
}
printk("[error] Not enough identity free page\n");
return 0;
}
void free_page(paddr_t addr)
{
paddr_t tmp = addr;
size_t i, j;
uint64_t v;
tmp = tmp - ((paddr_t) &pool);
tmp = tmp >> 12;
i = tmp / 64;
j = tmp % 64;
v = 1ul << j;
if ((bitset[i] & v) == 0) {
printk("[error] Invalid page free %p\n", addr);
die();
}
bitset[i] &= ~v;
}
/*
* Memory model for Rackdoll OS
*
* +----------------------+ 0xffffffffffffffff
* | Higher half |
* | (unused) |
* +----------------------+ 0xffff800000000000
* | (impossible address) |
* +----------------------+ 0x00007fffffffffff
* | User |
* | (text + data + heap) |
* +----------------------+ 0x2000000000
* | User |
* | (stack) |
* +----------------------+ 0x40000000
* | Kernel |
* | (valloc) |
* +----------------------+ 0x201000
* | Kernel |
* | (APIC) |
* +----------------------+ 0x200000
* | Kernel |
* | (text + data) |
* +----------------------+ 0x100000
* | Kernel |
* | (BIOS + VGA) |
* +----------------------+ 0x0
*
* This is the memory model for Rackdoll OS: the kernel is located in low
* addresses. The first 2 MiB are identity mapped and not cached.
* Between 2 MiB and 1 GiB, there are kernel addresses which are not mapped
* with an identity table.
* Between 1 GiB and 128 GiB is the stack addresses for user processes growing
* down from 128 GiB.
* The user processes expect these addresses are always available and that
* there is no need to map them exmplicitely.
* Between 128 GiB and 128 TiB is the heap addresses for user processes.
* The user processes have to explicitely map them in order to use them.
*/
void map_page(struct task *ctx, vaddr_t vaddr, paddr_t paddr)
{
uint64_t index;
paddr_t *pml = (paddr_t *)ctx->pgt;
for(int i = 3; i > 0; i--){
index = ((vaddr>>12)>>(i*9))&OFFSMASK;
if(!((pml[index])&1))
pml[index]= alloc_page();
pml[index]= pml[index]|7;
pml = (paddr_t *)(pml[index]&~ADDRMASK);
}
index = (vaddr>>12)&OFFSMASK;
pml[index]= paddr|7;
}
void load_task(struct task *ctx)
{
uint64_t i, dataSize, bssSize;
vaddr_t bssBegin;
paddr_t *pml4, *oldPml4, *pml3, *oldPml3;
ctx->pgt= alloc_page()&~ADDRMASK;
dataSize = ctx->bss_end_vaddr - ctx->load_vaddr;
bssBegin = ctx->load_vaddr + (ctx->load_end_paddr - ctx->load_paddr);
bssSize = ctx->bss_end_vaddr - bssBegin;
for(i=0; i < dataSize ; i+= PAGESIZE){
map_page(ctx, ctx->load_vaddr+i, ctx->load_paddr+i);
}
memset((void*)ctx->load_end_paddr, 0, bssSize);
pml4 = (paddr_t *)ctx->pgt;
oldPml4 = (paddr_t *)store_cr3();
pml3 = (paddr_t *)(pml4[0]&~ADDRMASK);
oldPml3 = (paddr_t *)(oldPml4[0]&~ADDRMASK);
pml3[0] = oldPml3[0];
}
/* Code de Vincent
void load_task(struct task *ctx)
{
uint64_t i;
uint64_t size_data = (ctx->bss_end_vaddr - ctx->load_vaddr);
paddr_t *bss_paddr = (paddr_t*)ctx->load_end_paddr;
vaddr_t bss_vaddr = ctx->load_vaddr + (ctx->load_end_paddr - ctx->load_paddr);
uint64_t size_bss = ctx->bss_end_vaddr - bss_vaddr;
ctx->pgt = alloc_page() & ~PAGE_MASK;
for (i = 0; i < size_data; i += PAGE_SIZE) {
map_page(ctx, ctx->load_vaddr + i, ctx->load_paddr + i);
}
memset(ctx->load_end_paddr, 0, size_bss);
paddr_t *cur_pml4 = (paddr_t *)store_cr3();
paddr_t *new_pml4 = (paddr_t *)ctx->pgt;
paddr_t *kernel_pml3 = (paddr_t*)(cur_pml4[0] & ~PAGE_MASK);
paddr_t *new_pml3 = (paddr_t*)(new_pml4[0] & ~PAGE_MASK);
new_pml3[0] = kernel_pml3[0];
}
*/
void set_task(struct task *ctx)
{
load_cr3(ctx->pgt);
}
void mmap(struct task *ctx, vaddr_t vaddr)
{
map_page(ctx, vaddr, alloc_page());
}
void munmap(struct task *ctx, vaddr_t vaddr)
{
}
void pgfault(struct interrupt_context *ctx)
{
uint64_t pgt = store_cr3();
if((store_cr2 < STACKSTART) && (store_cr2 > STACKEND))
map_page((struct task *) &pgt, store_cr2(), alloc_page());
else
exit_task(ctx);
}
void duplicate_task(struct task *ctx)
{
}
|
C | #include <stdio.h>
#define BUFFER_SIZE 100
int main()
{
char * words[100];
int n = 0;
int slice = 0;
char buffer[BUFFER_SIZE];
while (scanf("%s", buffer) != EOF)
{
words[n] = buffer;
n++;
}
} |
C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
//去除字符串前后的空格, 中间的不管
int trimSpace(char *str, char *newstr){
char *p = str;
int i, j, count;
j = strlen(p)-1;
if(str == NULL || newstr == NULL){
return -1;
}
while(isspace(p[i]) && *(p+i) != '\0'){
i++;
}
while(isspace(p[j]) && *(p+j) != '\0'){
j--;
}
count = j -i + 1;
strncpy(newstr, str+i, count);
newstr[count] = '\0';
return 0;
}
//根据key获取value
int getKeyByValue(char *keyvaluebuf, char *key, char *value){
if(keyvaluebuf == NULL || key == NULL || value == NULL){
return -1;
}
char *p = NULL;
int ret = 0;
//1查找key是不是在母串中
p = keyvaluebuf; //初始化辅助指针变量
p = strstr(p, key);
if(p == NULL){
return -1;
}
//让辅助指针变量 重新达到下一次检索的条件
p = p + strlen(key);
//2看有没有=号
p = strstr(p, "=");
if(p == NULL){
return -1;
}
p = p + strlen("=");
//3在等号后面 去除空格
ret = trimSpace(p, value);
if(ret == -1){
printf("trimSpece error\n");
return ret;
}
return ret;
}
int main(void){
int ret = 0;
char buf[1024] = {0};
char *keyandvalue = "key2= value2 ";
char *key = "key2";
ret = getKeyByValue(keyandvalue, key, buf);
if(ret == -1){
printf("getKeyByValue error\n");
exit(1);
}
printf("buf:%s\n", buf);
return 0;
}
|
C | #include <stdio.h>
#include <string.h>
int mystrstr(char *haystack, char *needle) {
if(*needle == 0) {
return 0;
}
for(unsigned q=0; *(haystack+q) != 0; q++) {
for(unsigned w=0; *(needle+w) != 0; w++) {
if(*(haystack+q+w) != *(needle+w)) {
break;
}
if(w == strlen(needle)-1) {
return q;
}
}
}
return -1;
}
int main() {
char a[100],b[100];
while(~scanf("%s %s", a, b)) {
printf("%d\n", mystrstr(a, b));
}
return 0;
}
|
C | #include <stdio.h>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <errno.h>
void s_debug()
{
printf("debug: %s \r\n", strerror(errno));
exit(1);
}
int main(int argc, char **argv)
{
int socknd;
struct sockaddr_in servx;
char buf[255];
int rt;
bzero(buf, 255);
socknd = socket(AF_INET, SOCK_STREAM, 0);
servx.sin_family = AF_INET;
servx.sin_port = htons(181);
inet_pton(AF_INET, "127.0.0.1", &servx.sin_addr);
rt = connect(socknd, (struct sockaddr *)&servx, sizeof(servx));
if(rt < 0) s_debug();
write(socknd, "GET \r\n\r\n", 9);
read(socknd, buf, 255);
//printf("c buf: %s \r\n", buf);
close(socknd);
return 0;
}
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* rotate_push.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: dquordle <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/04/07 15:13:30 by dquordle #+# #+# */
/* Updated: 2021/04/07 15:14:08 by dquordle ### ########.fr */
/* */
/* ************************************************************************** */
#include "push_swap.h"
int ft_pb_cycle_2(int **stack_a, int **stack_b, int cut_a, int **partition)
{
float median;
int buf;
int count_a;
int count;
count_a = 0;
count = 0;
median = ft_get_median(*stack_a, 1, (*stack_a)[0] - cut_a + 1);
buf = (*stack_a)[0] - cut_a;
while (buf > 0)
{
if ((*stack_a)[1] <= median)
{
ft_exec_command("pb\n", stack_a, stack_b);
count++;
}
else if (ft_need_to_ra(*stack_a, cut_a, median))
{
ft_exec_command("ra\n", stack_a, stack_b);
count_a++;
}
buf--;
}
*partition = ft_appstart(partition, count);
return (count_a);
}
void ft_pb_cycle(int **stack_a, int **stack_b, int *cut_a, int **partition)
{
int count_a;
while ((*stack_a)[0] - *cut_a > 3)
{
if (ft_is_sorted(*stack_a, 1, (*stack_a)[0] - 1))
{
*cut_a = (*stack_a)[0];
break ;
}
count_a = ft_pb_cycle_2(stack_a, stack_b, *cut_a, partition);
if (*cut_a > 1)
{
while (count_a--)
ft_exec_command("rra\n", stack_a, stack_b);
}
}
if (*cut_a == 1)
{
ft_three(*stack_a);
*cut_a = (*stack_a)[0];
}
else
ft_first_three(*stack_a, cut_a);
}
int ft_need_to_rb(int *stack_b, int buf, float median)
{
int i;
i = 1;
buf++;
while (buf > 0)
{
if (stack_b[i] >= median)
return (1);
i++;
buf--;
}
return (0);
}
void ft_pa_cycle_2(int **stack_a, int **stack_b, int *cut_a, int **partition)
{
float median;
int buf;
int count;
int count_a;
median = ft_get_median(*stack_b, 1, (*partition)[0] + 1);
buf = (*partition)[0];
count = 0;
count_a = 0;
while (buf-- > 0)
{
if ((*stack_b)[1] < median && ft_need_to_rb(*stack_b, buf, median)
&& ++count)
ft_exec_command("rb\n", stack_a, stack_b);
else if ((*stack_b)[1] >= median && ++count_a && (*partition)[0]--)
ft_exec_command("pa\n", stack_a, stack_b);
}
if (count_a <= 3)
ft_first_three(*stack_a, cut_a);
if ((*partition)[1])
{
while (count-- > 0)
ft_exec_command("rrb\n", stack_a, stack_b);
}
}
void ft_pa_cycle(int **stack_a, int **stack_b, int *cut_a, int **partition)
{
if ((*stack_b)[0] > 1 && (*stack_b)[0] <= 4)
{
ft_rev_three(*stack_b);
while ((*stack_b)[0] > 1)
ft_exec_command("pa\n", stack_a, stack_b);
*cut_a = (*stack_a)[0];
(*partition)[0] = 0;
}
else if (((*partition)[0] > 0 && (*partition)[0] <= 3)
|| ft_is_sorted(*stack_b, (*partition)[0], 1))
{
while ((*partition)[0]-- > 0)
ft_exec_command("pa\n", stack_a, stack_b);
*partition = ft_delstart(partition);
ft_first_three(*stack_a, cut_a);
}
else if ((*stack_b)[0] > 1)
ft_pa_cycle_2(stack_a, stack_b, cut_a, partition);
}
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_arg_format.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: anel-bou <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/06/12 10:38:10 by anel-bou #+# #+# */
/* Updated: 2019/10/23 20:17:09 by anel-bou ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
#define A2I ft_atoi(f)
#define TAILLE lst->taille
void ignore_spc_n_zero(char *s)
{
if (ft_strchr(s, ' ') && ft_strchr(s, '+'))
ft_del_char(s, ' ');
if (ft_strchr(s, '-') && ft_strchr(s, '0'))
ft_del_char(s, '0');
}
int taille(char *f)
{
if (*f == 'h' && *(f + 1) == 'h')
return (1);
else if (*f == 'h' && *(f + 1) != 'h')
return (2);
else if (*f == 'l' && *(f + 1) != 'l')
return (3);
else if (*f == 'l' && *(f + 1) == 'l')
return (4);
else if (*f == 'L')
return (5);
else if (*f == 'z')
return (6);
else if (*f == 'j')
return (7);
else if (*f == 't')
return (8);
return (0);
}
int get_taille(char **f, t_arg *lst)
{
if (**f == 'l' || **f == 'h' || **f == 'L' || **f == 'z'
|| **f == 't' || **f == 'j')
{
TAILLE = taille(*f);
*f = ((TAILLE == 1 || TAILLE == 4) ? (*f + 2) : (*f + 1));
return (1);
}
return (0);
}
void get_arg_format(char *f, t_arg *lst)
{
int tmp;
set_t_arg(lst);
tmp = 0;
(*f == '0') ? lst->option[0] = '0' : 0;
if (*f >= '0' && *f <= '9')
tmp = (A2I < 0) ? -1 : A2I;
while (*f >= '0' && *f <= '9')
f++;
(*f == '$') ? (lst->dollar = tmp) : 0;
(*f != '$') ? (lst->larg_min = tmp) : 0;
f = ((*f == '$') ? (f + 1) : f);
tmp = ((lst->option[0]) ? 1 : 0);
while (*f == '-' || *f == '+' || *f == '#' || *f == '0' || *f == ' ')
(!ft_strchr((lst->option), *f)) ? lst->option[tmp++] = *f++ : 0;
ignore_spc_n_zero(lst->option);
(*f >= '0' && *f <= '9') ? lst->larg_min = A2I : 0;
while (*f >= '0' && *f <= '9')
f++;
if (*f == '.' && ++lst->point && *(++f) >= '0' && *f <= '9')
lst->precision = (A2I < 0) ? 6 : A2I;
while (*f >= '0' && *f <= '9')
f++;
(get_taille(&f, lst));
(ft_strchr("cspfdiouxXegbrk", *f)) ? lst->conv_tp = *f : 0;
}
|
C | /* This applies to square matices n x n
1 0 0
0 1 0
0 0 1
we may allocate an array of size n only to save space
instead of n * n size to store zeros
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef struct {
int *matrix;
int deminsions;
} diagonal_t;
void set(diagonal_t *matrix_ptr, int i, int j, int input) {
if (i == j) {
matrix_ptr->matrix[i] = input;
}
}
int get(diagonal_t *matrix_ptr, int i, int j) {
if (i == j) {
return matrix_ptr->matrix[i];
} else {
return 0;
}
}
void display(diagonal_t *matrix_ptr) {
for(int i = 0; i < matrix_ptr->deminsions; i++) {
for(int j = 0; j < matrix_ptr->deminsions; j++) {
if (i == j)
{
printf("%d ", matrix_ptr->matrix[i]);
} else {
printf("%d ", 0);
}
}
printf("\n");
}
}
int main() {
diagonal_t matrix1;
matrix1.deminsions = 5;
matrix1.matrix = (int *)malloc(sizeof(int) * matrix1.deminsions);
if(!matrix1.matrix) {
printf("\nError: failed to allocate memroy\n");
}
srand(time(0));
for(int i = 0; i < matrix1.deminsions; i++) {
set(&matrix1, i, i, (rand() % 99) + 1);
}
display(&matrix1);
free(matrix1.matrix);
return 0;
} |
C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define VELICINA (11)
#define VEL_DAT (1024)
struct _stablo;
typedef struct _stablo *StabloPozicija;
typedef struct _stablo {
char data[VELICINA];
StabloPozicija lijevo;
StabloPozicija desno;
}Stablo;
struct _lista;
typedef struct _lista *ListaPozicija;
typedef struct _lista {
StabloPozicija stablo;
ListaPozicija next;
}Lista;
StabloPozicija stvori(char *);
int pushFront(ListaPozicija, StabloPozicija);
int pushBack(ListaPozicija, StabloPozicija);
StabloPozicija popFront(ListaPozicija);
int jeLiBroj(char*);
StabloPozicija citanjeIzDatoteke(char*);
void ispisInOrder(ListaPozicija, StabloPozicija);
int main(void) {
StabloPozicija cvor = NULL;
ListaPozicija p = NULL;
char imeDat[VEL_DAT] = { 0 };
FILE* novaDat;
novaDat = fopen("noviupis.txt", "w");
Lista head;
head.next = NULL;
printf("Unesite ime datoteke!\n");
scanf("%s", imeDat);
cvor = citanjeIzDatoteke(imeDat);
if (NULL == cvor) {
return EXIT_FAILURE;
}
ispisInOrder(&head, cvor);
for (p = head.next; p != NULL; p = p->next) {
fprintf(novaDat, "%s", p->stablo->data);
}
fclose(novaDat);
return EXIT_SUCCESS;
}
StabloPozicija stvori(char *data) {
StabloPozicija cvor = NULL;
cvor = (StabloPozicija)malloc(sizeof(Stablo));
if (NULL == cvor) {
printf("Pogresna alokacija memorije!\r\n");
return NULL;
}
strcpy(cvor->data, data);
cvor->lijevo = NULL;
cvor->desno = NULL;
return cvor;
}
int pushFront(ListaPozicija head, StabloPozicija cvorStablo) {
ListaPozicija cvorLista = malloc(sizeof(Lista));
if (NULL == cvorLista) {
printf("Pogresna alokacija memorije!\r\n");
return -1;
}
cvorLista->stablo = cvorStablo;
cvorLista->next = head->next;
head->next = cvorLista;
return 0;
}
int pushBack(ListaPozicija head, StabloPozicija cvorStablo) {
ListaPozicija p = head;//pitati
while (p->next != NULL) p = p->next;//dolazak do kraja
return pushFront(p, cvorStablo);
}
StabloPozicija popFront(ListaPozicija head) {
ListaPozicija prvi = head->next;
StabloPozicija temp = NULL;
if (NULL == prvi) return NULL;
head->next = prvi->next;
temp = prvi->stablo;
free(prvi);
return temp;
}
int jeLiBroj(char *data) {
int br = 0;
if (sscanf(data, "%d", &br) == 1) return 1;
return 0;
}
StabloPozicija citanjeIzDatoteke(char* imeDat) {
FILE *dat=NULL;
Lista head;
StabloPozicija temp=NULL;
char data[VELICINA] = { 0 };
head.next = NULL;
dat = fopen(imeDat, "r");
if (NULL == dat) {
printf("Datoteka %s ne postoji ili nemas ovlastenja.\r\n", imeDat);
return NULL;
}
while (!feof(dat)) {
StabloPozicija cvor = NULL;
fscanf(dat, "%s", data);
cvor = stvori(data);
if (NULL==cvor) {
fclose(dat);
return NULL;
}
if (jeLiBroj(cvor->data)) {
pushFront(&head, cvor);
}
else {
cvor->desno = popFront(&head);
if (NULL == cvor->desno) {
printf("Nevaljan upis postfixa u datoteci %s!\r\n", imeDat);
}
cvor->lijevo = popFront(&head);
if (NULL == cvor->lijevo) {
printf("Nevaljan upis postfixa u datoteci %s!\r\n", imeDat);
}
pushFront(&head, cvor);
}
}
temp = popFront(&head);
if (NULL == temp) {
printf("Nevaljan upis postfixa u datoteci %s!\r\n", imeDat);
return NULL;
}
if (popFront(&head) != NULL) {
printf("Nevaljan upis postfixa u datoteci %s!\r\n", imeDat);
return NULL;
}
return temp;
}
void ispisInOrder(ListaPozicija head, StabloPozicija trenutni) {
if (NULL == trenutni) return;
ispisInOrder(head, trenutni->lijevo);
pushBack(head, trenutni);
ispisInOrder(head, trenutni->desno);
}
|
C | #include <stdio.h>
#include <ctype.h>
#include <string.h>
#define MAX 80
float odnosGolemiMali(char *p)
{
int golemi=0;
int mali=0;
while(*p)
{
if(isalpha(*p)) {
if(isupper(*p)) {
golemi++;
} else if(islower(*p)) {
mali++;
}
}
p++;
}
return 1.0 * golemi / mali;
}
int main()
{
FILE *f = fopen("tekst.txt","r");
char row[MAX];
char maxRow[MAX];
int max=0;
int index=0;
while(fgets(row,MAX,f)!=NULL)
{
float m = odnosGolemiMali(row);
if(m>max)
{
max=index;
strcpy(maxRow,row);
}
printf("%0.2f %s",m,row);
index++;
}
fclose(f);
printf("\n%d\n",max);
return 0;
} |
C | #include "minicrt.h"
#include <stdarg.h>
int fputc(char c, FILE *stream)
{
if (fwrite(&c, 1, 1, stream) != 1)
return EOF;
else
return c;
}
int fputs(const char *str, FILE *stream)
{
int len = strlen(str);
if (fwrite(str, 1, len, stream) != len)
return EOF;
else
return len;
}
static int vfprintf(FILE *stream, const char *format, va_list args)
{
int translating = 0;
int ret = 0;
const char *p = 0;
for (p = format; *p != '\0'; p++)
{
switch (*p)
{
case '%':
if (!translating)
translating = 1;
else
{
if (fputc('%', stream) < 0)
return EOF;
ret++;
translating = 0;
}
break;
case 'd':
if (translating)
{
char buf[16];
translating = 0;
itoa(va_arg(args, int), buf, 10);
if (fputs(buf, stream) < 0)
return EOF;
ret += strlen(buf);
}
else if (fputc('d', stream) < 0)
return EOF;
else
ret++;
break;
case 's':
if (translating)
{
const char *str = va_arg(args, const char *);
translating = 0;
if (fputs(str, stream) < 0)
return EOF;
ret += strlen(str);
}
else if (fputc('s', stream) < 0)
return EOF;
else
ret++;
break;
default:
if (translating)
translating = 0;
if (fputc(*p, stream) < 0)
return EOF;
else
ret++;
break;
}
}
return ret;
}
int printf(const char *format, ...)
{
va_list args;
va_start(args, format);
return vfprintf(stdout, format, args);
}
int fprintf(FILE *stream, const char *format, ...)
{
va_list args;
va_start(args, format);
return vfprintf(stream, format, args);
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>
#include <fcntl.h>
# define LINK_LENGTH 100
void get_proc(char* str)
{
int len = strlen(str);
int count = 0, i = 0;
while (1)
{
if (str[i] == '\n')
break;
if (str[i] == '\t')
count = i;
i++;
}
memcpy(str, str + count, i - count);
memset(str + i - count, 0, len - i - count);
return;
}
int main()
{
int current_size = LINK_LENGTH;
char* slink = malloc(sizeof(char) * LINK_LENGTH);
char* linkname = malloc(sizeof(char) * LINK_LENGTH);
char* str = malloc(sizeof(char) * LINK_LENGTH);
memset(slink, 0, LINK_LENGTH);
memset(linkname, 0, LINK_LENGTH);
memset(str, 0, LINK_LENGTH);
DIR* proc_dir = opendir("/proc");
if (proc_dir == NULL)
{
printf("Error: can not open /proc directory\n");
return 1;
}
struct dirent* dir = (struct dirent*)malloc(sizeof(struct dirent));
struct dirent* result;
long pid;
int len, is_user = 1, fd;
FILE* fh;
while (1)
{
readdir_r(proc_dir, dir, &result);
if (result == NULL)
break;
if (!isdigit(*dir->d_name))
continue;
pid = strtol(dir->d_name, NULL, 10);
len = strlen(dir->d_name);
memcpy(slink, "/proc/", strlen("/proc/"));
memcpy(slink + strlen("/proc/"), dir->d_name, len);
memcpy(slink + strlen("/proc/") + len, "/exe", strlen("/exe"));
is_user = readlink(slink, linkname, current_size);
if (strlen(linkname) == current_size)
{
linkname = realloc(linkname, current_size * 2);
current_size *= 2;
memset(linkname, 0, current_size);
is_user = readlink(slink, linkname, current_size);
}
if (is_user == -1)
{
memcpy(slink + strlen("/proc/") + len, "/status", strlen("/status"));
fd = open(slink, O_RDONLY);
read(fd, str, LINK_LENGTH);
get_proc(str);
printf("pid: %ld link: %s\n", pid, str);
close(fd);
memset(str, 0, LINK_LENGTH);
memset(linkname, 0, current_size);
memset(slink, 0, LINK_LENGTH);
continue;
}
printf("pid: %ld link: \t%s\n", pid, linkname);
memset(linkname, 0, current_size);
memset(slink, 0, LINK_LENGTH);
}
closedir(proc_dir);
free(slink);
free(linkname);
free(str);
free(dir);
return 0;
}
|
C |
/***********************************************************************
*
* xvlrboundary.h
*
* left & right state boundary condition in x
*
*
* j, k : loop index of x, y, z
* m : Vl, Vr vector component index
*
*
* 2013 Apr. 15 : add XLeftVlAxisBoundary.
* 2012 Dec. 06 : coded by Sho Nakamura (Tohoku Univ).
*
**********************************************************************/
//==================================================
// i=ixmax1-1 right state free boundary
//==================================================
int XRightVrFreeBoundary(void)
{
int j, k;
int m;
//-----Vl, Vr free boundary in x-----
#pragma omp parallel for private(j, k, m)
for(m=0; m<9; m++){
for(j=0; j<jymax1; j++){
for(k=0; k<kzmax1; k++){
Vr[m][ixmax1-1][j][k]=Vl[m][ixmax1-1][j][k];
}
}
}
return 0;
}
//==================================================
// i=0 left state axis boundary
//==================================================
int XLeftVlAxisBoundary(void)
{
int j, k;
//-----Vl axis boundary-----
#pragma omp parallel for private(j, k)
for(j=0; j<jy/2+1; j++){
for(k=0; k<kzmax1; k++){
Vl[0][0][j][k]=Vr[0][0][j+jy/2][k];
Vl[1][0][j][k]=-Vr[1][0][j+jy/2][k];
Vl[2][0][j][k]=-Vr[2][0][j+jy/2][k];
Vl[3][0][j][k]=Vr[3][0][j+jy/2][k];
Vl[4][0][j][k]=-Vr[4][0][j+jy/2][k];
Vl[5][0][j][k]=-Vr[5][0][j+jy/2][k];
Vl[6][0][j][k]=Vr[6][0][j+jy/2][k];
Vl[7][0][j][k]=Vr[7][0][j+jy/2][k];
Vl[8][0][j][k]=Vr[8][0][j+jy/2][k];
}
}
#pragma omp parallel for private(j, k)
for(j=jy/2+1; j<jymax1; j++){
for(k=0; k<kzmax1; k++){
Vl[0][0][j][k]=Vr[0][0][j-jy/2][k];
Vl[1][0][j][k]=-Vr[1][0][j-jy/2][k];
Vl[2][0][j][k]=-Vr[2][0][j-jy/2][k];
Vl[3][0][j][k]=Vr[3][0][j-jy/2][k];
Vl[4][0][j][k]=-Vr[4][0][j-jy/2][k];
Vl[5][0][j][k]=-Vr[5][0][j-jy/2][k];
Vl[6][0][j][k]=Vr[6][0][j-jy/2][k];
Vl[7][0][j][k]=Vr[7][0][j-jy/2][k];
Vl[8][0][j][k]=Vr[8][0][j-jy/2][k];
}
}
/*
#pragma omp parallel for private(j, k)
for(j=0; j<jy/2+1; j++){
for(k=0; k<kzmax1; k++){
Vl[0][0][j][k]=Vr[0][0][j+jy/2][k];
Vl[1][0][j][k]=Vr[1][0][j+jy/2][k];
Vl[2][0][j][k]=Vr[2][0][j+jy/2][k];
Vl[3][0][j][k]=Vr[3][0][j+jy/2][k];
Vl[4][0][j][k]=-Vr[4][0][j+jy/2][k];
Vl[5][0][j][k]=-Vr[5][0][j+jy/2][k];
Vl[6][0][j][k]=Vr[6][0][j+jy/2][k];
Vl[7][0][j][k]=Vr[7][0][j+jy/2][k];
Vl[8][0][j][k]=Vr[8][0][j+jy/2][k];
}
}
#pragma omp parallel for private(j, k)
for(j=jy/2+1; j<jymax1; j++){
for(k=0; k<kzmax1; k++){
Vl[0][0][j][k]=Vr[0][0][j-jy/2][k];
Vl[1][0][j][k]=Vr[1][0][j-jy/2][k];
Vl[2][0][j][k]=Vr[2][0][j-jy/2][k];
Vl[3][0][j][k]=Vr[3][0][j-jy/2][k];
Vl[4][0][j][k]=-Vr[4][0][j-jy/2][k];
Vl[5][0][j][k]=-Vr[5][0][j-jy/2][k];
Vl[6][0][j][k]=Vr[6][0][j-jy/2][k];
Vl[7][0][j][k]=Vr[7][0][j-jy/2][k];
Vl[8][0][j][k]=Vr[8][0][j-jy/2][k];
}
}
*/
return 0;
}
//==================================================
// left & right state periodic boundary
//==================================================
int XVlrPeriodicBoundary(void)
{
int j, k;
int m;
//-----Vl, Vr periodic boundary in x-----
#pragma omp parallel for private(j, k, m)
for(m=0; m<9; m++){
for(j=0; j<jymax1; j++){
for(k=0; k<kzmax1; k++){
Vl[m][0][j][k]=Vl[m][ixmax1-1][j][k];
Vr[m][ixmax1-1][j][k]=Vr[m][0][j][k];
}
}
}
return 0;
}
//==================================================
// left & right state free boundary
//==================================================
int XVlrFreeBoundary(void)
{
int j, k;
int m;
//-----Vl, Vr free boundary in x-----
#pragma omp parallel for private(j, k, m)
for(m=0; m<9; m++){
for(j=0; j<jymax1; j++){
for(k=0; k<kzmax1; k++){
Vl[m][0][j][k]=Vr[m][0][j][k];
Vr[m][ixmax1-1][j][k]=Vl[m][ixmax1-1][j][k];
}
}
}
return 0;
}
|
C | #define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
//һûظֵУпܵȫС
void swap(int* nums, int a, int b) {
int temp = nums[a];
nums[a] = nums[b];
nums[b] = temp;
}
void backtrack(int* nums, int numsSize, int** ret, int first, int* returnSize, int** returnColumnSizes) {
if (first == numsSize) {
returnColumnSizes[0][*returnSize] = numsSize;
ret[*returnSize] = (int*)calloc(numsSize, sizeof(int));
memcpy(ret[*returnSize], nums, numsSize*sizeof(int));
(*returnSize)++;
return;
}
int i;
for (i = first; i<numsSize; i++) {
swap(nums, first, i);
backtrack(nums, numsSize, ret, first + 1, returnSize, returnColumnSizes);
swap(nums, first, i);
}
}
int** permute(int* nums, int numsSize, int* returnSize, int** returnColumnSizes) {
int** ret = (int **)calloc(720, sizeof(int *));
returnColumnSizes[0] = (int*)calloc(720, sizeof(int));
*returnSize = 0;
backtrack(nums, numsSize, ret, 0, returnSize, returnColumnSizes);
return ret;
}
|
C | double median(double x, double y, double z) {
double result;
if (x <= y) {
if (y <= z) result = y;
else if (x <= z) result = z;
else result = x;
}
if (z <= y) result = y;
if (x <= z) result = x;
result = z;
return result;
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <time.h>
#define GIGA pow(2, 30)
#define NANO 1e9
float dp(long, float *, float *);
int main(int argc, char * argv[])
{
// Declare and initialize vars.
long i;
float res = 0.;
// Parse command line args.
if (argc != 3)
{
printf("Usage: dp1 N M\n");
printf("N: Vector space dimension\n");
printf("M: Number of repetitions for the measurement\n");
exit(1);
}
long N = atol(argv[1]);
int M = atoi(argv[2]);
// Declare and initialize vecs.
float pA[N], pB[N];
for (i = 0; i < N; i++)
{
pA[i] = 1.;
pB[i] = 1.;
}
// Declare timespec structs and array to store exec. time measurements
struct timespec start, end;
double times[M];
// Measure exec. times and store measurements in secs.
for (i = 0; i < M; i++)
{
clock_gettime(CLOCK_MONOTONIC, &start);
res = dp(N, pA, pB);
clock_gettime(CLOCK_MONOTONIC, &end);
times[i] = (end.tv_sec - start.tv_sec) + ((end.tv_nsec - start.tv_nsec)/NANO);
}
// Compute avgerage exec. time and use the value to compute bandwidth and FLOPS in GB/sec. and GFLOPS, respectively
double avgTime = 0.;
for (i = M/2; i < M; i++)
avgTime += times[i];
avgTime /= (M/2);
double bw = (((double) N)*(2.*((double) sizeof(float))))/(avgTime*GIGA);
double flops = ((double) (N*2L))/(avgTime*GIGA);
// Print output
printf("N: %ld <T>: %f sec. B: %lf GB/sec. F: %lf GFLOPS result: %.3f\n", N, avgTime, bw, flops, res);
return 0;
}
// Function to benchmark
float dp(long N, float *pA, float *pB) {
float R = 0.0;
int j;
for (j=0;j<N;j++)
R += pA[j]*pB[j];
return R;
}
|
C | ////Includes //////////////////////////////////////////////////////
#include "BUTTON_IN.h"
#include "Button.h"
#include "Clock.h"
////Typedefs /////////////////////////////////////////////////////
typedef enum
{
BUTTON_EVENT_PRESS,
BUTTON_EVENT_HOLD,
BUTTON_EVENT_RELEASE,
BUTTON_EVENT_TYPE_MAX
} Button_Event_Type;
typedef struct
{
Button_Handler handler;
Button_Event_Type type;
bool call_handler;
uint32_t hold_duration;
} Button_Callback_Struct;
////Globals /////////////////////////////////////////////////////
////Local vars/////////////////////////////////////////////////////
static Button_Callback_Struct callbacks[BUTTON_CALLBACK_COUNT];
static bool button_state;
static uint32_t button_press_start_time;
static LDD_TDeviceData * button_in_data;
////Local Prototypes///////////////////////////////////////////////
int Find_Callback(Button_Handler handler);
bool Register_Callback(Button_Handler handler, Button_Event_Type type, uint32_t hold_duration);
void Unregister_Callback(Button_Handler handler);
bool Read_Button_State();
////Global implementations ////////////////////////////////////////
bool Button_Enable() {
bool rval = FALSE;
button_in_data = BUTTON_IN_Init(NULL);
button_state = BUTTON_IN_GetPortValue(button_in_data);
return rval;
}
void Button_Disable() {
BUTTON_IN_Deinit(button_in_data);
}
bool Button_Get_Status() {
#ifdef C6R2
button_state = (BUTTON_IN_GetPortValue(button_in_data) & BUTTON_IN_button_field_MASK) ? FALSE : TRUE; //c6r2 -- button active low
#else
button_state = (BUTTON_IN_GetPortValue(button_in_data) & BUTTON_IN_button_field_MASK) ? TRUE : FALSE; //c6r3 -- button active high
#endif
return button_state;
}
bool Button_Register_Press_Response(Button_Handler handler) {
return Register_Callback(handler, BUTTON_EVENT_PRESS, 0);
}
void Button_Unregister_Press_Response(Button_Handler handler) {
Unregister_Callback(handler);
}
bool Button_Register_Hold_Response(uint32_t duration_ms, Button_Handler handler) {
return Register_Callback(handler, BUTTON_EVENT_HOLD, duration_ms);
}
void Button_Unregister_Hold_Response(Button_Handler handler) {
Unregister_Callback(handler);
}
bool Button_Register_Release_Response(Button_Handler handler) {
return Register_Callback(handler, BUTTON_EVENT_RELEASE, 0);
}
void Button_Unregister_Release_Response(Button_Handler handler) {
Unregister_Callback(handler);
}
void Button_Event_Handler() {
//get_status updates button_state.
Button_Get_Status();
if (button_state) {
if (button_press_start_time == 0) {
button_press_start_time = Millis();
}
} else {
button_press_start_time = 0;
}
for (int i = 0; i < BUTTON_CALLBACK_COUNT; ++i) {
if (callbacks[i].handler != NULL) {
switch (callbacks[i].type) {
case BUTTON_EVENT_PRESS: { //TODO: update button_event_press to require that the button not be held.
if (button_state) {
callbacks[i].call_handler = TRUE;
}
break;
}
case BUTTON_EVENT_HOLD: {
if (button_state && (Millis() - button_press_start_time) > callbacks[i].hold_duration) {
callbacks[i].call_handler = TRUE;
}
break;
}
case BUTTON_EVENT_RELEASE: {
if (!button_state) {
callbacks[i].call_handler = TRUE;
}
break;
}
case BUTTON_EVENT_TYPE_MAX:
default: {
break;
}
}
}
}
}
void Button_Periodic_Call() {
//get_status updates button_state.
Button_Get_Status();
for (int i = 0; i < BUTTON_CALLBACK_COUNT; ++i) {
if (callbacks[i].call_handler) {
callbacks[i].handler();
callbacks[i].call_handler = FALSE;
} else if (button_state
&& callbacks[i].type == BUTTON_EVENT_HOLD
&& (Millis() - button_press_start_time) > callbacks[i].hold_duration) {
callbacks[i].handler();
}
}
}
////Local implementations ////////////////////////////////////////
int Find_Callback(Button_Handler handler) {
int rval = -1;
for (int i = 0; i < BUTTON_CALLBACK_COUNT; ++i) {
if (callbacks[i].handler == handler) {
rval = i;
}
}
return rval;
}
bool Register_Callback(Button_Handler handler, Button_Event_Type type, uint32_t hold_duration) {
bool rval = FALSE;
int open_index;
if (Find_Callback(handler) > 0) {
rval = TRUE;
} else {
open_index = Find_Callback(NULL);
if (open_index > 0) {
callbacks[open_index].handler = handler;
callbacks[open_index].type = type;
callbacks[open_index].hold_duration = hold_duration;
callbacks[open_index].call_handler = FALSE;
rval = TRUE;
} else {
rval = FALSE;
}
}
return rval;
}
void Unregister_Callback(Button_Handler handler) {
int open_index = Find_Callback(handler);
if (open_index > 0) {
callbacks[open_index].handler = NULL;
}
}
|
C |
#include "std_testcase.h"
#include <wchar.h>
void CWE476_NULL_Pointer_Dereference__char_54c_badSink(char * data);
void CWE476_NULL_Pointer_Dereference__char_54b_badSink(char * data)
{
CWE476_NULL_Pointer_Dereference__char_54c_badSink(data);
}
void CWE476_NULL_Pointer_Dereference__char_54c_cwe_fooSink(char * data);
void CWE476_NULL_Pointer_Dereference__char_54b_cwe_fooSink(char * data)
{
CWE476_NULL_Pointer_Dereference__char_54c_cwe_fooSink(data);
}
void CWE476_NULL_Pointer_Dereference__char_54c_cwe_barSink(char * data);
void CWE476_NULL_Pointer_Dereference__char_54b_cwe_barSink(char * data)
{
CWE476_NULL_Pointer_Dereference__char_54c_cwe_barSink(data);
}
|
C | #include<iostream>
#include<conio.h>
#define T 8
using namespace std;
using namespace System;
#define Ancho_Tablero 8
#define Alto_Tablero 8
#define Ficha_Blanca 'X'
#define Ficha_Negra 'O'
#define LIBRE ' '
#define Ancho_Caracter 3
struct Ficha {
int posC;
int posF;
char direccion;
char tipo; // (Derecha=D, Izquierda=I)
char color; //(Reina=R, Dama=D)
};
void Memoria_para_Tablero(char** Tablero, int nColumnas, int nFilas)
{
for (int f = 0; f < nFilas; f++)
{
Tablero[f] = new char[nColumnas];
}
}
void Inicializar_Tablero(char** Tablero, int nColumnas, int nFilas)
{
for (int f = 0; f < nFilas; f++)
for (int c = 0; c < nColumnas; c++)
{
Tablero[f][c] = LIBRE; //Espacio para cuadrcula libre
}
}
void Inicializar_Fichas(char** Tablero, int nColumnas, int nFilas)
{
//Fichas Negras
Tablero[0][1] = Ficha_Negra;
Tablero[0][3] = Ficha_Negra;
Tablero[0][5] = Ficha_Negra;
Tablero[0][7] = Ficha_Negra;
Tablero[1][0] = Ficha_Negra;
Tablero[1][2] = Ficha_Negra;
Tablero[1][4] = Ficha_Negra;
Tablero[1][6] = Ficha_Negra;
Tablero[2][1] = Ficha_Negra;
Tablero[2][3] = Ficha_Negra;
Tablero[2][5] = Ficha_Negra;
Tablero[2][7] = Ficha_Negra;
//Fichas Blancas
Tablero[5][0] = Ficha_Blanca;
Tablero[5][2] = Ficha_Blanca;
Tablero[5][4] = Ficha_Blanca;
Tablero[5][6] = Ficha_Blanca;
Tablero[6][1] = Ficha_Blanca;
Tablero[6][3] = Ficha_Blanca;
Tablero[6][5] = Ficha_Blanca;
Tablero[6][7] = Ficha_Blanca;
Tablero[7][0] = Ficha_Blanca;
Tablero[7][2] = Ficha_Blanca;
Tablero[7][4] = Ficha_Blanca;
Tablero[7][6] = Ficha_Blanca;
}
void Liberar_la_memoria_del_Tablero(char** Tablero, int nColumnas, int nFilas)
{
for (int f = 0; f < nFilas; f++)
{
delete[] Tablero[f];
}
delete[] Tablero;
}
void Imprimir_Tablero(char** Tablero, int nColumnas, int nFilas)
{
Console::Clear();
for (int f = 0; f < nFilas; f++)
{
for (int c = 0; c < nColumnas; c++)
{
if (f % 2 == 0)
{
if (c % 2 == 0)
{
Console::BackgroundColor = ConsoleColor::White;
}
else
{
Console::BackgroundColor = ConsoleColor::Black;
}
}
else
{
if (c % 2 == 0)
{
Console::BackgroundColor = ConsoleColor::Black;
}
else
{
Console::BackgroundColor = ConsoleColor::White;
}
}
// Imprimir los caracteres
cout.width(Ancho_Caracter);
if (Tablero[f][c] == Ficha_Blanca)
Console::ForegroundColor = ConsoleColor::White;
else
Console::ForegroundColor = ConsoleColor::Green;
cout << Tablero[f][c] << " ";
}
cout << endl;
}
}
void Mostrar_Menu_y_despues_la_opcion()
{
int opcionJuego;
string jugador1, jugador2;
cout << "------------------JUEGO DE DAMAS-----------------" << endl;
cout << "Programadores:" << endl;
cout << "Lorenzo Navarro Robles" << endl;
cout << "Bruno Robles Ayala" << endl;
cout << "Giuliana Sanchez Alvarez" << endl;
//Datos de los participantes
cout << "Inserte el nombre del primer jugador: "; cin >> jugador1;
cout << "Inserte el nombre del segundo jugador: "; cin >> jugador2;
//Opcin de juego
cout << "Elija el modo de Juego:" << endl << "1. Jugador1 vs Jugador2" << endl;
cout << "2. Jugador1 vs CPU" << endl << "3. CPU vs CPU" << endl; cin >> opcionJuego;
switch (opcionJuego)
{
case 1: system("cls");
cout << "opcion 1" << endl;
break;
case 2: system("cls");
cout << "opcion 2"<<endl;
break;
case 3: system("cls");
cout << "opcion 3"<<endl;
break;
}
}
int main()
{
Mostrar_Menu_y_despues_la_opcion();
int nColumnas = Ancho_Tablero; // Cantidad de filas
int nFilas = Alto_Tablero; // Cantidad de columnas
char** Tablero;
Tablero = new char* [nFilas];
Memoria_para_Tablero(Tablero, nColumnas, nFilas);
Inicializar_Tablero(Tablero, nColumnas, nFilas);
Inicializar_Fichas(Tablero, nColumnas, nFilas);
Imprimir_Tablero(Tablero, nColumnas, nFilas);
Liberar_la_memoria_del_Tablero(Tablero, nColumnas, nFilas);
_getch();
return 0;
}
|
C | /*
* Copyright (c) 2007 - 2014 Joseph Gaeddert
*
* This file is part of liquid.
*
* liquid 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.
*
* liquid 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 liquid. If not, see <http://www.gnu.org/licenses/>.
*/
//
// circular buffer
//
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "liquid.internal.h"
// linearize buffer (if necessary)
void CBUFFER(_linearize)(CBUFFER() _q);
// cbuffer object
struct CBUFFER(_s) {
// allocated memory array
T * v;
// length of buffer
unsigned int max_size;
// maximum number of elements that can be read at any given time
unsigned int max_read;
// number of elements allocated in memory
unsigned int num_allocated;
// number of elements currently in buffer
unsigned int num_elements;
// index to read
unsigned int read_index;
// index to write
unsigned int write_index;
};
// create circular buffer object of a particular size
CBUFFER() CBUFFER(_create)(unsigned int _max_size)
{
// create main object
CBUFFER() q = CBUFFER(_create_max)(_max_size, _max_size);
// return main object
return q;
}
// create circular buffer object of a particular size and
// specify the maximum number of elements that can be read
// at any given time.
CBUFFER() CBUFFER(_create_max)(unsigned int _max_size,
unsigned int _max_read)
{
// create main object
CBUFFER() q = (CBUFFER()) malloc(sizeof(struct CBUFFER(_s)));
// set internal properties
q->max_size = _max_size;
q->max_read = _max_read;
// internal memory allocation
q->num_allocated = q->max_size + q->max_read - 1;
// allocate internal memory array
q->v = (T*) malloc((q->num_allocated)*sizeof(T));
// reset object
CBUFFER(_clear)(q);
// return main object
return q;
}
// destroy cbuffer object, freeing all internal memory
void CBUFFER(_destroy)(CBUFFER() _q)
{
// free internal memory
free(_q->v);
// free main object
free(_q);
}
// print cbuffer object properties
void CBUFFER(_print)(CBUFFER() _q)
{
LOGI("cbuffer%s [max size: %u, max read: %u, elements: %u]\n",
EXTENSION,
_q->max_size,
_q->max_read,
_q->num_elements);
unsigned int i;
for (i=0; i<_q->num_elements; i++) {
LOGI("%u", i);
BUFFER_PRINT_LINE(_q,(_q->read_index+i)%(_q->max_size))
LOGI("\n");
}
}
// print cbuffer object properties and internal state
void CBUFFER(_debug_print)(CBUFFER() _q)
{
LOGI("cbuffer%s [max size: %u, max read: %u, elements: %u]\n",
EXTENSION,
_q->max_size,
_q->max_read,
_q->num_elements);
unsigned int i;
for (i=0; i<_q->max_size; i++) {
// print read index pointer
if (i==_q->read_index)
LOGI("<r>");
else
LOGI(" ");
// print write index pointer
if (i==_q->write_index)
LOGI("<w>");
else
LOGI(" ");
// print buffer value
BUFFER_PRINT_LINE(_q,i)
LOGI("\n");
}
LOGI("----------------------------------\n");
// print excess buffer memory
for (i=_q->max_size; i<_q->num_allocated; i++) {
LOGI(" ");
BUFFER_PRINT_LINE(_q,i)
LOGI("\n");
}
}
// clear internal buffer
void CBUFFER(_clear)(CBUFFER() _q)
{
_q->read_index = 0;
_q->write_index = 0;
_q->num_elements = 0;
}
// get the number of elements currently in the buffer
unsigned int CBUFFER(_size)(CBUFFER() _q)
{
return _q->num_elements;
}
// get the maximum number of elements the buffer can hold
unsigned int CBUFFER(_max_size)(CBUFFER() _q)
{
return _q->max_size;
}
// get the maximum number of elements that can be read from
// the buffer at any given time.
unsigned int CBUFFER(_max_read)(CBUFFER() _q)
{
return _q->max_read;
}
// return number of elements available for writing
unsigned int CBUFFER(_space_available)(CBUFFER() _q)
{
return _q->max_size - _q->num_elements;
}
// is buffer full?
int CBUFFER(_is_full)(CBUFFER() _q)
{
return (_q->num_elements == _q->max_size ? 1 : 0);
}
// write a single sample into the buffer
// _q : circular buffer object
// _v : input sample
void CBUFFER(_push)(CBUFFER() _q,
T _v)
{
// ensure buffer isn't already full
if (_q->num_elements == _q->max_size) {
LOGE("warning: cbuffer%s_push(), no space available\n",
EXTENSION);
return;
}
// add sample at write index
_q->v[_q->write_index] = _v;
// update write index
_q->write_index = (_q->write_index+1) % _q->max_size;
// increment number of elements
_q->num_elements++;
}
// write samples to the buffer
// _q : circular buffer object
// _v : output array
// _n : number of samples to write
void CBUFFER(_write)(CBUFFER() _q,
T * _v,
unsigned int _n)
{
// ensure number of samples to write doesn't exceed space available
if (_n > (_q->max_size - _q->num_elements)) {
LOGI("warning: cbuffer%s_write(), cannot write more elements than are available\n", EXTENSION);
return;
}
_q->num_elements += _n;
// space available at end of buffer
unsigned int k = _q->max_size - _q->write_index;
//LOGI("n : %u, k : %u\n", _n, k);
// check for condition where we need to wrap around
if (_n > k) {
memmove(_q->v + _q->write_index, _v, k*sizeof(T));
memmove(_q->v, &_v[k], (_n-k)*sizeof(T));
_q->write_index = _n - k;
} else {
memmove(_q->v + _q->write_index, _v, _n*sizeof(T));
_q->write_index += _n;
}
}
// remove and return a single element from the buffer
// _q : circular buffer object
// _v : pointer to sample output
void CBUFFER(_pop)(CBUFFER() _q,
T * _v)
{
// ensure there is at least one element
if (_q->num_elements == 0) {
LOGE("warning: cbuffer%s_pop(), no elements available\n",
EXTENSION);
return;
}
// set return value
if (_v != NULL)
*_v = _q->v[ _q->read_index ];
// increment read index
_q->read_index = (_q->read_index + 1) % _q->max_size;
// decrement number of elements in the buffer
_q->num_elements--;
}
// read buffer contents
// _q : circular buffer object
// _num_requested : number of elements requested
// _v : output pointer
// _nr : number of elements referenced by _v
void CBUFFER(_read)(CBUFFER() _q,
unsigned int _num_requested,
T ** _v,
unsigned int * _num_read)
{
// adjust number requested depending upon availability
if (_num_requested > _q->num_elements)
_num_requested = _q->num_elements;
// restrict maximum number of elements to originally specified value
if (_num_requested > _q->max_read)
_num_requested = _q->max_read;
// linearize tail end of buffer if necessary
if (_num_requested > (_q->max_size - _q->read_index))
CBUFFER(_linearize)(_q);
// set output pointer appropriately
*_v = _q->v + _q->read_index;
*_num_read = _num_requested;
}
// release _n samples in the buffer
void CBUFFER(_release)(CBUFFER() _q,
unsigned int _n)
{
// advance read_index by _n making sure not to step on write_index
if (_n > _q->num_elements) {
LOGI("error: cbuffer%s_release(), cannot release more elements in buffer than exist\n", EXTENSION);
return;
}
_q->read_index = (_q->read_index + _n) % _q->max_size;
_q->num_elements -= _n;
}
//
// internal methods
//
// internal linearization
void CBUFFER(_linearize)(CBUFFER() _q)
{
#if 0
// check to see if anything needs to be done
if ( (_q->max_size - _q->read_index) > _q->num_elements)
return;
#endif
//LOGI("cbuffer linearize: [%6u : %6u], num elements: %6u, read index: %6u, write index: %6u\n",
// _q->max_size, _q->max_read-1, _q->num_elements, _q->read_index, _q->write_index);
// move maximum amount
memmove(_q->v + _q->max_size, _q->v, (_q->max_read-1)*sizeof(T));
}
|
C | /**
* https://www.hackerrank.com/challenges/runningtime
*/
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
int n;
int aux;
int shift = 0;
int arraySize = 0;
int array[1001];
// Read de size of array
scanf("%d", &n);
// Iterate N times
while (n--) {
scanf("%d", &aux);
// Iterate over array to find the aux position
int position = arraySize;
for (; position > 0 && aux < array[position-1]; position--) {
array[position] = array[position-1];
shift++;
}
array[position] = aux;
arraySize++;
}
// Output the amount of shifts
printf ("%d\n", shift);
return 0;
}
|
C | #include <Foundation/FoundationInternal.h>
EZ_FOUNDATION_INTERNAL_HEADER
#if EZ_ENABLED(EZ_PLATFORM_64BIT)
// On 64-bit android platforms we can just use the posix implementation.
# include <Foundation/Time/Implementation/Posix/Timestamp_posix.h>
#else
// On 32-bit android platforms time.h uses 32bit time stamps. So we have to use time64.h instead
# include <time64.h>
const ezTimestamp ezTimestamp::CurrentTimestamp()
{
timeval currentTime;
gettimeofday(¤tTime, nullptr);
return ezTimestamp(currentTime.tv_sec * 1000000LL + currentTime.tv_usec, ezSIUnitOfTime::Microsecond);
}
bool operator!=(const tm& lhs, const tm& rhs)
{
if (lhs.tm_isdst == rhs.tm_isdst)
{
return !((lhs.tm_sec == rhs.tm_sec) && (lhs.tm_min == rhs.tm_min) && (lhs.tm_hour == rhs.tm_hour) && (lhs.tm_mday == rhs.tm_mday) &&
(lhs.tm_mon == rhs.tm_mon) && (lhs.tm_year == rhs.tm_year) && (lhs.tm_isdst == rhs.tm_isdst));
}
else
{
/// \todo check whether the times are equal if one is in dst and the other not.
/// mktime totally ignores your settings and overwrites them, there is no easy way
/// to check whether the times are equal when dst is involved.
/// mktime's dst *fix-up* will change hour, dst, day, month and year in the worst case.
return false;
}
}
const ezTimestamp ezDateTime::GetTimestamp() const
{
tm timeinfo = {0};
timeinfo.tm_sec = m_uiSecond; /* seconds after the minute - [0,59] */
timeinfo.tm_min = m_uiMinute; /* minutes after the hour - [0,59] */
timeinfo.tm_hour = m_uiHour; /* hours since midnight - [0,23] */
timeinfo.tm_mday = m_uiDay; /* day of the month - [1,31] */
timeinfo.tm_mon = m_uiMonth - 1; /* months since January - [0,11] */
timeinfo.tm_year = m_iYear - 1900; /* years since 1900 */
timeinfo.tm_isdst = 0; /* daylight savings time flag */
timeinfo.tm_zone = "UTC";
time64_t iTimeStamp = timegm64(&timeinfo);
// If it can't round trip it is assumed to be invalid.
tm timeinfoRoundtrip = {0};
if (gmtime64_r(&iTimeStamp, &timeinfoRoundtrip) == nullptr)
return ezTimestamp();
// mktime may have 'patched' our time to be valid, we don't want that to count as a valid date.
if (timeinfoRoundtrip != timeinfo)
return ezTimestamp();
iTimeStamp += timeinfo.tm_gmtoff;
// Subtract one hour if daylight saving time was activated by mktime.
if (timeinfo.tm_isdst == 1)
iTimeStamp -= 3600;
return ezTimestamp(iTimeStamp, ezSIUnitOfTime::Second);
}
ezResult ezDateTime::SetFromTimestamp(ezTimestamp timestamp)
{
tm timeinfo = {0};
time64_t iTime = (time64_t)timestamp.GetInt64(ezSIUnitOfTime::Second);
if (gmtime64_r(&iTime, &timeinfo) == nullptr)
return EZ_FAILURE;
m_iYear = timeinfo.tm_year + 1900;
m_uiMonth = timeinfo.tm_mon + 1;
m_uiDay = timeinfo.tm_mday;
m_uiHour = timeinfo.tm_hour;
m_uiMinute = timeinfo.tm_min;
m_uiSecond = timeinfo.tm_sec;
m_uiDayOfWeek = ezMath::MaxValue<ezUInt8>(); // TODO: no day of week exists, setting to uint8 max.
m_uiMicroseconds = 0;
return EZ_SUCCESS;
}
#endif
|
C | #include<stdio.h>
int main()
{
int a[4] = {1, 2, 3, 4};
int *p, (*P)[4];
P = a;
p = a;
printf("%d\n", a);
printf("%d\n", P);
printf("%d\n", *P);
printf("%d\n", **P);
printf("%d\n", P[1]);
printf("%d\n\n", &P);
printf("%d\n", p);
printf("%d\n", *p);
printf("%d\n", &p);
return 0;
}
|
C | /*-------------------------------------------------------------------------*/
/* jstickc.c Joy Stick Interface routines */
/* */
/* Author:Peter Savage Created:02-Jan-1992 */
/* jan 7,1993 - change Readjoystick to unsigned int -- Andy Stone */
/*-------------------------------------------------------------------------*/
#include <dos.h>
#include <stdio.h>
#include <bios.h>
#include <process.h>
#include <stdlib.h>
#include <string.h>
#include "jstick.h"
//#include "sound.h"
#define TRUE 1
#define FALSE 0
#define SLEEPTIME 5
static void InitConfigData(ConfigStruct *cs);
char joyinstall=FALSE;
/*****************************************************************************/
/* */
/* GetJoyPos function returns a joy stick position from 0 to 8, */
/* as well as any of the joystick buttons that are being pushed. */
/* */
/* This function requires that the joystruct structure has been */
/* loaded with this machies joy stick X and Y coordinates */
/* */
/* Joy Stick Position Map */
/* 1 */
/* 8 2 */
/* 7 0 3 */
/* 6 4 */
/* 5 */
/* Inputs/Outputs: */
/* pos - Pointer to a byte to return the joy stick position */
/* button - Pointer to a byte to return the pushed buttons */
/* js - Pointer to a loaded joy stick coordinates structure */
/* */
/* Call Format: */
/* GetJoyPos(&pos, &button, &js); */
/* */
/* Exception Conditions */
/* Error:No game port is installed on the machine */
/* pos - set to a value of -1 */
/* button - set to a value of -1 */
/* */
/*****************************************************************************/
void GetJoyPos(char far *pos, int far *button, ConfigStruct far *js)
{
unsigned int x=0;
unsigned int y=0;
unsigned int butn=0;
ReadJoyStick(&x,&y,&butn);
if ((y==0xFFFF)&(x==0xFFFF))
{ *pos=-1;}
if ((y>=js->joyy[1])&(y<=js->joyy[3])&(x>=js->joyx[1])&(x<=js->joyx[3]))
{ *pos=0; }
if ((y<=js->joyy[1])&(x>=js->joyx[1])&(x<=js->joyx[3]))
{ *pos=1; }
if ((y<=js->joyy[1])&(x>=js->joyx[3]))
{ *pos=2; }
if ((y>=js->joyy[1])&(y<=js->joyy[3])&(x>=js->joyx[3]))
{ *pos=3; }
if ((y>=js->joyy[3])&(x>=js->joyx[3]))
{ *pos=4; }
if ((y>=js->joyy[3])&(x>=js->joyx[1])&(x<=js->joyx[3]))
{ *pos=5; }
if ((y>=js->joyy[3])&(x>=js->joyx[0])&(x<=js->joyx[1]))
{ *pos=6; }
if ((y>=js->joyy[1])&(y<=js->joyy[3])&(x>=js->joyx[0])&(x<=js->joyx[1]))
{ *pos=7; }
if ((y<=js->joyy[1])&(x<=js->joyx[1]))
{ *pos=8; }
*button=butn;
}
int LoadConfigData(ConfigStruct *cs)
{
FILE *fp;
fp=fopen(CONFIGFILE,"rb");
if (fp==NULL) { InitConfigData(cs); return(FALSE); }
fread((unsigned char far *)cs, sizeof(ConfigStruct), 1, fp);
fclose(fp);
return(TRUE);
}
int SaveConfigData(ConfigStruct *cs)
{
FILE *fp;
fp=fopen(CONFIGFILE,"wb");
if (fp==NULL) return(FALSE);
fwrite((unsigned char far *)cs, sizeof(ConfigStruct), 1, fp);
fclose(fp);
return(TRUE);
}
static void InitConfigData(ConfigStruct *cs)
{
char *s;
int loop;
s = (char *) cs;
for (loop=0;loop<sizeof(ConfigStruct);loop++) s[loop]=0;
cs->ForceVGA = NoType;
cs->ForceSnd = None;
cs->SndInt = 7;
cs->SndPort = 0x220;
strcpy(cs->SndDrvr,"NotInit");
}
char InitJStick(void)
{
unsigned int joyxpos,joyypos,joybutn;
ReadJoyStick(&joyxpos,&joyypos,&joybutn); /* Read joystick, see if gameport */
if ((joyxpos!=0xFFFF)&&(joyypos!=0xFFFF)) /* or joystick exists on machine */
{
joyinstall=TRUE; /* Set joystick is installed flag*/
return(TRUE); /* Return Joystick installed */
}
joyinstall=FALSE; /* Set joystick not installed flag */
return(FALSE); /* Return not installed */
}
#pragma loop_opt(off)
void joyclearbuts(void)
{
unsigned int butn,x,y;
do
{
ReadJoyStick(&x,&y,&butn);
delay(SLEEPTIME);
} while (butn>0);
}
#pragma loop_opt(on)
|
C | #include "render_line.h"
#include "line.h"
#include "angle.h"
Render_Line create_render_line(Line *line)
{
Render_Line ret;
ret.line = line;
if (line->start.x != line->end.x)
{
double a = (line->end.y - line->start.y) / (line->end.x - line->start.x);
double b = line->start.y - a * line->start.x;
ret.a = a;
ret.b = b;
ret.angle = atan(a);
}
else
{
ret.a = INFINITY;
ret.b = INFINITY;
ret.angle = ANGLE_90;
}
return ret;
} |
C | // Copyright (c) 2017 , yogurt.yyj.
// All rights reserved.
//
// Filename: DFS.c
//
// Description:
//
// Version: 1.0
// Created: 2017/11/23 10时30分27秒
// Compiler: g++
//
// Author: yogurt (yyj), [email protected]
//
#include <string.h>
#include <stdio.h>
#define maxn 111
int vis[maxn][maxn]; // 用于标记一个位置是否被访问过
char mat[maxn][maxn]; // 保存迷宫
int tx, ty; // 终点T的横纵坐标
int sx, sy; // 起点S的横纵坐标
int arrival; // 标记是否可达T的标记变量
int n, m; // 迷宫的行数和列数
int dx[4] = {0, 0, 1, -1}; // 在每个位置可以走的四个方向
int dy[4] = {1, -1, 0, 0};
void dfs(int i, int j) {
if (i < 0 || i >= n || j < 0 || j >= m) return; //如果当前位置超出了边界
if (vis[i][j] || mat[i][j] == '#') return; // 或者当前位置已经来过,或者当前位置不可走,直接结束在当前位置的查找
vis[i][j] = 1; // 将当前位置标记为访问过
if (tx == i && ty == j) { // 如果当前位置与终点的坐标相同,表示从S可以到达这个位置
arrival = 1; return; // arrival 标记为1
}
int direct;
// 枚举在当前位置可以走的四个方向
for (direct = 0; direct < 4 && !arrival; ++direct) {
dfs(i + dx[direct], j + dy[direct]); // 递归得去四个方向接着寻找
}
}
int main() {
int i, j;
scanf("%d %d", &n, &m);
memset(vis, 0, sizeof(vis)); // 标记所有位置为未访问过
sx = sy = tx = ty = 0;
for (i = 0; i < n; ++i) {
scanf("%s", mat[i]);
for (j = 0; j < m; ++j) {
if (mat[i][j] == 'T') {
tx = i, ty = j; // 保存终点坐标
} else if (mat[i][j] == 'S') {
sx = i, sy = j; // 保存起点坐标
}
}
}
arrival = 0; // 标记变量初始化
dfs(sx, sy); // 从起点开始找
puts(arrival ? "Yes" : "No");
return 0;
}
|
C | /*
* tclUnixEvent.c --
*
* This file implements Unix specific event related routines.
*
* Copyright (c) 1997 by Sun Microsystems, Inc.
*
* See the file "license.terms" for information on usage and redistribution
* of this file, and for a DISCLAIMER OF ALL WARRANTIES.
*
* RCS: @(#) $Id: tclUnixEvent.c,v 1.1.1.1 2007/07/10 15:04:24 duncan Exp $
*/
#include "tclInt.h"
#include "tclPort.h"
/*
*----------------------------------------------------------------------
*
* Tcl_Sleep --
*
* Delay execution for the specified number of milliseconds.
*
* Results:
* None.
*
* Side effects:
* Time passes.
*
*----------------------------------------------------------------------
*/
void
Tcl_Sleep(ms)
int ms; /* Number of milliseconds to sleep. */
{
struct timeval delay;
Tcl_Time before, after;
/*
* The only trick here is that select appears to return early
* under some conditions, so we have to check to make sure that
* the right amount of time really has elapsed. If it's too
* early, go back to sleep again.
*/
Tcl_GetTime(&before);
after = before;
after.sec += ms/1000;
after.usec += (ms%1000)*1000;
if (after.usec > 1000000) {
after.usec -= 1000000;
after.sec += 1;
}
while (1) {
delay.tv_sec = after.sec - before.sec;
delay.tv_usec = after.usec - before.usec;
if (delay.tv_usec < 0) {
delay.tv_usec += 1000000;
delay.tv_sec -= 1;
}
/*
* Special note: must convert delay.tv_sec to int before comparing
* to zero, since delay.tv_usec is unsigned on some platforms.
*/
if ((((int) delay.tv_sec) < 0)
|| ((delay.tv_usec == 0) && (delay.tv_sec == 0))) {
break;
}
(void) select(0, (SELECT_MASK *) 0, (SELECT_MASK *) 0,
(SELECT_MASK *) 0, &delay);
Tcl_GetTime(&before);
}
}
|
C | #define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
int main()
{
int i = 1;
do
{
if (i == 5)
continue;
//break;
printf("%d ", i);
i++;
}
while (i < 10);
return 0;
}
//int main() {
// int i = 0;
// int k = 0;
// for (i = 0, k = 0;k = 0;i++, k++)
// {
// k++;
// }
//
// /*int x, y;
// for (x = 0, y = 0;x < 2 && y < 5;++x, y++)
// {
// printf("hehe\n");
// }*/
// return 0;
//}
//int main()
//{
// int count = 1;
// int i = 0;
// int j = 0;
// for (;i < 10;i++)
// {
// for (;j < 10;j++)//jֻѭһ֣Ժ10
// {
// printf("hehe %d\n",count);
// count++;
// }
// }
//
// //for (;;)//ѭ
// //{
// // printf("hehe\n");
// //}
//
//
// /*int arr[10] = { 1,2,3,4,5,6,7,8,9,10 };
// for (int i = 0;i < 10;i++)
// {
// printf("%d ", arr[i]);
// }*/
// return 0;
//}
////1-5
////6-7Ϣ
//int main()
//{
// //short day = 0;
// int day = 0;
// scanf("%d", &day);
// switch (day)
// {
// /*case 1:
// printf("һ\n");
// break;
// case 2:
// printf("ڶ\n");
// break;
// case 3:
// printf("\n");
// break;
// case 4:
// printf("\n");
// break;*/
// case 1:
// case 2:
// case 3:
// case 4:
//
// case 5:
// printf("\n");
// break;
// case 6:
// /*printf("\n");
// break;*/
// case 7:
// printf("\n");
// break;
// default :
// printf("\n");
// break;
// }
//
// return 0;
//}
//int main()
//{
// int n = 1;
// int m = 2;
// switch (n)
// {
// case 1:
// m++;
// case 2:
// n++;
// case 3:
// switch (n)
// {
// case 1:
// n++;
// case 2:
// m++;n++;
// break;
// }
// case 4:
// m++;
// break;
// default:
// break;
// }
// printf("%d %d\n", m, n);
// return 0;
//}
//int main()
//{
// int i = 1;
// while (i<=10)
// {
// if (i == 5)
// {
// //continue;//ѭ
// break;//ֹѭ
// }
// printf("%d\n",i);
// i++;
// }
// return 0;
//}
//int main()
//{
// int ch = getchar();//getcharӼ̻ȡһַ
// printf("%c\n", ch);
// return 0;
//}
/*int main()
{
int ch = 0;
while ((ch = getchar()) != EOF)
{
putchar(ch);
}
return 0;
}*/
//int main()
//{
// int ch = 0;
// char password[20] = { 0 };
// printf(":\n");
// scanf("%s", password);
// //ַ
// while ((getchar()) != '\n')
// {
// getchar();
// }
// printf("ȷ(Y/N):\n");
// //scanf("%c", & ch);
// ch = getchar();
// if ('Y' == ch)
// {
// printf("ȷϳɹ\n");
// }
// else
// printf("ȷ");
// return 0;
//
//}
//int main()
//{
// int i = 0;
// /*while (i < 10)
// {
// printf("%d ", i);
// i++;
// }*/
//// for (i = 0;i < 10;i++)
//// {
//// if (i == 5)
//// {
//// //continue;
//// break;
//// }
//// printf("%d ", i);
//// }
//// return 0;
////} |
C | /**
* Author: Daniel Coughran
* Date: 27/10/2017
* Purpose: encapsulate cd function, could be extended
* with related functionality if needed
* Param: Target Directory
**/
#include <stdlib.h>
#include <stdio.h>
void DoCd(char* dir){
printf("hit cd\n");
//system("cd %s", "Fuck this part doesnt work");
return;
}
/*int main()
{
//printf("files in directory are:\n");
DoCd("ThisWillError");
return(0);
}*/
|
C | // En una matriz de N x M enteros entre 1 y 10, contar numero de 3's
// Procesar por FILAS
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <sys/time.h>
main (int argc, char *argv[]) {
struct timeval ts, tf;
int i, j, N, M;
int **a;
int c = 0;
if (argc != 3) {printf ("USO: %s <dimX> <dimY>\n", argv[0]); exit (1);}
N = atoi(argv[1]);
M = atoi(argv[2]);
a = malloc (N * sizeof (int *));
if (a == NULL) { printf ("Memoria\n"); exit (1);}
for (i=0; i<N; i++) {
a[i] = malloc (M * sizeof (int));
if (a[i] == NULL) { printf ("Memoria\n"); exit (1);}
}
srandom (177845);
for (i=0; i<N; i++)
for (j=0; j<M; j++)
a[i][j] = random() % 10;
gettimeofday (&ts, NULL);
for (i=0; i<N; i++)
for (j=0; j<M; j++)
if (a[i][j] == 3)
c++;
gettimeofday (&tf, NULL);
printf ("TRES: %d (%f secs)\n", c, ((tf.tv_sec - ts.tv_sec)*1000000u +
tf.tv_usec - ts.tv_usec)/ 1.e6);
}
|
C | void error(int index)
{
switch(index)
{
case 0:
fprintf(error_txt, "第%d行:字符常量的字符非法;\n",line_count);
break;
case 1:
fprintf(error_txt, "第%d行:字符常量缺少右\' ;\n",line_count);
break;
case 2:
fprintf(error_txt, "第%d行:字符串过长;\n",line_count);
break;
case 3:
fprintf(error_txt, "第%d行:非法Token;\n",line_count);
break;
case 4:
fprintf(error_txt, "第%d行:缺少int/char的常量定义;\n",line_count);
break;
case 5:
fprintf(error_txt, "第%d行:源文件不完整;\n",line_count);
break;
case 6:
fprintf(error_txt, "第%d行:非0数不可以0开头;\n",line_count);
break;
case 7:
fprintf(error_txt, "第%d行:缺少\';\';\n",line_count);
break;
case 8:
fprintf(error_txt, "第%d行:缺少\'const\';\n",line_count);
break;
case 9:
fprintf(error_txt, "第%d行:int/char后缺少标识符;\n",line_count);
break;
case 10:
fprintf(error_txt, "第%d行:类型不匹配;\n",line_count);
break;
case 11:
fprintf(error_txt, "第%d行:缺少\'=\';\n",line_count);
break;
case 12:
fprintf(error_txt, "第%d行:0不该有符号;\n",line_count);
break;
case 13:
fprintf(error_txt, "第%d行:符号后缺少数字;\n",line_count);
break;
case 14:
fprintf(error_txt, "第%d行:存在重复定义的标识符;\n",line_count);
break;
case 15:
fprintf(error_txt, "第%d行:缺少\']\';\n",line_count);
break;
case 16:
fprintf(error_txt, "第%d行:数组元素个数应当为无符号整数;\n",line_count);
break;
case 17:
fprintf(error_txt, "第%d行:未定义的标识符;\n",line_count);
break;
case 18:
fprintf(error_txt, "第%d行:无法识别该语句;\n",line_count);
break;
case 19:
fprintf(error_txt, "第%d行:缺少\'}\';\n",line_count);
break;
case 20:
fprintf(error_txt, "第%d行:存在不期望的标识符;\n",line_count);
break;
case 21:
fprintf(error_txt, "第%d行:缺少\')\';\n",line_count);
break;
case 22:
fprintf(error_txt, "第%d行:期待一个字符而非字符串;\n",line_count);
break;
case 23:
fprintf(error_txt, "第%d行:函数声明头部定义错误;\n",line_count);
break;
case 24:
fprintf(error_txt, "第%d行:该函数缺少返回语句;\n",line_count);
break;
case 25:
fprintf(error_txt, "第%d行:该函数定义缺少\'{\';\n",line_count);
break;
case 26:
fprintf(error_txt, "第%d行:参数列表缺少类型标识符;\n",line_count);
break;
case 27:
fprintf(error_txt, "第%d行:有返回值的函数不可返回NULL;\n",line_count);
break;
case 28:
fprintf(error_txt, "第%d行:缺少\'(\';\n",line_count);
break;
case 29:
fprintf(error_txt, "第%d行:for循环条件有误;\n",line_count);
break;
case 30:
fprintf(error_txt, "第%d行:步长有误;\n",line_count);
break;
case 31:
fprintf(error_txt, "第%d行:\'scanf\'语句格式错误,期待标识符;\n",line_count);
break;
case 32:
fprintf(error_txt, "第%d行:无返回值函数无需返回;\n",line_count);
break;
case 33:
fprintf(error_txt, "第%d行:函数调用的参数个数或类型不匹配;\n",line_count);
break;
case 34:
fprintf(error_txt, "第%d行:主函数定义出错;\n",line_count);
break;
case 35:
fprintf(error_txt, "第%d行:主函数后有多余内容;\n",line_count);
break;
case 36:
fprintf(error_txt, "第%d行:赋值类型不匹配;\n",line_count);
break;
case 37:
fprintf(error_txt, "第%d行:缺少while;\n",line_count);
break;
case 38:
fprintf(error_txt, "第%d行:数组引用越界;\n",line_count);
break;
case 39:
fprintf(error_txt, "第%d行:有返回值的函数缺少返回语句;\n",line_count);
break;
}
error_flag = 1;
}
|
C | #include <stdio.h>
int main(void)
{
int nombres[] = {
1,
12,
123,
1234,
12345,
123456
};
printf("%6d%d\n", nombres[0], nombres[0]);
printf("%6d%d\n", nombres[1], nombres[1]);
printf("%6d%d\n", nombres[2], nombres[2]);
printf("%6d%d\n", nombres[3], nombres[3]);
printf("%6d%d\n", nombres[4], nombres[4]);
printf("%6d%d\n", nombres[5], nombres[5]);
} |
C | /* Author: Beat Hirsbrunner, University of Fribourg, July 2007 */
#include <stdio.h>
#include <ctype.h>
int getch(void);
void ungetch(int);
/* getint: get next integer from input into *pn --- kr97 */
/* and return -1 on EOF, 0 if the readed input is not a number, and a positive number otherwise */
int getint(int *pn)
{
int c, sign;
while (isspace(c = getch())) /* skip with space */
;
if (!isdigit(c) && c != EOF && c != '+' && c != '-')
{
ungetch(c); /* it's not a number */
return 0;
}
sign = (c == '-') ? -1 : 1;
if (c == '+' || c == '-')
c = getch();
for (*pn = 0; isdigit(c); c = getch())
*pn = 10 * *pn + (c - '0');
*pn *= sign;
if (c != EOF)
ungetch(c);
return c;
}
#define SIZE 7
main()
{
int array[SIZE];
int i, max, res;
/* Read input */
for (max=0;
max < SIZE && (res = getint(&array[max])) != EOF && res != 0;
max++)
;
printf("Readed integers: \n");
for (i=0; i < max; i++) printf("%d\n", array[i]);
printf("last return value of getint: %d\n", res);
}
/* ------------------------------------------- */
/* getch_ungetch "module" --------------- kr79 */
/* ------------------------------------------- */
#define BUFSIZE 100
char buf[BUFSIZE]; /* buffer for ungetch */
int bufp = 0; /* next free position in buf */
int getch(void) /* get a (possibly pushed back) character */
{
return (bufp > 0) ? buf[--bufp] : getchar();
}
void ungetch(int c) /* push character back on input */
{
if ( bufp >= BUFSIZE)
printf("ungetch: too many characters\n");
else
buf[bufp++] = c;
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include "colour.h"
#include "grade.h"
#include "ttt.h"
#include "employee.h"
int main(void)
{
/* Ex 15.1: Colour description */
/*
int n;
int i;
int r, g, b;
Colour c[N], average;
printf("Evaluating brightness of colours from their RGB values.\n");
printf("Enter the number of different colours: ");
scanf_s("%d", &n);
for (i = 0; i < n; i++)
{
printf("Give the RGB value of the %d-th colour: ", i);
scanf_s("%d%d%d", &r, &g, &b);
initColour(&c[i], r, g, b);
printColour(&c[i]);
}
printf("Average colour: ");
average = averageColour(c, n);
printColour(&average);
printf("\n\n");
*/
/* Ex 15.2: Averaging student's grades */
/*
printf("Now we're gonna average a student's grades: \n");
struct student std;
scanf_s("%d", &(std.count));
for (i = 0; i < std.count; i++)
{
scanf_s("%d", &(std.grade[i]));
}
printf("%f \n\n", average_grade(&std));
*/
/* Ex 15.4: Tictactoe */
printf("Here we start to play a tictactoe! \n");
TicTacToe ttt_game;
init(&ttt_game);
char mark; // choose 256: black & 128: middle gray
int x, y;
int validity;
printf("You're mark (enter o / x ): ");
scanf_s(" %c", &mark);
/*
do
{
printf("now it is color %d 's turn: \n", colour);
printf("indicate a position (x,y) to draw: ");
scanf_s("%d %d", &x, &y);
validity = play(&ttt_game, colour, x, y);
if (validity == -1)
{
printf("Game is over!!!\n\n");
}
if (colour == 255)
{
colour = 119;
}
else
{
colour = 255;
}
} while (win( &ttt_game, colour) == 0);
*/
while (1)
{
printf("now it is mark %c's turn: \n", mark);
printf("indicate a position (x,y) to draw: ");
scanf_s("%d %d", &x, &y);
validity = play(&ttt_game, mark, x, y);
displayBoard(&ttt_game);
if (validity == -1)
{
printf("Game is over!!!\n\n");
break;
}
if (win(&ttt_game, mark) == 1)
{
printf("Mark %c wins and game is over!\n\n", mark);
break;
}
if (mark == 'o')
{
mark = 'x';
}
else
{
mark = 'o';
}
}
printf("\n\n");
/* Ex 15.6: Relation between employees */
/*
printf("Here we want to determine the relation between any two employees in a company.\n");
int NumEmployees;
int k;
printf("number of employees ( do not exceed 20): ");
scanf_s("%d", &NumEmployees);
Employee staff[20];
for (k = 0; k < NumEmployees; k++)
{
printf("***the %d-th employee: \n", k);
printf("id: ");
scanf_s("%d", &(staff[k].id));
printf("first name: ");
scanf_s(" %s", staff[k].first_name, sizeof( staff[k].first_name) );
printf("last name: ");
scanf_s(" %s", staff[k].last_name, sizeof(staff[k].last_name));
printf("boss id: ");
scanf_s("%d", &(staff[k].boss_id));
}
for (k = 0; k < NumEmployees; k++)
{
printf("layer of the %d-th employee: %d \n", k, LayersCount(&staff[k], staff, NumEmployees));
}
*/
// to be completed
return 0;
}
|
C | /***************************************************************************
*
* Programmers and Purdue Email Addresses:
* 1. [email protected]
* 2. [email protected]
* 3. [email protected] (delete line if no third partner)
*
* Lab #: Lab 05
*
* Academic Integrity Statement:
*
* We have not used source code obtained from any other unauthorized source,
* either modified or unmodified. Neither have we provided access to our code
* to another. The project we are submitting is our own original work.
*
* Day, Time, Location of Lab: Tuesday, 3:30, SC289
*
* Program Description: This program computes the generated force, normal force,
* force of kinetic friction, and acceleration when given a seed by the user.
*
***************************************************************************/
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <fenv.h>
//Global Declarations
int getSeed(void);
int getRandom(void);
void displayOutput(int, int*, int, double*);
int main(void)
{
//Local Declarations
int seed; //Seed given by the user
int numAttempt = 1; //Initial attempt number
int range = 90; //Range values
int randomForce; //Random force generated by the seed
double offsetNumber = 0; //Offset Number
//Input Statements
seed = getSeed();
srand(seed);
randomForce = getRandom();
//Range Alternations
range = range + offsetNumber;
//Output Statements
displayOutput(range, &numAttempt, randomForce, &offsetNumber);
range = 90;
range = range + trunc(offsetNumber);
randomForce = getRandom();
displayOutput(range, &numAttempt, randomForce, &offsetNumber);
range = 90;
range = range + trunc(offsetNumber);
randomForce = getRandom();
displayOutput(range, &numAttempt, randomForce, &offsetNumber);
//Return Statement
return(0);
}
/***************************************************************************
*
* Function Information
*
* Name of Function: getSeed
*
* Function Return Type: int
*
* Parameters (list data type, name, and comment one per line):
* 1. void
*
* Function Description: This function recieves the seed input from the user
*
***************************************************************************/
int getSeed(void)
{
//Local Declarations
int inputSeed; //Input seed from the user
//Statements
printf("\nEnter seed value for random number generator -> ");
scanf("%d", &inputSeed);
//Return Statement
return(inputSeed);
} //End of getSeed
/***************************************************************************
*
* Function Information
*
* Name of Function: getRandom
*
* Function Return Type: int
*
* Parameters (list data type, name, and comment one per line):
* 1. int, seed, the seed value that was inputted by the user
*
* Function Description: This value generates a random number from the seed
* given by the user. This is used to compute random force.
*
***************************************************************************/
int getRandom (void)
{
//Local Declarations
int randomNumber; //Random Number generated by the seed
//Statements
randomNumber = rand() % 11;
//Return Statement
return (randomNumber);
} //End of getRandom
/***************************************************************************
*
* Function Information
*
* Name of Function: displayOutput
*
* Function Return Type: void
*
* Parameters (list data type, name, and comment one per line):
* 1. int, bottomRange, the bottom range of the attempt
* 2. int*, numAttempt, the attempt that the output is displaying
* 3. int, inputForce, the force generated by the random varaible
* 4. double*, offsetNumber, the offset number of the previous example to compute range
*
* Function Description: This function displays the outputs of the generated forces
*
***************************************************************************/
void displayOutput(int bottomRange, int* numAttempt, int inputForce, double* offsetNumber)
{
//Local Declarations
int generatedForce; //Calculated generated force
double normalForce; //Calculated normal force
double frictionKinetic; //Calculated frictionKinetic
double acceleration; //Calculated acceleration
//Calculations
generatedForce = bottomRange + inputForce;
normalForce = (20 * 9.8) - (generatedForce * sin(30 * (M_PI / 180)));
frictionKinetic = 0.5 * normalForce;
acceleration = ((generatedForce * cos(30 * (M_PI / 180)) - frictionKinetic) / 20);
*offsetNumber = trunc(*offsetNumber) + (20 * (0.5 - acceleration));
fesetround(FE_UPWARD); //Changing rounding to upward instead of the default setting of rouding for even numbers.
//Print Statements
printf("\nAttempt #: %d Range [%d, %d]", *numAttempt, bottomRange, (bottomRange + 10));
printf("\nGenerated Force: %d", generatedForce);
printf("\nNormal Force: %0.1lf", normalForce);
printf("\nForce of Kinetic Friction: %0.1lf", frictionKinetic);
printf("\nAcceleration: %0.2lf", acceleration);
printf("\nOffset for next attempt: %.0lf\n", trunc(*offsetNumber));
(*numAttempt)++;
//Return Statement
return;
}
|
C | char *substr_c(char *s1, char *s2) {
char *p1, *p2, *rv;
rv = 0;
while (*s1 != '\0') {
/* Loop over all characters in s1 */
p1 = s1;
p2 = s2;
while (*p1 != '\0' && *p2 != '\0' && (*p1 == *p2)) {
/* See if s2 is a substring here */
p1 += 1;
p2 += 1;
}
if (*p2 == '\0') {
rv = s1;
break;
}
s1 += 1;
}
return rv;
}
int matches_c(char *s1, char *s2) {
int count = 0;
char *next;
while (*s1 != '\0') {
if ((next = substr_c(s1, s2)) != 0) {
count += 1;
s1 = next + 1;
} else {
break;
}
}
return count;
}
|
C | #include <stdlib.h>
#include<stdio.h>
#include<stdbool.h>
#include "../inc/SetAssociative.h"
#include "../inc/HexToBin.h"
#include "../inc/BinToDec.h"
//Reads the data from the file and reports the hit and miss ratio (4 way set associative Cache)
void SetAssociative()
{
//Initialize the necessary parameters for computation
int SIZE = 16384, hit = 0, miss = 0;
int valid[SIZE][4], tag[SIZE][4];
for(int i = 0; i < SIZE; i++)
{
for(int j = 0; j < 4; j++)
{
valid[i][j] = 0;
}
}
char buff[15], hex[10];
int c = getc(fp);
//Compute the following operations till end of file
while(c != EOF)
{
int temp = 0;
//In this loop, take input char by char and store in in a char array (store a line in an array)
while(c != '\n' && c != EOF)
{
buff[temp++] = c;
c = getc(fp);
}
//Consider only the hexadecimal part of the line
for(int i = 0; i < 8; i++)
{
hex[i] = buff[4 + i];
}
char* address;
//Get the memory address in binary form
address = HexToBin(hex);
//Find the tag and index from the address
int tagNum = BinToDec(address, 0, 15);
int index = BinToDec(address, 16, 29);
int pos = -1;
bool present = false;
//For set associative, each row is assumed to be a priority queue (PRIORITY IS BASED ON LRU POLICY)
//Check if the tag is present or not
for(int i = 0; i < 4; i++)
{
if(valid[index][i] == 1 && tag[index][i] == tagNum)
{
hit++;
present = true;
pos = i; //Store the index of the tag
break;
}
}
//If the tag is present, put it at the end of the queue and update its priority
if(present == true)
{
//If the queue is full, shift some elements and move the tag to the end of the queue
if(valid[index][3] == 1)
{
for(int i = pos; i< 3; i++)
{
tag[index][i] = tag[index][i+1];
}
tag[index][3] = tagNum;
}
//If the queue is not full, put the tag at the end of the queue after shifting some elements in the queue
else
{
for(int i = pos; i < 3; i++)
{
if(valid[index][i+1] == 1)
{
tag[index][i] = tag[index][i+1];
}
else
{
tag[index][i] = tagNum;
break;
}
}
}
}
//If the tag is not present, insert the tag at the end of the queue
else
{
//If the queue is full, remove the first element and put the tag at the end after shifting all the elements
if(valid[index][3] == 1)
{
for(int i = 0; i < 3; i++)
{
tag[index][i] = tag[index][i+1];
}
tag[index][3] = tagNum;
}
else
{
//If the queue is not full, insert the tag at the end of the queue
for(int i = 0; i < 4; i++)
{
if(valid[index][i] == 0)
{
valid[index][i] = 1;
tag[index][i] = tagNum;
break;
}
}
}
miss++;
}
c = getc(fp);
}
//Find hit and miss ratio
float hitratio = (float)hit /(hit + miss);
float missratio = (float)miss /(miss + hit);
printf("\n\t\thit: %d\n\t\tmiss: %d\n\t\thit ratio: %f\n\t\tmiss ratio: %f\n", hit, miss, hitratio, missratio);
}
|
C | #include <stdio.h>
#include <stdlib.h>
#define CANT 5
int iniciarArray(int *pArray[], int limite, int valor);
int MostrarArray (int * pArray[], int limite);
int CargarEdad(int * pArray [], int limite);
int CargarNota1(int * pArray [], int limite);
int CargarNota2(int * pArray [], int limite);
int sumaArrays(int* pArray[],int limite,int* resultado);
int main()
{
int legajos[CANT];
int valorInicial=0;
int resulSumas=0;
int edad[CANT];
int nota1[CANT];
int nota2[CANT];
iniciarArray(legajos,CANT,valorInicial);
CargarEdad(edad,CANT);
MostrarArray(edad,CANT);
CargarNota1(nota1,CANT);
MostrarArray(nota1,CANT);
CargarNota2(nota2,CANT);
MostrarArray(nota2,CANT);
sumaArrays(nota1,CANT,resulSumas);
return 0;
}
int iniciarArray(int *pArray[], int limite, int valor)
{
int retorno = -1;
int i;
if(pArray != NULL && limite > 0)
{
for(i=0;i<limite;i++)
{
pArray[i]=valor;
}
retorno = 0;
}
return retorno;
}
int MostrarArray (int * pArray[], int limite)
{
int retorno= -1;
int i;
printf("\nDEBUG\n");
if(pArray != NULL && limite>0)//VALIDACION
{
for (i=0; i<limite; i++)
{
printf("\n %d",pArray[i]);
}
retorno=0;
}return retorno;
}
int CargarEdad(int * pArray [], int limite)
{
int retorno= -1;
int i;
int edad;
if(pArray != NULL && limite>0)//VALIDACION
{
for (i=0; i<limite; i++)
{
printf("\nIngrese la edad del alumno :");//TOMO EL NUMERO
scanf("%d",&edad);// LE DIGO QUE EDAD VA ESTAR GUARDADO COMO NUMERO
pArray[i]=edad;//GUARDO EL VALOR EN LOS INDICES DEL ARRAY
}
retorno=0;
}return retorno;
}
int CargarNota1(int * pArray [], int limite)
{
int retorno= -1;
int i;
int notaA;
if(pArray != NULL && limite>0)//VALIDACION
{
for (i=0; i<limite; i++)
{
printf("\nIngrese la 1er nota del alumno :");//TOMO EL NUMERO
scanf("%d",¬aA);// LE DIGO QUE VA ESTAR GUARDADO COMO NUMERO
pArray[i]=notaA;//GUARDO EL VALOR EN LOS INDICES DEL ARRAY
}
retorno=0;
}return retorno;
}
int CargarNota2(int * pArray [], int limite)
{
int retorno= -1;
int i;
int notaB;
if(pArray != NULL && limite>0)//VALIDACION
{
for (i=0; i<limite; i++)
{
printf("\nIngrese la 2da nota del alumno :");//TOMO EL NUMERO
scanf("%d",¬aB);// LE DIGO QUE VA ESTAR GUARDADO COMO NUMERO
pArray[i]= notaB;//GUARDO EL VALOR EN LOS INDICES DEL ARRAY
}
retorno=0;
}return retorno;
}
int sumaArrays(int* pArray[],int limite,int* resultado)
{
int res=0;
int i;
for (i=0; i<limite; i++)
{
res=res+pArray[i] ;
}
*resultado = res;
return 0;
}
|
C | /*
* seqsearch.c˳ʾ˳ҡ
* ߣCԼ(www.freecplus.net) ڣ20210325
*/
#include <stdio.h>
#include <string.h>
// IJұ˳ҡ
// sstableвkeyʧܷ-1ɹkeysstableе±ꡣ
int Seq_Search1(int *sstable,unsigned int len,int key)
{
int ii;
for (ii=0;ii<len;ii++) // ǰӺǰҶС
if (sstable[ii]==key) break; // ҵ˾break
if (ii==len) return -1; // ʧʱii==len
return ii;
}
/*
// IJұ˳Ҹд
// sstableвkeyʧܷ-1ɹkeysstableе±ꡣ
int Seq_Search1(int *sstable,unsigned int len,int key)
{
int ii;
for (ii=0;ii<len&&sstable[ii]!=key;ii++) // ǰӺǰҶС
;
return ii==len?-1:ii;
}
*/
// ڱIJұ˳ҡ
// sstableвkeyʧܷ0ɹkeysstableе±ꡣ
int Seq_Search2(int *sstable,unsigned int len,int key)
{
int ii;
sstable[0]=key; // ڱ
for (ii=len-1;sstable[ii]!=key;ii--) // Ӻǰҡ
; // ע䡣
return ii; // ҲʱiiΪ0
}
// IJұ˳ҡ
// sstableвkeyʧܷ-1ɹkeysstableе±ꡣ
int Seq_Search3(int *sstable,unsigned int len,int key)
{
int ii;
for (ii=0;ii<len;ii++) // ǰӺǰҶС
{
if (sstable[ii]==key) break; // ҵ˾break
if (sstable[ii] >key) return -1; // ˣ-1
}
if (ii==len) return -1; // ʧʱii==len
return ii;
}
// ԾķIJұ˳ҡ
// sstableвkeyʧܷ-1ɹkeysstableе±ꡣ
int Seq_Search4(int *sstable,unsigned int len,int key)
{
int ii=0;
while (ii<len && sstable[ii]<key) ii=ii+3; // ÿԾԪء
if (ii<len && sstable[ii]==key) return ii; // ҳɹ
else if (ii-1<len && sstable[ii-1]==key) return ii-1; // ҳɹ
else if (ii-2<len && sstable[ii-2]==key) return ii-2; // ҳɹ
return -1; // ʧܡ
}
int main()
{
// IJұ˳ҡ
int sstable1[]={2,5,6,3,1,7,4,8,9};
int len=sizeof(sstable1)/sizeof(int);
printf("result1=%d\n",Seq_Search1(sstable1,len,7));
printf("result1=%d\n",Seq_Search1(sstable1,len,15));
printf("result1=%d\n",Seq_Search1(sstable1,len,2));
printf("result1=%d\n",Seq_Search1(sstable1,len,9));
printf("\n");
// ڱIJұ˳ҡ
int sstable2[]={0,2,5,6,3,1,7,4,8,9};
len=sizeof(sstable2)/sizeof(int);
printf("result2=%d\n",Seq_Search2(sstable2,len,7));
printf("result2=%d\n",Seq_Search2(sstable2,len,15));
printf("result2=%d\n",Seq_Search2(sstable2,len,2));
printf("result2=%d\n",Seq_Search2(sstable2,len,9));
printf("\n");
// IJұ˳ҡ
int sstable3[]={1,2,3,4,5,6,7,8,9};
len=sizeof(sstable3)/sizeof(int);
printf("result3=%d\n",Seq_Search3(sstable3,len,7));
printf("result3=%d\n",Seq_Search3(sstable3,len,15));
printf("result3=%d\n",Seq_Search3(sstable3,len,1));
printf("result3=%d\n",Seq_Search3(sstable3,len,9));
printf("\n");
// ԾķIJұ˳ҡ
int sstable4[]={1,2,3,4,5,6,7,8,9};
len=sizeof(sstable4)/sizeof(int);
printf("result4=%d\n",Seq_Search4(sstable4,len,0));
printf("result4=%d\n",Seq_Search4(sstable4,len,7));
printf("result4=%d\n",Seq_Search4(sstable4,len,15));
printf("result4=%d\n",Seq_Search4(sstable4,len,1));
printf("result4=%d\n",Seq_Search4(sstable4,len,9));
printf("\n");
return 0;
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <conio.h>
main(){
float num1, num2, num3, mediaA, mediaH;
printf("Digite o primeiro valor \n");
scanf("%f", &num1);
printf("Digite o segundo valor \n");
scanf("%f", &num2);
printf("Digite o terceiro valor \n");
scanf("%f", &num3);
mediaA = (num1 + num2 + num3)/3;
mediaH = 3/((1/num1)+(1/num2)+(1/num3));
printf("Media aritimetica: %f", mediaA);
printf("\nMedia harmonica: %f ", mediaH);
system("pause");
}
|
C | #include <stdio.h>
int main()
{
int num;
int sum = 0;
int count = 0;
while(scanf("%d", &num) && num != -1)//һֱֱ-1
{
sum += num;
++count;
}
printf("%f", (double)sum / count);
system("pause");
return 0;
} |
C | #ifndef __LIST_STACK_H__
#define __LIST_STACK_H__
#include "interfaces.h"
#include <stdio.h>
#include <stdlib.h>
struct list_char
{
char ch;
struct list_char *prev;
};
struct list_int
{
int num;
struct list_int *prev;
};
void push(struct list_int **s, int x);
void pop(struct list_int **s, int *x);
void create(struct list_int **s);
int is_empty(struct list_int *s);
void pushc(struct list_char **s, char x);
void popc(struct list_char **s, char *x);
void createc(struct list_char **s);
int is_emptyc(struct list_char *s);
int need_free(struct list_int **q, struct list_char **w);
int WReadS(struct list_char **w, char **str_ptr);
void printSt(struct list_int *q);
void printStc(struct list_char *w);
void pushResult(char st_op, struct list_int **q);
int first_op_case(char **str_ptr, struct list_char **w, struct list_int **q, char *str);
#define DEPTH (5)
struct a_stack {
int n; //
int *array;
};
struct a_stackc {
int n; //
char *array;
};
void a_push(struct a_stack *s, int x);
void a_pop(struct a_stack *s, int *x);
void a_create(struct a_stack **s);
int a_is_empty(struct a_stack *s);
void a_pushc(struct a_stackc *s, char x);
void a_popc(struct a_stackc *s, char *x);
void a_createc(struct a_stackc **s);
int a_is_emptyc(struct a_stackc *s);
int a_need_free(struct a_stack **q, struct a_stackc **w);
int a_WReadS(struct a_stackc *w, char **str_ptr);
void a_printSt(struct a_stack *q);
void a_printStc(struct a_stackc *w);
void a_pushResult(char st_op, struct a_stack *q); //
int a_first_op_case(char **str_ptr, struct a_stackc **w, struct a_stack **q, char *str);
#endif |
C | #include <iostream>
using namespace std;
// 1+2+3+...+nʵַʽݹ顢ѭ
int AddFrom1ToN_Recursive(int n)
{
return n<=0 ? 0 : n + AddFrom1ToN_Recursive(n-1);
}
int AddFrom1ToN_Iterative(int n)
{
int result = 0;
for (int i = 0; i <= n ; ++i) {
result += i;
}
return result;
}
int main()
{
cout<<AddFrom1ToN_Recursive(100)<<endl;
cout<<AddFrom1ToN_Iterative(100)<<endl;
return 0;
} |
C | /*************************************************************************
*
* File: main.c
* Author: Jing Huang & Liang Wu
*
*
* Description: example compressors trying to compress files with
* adaptive Huffman coding.
*
************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <sys/stat.h>
#include <stdbool.h>
#include "huffman.h"
#include "timer.h"
int encodedFileLength;
/* create an input buffer for faster I/O */
#define IN_BUFSIZE 16384
unsigned char input_buf[ IN_BUFSIZE ];
unsigned int nread = 0, in_i = 0;
int GetFileLength(char *FileName)
{
struct stat statistics;
if (stat(FileName, &statistics) == -1) return 0;
return (int)statistics.st_size;
}
void Enc(void)
{
double WriteBytes, ReadBytes = 0;
int symbol;
double duration;
char InFileName[50] = "D:\\SJSU\\c++program\\tt\\AdaptiveHuffmanCoding\\061";
char OutFileName[50] = "D:\\SJSU\\c++program\\tt\\AdaptiveHuffmanCoding\\a";
FILE *InFile, *OutFile;
HUFFMANENCODER *HuffmanCoder;
encodedFileLength = GetFileLength(InFileName);
printf("Huffman Encoder 1.0 \n");
if ((InFile = fopen(InFileName, "rb")) == NULL)
{
printf("fail to open file %s.\n", InFileName);
exit(1);
}
if ((OutFile = fopen(OutFileName, "wb")) == NULL)
{
printf("fail to open file %s.\n", OutFileName);
exit(1);
}
HuffmanCoder = HuffmanEncoderAlloc(OutFile, 1);
StartTimer();
/*for ( ; ; )
{
symbol = getc(InFile);
if (symbol != EOF)
{
HuffmanEncoderEncode(HuffmanCoder, symbol);
}
else
{
//HuffmanEncoderEncode(HuffmanCoder, EndSymbol);
break;
}
ReadBytes += 1;
}*/
while( true )
{
/* load the input buffer. */
nread = fread( input_buf, 1, IN_BUFSIZE, InFile);
if ( nread == 0 ) break;
in_i = 0;
/* get bytes from the buffer and compress them. */
while( in_i < nread )
{
symbol = (unsigned char) *(input_buf + in_i);
++in_i;
if (symbol != EOF)
{
HuffmanEncoderEncode(HuffmanCoder, symbol);
}
else
{
//HuffmanEncoderEncode(HuffmanCoder, EndSymbol);
break;
}
ReadBytes += 1;
}
}
HuffmanEncoderFlush(HuffmanCoder);
StopTimer();
duration = ElapsedTime();
printf("Encode time: %lf\n", duration);
printf("ReadBytes : %d (%.3fk)\n", (int)ReadBytes, ReadBytes / 1024);
WriteBytes = HuffmanEncoderBytesWrite(HuffmanCoder);
printf("WriteBytes: %d (%.3fk)\n", (int)WriteBytes, WriteBytes / 1024);
printf("compression ratio: %.2f%%\n", (double) WriteBytes / ReadBytes * 100);
//printf("compression ratio: %.2f%%\n", (1 - WriteBytes / ReadBytes) * 100);
HuffmanEncoderDealloc(HuffmanCoder);
fclose(InFile);
fclose(OutFile);
printf("done.\n\n");
}
void Dec(void)
{
int symbol;
int length, count;
double duration;
char InFileName[50] = "D:\\SJSU\\c++program\\tt\\AdaptiveHuffmanCoding\\a";
char OutFileName[50] = "D:\\SJSU\\c++program\\tt\\AdaptiveHuffmanCoding\\062";
FILE *InFile, *OutFile;
HUFFMANDECODER *HuffmanDecoder;
printf("Huffman Decoder 1.0 \n");
length = GetFileLength(InFileName);
if ((InFile = fopen(InFileName, "rb")) == NULL)
{
printf("fail to open file %s.\n", InFileName);
exit(1);
}
if ((OutFile = fopen(OutFileName, "wb")) == NULL)
{
printf("fail to open file %s.\n", OutFileName);
exit(1);
}
count = 0;
HuffmanDecoder = HuffmanDecoderAlloc(InFile, 1);
StartTimer();
for ( ; ; )
{
symbol = HuffmanDecoderDecode(HuffmanDecoder);
count++;
putc(symbol, OutFile);
/*if (FGKDecoderBytesRead(HuffmanDecoder) == length )
{
break;
}*/
if(count == encodedFileLength)
{
break;
}
}
StopTimer();
duration = ElapsedTime();
printf("Decode time: %lf\n", duration);
HuffmanDecoderDealloc(HuffmanDecoder);
fclose(InFile);
fclose(OutFile);
printf("done.\n\n");
}
int main(int argc, char **argv)
{
Enc();
Dec();
return 0;
}
|
C | /* check the person is adult or not */
#include<stdio.h>
void main()
{
int a;
printf ("enter the Age ");
scanf("%d",&a);
if(a>=18)
{
printf("the person is adult");
}
else
{
printf("the person is miner");
}
} |
C | #include<stdio.h>
#include<conio.h>
void main()
{
float sum=0,a;
clrscr();
while(1)
{
printf("\n\nEnter the number and press 1000 to exit");
scanf("%f",&a);
if(a==1000)
goto bottom;
sum=sum+a;
printf("Sum=%f",sum);
}
bottom:getch();
}
|
C | #include <unistd.h>
int main(void)
{
//a função write pede três parâmetros = no caso usei 1 ali, pq quero um std-output. "a", escreverá a vogal a
//que pesa 1 byte. 1 depois é o número de bytes a serem usados. no caso, usa só 1, pra 1 letra.
write(1, "a", 1);
return (0);
}
|
C | #include <stdio.h>
#include <stdarg.h>
#include <time.h>
#include <string.h>
#include "irc_logger.h"
static void __get_time_str(char *buf);
void log_error(const char *fmt, ...)
{
char time_as_str[26];
va_list args;
va_start(args, fmt);
__get_time_str(time_as_str);
fprintf(stderr, "[%s error] ", time_as_str);
vfprintf(stderr, fmt, args);
va_end(args);
}
void log_info(const char *fmt, ...)
{
char time_as_str[26];
va_list args;
va_start(args, fmt);
__get_time_str(time_as_str);
fprintf(stdout, "[%s info] ", time_as_str);
vfprintf(stdout, fmt, args);
va_end(args);
}
static void __get_time_str(char *buf)
{
struct tm *tm;
time_t log_time;
log_time = time(NULL);
tm = localtime(&log_time);
strftime(buf, 26, "%Y-%m-%dT%H:%M:%S", tm);
}
|
C | /**
* \file main.c
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include "stream.h"
int ejpgl_main(stream_t *data_in, stream_t *data_out);
int main(int argc, char* argv[]) {
int ret;
FILE *infile, *outfile;
stream_t data_in, data_out;
struct stat file_status;
//Open input file:
if (stat(argv[1], &file_status) != 0) {
return 1;
}
// if (!S_ISREG(file_status)) {
// printf("BMP image %s is not a regular file\n", argv[1]);
// return 1;
// }
infile = fopen(argv[1], "rb");
if (infile == NULL) {
printf("Cannot open intput file %s\n", argv[1]);
return 1;
}
//Open output file:
outfile = fopen(argv[2], "wb");
if (outfile == NULL) {
printf("Cannot open output file %s\n", argv[2]);
return 1;
}
//Initialize streams:
data_in.size = file_status.st_size;
data_in.data = (byte_t *)malloc(file_status.st_size);
data_in.pos = data_in.data;
fread(data_in.data, sizeof(byte_t), file_status.st_size, infile);
data_out.data = (byte_t *)malloc(file_status.st_size);
data_out.pos = data_out.data;
data_out.size = 0;
ret = ejpgl_main(&data_in, &data_out);
fwrite(data_out.data, sizeof(byte_t), data_out.size, outfile);
free(data_in.data);
free(data_out.data);
return ret;
}
|
C | #include <stdio.h>
#define SIZE 10 /* Size of the array */
void printArray(int arr[]);
void rotateByOne(int arr[]);
int main()
{
int i, N;
int arr[SIZE];
printf("Enter 10 elements array: ");
for(i=0; i<SIZE; i++)
{
scanf("%d", &arr[i]);
}
printf("Enter number of times to left rotate: ");
scanf("%d", &N);
/* Actual rotation */
N = N % SIZE;
/* Print array before rotation */
printf("Array before rotationn");
printArray(arr);
/* Rotate array n times */
for(i=1; i<=N; i++)
{
rotateByOne(arr);
}
/* Print array after rotation */
printf("\n\nArray after rotation\n");
printArray(arr);
return 0;
}
void rotateByOne(int arr[])
{
int i, first;
/* Store first element of array */
first = arr[0];
for(i=0; i<SIZE-1; i++)
{
/* Move each array element to its left */
arr[i] = arr[i + 1];
}
/* Copies the first element of array to last */
arr[SIZE-1] = first;
}
/**
* Print the given array
*/
void printArray(int arr[])
{
int i;
for(i=0; i<SIZE; i++)
{
printf("%d ", arr[i]);
}
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <ctype.h>
#include "struct.h"
#include "main_player.h"
// Display error message for the error
ExitStatusPlayer exit_program(ExitStatusPlayer status)
{
const char *message = "";
switch (status) {
case Normal:
break;
case Arg:
message = "Usage: player pcount ID\n";
break;
case Pcount:
message = "Invalid player count\n";
break;
case PID:
message = "Invalid ID\n";
break;
case Path:
message = "Invalid path\n";
break;
case Early:
message = "Early game over\n";
break;
case Commu:
message = "Communications error\n";
break;
}
fprintf(stderr, "%s", message);
exit(status);
}
int convert_to_int(const char *string) {
if (!strlen(string)) {
return (-1);
}
for (int i = 0; i < strlen(string); i++) {
if (!isdigit(string[i])) {
return (-1);
}
}
return atoi(string);
}
struct Game *start_new_game(int argc, char **argv) {
if (argc != 3) {
exit_program(Arg);
}
int pcount = convert_to_int(argv[1]);
if (pcount < 1) {
exit_program(Pcount);
}
int id = convert_to_int(argv[2]);
if (id < 0 || id >= pcount) {
exit_program(PID);
}
struct Game *res = malloc(sizeof(struct Game));
res->pcount = pcount;
res->id = id;
res->players = malloc(sizeof(struct Player) * pcount);
int reachedLocationPosition = pcount - 1;
for (int p = 0; p < pcount; p++) {
res->players[p].index = p;
res->players[p].money = 7;
res->players[p].points = 0;
res->players[p].v1 = 0;
res->players[p].v2 = 0;
res->players[p].location = 0;
res->players[p].reachedLocationPosition = reachedLocationPosition;
reachedLocationPosition--;
memset(res->players[p].cards, 0, sizeof(int) * 5);
}
return res;
}
enum SiteTypes get_type(char first, char second) {
if (first == 'M' && second == 'o') {
return Mo;
}
if (first == 'R' && second == 'i') {
return Ri;
}
if (first == 'D' && second == 'o') {
return Do;
}
if (first == 'V' && second == '1') {
return V1;
}
if (first == 'V' && second == '2') {
return V2;
}
if (first == ':' && second == ':') {
return Barrier;
}
return Invalid;
}
void receive_path(struct Game *game) {
// "4;::-V14Do3::-"
char *path = malloc(80);
if (!fgets(path, 79, stdin)) {
// did not received path just got EOF
exit_program(Path);
}
path[strlen(path) - 1] = '\0';
int error;
int siteCount;
char sites[strlen(path)];
error = sscanf(path, "%d;%s", &siteCount, sites);
free(path);
if (error != 2 || siteCount < 2 || strlen(sites) != siteCount * 3) {
exit_program(Path);
}
game->siteCount = siteCount;
game->sites = malloc(sizeof(struct Site) * siteCount);
int pos = 0;
// "::-V14Do3::-"
for (int i = 0; i < strlen(sites); i += 3) {
char first = sites[i];
char second = sites[i + 1];
char third = sites[i + 2];
enum SiteTypes type = get_type(first, second);
if (type == Invalid || third == '0' || (!isdigit(third) && third != '-')) {
exit_program(Path);
}
int capacity = (isdigit(third)) ? ((int)(third - '0')) : game->pcount;
game->sites[pos].type = type;
game->sites[pos].capacity = capacity;
game->sites[pos++].players = 0;
}
// first and last site must be barrier
if (game->sites[0].type != Barrier ||
game->sites[siteCount - 1].type != Barrier) {
exit_program(Path);
}
game->sites[0].players = game->pcount;
}
void print_site(enum SiteTypes type) {
switch (type) {
case Mo:
fprintf(stderr, "Mo ");
break;
case Ri:
fprintf(stderr, "Ri ");
break;
case Do:
fprintf(stderr, "Do ");
break;
case V1:
fprintf(stderr, "V1 ");
break;
case V2:
fprintf(stderr, "V2 ");
break;
case Barrier:
fprintf(stderr, ":: ");
break;
case Invalid:
break;
}
}
bool is_all_players_printed(bool *printed, int pcount) {
for (int i = 0; i < pcount; i++) {
if (!printed[i]) {
return false;
}
}
return true;
}
void print_site_names(struct Site *sites, int siteCount) {
for (int i = 0; i < siteCount; i++) {
print_site(sites[i].type);
}
fputc('\n', stderr);
}
void print_state(struct Game *game) {
print_site_names(game->sites, game->siteCount);
bool printed[game->pcount];
memset(printed, 0, game->pcount * sizeof(bool));
while (!is_all_players_printed(&printed[0], game->pcount)) {
for (int i = 0; i < game->siteCount; i++) {
int player = (-1);
int reachedLocationPosition = game->pcount + 1;
for (int j = 0; j < game->pcount; j++) {
if (game->players[j].location == i && !printed[j]) {
if (game->players[j].reachedLocationPosition < reachedLocationPosition) {
player = j;
reachedLocationPosition = game->players[j].reachedLocationPosition;
}
}
}
if (player >= 0) {
fprintf(stderr, "%d ", player);
printed[player] = true;
} else {
fputs(" ", stderr);
}
}
fputc('\n', stderr);
}
}
void move_player_new_location(int player, int site, struct Game *game) {
struct Player *p = &game->players[player];
struct Site *current = &game->sites[p->location];
struct Site *newSite = &game->sites[site];
p->location = site;
current->players -= 1;
newSite->players += 1;
p->reachedLocationPosition = newSite->players;
}
bool valid_pnsmc(struct Player *player, struct Site *site, int score,
int money, int card) {
return ((site->players == site->capacity) ||
(score > 0 && site->type != Do) ||
(player->money > 1 && score <= 0 && site->type == Do) ||
(money < 0 && site->type != Do) ||
(money > 0 && site->type != Mo) ||
(money != 3 && site->type == Mo) ||
(card < 0 || card > 5) ||
(site->type == Ri && card == 0));
}
int get_points_money(struct Player *p) {
int money = p->money;
if ((money % 2) != 0) {
money -= 1;
}
int points = (money / 2);
return points;
}
void hap_message_handler(struct Game *game, char *pnsmc) {
int player, newSite, score, money, card;
int error = sscanf(pnsmc, "%d,%d,%d,%d,%d", &player, &newSite,
&score, &money, &card);
if (error != 5 || player < 0 || player >= game->pcount) {
exit_program(Commu);
}
struct Player *p = &game->players[player];
if (newSite <= p->location || newSite > game->siteCount) {
exit_program(Commu);
}
struct Site *s = &game->sites[newSite];
if (valid_pnsmc(p, s, score, money, card)) {
exit_program(Commu);
}
// here it looks like valid hap message
move_player_new_location(player, newSite, game);
p->money += money;
p->points += score;
switch (s->type) {
case Mo:
break;
case Ri:
p->cards[card - 1] += 1;
break;
case Do:
break;
case V1:
p->v1 += 1;
break;
case V2:
p->v2 += 1;
break;
case Barrier:
break;
case Invalid:
break;
}
fprintf(stderr, "Player %d Money=%d V1=%d V2=%d Points=%d A=%d B=%d C=%d D=%d E=%d\n",
player, p->money, p->v1, p->v2, p->points,
p->cards[0], p->cards[1], p->cards[2], p->cards[3],
p->cards[4]);
}
void game_loop(struct Game *game) {
while (true) {
char *dealerMessage = malloc(80);
if (!fgets(dealerMessage, 79, stdin)) {
free(dealerMessage);
exit_program(Commu);
}
dealerMessage[strlen(dealerMessage) - 1] = '\0';
if (!strcmp(dealerMessage, "EARLY")) {
free(dealerMessage);
exit_program(Early);
} else if (!strcmp(dealerMessage, "DONE")) {
free(dealerMessage);
break;
} else if (!strcmp(dealerMessage, "YT")) {
int choice = get_choice(game);
printf("DO%d\n", choice);
fflush(stdout);
} else if (!strncmp(dealerMessage, "HAP", 3)) {
char *pnsmc = dealerMessage + 3;
hap_message_handler(game, pnsmc);
print_state(game);
} else {
exit_program(Commu);
}
free(dealerMessage);
}
}
int get_set_of_cards(int *cards) {
int set = 0;
for (int i = 0; i < 5; i++) {
if (cards[i] > 0) {
cards[i] -= 1;
set += 1;
}
}
return set;
}
int calculate_card_score(struct Player *player) {
int score = 0;
while (true) {
int set = get_set_of_cards(&player->cards[0]);
if (set == 0) {
break;
} else if (set == 1) {
score += 1;
} else if (set == 2) {
score += 3;
} else if (set == 3) {
score += 5;
} else if (set == 4) {
score += 7;
} else {
score += 10;
}
}
return score;
}
int calculate_vsite_score(struct Player *player) {
int score = 0;
score += player->v1;
score += player->v2;
return score;
}
int calculate_score2(struct Player *player) {
int score = player->points;
score += calculate_card_score(player);
score += calculate_vsite_score(player);
return score;
}
int calculate_score(struct Player *player) {
int score = 0;
score += player->points;
score += player->v1;
score += player->v2;
while (true) {
int set = get_set_of_cards(&player->cards[0]);
if (set == 0) {
break;
} else if (set == 1) {
score += 1;
} else if (set == 2) {
score += 3;
} else if (set == 3) {
score += 5;
} else if (set == 4) {
score += 7;
} else {
score += 10;
}
}
return score;
}
void print_scores(struct Game *game) {
fprintf(stderr, "Scores: %d", calculate_score(&game->players[0]));
for (int i = 1; i < game->pcount; i++) {
fprintf(stderr, ",%d", calculate_score(&game->players[i]));
}
fputc('\n', stderr);
}
int main(int argc, char **argv) {
// player pcount id
struct Game *game = start_new_game(argc, argv);
fputc('^', stdout);
fflush(stdout);
receive_path(game);
print_state(game);
game_loop(game);
print_scores(game);
return Normal;
}
|
C | //открытие файла
#include "stdafx.h"
#include <windows.h>
#define MAX 10
struct person {
char *fname;
char *sname;
};
struct job {
struct person names;
char *jobs;
int id;
};
struct company {
struct job employer;
} IKEA[MAX];
int save_file();
int load_file();
int main(void)
{
SetConsoleCP(1251);
SetConsoleOutputCP(1251);
load_file();
return 0;
}
int save_file()
{
FILE* bd;
struct company* ptr;
ptr = IKEA;
if ((bd = fopen("Ikea.txt", "w+")) == NULL)
{
perror("Error openning file");
getchar();
return 1;
}
fprintf(bd, "--------Список сотрудников компании -------\n");
for (ptr = &IKEA[0]; ptr < &IKEA[MAX]; ptr++)
{
fprintf(bd, "Сотрудник: %s ", ptr->employer.names.fname);
fprintf(bd, "%s\n", ptr->employer.names.sname);
fprintf(bd, "Специальность: %s\n", ptr->employer.jobs);
fprintf(bd, "Порядковый номер: %d\n", ptr->employer.id);
fprintf(bd, "-------------------------------------------\n");
}
fclose(bd);
return 0;
}
int load_file()
{
FILE* bd;
char buffer[100];
char* ptr;
ptr = buffer;
if ((bd = fopen("Ikea.txt", "r+")) == NULL)
{
perror("Error openning file");
getchar();
return 1;
}
while (!feof(bd))
{
fgets(ptr, 1000, bd);
printf("%s", ptr);
}
fclose(bd);
return 0;
} |
C | /**
* @file searchOrdered.c Task to perform searches in ordered array
* @brief
* Load up an array of strings and perform number of ordered
* searches. No check for NULL is used.
*
* @author George Heineman
* @date 6/15/08
*/
#include <stdlib.h>
#include <string.h>
#include "report.h"
/**
* Problem: Linear search in an ordered array.
*
* Use insertion sort to properly order the elements.
* No check for NULL is used
*
*/
/** Array to contain final search structure. */
static char **ds;
/** Size of the array. */
static int dsSize;
/** Position into the array into which the next string is to be inserted. */
static int dsIdx;
/** construct the initial instance from the number of elements. */
void construct (int n) {
ds = (char **) calloc (n, sizeof (char **));
dsSize = n;
dsIdx = 0;
}
/** insert strings one at a time into its proper ordered spot within array. */
void insert (char *s) {
int i;
for (i = 0; i < dsIdx; i++) {
if (strcmp (ds[i], s) >= 0) {
/* insert here. */
memcpy (&ds[i+1], &ds[i], (dsIdx - i + 1)*sizeof(ds[i]));
ds[i] = s;
dsIdx++;
return;
}
}
/* add at the end! */
ds[dsIdx++] = s;
}
/** Search for the target within the linked list. */
int search (char *target, int(*cmp)(const void *,const void *)) {
int i;
for (i = 0; i < dsIdx; i++) {
int c = cmp(ds[i], target);
if (c == 0) {
return 1;
}
if (c == +1) { return 0;} /* too far! */
}
return 0; /* nope */
}
|
C | #include <stdio.h>
inline unsigned int test1(unsigned int a, unsigned int b)
{
unsigned int ret;
ret = a + b;
return ret;
}
static inline unsigned int test2(unsigned int a, unsigned int b)
{
unsigned int ret;
ret = a * b;
return ret;
}
int main(int argc, char const* argv[])
{
unsigned a, b;
a = test1(3, 6);
b = test2(2, 5);
/* printf("a=%d, b=%d\n", a, b);*/
return 0;
}
|
C | //PARAM: --set ana.activated[+] useAfterFree
#include <stdlib.h>
#include <stdio.h>
void *my_malloc(size_t size) {
return malloc(size);
}
void my_free(void *ptr) {
free(ptr);
}
void *my_malloc2(size_t size) {
return my_malloc(size);
}
void my_free2(void *ptr) {
my_free(ptr);
}
int main(int argc, char const *argv[]) {
char *p = my_malloc2(50 * sizeof(char));
*(p + 42) = 'c'; //NOWARN
printf("%s", p); //NOWARN
my_free2(p);
*(p + 42) = 'c'; //WARN
printf("%s", p); //WARN
char *p2 = p; //WARN
my_free2(p); //WARN
my_free2(p2); //WARN
return 0;
}
|
C | /*
* punto.c
*
* Created on: 8 abr. 2021
* Author: eneko
*/
#include "punto.h"
#include <math.h>
float distancia(Punto p1, Punto p2){
int restaX;
int restaY;
restaX = p1.x - p2.x;
restaY = p1.y - p2.y;
return sqrtf((powf(restaX,2)+powf(restaY,2)));
}
void trasladarXY(Punto *p1, Punto *p2, int x, int y){
p1->x= p1->x + x;
p2->x = p2->x + x;
p1->y = p1->y + y;
p2->y = p2->y + y;
}
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* draw.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: slimon <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/09/10 20:24:25 by slimon #+# #+# */
/* Updated: 2019/09/23 05:56:52 by slimon ### ########.fr */
/* */
/* ************************************************************************** */
#include "fdf.h"
static void setup_draw_line(t_draw_line *v, t_vec3f v1, t_vec3f v2,
t_vec3f *start)
{
v->dx = abs((int)v2.x - (int)v1.x);
v->dy = abs((int)v2.y - (int)v1.y);
v->sx = (int)v2.x > (int)v1.x ? 1 : -1;
v->sy = (int)v2.y > (int)v1.y ? 1 : -1;
v->err = (v->dx > v->dy ? v->dx : -v->dy) / 2;
start->x = v1.x;
start->y = v1.y;
start->color = v1.color;
}
static void draw_line(t_vec3f v1, t_vec3f v2, t_mlx *mlx)
{
int color;
t_draw_line v;
t_vec3f start;
setup_draw_line(&v, v1, v2, &start);
while (1)
{
color = ip_color(start, v2, (t_point){v.dx, v.dy},
(t_point){(int)v1.x, (int)v1.y});
mlx_pixel_put(mlx->ctx, mlx->win, (int)v1.x, (int)v1.y, color);
if ((int)v1.x == (int)v2.x && (int)v1.y == (int)v2.y)
break ;
v.err2 = v.err;
if (v.err2 > -v.dx)
{
v.err -= v.dy;
v1.x += v.sx;
}
if (v.err2 < v.dy)
{
v.err += v.dx;
v1.y += v.sy;
}
}
}
static void draw_edges(t_wireframe *model, t_mlx *mlx)
{
t_vec3f v1;
t_vec3f v2;
t_edge_table *edge_table_cur;
int i;
int num_edges;
edge_table_cur = model->edge_table_head;
num_edges = model->num_edges;
i = -1;
while (++i < num_edges)
{
v1 = (model->proj_verts[edge_table_cur->edge->v1_index]);
v2 = (model->proj_verts[edge_table_cur->edge->v2_index]);
if (v1.x >= 0 && v1.x < WIDTH && v1.y >= 0 && v1.y < HEIGHT &&
v2.x >= 0 && v2.x < WIDTH && v2.y >= 0 && v2.y < HEIGHT &&
v1.z >= -1 && v1.z <= 1 && v2.z >= -1 && v2.z <= 1)
draw_line(v1, v2, mlx);
edge_table_cur = edge_table_cur->next;
}
}
void draw(t_fdf *fdf)
{
t_mat44f mat_mvp;
t_mat44f mat_tmp;
t_mat44f mat_tmp2;
t_wireframe *model;
model = fdf->model;
set_model_transforms(model);
set_model_mat(model);
set_view_mat(model);
if (model->proj_type == 'p')
{
set_proj_mat(fdf);
mat_mult(model->proj_mat, model->view_mat, &mat_tmp);
mat_mult(&mat_tmp, model->model_mat, &mat_mvp);
mat_mult(&mat_mvp, model->model_transforms, &mat_tmp);
}
else
{
set_ortho_mat(fdf);
mat_mult(model->proj_mat, model->view_mat, &mat_tmp2);
mat_mult(&mat_tmp2, model->model_transforms, &mat_tmp);
}
proj_vertices(model, &mat_tmp, WIDTH * 0.5, HEIGHT * 0.5);
mlx_clear_window(fdf->mlx->ctx, fdf->mlx->win);
draw_edges(model, fdf->mlx);
}
|
C | #include <stdio.h>
#include <stdlib.h>
#define stackSize 5
typedef struct stack
{
int data;
struct stack *pBottom;
} myStack;
myStack*pTop;
myStack* creatStack(int data);
int push (int data);
int pop (int*data);
int dataLimit ;
int main()
{
printf("Hello World");
myStack cell;
push(5);
push(10);
push(30);
push(40);
push(50);
int data;
int i;
for (i=0;i<stackSize;i++)
{
if(pop(&data))
printf("%d\n",data);
else
printf("Empty\n");
}
return 0;
}
|
C | #include <stdio.h>
#define RECIPROCAL(number) (1.0 / (number))
int main() {
float counter; /* Counter for our table */
for (counter = 1.0; counter < 10.0;counter+= 1.0)
{
printf("1/%f = %f\n", counter, RECIPROCAL(counter));
}
return (0);
}
//CORREÇÃO:
//linha 2 o define criado nao estava assosiado a nenhum parametro, pois nao estava ligado, havia um espaçço
// => #define RECIPROCAL (number) (1.0 / (number)) => #define RECIPROCAL(number) (1.0 / (number))
|
C | /**
hind_brain.h
Purpose: Hindbrain libraries, constants, tuning parameters
@author Connor Novak
@email [email protected]
@version 0.0.1 19/02/24
*/
#ifndef HIND_BRAIN_H
#define HIND_BRAIN_H
// Libraries
#include <Servo.h> // ESC and Servo PWM control
#include <Arduino.h> // Used for Arduino functions
// Arduino Pins
const byte ESTOP_BUTTON_PIN = 3;
const byte STEER_SERVO_PIN = 5;
const byte VEL_SERVO_PIN = 6;
const byte ESTOP_LED_PIN = 13;
// General Constants
#define DEBUG True
#define WATCHDOG_TIMEOUT 250 // milliseconds
#define LED_BLINK_DELAY 750 // milliseconds
#define BAUD_RATE 9600 // Hz
#define DEBOUNCE_DELAY 500 // milliseconds
// Velocity Motor Ranges
const int VEL_CMD_MIN = 60; // ESC cmd for min speed
const int VEL_CMD_STOP = 91; // ESC cmd for 0 speed
const int VEL_CMD_MAX = 110; // ESC cmd for max speed (actual max 140)
const int VEL_MSG_MIN = -2; // Ackermann msg min speed
const int VEL_MSG_STOP = 0; // Ackermann msg 0 speed
const int VEL_MSG_MAX = 2; // Ackermann msg max speed
// Steering Motor Ranges
const int STEER_CMD_LEFT = 160; // Servo library cmd for max left turn
const int STEER_CMD_CENTER = 85; // Servo library cmd for straight
const int STEER_CMD_RIGHT = 35; // Servo library cmd for max right turn
const int STEER_MSG_LEFT = 45; // Ackermann msg min steering angle
const int STEER_MSG_CENTER = 0; // Ackermann msg center steering angle
const int STEER_MSG_RIGHT = -45; // Ackermann msg max steering angle
#endif
|
C | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <rays.h>
#include <constants.h>
#include <pthread.h>
#ifdef PARALLEL
#include <parallel_render.h>
#endif
#include "SDL.h"
uint8_t init();
SDL_Window *g_window = NULL;
SDL_Renderer *renderer = NULL;
uint8_t init() {
uint8_t success = 1;
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
printf("No se pudo inicializar SDL: %s\n", SDL_GetError());
return 0;
}
g_window = SDL_CreateWindow("Ray casting", SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
if (!g_window) {
printf("No se pudo crear la ventana: %s", SDL_GetError());
return 0;
}
return 1;
}
sphere* initialize_spheres(int n_spheres) {
sphere *s;
s = malloc(sizeof(sphere)*n_spheres);
// initialize random seed
time_t t;
srand((unsigned) time(&t));
for (int i = 0; i < n_spheres; i++) {
s[i].x = rand() % SCREEN_WIDTH;
s[i].y = rand() % SCREEN_HEIGHT;
s[i].z = rand() % SCREEN_WIDTH + 50;
// s[0]->z = 10.;
s[i].R = rand() % 255;
s[i].G = rand() % 255;
s[i].B = rand() % 255;
s[i].radius = s[i].z - s[i].z*0.1;
}
return s;
}
void sequential_render(int8_t *pixels, sphere *spheres, int n_spheres) {
for (int i = 0; i < SCREEN_HEIGHT * SCREEN_WIDTH; i++) {
const int x = i % (SCREEN_WIDTH);
const int y = i / (SCREEN_WIDTH);
const float current_value =
(float)i / (float)(SCREEN_WIDTH * SCREEN_HEIGHT);
const int c_i = (x + y*SCREEN_WIDTH)*4;
ray *r = malloc(sizeof(ray));
r->x = x;
r->y = y;
r->z = 0.;
r->k = 5001.;
r->alive = 1;
color *c = ray_marching(r, spheres, n_spheres);
pixels[c_i + 0] = c->R;
pixels[c_i + 1] = c->G;
pixels[c_i + 2] = c->B;
pixels[c_i + 3] = SDL_ALPHA_OPAQUE;
free(c);
free(r);
}
}
int main(int argc, char *argv[]) {
if (argc != 2) {
printf("Debe ingresar la cantidad de esferas\n");
return EXIT_FAILURE;
}
int n_spheres = atoi(argv[1]);
if (!init()) {
printf("No se pudo inicializar\n");
return EXIT_FAILURE;
}
#ifdef PARALLEL
printf("nthreads: %d\n", N_THREADS);
#endif
SDL_Renderer *renderer = SDL_CreateRenderer(g_window, -1,
SDL_RENDERER_SOFTWARE);
// Texture used for the 3d world simulation
SDL_Texture *texture = SDL_CreateTexture(renderer,
SDL_PIXELFORMAT_ABGR8888, SDL_TEXTUREACCESS_STREAMING,
SCREEN_WIDTH, SCREEN_HEIGHT);
int8_t *pixels = malloc(
SCREEN_WIDTH * SCREEN_HEIGHT * 4 * sizeof(int8_t));
uint8_t running = 1;
SDL_Event event;
sphere *spheres = initialize_spheres(n_spheres);
#ifdef PARALLEL
pthread_t threads[N_THREADS];
#endif
uint32_t iters = 0;
while(running && iters++ < 100) {
uint64_t start = SDL_GetPerformanceCounter();
SDL_SetRenderDrawColor(renderer, 0, 0, 0, SDL_ALPHA_OPAQUE);
SDL_RenderClear(renderer);
while(SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT) {
running = 0;
break;
}
}
#ifdef PARALLEL
parallel_render(pixels, spheres, n_spheres, threads);
#else
sequential_render(pixels, spheres, n_spheres);
#endif
SDL_UpdateTexture(texture, NULL, &pixels[0], SCREEN_WIDTH * 4);
SDL_RenderCopy(renderer, texture, NULL, NULL);
SDL_RenderPresent(renderer);
// calculation of frames per second.
uint64_t end = SDL_GetPerformanceCounter();
const double freq = (double)SDL_GetPerformanceFrequency();
const float secs = (float)(end - start) /(freq);
printf("%f\n", 1/(secs));
}
SDL_DestroyTexture(texture);
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(g_window);
free(spheres);
SDL_Quit();
return EXIT_SUCCESS;
}
|
C |
void ChangePWM() //
{
// - 976 16 1
TCCR1A = 0b00000001; // 8bit
TCCR1B = 0b00001011; // x64 fast pwm
// - 976 - 8 2
TCCR2B = 0b00000011; // x64
TCCR2A = 0b00000011; // fast pwm
}
/* 8 8 255
// - 62.5
TCCR0B = 0b00000001; // x1
TCCR0A = 0b00000011; // fast pwm
// - 31.4
TCCR0B = 0b00000001; // x1
TCCR0A = 0b00000001; // phase correct
// - 7.8
TCCR0B = 0b00000010; // x8
TCCR0A = 0b00000011; // fast pwm
// - 4
TCCR0B = 0b00000010; // x8
TCCR0A = 0b00000001; // phase correct
// - 976 -
TCCR0B = 0b00000011; // x64
TCCR0A = 0b00000011; // fast pwm
// - 490
TCCR0B = 0b00000011; // x64
TCCR0A = 0b00000001; // phase correct
// - 244
TCCR0B = 0b00000100; // x256
TCCR0A = 0b00000011; // fast pwm
// - 122
TCCR0B = 0b00000100; // x256
TCCR0A = 0b00000001; // phase correct
// - 61
TCCR0B = 0b00000101; // x1024
TCCR0A = 0b00000011; // fast pwm
// - 30
TCCR0B = 0b00000101; // x1024
TCCR0A = 0b00000001; // phase correct
*/
/* 16 8 255
// - 62.5
TCCR1A = 0b00000001; // 8bit
TCCR1B = 0b00001001; // x1 fast pwm
// - 31.4
TCCR1A = 0b00000001; // 8bit
TCCR1B = 0b00000001; // x1 phase correct
// - 7.8
TCCR1A = 0b00000001; // 8bit
TCCR1B = 0b00001010; // x8 fast pwm
// - 4
TCCR1A = 0b00000001; // 8bit
TCCR1B = 0b00000010; // x8 phase correct
// - 976
TCCR1A = 0b00000001; // 8bit
TCCR1B = 0b00001011; // x64 fast pwm
// - 490 -
TCCR1A = 0b00000001; // 8bit
TCCR1B = 0b00000011; // x64 phase correct
// - 244
TCCR1A = 0b00000001; // 8bit
TCCR1B = 0b00001100; // x256 fast pwm
// - 122
TCCR1A = 0b00000001; // 8bit
TCCR1B = 0b00000100; // x256 phase correct
// - 61
TCCR1A = 0b00000001; // 8bit
TCCR1B = 0b00001101; // x1024 fast pwm
// - 30
TCCR1A = 0b00000001; // 8bit
TCCR1B = 0b00000101; // x1024 phase correct
*/
/*
ATmega328p
Arduino
Timer0 8 31 1 32 258 1 CHANNEL_A D6 PD6
CHANNEL_B D5 PD5
Timer1 16 0.11 1 9 000 000 1 CHANNEL_A D9 PB1
CHANNEL_B D10 PB2
Timer2 8 31 1 32 258 1 CHANNEL_A D11 PB3
CHANNEL_B D3 PD3
ATmega2560
Arduino
Timer0 8 31 1 32 258 1 CHANNEL_A 13 PB7
CHANNEL_B 4 PG5
Timer1 16 0.11 1 9 000 000 1 CHANNEL_A 11 PB5
CHANNEL_B 12 PB6
CHANNEL_C 13 PB7
Timer2 8 31 1 32 258 1 CHANNEL_A 10 PB4
CHANNEL_B 9 PH6
Timer3 16 0.11 1 9 000 000 1 CHANNEL_A 5 PE3
CHANNEL_B 2 PE4
CHANNEL_C 3 PE5
Timer4 16 0.11 1 9 000 000 1 CHANNEL_A 6 PH3
CHANNEL_B 7 PH4
CHANNEL_C 8 PH5
Timer5 16 0.11 1 9 000 000 1 CHANNEL_A 46 PL3
CHANNEL_B 45 PL4
CHANNEL_C 44 PL5
*/ |
C | #ifndef ISTACK
#define ISTACK
#define INITIAL_CAPACITY 5
#define SCALING_FACTOR 2
typedef char* element;
typedef struct {
int capacity;
int top;
element *elements;
} stack;
stack *new_stack();
stack *create_stack( const int );
void destroy_stack( stack * );
stack *resize( stack *, const int );
int empty( const stack * );
void push( stack *, element );
element pop( stack * );
element peek( stack * );
void pretty_print( const stack * );
#endif
|
C | #include <stdio.h>
#include <time.h>
#define N 50000
float m[N][N];
int main()
{
float a = 0.0;
clock_t s, f;
s = clock();
for (int n = 0; n < 100; ++n)
for (int i = 0; i < N; ++i)
for (int j = 0; j < N; ++j)
a += m[i][j];
f = clock();
printf("%f: %f ms\n", a, ((double)(f - s)) * 1000.0 / CLOCKS_PER_SEC);
return 0;
} |
C | void main(int n) {
int i = 0;
int j;
for (i=0; i<n; i=i+1) {
print i;
for(j=0; j<i; j=j+1) {
print j;
}
}
}
// i=0;
// for (i=0; i < n ; i=i+1) {
// print i;
// for (j=0; j<n; j=j+1) {
// print j;
// if (j == 2) {
// break;
// }
// }
// if (i == 2) {
// break;
// }
// }
|
C | #include "dataset.h"
#include "dbg.h"
#define MAX_LINE_LENGTH BUFSIZ
void dataset_init(Dataset *data, FILE *data_file) {
VECTOR_INIT(data->ex);
size_t attribute_count = 0, last_attribute_count = 0;
FILE *string_stream;
float attribute_value;
char linha[MAX_LINE_LENGTH];
while (fgets(linha, MAX_LINE_LENGTH, data_file) != NULL) {
if (linha[0] != '%') {
if (last_attribute_count != 0 && last_attribute_count != attribute_count) {
log_err("datasets with missing attributes not supported.\n\
current attribute count: %zd\n\
last attribute count: %zd",\
attribute_count, last_attribute_count);
exit(1);
}
attribute_count = 0;
string_stream = fmemopen(linha, strlen(linha), "r");
while (fscanf(string_stream, "%f", &attribute_value) == 1) {
attribute_count++;
fgetc(string_stream);
VECTOR_APPEND(data->ex, attribute_value);
}
last_attribute_count = attribute_count;
fclose(string_stream);
}
}
if (!feof(data_file)) {
log_err("fgets returned NULL before EOF.");
exit(1);
}
data->nat = attribute_count;
data->nex = VECTOR_SIZE(data->ex) / attribute_count;
}
inline void dataset_free(Dataset *data) {
VECTOR_FREE(data->ex);
}
|
C | int sum(int *arr, int length){
int ret = 0;
for (int i = 0; i < length; i++){
ret += arr[i];
}
return ret;
}
|
C | #include "Oalloc.h" // "Once alloc", for allocating tons of little integers via pointers
#include "../blant.h"
#include "../blant-output.h"
#include "../blant-utils.h"
#include "blant-predict.h"
#include "htree.h"
#include "rand48.h"
#include <math.h>
#include <signal.h>
#include <ctype.h>
#include <unistd.h>
// Watch memory usage
#include <sys/time.h>
#include <sys/resource.h>
// Reasonable Defaults for a Mac with 16GB RAM since it's too much trouble to find the real values.
static double MAX_GB, totalGB = 16; //, freeGB = 8, MAX_GB;
#define GB (1024.0*1024.0*1024.0)
typedef sig_t sighandler_t;
#if __APPLE__
#define RUSAGE_MEM_UNIT 1L
#define SYSINFO_MEM_UNIT 1L
#else
#include <sys/sysinfo.h>
#if __WIN32__ || __CYGWIN__
#define SYSINFO_MEM_UNIT 4096L // 4k unit???
#define RUSAGE_MEM_UNIT 4096L // 4k page
#else
#define SYSINFO_MEM_UNIT info.mem_unit
#define RUSAGE_MEM_UNIT info.mem_unit
#endif
#endif
void CheckRAMusage(void)
{
static struct rusage usage;
static int status;
#if !__APPLE__
static struct sysinfo info;
status = sysinfo(&info);
assert(status == 0);
//Note("RAW sysinfo data: totalram %ld freeram %ld\n", info.totalram, info.freeram);
totalGB = info.totalram*1.0*SYSINFO_MEM_UNIT/GB;
//freeGB = info.freeram*1.0*SYSINFO_MEM_UNIT/GB;
#endif
MAX_GB=totalGB-4; //MIN(totalGB/2, freeGB-4); // at most half the machine's RAM, and leaving at least 4GB free
if(!usage.ru_maxrss) Note("System claims to have totalram %g GB; aiming to use MAX %g GB",
totalGB, MAX_GB);
status = getrusage(RUSAGE_SELF, &usage);
assert(status == 0);
//Note("RAW rusage data: res %ld drss %ld srss %ld", usage.ru_maxrss, usage.ru_idrss, usage.ru_isrss);
if(usage.ru_maxrss*RUSAGE_MEM_UNIT/GB > MAX_GB || (usage.ru_idrss+usage.ru_isrss)*RUSAGE_MEM_UNIT/GB > MAX_GB)
{
double new=usage.ru_maxrss*(double)RUSAGE_MEM_UNIT/GB;
static double previous;
if(new > 1.1*previous) {
#if !__APPLE__
status = sysinfo(&info);
//freeGB = info.freeram*SYSINFO_MEM_UNIT/GB;
#endif
Warning("WARNING: Resident memory usage has reached %g GB", new);
previous = new;
}
_earlyAbort=true;
}
}
/* General note: when associating any pair of nodes (u,v) in the large graph G, with "canonical orbit pairs" in
** canonical graphlets, the number of possible combination is so incredibly enormous and sparse, that even hashing
** was too wasteful of memory. Thus I moved to storing the associations for *each* pair (u,v) in one binary tree.
** Thus for G with n nodes, there are potentially (n choose 2) distinct binary trees, each holding the list
** of canonical orbit pair associations and the respective count. Basically for a 10,000 node graph, and using
** k=8, there are almost a quarter million possible orbit pairs... so the total number of possible *associations*
** between any (u,v) in G and any canonical node pair is (n choose 2) * 244,000 ... and for n=10,000 nodes, that's
** 1.2 x 10^13 associations... each of which must have a *count* (potentially requiring 32 bits), for a total
** of 5e13 bytes=50 TB. So not feasible, and even a hash table (which is sparsely stored to reduce collisions)
** was requiring >100GB to store these associations. A Binary tree is a bit slower but requires far less RAM.
*/
// Note for the PredictGraph we actually use an HTREE--heirarchical Tree, where the first key is the
// orbit pair (o,p) from graphlet K, and the second key is any edge in any graphlet K; we then use the
// total number of edges from G seen in any graphlet K to compute the weight of u:v's o:p orbit pair.
static HTREE ***_PredictGraph; // lower-triangular matrix (ie., j<i, not i<j) of dictionary entries
static BINTREE *_predictiveOrbits; // if non-NULL, any orbit not in this dictionary is ignored.
// Is is there anything in _PredictGraph[i][j]?
#define PREDICT_GRAPH_NON_EMPTY(i,j) (_PredictGraph[i][j] && _PredictGraph[i][j]->tree->root)
// This is a hack that's required for parallelism: technically we only need to output the *final* counts once
// we've accumulated them. But if we're a child process just shunting those counts off to a parent process who's
// accumulating these counts globally, it turns out that it's expensive for the parent, and if we wait until the
// end to provide our output then the parent is sitting around twiddling its thumbs until the end, and is suddenly
// inundated with expensive parsing. So instead, if we're a child process, every fraction of a second (0.1s seems
// best), we spit out our accumulation so far so the parent can parse them online. This Boolean is set to true each
// 0.1s, and below we check it to see if it's time to flush our counts.
static Boolean _flushCounts = true;
// Signal handler for the SIGALRM that occurs periodically forcing us to flush our counts to a parent (if we're _child).
int AlarmHandler(int sig)
{
//assert(_child && !_flushCounts);
//fprintf(stderr, "Alarm in process %d\n", getpid());
alarm(0);
CheckRAMusage();
if(_child) _flushCounts = true;
signal(SIGALRM, (sighandler_t) AlarmHandler);
alarm(1); // set alarm for 1 second hence
return 0;
}
// Allocate the NULL pointers for just the *rows* of the PredictGraph[i].
void Predict_Init(GRAPH *G) {
int i;
assert(_PredictGraph==NULL);
// This just allocates the NULL pointers, no actual binary trees are created yet.
_PredictGraph = Calloc(G->n, sizeof(HTREE**)); // we won't use element 0 but still need n of them
for(i=1; i<G->n; i++) _PredictGraph[i] = Calloc(i, sizeof(HTREE*));
char *predictive = getenv("PREDICTIVE_ORBITS");
if(predictive) {
int numPredictive=0;
_predictiveOrbits = BinTreeAlloc((pCmpFcn) strcmp, (pFointCopyFcn) strdup, (pFointFreeFcn) free, NULL, NULL);
// Is it a string containing orbits, or a filename?
char *s = predictive;
// The only characters allowed in orbit lists are digits, spaces, and colons.
while(*s && (isdigit(*s) || isspace(*s) || *s == ':')) s++;
if(*s) { // we found an invalid orbit-descriptor character; assume it's a filename
FILE *fp = Fopen(predictive,"r");
char buf[BUFSIZ];
while(1==fscanf(fp,"%s",buf)) {
++numPredictive;
BinTreeInsert(_predictiveOrbits, (foint) buf, (foint) NULL);
}
fprintf(stderr, "Read %d predictive orbits from file %s\n", numPredictive, predictive);
} else { // we got to the end of the string, it's a raw list of orbits
FILE *fp = fopen(predictive,"r");
if(fp) Fatal("PREDICTIVE_ORBITS <%s> looks like a list of orbits but there's also a file by that name", predictive);
fprintf(stderr, "Reading $PREDICTIVE_ORBITS: <%s>\n", predictive);
s=predictive;
while(*s)
{
while(isspace(*s)) s++; // get past whitespace
if(!*s) break;
predictive = s;
while(*s && !isspace(*s)) s++; // get to next whitespace
if(isspace(*s)) *s++ = '\0'; // terminate the string
++numPredictive;
BinTreeInsert(_predictiveOrbits, (foint) predictive, (foint) NULL);
}
fprintf(stderr, "Read %d orbits from $PREDICTIVE_ORBITS\n", numPredictive);
}
}
if(_child) {
signal(SIGALRM, (sighandler_t) AlarmHandler);
alarm(1); // (int)(2*_MAX_THREADS*drand48())); // on average, have one child per second send data to the parent process
}
}
/*
** Our ultimate goal is: for a pair of nodes (u,v) and an orbit pair (o,p), count the number of distinct quadruples
** (q,r,x,y) where (q,r)!=(o,p) is an edge, and (x,y) is an edge in G also !=(u,v). NOTE: after some experimentation
** it may be sufficient to ignore (q,r) and only count the edges (x,y) in G.
**
** In the case that we can ignore (q,r), it's fairly easy: our "count only" version creates one sorted binary
** tree for each (u,v) pair in G, with the tree sorted on the key (o,p) represented as a string, and with the data
** member being an integer count. Adding (x,y) into the mix is easy: instead of the data member being a count, it'll
** be *another* binary tree using the key (x,y), and *that* binary tree will have no data member. Then the count for
** (u,v,o,p) is simply the number of entries in the (u,v)->(o,p) binary tree, ie the number of unique (x,y) keys in it.
**
** To use a binary tree for the more complex case, we *could* do it as follows: for each (u,v) and each (o,p), have a
** separate binary tree--which multiplies our number of binary tree by (k choose 2)--and then in each such binary tree,
** keep track of the number of distinct keys (q,r,x,y); we wouldn't even need a data member, we just need to count
** distinct keys, which would be B->n. [THIS IS HOW WE ACTUALLY DO IT, using an HTREE.]
** If we wanted to be more clever, we could do some clever encoding. (We won't unless saving memory becomes crucial.)
** Note that (o,p,q,r) has exactly (k choose 2)^2 possible values [or just (k choose 2) if we ignore (q,r).].
** At k=8 that's only 784 [28] possible values, and we only need to remember a BOOLEAN of each.
** Thus, we'll represent whether we've seen (o,p,q,r) as a SET*, which will require
** about 100 [4] bytes total. Given (o,p,q,r) we'll convert (o,p) to int via creating an empty TinyGraph, adding (o,p),
** then op=TinyGraphToInt; same with (q,r) giving qr; finally opqr=op*(k choose2) + qr.
** Then, to fully encode the (u,v,o,p,q,r,x,y) octuplet [sextuplet], we'll keep the _PredictGraph[u][v]
** binary trees, but now the *key* will simply be "x:y", the "internal edge", and then the octuplet [sextuplet]
** can be queried as: key = BinaryTreeLookup(PG[u][v], "x:y"); SET *uvxy=(SET*) key; and finally SetAdd(uvxy,opqr).
** Finally retrieving and printing the output will require, for each (u,v) pair, to traverse its binary
** tree across all (x,y) pairs, accumulating sum[qr] += !!SetIn(uvxy, opqr) (!! to ensure it's 0 or 1).
** In English, that's saying: for a given (u,v) pair, its value at CNP (o,p) is the sum, across all (x,y)
** edges that have been observed in the same sampled graphlet, of [1 if ignoring qr, or] whether (x,y) has
** appeared at CNP (q,r). (1 if yes, 0 if no).
*/
#define COUNT_uv_only 1 // this works OK but COUNT_xy_only may work better
#if COUNT_uv_only
// These two are mutually exclusive
#define DEG_WEIGHTED_COUNTS 1
#define COMMON_NEIGHBORS 0
#if (DEG_WEIGHTED_COUNTS && COMMON_NEIGHBORS)
#error cannot have both (DEG_WEIGHTED_COUNTS && COMMON_NEIGHBORS)
#endif
#else
#define COUNT_xy_only 1 // count unique [xy] edges only; othewise include both q:r and x:y; edges only seems to work best.
#endif
#define DEG_ORDER_MUST_AGREE 1 // This sometimes gives great improvement, and sometimes not. Not sure what to do...
#ifdef COUNT_xy_only
// This function is only used if we want to see how many times each xy edge has been seen--but it doesn't seem necessary.
Boolean Traverse_xy(foint key, foint data) {
if(!COUNT_xy_only) Apology("!COUNT_xy_only not yet implemented");
char *ID = key.v;
printf("(x:y)=%s %g",ID, data.f);
return true;
}
#endif
/* TraverseNodePairCounts is called indirectly via BinTreeTraverse, which prints *all* the currently stored
** participation counts of a particular pair of nodes (u,v) in G. This function is called on each such
** participation count, and it simply prints the k:o:p canonical orbit pair, and its weight (|xy|), to stdout.
*/
Boolean TraverseNodePairCounts(foint key, foint data) {
char *ID = key.v;
#if COUNT_uv_only
printf("\t%s %g",ID, data.f);
#else // seems to be the same output whether or not COUNT_xy_only, since it's the ID that distinguishes them.
BINTREE *op_xy = data.v;
printf("\t%s %d",ID, op_xy->n);
//BinTreeTraverse(op_xy, Traverse_xy); // only if we want to the count of each edge or (q,r,x,y) quad.
#endif
return true;
}
/* Loop across all pairs of nodes (u,v) in G, and for each pair, print one line that contains:
** the pair of nodes, the edge truth, and all the participation counts.
*/
void PredictFlushAllCounts(GRAPH *G){
alarm(0); // turn off _flushCounts alarm
int i,j;
for(i=1; i < G->n; i++) for(j=0; j<i; j++) {
if(PREDICT_GRAPH_NON_EMPTY(i,j)) // only output node pairs with non-zero counts
{
printf("%s %d", PrintNodePairSorted(i,':',j), GraphAreConnected(G,i,j));
BinTreeTraverse(_PredictGraph[i][j]->tree, TraverseNodePairCounts);
puts("");
}
}
}
static void UpdateNodePair(int G_u, int G_v, char *ID, double count); // Prototype; code is below
// TraverseCanonicalPairs is called via BinaryTreeTraverse to traverse all the known associations between a particular pair
// of nodes in a canonical graphlet, in order to transfer that information to a a pair of nodes from a sampled graphlet in G.
// (A new traversal is constructed for every pair of nodes in the sampled graphlet.)
// This functions' job is to transfer that info to global node pairs in G called (G_u,G_v).
// The pair of nodes (G_u,G_v) in G must be global since there's no other mechanism to get that info here.
static int _TraverseCanonicalPairs_G_u, _TraverseCanonicalPairs_G_v; // indices into _PredictGraph[G_u][G_v]
static char *_TraverseCanonicalPairs_perm; // canonical permutation array for the current sampled graphlet...
static unsigned *_TraverseCanonicalPairs_Varray; // ...and the associated Varray.
static double _TraverseCanonicalPairs_weight; // degree-based weight of interior nodes
static Boolean TraverseCanonicalPairs(foint key, foint data) {
char *ID = key.v; // ID is a *string* of the form k:o:p[[q:r]:x:y], where (o,p) is the canonical orbit pair.
int *pCanonicalCount = data.v; // the count that this (o,p) pair was seen at (u,v) during canonical motif enumeration.
static char ID2[BUFSIZ], ID3[BUFSIZ];
#if COUNT_uv_only // the tail end of the ID string contains either x:y (COUNT_xy_only) or q:r:x:y (otherwise)
strcpy(ID3, ID); // make a copy so we can nuke bits of it.
#else // the tail end of the ID string contains either x:y (COUNT_xy_only) or q:r:x:y (otherwise)
strcpy(ID2, ID); // make a copy so we can nuke bits of it.
int q,r, IDlen = strlen(ID);
q = *(ID+IDlen-3)-'0';
r = *(ID+IDlen-1)-'0';
assert(0<=q && 0 <= r && q<_k && r<_k);
// x and y in the non-canonical motif g that is induced from G
int g_x=_TraverseCanonicalPairs_perm[q], g_y=_TraverseCanonicalPairs_perm[r];
int G_x=_TraverseCanonicalPairs_Varray[g_x], G_y=_TraverseCanonicalPairs_Varray[g_y]; // x and y in BIG graph G.
if(g_x < g_y) { int tmp = g_x; g_x=g_y; g_y=tmp; } // lower triangle of g
if(G_x < G_y) { int tmp = G_x; G_x=G_y; G_y=tmp; } // for consistency in accessing _PredictGraph
char *pColon = (ID2+IDlen-4); // prepare to nuke the : before q:r
assert(*pColon == ':'); *pColon = '\0';
#if COUNT_xy_only
sprintf(ID3, "%s:%d:%d", ID2, G_x,G_y); // becomes k:o:p:x:y, where x and y are from G (not g)
#else
sprintf(ID3, "%s:%d:%d:%d:%d", ID2, q,r,G_x,G_y); // k:o:p:q:r:x:y
#endif
#endif
UpdateNodePair(_TraverseCanonicalPairs_G_u, _TraverseCanonicalPairs_G_v, ID3,
*pCanonicalCount * _TraverseCanonicalPairs_weight);
return true;
}
// Given a pair of nodes (u,v) in G and an association ID, increment the (u,v) count of that association by the count
// of the ID. Note that unless COUNT_uv_only is true, this function is *only* used during merge mode (-mq).
static void UpdateNodePair(int G_u, int G_v, char *ID, double count) {
foint fUVassoc; // either a count, or a pointer to either a count or sub-binary tree.
if(G_u<G_v) { int tmp=G_u; G_u=G_v;G_v=tmp;}
if(_PredictGraph[G_u][G_v] == NULL)
_PredictGraph[G_u][G_v] = HTreeAlloc(1+!COUNT_uv_only); // depth 1 if COUNT_uv_only, or 2 for any COUNT_*xy
char buf[BUFSIZ], *IDarray[2];
IDarray[0] = strcpy(buf,ID);
#if !COUNT_uv_only
// find the 3rd colon so we can isolate k:o:p from [q:r:]x:y
int i, G_x,G_y;
char *s=buf;
for(i=0;i<3;i++)while(*s++!=':') ;
assert(*--s==':'); *s++='\0';
#if PARANOID_ASSERTS && COUNT_xy_only
assert(2==sscanf(s,"%d:%d",&G_x,&G_y)); assert(G_x > G_y);
#endif
IDarray[1] = s; // the string [q:r:]x:y
#endif
if(HTreeLookup(_PredictGraph[G_u][G_v], IDarray, &fUVassoc))
fUVassoc.f += count;
else
fUVassoc.f = count;
HTreeInsert(_PredictGraph[G_u][G_v], IDarray, fUVassoc);
#if PARANOID_ASSERTS
float newValue = fUVassoc.f;
assert(HTreeLookup(_PredictGraph[G_u][G_v], IDarray, &fUVassoc) &&
(/*(fUVassoc.f==0 && newValue==0) ||*/ fabs(fUVassoc.f - newValue)/newValue < 1e-6));
#endif
//printf("P %s %s %g (%g)\n", PrintNodePairSorted(G_u,':',G_v), ID, count, fUVassoc.f);
}
/* This function is used to merge the types of lines above (u:v edge, k:g:i:j count, etc) from several
** sources. It processes one line to figure out the node pair, and all the participation counts, and
** then adds that data to the internal tally, which will later be printed out. Used either when -mp mode
** is invoked with multi-threading (-t N) or in predict_merge mode (-mq).
** NOTE ON EFFICIENCY: it may be more efficient to use built-in functions like strtok or scanf but I
** couldn't esaily get them to work so decided to hack it together myself. It's NOT particularly efficient
** and could probably be improved. (I think the BinaryTree stuff is not the bottleneck, it's the code
** right here.)
*/
void Predict_ProcessLine(GRAPH *G, char line[])
{
assert(!_child);
if(line[strlen(line)-1] != '\n') {
assert(line[strlen(line)-1] == '\0');
Fatal("char line[%s] buffer not long enough while reading child line in -mp mode",line);
}
char *s0=line, *s1=s0;
foint fu, fv;
int G_u, G_v;
char *nameGu, *nameGv;
if(_supportNodeNames) {
while(*s1!=':') s1++; *s1++='\0'; nameGu=s0; s0=s1;
while(*s1!=' ') s1++; *s1++='\0'; nameGv=s0; s0=s1;
if(!BinTreeLookup(G->nameDict, (foint)nameGu, &fu)) Fatal("PredictMerge: node name <%s> not in G", nameGu);
if(!BinTreeLookup(G->nameDict, (foint)nameGv, &fv)) Fatal("PredictMerge: node name <%s> not in G", nameGv);
G_u = fu.i; G_v = fv.i;
//printf("Found names <%s> (int %d) and <%s> (int %d)\n", nameGu, G_u, nameGv, G_v);
}
else {
while(isdigit(*s1)) s1++; assert(*s1==':'); *s1++='\0'; G_u=atoi(s0); s0=s1;
while(isdigit(*s1)) s1++; assert(*s1==' '); *s1++='\0'; G_v=atoi(s0); s0=s1;
}
assert(0 <= G_u && G_u < G->n);
assert(0 <= G_v && G_v < G->n);
assert(*s0=='0' || *s0=='1'); // verify the edge value is 0 or 1
// Now start reading through the participation counts. Note that the child processes will be
// using the internal INTEGER node numbering since that was created before the ForkBlant().
s1=++s0; // get us to the tab
while(*s0 == '\t') {
int kk,g,i,j, count;
char *ID=++s0; // point at the k value
assert(isdigit(*s0)); kk=(*s0-'0'); assert(3 <= kk && kk <= 8); s0++; assert(*s0==':');
s0++; s1=s0; while(isdigit(*s1)) s1++; assert(*s1==':'); *s1='\0'; g=atoi(s0); *s1=':'; s0=s1;
s0++; assert(isdigit(*s0)); i=(*s0-'0'); assert(0 <= i && i < kk); s0++; assert(*s0==':');
s0++; assert(isdigit(*s0)); j=(*s0-'0'); assert(0 <= j && j < kk); s0++; assert(*s0==' '); *s0='\0';
s0++; s1=s0; while(isdigit(*s1)) s1++;
if(!(*s1=='\t' || *s1 == '\n'))
Fatal("(*s1=='\\t' || *s1 == '\\n'), line is \n%s", line);
// temporarily nuke the tab or newline, and restore it after (need for the top of the while loop)
char tmp = *s1;
*s1='\0'; count=atoi(s0);
assert(0 <= g && g < _numCanon && 0<=i&&i<kk && 0<=j&&j<kk);
UpdateNodePair(MAX(G_u,G_v) , MIN(G_u,G_v), ID, count);
*s1 = tmp;
assert(*(s0=s1)=='\n' || *s0 == '\t');
}
assert(*s0 == '\n');
}
/* Rather than explicitly enumerating the sub-motifs of every graphlet sampled from G, we do the recursive enumeration
** of all motifs under a graphlet only once---on the canonical graphlet. Then we *store* the association between the
** nodes of the canonical graphlet, and the motif associations. The associations get stored in a binary tree, one
** for each pair of canonical nodes in each canonical graphlet. Then, when we sample a graphlet from G, we simply
** determine what canonical it is using our standard BLANT lookup table _K, and use the perm[] matrix to transfer
** the canonical associations to the nodes of the graphlet sampled from G. The information is transferred from
** canonical to Varray in the function "TraversCanonicalNodes" elsewhere in the code.
**
** For each canonical graphlet, and for each pair of nodes in the graphlet, we maintain a dictionary (as a binary tree)
** of all the participation counts for all motif node-pairs that that canonical graphlet node pair participates in,
** across all sub-motifs of that canonical graphlet.
** Note that WE DO NOT KNOW HOW TO PROPERTLY NORMALIZE YET.... so for now do the easiest thing, which is count them all.
*/
static BINTREE *_canonicalParticipationCounts[MAX_CANONICALS][MAX_K][MAX_K];
#if 0 // alternate (which I think is correct) accumulation
#include "blant-predict-accumulate-alternate.c"
#else // Original accumulation of submotifs
/*
** All we need to add here is the inner loop that you have further down, over q and r, storing
** the count in relation to o and p. Then, when you TraverseCanonicals later, you'll use _perm[]
** to recover both u:v and x:y, and then do one of the following:
*/
void SubmotifIncrementCanonicalPairCounts(int topOrdinal, int Gint, TINY_GRAPH *g)
{
#if PARANOID_ASSERTS
assert(TinyGraph2Int(g,_k) == Gint);
#endif
int i, j, GintOrdinal=_K[Gint];
char perm[MAX_K];
memset(perm, 0, _k);
ExtractPerm(perm, Gint);
for(i=1;i<_k;i++) for(j=0;j<i;j++) // all pairs of canonical nodes
{
// We are trying to determine the frequency that a pair of nodes in the topOrdinal have an edge based on their
// being located at a pair of canonical nodes in a sub-motif. The frequency only makes sense if the underlying
// edge between them can sometimes exist and sometimes not; but if TinyGraphAreConnected(u,v)=true, the edge
// already exists in this motif (and thus also in the topOrdinal) and there's nothing to predict. Thus, we only
// want to check this node pair if the motif does NOT have the edge. (Comment label: (+++))
int u=(int)perm[i], v=(int)perm[j]; // u and v in the *current* motif
if(!TinyGraphAreConnected(g,u,v))
{
int o=_orbitList[GintOrdinal][i], p=_orbitList[GintOrdinal][j];
// the association is between a node *pair* in the canonical top graphlet, and a node *pair* of the
// motif that they are participating in. Since the pair is undirected, we need to choose a unique order
// to use an a key, so we simply sort the pair.
// And since we want lower triangle, row > column, always, so o=1...n-1, p=0...o-1
if(u < v) { int tmp = u; u=v; v=tmp; }
if(o < p) { int tmp = o; o=p; p=tmp; }
assert(_canonicalParticipationCounts[topOrdinal][u][v]);
int *pcount;
char buf[BUFSIZ], buf_kop_only[BUFSIZ];
sprintf(buf_kop_only,"%d:%d:%d", _k,o,p);
#if COUNT_uv_only
sprintf(buf,"%d:%d:%d", _k,o,p);
#else
int q,r;
for(q=1;q<_k;q++) for(r=0;r<q;r++) if(q!=o || r!=p) {
int x=(int)perm[q], y=(int)perm[r];
if(TinyGraphAreConnected(g,x,y)) { // (x,y) only counts if it's an edge
#if COUNT_xy_only
sprintf(buf,"%d:%d:%d:%d:%d", _k,o,p,x,y);
#else
sprintf(buf,"%d:%d:%d:%d:%d:%d:%d", _k,o,p,q,r,x,y);
#endif
}
}
#endif
if(!_predictiveOrbits || BinTreeLookup(_predictiveOrbits, (foint)(void*) buf_kop_only, (void*) NULL)) {
if(BinTreeLookup(_canonicalParticipationCounts[topOrdinal][u][v], (foint)(void*) buf, (void*) &pcount))
++*pcount;
else {
pcount = Omalloc(sizeof(int));
*pcount = 1;
BinTreeInsert(_canonicalParticipationCounts[topOrdinal][u][v], (foint)(void*) buf, (foint)(void*) pcount);
}
#if 0
int l,m;
for(l=0;l<_k-1;l++) for(m=l+1;m<_k;m++) if(l!=i && m!=j && TinyGraphAreConnected(g,perm[l],perm[m])) {
int q=_orbitList[GintOrdinal][l];
int r=_orbitList[GintOrdinal][m];
int x=(int)perm[l];
int y=(int)perm[m];
if(x < y) { int tmp = x; x=y; y=tmp; }
if(r < q) { int tmp = q; q=r; r=tmp; }
// increase the count of octuplet (u,v, o,p, q,r, x,y)
}
#endif
}
}
}
}
// Given any canonical graphlet g, accumulate all submotifs of its canonical version. This is the
// fundamental pre-computation of the counts of (canonical node pair, canonical motif node pair)
// associations that's performed on the fly and then memoized for future use.
static void AccumulateCanonicalSubmotifs(int topOrdinal, TINY_GRAPH *g)
{
static int depth;
static Boolean initDone;
static SET *seen; // size 2^B(k), *not* canonical but a specific set of nodes and edges in the *top* graphlet
int i,j,l;
if(!initDone) {
assert(_Bk>0);
seen = SetAlloc(_Bk);
assert(_k>= 3 && _k <= 8);
initDone = true;
}
int Gint = TinyGraph2Int(g,_k);
if(depth==0){
int GintOrdinal = _K[Gint];
if(Gint != _canonList[GintOrdinal])
Fatal("AccumulateCanonicalSubmotifs can only initially be called with a canonical, but ord %d = %d != %d",
GintOrdinal, _canonList[GintOrdinal], Gint);
assert(GintOrdinal == topOrdinal);
SetReset(seen);
}
if(SetIn(seen,Gint)) return;
SetAdd(seen,Gint);
SubmotifIncrementCanonicalPairCounts(topOrdinal, Gint, g);
// Now go about deleting edges recursively.
for(i=1; i<_k; i++)for(j=0;j<i;j++)
{
if(TinyGraphAreConnected(g,i,j)) // if it's an edge, delete it.
{
TinyGraphDisconnect(g,i,j);
if(TinyGraphDFSConnected(g,0)) {
++depth;
AccumulateCanonicalSubmotifs(topOrdinal, g);
--depth;
}
TinyGraphConnect(g,i,j);
}
}
}
#endif // AccumulateCanonicals versions
/* This is called from ProcessGraphlet: a whole Varray of nodes from a sampled graphlet. Our job here is to
** accumulate the association counts for each pair of nodes, using the memoized counts from canonical graphlets
** computed above.
*/
void AccumulateGraphletParticipationCounts(GRAPH *G, unsigned Varray[], TINY_GRAPH *g, int Gint, int GintOrdinal)
{
static int ramCheck;
if(++ramCheck % 100000 == 0) CheckRAMusage();
int i,j;
char perm[MAX_K];
if(_canonicalParticipationCounts[GintOrdinal][1][0] == NULL) { // [1][0] since [0][0] will always be NULL
for(i=1;i<_k;i++) for(j=0;j<i;j++)
_canonicalParticipationCounts[GintOrdinal][i][j] =
BinTreeAlloc((pCmpFcn) strcmp, (pFointCopyFcn) strdup, (pFointFreeFcn) free, NULL, NULL);
static TINY_GRAPH *canonical;
if (!canonical) canonical = TinyGraphAlloc(_k);
Int2TinyGraph(canonical, _canonList[GintOrdinal]);
AccumulateCanonicalSubmotifs(GintOrdinal, canonical);
}
memset(perm, 0, _k);
ExtractPerm(perm, Gint);
#if DEG_WEIGHTED_COUNTS
double totalWeight = 0;
for(i=0;i<_k;i++) totalWeight += 1.0/G->degree[Varray[i]];
#endif
// Unlike the comment (+++) above, here we need info an *all* pairs of nodes in G that belong to this graphlet,
// so we do not filter on the node pair being unconnected.
for(i=1;i<_k;i++) for(j=0;j<i;j++) // loop through all pairs of nodes in the *canonical* version of the graphlet
{
int g_u=perm[i], g_v=perm[j]; // u and v in the non-canonical motif g that is induced from G
int G_u=Varray[g_u], G_v=Varray[g_v]; // u and v in the BIG input graph G.
_TraverseCanonicalPairs_weight = 1; // default
#if PARANOID_ASSERTS
assert(!TinyGraphAreConnected(g,g_u,g_v) == !GraphAreConnected(G,G_u,G_v));
#endif
#if COUNT_uv_only
#if DEG_WEIGHTED_COUNTS
// We have found experimentally that if the sorted order of the degree of the motif agrees with that of the ful
// nodes it G, we get a better prediction. We will interpret this as using a greater weight if these agree.
// This check needs to be done BEFORE we re-order G_u,G_v to make G_u>G_v.
double subtract_uv = 0.0;
subtract_uv = 1.0/GraphDegree(G,G_u) + 1.0/GraphDegree(G,G_v);
_TraverseCanonicalPairs_weight = totalWeight - subtract_uv;
#elif COMMON_NEIGHBORS
#define MAX_N 9000 // ugly for now--max 32767 since signed short; feel free to change and recompile as necessary.
typedef short CNcount;
assert(G->n < MAX_N);
static CNcount CN[MAX_N][MAX_N];
static Boolean CNinit;
if(!CNinit) {
int i,j; for(i=0;i<G->n;i++)for(j=0;j<G->n;j++) CN[i][j]=-1;
CNinit=true;
}
if(CN[G_u][G_v] == -1) CN[G_u][G_v] = CN[G_v][G_u] = GraphNumCommonNeighbors(G, G_u, G_v); // inspired by RAT theory
if(CN[G_u][G_v]) _TraverseCanonicalPairs_weight /= sqrt((double)CN[G_u][G_v]);
#endif // DEG_WEIGHTED_COUNTS || COMMON_NEIGHBORS
#endif
#if DEG_ORDER_MUST_AGREE
int motifDegOrder = TinyGraphDegree(g,g_u) - TinyGraphDegree(g,g_v);
int graphDegOrder = GraphDegree(G,G_u) - GraphDegree(G,G_v);
int degOrderAgree = motifDegOrder * graphDegOrder;
if(degOrderAgree < 0) _TraverseCanonicalPairs_weight = 0; // disagreeing degree order count for nothing
#endif //DEG_ORDER_MUST_AGREE
// Now re-order for accessing matrices and output.
if(G_u < G_v) { int tmp = G_u; G_u=G_v; G_v=tmp; } // for consistency in accessing _PredictGraph
if(g_u < g_v) { int tmp = g_u; g_u=g_v; g_v=tmp; } // lower triangle of g
_TraverseCanonicalPairs_G_u = G_u; _TraverseCanonicalPairs_G_v = G_v;
_TraverseCanonicalPairs_Varray = Varray; _TraverseCanonicalPairs_perm = perm;
if(_TraverseCanonicalPairs_weight) {
#if 0
// I do NOT understand why attempting to account for the overcount makes prediction WORSE... plus I can't
// seem to get the counts to be equal between training edges and "phantom" test edges; the raw L3 counts
// are equal but I can't get the smpled 4:11:11 counts to agree... and the closer I managed to get to
// agreement by messing with the below ratios, the *worse* the prediction gets.
double over = 1.0; //_alphaList[GintOrdinal]/_g_overcount;
assert(over);
_TraverseCanonicalPairs_weight *= over; // account for MCMC alpha
#endif
BinTreeTraverse(_canonicalParticipationCounts[GintOrdinal][i][j], TraverseCanonicalPairs);
}
#if 0
int l,m;
for(l=1;l<_k;l++) for(m=0;m<l;m++) if(l!=i && m!=j && TinyGraphAreConnected(g,perm[l],perm[m])) {
int q=perm[l], r=perm[m];
int x=Varray[q], y=Varray[r];
assert(GraphAreConnected(G,x,y));
if(x < y) { int tmp = x; x=y; y=tmp; }
if(q < r) { int tmp = q; q=r; r=tmp; }
PrintNodePairSorted(G_u,':',G_v);
printf(" %d %d:%d %d:%d", GraphAreConnected(G,G_u,G_v),g_u,g_v,q,r);
PrintNodePairSorted(x,':',y);
putchar('\n');
}
#endif
}
#if 0 //PREDICT_USE_TREE && have _THREADS
Boolean debug = false;
if(_child && _flushCounts) {
fprintf(stderr, "Flushing child %d\n", getpid());
_flushCounts = false;
int G_u, G_v;
for(G_u=1;G_u<G->n;G_u++) for(G_v=0;G_v<G_u;G_v++) {
assert(G_u > G_v);
if(PREDICT_GRAPH_NON_EMPTY(G_u,G_v)) {
printf("%s %d", PrintNodePairSorted(G_u,':',G_v), GraphAreConnected(G,G_u,G_v));
if(debug) {
_supportNodeNames=true;
fprintf(stderr, "CHILD has %d entries for %s %d", _PredictGraph[G_u][G_v]->n,
PrintNodePairSorted(G_u,':',G_v), GraphAreConnected(G,G_u,G_v));
_supportNodeNames=false;
}
BinTreeTraverse(_PredictGraph[G_u][G_v], TraverseNodePairCounts);
if(debug) fprintf(stderr, "\n");
puts("");
BinTreeFree(_PredictGraph[G_u][G_v]);
_PredictGraph[G_u][G_v]=NULL;
}
}
}
#endif
}
int PredictMerge(GRAPH *G)
{
assert(_outputMode == predict_merge);
Predict_Init(G);
if(isatty(fileno(stdin)))
Warning("-mq (predict_merge) takes input only on stdin, which is currently a terminal. Press ^D or ^C to exit");
assert(_JOBS==1); // we only read from standard input, so threads make no sense.
char line[MAX_ORBITS * BUFSIZ];
int lineNum = 0;
while(fgets(line, sizeof(line), stdin) && !_earlyAbort) {
Predict_ProcessLine(G, line);
++lineNum;
}
assert(!ferror(stdin));
assert(feof(stdin));
PredictFlushAllCounts(G);
return 0;
}
|
C | #include <stdio.h>
int binary_search(int list[], int item, int left, int right);
void main()
{
int pos, max = 12, item = 60;
int list = {4,7,12,18,32,36,48,53,60,67,80,82};
pos = binary_search(list, item, 0, max-1);
printf("where? : %d", pos);
}
int binary_search(int list[], int item, int left, int right){
int median;
while(left <= right){
median = (left + right)/2;
if(list[median] == item){
return median;
}
else {
if(item < list[median]){ //왼쪽 서브 트리를 봐야한다
right = median - 1;
}else{
left = median + 1;
}
}
return -1;
}
}
//재귀적 방법 이용한 이진 탐색
int rbinary_search(int list[], int searchkey, int left, int right){
int median;
if(left <= right){
median = (left + right)/2;
if(searchkey < list[median]){ //왼쪽 서브 트리를 봐야한다
return rbinary_search(list, searchkey, left, median-1);
}
else if(searchkey > list[median]){ //오른쪽 서브 트리를 봐야한다
return binary_search(list, searchkey, median+1, right);
}
else{
return median;
}
}
return -1;
} |
C | #include "holberton.h"
#include <stdio.h>
char *_strncpy(char *dest, char *src, int n)
{
int copycounter = 0;
for (copycounter = 0; copycounter < n && *(src + copycounter) != '\0'; copycounter++)
*(dest + copycounter) = *(src + copycounter);
for ( ; copycounter < n; copycounter++)
*(dest + copycounter) = '\0';
return (dest);
}
int copycounter = 0;
/*while the value held at destination is not null increment the address*/
while( *dest != '\0')
dest++;
/*while *dest and *src don't contain a null byte*/
while (*dest && *src)
{
/*add the value held at *src to the value held at *dest*/
*dest = *src;
/*increment the address of destination*/
dest++;
/*increment the address of the source*/
src++;
}
return (dest);
|
C | /* 20170201 NaJiwoong */
/* 2020 April 19 */
/* Environment
Ubuntu 16.04.12
gcc 5.4.0 */
/* Execution
"make"
- make execution file, and output.txt
"make clean"
- clean executino file, and output.txt */
#include <stdio.h>
#include <stdlib.h>
/* Function for S4-box mapping */
int s4box(int input){
if (input >= 64 || input < 0){ // Check validity of input
return 16; // Error case
}
int bits[2];
bits[0] = ((input >> 4) & 2) + (input & 1); // bits[0] is outer bits
bits[1] = (input >> 1) & 0xF; // bits[1] is inner bits
int box[4][16] = {{7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15}
,{13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9}
,{10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4}
,{3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14}};
return (int)box[bits[0]][bits[1]];
}
/* Function for S5-box mapping */
int s5box(int input){
if (input >= 64 || input < 0){ // Check validity of input
return 16; // Error case
}
int bits[2];
bits[0] = ((input >> 4) & 2) + (input & 1); // bits[0] is outer bits
bits[1] = (input >> 1) & 0xF; // bits[1] is inner bits
int box[4][16] = {{2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9}
,{14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6}
,{4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14}
,{11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3}};
return (int)box[bits[0]][bits[1]];
}
/* Function for hamming distance */
int hamming(int a, int b){
int ham = 0;
int i;
for (i=0; i<6; i++){
ham += ((a >> i) & 1) == ((b >> i) & 1) ? 0 : 1;
}
return ham;
}
/* Function for binary printing */
char *tobinary(int x,int n){
int i;
char *b = malloc (sizeof (char)*n);
for (i = 0; i < n; i++){
b[i] = (x >> (n-1-i)) & 1 ? '1' : '0';
}
return b;
}
|
C | #include<stdio.h>
#include<math.h>
#define MOD 1000000007
typedef unsigned long long int ull;
ull pp(ull n,ull x)
{
ull i,ans=1;
for(i=1;i<=x;i++)
{
ans=ans*10;
}
return ans;
}
ull power(ull n)
{
ull ans=2,j=1,i,count=0;
//printf("%llu\n",n);
//printf("hello1\n");
if(n==1)
{
return ans;
}
if(n==0)
{
return 1;
}
//printf("hello2\n");
while(j<n && j<=9223372036854775807)
{
j+=j;
count++;
}
//printf("hello3\n");
if(n!=1)
{
j=j/2;
count--;
}
//printf("%llu\n",j);
for(i=0;i<count;i++)
{
ans=(ans*ans)%MOD;
}
ans=(ans*power(n-j))%MOD;
/*if(n==0)
{
return 1;
}
if(n==1)
{
return 2;
}
if(n%2==0)
{
ans=(power(n/2)*power(n/2))%MOD;
}
else
{
ans=(power(n/2)*power(n/2)*2)%MOD;
}*/
return ans;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
ull n,p=0,tmp,i,ten=10,ans=0;
scanf("%llu",&n);
tmp=n;
int a[20]={0};
i=19;
while(tmp>0)
{
a[i]=tmp%2;
tmp=tmp/2;
i--;
}
/*for(i=0;i<20;i++)
{
printf("%llu",a[i]);
}*/
//printf("\n");
for(i=20;i>0;i--)
{
p+=(a[i-1]*pp(ten,20-i));
}
//printf("%llu\n",p);
ans=power(p);
ans=(ans*ans)%MOD;
printf("%llu\n",ans);
}
return 0;
}
|
C | #include <stdio.h>
#include <stdlib.h>
int main()
{
typedef struct {
int a[100];
char b;
double * c;
} mystruct_t;
mystruct_t d[10];
mystruct_t * ap = d;
printf("%x %u\n",ap, ap);
printf("%x %u\n", ap+1, ap+1);
printf("%x %u\n", &d[10]-d, &d[10]-d);
return 0;
}
|
C | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* read.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: myuliia <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/02/08 21:00:22 by myuliia #+# #+# */
/* Updated: 2019/02/08 21:00:23 by myuliia ### ########.fr */
/* */
/* ************************************************************************** */
#include "../include/wolf3d.h"
char *read_two(t_read *red, char *buf, char *tmp, char *line)
{
ft_valid_symbol(line);
if (red->width == ft_count_words(line, ' ') || red->height == 1)
red->width = ft_count_words(line, ' ');
else
ft_error(3);
if (red->width < 3)
ft_error(4);
tmp = ft_strjoin(buf, line);
free(buf);
free(line);
buf = ft_strjoin(tmp, "\n");
free(tmp);
return (buf);
}
t_read *ft_read(char *file)
{
char *line;
char *buf;
char **map;
char *tmp;
t_read *red;
red = (t_read *)malloc(sizeof(t_read));
red->height = 0;
red->width = 0;
buf = ft_strdup("\0");
if ((red->fd = open(file, O_RDONLY)) < 0)
ft_error(2);
while ((get_next_line(red->fd, &line)) == 1 && ++red->height)
{
buf = read_two(red, buf, tmp, line);
}
if (!red->width)
ft_error(3);
close(red->fd);
map = ft_strsplit(buf, '\n');
free(buf);
map_in_int(map, red);
close(red->fd);
return (red);
}
void map_in_int(char **map, t_read *red)
{
char **tmp;
int y;
int x;
y = -1;
red->map = (int**)malloc(sizeof(int*) * red->height);
if (red->height < 3)
ft_error(4);
if (red->height > 97 || red->width > 97)
ft_error(6);
while (++y < red->height)
{
red->map[y] = (int*)malloc(sizeof(int) * red->width);
tmp = ft_strsplit(map[y], ' ');
free(map[y]);
x = -1;
while (++x < red->width)
{
red->map[y][x] = atoi(tmp[x]);
free(tmp[x]);
}
free(tmp);
}
free(map);
}
|
C | #ifndef MAIN_H
#define MAIN_H
#include<stdio.h>
#include<stdlib.h>
typedef int data_t;
typedef struct node
{
data_t data;
struct node *link;
}slist;
enum status
{
FAILURE,
SUCCESS,
LIST_EMPTY,
DATA_NOT_FOUND
};
int insert_at_first(slist **head, data_t);
int insert_at_last(slist **head, data_t);
int delete_first(slist **head);
int delete_last(slist **head);
int find_node(slist **head, data_t n_data);
int delete_list(slist **head);
void print_slist(slist *head);
#endif
|
C | /* File : sampleTimeSync.c
* Abstract:
*
* C-file S-function para sincronizarse con los tiempos de sampleo,
* mediante el uso de un reloj en tiempo real (PerformanceCounter)
* De esa forma, conseguimos una simulacion pseudo-tiempo-real.
*
* Copyright 2007 Toni Benedico Blanes
* Version: 1.0
*/
#define S_FUNCTION_NAME sampleTimeSync
#define S_FUNCTION_LEVEL 2
#include "simstruc.h"
#include "windows.h"
#define U(element) (*uPtrs[element]) /* Pointer to Input Port0 */
char primeraIteracio;
LONGLONG ticsPerSegon;
LONGLONG ticsAnteriors;
time_T sampleTime;
/*====================*
* S-function methods *
*====================*/
/* Function: mdlInitializeSizes ===============================================
* Abstract:
* The sizes information is used by Simulink to determine the S-function
* block's characteristics (number of inputs, outputs, states, etc.).
*/
static void mdlInitializeSizes(SimStruct *S)
{
BOOL out_qpf;
LARGE_INTEGER tmp_qpf;
ssSetNumSFcnParams(S, 0); /* Number of expected parameters */
if (ssGetNumSFcnParams(S) != ssGetSFcnParamsCount(S)) {
return; /* Parameter mismatch will be reported by Simulink */
}
ssSetNumContStates(S, 0);
ssSetNumDiscStates(S, 1);
if (!ssSetNumInputPorts(S, 0)) return;
if (!ssSetNumOutputPorts(S, 1)) return;
ssSetOutputPortWidth(S, 0, 1);
ssSetNumSampleTimes(S, 1);
ssSetNumRWork(S, 0);
ssSetNumIWork(S, 0);
ssSetNumPWork(S, 0);
ssSetNumModes(S, 0);
ssSetNumNonsampledZCs(S, 0);
/* Take care when specifying exception free code - see sfuntmpl_doc.c */
// ssSetOptions(S, SS_OPTION_EXCEPTION_FREE_CODE);
out_qpf = QueryPerformanceFrequency( &tmp_qpf);
ticsPerSegon=tmp_qpf.QuadPart;
printf("PerformanceCounter Frequency: %08X",(ticsPerSegon>>32)&0x0FFFFFFFF);
printf("%08X\n",ticsPerSegon&0x0FFFFFFFF);
primeraIteracio=1;
}
/* Function: mdlInitializeSampleTimes =========================================
* Abstract:
* Specifiy that we inherit our sample time from the driving block.
*/
static void mdlInitializeSampleTimes(SimStruct *S)
{
InputRealPtrsType uPtrs = ssGetInputPortRealSignalPtrs(S,0);
mxArray *array_ptr;
double stTmp;
// Leemos el sample time definido por el usuario
array_ptr = mexGetVariable("caller", "SampleTime");
if (array_ptr == NULL ){
mexPrintf("No se encontro la variable SampleTime. Se usar 0.001\n");
stTmp = 0.001;
}
else
{
stTmp=*((double*)(mxGetData(array_ptr)));
mexPrintf("Usando variable SampleTime con valor = %f\n", sampleTime);
}
sampleTime = stTmp;
/* Destroy array */
mxDestroyArray(array_ptr);
ssSetSampleTime(S, 0, sampleTime);
ssSetOffsetTime(S, 0, 0.0);
}
#define MDL_INITIALIZE_CONDITIONS
/* Function: mdlInitializeConditions ========================================
* Abstract:
* Initialize both discrete states to one.
*/
static void mdlInitializeConditions(SimStruct *S)
{
real_T *x0 = ssGetRealDiscStates(S);
x0[0]=0;
}
/* Function: mdlOutputs =======================================================
* Abstract:
* y = Cx + Du
*/
static void mdlOutputs(SimStruct *S, int_T tid)
{
real_T *y = ssGetOutputPortRealSignal(S,0);
real_T *x = ssGetRealDiscStates(S);
// InputRealPtrsType uPtrs = ssGetInputPortRealSignalPtrs(S,0);
UNUSED_ARG(tid); /* not used in single tasking mode */
y[0]=x[0];
}
#define MDL_UPDATE
/* Function: mdlUpdate ======================================================
* Abstract:
* xdot = Ax + Bu
*/
static void mdlUpdate(SimStruct *S, int_T tid)
{
// real_T tempX[2] = {0.0, 0.0};
real_T *x = ssGetRealDiscStates(S);
// InputRealPtrsType uPtrs = ssGetInputPortRealSignalPtrs(S,0);
BOOL out_qpf;
LARGE_INTEGER tmp_qpf;
LONGLONG ticsTarget;
LONGLONG tmpTicsPeriode;
UNUSED_ARG(tid); /* not used in single tasking mode */
/*
x[0]=x[0]+U(0);
x[1]=x[1]+U(1);
*/
if (primeraIteracio)
{
primeraIteracio=0;
out_qpf = QueryPerformanceCounter( &tmp_qpf);
ticsAnteriors=tmp_qpf.QuadPart;
}
tmpTicsPeriode=ticsPerSegon/((LONGLONG)(1.0/sampleTime));
ticsTarget=ticsAnteriors+tmpTicsPeriode;
out_qpf = QueryPerformanceCounter( &tmp_qpf);
//if (tmp_qpf.QuadPart>ticsTarget)
// x[0]=101;
//else
x[0]=100-((ticsTarget-tmp_qpf.QuadPart)*100)/tmpTicsPeriode;
do
{
out_qpf = QueryPerformanceCounter( &tmp_qpf);
} while(tmp_qpf.QuadPart<ticsTarget);
ticsAnteriors=ticsTarget;
//printf("Contador: %08X",(ticsTarget>>32)&0x0FFFFFFFF);
//printf("%08X\n",ticsTarget&0x0FFFFFFFF);
}
/* Function: mdlTerminate =====================================================
* Abstract:
* No termination needed, but we are required to have this routine.
*/
static void mdlTerminate(SimStruct *S)
{
UNUSED_ARG(S); /* unused input argument */
}
#ifdef MATLAB_MEX_FILE /* Is this file being compiled as a MEX-file? */
#include "simulink.c" /* MEX-file interface mechanism */
#else
#include "cg_sfun.h" /* Code generation registration function */
#endif
|
C | #include <stdio.h>
main()
{
printf("Sup! This my 1st C program after trying Learn C in 24 hours.\n");
return 0;
}
|
C | #include"handsk.h"
#include"ot.h"
#include <time.h>
SOCKET clientSOCKET;//全局的socket
int random_unique = 11;
void get_msg() {
char recv_buff[1024];
int r;
while (1) {
memset(recv_buff, 0, sizeof(recv_buff));
r = recv(clientSOCKET, recv_buff, 1023, NULL);
if (r > 0) {
recv_buff[r] = 0;
printf("recv from serv:%s\n", recv_buff);
}
}
}
void main_loop() {
//1.请求协议版本
WSADATA wsaDATA;
WSAStartup(MAKEWORD(2, 2), &wsaDATA);
if (LOBYTE(wsaDATA.wVersion) != 2 || HIBYTE(wsaDATA.wVersion) != 2) {
printf("protocol error!\n");
return -1;
}
//2.创建socket
clientSOCKET = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);//参数1 通信协议的类型 参数2 tcp、udp 参数3 保护方式
if (SOCKET_ERROR == clientSOCKET) {//SOCKET_ERROR=-1
printf("init socket error\n");
WSACleanup();
return -2;
}
//3.获取服务器协议地址族(手动确定服务器的,只需要和服务器写的一样即可)
SOCKADDR_IN addr = { 0 };
addr.sin_family = AF_INET;//协议版本
addr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");//ip地址的本质是个整数可以使用本机ip(使用别的ip会导致绑定失败)
addr.sin_port = htons(10086);//端口65536 10000左右的
//4.连接服务器
int r = connect(clientSOCKET, (struct sockaddr*)&addr, sizeof(addr));
if (-1 == r) {
printf("connect error\n");
return -1;
}
//5.通信
char buff[1024];
CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)get_msg, NULL, NULL, NULL);//创建线程,第三个参数写函数名,其他全部填NULL
//子线程的作用主要就是接收消息
while (1) {
memset(buff, 0, 1024);
printf("please input:");
scanf("%s", buff);
r = send(clientSOCKET, buff, strlen(buff), NULL);
}
}
void get_random_str(char* random_str, const int random_len)
{
srand(time(NULL)+random_unique);
int i;
for (i = 0; i < random_len; ++i)
{
switch ((rand() % 3))
{
case 1:
random_str[i] = 'A' + rand() % 26;
break;
case 2:
random_str[i] = 'a' + rand() % 26;
break;
default:
random_str[i] = '0' + rand() % 10;
break;
}
}
random_str[random_len] = '\0';
random_unique++;
}
/*
函数连接服务器,简化所有使用socket的函数
*/
void socket_conn() {
//1.请求协议版本
WSADATA wsaDATA;
WSAStartup(MAKEWORD(2, 2), &wsaDATA);
if (LOBYTE(wsaDATA.wVersion) != 2 || HIBYTE(wsaDATA.wVersion) != 2) {
printf("protocol error!\n");
return -1;
}
//2.创建socket
clientSOCKET = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);//参数1 通信协议的类型 参数2 tcp、udp 参数3 保护方式
if (SOCKET_ERROR == clientSOCKET) {//SOCKET_ERROR=-1
printf("init socket error\n");
WSACleanup();
return -2;
}
//3.获取服务器协议地址族(手动确定服务器的,只需要和服务器写的一样即可)
SOCKADDR_IN addr = { 0 };
addr.sin_family = AF_INET;//协议版本
addr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");//ip地址的本质是个整数可以使用本机ip(使用别的ip会导致绑定失败)
addr.sin_port = htons(10086);//端口65536 10000左右的
//4.连接服务器
int r = connect(clientSOCKET, (struct sockaddr*)&addr, sizeof(addr));//addr就是服务器的地址族
if (-1 == r) {
printf("connect error\n");
return -1;
}
}
/*
socket 清理函数
*/
void socket_clean() {
closesocket(clientSOCKET);
WSACleanup();
}
/*
一个函数进行ot-----ot函数的入口应该是两个随机的字符串,没有出口,出口在serv端
发送的参数在一个结构体中,接收的数据也在一个结构体中
在一个结构体中开销小,实现时需要解决:1.buff的长度问题,buff中使用分隔符分割各个位的问题
需要提供参数:真实消息1,真实消息2.什么都不得到
*/
void ot_msg(char* irl_msg1,char * irl_msg2) {
//char* irl_msg1 = "hello lili";//真实消息
//char* irl_msg2 = "are you ok?";
int r;
char send1[1024];//包装ot第一次传送的buff
memset(send1, 0, sizeof(send1));
char nn[100];
char ee[100];
char dd[100];//dd保存在本地
ot_send_rsa_msg(nn, ee, dd);
char msg_r1[100];
char msg_r2[100];
ot_send_rand_msg(msg_r1, msg_r2);//得到两个随即消息
//int offset = 0;
strcat(send1, nn);
strcat(send1, "/");
strcat(send1, ee);
strcat(send1, "/");
strcat(send1, msg_r1);
strcat(send1, "/");
strcat(send1, msg_r2);
r = send(clientSOCKET, send1, strlen(send1), NULL);
//printf("%s\n", send1);
//接收v
char v[100];
memset(v, 0, sizeof(v));
recv(clientSOCKET, v, 99, NULL);
printf("get rev:%s\n", v);
//printf("v:%s\n", v);
char k1[100];
char k2[100];
ot_compute_ki_msg(k1, k2, v, msg_r1, msg_r2, dd, nn);
//printf("%s\n", k1);
//printf("%s\n", k2);
//对真实消息进行加密
char enmsg1[100];
char enmsg2[100];
ot_encode_msg(enmsg1, enmsg2, k1, k2, irl_msg1, irl_msg2);
//把两个真实消息发送给serv
char send2[1024];
memset(send2, 0, sizeof(send2));
//真实消息含有\0,需要手动拷贝
printf("%s\n", enmsg1);
printf("%s\n", enmsg2);
strcat(send2, enmsg1);
strcat(send2, "/");
strcat(send2, enmsg2);
send(clientSOCKET, send2, strlen(send2), NULL);
//【问题】:问什么需要debug两次,exe文件才会更新。猜测:和工程的组织方式有关
}
void binarystring(char c)
{
int i;
for (i = 0; i < 8; i++)
{
if (c & 0x80) putchar('1'); else putchar('0');
c <<= 1;
}
}
/*
实现函数:
对于一个128位的字符串,生成对应的128个0、1 在ot中这256个消息都属于真实信息,需要serv进行选择
itoa(整型数据,目标字符串,进制)不能自动补0
这个函数应该在serv端,serv端根据rule生成的01,输入01
大ot函数,每次输入128个0、1
client端每次输入256个随机串对应这些0.1
*/
void string2bin(char *cc) {
char bin[129];//多一位放\0
memset(bin, 0, sizeof(bin));
for (int i = 0; i < strlen(cc); i++) {
char c = cc[i];
for (int j = 0; j < 8; j++) {
if (c & 0x80) bin[i * 8 + j] = '1';
else bin[i * 8 + j] = '0';
c <<= 1;
}
}
printf("bin:%s\nbinlen:%d", bin, strlen(bin));
}
/*
生成永不改变的r,128bit
@random_r:生成的128bit数(以0101的方式放在char中)
只要char是满的,不是aecii码式的填充,就能直接异或
*/
void generate_r(char *random_r) {
//BIGNUM* rnd;
//rnd = BN_new();
////BN_random
//int bits = 128;
//int top = 0;
//int bottom = 0;
//BN_rand(rnd, bits, top, bottom);
//char show2[17];
//memset(show2, 0, sizeof(show2));
//BN_bn2bin(rnd, show2);
//while (strlen(show2) != 16)
//{
// BN_rand(rnd, bits, top, bottom);
// memset(show2, 0, sizeof(show2));
// BN_bn2bin(rnd, show2);
//}
////printf("%s\n", show2);//嶏_Mg菕gZOQd ~"_
////printf("%d\n", strlen(show2));//16
//strcpy(random_r, show2);
///*
//每个char都异或一个char-------------------代码块测试可行,用char*保存生成的01串即可
//
//char* irl_msg1 = "abcdefghijkl1234";
//char buf[17];
//memset(buf, 0, sizeof(buf));
//for (int i = 0; i < 16; i++) {
// buf[i] = irl_msg1[i] ^ show2[i];
//}
//printf("%s\n",buf);
//char ans[17];
//memset(ans, 0, sizeof(ans));
//for (int i = 0; i < 16; i++) {
// ans[i] = buf[i] ^ show2[i];
//}
//printf("%s\n", ans);
//*/
//BN_free(rnd);//而是每4位组成一个十进制数储存在to中
get_random_str(random_r, 16);
}
/*
生成128个向量,使它们的异或之和为random_r
@char *random_r:固定的异或之和值
@char** r_vector:返回128个随机串,每个串的长度是128
直接生成时间太长了,不可行,随机生成127组,最后一组匹配
*/
void generate_r_vector(char (*r_vector)[17],char *random_r) {
//BIGNUM* vector[127];
//char r_v[128][17];
//char flag[17];//判断是否一致
//memset(flag, 0, sizeof(flag));
//int bits = 128;
//int top = 0;
//int bottom = 0;
//for (int i = 0; i < 127; i++) {
// vector[i] = BN_new();
// BN_rand(vector[i], bits, top, bottom);
// memset(r_v[i], 0, sizeof(r_v[i]));
// BN_bn2bin(vector[i], r_v[i]);
//}
//memset(r_v[127], 0, sizeof(r_v[127]));
//for (int i = 0; i < 127; i++) {
// for (int j = 0; j < 16; j++) {
// flag[j] = flag[j] ^ r_v[i][j];
// }
//}
//for (int i = 0; i < 16; i++) {
// r_v[127][i] = flag[i] ^ random_r[i];
//}
///*char ans[17];
//memset(ans, 0, sizeof(ans));
//for (int i = 0; i < 128; i++) {
// for (int j = 0; j < 16; j++) {
// ans[j] = ans[j] ^ r_v[i][j];
// }
//}
//printf("===%s\n", ans);*/
//
//for (int i = 0; i < 128; i++) {
// memcpy(r_vector[i], r_v[i], 17);//逐字节拷贝解决问题strcpy会出现问题,原因未知
//}
char flag[17];//判断是否一致
memset(flag, 0, sizeof(flag));
for (int i = 0; i < 127; i++) {
get_random_str(r_vector[i], 16);
}
for (int i = 0; i < 127; i++) {
for (int j = 0; j < 16; j++) {
flag[j] = flag[j] ^ r_vector[i][j];
}
}
for (int i = 0; i < 16; i++) {
r_vector[127][i] = flag[i] ^ random_r[i];
}
}
/*
产生连接key数字的函数,输入ip,产生128对key,都存放在一个结构体中HAND_KEY
@key:返回的带有ip和key_array的结构体
@ipadd:输入的ip地址
*/
void generate_key_array(HAND_KEY *key,char *ipadd) {//这里的key就是外面真实的key,不需要copy即可传值
key->ipaddr = ipadd;
char a1[17], a2[17];
//生成128对 17 长的随机串
for (int i = 0; i < 128; i++) {
memset(a1, 0, sizeof(a1));
memset(a2, 0, sizeof(a2));
generate_r(a1);
generate_r(a2);
memcpy(key->key_array[i][0], a1, sizeof(a1));
memcpy(key->key_array[i][1], a2, sizeof(a2));
}
}
/*
进行128次 每次两个128bit字符串的 ot
现在已有的ot可以进行一次2选1,黄的论文:128次每次得到128bit字符串的ot
需要进行128次ot
可能存在问题:上次ot没有结束,就开始进行下一次ot了
把128组char* 数组放在ot_msg中,另一边接收128个
两个参数:真实消息向量1,真实消息向量2
*/
void ot_128_send(char (*irl_megs1)[17], char(*irl_megs2)[17]) {
char buf1[17], buf2[17];
for (int i = 0; i < 128; i++) {
//memset(buf1, 0, sizeof(buf1));
//memset(buf2, 0, sizeof(buf2));
//memcpy(buf1, irl_megs1[i], 17);
//memcpy(buf2, irl_megs2[i], 17);
//printf("%d\n", i);
//printf("%s\n", irl_megs1[i]);
//printf("%s\n", irl_megs2[i]);
//printf("%s\n", buf1);
//printf("%s\n", buf2);
//printf("\n");
ot_msg(irl_megs1[i], irl_megs2[i]);
}
}
/*
client端进行多少次128ot是由serv端确定的
serv端根据rule的数量发送进行多少组ot的请求,serv端发送ot数量,client端接收到数量后进行ot,每个r都新生成k是不变的
返回serv希望进行ot的次数
*/
int client_handsk_ot() {
int nums;
//memset(nums, 0, sizeof(nums));
recv(clientSOCKET,&nums, sizeof(nums), NULL);
printf("ot times:%d\n", nums);
return nums;
}
int main1() {//socket的设置函数独立出来(至少在解决128ot之后再考虑这个问题)
//main_loop();
socket_conn();
printf("service readlly!\n");
char* irl_msg1 = "abcdefghijkl1234";//真实消息 显示的16实际长度是15 有\0占一位
char* irl_msg2 = "are you ok?";
//ot_msg(irl_msg1,irl_msg2);
//string2bin(irl_msg1);
//char random[17];
//memset(random, 0, sizeof(random));
//generate_r(random);
//char r_v[128][17];
//memset(r_v, 0, sizeof(r_v));
//generate_r_vector(r_v,random);
/*
//char ans[17];test
//memset(ans, 0, sizeof(ans));
//for (int i = 0; i < 128; i++) {
// for (int j = 0; j < 16; j++) {
// ans[j] = ans[j] ^ r_v[i][j];
// }
//}
//printf("%s\n", ans);
//printf("%d\n", strcmp(ans, random));
*/
int loop_time=client_handsk_ot();
HAND_KEY handkey;
char* ipadd = "123.12.3.4";
generate_key_array(&handkey, ipadd);//可以直接得到
/*验证生成的随机密钥数组
for (int i = 0; i < 128; i++) {
printf("%s\n", handkey.key_array[i][0]);
printf("%s\n", handkey.key_array[i][1]);
printf("\n");
}
*/
/*128ot的基本步骤
char random[17];
memset(random, 0, sizeof(random));
generate_r(random);
printf("random:%s\n", random);
char r_v1[128][17];
memset(r_v1, 0, sizeof(r_v1));
generate_r_vector(r_v1,random);//生成了一组
char r_v2[128][17];
memset(r_v2, 0, sizeof(r_v2));
generate_r_vector(r_v2, random);//生成了一组
//生成第二组 client在本地测试生成的两组是否能异或成目标值
*/
/*验证生成128个随机向量能否异或成一个
char ans[17];
memset(ans, 0, sizeof(ans));
for (int i = 0; i < 128; i++) {
for (int j = 0; j < 16; j++) {
ans[j] = ans[j] ^ r_v1[i][j];
}
}
printf("%s\n", ans);
printf("ans:%d\n", strcmp(ans, random));
memset(ans, 0, sizeof(ans));
for (int i = 0; i < 128; i++) {
for (int j = 0; j < 16; j++) {
ans[j] = ans[j] ^ r_v2[i][j];
}
}
printf("%s\n", ans);
printf("%d\n", strcmp(ans, random));
*/
//使用ot发送
//ot_128_send(r_v1, r_v2);
//测试多次128ot的可行性
/*
memset(random, 0, sizeof(random));
generate_r(random);
printf("random:%s\n", random);
memset(r_v1, 0, sizeof(r_v1));
generate_r_vector(r_v1, random);//生成了一组
memset(r_v2, 0, sizeof(r_v2));
generate_r_vector(r_v2, random);//生成了一组
ot_128_send(r_v1, r_v2);
*/
char random[17];
memset(random, 0, sizeof(random));
generate_r(random);
printf("random:%s\n", random);
char r_v1[128][17];
memset(r_v1, 0, sizeof(r_v1));
generate_r_vector(r_v1, random);//生成了一组
char r_v2[128][17];
memset(r_v2, 0, sizeof(r_v2));
generate_r_vector(r_v2, random);//生成了一组
for (int i = 0; i < loop_time; i++) {
memset(random, 0, sizeof(random));
generate_r(random);
printf("random:%s\n", random);
memset(r_v1, 0, sizeof(r_v1));
generate_r_vector(r_v1, random);//生成了一组
memset(r_v2, 0, sizeof(r_v2));
generate_r_vector(r_v2, random);//生成了一组
ot_128_send(r_v1, r_v2);
ot_128_send(r_v1, r_v2);
}
socket_clean();
system("pause");
return 0;
}
//78min |
C | #include "log.h"
static FILE *log_fp = NULL;
/**
* Start our own debug logger.
* @param file_name
* @return
*/
int start_logger(char* file_name) {
log_fd = fopen(file_name, "w");
if (log_fd == NULL) {
fprintf(stderr, "Can not start logger.\n");
return 1;
}
return 0;
}
/**
* Close our own debug logger.
* @return
*/
int close_logger() {
if (log_fd != NULL) {
fclose(log_fd);
return 0;
}
fprintf(stderr, "Wrong log file descriptor.\n");
return 1;
}
/**
* Log out debug message to our own log file.
* @param format
*/
void logout(const char* format, ...) {
va_list arg;
va_start(arg, format);
vfprintf(log_fd, format, arg);
va_end(arg);
fflush(log_fd);
}
/**
* Log out dns message.
* @param log_name
* @param time
* @param client_ip
* @param query_name
* @param response_ip
*/
void log_record(const char *log_name, int time, const char *client_ip,
const char *query_name, const char *response_ip) {
log_fp = fopen(log_name, "a+");
if (!log_fp) {
return;
}
int ret = fprintf(log_fp, "%d %s %s %s\n", time, client_ip, query_name, response_ip);
if (ret < 0) {
perror("log_record");
}
if (log_fp != NULL) {
fclose(log_fp);
}
}
/**
* Init empty log file.
* @param log_name
*/
void log_init(const char *log_name) {
log_fd = fopen(log_name, "w");
} |
C | /**
* @author Joseph Kawamura
*
* Desc:
* Node class used to construct the huffman tree. Each node contains a character, that characters frequency
* within the given text file as well as pointers to left and right children that can be used to construct
* a binary tree.
*
* Modified: April 26, 2021
* Modified: April 28, 2021
* Modified: April 29, 2021
* Modified: May 4, 2021
* Modified: May 6, 2021
*/
#include <stdio.h>
#include <stdlib.h>
#include "Node.h"
/**
* constructor for node class
* @param c the character being stored in the node
* @param freq the frequency at which that character occurs
* @param left pointer to left branch
* @param right pointer to right branch
*/
node* makeNode(char c, int freq, node*left, node*right){
node* output = malloc(sizeof(node));
output->c = c;;
output->freq = freq;
output->left = left;
output->right = right;
}
/**
* destructor that frees memory for a given node and all of
* its children (ie a destructor for a binary tree)
* @param root the root node
*/
void destroyNode(node* root){
if(root->left == NULL && root->right == NULL){
free(root);
return;
}
destroyNode(root->left);
destroyNode(root->right);
free(root);
}
|
C | #include <stdio.h>
#include <string.h>
char *mystrcpy(char *dest, char *src)
{
if(NULL == dest || NULL == src)
{
puts("NULL pointer error.");
return NULL;
}
char *p = dest;
while(*src)
{
*p = *src;
src++;
p++;
}
*p = 0;
return dest;
}
int mystrlen(const char *src)
{
if(NULL == src)
{
puts("src is null.");
return -1;
}
int len = 0;
while(*src)
{
len++;
src++;
}
return len;
}
char *mystrtok(char *src, char c)
{
if(NULL == src)
{
return NULL;
}
char *p = src;
while(*p)
{
if(*p == c)
{
*p = 0;
break;
}
p++;
}
return src;
}
char *mystrcat(char *s1, const char *s2)
{
if(NULL == s1 && NULL != s2)
{
return s2;
}
if(NULL != s1 && NULL == s2)
{
return s1;
}
if(NULL == s1 && NULL == s2)
{
return NULL;
}
char *p = s1 + strlen(s1);
while(*s2)
{
*p = *s2;
s2++;
p++;
}
*p = 0;
return s1;
}
int myatoi(char *nptr)
{
if(NULL == nptr)
{
puts("nptr is null.");
return -1;
}
int sum = 0;
while(*nptr)
{
sum = sum * 10 + (*nptr - '0');
nptr++;
}
return sum;
}
|
C | #include <stdio.h>
#include <string.h>
int ft_strlen(char *str)
{
int l;
l = 0;
while (str[l] != '\0')
{
l++;
}
return(l);
}
int main()
{
char *str;
str = "lol";
printf("%d\n", ft_strlen(str));
printf("%lu\n", strlen(str));
return (0);
}
|
C | #include "libmy.h"
int my_count(long n)
{
int count;
count = 0;
if (n == -2147483648)
return (11);
if (n == 0)
return (1);
if (n < 0)
count++;
while (n != 0)
{
n = n / 10;
count++;
}
return (count);
}
char *my_itoa(int num)
{
int i;
char *str;
int len;
long n;
n = num;
i = 0;
len = my_count(n);
str = (char *)malloc(sizeof(char) * (len + 1));
if (!str)
return (NULL);
if (n < 0)
{
str[0] = '-';
n = n * -1;
i++;
}
str[len] = '\0';
while (len > i)
{
str[len - 1] = n % 10 + 48;
n = n / 10;
len--;
}
return (str);
}
|
C | #include <sat/driver.h>
#include <avr/io.h>
void driver_init(void)
{
// For driver communication, we use PORTB by default
// Configuring pins to output
DDRB |= (1<<4)|(1<<3)|(1<<2);
// For PWM feature, we use Timer1
// Configuring timer
// Compare ch.A, PWM Phase Correct, 10-bit
TCCR1A = (1<<COM1B1)|(1<<WGM11)|(1<<WGM10);
TCCR1B = (1<<CS11); // clock divide by 64
}
void driver_set_dir(uint8_t dir)
{
// Variable dir in this function - one of consts: FORWARD or BACKWARD
// This consts contains a ready bitmask for I/O port
// Simply write it to the port!
PORTB |= dir<<2;
PORTB &= 0xFF & (dir<<2);
}
void driver_set_speed(uint16_t speed)
{
// Formally, to set speed of motor, we need to change PWM length
// Change PWM is to change timer compare register :)
OCR1B = speed;
}
void driver_stop(void)
{
// To stop motor, we will make short connection of wires
// To make it, dir pins must be equal
// Let's make it equals 1
PORTB |= 3<<2;
}
uint8_t driver_get_dir(void)
{
return drv_get_dir();
}
void driver_set_fspeed(int16_t speed)
{
if(speed > 0)
driver_set_dir(FORWARD);
else
{
driver_set_dir(BACKWARD);
speed = -speed;
}
if(speed < 1024)
driver_set_speed((uint16_t) speed);
else
PORTB |= 3<<2;
}
|
C | /*
* Author: 段鹏远(alex)
* Version: 0.1
* Time: 2014-9-29
* Function:
使用递归方法实现atoi函数
功能:将字符串转换成整数
*/
#include "apue.h"
int my_atoi(const char* p);
size_t my_atoi_r(const char* p, size_t num);
size_t tens(size_t num);
int main(int argc, char* argv[]){
printf("%d\n", my_atoi("-1234"));
return 0;
}
int my_atoi(const char* p){
if(*p == '-')
return -my_atoi_r(p+1, strlen(p) - 2);
else
return my_atoi_r(p, strlen(p) - 1);
}
size_t my_atoi_r(const char* p, size_t num){
if(num == 0){
return (*p - '0');
}else {
return (*p - '0')*tens(num) + my_atoi_r(p+1, num - 1);
}
}
size_t tens(size_t num){
size_t sum = 1;
for(;num > 0; num--)
sum *= 10;
return sum;
}
|
C | #include <stdio.h>
#include <stdlib.h>
int main()
{
printf("\"Ahmed said:\"I searched online and found that \\,\",new lines('\\n')and tabs('\\t')are among the special characters.\"\n");
printf("Mohamed replied:\"Great, I also managed to make a beep sound using the special character'\\a'.Hear this ..\"");
return 0;
}
|
C | /***************************************************************************
* File : vsyn_lib *
* Note : This file contains functions for synthesis of vowels. *
***************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "vtconfig.h"
#include "vsyn_lib.h"
/****************( externally defined global variables )*******************/
extern float smpfrq;
extern float Ag;
/****************************( functions )*********************************/
/*****
* Function : glottal_area
* Note : To calculate glottal area (Ag cm2) at sample point n during
* a fundamental period or a transition quotient (t0 samples).
* In the oscilation mode (mode = 1), Ag is specified either
* Fant's model or Maeda's model. In the transition mode
* (mode = 2), the Ag variation from the initial to the target
* area is specified by a raised cosine curve. The calculated
* area is returned by value to the calling program.
*****/
float glottal_area (
char model, /* 'F' for Fant, 'M' for Maeda model */
char mode, /* 'o' for oscilating, 't' for transition */
float Ap, /* peak glottal area (cm2) with mode=1, */
/* target area (cm2) with mode=2 */
short *t0 ) /* fundamental period or transion quotient*/
/* in samples. The non-zero value signals */
/* a new glottal cycle or transion. */
/* t0 will be zeroed */
{
float oqF, cqF; /* opening & closing quotients for Fant's */
/* model. */
float wp, oqM, cqM; /* time warping coefficients for Maeda's */
/* model. */
static short n;
static float amp;
static short t1, t2, t3;
static float a, b, A, A0;
float t;
/*** oscilation mode ***/
if(mode == 'o' ) {
if( *t0 > 0 ) { /* set a new glottal cycle */
A = (float)0.5*Ap;
if( model == 'F'){
oqF = 0.36f;
cqF = 0.26f;
t1 = (short)(oqF * (*t0));
t2 = (short)(cqF * (*t0));
t3 = t1 + t2;
a = 3.141593f/t1;
b = (float)(1./(1. - cos(a*t2)));
}
if( model == 'M') {
wp = 2.f;
oqM = 0.5f;
cqM = 0.2f;
t1 = (short)(oqM * (*t0));
t2 = (short)(cqM * (*t0));
t3 = t1 + t2;
a = (float)(3.141593f/t1);
b = (float)( (t1 - t2)/pow( t2, wp ));
}
*t0 = 0;
n = 0;
}
if( n < t1 ) amp = (float)(A*(1.0 - cos(a*n))); /* opening */
if( n >= t1 && n < t3 ) { /* closing */
t = (float)(n - t1);
if( model == 'F' ) amp = (float)(Ap*(1. - b + b*cos(a*t)));
if( model == 'M' ) amp = (float)(A*(1. + cos(a*(t+pow(t,wp)))));
}
if( n >= t3 ) amp = 0.0; /* closed */
n++;
return( amp );
}
/*** transion mode ***/
if( mode == 't' ) {
if( *t0 > 0 ) {
t1 = *t0;
A0 = amp;
A = (float)(0.5*( Ap - A0 ));
a = (float)(3.141593/t1);
n = 0;
*t0 = 0;
}
if( n < t1 ) amp = (float)(A0 + A*(1. - cos(a*n)));
else amp = Ap;
n++;
return( amp );
}
return 0;
}
/*****
* Function : vowel_synthesis
* Note : Synthesis of a stationary vowels with varying F0.
*****/
void vowel_synthesis ( FILE *sig_file ) {
float Ap = 0.2f;
long buf_count;
short *sig_buf;
float f[3] = { 120., 130., 100. }; /* F0 pattern, Hz */
float d[3] = { 0., 100., 200. }; /* duration, ms */
float p_trgt[3], d_trgt[3];
long num_samples; /* how long is this sound in samples? */
long num_written; /* we add room for three cycles of "transition" at 50 Hz*/
float a, p, n;
short np, t0;
short i, j;
short temp;
float duration = 0;
/* define F0 contour */
for(i=0; i<3; i++){
p_trgt[i] = smpfrq/f[i]; /* target pitch (samples) */
d_trgt[i] = (float)(smpfrq*d[i]/1000.); /* duration in samples */
duration += d[i];
}
num_samples = (smpfrq * duration/1000.) + (3*(smpfrq/50));
/* allocate buffer */
if ((sig_buf = (short *) calloc( num_samples, sizeof(short) ))==NULL) {
fprintf(stderr,"%s/n","error allocating memory for wave");
}
/* initialize simulator */
Ag = 0;
vtt_ini(afvt); /* discard returned value, constant delay */
/* pitch loop */
n = 0;
buf_count = 0;
for(j=0; j<2; j++) { /* looping here over a sequence of target values */
a = (p_trgt[j+1] - p_trgt[j])/d_trgt[j+1]; /* slope of pitch contour for interpolation */
n = n - d_trgt[j]; /* time location in pitch contour */
p = 0;
do { /* we're doing a pitch-synchronous update of f0 target */
n = n + p; /* sample count in the output buffer */
p = a*n + p_trgt[j]; /* updated pitch period in samples */
t0 = np = (short)(p + 0.5); /* pitch period as an integer */
//printf("%d\t%ld\t%0.2f\t%0.2f\n",np,buf_count,n,d_trgt[2]);
/* time vary vocal tract parameters here */
for(i=0; i<np; i++){ /* single period */
Ag = glottal_area( 'F', 'o', Ap, &t0 );
temp = (short) (DACscale * vtt_sim()); /* synthesize next sample */
printf("%ld\t%0.3f\t%hd\n",buf_count,Ag,temp);
sig_buf[buf_count++] = temp;
}
} while( n < d_trgt[j+1] ); /* keep synthesizing until the number of samples is reached */
}
t0 = np; /* open glottis to decay signal */
for(j=0; j<3; j++) { /* add three "transition" glottal pulses */
for(i=0; i<np; i++) {
Ag = glottal_area( 'F', 't', Ap, &t0 );
temp = (short) (DACscale * vtt_sim(afvt)); /* synthesize next sample */
printf("%ld\t%0.3f\t%hd\n",buf_count,Ag,temp);
sig_buf[buf_count++] = temp;
}
}
if ((num_written = fwrite( sig_buf, sizeof(short), num_samples, sig_file )) != num_samples) {
printf("%s\n","write to file failed");
}
vtt_term();
}
|
C | /*************************************************************************
> File Name: memset.c
> Author: Amano Sei
> Mail: [email protected]
> Created Time: 2019年10月20日 星期日 11时57分56秒
************************************************************************/
#include <stdio.h>
#define VBYTES 32
//typedef unsigned char vec_t __attribute__ ((vector_size(VBYTES)));
typedef unsigned long long vec_t __attribute__ ((vector_size(VBYTES)));
void *memset(void *s, int c, size_t n){
unsigned char *schar = s;
if(n >= VBYTES*VBYTES){
//尝试了两种写法,如果前向不跳的话对于少量的memset都避免不了预测惩罚
while((unsigned long long)schar%VBYTES != 0)
*schar++ = (unsigned char)c;
vec_t cdata;
unsigned long long ulc = (unsigned char)c;
ulc = (((ulc << 56)|(ulc << 48))|((ulc << 40)|(ulc << 32)))|(((ulc << 24)|(ulc << 16))|((ulc << 8)|ulc));
cdata[0] = ulc;
cdata[1] = ulc;
cdata[2] = ulc;
cdata[3] = ulc;
//cdata[0] = cdata[1] = cdata[2] = cdata[3] =
//cdata[4] = cdata[5] = cdata[6] = cdata[7] =
//cdata[8] = cdata[9] = cdata[10] = cdata[11] =
//cdata[12] = cdata[13] = cdata[14] = cdata[15] =
//cdata[16] = cdata[17] = cdata[18] = cdata[19] =
//cdata[20] = cdata[21] = cdata[22] = cdata[23] =
//cdata[24] = cdata[25] = cdata[26] = cdata[27] =
//cdata[28] = cdata[29] = cdata[30] = cdata[31] =
// (unsigned char)c;
//对着100多条的初始化语句懵逼...
//然后改成上面这样了(
//手调了下产出的汇编的赋值部分(三操作数四操作数让我着实花了好多时间去理解...
//↑你都手调了,不调成少量的情况下没有惩罚(
//emmm主要是不知道cpu到底会怎么预测,所以就不动这部分了(
while(n >= VBYTES){
*(vec_t *)schar = cdata;
schar += VBYTES;
n -= VBYTES;
}
}
while(n > 0){
*schar++ = (unsigned char)c;
n--;
}
return s;
}
|
C | /*****************************************
Emitting C Generated Code
*******************************************/
#include <functional>
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
/**************** Snippet ****************/
void Snippet(int x0) {
int x1 = 100;
std::function<int*(int)> x2 = [&](int x3) {
int* x4 = (int*)malloc(x3 * sizeof(int));
x4[0] = x1;
x1 = 20;
return x4;
};
int* x5 = x2(3);
int x6 = x1;
x5[1] = x6;
printf("%d, %d, %d\n", x5[0], x6, x1);
}
/*****************************************
End of C Generated Code
*******************************************/
int main(int argc, char *argv[]) {
if (argc != 2) {
printf("usage: %s <arg>\n", argv[0]);
return 0;
}
Snippet(atoi(argv[1]));
return 0;
}
|
C | #include <stdio.h>
#include <string.h>
const char* color[] = {"red", "blue", "yellow", "green", "black"};
int main(){
char str[10];
scanf("%s", str);
for (register int i = 0; i < 5; i++)
if (strcmp(str, color[i]) == 0){
printf("%d\n", i+1);
goto Founded;
}
printf("Not Found\n");
return 0;
Founded:
return 0;
} |
C | #include <stdio.h>
#include <laniakea/ini.h>
void test_section_insert()
{
la_ini_section *sec = la_ini_section_new("Section 1");
la_ini_section_insert(sec, "key1", "value1");
la_ini_section_insert(sec, "key2", "value2");
la_ini_section_free(sec);
}
void test_insert()
{
la_ini *ini = la_ini_new();
la_ini_insert(ini, "Section 1", "key1", "value1");
la_ini_insert(ini, "Section 1", "key2", "value2");
la_ini_insert(ini, "Section 2", "key1", "value1");
la_ini_insert(ini, "Section 2", "key2", "value2");
la_ini_insert(ini, "Section 3", "key1", "value1");
la_ini_insert(ini, "Section 4", "key1", "value1");
la_ini_free(ini);
}
int main()
{
//======================
// Test section insert
//======================
printf("test section insert.\n");
printf("=====================\n");
test_section_insert();
printf("\n");
//================
// Test insert
//================
printf("test insert.\n");
printf("==============\n");
test_insert();
printf("\n");
//================
// Test load
//================
printf("test load\n");
printf("==============\n");
la_ini *ini = la_ini_new();
int err = la_ini_load(ini, "tests/test.ini");
if (err != LA_FILE_ERROR_SUCCESS) {
fprintf(stderr, "Failed to load ini file.\n");
return 1;
}
printf("\n");
//=================
// Test reload
//=================
printf("test reload\n");
printf("==================\n");
la_ini_free(ini);
ini = la_ini_new();
la_ini_load(ini, "tests/test.ini");
la_ini_free(ini);
ini = la_ini_new();
la_ini_load(ini, "tests/test.ini");
printf("\n");
//=================
// Test save
//=================
printf("test save\n");
printf("=============\n");
err = la_ini_save(ini, "tests/save_test.ini");
if (err != LA_FILE_ERROR_SUCCESS) {
fprintf(stderr, "Failed to save ini file.\n");
return 1;
}
// Free.
la_ini_free(ini);
return 0;
}
|
C | #include<cstdio>
class Buffer {
public:
virtual int size() = 0;
virtual char &elem(int idx) = 0;
};
#define ARRAY_SIZE 10
class ArrayBuffer : public Buffer {
char buf[ARRAY_SIZE];
int id;
public:
int size() override {
return sizeof(buf);
}
char &elem(int idx) override {
return buf[idx];
}
ArrayBuffer(int id) : buf{}, id(id) {}
};
class DynamicBuffer : public Buffer {
char *buf;
int _size;
public:
int size() override {
return _size;
}
char &elem(int idx) override {
return buf[idx];
}
DynamicBuffer(int size) : buf(new char[size]), _size(size) {}
};
Buffer *makeBuffer(char *arr, int size) {
if (size > ARRAY_SIZE) {
Buffer *buf = new DynamicBuffer(size);
for (int i = 0; i < size; i++) {
buf->elem(i) = arr[i];
}
return buf;
} else {
Buffer *buf = new ArrayBuffer(1);
for (int i = 0; i < size; i++) {
buf->elem(i) = arr[i];
}
return buf;
}
}
int main() {
char arr[12] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
Buffer *buf = makeBuffer(arr, sizeof(arr));
Buffer *arrBuf = new ArrayBuffer(0);
for (int i = 0; i < buf->size(); i++) {
arrBuf->elem(i) = buf->elem(i);
}
for (int i = 0; i < arrBuf->size(); i++) {
printf("%d ", arrBuf->elem(i));
}
printf("\n");
}
|
C | #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(int argc, char **argv){
unsigned int i;
int arquivo = open("mem4disk.DATA", O_RDONLY);
char *mem;
if((mem = (char*) malloc(DATASIZE)) == NULL){
perror("memory failure");
exit(EXIT_FAILURE);
}
for(i=0; i<NUMBERWRITE; i++){
if(read(arquivo, mem, DATASIZE) != DATASIZE){
perror("read failure");
exit(EXIT_FAILURE);
}
}
close(arquivo);
return EXIT_SUCCESS;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.