language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
|---|---|
C
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: main.c
* Author: Vitor
*
* Created on 8 de Junho de 2018, 11:11
*/
#include <stdio.h>
#include <stdlib.h>
/*
*
*/
int main(void)
{
int matriz[4][5];
int i,j,somatotal = 0,somalinha;
//preencher a matriz
for(i=0;i<4;i++)
{
for(j=0;j<5;j++)
{
printf("M[%d,%d]: ",i+1,j+1);
scanf(" %d", &matriz[i][j]);
}
}
//soma linha e total
for(i=0;i<4;i++)
{
somalinha=0;
for(j=0;j<5;j++)
somalinha=somalinha + matriz[i][j];
printf("A soma da linha %d é %d\n", i+1, somalinha);
somatotal= somatotal + somalinha;
}
printf("A soma total foi de %d", somatotal);
}
|
C
|
/*
* The Towers Of Hanoi
* C
* Copyright (C) 1998 Amit Singh. All Rights Reserved.
*
* Tested with, ah well ... :)
*/
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#define FROM 1
#define TO 3
#define USING 2
void
dohanoi(int N, int from, int to, int using)
{
if (N > 0) {
dohanoi(N-1, from, using, to);
#ifdef PRINT
printf ("move %d --> %d\n", from, to);
#endif
dohanoi(N-1, using, to, from);
}
}
int
main (void)
{
long int N = 10;
/* a bit of error checking, LONG_XXX should be there in limits.h */
if (N == LONG_MIN || N == LONG_MAX || N <= 0) {
#ifdef PRINT
fprintf(stderr, "illegal value for number of disks\n");
#endif
exit(2);
}
dohanoi(N, FROM, TO, USING);
exit(0);
}
|
C
|
/*分数求和*/
#include <stdio.h>
long long gcd(long long a,long long b)//求最大公约数。
{
if(a == 0)
return 0;
else
return (b == 0) ? a : gcd(b, a % b);
}
int main()
{
int N;
long long lcp;//用以记录最小公倍数
long long a,b,c,d;
int i = 1;
scanf("%d",&N);
scanf("%lld/%lld",&a,&b);
int t0 = gcd(a,b);
if(a)
{
a /= t0;
b /= t0;
}
while(i < N)
{
scanf("%lld/%lld",&c,&d);
lcp = b / gcd(b,d) * d;//通过最大公约数换算出两个分母的最小公倍数
a = a * lcp / b + c * lcp / d;//通分后分子和
b = lcp;
int t0 = gcd(a,b);
if(t0 != 0)//从扩大最小公倍数之后的形式变换回来
{
a = a / t0;
b = b / t0;
}
i++;
}
if(a && a/b == 0)/// 整数部分为0 且 a不为 0
printf("%lld/%lld\n",a%b,b);
else if(a%b == 0)/// 小数部分为0
printf("%lld\n",a/b);
else
printf("%lld %lld/%lld\n",a/b,a%b,b);
return 0;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include "header.h"
int checkCollision(BoundingBox box1, BoundingBox box2) {
/*printf("box1 : %f %f %f %f\n", box1.pMinX, box1.pMaxX, box1.pMinY, box1.pMaxY);
printf("box2 : %f %f %f %f\n", box2.pMinX, box2.pMaxX, box2.pMinY, box2.pMaxY);*/
/* Collisions par l'avant */
if (box1.pMaxX > box2.pMinX && box1.pMaxX < box2.pMaxX) {
/* Collisions par dessus */
if (box1.pMinY < box2.pMaxY && box1.pMinY > box2.pMinY) {
return 1;
}
/* Collisions par dessous */
else if (box1.pMaxY > box2.pMinY && box1.pMaxY < box2.pMaxY) {
return 1;
}
}
/* Collisions par l'arrière */
else if (box1.pMinX < box2.pMaxX && box1.pMinX > box2.pMinX) {
/* Collisions par dessus */
if (box1.pMinY < box2.pMaxY && box1.pMinY > box2.pMinY) {
return 1;
}
/* Collisions par dessous */
else if (box1.pMaxY > box2.pMinY && box1.pMaxY < box2.pMaxY) {
return 1;
}
}
return 0;
}
// Gère les collisions entre les enemies et les obstacles
void collEnemiesObstacles(ObstacleList *obstacle, EnemyList *enemy) {
ObstacleList tmp = *obstacle;
if (tmp != NULL) {
int coll = collEnemies(enemy, tmp->box);
if (coll == 1) {
printf("collision avec enemy / décor\n");
}
collEnemiesObstacles(&tmp->next, enemy);
}
}
void collEnemiesMissiles(MissileList *missile, EnemyList *enemy) {
MissileList tmp = *missile;
if (tmp != NULL) {
int coll = collEnemies(enemy, tmp->box);
if (coll == 1) {
printf("collision avec enemy / missile\n");
supprimerMissileFromList(tmp, missile);
}
collEnemiesMissiles(&tmp->next, enemy);
}
}
void collObstaclesMissiles(MissileList *missile, ObstacleList *obstacle) {
MissileList tmp = *missile;
if (tmp != NULL) {
int coll = collObstacles(obstacle, tmp->box);
if (coll == 1) {
printf("collision avec obstacle / missile\n");
supprimerMissileFromList(tmp, missile);
}
collObstaclesMissiles(&tmp->next, obstacle);
}
}
|
C
|
#include <stdio.h>
#include <malloc.h>
#include <math.h>
#include <memory.h>
/*
* License:
* CC BY 4.0
*
* Author: DrMarcel
*/
/*
* Infos:
* YUV, 4:2:0
* CIF:352x288 -> Luminanz
* 176x144 -> Chrominanz
* Framerate:30Hz
*
* Dateiaufbau
* Bild 1 YUV , Bild 2 YUV, Bild 3 YUV, ...
* 1byte pro px
*
*/
/* Constants
*/
static const unsigned int W = 352;
static const unsigned int H = 288;
static const unsigned int BLOCK_W = 16;
static const unsigned int BLOCK_H = 16;
/* Structure contains the YUV color data
* of a Frame with the size WxH px.
* The memory locaction of a specific pixel
* can be reached with addr=y*W+x.
*/
typedef struct
{
unsigned char* y;
unsigned char* u;
unsigned char* v;
} Frame;
/* Structure contains the YUV color data
* of a Block with the size BLOCK_WxBLOCK_H px.
* The memory locaction of a specific pixel
* can be reached with addr=y*BLOCK_W+x.
*/
typedef struct
{
unsigned char* y;
unsigned char* u;
unsigned char* v;
} Block;
/* Allocate memory for one Frame
*/
Frame* newFrame()
{
Frame *frame = malloc(sizeof(Frame));
frame->y = malloc(W*H);
frame->u = malloc(W*H/4);
frame->v = malloc(W*H/4);
return frame;
}
/* Allocate memory for one Block
*/
Block* newBlock()
{
Block *block = malloc(sizeof(Block));
block->y = malloc(BLOCK_W*BLOCK_H);
block->v = malloc(BLOCK_W*BLOCK_H/4);
block->u = malloc(BLOCK_W*BLOCK_H/4);
return block;
}
/* Free memory of one Frame
*/
void freeFrame(Frame* frame)
{
free(frame->y);
free(frame->u);
free(frame->v);
free(frame);
}
/* Free memory of one Block
*/
void freeBlock(Block* block)
{
free(block->y);
free(block->u);
free(block->v);
free(block);
}
/* Read the YUV data of a single Frame
* out of a file. The file has to be opened
* before and closed after the function call.
* The function can be called multiple times
* to read more than one Frame.
*/
Frame* readFrame(FILE *fp)
{
Frame *frame = newFrame();
fread(frame->y, sizeof(unsigned char), W*H, fp);
fread(frame->u, sizeof(unsigned char), W*H/4, fp);
fread(frame->v, sizeof(unsigned char), W*H/4, fp);
return frame;
}
/* Write Y data of a Frame into a file.
* The file has to be opened before and closed
* after the function call.
*/
void writeFrameY(FILE *fp, Frame* frame)
{
fwrite(frame->y, sizeof(unsigned char),W*H, fp);
}
/* Write U data of a Frame into a file.
* The file has to be opened before and closed
* after the function call.
*/
void writeFrameU(FILE *fp, Frame* frame)
{
fwrite(frame->u, sizeof(unsigned char),W*H/4, fp);
}
/* Write V data of a Frame into a file.
* The file has to be opened before and closed
* after the function call.
*/
void writeFrameV(FILE *fp, Frame* frame)
{
fwrite(frame->v, sizeof(unsigned char),W*H/4, fp);
}
/* Write a Frame into a file. The function can
* be called multiple times to generate a *.yuv
* conform file.
* The file has to be opened before and closed
* after the function call.
*/
void writeFrame(FILE *fp, Frame* frame)
{
writeFrameY(fp, frame);
writeFrameU(fp, frame);
writeFrameV(fp, frame);
}
/* Returns a data array which contains the
* difference d2 - d1 for each element of the
* input arrays and the average difference.
*
* d1: Pointer to array 1
* d2: Pointer to array 2
* DW: 2d Array width
* DW: 2d Array height
* MSE: Return pointer for average difference
*/
unsigned char* getDifData(unsigned char* d1, unsigned char* d2, unsigned int DW, unsigned int DH, double* MSE)
{
//Alloc output array
unsigned char* ret = malloc(DW*DH);
double MSEtmp=0;
//Loop over all array elements
for(unsigned int y=0; y<DH; y++)
{
for(unsigned int x=0; x<DW; x++)
{
//Calculate d2-d1
int dif = (int)(d2[y*DW + x]) - (int)(d1[y*DW + x]);
//Offset and overflow control
int difoff = dif + 127;
if(difoff > 255) difoff = 255;
if(difoff < 0) difoff = 0;
//Output data
ret[y*DW + x] = (unsigned char)(difoff);
//Sum squared difference over all elements
MSEtmp += dif*dif;
}
}
//Calculate and return MSE
MSEtmp = MSEtmp / (W*H);
if(MSE!=NULL) *MSE = MSEtmp;
//Return array data
return ret;
}
/* Returns difference between two Frames f2-f1
* and the average difference MSE of the Luminance.
*/
Frame* getDifFrame(Frame* f1, Frame* f2, double* MSE)
{
Frame *frame = newFrame();
frame->y = getDifData(f1->y, f2->y, W, H, MSE);
frame->u = getDifData(f1->u, f2->u, W/2, H/2, NULL);
frame->v = getDifData(f1->v, f2->v, W/2, H/2, NULL);
return frame;
}
/* Returns difference between two Blocks b2-b1
* and the average difference MSE of the Luminance.
*/
Block* getDifBlock(Block* b1, Block* b2, double* MSE)
{
Block *block = newBlock();
block->y = getDifData(b1->y, b2->y, BLOCK_W, BLOCK_H, MSE);
block->u = getDifData(b1->u, b2->u, BLOCK_W/2, BLOCK_H/2, NULL);
block->v = getDifData(b1->v, b2->v, BLOCK_W/2, BLOCK_H/2, NULL);
return block;
}
/* Return a single Block of a Frame at position (x,y)px.
* The return value is NULL if the Block is out of
* the Frame borders.
*/
Block* getBlock(Frame *frame, unsigned int x, unsigned int y)
{
//Check if Block is within Frame
if(x+BLOCK_W > W || y+BLOCK_H > H) return NULL;
Block* block = newBlock();
//Copy Block line by line
//Line address in Block: iy*BLOCK_W
//Line address plus Block offset in Frame: (y+iy)*W+x
for(unsigned int iy=0; iy<BLOCK_H; iy++)
memcpy(&block->y[iy*BLOCK_W], &frame->y[(y+iy)*W+x], BLOCK_W);
return block;
}
/* Copy a single Block into a Frame at position (x,y)px.
* Does nothing if Block is outside Frame border.
*/
void setBlock(Frame *frame, Block *block, unsigned int x, unsigned int y)
{
//Check if Block is within Frame
if(x+BLOCK_W > W || y+BLOCK_H > H) return;
//Copy Block line by line
//Line address in Block: iy*BLOCK_W
//Line address plus Block offset in Frame: (y+iy)*W+x
for(unsigned int iy=0; iy<BLOCK_H; iy++)
memcpy(&frame->y[(y+iy)*W+x], &block->y[iy*BLOCK_W], BLOCK_W);
}
/* Get the Block from a source Frame which is most similar
* to a block at a specific position in target Frame.
* Searches in the source frame in the space (x+-area,y+-area).
*
* target: The frame that should be predicted
* source: The source Frame from which the target should be predicted
* x,y: Position of the Block in target Frame to predict
* vectx,vecty: Pointer return the offset for the movement prediction
* area: Space around (x,y) to search for a prediction Block
*/
Block* getPredictBlock(Frame* target, Frame* source, unsigned int x, unsigned int y, int* vectx, int* vecty, int area)
{
Block *targetBlock = getBlock(target,x,y);
//Save the data of the Block with the lowest MSE
Block *lowestMSEBlock = NULL;
double lowestMSE=0;
int lowestMSEVectX=0;
int lowestMSEVectY=0;
//Loop over the search area
for(int iy=-area; iy<=area; iy++)
{
for(int ix=-area; ix<=area; ix++)
{
//Calculate position of the Block to compare
int compx=(int)x+ix;
int compy=(int)y+iy;
//Check if block is within source Frame
if(compx>=0 && compy>=0 && (unsigned)compx+BLOCK_W<W && (unsigned)compy+BLOCK_H<H)
{
//Get Block from source to compare with target
Block *compBlock = getBlock(source,(unsigned)compx,(unsigned)compy);
//Calculate MSE between source and target Block
double MSE;
getDifBlock(compBlock,targetBlock,&MSE);
//Check if MSE is lower than before
//or no Block has been selected before
if(MSE<lowestMSE || lowestMSEBlock==NULL)
{
lowestMSE = MSE;
lowestMSEVectX=ix;
lowestMSEVectY=iy;
lowestMSEBlock = compBlock;
}
}
}
}
//Return Block data
*vectx = lowestMSEVectX;
*vecty = lowestMSEVectY;
return lowestMSEBlock;
}
int main()
{
printf("\n*** Initialize ***\n");
//Try to open input file
printf("Open ../videodecoder/FOOTBALL_352x288_30_orig_01.yuv\n");
FILE* fp_in = fopen("../videodecoder/FOOTBALL_352x288_30_orig_01.yuv", "rb");
if(fp_in == NULL)
{
printf("File read error!\n");
return 1;
}
//Read the first two frames
printf("Read frame1\n");
Frame* frame1 = readFrame(fp_in);
printf("Read frame2\n");
Frame* frame2 = readFrame(fp_in);
//Close file
printf("Close file\n");
fclose(fp_in);
// ### Methode 1 ###
printf("\n*** Methode 1 ***\n");
//Get dif frame and MSE
printf("Calculate frame2 - frame1\n");
double MSE = 0;
Frame* out1 = getDifFrame(frame1, frame2, &MSE);
//Output MSE
printf("MSE: %f\n", MSE);
//Try to open output file
printf("Open file ../videodecoder/output_m1_error.yuv\n");
FILE* fp_out = fopen("../videodecoder/output_m1_error.yuv", "wb");
if(fp_out == NULL)
{
printf("File write error!");
return 1;
}
//Output dif frame
printf("Output frame data\n");
writeFrameY(fp_out, out1);
//Close file
printf("Close file\n");
fclose(fp_out);
// ### Methode 2 ###
printf("\n*** Methode 2 ***\n");
//Generate prediction Frame
Frame* predict = newFrame();
//Loop over all Blocks in source Frame
for(unsigned int by=0; by<H; by+=BLOCK_H)
{
for(unsigned int bx=0; bx<W; bx+=BLOCK_W)
{
//Find prediction for current Block
printf("Predict block[%d,%d] : ", bx/BLOCK_W, by/BLOCK_H);
int vx, vy;
Block* ret = getPredictBlock(frame2,frame1,bx,by,&vx,&vy,16);
printf("vector = (%d,%d)px\n", vx, vy);
//Draw the prediction Block into prediction Frame
setBlock(predict,ret,bx,by);
}
}
//Get dif frame and MSE
printf("Calculate predict_frame - frame2\n");
double MSE2 = 0;
Frame* out2 = getDifFrame(predict, frame2, &MSE2);
//Output MSE
printf("MSE: %f\n", MSE2);
//Try to open output file
printf("Open file ../videodecoder/output_m2_error.yuv\n");
FILE* fp_out2 = fopen("../videodecoder/output_m2_error.yuv", "wb");
if(fp_out2 == NULL)
{
printf("File write error!");
return 1;
}
//Output dif frame
printf("Output frame data\n");
writeFrameY(fp_out2, out2);
//Try to open output file
printf("Open file ../videodecoder/output_m2_predict.yuv\n");
FILE* fp_out3 = fopen("../videodecoder/output_m2_predict.yuv", "wb");
if(fp_out3 == NULL)
{
printf("File write error!");
return 1;
}
//Output dif frame
printf("Output frame data\n");
writeFrameY(fp_out3, predict);
//Close file
printf("Close file\n");
fclose(fp_out3);
//Free memory
freeFrame(frame1);
freeFrame(frame2);
freeFrame(predict);
freeFrame(out1);
freeFrame(out2);
printf("\nFinish!\n\n");
return 0;
}
|
C
|
/*-----------Matrice de covariance pour un processus Ornstein-Uhlenbeck-------------------------*/
/*-mvMORPH 1.0.3 - 2014 - Julien Clavel - julien.clavel@hotmail.fr/julien.clavel@univ-lyon1.fr--*/
#include "mvmorph.h"
// Fixed root covariance matrix
static void mvmorph_covar_OU_fixed(int *nt,
double *A,
double *ans,
double *alpha,
double *sigma) {
double sij, ti, tj, T, temp, var, value;
int n = *nt;
int i, j;
var=sigma[0]/(2.0*alpha[0]);
/* Compute the vcv-Ou matrix */
for(i=0; i<n; i++){
for(j=0; j<=i; j++){
/* allows non-ultrametric trees */
sij=A[j*n+i];
ti = A[i+i*n]-A[j+i*n];
tj = A[j+j*n]-sij;
T=ti+tj;
temp=(1-exp(-2.0*alpha[0]*sij))*exp(-1.0*alpha[0]*T);
value=temp*var;
ans[i*n+j]=value;
if (j != i){
ans[j*n+i]=value;
}
}
}
}
// Random root covariance matrix
static void mvmorph_covar_OU_random(int *nt,
double *A,
double *ans,
double *alpha,
double *sigma) {
double ti, tj, T, var, value;
int n = *nt;
int i, j;
var=sigma[0]/(2.0*alpha[0]);
/* Compute the vcv-Ou matrix */
for(i=0; i<n; i++){
for(j=0; j<=i; j++){
/* allows non-ultrametric trees */
ti = A[i+i*n]-A[j+i*n];
tj = A[j+j*n]-A[j*n+i];
T=ti+tj;
value=var*exp(-1.0*alpha[0]*T);
ans[i*n+j]=value;
if (j != i){
ans[j*n+i]=value;
}
}
}
}
// fixed and random root covariance matrix
SEXP mvmorph_covar_ou_fixed(SEXP A, SEXP alpha, SEXP sigma) {
int nt;
PROTECT(coerceVector(A,REALSXP));
nt=INTEGER(GET_DIM(A))[0];
SEXP ans;
PROTECT(ans = allocMatrix(REALSXP,nt,nt));
mvmorph_covar_OU_fixed(&nt,REAL(A),REAL(ans),REAL(alpha), REAL(sigma));
UNPROTECT(2);
return ans;
}
SEXP mvmorph_covar_ou_random(SEXP A, SEXP alpha, SEXP sigma) {
int nt;
PROTECT(coerceVector(A,REALSXP));
nt=INTEGER(GET_DIM(A))[0];
SEXP ans;
PROTECT(ans = allocMatrix(REALSXP,nt,nt));
mvmorph_covar_OU_random(&nt,REAL(A),REAL(ans),REAL(alpha), REAL(sigma));
UNPROTECT(2);
return ans;
}
|
C
|
//>>> 使用参数
#include<stdio.h>
int main(int argc, char** argv)
{
while(*++argv!=NULL)
{
printf("%s ", *argv);
}
if(argc>1)
printf("\n");
return 0;
}
|
C
|
#include "types.h"
#include "stat.h"
#include "user.h"
void small_stack()
{
char name[256] = "small-stack()";
int i = 0;
char j[20];
uint k = 97;
for(i = 0; i < 20; i++)
{
j[i] = k++;
}
printf(1,"name: \"%s\" address: %d\n",name, &name);
printf(1,"i: %d address: %d\n",i, &i);
for(i = 19; i >= 0; i--)
{
printf(1,"j[%d]: %c address: %d\n",i, j[i], &j[i]);
}
return;
}
int main(int argc, char **argv)
{
printf(1,"STARTING TEST: small-stack.\nallocating 1 page less amount of varibles in a function (stack) and check the addresses.\n");
printf(1,"EXPECTED: varibles are allocated on stack and addresses should look reasonable.\n");
small_stack();
printf(1,"EXPECTED: varibles are allocated on stack and addresses look reasonable.\n");
printf(1,"TEST PASSED\n");
exit();
}
|
C
|
/**
* Gauss-Seidel implementation using pthreads.
*
*
* Course: Advanced Computer Architecture, Uppsala University
* Course Part: Lab assignment 3
*
* Original author: Frdric Haziza <daz@it.uu.se>
* Heavily modified by: Andreas Sandberg <andreas.sandberg@it.uu.se>
*
*/
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "gs_interface.h"
/**
* Tell the startup code that we want run in parallel mode.
*/
const int gsi_is_parallel = 1;
/**
* Thread data structure passed to the thread entry function.
*/
typedef struct {
int thread_id;
pthread_t thread;
volatile double error;
/* TASK: Do you need any thread local state for synchronization? */
volatile int curRow;
int padd_data1[8];
} thread_info_t;
/** Define to enable debug mode */
#define DEBUG 0 /* 1 */
/** Debug output macro. Only active when DEBUG is non-0 */
#define dprintf(...) \
if (DEBUG) \
fprintf(stderr, __VA_ARGS__)
/** Vector with information about all active threads */
thread_info_t *threads = NULL;
/** The global error for the last iteration */
static double global_error;
pthread_barrier_t barrier;
void
gsi_init()
{
gs_verbose_printf("\t**** Initializing the environment ****\n");
threads = (thread_info_t *)malloc(gs_nthreads * sizeof(thread_info_t));
if (!threads) {
fprintf(stderr,
"Failed to allocate memory for thread information.\n");
exit(EXIT_FAILURE);
}
/* Initialize global_error to something larget than the
* tolerance to get the algorithm started */
global_error = gs_tolerance + 1;
/* TASK: Initialize global variables here */
pthread_barrier_init(&barrier, NULL, gs_nthreads);
for(int i=0; i<4; i++)
threads[i].curRow=0;
}
void
gsi_finish()
{
gs_verbose_printf("\t**** Cleaning environment ****\n");
/* TASK: Be nice and cleanup the stuff you initialized in
* gsi_init()
*/
if (threads)
free(threads);
}
static void
thread_sweep(int tid, int iter, int lbound, int rbound)
{
threads[tid].error = 0.0;
for (int row = 1; row < gs_size - 1; row++) {
dprintf("%d: checking wait condition iteration: %i, row: %i\n", tid, iter, row);
/* TASK: Wait for data to be available from the thread
* to the left */
while(tid!=0 && threads[tid-1].curRow <= threads[tid].curRow){}
dprintf("%d: Starting on row: %d\n", tid, row);
/* Update this thread's part of the matrix */
for (int col = lbound; col < rbound; col++) {
double new_value = 0.25 * (
gs_matrix[GS_INDEX(row + 1, col)] +
gs_matrix[GS_INDEX(row - 1, col)] +
gs_matrix[GS_INDEX(row, col + 1)] +
gs_matrix[GS_INDEX(row, col - 1)]);
threads[tid].error +=
fabs(gs_matrix[GS_INDEX(row, col)] - new_value);
gs_matrix[GS_INDEX(row, col)] = new_value;
}
/* TASK: Tell the thread to the right that this thread
* is done */
threads[tid].curRow++;
dprintf("%d: row %d done\n", tid, row);
}
threads[tid].curRow++;
}
/**
* Computing routine for each thread
*/
static void *
thread_compute(void *_self)
{
thread_info_t *self = (thread_info_t *)_self;
const int tid = self->thread_id;
int lbound, rbound;
/* TASK: Compute bounds for this thread */
lbound = tid * (gs_size/gs_nthreads);
rbound = (tid+1) * (gs_size/gs_nthreads); // Deduct one to avoid overlap of columns.
if(tid == 0)
lbound++;
if(tid == gs_nthreads-1)
rbound--;
printf("Left: %d, Right: %d \n", lbound, rbound);
gs_verbose_printf("%i: lbound: %i, rbound: %i\n",
tid, lbound, rbound);
for (int iter = 0;
iter < gs_iterations && global_error > gs_tolerance;
iter++) {
dprintf("%i: Starting iteration %i\n", tid, iter);
thread_sweep(tid, iter, lbound, rbound);
/* TASK: Update global error */
/* Note: The reduction should only be done by one
* thread after all threads have updated their local
* errors */
/* Hint: Which thread is guaranteed to complete its
* sweep last? */
if(gs_nthreads-1 == tid){
global_error = 0.0;
for(int i=0; i<=gs_nthreads; i++)
global_error+=threads[i].error;
}
dprintf("%d: iteration %d done\n", tid, iter);
/* TASK: Iteration barrier */
pthread_barrier_wait(&barrier);
}
gs_verbose_printf(
"\t**** Thread %d done after %d iterations ****\n",
tid, gs_iterations);
return NULL;
}
/**
* Parallel implementation of the GS algorithm. Called from
* gs_common.c to start the solver.
*/
void
gsi_calculate()
{
int err;
for (int t = 0; t < gs_nthreads; t++) {
gs_verbose_printf("\tSpawning thread %d\n",t);
threads[t].thread_id = t;
err = pthread_create(&threads[t].thread, NULL,
thread_compute, &threads[t]);
if (err) {
fprintf(stderr,
"Error: pthread_create() failed: %d, "
"thread %d\n",
err, t);
exit(EXIT_FAILURE);
}
}
/* Calling pthread_join on a thread will block until the
* thread terminates. Since we are joining all threads, we
* wait until all threads have exited. */
for (int t = 0; t < gs_nthreads; t++) {
err = pthread_join(threads[t].thread, NULL);
if (err) {
fprintf(stderr,
"Error: pthread_join() failed: %d, "
"thread %d\n",
err, t);
exit(EXIT_FAILURE);
}
}
if (global_error <= gs_tolerance)
printf("Solution converged!\n");
else {
printf("Solution did NOT converge.\n");
printf("Note: This is normal if you are using the "
"default settings.\n");
}
printf("Final global error: %f\n", global_error);
printf("Size of pthread_t: %ld\n", sizeof(thread_info_t));
}
/*
* Local Variables:
* mode: c
* c-basic-offset: 8
* indent-tabs-mode: nil
* c-file-style: "linux"
* End:
*/
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_DB_LENGTH 1000
struct directoryDB {
int num;
char element[100];
char isLast;
};
struct mapDB {
char element[100];
char map[20];
};
struct directoryDB dirDB[MAX_DB_LENGTH];
struct mapDB mDB[MAX_DB_LENGTH];
int dirDB_len = 0;
int mDB_len = 0;
void getDirectory() {
char buffer[1024];
char* context = NULL;
int num = 0;
FILE* file;
fopen_s(&file, "Directory.csv", "r");
if (file) {
while (fgets(buffer, sizeof(buffer), file) != NULL) {
dirDB[num].num = atoi(strtok_s(buffer, ",", &context));
strcpy_s(dirDB[num].element, 100, strtok_s(NULL, ",", &context));
dirDB[num].isLast = strtok_s(NULL, "", &context)[0];
num++;
}
dirDB_len = num;
fclose(file);
}
}
void getMap() {
char buffer[1024];
char* context = NULL;
int num = 0;
FILE* file;
fopen_s(&file, "Map.csv", "r");
if (file) {
while (fgets(buffer, sizeof(buffer), file) != NULL) {
strcpy_s(mDB[num].element, 100, strtok_s(buffer, ",", &context));
strcpy_s(mDB[num].map, 20, strtok_s(NULL, ",", &context));
num++;
}
mDB_len = num;
fclose(file);
}
}
char* getMapNumber(char* element) {
int i;
for (i = 0; i < mDB_len; i++) {
if (strcmp(element, mDB[i].element) == 0) {
return mDB[i].map;
}
}
}
|
C
|
//使用pthread_create函数实现线程的创建
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
void* task(void *p)
{
while(1)
printf("我是子线程\n");
}
int main(void)
{
//启动一个新的线程
pthread_t tid;
pthread_create(&tid,NULL,task,NULL);
usleep(100000);
return 0;
}
|
C
|
//Code by AkshayKumar Prakash Mantriwar TY CSE A-DIV
#include<stdio.h>
void main(){
int adj[20][20],n,i,j,c=0,k,d=0,S[20],sindex=0,Q[20],min=999,counter=0;
char vertices[20],Q1[20];
scanf("%d",&n);
for(i=0;i<n;i++){ //get the adj matrix
for(j=0;j<n;j++){
scanf("%d",&adj[i][j]);
}
}
scanf("%s",&vertices); //get the name of vertices
for(i=0;i<n;i++){
Q[i]=999;
}
Q[0]=0;
c=1;
while(c < n ){ // n-1 times
c++;
for(i=0;i<n;i++){
for(j=0;j<n;j++){
if(adj[i][j]!=0){
if(Q[j] > Q[i]+adj[i][j]){ //relax...updating
Q[j] = Q[i]+adj[i][j];
S[j]=i;
}
}
}
for(k=0;k<n;k++){
printf("%c\t%d\n",vertices[k],Q[k]);
}
}
}
for(i=0;i<n;i++){ //nth time
for(j=0;j<n;j++){
if(adj[i][j]!=0){
if(Q[j]>Q[i]+adj[i][j]){
printf("found a neg cycle\n");
}
}
}}
for(i=0;i<n;i++){
printf("%c\t%d\n",vertices[i],Q[i]);
}
}
|
C
|
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
struct sockaddr_in addr;
if (inet_aton("10.0.0.1", &addr.sin_addr)) {
for (int i = 0; i < 4; i++) {
printf("%d ", (addr.sin_addr.s_addr >> (i * 8)) & 0xff);
}
printf("\n");
} else {
perror("inet_aton()");
}
printf("%s\n", inet_ntoa(addr.sin_addr));
addr.sin_addr.s_addr = inet_addr("10.0.0.2");
for (int i = 0; i < 4; i++) {
printf("%d ", (addr.sin_addr.s_addr >> (i * 8)) & 0xff);
}
printf("\n");
printf("%s\n", inet_ntoa(addr.sin_addr));
return EXIT_SUCCESS;
}
|
C
|
#include <stdio.h>
#include <string.h>
// PART 2
void findStr() {
char smallest_word[20] = "zzzzzzzzzzzzzzzzzzzz"; //biggest string possible in dictionary order
char largest_word[20] = ""; // smallest string possible
char input[20];
// if (strcmp("cat",smallest_word) > 0) {
// strcpy(smallest_word,"cat");
// printf("%s\n", smallest_word);
// }
while ((unsigned)strlen(input) != 4) {
printf("Enter word: ");
scanf("%[^\n]%*c", input);
if (strcmp(input,smallest_word) < 0) { //if input smaller than smallest_word
strcpy(smallest_word,input);
} else if (strcmp(input,largest_word) > 0) { // if input bigger than largest_word
strcpy(largest_word,input);
}
}
printf("Smallest word: %s\n", smallest_word);
printf("Largest word: %s\n", largest_word);
}
int main()
{
findStr();
return 0;
}
|
C
|
/* Copyright 2011 Tom Jollans <t@jollybox.de>
* This code is under the Chicken Dance License v0.1 */
#include <stdio.h>
#include "card.h"
char *irc_print_card (card_t card, int color, int utf8)
{
static const char *red_start = "\x03" "4 ";
static const char *red_end = "\x03";
static char result[32];
char *resp = result;
int red = 0;
switch (card.suit) {
case DIAMONDS:
case HEARTS:
red = color;
default:;
}
if (red) {
resp += sprintf(resp, "%s", red_start);
}
switch (card.value) {
case 1:
resp += sprintf(resp, " A");
break;;
case 11:
resp += sprintf(resp, " J");
break;;
case 12:
resp += sprintf(resp, " Q");
break;;
case 13:
resp += sprintf(resp, " K");
break;;
default:
resp += sprintf(resp, "%2d", card.value);
}
switch (card.suit) {
case CLUBS:
if (utf8) resp += sprintf(resp, "\xe2\x99\xa3");
else resp += sprintf(resp, " Clubs");
break;;
case DIAMONDS:
if (utf8) resp += sprintf(resp, "\xe2\x99\xa6");
else resp += sprintf(resp, " Diamonds");
break;;
case HEARTS:
if (utf8) resp += sprintf(resp, "\xe2\x99\xa5");
else resp += sprintf(resp, " Hearts");
break;;
case SPADES:
if (utf8) resp += sprintf(resp, "\xe2\x99\xa0");
else resp += sprintf(resp, " Spades");
break;;
}
if (red) {
resp += sprintf(resp, "%s", red_end);
}
*resp = '\0';
return result;
}
|
C
|
#include "Dev_Inf.h"
/* This structure containes information used by ST-LINK Utility to program and erase the device */
#if defined (__ICCARM__)
__root struct StorageInfo const StorageInfo = {
#else
struct StorageInfo const StorageInfo = {
#endif
.DeviceName = "W25Q32FV_STM32F730", // Device Name + version number
.DeviceType = SPI_FLASH, // Device Type
.DeviceStartAddress = 0x90000000, // Device Start Address
.DeviceSize = 0x00400000, // Device Size in Bytes (32Mbits)
.PageSize = 0x00000100, // Programming Page Size
.EraseValue = 0xFF, // Initial Content of Erased Memory
// Specify Size and Address of Sectors (view example below)
.sectors = {
{ // Sector Num : 8 ,Sector Size: 32KBytes
.SectorNum = 0x00000080,
.SectorSize = 0x000008000
},
{
.SectorNum = 0x00000000,
.SectorSize = 0x00000000
},
},
};
/* Sector coding example
A device with succives 16 Sectors of 1KBytes, 128 Sectors of 16 KBytes,
8 Sectors of 2KBytes and 16384 Sectors of 8KBytes
0x00000010, 0x00000400, // 16 Sectors of 1KBytes
0x00000080, 0x00004000, // 128 Sectors of 16 KBytes
0x00000008, 0x00000800, // 8 Sectors of 2KBytes
0x00004000, 0x00002000, // 16384 Sectors of 8KBytes
0x00000000, 0x00000000, // end
*/
|
C
|
#include<stdlib.h>
/* The function get_len
* returns the length of the input number
* It takes a argument (unsigned long void) and
* returns length of number (int)
*/
int get_len (long value){
int l=1;
while(value>9)
{
l++;
value/=10;
}
return l;
}
/* The function power computes the power recursively
* and returns the value of x ^ y
* It takes 2 arguments (unsigned long,int) and
* returns a number (long)
*/
int power(int x,int y)
{
if( y == 0)
return 1;
else if (y%2 == 0)
return power(x, y/2)*power(x, y/2);
else
return x*power(x, y/2)*power(x, y/2);
}
/*
* The function returns a pointer to
* a newly allocated space in memory,
* which contains a string representing
* the number given as a parameter
*
*/
char *int_to_string(int x)
{
int len = 0,i = 0,j = 0,flag = 0;
char *s; long n = x, temp =0;
if ( n < 0 )
{
n = n * -1;
flag = 1;
}
len = get_len(n);
s = flag ? malloc(sizeof( *s ) * (len + 1)): malloc(sizeof( *s ) * len);
if (s == NULL)
return (NULL);
else
{
if(flag)
{
s[j]='-';
j++;
}
for(i = len -1 ;i >= 0; i--, j++)
{
temp = n / power(10,i);
s[j] = temp + 48;
n = n - temp * power(10 , i);
}
}
return s;
}
|
C
|
#include <stdarg.h>
#include "util/util_printer.h"
/**
* Print the string to stream with the selected color and add a newline if newline is true
* @param stream Stream pointer output
* @param color The Color
* @param format The String
* @param newline Add a newline at the end
* @param args Format tags
*/
static void printer(FILE *stream, const char *color, const char *format, bool newline, va_list args);
static void printer(FILE *stream, const char *color, const char *format, bool newline, va_list args) {
fprintf(stream, "%s", color);
vfprintf(stream, format, args);
fprintf(stream, "%s", COLOR_RESET);
if (newline) fprintf(stream, "\n");
}
void print(const char *format, ...) {
va_list args;
va_start(args, format);
printer(stdout, COLOR_WHITE, format, false, args);
va_end(args);
}
void print_color(const char *color, const char *format, ...) {
va_list args;
va_start(args, format);
printer(stdout, color, format, false, args);
va_end(args);
}
void println(const char *format, ...) {
va_list args;
va_start(args, format);
printer(stdout, COLOR_WHITE, format, true, args);
va_end(args);
}
void println_color(const char *color, const char *format, ...) {
va_list args;
va_start(args, format);
printer(stdout, color, format, true, args);
va_end(args);
}
|
C
|
#include <stdio.h>
#include <math.h>
int main() {
float sqrt(float x) {
float e = 0.000001, g2 = x/2, g1;
do {
g1 = g2;
g2 = (g1 + x/g1)/2;
} while(((g2 - g1)/g2) * ((g2 - g1)/g2));
return g2;
}
return 0;
}
|
C
|
#pragma once
#include "stdafx.h"
typedef struct
{
unsigned char packet[1500]; //һݰͷ
int packet_len; //ݰЧ freadʱõ
int ID; //IDʱ丳ֵ
} PAC;
struct Stream_list //
{
UINT32 src_addr;
UINT32 dst_addr;
UINT16 src_port;
UINT16 dst_port; //ipͶ˿Ϊĵһʶ
int stream_ID; //IDΪĵڶʶ ΪͬipͶ˿пܵڶνӡ
//STREAM stream; // дŰID 鲻
//PAC packet[135];
int packet[200]; // ݰidʶʡռ䡣
int packet_number; //
struct Stream_list *next;
//PAC packet[100]
};
typedef struct Stream_list STREAM_LIST;
struct Stream //ݰ
{
unsigned char packet[1500];
int packet_len;
struct Stream *next;
};
typedef struct Stream STREAM;
|
C
|
/*
* main.c
*
* Created on: Dec 31, 2015
* Author: m.mamdooh
*/
#include "stdio.h"
#include "string.h"
#include "stdlib.h"
#include <ctype.h>
static const long hextable[] = {
[0 ... 255] = -1, // bit aligned access into this table is considerably
['0'] = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, // faster for most modern processors,
['A'] = 10, 11, 12, 13, 14, 15, // for the space conscious, reduce to
['a'] = 10, 11, 12, 13, 14, 15 // signed char.
};
long hexdec(unsigned const char *hex);
void dectohex(long int decimalNumber ,unsigned char *hexadecimalNumber);
void bintodec( long int binaryNumber);
void dectobin(int decimalno);
void append(char* s, char c);
unsigned char sk[100]="0" ,uc,dechex[100]="0", hexstr[50]="0";
char x [100] ={0} ;
unsigned char entry_1[23],entry_2[23] , command[1000] , lmd[20] ,st1[100] ;
char ch, lns=0 , lmod=0 , dig1=0,dig2=0;
long int cs=0 ,s=0 , count=0, c=0 ,i=0 ,lines=1,flines,hexadecimalNumber=0;
FILE *fasm , *fhex , *fi;
void init();
void ifile();
void read();
void write_rlen();
void write_add() ;
void write_rectyp();
void lins_num();
void write_data();
void write_chksum();
int main ()
{
init();
ifile();
lins_num();
for(count=0 ; count<=lns ; count++)
{
if(flines == (count*8)) break ;
write_rlen();
write_add();
write_rectyp();
write_data();
write_chksum();
cs=0;
fprintf(fhex, "\n");
}
fprintf(fhex, ":00000001FF") ;
return 0 ;
}
void write_chksum()
{
fhex = fopen("filehex" , "r+");
c=count+2; // counter for hex file lines + 2
cs=0;
while(c)
{ // the program will read the lines by the : , so it has to read accourding to number of lines it's write on to wriite the cs in the right place
while(dig1 != ':')
dig1 = fgetc(fhex);
dig1=0;
c--;
}
while(!feof(fhex))
{
dig1 = fgetc(fhex);//reading the 2 digits each time
dig2 = fgetc(fhex);
//printf("%c %c\n",dig1,dig2);
sprintf(sk, "%c%c", dig1,dig2); //converting the digits to string sk
s=hexdec(sk); // converting the string to hex dec. num
//printf("%d\n",s);
if(s!=-1) // making sure that it reades right hex num , if the hex is wrong the func ret -1
cs+=s;
//printf("%d\n",cs);
}
dectohex(cs,dechex) ; //converting the number to hex to get only it's low nible "first 2 hex nums"
//printf("%s\n",dechex);
uc=hexdec(dechex); // converting the two digits back to dec with implicit casting to unsigned char
uc=~uc+1 ; // taking the 2's complement
dectohex(uc,dechex) ; //returning the num back to hex
//printf("%c %c",dechex[0],dechex[1]);
fputc(dechex[0],fhex); //printing the cs in the hex file
fputc(dechex[1],fhex);
}
void init()
{
fasm = fopen("fileasm" , "r"); //opening the file and printing the first fixed line
fhex = fopen("filehex" , "w");
fi = fopen("filei" , "w");
fprintf(fhex, ":020000020000FC\n");
}
void ifile()
{
char *token ;
while(!feof(fasm))
{
fgets (x, 100, fasm); // reding all the data from the asm file line by line
//printf("%s\n",x);
for(i=0 ; i<100;i++)
{
if(x[i]==',') // converting every "," in the file to space
x[i]=' ';
if(x[i]=='\0') // converting every NULL in the file to space
x[i]=' ';
}
/* get the first token */
fwrite(x , 1 , sizeof(x) , fi ); //write the modified asm file to an intermediate file
}
fclose(fi);
fclose(fasm);
}
void lins_num()
{
fi = fopen("filei" , "r");
fasm = fopen("fileasm" , "r");
//fprintf(fhex, ":") ;
while(!feof(fasm))
{
ch = fgetc(fasm);
if(ch == '\n')
{
lines++; //counting how many lines in the asm file
}
}
//printf("%d",lines);
flines=lines; // fixed lines number
lns=lines/8;
lmod=lines%8 ;
}
void read ()
{
fscanf(fi,"%s%s%s",command,entry_1,entry_2); //reading first 3 strings from each line in the asm file
//printf("\n%s%s%s",command,entry_1,entry_2);
// if(isdigit(atoi(command)))
// strcpy(command," ");
}
void write_rlen()
{
if(count<lns)
fprintf(fhex, ":10") ; // if there is a complete line the rec length will be 10
else
{
lmod*=2 ; // if the line is not complete , each line of inst take 2 bytes
if (lmod>9)
{
lmod%=10 ;
switch(lmod)
{
case 0 : fprintf(fhex, ":0A") ;
break;
case 1 : fprintf(fhex, ":0B") ;
break;
case 2 : fprintf(fhex, ":0C") ;
break;
case 3 : fprintf(fhex, ":0D") ;
break;
case 4 : fprintf(fhex, ":0E") ;
break;
case 5 : fprintf(fhex, ":0F") ;
break;
}
}
else
{
itoa(lmod, lmd, 10);
fprintf(fhex, ":0");
fprintf(fhex, lmd) ;
}
}
}
void write_add()
{
char j[100] ;
if (count>9)
{
switch(count)
{
case 10 : count='A' ;
break;
case 11 : count='B' ;
break;
case 12 : count='C' ;
break;
case 13 : count='D' ;
break;
case 14 : count='E' ;
break;
case 15 :count='F' ;
break;
}
}
if(count<=16)
{
fprintf(fhex, "00");
itoa(count,j,10);
fprintf(fhex, j);
fprintf(fhex, "0");
}
else if (count>(16) && count<=(32) )
{
fprintf(fhex, "01");
itoa(count,j,10);
fprintf(fhex, j);
fprintf(fhex, "0");
}
else if (count>(32) && count<=(48) )
{
fprintf(fhex, "02");
itoa(count,j,10);
fprintf(fhex, j);
fprintf(fhex, "0");
}
}
void write_rectyp(void)
{
fprintf(fhex, "00");
}
void write_data()
{
//printf("%d",lines);
int count =0 ,k=0 ,l=0;
unsigned char com[100] , obc[100] ,reg1[100],reg2[100]="NULL" , tobc[100] , hexstr1[10]="0",hexstr2[10]="0",hexstr3[10]="0",hexstr4[10]="0";
FILE *fot;
fot=fopen("opcodtable" , "r");
while(lines)
{
read();
//printf("\n%s",command);
while(!feof(fot))
{
fscanf(fot,"%s%s",com,obc);
if(!strcmp(command,com))
strcpy(tobc,obc);
else if(!strcmp(entry_1,com))
strcpy(reg1,obc);
else if(!strcmp(entry_2,com))
strcpy(reg2,obc);
}
//
if(!strcmp(command ,"SBI")||!strcmp(command ,"CBI")||!strcmp(command ,"SBIC")||!strcmp(command ,"SBIS"))
{
dectobin(atoi(entry_2));
strcat(reg1,st1);
bintodec(atoi(reg1));
dectohex(hexadecimalNumber,hexstr4);
printf("\n%s",hexstr4);
printf("\n%s",tobc);
fprintf(fhex, hexstr4);
fprintf(fhex, tobc);
}
else if(!strcmp(command ,"ADD")||!strcmp(command ,"ADC")||!strcmp(command ,"AND")||!strcmp(command ,"CP")||!strcmp(command ,"EOR")||!strcmp(command ,"MOV")||!strcmp(command ,"SUB")||!strcmp(command ,"OR")||!strcmp(command ,"SBC")||!strcmp(command ,"MUL"))
{
append(tobc,reg2[0]);
strcat(tobc,reg1);
for(k=1;k<5;k++)
append(tobc,reg2[k]);
for(k=0;k<8;k++)
{
hexstr1[k]=tobc[k];
}
bintodec(atoi(hexstr1));
dectohex(hexadecimalNumber,hexstr2);
for(k=8;k<16;k++)
{
hexstr[l]=tobc[k];
l++;
}
bintodec(atoi(hexstr));
// printf("\n%s",hexstr);
dectohex(hexadecimalNumber,hexstr3);
// printf("\n%s",hexstr3);
// printf("\n%s",hexstr2);
fprintf(fhex, hexstr3);
fprintf(fhex, hexstr2);
}
else
{
fprintf(fhex, tobc);
}
lines--;
count++;
if (count==8)
break;
l=0;
fseek(fot, 0, SEEK_SET );
}
fclose(fhex);
}
long hexdec(unsigned const char *hex) {
long ret = 0;
while (*hex && ret >= 0) {
ret = (ret << 4) | hextable[*hex++];
}
return ret;
}
void dectohex(long int decimalNumber ,unsigned char *hexadecimalNumber)
{
long int quotient;
long int i=1,temp;
quotient = decimalNumber;
while(quotient!=0) {
temp = quotient % 16;
//To convert integer into character
if( temp < 10)
temp =temp + 48;
else
temp = temp + 55;
hexadecimalNumber[i--]= temp;
quotient = quotient / 16;
}
}
void dectobin(int decimalno)
{
int i =0 ,d;
unsigned char stt[50];
if(decimalno==0)
strcpy(st1,"000");
while(decimalno>0)
{
d=decimalno%2;
itoa(d,stt,10);
if(i==0)
strcpy(st1,stt);
else
strcat(st1,stt);
i++;
decimalno=decimalno/2;
}
if(strlen(st1)==1)
strcat(st1,"00");
else if(strlen(st1)==2)
strcat(st1,"0");
strrev(st1);
}
void bintodec( long int binaryNumber)
{
long int j=1,remainder;
hexadecimalNumber=0;
while(binaryNumber!=0){
remainder=binaryNumber%10;
hexadecimalNumber=hexadecimalNumber+remainder*j;
j=j*2;
binaryNumber=binaryNumber/10;
}
}
void append(char* s, char c)
{
int len = strlen(s);
s[len] = c;
s[len+1] = '\0';
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char *argv[]) {
struct timeval tv1,tv2;
int rs, i;
char key[4096]; // ũ. δ پ ũ⸦ ó ־ .
char value[256]; // ũ. δ پ ũ⸦ ó ־ .
char buf[256]; // ũ. δ پ ũ⸦ ó ־ .
gettimeofday(&tv1, NULL);
rs=kvopen();
gettimeofday(&tv2, NULL);
printf("kvopen ok %d\n", rs);
printf("time : %f\n",((tv2.tv_sec+tv2.tv_usec*0.000001)-(tv1.tv_sec+tv1.tv_usec*0.000001)));
gettimeofday(&tv1, NULL);
for (i=0; i<100; i++)
{
rs=kvput(key, value);
}
gettimeofday(&tv2, NULL);
printf("kvput ok %d\n", rs);
printf("time : %f\n",((tv2.tv_sec+tv2.tv_usec*0.000001)-(tv1.tv_sec+tv1.tv_usec*0.000001)));
gettimeofday(&tv1, NULL);
for (i=0; i<100; i++)
{
rs=kvget(key, buf);
}
gettimeofday(&tv2, NULL);
printf("kvget ok %d\n", rs);
printf("time : %f\n",((tv2.tv_sec+tv2.tv_usec*0.000001)-(tv1.tv_sec+tv1.tv_usec*0.000001)));
gettimeofday(&tv1, NULL);
for (i=0; i<100; i++)
{
rs=kvdel(key);
}
gettimeofday(&tv2, NULL);
printf("kvdel ok %d\n", rs);
printf("time : %f\n",((tv2.tv_sec+tv2.tv_usec*0.000001)-(tv1.tv_sec+tv1.tv_usec*0.000001)));
gettimeofday(&tv1, NULL);
rs=kvclose();
gettimeofday(&tv2, NULL);
printf("kvclose ok %d\n", rs);
printf("time : %f\n",((tv2.tv_sec+tv2.tv_usec*0.000001)-(tv1.tv_sec+tv1.tv_usec*0.000001)));
return 0;
}
|
C
|
/* pe14-5.c -- student */
#include <stdio.h>
#define CSIZE 4
struct name {
char first[20];
char last[20];
};
struct student {
struct name st_name;
float grades[3];
float average;
};
void print_student(struct student * pstudent);
int main(void)
{
struct student students[CSIZE];
float average_grades[3] = {0, 0, 0};
int i;
for (i = 0; i < CSIZE; i++) {
printf("Enter student name: ");
scanf("%s %s", students[i].st_name.first, students[i].st_name.last);
printf("Enter grades:");
scanf("%f %f %f", &students[i].grades[0], &students[i].grades[1], &students[i].grades[2]);
while (getchar() != '\n')
continue;
students[i].average = (students[i].grades[0] + students[i].grades[1] + students[i].grades[2]) / 3;
}
for (i = 0; i < CSIZE; i++) {
average_grades[0] += students[i].grades[0];
average_grades[1] += students[i].grades[1];
average_grades[2] += students[i].grades[2];
}
for (i = 0; i < CSIZE; i++) {
print_student(&students[i]);
}
for (i = 0; i < 3; i++)
printf("%.2f ", average_grades[i]/CSIZE);
return 0;
}
void print_student(struct student * pstudent)
{
printf("Student name: %s %s\n", pstudent->st_name.first, pstudent->st_name.last);
printf("Grades: %.2f %.2f %.2f\n", pstudent->grades[0], pstudent->grades[1], pstudent->grades[2]);
printf("Average grade: %.2f\n", pstudent->average);
}
|
C
|
/*
* Copyright (c) 2010 Scott Vokes <vokes.s@gmail.com>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <stdlib.h>
#include <unistd.h>
#define DEF_PAUSE 1
#define DEBUG 0
static double p_avg();
static void wait_until_idle(int, double, int);
static double p_avg() {
double avg[1];
if (getloadavg(avg, 1) == -1) {
printf("got error\n");
exit(1);
}
return avg[0];
}
static void wait_until_idle(int wait, double load, int maxwait) {
int waited = 0;
double cur_load;
if (DEBUG) printf("maxwait: %d\n", maxwait);
while ((cur_load = p_avg()) >= load) {
sleep(wait);
waited += wait;
if (DEBUG) printf("load: %2.2f\twaited: %d\n",
cur_load, waited);
if (maxwait > 0 && waited >= maxwait) break;
}
}
static void print_usage() {
printf("idlewait: Sleep until system load is less than the first argument.\n");
printf("Usage: idlewait load [max_wait_in_seconds]\n");
}
int main(int argc, char* argv[]) {
int pause = DEF_PAUSE;
int maxwait = 0; /* forever */
double load;
if (argc < 2 || argc > 3) {
print_usage();
exit(1);
} else if (argc == 3) {
maxwait = atoi(argv[2]);
}
load = strtod(argv[1], NULL);
if (load <= 0) {
printf("Invalid load: %s\n", argv[1]);
printf("(Load must be a decimal, e.g. 1.4.)\n", argv[1]);
exit(1);
}
wait_until_idle(pause, load, maxwait);
return 0;
}
|
C
|
//Question de l'exam
1()
int i = 5;
int j = 2;
printf("%f",1.5+(float)(i+1)/(float)j+5/j);
=> 1.5+6.0/2.0+5/2
=> 1.5+6.0/2.0+2
=> 1.5+3+2
=> 6.5 => Réponse
2()
int *ptr,*tmp,*v;
int a;
v=&a;
ptr=v;
tmp=ptr;
v=ptr;
=> QCM 3 propositions => Tout pointe vers a
3()
int i = 0;
int v = 0;
while(i == 0 || v == 20)
{
if(v % 20)
i++;
v = v + 10;
}
//Combien de tour de boucle va faire le programme?
//Propositions: 1,0,3,5,20
Réponse:Tour de boucle => 3
4()
//Exercices complet en programmation papier
5()
//Ecrire les prototypes des 2 fonctions
int a[10][5],*b,*c,n;
char nom[25];
b=&a[0][0];
n=Fonction1(b,n,nom);
Fonctions2(&b,n)
//Réponse:
int Fonction1(int *,int ,char*)
void Fonction2(int **,int) //=>Attention au deux "*"
6()
//Tableau et il faut acceder au 5eme element
//t est un tableau
a:t[4]
b:t,4
c:t+4
d:*(t+4)
e:4t[]
Réponses:a et d
7()
//QCM 4 choix
int main(void)
{
int tab[10];
int *start = ; //1
int *end = ; //2
int taille_tab = ; //3
return 0;
}
//un pointeur moins un autre donne l'indice du pointeur a la fin
Réponse: //1 = &tab[0] 2 = &tab[9] 3 = end + 1
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "hw6.h"
int main()
{
FloatList *aList = CreateFloatList();
if(NULL == aList)
{
return -1;
}
AddFloatValue(aList,3.283);
AddFloatValue(aList,3.243);
AddFloatValue(aList,8.143);
AddFloatValue(aList,9.944);
AddFloatValue(aList,6.193);
AddFloatValue(aList,8.936);
AddFloatValue(aList,1.458);
AddFloatValue(aList,1.234);
AddFloatValue(aList,9.876);
PrintList(aList);
printf("The value at index %d: %.3f\n", 5, FloatValueIndex(aList, 5));
printf("The count of value in the list: %d\n", aList->count);
InsertFloatValueIndex(aList, 2.825, 0);
PrintList(aList);
DeleteFloatValueIndex(aList,8);
PrintList(aList);
printf("\n");
printf("\tBefore sorting:\n");
PrintList(aList);
printf("\n");
printf("\tAfter sorting:\n");
shellSort(aList);
PrintList(aList);
DeleteFloatList(aList);
return 0;
}
|
C
|
/*
Author: Dung Harry
Date created: 22nd, December 2013
Operating System: Ubuntu 13.10 Desktop x86_64
Compiler: GNU compiler 4.4.0
Description: this is the testing source code for shared library
in C programming language
Compile this source code into shared library by following
commands:
gcc -c -fpic SharedLib.c
gcc -shared -o libSharedLib.so SharedLib.o
export LD_LIBRARY_PATH=[path to this
folder]:$LD_LIBRARY_PATH
*/
#include <stdio.h>
#include <stdlib.h>
typedef struct stCaculator Caculator;
struct stCaculator {
int data;
int (*add) (Caculator *pCaculator, int a);
int (*multiply) (Caculator *pCaculator, int a);
void (*print) (Caculator *pCaculator);
void (*input) (Caculator *pCaculator);
};
int iCCLT_add(Caculator *pCaculator, int a);
int iCCLT_multiply(Caculator *pCaculator, int a);
void vCCLT_print(Caculator *pCaculator);
void vCCLT_input(Caculator *pCaculator);
void Caculator1(Caculator **pCaculator) {
(*pCaculator) = (Caculator *) malloc(sizeof(Caculator));
(*pCaculator)->add = &iCCLT_add;
(*pCaculator)->multiply = &iCCLT_multiply;
(*pCaculator)->print = &vCCLT_print;
(*pCaculator)->input = &vCCLT_input;
}
int iCCLT_add(Caculator *pCaculator, int a) {
return pCaculator->data += a;
}
int iCCLT_multiply(Caculator *pCaculator, int a) {
return pCaculator->data *= a;
}
void vCCLT_print(Caculator *pCaculator) {
printf("The value is: %d\n", pCaculator->data);
}
void vCCLT_input(Caculator *pCaculator) {
printf("Enter the value: ");
scanf("%d", &(pCaculator->data));
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define NUM_THREADS 2
typedef struct rectangle_t
{
double length;
double width;
} rectangle;
void *thread_function(void *arg)
{
rectangle *r = (rectangle *)arg;
float r_length = r->length;
float r_width = r->width;
float r_area = r_length * r_width;
printf("l=%.2f, w=%.2f, area=%.2f\n", r_length, r_width, r_area);
pthread_exit(NULL);
}
int main(int argc, char *argv[])
{
pthread_t t[NUM_THREADS];
rectangle *r1, *r2;
long i;
r1 = malloc(sizeof(rectangle));
r1->length = 4;
r1->width = 2;
r2 = malloc(sizeof(rectangle));
r2->length = 6.8;
r2->width = 4;
printf("Creating thread 1\n");
pthread_create(&t[0], NULL, thread_function, (void *)r1);
printf("Creating thread 2\n");
pthread_create(&t[1], NULL, thread_function, (void *)r2);
printf("Waiting for the threads to end\n");
for (i = 0; i < NUM_THREADS; i++)
{
pthread_join(t[i], NULL);
}
printf("The threads are over\n");
return 0;
}
|
C
|
/*Code to test bluetooth serial connection
using android phone with app inventor app
as device to connect to....
Module: HC-05
baud=9600
Author: Jose Estrada
*/
#include <stdio.h>
#include <string.h>
#include <wiringPi.h>
#include <wiringSerial.h>
//GPIO pin setup
#define motor1 0
#define motor2 1
#define motor3 2
#define motor4 3
int main(void){
//Necessary variables to initailize
int fd,x,i=0;
char data[5];
wiringPiSetup(); //Needed to setup wiringPi library
//GPIO pin setup
pinMode(motor1,OUTPUT); //set pin 0 to control motor1
pinMode(motor2,OUTPUT); //set pin 1 to control motor2
pinMode(motor3,OUTPUT); //set pin 2 to control motor3
pinMode(motor4,OUTPUT); //set pin 3 to control motor4
printf("Start Bluetooth Communication\n");
fd=serialOpen("/dev/ttyAMA0",9600); //Open serial port and set baud=9600
for(;;){
while(serialDataAvail(fd)){
data[i++]=(char)serialGetchar(fd);
if(strcmp(data,"on")==0){
digitalWrite(motor1,HIGH);
printf("-> %s\n",data);
fflush(stdout);
for(x=0;x<i;x++){
data[x]=0;
}
i=0;
}
else if(strcmp(data,"off")==0){
digitalWrite(motor1,LOW);
printf("-> %s\n",data);
fflush(stdout);
for(x=0;x<i;x++){
data[x]=0;
}
i=0;
}
}
}
return 0;
}
|
C
|
#include "grammar.h"
#include <stdio.h>
#include <stdlib.h>
TryVariable_t parse_typedef(const ConstString_t str) {
TryVariable_t output;
TryConstString_t typedef_str = find_string(str, const_string_from_cstr("typedef"));
if (typedef_str.status == TRY_SUCCESS) {
ConstString_t working = strip(str, typedef_str.value).value;
TryConstString_t ws = find_whitespace(working);
if (ws.status == TRY_NONE) {
output.status = TRY_ERROR;
output.error.location = working;
output.error.desc = "There must be whitespace after a typedef";
return output;
}
working = strip_whitespace(working);
output = parse_variable(working);
return output;
}
output.status = TRY_NONE;
return output;
}
/**
* Parse a statement
* SUCCESS: a statement was parsed
* NONE: a statement was not found
* ERROR: there was an error with statement syntax
*/
TryStatement_t parse_statement(const ConstString_t str, ErrorLinkedListNode_t ***const errors, ConstString_t *const stmt_str) {
TryStatement_t output;
output.value.variant = STATEMENT_DECLARATION;
ConstString_t working = strip_whitespace(str);
stmt_str->begin = str.begin;
if (*working.begin == '{') {
TryConstString_t braces = find_closing(working, '{', '}');
GrammarPropagateError(braces, output);
if (braces.status == TRY_SUCCESS) {
stmt_str->end = braces.value.end;
ConstString_t contents;
contents.begin = braces.value.begin + 1;
contents.end = braces.value.end - 1;
TryScope_t scope = parse_scope(contents, errors);
GrammarPropagateError(scope, output);
if (scope.status == TRY_SUCCESS) {
output.status = TRY_SUCCESS;
output.value.str = working;
output.value.variant = STATEMENT_SCOPE;
output.value.scope = malloc(sizeof(Scope_t));
*output.value.scope = scope.value;
return output;
}
}
}
TryConstString_t keyword;
Control_t control;
if ((keyword = find_string(working, const_string_from_cstr("break"))).status == TRY_SUCCESS) {
output.value.variant = STATEMENT_CONTROL;
control.variant = CONTROL_BREAK;
}
else if ((keyword = find_string(working, const_string_from_cstr("continue"))).status == TRY_SUCCESS) {
output.value.variant = STATEMENT_CONTROL;
control.variant = CONTROL_CONTINUE;
}
else if ((keyword = find_string(working, const_string_from_cstr("return"))).status == TRY_SUCCESS) {
output.value.variant = STATEMENT_CONTROL;
control.variant = CONTROL_RETURN;
}
if (output.value.variant == STATEMENT_CONTROL) {
TryConstString_t semicolon = find_string_nesting_sensitive(working, const_string_from_cstr(";"));
GrammarPropagateError(semicolon, output);
if (semicolon.status == TRY_NONE) {
output.status = TRY_ERROR;
output.error.location = keyword.value;
output.error.desc = "Control statement should be ended by a ';'";
return output;
}
ConstString_t following;
following.begin = keyword.value.end;
following.end = semicolon.value.begin;
TryConstString_t ws = find_whitespace(following);
following = strip_whitespace(following);
if (following.begin != following.end) {
if (control.variant == CONTROL_RETURN) {
TryExpression_t expr = parse_right_expression(following);
GrammarPropagateError(expr, output);
if (expr.status == TRY_NONE) {
output.status = TRY_ERROR;
output.error.location = following;
output.error.desc = "return accepts only right expressions";
return output;
}
control.ret = expr.value;
}
else {
output.status = TRY_ERROR;
output.error.location = following;
output.error.desc = "break/continue does not accept data";
return output;
}
}
else if (control.variant == CONTROL_RETURN) {
control.ret.variant = EXPRESSION_VOID;
}
output.status = TRY_SUCCESS;
output.value.control = malloc(sizeof(Control_t));
*output.value.control = control;
output.value.str.begin = working.begin;
output.value.str.end = semicolon.value.end;
stmt_str->end = semicolon.value.end;
return output;
}
if ((keyword = find_string(working, const_string_from_cstr("if"))).status == TRY_SUCCESS) {
output.value.variant = STATEMENT_CONTROL;
control.variant = CONTROL_IF;
}
else if ((keyword = find_string(working, const_string_from_cstr("for"))).status == TRY_SUCCESS) {
output.value.variant = STATEMENT_CONTROL;
control.variant = CONTROL_FOR;
}
else if ((keyword = find_string(working, const_string_from_cstr("while"))).status == TRY_SUCCESS) {
output.value.variant = STATEMENT_CONTROL;
control.variant = CONTROL_WHILE;
}
else if ((keyword = find_string(working, const_string_from_cstr("do"))).status == TRY_SUCCESS) {
output.value.variant = STATEMENT_CONTROL;
control.variant = CONTROL_DO;
}
if (output.value.variant == STATEMENT_CONTROL) {
ConstString_t cont_working = strip_whitespace(strip(working, keyword.value).value);
if (control.variant == CONTROL_IF || control.variant == CONTROL_WHILE || control.variant == CONTROL_FOR) {
TryConstString_t cond_str = find_closing(cont_working, '(', ')');
GrammarPropagateError(cond_str, output);
if (cond_str.status == TRY_NONE) {
output.status = TRY_ERROR;
output.error.location = cont_working;
output.error.desc = "Control statement needs condition in ()";
return output;
}
cont_working = strip_whitespace(strip(cont_working, cond_str.value).value);
cond_str.value.begin += 1;
cond_str.value.end -= 1;
if (control.variant == CONTROL_IF || control.variant == CONTROL_WHILE) {
TryExpression_t cond = parse_right_expression(cond_str.value);
GrammarPropagateError(cond_str, output);
if (cond.status == TRY_NONE) {
output.status = TRY_ERROR;
output.error.location = cond_str.value;
output.error.desc = "Control statement needs a condition in ()";
return output;
}
control.condition = cond.value;
}
else {
ConstString_t init_str, check_str, inc_str;
TryConstString_t semicolon1_str = find_string_nesting_sensitive(cond_str.value, const_string_from_cstr(";"));
GrammarPropagateError(semicolon1_str, output);
if (semicolon1_str.status == TRY_NONE) {
output.status = TRY_ERROR;
output.error.location = cond_str.value;
output.error.desc = "For statement needs a first ';'";
return output;
}
init_str.begin = cond_str.value.begin;
init_str.end = semicolon1_str.value.begin;
cond_str.value.begin = semicolon1_str.value.end;
TryConstString_t semicolon2_str = find_string_nesting_sensitive(cond_str.value, const_string_from_cstr(";"));
GrammarPropagateError(semicolon2_str, output);
if (semicolon2_str.status == TRY_NONE) {
output.status = TRY_ERROR;
output.error.location = cond_str.value;
output.error.desc = "For statement needs a second ';'";
return output;
}
check_str.begin = semicolon1_str.value.end;
check_str.end = semicolon2_str.value.begin;
inc_str.begin = semicolon2_str.value.end;
inc_str.end = cond_str.value.end;
TryExpression_t init_expr = parse_right_expression(init_str);
GrammarPropagateError(init_expr, output);
if (init_expr.status == TRY_NONE) {
control.ctrl_for.init = NULL;
}
else {
control.ctrl_for.init = malloc(sizeof(Expression_t));
*control.ctrl_for.init = init_expr.value;
}
TryExpression_t cond_expr = parse_right_expression(check_str);
GrammarPropagateError(cond_expr, output);
if (cond_expr.status == TRY_NONE) {
control.condition.variant = EXPRESSION_UINT_LIT;
control.condition.uint_lit = 1;
}
else {
control.condition = cond_expr.value;
}
TryExpression_t inc_expr = parse_right_expression(inc_str);
GrammarPropagateError(inc_expr, output);
if (inc_expr.status == TRY_NONE) {
control.ctrl_for.increment = NULL;
}
else {
control.ctrl_for.increment = malloc(sizeof(Expression_t));
*control.ctrl_for.increment = inc_expr.value;
}
}
}
ConstString_t exec_str;
TryStatement_t exec = parse_statement(cont_working, errors, &exec_str);
GrammarPropagateError(exec, output);
if (exec.status == TRY_NONE) {
output.status = TRY_ERROR;
output.error.location = cont_working;
output.error.desc = "Control needs a scope";
return output;
}
control.exec = exec.value;
output.value.str.begin = working.begin;
output.value.str.end = exec_str.end;
if (control.variant == CONTROL_IF) {
control.ctrl_if.continuation = NULL;
ConstString_t continuation_str;
continuation_str.begin = exec_str.end;
continuation_str.end = working.end;
continuation_str = strip_whitespace(continuation_str);
TryConstString_t else_str = find_string(continuation_str, const_string_from_cstr("else"));
if (else_str.status == TRY_SUCCESS) {
continuation_str = strip(continuation_str, else_str.value).value;
TryConstString_t id_str = find_identifier(continuation_str);
if (id_str.status == TRY_NONE) {
ConstString_t scope_str;
TryStatement_t else_stmt = parse_statement(continuation_str, errors, &scope_str);
GrammarPropagateError(else_stmt, output);
if (else_stmt.status == TRY_NONE) {
output.status = TRY_ERROR;
output.error.location = cont_working;
output.error.desc = "Else needs a scope";
return output;
}
control.ctrl_if.continuation = malloc(sizeof(Statement_t));
*control.ctrl_if.continuation = else_stmt.value;
output.value.str.end = scope_str.end;
}
}
}
output.status = TRY_SUCCESS;
output.value.control = malloc(sizeof(Control_t));
*output.value.control = control;
stmt_str->end = output.value.str.end;
return output;
}
TryConstString_t parens = find_string_nesting_sensitive(working, const_string_from_cstr("("));
GrammarPropagateError(parens, output);
if (parens.status == TRY_SUCCESS) {
ConstString_t func_str;
func_str.begin = parens.value.begin;
func_str.end = working.end;
parens = find_closing(func_str, '(', ')');
if (parens.status == TRY_SUCCESS) {
func_str = strip(func_str, parens.value).value;
TryConstString_t braces = find_string_nesting_sensitive(working, const_string_from_cstr("{"));
if (braces.status == TRY_SUCCESS) {
func_str.begin = braces.value.begin;
braces = find_closing(func_str, '{', '}');
if (braces.status == TRY_SUCCESS) {
ConstString_t func_sig;
func_sig.begin = working.begin;
func_sig.end = braces.value.begin;
ConstString_t scope_str;
scope_str.begin = braces.value.begin + 1;
scope_str.end = braces.value.end - 1;
TryVariable_t signature = parse_variable(func_sig);
if ( signature.status == TRY_SUCCESS &&
signature.value.has_name &&
signature.value.type->variant == DERIVED_TYPE_FUNCTION) {
TryScope_t scope = parse_scope(scope_str, errors);
if (scope.status == TRY_SUCCESS) {
Function_t *function = malloc(sizeof(Function_t));
function->signature = signature.value;
function->scope = scope.value;
output.status = TRY_SUCCESS;
output.value.variant = STATEMENT_FUNCTION;
output.value.function = function;
stmt_str->end = braces.value.end;
output.value.str.begin = working.begin;
output.value.str.end = braces.value.end;
return output;
}
}
}
}
}
}
TryConstString_t semicolon = find_string_nesting_sensitive(working, const_string_from_cstr(";"));
GrammarPropagateError(semicolon, output);
if (semicolon.status == TRY_NONE) {
output.status = TRY_ERROR;
output.error.location = str;
output.error.desc = "Expected a semicolon";
return output;
}
stmt_str->end = semicolon.value.end;
ConstString_t op_str;
op_str.begin = working.begin;
op_str.end = semicolon.value.begin;
TryOperator_t op = parse_operator(op_str);
if (op.status == TRY_SUCCESS) {
output.status = TRY_SUCCESS;
output.value.str.begin = op_str.begin;
output.value.str.end = semicolon.value.end;
output.value.variant = STATEMENT_OPERATOR;
output.value.operator = malloc(sizeof(Operator_t));
*output.value.operator = op.value;
return output;
}
else {
TryVariable_t var = parse_variable(op_str);
output.value.variant = STATEMENT_DECLARATION;
if (var.status != TRY_SUCCESS) {
var = parse_typedef(op_str);
output.value.variant = STATEMENT_TYPEDEF;
}
if (var.status == TRY_SUCCESS && var.value.has_name) {
output.status = TRY_SUCCESS;
output.value.str.begin = op_str.begin;
output.value.str.end = semicolon.value.end;
output.value.declaration = malloc(sizeof(Variable_t));
*output.value.declaration = var.value;
return output;
}
else {
**errors = malloc(sizeof(ErrorLinkedListNode_t));
(**errors)->next = NULL;
(**errors)->value.location = op_str;
if (var.status == TRY_ERROR) {
(**errors)->value.desc = var.error.desc;
}
else {
(**errors)->value.desc = var.status != TRY_SUCCESS ?
"Operator, declaration, or typedef did not parse" :
"Declaration or typedef has no name";
}
*errors = &(**errors)->next;
}
}
output.status = TRY_NONE;
return output;
}
TryScope_t parse_scope(const ConstString_t str, ErrorLinkedListNode_t ***const errors) {
TryScope_t output;
if (str.begin == str.end) {
output.status = TRY_NONE;
return output;
}
output.status = TRY_SUCCESS;
output.value.statements = NULL;
StatementLinkedListNode_t **stmt_head = &output.value.statements;
ConstString_t working = str;
working = strip_whitespace(working);
while (working.begin < working.end) {
ConstString_t stmt_str;
TryStatement_t stmt = parse_statement(working, errors, &stmt_str);
GrammarPropagateError(stmt, output);
working = strip_whitespace(strip(working, stmt_str).value);
if (stmt.status == TRY_SUCCESS) {
*stmt_head = malloc(sizeof(StatementLinkedListNode_t));
(*stmt_head)->next = NULL;
(*stmt_head)->value = stmt.value;
stmt_head = &(*stmt_head)->next;
}
}
output.status = TRY_SUCCESS;
return output;
}
size_t print_scope(char *buffer, const Scope_t *const scope, const int32_t depth) {
buffer[0] = 0;
size_t num_chars = 0;
const StatementLinkedListNode_t *statement = scope->statements;
if (statement) {
if (depth >= 0) {
num_chars += sprintf(buffer, "{\n");
}
while (statement) {
num_chars += sprintf(buffer + num_chars, "%*s", (depth + 1) * 4, "");
num_chars += print_statement(buffer + num_chars, &statement->value, depth + 1);
num_chars += sprintf(buffer + num_chars, "\n");
statement = statement->next;
}
if (depth >= 0) {
num_chars += sprintf(buffer + num_chars, "%*s}", 4 * depth, "");
}
}
else {
if (depth >= 0) {
num_chars += sprintf(buffer, "{ }");
}
}
return num_chars;
}
size_t print_statement(char *buffer, const Statement_t *const stmt, const int32_t depth) {
buffer[0] = 0;
size_t num_chars = 0;
switch (stmt->variant) {
case STATEMENT_OPERATOR:
num_chars += print_operator(buffer + num_chars, stmt->operator);
num_chars += sprintf(buffer + num_chars, ";");
break;
case STATEMENT_SCOPE:
num_chars += print_scope(buffer + num_chars, stmt->scope, depth);
break;
case STATEMENT_DECLARATION:
num_chars += print_variable(buffer + num_chars, stmt->declaration);
num_chars += sprintf(buffer + num_chars, ";");
break;
case STATEMENT_CONTROL:
switch (stmt->control->variant) {
case CONTROL_IF:
num_chars += sprintf(buffer + num_chars, "if (");
num_chars += print_expression(buffer + num_chars, &stmt->control->condition, NULL);
num_chars += sprintf(buffer + num_chars, ") ");
num_chars += print_statement(buffer + num_chars, &stmt->control->exec, depth);
if (stmt->control->ctrl_if.continuation) {
num_chars += sprintf(buffer + num_chars, "\n%*selse ", depth * 4, "");
num_chars += print_statement(buffer + num_chars, stmt->control->ctrl_if.continuation, depth);
}
break;
case CONTROL_WHILE:
num_chars += sprintf(buffer + num_chars, "while (");
num_chars += print_expression(buffer + num_chars, &stmt->control->condition, NULL);
num_chars += sprintf(buffer + num_chars, ") ");
num_chars += print_statement(buffer + num_chars, &stmt->control->exec, depth);
break;
case CONTROL_FOR:
num_chars += sprintf(buffer + num_chars, "for (");
num_chars += print_expression(buffer + num_chars, stmt->control->ctrl_for.init, NULL);
num_chars += sprintf(buffer + num_chars, "; ");
num_chars += print_expression(buffer + num_chars, &stmt->control->condition, NULL);
num_chars += sprintf(buffer + num_chars, "; ");
num_chars += print_expression(buffer + num_chars, stmt->control->ctrl_for.increment, NULL);
num_chars += sprintf(buffer + num_chars, ") ");
num_chars += print_statement(buffer + num_chars, &stmt->control->exec, depth);
break;
case CONTROL_BREAK:
num_chars += sprintf(buffer + num_chars, "break;");
break;
case CONTROL_CONTINUE:
num_chars += sprintf(buffer + num_chars, "continue;");
break;
case CONTROL_RETURN:
if (stmt->control->ret.variant == EXPRESSION_VOID) {
num_chars += sprintf(buffer + num_chars, "return;");
}
else {
num_chars += sprintf(buffer + num_chars, "return ");
num_chars += print_expression(buffer + num_chars, &stmt->control->ret, NULL);
num_chars += sprintf(buffer + num_chars, ";");
}
break;
}
break;
case STATEMENT_TYPEDEF:
num_chars += sprintf(buffer + num_chars, "typedef ");
num_chars += print_variable(buffer + num_chars, stmt->tdef);
num_chars += sprintf(buffer + num_chars, ";");
break;
case STATEMENT_FUNCTION:
num_chars += print_variable(buffer + num_chars, &stmt->function->signature);
num_chars += sprintf(buffer + num_chars, " ");
num_chars += print_scope(buffer + num_chars, &stmt->function->scope, depth);
break;
}
return num_chars;
}
|
C
|
#include <stdio.h>
#include <signal.h>
void myHandler()
{
printf("Signal caught\n");
}
int main()
{
struct sigaction handler;
handler.sa_handler = myHandler;
sigaction(SIGALRM,&handler,NULL);
while(1)
{
alarm(5);
pause();
}
return 0;
}
|
C
|
//hashmap.h
#ifndef HASHMAP_H
#define HASHMAP_H
typedef struct hashmap_t hashmap_t;
typedef int (*equals_callback_t)(void*,void*);
typedef int (*hashcode_callback_t)(void*);
hashmap_t* new_map(equals_callback_t equals_callback,hashcode_callback_t hashcode_callback);
hashmap_t* new_map_with_init_capacity(equals_callback_t equals_callback,hashcode_callback_t hashcode_callback, size_t initial_capacity);
void* map_insert(hashmap_t* map, void* key, void* value);
void* map_get(hashmap_t* map, void* key);
int map_contains_key(hashmap_t* map, void* key);
int map_is_empty(hashmap_t* map);
void map_keys(hashmap_t* map, void** key_list);
void map_values(hashmap_t* map, void** value_list);
void* map_remove(hashmap_t* map, void* key);
size_t map_size(hashmap_t* map);
void map_free(hashmap_t* map);
size_t map_capacity(hashmap_t* map);
#endif //HASHMAP_H
|
C
|
#include <stdio.h>
int main(){
int i, w, backup_i;
printf("N\t Bin\t Oct\t Hex\n");
/* Istruzioni per ogni riga */
for(i=0; i < 20; i++){
printf("%d\t", i); /* Stampa il numero della riga*/
backup_i = i;
/* Inizio Stampa binario */
for(w = 128; w > 0 ; w/= 2){
printf("%d", i/w);
i %= w;
}
/* Fine stampa binario */
printf(" ");
i = backup_i;
/* Inizio stampa ottale */
for(w = 64; w > 0; w /= 8){
printf("%d", i/w);
i %= w;
}
/* Fine stampa ottale */
printf(" ");
i = backup_i;
/* Inizio stampa esadecimale */
for(w = 16; w > 0; w /= 16){
switch(i/w){
case 10:
printf("A");
break;
case 11:
printf("B");
break;
case 12:
printf("C");
break;
case 13:
printf("D");
break;
case 14:
printf("E");
break;
case 15:
printf("F");
break;
default:
printf("%d", i/w);
}
i %= w;
}
/* Fine stampa esadecimale */
i = backup_i;
printf("\n");
}
printf("\n\n");
return 0;
}
|
C
|
/***********************************************************************
*
* Name: comdrtst
*
* Purpose: Test program for comdrive read and write
*
* Algorithm: Tests both comdrive for both input (com_read)
* and output (com_write)
*
***************************************************************************/
#include <stdio.h>
#include <dos.h>
extern int com_read(char far *buff, int far *len);
extern int com_write(char far *buff, int far *len);
int main()
{
int e_flag;
int tmp;
int rc;
char buffer[100];
char prompt[20];
int length;
rc = com_open(&e_flag,1200);
/* if bad return code, display value and exit */
if (rc != 0)
{
printf("\nrc(com_open) = %d",rc);
exit();
}
strcpy(buffer,"");
while (strcmp(buffer,"quit") != 0)
{
/* command prompt on com port */
length = 16;
e_flag = 0;
rc = com_write("\015\012Enter string: ",&length);
/* if bad return code, display value and exit */
if (rc != 0)
{
printf("\nrc(com_write) = %x",rc);
exit();
}
/* loop until write complete */
while (e_flag == 0)
printf("wait for write\n");
/* read string */
length = 30;
e_flag = 0;
rc = com_read(buffer,&length);
/* if bad return code, display value and exit */
if (rc != 0)
{
printf("\nrc(com_read) = %x",rc);
exit();
}
/* loop until read is done */
while (e_flag == 0)
printf("wait - reading\n");
/* display string entered */
e_flag = 0;
tmp = 22;
rc = com_write("\015\012string entered was: ",&tmp);
/* if bad return code, display value and exit */
if (rc != 0)
{
printf("\nrc(com_write) = %x",rc);
exit();
}
/* loop until write is done */
while (e_flag == 0)
printf("wait for string to be written\n");
e_flag = 0;
rc = com_write(buffer,&length);
/* if bad return code, display value and exit */
if (rc != 0)
{
printf("\nrc(com_write) = %x",rc);
}
/* loop until write is done */
while (e_flag == 0);
}
length = 29;
e_flag = 0;
rc = com_write ("\015\012Com Driver Test Completed\015\012",&length);
/* if bad return code, display value and exit */
if (rc != 0)
{
printf("\nrc(com_write) = %x",rc);
}
/* loop until last write is done */
while (e_flag == 0);
com_close();
return 0;
}
int IO_complete(int device, int *stkptr)
{
return 0;
}
|
C
|
#include <stdio.h>
int main()
{
int num1 = 10;
int num2 = 20;
int *ptr1 = &num1;
int *ptr2 = &num2;
int *tmp;
(*ptr1)+=10;
(*ptr2)-=10;
tmp = ptr1;
ptr1 = ptr2;
ptr2 = tmp;
printf("%d %d\n", *ptr1, *ptr2);
return 0;
}
|
C
|
/*============================================================================
CSci5103 Spring 2016
Assignment# : 4-2
Name : John Erickson
Student id : 2336359
x500 id : eric0870
CSELABS machine : csel-kh4250-03.cselabs.umn.edu
============================================================================*/
/**********************************************************************************************
* Requirements
* - Create shared memory bank to facilitate communication between 3 threads
* -- 2 buffers to hold black and green items
* -- each item is a string of the form "<color> <unix_timestamp>"
* -- color may be the string "BLACK" or "GREEN" depending on the producer
* -- time tag is a local unix timestamp in microseconds
* -- head and tail pointers for each buffer
* -- mutex variable for mutual exclusion
* -- condition variables to signal space and item availability in buffers
*
* - Create 2 producer processes
* -- Each producer process creates a specific colored item
* -- one producer creates BLACK items and the other producer creates GREEN items
* -- each producer creates 1000 items before completing
* -- wait for random delay between 0-100 ms before producing an item
* -- deposit item in available buffer in shared memory
* -- write item to output file
*
* - Create a consumer process
* -- read contents of shared memory
* -- write contents to output file
*
* Considerations
* - Use POSIX API for thread management and synchronization
*
* Code reuse
* - Lecture Notes 6
* - homework assignment 1
*
**********************************************************************************************/
/* includes */
#include <sys/time.h>
#include <sys/ipc.h>
#include <sys/wait.h>
#include <sys/shm.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <fcntl.h>
#include <unistd.h>
#include <pthread.h>
/* constants */
#define NUM_ITEMS 1000
#define BUF_SIZE 4
#define MAX_CHARS 100
#define SEC_TO_USEC 1000000
/* global vars */
typedef struct
{
char buf1[BUF_SIZE][MAX_CHARS];
char buf2[BUF_SIZE][MAX_CHARS];
int buf1_head;
int buf2_head;
int buf1_tail;
int buf2_tail;
int buf1_cnt;
int buf2_cnt;
//
pthread_mutex_t lock;
pthread_cond_t spaceA;
pthread_cond_t itemA;
} SH_MEM_OBJ;
//
static key_t key; /* key to access shared memory segments */
static int flag; /* r/w permissions */
/* function prototypes */
static void prod_generic( char * );
static void consumer( void );
static void create_item( char *, const char * );
static int print_item( FILE *, char * );
static void printids( void );
int main( int argc, char *argv[] )
{
int size; /* memory size in bytes */
static int shmem_id; /* shared memory identifier */
static SH_MEM_OBJ *shmem_ptr; /* pointer to shared segment */
//
pthread_mutexattr_t attr_sh_lock;
pthread_condattr_t attr_sh_spaceA;
pthread_condattr_t attr_sh_itemA;
printf( "Begin main() thread, " );
printids();
/*******************************************
* Create shared memory bank
*******************************************/
key = 4455;
flag = 1023; /* 1023 = 111111111b (all permissions and modes set) */
size = sizeof( SH_MEM_OBJ );
/* First, create a shared memory segment */
shmem_id = shmget(key, size, flag);
if (shmem_id == -1)
{
perror("shmget failed");
exit(1);
}
/* Now attach the new segment into my address space */
shmem_ptr = shmat(shmem_id, (void *) NULL, flag);
if (shmem_ptr == (void *) -1)
{
perror("shmat failed");
exit(2);
}
/* initialize buffer pointers, mutex and conditions */
shmem_ptr->buf1_head = 0;
shmem_ptr->buf2_head = 0;
shmem_ptr->buf1_tail = 0;
shmem_ptr->buf2_tail = 0;
shmem_ptr->buf1_cnt = 0;
shmem_ptr->buf2_cnt = 0;
//
pthread_mutexattr_init( &attr_sh_lock );
pthread_condattr_init( &attr_sh_spaceA );
pthread_condattr_init( &attr_sh_itemA );
//
pthread_mutexattr_setpshared( &attr_sh_lock, PTHREAD_PROCESS_SHARED );
pthread_condattr_setpshared( &attr_sh_spaceA, PTHREAD_PROCESS_SHARED );
pthread_condattr_setpshared( &attr_sh_itemA, PTHREAD_PROCESS_SHARED );
//
pthread_mutex_init( &(shmem_ptr->lock), &attr_sh_lock );
pthread_cond_init( &(shmem_ptr->spaceA), &attr_sh_spaceA );
pthread_cond_init( &(shmem_ptr->itemA), &attr_sh_itemA );
/* use fork to create child processes
* - child 1: producer (black items)
* - child 2: producer (green items)
* - child 3: consumer
*/
pid_t pid;
if ( (pid = fork()) < 0 )
{
perror("Error forking");
exit(1);
}
//
if ( pid == 0 )
{
/* child 1 process */
prod_generic( "prod_black" );
}
else
{
/* parent process */
pid_t pid;
if ( (pid = fork()) < 0 )
{
perror("Error forking");
exit(1);
}
//
if ( pid == 0 )
{
/* child 2 process */
prod_generic( "prod_green" );
}
else
{
/* parent process */
pid_t pid2;
if ( (pid2 = fork()) < 0 )
{
perror("Error forking");
exit(1);
}
//
if ( pid2 == 0 )
{
/* child 3 process */
consumer();
}
else
{
/* parent process - main thread */
/* wait on producer and consumer threads to complete before exiting */
wait( NULL );
wait( NULL );
wait( NULL );
/* release shared memory segment */
shmctl(shmem_id, IPC_RMID, NULL);
printf( "End main() thread \n" );
exit(0);
}
}
}
printf("\tpid %d exiting\n", getpid());
return 0;
}
void prod_generic( char *tname )
{
/*
* use generic producer function to minimize code redundancy
*/
char filename[100];
int ii;
FILE *fout;
static int shmem_id; /* shared memory identifier */
static SH_MEM_OBJ *shmem_ptr; /* pointer to shared segment */
printf( "\tBegin %s() thread, ", tname );
printids();
/* Reuse key set in main to get the segment id of the
segment that the parent process created. The size parameter is set
to zero, and the flag to IPC_ALLOC, indicating that the segment is
not being created here, it already exists
*/
shmem_id = shmget(key, 0, 0);
if (shmem_id == -1)
{
perror("child shmget failed");
exit(1);
}
/* Now attach this segment into the child address space */
shmem_ptr = shmat(shmem_id, (void *) NULL, flag);
if (shmem_ptr == (void *) -1)
{
perror("child shmat failed");
exit(2);
}
/* open output file */
strcpy(filename, tname);
strcat(filename, ".txt");
fout = fopen( filename, "w+" );
/* enter loop to
* - create items
* - add items to buffer for consumer
* - print items to log file
*/
for ( ii=0; ii<NUM_ITEMS; ii++ )
{
// check for buffer availability
pthread_mutex_lock( &(shmem_ptr->lock) ); // enter critical section
/* wait until space available in buffer */
while ( (shmem_ptr->buf1_cnt + shmem_ptr->buf2_cnt) == 2*BUF_SIZE )
while ( pthread_cond_wait(&(shmem_ptr->spaceA), &(shmem_ptr->lock)) != 0 );
/* sleep using condition variable */
/*
* by this point we know there is space in one of the buffers
* create and add item to available buffer
*/
if ( shmem_ptr->buf1_cnt < BUF_SIZE )
{
create_item( &shmem_ptr->buf1[shmem_ptr->buf1_tail][0], tname );
print_item( fout, &(shmem_ptr->buf1[shmem_ptr->buf1_tail][0]) );
shmem_ptr->buf1_tail = ( shmem_ptr->buf1_tail + 1 ) % BUF_SIZE;
shmem_ptr->buf1_cnt++;
}
else
{
create_item( &shmem_ptr->buf2[shmem_ptr->buf2_tail][0], tname );
print_item( fout, &(shmem_ptr->buf2[shmem_ptr->buf2_tail][0]) );
shmem_ptr->buf2_tail = ( shmem_ptr->buf2_tail + 1 ) % BUF_SIZE;
shmem_ptr->buf2_cnt++;
}
pthread_mutex_unlock( &(shmem_ptr->lock) ); // exit critical section
pthread_cond_signal( &(shmem_ptr->itemA) ); // signal consumer that there is an item available
}
/* close the file */
fclose( fout );
/* done with the program, so detach the shared segment */
shmdt((void *)shmem_ptr);
printf( "\tEnd %s() thread \n", tname );
}
void consumer( void )
{
int ii;
FILE *fout;
static int shmem_id; /* shared memory identifier */
static SH_MEM_OBJ *shmem_ptr; /* pointer to shared segment */
printf( "\tBegin consumer() thread, " );
printids();
/* Reuse key set in main to get the segment id of the
segment that the parent process created. The size parameter is set
to zero, and the flag to IPC_ALLOC, indicating that the segment is
not being created here, it already exists
*/
shmem_id = shmget(key, 0, 0);
if (shmem_id == -1)
{
perror("child shmget failed");
exit(1);
}
/* Now attach this segment into the child address space */
shmem_ptr = shmat(shmem_id, (void *) NULL, flag);
if (shmem_ptr == (void *) -1)
{
perror("child shmat failed");
exit(2);
}
fout = fopen( "output.txt", "w+" );
for ( ii=0; ii<2*NUM_ITEMS; ii++ )
{
pthread_mutex_lock( &(shmem_ptr->lock) ); // enter critical section
/* wait until item available in buffer */
while ( shmem_ptr->buf1_cnt + shmem_ptr->buf2_cnt == 0 )
while ( pthread_cond_wait(&(shmem_ptr->itemA), &(shmem_ptr->lock)) != 0 );
/* sleep using condition variable */
/* by this point we know there is an item in one of the buffers */
if ( shmem_ptr->buf1_cnt > 0 )
{
print_item( fout, &(shmem_ptr->buf1[shmem_ptr->buf1_head][0]) );
shmem_ptr->buf1_head = (shmem_ptr->buf1_head + 1) % BUF_SIZE;
shmem_ptr->buf1_cnt--;
}
else
{
print_item( fout, &(shmem_ptr->buf2[shmem_ptr->buf2_head][0]) );
shmem_ptr->buf2_head = (shmem_ptr->buf2_head + 1) % BUF_SIZE;
shmem_ptr->buf2_cnt--;
}
pthread_mutex_unlock( &(shmem_ptr->lock) ); // exit critical section
pthread_cond_signal( &(shmem_ptr->spaceA) ); // signal producer that there is space available
}
/* close the file */
fclose( fout );
/* done with the program, so detach the shared segment */
shmdt((void *)shmem_ptr);
printf( "\tEnd consumer() thread \n" );
}
void create_item( char *item, const char *tname )
{
/*
* create item
* - either black or green item, depending on input color
* - item includes a unix timestamp in microseconds
* -- use seconds field to unwrap timestamps
* - creation includes a random time delay between 0-100 ms
*/
struct timeval mytimeval;
struct timespec mytimespec;
char str[100];
/* prepend color to item */
if ( strcmp(tname, "prod_black") == 0 )
strcpy( item, "BLACK" );
else
strcpy( item, "GREEN" );
/* append timestamp to item */
gettimeofday( &mytimeval, NULL );
sprintf( str, " %li", mytimeval.tv_sec*SEC_TO_USEC + mytimeval.tv_usec );
strcat( item, str );
/* introduce a random delay between 0-100 ms */
srand( (unsigned int)mytimeval.tv_sec ); // set seed from time of day
mytimespec.tv_sec = 0;
mytimespec.tv_nsec = rand() % 100000000; // get random number for delay (in ns)
nanosleep( &mytimespec, NULL );
}
int print_item( FILE *fid, char *item )
{
/* write item to output file */
fprintf( fid, "%s \n", item );
return 0;
}
void printids( void )
{
pid_t pid = getpid();
printf( "pid= %u \n", (unsigned int)pid );
}
|
C
|
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
#include <malloc.h>
#include <stdio.h>
#include <stdbool.h>
struct ListNode
{
int val;
struct ListNode *next;
};
int addNode(struct ListNode *l1, struct ListNode *l2, int inc)
{
int value = 0;
value = l1->val + l2->val + inc;
if (value > 9)
{
value -= 10;
inc = 1;
}
else
{
inc = 0;
}
l1->val = value;
return inc;
}
int addNode2(struct ListNode *l1, int inc){
int value = l1->val + inc;
if (value > 9)
{
value -= 10;
inc = 1;
}
else
{
inc = 0;
}
l1->val = value;
return inc;
}
bool checkEnd(struct ListNode *l1, int inc){
if(l1->next == NULL){
if(inc){
struct ListNode *tem = (struct ListNode *)malloc(sizeof(struct ListNode));
tem->val = 1;
tem->next = NULL;
l1->next = tem;
}
return true;
}
return false;
}
struct ListNode *addTwoNumbers(struct ListNode *l1, struct ListNode *l2)
{
struct ListNode *res = l1;
int inc = 0, value = 0;
while (l1->next != NULL && l2->next != NULL)
{
inc = addNode(l1, l2, inc);
l2 = l2->next;
l1 = l1->next;
}
inc = addNode(l1, l2, inc);
if(l1->next == NULL && l2->next == NULL){
checkEnd(l1, inc);
return res;
}
if(l1->next == NULL){
l1->next = l2->next;
}
while(!checkEnd(l1, inc)){
l1 = l1->next;
inc = addNode2(l1, inc);
}
return res;
}
struct ListNode* createNode(int value){
struct ListNode *node = (struct ListNode*)malloc(sizeof(struct ListNode));
node->val = value;
node->next = NULL;
return node;
}
int main(){
struct ListNode* l1 = createNode(9);
l1->next = createNode(8);
struct ListNode* l2 = createNode(1);
struct ListNode* res = addTwoNumbers(l1, l2);
while(res != NULL){
printf("%d",res->val);
res = res->next;
}
}
|
C
|
#include <stdio.h>
#include <stdbool.h>
#include <signal.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
#define Max_Buf 50
#define Max_Buf_Read 6
bool IsParent = false;
bool parent_running = false;
int counter =0;
int Write2File()
{
int fd, length, position, idx, jidx, ret;
char Write_Buf[Max_Buf];
char Read_Buf[Max_Buf_Read];
char Counter_Buf[Max_Buf_Read];
char Init_Buf[] = "The initial counter: 0\n";
jidx =0;
/*Open the file text.txt with mode create, read, write*/
fd = open("text.txt", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
if(fd == -1)
{
perror("Fail to open text file\n");
}
/*Init the first line in text.txt*/
if (counter == 0)
{
write(fd, Init_Buf, sizeof(Init_Buf));
}
/*Set the file offset 6 byte from the end of file*/
position = lseek(fd, -6, SEEK_END);
/*Read the last 6 byte of file*/
memset(Read_Buf, 0x0, Max_Buf_Read);
length = read(fd, Read_Buf, Max_Buf);
/*Get the value of counter*/
for(idx = 0; idx < length; idx++)
{
if((Read_Buf[idx] <= '9')&&(Read_Buf[idx] >= '0')){
Counter_Buf[jidx] = Read_Buf[idx];
jidx++;
}
Counter_Buf[jidx] = '\0';
}
counter = atoi(Counter_Buf);
counter++;
if(IsParent == true)
{
memset(Write_Buf, 0x0, Max_Buf);
length = sprintf(Write_Buf, "This is the parent process, the counter: %d\n", counter);
}else{
memset(Write_Buf, 0x0, Max_Buf);
length = sprintf(Write_Buf, "This is the child process, the counter: %d\n", counter);
}
printf("%s\n", Write_Buf);
/*Set the cursor to the end of file to start writing*/
position = lseek(fd, 0, SEEK_END);
ret = write (fd, Write_Buf, length);
if(ret == -1){
perror("Fail to write to file\n");
return -1;
}
}
void sig_int_handler(int signo)
{
if(signo == SIGINT){
if(IsParent){
parent_running = true;
printf("Parent Process is continuing writing\n");
}
else{
parent_running = false;
printf("Child Process is continuing writing\n");
}
}
}
int main(int argc, char const *argv[])
{
int write_number, ret, child_idx, parent_idx;
int parent_pid, child_pid;
printf("Input the number of writing pair:\n");
scanf("%d", &write_number);
// signal(SIGINT , sig_int_handler);
if((ret = fork()) < 0)
{
perror("Fail to create child process\n");
return -1;
}
else if(ret == 0)
{
child_pid = getpid();
parent_pid = getppid();
printf("This is child process with pid = %d\n", (int)child_pid);
parent_running = false;
for(child_idx = 0; child_idx < write_number; child_idx++)
{
IsParent = false;
/*First the child process send the sigstop to its parent*/
kill(parent_pid, SIGSTOP);
/*Write to file*/
Write2File();
/*Send sigcont to the parent*/
kill(parent_pid, SIGCONT);
kill(parent_pid, SIGINT);
sleep(1000);
}
kill(parent_pid, SIGCHLD);
return 0;
}
else
{
child_pid = ret;
parent_pid = getpid();
printf("This is parent process with pid = %d\n", (int)parent_pid);
parent_running = true;
/*Sleep 1s to make sure the child is running first*/
sleep(1);
for(parent_idx = 0; parent_idx < write_number; parent_idx++)
{
IsParent = true;
/*First the process send the sigstop to its child*/
kill(child_pid, SIGSTOP);
/*Write to file*/
Write2File();
/*Send sigcont to the child*/
kill(child_pid, SIGCONT);
kill(child_pid, SIGINT);
sleep(1000);
}
return 0;
}
}
|
C
|
#include <pebble.h>
#include "cue_sheet_data.h"
int cue_sheet_data_get_distance(cue_sheet_data_t* data) {
return (data->ride_list[data->ride_number].ride[data->cue_number].distance);
}
char* cue_sheet_data_get_description(cue_sheet_data_t* data) {
return (data->ride_list[data->ride_number].ride[data->cue_number].cue);
}
char cue_sheet_data_get_direction(cue_sheet_data_t* data) {
return (data->ride_list[data->ride_number].ride[data->cue_number].direction);
}
void cue_sheet_data_next_cue(cue_sheet_data_t* data) {
int max_cue = data->ride_list[data->ride_number].max_cue;
if (data->cue_number < max_cue) {
data->cue_number++;
}
persist_write_int(PERSIST_CUE_NUMBER, data->cue_number);
}
void cue_sheet_data_prev_cue(cue_sheet_data_t* data) {
if (data->cue_number > 0) {
data->cue_number--;
}
persist_write_int(PERSIST_CUE_NUMBER, data->cue_number);
}
void cue_sheet_data_next_ride(cue_sheet_data_t* data) {
data->ride_number++;
if (data->ride_list[data->ride_number].max_cue == 0) {
data->ride_number = 0;
}
persist_write_int(PERSIST_RIDE_NUMBER, data->ride_number);
}
void cue_sheet_data_init(cue_sheet_data_t* data) {
data->ride_number = persist_read_int(PERSIST_RIDE_NUMBER);
data->cue_number = persist_read_int(PERSIST_CUE_NUMBER);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* init_process_arena.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mzaboub <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/11/25 10:15:04 by mzaboub #+# #+# */
/* Updated: 2021/01/16 12:03:34 by del-alj ### ########.fr */
/* */
/* ************************************************************************** */
#include "virtual_machine.h"
extern t_process *g_procs_head;
/*
*******************************************************************************
*/
void mz_update_procs(t_process **proc)
{
if (g_procs_head != NULL)
*proc = g_procs_head;
g_procs_head = NULL;
}
/*
*******************************************************************************
** procs id starts from 1
** players id starts from 1
** proc 1 <-- last player
*/
int ft_get_player_index(t_input_data *bloc, int player_id)
{
int i;
i = 0;
while (i < bloc->players_counter)
{
if (bloc->ids[i] == player_id)
return (i);
i++;
}
return (-1);
}
/*
*******************************************************************************
** this function iterates on the input data and created a linked list of
** the procs that we gonna use afer, and allocates/ filles the arena
*/
void ft_init_procs_arena(t_process **procs, t_input_data *bloc)
{
int player_id;
t_process *proc;
t_process *temp;
unsigned char *arena[2];
arena[0] = (unsigned char*)ft_memalloc(MEM_SIZE);
arena[1] = (unsigned char*)ft_memalloc(MEM_SIZE);
if (!arena[0] || !arena[1])
exit(0);
proc = ft_init_proc(bloc, arena);
player_id = bloc->players_counter - 1;
*procs = proc;
while (player_id > 0)
{
temp = ft_init_proc(bloc, arena);
temp->next = proc;
proc->previous = temp;
proc = temp;
temp = NULL;
player_id--;
}
*procs = proc;
}
/*
*******************************************************************************
** this function, allocates and initialize one node of the processes list.
*/
t_process *ft_init_proc(t_input_data *bloc, unsigned char *arena[2])
{
t_process *proc;
int idx;
static int proc_id;
idx = ft_get_player_index(bloc, proc_id + 1);
if (!(proc = (t_process*)ft_memalloc(sizeof(t_process))))
exit(0);
proc->proc_id = 1 + proc_id++;
proc->player_id = -1 * proc->proc_id;
proc->arena[0] = arena[0];
proc->arena[1] = arena[1];
proc->pc = ft_init_arena(bloc, arena, idx, proc->player_id);
ft_memset(proc->regestries, 0, REG_NUMBER);
proc->regestries[0] = proc->player_id;
proc->players_counter = bloc->players_counter;
proc->execution_cycle = -1;
proc->next = NULL;
proc->previous = NULL;
proc->carry = 0;
proc->process_live = 0;
proc->valid_player_live_counter = 0;
proc->is_new_bol = 1;
return (proc);
}
/*
*******************************************************************************
*/
/*
** this func reverse the endianess of a number (int, long ...)
** for now it's working only with 2/4 bytes values (what we need)
*/
unsigned int ft_reverse_endianness(unsigned char *temp, size_t size)
{
size_t i;
unsigned int hex;
i = 0;
hex = 0;
while (i < size)
{
hex = hex << 8;
hex = hex | (unsigned int)temp[i];
++i;
}
return (hex);
}
|
C
|
//sending a msg to a specific queue(already created msgQ)..(all manipulated through comdline arg only)
#include"./headers.h"
void msq_details(int msqid){
struct msqid_ds buf;
msgctl(msqid,IPC_STAT,&buf);
printf("created msgQid: %d type: %ld size = %d bytes\n",msqid,msgp.mtype,len);
printf("max no of bytes allowd in a que = %lu\n",buf.msg_qbytes);
}
main(int argc,char *argv[]){
if(argc ==3){
int msqid = msgget(KEY,IPC_CREAT); //we are opening a already created msgQ for this u shudnt pass IPC_EXCL;
len = strlen(argv[2])+1;
msgp.mtype = atoi(argv[1]);
strcpy(msgp.mtext,argv[2]);
msgp.mtext[strlen(argv[2])+1]='\0';
if(msgsnd(msqid,&msgp,len,IPC_NOWAIT|MSG_NOERROR)==-1) perror("msgsend"),exit(1);
msq_details(msqid);
}
else printf("Invalid argument\nUsage: sudo <executable> <mtype> <msg(char's)>\n");
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* vertex_manager.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: lseema <lseema@student.21-school.ru> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/11/21 02:13:50 by lseema #+# #+# */
/* Updated: 2020/12/06 18:07:35 by lseema ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/lem_in.h"
t_vertex *new_vertex(char *name, size_t index, int x, int y)
{
t_vertex *vertex;
if (!(vertex = (t_vertex *)malloc(sizeof(t_vertex))))
return (NULL);
vertex->name = name;
vertex->index = index;
vertex->x = x;
vertex->y = y;
vertex->splited = 0;
vertex->next = NULL;
vertex->prev = NULL;
return (vertex);
}
int add_vertex(t_vertex **rooms, t_vertex *vertex)
{
t_vertex *tail;
if (!rooms || !vertex)
return (0);
tail = *rooms;
while (tail->next)
tail = tail->next;
tail->next = vertex;
vertex->next = NULL;
vertex->prev = tail;
return (1);
}
int is_room_dup(t_vertex **rooms, char *name, int x, int y)
{
t_vertex *tail;
if (!rooms || !*rooms)
return (0);
tail = *rooms;
while (tail->next)
{
if (!ft_strcmp(tail->name, name) || (tail->x == x && tail->y == y))
return (1);
tail = tail->next;
}
return (!ft_strcmp(tail->name, name) || (tail->x == x && tail->y == y));
}
int is_room_contain(t_vertex **rooms, char *name)
{
t_vertex *tail;
if (!rooms || !*rooms)
return (0);
tail = *rooms;
while (tail->next)
{
if (!ft_strcmp(name, tail->name))
return (1);
tail = tail->next;
}
return (!ft_strcmp(name, tail->name));
}
size_t get_room_index(char *name, t_vertex **rooms)
{
t_vertex *tail;
if (!rooms)
return (-1);
tail = *rooms;
while (tail->next)
{
if (!ft_strcmp(name, tail->name))
return (tail->index);
tail = tail->next;
}
if (!ft_strcmp(name, tail->name))
return (tail->index);
return (-1);
}
t_vertex *get_last_added(t_vertex **rooms)
{
t_vertex *tail;
if (!rooms)
return (NULL);
tail = *rooms;
while (tail->next)
tail = tail->next;
return (tail);
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<maps.h>
#include<files.h>
void set_rect_map(MAP* m,int y,int x,char wall){
int i,j;
m->cinfo = '0';
m->campo = (char**)malloc(sizeof(char*)*y);
for(i=0;i<y;i++){
m->campo[i] = (char*)malloc(sizeof(char)*x);
}
for(i=0;i<y;i++){
m->campo[i][0] = wall;
m->campo[i][x-1] = wall;
}
for(j=0;j<x;j++){
m->campo[0][j] = wall;
m->campo[y-1][j] = wall;
}
for(i=1;i<y-1;i++){
for(j=1;j<x-1;j++){
m->campo[i][j] = ' ';
}
}
m->y = y;
m->x = x;
}
int load_map_from_file(MAP* m,char* name){
FILE* p = fopen(name,"r");
if(p==NULL){
return -1;
}
char* aux;
scan_file(name,&aux);
int i=0,l = strlen(aux);
free(aux);
m->x = 0;
m->y = 0;
int j=0;
m->cinfo = '1';
m->iinfo = (int*)malloc(sizeof(int));
m->campo = (char**)malloc(sizeof(char*));
m->campo[0] = (char*)malloc(sizeof(char));
while(i<l){
if(fgetc(p) == '\n'){
m->iinfo = (int*)realloc(m->iinfo,sizeof(int)*(m->y+1));
m->iinfo[m->y] = (j);
m->y++;
m->campo = (char**)realloc(m->campo,sizeof(char*)*(m->y+1));
m->campo[m->y] = (char*)malloc(sizeof(char));
j=0;
i++;
}
else{
fseek(p,-1,1);
m->campo[m->y] = (char*)realloc(m->campo[m->y],sizeof(char)*(j+1));
m->campo[m->y][j] = fgetc(p);
j++;
i++;
}
}
m->iinfo = (int*)realloc(m->iinfo,sizeof(int)*(m->y+1));
m->iinfo[m->y] = j;
m->y++;
fclose(p);
return 0;
}
int print_rect_map(MAP m){
if(m.cinfo == '1'){
return -1;
}
int i,j;
for(i=0;i<m.y;i++){
for(j=0;j<m.x;j++){
printf("%c",m.campo[i][j]);
}
printf("\n");
}
return 0;
}
int print_irregular_map(MAP m){
int i,j;
if(m.cinfo == '0'){
return -1;
}
for(i=0;i<m.y;i++){
for(j=0;j<m.iinfo[i];j++){
printf("%c",m.campo[i][j]);
}
printf("\n");
}
return 0;
}
void free_map(MAP* m){
int i;
if(m->cinfo == '1'){
free(m->iinfo);
}
for(i=0;i<m->y;i++){
free(m->campo[i]);
}
free(m->campo);
}
|
C
|
#ifndef __ELEMENTYPPE__
#define __ELEMENTTYPE__
#include <stdio.h>
#include <stdlib.h>
#define MAX_ 255
typedef struct {
int num;
char name[10];
}Element;
typedef struct {
Element ele[MAX_];
int length ;
}Seqlist;
#endif
|
C
|
#include "header.h"
/*
* Main function to all of our goodies
* argv[1] localhost
* argv[2] client IP
*/
int main(int argc, char *argv[])
{
// Declare our server socket
my_socket receiver =
{
"",
"",
{
.sin_family = AF_INET,
.sin_port = htons(PORT),
.sin_addr.s_addr = htonl(INADDR_ANY)
}
};
// Create our main socketn
int sock = socket(AF_INET, SOCK_STREAM, 0);
if(sock == 0)
{
printf("Unable to create socket\n\r");
exit(0);
}
// Allow port reuse, so the kernel will allow the same port to be
// Used again if the server is quit and reopened
int optval = 1;
setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &optval, sizeof(optval));
// Setting TO period to 3 seconds
timeval tv;
tv.tv_sec = 3;
tv.tv_usec = 0;
// setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (const char*) &tv, sizeof(tv));
//Bind socket to the port
if(bind(sock, (struct sockaddr*) &receiver.server, sizeof(receiver.server)) < 0)
{
printf("Unable to bind socket\n\r");
exit(0);
}
// Start server listening
if(listen(sock, 3) < 0)
{
printf("Unable to listen\n\r");
exit(0);
}
// File for input
FILE *f = fopen("input.txt", "r");
char *message = nextLine(f);
fclose(f);
// Adding congestion
AddCongestion(message, 0.00001);
// Connect to our socket
int connectSocket = accept(sock, NULL, NULL);
if(connectSocket < 0)
{
printf("Unable to accept connection\n\r");
return 0;
}
printf("Connection established\n\r");
// Iterative server, will go on forever
for(short int i = 1000, j = 0; j < 1024; i++, j+=2)
{
// What we are sending over
char c[] = {message[j], message[j+1]};
packet p =
{
i,
{
c[0],
c[1]
},
calculate_CCITT16(c, 2, GENERATE_CRC)
};
char *temp = toString(&p);
// Send a message to our socket
write(connectSocket, temp, 7);
printf("Server sent message to client\n\r");
free(temp);
// Will attempt to read up until timeout
char ACK[2];
recv(connectSocket, ACK, 2, 0);
unsigned int first = (ACK[0] << 8) & 0xFF00;
unsigned short int second = ACK[1] & 0xFF;
int combined = first | second;
printf("%i ONE PRINTY BOI IT IS!\n\r", combined);
}
if(close(connectSocket) == 0)
printf("Connection closed\n\r");
free(message);
close(sock);
printf("Server closed\n\r");
return 0;
}
/*
* Handy dandy, string parser!
*/
char *nextLine(FILE *input)
{
int buf = 10;
int read = 0;
char *buffer = malloc(buf);
while(true)
{
char nextChar = fgetc(input);
if(read == buf)
{
buf *= 2;
buffer = realloc(buffer, buf);
}
if(nextChar == '\n' || nextChar == EOF)
{
buffer = realloc(buffer, read + 1);
buffer[buf] = '\0';
return buffer;
}
buffer[read] = nextChar;
read++;
}
}
/*
* toString method for packet
*/
char *toString(packet *p)
{
char *send = malloc(7);
send[0] = ((p->sequenceNum) & 0xFF00) >> 8;
send[1] = (p->sequenceNum) & 0xFF;
send[2] = p->data[0];
send[3] = p->data[1];
send[4] = ((p->crc) & 0xFF00) >> 8;
send[5] = (p->crc) & 0xFF;
send[6] = '\0';
return send;
}
|
C
|
#include "NMUSocket.h"
#include "fortuneClient.h"
void handleOptions(int argc, char *argv[], char **hostNamePtr, char **portPtr);
bool shouldQuit(void);
int handleFortuneReply(nmu_socket_t pSocket);
int main(int argc, char *argv[])
{
nmu_socket_t pSocket;
char *portno;
char *hostName;
handleOptions( argc, argv, &hostName, &portno );
socketFactory.initialize();
pSocket = socketFactory.connectTCPForHostnameAndPort( hostName, portno );
handleFortuneProtocol(pSocket);
return 0;
}
void handleOptions(int argc, char *argv[], char **hostNamePtr, char **portPtr)
{
if (argc != 3) {
fprintf(stderr,"usage: %s hostname port\n", argv[0]);
exit(0);
}
*hostNamePtr = argv[1];
*portPtr = argv[2];
}
void handleFortuneProtocol(nmu_socket_t pSocket)
{
uint8_t protocolState = RUNNING;
uint8_t pduId;
pduId = FORTUNE_REQUEST;
pSocket->write(pSocket, &pduId, sizeof(uint8_t));
while(protocolState != DONE){
pSocket->read(pSocket, &pduId, sizeof(uint8_t));
switch(pduId){
case FORTUNE_REPLY:
protocolState = handleFortuneReply(pSocket);
break;
default:
pSocket->error(pSocket, "ERROR: protocol error\n");
}
if(protocolState == DONE)
break;
}
}
int handleFortuneReply(nmu_socket_t pSocket)
{
uint8_t pduId;
uint8_t count;
char buffer[256];
memset(buffer, 0, 256);
pSocket->read(pSocket, &count, sizeof(uint8_t));
pSocket->read(pSocket, buffer, count);
printf("%s", buffer);
if( shouldQuit() ){
pduId = FORTUNE_QUIT;
pSocket->write(pSocket, &pduId, sizeof(uint8_t));
pSocket->close(pSocket);
return DONE;
} else {
pduId = FORTUNE_REQUEST;
pSocket->write(pSocket, &pduId, sizeof(uint8_t));
return RUNNING;
}
}
bool shouldQuit(void)
{
static int fortuneCount = 0;
return (fortuneCount++ >= 9);
}
|
C
|
/*-----------------------------------------------------------------------*
* Multilevel Incomplete QR Factorization *
*-----------------------------------------------------------------------*
* Na Li, Mar, 2005 *
* *
* Report bugs / send comments to: nli@cs.umn.edu *
*-----------------------------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <time.h>
#include "heads.h"
#include "matfun.h"
#define MIN_NUM (1e-14)
/* working arrays: */
double *vecnval = NULL, *vecmval = NULL;
int *vecnpat = NULL, *vecnidx = NULL;
int *vecmpat = NULL, *vecmidx = NULL;
grphnd nodes = NULL;
double *Anrms = NULL;
int imqr_step( matptr A1, mqrptr *pmqr, matptr *pA2,
double tol_cos, double tol_drop,
int lfil, int nosort );
int iqr( matptr mat, matptr R, double tol_drop, int lfil );
int comp_nodes( const void *buf1, const void *buf2 )
{
const grphnd nd1 = (grphnd)buf1;
const grphnd nd2 = (grphnd)buf2;
/*if( nd1->deg < nd2->deg ) return -1;
else if( nd1->deg > nd2->deg ) return 1;
return 0;*/
return nd1->deg - nd2->deg;
}
int imqr( matptr mat, mqrsptr mqrs, int nomulti, int nosort,
double tol_level, int maxlvl, double tol_cos,
double tol_cos_adaptive, double tol_drop,
int lfil, double *wrk, int *iwrk, FILE *fp )
{
/*---------------------------------------------------------------------
* Incomplete multi-level QR factorization
*---------------------------------------------------------------------
* Parameters
*---------------------------------------------------------------------
* on entry:
* =========
* mat : matrix stored in SparMat format -- see heads.h for details
* mqrs : pointer to a SparMQRS struct -- see heads.h for details
* nomulti : 0: IMQR, 1: IQR
* tol_level: tolerance for stopping MQR. Stop if
* reduced size < tol_level * previous size
* tol_cos : orthogonal tolerance: if (v1,v2) < tol_cos*||v1||*||v2||
* vectors v1 and v2 are considered as orthogoanl
* tol_drop : dropping tolerance
* lfil : max # of elements allowed in each column
* fp : file pointer for error log (might be stdout )
*
* on return:
* ==========
* ierr = return value.
* ierr = 0 --> successful return.
* ierr != 0 --> error
* mqrs
*-----------------------------------------------------------------------
* work array: wrk at least m + n, iwrk at least 2m + 2n, iwrk[i] = 0
*----------------------------------------------------------------------*/
printf("begin imqr\n");
int i, lvl = 0, m = mat->m, n = mat->n, min_n = (int)(0.01*n), *pos;
matptr A1 = mat, A2 = NULL;
clock_t clk;
vecnval = wrk;
vecmval = vecnval + n;
vecnpat = iwrk;
vecnidx = vecnpat + n;
vecmpat = vecnidx + n;
vecmidx = vecmpat + m;
nodes = (grphnd)Malloc( n*sizeof(GraphNode), "imqr" );
Anrms = (double *)Malloc( n*sizeof(double), "imqr" );
setupMQRS( mqrs );
clk = clock();
if( nomulti == 0 ) {
/* implement multilevel IQR */
int done = 0;
mqrptr mqr;
while( !done ) {
imqr_step( A1, &mqr, &A2, tol_cos, tol_drop, lfil, nosort );
printf("END imqr_step OUT\n");
mqrs->amqrs[lvl++] = mqr;
if( (double)mqr->s <= tol_level * (double)mqr->n ) done = 1;
if( A2->n < min_n ) done = 1;
if( lvl >= maxlvl ) done = 1;
if( lvl > 1 ) cleanMat( A1 );
A1 = A2;
tol_cos += tol_cos_adaptive; /* adaptive angle tolerance */
}
}
printf("TEST--------0\n");
clk = clock() - clk;
mqrs->tm_lvl = clk/(double)CLOCKS_PER_SEC;
clk = clock();
printf("TEST--------2\n");
iqr( A1, mqrs->R, tol_drop, lfil );
clk = clock() - clk;
mqrs->tm_iqr = clk/(double)CLOCKS_PER_SEC;
if( lvl > 1 ) cleanMat( A1 );
mqrs->n = mat->n;
mqrs->lvl = lvl;
pos = mqrs->pos;
pos[0] = 0;
if( lvl > 0 ) {
for( i = 1; i <= lvl; i++ ) {
pos[i] = pos[i-1] + mqrs->amqrs[i-1]->s;
}
}
free( nodes );
free( Anrms );
return 0;
}
int imqr_step( matptr A1, mqrptr *pmqr, matptr *pA2,
double tol_cos, double tol_drop, int lfil, int nosort )
{
printf("begin imqr_step\n");
int m = A1->m, n = A1->n, i, j, j1, j2, s, row, col, id, flag;
int *perm = NULL, *iperm = NULL;
SparVec Ei, a2i;
matptr A2 = NULL, graph = NULL, E = NULL;
matptr max_ortho_columns( matptr, int *, int *, double, int, int * );
mqrptr mqr;
mqr = (mqrptr)Malloc( sizeof(SparMQR), "imqr_step" );
mqr->E = (SparMat *)Malloc( sizeof(SparMat), "imqr_step" );
E = mqr->E;
Vector vec, vecE;
double alpha, diag, nrm2;
clock_t clk;
setupMQR( mqr, n );
perm = mqr->perm;
iperm = mqr->iperm;
/* A1 = ( A11 | A12 ), where columns of A11 are orthogonal to each other */
clk = clock();
/* calculate 2-norm for each column of A in order to calculate
* the cosine of the angle between two columns later */
for( i = 0; i < n; i++ ) {
loadVectorC( &vec, A1, i );
Anrms[i] = sparvec_nrm2( &vec );
}
graph = max_ortho_columns( A1, perm, iperm, tol_cos, nosort, &s );
clk = clock() - clk;
/*fprintf( stderr, "max_othor time: %g\n", clk/(double)CLOCKS_PER_SEC );*/
/* D_1 = diag( 1/||A11(1)||, 1/||A11(2)||, ..., 1/||A11(s)|| ) */
mqr->s = s;
mqr->D_1 = (double *)Malloc( s*sizeof(double), "imqr_step" );
for( i = 0; i < s; i++ ) {
diag = Anrms[perm[i]];
if( diag < MIN_NUM ) mqr->D_1[i] = 0.0;
else mqr->D_1[i] = 1.0 / diag;
}
Ei.idx = vecnidx;
Ei.pat = vecnpat;
Ei.val = vecnval;
setupMat( E, s, n-s, MAT_COLBASE_INDEX|MAT_COLBASE_VALUE,
A1->bufsz/2, A1->incsz/2 );
E->cvec[0] = E->nnz;
/* calculate E = Q1^T * A12, where Q1 = A11 * inv(D) */
/* the graph matrix A^T * A can be reused */
clk = clock();
for( i = 0; i < n-s; i++ ) {
loadVectorR( &vec, graph, perm[s+i] );
Ei.nnz = 0;
for( j = 0; j < vec.nnz; j++ ) {
id = iperm[vec.idx[j]];
if( id < s ) {
Ei.idx[Ei.nnz] = id;
Ei.val[Ei.nnz] = vec.val[j] * mqr->D_1[id];
Ei.nnz++;
}
}
/* copy Ei to the i-th column of E */
checkMatBuffer( E, Ei.nnz );
for( j = 0; j < Ei.nnz; j++ ) {
E->cidx[E->nnz] = Ei.idx[j];
E->cval[E->nnz] = Ei.val[j];
E->nnz++;
}
E->cvec[i+1] = E->nnz;
}
cleanMat( graph );
clk = clock() - clk;
/*fprintf( stderr, "Calculating E: %g\n", clk/(double)CLOCKS_PER_SEC );*/
a2i.val = vecmval;
a2i.pat = vecmpat;
a2i.idx = vecmidx;
A2 = (matptr)Malloc( sizeof(SparMat), "imqr_step" );
flag = MAT_ROWBASE_INDEX|MAT_ROWBASE_VALUE|
MAT_COLBASE_INDEX|MAT_COLBASE_VALUE;
setupMat( A2, m, n-s, flag, A1->bufsz, A1->incsz );
A2->cvec[0] = A2->nnz;
/* Calculate A2_new = A2 - Q1 * E */
clk = clock();
for( i = 0; i < n-s; i++ ) {
fsparvec_loadC( &a2i, A1, perm[s+i] );
loadVectorC( &vecE, E, i );
for( j = 0; j < vecE.nnz; j++ ) {
col = vecE.idx[j];
/* A2i = A2i - <A2i,qj>*qj */
alpha = - vecE.val[j] * mqr->D_1[col];
loadVectorC( &vec, A1, perm[col] );
fsparvec_add( &a2i, &vec, alpha );
}
/* copy a2i to the i-th column of A2 */
checkMatBuffer( A2, a2i.nnz );
for( j = 0; j < a2i.nnz; j++ ) {
row = a2i.idx[j];
A2->cidx[A2->nnz] = row;
A2->cval[A2->nnz] = a2i.val[row];
A2->nnz++;
a2i.pat[row] = 0; /* reset pat to 0 array */
}
A2->cvec[i+1] = A2->nnz;
}
transMat( A2 ); /* store A2 row-wise */
clk = clock() - clk;
/*fprintf( stderr, "Calculating A2: %g\n", clk/(double)CLOCKS_PER_SEC );*/
*pmqr = mqr;
*pA2 = A2;
printf("END imqr_step\n");
return 0;
}
matptr max_ortho_columns( matptr A, int *perm, int *iperm,
double tol_cos, int nosort, int *ps )
{
int n = A->n, i, j, k, row, col, id, pm, ipm, s, nnz, j1, j2;
double cs, cosnrm, aTval;
Vector rvec;
SparVec ci;
matptr C;
/* initial ci, used as the i-th row of C */
ci.val = vecnval;
ci.pat = vecnpat;
ci.idx = vecnidx;
C = (matptr)Malloc( sizeof(SparMat), "max_ortho_columns" );
setupMat( C, n, n, MAT_ROWBASE_INDEX|MAT_ROWBASE_VALUE,
A->bufsz*2, A->incsz );
C->rvec[0] = C->nnz;
/* nodes will be used to store the degree of each vertex, so that it */
/* can be sorted by qsort */
for( i = 0; i < n; i++ ) {
nodes[i].deg = 0;
nodes[i].idx = i;
}
for( i = 0; i < n; i++ ) {
/* calculate the i-th row of C: ci = ai^T * a(:,i+1:n) */
ci.nnz = 0;
j1 = A->cvec[i];
j2 = A->cvec[i+1];
for( j = j1; j < j2; j++ ) {
row = A->cidx[j];
aTval = A->cval[j];
loadVectorR( &rvec, A, row );
for( k = rvec.nnz-1; k >= 0; k-- ) {
/* row indices are in increasing order, stop when idx <= i */
col = rvec.idx[k];
if( col <= i ) break;
if( ci.pat[col] == 0 ) {
/* fill-in */
ci.idx[ci.nnz] = col;
ci.pat[col] = 1;
ci.val[col] = aTval * rvec.val[k];
ci.nnz++;
} else {
ci.val[col] += aTval * rvec.val[k];
}
}
}
/* setup the upper part of the graph of normalized A^T * A */
/* copy ci to the i-th row of C */
nnz = nodes[i].deg + ci.nnz;
checkMatBuffer( C, nnz );
C->nnz += nodes[i].deg;
if( ci.nnz > 0 ) {
/* if (ai,aj) < tol_cos * |ai| * |aj|, assume ai is orthogonal to aj */
cosnrm = tol_cos * Anrms[i];
for( j = 0; j < ci.nnz; j++ ) {
col = ci.idx[j];
cs = ci.val[col];
if( fabs(cs) > cosnrm * Anrms[col] ) {
nodes[col].deg++;
C->ridx[C->nnz] = col;
C->rval[C->nnz] = cs;
C->nnz++;
}
ci.pat[col] = 0; /* reset pattern to 0 */
}
}
C->rvec[i+1] = C->nnz;
}
for( i = 0; i < n; i++ ) {
ci.idx[i] = C->rvec[i] + nodes[i].deg; /* pointing to boundary index */
nodes[i].deg = C->rvec[i]; /* pointing to the next available position */
}
/* convert to full graph from the upper part */
for( i = 0; i < n; i++ ) {
j1 = ci.idx[i];
j2 = C->rvec[i+1];
for( j = j1; j < j2; j++ ) {
row = C->ridx[j];
C->ridx[nodes[row].deg] = i;
C->rval[nodes[row].deg] = C->rval[j];
nodes[row].deg++;
}
}
for( i = 0; i < n; i++ ) {
nodes[i].deg = C->rvec[i+1] - C->rvec[i];
}
if( !nosort ) {
qsort( nodes, n, sizeof(GraphNode), comp_nodes );
}
s = 0;
for( i = 0; i < n; i++ ) {
perm[i] = i;
iperm[i] = i;
ci.idx[i] = 0;
}
for( i = 0; i < n; i++ ) {
id = nodes[i].idx;
if( ci.idx[id] == 1 ) continue;
pm = perm[s];
ipm = iperm[id];
perm[s] = id;
perm[ipm] = pm;
iperm[id] = s;
iperm[pm] = ipm;
s++;
j1 = C->rvec[id];
j2 = C->rvec[id+1];
for( j = j1; j < j2; j++ ) {
ci.idx[C->ridx[j]] = 1;
}
}
*ps = s;
return C;
}
typedef struct tagElement
{
double val;
int col;
int next;
} Element;
int iqr( matptr mat, matptr R, double tol_drop, int lfil )
{
/*==================================================================*/
/* IQR using Saad's ILQ method */
/*==================================================================*/
/* Input: */
/* */
/*==================================================================*/
/* work array: wk at least m + n, iwk at least 2m + n */
/* iwk initially is 0 array */
/*==================================================================*/
/* */
/*==================================================================*/
int m = mat->m, n = mat->n, i, j, k, nnz;
int Apos, Qnext, Ridx, QTpos;
double Aval, Rval, invRval, value, tnorm;
int szBase, szQlist, szQbuf, szQinc, Qnnz, index;
const int *idx, *Qidx;
const double *val, *Qval;
matptr Q = (matptr)Malloc( sizeof(SparMat), "iqr" );
SparVec qi, ri;
Element *Qlist;
Vector cvec, vec;
/* initialize Q and R (column wise) */
setupMat( Q, m, n, MAT_COLBASE_INDEX|MAT_COLBASE_VALUE,
mat->bufsz, mat->incsz );
setupMat( R, n, n, MAT_COLBASE_INDEX|MAT_COLBASE_VALUE,
n+mat->bufsz, mat->incsz );
Q->cvec[0] = Q->nnz;
R->nnz = n;
R->cvec[0] = R->nnz; /* the first n elements are diagonals */
/* initialize buffers for qi and ri (the i-th column of Q and R resp.) */
qi.val = vecmval;
qi.pat = vecmpat;
qi.idx = vecmidx;
ri.val = vecnval;
ri.pat = vecnpat;
ri.idx = vecnidx;
/* initialize the linked list of Q (row wise) using a linear array */
/* Qlist (cf. Saad's ILQ). Qlist[i] points to the i-th row of Q */
/* szQbuf: the current buffer size */
/* szQinc: the size to increase when the buffer is full */
/* QTpos : the next available position in Qlist */
szBase = nnzMat( mat );
szQlist = m;
szQbuf = m + mat->bufsz;
szQinc = mat->incsz;
Qlist = (Element *)malloc( szQbuf * sizeof(Element) );
for( i = 0; i < m; i++ )
{
Qlist[i].next = -1;
}
QTpos = m;
for( i = 0; i < n; i++ )
{
loadVectorC( &cvec, mat, i );
idx = cvec.idx;
val = cvec.val;
nnz = cvec.nnz;
/* reset the i-th column of Q and R */
qi.dim = m;
ri.dim = n;
qi.nnz = 0;
ri.nnz = 0;
/* load the i-th column of A and use Saad's ILQ method to calculate */
/* entries in the i-th column of R */
tnorm = 0.0;
for( j = 0; j < nnz; j++ )
{
Apos = idx[j];
Aval = val[j];
tnorm += fabs( Aval );
qi.idx[qi.nnz] = Apos;
qi.val[Apos] = Aval;
qi.pat[Apos] = 1;
qi.nnz++;
Qnext = Qlist[Apos].next;
while( Qnext != -1 )
{
index = Qlist[Qnext].col;
value = Qlist[Qnext].val;
if( ri.pat[index] == 0 )
{
/* fill-in */
ri.idx[ri.nnz] = index;
ri.pat[index] = 1;
ri.val[index] = value * Aval;
ri.nnz++;
}
else
{
/* not a fill-in */
ri.val[index] += value * Aval;
}
Qnext = Qlist[Qnext].next;
}
}
tnorm *= tol_drop;
for( j = 0; j < ri.nnz; j++ )
{
ri.pat[ ri.idx[j] ] = 0; /* reset pattern to 0 */
}
/* keep only the lfil largest elements (in absolute value) in R(:,i) */
if( ri.nnz > lfil ) {
qsplit2( ri.val, &n, ri.idx, &ri.nnz, &lfil );
ri.nnz = lfil;
}
/* calculate Ai - Sum <Ai,Qj>Qj, i.e., Ai - Sum(rj*Qj) */
/* store Ri = <Ai,Qj> */
checkMatBuffer( R, ri.nnz );
for( j = 0; j < ri.nnz; j++ )
{
Ridx = ri.idx[j];
Rval = ri.val[Ridx];
loadVectorC( &vec, Q, Ridx );
fsparvec_add( &qi, &vec, -Rval );
if( fabs(Rval) >= tnorm ) { /* drop very small elements */
R->cidx[R->nnz] = ri.idx[j];
R->cval[R->nnz] = Rval;
R->nnz++;
}
}
R->cvec[i+1] = R->nnz;
for( j = 0; j < qi.nnz; j++ )
{
qi.pat[ qi.idx[j] ] = 0; /* reset pattern to 0 */
}
/* keep only the lfil largest elements (in absolute value) in Q(:,i) */
if( qi.nnz > lfil ) {
qsplit2( qi.val, &m, qi.idx, &qi.nnz, &lfil );
qi.nnz = lfil;
}
Rval = fsparvec_nrm2( &qi );
if( Rval == 0.0 ) {
fprintf( stderr, "Zero column encountered.\n" );
Rval = MIN_NUM;
}
invRval = 1.0 / Rval;
R->cval[i] = invRval; /* the first n elements store inv of R diag */
/* update Q and Qlist */
if( szQlist + qi.nnz > szQbuf )
{
/* if the current buffer is not large enough, enlarge it */
szQbuf += szQinc;
while( szQlist + qi.nnz > szQbuf )
{
szQbuf += szQinc;
}
Qlist = (Element *)realloc( Qlist, szQbuf * sizeof(Element) );
}
checkMatBuffer( Q, qi.nnz );
for( j = 0; j < qi.nnz; j++ )
{
index = qi.idx[j];
value = qi.val[index] * invRval;
/* ignore very small entries */
/* if( fabs(value) < tnorm ) continue; */
Q->cidx[Q->nnz] = index;
Q->cval[Q->nnz] = value;
Q->nnz++;
/* add to Qlist's row Qidx */
Qlist[QTpos].col = i;
Qlist[QTpos].val = value;
Qlist[QTpos].next = Qlist[index].next;
Qlist[index].next = QTpos;
szQlist++;
QTpos++;
}
Q->cvec[i+1] = Q->nnz;
}
if( Qlist ) free( Qlist );
cleanMat( Q );
return 0;
}
/*-----------------------------------------------------------------------*/
int cond_est( matptr mat, mqrsptr mqrs, double *y, double *x, FILE *fp )
{
int n = mqrs->n, i;
double norm;
for(i = 0; i < n; i++ ) {
y[i] = 1.0;
}
printf("begin cond_est------1\n");
mqrsol( mqrs, y, x, 1, y );
printf("begin cond_est------2\n");
mqrsol( mqrs, x, x, 0, y );
norm = vec_nrminf( n, x );
printf("begin cond_est------3\n");
fprintf(fp, " MQR inf-norm lower bound : %16.2f\n", norm );
if( norm > 1e30 ) {
return -1;
}
return 0;
}
/*-----------------------------------------------------------------------*/
|
C
|
#ifndef PERSON_H
#define PERSON_H 1
typedef enum Bool{true=1,false=0}bool;
typedef struct Person{
char name[20];
bool gender;
int age;
double salary;
}person;
//struct Personһṹ
#endif
|
C
|
/*
* @lc app=leetcode id=696 lang=c
*
* [696] Count Binary Substrings
*
* https://leetcode.com/problems/count-binary-substrings/description/
*
* algorithms
* Easy (53.46%)
* Total Accepted: 31K
* Total Submissions: 58.1K
* Testcase Example: '"00110"'
*
* Give a string s, count the number of non-empty (contiguous) substrings that
* have the same number of 0's and 1's, and all the 0's and all the 1's in
* these substrings are grouped consecutively.
*
* Substrings that occur multiple times are counted the number of times they
* occur.
*
* Example 1:
*
* Input: "00110011"
* Output: 6
* Explanation: There are 6 substrings that have equal number of consecutive
* 1's and 0's: "0011", "01", "1100", "10", "0011", and "01".
* Notice that some of these substrings repeat and are counted the number of
* times they occur.
* Also, "00110011" is not a valid substring because all the 0's (and 1's) are
* not grouped together.
*
*
*
* Example 2:
*
* Input: "10101"
* Output: 4
* Explanation: There are 4 substrings: "10", "01", "10", "01" that have equal
* number of consecutive 1's and 0's.
*
*
*
* Note:
* s.length will be between 1 and 50,000.
* s will only consist of "0" or "1" characters.
*
*/
int countBinarySubstrings(char * s){
}
|
C
|
#include "raylib.h"
int main(void)
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib example.");
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
// Update
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(RAYWHITE);
// Here we test is mouse button 0 or 1 or 2 is down.
if(IsMouseButtonDown(0)){
DrawText("Mouse Button 0 is Down.",50,100,20,BLACK);
}else{
DrawText("Mouse Button 0 is NOT Down.",50,100,20,BLACK);
}
if(IsMouseButtonDown(1)){
DrawText("Mouse Button 1 is Down.",50,120,20,BLACK);
}else{
DrawText("Mouse Button 1 is NOT Down.",50,120,20,BLACK);
}
if(IsMouseButtonDown(2)){
DrawText("Mouse Button 2 is Down.",50,140,20,BLACK);
}else{
DrawText("Mouse Button 2 is NOT Down.",50,140,20,BLACK);
}
// Here we test if the space key is down.
if(IsKeyDown(KEY_SPACE)){
DrawText("KEY_SPACE is Down.",370,100,20,BLACK);
}else{
DrawText("KEY_SPACE is NOT Down.",370,100,20,BLACK);
}
// Here we test if any key is down.
// Note that the value i<x might be higher than here.
bool onedown=false;
for(int i=0;i<355;i++){
if(IsKeyDown(i)){
DrawText(FormatText("IsKeyDown : %i",i),370,120,20,BLACK);
onedown = true;
}
}
if (onedown==false)DrawText("IsKeyDown : Nothing",370,120,20,BLACK);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;
}
|
C
|
#include<stdio.h>
#include<conio.h>
#include<string.h>
enum NT{E=0,e=1,T=2,t=3,F=4};
int top=0,ci=0;
char table[5][6][4]={"\0"},exp[20],st[20];
int flag=0;
void parser(void);
void push(char);
void pop(void);
int p_table(char);
void create_table();
void main()
{
int l,m,n,lp=0;
char t;
clrscr();
printf("Give Expression:");
scanf("%s",exp);
l=strlen(exp);
printf("\n%d",strlen(exp));
exp[l]='$';
st[0]='$';
st[1]='E';
top=1;
create_table();
while(ci<strlen(exp))
{
parser();
lp++;
}
if(flag==0)
printf("String Unaccepted");
getch();
}
void parser()
{
int j,m,n;
char str[5];
if(st[top]==exp[ci])
{
if(st[top]=='$')
{
printf("\nString Accepted");
ci++;
flag=1;
}
else
{
pop();
ci++;
}
}
else if(st[top]=='E' || st[top]=='F' || st[top]=='T' || st[top]=='t' || st[top]=='e')
{
m=p_table(st[top]);
n=p_table(exp[ci]);
strcpy(str,table[m][n]);
printf("\nexp=%c",exp[ci]);
printf("\nstr=%s",str);
if(strcmp(str,"\0")==0)
{
printf("\nNO VALUE IN TABLE");
ci=strlen(exp);
}
else if(strcmp(str,"eps")==0)
{
pop();
}
else
{
printf("\n%s",str);
strrev(str);
printf("\n%s",str);
pop();
j=0;
while(j<strlen(str))
{
push(str[j]);
j++;
}
}
}
else
{
ci=strlen(exp);
}
}
void push(char ch)
{
top++;
st[top]=ch;
printf("\nPUSH:%c",ch);
}
void pop()
{
printf("\nPOP:%c",st[top]);
st[top]='\0';
top--;
}
int p_table(char eci)
{
int x;
if(eci=='i')
x=0;
else if(eci=='+')
x=1;
else if(eci=='*')
x=2;
else if(eci=='(')
x=3;
else if(eci==')')
x=4;
else if(eci=='$')
x=5;
else if(eci=='E')
x=0;
else if(eci=='e')
x=1;
else if(eci=='T')
x=2;
else if(eci=='t')
x=3;
else if(eci=='F')
x=4;
else
x=-1;
return x;
}
void create_table()
{
strcpy(table[E][0],"Te");
strcpy(table[E][3],"Te");
strcpy(table[e][1],"+Te");
strcpy(table[e][4],"eps");
strcpy(table[e][5],"eps");
strcpy(table[T][0],"Ft");
strcpy(table[T][3],"Ft");
strcpy(table[t][1],"eps");
strcpy(table[t][2],"*Ft");
strcpy(table[t][4],"eps");
strcpy(table[t][5],"eps");
strcpy(table[F][0],"i");
strcpy(table[F][3],"(E)");
}
|
C
|
/*Generalize o código acima para qualquer frequência possível.*/
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
int fd;
//função para fechar corretamente e unexportar os pinos
void close(){
close(fd);
fd = open("/sys/class/gpio/unexport",O_WRONLY);
write(fd,"4",2);
printf("Fechando programa\n");
close(fd);
sleep(1);
exit(0);
}
int main(){
float frequencia;
float periodo;
signal(SIGINT,fechar);
printf("Qual a frequência (em Hz)?\n");
scanf("%f",&frequencia); //Entrada da freq pelo usuario
periodo = 1000000/(2*(frequencia)); //Conversão de Hz para S
//Setando como export
printf("Realizando o export\n");
fd = open("/sys/class/gpio/export",O_WRONLY);
write(fd,"4",2);
close(fd);
sleep(1);
//Setando como saída
printf("Iniciando o pin como saída\n");
fd = open("/sys/class/gpio/gpio4/direction",O_WRONLY);
write(fd,"out",4);
close(fd);
sleep(1);
fd = open("/sys/class/gpio/gpio4/value",O_WRONLY);
printf("Iniciando o blink com a frequência de %.2f Hz\n",frequencia);
while(1){
write(fd,"1",2);
usleep(periodo);
write(fd,"0",2);
usleep(periodo);
}
return 0;
}
|
C
|
#include <bits/stdc++.h>
#include <limits.h>
using namespace std;
// Number of cities in TSP
#define V 5
// Names of the cities
#define GENES ABCDE
// Starting Node Value
#define START 0
// Initial population size for the algorithm
#define POP_SIZE 10
// Structure of a GNOME
// string defines the path traversed
// by the salesman while the fitness value
// of the path is stored in an integer
struct individual {
string gnome;
int fitness;
};
// Function to return a random number
// from start and end
int rand_num(int start, int end)
{
int r = end - start;
int rnum = start + rand() % r;
return rnum;
}
// Function to check if the character
// has already occurred in the string
bool repeat(string s, char ch)
{
for (int i = 0; i < s.size(); i++) {
if (s[i] == ch)
return true;
}
return false;
}
// Function to return a mutated GNOME
// Mutated GNOME is a string
// with a random interchange
// of two genes to create variation in species
string mutatedGene(string gnome)
{
while (true) {
int r = rand_num(1, V);
int r1 = rand_num(1, V);
if (r1 != r) {
char temp = gnome[r];
gnome[r] = gnome[r1];
gnome[r1] = temp;
break;
}
}
return gnome;
}
// Function to return a valid GNOME string
// required to create the population
string create_gnome()
{
string gnome = "0";
while (true) {
if (gnome.size() == V) {
gnome += gnome[0];
break;
}
int temp = rand_num(1, V);
if (!repeat(gnome, (char)(temp + 48)))
gnome += (char)(temp + 48);
}
return gnome;
}
// Function to return the fitness value of a gnome.
// The fitness value is the path length
// of the path represented by the GNOME.
int cal_fitness(string gnome)
{
int map[V][V] = { { 0, 2, INT_MAX, 12, 5 },
{ 2, 0, 4, 8, INT_MAX },
{ INT_MAX, 4, 0, 3, 3 },
{ 12, 8, 3, 0, 10 },
{ 5, INT_MAX, 3, 10, 0 } };
int f = 0;
for (int i = 0; i < gnome.size() - 1; i++) {
if (map[gnome[i] - 48][gnome[i + 1] - 48] == INT_MAX)
return INT_MAX;
f += map[gnome[i] - 48][gnome[i + 1] - 48];
}
return f;
}
// Function to return the updated value
// of the cooling element.
int cooldown(int temp)
{
return (90 * temp) / 100;
}
// Comparator for GNOME struct.
bool lessthan(struct individual t1,
struct individual t2)
{
return t1.fitness < t2.fitness;
}
// Utility function for TSP problem.
void TSPUtil(int map[V][V])
{
// Generation Number
int gen = 1;
// Number of Gene Iterations
int gen_thres = 5;
vector<struct individual> population;
struct individual temp;
// Populating the GNOME pool.
for (int i = 0; i < POP_SIZE; i++) {
temp.gnome = create_gnome();
temp.fitness = cal_fitness(temp.gnome);
population.push_back(temp);
}
cout << "\nInitial population: " << endl
<< "GNOME FITNESS VALUE\n";
for (int i = 0; i < POP_SIZE; i++)
cout << population[i].gnome << " "
<< population[i].fitness << endl;
cout << "\n";
bool found = false;
int temperature = 10000;
// Iteration to perform
// population crossing and gene mutation.
while (temperature > 1000 && gen <= gen_thres) {
sort(population.begin(), population.end(), lessthan);
cout << "\nCurrent temp: " << temperature << "\n";
vector<struct individual> new_population;
for (int i = 0; i < POP_SIZE; i++) {
struct individual p1 = population[i];
while (true) {
string new_g = mutatedGene(p1.gnome);
struct individual new_gnome;
new_gnome.gnome = new_g;
new_gnome.fitness = cal_fitness(new_gnome.gnome);
if (new_gnome.fitness <= population[i].fitness) {
new_population.push_back(new_gnome);
break;
}
else {
// Accepting the rejected children at
// a possible probablity above threshold.
float prob = pow(2.7,
-1 * ((float)(new_gnome.fitness
- population[i].fitness)
/ temperature));
if (prob > 0.5) {
new_population.push_back(new_gnome);
break;
}
}
}
}
temperature = cooldown(temperature);
population = new_population;
cout << "Generation " << gen << " \n";
cout << "GNOME FITNESS VALUE\n";
for (int i = 0; i < POP_SIZE; i++)
cout << population[i].gnome << " "
<< population[i].fitness << endl;
gen++;
}
}
int main()
{
int map[V][V] = { { 0, 2, INT_MAX, 12, 5 },
{ 2, 0, 4, 8, INT_MAX },
{ INT_MAX, 4, 0, 3, 3 },
{ 12, 8, 3, 0, 10 },
{ 5, INT_MAX, 3, 10, 0 } };
TSPUtil(map);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
void copy(char *c, char *x)
{
char str[1000];
FILE *C, *X;
C = fopen(c, "r");
X = fopen(x, "w");
char i;
while ((i = fgetc(C)) != EOF)
{
fputc(i, X);
}
}
int main()
{
setlocale(0, "Russian");
char a[1000], b[1000];
printf("Введите путь к расположению файла (C:\/Papka\/name.txt)");
gets(a);
printf("Куда копировать нужный файл (C:\/papka\/name2.txt)");
gets(b);
copy(a, b);
printf("Операция завершена");
return 0;
}
|
C
|
#include<stdio.h>
#include<math.h>
int main(){
printf("Enter any Number");
int number;
scanf("%d",&number);
int squaredNumber = number * number ;
int lastDigits = 0;
int counter = 0;
int number_cpy = number;
while(number){
lastDigits += (squaredNumber %10)*pow(10,counter);
squaredNumber = squaredNumber/10;
number = number /10;
counter++;
}
if(number_cpy == lastDigits)
printf("AutoMorphic:\n");
else
printf("Not Automorphic");
}
|
C
|
#include <iostream>
#include <fstream>
#include <cmath>
#include "random.h"
#include <string>
#include "esercitazione81.h"
#include <iomanip>
using namespace std;
//Esercizio 8.1
//
int main(){
rnd.LoadSeed();
settings(); //Inizialization
for(int i=0; i<par;i++){
for(int j=0; j<par;j++){
sigma=sigmapar[i];
mu=mupar[j];
cout <<"---------------------------------" << endl;
cout << "Mu: " << mu << " " << "sigma: " << sigma << endl;
x[0]=x_0;
for(int iblk=1; iblk <= nblock; ++iblk){
Reset(iblk); //Reset block averages
for(int istep=1; istep <= L; ++istep)
{
metropolis(x[0]);
Measure(x[0]);
Accumulate(); //Update block averages
}
Averages(iblk); //Print results for current block
}
//cout << glob_av[0]/(double)nblock << endl;
best(nblock);
}
}
//Salvo il migliore
mu=bestmu;
sigma=bestsigma;
x[0]=x_0;
for(int iblk=1; iblk <= nblock; ++iblk){
Reset(iblk); //Reset block averages
for(int istep=1; istep <= L; ++istep)
{
metropolis(x[0]);
Measure(x[0]);
Accumulate(); //Update block averages
Print_x();
//cout << H << endl;
}
Averages(iblk); //Print results for current block
Print(iblk);
}
}
/////////////////////////////////*//////////////////////////////////////////////
//funzioni
void best(int nblock){
ofstream out;
//cout <<glob_av[0]/(double)nblock<< " " << amin << endl;
if ( glob_av[0]/(double)nblock < amin) {
bestmu=mu;
bestsigma=sigma;
out.open("bestpar.dat");
amin=glob_av[0]/(double)nblock;
//cout << "printing on file" << endl;
out << mu << setw(12) << sigma << endl;
out.close();
}
}
double Accumulate(){
blk_av[0] = blk_av[0] + H;
blk_norm = blk_norm + 1.0;
}
void Reset(int iblk) //Reset block averages
{
if(iblk == 1)
{
glob_av[0] = 0;
glob_av2[0] = 0;
}
blk_av[0] = 0;
blk_norm = 0;
attempted = 0;
acc = 0;
}
double Measure(double x){
H=-0.5 * der(x,mu,sigma)/doublegauss(x,mu,sigma)+V(x);
return H;
}
double der(double x, double mu, double sigma){
double m1,m2,exp1,exp2;
m1 = pow(((x-mu)/sigma),2);
m2 = pow(((x+mu)/sigma),2);
exp1 = exp(-m1/2.);
exp2 = exp(-m2/2.);
return (exp1*(m1-1.) + exp2*(m2-1.))/(sigma * sigma);
}
//calcolare l'errore nella media a blocchi
double Error(double sum, double sum2, int iblk)
{
if( iblk == 1 ) return 0.0;
else return sqrt((sum2/(double)iblk - pow(sum/(double)iblk,2))/(double)(iblk-1));
}
//distribuzione uniforme
double uniform(double x){
return (x + (rnd.Rannyu(-delta,delta)));
}
//distribuzione gaussiana
double gaussian(double x){
return rnd.Gauss(x,delta);
}
//funzione di prob
double doublegauss(double x,double mu, double sigma){
double d,m1,m2;
m1=pow((x-mu),2);
m2=pow((x+mu),2);
d = 2*sigma*sigma;
return exp(-m1/d)+exp(-m2/d);
}
//modulo quadro della funzione di prob
double doublegauss2(double x, double mu, double sigma){
return pow(doublegauss(x,mu,sigma),2);
}
double V(double x){
return pow(x,4)-(5./2.)*x*x;
}
//Metropolis!
void metropolis(double xo){
double y;
double p,r,px,py;
y= t(xo);
px=f(xo,mu,sigma);
py=f(y,mu,sigma);
p=min(1.,py/px);
r=rnd.Rannyu();
if (r<=p){
acc++;
x[0]=y;
}
attempted++;
}
void Averages(int iblk){
//cout << "Block number " << iblk << endl;
//cout << "Acceptance rate " << acc*1./attempted << endl << endl;
stima_H = blk_av[0]/(1.*blk_norm);
glob_av[0] += stima_H;
glob_av2[0] += stima_H*stima_H;
err_H= Error(glob_av[0],glob_av2[0],iblk);
}
void Print(int iblk){
ofstream out;
out.open("H.dat",ios::app);
out << setw(12) << iblk << setw(12) << stima_H << setw(12) << glob_av[0]/(double)iblk << setw(12) << err_H << endl;
}
void Print_x(){
ofstream out;
out.open("x.dat",ios::app);
out << x[0] << endl;
}
//Funzione per evitare di dover cambiare ogni volta tutti i parametri
//settings.C contiene informazioni sull'orbitale e sulla funzione da usare in metropolis
void settings(){
ifstream in;
in.open("settings.C");
cout << "Metropolis algorithm to solve a 1D quantum problem" << endl;
cout << "Reading input from settings.C" << endl;
in >> function;
cout << "You are using a uniform probability" << endl;
in >> delta;
cout << "The step of the simulation is " << delta << endl;
in >> x_0;
cout << "The starting point is " << x_0 << endl;
in >> nsteps;
cout << "Simulation with " << nsteps << " step" << endl;
in >> nblock;
cout << "Simulation divided in " << nblock << " blocks" << endl;
L=nsteps/nblock;
if (function == "uniform") t=&uniform;
if (function =="gaussian") t=&gaussian;
f=&doublegauss2;
//grid of parameters
for (int i=0; i<par;i++){
sigmapar[i] = 0.5+i*0.002;
mupar[i] = 0.6+i*0.002;
}
}
|
C
|
/****************************************************************************
* libs/libc/signal/sig_raise.c
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. The
* ASF licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#include <signal.h>
#include <pthread.h>
#include <assert.h>
#include <errno.h>
/****************************************************************************
* Public Functions
****************************************************************************/
/****************************************************************************
* Name: sig_raise
*
* Description:
* The raise() function sends the signal signo to the executing thread or
* process. If a signal handler is called, the raise() function does not
* return until after the signal handler does.
*
* If the implementation supports the Threads option, the effect of the
* raise() function is equivalent to calling:
*
* pthread_kill(pthread_self(), signo);
*
* except that on failures, -1 (ERROR) is returned and the errno() variable
* is set accordingly. Otherwise, the effect of the raise() function is
* equivalent to calling:
*
* kill(getpid(), signo)
*
****************************************************************************/
int raise(int signo)
{
#ifndef CONFIG_DISABLE_PTHREAD
int errcode = pthread_kill(pthread_self(), signo);
if (errcode != OK)
{
DEBUGASSERT(errcode > 0);
set_errno(errcode);
return ERROR;
}
return OK;
#else
return kill(getpid(), signo);
#endif
}
|
C
|
# include <stdio.h>
unsigned int replace(unsigned int x, int i, unsigned char b)
{
unsigned int x2;
switch(i) {
case 0:
x2 = x&0xFFFFFF00;
break;
case 1:
x2 = x&0xFFFF00FF;
break;
case 2:
x2 = x&0xFF00FFFF;
break;
case 3:
x2 = x&0x00FFFFFF;
break;
}
return (x2 | (b<<(8*i)));
/*Use a switch so i will correllate to whichever case and then b will servce as the replacement in the correct position. Then get the correct replacedment by returning this x2 in the switch or left shift b by 2 bits */
}
int main(int argc, char *argv[]){
printf("%X\n",replace(0x12345678, 0, 0xAB));
printf("%X\n", replace(0x12345678, 2, 0xAB));
return 0;
}
|
C
|
/*
array.h
foundation
Created by Christopher Loonam on 11/8/15.
Copyright (c) 2015 Christopher Loonam. All rights reserved.
*/
#ifndef __foundation__array__
#define __foundation__array__
#include <stdio.h>
/**
@brief @c array_t is a structure that holds an ordered collection of objects of any type.
*/
typedef struct array array_t;
/**
@brief Creates a new zero-indexed array.
@param o The objects the array will hold. This list must be terminated with @c NULL; if this is not done, the behavior is undefined.
@return A newly allocated array containing the objects passed as arguments; if no objects are passed in the function call, an empty array is returned. This array is dynamically allocated and should be freed with a call to @c arrfree()
*/
array_t * arrnew(void *o, ...);
/**
@brief Returns the object located at index @c idx.
@param arr The array from which the object will be returned.
@param idx The index of the object to be returned.
@return If @c idx is less than the count of the array, the object at that index will be returned. If @c idx is greater than or equal to the count of the array, @c NULL will be returned, as the index will be out of the range of the array.
*/
void * arrobj(array_t *arr, unsigned idx);
/**
@brief Appends an object to the end of an array.
@param arr The array to which the object will be added.
@param o The object to append to the array. If this argument is @c NULL, the array will go unmodified.
*/
void arradd(array_t *arr, void *o);
/**
@brief Removes the object located at index @c idx from the array.
@param arr The array from which the object will be removed.
@param idx The index of the object to be removed. If the index is outside of the bounds of the array, the array will go unmodified.
*/
void arrrm(array_t *arr, unsigned idx);
/**
@brief Returns the number of objects that are contained in the array @c arr.
@param arr The array whose count will be returned.
@return The count of the array @c arr.
*/
unsigned arrcnt(array_t *arr);
/**
@brief Frees the memory pointed to by the array.
@param arr The array pointer whose memory will be freed.
*/
void arrfree(array_t *arr);
#endif /* defined(__foundation__array__) */
|
C
|
#include <stdio.h>
int main() {
int op1, op2, sum; // variable declaration
op1 = 5; // variable definition
op2 = 3;
sum = op1 + op2; // addition operation just change sign for other operation ex substraction , multiplication , division etc..
printf("sum of %d and %d is %d", op1, op2, sum);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: zzeynalo <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/04/14 20:42:41 by zzeynalo #+# #+# */
/* Updated: 2019/04/14 20:42:48 by zzeynalo ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_ref.h"
#include <stdlib.h>
int main(void)
{
t_char *list_char;
t_char *start;
char **tocompare;
int *results;
list_char = ft_create_elem();
start = list_char;
while (read(0, &list_char->character, 1))
{
list_char->next = ft_create_elem();
list_char = list_char->next;
}
tocompare = ft_get_colles(ft_get_col(start), ft_get_lines(start));
results = ft_compare(tocompare, start);
ft_print_results(results, ft_get_col(start), ft_get_lines(start));
return (0);
}
|
C
|
#include "main.h"
void build_wheel()
{
roulette = malloc(sizeof(int) * population_fitness);
int *ptr = roulette ;
int i = 0 ;
int j = 0 ;
for(; i < POP ; i++){
for(j = 0 ; j < fitnesses[i] ; j++){
*(ptr++) = i ;
}
}
}
void initialize_population()
{
int i = 0 ;
int j ;
for(; i < POP ; i++){
for(j = 0 ; j < LEN ; j++){
population[i][j] = get_random_char();
}
fitnesses[i] = fitness(population[i]);
population_fitness += fitnesses[i] ;
}
}
|
C
|
#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>
volatile uint8_t counter = 0;
ISR (TIMER0_OVF_vect){ // Timer0 ISR
counter++;
TCNT0 = 6; // for 1 sec at 16 MHz
}
int main(){
DDRB = DDRB | (1<<5); // set pin 5 of port B for output
TCNT0 = 6; // for 1 sec at 16 MHz
TCCR0A = 0x00; // Timer0 with normal mode
TCCR0B = 0x04; // Timer0 mode with 256 prescler
TIMSK0 = 0b00000001; // Enable timer0 overflow interrupt(TOIE0)
sei(); // Enable global interrupts by setting global interrupt enable bit in SREG
while(1){
if (counter == 25){
PORTB = PORTB ^ (1<<5); // toggle LED
counter = 0;
}
}
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<omp.h>
//Dimension por defecto de las matrices
int N=100;
//int N=3; <-- para testear, la cambiamos por 3
//Asignamos un numero fijo de threads, también podrían llegar por parámetro
int numThreads=4;
struct celda {
double pos;
double value;
} valor, *column, auxCelda, aux, *merge, *merge2;
//Este metodo devuelve el max-min en result[0] y el promedio en result[1]
void getValues(double *matriz, double *resultados) {
int i=0;
double min=999999;
double max=-999999;
double total=0;
#pragma omp parallel for shared (matriz,N,max,min) reduction(+:total)
for(i=0;i<(N*N);i++) {
if(matriz[i]>max) {
max=matriz[i];
}
if(matriz[i]<min) {
min=matriz[i];
}
total+=matriz[i];
}
resultados[0]=max-min;
resultados[1]=total/(N*N);
}
void* sort(int slice) {
int s=(int)slice; // retrive the slice info
int from=(s*N)/numThreads; // note that this 'slicing' works fine
int to=((s+1)*N)/numThreads; // even if SIZE is not divisible by num_thrd
int j,k;
struct celda aux;
for(j=1;j<N;j++) {
for(k=from;k<to-j;k++) {
if(column[k].value<column[k+1].value) {
auxCelda=column[k];
column[k]=column[k+1];
column[k+1]=aux;
}
}
}
}
void* initial_merge(int slice) {
int s=(int)slice; // retrive the slice info
int i=(s*N)/2;
int n2=((s+1)*N)/2; // even if SIZE is not divisible by num_thrd
int j=n2/2;
int n1=n2/2;
int k=0;
merge2=(struct celda*)malloc((sizeof(double)+sizeof(double))*N/2);
while(i<n1 && j<n2) {
if (column[i].value<=column[j].value){
merge2[k]=column[i];
i++;
}else{
merge2[k]=column[j];
j++;
}
k++;
}
while(i<n1) {
merge2[k]=column[i];
i++;
k++;
}
while(j<n2) {
merge2[k]=column[j];
j++;
k++;
}
for(i=0;i<N/2;i++) {
column[i+((s*N)/2)]=merge2[i];
}
}
//Para calcular tiempo
double dwalltime(){
double sec;
struct timeval tv;
gettimeofday(&tv,NULL);
sec = tv.tv_sec + tv.tv_usec/1000000.0;
return sec;
}
int main(int argc,char*argv[]) {
omp_set_num_threads(numThreads);
double *A,*B,*B2,*C,*D,*r1,*r2, *aux, *C2;
int i,j,k;
double timetick;
int check=1;
int param[numThreads];
if ((argc != 2) || ((N = atoi(argv[1])) <= 0) )
{
printf("\nUsar: %s n\n n: Dimension de la matriz (nxn X nxn)\n", argv[0]);
exit(1);
}
//Aloca memoria para las matrices
A=(double*)malloc(sizeof(double)*N*N);
B=(double*)malloc(sizeof(double)*N*N);
C=(double*)malloc(sizeof(double)*N*N);
B2=(double*)malloc(sizeof(double)*N*N);
D=(double*)malloc(sizeof(double)*N);
r1=(double*)malloc(sizeof(double)*2);
r2=(double*)malloc(sizeof(double)*2);
/*
A=(double*)malloc(sizeof(double)*9);
B=(double*)malloc(sizeof(double)*9);
C=(double*)malloc(sizeof(double)*9);
B2=(double*)malloc(sizeof(double)*9);
D=(double*)malloc(sizeof(double)*3);
*/
//Inicializa las matrices A y B en 1, el resultado sera una matriz con todos sus valores en N
// private(j) ?
#pragma omp parallel for shared (A,B,D)
for(i=0;i<N;i++){
for(j=0;j<N;j++){
A[i*N+j]=1;
B[i+j*N]=1;
}
D[i]=1;
}
/*Inicializa matrices con los valores de prueba
A[0]=1;
A[1]=2;
A[2]=6;
A[3]=5;
A[4]=9;
A[5]=3;
A[6]=4;
A[7]=8;
A[8]=7;
B[0]=3;
B[1]=3;
B[2]=1;
B[3]=2;
B[4]=5;
B[5]=7;
B[6]=1;
B[7]=3;
B[8]=2;
D[0]=4;
D[1]=2;
D[2]=3;
*/
//Punto A
timetick = dwalltime();
#pragma omp parallel for private(j,k) shared (A,B,B2,N)
for(i=0;i<N;i++){
for(j=0;j<N;j++){
B2[i*N+j]=0;
for(k=0;k<N;k++){
B2[i*N+j]=(B2[i*N+j] + A[i*N+k]*B[k+j*N]);
}
}
}
#pragma omp parallel for private(j) shared (C,B2,D,N)
for(i=0;i<N;i++){
for(j=0;j<N;j++){
C[i*N+j]=(B2[i*N+j]*D[j]);
}
}
free(B2);
/*VERIFICACION
printf("\n");
printf("Matriz resultante del punto A:\n");
printf(" %f",C[0]);printf(" %f",C[1]);printf(" %f\n",C[2]);
printf(" %f",C[3]);printf(" %f",C[4]);printf(" %f\n",C[5]);
printf(" %f",C[6]);printf(" %f",C[7]);printf(" %f\n",C[8]);
*/
//Punto B
double result;
int l;
getValues(A,r1);
getValues(B,r2);
result=((r1[0]*r1[0])/r1[1])*((r2[0]*r2[0])/r2[1]);
#pragma omp parallel for shared(C)
for(l=0;l<(N*N);l++) {
C[l]=C[l]*result;
}
/*VERIFICACION
printf("\n");
printf("Matriz resultante del punto B:\n");
printf(" %f",C[0]);printf(" %f",C[1]);printf(" %f\n",C[2]);
printf(" %f",C[3]);printf(" %f",C[4]);printf(" %f\n",C[5]);
printf(" %f",C[6]);printf(" %f",C[7]);printf(" %f\n",C[8]);
*/
free(r1);
free(r2);
//Punto C
C2=(double*)malloc(sizeof(double)*N*N);
column=(struct celda*)malloc((sizeof(double)+sizeof(double))*N);
merge=(struct celda*)malloc((sizeof(double)+sizeof(double))*N);
for(i=0;i<N;i++) {
#pragma omp parallel for shared (valor,column)
for(k=0;k<N;k++) {
valor.pos=k;
valor.value=C[i+N*k];
column[k]=valor;
}
#pragma omp parallel for
for(k=0; k<numThreads; k++){
//param[k]=k;
sort( k );
}
#pragma omp parallel for
for(k=0; k<2; k++){
initial_merge(k);
}
j=0;
k=N/2;
l=0;
while(j<N/2 && k<N) {
if (column[j].value<=column[k].value){
merge[l]=column[j];
j++;
}else{
merge[l]=column[k];
k++;
}
l++;
}
while(j<N/2) {
merge[l]=column[j];
j++;
l++;
}
while(k<N) {
merge[l]=column[k];
k++;
l++;
}
#pragma omp parallel for private(k) shared (valor,N,i,C2,C)
for(j=0;j<N;j++){
valor=column[j];
for(k=0;k<N-i;k++){
C2[(j*N)+k]=C[((int)valor.pos*N)+i+k];
}
}
#pragma omp parallel for private(k) shared (N,i,C2,C)
for(j=0;j<N;j++){
for(k=0;k<N-i;k++){
C[(j*N)+k+i]=C2[(j*N)+k];
}
}
}
free(C2);
/*VERIFICACION
printf("\n");
printf("Matriz resultante del punto C:\n");
printf(" %f",C[0]);printf(" %f",C[1]);printf(" %f\n",C[2]);
printf(" %f",C[3]);printf(" %f",C[4]);printf(" %f\n",C[5]);
printf(" %f",C[6]);printf(" %f",C[7]);printf(" %f\n",C[8]);
*/
printf("Tiempo en segundos %f\n", dwalltime() - timetick);
free(A);
free(B);
free(C);
free(D);
return 0;
}
|
C
|
### 1.Pattern 1 ###
*****
*****
*****
*****
*****
#include<stdio.h>
int main()
{
int i,j;
for(i=1;i<=5;i++)
{
for(j=1;j<=5;j++)
printf("*",i);
printf("\n");
}
return 0;
}
### 2.Pattern 2 ###
*
**
***
****
*****
#include<stdio.h>
int main()
{
int i,j;
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
printf("*",i);
printf("\n");
}
return 0;
}
### 3.Pattern 3 ###
*****
****
***
**
*
#include<stdio.h>
int main()
{
int i,j;
for(i=1;i<=5;i++)
{
for(j=i;j<=5;j++)
printf("*",j);
printf("\n");
}
return 0;
}
### 4.Pattern 4 ###
*****
****
***
**
*
# include <stdio.h>
int main ()
{
int i,j;
for (j = 1;j<=10;j++)
{
for (i = 1;i<=5;i++) /*here i = number of rows*/ /*j = number of column*/
{
if (j<=i)
printf("*");
else
printf(" ");
}
printf("\n");
}
return 0;
}
### 5.Pattern 5 ###
*
**
***
****
*****
# include <stdio.h>
int main ()
{
int i,j;
for (j = 5;j>=1;j--)/*here i = number of rows*/
{
for (i = 1;i<=5;i++)/*j = number of column*/
{
if(j<=i)
printf("*");
else
printf(" ");
}
printf("\n");
}
return 0;
}
### 6.Pattern 6 ###
*
**
***
****
*****
*****
****
***
**
*
# include <stdio.h>
int main ()
{
int i,j;
for ( j =1; j<=5; j++ )
{
for (i =1; i<=5; i++)
{
if (i<=j)
printf("*");
else
printf(" ");
}
printf("\n");
}
for ( j =5; j>=1; j-- )
{
for (i =1; i<=5; i++)
{
if (i<=j)
printf("*");
else
printf(" ");
}
printf("\n");
}
return 0;
}
### 7.Pattern 7 ###
*
**
***
****
*****
*****
****
***
**
*
# include <stdio.h>
int main ()
{
inti,j;
for ( j =5; j>=1; j-- )
{
for (i =1; i<=5; i++)
{
if (j<=i)
printf("*");
else
printf(" ");
}
printf("\n");
}
for ( j =1; j<=5; j++ )
{
for (i =1; i<=5; i++)
{
if (i>=j)
printf("*");
else
printf(" ");
}
printf("\n");
}
return 0;
}
### 8.Pattern 8###
*
**
***
****
*****
*****
****
***
**
*
*
**
***
****
*****
*****
****
***
**
*
# include <stdio.h>
int main ()
{
int i,j;
for (j = 5;j>=1;j--)
{
for (i=1;i<=5;i++)
{
if(j<=i)
printf("*");
else
printf(" ");
}
printf("\n");
}
for (j = 1;j<=5;j++)
{
for (i = 1;i <=5;i++)
{
if(j<=i)
printf ("*");
else
printf(" ");
}
printf( "\n");
}
for (j = 1;j<=5;j++)
{
for (i = 1;i<=5;i++)
{
if(j>=i)
printf("*");
else
printf(" ");
}
printf("\n");
}
for (j = 5; j >=1;j--)
{
for (i = 1;i<=5;i++)
{
if( j>=i)
printf("*");
else
printf(" ");
}
printf("\n");
}
return 0;
}
### 9.Pattern 9 ###
*
**
***
****
*****
*****
****
***
**
*
# include <stdio.h>
int main ()
{
int j,i;
for (j = 1;j<=5;j++)
{
for (j = 1;j<=5;j++)
{
for (i= 1;i<=5;i++)
{
if(j>=i)
printf("*");
else
printf(" ");
}
printf("\n");
}
for (j = 1;j<=5;j++)
{
for (i= 1;i<=5;i++)
//for (i = 5;i>=1;i--)
{
if(j<=i)
printf("*");
else
printf(" ");
}
printf("\n");
}
return 0;
}
}
### 10.Pattern 10 ###
1
22
333
4444
55555
#include<stdio.h>
int main ()
{
int i,j;
for(j=1;j<=5;j++)
{
for(i=1;i<=5;i++)
{
if(i<=j)
printf("%d",j);
else
printf(" ");
}
printf("\n");
}
return 0;
}
### 11.Pattern 11 ###
1
12
123
1234
12345
#include<stdio.h>
int main ()
{
int i,j;
for(j=1;j<=5;j++)
{
for(i=1;i<=5;i++)
{
if(i<=j)
printf("%d",i);
else
printf(" ");
}
printf("\n");
}
return 0;
}
### 12.Pattern 12 ###
12345
2345
345
45
5
#include<stdio.h>
int main ()
{
int i,j;
for(j=1;j<=5;j++)
{
for(i=1;i<=5;i++)
{
if(j<=i)
printf("%d",i);
else
printf(" ");
}
printf("\n");
}
return 0;
}
###13.Pattern 13 ###
5
54
543
5432
54321
#include<stdio.h>
int main ()
{
int i,j;
for(j=5;j>=1;j--)
{
for(i=5;i>=1;i--)
{
if(j<=i)
printf("%d",i);
else
printf(" ");
}
printf("\n");
}
return 0;
}
### 14.Pattern 14 ###
5
45
345
2345
12345
#include<stdio.h>
int main ()
{
int i,j;
for(j=5;j>=1;j--)
{
for(i=1;i<=5;i++)
{
if(j<=i)
printf("%d",i);
else
printf(" ");
}
printf("\n");
}
return 0;
}
### 15.Pattern 15 ###
12345
1234
123
12
1
#include<stdio.h>
int main ()
{
int i,j;
for(j=5;j>=1;j--)
{
for(i=1;i<=5;i++)
{
if(j>=i)
printf("%d",i);
else
printf(" ");
}
printf("\n");
}
return 0;
}
OUTPUT:
*
* *
* * *
* * * *
* * * * *
#include<stdio.h>
int main()
{
int i,j;
for(i=0;i<5;i++)
{
for(j=4;j>=0;j--)
{
if(j>i)
printf(" ");
else
printf("* ");
}
printf("\n");
}
return 0;
}
End of fifth Program
---------------------------------
-----------------------------------
Extra Program:
* * * * *
* * * *
* * *
* *
*
#include<stdio.h>
int main()
{
int i,j;
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
if(j<i)
printf(" ");
else
printf("* ");
}
printf("\n");
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
#define ALPHABET_SIZE 26
char * encrypt(string plain, int cipher_key);
int main(int argc, string argv[])
{
// Checks if there is a command line agrument passed for Key
if (argc != 2)
{
printf("Missing Key agrument for Caesar cipher\n");
return 1;
}
// Set key
int key = atoi(argv[1]);
printf("plaintext:");
string plaintext = get_string();
// Encrypt plaintext
char *ciphertext;
ciphertext = encrypt(plaintext, key);
printf("ciphertext:%s\n", ciphertext);
return 0;
}
// Returns plaintext encrypted with string
char * encrypt(string plain, int cipher_key)
{
int text_length = strlen(plain);
int shift;
char *cipher = malloc(text_length);
// Loop through user input
for (int i = 0; i < text_length; i++)
{
// Only shift letters
if (isalpha(plain[i]))
{
if (isupper(plain[i]))
{
// Shift plaintext by key
shift = (plain[i] - 'A' + cipher_key) % ALPHABET_SIZE;
// Uppercase case
cipher[i] = 'A' + shift;
}
else
{
// Shift plaintext by key
shift = (plain[i] - 'a' + cipher_key) % ALPHABET_SIZE;
// Lowercase case
cipher[i] = 'a' + shift;
}
}
else
{
cipher[i] = plain[i];
}
}
return cipher;
}
|
C
|
#include <SDL.h>
#include <stdio.h>
#include <stdbool.h>
#include "graphics.h"
#include "game.h"
int main(void)
{
Game game;
// startup SDL, game window, and whatnot
bool check = startup(&game.window);
if (!check)
{
printf("Game startup failed!\n");
return 1;
}
// start a new game (i.e. intialize a blank board and enter the game)
check = newGame(&game);
if (!check)
{
printf("Failed to create new game!\n");
return 2;
}
check = shutdown(&game.window);
if (!check)
{
printf("IDK how, but shutdown failed!\n");
return 9001;
}
// GG, success!
return 0;
}
|
C
|
#include "STD_TYPES.h"
#include "BIT_MATH.h"
#include "UART_private.h"
#include "UART_config.h"
#include "UART_interface.h"
/************************************************************/
void UART_VoidInit (void)
{
u8 ucsra =0b00000000;
u8 ucsrb =0b00011000;
u8 ucsrc =0b10000110;
/* UCSRA */
#if PARITY_STATE == PARITY_OFF
CLR_BIT(ucsra,2);
#elif PARITY_STATE == PARITY_ON
SET_BIT(ucsra,2);
#endif
#if PARITY_MODE == DISABLE
CLR_BIT(ucsrc,4);
CLR_BIT(ucsrc,5);
#elif PARITY_MODE == EVEN
CLR_BIT(ucsrc,4);
SET_BIT(ucsrc,5);
#elif PARITY_MODE == ODD
SET_BIT(ucsrc,4);
SET_BIT(ucsrc,5);
#endif
#if DOUBLE_SPEED_MODE == DOUBLE_SPEED_MODE_OFF
CLR_BIT(ucsra,1);
#elif DOUBLE_SPEED_MODE == DOUBLE_SPEED_MODE_ON
SET_BIT(ucsra,1);
#endif
/* FRAM SIZE */
#if FRAM_SIZE == FIVE_BITS
CLR_BIT(ucsrb,2);
CLR_BIT(ucsrc,1);
CLR_BIT(ucsrc,2);
#elif FRAM_SIZE == SIX_BITS
CLR_BIT(ucsrb,2);
SET_BIT(ucsrc,1);
CLR_BIT(ucsrc,2);
#elif FRAM_SIZE == SEVEN_BITS
CLR_BIT(ucsrb,2);
CLR_BIT(ucsrc,1);
SET_BIT(ucsrc,2);
#elif FRAM_SIZE == EIGHT_BITS
CLR_BIT(ucsrb,2);
SET_BIT(ucsrc,1);
SET_BIT(ucsrc,2);
#endif
/* UART MODE */
#if UART_MODE == Asynchronous
CLR_BIT(ucsrc,6);
#elif UART_MODE == synchronous
SET_BIT(ucsrc,6);
#endif
#if STOP_BITS == ONE_BIT
CLR_BIT(ucsrc,3);
#elif STOP_BITS == TWO_BITS
SET_BIT(ucsrc,3);
#endif
#if TRANSMIT_AT == RISING
CLR_BIT(ucsrc,0);
#elif TRANSMIT_AT == FALLING
SET_BIT(ucsrc,0);
#endif
UCSRA=ucsra;
UCSRB=ucsrb;
UCSRC=ucsrc;
UBRRL=103;
UBRRH=0;
}
/************************************************************/
void UART_VoidTransmit (u8 Data)
{
while(GET_BIT(UCSRA,5)==0);
UDR=Data;
}
/************************************************************/
u8 UART_VoidRecieve (void)
{
while(GET_BIT(UCSRA,7)==0);
return UDR;
}
/************************************************************/
void UART_voidWriteString (u8 *ptr)
{
u8 i = 0 ;
while( ptr[ i ] != '\0' )
{
UART_VoidTransmit(ptr[i] );
i++;
}
}
/************************************************************/
u8 String[20];
u8 * UART_voidReadString (void)
{
u8 i=0;u8 x=0;
while((x=UART_VoidRecieve()) != 'E')
{
String[i]=x;
i++;
}
String[i]='\0';
return String;
}
|
C
|
#ifndef STDDEF_H_
#define STDDEF_H_
#define NULL 0
typedef signed char int8;
typedef signed short int16;
typedef signed int int32;
typedef unsigned char uint8;
typedef unsigned short uint16;
typedef unsigned int uint32;
typedef unsigned int uint;
static void memclear(uint8* p, int len) {
for (int i = len; i > 0; i--)
*p++ = 0;
}
static void memcopy(uint8* dst, const uint8* src, int len) {
for (int i = len; i > 0; i--)
*dst++ = *src++;
}
#endif
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include "buffer_mgr.h"
#include "dberror.h"
#include "storage_mgr.h"
#define MAX_PAGES 20000
#define MAX_FRAMES 200
#define MAX_K 10
/*Frame list operations*/
/* Auxiliary function */
/*
Create a new pageframe node in frame list
*/
pageFrame *createNewFrame(){
//allocate memory for the pageFrame entry
pageFrame *pf = malloc(sizeof(pageFrame));
//initialize the BM_PageHandle content
pf->page = MAKE_PAGE_HANDLE();
pf->page->data = calloc(PAGE_SIZE, sizeof(SM_PageHandle));
pf->page->pageNum = NO_PAGE;
//initialize pageFrame's attribute
pf->next = NULL;
pf->previous = NULL;
pf->frameNum = 0;
pf->dirtyFlag = FALSE;
pf->fixCount = 0;
pf->rf = 0;
pf->pageFrequency = 0;
//return this node
return pf;
}
/* makeHead() is to make the given pf the head of the list.*/
void makeHead(pageList **plist, pageFrame *NodeToMake){
//connect the list head with the pageFrame's head node
pageFrame *headFrame = (*plist)->head;
//if node already in head or head is null or the node is null
//Simply return.
if(headFrame == NULL || NodeToMake == NULL ||
NodeToMake == (*plist)->head){return;}
//else if this node is tail node
//exchange the head and the tail
else if(NodeToMake == (*plist)->tail){
pageFrame *temp = ((*plist)->tail)->previous;
temp->next = NULL;
(*plist)->tail = temp;
}
//if code runs here, this node is in the middle of the list
//remove its link and change its next node's previous pointer to
//its previous node and its previous node's next pointer to its next node
else{
NodeToMake->previous->next = NodeToMake->next;
NodeToMake->next->previous = NodeToMake->previous;
}
//append this node to the head frame
NodeToMake->next = headFrame;
headFrame->previous = NodeToMake;
NodeToMake->previous = NULL;
//change the head pointer point to the new node
(*plist)->head = NodeToMake;
(*plist)->head->previous = NULL;
return;
}
/* searchByPageNum() search the pageList and
return a pointer to the pagefame given the pageNum */
pageFrame *searchByPageNum(pageList *plist, const PageNumber pageNum){
//define a current pointer first pointing to head,
//if isfound, return this pageframe
//if not, return NULL
for(pageFrame *current = plist->head;
current != NULL; current = current->next){
if(current->page->pageNum == pageNum){ return current;}
}
return NULL;
}
/* inPageList() can tell whether a page in the list
If yes, return a pointer to it and increase fixCount
If no, return a NULL pointer
*/
pageFrame *inPageList(BM_BufferPool *const bm,
BM_PageHandle *const page,const PageNumber pageNum){
BMAttri *attribute = (BMAttri *)bm->mgmtData;
pageFrame *pftoFind = searchByPageNum(attribute->plists, pageNum);
if((attribute->frameContent)[pageNum] != NO_PAGE){
if((pftoFind) != NULL){
//give the client data of that page
page->pageNum = pageNum;
page->data = pftoFind->page->data;
//pinned, increase fixCount
pftoFind->fixCount++;
pftoFind->rf = 1;
return pftoFind;
}
return NULL;
}
return NULL;
}
/* exchangePageFrame() check pageframe's dirtyFlag, If is true, write back to the file
and then increment writeNum
then read the bm_pagehandle into memory, store in the pageFrame
update all relative attribute */
RC exchangePageFrame(BM_BufferPool *const bm, BM_PageHandle *const page,
const PageNumber pageNum, pageFrame *toUpdate){
SM_FileHandle fhandle;
BMAttri *attribute = (BMAttri *)bm->mgmtData;
RC rc;
//open pagefile to write the changes
if ((rc = openPageFile ((char *)(bm->pageFile), &fhandle)) != RC_OK){
return rc;
}
//If the frame to be replaced is dirty, write it back to the disk.
if(toUpdate->dirtyFlag == TRUE){
//first, append enough pages to write
if((rc = ensureCapacity(toUpdate->page->pageNum,
&fhandle)) != RC_OK){return rc;}
//write pages back to the file
if((rc = writeBlock(toUpdate->page->pageNum,&fhandle,
toUpdate->page->data)) != RC_OK){return rc;}
attribute->numWrite ++;
}
// Update the frameContent array, set the replaceable page's pageNum to NO_PAGE.
(attribute->frameContent)[toUpdate->page->pageNum] = NO_PAGE;
// Read the page's data into toupdated pageframe
if((rc = ensureCapacity(pageNum, &fhandle)) != RC_OK){return rc;}
if((rc = readBlock(pageNum, &fhandle,
toUpdate->page->data)) != RC_OK){return rc;}
//set the page handler with new pageNum and data
page->pageNum = pageNum;
page->data = toUpdate->page->data;
//increment total readNum
(attribute->numRead)++;
//update all the parameters of the new frame
toUpdate->dirtyFlag = FALSE;
toUpdate->fixCount = 1;
toUpdate->page->pageNum = pageNum;
toUpdate->rf = 1;
//update the pagetoFrame[] and frametoPage[]
(attribute->frameContent)[toUpdate->page->pageNum] = toUpdate->frameNum;
(attribute->pageContent)[toUpdate->frameNum] = toUpdate->page->pageNum;
//close the pagefile
closePageFile(&fhandle);
return RC_OK;
}
/* Page replacement strategies.*/
/* FIFO is First in First out Strategy
1. call inPageList() to check whether the page is in the memory
if True, return RC_OK
2. Check if the List is full,
if not, update the frame into the empty frame and update it as head
if full, traverse the whole list to point to the oldest frame
with fixCount = 0, update isfound frame as head
3. call exchangePageFrame() */
RC FIFO (BM_BufferPool *const bm, BM_PageHandle *const page,
const PageNumber pageNum){
pageFrame *isfound;
BMAttri *attribute = (BMAttri *)bm->mgmtData;
printf("searching page: %d\n", pageNum);
// Check if page already in memory.
isfound = inPageList(bm, page, pageNum);
if(isfound != NULL){
printf("Page: %d found\n", pageNum);
return RC_OK;
}
printf("Page: %d not found\n", pageNum);
// If not isfound, need to update the page into memory
// If the pagelists in the memory are less than the
// total available pagelists, locate the first empty frame from the head.
if(attribute->plists->length < bm->numPages){
printf("Ready to append Page: %d\n", pageNum);
isfound = attribute->plists->head;
for(int i = 0; i < attribute->plists->length; i++){
isfound = isfound->next;
}
//add pages to the pageLists, increment the size
(attribute->plists->length)++;
printf("Page: %d has append\n", pageNum);
makeHead(&(attribute->plists), isfound);
}
else{
//For new page, if the pagelists are filled,
//locate the oldest frame has fixCount = 0
printf("Replace Page: %d\n", pageNum);
isfound = attribute->plists->tail;
while(isfound != NULL && isfound->fixCount != 0){
isfound = isfound->previous;
}
if (isfound == NULL){
return RC_TRAVERSE_TO_THE_END;
}
printf("Page: %d replaced\n", pageNum);
makeHead(&(attribute->plists), isfound);
}
//initialize return code
RC rc;
//exchange isfound frame with page requested
if((rc =
exchangePageFrame(bm, page, pageNum, isfound)) != RC_OK){return rc;}
return RC_OK;
}
/*LRU strategy:
1. call inPageList() to check whether the page is in memory
if yes, return RC_OK;
2. check if the list is full:
if not, update the page into empty page and make it as head of the list
if fulll, traverse from tail to look for a frame with fixCount = 0
3. Since the new comming frame always considered as head pageframe,
then the head pageframe is latest used pageframe. The tail should be the least
recently used pageframe. */
RC LRU (BM_BufferPool *const bm, BM_PageHandle *const page,
const PageNumber pageNum){
printf("You are in LRU test\n");
pageFrame *isfound;
BMAttri *attribute = (BMAttri *)bm->mgmtData;
printf("searching page: %d\n", pageNum);
//Check if page already in memory.
if((isfound = inPageList(bm, page, pageNum)) != NULL){
//When found, make this new pageframe as head since tthis is the latest
printf("Page: %d found\n", pageNum);
makeHead(&(attribute->plists), isfound);
return RC_OK;
}
printf("Page: %d not found\n", pageNum);
// If the pagelists in the memory is less than the total available pagelists,
// locate the first empty frame from the head.
if((attribute->plists->length) < bm->numPages){
printf("Ready to append Page: %d\n", pageNum);
isfound = attribute->plists->head;
for(int i=0; i< attribute->plists->length; i++){
isfound = isfound->next;
}
printf("Page: %d has append\n", pageNum);
//add pages to the pageLists, increment the size
attribute->plists->length ++;
}
else{
//For new page, if the pagelists are filled,
//locate the oldest frame has fixCount = 0
isfound = attribute->plists->tail;
printf("Replace Page: %d\n", pageNum);
while(isfound != NULL && isfound->fixCount != 0){
isfound = isfound->previous;
}
printf("Page: %d replaced\n", pageNum);
// Check whether traverse the whole list,
// if True, then no pages available to update
if (isfound == NULL){
return RC_TRAVERSE_TO_THE_END;
}
}
// Initialize return code
RC rc;
if((rc =
exchangePageFrame(bm, page, pageNum, isfound)) != RC_OK){return rc;}
//make the new pageframe as head
makeHead(&(attribute->plists), isfound);
return RC_OK;
}
/* LRU_K() replacement strategy :
1. same as FIFO and LRU, check whether the requested pageframe in memory
or not, if not, then check if the list is full, If not full,
find empty pageframe and update.
2. everytime a page has been pinned, store the pinCount into khist array.
3. If the requested pageframe not in memory, traverse from the head pointer,
find pageframe with fixCount = 0,
and calculate the distance between current entry in khist and k-th
entry in khist, replace the longest one.
4. If no page is called k times, worked just as LRU.
*/
RC LRU_K (BM_BufferPool *const bm, BM_PageHandle *const page,
const PageNumber pageNum){
pageFrame *isfound;
BMAttri *attribute = (BMAttri *)bm->mgmtData;
//initialize distance and maxdistance
int distance, maxDistance = -1;
int K = (uintptr_t)(attribute->stratData);
attribute->countPinning++;
// Check if page already in memory.
if((isfound = inPageList(bm, page, pageNum)) != NULL){
for(int i = K-1; i > 0; i--){
attribute->khist[isfound->page->pageNum][i] =
attribute->khist[isfound->page->pageNum][i-1];
}
//store the pinCount in khist array
attribute->khist[isfound->page->pageNum][0] = attribute->countPinning;
return RC_OK;
}
// If the pagelists in the memory are less than the total available pagelists,
// find out the first empty pageframe from the head.
if((attribute->plists->length) < bm->numPages){
isfound = attribute->plists->head;
for(int i=0; i< attribute->plists->length; i++){
isfound = isfound->next;
}
//add pages to the pageLists, increment the size
(attribute->plists->length)++;
}
else{
//traverse from the head
pageFrame *current = attribute->plists->head;
//check fixCount !=0 and exist distance
while(current != NULL){
if(current->fixCount == 0 &&
attribute->khist[current->page->pageNum][K] != -1){
distance = attribute->countPinning -
attribute->khist[current->page->pageNum][K];
//update maxDistance and current pageframe
if(distance > maxDistance){
maxDistance = distance;
isfound = current;
}
}
current = current->next;
}
// Check whether traverse the whole list,
// if there isn't exist distance, apply LRU
if(maxDistance == -1){
current = attribute->plists->head;
//checks for the least recently used node
while(current->fixCount != 0 && current != NULL){
distance = attribute->countPinning -
attribute->khist[current->page->pageNum][0];
if(distance > maxDistance){
maxDistance = distance;
isfound = current;
}
current = current->next;
}
// Check whether traverse the whole list,
// if True, then no pages available to update
if (maxDistance == -1){
return RC_TRAVERSE_TO_THE_END;
}
}
}
//initialize return code
RC rc;
if((rc =
exchangePageFrame(bm, page, pageNum, isfound)) != RC_OK){return rc;}
//update the khist array
for(int i = K-1; i>0; i--){
attribute->khist[isfound->page->pageNum][i] =
attribute->khist[isfound->page->pageNum][i-1];
}
attribute->khist[isfound->page->pageNum][0] = attribute->countPinning;
return RC_OK;
}
/*
LFU() replacement strategy :
1. same as FIFO and LRU, check whether the requested pageframe in memory
or not, if not, then check if the list is full, If not full,
find empty pageframe and update.
2. if full, traverse from the tail node to locate minimum page frequency,
locate this pageframe as head
*/
RC LFU (BM_BufferPool *const bm, BM_PageHandle *const page,
const PageNumber pageNum){
pageFrame *isfound;
BMAttri *attribute = (BMAttri *)bm->mgmtData;
page->data = (SM_PageHandle) malloc(PAGE_SIZE);
// Check if page already in memory.
if((attribute->frameContent)[pageNum] != -1){
isfound = searchByPageNum(attribute->plists, pageNum);
//give the client the detail of the page
page->pageNum = pageNum;
page->data = isfound->page->data;
//pinned, increase fixCount and pageFrequency
isfound->fixCount++;
isfound->pageFrequency++;
isfound->rf = 1;
return RC_OK;
}
// If the pagelists in the memory are less than the total available pagelists,
// find out the first empty pageframe from the head.
if((attribute->plists->length) < bm->numPages){
isfound = attribute->plists->head;
for(int i=0; i< attribute->plists->length; i++){
isfound = isfound->next;
}
//add pages to the pageLists, increment the size
attribute->plists->length ++;
makeHead(&(attribute->plists), isfound);
}
//If the pageLists is full
else{
//traverse from the tail
isfound = attribute->plists->tail;
//if current page frequency < previous page frequency,
//locate the previous pageframe as current
while(isfound != NULL &&
isfound->previous->pageFrequency < isfound->pageFrequency) {
isfound = isfound->previous;
}
//Check fixCount = 0
while(isfound->fixCount != 0 && isfound != NULL){
isfound = isfound->previous;
}
//doesn't exist fixCount = 0, return Error
if (isfound == NULL){
return RC_TRAVERSE_TO_THE_END;
}
//Make new pageframe as head
makeHead(&(attribute->plists), isfound);
}
SM_FileHandle fhandle;
//initialize return code
RC rc;
//open page file
if ((rc = openPageFile (bm->pageFile, &fhandle)) != RC_OK){
return RC_FILE_NOT_FOUND;
}
// Write it back if requested pageFrame is dirty
if(isfound->dirtyFlag == TRUE){
writeBlock(isfound->page->pageNum,&fhandle, isfound->page->data);
attribute->numWrite ++;
}
//Update frameContent[] array, set this pageframe pageNum = NO_PAGE
(attribute->frameContent)[isfound->page->pageNum] = NO_PAGE;
// Read the data into new frame.
isfound->page->data = (SM_PageHandle) malloc(PAGE_SIZE);
if((rc = ensureCapacity(pageNum, &fhandle)) != RC_OK){return rc;}
if((rc = readBlock(pageNum, &fhandle,
isfound->page->data)) != RC_OK){return rc;}
//give the client the detail of the page
page->pageNum = pageNum;
page->data = isfound->page->data;
attribute->numRead++;
//set attribute of the bufferpool
isfound->dirtyFlag = FALSE;
isfound->fixCount = 1;
isfound->page->pageNum = pageNum;
isfound->rf = 1;
isfound->pageFrequency = 1;
//update frameContent and>pageContent
(attribute->frameContent)[isfound->page->pageNum] = isfound->frameNum;
(attribute->pageContent)[isfound->frameNum] = isfound->page->pageNum;
return RC_OK;
}
/*
CLOCK() replacement strategy:
1. same as FIFO and LRU, check whether the requested pageframe in memory
or not
2. Instead of check full, instantly check the first pageframe with a reference
bit = 0 from head.
3. set reference bit = 0 when traversing.
*/
RC CLOCK (BM_BufferPool *const bm, BM_PageHandle *const page,const PageNumber pageNum)
{
pageFrame *isfound;
BMAttri *attribute = (BMAttri *)bm->mgmtData;
//Check if pageframe in pageLists
if((isfound = inPageList(bm, page, pageNum)) != NULL){return RC_OK;}
//traverse from head
else{
pageFrame *current = attribute->plists->head;
//locate the pageframe with reference bit = 0
while (current != NULL && current->rf == 1){
current->rf = 0;
current = current->next;
}
//If all pageframe's reference bit = 1, return an Error
if (current == NULL){
return RC_TRAVERSE_TO_THE_END;
}
isfound = current;
}
//Initialize return code
RC rc;
// call exchangePageFrame with the new value of isfound
if((rc =
exchangePageFrame(bm, page, pageNum, isfound)) != RC_OK){return rc;}
return RC_OK;
}
/*Buffer Pool Functions*/
RC initBufferPool(BM_BufferPool *const bm, const char *const pageFileName,
const int numPages, ReplacementStrategy strategy,
void *stratData){
//initialize storagemanager
SM_FileHandle fhandle;
//Check valid PageNum
if(!bm || numPages <= 0){
return RC_INVALID_PARAMETER;
}
//open the pageFile
if (openPageFile ((char *)pageFileName, &fhandle) != RC_OK){
return RC_FILE_NOT_FOUND;
}
//Initialize Buffer manager mgmtInfo
BMAttri *attribute = malloc(sizeof(BMAttri));
attribute->numRead = 0;
attribute->numWrite = 0;
attribute->stratData = stratData;
attribute->countPinning = 0;
// Initialize the lookup arrays with 0 values.
memset(attribute->pageContent,NO_PAGE,MAX_FRAMES*sizeof(int));
memset(attribute->frameContent,NO_PAGE,MAX_PAGES*sizeof(int));
memset(attribute->dirtyFlagContent,NO_PAGE,MAX_FRAMES*sizeof(bool));
memset(attribute->fixCountContent,NO_PAGE,MAX_FRAMES*sizeof(int));
memset(attribute->khist, -1, sizeof(&(attribute->khist)));
memset(attribute->FrequencyContent,0,MAX_PAGES*sizeof(int));
// Creating the linked list of empty plists.
attribute->plists = malloc(sizeof(pageList));
attribute->plists->head = attribute->plists->tail = createNewFrame();
attribute->plists->length = 0;
//Create the pageLists
for(int i = 1; i<numPages; ++i){
attribute->plists->tail->next = createNewFrame();
attribute->plists->tail->next->previous = attribute->plists->tail;
attribute->plists->tail = attribute->plists->tail->next;
attribute->plists->tail->frameNum = i;
}
//set bm attribute
bm->numPages = numPages;
bm->pageFile = (char*) pageFileName;
bm->strategy = strategy;
bm->mgmtData = attribute;
//close the pagefile
closePageFile(&fhandle);
return RC_OK;
}
RC shutdownBufferPool(BM_BufferPool *const bm){
//Initialize return code
RC rc;
BMAttri *attribute = (BMAttri *)bm->mgmtData;
pageFrame *current = attribute->plists->head;
if (!bm || bm->numPages <= 0){
return RC_INVALID_PARAMETER;
}
//call forceFlushPool()
if((rc = forceFlushPool(bm)) != RC_OK){return rc;}
//traverse from head
while(current != NULL){
current = current->next;
//deallocate memory
free(attribute->plists->head->page->data);
free(attribute->plists->head);
attribute->plists->head = current;
}
//deallocate head and tail pointer
attribute->plists->head = attribute->plists->tail = NULL;
free(attribute->plists);
free(attribute);
bm->numPages = 0;
return RC_OK;
}
RC forceFlushPool(BM_BufferPool *const bm){
//check valid Parameter
if (!bm || bm->numPages <= 0){
return RC_INVALID_PARAMETER;
}
BMAttri *attribute = (BMAttri *)bm->mgmtData;
SM_FileHandle fhandle;
pageFrame *current = attribute->plists->head;
//open a file
if (openPageFile ((char *)(bm->pageFile), &fhandle) != RC_OK){
return RC_FILE_NOT_FOUND;
}
//If a file is dirty, write back to the file
while(current != NULL){
if(current->dirtyFlag == TRUE){
if(writeBlock(current->page->pageNum,
&fhandle, current->page->data) != RC_OK){
return RC_WRITE_FAILED;
}
current->dirtyFlag = FALSE;
(attribute->numWrite)++;
}
current = current->next;
}
closePageFile(&fhandle);
return RC_OK;
}
/*Page Management Functions*/
RC pinPage (BM_BufferPool *const bm, BM_PageHandle *const page,
const PageNumber pageNum){
if (!bm || bm->numPages <= 0){
return RC_INVALID_PARAMETER;
}
if(pageNum < 0){
return RC_READ_NON_EXISTING_PAGE;
}
//Cases to implement replacement strategy
switch (bm->strategy)
{
case RS_FIFO:
return FIFO(bm,page,pageNum);
break;
case RS_LRU:
return LRU(bm,page,pageNum);
break;
case RS_CLOCK:
return CLOCK(bm,page,pageNum);
break;
case RS_LFU:
return LFU(bm,page,pageNum);
break;
case RS_LRU_K:
return LRU_K(bm,page,pageNum);
break;
default:
return RC_INVALID_STRATEGY;
break;
}
return RC_OK;
}
RC unpinPage (BM_BufferPool *const bm, BM_PageHandle *const page){
//check invalid parameter
if (!bm || bm->numPages <= 0){
return RC_INVALID_PARAMETER;
}
BMAttri *attribute = (BMAttri *)bm->mgmtData;
pageFrame *toUnpinned;
//Set the pointer to the target pageframe which need to unpinned
if((toUnpinned =
searchByPageNum(attribute->plists, page->pageNum)) == NULL){
return RC_LOCATE_PAGE_FAILED;
}
//When finished unpin, decrement fixCount by 1
if(toUnpinned->fixCount > 0){
toUnpinned->fixCount--;
}
else{
return RC_LOCATE_PAGE_FAILED;
}
return RC_OK;
}
RC markDirty (BM_BufferPool *const bm, BM_PageHandle *const page){
//check invalid parameter
if (!bm || bm->numPages <= 0){
return RC_INVALID_PARAMETER;
}
BMAttri *attribute = (BMAttri *)bm->mgmtData;
pageFrame *toMarkDirty;
//Set the pointer to the target pageframe which need to markDirty
if((toMarkDirty =
searchByPageNum(attribute->plists, page->pageNum)) == NULL){
return RC_LOCATE_PAGE_FAILED;
}
//Update the pageframe's dirtyFlag = True
toMarkDirty->dirtyFlag = TRUE;
return RC_OK;
}
RC forcePage (BM_BufferPool *const bm, BM_PageHandle *const page){
//Check invalid parameter
if (!bm || bm->numPages <= 0){
return RC_INVALID_PARAMETER;
}
BMAttri *attribute = (BMAttri *)bm->mgmtData;
SM_FileHandle fhandle;
pageFrame *toWriteBack;
//open the pageFile
if (openPageFile ((char *)(bm->pageFile), &fhandle) != RC_OK){
return RC_FILE_NOT_FOUND;
}
//Set the pointer to the target pageframe which need to writeback
if((toWriteBack =
searchByPageNum(attribute->plists, page->pageNum)) == NULL){
closePageFile(&fhandle);
return RC_LOCATE_PAGE_FAILED;
}
//Write the pointing pageframe's content banck to pageFile
if(writeBlock(toWriteBack->page->pageNum,
&fhandle, toWriteBack->page->data) != RC_OK){
closePageFile(&fhandle);
return RC_WRITE_FAILED;
}
attribute->numWrite ++;
closePageFile(&fhandle);
return RC_OK;
}
/*Statistics Functions*/
/*return the value of>pageContent*/
PageNumber *getFrameContents (BM_BufferPool *const bm){
BMAttri *attribute = (BMAttri *)bm->mgmtData;
return attribute->pageContent;
}
/*Traverse through the pagelists from head then
updates the entry of dirtyFlagContent accordingly*/
bool *getDirtyFlags (BM_BufferPool *const bm){
BMAttri *attribute = (BMAttri *)bm->mgmtData;
pageFrame *current = attribute->plists->head;
while (current != NULL){
(attribute->dirtyFlagContent)[current->frameNum] = current->dirtyFlag;
current = current->next;
}
return attribute->dirtyFlagContent;
}
/*Traverse through the pagelists from head then
updates the entry of fixCountContent accordingly*/
int *getFixCounts (BM_BufferPool *const bm){
BMAttri *attribute = (BMAttri *)bm->mgmtData;
pageFrame *current = attribute->plists->head;
while (current != NULL){
(attribute->fixCountContent)[current->frameNum] = current->fixCount;
current = current->next;
}
return attribute->fixCountContent;
}
/*returns the value of numRead*/
int getNumReadIO (BM_BufferPool *const bm){
BMAttri *attribute = (BMAttri *)bm->mgmtData;
return attribute->numRead;
}
/*returns the value of numWrite*/
int getNumWriteIO (BM_BufferPool *const bm){
BMAttri *attribute = (BMAttri *)bm->mgmtData;
return attribute->numWrite;
}
|
C
|
#include "boot_systicks.h"
#include "boot_regmap.h"
static volatile uint32_t g_u32SysTickCount = 0;
/**
* @brief This function is init system tick module.
* @note ticks should be the CPU frequency, then the count interval should be 1ms.
* @retval None
*/
void SysTicks_Init(uint32_t ticks)
{
if ((ticks - 1UL) > SysTick_LOAD_RELOAD_Msk) { return; } /* Reload value impossible */
SysTick->LOAD = (uint32_t)(ticks - 1UL); /* set reload register */
SysTick->VAL = 0UL; /* Load the SysTick Counter Value */
SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk |
SysTick_CTRL_TICKINT_Msk |
SysTick_CTRL_ENABLE_Msk; /* Enable SysTick IRQ and SysTick Timer */
return ; /* Function successful */
}
/**
* @brief This function is uninit system tick module.
* @note None
* @retval None
*/
void SysTicks_UnInit(void)
{
SysTick->CTRL &= ~(SysTick_CTRL_CLKSOURCE_Msk |
SysTick_CTRL_TICKINT_Msk |
SysTick_CTRL_ENABLE_Msk); /* Disable SysTick IRQ and SysTick Timer */
return ; /* Function successful */
}
/**
* @brief This function is called to increment a global variable "g_u32SysTickCount"
* used as application time base.
* @note In the default implementation, this variable is incremented each in Systick ISR.
* @retval None
*/
void SysTicks_IncTickCount(void)
{
g_u32SysTickCount++;
}
/**
* @brief Provides a tick value
* @note: Call xTaskGetTickCount instead if the FreeRTOS is running.
* @retval Tick value
*/
uint32_t SysTicks_GetTickCount(void)
{
return g_u32SysTickCount;
}
/**
* @brief This function provides delay based on variable incremented.
* @note In the default implementation , SysTick timer is the source of time base.
* It is used to generate interrupts at regular time intervals where u32_Tick
* is incremented.
* call vTaskDelay instead if the FreeRTOS is running.
* @param Delay: specifies the delay time length, in milliseconds.
* @retval None
*/
void SysTicks_DelayMS(uint32_t msDelay)
{
uint32_t tickstart = 0;
uint32_t tickcurrent = 0;
tickstart = g_u32SysTickCount;
while(1)
{
tickcurrent = g_u32SysTickCount;
if (tickcurrent >= tickstart)
{
if ((tickcurrent - tickstart) >= msDelay)
{
break;
}
}
else
{
if (((MAX_SYS_TICK_COUNT - tickstart) + tickcurrent) >= msDelay)
{
break;
}
}
}
}
/**
* @brief Standard millisecond sleep API.
* @note
* @retval None
*/
void msleep(uint32_t millisecs)
{
SysTicks_DelayMS(millisecs);
}
/**
* @brief Standard second sleep API.
* @note
* @retval None
*/
void ssleep(uint32_t seconds)
{
SysTicks_DelayMS(seconds * 1000);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* fillers1.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: srobert- <srobert-@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/03/14 21:01:13 by srobert- #+# #+# */
/* Updated: 2019/04/08 15:18:27 by srobert- ### ########.fr */
/* */
/* ************************************************************************** */
#include "head.h"
int knight_hor_fill3(t_mapcache **mapa, char c)
{
if ((*mapa)->side - (*mapa)->i < 2)
return (-1);
if ((*mapa)->side - (*mapa)->j < 3)
return (-2);
if ((*mapa)->side - (*mapa)->j >= 3 &&
(ft_isalpha((*mapa)->map[(*mapa)->i][(*mapa)->j])) == 0 &&
(ft_isalpha((*mapa)->map[(*mapa)->i][(*mapa)->j + 1])) == 0 &&
(ft_isalpha((*mapa)->map[(*mapa)->i][(*mapa)->j + 2])) == 0 &&
(ft_isalpha((*mapa)->map[(*mapa)->i + 1][(*mapa)->j + 2]) == 0))
{
(*mapa)->map[(*mapa)->i][(*mapa)->j] = c;
(*mapa)->map[(*mapa)->i][(*mapa)->j + 1] = c;
(*mapa)->map[(*mapa)->i][(*mapa)->j + 2] = c;
(*mapa)->map[(*mapa)->i + 1][(*mapa)->j + 2] = c;
return (1);
}
return (0);
}
int snake_hor_fill1(t_mapcache **mapa, char c)
{
if ((*mapa)->side - (*mapa)->i < 2)
return (-1);
if ((*mapa)->side - (*mapa)->j < 2)
return (-2);
if ((*mapa)->j > 0 &&
(ft_isalpha((*mapa)->map[(*mapa)->i][(*mapa)->j])) == 0 &&
(ft_isalpha((*mapa)->map[(*mapa)->i][(*mapa)->j + 1])) == 0 &&
(ft_isalpha((*mapa)->map[(*mapa)->i + 1][(*mapa)->j])) == 0 &&
(ft_isalpha((*mapa)->map[(*mapa)->i + 1][(*mapa)->j - 1])) == 0)
{
(*mapa)->map[(*mapa)->i][(*mapa)->j] = c;
(*mapa)->map[(*mapa)->i][(*mapa)->j + 1] = c;
(*mapa)->map[(*mapa)->i + 1][(*mapa)->j] = c;
(*mapa)->map[(*mapa)->i + 1][(*mapa)->j - 1] = c;
return (1);
}
return (0);
}
int square_fill(t_mapcache **mapa, char c)
{
if ((*mapa)->side - (*mapa)->i < 2)
return (-1);
if ((*mapa)->side - (*mapa)->j < 2)
return (-2);
if ((ft_isalpha((*mapa)->map[(*mapa)->i][(*mapa)->j])) == 0 &&
(ft_isalpha((*mapa)->map[(*mapa)->i][(*mapa)->j + 1])) == 0 &&
(ft_isalpha((*mapa)->map[(*mapa)->i + 1][(*mapa)->j])) == 0 &&
(ft_isalpha((*mapa)->map[(*mapa)->i + 1][(*mapa)->j + 1])) == 0)
{
(*mapa)->map[(*mapa)->i][(*mapa)->j] = c;
(*mapa)->map[(*mapa)->i][(*mapa)->j + 1] = c;
(*mapa)->map[(*mapa)->i + 1][(*mapa)->j] = c;
(*mapa)->map[(*mapa)->i + 1][(*mapa)->j + 1] = c;
return (1);
}
return (0);
}
int stick_hor_fill(t_mapcache **mapa, char c)
{
if ((*mapa)->side - (*mapa)->i < 1)
return (-1);
if ((*mapa)->side - (*mapa)->j < 4)
return (-2);
if ((ft_isalpha((*mapa)->map[(*mapa)->i][(*mapa)->j])) == 0 &&
(ft_isalpha((*mapa)->map[(*mapa)->i][(*mapa)->j + 1])) == 0 &&
(ft_isalpha((*mapa)->map[(*mapa)->i][(*mapa)->j + 2])) == 0 &&
(ft_isalpha((*mapa)->map[(*mapa)->i][(*mapa)->j + 3])) == 0)
{
(*mapa)->map[(*mapa)->i][(*mapa)->j] = c;
(*mapa)->map[(*mapa)->i][(*mapa)->j + 1] = c;
(*mapa)->map[(*mapa)->i][(*mapa)->j + 2] = c;
(*mapa)->map[(*mapa)->i][(*mapa)->j + 3] = c;
return (1);
}
return (0);
}
int stick_vert_fill(t_mapcache **mapa, char c)
{
if ((*mapa)->side - (*mapa)->i < 4)
return (-1);
if ((*mapa)->side - (*mapa)->j < 1)
return (-2);
if ((ft_isalpha((*mapa)->map[(*mapa)->i][(*mapa)->j])) == 0 &&
(ft_isalpha((*mapa)->map[(*mapa)->i + 1][(*mapa)->j])) == 0 &&
(ft_isalpha((*mapa)->map[(*mapa)->i + 2][(*mapa)->j])) == 0 &&
(ft_isalpha((*mapa)->map[(*mapa)->i + 3][(*mapa)->j])) == 0)
{
(*mapa)->map[(*mapa)->i][(*mapa)->j] = c;
(*mapa)->map[(*mapa)->i + 1][(*mapa)->j] = c;
(*mapa)->map[(*mapa)->i + 2][(*mapa)->j] = c;
(*mapa)->map[(*mapa)->i + 3][(*mapa)->j] = c;
return (1);
}
return (0);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#define MAXN 200001
int Compare(const void *a, const void *b){
return *(int *)a - *(int *)b ;
}
int main()
{
int n, k;
unsigned long long int count = 0;
int a[MAXN] = {0};
scanf("%d %d", &n, &k);
for(int i = 0; i < n; i++){
scanf("%d", &a[i]);
}
qsort(a, n, sizeof(int), Compare);
for(int i = 0, j = n-1; i < j;){
if( a[i] + a[j] > k){
j--;
}
else{
count = count + (j - i);//找到能结合最小的数a[0]的数a[j]。 他们中间所有的数都可以和a[0结合]。下一个循环找a[1]结合的数
i++;
}
if
}
printf("%d", count);
return 0;
}
|
C
|
/* Write a program to count the number of occurrences of any two vowels insuccession in a line of text.
for example , in the sentence "Please read this application and give me gratuity"
such occurrences are ea, ea, ui*/
#include <stdio.h>
#include <string.h>
int is_vowel(char vowel);
int main(void)
{
char array[100];
int counter = 0, i = 0,j;
printf("enter the sentence:");
scanf("%[^\n]", array);
while(array[i] != '\0')
{
if(is_vowel(array[i]) && is_vowel(array[i + 1]))
{
counter++;
i = i + 2;
}
else
{
i++;
}
}
printf("counter is %d\n", counter);
}
int is_vowel(char vowel)
{
return(vowel == 'a' || vowel == 'e'|| vowel == 'i' || vowel == 'o' || vowel == 'u');
}
|
C
|
/** @file
Byte Swap routines for endian-nes conversions.
Copyright (c) 2010, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials are licensed and made available under
the terms and conditions of the BSD License that accompanies this distribution.
The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php.
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
**/
#include <Library/BaseLib.h>
#include <LibConfig.h>
#include <sys/bswap.h>
// Undefine macro versions of the functions to be defined below.
#undef bswap16
#undef bswap32
#undef bswap64
/**
Switches the endianness of a 16-bit integer.
This function swaps the bytes in a 16-bit unsigned value to switch the value
from little endian to big endian or vice versa. The byte swapped value is
returned.
@param Value A 16-bit unsigned value.
@return The byte swapped Value.
**/
uint16_t bswap16(uint16_t Value)
{
return SwapBytes16(Value);
}
/**
Switches the endianness of a 32-bit integer.
This function swaps the bytes in a 32-bit unsigned value to switch the value
from little endian to big endian or vice versa. The byte swapped value is
returned.
@param Value A 32-bit unsigned value.
@return The byte swapped Value.
**/
uint32_t bswap32(uint32_t Value)
{
return SwapBytes32(Value);
}
/**
Switches the endianness of a 64-bit integer.
This function swaps the bytes in a 64-bit unsigned value to switch the value
from little endian to big endian or vice versa. The byte swapped value is
returned.
@param Value A 64-bit unsigned value.
@return The byte swapped Value.
**/
uint64_t bswap64(uint64_t Value)
{
return SwapBytes64(Value);
}
|
C
|
#include <stdio.h>
#include <unistd.h>
#include "zenoh.h"
#include "zenoh/codec.h"
int main(int argc, char **argv) {
char *locator = strdup("tcp/127.0.0.1:7447");
if (argc > 1) {
locator = argv[1];
}
printf("Connecting to %s...\n", locator);
z_zenoh_p_result_t r_z = z_open(locator, 0, 0);
ASSERT_RESULT(r_z, "Unable to open session with broker")
z_zenoh_t *z = r_z.value.zenoh;
printf("Declaring Resource...\n");
z_iobuf_t data = z_iobuf_make(256);
char *str = "Hello World!";
z_string_encode(&data, str);
printf("Streaming Data...\n");
while (1) {
z_write_data(z, "/demo/hello/1", data.buf, z_iobuf_readable(&data));
sleep(1);
}
return 0;
}
|
C
|
#include<stdio.h>
int main() {
int i, num, countPares=0, countImpares=0, countPositivos=0, countNegativos=0;
for(i=0; i<5; i++) {
scanf("%d", &num);
if(num%2 == 0) {
countPares++;
}
if(num%2 != 0){
countImpares++;
}
if(num > 0) {
countPositivos++;
}
if(num < 0) {
countNegativos++;
}
}
printf("%d valor(es) par(es)\n", countPares);
printf("%d valor(es) impar(es)\n", countImpares);
printf("%d valor(es) positivo(s)\n", countPositivos);
printf("%d valor(es) negativo(s)\n", countNegativos);
return 0;
}
|
C
|
/**
* @file CodeQ1_server.c
* @brief This file is used for the server side creation of node created using TCP protocol and
* IPv4 and to send and listen to the messages
* through the port and also to connect with other client sockets.
*
* @author Abhishek Rathod (17114004)
*
* @date 1/10/2019
*/
#include <unistd.h>
#include <stdio.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <string.h>
#include <time.h> // time()
#define PORT 8080
/// addseven parity to a string
void add_parity(char message[]){
int parity=0 ;
for(int i=0;i<strlen(message);i++){
if(message[i]=='1'){
parity=(parity+1)%2 ;
}
}
if(parity==1){
strcat(message,"1") ;
} else {
strcat(message,"0") ;
}
}
/// adds 2d parity to an 2-d character array
char* add_2dparity(char** message,int segments,int len){
for(int i=0;i<segments;i++){
add_parity(message[i]) ;
}
int parity=0 ;
char* add = malloc(sizeof(char)*(len+1));
for(int i=0;i<len+1;i++){
add[i]='0' ;
}
for(int i=0;i<len+1;i++){
parity=0 ;
for(int j=0;j<segments;j++){
if(message[j][i]=='1'){
parity=(parity+1)%2 ;
}
}
if(parity==1){
add[i]='1' ;
}
}
return (char *)add ;
}
/// adds 2 binary strings
char* add_bin(char* m1, char* m2, int len){
char* ans=malloc(sizeof(char)*len) ;
char carry='0' ;
for(int i=strlen(m1)-1;i>=0;i--){
if(m1[i]=='0' && m2[i]=='0'){
if(carry=='0'){
ans[i]='0' ;
} else{
ans[i]='1' ;
carry='0' ;
}
} else if(m1[i]=='0' && m2[i]=='1'){
if(carry=='0'){
ans[i]='1' ;
} else{
ans[i]='0' ;
carry='1' ;
}
} else if(m1[i]=='1' && m2[i]=='0'){
if(carry=='0'){
ans[i]='1' ;
} else{
ans[i]='0' ;
carry='1' ;
}
} else if(m1[i]=='1' && m2[i]=='1'){
if(carry=='0'){
ans[i]='0' ;
carry='1' ;
} else{
ans[i]='1' ;
carry='1' ;
}
}
}
if(carry=='1'){
for(int i=strlen(ans)-1;i>=0;i--){
if(ans[i]=='1'){
ans[i]='0' ;
} else {
ans[i]='1' ;
break ;
}
}
}
return (char *)ans;
}
/// sums up the character array with segments
char* add_sum(char** message,int segments,int len){
if(segments==1){
return (char *)message[0] ;
}
char* sum = malloc(sizeof(char)*len) ;
for(int i=1;i<segments;i++){
if(i==1){
sum=add_bin(message[0],message[1],len) ;
} else {
sum=add_bin(sum,message[i],len) ;
}
}
for(int i=0;i<len;i++){
if(sum[i]=='1'){
sum[i]='0' ;
} else {
sum[i]='1' ;
}
}
return (char *)sum ;
}
/// giver xor of 2 strings
char* xor(char* a, char* b){
char* ret = malloc(sizeof(char)*strlen(a)) ;
for(int i=0;i<strlen(a);i++){
if((a[i]=='0'&&b[i]=='0') || (a[i]=='1'&&b[i]=='1')){
ret[i]='0' ;
} else if((a[i]=='0'&&b[i]=='1') || (a[i]=='1'&&b[i]=='0')){
ret[i]='1';
}
}
char* ret1 = malloc(sizeof(char)*(strlen(a)-1)) ;
for(int i=0;i<strlen(a)-1;i++){
ret1[i]=ret[i+1] ;
}
return (char *)ret1 ;
}
/// the CRC encoder block
char* update_CRC(char* message, char* divi1, int len){
char ch1[strlen(divi1)] ;
for(int i=0;i<strlen(divi1)-1;i++){
ch1[i]='0' ;
}
strcat(message,ch1) ;
strcat(ch1,"0") ;
int pick=strlen(divi1) ;
char* tmp=malloc(sizeof(char)*pick) ;
for(int i=0;i<pick;i++){
tmp[i]=message[i] ;
}
while(pick<strlen(message)){
if(tmp[0]=='1'){
tmp=xor(divi1, tmp);
tmp[strlen(tmp)]=message[pick] ;
} else {
tmp=xor(ch1, tmp);
tmp[strlen(tmp)]=message[pick] ;
}
pick++ ;
}
if(tmp[0]=='1'){
tmp=xor(divi1,tmp) ;
} else {
tmp=xor(ch1, tmp) ;
}
return (char *)tmp ;
}
/**
* This is the main method and all the functions used to create, bind the socket and to communicate
* with other sockets are implemented in this method.
* @author Abhishek Rathod (17114004)
* @param
* @date 1/10/2019
*/
int main(int argc, char const *argv[])
{
/// This is used to store the file descriptors of the socket.
int server_fd ;
/// This will create a new socket for the client when input will be given by client.
int new_socket ;
/// This will contain the return value when message will be sent by the client.
int valread ;
/// This will store various socket attributes.
struct sockaddr_in address;
int opt = 1;
int addrlen = sizeof(address);
/// This will contian the message that the client has sent.
char buffer[1024] = {0};
/// This is the message that will be sent to the client.
printf("Which algorithm do you want to use for checking :-\n") ;
printf("1. Single Parity Check\n2. Two-dimensional Parity Check\n3. Checksum\n4. Cyclic Redundancy Check (CRC)\n") ;
int option ;
scanf("%d",&option) ;
int len=0 ;
int segments=0 ;
char* divisor;
char* message1 ;
char** message23 ;
char* message4 ;
switch(option){
case 1 :
printf("Length of the Message:") ;
scanf("%d",&len) ;
printf("N bits binary message:");
message1 = calloc(sizeof(char),len) ;
scanf("%s",message1) ;
add_parity(message1) ;
break ;
case 2 :
printf("Length of the Message:") ;
scanf("%d",&len) ;
printf("Number of segments of message:") ;
scanf("%d",&segments) ;
len=len/segments ;
message23 = calloc(sizeof(char*),segments) ;
for(int i=0;i<segments;i++){
printf("%dth segment of %d bits:\n",(i+1),len);
message23[i] = calloc(sizeof(char),len) ;
scanf("%s",message23[i]) ;
}
message23[segments]=add_2dparity(message23,segments,len) ;
segments++ ;
break ;
case 3 :
printf("Length of the Message:") ;
scanf("%d",&len) ;
printf("Number of segments of message:") ;
scanf("%d",&segments) ;
len=len/segments ;
message23 = calloc(sizeof(char*),segments) ;
for(int i=0;i<segments;i++){
printf("%dth segment of %d bits:\n",(i+1),len);
message23[i] = calloc(sizeof(char),len) ;
scanf("%s",message23[i]) ;
}
message23[segments]=add_sum(message23,segments,len) ;
segments++ ;
break ;
case 4 :
printf("Divisor: ");
scanf("%s",divisor) ;
printf("Length of the Message:") ;
scanf("%d",&len) ;
message4 = calloc(sizeof(char),len) ;
printf("N bits binary message:");
scanf("%s",message4) ;
char* rem = malloc(sizeof(char)*(strlen(divisor)-1));
rem=update_CRC(message4,divisor,len) ;
for(int i=len;i<strlen(message4);i++){
message4[i]=rem[i-len] ;
}
len=strlen(message4) ;
break ;
default:
printf("Enter a valid option !!!");
}
/// Creating socket file descriptor
server_fd = socket(AF_INET, SOCK_STREAM, 0) ;
if (server_fd < 0) {
printf("socket creation failed");
exit(EXIT_FAILURE);
}
/// Assigning various attribute values to the sockaddr_in struct.
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons( PORT );
///printing original message
printf("\nThe Original message is :- \n");
if(option==1){
printf("%s\n",message1);
} else if(option==4){
printf("%s\n",message4);
} else if(option==2 || option==3){
for(int i=0;i<segments;i++){
printf("%s\n",message23[i]);
}
}
int er_opt ;
printf("\nHow you want to add an error\n1.Manually add an error\n2.Randomly add an error\n") ;
scanf("%d",&er_opt) ;
int n_flips=0 ;
int** flip_indices ;
float pe=0.0;
switch(er_opt) {
case 1 :
if(option==1){
printf("a. Enter number of bits to be flipped:");
scanf("%d",&n_flips) ;
flip_indices = calloc(sizeof(int*),n_flips) ;
printf("b. Enter bits (B indices) to be flipped:-\n") ;
for(int i=0;i<n_flips;i++){
flip_indices[i] = calloc(sizeof(int),1) ;
scanf("%d",flip_indices[i]) ;
}
for(int i=0;i<n_flips;i++){
if(message1[*flip_indices[i]]=='1'){
message1[*flip_indices[i]]='0' ;
} else {
message1[*flip_indices[i]]='1' ;
}
}
printf("Message to be transmitted is : %s\n",message1);
} else if(option==4) {
printf("a. Enter number of bits to be flipped:");
scanf("%d",&n_flips) ;
flip_indices = calloc(sizeof(int*),n_flips) ;
printf("b. Enter bits (B indices) to be flipped:-\n") ;
for(int i=0;i<n_flips;i++){
flip_indices[i] = calloc(sizeof(int),1) ;
scanf("%d",flip_indices[i]) ;
}
for(int i=0;i<n_flips;i++){
if(message4[*flip_indices[i]]=='1'){
message4[*flip_indices[i]]='0' ;
} else {
message4[*flip_indices[i]]='1' ;
}
}
printf("Message to be transmitted is : %s\n",message4);
} else {
for(int i=0;i<segments;i++){
printf("For %dth segment\n",(i+1));
printf("a. Enter number of bits to be flipped:");
scanf("%d",&n_flips) ;
flip_indices = calloc(sizeof(int*),n_flips) ;
printf("b. Enter bits (B indices) to be flipped:-\n") ;
for(int i=0;i<n_flips;i++){
flip_indices[i] = calloc(sizeof(int),1) ;
scanf("%d",flip_indices[i]) ;
}
for(int j=0;j<n_flips;j++){
if(message23[i][*flip_indices[j]]=='1'){
message23[i][*flip_indices[j]]='0' ;
} else {
message23[i][*flip_indices[j]]='1' ;
}
}
}
for(int i=0;i<segments;i++){
printf("Message to be transmitted is : %s\n",message23[i]);
}
}
break ;
case 2 :
printf("Enter probability of induced error:") ;
scanf("%f",&pe) ;
srand(time(0));
if(option==1){
for(int i=0;i<len;i++){
if(pe<=(float)rand()/(float)RAND_MAX){
if(message1[i]=='1'){
message1[i]='0' ;
} else {
message1[i]='1' ;
}
}
}
printf("Message to be transmitted is : %s\n",message1);
} else if(option==4) {
for(int i=0;i<len;i++){
if(pe<=(float)rand()/(float)RAND_MAX){
if(message4[i]=='1'){
message4[i]='0' ;
} else {
message4[i]='1' ;
}
}
}
printf("Message to be transmitted is : %s\n",message4);
} else {
for(int i=0;i<segments;i++){
for(int j=0;j<len;j++){
if(pe<=(float)rand()/(float)RAND_MAX){
if(message23[i][j]=='1'){
message23[i][j]='0' ;
} else {
message23[i][j]='1' ;
}
}
}
}
for(int i=0;i<segments;i++){
printf("Message to be transmitted is : %s\n",message23[i]);
}
}
break ;
default:
printf("INVALID OPTION");
}
/// Forcefully binding socket to the port 8080
if (bind(server_fd, (struct sockaddr *)&address,sizeof(address))<0) {
printf("bind failed\n");
exit(EXIT_FAILURE);
}
/// Waiting for the client to connect
if (listen(server_fd, 3) < 0) {
printf("listen\number");
exit(EXIT_FAILURE);
}
/// creating a new socket for the client
new_socket = accept(server_fd, (struct sockaddr *)&address,(socklen_t*)&addrlen) ;
if(new_socket<0) {
printf("accept\n");
exit(EXIT_FAILURE);
}
/// Sending message to the client.
if(option==1){
send(new_socket , message1 , strlen(message1) , 0 );
} else if(option==4) {
send(new_socket , message4 , strlen(message4) , 0 );
} else {
for(int i=0;i<segments;i++){
send(new_socket , message23[i] , strlen(message23[i]) , 0 );
}
}
/// Reading the value from the client
// valread = read( new_socket , buffer, 1024);
// printf("%s\n",buffer );
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
struct Person
{
int month;
int day;
int year;
int number;
};
int main(int argc, char* argv[])
{
//Define a variable p of type struct Person
struct Person p;
p.month = 10;
p.day = 13;
p.year = 2016;
p.number = 1234;
printf("Person %d:\n\tDate: %d/%d/%d\n", p.number, p.month, p.day, p.year);
//Pointers are fun
int* age;
//The * dentoes a pointer
//The variable age is a pointer of int type
printf("Ages memory address: %p", age);
//Intitially pointers point to a random memory address
//Lets create a place for age to point
age = (int*)malloc(sizeof(int));
//allocate a block of memory the sizeof an int
//and story memory address in the age pointer
*age = 15;
//The * in front dereferences the pointer so we can acess the content of memory instead of address
printf("\n\tAge is: %d", *age);
//Then free the dynamically allocated memory
free(age);
int q;
scanf("%d", &q);
return 0;
}
|
C
|
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
/* Type definitions */
struct conf {char* c_name; } ;
/* Variables and functions */
int /*<<< orphan*/ EXIT_FAILURE ;
int /*<<< orphan*/ err (int /*<<< orphan*/ ,char*) ;
void* realloc (struct conf**,size_t) ;
scalar_t__ strcmp (char*,char*) ;
__attribute__((used)) static void
uniqueadd(struct conf ***listp, size_t *nlist, size_t *mlist, struct conf *c)
{
struct conf **list = *listp;
if (c->c_name[0] == '\0')
return;
for (size_t i = 0; i < *nlist; i++) {
if (strcmp(list[i]->c_name, c->c_name) == 0)
return;
}
if (*nlist == *mlist) {
*mlist += 10;
void *p = realloc(*listp, *mlist * sizeof(*list));
if (p == NULL)
err(EXIT_FAILURE, "Can't allocate for rule list");
list = *listp = p;
}
list[(*nlist)++] = c;
}
|
C
|
//#define TEST
#include <stdlib.h>
//#include "../my_malloc.c"
#include "lang.h"
#ifdef TEST
#include <stdio.h>
#endif
int eval_stmt(Def* def, Stmt* stmt, ProgramState* s);
int eval_expr(Def* def, Expr* e, ProgramState* s) {
int * values = s->vars;
int l, r;
if (e->type == TConst) {
return ((Const *)e->p)->val;
}
#ifdef TEST
if (e->type == TRead) {
int res;
printf("> ");
scanf("%d", &res);
return res;
}
#endif
else if (e->type == TVar) {
return values[((Var*)e->p)->var];
}
else if (e->type == TBinop) {
l = eval_expr(def, ((Binop *)e->p)->l, s);
r = eval_expr(def, ((Binop *)e->p)->r, s);
if (((Binop *)e->p)->op == Oadd) {
return l + r;
}
if (((Binop *)e->p)->op == Osub) {
return l - r;
}
if (((Binop *)e->p)->op == Omul) {
return l * r;
}
if (((Binop *)e->p)->op == Odiv) {
return l / r;
}
if (((Binop *)e->p)->op == Omod) {
return l % r;
}
if (((Binop *)e->p)->op == Olt) {
if (l < r) {
return 1;
}
return 0;
}
if (((Binop *)e->p)->op == Ole) {
if (l <= r) {
return 1;
}
return 0;
}
if (((Binop *)e->p)->op == Ogt) {
if (l > r) {
return 1;
}
return 0;
}
if (((Binop *)e->p)->op == Oge) {
if (l >= r) {
return 1;
}
return 0;
}
if (((Binop *)e->p)->op == Oeq) {
if (l == r) {
return 1;
}
return 0;
}
if (((Binop *)e->p)->op == One) {
if (l != r) {
return 1;
}
return 0;
}
if (((Binop *)e->p)->op == Oand) {
return l && r;
}
if (((Binop *)e->p)->op == Oor) {
return l || r;
}
}
else if (e->type == TCall) {
ProgramState* new_s = (ProgramState*) my_malloc(sizeof(ProgramState));
new_s->vars = (int*) my_malloc(sizeof(int) * 200);
new_s->is_ret = 0;
new_s->ret_val = 0;
Def* copy = def;
while (copy->name != ((Call *) e->p)->fun) { //no null check
copy = copy->next;
}
Par* param = ((Call *) e->p)->params;
Arg* arg = (copy)->args;
while (param != NULL) {
int * vars = new_s->vars;
vars[arg->var] = eval_expr(def, param->e, s);
arg = arg->next;
param = param->next;
}
eval_stmt(def, copy->s, new_s);
return new_s->ret_val;
}
return 0;
}
int eval_stmt(Def* def, Stmt* stmt, ProgramState* s) {
int * values = s->vars;
if (stmt->type == TSkip) {
}
else if (stmt->type == TAss) {
Ass* ass = (Ass *) stmt->s;
values[ass->var] = eval_expr(def, ass->e, s);
}
else if (stmt->type == TSeq) {
eval_stmt(def, ((Seq *) stmt->s)->l, s);
eval_stmt(def, ((Seq *) stmt->s)->r, s);
}
else if (stmt->type == TIf) {
int res = eval_expr(def, ((If *) stmt->s)->e, s);
if (res) {
eval_stmt(def, ((If *) stmt->s)->l, s);
}
else {
eval_stmt(def, ((If *) stmt->s)->r, s);
}
}
else if (stmt->type == TWhile) {
while (eval_expr(def, ((While *) stmt->s)->e, s)) {
eval_stmt(def, ((While *) stmt->s)->s, s);
}
}
else if (stmt->type == TRun) {
ProgramState* new_s = (ProgramState*) my_malloc(sizeof(ProgramState));
new_s->vars = (int*) my_malloc(sizeof(int) * 200);
new_s->is_ret = 0;
new_s->ret_val = 0;
Def* copy = def;
while (copy->name != ((Run *) stmt->s)->fun) { //no null check
copy = copy->next;
}
Par* param = ((Run *) stmt->s)->params;
Arg* arg = (copy)->args;
while (param != 0) {
int* vars = new_s->vars;
vars[arg->var] = eval_expr(def, param->e, s);
arg = arg->next;
param = param->next;
}
eval_stmt(def, copy->s, new_s);
}
#ifdef TEST
else if (stmt->type == TWrite) {
int res = eval_expr(def, ((Write *) stmt->s)->e, s);
printf("%d\n", res);
}
#endif
else if (stmt->type == TReturn) {
s->is_ret = 1;
s->ret_val = eval_expr(def, ((Return *) stmt->s)->e, s);
return s->ret_val;
}
return 0;
}
int eval_prog(Program* prog, ProgramState* s) {
return eval_stmt(prog->defs, prog->s, s);
}
|
C
|
int* data;
int find(int x) {
return data[x] == x ? x : (data[x] = find(data[x]));
}
void merge(int x, int y) {
if (find(x) != find(y)) data[find(x)] = find(y);
}
int count(int N) {
int cnt = 0;
for (int i = 0; i < N; i++)
cnt += data[i] == i;
return cnt;
}
int findCircleNum(int** M, int N, int* MColSize){
data = malloc(N * sizeof(int));
for (int i = 0; i < N; i++)
data[i] = i;
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
if (M[i][j])
merge(i, j);
int res = count(N);
free(data);
return res;
}
|
C
|
//
// Created by aaron on 10/13/16.
//
#include <stdlib.h>
#include "pow.h"
#include "util.h"
long Pow(long X, unsigned long N) {
unsigned int n = msb(N);
long* powersOfX = malloc(n * sizeof(long));
powersOfX[0] = X;
for (int i = 1; i < n; ++i) {
powersOfX[i] = powersOfX[i-1] * powersOfX[i-1];
}
long power = 1;
int i = 0;
while (N > 0) {
if (N & 1) {
power *= powersOfX[i];
}
N >>= 1;
i++;
}
return power;
}
long PowRecursion(long X, unsigned long N) {
if (N == 0) {
return 1;
} else if (N == 1) {
return X;
} else if (isEven(N)) {
return Pow(X * X, N / 2);
} else {
return Pow(X, N - 1) * X;
}
}
|
C
|
#include <stdio.h>
#define MAXNUM 20
int main()
{
int i, testn, n[MAXNUM];
testn = 8;
for (i = 0; i < MAXNUM; i++)
n[i] = i;
for (i = 0; i < MAXNUM; i++) {
if (n[i] == testn) {
printf("break at %d\n", n[i]);
break;
}
printf("%d ", n[i]);
}
i = 0;
while (i < MAXNUM) {
if (n[i] == testn) {
printf("break at %d\n", n[i]);
break;
}
printf("%d ", n[i]);
i++;
}
return 0;
}
|
C
|
#include <stdio.h>
int checkdiag (int **matrix, int size); /*Declaring Function prior to main function.(Required unless function is already placed before main*/
int
main(void)
{
int size, i, p;
int **mat;
/*Using pointer because you cannot declare an array with varibles, only with numbers. Since we must
obtain the numbers from the txt file, point is used to allow us to declare the size of this array.
Recall: You can only declare varibles in before any commands using C language. Thus you cannot
obtian the numbers form the file, then set the size of the array.*/
FILE*in;
in = fopen("matrix1.txt", "r");/*text files are: matrix1.txt matrix2.txt matrix3.txt matrix4.txt */
fscanf(in, "%d",&size);/*Obtaining size of array from txt file*/
mat = (int**) calloc (size,sizeof(int*));/*Obtaining the row for the 2-D pointer array*/
for(i=0;i<size;i++)
{
mat[i] = (int*) calloc (size, sizeof(int));/*Adding the amount of columns per row of the array*/
}
for(i=0;i<size;i++)
{
for(p=0;p<size;p++)
{
fscanf(in, "%d", &mat[i][p]);/*Scanning a single value to place into 2-Dimensional array*/
printf("%d ", mat[i][p]); /*Outputting the value at the array's position*/
}
printf("\n");
}
for(i=0;i<size;i++)/*For using pointers. pointers are "*". Used to free space or something for 2-D arrays. Similiar to using fclose()*/
{
free(mat[i]);
}
if((checkdiag(mat, size))==1)
{
printf("\nThe matrix is a %dx%d and all the numbers on the main diagonal are the same.\n", size, size);
}
else
{
printf("\nThe matrix is a %dx%d and all the numbers on the main diagonal are not the same.\n", size, size);
}
free(mat);
fclose(in);
}
int checkdiag (int **matrix, int size)
{
int i, n;
n = 0;
if(size<=100)
{
for(i=0;i<size;i++)
{
if(matrix[i][i]==matrix[0][0])
{
n++;
}
}
if(n==size)
{
return 1;
}
else
{
return 0;
}
}
}
|
C
|
#include <stdio.h>
void print(char str[])
{
printf("Your Name: ");
puts(str);
}
int main()
{
char string1[30];
char string2[30]
int result;
printf("Enter First and Last name: ");
gets(string1);
gets(string2);
print(string1);
print(string2);
result = strcmp(string1, string2);
printf("strcmp(string1,string2) = %d\n",result);
return 0;
}
|
C
|
#include "heap_lib.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define INT_MAX 9999999
void
min_heapify(hNode *ptr, int i, int size)
{
//printf("\nInside max heapify\n");
int smallest = i;
int left = (2 * i) + 1;
int right = (2 * i) + 2;
hNode *temp = NULL;
if ((left < size) && ptr[i].value > ptr[left].value)
smallest = left;
if ((right < size) && ptr[smallest].value > ptr[right].value)
smallest = right;
if (smallest != i) {
temp = &ptr[i];
ptr[i].value = ptr[smallest].value;
ptr[i].aptr = ptr[smallest].aptr;
ptr[i].index = ptr[smallest].index;
ptr[smallest].value = temp->value;
ptr[smallest].aptr = temp->aptr;
ptr[smallest].index = temp->index;
min_heapify(ptr, smallest, size);
}
//printf("\nExiting max heapify\n");
}
void
max_heapify(hNode *ptr, int i, int size)
{
#ifdef _INCLUDE
//printf("\nInside max heapify\n");
int largest = i;
int left = (2 * i) + 1;
int right = (2 * i) + 2;
hNode *temp = NULL;
if ((left < size) && ptr[i] < ptr[left])
largest = left;
if ((right < size) && ptr[largest] < ptr[right])
largest = right;
if (largest != i) {
temp = &ptr[i];
ptr[i].value = ptr[largest].value;
ptr[i].aptr = ptr[largest].aptr;
ptr[largest].value = temp->value;
ptr[largest].aptr = temp->aptr;
max_heapify(ptr, largest, size);
}
//printf("\nExiting max heapify\n");
#endif
}
void
build_max_heap(hNode *ptr, int size)
{
//printf("\nInside build max heap\n");
int i = size >> 1;
printf("i: %d\n", i);
while (i >= 0) {
max_heapify(ptr, i, size);
i--;
}
//printf("\nExiting build max heap\n");
}
void
build_min_heap(hNode *ptr, int size)
{
//printf("\nInside build max heap\n");
int i = size >> 1;
printf("i: %d\n", i);
while (i >= 0) {
min_heapify(ptr, i, size);
i--;
}
//printf("\nExiting build max heap\n");
}
int
extractMin (hNode *ptr, int size)
{
int value = ptr[0].value;
ptr[0].index++;
if (ptr[0].index == ptr[0].size)
{
ptr[0].value = INT_MAX;
min_heapify(ptr, 0, size);
return value;
}
(ptr[0].aptr)++;
ptr[0].value = *(ptr[0].aptr);
min_heapify(ptr, 0, size);
return value;
}
void
heapsort(hNode *ptr, int size)
{
#ifdef _INCLUDE
//printf("\nInside heap sort\n");
int i = size - 1;
hNode *temp = NULL;
/* First build max heap. This takes O(n) time */
build_max_heap(ptr, size);
printf("\nMax Heap\n");
for (i = 0; i < size; i++) {
printf("%d ", ptr[i].value);
}
i = size - 1;
/* Sort the max heap by extracting root each time and replace it with the last slot in the array. Then heapify */
while (i >= 1) {
temp = &ptr[0];
ptr[0].value = ptr[i].value;
ptr[0].aptr = ptr[i].aptr;
ptr[i].value = temp->value;
ptr[i].aptr = temp->aptr;
size--;
max_heapify(ptr, 0, size);
i--;
}
//printf("\nExiting heap sort\n");
#endif
}
|
C
|
#include<stdio.h>
#include<unistd.h>
int ft_iterative_power(int nb, int power)
{
int i;
if (power < 0)
return (0);
if (power == 0)
return (0);
i = nb;
while (power > 1)
{
nb *= i;
power--;
}
write(1 &nb, sizeof(nb));
return (0);
}
int main(void)
{
ft_iterative_power(5,2);
}
|
C
|
#include <stdio.h>
#define N 10
int vett[N];
void scambia(int *a,int *b) {
int c;
c=*a; *a=*b; *b=c;
}
main() {
int i;
for (i=0;i<N;i++)
vett[i]=i;
for (i=N-1;i>=0;i--)
scambia(&vett[i],&vett[i%3]);
for (i=0;i<N;i++)
printf("%d ",vett[i]);
}
/* output
* con N 10
* 3 4 5 6 7 8 9 1 2 0
* con N 5
* 3 4 2 0 1
* */
|
C
|
#include <stdio.h>
int main(void){
float num1, num2;
puts("Ola, bem vindo.");
puts("Este programa exibe o menor dentre dois numeros digitados pelo usuario.");
printf("\nPara iniciar digite o primeiro numero: ");
scanf("%f", &num1);
printf("Agora digite o segundo numero: ");
scanf("%f", &num2);
if(num1 == num2){
puts("\nEsses numeros sao iguais.");
}else if(num1 > num2){
printf("\nO menor numero eh: %.2f\n", num2);
}else{
printf("\nO menor numero eh: %.2f\n", num1);
}
return 0;
}
|
C
|
#if 0
fwatch monitors files for changes
once a change is detected, an email containing the contents
of the file being monitored is sent
compilation:
gcc fwatch.c -Wall -Wextra -Werror -Wpedantic -D_GNU_SOURCE -O3 -o fwatch
usage:
./fwatch [filename] [email_recipient]
NOTE:
make sure that postfix has been started before running this
#endif
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/socket.h>
#include <sys/un.h>
#include "shared.h"
#include "host.h"
#include "client.h"
extern struct fwpa_cont watched_files;
_Bool strtoi(const char* str, int* i){
char* res;
unsigned int r = strtol(str, &res, 10);
if(*res)return 0;
if(i)*i = (int)r;
return 1;
}
_Bool sock_open(){
/* i_connect returns -1 if it cannot connect to sock */
int sock = cli_connect();
if(sock == -1)return 0;
close(sock);
return 1;
}
void p_usage(char* bin_name){
printf("usage: %s <[a]dd filename> <[r]em fileno> <[l]ist> <[q]uit>\n", bin_name);
}
int main(int a, char** b){
if(a == 2){
switch(*b[1]){
case 'l':
list_files();
return 0;
case 'q':
quit();
return 0;
default:
if(sock_exists() && sock_open()){
printf("an instance of %s is already running. refusing to start\n", *b);
return 0;
}
init_fwpa_cont(&watched_files);
wait_conn(b[1]);
return 0;
}
}
if(a > 2){
switch(*b[1]){
case 'a':
add_file(b[2]);
return 0;
case 'r':{
int rm_ind;
if(strtoi(b[2], &rm_ind))
rm_file(rm_ind);
return 0;
}
}
}
p_usage(*b);
return 1;
}
|
C
|
#include <stdio.h>
int main(void)
{
int n = 5;
while (n < 7)
{
printf("n=%d\n", n);
n++;
printf("Now n=%d\n", n);
}
printf("Done.\n");
return 0;
}
|
C
|
/*************************************************************************
> File Name: server.c
> Author: stmatengss
> Mail: stmatengss@163.com
> Created Time: Sun Jan 22 22:48:12 2017
************************************************************************/
#include<stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <unistd.h>
//#include <linux/stat.h>
#define FIFO_FILE "sampleFIFO"
int main(void)
{
FILE *fp;
char readbuf[80];
k(0);
/*在文件系统中创建有名管道*/
mknod(FIFO_FILE, S_IFIFO|0666, 0);
while(1)
{
/*打开有名管道*/
fp = fopen(FIFO_FILE, "r");
/*从有名管道中读取数据*/
fgets(readbuf, 80, fp);
printf("Received string: %s\n", readbuf);
/*关闭有名管道*/
fclose(fp);
}
return(0);
}
|
C
|
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <glib.h>
#include "includes/common.h"
double product(int * items, int index) {
double res = 1.0;
for (int i=0; i<index; i++) {
if (items[i] != 0) {
res *= items[i];
}
}
return res;
}
int main() {
sized_digit_array digits_n;
sized_digit_array digits_d;
int ns[50];
int ds[50];
int nsds_index = 0;
int n;
int d;
for (n=11; n<99; n++) {
MEM_COPY(&d, &n);
while (d < 100) {
d++;
if (n % 10 != 0 && d % 10 != 0) {
digits_n = get_digits_array(n);
digits_d = get_digits_array(d);
if (digits_n.arr[0] == digits_d.arr[1]) {
short a = digits_n.arr[1];
short b = digits_d.arr[0];
if ((double)a / (double)b == (double)n / (double)d) {
ns[nsds_index] = n;
ds[nsds_index] = d;
nsds_index += 1;
}
}
}
}
}
printf("%lf \n%lf \n%lf\n", product(ns, nsds_index), product(ds, nsds_index), product(ns, nsds_index) /product(ds, nsds_index));
return 0;
}
|
C
|
#include <stdio.h>
/**
* main - prints the size of various types on the current machine
*
* Return: Always 0 (Success)
*/
int main(void)
{
char c;
int i;
long int long1;
long long int long2;
float f;
printf("Size of a char: %zd byte(s)\n", sizeof(c));
printf("Size of an int: %zd byte(s)\n", sizeof(i));
printf("Size of a long int: %zd byte(s)\n", sizeof(long1));
printf("Size of a long long int: %zd byte(s)\n", sizeof(long2));
printf("Size of a float: %zd byte(s)\n", sizeof(f));
return (0);
}
|
C
|
#include "monty.h"
/**
* pint - print the numbers add
* @node: is the element
* @line_number: line number
*/
void pint(stack_t **node, unsigned int line_number)
{
stack_t *node_pall = *node;
if (!node_pall)
{
fprintf(stderr, "L%u: can't pint, stack empty\n", line_number);
free(var.buff);
free_stack(*node);
fclose(var.fd);
exit(EXIT_FAILURE);
}
printf("%d\n", node_pall->n);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "binary_tree.h"
#include "stack.h"
BinaryTree *create_BinaryTree()
{
BinaryTree *new = (BinaryTree *)malloc(sizeof(BinaryTree));
(*new) = NULL;
return new;
}
int insert_BinaryTree(BinaryTree *root, int data)
{
if (root != NULL)
{
Node *new = (Node *)malloc(sizeof(Node));
new->left = NULL;
new->right = NULL;
new->data = data;
Node *aux = (*root);
if ((*root) == NULL)
{
(*root) = new;
aux = (*root);
return 1;
}
while (aux->left != NULL || aux->right != NULL)
{
if (data < aux->data)
{
if (aux->left == NULL)
{
break;
}
else
{
aux = aux->left;
}
}
else if (data > aux->data)
{
if (aux->right == NULL)
{
break;
}
else
{
aux = aux->right;
}
}
else
{
printf("Data is already present in the binary tree.\n");
}
}
if (data < aux->data)
{
aux->left = new;
}
else if (data > aux->data)
{
aux->right = new;
}
else
{
free(new);
return 0;
}
return 1;
}
else
{
return 0;
}
}
void free_Node(Node *no)
{
if (no != NULL)
{
free_Node(no->left);
free_Node(no->right);
free(no);
}
}
void free_BinaryTree(BinaryTree *raiz)
{
if (raiz != NULL)
{
free_Node(*raiz);
free(raiz);
}
}
void print_pre_order_BinaryTree(BinaryTree *root)
{
if (root != NULL)
{
printf("%i\n", (*root)->data);
if ((*root)->left != NULL)
{
print_pre_order_BinaryTree(&((*root)->left));
}
if ((*root)->right != NULL)
{
print_pre_order_BinaryTree(&((*root)->right));
}
}
}
void print_in_order_BinaryTree(BinaryTree *root)
{
if (root != NULL)
{
if ((*root)->left != NULL)
{
print_in_order_BinaryTree(&((*root)->left));
}
printf("%i\n", (*root)->data);
if ((*root)->right != NULL)
{
print_in_order_BinaryTree(&((*root)->right));
}
}
}
void print_post_order_BinaryTree(BinaryTree *root)
{
if (root != NULL)
{
if ((*root)->left != NULL)
{
print_post_order_BinaryTree(&((*root)->left));
}
if ((*root)->right != NULL)
{
print_post_order_BinaryTree(&((*root)->right));
}
printf("%i\n", (*root)->data);
}
}
int local_subtree(BinaryTree *a, BinaryTree *b)
{
if (a == NULL || b == NULL || *a == NULL || *b == NULL)
{
return 0;
}
int igual_left;
int igual_right;
igual_left = is_subtree(&((*a)->left), &((*b)->left));
igual_right = is_subtree(&((*a)->right), &((*b)->right));
return (igual_left == igual_right) && ((*a)->data == (*b)->data);
}
int is_subtree(BinaryTree *a, BinaryTree *b)
{
if (a == NULL || b == NULL || *a == NULL || *b == NULL)
{
return 0;
}
int sub = 0;
sub = local_subtree(a, b) || is_subtree(&((*a)->right), b) || is_subtree(&((*a)->left), b);
return sub;
}
void print_BinaryTree_Stack_post_order(BinaryTree *root)
{
Stack *stack = create_Stack();
Node *aux = (*root);
Node *popped = (Node *)malloc(sizeof(Node));
while (aux != NULL)
{
push(stack, aux);
aux = aux->right;
}
// printf("Esquerda nulo.\n");
while (!is_empty(stack))
{
// printf("Poppando e printando...\n");
pop(stack, popped);
printf("%i\n", popped->data);
aux = popped->left;
while (aux != NULL)
{
printf("%i\n", aux->data);
aux = aux->left;
}
}
}
void print_BinaryTree_Stack_in_order(BinaryTree *root)
{
Stack *stack = create_Stack();
Node *aux = (*root);
Node *popped = (Node *)malloc(sizeof(Node));
while (aux != NULL)
{
push(stack, aux);
aux = aux->left;
}
// printf("Esquerda nulo.\n");
while (!is_empty(stack))
{
// printf("Poppando e printando...\n");
pop(stack, popped);
printf("%i\n", popped->data);
aux = popped->right;
while (aux != NULL)
{
printf("%i\n", aux->data);
aux = aux->right;
}
}
free_Stack(stack);
free(popped);
}
|
C
|
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
int main(void)
{
int data[10] = {0};
int fd;
int i;
int n;
fd = open("test2", O_RDONLY);
if (fd == -1)
{
perror("error!");
return (0);
}
n = read(fd, data, 5);
data[n] = 0;
printf("%s", data);
return (0);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "list_node.h"
//https://leetcode-cn.com/problems/partition-list/
struct ListNode* partition(struct ListNode* head, int x) {
struct ListNode *less_ptr = NULL;
struct ListNode *less_head = NULL;
struct ListNode *greater_ptr = NULL;
struct ListNode *geater_head = NULL;
struct ListNode *cur = head;
while(cur != NULL) {
if (cur->val < x) {
if (less_head == NULL) {
less_head = cur;
less_ptr = cur;
} else {
less_ptr->next = cur;
less_ptr = less_ptr->next;
}
} else {
if (geater_head == NULL) {
geater_head = cur;
greater_ptr = cur;
} else {
greater_ptr->next = cur;
greater_ptr = greater_ptr->next;
}
}
cur = cur->next;
}
if (less_ptr != NULL) {
less_ptr->next = geater_head;
}
if (greater_ptr != NULL) {
greater_ptr->next = NULL;
}
if (less_head != NULL){
return less_head;
}
return geater_head;
}
|
C
|
/*!
* \file display.h
* \brief Functions that work with LEDS(two displays)
* COPYRIGHT: College of electrical engineering, www.etfbl.net
* This software was written in accordance to the guidelines at https://github.com/knezicm/battleship-8051/blob/master/LICENSE
* VERSION: 1.0, PF 2-OCT-17
*/
#ifndef DISPLAY_H_
#define DISPLAY_H_
/*!
* \brief We use this enum to identify display that will be enabled
* There are two displays, left for setting ships and right for shooting enemy.
*/
const enum display {
DISPLAY_LEFT = 0,
DISPLAY_RIGHT
};
/*!
* \brief We use this enum to identify what color on display will be enabled
* There are two colors, red and green. The display also has a blue color but it is not used for the project.
*/
const enum diode {
DIODE_RED = 0,
DIODE_GREEN
};
/*!
* \brief This function is used to set some default settings for drawing on display.
*/
void initDisplay();
/*!
* \brief This function is used to show set ships on display.
*/
void showDisplay();
/**
* \brief This function return ship for position passed as argument
* \param position Is a position where need to show ship
* \return Ship that need to be displayed. if there is no ship nothing will be shown, function return 0xff.
*/
unsigned char returnShip(unsigned char position);
/**
* \brief This function return info is (x,y) position free and can we set ship at that position.
* "x" and "y" variable are global variable and used to save current position of cursor.
* \return 1 if we can set current ship at position, otherwise it return 0.
*/
unsigned char availablePosition();
/**
* \brief This function is used to display ship on right display that will be set on battlefield.
* On left display show current position of ship that will be set.
*/
void drawShip();
/**
* \brief This function is used to display current position of cursor when we want to shout enemy.
* It used global x and y variable.
*/
void drawCursor();
/**
* \brief This function is used to display info on right display with red or green color.
* When we call this function fourth and fifth row are bright in that color.
*/
void showInfo(unsigned char color);
/**
* \brief This function enable one diode on display, and save that state.
* \param d Left or right display
* \param di Red or green color of diodes
* \param y is row in matrix
* \param x is column in matrix
*/
void setDiodes(enum display d, enum diode di, unsigned char y, unsigned char x);
/**
* \brief This function enable diodes in one row for one display, and save that state.
* \param d Left or right display
* \param di Red or green color of diodes
* \param y is row in matrix
* \param row diodes in one row that need to be set
*/
void setDiodesRow(enum display d, enum diode di, unsigned char y,
unsigned char row);
/**
* \brief This function disable one diode in display, and save that state.
* \param d Left or right display
* \param di Red or green color of diodes
* \param y is row in matrix
* \param x is column in matrix
*/
void resetDiode(enum display d, enum diode di, unsigned char y,
unsigned char x);
/**
* \brief This function check is diode on (x,y) position enabled
* \param d Left or right display
* \param di Red or green color of diodes
* \param y is row in matrix
* \param x is column in matrix
* \return 1 if diode enabled, otherwise it return 0.
*/
unsigned char diodeOn(enum display d, enum diode di, unsigned char y,
unsigned char x);
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.