language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C
|
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "stack.h"
int main(int argc, char *argv[])
{
int ret = 0;
int i = 0;
int a[10];
SeqStack *stack = NULL;
stack = SeqStack_Create(10);
if (NULL == stack)
{
printf("func SeqStack_Create() err line:%d, file:%s\n", __LINE__, __FILE__);
goto End;
}
for (i = 0; i < 1; i++)
{
a[i] = i + 1;
SeqStack_Push(stack, a + i);
}
printf("Capacity: %d\n", SeqStack_Capacity(stack));
printf("Size:%d\n", SeqStack_Size(stack));
printf("Front:%d\n", *((int *)(SeqStack_Front(stack))));
while (SeqStack_Size(stack) > 0)
{
int num = *((int *)SeqStack_Pop(stack));
printf("num:%d\t", num);
}
puts("");
End:
SeqSatck_Destroy(stack);
system("pause");
return ret;
}
|
C
|
//冒泡排序
#include <stdio.h>
void swap(int* x, int* y){
int temp;
temp = *x;
*x = *y;
*y = temp;
}
void fun(int* arr, int size){
int bound;
for(bound = 0; bound < size; bound++){
for(int cur = size - 1; cur > bound; cur--){
if(arr[cur - 1] > arr[cur]){
swap(&arr[cur - 1], &arr[cur]);
}
}
}
}
int main(){
int arr[] = {2, 0, 1, 9};
int size = sizeof(arr) / sizeof(arr[0]);
fun(arr, size);
for(int i = 0; i < size; i++){
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "funciones.h"
void inicializar( eLibro book[], int cantidad)
{
int i;
for(i=0; i<cantidad; i++)
{
book[i].estado = 0;
}
}
void mostrarDocumento(eLibro lib)
{
printf("\n %3d %d %10s %d \n", lib.codigoAutor, lib.codigoLibro, lib.tituloLibro, lib.stock );
}
int buscarEspacioLibre(eLibro book[], int cantidad)
{
int i;
int indice = -1;// devuelve -1 si no hay mas espaciop libre
for(i=0; i<cantidad; i++)
{
if(book[i].estado == 0)
{
indice = i;// devolvera cualquier otro numero si encuentra un espacio libre
break;
}
}
return indice;
}
int buscarPorCodigo(eLibro book[], int cantidad, int codigo)
{
int i;
int indice = -1;// el dni no esta en la base de datos
for(i=0; i<cantidad; i++)
{
if(book[i].estado == 1 && book[i].codigoLibro == codigo)
{
indice = i;// se encontro el dni en la base de datos
break;
}
}
return indice;
}
|
C
|
//
// QuickSort.c
// AlgorithmForC
//
// Created by gjh on 2021/1/28.
//
#include "QuickSort.h"
// 912.排序数组 最快的排序:必须掌握 快速排序
void swap(int arr[], int a, int b) {
int tmp = arr[a];
arr[a] = arr[b];
arr[b] = tmp;
}
// 划分区域
int partition(int arr[], int leftBound, int rightBound) {
int pivot = rightBound; // 枢纽元
// 左边指针
int left = leftBound;
for (int i = leftBound; i <= rightBound; i++) {
if (arr[i] < arr[pivot]) {
if (left != i) swap(arr, i, left);
left++;
}
}
swap(arr, left, pivot);
return left;
}
void quickSort(int arr[], int leftBound, int rightBound) {
if (leftBound > rightBound) return;
int pivot = partition(arr, leftBound, rightBound);
// 递归
quickSort(arr, leftBound, pivot - 1);
quickSort(arr, pivot + 1, rightBound);
}
int* sortArray(int* nums, int numsSize){
quickSort(nums, 0, numsSize - 1);
return nums;
}
|
C
|
/* 2018/11/13
* version 1.0
* */
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h> // recv()
#include <unistd.h> // close()
#include <pthread.h> // POSIX thread
#include <signal.h> // signal()
#include <time.h> // time_t, struct tm
#include <getopt.h> // getopt()
#include "message.h"
#include "connection.h"
#include "config.h"
#include "error.h"
#include "structure.h"
void *ThreadRecv(void *threadArgs);
void *ThreadSend(void *threadArgs);
void sigintHandler(int sig_num);
struct ThreadArgs {
int clntSock;
};
int requestNo = 0; // keep track of number of requests
int debugFlag = 0;
int helpFlag = 0;
int lock = 1; // handle data race between 2 threads
int port = 0;
int tries = 0;
int count = 0;
pthread_t threadID[MAX_PENDING+2];
FILE *logFp;
void handleCommandArg(int argc, char **argv);
int main (int argc, char **argv) {
struct ThreadArgs *threadArgs;
int listenfd, connfd;
int port = 0;
// opening logs file for writing
if((logFp = fopen("logs", "a+")) == NULL) {
error(ERR_OPEN_LOGS);
} else {
time_t t = time(NULL);
struct tm tm = *localtime(&t);
fprintf(logFp, "%d-%d-%d %d:%d:%d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
fprintf(logFp, "------------------------------\n");
}
// ===============================
signal(SIGINT, sigintHandler); // handle Ctr+C
signal(SIGPIPE, SIG_IGN);
handleCommandArg(argc, argv); // handle command line argument
init(); // init all data structure
// for(int i = 0; i < MAX_PENDING - 1; i++)
// for(int j = 0; j < MAX_REQUEST; j++)
// printf("%d\n", requesterList[i].request[j].requestID);
port = port ? port : SERV_PORT;
listenfd = createTCPServerSocket(port);
// spawn a thread for sending job purpose
pthread_create(&threadID[count++], NULL, ThreadSend, NULL);
while(1) {
connfd = acceptTCPConnection(listenfd);
threadArgs = (struct ThreadArgs *)malloc(sizeof(struct ThreadArgs));
threadArgs -> clntSock = connfd;
pthread_create(&threadID[count++], NULL, ThreadRecv, (void *) threadArgs);
}
// closing logs file
if(fclose(logFp)) {
error(ERR_CLOSE_LOGS);
}
// ===============================
return 0;
}
void usage(FILE *fp, const char *path) {
const char *basename = strrchr(path, '/');
basename = basename ? basename + 1 : path;
fprintf(fp, "usage: %s [OPTION]\n", basename);
fprintf(fp, " -h\t"
"Print this help and exit.\n");
fprintf(fp, " -d\t"
"Ouput debug information to stdout.\n");
fprintf(fp, " -pPORT_NUMBER\t"
"Assign a port number. Default is 3000.\n");
}
void handleCommandArg(int argc, char **argv) {
int opt;
while ((opt = getopt(argc, argv, "hdp:")) != -1) {
switch (opt) {
case 'h':
helpFlag = 1;
break;
case 'd':
debugFlag = 1;
break;
case 'p': ;
char *ptr;
port = (int) strtol(optarg, &ptr, 10);
break;
case '?':
usage (stderr, argv[0]);
exit(1);
default:
break;
}
}
if(helpFlag) {
usage(stdout, argv[0]);
exit(0);
}
}
typedef enum TYPE_ {
RECV,
SEND
}TYPE; // differentiate send & recv message
void debug(Message msg, TYPE type) {
char s[15];
strcpy(s, commandStr[msg.command]);
int len = strlen(s)/sizeof(char);
if(type == RECV)
printf("SERVER <----%*s%*s----- Client: %u\n",
10+len/2,s,10-len/2,"",msg.clientID);
else if(type == SEND)
printf("SERVER -----%*s%*s----> Client: %u\n",
10+len/2,s,10-len/2,"",msg.clientID);
}
void writeToLog(Message msg, TYPE type) {
char s[15];
strcpy(s, commandStr[msg.command]);
int len = strlen(s)/sizeof(char);
if(type == RECV)
fprintf(logFp, "SERVER <----%*s%*s----- Client: %u\n",
10+len/2,s,10-len/2,"",msg.clientID);
else if(type == SEND)
fprintf(logFp, "SERVER -----%*s%*s----> Client: %u\n",
10+len/2,s,10-len/2,"",msg.clientID);
}
void sendMsg(int sockfd, Message msg) {
send(sockfd, (struct Message*)&msg, sizeof msg, 0);
writeToLog(msg, SEND);
if(debugFlag)
debug(msg, SEND);
}
void sigintHandler(int sig_num) {
Message res;
int clientID;
for(int i = 0; i < MAX_PENDING; i++) {
if(connectionList[i].clientID != 0) {
clientID = connectionList[i].clientID;
res = response(SHUTDOWN, clientID, 0, "");
send(connectionList[i].sockfd, (struct Message *)&res, sizeof(res), 0);
debug(res, SEND);
removeConnection(clientID);
}
}
// wait for all child thread terminate
for(int i = 0; i < MAX_PENDING + 2; i++)
pthread_join(threadID[i], NULL);
exit(0);
}
Connection conn = {0, 0};
Requester requester = {0, {0, ""}};
Worker worker = {0, 0};
Request request = {0, ""};
void handleHashRequest(int sockfd, Message msg) {
request.requestID = ++requestNo;
strcpy(request.hash, msg.other);
int clientID = msg.clientID;
if(clientID == 0) {
clientID = getNewClientID();
setConnection(&conn, clientID, sockfd);
addConnection(conn);
requester.clientID = clientID;
addRequester(requester);
}
Message res = response(ACCEPT, clientID, request.requestID, request.hash);
sendMsg(sockfd, res);
addRequestToRequester(clientID, request);
// printRequesterList();
splitJob(request);
}
void handleJoinRequest(int sockfd, Message msg) {
if(msg.clientID == 0) {
int clientID = getNewClientID();
setConnection(&conn, clientID, sockfd);
addConnection(conn);
Message res = response(ACCEPT, clientID, 0, "");
sendMsg(sockfd, res);
worker.clientID = clientID;
addWorker(worker);
}
}
void handleDNFRequest(int sockfd, Message msg) {
int clientID = getRequesterFromRequest(msg.requestID);
int clientSock = getSocketDesc(clientID);
char *hash = getHash(msg.other);
int package = getPackage(msg.other);
Message res = response(DONE_NOT_FOUND, clientID, msg.requestID, hash);
if(clientID != 0)
sendMsg(clientSock, res);
removeJob(msg.requestID, package);
}
void handleDFRequest(int sockfd, Message msg) {
lock = 0;
int clientID = getRequesterFromRequest(msg.requestID);
int clientSock = getSocketDesc(clientID);
Message res = response(DONE_FOUND, clientID, msg.requestID, msg.other);
sendMsg(clientSock, res);
// broadcast DONE_FOUND to all workers
int *worker = getWorkerFromRequest(msg.requestID);
for (int i = 0; i < 26; i++) {
if(worker[i] != 0) {
clientSock = getSocketDesc(worker[i]);
res = response(DONE_FOUND, worker[i], msg.requestID, "");
if(clientSock != sockfd) // not sending back to worker solved problem
sendMsg(clientSock, res);
}
}
removeAllJobs(msg.requestID);
lock = 1;
}
void handleQuitRequest(int sockfd, Message msg) {
int clientID = getClientIDFromSocket(sockfd);
recoverJob(clientID);
removeWorker(clientID);
removeConnection(clientID);
}
void handleStopRequest(int sockfd, Message msg) {
if(msg.clientID != 0) {
int clientID = getClientIDFromSocket(sockfd);
int *request = getRequestFromRequester(clientID);
int clientSock;
Message res;
for(int i = 0; i < MAX_REQUEST; i++)
if(request[i] != 0) {
lock = 0;
int *worker = getWorkerFromRequest(request[i]);
for (int j = 0; j < 26; j++) {
if(worker[j] != 0) {
clientSock = getSocketDesc(worker[i]);
res = response(STOP, worker[j], request[i], "");
sendMsg(clientSock, res);
}
}
removeAllJobs(request[i]);
lock = 1;
}
removeRequester(clientID);
removeConnection(clientID);
}
}
void *ThreadRecv(void *threadArgs) {
int sockfd = -1;
pthread_detach(pthread_self());
sockfd = ((struct ThreadArgs *) threadArgs) -> clntSock;
free(threadArgs);
Message msg;
while(recv(sockfd, (struct Message *)&msg, sizeof(msg), 0) > 0) {
writeToLog(msg, RECV);
if(debugFlag)
debug(msg, RECV);
switch(msg.command) {
case HASH:
handleHashRequest(sockfd, msg);
break;
case JOIN:
handleJoinRequest(sockfd, msg);
break;
case DONE_NOT_FOUND:
handleDNFRequest(sockfd, msg);
break;
case DONE_FOUND:
handleDFRequest(sockfd, msg);
break;
case QUIT:
handleQuitRequest(sockfd, msg);
break;
case STOP:
handleStopRequest(sockfd, msg);
break;
default:
break;
}
}
}
char *getMsgFromJob(Job job) {
char *hash = getHashFromRequest(job.requestID);
char tmp[3];
sprintf(tmp, "%d", job.package);
char *other = malloc(MSG_OTHER_LENGTH);
strcat(other, hash);
strcat(other, " ");
strcat(other, tmp);
return other;
}
void*ThreadSend(void *threadArgs) {
pthread_detach(pthread_self());
Message res;
char *other = malloc(MSG_OTHER_LENGTH);
int sockfd;
int jobPos;
int workerPos;
while(1) {
jobPos = getFirstJob();
if(jobPos != -1) { // check if we have a job
workerPos = getFirstEnableWorker();
if(workerPos != -1) { // check if we have a worker
memset(&other, 0, sizeof other);
other = getMsgFromJob(jobList[jobPos]);
sockfd = getSocketDesc(workerList[workerPos].clientID);
res = response(JOB, workerList[workerPos].clientID, jobList[jobPos].requestID, other);
if(lock == 1) {
sendMsg(sockfd, res);
assignJob(&workerList[workerPos], &jobList[jobPos]);
}
}
}
}
}
|
C
|
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/errno.h>
#include <linux/types.h>
#include <linux/vmalloc.h>
#include <linux/genhd.h>
#include <linux/blkdev.h>
#include <linux/hdreg.h>
MODULE_LICENSE("GPL");
static int major_num = 0;
static int l_block_size = 512;
static int sectors = 10000;
#define KERNEL_SECTOR_SIZE 512
static struct request_queue *Queue;
// Internal representation of the device
static struct my_device {
unsigned long size; // size of the device
spinlock_t lock; // array where the disk stores its data
u8 *data; // for mutual exclusion
struct gendisk *gd; // kernel representation of our device
} Device;
int getgeo(struct block_device * block_device, struct hd_geometry * geo) {
long size;
size = Device.size * (l_block_size / KERNEL_SECTOR_SIZE);
geo->cylinders = (size & ~0x3f) >> 6;
geo->heads = 4;
geo->sectors = 16;
geo->start = 0;
return 0;
}
int ioctl (struct inode *inode, struct file *filp,
unsigned int cmd, unsigned long arg)
{
long size;
struct hd_geometry geo;
printk(KERN_INFO "Inside ioctl\n");
printk(KERN_INFO "Cmd = %d, HDIO = %d \n", cmd, HDIO_GETGEO);
switch(cmd) {
case HDIO_GETGEO:
size = Device.size*(l_block_size/KERNEL_SECTOR_SIZE);
geo.cylinders = (size & ~0x3f) >> 6;
geo.heads = 4;
geo.sectors = 16;
geo.start = 0;
printk(KERN_INFO "Inside ioctl case\n");
if (copy_to_user((void *) arg, &geo, sizeof(geo)))
return -EFAULT;
return 0;
}
return -ENOTTY;
}
static struct block_device_operations ops = {
.owner = THIS_MODULE,
.getgeo = getgeo,
.ioctl = ioctl
};
// is really a just a memcopy with some checking
static void transfer(struct my_device *dev, sector_t sector,
unsigned long nsect, char *buffer, int write) {
unsigned long offset = sector * l_block_size;
unsigned long nbytes = nsect * l_block_size;
printk (KERN_INFO "Inside transfer\n");
printk (KERN_INFO "offset = %ld, nbytes = %ld, dev-> size = %ld\n", offset, nbytes, dev->size);
if ((offset + nbytes) > dev->size) {
printk (KERN_NOTICE "Beyond-end write (%ld %ld)\n", offset, nbytes);
return;
}
printk (KERN_INFO "write = %d\n", write);
if (write)
memcpy(dev->data + offset, buffer, nbytes);
else
memcpy(buffer, dev->data + offset, nbytes);
}
// Device.lock will be held on the entry to the request function
static void request(struct request_queue *q) {
struct request *req;
// For getting the first request in the queue is now elv_next_request (Can use blk_fetch_request)
// A NULL return means there are no more requests on the queue that are ready to process
// function does not actually remove the request from the queue; it just a properly adjusted view of the top request
req = blk_fetch_request(q);
printk("Request %s \n", req);
while (req != NULL) {
if (req->cmd_type != REQ_TYPE_FS) {
printk("Cehcking FS request \n");
printk (KERN_NOTICE "Skip non-CMD request\n");
// is called to finish processing of this request
__blk_end_request_all(req, -EIO);
continue;
}
transfer(&Device, blk_rq_pos(req), blk_rq_cur_sectors(req),
req->buffer, rq_data_dir(req));
if ( ! __blk_end_request_cur(req, 0) ) {
req = blk_fetch_request(q);
}
}
printk (KERN_INFO "Leaving request\n");
}
static __init Start(void) {
spin_lock_init(&Device.lock);
Device.size = sectors * l_block_size;
Device.data = vmalloc(Device.size);
if (Device.data == NULL)
return -ENOMEM;
// lock is used by the driver to serialize access to intenal resources is the best choice for controlling
// access to the request queue as well
Queue = blk_init_queue(request, &Device.lock);
if (Queue == NULL) {
vfree(Device.data);
return -ENOMEM;
}
blk_queue_logical_block_size(Queue, l_block_size);
// no device operations structure is passed to this function
// only task performed by this function "register_blkdev" are the assignment of a dynamic major number
// causing the block driver to show up in /proc/devices
major_num = register_blkdev(major_num, "yatendra");
if (major_num < 0) {
printk( KERN_WARNING "Unable to get major number");
vfree(Device.data);
return -ENOMEM;
}
// gendisk setup
// parameter to alloc_disk(n) is number of minor number that should be dedicated to this device
// n-1 will suported patitions
Device.gd = alloc_disk(2);
if (!Device.gd)
unregister_blkdev(major_num, "yatendra");
Device.gd->major = major_num;
Device.gd->first_minor = 0;
Device.gd->fops = &ops;
Device.gd->private_data = &Device;
strcpy(Device.gd->disk_name, "yatendra");
// tell how large the device is
set_capacity(Device.gd, sectors);
// a pointer to the queue must be stored in the gendisk structure
Device.gd->queue = Queue;
// add the disk to the system
// add_disk may well generates I/O to the device before it returns- the driver must be in state where it can handle
// requests before adding disks. The driver also should not fail initialization after it has successfully added a disk
add_disk(Device.gd);
return 0;
}
static void __exit Stop(void) {
del_gendisk(Device.gd);
put_disk(Device.gd);
unregister_blkdev(major_num, "yatendra");
blk_cleanup_queue(Queue);
vfree(Device.data);
}
module_init(Start);
module_exit(Stop);
|
C
|
#include <stdio.h>
void swap(char *a, char *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
char *str_rev(char *s)
{
char *begin = s;
char *end = s;
while (*end != '\0')
{
end++;
}
end--;
while (begin < end)
{
swap(begin, end);
begin++;
end--;
}
return s;
}
char *get_hex(int n, char *a)
{
int i = 0;
while(n > 0)
{
if(n % 16 > 9)
{
a[i] = n % 16 - 10 + 'A';
}
else if (n % 16 < 10)
{
a[i] = n % 16 + '0';
}
n /= 16;
i++;
}
a[i++] = 'x';
a[i++] = '0';
a[i] = '\0';
return str_rev(a);
}
int main ()
{
char a[20];
printf("%s\n", get_hex(123,a));
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* fillit.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: tburnouf <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/10/26 14:39:41 by tburnouf #+# #+# */
/* Updated: 2017/10/26 16:06:13 by tburnouf ### ########.fr */
/* */
/* ************************************************************************** */
#include "fillit.h"
/*
** array = map of the result
** t = struct of tetris
** i = size of the map
**
** Try to place a piece in the map
*/
int place_piece(char **array, t_tetris *t, int i)
{
while (!test_place_piece(array, t, i) && t->x < i && t->y < i)
incrementation(t, i);
if (t->x >= i)
{
t->x = 0;
t->y = 0;
if (t->c == 'A')
return (0);
t = t->prev;
incrementation(t, i);
delete_last_piece(array, i, t->c);
return (place_piece(array, t, i));
}
else if (t->next == NULL)
return (1);
return (place_piece(array, t->next, i));
}
/*
** array_pieces = map of the different coords of pieces
** c = character of the piece
** prev = adress of the previous piece
**
** Save the infos of a piece in a struct
*/
t_tetris *set_pieces(char **array_pieces, char c, t_tetris *prev)
{
t_tetris *tetris;
t_tetris *t_prev;
t_prev = prev;
if (array_pieces[0][0] != '0')
{
tetris = malloc(sizeof(t_tetris));
tetris->c = c;
tetris->x = 0;
tetris->y = 0;
tetris->points = find_points(array_pieces[0], 0, 0);
tetris->prev = t_prev;
tetris->next = set_pieces(++array_pieces, ++c, tetris);
}
else
tetris = NULL;
return (tetris);
}
/*
** a_result = map of the result
** t = struct of the tetris (piece info)
** size = width of the result
**
** Try to place a piece
*/
int test_place_piece(char **a_result, t_tetris *t, int size)
{
int i;
i = 0;
while (i < 4)
{
if (!test_point(a_result, t, i, size))
return (0);
i++;
}
i = 0;
while (i < 4)
{
if (!place_point(a_result, t, i, size))
return (0);
i++;
}
return (1);
}
/*
** a_result = map of the result
** index = width of the result
** c = character of the piece
**
** Delete the last piece in the map
*/
void delete_last_piece(char **a_result, int index, char c)
{
int i;
int j;
i = 0;
while (i < index)
{
j = 0;
while (j < index)
{
if (a_result[i][j] == c)
a_result[i][j] = '.';
j++;
}
i++;
}
}
/*
** array_pieces = array of the differents coords of the piece
** index = width of the result
**
** Main function of the solver
*/
void fillit(char **array_pieces, int index)
{
char **array_result;
t_tetris *tetris;
tetris = set_pieces(array_pieces, 'A', NULL);
array_result = initialize(index, index, '.');
while (!place_piece(array_pieces, tetris, index))
{
index++;
array_result = initialize(index, index, '.');
}
print_result(array_pieces, index);
free(array_result);
}
|
C
|
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include "disk.h"
#include "fs.h"
#define UNUSED(x) (void)(x)
#define FAT_EOC 0xFFFF
typedef struct __attribute__((__packed__)){
uint8_t signature[8];
uint16_t totalBlocks;
uint16_t rootDirBlockIndex;
uint16_t dataBlockStartIndex;
uint16_t numDataBlocks;
uint8_t numFATBlocks;
uint8_t padding[4079];
}superblock;
typedef uint16_t* FAT;
typedef struct __attribute__((__packed__)){
uint8_t filename[FS_FILENAME_LEN];
uint32_t fileSize;
uint16_t firstDataBlockIndex;
uint8_t padding[10];
}rootDirEntry;
typedef struct __attribute__((__packed__)) {
rootDirEntry rootDirEntries[FS_FILE_MAX_COUNT];
} rootDirectory;
typedef struct{
superblock superblock;
FAT FAT;
rootDirectory rootDir;
} ECS150FS;
typedef struct{
uint8_t filename[FS_FILENAME_LEN];
size_t offset;
} fileDescriptor;
fileDescriptor fileDescriptorTable[FS_OPEN_MAX_COUNT];
int numFiles;
int numOpenFiles;
ECS150FS* FS;
int fs_mount(const char *diskname)
{
if(diskname == NULL){
return -1;
}
if(block_disk_open(diskname) == -1){
return -1;
}
FS = malloc(sizeof(ECS150FS));
block_read(0, &FS->superblock);
char desiredSig[] = "ECS150FS";
const void *sig = (char*)FS->superblock.signature;
if(memcmp(desiredSig, sig, 8) != 0){
return -1;
}
FS->FAT = (uint16_t*)malloc(FS->superblock.numFATBlocks*BLOCK_SIZE);
for(int i = 0; i<FS->superblock.numFATBlocks; i++){
block_read(i + 1, FS->FAT + (BLOCK_SIZE/2) * i);
}
block_read(FS->superblock.rootDirBlockIndex, &FS->rootDir);
for(int i = 0; i<FS_OPEN_MAX_COUNT; i++){
fileDescriptorTable[i].filename[0] = '\0';
}
numFiles = 0;
numOpenFiles = 0;
return 0;
}
int fs_umount(void)
{
//Check if underlying virtual disk open
if(block_disk_count() == -1){
return -1;
}
if(FS == NULL || numOpenFiles != 0){
return -1;
}
block_write(0, &(FS->superblock));
for(int i = 0; i<FS->superblock.numFATBlocks; i++){
block_write(i + 1, FS->FAT + (BLOCK_SIZE/2) * i);
}
block_write(FS->superblock.numFATBlocks+1, &(FS->rootDir));
free(FS->FAT);
free(FS);
return block_disk_close();
}
int fs_info(void)
{
//Check if underlying virtual disk open
if(block_disk_count() == -1){
return -1;
}
printf("FS Info:\n");
printf("total_blk_count=%d\n", FS->superblock.totalBlocks);
printf("fat_blk_count=%d\n", FS->superblock.numFATBlocks);
printf("rdir_blk=%d\n", FS->superblock.rootDirBlockIndex);
printf("data_blk=%d\n", FS->superblock.dataBlockStartIndex);
printf("data_blk_count=%d\n", FS->superblock.numDataBlocks);
int fat_free = 0;
for(int i = 0; i<FS->superblock.numDataBlocks; i++){
if(FS->FAT[i] == 0){
fat_free++;
}
}
printf("fat_free_ratio=%d/%d\n", fat_free, FS->superblock.numDataBlocks);
int rdir_free = 0;
for(int i = 0; i<FS_FILE_MAX_COUNT; i++){
if((char)FS->rootDir.rootDirEntries[i].filename[0] == '\0'){
rdir_free++;
}
}
printf("rdir_free_ratio=%d/%d\n", rdir_free, FS_FILE_MAX_COUNT);
return 0;
}
int fs_create(const char *filename)
{
//Check error conditions
size_t filename_len = strlen(filename);
if(filename == NULL || filename[filename_len] != '\0' || filename_len > FS_FILENAME_LEN || numFiles > FS_FILE_MAX_COUNT){
return -1;
}
//Check if root directory contains max number of files
if(FS->rootDir.rootDirEntries[FS_FILE_MAX_COUNT-1].filename[0] != '\0'){
return -1;
}
//Check if file already exists
for(int i = 0; i<FS_FILE_MAX_COUNT; i++){
if(memcmp(FS->rootDir.rootDirEntries[i].filename, filename, filename_len) == 0){
return -1;
}
}
//Find a place in the root directory to add the file
int availableIndex = -1;
for(int i = 0; i<FS_FILE_MAX_COUNT; i++){
if(FS->rootDir.rootDirEntries[i].filename[0] == '\0'){
availableIndex = i;
break;
}
}
//Create a new empty file
rootDirEntry r = FS->rootDir.rootDirEntries[availableIndex];
for(size_t i = 0; i<filename_len; i++){
r.filename[i] = (uint8_t)filename[i];
}
r.fileSize = 0;
r.firstDataBlockIndex = FAT_EOC;
FS->rootDir.rootDirEntries[availableIndex] = r;
numFiles++;
return 0;
}
int fs_delete(const char *filename)
{
//Removing a file is the opposite procedure: the file’s entry must be emptied and all the data blocks containing the file’s contents must be freed in the FAT.
//Check error conditions
size_t filename_len = strlen(filename);
if(filename == NULL || filename[filename_len] != '\0' || filename_len > FS_FILENAME_LEN){
return -1;
}
int fileIndex = -1;
for(int i = 0; i<FS_FILE_MAX_COUNT; i++){
if(memcmp(FS->rootDir.rootDirEntries[i].filename, filename, filename_len) == 0){
fileIndex = i;
}
}
if (fileIndex == -1){
return -1;
}
//CHECK IF FILE IS OPEN
for(int i = 0; i<FS_OPEN_MAX_COUNT; i++){
if(memcmp(fileDescriptorTable[i].filename, filename, FS_FILENAME_LEN) == 0){
return -1;
}
}
//Free the file's entries in the FAT
size_t FAT_index = FS->rootDir.rootDirEntries[fileIndex].firstDataBlockIndex;
while(FAT_index != FAT_EOC){
size_t new_FAT_index = FS->FAT[FAT_index];
FS->FAT[FAT_index] = 0;
FAT_index = new_FAT_index;
}
//Free the root directory entry
FS->rootDir.rootDirEntries[fileIndex].filename[0] = '\0';
FS->rootDir.rootDirEntries[fileIndex].fileSize = 0;
FS->rootDir.rootDirEntries[fileIndex].firstDataBlockIndex = FAT_EOC;
numFiles--;
return 0;
}
int fs_ls(void)
{
//Check if underlying virtual disk open
if(block_disk_count() == -1){
return -1;
}
printf("FS Ls:\n");
for(int i = 0; i<FS_FILE_MAX_COUNT; i++){
rootDirEntry r = FS->rootDir.rootDirEntries[i];
if(r.filename[0] != '\0'){
printf("file: %s, size: %d, data_blk: %d\n", r.filename, r.fileSize, r.firstDataBlockIndex);
}
}
return 0;
}
int fs_open(const char *filename)
{
//Check error conditions
size_t filename_len = strlen(filename);
if(filename == NULL || filename[filename_len] != '\0' || filename_len > FS_FILENAME_LEN){
return -1;
}
int fileIndex = -1;
for(int i = 0; i<FS_FILE_MAX_COUNT; i++){
if(memcmp(FS->rootDir.rootDirEntries[i].filename, filename, filename_len) == 0){
fileIndex = i;
break;
}
}
if (fileIndex == -1){
return -1;
}
if(numOpenFiles >= FS_OPEN_MAX_COUNT){
return -1;
}
int fd = -1;
for(int i = 0; i<FS_OPEN_MAX_COUNT; i++){
if(fileDescriptorTable[i].filename[0] == '\0'){
for(size_t j = 0; j<filename_len; j++){
fileDescriptorTable[i].filename[j] = (uint8_t)filename[j];
}
fileDescriptorTable[i].offset = 0;
fd = i;
break;
}
}
numOpenFiles++;
return fd;
}
int fs_close(int fd)
{
if(fd >= FS_OPEN_MAX_COUNT || fd < 0){
return -1;
}
if(fileDescriptorTable[fd].filename[0] == '\0'){
return -1;
}
fileDescriptorTable[fd].filename[0] = '\0';
fileDescriptorTable[fd].offset = 0;
numOpenFiles--;
return 0;
}
int fs_stat(int fd)
{
if(fd >= FS_OPEN_MAX_COUNT || fd < 0){
return -1;
}
if(fileDescriptorTable[fd].filename[0] == '\0'){
return -1;
}
uint8_t filename[FS_FILENAME_LEN];
memcpy(filename, fileDescriptorTable[fd].filename, sizeof(fileDescriptorTable[fd].filename));
for(int i = 0; i<FS_FILE_MAX_COUNT; i++){
if(memcmp(FS->rootDir.rootDirEntries[i].filename, filename, sizeof(filename)) == 0){
return FS->rootDir.rootDirEntries[i].fileSize;
}
}
return -1;
}
int fs_lseek(int fd, size_t offset)
{
if(fd >= FS_OPEN_MAX_COUNT || fd < 0){
return -1;
}
if(fileDescriptorTable[fd].filename[0] == '\0'){
return -1;
}
if(offset > (size_t)fs_stat(fd)){
return -1;
}
fileDescriptorTable[fd].offset = offset;
return 0;
}
//THIS RETURNS THE FIRST AVAIALBLE FAT INDEX!!!!!
uint16_t allocateNewFATBlock(int rootDirEntryIndex){
uint16_t availableIndex = 0;
if(FS->rootDir.rootDirEntries[rootDirEntryIndex].firstDataBlockIndex == FAT_EOC){
for(uint16_t i = 0; i< FS_FILE_MAX_COUNT; i++){
if(FS->FAT[i] == 0){
FS->FAT[i] = FAT_EOC;
availableIndex = i;
FS->rootDir.rootDirEntries[rootDirEntryIndex].firstDataBlockIndex = i;
return availableIndex;
}
}
}
else{
for(uint16_t i = 0; i< FS_FILE_MAX_COUNT; i++){
if(FS->FAT[i] == 0){
availableIndex = i;
break;
}
}
if(availableIndex == 0){
return FAT_EOC;
}
uint16_t curFATBlockIndex = FS->rootDir.rootDirEntries[rootDirEntryIndex].firstDataBlockIndex;
while(FS->FAT[curFATBlockIndex] != FAT_EOC){
curFATBlockIndex = FS->FAT[curFATBlockIndex];
}
FS->FAT[curFATBlockIndex] = availableIndex;
FS->FAT[availableIndex] = FAT_EOC;
//FS->superblock.numDataBlocks++;
return availableIndex;
}
return FAT_EOC;
}
static uint16_t findCurrentFATBlockIndex(rootDirEntry r, size_t offset){
uint16_t curFATBlockIndex = r.firstDataBlockIndex;
while(offset > BLOCK_SIZE && curFATBlockIndex != FAT_EOC){
curFATBlockIndex = FS->FAT[curFATBlockIndex];
offset = offset - BLOCK_SIZE;
}
return curFATBlockIndex;
}
static int bounceBufferRead(void* buf, uint16_t curBlockIndex, size_t blockOffset, size_t numBytesToRead){
void* bounceBuffer = malloc(BLOCK_SIZE);
if(block_read((size_t)curBlockIndex, bounceBuffer) == 0){
memcpy(buf, bounceBuffer + blockOffset, numBytesToRead);
free(bounceBuffer);
return 0;
}
free(bounceBuffer);
return -1;
}
static int bounceBufferWrite(void* buf, uint16_t curBlockIndex, size_t blockOffset, size_t numBytesToWrite){
void* bounceBuffer = malloc(BLOCK_SIZE);
if(block_read((size_t)curBlockIndex, bounceBuffer) == 0){
memcpy(bounceBuffer + blockOffset, buf, numBytesToWrite);
if(block_write((size_t)curBlockIndex, bounceBuffer) == 0){
free(bounceBuffer);
return 0;
}
}
free(bounceBuffer);
return -1;
}
int fs_write(int fd, void *buf, size_t count)
{
if(fd >= FS_OPEN_MAX_COUNT || fd < 0){
return -1;
}
if(fileDescriptorTable[fd].filename[0] == '\0'){
return -1;
}
int rootDirIndex = -1;
for(int i = 0; i<FS_FILE_MAX_COUNT; i++){
if(memcmp(fileDescriptorTable[fd].filename, FS->rootDir.rootDirEntries[i].filename, FS_FILENAME_LEN) == 0){
rootDirIndex = i;
break;
}
}
if(fileDescriptorTable[fd].offset + count >= BLOCK_SIZE*FS->superblock.numDataBlocks){
return -1;
}
size_t blockOffset = fileDescriptorTable[fd].offset%BLOCK_SIZE;
size_t bytesLeftToWrite = count;
uint32_t newBlocksAllocated = 0;
uint16_t curFATBlockIndex = findCurrentFATBlockIndex(FS->rootDir.rootDirEntries[rootDirIndex], fileDescriptorTable[fd].offset);
if(curFATBlockIndex == FAT_EOC){
//Allocate space. If we were unable to allocate a new block, return.
curFATBlockIndex = allocateNewFATBlock(rootDirIndex);
if(curFATBlockIndex == FAT_EOC){
fileDescriptorTable[fd].offset += count - bytesLeftToWrite;
return count - bytesLeftToWrite;
}
//If allocated, add to new blocks allocated
newBlocksAllocated++;
}
uint16_t curBlockIndex = curFATBlockIndex + FS->superblock.dataBlockStartIndex;
while(bytesLeftToWrite > BLOCK_SIZE){
size_t distanceToBlockEnd = BLOCK_SIZE - blockOffset;
if(distanceToBlockEnd < BLOCK_SIZE){
void* fragmentToWrite = malloc(distanceToBlockEnd);
memcpy(fragmentToWrite, buf, distanceToBlockEnd);
if(bounceBufferWrite(fragmentToWrite, curBlockIndex, blockOffset, distanceToBlockEnd) != 0){
return -1;
}
else{
buf = buf + distanceToBlockEnd;
bytesLeftToWrite = bytesLeftToWrite - distanceToBlockEnd;
}
}
else{
block_write(curBlockIndex, buf);
buf = buf + BLOCK_SIZE;
bytesLeftToWrite = bytesLeftToWrite - BLOCK_SIZE;
}
blockOffset = 0;
curFATBlockIndex = FS->FAT[curFATBlockIndex];
if(curFATBlockIndex == FAT_EOC){
//Allocate space
curFATBlockIndex = allocateNewFATBlock(rootDirIndex);
//If allocation unsuccessful, return
if(curFATBlockIndex == FAT_EOC){
fileDescriptorTable[fd].offset += count - bytesLeftToWrite;
return count - bytesLeftToWrite;
}
//increment new blocks allocated
newBlocksAllocated++;
}
curBlockIndex = curFATBlockIndex + FS->superblock.dataBlockStartIndex;
}
if(bytesLeftToWrite == BLOCK_SIZE){
block_write(curBlockIndex, buf);
//FS->rootDir.rootDirEntries[rootDirIndex].fileSize+=(newBlocksAllocated*BLOCK_SIZE);
bytesLeftToWrite-=BLOCK_SIZE;
}
else if(bytesLeftToWrite != 0 && bytesLeftToWrite < BLOCK_SIZE){
if(bounceBufferWrite(buf, curBlockIndex, blockOffset, bytesLeftToWrite) != 0){
return -1;
}
bytesLeftToWrite=0;
}
fileDescriptorTable[fd].offset+=(count-bytesLeftToWrite);
if(FS->rootDir.rootDirEntries[rootDirIndex].fileSize <= fileDescriptorTable[fd].offset){
FS->rootDir.rootDirEntries[rootDirIndex].fileSize += (count - bytesLeftToWrite);
}
return count - bytesLeftToWrite;
}
int fs_read(int fd, void *buf, size_t count)
{
if(fd >= FS_OPEN_MAX_COUNT || fd < 0){
return -1;
}
if(fileDescriptorTable[fd].filename[0] == '\0'){
return -1;
}
rootDirEntry r = FS->rootDir.rootDirEntries[0];
for(int i = 0; i<FS_FILE_MAX_COUNT; i++){
if(memcmp(fileDescriptorTable[fd].filename, FS->rootDir.rootDirEntries[i].filename, FS_FILENAME_LEN) == 0){
r = FS->rootDir.rootDirEntries[i];
break;
}
}
if(count + fileDescriptorTable[fd].offset > r.fileSize){
return -1;
}
uint16_t curFATBlockIndex = findCurrentFATBlockIndex(r, fileDescriptorTable[fd].offset);
uint16_t curBlockIndex = curFATBlockIndex + FS->superblock.dataBlockStartIndex;
size_t blockOffset = fileDescriptorTable[fd].offset%(size_t)BLOCK_SIZE;
size_t bytesLeftToRead = count;
while(bytesLeftToRead > BLOCK_SIZE){
size_t distanceToBlockEnd = BLOCK_SIZE - blockOffset;
if(distanceToBlockEnd < BLOCK_SIZE){
void* fragmentToRead = malloc(distanceToBlockEnd);
if(bounceBufferRead(fragmentToRead, curBlockIndex, blockOffset, distanceToBlockEnd) != 0){
return -1;
}
else{
memcpy(buf, fragmentToRead, distanceToBlockEnd);
buf = buf + distanceToBlockEnd;
bytesLeftToRead = bytesLeftToRead - distanceToBlockEnd;
}
}
else{
block_read(curBlockIndex, buf);
buf = buf + BLOCK_SIZE;
bytesLeftToRead = bytesLeftToRead - BLOCK_SIZE;
}
blockOffset = 0;
curFATBlockIndex = FS->FAT[curFATBlockIndex];
if(curBlockIndex == FAT_EOC){
fileDescriptorTable[fd].offset += (count - bytesLeftToRead);
return count - bytesLeftToRead;
}
curBlockIndex = curFATBlockIndex + FS->superblock.dataBlockStartIndex;
}
if(bytesLeftToRead == BLOCK_SIZE){
block_read(curBlockIndex, buf);
bytesLeftToRead-=BLOCK_SIZE;
}
else if(bytesLeftToRead < BLOCK_SIZE && bytesLeftToRead != 0){
if(bounceBufferRead(buf, curBlockIndex, blockOffset, bytesLeftToRead) != 0){
return -1;
}
bytesLeftToRead = 0;
}
fileDescriptorTable[fd].offset+= (count - bytesLeftToRead);
return count - bytesLeftToRead;
}
|
C
|
/******************************************************************************
*
* FILE NAME : new_user.c
*
* DESCRIPTION : it include funtion that does the pocessing for new client
*
* DATE NAME REFERENCE REASON
* 23/04/18 GR_TH5_C_1 Multi Party Conference Chat Nalanda Project
*
* Copyright 2018, Aricent Tech. (Holdings) Ltd.
*
*******************************************************************************/
/******************************************************************************
* ALL NECESSARY COMMON HEADERS, MACROS AND FUNCTIONS FOR CLIENT PROGRAM
*******************************************************************************/
#include <client_util.h>
#include <common_crypto.h>
/******************************************************************************
* FUNCTION NAME : new_user_processing
*
* DESCRIPTION : This function is for new user registration that
* calls the other following functions :
* 1. get_login_details
* 2. send_to_server
* 3. recv_from_server
* 4. existing_user_processing
*
* RETURNS : SUCCESS or FAILURE
*
*******************************************************************************/
int new_user_processing(
int socket_fd, /* for socket fd */
char *send_buf, /* send buffer that stores login details of Client */
char *recv_buf) /* recv buffer that stores message sent by Server */
{
log_client_report(NORMAL, "Entering : New_User_Processing", __FILE__, __LINE__);
int status = 0;
status = get_login_details(send_buf); /* calling the get_login_detail function
to get login and password from Client */
if (status == SUCCESS) //Validating the get_login_details function
{
encrypt(send_buf); //encrypting userid pass before sending
status = send_to_server(socket_fd, send_buf); /* Calling the send_to_server function
to send login and password to Server */
if (status == SUCCESS) //Validating the send_to_server function
{
printf ("\n\tLogin details send to Server Successfully\n\n");
status = recv_from_server(socket_fd, recv_buf); /* Calling the recv_from_server function
to receive the message from Server */
if (status == SUCCESS) //Validating the send_to_server function
{
if (strcmp(recv_buf, "User Already Exists") == 0)
{
printf ("\n\tMsg from server = %s\n\n", recv_buf); //printing the message sent by Server
exit(EXIT_FAILURE);
}
else
{
printf ("\n\tMsg from server = %s\n\n", recv_buf); //printing the message sent by Server
memset(send_buf, '\0', strlen(send_buf)); //flushing the send_buf for reuse
memset(recv_buf, '\0', strlen(recv_buf));
status = existing_user_processing(socket_fd, send_buf, recv_buf); /* Calling the existing_user_processing
function to get the login details again
to send message in conference chat room */
if (status == FAILURE) //Validating the send_to_server function
{
printf ("\n\tError in calling Existing_User_Processing function......\n\n"); //printing the error message
return FAILURE;
}
}
memset(recv_buf, '\0', strlen(recv_buf)); //flushing the recv_buf for reuse
}
else
{
log_client_report(ERROR, "ERROR : Error receiving Message", __FILE__, __LINE__); //writing the error message to output log file
printf ("\n\tError in Receiving Message from Server....\n\n"); //printing the error message
return FAILURE;
}
}
else
{
log_client_report(ERROR, "ERROR : Error in Sending Details", __FILE__, __LINE__); //writing the error message to output log file
printf ("\n\tError in sending details to Server\n\n"); //printing the error message
return FAILURE;
}
}
else
{
log_client_report(ERROR, "ERROR : Error in getting Details", __FILE__, __LINE__); //writing the error message to output log file
printf ("\n\tError in getting Login Details.........\n\n"); //printing the error message
return FAILURE;
}
log_client_report(NORMAL, "Exiting : New_User_Processing", __FILE__, __LINE__); //writing to the output log file
return SUCCESS; //returning SUCCESS status to calling function
}
|
C
|
#include "pctl.h"
int main(int argc, char *argv[])
{
int i,pid_ls,pid_ps,status;
char *args_ls[]={"/bin/ls","-a",NULL};
char *args_ps[]={"/bin/ps","-a",NULL};
signal(SIGINT,(sighandler_t)sigcat);
pid_ls=fork();
if(pid_ls<0){
printf("Create Process fail!\n");
exit(EXIT_FAILURE);
}
if(pid_ls==0){
printf("I am Child process:ls %d\nMy father is %d\n",getpid(),getppid());
pause();
printf("%d child will Running:\n",getpid());
for(i=0;args_ls[i]!=NULL;i++)
printf("%s ",args_ls[i]);
puts("");
status=execve(args_ls[0],args_ls,NULL);
}
else{
printf("I am Parent process %d\n",getpid());
pid_ps=fork();
if(pid_ps==0){
printf("I am Child process:ps %d\nMy father is %d\n",getpid(),getppid());
pause();
printf("%d child will Running:\n",getpid());
for(i=0;args_ps[i]!=NULL;i++)
printf("%s ",args_ps[i]);
puts("");
status=execve(args_ps[0],args_ps,NULL);
}else{
usleep(1000);
kill(pid_ps,SIGINT);
waitpid(pid_ps,&status,0);
printf("Child to process ps %d is done. status:%d\n",pid_ps,status);
kill(pid_ls,SIGINT);
waitpid(pid_ls,&status,0);
printf("Child to process ls %d is done. status:%d\n",pid_ls,status);
printf("Parent process exit.\n");
}
}
return EXIT_SUCCESS;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a;
printf("Input the number: ");
scanf("%d",&a);
printf("Your number can be from ");
if(a<2) printf("binary number system or ");
if(a<8) printf("octal number system or ");
if(a<10) printf("decimal number system\n");
getchar(); getchar(); return 0;
}
|
C
|
#include<stdio.h>
int main()
{
int C,F;
scanf("%d",&F);
C = 5*(F-32)/9;
printf("Celsius = %d",C);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define maxLength 100000
typedef struct node node;
typedef struct hashTable hashTable;
typedef int (*HashFunction)(char*, int);
struct node
{
char key[maxLength];
int value;
struct node *next;
};
struct hashTable
{
int size;
node **table;
HashFunction hashFunc;
};
hashTable *CreateTable(int size, HashFunction HashFunc)
{
hashTable *newTable;
newTable = (hashTable*)malloc(sizeof(node));
if (newTable == NULL)
{
printf("Memory is not allocated");
return NULL;
}
newTable->table = (node*)malloc(sizeof(node) * size);
if (newTable->table == NULL)
{
printf("Memory is not allocated");
return NULL;
}
int i;
for(i = 0; i < size; i++)
{
newTable->table[i] = NULL;
}
newTable->size = size;
newTable->hashFunc = HashFunc;
return newTable;
}
void deleteTable(hashTable *HashTable)
{
int i = 0;
for(i; i < HashTable->size; i++)
{
deleteCell(&(HashTable->table[i]));
}
free(HashTable);
}
void deleteCell(node **head)
{
node *tmp;
while ((*head) != NULL)
{
tmp = (*head);
(*head) = (*head)->next;
free(tmp);
}
}
node *search(hashTable *HashTable, char *key)
{
int number = HashTable->hashFunc(key, HashTable->size);
node *tmp = HashTable->table[number];
while(tmp != NULL)
{
if(strcmp(key, tmp->key) == 0)
{
return tmp;
}
tmp = tmp->next;
}
return tmp;
}
void set (hashTable *HashTable, char *key, int value)
{
node *tmp = search(HashTable, key);
if (tmp != NULL)
{
tmp->value = value;
}
else
{
int number = HashTable->hashFunc(key, HashTable->size);
tmp = (node*)malloc(sizeof(node));
if (tmp == NULL)
{
printf("Memory is not allocated");
return;
}
tmp->value = value;
strcpy(tmp->key, key);
tmp->next = HashTable->table[number];
HashTable->table[number] = tmp;
}
}
int get(hashTable *HashTable, char *key)
{
node *tmp = search(HashTable, key);
if (tmp)
{
return tmp->value;
}
else
{
return NULL;
}
}
int del(node **head, char *key)
{
if ((*head) != NULL)
{
if (strcmp((*head)->key, key) == 0)
{
node *tmp = (*head);
if ((*head)->next != NULL)
{
(*head) = (*head)->next;
}
else
{
(*head) = NULL;
}
free(tmp);
return 1;
}
else
{
node *tmp1, *tmp2;
tmp1 = (*head);
tmp2 = (*head)->next;
while (tmp2 != NULL)
{
if (strcmp(tmp2->key, key) == 0)
{
tmp1->next = tmp2->next;
free(tmp2);
return 1;
}
tmp1 = tmp1->next;
tmp2 = tmp1->next;
}
}
}
return 0;
}
void removeNode(hashTable *Hashtable, char *key)
{
int number = Hashtable->hashFunc(key, Hashtable->size);
if (!del(&(Hashtable->table[number]), key))
{
printf("This string is not in the table\n");
}
}
int Hash1(char *key, int sizeOfTable)
{
return 5;
}
int Hash2(char *key, int sizeOfTable)
{
int l = strlen(key);
int i;
int hash = 0;
for (i = 0; i < l; i++)
{
hash = hash + (int)key[i];
}
return hash % sizeOfTable;
}
int Hash3(char *key, int sizeOfTable)
{
int i = 0;
int p = 53;
long long hash = 0;
while(key[i]!='\0')
{
hash = (hash * p + key[i++]) % sizeOfTable;
}
return hash;
}
void printTable(hashTable *Table)
{
int i = 0;
for(i; i < Table->size; i++)
{
node *tmp = Table->table[i];
p(&tmp, i);
}
}
void p(node **head, int i)
{
printf("Elements of cell %d:\n\n", i);
node *tmp = (*head);
while (tmp != NULL)
{
printf("%s\n", tmp->key);
tmp = tmp->next;
}
printf("\n");
}
void fillTable(hashTable *HashTable, FILE *fp)
{
if(fp == NULL)
{
printf("Cannot open file");
return;
}
int i = 0;
int data;
char str[maxLength];
while(fgets(str, sizeof(str), fp))
{
data = strlen(str);
str[strlen(str)-1] = '\0';
set(HashTable, str, data);
}
fclose(fp);
}
void statistics(hashTable *HashTable)
{
int filled = 0;
int sum = 0;
int min = maxLength + 1;
int max = -1;
int num = 0;
int i = 0;
for (i; i < HashTable->size; i++)
{
if (HashTable->table[i] != NULL)
{
filled += 1;
node *tmp = HashTable->table[i];
while (tmp != NULL)
{
num += 1;
sum += 1;
tmp = tmp->next;
}
if (num < min)
{
min = num;
}
if (num > max)
{
max = num;
}
num = 0;
}
}
double avg = (double)sum / (double)filled;
printf("The number of non-empty cells: %d\n", filled);
printf("The number of elements: %d\n", sum);
printf("The average length of chain: %f\n", avg);
if(min != maxLength + 1)
{
printf("The minimum length of the non-empty chain: %d\n", min);
}
if(max != -1)
{
printf("The maximum length of the chain: %d\n", max);
}
}
|
C
|
#include <stdio.h>
int search(int key, int a[], int length){
int i;
int ret = -1;
for(i=0; i<length; i++){
if(a[i]==key){
ret = i;
break;
}
}
return ret;
}
int main()
{
int a[] = {1,3,4,5,12,14,13,49};
int x;
scanf("%d",&x);
int ret = search(x, a, sizeof(a)/sizeof(a[0]));
if(ret == -1){
printf("没有找到\n");
}
else{
printf("%d在数组a中的第%d个\n", x, ret+1);
}
return 0;
}
|
C
|
#include<stdio.h>
int main()
{
int a,b;
printf("Enter the value of A and B");
scanf("%d %d ",&a,&b);
switch(a<b)
{
case 0:
printf("%d is greater number ",a);
case 1:
printf("%d is is greater number ",b);
// default :
// printf("Both are equal");
}
return 0;
}
|
C
|
#include<stdio.h>
int main(void){
char str[256];
int i;
printf("文字列を入力してください:");
scanf("%s",str);
for(i=0;str[i]>'\0';i++){
printf("%d番目の文字:%c(文字コード:%x)\n",i,str[i],str[i]);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <string.h>
int main(void)
{
int i, m, n;
char name[10][10];
int out = 0, count = 0;
printf("please input m and n : ");
scanf("%d%d", &m, &n);
getchar();
for (i = 0; i < m; i++)
{
printf("please input %d name : ", i + 1);
fgets(name[i], sizeof(name[i]), stdin);
if (name[i][strlen(name[i]) - 1] == '\n')
name[i][strlen(name[i]) - 1] = '\0';
}
for (i = 0; i < m; i++)
{
printf("%s ", name[i]);
}
printf("\n");
while (out < m)
{
for (i = 0; i < m; i++)
{
if (name[i][0] != '\0')
{
count++;
}
if (count == n)
{
printf("%s ", name[i]);
name[i][0] = '\0';
count = 0;
out++;
}
}
}
printf("\n");
return 0;
}
|
C
|
#include<stdio.h>
long int stack[30],fac=1;
int top=-1;
void push(int);
int pop();
main()
{
int num;
printf("enter the number:");
scanf("%d",&num);
while(num!=0)
{
push(num);
num--;
}
while(top!=1)
{
fac=fac*pop();
top--;
}
printf("the factorial of the number is %ld");
}
void push(int item)
{
top++;
stack[top]=item;
}
int pop()
{
return stack[top];
}
}
|
C
|
#include<stdio.h>
/*
Este programa valida si el nmero a es mayor al nmero b.
*/
int main (){
int a, b;
a = 3;
b = 8;
if (a > b) {
printf("\ta (%d) es mayor a b (%d).\n",a,b);
}
else{
printf ("\tb (%d)es mayor a la variable a (%d).\n",b,a);
}
printf("\t\vEl programa sigue su flujo.\n");
return 0;
}
|
C
|
#include <stddef.h>
#include <stdio.h>
#include "cutest/CuTest.h"
#include "utils/clargs.h"
struct __fixture_parse
{
int32_t argc;
const char *argv[8];
int32_t has_error;
char expected_name[8];
int32_t expected_score;
int32_t expected_flag;
};
void test_clargs_parse(CuTest *tc)
{
struct clargs_parser *p = clargs_create_parser();
char arg_name[8] = {0};
int32_t arg_score = 0;
int32_t arg_flag = 0;
clargs_add_argument(p, "name", NULL, CLARGS_TYPE_STRING, 0, (void *)8, arg_name);
clargs_add_argument(p, "score", NULL, CLARGS_TYPE_INT, 0, NULL, &arg_score);
clargs_add_argument(p, "flag", NULL, CLARGS_TYPE_BOOL, 1, NULL, &arg_flag);
char error[CLARGS_ERROR_SIZE] = {0};
char failed = 0;
const struct __fixture_parse test_cases[] = {
{5, {"--name", "foo", "--score", "32", "--flag", NULL}, 0, "foo", 32, 1},
{6, {"--name", "foo", "--score", "16", "--flag", "n", NULL}, 0, "foo", 16, 0},
{4, {"--score", "16", "--flag", "n", NULL}, 0, "", 16, 0},
{4, {"--flag", "1", "--score", "16", NULL}, 0, "", 16, 1},
{4, {"--flag", "1", "--score", "x", NULL}, 1, "", 0, 0},
{3, {"--flag", "1", "--score", NULL}, 1, "", 0, 0},
{2, {"--score", "16", NULL}, 1, "", 16, 0},
};
size_t fixtures_count = sizeof(test_cases) / sizeof(struct __fixture_parse);
char trace_msg[32] = {0};
size_t i;
for (i = 0; i < fixtures_count; i++)
{
snprintf(trace_msg, sizeof(trace_msg), "test case #%zu", i);
failed = clargs_parse(p, test_cases[i].argc, test_cases[i].argv, error);
CuAssertIntEquals_Msg(tc, trace_msg, test_cases[i].has_error, failed);
if (!failed)
{
CuAssertStrEquals_Msg(tc, trace_msg, test_cases[i].expected_name, arg_name);
CuAssertIntEquals_Msg(tc, trace_msg, test_cases[i].expected_score, arg_score);
CuAssertIntEquals_Msg(tc, trace_msg, test_cases[i].expected_flag, arg_flag);
}
// Properly reset the arguments
strcpy(arg_name, "");
arg_score = 0;
arg_flag = 0;
strcpy(error, "");
}
}
void test_clargs_add_argument(CuTest *tc)
{
struct clargs_parser *p = clargs_create_parser();
int32_t err = 0;
int32_t dummy = 0;
err = clargs_add_argument(p, "", NULL, CLARGS_TYPE_BOOL, 0, NULL, &dummy);
CuAssertIntEquals_Msg(tc, "empty name", CLARGS_ERR_NAME_REQUIRED, err);
err = clargs_add_argument(p, NULL, NULL, CLARGS_TYPE_BOOL, 0, NULL, &dummy);
CuAssertIntEquals_Msg(tc, "null name", CLARGS_ERR_NAME_REQUIRED, err);
err = clargs_add_argument(p, "foo", NULL, CLARGS_TYPE_INT, 0, NULL, &dummy);
CuAssertIntEquals_Msg(tc, "correct addition", 0, err);
}
struct __fixture_parse_numeric_like
{
char raw[24];
int32_t has_error;
int32_t expected;
};
void test_clargs_parse_int(CuTest *tc)
{
struct __fixture_parse_numeric_like test_cases[] = {
{"16", 0, 16},
{"-10", 0, -10},
{"+10", 0, 10},
{"f", 1, 0},
{" 10 ", 1, 10},
{"10.", 1, 0},
{"John", 1, 0},
{"9999999999999999999", 1, 0}, // out of range
};
int32_t n = sizeof(test_cases) / sizeof(struct __fixture_parse_numeric_like);
char trace_msg[32] = {0};
int32_t i;
for (i = 0; i < n; i++)
{
snprintf(trace_msg, sizeof(trace_msg), "test case #%d", i);
int32_t has_error = 0;
char error[CLARGS_ERROR_SIZE] = {0};
int32_t actual = clargs_parse_int(test_cases[i].raw, NULL, &has_error, error);
CuAssertIntEquals_Msg(tc, trace_msg, test_cases[i].has_error, has_error);
if (!test_cases[i].has_error)
{
CuAssertIntEquals_Msg(tc, trace_msg, test_cases[i].expected, actual);
}
}
}
void test_clargs_parse_bool(CuTest *tc)
{
struct __fixture_parse_numeric_like test_cases[] = {
{"true", 0, 1},
{"True", 0, 1},
{"t", 0, 1},
{"T", 0, 1},
{"", 0, 1},
{"yes", 0, 1},
{"y", 0, 1},
{"1", 0, 1},
{"false", 0, 0},
{"fALSE", 0, 0},
{"False", 0, 0},
{"f", 0, 0},
{"no", 0, 0},
{"n", 0, 0},
{"0", 0, 0},
{" false ", 1, 0},
{" true ", 1, 0},
};
int32_t n = sizeof(test_cases) / sizeof(struct __fixture_parse_numeric_like);
char trace_msg[32] = {0};
int32_t i;
for (i = 0; i < n; i++)
{
snprintf(trace_msg, sizeof(trace_msg), "test case #%d", i);
int32_t has_error = 0;
char error[CLARGS_ERROR_SIZE] = {0};
int32_t actual = clargs_parse_bool(test_cases[i].raw, NULL, &has_error, error);
CuAssertIntEquals_Msg(tc, trace_msg, test_cases[i].has_error, has_error);
if (!test_cases[i].has_error)
{
CuAssertIntEquals_Msg(tc, trace_msg, test_cases[i].expected, actual);
}
}
}
void test_clargs_parse_long(CuTest *tc)
{
struct __fixture_parse_numeric_like test_cases[] = {
{"16", 0, 16},
{"-10", 0, -10},
{"+10", 0, 10},
{"f", 1, 0},
{" 10 ", 1, 10},
{"10.", 1, 0},
{"John", 1, 0},
{"9999999999999999999", 1, 0}, // out of range
};
int32_t n = sizeof(test_cases) / sizeof(struct __fixture_parse_numeric_like);
char trace_msg[32] = {0};
int32_t i;
for (i = 0; i < n; i++)
{
snprintf(trace_msg, sizeof(trace_msg), "test case #%d", i);
int32_t has_error = 0;
char error[CLARGS_ERROR_SIZE] = {0};
int32_t actual = clargs_parse_long(test_cases[i].raw, NULL, &has_error, error);
CuAssertIntEquals_Msg(tc, trace_msg, test_cases[i].has_error, has_error);
if (!test_cases[i].has_error)
{
CuAssertIntEquals_Msg(tc, trace_msg, test_cases[i].expected, actual);
}
}
}
struct __fixture_parse_string
{
char raw[24];
size_t max_allowed_length;
int32_t has_error;
char expected[24];
};
void test_clargs_parse_string(CuTest *tc)
{
struct __fixture_parse_string test_cases[] = {
{"", 0, 0, ""},
{"foo", 0, 0, "foo"},
{"foo", 16, 0, "foo"},
{"foobarbaz", 3, 1, ""},
};
size_t n = sizeof(test_cases) / sizeof(struct __fixture_parse_string);
char trace_msg[32] = {0};
int32_t i;
for (i = 0; i < n; i++)
{
snprintf(trace_msg, sizeof(trace_msg), "test case #%i", i);
int32_t has_error = 0;
char error[CLARGS_ERROR_SIZE] = {0};
char *actual = clargs_parse_string(test_cases[i].raw, (void *)test_cases[i].max_allowed_length,
&has_error, error);
CuAssertIntEquals_Msg(tc, trace_msg, test_cases[i].has_error, has_error);
if (!test_cases[i].has_error)
{
CuAssertStrEquals_Msg(tc, trace_msg, test_cases[i].expected, actual);
}
}
}
CuSuite *make_suite_clargs()
{
CuSuite *suite = CuSuiteNew();
SUITE_ADD_TEST(suite, test_clargs_parse);
SUITE_ADD_TEST(suite, test_clargs_add_argument);
SUITE_ADD_TEST(suite, test_clargs_parse_int);
SUITE_ADD_TEST(suite, test_clargs_parse_bool);
SUITE_ADD_TEST(suite, test_clargs_parse_long);
SUITE_ADD_TEST(suite, test_clargs_parse_string);
return suite;
}
|
C
|
//
// sys_file_calls.c
//
//
// Created by Niklas Blomqvist on 2013-02-16.
//
//
#include <syscall-nr.h>
#include <string.h>
#include <stdio.h>
#include "threads/interrupt.h"
#include "threads/thread.h"
#include "threads/init.h"
#include "threads/vaddr.h"
#include "filesys/filesys.h"
#include "filesys/file.h"
#include "filesys/off_t.h" // off_t (int32_t)
#include "devices/input.h" // input_getc()
#include "userprog/syscall.h"
#include "userprog/pagedir.h"
#include "userprog/process.h"
#include "userprog/flist.h" // map
#include "userprog/sys_file_calls.h"
int sys_open(const char* file)
{
struct file* temp = filesys_open(file);
if(temp != NULL)
{
// Mata in pekaren till filen i mapen
// filemap finns initierad i thread.h/c
return map_insert(get_filemap(), temp); // returnerar värdet i mapen
}
return -1; // filen fanns inte
}
int sys_read(int fd, char* buffer, unsigned length)
{
if (fd == STDOUT_FILENO)
return -1; // Vi kan inte läsa från skärmen
unsigned i = 0;
char key;
for (i = 0; i != length; i++)
{
if (fd == STDIN_FILENO) // Tangentbord
{
key = (char)input_getc();
if (key == '\r') // enter
{
key = '\n'; // lägg till ny rad-tecken
buffer[i] = key;
break;
}
else
buffer[i] = key;
putbuf(&buffer[i], 1);
}
else
{
//Read from file
struct file* read_from = map_find(get_filemap(), fd);
if(read_from != NULL && length > 0)
return file_read(read_from, buffer, length);
else
return -1;
}
}
return length; // Så här många tecken läste jag
}
/**
* Skriver till fd (skärm eller fil)
* Returnerar antalet skrivna tecken eller -1 om antalet tecken som ska skrivas
* är 0 eller om filen inte finns.
*/
int sys_write(int fd, const void* buffer, unsigned length)
{
if (fd == STDIN_FILENO) // Vi kan inte skriva till tangentbordet
{
return -1;
}
if (fd == STDOUT_FILENO) // skärmen
{
putbuf(buffer, length);
return length;
}
else
{
// Skriva till fil
struct file* write_to = map_find(get_filemap(), fd);
if(write_to != NULL)
{
// Skriver buffer till write_to. Returnerar antalet skrivna tecken
// Kan returnera ett antal tecken < length om filen är för liten
return file_write(write_to, buffer, length);
}
else
{
return -1; // Filen finns inte, eller så ville vi skriva 0 tecken.
}
}
// Hit ska vi inte komma!
}
bool sys_create(const char* file, unsigned initial_size)
{
if (filesys_create(file, initial_size) && initial_size >= 0)
{
map_insert(get_filemap(), filesys_open(file));
return true;
}
return false;
}
bool sys_remove(const char* file)
{
return filesys_remove(file);
}
void sys_close(int fd)
{
struct file* close_file = map_find(get_filemap(), fd);
if(close_file != NULL)
{
filesys_close(close_file);
map_remove(get_filemap(), fd); // important to remove from file hEHE
}
}
void sys_seek(int fd, unsigned position)
{
struct file* file = map_find(get_filemap(), fd);
if (file != NULL && position <= (unsigned)sys_filesize(fd))
file_seek(file, position);
}
unsigned sys_tell (int fd)
{
struct file* file = map_find(get_filemap(), fd);
if (file != NULL)
return file_tell(file);
return -1;
}
int sys_filesize(int fd)
{
struct file* file = map_find(get_filemap(), fd);
if (file != NULL)
return file_length(file);
return -1;
}
struct map* get_filemap()
{
return &thread_current()->filemap; //.node;
}
|
C
|
#include "prim.h"
// Funktion zur Zerlegung einer Zahl in ihre Primfaktoren
void primfaktoren(zahl)
{
int i;
printf("1 ");
for(i=2;i<=zahl;)
{
if(zahl%i==0)
{
printf("x %d ", i);
zahl /= i;
}
else
{
i++;
}
}
printf("\n");
return;
}
// Funktion für die n-te Potenz
int power(int x,int n)
{
int i;
long long y=x;
if(n==0)
return 1;
if(n==1)
return x;
if(n<=0)
return -1;
for(i=2;i<=n; i++)
{
y=x*y;
}
return y;
}
// Funktion zur Berechnung der n-ten Fibonacci-Zahl
int fibonacci(n)
{
int i, j = 1, k=0,tmp=0;
if(n<1)
return -1;
if(n==1)
return 0;
if(n==2)
return 1;
if(n==3)
return 1;
for(i=3;i<=n;i++)
{
k=j;
j=k+tmp;
tmp=k;
}
return j;
}
// Funktion zur Berechnung der ersten n Fibonacci-Zahlen (als Array, das >= n sein muss)
int *fibonacci_array(int n, int *fibo_array)
{
int i;
if(n<1)
return 0;
fibo_array[0]=0;
fibo_array[1]=0;
fibo_array[2]=1;
for(i=3;i<=n;i++)
{
fibo_array[i]=fibo_array[i-2]+fibo_array[i-1];
}
return fibo_array;
}
// Funktion die testet, ob eine Primzahl vorliegt
int ist_prim(test)
{
int grenze = sqrt(test), i;
for(i=2;i<=grenze;i++)
{
if(test%i==0 || test == 1)
{
return 0;
}
}
return 1;
}
// Funktionsgruppe, die schneller große Primzahlen errechnet
void prim_ermitteln(unsigned long max)
{
unsigned laenge=0, *prim_liste;
short *array=0;
if(max==0)
{
printf("Bis zu Welcher Zahl, sollen Primzahlen gesucht werden?\n");
scanf("%lu", &max);
printf("\n\n");
}
array = (short *) calloc(max+1, sizeof(short));
primzahl(max, array);
prim_liste = prim_array_bereinigen(array, max+1, &laenge);
prim_ausgabe(prim_liste, laenge);
//~ free(array);
free(prim_liste);
}
// Primzahlenermittlung mit Array
void primzahl(unsigned max, short *a)
{
unsigned pot,wurzpot, i, n;
short *c;
pot=sqrt(max);
wurzpot=sqrt(pot);
c = (short *) calloc(pot+1, sizeof(short));
a[0]=1; a[1]=1;
c[0]=1; c[1]=1;
for(i=2;i<=wurzpot;i++)
for(n=i+1;n<=pot;n++)
if(n%i==0)
if(c[n]!=1)
c[n]=1;
for(n=2;n<=pot;n++)
if(c[n]==0)
for(i=n+n;i<=max;i=i+n)
if(a[i]!=1)
a[i]=1;
free(c);
return;
}
unsigned *prim_array_bereinigen(short *alt_array, unsigned alt_array_laenge, unsigned *neu_array_laenge)
{
unsigned i, n=0, *neu_array;
for(i=0; i<=alt_array_laenge; i++){
if(alt_array[i]!=1){
n++;
}
}
*neu_array_laenge=n;
neu_array = (unsigned *) calloc(*neu_array_laenge, sizeof(unsigned));
n=0;
for(i=0; i<=alt_array_laenge; i++){
if(alt_array[i]!=1){
neu_array[n]=i;
n++;
}
}
free(alt_array);
return neu_array;
}
unsigned prim_max(unsigned *prim_liste, unsigned letzte)
{
return (prim_liste[letzte-1]);
}
void prim_ausgabe(unsigned *prim_liste, unsigned anzahl_prim)
{
unsigned i;
short tmp=0;
for(i=0; i<anzahl_prim; i++){
printf("%10u ",prim_liste[i]);
tmp++;
if(tmp%5==0)
printf("\n");
}
printf("\n#%d\n", anzahl_prim);
return;
}
int ist_prim_array(test)
{
short *array=0;
unsigned *prim_liste, laenge;
if(test<=1)
return 0;
array = (short *) calloc(test, sizeof(short));
primzahl(test, array);
prim_liste = prim_array_bereinigen(array, test, &laenge);
//~ free(array);
if(prim_max(prim_liste, laenge) == test)
return 1;
else
return 0;
}
|
C
|
/**
* USB Midi-Fader
*
* Fader implementation
*
* Kevin Cuzner
*/
#include "fader.h"
#include "stm32f0xx.h"
#include "osc.h"
/**
* In reality, this is a really crappy abstraction around the ADC. It is not
* really transferrable to any of my other projects, which I dislike. But, in
* the interest of time I am implementing it this way.
*
* The basic premise is that this will simply place the ADC in continuous
* conversion mode, scanning the 8 channels. At the end of a sequence, it will
* transfer the scanned data to a buffer visible to the rest of the program.
* It will also call a hook function which I may or may not use. Real simple,
* real quick.
*/
#define FADER_CHANNELS 8
/**
* A basic averaging filter is implemented by simply averaging every Nth
* element of the fader data. This should be a power of two for fast
* division.
*/
#define FADER_AVERAGES 16
/**
* Target for the DMA, contains the latest fader data
*/
static uint16_t fader_data[FADER_CHANNELS * FADER_AVERAGES];
void fader_init(void)
{
// Enable HSI14 for the ADC clock
osc_start_hsi14();
// Enable ADC and PortA
RCC->APB2ENR |= RCC_APB2ENR_ADCEN;
RCC->AHBENR |= RCC_AHBENR_GPIOAEN;
// Enable DMA
RCC->AHBENR |= RCC_AHBENR_DMA1EN;
// Set up the ADC pins
GPIOA->MODER |= GPIO_MODER_MODER0_0 | GPIO_MODER_MODER0_1 |
GPIO_MODER_MODER1_0 | GPIO_MODER_MODER1_1 |
GPIO_MODER_MODER2_0 | GPIO_MODER_MODER2_1 |
GPIO_MODER_MODER3_0 | GPIO_MODER_MODER3_1 |
GPIO_MODER_MODER4_0 | GPIO_MODER_MODER4_1 |
GPIO_MODER_MODER5_0 | GPIO_MODER_MODER5_1 |
GPIO_MODER_MODER6_0 | GPIO_MODER_MODER6_1 |
GPIO_MODER_MODER7_0 | GPIO_MODER_MODER7_1;
//Perform ADC calibration
if (ADC1->CR & ADC_CR_ADEN)
{
ADC1->CR |= ADC_CR_ADDIS;
while (ADC1->CR & ADC_CR_ADEN) { }
}
ADC1->CR |= ADC_CR_ADCAL;
while (ADC1->CR & ADC_CR_ADCAL) { }
//Enable the ADC
ADC1->CR |= ADC_CR_ADEN;
while (!(ADC1->ISR & ADC_ISR_ADRDY)) { }
ADC1->ISR = ADC_ISR_ADRDY;
// Prepare for sequenced conversion, continuously
//
// The DMA is set up in circular mode so that we just keep filling the
// buffer as fast as possible
ADC1->CFGR1 = ADC_CFGR1_CONT | ADC_CFGR1_DMAEN | ADC_CFGR1_DMACFG;
ADC1->CHSELR = ADC_CHSELR_CHSEL0 | ADC_CHSELR_CHSEL1 |
ADC_CHSELR_CHSEL2 | ADC_CHSELR_CHSEL3 | ADC_CHSELR_CHSEL4 |
ADC_CHSELR_CHSEL5 | ADC_CHSELR_CHSEL6 | ADC_CHSELR_CHSEL7;
ADC1->SMPR = ADC_SMPR_SMP_0 | ADC_SMPR_SMP_1 | ADC_SMPR_SMP_2;
DMA1_Channel1->CPAR = (uint32_t)(&ADC1->DR);
DMA1_Channel1->CMAR = (uint32_t)(fader_data);
DMA1_Channel1->CNDTR = sizeof(fader_data) / sizeof(fader_data[0]);
DMA1_Channel1->CCR = DMA_CCR_MINC | DMA_CCR_MSIZE_0 | DMA_CCR_PSIZE_0 |
DMA_CCR_TEIE | DMA_CCR_CIRC;
DMA1_Channel1->CCR |= DMA_CCR_EN;
ADC1->IER |= ADC_IER_EOSEQIE;
ADC1->CR |= ADC_CR_ADSTART;
NVIC_EnableIRQ(ADC1_COMP_IRQn);
}
uint16_t fader_get_value(uint8_t channel)
{
if (channel > FADER_CHANNELS - 1)
return 0;
uint32_t accumulator = 0;
for (uint32_t i = channel; i < sizeof(fader_data)/sizeof(fader_data[0]); i += FADER_CHANNELS)
{
accumulator += fader_data[i];
}
accumulator /= FADER_AVERAGES;
return accumulator;
}
static uint32_t conversions = 0;
void ADC1_IRQHandler(void)
{
if (ADC1->ISR & ADC_ISR_EOSEQ)
conversions++;
ADC1->ISR = ADC1->ISR;
}
|
C
|
#include<stdio.h>
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
struct TreeNode* BuildBst(int *nums,int start,int end)
{
if(start > end)
{
return NULL;
}
struct TreeNode *pnode = (struct TreeNode*)malloc(sizeof(struct TreeNode));
pnode->val = nums[(end + start) >> 1];
pnode->left = BuildBst(nums, start, ((end + start) >> 1) - 1);
pnode->right = BuildBst(nums, ((end + start) >> 1) + 1,end);
return pnode;
}
struct TreeNode* sortedArrayToBST(int* nums, int numsSize){
return BuildBst(nums, 0, numsSize - 1);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <dlfcn.h>
#include "f12.h"
#include "bindsym.h"
/*
* f12 x = f12_bind( char *module, char *errmsg );
* locate "lib<module>.so", and attempt to locate all the
* required function symbols (and their ancillary signature variables
* to guarantee they are match the parameter signatures) inside
* the library. For each function called <fname>, we look first for
* a symbol "module_fname", and second for a symbol "fname".
*
* If we fail to find any of the required functions: strcpy an error
* message into errmsg and return NULL.
*
* If we succeed then we say we have "bound" the library to the interface:
* we return an newly malloc()d f12 object with the function
* pointers bound to the corresponding functions in lib<module>.so
*/
f12 f12_bind( char * module, char * errmsg )
{
char libname[1024];
assert( strlen(module) < 1000 );
sprintf( libname, "lib%s.so", module );
void *dl = dlopen( libname, RTLD_NOW );
if( dl == NULL )
{
sprintf( errmsg, "f12_bind: dlopen of %s failed", libname );
return NULL;
}
f12 r = malloc(sizeof(*r));
if( r == NULL )
{
strcpy( errmsg, "f12_bind: malloc() failed" );
return NULL;
}
bindsym_info info;
info.dl = dl;
info.interface = "f12";
info.module = module;
info.libname = libname;
info.errmsg = errmsg;
r->f1 = (f12_void_void_f) bindsym( &info, "f1", "f1_void_void" );
if( r->f1 == NULL )
{
free(r);
return NULL;
}
r->f2 = (f12_int_void_f) bindsym( &info, "f2", "f2_int_void" );
if( r->f2 == NULL )
{
free(r);
return NULL;
}
return r;
}
|
C
|
#pragma once
struct VideoFrame
{
double m_displayTime;
int64_t m_duration;
AVFrame* const m_image;
VideoFrame()
: m_displayTime(0)
, m_duration(0)
, m_image(av_frame_alloc())
{}
~VideoFrame()
{
av_frame_free(const_cast<AVFrame**>(&m_image));
}
VideoFrame(const VideoFrame&) = delete;
VideoFrame& operator=(const VideoFrame&) = delete;
void free()
{
av_frame_unref(m_image);
}
void realloc(AVPixelFormat pix_fmt, int width, int height)
{
if (pix_fmt != m_image->format || width != m_image->width || height != m_image->height)
{
free();
m_image->format = pix_fmt;
m_image->width = width;
m_image->height = height;
av_frame_get_buffer(m_image, 1);
}
}
};
|
C
|
/**
* Módulo para manipulação de JSON.
* Autor: Gabriel Dertoni
* GitHub: github.com/GabrielDertoni
*/
#ifndef __JSON_H__
#define __JSON_H__
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
#include <parsing_utils.h>
#include <dict.h>
/**
* Conversões entre tipos de valores JSON:
*
* Um determinado valor json pode tomar uma de várias formas. Todos os tipos de
* valores suportados podem ser vistos na definição de json_type_t. Cada um
* desses tipos é representado por um struct diferente e todos possuem em comum
* o primeiro campo que sempre será um json_self_t. Isso garante que a conversão
* json_X_t* -> json_self_t* é sempre possível. A conversão oposta só é garantida
* se o jtype(valor) = X.
*
* Para representar um valor genérico que pode assumir qualquer tipo existe o
* json_value_t que é definido como void, já não é possível saber seu tamanho.
* A conversão json_value_t* <-> json_self_t* sempre é garantida. Entretanto
* vale notar que json_self_t representa apenas parte da memória de json_value_t
* e portanto sizeof(json_self_t) não pode ser usado para memcpy de json_value_t.
* Para isso, deve ser usado json_sizeof().
*/
#define jtype(value) (((json_self_t *)value)->type)
#define jis_obj(v) (jtype(v) == JSON_OBJECT )
#define jis_arr(v) (jtype(v) == JSON_ARRAY )
#define jis_str(v) (jtype(v) == JSON_STRING )
#define jis_num(v) (jtype(v) == JSON_NUMBER )
#define jis_bool(v) (jtype(v) == JSON_BOOL )
#define jis_undef(v) (jtype(v) == JSON_UNDEFINED)
#define jis_null(v) (jtype(v) == JSON_NULL )
// Macros para conversão de json_value_t -> json_X_t.
#define jas_val(v) ((json_value_t *)v) // Sempre é seguro.
#define jas_obj(v) ({ assert(jis_obj (v)); (json_object_t *)v; })
#define jas_arr(v) ({ assert(jis_arr (v)); (json_array_t *)v; })
#define jas_str(v) ({ assert(jis_str (v)); (json_string_t *)v; })
#define jas_num(v) ({ assert(jis_num (v)); (json_number_t *)v; })
#define jas_bool(v) ({ assert(jis_bool (v)); (json_bool_t *)v; })
#define jas_undef(v) ({ assert(jis_undef(v)); (json_undefined_t *)v; })
#define jas_null(v) ({ assert(jis_null (v)); (json_null_t *)v; })
typedef enum {
JSON_OBJECT,
JSON_ARRAY,
JSON_STRING,
JSON_NUMBER,
JSON_BOOL,
JSON_UNDEFINED,
JSON_NULL,
} json_type_t;
typedef void json_value_t;
typedef struct {
json_type_t type;
} json_self_t;
typedef struct {
char *key;
json_value_t *value;
} json_pair_t;
typedef struct {
json_self_t self;
dict_t *pairs;
} json_object_t;
typedef struct {
json_self_t self;
json_value_t **values;
uint size;
} json_array_t;
typedef struct {
json_self_t self;
char *content;
} json_string_t;
typedef struct {
json_self_t self;
double number;
} json_number_t;
typedef struct {
json_self_t self;
bool value;
} json_bool_t;
typedef struct {
json_self_t self;
} json_null_t;
typedef struct {
json_self_t self;
} json_undefined_t;
parser_result_t json_parse_file(char *fname, json_value_t **parsed);
parser_result_t json_parse_value(char **input, json_value_t **parsed);
parser_result_t json_parse_object(char **input, json_object_t **parsed);
parser_result_t json_parse_array(char **input, json_array_t **parsed);
parser_result_t json_parse_string(char **input, json_string_t **parsed);
parser_result_t json_parse_number(char **input, json_number_t **parsed);
parser_result_t json_parse_bool(char **input, json_bool_t **parsed);
parser_result_t json_parse_null(char **input, json_null_t **parsed);
parser_result_t json_parse_undefined(char **input, json_undefined_t **parsed);
void json_value_delete(json_value_t *value);
size_t json_sizeof(json_value_t *value);
json_value_t *json_object_get(json_object_t *obj, char *key);
json_value_t *json_js_index(json_value_t *value, char *indexing);
#endif
|
C
|
/*
* ejercicio1.c
*
* Created on: Feb 27, 2017
* Author: Javier Quiroz
*/
#include<stdio.h>
#include<string.h>
#define MAX_LONG 200
#define CADENA_PRUEBA "Hola a todos"
int longitud_string_vieja(char s[]){
int i;
i=0;
while(s[i] != '\0')
i++;
return i;
}
int longitud_string(char *s){
int i = 0;
char *p = s;
while(*(p) != '\0') {
p++;
i++;
}
return i;
}
/*
* a) cambiar longitud_string a que use apuntadores
*
* Respuesta: Se presenta el driver siguiente para probar este inciso: Para ver
* sus resultados a que cambiar
*
* b) Investiga el uso de la función scanf para que imprima la longitud de los
* strings del archivo.txt: hamburguesas permisos exponencialmente 549
* $./ejercicio_1_scanf.out < archivo.txt
*
longitud hamburguesas: 12
longitud permisos: 8
longitud exponencialmente: 16
longitud 549: 3
*/
int main(void){
// inciso a
char string1[] = CADENA_PRUEBA; //definición y declaracion de variable e inicializacion.
char string2[MAX_LONG]; //definición y declaracion.
char string3[] = CADENA_PRUEBA; //definición y declaracion de variable e inicializacion.
int tamanio = 0;
printf( "a) \n");
printf("cadena: %s\n", string1);
printf("longitud cadena: %d\n", longitud_string(string1));
strcpy(string2, "leer libros y revistas"); //inicializacion de string2
printf("cadena2: %s\n", string2);
printf("longitud cadena: %d\n", longitud_string(string2));
//inciso b
printf( "b) \n");
while ( ( tamanio = scanf( "%s", string3 ) ) > 0 )
printf( "Longitud %s: %d \n", string3, strlen(string3) );
return 0;
}
|
C
|
#include<libebox/core.h>
#include<libebox/errors.h>
#include<sys/stat.h>
#include<sys/epoll.h>
#include<sys/socket.h>
#include<fcntl.h>
#include<errno.h>
#include<unistd.h>
#include<stdio.h>
#include<string.h>
int ebox_poller_init(struct ebox_poller* poller, int maxevents) {
if(poller == NULL) {
return LIBEBOX_ERR_BADPTR;
}
if(maxevents == -1) {
maxevents = 4;
} else if(maxevents < 0) {
return LIBEBOX_ERR_BADARG;
}
int fd = epoll_create1(EPOLL_CLOEXEC);
if(fd == -1) {
switch(errno) {
case EMFILE:
return LIBEBOX_ERR_LIMIT;
case ENOMEM:
return LIBEBOX_ERR_OOM;
case EINVAL:
default:
return LIBEBOX_ERR_INTERNAL;
}
}
poller->epoll_fd = fd;
poller->maxevents = maxevents;
return LIBEBOX_ERR_NONE;
}
static int ebox_poll_new_internal(struct ebox_poller *poller, struct ebox_poll_state **conn, int fd, bool issock) {
//check inputs
if(poller == NULL || conn == NULL) {
return LIBEBOX_ERR_BADPTR;
}
*conn = NULL;
if(poller->epoll_fd == 0) {
return LIBEBOX_ERR_BADFD;
}
//create state object
struct ebox_poll_state *state = autoalloc(struct ebox_poll_state);
if(state == NULL) {
return LIBEBOX_ERR_OOM;
}
//set fd as non-blocking
int flags = fcntl(fd, F_GETFL, 0);
if(flags < 0) {
free(state);
return LIBEBOX_ERR_IO;
}
flags |= O_NONBLOCK | O_CLOEXEC;
if(fcntl(fd, F_SETFL, flags) == -1) {
free(state);
return LIBEBOX_ERR_IO;
}
//populate state object
state->poller = poller;
state->isSocket = issock;
state->fd = fd;
state->ctx = NULL;
if(!issock) {
state->epollstat = 0;
state->rxenable = false;
state->txenable = false;
ebox_buf_alloc(&state->txbuf, 0);
ebox_buf_alloc(&state->rxbuf, 0);
state->onrecv = NULL;
state->ondonesending = NULL;
state->onclosed = NULL;
} else {
state->onaccept = NULL;
}
//save result
*conn = state;
return LIBEBOX_ERR_NONE;
}
int ebox_poll_new(struct ebox_poller *poller, struct ebox_poll_state **conn, int fd) {
return ebox_poll_new_internal(poller, conn, fd, false);
}
int ebox_poll_upd(struct ebox_poll_state *conn) {
//check that conn is valid
if(conn == NULL) {
return LIBEBOX_ERR_BADPTR;
}
if(conn->poller == NULL) {
return LIBEBOX_ERR_BADPTR;
}
if(conn->poller->epoll_fd < 0) {
return LIBEBOX_ERR_BADARG;
}
if(conn->isSocket) {
//do nothing
} else {
//turn off tx if done sending
if(conn->txbuf.len == 0) {
conn->txenable = false;
}
//determine epoll events
int epollstat = 0
| (conn->rxenable ? EPOLLIN : 0)
| (conn->txenable ? EPOLLOUT : 0);
//update if change
if(epollstat != conn->epollstat) {
int op;
//determine if it is adding, removing, or changing
if(conn->epollstat == 0) {
op = EPOLL_CTL_ADD;
} else if(epollstat == 0) {
op = EPOLL_CTL_DEL;
} else {
op = EPOLL_CTL_MOD;
}
//try to update
struct epoll_event ev;
ev.events = epollstat;
ev.data.ptr = conn;
if(epoll_ctl(conn->poller->epoll_fd, op, conn->fd, &ev) == -1) {
return LIBEBOX_ERR_IO;
}
//write updated state
conn->epollstat = epollstat;
}
}
return LIBEBOX_ERR_NONE;
}
int ebox_poll_cycle(struct ebox_poller *poller) {
//check that poller is valid
if(poller == NULL) {
return LIBEBOX_ERR_BADPTR;
} else if(poller->maxevents < 0) {
return LIBEBOX_ERR_BADARG;
} else if(poller->epoll_fd < 0) {
return LIBEBOX_ERR_BADFD;
}
struct epoll_event evs[poller->maxevents];
ew:;
int n = epoll_wait(poller->epoll_fd, evs, poller->maxevents, -1);
if(n == -1) {
switch(errno) {
case EBADF:
return LIBEBOX_ERR_BADFD;
case EFAULT:
return LIBEBOX_ERR_BADPTR;
case EINTR:
goto ew;
case EINVAL:
return LIBEBOX_ERR_BADFD;
default:
return LIBEBOX_ERR_INTERNAL;
}
}
for(int i = 0; i < n; i++) {
struct epoll_event ev = evs[i];
struct ebox_poll_state *conn = ev.data.ptr;
if(conn == NULL) {
return LIBEBOX_ERR_BADPTR;
}
fixit:
if(ev.events & (EPOLLHUP|EPOLLRDHUP)) {
ebox_poll_close(conn);
} else if(ev.events & (EPOLLERR|EPOLLPRI)) {
conn->onerr(conn);
ebox_poll_close(conn);
} else if(ev.events & EPOLLOUT) {
struct ebox_buf *txb = &(conn->txbuf);
ssize_t n = write(conn->fd, txb->dat, (txb->len > 1024) ? 1024 : txb->len);
if(n == -1) {
conn->onerr(conn);
ebox_poll_close(conn);
goto y;
}
txb->len -= n;
txb->dat += n;
if(txb->len == 0) {
ebox_buf_free(txb);
if(conn->ondonesending != NULL) {
conn->ondonesending(conn);
}
ebox_poll_upd(conn);
}
} else if(ev.events & EPOLLIN) {
if(conn->isSocket) {
int fd = accept(conn->fd, NULL, NULL);
if(errno == -1) {
return LIBEBOX_ERR_IO;
}
conn->onaccept(conn, fd);
} else {
//read up to 1024 bytes
char buf[1024];
int n = read(conn->fd, buf, 1024);
if(n == 0) {
ev.events = EPOLLRDHUP;
goto fixit;
}
if(n == -1) {
conn->onerr(conn);
ebox_poll_close(conn);
goto y;
}
int ok = ebox_buf_append(&conn->rxbuf, buf, n);
if(ok != LIBEBOX_ERR_NONE) {
conn->onerr(conn);
ebox_poll_close(conn);
goto y;
}
if(conn->onrecv != NULL) {
conn->onrecv(conn);
}
}
}
y:;
}
return LIBEBOX_ERR_NONE;
}
int ebox_poll_close(struct ebox_poll_state *conn) {
if(conn == NULL || conn->poller == NULL) {
return LIBEBOX_ERR_BADPTR;
}
if(conn->fd < 0 || conn->poller->epoll_fd < 0) {
return LIBEBOX_ERR_BADFD;
}
if(conn->onclosed != NULL) {
conn->onclosed(conn);
}
free(conn->ctx);
if(!conn->isSocket) {
if(conn->epollstat != 0) {
if(epoll_ctl(conn->poller->epoll_fd, EPOLL_CTL_DEL, conn->fd, NULL) == -1) {
switch(errno) {
case EBADF:
case EINVAL:
return LIBEBOX_ERR_BADFD;
case ENOENT:
break; //it is not registered with epoll
//that is ok
case ENOMEM:
return LIBEBOX_ERR_OOM;
case EPERM: //not sure how this would happen
return LIBEBOX_ERR_INTERNAL;
default:
return LIBEBOX_ERR_INTERNAL;
}
}
}
ebox_buf_free(&conn->rxbuf);
ebox_buf_free(&conn->txbuf);
}
close(conn->fd);
free(conn);
return LIBEBOX_ERR_NONE;
}
int ebox_poll_serve(struct ebox_poller *poller, struct ebox_poll_state **sock, int sockfd, void (*handler)(struct ebox_poll_state*, int)) {
if(poller == NULL || sock == NULL || handler == NULL) {
return LIBEBOX_ERR_BADPTR;
}
if(sockfd < 0) {
return LIBEBOX_ERR_BADFD;
}
struct ebox_poll_state *s = NULL;
int err = ebox_poll_new_internal(poller, &s, sockfd, true);
if(err != LIBEBOX_ERR_NONE) {
return err;
}
s->onaccept = handler;
struct epoll_event ev;
ev.events = EPOLLIN;
ev.data.ptr = s;
if(epoll_ctl(s->poller->epoll_fd, EPOLL_CTL_ADD, s->fd, &ev) == -1) {
free(s);
return LIBEBOX_ERR_IO;
}
*sock = s;
return LIBEBOX_ERR_NONE;
}
|
C
|
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/mman.h>
int change_page_permissions_of_address(void *addr);
void foo();
void get_permission(void *foo_addr);
char *err_string = "Error while changing page permissions of foo()\n";
int main(void)
{
get_permission(foo);
unsigned char *foo_code = (unsigned char *)malloc(sizeof(unsigned char) * 55);
memcpy(foo_code, foo, 55);
for (int i = 0; i < 55; i++)
{
foo_code[i] = foo_code[i] ^ -1;
}
memcpy(foo, foo_code, 55);
for (int i = 0; i < 55; i++)
{
foo_code[i] = foo_code[i] ^ -1;
}
memcpy(foo, foo_code, 55);
foo();
}
void foo()
{
int num = 0;
printf("This is Foo Function\n");
num += 10;
printf("num = %d\n", num);
}
void get_permission(void *foo_addr)
{
if (change_page_permissions_of_address(foo_addr) == -1)
{
write(STDERR_FILENO, err_string, strlen(err_string) + 1);
exit(1);
}
}
int change_page_permissions_of_address(void *addr)
{
int page_size = 4096;
addr -= (unsigned long)addr % page_size;
if (mprotect(addr, page_size, PROT_READ | PROT_WRITE | PROT_EXEC) == -1)
{
return -1;
}
return 0;
}
|
C
|
/* -----------------------------------------------------------------------
* Sylvan Canales
* Assignment 3
* Include the following lines in your makefile:
*
* cardtest3: cardtest3.c dominion.o rngs.o
* gcc -o cardtest3 -g cardtest3.c dominion.o rngs.o $(CFLAGS)
* -----------------------------------------------------------------------
*/
#include "dominion.h"
#include "dominion_helpers.h"
#include <string.h>
#include <stdio.h>
#include <assert.h>
// set NOISY_TEST to 0 to remove printfs from output
#define NOISY_TEST 0
int main()
{
int seed = 10;
int players = 2;
int p = 0;
int handPos = 0;
int bonus = 0;
int choice1 = 0;
int choice2 = 0;
int choice3 = 0;
int card = cutpurse;
int count_pre;
int count_post;
int pass = 1;
int r, i;
int k[10] = {adventurer, council_room, feast, gardens, mine, remodel, smithy, cutpurse, baron, great_hall};
struct gameState G;
struct gameState G2;
printf ("TESTING Cutpurse:\n");
initializeGame(players, k, seed, &G); // initialize a new game
// Need to give other player some cards in the hand, since initializeGame only does Player 0
for (i = 0; i < 5; i++) {
drawCard(1, &G);
}
// Make copy of gameState so we can compare before and after
memcpy (&G2, &G, sizeof(struct gameState));
// Get the count of coppers for player 2
count_pre = 0;
for (i = 0; i < G.handCount[1]; i++) {
if (G.hand[1][i] == copper) count_pre++;
}
#if (NOISY_TEST == 1)
printf("Testing PRE. player %d, coins %d, other player coppers %d\n", p, G.coins, count_pre);
#endif
r = cardEffect(card, choice1, choice2, choice3, &G, handPos, &bonus);
// Get the count of coppers for player 2
count_post = 0;
for (i = 0; i < G.handCount[1]; i++) {
if (G.hand[1][i] == copper) count_post++;
}
#if (NOISY_TEST == 1)
printf("Testing POST. player %d, coins %d, other player coppers %d\n", p, G.coins, count_post);
#endif
assert(r == 0);
assert(G.coins == G2.coins + 2); // Player 0 should have 2 more coins
// Check that player 1 has 1 less copper
if (count_pre > 0) {
if (!(count_post == count_pre - 1)) {
printf("Assertion failed: (count_post == count_pre - 1)\n");
pass = 0;
}
}
// Test a new scenario where player 1 has no coppers in the hand
// This is supposed to reach the conditional branch that reveals
// the cards in the hand.
memset(&G, 23, sizeof(struct gameState)); // clear the game state
initializeGame(players, k, seed, &G); // initialize a new game
// Need to give other player some cards in the hand, since initializeGame only does Player 0
for (i = 0; i < 5; i++) {
drawCard(1, &G);
if (G.hand[1][i] == copper) {
G.hand[1][i] = gold;
}
}
// Make copy of gameState so we can compare before and after
memcpy (&G2, &G, sizeof(struct gameState));
// Get the count of coppers for player 2
count_pre = 0;
for (i = 0; i < G.handCount[1]; i++) {
if (G.hand[1][i] == copper) count_pre++;
}
#if (NOISY_TEST == 1)
printf("Testing PRE. player %d, coins %d, other player coppers %d\n", p, G.coins, count_pre);
#endif
r = cardEffect(card, choice1, choice2, choice3, &G, handPos, &bonus);
// Get the count of coppers for player 2
count_post = 0;
for (i = 0; i < G.handCount[1]; i++) {
if (G.hand[1][i] == copper) count_post++;
}
#if (NOISY_TEST == 1)
printf("Testing POST. player %d, coins %d, other player coppers %d\n", p, G.coins, count_post);
#endif
// Make sure unrelated state is unchanged for other player
p = 1;
assert(G.deckCount[p] == G2.deckCount[p]);
assert(G.handCount[p] == G2.handCount[p]);
assert(G.discardCount[p] == G2.discardCount[p]);
assert(memcmp(&G.deck[p], &G2.deck[p], MAX_DECK * sizeof(int)) == 0);
assert(memcmp(&G.hand[p], &G2.hand[p], MAX_HAND * sizeof(int)) == 0);
assert(memcmp(&G.discard[p], &G2.discard[p], MAX_DECK * sizeof(int)) == 0);
if (pass) {
printf("TEST SUCCESSFULLY COMPLETED!\n");
} else {
printf("TEST FAILED!\n");
}
return 0;
}
|
C
|
/* A program implementing the quicksort sorting algorithm concurrently
* using the POSIX Thread (pthread) api.
*
* Usage: gcc quickSort.c -lpthread
* ./quickSort || ./quickSort sizeOfArrayToSort
* If no int argument sizeOfArrayToSort is given, we sort an array of 10000 numbers.
* The array contains numbers of random value between 0 and 98
*
* Written by Jacob Hedén Malm ([email protected])
*
*/
#ifndef _REENTRANT
#define _REENTRANT
#endif
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <time.h>
#include <sys/time.h>
#include <semaphore.h>
#define MAXSIZE 10000
//#define DEBUG 1
//method declarations
void swap(int, int);
void* quickSort(void *);
int partition();
void printArray();
//Global vars
int size;
int array[MAXSIZE];
//variable that keeps count of current number of threads active
int threadCounter = 0;
pthread_t workerId[MAXSIZE];
//pointers to pass to new thread
int args[2];
sem_t sem;
//timer function taken from matrixSum.c
double read_timer() {
static bool initialized = false;
static struct timeval start;
struct timeval end;
if( !initialized )
{
gettimeofday( &start, NULL );
initialized = true;
}
gettimeofday( &end, NULL );
return (end.tv_sec - start.tv_sec) + 1.0e-6 * (end.tv_usec - start.tv_usec);
}
int main(int argc, char * argv[]){
sem_init(&sem, 1, 1);
//populate the array
size = (argc > 1) ? atoi(argv[1]) : MAXSIZE;
for (int i = 0; i < size; i++){
array[i] = rand() % 99;
}
printf("The array to sort: ");
printArray();
int pointers[2] = {0, size - 1};
double starttime = read_timer();
//create the first thread
pthread_create(&workerId[0], NULL, quickSort, (void *) pointers);
threadCounter++;
pthread_join(workerId[0], NULL);
while (threadCounter != 0){
//wait for all child threads to terminate
}
double endtime = read_timer();
printf("The sorted array: ");
printArray();
printf("The execution time is %g sec\n", endtime - starttime);
return 0;
}
//method that outputs the global array to stdout
void printArray(){
printf("|");
for (int i = 0; i < size; i++){
printf("%d|", array[i]);
}
printf("\n");
}
//take arguments, put them in new mem location outside of scope of the thread that spawns this one
//and allow other threads to use global vars to spawn threads through incrementing semaphore
void * passArgs(void * arg){
int * low = (int*) arg;
int * high = low + 1;
int * passed = (int*) malloc(2 * sizeof(int));
*passed = *low;
*(passed + 1) = *high;
sem_post(&sem);
quickSort((void*) passed);
free(passed);
}
//the managing method of quicksort, spawning threads and doing recursive calls with the right pointers
void* quickSort(void * arg){
int * low = (int*) arg;
int * high = low + 1;
#ifdef DEBUG
printf("index of low: %d\n", *low);
printf("index of high: %d\n", *high);
#endif
//if the size of the subarray is not small enough we need to sort it, otherwise we have broken the problem down sufficiently
if (*low < *high){
//logic for partitioning the array
int partitionElement = partition(*low, *high);
//lock semaphore so only one thread passes arguments at a time
sem_wait(&sem);
args[0] = *low;
args[1] = partitionElement - 1;
pthread_create(&workerId[threadCounter], NULL, passArgs, (void *) args);
threadCounter++;
//solve the other partition recursively, so we only spawn need to spawn one new thread per partition
int args1[2] = {partitionElement + 1, *high};
quickSort((void *) args1);
}
else {
threadCounter--;
return NULL;
}
}
int partition(int low, int high){
//the rightmost index is the pivot element
int pivot = high;
int invPos = low - 1; //index in array where we know all elements below it are smaller than the pivot: an invariant
#ifdef DEBUG
printf("pivot : %d\n", array[pivot]);
printf("invariant pos: %d\n", invPos);
printArray();
#endif
//iterate over the array, swapping elements positionally so that we divide the elements into smaller than pivot and larger than pivot
//at the end we put the pivot in the spot after invPos where we know all elements are smaller than it to the left, and all elements
//are larger than it to the right, effectively partitioning the array
for (int i = low; i < high; i++){
if (array[i] < array[pivot]){
invPos++;
swap(invPos, i);
}
#ifdef DEBUG
printArray();
#endif
}
invPos++;
swap(invPos, pivot);
#ifdef DEBUG
printArray();
#endif
//return the position of the pivot element, we know we still need to sort the parts of the array to the left and to the right
//of the pivot
return invPos;
}
// A method to swap two elements given their positions in the array that we are to sort
void swap(int i1, int i2){
int temp = array[i1];
array[i1] = array[i2];
array[i2] = temp;
return;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
struct no {
int item;
struct no *prox;
};
typedef struct no Node;
Node* aloca(){
Node *no = (Node*)malloc(sizeof(Node));
return no;
}
Node* newNode(){
Node *node = aloca();
int num;
printf("Type a new item: ");
scanf("%d",&node->item);
node->prox = NULL;
}
void add(Node *prim){
Node *no = prim;
while (no->prox!=NULL){
no = no->prox;
}
no->prox = newNode();
}
int check(Node *node, int p){
while (node->prox!=NULL){
if(node->prox->item==p){
return 1;
break;
}
node = node->prox;
}
return 0;
}
void search(Node *prim){
int p;
printf("Type the item to be searched: ");
scanf("%d",&p);
(check(prim,p))?printf("\nItem found!!!\n"):printf("\nItem not found!!!\n");
}
void delete(Node *prim){
int r; Node *node = prim; Node *p;
printf("Type the item to be removed: ");
scanf("%d",&r);
while (node->prox->item!=r){
node = node->prox;
}
p = node->prox;
node->prox = p->prox;
free(p);
}
void print(Node *no){
Node *aux = no->prox;
printf("\nPrinting items...\n");
while(aux!=NULL){
printf("Item: %d \n",aux->item );
aux = aux->prox;
}
}
int main(){
int op;
Node *list = aloca();
do{
printf("\n\tMenu:\n");
printf( "- Type 0 to leave\n"
"- Type 1 do add a new item\n"
"- Type 2 to print the list\n"
"- Type 3 to delete an item\n"
"- Type 4 to search for an item\n"
"\nChoose an option: ");
scanf("%d",&op);
if(op == 1)
add(list);
else if(op==2)
print(list);
else if(op==3)
delete(list);
else if(op==4)
search(list);
else if(op==0)
printf("\nFim da operacao...\n");
else printf("Invalid option...\n");
}while(op!=0);
return 0;
}
|
C
|
#include<stdio.h>
int main()
{
int i,j,max,k,l;
scanf("%d",&k);
int num[k];
for(i=0;i<k;i++)
{
scanf("%d",&num[i]);
}
for(j=0;j<k;j++)
{
if(j==0)
{
max=num[j];
}
else if(max<num[j])
{
max=num[j];
}
}
for(i=0;i<k;i++)
{
if(max==num[i])
{
l=i+1;
break;
}
}
printf("%d %d",l,max);
return 0;
}
|
C
|
#include <float.h> /* LDBL_MAX, LDBL_EPSILON */
#include <limits.h> /* CHAR_BIT, SCHAR_MIN, SCHAR_MAX, CHAR_MIN, CHAR_MAX
SHRT_MIN, SHRT_MAX, INT_MIN, INT_MAX, LONG_MIN,
LONG_MAX LLONG_MIN, LLONG_MAX */
#include <stdio.h> /* printf */
int main() {
printf("short int [min] = %d\n", SHRT_MIN);
printf("short int [max] = %d\n", SHRT_MAX);
printf("long int [min] = %ld\n", LONG_MIN);
printf("long int [max] = %ld\n", LONG_MAX);
printf("long long int [min] = %lld\n", LLONG_MIN);
printf("long long int [max] = %lld\n", LLONG_MAX);
printf("long double [max] = %Lg\n", LDBL_MAX);
printf("long double [min] = %Lg\n", LDBL_MIN);
printf("long double [smallest] = %Lg\n", LDBL_EPSILON);
}
|
C
|
#include <stdio.h>
int reverse(int);
int main()
{
int t;
int a;
int b;
int i;
scanf("%d", &t);
int c[t];
for (i = 0; i < t; i++) {
scanf("%d", &a);
scanf("%d", &b);
c[i] = reverse(a) + reverse(b);
}
for (i = 0; i < t; i++) {
printf("%d\n", reverse(c[i]));
}
return 0;
}
int reverse(int a)
{
int r;
int s = 0;
while (a > 0) {
r = a % 10;
a = a / 10;
s = s * 10 + r;
}
return s;
}
|
C
|
#include "zbaselib_socket.h"
#include <assert.h>
#define PORT 9000
zbaselib_socket_t zbaselib_socket_create_tcpclient11(const struct sockaddr_in* addr)
{
zbaselib_socket_t sock = 0;
sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (!zbaselib_socket_isvalid(sock))
return INVALID_SOCKET;
assert(zbaselib_socket_nonblocking(sock) == 0);
assert(zbaselib_socket_keepalive(sock, 5000, 3000) == 0);
if (connect(sock, (const struct sockaddr *) addr, sizeof(*addr)) != 0
&& !zbaselib_socket_connect_wouldblock())
{
zbaselib_socket_close(sock);
return INVALID_SOCKET;
}
return sock;
}
int main(int argc, char* argv[])
{
zbaselib_socket_t clnt;
struct sockaddr_in addr;
assert(zbaselib_socket_init() == 0);
zbaselib_socket_setaddr(&addr, inet_addr("192.168.1.44"), htons(PORT));
CONN:
clnt = zbaselib_socket_create_tcpclient11(&addr);
if(zbaselib_socket_waitforconnect(clnt, 2000) < 0)
{
zbaselib_socket_close(clnt);
goto CONN;
}
if(zbaselib_socket_isvalid(clnt))
{
printf("connect ok\n");
}
else
{
printf("error:%d\n", zbaselib_socket_geterror());
}
zbaselib_socket_close(clnt);
zbaselib_socket_deinit();
return 0;
}
|
C
|
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include "stack.h"
//创建栈
_stack *stack_create(int size)
{
//参数检查
assert(size > 0);
if (size <= 0) return NULL;
//内存申请
_stack *stack = (_stack *)malloc(sizeof(_stack));
if (!stack) return NULL;
stack->table = (void **)malloc(size * sizeof(void *));
if (!stack)
{
free(stack);
return NULL;
}
//赋初值
stack->size = size;
stack->base = stack->top = 0;
return stack;
}
//入栈
int stack_push(_stack *stack, void *item)
{
//参数检查
assert(stack && item);
if (!stack || !item) return STACK_PARAM_ERROR;
//如果满了,扩展内存。
if (stack_full(stack))
{
int new_size = stack->size + stack->size / 2;
void **new_table = (void **)realloc(stack->table, new_size * sizeof(void *));
if (!new_table) return STACK_MEM_ERROR;
stack->table = new_table;
stack->size = new_size;
}
stack->table[stack->top++] = item;
return STACK_SUCCESS;
}
//出栈
void *stack_pop(_stack *stack)
{
//参数检查
assert(stack);
if (!stack) return NULL;
if (stack_empty(stack)) return NULL;
return stack->table[--stack->top];
}
|
C
|
#include "GraphAdjListUtil.h"
#include <stdio.h>
/*
0 1
1 2
2 3
2 0
-1 -1
//Ϊõͷ巨,2 32 0ʹڽӱΪ2-->0->3
*/
int main(void)
{
GraphList *graphList = NULL;
graphList = InitGraph(4);
ReadGraph(graphList);
WriteGraph(graphList);
printf("\n");
return 0;
}
|
C
|
#include "Logging.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <windows.h>
#include "MemoryPatch.h"
/* Initialize a fairly basic patch that basically overwrites the code with a call. */
t_memorypatch *mp_initialize(void *address, void *call_function, int length)
{
t_memorypatch *newpatch = (t_memorypatch *) malloc(sizeof(t_memorypatch));
if(!newpatch)
{
log_add("Out of memory!\n");
exit(1);
}
memset(newpatch, 0, sizeof(t_memorypatch));
newpatch->address = address;
newpatch->call_function = call_function;
newpatch->original = buffer_initialize();
newpatch->patch = buffer_initialize();
newpatch->wrapper = buffer_initialize();
newpatch->length = length;
newpatch->preserve_original = FALSE;
newpatch->preserve_registers = FALSE;
newpatch->return_register = NO_REGISTER;
newpatch->parameters = pl_initialize();
return newpatch;
}
/** Initialize a patch that preserves the original code, stores the return address in
* ecx (note that ecx gets whacked), and saves the registers. This is probably the most
* common patch. */
t_memorypatch *mp_initialize_useful(void *address, void *call_function, int length)
{
t_memorypatch *newpatch = mp_initialize(address, call_function, length);
newpatch->preserve_original = TRUE;
newpatch->preserve_registers = TRUE;
newpatch->return_register = ECX;
return newpatch;
}
void mp_destroy(t_memorypatch *patch)
{
if(patch)
{
if(is_applied(patch))
mp_remove(patch);
pl_destroy(patch->parameters);
buffer_destroy(patch->original);
buffer_destroy(patch->patch);
buffer_destroy(patch->wrapper);
memset(patch, 0, sizeof(patch));
free(patch);
}
}
void mp_set_preserve_original(t_memorypatch *patch, BOOL preserve_original)
{
patch->preserve_original = preserve_original;
}
void mp_set_preserve_registers(t_memorypatch *patch, BOOL preserve_registers)
{
patch->preserve_registers = preserve_registers;
}
void mp_set_return_register(t_memorypatch *patch, t_register return_register)
{
patch->return_register = return_register;
}
void mp_add_register_parameter(t_memorypatch *patch, t_register parameter)
{
pl_add_register(patch->parameters, parameter);
}
void mp_add_memoryoffset_parameter(t_memorypatch *patch, t_register parameter, char offset)
{
pl_add_memoryoffset(patch->parameters, parameter, offset);
}
void mp_add_pointeroffset_parameter(t_memorypatch *patch, t_register baseregister, t_register tempregister, char offset)
{
pl_add_pointeroffset(patch->parameters, baseregister, tempregister, offset);
}
void mp_add_custom_parameter(t_memorypatch *patch, char *patch_string, int patch_length)
{
pl_add_custom(patch->parameters, patch_string, patch_length);
}
BOOL mp_apply(t_memorypatch *patch)
{
char *original;
HANDLE hProcess = GetCurrentProcess();
char call_buffer[5];
BOOL success = FALSE;
log_add("Applying patch");
log_indent();
if(patch && !patch->is_applied)
{
/* Back up the original data */
original = malloc(sizeof(char) * patch->length + 1);
ReadProcessMemory(hProcess, patch->address, original, patch->length, NULL);
buffer_clear(patch->original);
buffer_insert_bytes(patch->original, original, patch->length);
free(original);
/* Create the wrapper. The contents of the wrapper depends on which varibles
* are set, but the maximum wrapper will do the following:
* - Save the return address (pop [reg])
* - Run the original code ([varies])
* - Preserve registers (pushad)
* - Call the function (call [func])
* - Restore registers (popad)
* - Restore the return address (push [reg])
* - Return (ret) */
buffer_clear(patch->wrapper);
/* Pop the return address, if applicable. */
if(patch->return_register != NO_REGISTER)
buffer_insert_byte(patch->wrapper, asm_pop(patch->return_register));
/* Insert the original code, if applicable. */
if(patch->preserve_original)
buffer_insert_buffer(patch->wrapper, patch->original);
/* Preserve all registers, if applicable. */
if(patch->preserve_registers)
{
buffer_insert_byte(patch->wrapper, asm_pushad());
buffer_insert_byte(patch->wrapper, asm_pushfd());
}
/* Push the parameters, if applicable. */
pl_add_pushes(patch->parameters, patch->wrapper);
/* Call the actual function. Also allocate enough space so that the buffer isn't
* re-allocated. */
buffer_allocate(patch->wrapper, 1024);
buffer_insert_bytes(patch->wrapper, asm_call(buffer_gettipaddress(patch->wrapper), patch->call_function, call_buffer), 5);
/* Restore all registers, if applicable. */
if(patch->preserve_registers)
{
buffer_insert_byte(patch->wrapper, asm_popfd());
buffer_insert_byte(patch->wrapper, asm_popad());
}
/* Restore the return address, if applicable. */
if(patch->return_register != NO_REGISTER)
buffer_insert_byte(patch->wrapper, asm_push(patch->return_register));
/* Finally, return. */
buffer_insert_byte(patch->wrapper, asm_ret());
/* Create the patch. */
buffer_clear(patch->patch);
buffer_allocate(patch->patch, 256);
buffer_insert_bytes(patch->patch, asm_call(patch->address, buffer_get_cstring(patch->wrapper), call_buffer), 5);
/* Pad the patch up to the proper length. */
while(buffer_get_length(patch->patch) < patch->length)
buffer_insert_byte(patch->patch, asm_nop());
/* Can be uncommented for debugging: */
mp_print(patch);
/* Apply the patch. */
success = WriteProcessMemory(GetCurrentProcess(), patch->address, buffer_get_cstring(patch->patch), patch->length, NULL);
/* Set the patch to applied. */
patch->is_applied = success;
}
if(success)
log_add("--> Patch Successful!");
else
log_add("--> Patch Failed!");
log_undent();
return success;
}
void mp_remove(t_memorypatch *patch)
{
if(patch && patch->is_applied)
{
/* Restore the original memory. */
WriteProcessMemory(GetCurrentProcess(), patch->address, buffer_get_cstring(patch->original), patch->length, NULL);
/* Clear the buffers. */
buffer_clear(patch->original);
buffer_clear(patch->wrapper);
buffer_clear(patch->patch);
patch->is_applied = FALSE;
}
}
void mp_print(t_memorypatch *patch)
{
if(patch)
{
log_add("Address: %p", patch->address);
log_add("Length: %d bytes", patch->length);
log_add("Call function: %p", patch->call_function);
log_add("Preserve original: %d", patch->preserve_original);
log_add("Preserve registers: %d", patch->preserve_registers);
log_add("Return register: %s", t_register_list[patch->return_register]);
log_add("Original code (if applicable): ");
log_indent();
buffer_print(patch->original);
log_undent();
log_add("Parameters:");
log_indent();
pl_print(patch->parameters);
log_undent();
}
}
BOOL is_applied(t_memorypatch *patch)
{
return patch && patch->is_applied;
}
|
C
|
int main() {
if (1 == 1) printf("Hello world");
return 0;
}
// Some local changes
// More local changes. This time, don't rebase on merging.
// Third local changes
int newFeature() {
doSomethingAwesome();
doSomethingEvenBetter();
return 0; // Bug fix!
}
int secondNewFeature() {
firstLine();
secondLine();
return 3.14;
}
// ALL THESE LINES WERE DELETED
// EDIT THIS RIGHT HERE
// THE THIRD UPDATE TO main.c
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/time.h>
int int_compare(void const *a, void const *b){
return (*((int *) a) - *((int *) b));
}
void swap(int *a, int *b){
int temp = *a;
*a = *b;
*b = temp;
}
int testSorted(int arr[], int n){
int i;
for(i = 1; i < n; i++){
if(arr[i] < arr[i - 1])
return 0;
}
return 1;
}
void printArray(int arr[], int n){
int i;
printf("\n");
for(i = 0; i < n; i++){
printf("%d ", arr[i]);
}
printf("\n");
}
void sort3way(int a[], int l, int r) {
if (r <= l) return;
int i = l-1, j = r;
int p = l-1, q = r;
while(1){
while (a[++i] < a[r]);
while (a[r] < a[--j]) if (j == l) break;
if (i >= j) break;
swap(&a[i], &a[j]);
if (a[i]==a[r]) swap(&a[++p], &a[i]);
if (a[j]==a[r]) swap(&a[--q], &a[j]);
}
swap(&a[i], &a[r]);
j = i - 1;
i = i + 1;
for (int k = l ; k <= p; k++) swap(&a[k], &a[j--]);
for (int k = r-1; k >= q; k--) swap(&a[k], &a[i++]);
sort3way(a, l, j);
sort3way(a, i, r);
}
void main(){
int n;
double elapsed;
struct timeval start, stop;
//input size
printf("Enter n: ");
scanf("%d", &n);
//randomize array
srand(time(NULL));
int arr1[n];
int arr2[n];
int i;
for(i = 0; i < n; i++){
arr1[i] = 1 + rand() % 10;
arr2[i] = arr1[i];
}
//using qsort
gettimeofday(&start, NULL);
qsort(arr1, n, sizeof(int), int_compare);
gettimeofday(&stop, NULL);
printf("\nCheck: ");
if(testSorted(arr1, n)){
printf("%s\n", "true");
}
else{
printf("%s\n", "false");
}
elapsed = (double)(stop.tv_usec - start.tv_usec)/1000000 + (double)(stop.tv_sec - start.tv_sec);
printf("time: %f\n", elapsed);
//using handmade qsort
gettimeofday(&start, NULL);
sort3way(arr2, 0, n - 1);
gettimeofday(&stop, NULL);
printf("\nCheck handmade: ");
if(testSorted(arr2, n)){
printf("%s\n", "true");
}
else{
printf("%s\n", "false");
}
elapsed = (double)(stop.tv_usec - start.tv_usec)/1000000 + (double)(stop.tv_sec - start.tv_sec);
printf("time: %f\n", elapsed);
}
|
C
|
#include <stdio.h>
int main(){
int n, x, intervalo=0;
scanf("%d", &n);
for(int i=0; i<n; i++){
scanf("%d", &x);
if(x>=10 && x<=20) intervalo++;
}
printf("%d in\n%d out\n", intervalo, n-intervalo);
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* fillit.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: vportell <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/10/31 08:02:33 by vportell #+# #+# */
/* Updated: 2016/11/13 12:09:05 by vportell ### ########.fr */
/* */
/* ************************************************************************** */
#include "fillit.h"
int error_message(int n)
{
if (n != 2)
ft_putstr("usage: ./fillit [ file ]\n");
else
ft_putstr("error\n");
return (0);
}
int free_memory(t_piece *piece)
{
t_piece *temp;
while (piece)
{
temp = piece->next;
free(piece->x);
free(piece->y);
free(piece);
piece = temp;
}
return (0);
}
int main(int ac, char **av)
{
t_piece *pieces;
char **board;
unsigned int done;
unsigned int size;
if (ac != 2 || !parse_nodes(&pieces, av[1]))
return (error_message(ac));
done = 0;
pieces = ft_piece_to_letter(pieces, av[1], 0);
size = give_size(pieces);
while (!done)
{
board = build_plan(size);
done = solve(size, 0, board, &pieces);
if (!done)
size++;
}
delete_piece(&pieces, &delete_one_piece);
print_plan(board, size);
return (0);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
int year=2021,month=5,day=26,days=0,first,d,i,j,n;
int a[12]={31,28,31,30,31,30,31,31,30,31,30,31};
printf("%dԪΪ%d\n",year,date(year));
first=date(year);
switch(month)
{
case 1: days=day;break;
case 2: days=31+day;break;
case 3: days=31+28+day;break;
case 4: days=31+28+31+day;break;
case 5: days=31+28+31+30+day;break;
case 6: days=31+28+31+30+31+day;break;
case 7: days=31+28+31+30+31+30+day;break;
case 8: days=31+28+31+30+31+30+31+day;break;
case 9: days=31+28+31+30+31+30+31+30+day;break;
case 10:days=31+28+31+30+31+30+31+30+31+day;break;
case 11:days=31+28+31+30+31+30+31+30+31+30+day;break;
case 12:days=31+28+31+30+31+30+31+30+31+30+31+day;break;
}
if(run(year)&&month>2)
days++;
printf("%d %d %d չ %d \n",year,month,day,days);
if((first+days%7-1)<7)
d=first+days%7-1;
else
{
if((first+days%7-1)%7!=0)
d=(first-1+days%7)%7;
else
d=7;
}
printf("%d\n",d);
for(i=0;i<12;i++)
{
printf("Num %d \n",i+1);
printf("\tһ\t\t\t\t\t\n");
n=1;
for(j=0;;j++)
{
if(j<first)
printf("\t");
else
{
printf("%d\t",n);
n++,first++;
if(first>6)
first=0,printf("\n");
if(n>a[i])
break;
}
}
printf("\n");
printf("\n");
}
return 0;
}
int run(int year)
{
if(year%100!=0&&year%4==0 || year%400==0)
return 1;
else
return 0;
}
int date(int year)
{
int date=1,i;
for(i=1900;i<year;i++)
{
if(run(i))
date+=2;
else
date++;
}
if(date>7)
if(date%7!=0)
return date=date%7;
else
return date=7;
else
return date;
}
|
C
|
/*
* File: main.c
*
* Test driver to exercise some sorting code
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "bubblesort.h"
#include "heapsort.h"
#include "insertionsort.h"
#include "mergesort.h"
#include "quicksort.h"
#ifndef TRUE
# define TRUE 1
#endif
#ifndef FALSE
# define FALSE 0
#endif
char *ProgramName;
#define USAGE_STRING "[-h] [-i] [-o offset] [-r range] [-s size] [-u] [-v]"
/* control strings for colored text output: */
#define DEFAULT_COLOR_TEXT "\033[0m" /* goes back to shell default color */
#define RED_COLOR_TEXT "\033[1;31m"
#define GREEN_COLOR_TEXT "\033[1;32m"
#define TEST_SIZE 1024
#define TEST_DATA_RANGE 1024
static int arr_size = TEST_SIZE;
static int test_data_range = TEST_DATA_RANGE;
static int test_data_offset = 0;
static int be_quiet = TRUE;
/* UTILITY FUNCTIONS */
/* an structure to test with irregular objects: */
typedef struct {
int key; /* will sort on this key */
char crap[3];
float val;
} dummy_td;
dummy_td *funny_array = (dummy_td *)NULL;
static void
FillFunnyArray(int count)
{
int i;
for (i=0; i<count; i++) {
funny_array[i].key = (rand() % test_data_range) - test_data_offset;
funny_array[i].crap[0] = i;
funny_array[i].crap[1] = i+1;
funny_array[i].crap[2] = i+2;
funny_array[i].val = (float)i * (float)(test_data_range-test_data_offset);
}
}
/* test function, prints out an array of my irregular structures */
static void
PrintFunnyArray(dummy_td array[], int size, int verbose)
{
int i;
if (verbose) {
for (i=0; i<size; i++) {
fprintf(stdout,"\tkey = %d, crap = %02x %02x %02x, val = %f\n",
array[i].key, array[i].crap[0], array[i].crap[1], array[i].crap[2], array[i].val);
}
} else {
fprintf(stdout,"\t");
for (i=0; i<size; i++) {
fprintf(stdout,"%d ", array[i].key);
}
fprintf(stdout,"\n");
}
}
/* compare my irregular structures */
int funny_compare(const void *a, const void *b)
{
dummy_td *ad, *bd;
ad = (dummy_td *) a;
bd = (dummy_td *) b;
if (ad->key < bd->key)
return (-1);
else if (ad->key > bd->key)
return (1);
else
return (0);
}
/* Function to print an array */
static void
printArray(int A[], int size)
{
int i;
for (i=0; i < size; i++)
fprintf(stdout,"%d ", A[i]);
fprintf(stdout,"\n");
}
/* see if 2 arrays of integers are the same (to validate sort) */
static int
compareArray(int a[], int b[], int size)
{
int i, retval = TRUE;
for (i=0; i<size && retval; i++) {
if (a[i] != b[i])
retval = FALSE;
}
return(retval);
}
/* comparison routine to pass to sort algorithms which use the stdlib format */
static int
my_int_compare(const void *a, const void *b)
{
int ai, bi;
ai = * ((int *) a);
bi = * ((int *) b);
if (ai < bi)
return (-1);
else if (ai > bi)
return (1);
else
return (0);
}
/* tests the *SortINT() versions of the functions */
static void
testINTsorts(int tarr[], int arr[], int gold_arr[], int arr_size)
{
clock_t begin, end;
float elapsed;
int i;
/* macro to minimize repeated code...
* uses macro-fu to pass the parameter that is the sort routine to call,
* as well as the text label in the fpritnf reporting on that sort
*/
#define TEST_SORT(a) \
{ \
int alen = strlen(""#a""); \
char *ac = (alen > 15) ? " " : "\t "; \
for (i=0; i<arr_size; i++) { arr[i] = tarr[i]; } \
begin = clock(); \
a(arr, arr_size); \
end = clock(); \
elapsed = (double)(end - begin) / CLOCKS_PER_SEC; \
if (compareArray(gold_arr, arr, arr_size)) { \
fprintf(stdout,"%s : %s()\t%ssort is %s%s%s\t took %lf seconds.\n", \
ProgramName,""#a"",ac,GREEN_COLOR_TEXT,"CORRECT",DEFAULT_COLOR_TEXT,elapsed); \
} else { \
fprintf(stdout,"%s : %s()\t%ssort is %s%s%s\t took %lf seconds.\n", \
ProgramName,""#a"",ac,RED_COLOR_TEXT,"INCORRECT",DEFAULT_COLOR_TEXT,elapsed); } }
TEST_SORT(BubbleSortINT);
TEST_SORT(HeapSortINT);
TEST_SORT(InsertionSortINT);
TEST_SORT(MergeSortINT);
TEST_SORT(QuickSortINT);
#undef TEST_SORT
}
/*
* main routine.
*
*/
int
main(int argc, char *argv[])
{
clock_t begin, end;
time_t t;
float elapsed;
int i, *tarr, *arr, *gold_arr;
int use_int = FALSE, use_funny = FALSE;
ProgramName = (char *) malloc(strlen(argv[0])+1);
strcpy(ProgramName, argv[0]);
srand((unsigned) time(&t)); /* seed rand() */
/* check for any program arguments: */
while ((argc > 1) && (argv[1][0] == '-')) {
switch(argv[1][1]) {
case 'h':
fprintf(stderr,"%s : %s\n",ProgramName,USAGE_STRING);
exit(EXIT_SUCCESS);
break;
case 'i': /* also run the *SortINT() tests */
use_int = TRUE;
break;
case 'u':
use_funny = TRUE; /* also test the array of structure test */
break;
case 'o':
test_data_offset = atoi(argv[2]);
argc--;
argv++;
break;
case 'v':
be_quiet = FALSE; /* verbose, more output, useful for small tests */
break;
case 'r':
test_data_range = atoi(argv[2]);
argc--;
argv++;
break;
case 's':
arr_size = atoi(argv[2]);
argc--;
argv++;
break;
default:
fprintf(stderr,"%s : %s : program option [%s] not recognized. Ignored. (File %s, line %d)\n",
ProgramName,"WARNING",argv[1],__FILE__,__LINE__);
fprintf(stderr,"%s : %s\n",ProgramName,USAGE_STRING);
break;
}
argc--;
argv++;
}
/* initialize some test data, run qsort() to generate golden output */
funny_array = (dummy_td *) malloc(arr_size*sizeof(dummy_td));
arr = (int *) malloc(arr_size*sizeof(int));
tarr = (int *) malloc(arr_size*sizeof(int));
gold_arr = (int *) malloc(arr_size*sizeof(int));
fprintf(stdout,"\n%s : Sort Suite algorithm comparison (array of %d integers):\n",ProgramName,arr_size);
fprintf(stdout,"---------------------------------------------------------------\n");
for (i=0; i<arr_size; i++) { tarr[i] = (rand() % test_data_range)-test_data_offset; }
for (i=0; i<arr_size; i++) { gold_arr[i] = tarr[i]; }
if (!be_quiet) {
fprintf(stdout,"%s : Test input array is:\n\t",ProgramName);
printArray(gold_arr, arr_size);
}
begin = clock();
qsort(gold_arr, arr_size, sizeof(int), my_int_compare);
end = clock();
elapsed = (double)(end - begin) / CLOCKS_PER_SEC;
if (!be_quiet) {
fprintf(stdout,"%s : Correct Sorted array is:\n\t",ProgramName);
printArray(gold_arr, arr_size);
fprintf(stdout,"\n");
fprintf(stdout,"%s : %s\t\t sort is %s%s%s\t took %lf seconds.\n",
ProgramName,"qsort() (stdlib)",GREEN_COLOR_TEXT,"CORRECT",DEFAULT_COLOR_TEXT,elapsed);
}
/* macro to minimize repeated code...
* uses macro-fu to pass the parameter that is the sort routine to call,
* as well as the text label in the fprintf reporting on that sort
*/
#define TEST_SORT(a) \
{ \
int alen = strlen(""#a""); \
char *ac = (alen < 8) ? "\t " : " "; \
for (i=0; i<arr_size; i++) { arr[i] = tarr[i]; } \
begin = clock(); \
a((void *) &(arr[0]), arr_size, sizeof(int), my_int_compare); \
end = clock(); \
elapsed = (double)(end - begin) / CLOCKS_PER_SEC; \
if (compareArray(gold_arr, arr, arr_size)) { \
fprintf(stdout,"%s : %s()\t\t%ssort is %s%s%s\t took %lf seconds.\n", \
ProgramName,""#a"",ac,GREEN_COLOR_TEXT,"CORRECT",DEFAULT_COLOR_TEXT,elapsed); \
} else { \
fprintf(stdout,"%s : %s()\t\t%ssort is %s%s%s\t took %lf seconds.\n", \
ProgramName,""#a"",ac,RED_COLOR_TEXT,"INCORRECT",DEFAULT_COLOR_TEXT,elapsed); } }
TEST_SORT(BubbleSort);
TEST_SORT(heapsort); /* stdlib version */
TEST_SORT(HeapSort);
TEST_SORT(InsertionSort);
TEST_SORT(mergesort); /* stdlib version */
TEST_SORT(MergeSort);
TEST_SORT(qsort); /* stdlib version */
TEST_SORT(QuickSort);
#undef TEST_SORT
if (use_int) {
testINTsorts(tarr, arr, gold_arr, arr_size);
}
if (use_funny) {
/* test array of structure data sort */
FillFunnyArray(arr_size);
if (!be_quiet) {
fprintf(stdout,"\nTest QuickSort() with structure data:\n");
fprintf(stdout,"\tTest input structure array sort keys are:\n\t");
PrintFunnyArray(funny_array, arr_size, 0);
}
begin = clock();
QuickSort((void *) &(funny_array[0]), arr_size, sizeof(dummy_td), funny_compare);
end = clock();
elapsed = (double)(end - begin) / CLOCKS_PER_SEC;
if (!be_quiet) {
fprintf(stdout,"\n\tSorted structure array sort keys are:\n\t");
PrintFunnyArray(funny_array, arr_size, 0);
}
fprintf(stderr,"%s : %s() of structure array took %lf seconds.\n\n",
ProgramName,"QuickSort",elapsed);
}
fprintf(stdout,"\n");
exit(EXIT_SUCCESS);
}
|
C
|
#include <stdio.h>
void gt(int n)
{
int i, gt = 1;
for (i = 1;i <= n;i ++)
{
gt = gt*i;
}
printf("giai thua cua %d:%d",n,gt);
}
|
C
|
/*
------------------------------------------------------
@copyright Luiz Paulo Rabachini @file: lista_dup_enc.h
Release: 1.4 - Updated: 20/04/2010
------------------------------------------------------
Resume: Header do arquivo lista_dup_enc.c
------------------------------------------------------
*/
typedef struct Reg No;
// Definio da estrutura de cada N
struct Reg
{
int info;
No *ant;
No *prox;
};
// Definio do TAD Lista
typedef struct
{
No *prim;
No *ult;
} Lista;
// Escopos das funes
void Start(Lista *L);
void Menu(Lista *L);
short Insert(int Set, Lista *L, int Info);
short Remove(Lista *L,int Info);
int Search(int Set, No **Elem, Lista *L, int Info);
void Print(Lista *L);
void CAux(int *Aux);
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char *argv[]){
if (argc != 2) {
fprintf(stderr, "need year argument");
exit(1);
}
int c = atoi(argv[1]);
if((c%400==0) || ((c%4==0)&&(c%100!=0))){
printf("is a leap year!");
}else{
printf("is not a leap year!");
}
}
|
C
|
/****************************************************************************************
* ļSPLINE.H
* ܣβɳͷļ
* ߣܱ
* ڣ2003.09.09
****************************************************************************************/
#ifndef SPLINE_H
#define SPLINE_H
/* غ */
#define NPMAX 10 /* */
typedef struct
{
float Px[NPMAX];
float Py[NPMAX];
float Ax[NPMAX]; // ָABCָ
float Ay[NPMAX];
float Bx[NPMAX];
float By[NPMAX];
float Cx[NPMAX];
float Cy[NPMAX];
float Mat[3][NPMAX];
int Np; // ߵ
} SPLINE;
/****************************************************************************
* ƣSPLINE_Spline()
* ܣ߳ʼ뵽߶С
* ڲsl Ҫ߶SPLINEṹ
* pt
* np
* ڲ
* ˵
****************************************************************************/
extern void SPLINE_SetSpline(SPLINE *sl, PointXY pt[], int np);
/****************************************************************************
* ƣSPLINE_Generate()
* ܣͼΡĸ˵㱣浽slĽṹڡ
* ڲsl Ҫ߶SPLINEṹ
* ڲ
* ˵slҪʹSPLINE_SetSpline()ø㡣
****************************************************************************/
extern void SPLINE_Generate(SPLINE *sl);
/****************************************************************************
* ƣSPLINE_GetCurveCount()
* ܣȡ϶˵ֵ
* ڲsl Ҫ߶SPLINEṹ
* ڲֵ߸˵
* ˵slҪʹSPLINE_SetSpline()ø㡣
****************************************************************************/
extern int SPLINE_GetCurveCount(SPLINE *sl);
/****************************************************************************
* ƣSPLINE_GetCurve()
* ܣȡϸ˵㣬ԱʹGUI_Line()ߡ
* ڲsl Ҫ߶SPLINEṹ
* points ڽߵĻPointXY
* PointCount ڽߵָ
* ڲ
* ˵ߵpointsأߵPointCountأ
* slҪʹSPLINE_SetSpline()ø㡣
****************************************************************************/
extern void SPLINE_GetCurve(SPLINE *sl, PointXY points[], int *PointCount);
/****************************************************************************
* ƣGUI_Spline()
* ܣ(3)ߡ
* ڲppoints
* no ĸ
* ڲ
****************************************************************************/
extern void GUI_Spline(PointXY points[], int no, TCOLOR color);
#endif
|
C
|
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
////////// begin ADT ////////////
struct vec
{
float *val;
};
typedef struct vec *Vector;
Vector adt_createVector(int dim)
{
Vector a= (Vector) malloc(sizeof(struct vec));
a->val = (float*)malloc(dim*sizeof(float));
return a;
}
void adt_loadVector(Vector vec, int dim)
{
float tmp;
int i;
for (i=0;i<dim;i++)
{
scanf("%f", &tmp);
vec->val[i]=tmp;
}
}
Vector adt_addVector(Vector vec1, Vector vec2, int dim)
{
int i;
for (i=0;i<dim;i++)
vec1->val[i]+=vec2->val[i];
return vec1;
}
float adt_normVector(Vector vec, int dim)
{
float sum=0;
int i;
for (i=0;i<dim;i++)
sum+=(vec->val[i])*(vec->val[i]);
sum=sqrt(sum);
return sum;
}
Vector adt_scaleVector(Vector vec, float norm, int dim)
{
int i;
for (i=0;i<dim;i++)
vec->val[i] *= norm;
return vec;
}
///////// end of ADT //////////
int main() {
/* Function names starting with adt_ are from the vector ADT */
/* Get vector dimension from stdin */
int dim;
scanf("%d", &dim);
float norm2;
/* Create the empty vectors */
Vector vec1 = adt_createVector(dim);
Vector vec2 = adt_createVector(dim);
Vector vec3 = adt_createVector(dim);
Vector vec4 = adt_createVector(dim);
/* Populate the vectors from stdin */
adt_loadVector(vec1,dim);
adt_loadVector(vec2,dim);
/* perform operations */
vec3 = adt_addVector(vec1,vec2,dim);
norm2 = adt_normVector(vec2,dim);
vec4 = adt_scaleVector(vec3,norm2,dim);
/* Display the result */
int i;
for (i=0;i<dim;i++)
printf("%.2f ", vec4->val[i]);
return 0;
}
|
C
|
/*************************************************************************
> File Name: mywho.c
> Author: weijie.yuan
> Mail:
> Created Time: Tue 02 Aug 2016 04:07:26 PM CST
************************************************************************/
#include <stdio.h>
#include "mywho.h"
#include <utmp.h>
#include <time.h>
/* var/run/utmp /var/log/wtmp */
int mywho()
{
struct utmp *um;
/* option q, count all login names and number of users logged on */
if (opt_q)
{
int users = 0;
/* open utmp file */
while ((um = getutent()))
{
/* get user process */
if(um->ut_type != USER_PROCESS)
continue;
printf("%s ",um->ut_user);
users += 1;
}
printf("\n# users=%d\n",users);
/* close utmp file */
endutent();
return 0;
}
/* print line of column headings */
if (opt_H)
printf("%-12s%-12s%-20.20s %s\n","NAME","LINE","TIME","COMMENT");
/* time of last system boot */
if (opt_b)
{
int n = 0;
time_t tm;
char timebuf[24];
utmpname(_PATH_WTMP);//set wtmp path
/* open wtmp file */
while ((um = getutent()))
{
/* get boot time */
if(um->ut_type != BOOT_TIME)
continue;
n++;
}
setutent();// read from head
while (n--)
{
um = getutent();
if (um->ut_type != BOOT_TIME)
{
n++;
continue;
}
}
tm = (time_t)(um->ut_tv.tv_sec);
strftime(timebuf,24,"%F %R",localtime(&tm));
printf("system boot %-20.20s\n",timebuf);
/* close wtmp file */
endutent();
return 0;
}
/* no option,open utmp */
while ((um = getutent()))
{
if(um->ut_type != USER_PROCESS)
continue;
time_t tm;
char timebuf[24];
tm = (time_t)(um->ut_tv.tv_sec);
strftime(timebuf,24,"%F %R",localtime(&tm));
printf("%-12s%-12s%-20.20s (%s)\n",um->ut_user,um->ut_line,timebuf,um->ut_host);
}
endutent();
return 0;
}
|
C
|
///scan ch from the user display that char & its ASCII nu if small if not small then say propar input enter
#include<stdio.h>
main()
{
char ch;
abc:printf("Enter the Char.....\n");
scanf("%c",&ch);
if(ch>=97 && ch<=122)
{
printf("ch...%c and it's ASCII...%d\n",ch,ch);
}
else
{
goto abc;
}
printf("thanks.....\n");
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
/**
* * Reverse a single byte
* *
* * this was adapted from the example at
* * http://graphics.stanford.edu/~seander/bithacks.html#BitReverseObvious
* */
uint8_t reverse_byte (uint8_t byte ///< byte to reverse
)
{
uint8_t v=byte;
uint8_t r=v ; // local storage for building the byte
uint8_t s = sizeof(v) * 8 - 1; // extra shift needed at end
for (v >>= 1; v; v >>= 1) {
r <<= 1;
r |= v & 1;
s--;
}
r <<= s; // shift when v's highest bits are zero
return r;
}
int main(void){
int i ;
uint8_t cola,colb,rev;
printf("static unsigned char __attribute__ ((progmem)) columna_lookup[] = {\n\t");
for(i=0;i<16;i++){
cola = ~(1<<(15-i)>>8);
printf("0x%2x,",cola);
}
printf("\n};\n\n");
printf("static unsigned char __attribute__ ((progmem)) columnb_lookup[] = {\n\t");
for(i=0;i<16;i++){
colb = ~(1<<(i) >> 8);
printf("0x%x,",colb);
}
printf("\n};\n");
printf("static unsigned char __attribute__ ((progmem)) reverse_lookup[] = {");
for(i=0;i<256;i++){
if (i%16==0){
printf("\n\t");
}
rev = reverse_byte(i);
printf("0x%02x,",rev);
}
printf("\n};\n");
return 0;
}
|
C
|
#include<stdio.h>
int main()
{ //convert a number desimal to octaol
int a, b, c, d, e, f, g, h, i, j, x;
scanf("%d", &x);
a = x / 8;
b = x % 8;
c = a / 8;
d = a % 8;
e = c / 8;
f = c % 8;
g = e / 8;
h = e % 8;
i = g / 8;
j = g % 8;
printf("%d%d%d%d%d",j,h,f,d,b);
return 0;
}
|
C
|
#include<stdio.h>
int main(void)
{ int March = 3;
int April = 4;
int year;
int EasterDate;
int a;
int b;
int c;
int d;
int e;
int f;
int g;
int h;
int i;
int k;
int l;
int m;
int p;
int EasterMonth;
printf("Enter Year: ");
scanf("%d", &year);
a=year%19;
b=year/100;
c=year%100;
d=b/4;
e=b%4;
f=(b+8)/25;
g=(b-f+1)/3;
h=(19*a+b-d-g+15)%30;
i=c/4;
k=c%4;
l=(32+2*e+2*i-h-k)%7;
m=(a+11*h+22*l)/451;
EasterMonth =(h+l-7*m+114)/31;
p=(h+l-7*m+114)%31;
EasterDate=p+1;
if(EasterMonth==3){
printf("Easter is March %d in %d.\n",EasterDate,year);}
if (EasterMonth==4){printf("Easter is April %d in %d.\n",EasterDate,year);}
return 0;
}
|
C
|
/*
Zapoj ATmega8 s krystalom 4MHz (2x keramicky kondenzator 22[p/n ???],
1x elektrolyticky kondenzator 47uF medzi napajanie +/-).
Port C (PC0 az PC3) pripoj na 4056BE (piny 2 az 5, pozor na poradie!).
Ku 4056BE pripoj 7-segmentovy display.
*/
#define F_CPU 4000000UL
#include <avr/io.h>
#include <util/delay.h>
#include <avr/interrupt.h>
// char input = 0x00;
// int interrupt = 0;
char i = 0;
ISR (INT0_vect)
{
// input = PIND;
// interrupt = 1;
if ((PIND & 0x01) == 1)
i++;
else
i--;
if (i > 9)
i = 0;
if (i < 0)
i = 9;
PORTC = i;
}
int main(void)
{
// char A, B;
// Global Interrupt enabled
sei();
// Status Register
// SREG |= (1 << I);
// General Interrupt Control Register - INT0 enable
GICR |= (1 << INT0);
// MCU Control Register
//
// 7 6 5 4 3 2 1 0
// SE SM2 SM1 SM0 ISC11 ISC10 ISC01 ISC00
//
// 0 0 - The low level of INT0 generates an interrupt request.
// 0 1 - Any logical change on INT0 generates an interrupt request.
// 1 0 - The falling edge of INT0 generates an interrupt request.
// 1 1 - The rising edge of INT0 generates an interrupt request.
MCUCR |= (1 << ISC01);
MCUCR &= ~(1 << ISC00);
// Data Direction Register C - set as output
DDRC = 0x0F;
// Data Direction Register D - set as input
DDRD = 0x00;
while (1)
{
// if (interrupt == 1)
// {
// A = (input & 0x08) >> 3;
// B = (input & 0x01) >> 0;
// if ((B == 0) && (A == 1)) i++;
// if ((B == 1) && (A == 0)) i++;
// if ((B == 1) && (A == 1)) i--;
// if ((B == 0) && (A == 0)) i--;
// interrupt = 0;
// }
// ak prisiel pulz ...
// if ((input & 0x01) == 0)
// {
// // ak tocim do jednej strany ...
// if ((input & 0x02) == 0)
// i--;
// else
// i++;
// }
// i = (input & 0x03);
// _delay_ms(2);
}
return 0;
}
|
C
|
#include <sys/types.h> /* 定义数据类型,如 ssize_t,off_t 等 */
#include <fcntl.h> /* 定义 open,creat 等函数原型,创建文件权限的符号常量 S_IRUSR 等 */
#include <unistd.h> /* 定义 read,write,close,lseek 等函数原型 */
#include <errno.h> /* 与全局变量 errno 相关的定义 */
#include <stdio.h>
int main(int argc, char *argv[])
{
char sz_filename[] = "hello.txt"; /* 要打开的文件 */
int fd = -1;
int mode = 0x664;
fd = open(sz_filename, O_WRONLY | O_CREAT, mode); /* 权限模式 mode=0x664 */
/* 以只写、创建标志打开文件 */
if (fd < 0)
{
/*出错处理*/
printf("%d\n", fd);
}
printf("%d\n", close(fd));
}
|
C
|
/*Accept Character from user and check whether it is alphabet or not (A-Z a-z).
Input : F
Output : TRUE
Input : &
Output : FALSE*/
#include<stdio.h>
#include<conio.h>
#define TRUE 1
#define FALSE 0
typedef int BOOL;
BOOL ChkAlpha(char);
BOOL ChkAlpha(char ch)
{
if((ch>='A'&&ch<='Z')||(ch>='a'&&ch<='z'))
{
return 1;
}
return 0;
}
int main()
{
char cValue = '\0';
BOOL bRet = FALSE;
printf("\nEnter the character => ");
scanf("%c",&cValue);
bRet = ChkAlpha(cValue);
if(bRet == TRUE)
{
printf("\nIt is Character \n");
}
else
{
printf("\nIt is not a Character \n");
}
getch();
return 0;
}
|
C
|
#include <algorithm> // for min_element, max_element
double peconvert = 0.00502; // volts per photoelectrion
void doit(const char*);
void simplecosmics()
{
//doit("20150930-1720");
doit("20151009-1743");
}
void doit(const char *basename)
{
// --- read in the data and create a vector with all the values
// --- note that this code requires an duplicates to have already been cleaned out
// --- this is automatically fixed with the new version of the DAQ/stepper code
// --- but the user would do well do double check all output files anyway
//ifstream fin1("TEMP/20150930-1720_Unaveraged_VMin1.txt");
ifstream fin1(Form("TEMP/%s_Unaveraged_VMin1.txt",basename));
double content;
vector<double> voltage1;
while(fin1>>content)
{
voltage1.push_back(content);
}
fin1.close();
cout << voltage1.size() << endl;
// --- do the same for SiPM2
//ifstream fin2("TEMP/20150930-1720_Unaveraged_VMin2.txt");
ifstream fin2(Form("TEMP/%s_Unaveraged_VMin2.txt",basename));
vector<double> voltage2;
while(fin2>>content)
{
voltage2.push_back(content);
}
fin2.close();
cout << voltage2.size() << endl;
// --- get the number of entries and the min and max
int number = voltage1.size();
double max = *max_element(voltage1.begin(),voltage1.end());
double min = *min_element(voltage1.begin(),voltage1.end());
cout << max << endl;
cout << min << endl;
// --- use the min and max to calculate a range for the histogram
double newmax = min*-0.95;
double newmin = max*-1.05 - newmax*0.1;
// --- create the new histogram
const int nbins = 100;
TH1D *h1 = new TH1D("h1","",nbins,newmin,newmax);
TH1D *h2 = new TH1D("h2","",nbins,newmin,newmax);
TH1D *hsum = new TH1D("hsum","",nbins,2*newmin,2*newmax);
TH2D *hh1v2 = new TH2D("hh1v2","",nbins*2,newmin,newmax,nbins*2,newmin,newmax); // SiPM1 vs SiPM2
TH2D *hhSvA = new TH2D("hhSvA","",nbins*2,2*newmin,2*newmax,nbins*2,-1,1); // Sum vs Asymmetry
TH2D *hh1v2_cut1 = new TH2D("hh1v2_cut1","",nbins*2,newmin,newmax,nbins*2,newmin,newmax); // SiPM1 vs SiPM2
TH2D *hhSvA_cut1 = new TH2D("hhSvA_cut1","",nbins*2,2*newmin,2*newmax,nbins*2,-1,1); // Sum vs Asymmetry
TH2D *hh1v2_cut2 = new TH2D("hh1v2_cut2","",nbins*2,newmin,newmax,nbins*2,newmin,newmax); // SiPM1 vs SiPM2
TH2D *hhSvA_cut2 = new TH2D("hhSvA_cut2","",nbins*2,2*newmin,2*newmax,nbins*2,-1,1); // Sum vs Asymmetry
vector<double> sum;
vector<double> asym;
// --- loop over the vector to fill the histogram
for(int i=0; i<500; i++)
{
// --- SiPM1
h1->Fill(-voltage1[i]);
// --- SiPM2
h2->Fill(-voltage2[i]);
// --- SiPM1 vs SiPM2
hh1v2->Fill(-voltage1[i],-voltage2[i]);
// --- sum vs asymmetry
double tempsum = -voltage1[i] + -voltage2[i];
double tempasym = (voltage1[i] - voltage2[i]) / (-voltage1[i] + -voltage2[i]);
hsum->Fill(tempsum);
hhSvA->Fill(tempsum,tempasym);
sum.push_back(tempsum);
asym.push_back(tempasym);
// --- now do some cuts...
if(fabs(tempasym)<0.4)
{
hh1v2_cut1->Fill(-voltage1[i],-voltage2[i]);
hhSvA_cut1->Fill(tempsum,tempasym);
}
if((voltage1[i]<(voltage2[i]+20*peconvert))&&(voltage2[i]<(voltage1[i]+20*peconvert)))
{
hh1v2_cut2->Fill(-voltage1[i],-voltage2[i]);
hhSvA_cut2->Fill(tempsum,tempasym);
}
}
// --- make a canvas and draw the histogram
TCanvas *c1 = new TCanvas("c1","",800,600);
// --- rescale the histograms from volts to photoelectrons
h1->GetXaxis()->SetLimits(newmin/peconvert,newmax/peconvert);
h1->GetXaxis()->SetTitle("Number of photoelectrons");
h1->GetYaxis()->SetTitle("Counts");
// --- define Landau function and draw
// --- don't fit yet because the data have tons of ugly low voltage1 background
double height = 1049;
double mu = 23;
double sigma = 3;
//TF1 *fun = new TF1("fun","[0]*TMath::Landau(x,[1],[2])",newmin/peconvert,newmax/peconvert);
TF1 *fun = new TF1("fun","[0]*TMath::Landau(x,[1],[2])",2*newmin/peconvert,2*newmax/peconvert);
fun->SetParameter(0,height);
fun->SetParameter(1,mu);
fun->SetParameter(2,sigma);
double bgscale = 650; // guess...
c1->SetLogy(0);
c1->Clear();
hh1v2->Draw("colz");
hh1v2->GetXaxis()->SetLimits(newmin/peconvert,newmax/peconvert);
hh1v2->GetYaxis()->SetLimits(newmin/peconvert,newmax/peconvert);
hh1v2->GetXaxis()->SetTitle("#pe SiPM1");
hh1v2->GetYaxis()->SetTitle("#pe SiPM2");
c1->SetLogz(0);
c1->Print(Form("Cosmics/%s_cosmics_1v2.png",basename));
c1->Print(Form("Cosmics/%s_cosmics_1v2.pdf",basename));
c1->SetLogz(1);
c1->Print(Form("Cosmics/%s_cosmics_1v2_log.png",basename));
c1->Print(Form("Cosmics/%s_cosmics_1v2_log.pdf",basename));
hhSvA->Draw("colz");
hhSvA->GetXaxis()->SetLimits(2*newmin/peconvert,2*newmax/peconvert);
hhSvA->GetXaxis()->SetTitle("Sum");
hhSvA->GetYaxis()->SetTitle("Asymmetry");
c1->SetLogz(0);
c1->Print(Form("Cosmics/%s_cosmics_SvA.png",basename));
c1->Print(Form("Cosmics/%s_cosmics_SvA.pdf",basename));
c1->SetLogz(1);
c1->Print(Form("Cosmics/%s_cosmics_SvA_log.png",basename));
c1->Print(Form("Cosmics/%s_cosmics_SvA_log.pdf",basename));
// --- now for some cuts...
c1->SetLogz(0);
hh1v2_cut1->Draw("colz");
hh1v2_cut1->GetXaxis()->SetLimits(newmin/peconvert,newmax/peconvert);
hh1v2_cut1->GetYaxis()->SetLimits(newmin/peconvert,newmax/peconvert);
hh1v2_cut1->GetXaxis()->SetTitle("#pe SiPM1");
hh1v2_cut1->GetYaxis()->SetTitle("#pe SiPM2");
TLatex *tex1 = new TLatex(0.2,0.8,"|Asymmetry|<0.4");
tex1->SetTextSize(0.05);
tex1->SetNDC(kTRUE);
tex1->Draw();
c1->SetLogz(0);
c1->Print(Form("Cosmics/%s_cosmics_1v2_cut1.png",basename));
c1->Print(Form("Cosmics/%s_cosmics_1v2_cut1.pdf",basename));
c1->SetLogz(1);
c1->Print(Form("Cosmics/%s_cosmics_1v2_cut1_log.png",basename));
c1->Print(Form("Cosmics/%s_cosmics_1v2_cut1_log.pdf",basename));
hhSvA_cut1->Draw("colz");
hhSvA_cut1->GetXaxis()->SetLimits(2*newmin/peconvert,2*newmax/peconvert);
hhSvA_cut1->GetXaxis()->SetTitle("Sum");
hhSvA_cut1->GetYaxis()->SetTitle("Asymmetry");
tex1->Draw();
c1->SetLogz(0);
c1->Print(Form("Cosmics/%s_cosmics_SvA_cut1.png",basename));
c1->Print(Form("Cosmics/%s_cosmics_SvA_cut1.pdf",basename));
c1->SetLogz(1);
c1->Print(Form("Cosmics/%s_cosmics_SvA_cut1_log.png",basename));
c1->Print(Form("Cosmics/%s_cosmics_SvA_cut1_log.pdf",basename));
c1->SetLogz(0);
hh1v2_cut2->Draw("colz");
hh1v2_cut2->GetXaxis()->SetLimits(newmin/peconvert,newmax/peconvert);
hh1v2_cut2->GetYaxis()->SetLimits(newmin/peconvert,newmax/peconvert);
hh1v2_cut2->GetXaxis()->SetTitle("#pe SiPM1");
hh1v2_cut2->GetYaxis()->SetTitle("#pe SiPM2");
TLatex *tex2 = new TLatex(0.2,0.8,"SiPMA < SiPMB + 20");
tex2->SetTextSize(0.05);
tex2->SetNDC(kTRUE);
tex2->Draw();
c1->SetLogz(0);
c1->Print(Form("Cosmics/%s_cosmics_1v2_cut2.png",basename));
c1->Print(Form("Cosmics/%s_cosmics_1v2_cut2.pdf",basename));
c1->SetLogz(1);
c1->Print(Form("Cosmics/%s_cosmics_1v2_cut2_log.png",basename));
c1->Print(Form("Cosmics/%s_cosmics_1v2_cut2_log.pdf",basename));
hhSvA_cut2->Draw("colz");
hhSvA_cut2->GetXaxis()->SetLimits(2*newmin/peconvert,2*newmax/peconvert);
hhSvA_cut2->GetXaxis()->SetTitle("Sum");
hhSvA_cut2->GetYaxis()->SetTitle("Asymmetry");
tex2->Draw();
c1->SetLogz(0);
c1->Print(Form("Cosmics/%s_cosmics_SvA_cut2.png",basename));
c1->Print(Form("Cosmics/%s_cosmics_SvA_cut2.pdf",basename));
c1->SetLogz(1);
c1->Print(Form("Cosmics/%s_cosmics_SvA_cut2_log.png",basename));
c1->Print(Form("Cosmics/%s_cosmics_SvA_cut2_log.pdf",basename));
hsum->SetLineColor(kBlack);
hsum->SetLineWidth(2);
hsum->GetXaxis()->SetLimits(2*newmin/peconvert,2*newmax/peconvert);
hsum->GetXaxis()->SetRangeUser(0.0,160.0);
hsum->GetXaxis()->SetTitle("Number of photoelectrons SiPM1+SiPM2");
hsum->Draw();
c1->Print(Form("Cosmics/%s_temp.png",basename));
c1->Print(Form("Cosmics/%s_temp.pdf",basename));
hsum->SetMaximum(175);
c1->Print(Form("Cosmics/%s_templow.png",basename));
c1->Print(Form("Cosmics/%s_templow.pdf",basename));
c1->SetLogy();
hsum->SetMaximum(1.1*h1->GetBinContent(hsum->GetMaximumBin()));
c1->Print(Form("Cosmics/%s_templog.png",basename));
c1->Print(Form("Cosmics/%s_templog.pdf",basename));
bgscale = 100;
//hsum->Fit(fun,"","",20,60);
hsum->Fit(fun,"","",40,80);
fun->SetLineColor(kRed);
fun->SetLineWidth(2);
fun->Draw("same");
cout << fun->GetChisquare() << "/" << fun->GetNDF() << endl;
c1->SetLogy(0);
c1->Print(Form("Cosmics/%s_tempfit.png",basename));
c1->Print(Form("Cosmics/%s_tempfit.pdf",basename));
hsum->SetMaximum(175);
c1->Print(Form("Cosmics/%s_templowfit.png",basename));
c1->Print(Form("Cosmics/%s_templowfit.pdf",basename));
c1->SetLogy(1);
hsum->SetMaximum(1.1*h1->GetBinContent(hsum->GetMaximumBin()));
c1->Print(Form("Cosmics/%s_templogfit.png",basename));
c1->Print(Form("Cosmics/%s_templogfit.pdf",basename));
c1->Clear();
hsum->Draw();
double hax = fun->GetParameter(0);
double mux = fun->GetParameter(1);
double six = fun->GetParameter(2);
fun->SetParameter(0,0.95*hax);
fun->SetParameter(1,mux);
fun->SetParameter(2,1.1*six);
//fun->Draw("same");
//hsum->Fit(simplefun,"","",0,60);
TF1 *fun2 = new TF1("fun2","([0]/sqrt(6.28))*TMath::Exp(-0.5*((x-[1])/[2] + TMath::Exp(-(x-[1])/[2])))",0,250);
fun2->SetParameter(0,hax);
fun2->SetParameter(1,mux);
fun2->SetParameter(2,six);
//fun2->SetLineColor(kBlack);
//hsum->Fit(fun2,"","",15,60);
hsum->Fit(fun2,"","",30,120);
fun2->Draw("same");
cout << fun2->GetChisquare() << "/" << fun2->GetNDF() << endl;
double par1 = fun2->GetParameter(1);
TLine line(par1,0,par1,0.24*fun2->GetParameter(0));
line.Draw();
c1->SetLogy(0);
c1->Print(Form("Cosmics/%s_tempffit.png",basename));
c1->Print(Form("Cosmics/%s_tempffit.pdf",basename));
hsum->SetMaximum(175);
c1->Print(Form("Cosmics/%s_templowffit.png",basename));
c1->Print(Form("Cosmics/%s_templowffit.pdf",basename));
hsum->SetMaximum(25);
c1->Print(Form("Cosmics/%s_tempLOWffit.png",basename));
c1->Print(Form("Cosmics/%s_tempLOWffit.pdf",basename));
c1->SetLogy(1);
hsum->SetMaximum(1.1*h1->GetBinContent(hsum->GetMaximumBin()));
c1->Print(Form("Cosmics/%s_templogffit.png",basename));
c1->Print(Form("Cosmics/%s_templogffit.pdf",basename));
}
|
C
|
#include "binary_trees.h"
/**
* binary_tree_size - This finds the size of a binary tree by
* @tree: This is a pointer to the struct
* Return: fgd
*/
size_t binary_tree_size(const binary_tree_t *tree)
{
if (tree == NULL)
return (0);
return (binary_tree_size(tree->left) + 1 + binary_tree_size(tree->right));
}
|
C
|
#include <stdio.h>
#include <cs50.h>
#include <stdlib.h>
#include <string.h>
int main ()
{
FILE *miArchivo;
miArchivo = fopen ("datos.csv", "r");
char linea [40];
for (int z = 0; z < 3; z++)
{
fgets (linea, 40, miArchivo);
string nombres = strtok(linea, ",");
string apellidos = strtok(NULL, ",");
printf ("Estudiante %s %s\n", nombres, apellidos);
float nota [3];
float sum = 0;
int x = 3;
for (int i = 0; i < x; i++)
{
nota[i] = atof(strtok (NULL, ","));
sum = sum+nota[i];
}
float prom = sum/x;
printf ("promedio: %.1f\n\n", prom);
}
}
|
C
|
/*
* main.c
*
* Created on: 10-02-2013
* Author: bk
*/
/*
*
* TODO
* 1. Zapisac do "chan" adres OCR0A/B
* Odczytywac i zapisywac OCR0A/B przez pointer
*
* 2. PowerDown na Timerze; w razie niepstrykniecia zasilania
*
* 3. Zrobić 'inteligentny' random dla kanałów i wietlików
*
*
*
*/
#include <avr/io.h>
#include <util/delay.h>
#include <avr/pgmspace.h>
#include <stdlib.h>
#define ALL_FLYS_ON (1<<PB2) | (1<<PB3) | (1<<PB4)
#define u8 uint8_t
void fadeInOut(const u8 *channel, const u8 *flyNo);
const u8 chan[20] PROGMEM = {
1, 0,
1, 0,
0, 1,
1, 0,
0, 1,
0, 1,
1, 0,
0, 1,
1, 0,
0, 1
};
const u8 fly[20] PROGMEM = {
2,3,3,2,2,3,3,2,2,3,2,3,3,2,2,3,3,2,2,3
};
int main(void)
{
DDRB = ALL_FLYS_ON;
PORTB = ALL_FLYS_ON;
TCCR0A |= (1<<WGM00) | (1<<WGM01); //Fast PWM
TCCR0A |= (1<<COM0A1); // Set on compare match
TCCR0A |= (1<<COM0B1); // Set on compare match
TCCR0B |= (1<<CS00); // Clk / 1
/*
* Clk = 4800000 Hz
* Fpwm = Clk / prescal / 256
* presk = 1 Fpwm = 17968,75
* presk = 8 Fpwm = 2246 Hz
* presk = 64 Fpwm = 280 Hz
* presk = 256 Fpwm = 70 Hz
* presk = 1024 Fpwm = 17,54 Hz
*
* Clk = 4800000 / 8 = 575000 Hz (1 MHz, 1.8V: 240 µA)
* prescal = 1 Fpwm = 2246 Hz
*
*/
for(;;)
{
fadeInOut(chan, fly);
}
}
void fadeInOut(const u8 *channel, const u8 *flyNo)
{
u8 i;
u8 j;
for(j=0; j<=20; j++)
{
PORTB &= ~(1<<pgm_read_byte(flyNo + j)); //Zapal odpowieni LED
switch(pgm_read_byte(channel + j)) // Który kanał PWM odpalić
{
case 0:
DDRB |= (1<<PB0);
for(i=0; i<255; i++)
{
OCR0A = i;
_delay_ms(150);
}
_delay_ms(200);
for(i = 255; i; i--)
{
OCR0A = i;
_delay_ms(150);
}
DDRB &= ~(1<<PB0);
PORTB |= ALL_FLYS_ON;
_delay_ms(200);
break;
case 1:
DDRB |= (1<<PB1);
for(i=0; i<255; i++)
{
OCR0B = i;
_delay_ms(150);
}
_delay_ms(200);
for(i = 255; i; i--)
{
OCR0B = i;
_delay_ms(150);
}
DDRB &= ~(1<<PB1);
PORTB |= ALL_FLYS_ON;
_delay_ms(200);
break;
}
}
}
|
C
|
#include "h8-3052-iodef.h"
void sub_1(void)
{
int i;
i = 0;
}
int sub_2(void)
{
return 0;
}
int sub_3(void)
{
int i;
i = 1;
return i;
}
int sub_4(int i)
{
int j;
if (i == 0) {
j = 1;
}
else if (i == 1) {
j = 10;
}
else {
j = 100;
}
return j;
}
int sub_5(int i)
{
int j, k;
k = 0;
for (j = 0; j < i; j++) {
k = k + j;
}
return k;
}
int main(void)
{
int i;
sub_1();
sub_2();
i = sub_3();
i = sub_4(i);
i = sub_5(i);
return i;
}
|
C
|
//
// Created by deangeli on 5/19/17.
//
#ifndef LIBFL_MATRIXUTIL_H
#define LIBFL_MATRIXUTIL_H
#include "matrix.h"
#include "distanceFunctions.h"
inline double computeDistanceBetweenRows(Matrix* matrix1, Matrix* matrix2,
size_t indexRow_Source ,size_t indexRow_Target,
DistanceFunction distanceFunction,
ArgumentList* argumentList){
size_t nCols = matrix2->numberColumns;
float *vec_source = ((float*)matrix1->matrixData->data) + (indexRow_Source*matrix1->numberColumns);
float *vec_target = ((float*)matrix2->matrixData->data) + (indexRow_Target*matrix2->numberColumns);
return distanceFunction(vec_source,vec_target,nCols,argumentList);
}
inline size_t findNearestRow(Matrix* source, Matrix* target,
size_t indexRow_Target,
DistanceFunction distanceFunction = computeNormalizedL1Norm,
ArgumentList* argumentList = NULL){
double minDistance = DBL_MAX;
double currentDistance = 0;
size_t indexMin = 0;
for (size_t i = 0; i < source->numberRows; ++i) {
//printf("eiei2\n");
currentDistance = computeDistanceBetweenRows(source,target,i,indexRow_Target,distanceFunction,argumentList);
//printf("eiei1\n");
if(currentDistance < minDistance){
minDistance = currentDistance;
indexMin = i;
}
}
return indexMin;
}
inline double* computeAllDistancesBetweenRowAndMatrix(Matrix* source, Matrix* target,
size_t indexRow_Target,
DistanceFunction distanceFunction = computeNormalizedL1Norm,
ArgumentList* argumentList = NULL){
double* distances = (double*)calloc(source->numberRows,sizeof(double));
for (size_t i = 0; i < source->numberRows; ++i) {
distances[i] = computeDistanceBetweenRows(source,target,i,indexRow_Target,distanceFunction,argumentList);
}
return distances;
}
inline double* myInsertionSort(double* vector, size_t n){
double* auxVector = (double*)calloc(n,sizeof(double));
double aux;
for (size_t i = 0; i < n; ++i) {
auxVector[i] = vector[i];
for (size_t j = i; j > 0; --j) {
if(auxVector[j-1] > auxVector[j]){
aux = auxVector[j];
auxVector[j] = auxVector[j-1];
auxVector[j-1] = aux;
}else{
break;
}
}
}
return auxVector;
}
//option = 0 : vertical
//option = 1 : horizontal;
inline Matrix* computeMatrixMean(Matrix* matrix, int option = 0){
Matrix* output = NULL;
if(option == 0){
output = createMatrix(1,matrix->numberColumns,matrix->numberElements);
for (size_t i = 0; i < matrix->numberRows; ++i) {
for (size_t j = 0; j < matrix->numberColumns; ++j) {
MATRIX_GET_ELEMENT_PO_AS(float,output,0,j) += MATRIX_GET_ELEMENT_PO_AS(float,matrix,i,j);
}
}
for (size_t j = 0; j < matrix->numberColumns; ++j) {
MATRIX_GET_ELEMENT_PO_AS(float,output,0,j) /= matrix->numberColumns;
}
}else if(option == 1){
output = createMatrix(matrix->numberRows,1,matrix->numberElements);
for (size_t i = 0; i < matrix->numberRows; ++i) {
for (size_t j = 0; j < matrix->numberColumns; ++j) {
MATRIX_GET_ELEMENT_PO_AS(float,output,i,0) += MATRIX_GET_ELEMENT_PO_AS(float,matrix,i,j);
}
}
for (size_t j = 0; j < matrix->numberColumns; ++j) {
MATRIX_GET_ELEMENT_PO_AS(float,output,0,j) /= matrix->numberColumns;
}
}
return output;
}
#endif //LIBFL_MATRIXUTIL_H
|
C
|
#include "md_getoption.h"
#include "md_compression.h"
#include <stdio.h>
#include <stddef.h>
#include <string.h>
#define FORMAT_NEMESIS 0
void print_usage(FILE* fp) {
}
int main(int argc, const char* argv[]) {
FILE* finput;
FILE* foutput;
const char* option;
const char* input;
const char* output;
int format;
int arg;
int r;
input = NULL;
output = NULL;
format = -1;
arg = 1;
while(md_getoption(argc, argv, &arg, &option)) {
if(strcmp("-h", option) == 0 || strcmp("--help", option) == 0) {
print_usage(stdout);
return 0;
}
else if(strcmp("-i", option) == 0 || strcmp("--input", option) == 0) {
if(input != NULL || !md_getoption(argc, argv, &arg, &input)) {
fprintf(stderr, "Only one input file may be selected\n");
print_usage(stderr);
return 1;
}
}
else if(strcmp("-o", option) == 0 || strcmp("--output", option) == 0) {
if(output != NULL || !md_getoption(argc, argv, &arg, &output)) {
fprintf(stderr, "Only one output file may be selected\n");
print_usage(stderr);
return 1;
}
}
else if(strcmp("-n", option) == 0 || strcmp("--nemesis", option) == 0) {
if(format != -1) {
fprintf(stderr, "Only one compression format may be selected\n");
return 1;
}
format = FORMAT_NEMESIS;
}
else {
fprintf(stderr, "Unknown option: %s\n", option);
print_usage(stderr);
return 1;
}
}
if(format != FORMAT_NEMESIS) {
fprintf(stderr, "Must specify a compression format\n");
print_usage(stderr);
return 1;
}
if(input == NULL) {
fprintf(stderr, "Must specify a input filename\n");
print_usage(stderr);
return 1;
}
if(output == NULL) {
fprintf(stderr, "Must specify a output filename\n");
print_usage(stderr);
return 1;
}
finput = fopen(input, "rb");
if(finput == NULL) {
fprintf(stderr, "Failed to open input file for reading\n");
return 2;
}
foutput = fopen(output, "wb");
if(foutput == NULL) {
fclose(finput);
fprintf(stderr, "Failed to open output file for writing\n");
return 3;
}
switch(format) {
case FORMAT_NEMESIS:
r = md_compress_nemesis(finput, foutput);
break;
default:
r = 4;
break;
}
fclose(finput);
fclose(foutput);
return r;
}
|
C
|
#ifndef __SeqListD_H__
#define __SeqListD_H__
#pragma once
#include<stdio.h>
#include<assert.h>
#include<stdlib.h>
#include<malloc.h>
typedef int DataType;
typedef unsigned int size_t;
typedef struct SeqListD
{
DataType* _array;
size_t _capacity;//底层空间的大小
size_t _size;//有效元素的个数
}SeqListD, *PSeqListD;
void SeqListDInit(PSeqListD pSeq);//初始化
int SeqListDEmpty(PSeqListD pSeq);//判定动态顺序表是否为空
int SeqListDSize(PSeqListD pSeq);//元素个数
void SeqListDPushBack(PSeqListD pSeq, DataType data);//尾插
// 检测顺序表是否需要增容
int CheckCapacity(PSeqListD pSeq);
int SeqListDCapacity(PSeqListD pSeq);//增容
void PrintSeqListD(PSeqListD pSeq);// 打印顺序表中的元素
// 清空顺序表中的所有元素,注意不改变底层空间的大小
void SeqListDClear(PSeqListD pSeq);
// 销毁顺序表
void SeqListDDestroy(PSeqListD pSeq);
#endif //__SeqListD_H__
|
C
|
//Capacity of the line card in megabytes
#define C 64000
#define T 50 //Control Interval in ms
#define A 50000 //1000*T
/*********State Variables****************/
// Running average of RTT in ms
int RTT = 200;
int R = 200; //RCP feedback rate in MB/s
int B = 0; //Number of Bytes received
int S = 0; //Spare capacity in MB/s
/****Packet headers and meta-data********/
struct Packet {
int size_bytes;
int rtt; //Parsed from RCP header
int queue;
int Rp; //RCP feedback rate
int tick;
};
/*********Packet Transaction****************/
void func(struct Packet pkt) {
//Calculate running average of RTT
RTT = (RTT * 49 + pkt.rtt)/50;
//Write the throughput in packet header
if (pkt.Rp > R)
pkt.Rp = R;
//Control interval has expired, so
// calculate the feeback throughput
// and reset the state variables
if (pkt.tick % T == 0) {
S = C - B/A;
B = 0;
R *= 1+((S-((pkt.queue/RTT)/2))*T/RTT)/C;
}
else {
B += pkt.size_bytes;
}
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_find_way.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ajanmot <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/01/04 15:53:43 by ajanmot #+# #+# */
/* Updated: 2018/01/05 19:10:26 by ajanmot ### ########.fr */
/* */
/* ************************************************************************** */
#include "includes/include.h"
void ft_backtrack_elem(t_room *elem, t_file **new)
{
t_file *current;
if (!elem)
return ;
ft_backtrack_elem(elem->previous, new);
if (*new == NULL)
*new = ft_new_file(elem);
else
{
current = *new;
while (current->next)
current = current->next;
current->next = ft_new_file(elem);
}
}
t_file *get_shorter_way(t_file *head, char **start_end)
{
t_file *new;
t_file *current;
while (head)
{
if (!ft_strcmp(head->room->name, start_end[1]))
break ;
head = head->next;
}
if (!head)
return (NULL);
new = NULL;
ft_backtrack_elem(head->room, &new);
current = new;
while (current)
{
if (current->room->is_full == 0)
current->room->used = 1;
current = current->next;
}
return (new);
}
void ft_browse_way(t_file *current)
{
if (current)
{
ft_browse_way(current->next);
if (current->room->is_full > 0)
{
if (current->next->room->is_full >= 0)
{
ft_printf("L%d-%s ", current->room->is_full,
current->next->room->name);
current->next->room->is_full = current->room->is_full;
current->room->is_full = 0;
}
else
{
ft_printf("L%d-%s ", current->room->is_full,
current->next->room->name);
current->room->is_full = 0;
current->next->room->is_full--;
}
}
}
}
|
C
|
/*
Print weekday to console using a switch-statement.
Lecture: IE-B1-SO1 (Software construction 1)
Author: Marc Hensel
*/
#define _CRT_SECURE_NO_DEPRECATE // Else MSVC++ prevents using scanf() (concern: buffer overflow)
#include <stdio.h>
int main(void)
{
int weekday;
/* Get user input: Day of the week */
printf("Enter a day (1: Monday, 2: Tuesday, ..., 7: Sunday): ");
scanf("%d", &weekday);
getchar();
/* Print day of the week to console */
switch (weekday)
{
case 1:
case 2:
case 3:
case 4:
case 5:
printf("Go to work\n");
break;
case 6:
printf("Go shopping\n");
break;
case 7:
printf("Relax\n");
break;
default:
printf("I don't know that day ...\n");
/* No need for a break-statement here */
}
getchar();
return 0;
}
|
C
|
#include "ft_list.h"
#include <stdio.h>
#include <stdlib.h>
t_list *add_list(t_list *list, char c)
{
t_list *new;
if (!(new = (t_list*)malloc(sizeof(t_list))))
return (NULL);
if (new)
{
new->data = c;
new->next = list;
}
return (new);
}
char is_upper(char c)
{
if (c >= 'a' && c <= 'z')
c -= 32;
return (c);
}
void ft_list_foreach(t_list **begin_list, char (*f)(char c))
{
t_list *curr;
curr = *begin_list;
while (curr)
{
curr->data = (*f)(curr->data);
curr = curr->next;
}
}
void ft_list_foreach2(t_list *begin_list, void (*f)(void *))
{
t_list *list_ptr;
list_ptr = begin_list;
if (list_ptr)
{
(*f)(list_ptr->data);
ft_list_foreach(list_ptr->next, f);
}
}
void ft_print(t_list *list)
{
while (list)
{
printf("%c", list->data);
list = list->next;
}
}
int main(void)
{
t_list *list;
list = NULL;
list = add_list(list, 'a');
list = add_list(list, 'b');
// void (*f)(char c) = &is_upper;
ft_list_foreach(&list, &is_upper);
ft_print(list);
return (0);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "storage_mgr.h"
#include "dberror.h"
#include "test_helper.h"
RC readBlock (int pageNum, SM_FileHandle *fHandle, SM_PageHandle memPage){
if(pageNum>=1&&pageNum<=totalNumPages){
fseek(fHandle->mgmtInfo, (pageNum-1)*PAGE_SIZE , SEEK_SET);
//printf("seeked");
fread(memPage, 1, PAGE_SIZE, fHandle->mgmtInfo);
//printf("read")
return RC_OK;
}
else{
return RC_FILE_NOT_FOUND;
}
}
int getBlockPos (SM_FileHandle *fHandle)
{
return fHandle->curPagePos; //returns current position of the pointer in the file
}
RC readFirstBlock (SM_FileHandle *fHandle, SM_PageHandle memPage){
readBlock(1, fHandle, memPage); //returns the first block = 1
}
RC readPreviousBlock (SM_FileHandle *fHandle, SM_PageHandle memPage){
readBlock(fHandle->curPagePos-1, fHandle, memPage); // returns the previous block
}
RC readCurrentBlock (SM_FileHandle *fHandle, SM_PageHandle memPage){
readBlock(fHandle->curPagePos, fHandle, memPage); //returns the current block
}
RC readNextBlock (SM_FileHandle *fHandle, SM_PageHandle memPage){
readBlock(fHandle->curPagePos+1, fHandle, memPage); // returns the next block
}
RC readLastBlock (SM_FileHandle *fHandle, SM_PageHandle memPage){
readBlock(fHandle->totalNumPages, fHandle, memPage); //returns the last block
}
RC writeBlock (int pageNum, SM_FileHandle *fHandle, SM_PageHandle memPage){
/* to check the number of pages lies inbetween the pagenumbers available and then add information */
if(pageNum>0 && pageNum<=totalNumPages){
fseek(fHandle->mgmtInfo,(pageNum-1)*PAGE_SIZE, SEEK_SET);
fwrite(memPage,PAGE_SIZE,1,fHandle->mgmtInfo);
pageNum = pageNum + 1;
totalNumPages = totalNumPages + 1;
return RC_OK;
}
/* to create NULL pages and add more information */
else if(pageNum>totalNumPages){
ensureCapacity(pageNum-totalNumPages,fHandle);
fseek(fHandle->mgmtInfo,(pageNum-1)*PAGE_SIZE, SEEK_SET);
fwrite(memPage,PAGE_SIZE,1,fHandle->mgmtInfo);
pageNum = pageNum + 1;
totalNumPages = totalNumPages + 1;
return RC_OK;
}
else{
return RC_FAILED_WRITE
}
}
RC writeCurrentBlock (SM_FileHandle *fHandle, SM_PageHandle memPage){
// to write in the current block
writeBlock(fHandle->curPagePos, fHandle, memPage);
}
RC appendEmptyBlock (SM_FileHandle *fHandle){
//create an empty block with value = NULL ('/0')
int i=0;
char emptyString[PAGE_SIZE];
for(i=0;i<PAGE_SIZE;i++){
emptyString[i]='\0';
}
//find the last page
fseek(fHandle->mgmtInfo,fHandle->totalNumPages*PAGE_SIZE,SEEK_SET);
//write the empty block
fwrite(emptyString,PAGE_SIZE,1,fHandle->mgmtInfo);
return RC_OK;
fHandle->curPagePos=lastPage;
fHandle->totalNumPages = lastPage+1;
}
RC ensureCapacity (int numberOfPages, SM_FileHandle *fHandle){
/*if there are lesser number of pages => totalNUmPages < numberOfPages
appendEmptyBlock numofblocksadded = totalNumPages-numberOfPages
location = curPagePos */
int i=0;
if(numberOfPages>totalNumPages){
for(i=fHandle->totalNumPages;i<numberOfPages;i++){
appendEmptyBlock(fHandle);
}
return RC_OK
//printf("capacity ensured")
}
else{
return RC_FAILED_WRITE
}
}
|
C
|
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <signal.h>
#include "mutex_lib.h"
#include "semaphore_lib.h"
void sem_sig_hand(int sig) // prinde semnalul si trezeste thread-ul
{
//write(0,"Sem: am primit mesajul\n",23);
return;
}
void sem_enqueue(Sem *sem)
{
//bagam doar conditia;
struct process *new = malloc(sizeof(struct process));
new->pid = pthread_self();
new->wait = 1; // flag de asteptare
new->next = NULL;
if(sem->listStart == NULL)
{
sem->listStart = new;
sem->listEnd = new;
}
else
{
sem->listEnd->next = new;
sem->listEnd = new;
}
}
void sem_dequeue(Sem *sem)
{
if(sem->listStart == NULL)
return;
else
{
struct process *p = sem->listStart;
if(sem->listStart == sem->listEnd)
sem->listEnd = NULL;
sem->listStart = sem->listStart->next;
free(p);
}
}
int thread_wait(char *cond,Sem *sem) // pune thread-ul in asteptare
{
mutex_unlock_meu(&sem->mtx);
while(*cond);
mutex_lock_meu(&sem->mtx);
sem_dequeue(sem);
mutex_unlock_meu(&sem->mtx);
return 0;
}
int thread_signal(Sem *sem)
{
//write(0,"Sem: trimitem semnal\n",21);
if(sem->listStart)
pthread_kill(sem->listStart->pid,SIGALRM);
//sem->listStart->wait = 0;
}
int sem_init(Sem *sem,int pshared, int N)
{
sem->N = N;
mutex_init_meu(&sem->mtx);
sem->listStart = NULL;
sem->listEnd = NULL;
return 0;
}
void sem_wait(Sem *sem)
{//asteapta in ordine
mutex_lock_meu(&sem->mtx);
sem->N--;
if(sem->N < 0)
{
signal(SIGALRM,sem_sig_hand);
//write(0,"n < 0\n",6);
sem_enqueue(sem);
mutex_unlock_meu(&sem->mtx); // unlock the mutex befor sleeping
pause();
//thread_wait(&sem->listStart->wait,sem); //pune thread-ul in asteptare si da realese la lock
}
mutex_unlock_meu(&sem->mtx);
}
void sem_post(Sem *sem)
{//se elibereaza si cheama urmatorul la rand
mutex_lock_meu(&sem->mtx);
sem->N++;
if(sem->N <= 0)
{
//write(0,"N < 0\n",6);
thread_signal(sem);
sem_dequeue(sem);
}
mutex_unlock_meu(&sem->mtx);
}
int sem_destroy(Sem *sem)
{
//stergem lista
struct process *p = sem->listStart,*t;
while(p)
{
t = p->next;
free(p);
p = t;
}
//free(sem);
//probabil vom aloca campurile structurii, dimamic
return 0;
}
|
C
|
// Author:Michael Sullivan
// Olivia Mandola [email protected]
// Dymea Schippers [email protected]
//Section 11r
//Breakout11
#include <stdio.h>
#include <stdlib.h>
#include <readline/readline.h>
int sum_n(int n);
void print_n(const char *s, int n);
int main(void) {
char* numHold = readline("Enter an int: ");
int n = atoi(numHold);
int total = sum_n(n);
printf("sum is %d.\n", total);
char* s = readline("Enter a string: ");
print_n(s, n);
return 0;
}
int sum_n(int n){
if (n <= 0){
return 0; }
else {
return n+sum_n(n-1);
}
}
void print_n(const char *s, int n){
if (n >= 1) {
printf("%s\n", s);
print_n(s, n-1);
}
}
|
C
|
/*
** eyes.c for raytracer in /home/le-mai_s/recode/TP/raytracer1/Raytracer/mlx
**
** Made by sebastien le-maire
** Login <[email protected]>
**
** Started on Thu Sep 10 17:04:02 2015 sebastien le-maire
** Last update Wed Oct 21 11:25:58 2015 sebastien le-maire
*/
#include <float.h>
#include "raytracer_mlx.h"
void init_tmp_eyes(t_eyes *eyes, double (*pos)[3],
double (*vec)[3], double k)
{
fill_tab3d(&eyes->pos, (*pos)[X], (*pos)[Y], (*pos)[Z]);
fill_tab3d(&eyes->vec, (*vec)[X], (*vec)[Y], (*vec)[Z]);
eyes->k = k;
}
void fill_tab3d(double (*tab3d)[3], double x,
double y, double z)
{
(*tab3d)[X] = x;
(*tab3d)[Y] = y;
(*tab3d)[Z] = z;
}
void init_eyes(t_eyes *eyes, double x, double y, double z)
{
eyes->pos[X] = x;
eyes->pos[Y] = y;
eyes->pos[Z] = z;
eyes->rot[X] = 0;
eyes->rot[Y] = 0;
eyes->rot[Z] = 0;
}
void set_eyes(t_eyes *eyes)
{
eyes->k = DBL_MAX;
eyes->color = BLACK;
}
|
C
|
#include <avr/io.h>
#include "adc.h"
#define MASKBITS 0b00001111
void adc_init(void)
{
ADMUX |= (1 << REFS0); // Initialize the ADC
ADMUX &=~(1 << REFS1);
ADMUX |= (1 << ADLAR); //set ADLAR bit in ADMUX to 1 to get 8-bit conversion
ADCSRA |= ((1 << ADPS2) | (1 << ADPS1) | (1 << ADPS0)); //set ADPS[2:0] bits in ADCSRA to 1
ADCSRA |= (1 << ADEN); //Set ADEN bit in ADCSRA to enable ADC module
}
unsigned char adc_sample(unsigned char channel)
{
// Set ADC input mux bits to 'channel' value
ADMUX &= ~MASKBITS; //cleared lower bits [3:0]
ADMUX |= (channel & MASKBITS);
// Convert an analog input and return the 8-bit result
ADCSRA |= (1 << ADSC);
while((ADCSRA & (1 << ADSC)) != 0)
{
}
unsigned char result = ADCH;
return result;
}
|
C
|
// Tutoriel base en Langage C <Coding seule/>
#include <stdio.h>
int main(){
int x, y;
printf("Donnez un nombre entier : ");
scanf("%d", &x);
printf("Donnez un autre nombre entier : ");
scanf("%d", &y);
if(x > y){
printf("%d est superieur a %d\n", x, y);
}
else
printf("%d est inferieur a %d\n",x, y );
}
|
C
|
/*
* This file is part of the exercises for the Lectures on
* "Foundations of High Performance Computing"
* given at
* Master in HPC and
* Master in Data Science and Scientific Computing
* @ SISSA, ICTP and University of Trieste
* 2019
*
* This is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
* This code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
#define _XOPEN_SOURCE 700
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
//#include <ptiming.h>
#include <time.h>
#define CPU_TIME (clock_gettime( id, &ts ), (double)ts.tv_sec + \
(double)ts.tv_nsec * 1e-9)
#ifndef DATASIZE
#define DATASIZE 200
#endif
typedef struct node_t {
double key;
struct node_t *next;
char data[DATASIZE];
} node;
#define N_default 10000
int main( int argc, char **argv )
{
struct timespec ts;
clockid_t id = CLOCK_PROCESS_CPUTIME_ID;
// -------------------------------------
// startup
int N = N_default;
if ( argc > 1 )
N = atoi( *(argv+1) );
// -------------------------------------
// setup
double *keys = (double*)calloc( N, sizeof(double));
node *last = NULL;
node *first = NULL;
printf("creating and initializing %d nodes\n", N ); fflush(stdout);
srand48( time(NULL) );
for( int nn = 0; nn < N; nn++ )
{
node *new = (node*)calloc( 1, sizeof(node) );
if ( last != NULL )
last->next = new;
else
first = new;
new ->key = drand48();
keys[nn] = new->key;
new ->next = NULL;
memset( new->data, 0, sizeof(char)*DATASIZE);
last = new;
}
printf("now let's search for all of them\n"); fflush(stdout);
int NSHOTS = N;
double sum = 0;
double tstart = CPU_TIME;
for( int ii = 0; ii < NSHOTS; ii++ )
{
double key = keys[(int)(drand48() * N)];
node *target = first;
while ( target->key != key )
target = target->next;
sum += target->key;
}
double et = CPU_TIME - tstart;
printf("timing for %d shots: %g\n", NSHOTS, et );
node *target = first;
while( target->next != NULL )
{
node *tmp = target->next;
free(target);
target = tmp;
}
return 0;
}
|
C
|
/*
Z SCPC ȭ
: 88
ð: 0.38
:8312
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
//#pragma warning(disable:4996)
int Answer;
int main(void)
{
int T, test_case, len, count = 0, i, two = 1;
char str[1000001];
char* ele[] = {
"H", "He", "Li", "Be", "B", "C", "N", "O", "F", "Ne", "Na", "Mg", "Al",
"Si", "P", "S", "Cl", "Ar", "K", "Ca", "Sc", "Ti", "V", "Cr", "Mn", "Fe",
"Co", "Ni", "Cu", "Zn", "Ga", "Ge", "As", "Se", "Br", "Kr", "Rb", "Sr",
"Y","Zr", "Nb", "Mo", "Tc", "Ru", "Rh", "Pd", "Ag", "Cd", "In", "Sn", "Sb",
"Te", "I", "Xe", "Cs", "Ba", "Hf", "Ta", "W", "Re", "Os", "Ir", "Pt", "Au",
"Hg", "Tl", "Pb", "Bi", "Po", "At", "Rn", "Fr", "Ra", "Rf", "Db", "Sg",
"Bh", "Hs", "Mt", "Ds", "Rg", "Cn", "Fl", "Lv", "La", "Ce", "Pr", "Nd",
"Pm", "Sm", "Eu", "Gd", "Tb", "Dy", "Ho", "Er", "Tm", "Yb", "Lu", "Ac",
"Th", "Pa", "U", "Np", "Pu", "Am", "Cm", "Bk", "Cf", "Es", "Fm", "Md",
"No", "Lr"
};
setbuf(stdout, NULL);
scanf("%d", &T);
for (test_case = 0; test_case < T; test_case++){
Answer = 1;
fgets(str, sizeof(str), stdin);
len = strlen(str);
while (len >= count){
char tmp[3];
if (len - count > 2){
if (two == 1){
tmp[0] = str[count];
tmp[1] = str[count + 1];
tmp[2] = '\0';
}
else{
tmp[0] = str[count];
tmp[1] = '\0';
}
}
else{
tmp[0] = str[count];
tmp[1] = '\0';
}
for (i = 0; i < 114; i++){
if (strcasecmp(tmp, ele[i]) == 0){
break;
}
else{
continue;
}
}
if (i == 114){
if (two == 1){
two = 0;
}
else{
Answer = 0;
break;
}
}
else{
if (two == 1)
count = count + 2;
else
count++;
two = 1;
}
}
printf("Case #%d\n", test_case + 1);
if (Answer == 1)
printf("YES\n");
else
printf("NO\n");
count = 0;
}
return 0;//Your program should return 0 on normal termination.
}
|
C
|
/***************************************************************************************************
*FileName:
*Description:
*Author:xsx
*Data:
***************************************************************************************************/
/***************************************************************************************************/
/******************************************ͷļ***************************************************/
/***************************************************************************************************/
#include "JsonToObject.h"
#include "CRC16.h"
#include <string.h>
#include "stdio.h"
/***************************************************************************************************/
/**************************************ֲ*************************************************/
/***************************************************************************************************/
/***************************************************************************************************/
/**************************************ֲ*************************************************/
/***************************************************************************************************/
/***************************************************************************************************/
/***************************************************************************************************/
/***********************************************************************************************/
/***************************************************************************************************/
/***************************************************************************************************/
/***************************************************************************************************/
/***************************************************************************************************
*FunctionName: ParseJsonToDateTime
*Description: jsonDateTimeṹ
*Input:
*Output:
*Return:
*Author: xsx
*Date: 201761 15:13:29
***************************************************************************************************/
MyRes ParseJsonToDateTime(const char * jsonStr, DateTime * dateTime)
{
cJSON * json = NULL;
cJSON * tempJson = NULL;
MyRes status = My_Fail;
if(jsonStr && dateTime)
{
json = cJSON_Parse(jsonStr);
if(json)
{
//
tempJson = cJSON_GetObjectItem(json, "year");
if((tempJson) && (tempJson->valueint > 2000))
dateTime->year = tempJson->valueint - 2000;
else
goto END;
//
tempJson = cJSON_GetObjectItem(json, "monthValue");
if((tempJson) && (tempJson->valueint <= 12))
dateTime->month = tempJson->valueint;
else
goto END;
//
tempJson = cJSON_GetObjectItem(json, "dayOfMonth");
if((tempJson) && (tempJson->valueint <= 31))
dateTime->day = tempJson->valueint;
else
goto END;
//ʱ
tempJson = cJSON_GetObjectItem(json, "hour");
if((tempJson) && (tempJson->valueint <= 24))
dateTime->hour = tempJson->valueint;
else
goto END;
//
tempJson = cJSON_GetObjectItem(json, "minute");
if((tempJson) && (tempJson->valueint <= 59))
dateTime->min = tempJson->valueint;
else
goto END;
//
tempJson = cJSON_GetObjectItem(json, "second");
if((tempJson) && (tempJson->valueint <= 59))
dateTime->sec = tempJson->valueint;
else
goto END;
status = My_Pass;
}
}
END:
cJSON_Delete(json);
return status;
}
/***************************************************************************************************
*FunctionName: ParseJsonToDeviceAndOperator
*Description: json豸ϢͲ
*Input: jsonStr -- jsonַ
* device -- 豸ݵλ
* operator -- ˵λ
*Output:
*Return:
*Author: xsx
*Date:
***************************************************************************************************/
MyRes ParseJsonToDevice(const char * jsonStr, Device * device)
{
cJSON * json = NULL;
cJSON * tempJson1 = NULL;
cJSON * tempJson2 = NULL;
unsigned char size = 0, i;
MyRes status = My_Fail;
if(jsonStr && device)
{
json = cJSON_Parse(jsonStr);
if(json)
{
//豸ַ
tempJson1 = cJSON_GetObjectItem(json, "addr");
if(tempJson1)
memcpy(device->addr, tempJson1->valuestring, strlen(tempJson1->valuestring)+1);
else
goto END;
//豸
tempJson1 = cJSON_GetObjectItem(json, "department");
if(tempJson1)
{
tempJson2 = cJSON_GetObjectItem(tempJson1, "name");
memcpy(device->department, tempJson2->valuestring, strlen(tempJson2->valuestring)+1);
}
else
goto END;
//豸ʱ
tempJson1 = cJSON_GetObjectItem(json, "modifyTimeStamp");
if(tempJson1)
{
device->modifyTimeStamp = tempJson1->valueint;
}
else
goto END;
//
tempJson1 = cJSON_GetObjectItem(json, "operator");
if(tempJson1)
{
if(My_Fail == ParseJsonToOperator(tempJson1, &(device->operator)))
goto END;
}
else
goto END;
//
tempJson1 = cJSON_GetObjectItem(json, "operators");
if(tempJson1)
{
size = cJSON_GetArraySize(tempJson1);
for(i=0; i<size; i++)
{
tempJson2 = cJSON_GetArrayItem(tempJson1, i);
if(My_Fail == ParseJsonToOperator(tempJson2, &device->operators[i]))
goto END;
}
}
else
goto END;
device->crc = CalModbusCRC16Fun(device, DeviceStructCrcSize, NULL);
status = My_Pass;
}
}
END:
cJSON_Delete(json);
return status;
}
MyRes ParseJsonToOperator(cJSON * json, Operator * opeartor)
{
cJSON * tempJson1 = NULL;
cJSON * tempJson2 = NULL;
MyRes status = My_Fail;
if(json && opeartor)
{
//id
tempJson1 = cJSON_GetObjectItem(json, "id");
if(tempJson1)
opeartor->id = tempJson1->valueint;
else
goto END;
//
tempJson1 = cJSON_GetObjectItem(json, "name");
if(tempJson1)
memcpy(opeartor->name, tempJson1->valuestring, strlen(tempJson1->valuestring)+1);
else
goto END;
//
tempJson1 = cJSON_GetObjectItem(json, "age");
if(tempJson1)
memcpy(opeartor->age, tempJson1->valuestring, strlen(tempJson1->valuestring)+1);
else
goto END;
//Ա
tempJson1 = cJSON_GetObjectItem(json, "sex");
if(tempJson1)
memcpy(opeartor->sex, tempJson1->valuestring, strlen(tempJson1->valuestring)+1);
else
goto END;
//ϵʽ
tempJson1 = cJSON_GetObjectItem(json, "phone");
if(tempJson1)
memcpy(opeartor->phone, tempJson1->valuestring, strlen(tempJson1->valuestring)+1);
else
goto END;
//ְ
tempJson1 = cJSON_GetObjectItem(json, "job");
if(tempJson1)
memcpy(opeartor->job, tempJson1->valuestring, strlen(tempJson1->valuestring)+1);
else
goto END;
//ע
tempJson1 = cJSON_GetObjectItem(json, "department");
if(tempJson1)
{
tempJson2 = cJSON_GetObjectItem(tempJson1, "name");
if(tempJson2)
memcpy(opeartor->department, tempJson2->valuestring, strlen(tempJson2->valuestring)+1);
else
goto END;
}
else
goto END;
opeartor->crc = CalModbusCRC16Fun(opeartor, OneOperatorStructCrcSize, NULL);
status = My_Pass;
}
END:
return status;
}
MyRes ParseJsonToRemoteSoftInfo(const char * jsonStr, RemoteSoftInfo * remoteSoftInfo)
{
cJSON * json = NULL;
cJSON * tempJson1 = NULL;
MyRes status = My_Fail;
if(jsonStr && remoteSoftInfo)
{
json = cJSON_Parse(jsonStr);
if(json)
{
//version
tempJson1 = cJSON_GetObjectItem(json, "version");
if(tempJson1)
{
remoteSoftInfo->RemoteFirmwareVersion = tempJson1->valueint;
}
else
goto END;
//md5
tempJson1 = cJSON_GetObjectItem(json, "md5");
if(tempJson1)
memcpy(remoteSoftInfo->md5, tempJson1->valuestring, strlen(tempJson1->valuestring)+1);
else
goto END;
status = My_Pass;
}
}
END:
return status;
}
|
C
|
#include <stdint.h>
#include "PLL.h"
#include "LCD.h"
#include "os.h"
#include "joystick.h"
#include "FIFO.h"
#include "PORTE.h"
#include "tm4c123gh6pm.h"
// Constants
#define BGCOLOR LCD_BLACK
#define CROSSSIZE 5
//------------------Defines and Variables-------------------
uint16_t origin[2]; // the original ADC value of x,y if the joystick is not touched
int16_t x = 63; // horizontal position of the crosshair, initially 63
int16_t y = 63; // vertical position of the crosshair, initially 63
int16_t prevx = 63;
int16_t prevy = 63;
uint8_t select; // joystick push
//---------------------User debugging-----------------------
#define TEST_TIMER 0 // Change to 1 if testing the timer
#define TEST_PERIOD 3999999 // Defined by user
#define PERIOD 3999999 // Defined by user
unsigned long Count; // number of times thread loops
//--------------------------------------------------------------
void CrossHair_Init(void){
BSP_LCD_FillScreen(LCD_BLACK); // Draw a black screen
BSP_Joystick_Input(&origin[0], &origin[1], &select); // Initial values of the joystick, used as reference
}
//******** Producer ***************
void Producer(void){
#if TEST_TIMER
PE1 ^= 0x02; // heartbeat
Count++; // Increment dummy variable
#else
// Variable to hold updated x and y values
int16_t newX;
int16_t newY;
int16_t deltaX = 0;
int16_t deltaY = 0;
int16_t count = 0;
uint16_t rawX, rawY; // To hold raw adc values
uint8_t select; // To hold pushbutton status
rxDataType data;
while(count < 5) {
BSP_Joystick_Input(&rawX, &rawY, &select);
deltaX += rawX; // sample 5 values to insure that the joystick ADC isn't just jumping around
deltaY += rawY;
count++;
}
newX = (deltaX / 5); // Get the average of the 5 samples
newY = (deltaY / 5);
if(newX > 2500){x += 2;} // If the ADC reads larger than 2500 move the x coordinate to the right twice
else if(newX < 1000){x -= 2;} // If the ADC reads less than 1000 move the x coordinate to the left twice
if(newY > 2500) {y -= 2;} // If the ADC reads larger than 2500 move the y coordinate up twice
else if(newY < 1000){y += 2;} // If the ADC reads less than 1000 move the x coordinate down twice
if(x > 127){x = 127;} // Dont allow the crosshairs to move outside the frame of the screen (+X)
else if(x < 0){x = 0;} // Dont allow the crosshairs to move outside the frame of the screen (-X)
if(y > 115){y = 115;} // Dont allow the crosshairs to move outside the frame of the screen (-Y)
else if(y < 0){y = 0;} // Dont allow the crosshairs to move outside the frame of the screen (+Y)
data.x = x; // Store new updated value of x into the data struct
data.y = y; // Store new updated value of y into the data struct
RxFifo_Put(data); // Send the data struct to the stack (FIFO)
#endif
}
//******** Consumer ***************
void Consumer(void){
rxDataType data;
char x_array[] = "X: ";
char y_array[] = "Y: ";
char* x_ptr = x_array;
char* y_ptr = y_array;
prevx = data.x; // Before reading in a new value from the data struct store the old ones in the prevx global
prevy = data.y; // Before reading in a new value from the data struct store the old ones in the prevy global
RxFifo_Get(&data); // Read top value from stack and place it into the data struct
x = data.x; // Store values from the data struct into the x global
y = data.y; // Store values from the data struct into the y global
BSP_LCD_DrawCrosshair(prevx, prevy, LCD_BLACK); // Erase old crossgair using prevx and prevy in prep for new crosshair
BSP_LCD_DrawCrosshair(x, y, LCD_GREEN); // Draw new crosshair using x and y
BSP_LCD_Message(1, 12, 4, x_ptr, x); // Write out message X: value of global x
BSP_LCD_Message(1, 12, 12, y_ptr, y); // Write out message Y: value of global y
}
//******** Main ***************
int main(void){
PLL_Init(Bus80MHz); // set system clock to 80 MHz
#if TEST_TIMER
PortE_Init(); // profile user threads
Count = 0;
OS_AddPeriodicThread(&Producer, TEST_PERIOD, 1);
while(1){}
#else
BSP_LCD_Init(); // initialize LCD
BSP_Joystick_Init(); // initialize Joystick
CrossHair_Init();
RxFifo_Init();
OS_AddPeriodicThread(&Producer,PERIOD, 1);
while(1){
Consumer();
}
#endif
}
|
C
|
#include "RemoteDeal.h"
#include "MathLib.h"
/*ңؽṹ*/
REMOTE_t REMOTE;
/*ң*/
static const u8 DeadZone = 10;
/*************************************************************************************************
*: Get_RemoteDeal_Point
*: شңֵƱָͨ봫ݷʽϢ
*β:
*:
*˵:
*************************************************************************************************/
REMOTE_t *Return_RemoteDeal_Point(void)
{
return &REMOTE;
}
/*************************************************************************************************
*: Remote_Data_Init
*: ңֵʼ
*β:
*:
*˵:
*************************************************************************************************/
void Remote_Data_Init(void)
{
/*ӳ*/
REMOTE.Get_Remote_Point = Return_Remote_Point;
/*ңֵʼ*/
REMOTE.RC_ctrl->ch0 = REMOTE.RC_ctrl->ch1 = REMOTE.RC_ctrl->ch2 = REMOTE.RC_ctrl->ch3 = 0;
REMOTE.RC_ctrl->s1 = REMOTE.RC_ctrl->s2 = REMOTE.RC_ctrl->sw = REMOTE.RC_ctrl->Flag = 0;
REMOTE.RC_ctrl->KV.x = REMOTE.RC_ctrl->KV.y = REMOTE.RC_ctrl->KV.z = 0;
REMOTE.RC_ctrl->KV.key = REMOTE.RC_ctrl->KV.press_l = REMOTE.RC_ctrl->KV.press_r = 0;
/*ͨ˲ʼ*/
First_Order_Init(&REMOTE.RC_X,0.08);
First_Order_Init(&REMOTE.RC_Y,0.08);
First_Order_Init(&REMOTE.RC_Z,0.08);
First_Order_Init(&REMOTE.KM_X,0.005);
First_Order_Init(&REMOTE.KM_Y,0.005);
First_Order_Init(&REMOTE.KM_Z,0.005);
/*ȡңָ*/
REMOTE.RC_ctrl = REMOTE.Get_Remote_Point();
}
/*************************************************************************************************
*: Rc_Deal
*: ң˲˵ֵ
*β:
*:
*˵:
*************************************************************************************************/
static void Rc_Deal(void)
{
/**/
REMOTE.RC_ctrl->ch0 = Dead_Zone(REMOTE.RC_ctrl->ch0,DeadZone);
REMOTE.RC_ctrl->ch1 = Dead_Zone(REMOTE.RC_ctrl->ch1,DeadZone);
REMOTE.RC_ctrl->ch2 = Dead_Zone(REMOTE.RC_ctrl->ch2,DeadZone);
/*˲*/
First_Order(&REMOTE.RC_X,REMOTE.RC_ctrl->ch1);
First_Order(&REMOTE.RC_Y,REMOTE.RC_ctrl->ch0);
First_Order(&REMOTE.RC_Z,REMOTE.RC_ctrl->ch2);
}
/*************************************************************************************************
*: KEY_MOUSE
*: ֵ
*β:
*:
*˵:
*************************************************************************************************/
static void Key_Mouse_Deal(void)
{
uint16_t key = REMOTE.RC_ctrl->KV.key;
/*ǰ*/
if(key & KEY_PRESSED_OFFSET_W)
{
REMOTE.RC_ctrl->KV.kv0 += 10;
}
else if(key & KEY_PRESSED_OFFSET_S)
{
REMOTE.RC_ctrl->KV.kv0 -= 10;
}
else
{
REMOTE.RC_ctrl->KV.kv0 = 0;
}
/**/
if(key & KEY_PRESSED_OFFSET_A)
{
REMOTE.RC_ctrl->KV.kv1 -= 10;
}
else if(key & KEY_PRESSED_OFFSET_D)
{
REMOTE.RC_ctrl->KV.kv1 += 10;
}
else
{
REMOTE.RC_ctrl->KV.kv1 = 0;
}
/*Yת*/
REMOTE.RC_ctrl->KV.kv3 = (float)REMOTE.RC_ctrl->KV.x * 15;
/*Zת*/
REMOTE.RC_ctrl->KV.kv2 = (float)REMOTE.RC_ctrl->KV.y * 15;
/*Ʒȴ*/
REMOTE.RC_ctrl->KV.kv0 = limit(REMOTE.RC_ctrl->KV.kv0,660,-660);
REMOTE.RC_ctrl->KV.kv1 = limit(REMOTE.RC_ctrl->KV.kv1,660,-660);
REMOTE.RC_ctrl->KV.kv2 = limit(REMOTE.RC_ctrl->KV.kv2,660,-660);
REMOTE.RC_ctrl->KV.kv3 = limit(REMOTE.RC_ctrl->KV.kv3,660,-660);
/*˲*/
First_Order(&REMOTE.KM_X,REMOTE.RC_ctrl->KV.kv1);
First_Order(&REMOTE.KM_Y,REMOTE.RC_ctrl->KV.kv0);
First_Order(&REMOTE.KM_Z,REMOTE.RC_ctrl->KV.kv2);
}
/*************************************************************************************************
*: RC_DATA_DEAL
*: ңֵ
*β:
*:
*˵:
*************************************************************************************************/
void Remote_Data_Deal(void)
{
/*ݸ±־λ*/
if(REMOTE.RC_ctrl->Flag == 1)
{
Rc_Deal();
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "lt.h"
#include "dboracle.h"
#include "ltdb.h"
/*ݿ*/
//ltDbConn *ltDbConnect(char *pUser,char *pPassword,char *pService);
/* رݿӣͷйԴ */
//void ltDbClose(ltDbConn *psConn);
/*¼*/
//LT_DBROW ltDbOneRow(ltDbConn *pConn,int *fieldnum,char *pSmt,...);
//void ltDbFreeRow(LT_DBROW dbRow,int fieldnum);
main(){
ltDbConn *tempCon;
LT_DBROW tempRow;
int i;
int fieldnum;
tempCon=ltDbConnect("nc","nc",NULL);
if(tempCon!=NULL){
printf("ok\n");
}else{
printf("connect error\n");
}
tempRow=ltDbOneRow(tempCon,&fieldnum,"select * from NCADMUSER");
printf("fieldnum:%d\n",fieldnum);
if(tempRow==NULL){
printf("get row error:\n");
}
for (i=0; i<fieldnum;i++){
printf("%s\n",tempRow[i]);
}
ltDbFreeRow(tempRow,fieldnum);
ltDbClose(tempCon);
}
|
C
|
#include<stdio.h>
int main(void){
int num[]={125814,225547,132254,224321,352124,342214,382154,321014,112254,153789}; /**/
int numm[]={10000,5000,1000,500,100,50,10,5,1}; /*̗*/
int n[]={0,0,0,0,0,0,0,0,0,0}; /**/
int i, j; /*JԂp*/
for(i=0;i<=9;i++){
for(j=0;j<=8;j++){
while(num[i]>=numm[j]){ /*邨z܂*/
num[i]=num[i]-numm[j];
n[j]=n[j]+1;
}
}
}
for(i=0;i<=8;i++){
printf("%5d~%6d\n",numm[i],n[i]); /*ʂ̕\*/
}
return 0;
}
|
C
|
/*********************************************************************
* FileName: vector.h
********************************************************************/
#include <math.h>
struct vector3
{
float x;
float y;
float z;
};
struct matrix
{
float m11, m12, m13;
float m21, m22, m23;
float m31, m32, m33;
};
struct vector3 MakeVector(float x, float y, float z);
struct vector3 AddVector(struct vector3 v1, struct vector3 v2);
struct vector3 Normalize(float x, float y, float z);
float DotVector (struct vector3 v1, struct vector3 v2);
struct vector3 CrossProduct(struct vector3 v1, struct vector3 v2);
struct vector3 Multiply(float k, struct vector3 v);
struct matrix SetupRotationMatrix(int axis, float theta);
struct vector3 RotationMatrixObjectToInertial(struct matrix m, struct vector3 v);
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main()
{int x, y;
double f;
scanf("%d%d",&x, &y);
if (x>-2 && 2<y && y<10){
f= sqrt(abs(pow(x,2)-pow(y,2)));}
else if (x<-5 || y<2){
f=log10(-x)+ 2 * y;}
else {
f=sin(y);}
printf("%f", f);
return 0;
}
|
C
|
#include <memory.h>
/* API provided by system */
void ip_DiscardPkt(char * pBuffer ,int type);
void ip_SendtoLower(char *pBuffer ,int length);
void ip_SendtoUp(char *pBuffer, int length);
unsigned int getIpv4Address();
int stud_ip_recv(char * pBuffer, unsigned short length){
// in case version == 1xxx, which would also yield VERSION_ERROR, but just to be concise
unsigned int version = ((unsigned int)pBuffer[0]) >> 4;
if(version != 4){
ip_DiscardPkt(pBuffer, STUD_IP_TEST_VERSION_ERROR);
return -1;
}
unsigned int ip_head_length = ((unsigned int)pBuffer[0]) & 0xF;
if(ip_head_length < 5 || ip_head_length > 15){
// according to RFC791, ip_head_length <= 15
// see RFC791 section 3.1, mentioned in "total length" part
// ref: https://tools.ietf.org/html/rfc791
ip_DiscardPkt(pBuffer, STUD_IP_TEST_HEADLEN_ERROR);
return -1;
}
unsigned int time_to_live = ((unsigned int)pBuffer[8]);
if(time_to_live == 0){
ip_DiscardPkt(pBuffer, STUD_IP_TEST_TTL_ERROR);
return -1;
}
unsigned int destination_address = ntohl(*(unsigned int* )(pBuffer + 16)); // might be wrong
if(destination_address != getIpv4Address() && destination_address != (~0)){
// if it is necessray to consider
// - localhost address: 127.0.0.0/8
// - link-local address: 169.254.0.0/16
// then check: (dst_addr >> 24) != 127 and (dst_addr >> 16) != ((169 << 8) + 254)
ip_DiscardPkt(pBuffer, STUD_IP_TEST_DESTINATION_ERROR);
return -1;
}
unsigned int header_checksum = 0;
for(int i = 0; i < 4 * ip_head_length; i += 2){
// 4 * IHL % 2 == 0, no need to consider odd/even issue
header_checksum += (pBuffer[i] << 8) + pBuffer[i + 1];
}
while(header_checksum >> 16){
// in case header_checksum == 0x1FFFF
// add once might not be enough
// ref: https://tools.ietf.org/html/rfc1071 section 4.1
// we stick to big-endian byte order, since checksum is byte order independent
// ref: https://tools.ietf.org/html/rfc1071 section 1.2.(B)
header_checksum == (header_checksum >> 16) + (header_checksum & 0xFFFF);
}
header_checksum = ~header_checksum;
if(header_checksum != 0){
ip_DiscardPkt(pBuffer, STUD_IP_TEST_CHECKSUM_ERROR);
return -1;
}
ip_SendtoUp(pBuffer, length);
return 0;
}
int stud_ip_Upsend(char* pBuffer, unsigned short len, unsigned int srcAddr,
unsigned int dstAddr ,byte protocol, byte ttl){
unsigned int version = 4;
unsigned int ip_head_length = 5; // no option header in this case
unsigned int total_length = 4 * ip_head_length + len;
unsigned char* total_buffer = malloc(total_length);
memset(total_buffer, 0, total_length);
total_buffer[0] = (version << 4) | ip_head_length;
// type of service not specified -> set to zero
total_buffer[2] = total_length >> 8;
total_buffer[3] = total_length & 0xFF;
// identification, flags, fragment offset not specified
total_buffer[8] = time_to_live;
total_buffer[9] = protocol;
total_buffer[12] = srcAddr >> 24;
total_buffer[13] = srcAddr >> 16;
total_buffer[14] = srcAddr >> 8;
total_buffer[15] = srcAddr & 0xFF;
total_buffer[16] = dstAddr >> 24;
total_buffer[17] = dstAddr >> 16;
total_buffer[18] = dstAddr >> 8;
total_buffer[19] = dstAddr & 0xFF;
unsigned int header_checksum = 0;
for(int i = 0; i < 20; i += 2){
header_checksum += (total_buffer[i] << 8) + total_buffer[i + 1];
}
while(header_checksum >> 16){
header_checksum == (header_checksum >> 16) + (header_checksum & 0xFFFF);
}
header_checksum = ~header_checksum;
total_buffer[10] = header_checksum >> 8;
total_buffer[11] = header_checksum & 0xFF;
memcpy(total_buffer + 20, pBuffer, len);
ip_SendtoLower(total_buffer, total_length);
return 0;
}
|
C
|
#ifndef LAB1_5_PRINT_H
#define LAB1_5_PRINT_H
#include "Matrix.h"
void PrintMatrixToFile(Matrix &A, ofstream &fout) {
int32_t n = A.size();
for (int32_t i = 0; i < n; ++i) {
for (int32_t j = 0; j < n; ++j) {
fout.width(10);
fout.precision(3);
fout << left << A.get(i, j) << " ";
}
fout << "\n";
}
fout << "\n";
}
void PrintVectorToFile(vector<double> &v, ofstream &fout) {
fout << "(";
for (int32_t i = 0; i < v.size() - 1; ++i) {
fout << v[i] << " ";
}
fout << v[v.size() - 1];
fout << ")\n\n";
}
#endif //LAB1_5_PRINT_H
|
C
|
#include <stdio.h>
int fun(char *a){
printf("fun: %lu\n",sizeof(a));
return 1;
}
int main(void){
char a[20];
int *ptr = a;
printf("main: %lu\n",sizeof(fun(a)));
printf("main: %lu\n",sizeof(fun));
return 0;
}
|
C
|
#include<stdio.h>
int greatNum(int a, int b); // function declaration
int main()
{
int i, j, result;
printf("Enter 2 numbers that you want to compare...");
scanf("%d%d", &i, &j);
result = greatNum(i, j); // function call
printf("The greater number is: %d", result);
return 0;
}
int greatNum(int x, int y) // function definition
{
if(x > y) {
return x;
}
else {
return y;
}
}
|
C
|
// This program reads input with floating-point conversion specifier
// by Ericka.H
#include<stdio.h>
int main(void) {
double a;
double b;
double c;
puts("Enter three floating-point numbers:");
scanf("%le%lf%lg", &a, &b, &c);
printf("\nHere are the numbers entered in plain:");
puts("floating-pint notation:\n");
printf("%f\n%f\n%f\n", a, b, c);
}
|
C
|
#include <wiringPi.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
/**
* A program to turn on/off a LED through a button(the polling way).
*
* @author Darran Zhang @ codelast.com
*/
int main (int argc,char* argv[])
{
if (argc < 3) {
printf("Usage example: ./%s button_gpio_port led_gpio_port\n", argv[0]);
return 1;
}
int buttonGpioPort = atoi(argv[1]);
int ledGpioPort = atoi(argv[2]);
wiringPiSetup();
pinMode(buttonGpioPort, INPUT); // set mode to input
pinMode(ledGpioPort, OUTPUT); // set mode to output
int level = 0;
while(1) {
int currentLevel = digitalRead(buttonGpioPort);
// when the button is pressed/released, we want the LED to be turn on/off
if (level != currentLevel) {
digitalWrite(ledGpioPort, level); // turn on/off the LED
level = currentLevel;
}
delay(10);
}
return 0;
}
|
C
|
// base on https://github.com/bk138/Multicast-Client-Server-Example
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include "mcast-socket.h"
#define LOG_TAG "MCAST"
#include "Log.h"
#if 0
static void dump_hex(char* title, unsigned char* raw, int length)
{
int i;
printf("dump_hex(%s):\n", title);
for (i = 0; i < length; i++) {
printf("%02X ", raw[i]);
}
printf("\n");
}
#endif
/*
Init a socket fd for sending multicast packet.
multicastIP:
multicast ip addr
multicastPort:
multicast port
multicastAddr:
multicast addr instance for send_mcast_message()
Return socket fd for success, -1 for fail
*/
SOCKET init_send_mcast_socket(char* multicastIP, char* multicastPort, struct addrinfo **multicastAddr)
{
SOCKET sock = INVALID_SOCKET;
struct addrinfo hints = { 0 }; /* Hints for name lookup */
int multicastTTL = LP_MUTICAST_TTL;
int result;
#ifdef WIN32
WSADATA trash;
if(WSAStartup(MAKEWORD(2,0),&trash)!=0) {
LOGE("WSAStartup failed");
return -1;
}
#endif
// Resolve destination address for multicast datagrams
hints.ai_family = AF_INET; //PF_UNSPEC;
hints.ai_socktype = SOCK_DGRAM;
hints.ai_flags = AI_NUMERICHOST;
result = getaddrinfo(multicastIP, multicastPort, &hints, multicastAddr);
SOCKET_NONZERO_GOTO_ERROR(result, "init_send_mcast_socket: getaddrinfo failed");
// Create socket for sending multicast datagrams
sock = socket((*multicastAddr)->ai_family, (*multicastAddr)->ai_socktype, 0);
SOCKET_NOTVALID_GOTO_ERROR(sock, "init_send_mcast_socket: socket() failed");
// Set TTL of multicast packet
result = setsockopt(sock,
(*multicastAddr)->ai_family == PF_INET6 ? IPPROTO_IPV6 : IPPROTO_IP,
(*multicastAddr)->ai_family == PF_INET6 ? IPV6_MULTICAST_HOPS : IP_MULTICAST_TTL,
(char*) &multicastTTL, sizeof(multicastTTL));
SOCKET_RESULT_GOTO_ERROR(result, "TTL setsockopt() failed");
// set the sending interface
if((*multicastAddr)->ai_family == PF_INET) {
in_addr_t iface = INADDR_ANY; /* well, yeah, any */
result = setsockopt (sock,
IPPROTO_IP,
IP_MULTICAST_IF,
(char*)&iface, sizeof(iface));
SOCKET_RESULT_GOTO_ERROR(result, "IP_MULTICAST_IF setsockopt() failed");
}
if((*multicastAddr)->ai_family == PF_INET6) {
unsigned int ifindex = 0; /* 0 means 'default interface'*/
setsockopt (sock,
IPPROTO_IPV6,
IPV6_MULTICAST_IF,
(char*)&ifindex, sizeof(ifindex));
SOCKET_RESULT_GOTO_ERROR(result, "IPV6_MULTICAST_IF setsockopt() failed");
}
return sock;
error:
if (sock != INVALID_SOCKET) {
close(sock);
sock = INVALID_SOCKET;
}
if (*multicastAddr) {
freeaddrinfo(*multicastAddr);
}
return -1;
}
/*
Init a socket fd for reading multicast packet.
Return socket fd for success, -1 for fail
*/
SOCKET init_recv_mcast_sockt(char* multicastIP, char* multicastPort)
{
SOCKET sock = INVALID_SOCKET;
struct addrinfo hints = { 0 }; /* Hints for name lookup */
struct addrinfo* localAddr = 0; /* Local address to bind to */
struct addrinfo* multicastAddr = 0; /* Multicast Address */
int yes=1;
int result;
#ifdef WIN32
WSADATA wsaData;
WSAStartup(MAKEWORD(2,2), &wsaData);
int tv = 30000; // 30 sec.
#else
struct timeval tv;
tv.tv_sec = 30; // 30 Secs Timeout
tv.tv_usec = 0;
#endif
// Get the family of multicast address
hints.ai_family = AF_INET; //PF_UNSPEC;
hints.ai_flags = AI_NUMERICHOST; // return a numerical network address
result = getaddrinfo(multicastIP, NULL, &hints, &multicastAddr);
SOCKET_NONZERO_GOTO_ERROR(result, "getaddrinfo failed 1");
/*
Get a local address with the same family (IPv4 or IPv6) as our multicast group
It is port specified address.
*/
hints.ai_family = multicastAddr->ai_family;
hints.ai_socktype = SOCK_DGRAM;
hints.ai_flags = AI_PASSIVE; // full the address of local machine, so we can bind it.
result = getaddrinfo(NULL, multicastPort, &hints, &localAddr);
SOCKET_NONZERO_GOTO_ERROR(result, "getaddrinfo failed 2");
// Create socket for receiving datagrams
sock = socket(localAddr->ai_family, localAddr->ai_socktype, 0);
SOCKET_NOTVALID_GOTO_ERROR(sock, "socket() failed");
// Enable SO_REUSEADDR to allow multiple instances of this application to receive copies of the multicast datagrams.
result = setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,(char*)&yes,sizeof(int));
SOCKET_RESULT_GOTO_ERROR(result, "SO_REUSEADDR setsockopt() failed");
// set timeout to avoid tcp port is occupy by dead proccess
result = setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO,(char*)&tv,sizeof(struct timeval));
SOCKET_RESULT_GOTO_ERROR(result, "SO_RCVTIMEO setsockopt() failed");
result = bind(sock, localAddr->ai_addr, localAddr->ai_addrlen);
SOCKET_RESULT_GOTO_ERROR(result, "bind() failed");
// Join the multicast group. We do this seperately depending on whether we are using IPv4 or IPv6.
if ( multicastAddr->ai_family == PF_INET &&
multicastAddr->ai_addrlen == sizeof(struct sockaddr_in) ) //IPv4
{
struct ip_mreq multicastRequest; // Multicast address join structure
// Specify the multicast group
memcpy(&multicastRequest.imr_multiaddr,
&((struct sockaddr_in*)(multicastAddr->ai_addr))->sin_addr,
sizeof(multicastRequest.imr_multiaddr));
// Accept multicast from any interface
multicastRequest.imr_interface.s_addr = htonl(INADDR_ANY);
// Join the multicast address
if ( setsockopt(sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char*) &multicastRequest, sizeof(multicastRequest)) != 0 ) {
LOGE("IP_ADD_MEMBERSHIP setsockopt() failed, errno=%d", errno);
goto error;
}
}
else if ( multicastAddr->ai_family == PF_INET6 &&
multicastAddr->ai_addrlen == sizeof(struct sockaddr_in6) ) /* IPv6 */
{
struct ipv6_mreq multicastRequest; /* Multicast address join structure */
/* Specify the multicast group */
memcpy(&multicastRequest.ipv6mr_multiaddr,
&((struct sockaddr_in6*)(multicastAddr->ai_addr))->sin6_addr,
sizeof(multicastRequest.ipv6mr_multiaddr));
/* Accept multicast from any interface */
multicastRequest.ipv6mr_interface = 0;
/* Join the multicast address */
if ( setsockopt(sock, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, (char*) &multicastRequest, sizeof(multicastRequest)) != 0 ) {
LOGE("IPV6_ADD_MEMBERSHIP setsockopt() failed, errno=%d", errno);
goto error;
}
}
else {
LOGE("Neither IPv4 or IPv6, errno=%d", errno);
goto error;
}
if(localAddr)
freeaddrinfo(localAddr);
if(multicastAddr)
freeaddrinfo(multicastAddr);
return sock;
error:
if (sock != INVALID_SOCKET) {
close(sock);
}
if(localAddr)
freeaddrinfo(localAddr);
if(multicastAddr)
freeaddrinfo(multicastAddr);
return INVALID_SOCKET;
}
/*
Read message from multicast network
sock:
multicast socket fd
message:
message buffer to read
length:
length limit of message
addr:
addr should be the ipv4(16) or ipv6(40)
Return the length of mcast message that read, -1 for fail
*/
int read_mcast_message(SOCKET sock,
unsigned char* message,
int length,
char* addr)
{
int bytes;
struct sockaddr srcAddr;
socklen_t addrlen = sizeof(struct sockaddr);
struct sockaddr_in* addr4;
struct sockaddr_in6* addr6;
/*
// read total legnth
bytes = recvfrom(sock, ((unsigned char*)&totalLength), sizeof(totalLength), 0, &srcAddr, &addrlen);
SOCKET_RESULT_GOTO_ERROR(bytes, "recv(totalLength) failed");
if (bytes != sizeof(totalLength)) { // end of one mcast packet, but data is not complete
return -1;
}
*/
// read data
bytes = recvfrom(sock, message, length, 0, &srcAddr, &addrlen);
SOCKET_RESULT_GOTO_ERROR(bytes, "recv(message) failed");
if (bytes != length) { // end of one mcast packet, but data is not complete
LOGE("recv(message) length is not match");
return -1;
}
// resolve addr
if (addr) {
if (addrlen == sizeof(struct sockaddr_in)) {
addr4 = (struct sockaddr_in*) &srcAddr;
inet_ntop(AF_INET, &(addr4->sin_addr), addr, INET_ADDRSTRLEN);
} else if (addrlen == sizeof(struct sockaddr_in6)) {
addr6 = (struct sockaddr_in6*) &srcAddr;
inet_ntop(AF_INET, &(addr6->sin6_addr), addr, INET6_ADDRSTRLEN);
}
}
/*
if (totalLength > length) { // read remainder
LOGE("read_mcast_message: cipher size is not engouth, require %d", totalLength);
recv(sock, message, totalLength-length, 0); // flush buffer
return -1;
}
*/
return length;
error:
return -1;
}
/*
Send message to multicast network
sock:
multicast socket fd
addr:
multicast addr
message:
message buffer to send
length
length of message to be sent
return 0 for success, -1 for fail
*/
int send_mcast_message(SOCKET sock,
struct addrinfo* addr,
const unsigned char* message,
int length)
{
// send data
if ( sendto(sock, message, length, 0,
addr->ai_addr, addr->ai_addrlen) != length )
{
LOGE("sendto(message) fail, errno=%d", errno);
return -1;
}
return 0;
}
/*
Read message from multicast network with simple protocol
| data length | raw data |
sock:
multicast socket fd
message:
message buffer to read
length:
length limit of message
addr:
addr should be the ipv4(16) or ipv6(40)
Return the length of mcast message that read, -1 for fail
*/
int read_mcast_message_ex(SOCKET sock,
unsigned char* message,
int length,
char* addr)
{
int32_t dataLength;
int bytes;
struct sockaddr srcAddr;
socklen_t addrlen = sizeof(struct sockaddr);
struct sockaddr_in* addr4;
struct sockaddr_in6* addr6;
// read data legnth
bytes = recvfrom(sock, ((unsigned char*)&dataLength), sizeof(dataLength), 0, &srcAddr, &addrlen);
SOCKET_RESULT_GOTO_ERROR(bytes, "recvfrom(dataLength) failed");
if (bytes != sizeof(dataLength)) { // end of one mcast packet, but data is not complete
LOGE("recvfrom(dataLength) length is not match, %d, %d", bytes, dataLength);
return -1;
}
if (dataLength > length) {
LOGE("read_mcast_message_ex: Buffer is not engouth, dataLength=%d", dataLength);
return -1;
}
// read data
bytes = recvfrom(sock, message, dataLength, 0, NULL, NULL);
SOCKET_RESULT_GOTO_ERROR(bytes, "recvfrom(message) failed");
if (bytes != dataLength) { // end of one mcast packet, but data is not complete
LOGE("recvfrom(message) length is not match, %d, %d", bytes, dataLength);
return -1;
}
// resolve addr
if (addr) {
if (addrlen == sizeof(struct sockaddr_in)) {
addr4 = (struct sockaddr_in*) &srcAddr;
inet_ntop(AF_INET, &(addr4->sin_addr), addr, INET_ADDRSTRLEN);
} else if (addrlen == sizeof(struct sockaddr_in6)) {
addr6 = (struct sockaddr_in6*) &srcAddr;
inet_ntop(AF_INET, &(addr6->sin6_addr), addr, INET6_ADDRSTRLEN);
}
}
/*
if (dataLength > length) { // read remainder
LOGE("read_mcast_message_ex: cipher size is not engouth, require %d", dataLength);
recv(sock, message, dataLength-length, 0); // flush buffer
return -1;
}
*/
return dataLength;
error:
return -1;
}
/*
Send message to multicast network with simple protocol
| data length | raw data |
sock:
multicast socket fd
addr:
multicast addr
message:
message buffer to send
length
length of message to be sent
return 0 for success, -1 for fail
*/
int send_mcast_message_ex(SOCKET sock,
struct addrinfo* addr,
const unsigned char* message,
int32_t length)
{
int result;
// send legnth
if ( (result = sendto(sock, (unsigned char*) &length, sizeof(length), 0,
addr->ai_addr, addr->ai_addrlen) ) != sizeof(length) ) {
SOCKET_RESULT_GOTO_ERROR(result, "sendto(length) fail");
return -1;
}
// send data
if ( (result = sendto(sock, message, length, 0,
addr->ai_addr, addr->ai_addrlen) ) != length )
{
LOGE("sendto(message) fail, errno=%d", errno);
SOCKET_RESULT_GOTO_ERROR(result, "sendto(message) fail");
return -1;
}
return 0;
error:
return -1;
}
|
C
|
#define GPS_STRUCT_GLOBAL
#include "include.h"
///1=1/Сʱ=1.852ǧ/Сʱ
uint8 GpsGetTime(uint8 utc_time[],uint8 hex_time[])
{
uint8 i,res,u8_val;
res = IsValidNum(utc_time,6);
if(!res)
{
goto RETURN_LAB;
}
for(i=0;i<3;i++)
{
u8_val = (utc_time[i*2] - '0')*10;
u8_val += utc_time[i*2+1] - '0';
hex_time[i] = u8_val;
}
if((hex_time[0] >= 24)||(hex_time[1] >= 60)||(hex_time[2] >= 60))
{
res = FALSE;
}
else
{
res = TRUE;
}
RETURN_LAB:
return res;
}
uint8 GpsGetDate(uint8 utc_date[],uint8 hex_date[])
{
uint8 i,u8_val,res;
res = IsValidNum(utc_date,6);
if(!res)
{
goto RETURN_LAB;
}
for(i=0;i<3;i++)
{
u8_val = (utc_date[i*2] - '0')*10;
u8_val += utc_date[i*2+1] - '0';
hex_date[2-i] = u8_val;
}
if((hex_date[0] < 14 )||
(hex_date[0] >= 99)||
(hex_date[1] > 12 )||
(hex_date[1] < 1 )||
(hex_date[2] > 31)||
(hex_date[2] < 1))///꣬£
{
res = FALSE;
}
else
{
res = TRUE;
}
RETURN_LAB:
return res;
}
uint8 GpsCharFloatDataToHex(uint8 gps_data[],uint8 len,uint8 type,uint32 *r_val)///GPSַתʮ
{
uint8 i,j,k,m,res;
uint32 u32_val = 0,u32_val_div = 0;
res = IsValidCharFloatNum(gps_data,len);
if(!res)
{
goto RETURN_LAB;
}
for(i=0;i<len;i++)
{
if(gps_data[i] != '.')
{
u32_val *= 10;
u32_val += gps_data[i] - 0x30;
}
else
{
j = len - i - 1;///Сλ
break;
}
}
i++;
if((type == LAT_TYPE)||(type == LONG_TYPE))///γȡС5λ
{
k = 0;
if(j > 5)
{
j = 5;
}
else
{
if(j < 5)
{
k = 5 - j;///5λ0
}
}
}
if((type == LAT_TYPE)||(type == LONG_TYPE))
{
u32_val_div = u32_val % 100;
u32_val /= 100;
u32_val *= 100;
for(m=0;m<j;m++)///С
{
u32_val *= 10;
u32_val_div *= 10;
u32_val_div += gps_data[i++] - 0x30;
}
for(m=0;m<k;m++)
{
u32_val *= 10;
u32_val_div *= 10;
}
u32_val_div += 5;///l
u32_val_div = u32_val_div * 5;
u32_val_div /= 3;
}
else
{
for(m=0;m<j;m++)///С
{
u32_val *= 10;
u32_val += gps_data[i++] - 0x30;
}
}
if(type == LAT_TYPE)
{
u32_val += u32_val_div;
u32_val /= 10;///ȣС4λ
if(u32_val > 90000000)
{
res = FALSE;
goto RETURN_LAB;
}
}
else if(type == LONG_TYPE)
{
u32_val += u32_val_div;
u32_val /= 10;
if(u32_val > 180000000)
{
res = FALSE;
goto RETURN_LAB;
}
}
else if(type == SPEED_TYPE)
{
for(i=0;i<j;i++)///ȡ
{
u32_val /= 10;
}
u32_val *= 1852;
u32_val /= 1000;
if(u32_val > 255)///תKM/H
{
res = FALSE;
goto RETURN_LAB;
}
}
else if(type == DIR_TYPE)
{
for(i=0;i<j;i++)///ȡ
{
u32_val /= 10;
}
u32_val /= 2;///12
if(u32_val > 180)
{
res = FALSE;
goto RETURN_LAB;
}
}
else if(type == AMP_TYPE)
{
for(i=0;i<j;i++)///ȡ
{
u32_val /= 10;
}
if(u32_val > 9999)
{
res = FALSE;
goto RETURN_LAB;
}
}
else
{
res = FALSE;
goto RETURN_LAB;
}
*r_val = u32_val;
res = TRUE;
RETURN_LAB:
return res;
}
void GpsAdd8Hour(uint8 d_t[])
{
if(d_t[3] < 16)
{
d_t[3] += 8;
}
else
{
d_t[3] += 8;
d_t[3] = d_t[3] % 24;
d_t[2] += 1;
if(d_t[2] > 28)
{
switch(d_t[1])
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
{
if(d_t[2] > 31)
{
d_t[2] = 1;
d_t[1] += 1;
}
break;
}
case 2:
{
if((d_t[0] % 4 == 0)&&(d_t[0] % 100 != 0))
{
if(d_t[2] > 29)
{
d_t[2] = 1;
d_t[1] += 1;
}
}
else
{
if(d_t[2] > 28)
{
d_t[2] = 1;
d_t[1] += 1;
}
}
break;
}
case 4:
case 6:
case 9:
case 11:
{
if(d_t[2] > 30)
{
d_t[2] = 1;
d_t[1] += 1;
}
break;
}
case 12:
{
if(d_t[2] > 31)
{
d_t[2] = 1;
d_t[1] = 1;
d_t[0] += 1;
}
break;
}
}
}
}
}
void GpsGetGprmcGpggaInfo(uint8 gps_data[],uint8 len,uint8 type)///ȡGPRMC
{
uint8 i,j,dot_index[9],t_d[6],res,res_1,res_2;
uint8 lat_len,long_len,speed_len,dir_len,sat_len,amp_len;
uint16 tmp_amp_val;
uint32 lat_val,long_val,speed_val,dir_val,sat_val,amp_val;
#ifdef GPS_DEBUG
char str_ch[256];
uint8 str_len;
#endif
i = 0;j = 0;
while((i<len)&&(j<11))
{
if(gps_data[i] == ',')
{
dot_index[j++] = i;
}
i++;
}
if(j != 11)
{
goto RETURN_LAB;
}
if(type == RMC_TYPE)
{
if((gps_data[0] != ',')&&(dot_index[0] >= 6)&&
(gps_data[dot_index[7]+1] != ',')&&((dot_index[8]-dot_index[7]) >= 6))///ȡʱ
{
res_1 = GpsGetTime(gps_data,t_d+3);
res_2 = GpsGetDate(gps_data+dot_index[7]+1,t_d);
if(res_1 && res_2)
{
GpsAdd8Hour(t_d);
MemCpy(sys_work_para_struct.date_time,t_d,6);
if(sys_misc_run_struct.gps_need_datetime_check_flag)
{
sys_misc_run_struct.gps_need_datetime_check_flag = FALSE;
RtcSetCalendarTime();
}
#ifdef GPS_DEBUG
str_len = sprintf(str_ch,"%02d%02d%02d %02dʱ%02d%02d\t",t_d[0],t_d[1],t_d[2],t_d[3],t_d[4],t_d[5]);
LocalDebug((uint8*)str_ch,str_len,LOCAL_GPS_DEBUG);
#endif
}
}
if(type == RMC_TYPE)
{
if(gps_data[dot_index[0]+1] != 'A')
{
OFF_GPS_LED();
sys_work_para_struct.term_run_status_word &= ~STATE_A_GPS;
}
else
{
sys_work_para_struct.term_run_status_word |= STATE_A_GPS;
ON_GPS_LED();
}
}
if(!(sys_work_para_struct.term_run_status_word & STATE_A_GPS))
{
goto RETURN_LAB;
}
lat_len = dot_index[2]-dot_index[1]-1;
long_len = dot_index[4]-dot_index[3]-1;
if((gps_data[dot_index[1]+1] != ',')&&(lat_len > 0)&&
(gps_data[dot_index[3]+1] != ',')&&(long_len > 0))
{
if(((gps_data[dot_index[2]+1] == 'N')||(gps_data[dot_index[2]+1] == 'S'))&&
((gps_data[dot_index[4]+1] == 'E')||(gps_data[dot_index[4]+1] == 'W')))///ȡγ뾭
{
res_1 = GpsCharFloatDataToHex(gps_data+dot_index[1]+1,lat_len,LAT_TYPE,&lat_val);
res_2 = GpsCharFloatDataToHex(gps_data+dot_index[3]+1,long_len,LONG_TYPE,&long_val);
if(res_1 && res_2)
{
if(gps_data[dot_index[2]+1] == 'N')
{
sys_work_para_struct.term_run_status_word |= STATE_N_LAT;
}
else
{
sys_work_para_struct.term_run_status_word &= ~STATE_N_LAT;
}
if(gps_data[dot_index[4]+1] == 'E')
{
sys_work_para_struct.term_run_status_word |= STATE_E_LONG;
}
else
{
sys_work_para_struct.term_run_status_word &= ~STATE_E_LONG;
}
sys_data_struct.gps_info_of_gprs[LAT_INDEX] = lat_val >> 24;
sys_data_struct.gps_info_of_gprs[LAT_INDEX+1] = lat_val >> 16;
sys_data_struct.gps_info_of_gprs[LAT_INDEX+2] = lat_val >> 8;
sys_data_struct.gps_info_of_gprs[LAT_INDEX+3] = lat_val;
sys_data_struct.gps_info_of_gprs[LONG_INDEX] = long_val >> 24;
sys_data_struct.gps_info_of_gprs[LONG_INDEX+1] = long_val >> 16;
sys_data_struct.gps_info_of_gprs[LONG_INDEX+2] = long_val >> 8;
sys_data_struct.gps_info_of_gprs[LONG_INDEX+3] = long_val;
#ifdef GPS_DEBUG
str_len = sprintf(str_ch,"%ld%c %ld%c\t",lat_val,gps_data[dot_index[2]+1],long_val,gps_data[dot_index[4]+1]);
LocalDebug((uint8*)str_ch,str_len,LOCAL_GPS_DEBUG);
#endif
}
}
}
speed_len = dot_index[6]-dot_index[5]-1;
if((gps_data[dot_index[5]+1] != ',')&&(speed_len > 0))///ȡٶ
{
res = GpsCharFloatDataToHex(gps_data+dot_index[5]+1,speed_len,SPEED_TYPE,&speed_val);
if(res)
{
sys_data_struct.gps_info_of_gprs[SPEED_INDEX] = speed_val;
#ifdef GPS_DEBUG
str_len = sprintf(str_ch,"ٶȣ%03d\t",speed_val);
LocalDebug((uint8*)str_ch,str_len,LOCAL_GPS_DEBUG);
#endif
}
}
dir_len = dot_index[7]-dot_index[6]-1;
if((gps_data[dot_index[6]+1] != ',')&&(dir_len > 0))///ȡ
{
res = GpsCharFloatDataToHex(gps_data+dot_index[6]+1,dir_len,DIR_TYPE,&dir_val);
if(res)
{
sys_data_struct.gps_info_of_gprs[DIR_INDEX] = dir_val;
#ifdef GPS_DEBUG
str_len = sprintf(str_ch,"%03d \t",dir_val*2);
LocalDebug((uint8*)str_ch,str_len,LOCAL_GPS_DEBUG);
#endif
}
}
}
else if(type == GGA_TYPE)
{
sat_len = dot_index[6]-dot_index[5]-1;
if((gps_data[dot_index[5]+1] != ',')&&(sat_len > 0)&&(sat_len <= 2))///ȡǸ
{
res = IsValidNum(gps_data+dot_index[5]+1,sat_len);
if(res)
{
sat_val = 0;
for(i=0;i<sat_len;i++)
{
sat_val *= 10;
sat_val += gps_data[dot_index[5]+1+i] - 0x30;
}
sys_data_struct.gps_info_of_gprs[SAT_INDEX] = sat_val;
#ifdef GPS_DEBUG
str_len = sprintf(str_ch,": %02d\t",sat_val);
LocalDebug((uint8*)str_ch,str_len,LOCAL_GPS_DEBUG);
#endif
}
}
else
{
sys_data_struct.gps_info_of_gprs[SAT_INDEX] = 0;
}
amp_len = dot_index[8]-dot_index[7]-1;
if((gps_data[dot_index[7]+1] != ',')&&(amp_len > 0))///ȡ
{
tmp_amp_val = 0x0000;
i = 1;
if(gps_data[dot_index[7]+1] == '-')
{
tmp_amp_val = 0x8000;
i = 2;
amp_len -= 1;
}
res = GpsCharFloatDataToHex(gps_data+dot_index[7]+i,amp_len,AMP_TYPE,&_val);
if(res)
{
amp_val = tmp_amp_val | amp_val;
sys_data_struct.gps_info_of_gprs[AMP_INDEX] = amp_val >> 8;
sys_data_struct.gps_info_of_gprs[AMP_INDEX+1] = amp_val;
#ifdef GPS_DEBUG
str_len = sprintf(str_ch,": %d\r\n",amp_val);
LocalDebug((uint8*)str_ch,str_len,LOCAL_GPS_DEBUG);
#endif
}
}
}
RETURN_LAB:
return;
}
uint8 GpsFrameCheck(uint8 gps_data[],uint8 len)
{
uint8 i,res = FALSE;
uint8 gps_check,cal_check;
i = 0;
cal_check = gps_data[i++];
for(i=1;i<len-3;i++)
{
cal_check ^= gps_data[i];
}
gps_check = AsciiToHexVal(gps_data[len-2],gps_data[len-1]);
if(gps_check == cal_check)
{
res = TRUE;
}
return res;
}
uint8 GetGpsInfo(uint8 data[])
{
uint32 tmp_status;
MemCpy(data,sys_data_struct.gps_info_of_gprs,12);
tmp_status = sys_work_para_struct.term_run_status_word;
tmp_status &= STATE_MASK_BITS;
MemCpy(data+12,(uint8*)&tmp_status,4);
RtcGetCalendarTime(data+16);
return GPS_INFO_LEN;
}
void GpsMain(void)
{
uint8 res,rx_data[GPS_UART_BUF_LEN],rx_gprmc_flag = FALSE;
uint16 mat_index,rx_len,i,j;
static uint16 sys_rtc_pre_val=0;
static uint16 sys_rtc_cur_val=0;
uint16 past_sec_val;
sys_rtc_cur_val = sys_misc_run_struct.sys_rtc_sec_counter;///ȡϵͳrtc sec
past_sec_val = (sys_rtc_cur_val + (65535 - sys_rtc_pre_val)) % 65535;
rx_len = GetGpsUartRxData(rx_data);
if(rx_len > 0)
{
sys_rtc_pre_val = sys_rtc_cur_val;
#ifdef GPS_DEBUG
LocalDebug(rx_data,rx_len,LOCAL_GPS_DEBUG);
#endif
i = 0;
j = 0;
while(rx_len > 3)///ȥ$,CH,CRַ
{
while((rx_data[i] != '$')&&(i<rx_len))
{
i++;
}
if(i == rx_len)
{
break;
}
j=0;
while((rx_data[i+j] != 0x0a)&&((i+j)<rx_len))
{
j++;
}
if((i+j) == rx_len)
{
break;
}
res = GpsFrameCheck(rx_data+i+1,j-2);///֡У
if(res)
{
gps_struct.gps_rx_right_data_flag = TRUE;
mat_index = SubMatch("$GPRMC,",StrLen("$GPRMC,",0),rx_data+i,j);
if(mat_index > 0)
{
gps_struct.sms_gprmc_ack[0] = VALID_VAL_2A;
MemCpy(gps_struct.sms_gprmc_ack+1,rx_data+i,j-1);
rx_gprmc_flag = TRUE;
gps_struct.sms_gprmc_ack[j] = '\0';
GpsGetGprmcGpggaInfo(rx_data+i+mat_index,j-mat_index,RMC_TYPE);///GPRMC,GPGGA
}
if(!rx_gprmc_flag)
{
gps_struct.sms_gprmc_ack[0] = '\0';
}
if(mat_index > 0)
{
i += j;
continue;
}
mat_index = SubMatch("$GPGGA,",StrLen("$GPGGA,",0),rx_data+i,j);
if(mat_index > 0)
{
GpsGetGprmcGpggaInfo(rx_data+i+mat_index,j-mat_index,GGA_TYPE);///GPRMC,GPGGA
break;///GGAֱӽ
}
}
i += j;
}
}
else
{
if(past_sec_val > 10)///10,δյ,GPSλ־
{
sys_work_para_struct.term_run_status_word &= ~STATE_A_GPS;
sys_misc_run_struct.gps_need_datetime_check_flag = TRUE;
gps_struct.sms_gprmc_ack[0] = '\0';
OFF_GPS_LED();
}
}
}
|
C
|
#include <stdio.h>
int main(void)
{
int a, b;
int t;
scanf("%d%d", &a, &b);
t = a > b;
if (t == 1) {
goto true;
}
printf("a is lower than b\n");
goto done;
true:
printf("a is higher than b\n");
done:
return 0;
}
|
C
|
/*Задача 10.
Как работи? Дефинираме променлива “а“, дефинираме
пойнтер, но още не му задаваме стойност. Отпечатайте
адреса на “а”. След това присвояваме стойност на
пойнтера, като внимаваме типовете на пойнтера и
променливата да са от един и същи тип. Отпечатваме
на екрана стойността на пойнтера с %р, стойността на
„а“ с %d, стойността на *ptr с %d.*/
#include<stdio.h>
int main(){
int a;
int*p;
printf("The address of a:%p\n",&a);
p=&a;
printf("The address of p:%p\n",p);
printf("The value of a:%d\n",a);
printf("The value of p:%d\n",*p);
return 0;
}
|
C
|
/*
剑指 Offer 10- I. 斐波那契数列 非递归实现
Garker-gan
2020-11-10
*/
//非递归
int fib(int n){
int a = 0;
int b = (n == 0) ? 0 : 1;
int c = 1e9 + 7; //防止溢出
int res = a+b;
for(int i = 0 ; i < n-1 ; i++)
{
res = (a + b)%c;
a = b;
b = res;
}
return res;
}
|
C
|
// Created by Akira Kyle on 10/26/14.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
int main (void) {
//Setup
clock_t start = clock(), diff;
FILE *file = fopen("Developer/MatterAndInteractionsIProject/Data/gasSimData.txt", "w");
if (file == NULL)
{
printf("Error opening file!\n");
exit(1);
}
struct position {
float x;
float y;
float z;
};
struct velelocity {
float x;
float y;
float z;
};
struct particleStruct {
struct position pos;
struct velelocity vel;
};
//Constants
const unsigned int num = 500; //total number of particles
const int totalTime = 20; //total time simulation is run for
const float dt = 0.01; //time step for numeric integration
const float epsilon = 10; //depth of Lennard Jones potential well (affects magnitude of interatomic force)
const float forceDistance = 0.39; //atomic radius* 2^(1/6) (nm)
//container is cylinder
const float volume = 37.2*num; // in nm^3 (note: 22.4L/mol = 37.2nm^3/particle)
const float hTorRaio = 100; //height/radius ratio
const float temperature = 20; //e-19 temperature in Kelvin
const float mass = 28; //particle mass (diatomic nitrogen) in amu
const float kb = 8.3148; //e21 Boltzman constant 8.3148×10^21 amu nm^2/(s^2*K) (atomic mass unit (chemical scale) nanometers squared per second squared kelvin)
const float avgVelInit = sqrt(3*kb*temperature/mass); //initaizes velocity of the particles (Given by temp) (nm/sec)
//wall that creates pressure wave
const float wallVel = 10; //the velocity that the wall moves to create sound wave
const float period = .5; //the time that the wall takes to move (either forward or back)
//actually like a half period then
//Calculated constants
const float sigma = forceDistance/pow(2,(1.0/6.0)); //Lennard Jones constant
const float k = -24*epsilon*pow(sigma,6)/mass; //Lennard Jones constant simplification
const float cylinderHeight = pow((hTorRaio * volume/M_PI), (1.0/3.0)); //in nm
const float cylinderRadius = pow((volume/(M_PI*hTorRaio)), (1.0/3.0)); //in nm
float cylinderWallPosX = cylinderHeight/2;
const float cylinderWallNegX = -cylinderHeight/2;
const float maxVel = 0.05*cylinderRadius/dt; //limits the maximum vel of the particles (necessary b/c numeric integration and finite time step
printf("height:%f, radius:%f, maxVel:%f\n", cylinderHeight,cylinderRadius,maxVel);
fprintf(file, "cylinderHeight,cylinderRadius,num,totalTime,dt,epsilon,forceDistance,temperature,mass,wallVel,period,maxVel,\n");
fprintf(file, "%f,%f,%d,%d,%f,%f,%f,%f,%f,%f,%f,%f\n",cylinderHeight,cylinderRadius,num,totalTime,dt,epsilon,forceDistance,temperature,mass,wallVel,period,maxVel);
//Var initalizations
struct particleStruct particle[num];
int iteration = 0;
float r;
float forceMag;
float forceX;
float forceY;
float forceZ;
//initilization of particle array
for (int n=0; n<num; n++) {
particle[n].pos.x = ((float)rand()/(float)RAND_MAX * cylinderHeight-.01) - (cylinderHeight/2-.01);
float r = ((float)rand()/(float)RAND_MAX * cylinderRadius-.1);
float theta = ((float)rand()/(float)RAND_MAX * 2 * M_PI);
float phi = ((float)rand()/(float)RAND_MAX * 2 * M_PI);
particle[n].pos.y = r * cos(theta);
particle[n].pos.z = r * sin(theta);
particle[n].vel.x = avgVelInit * sin(phi) * cos(theta);
particle[n].vel.y = avgVelInit * sin(phi) * sin(theta);
particle[n].vel.z = avgVelInit * cos(phi);
}
//start calculations
for (float t=0; t<totalTime; t=t+dt) {
int cycle = (int) floor(t/period);
if ( cycle % 2 == 0) {
cylinderWallPosX = cylinderHeight/2 - (t-cycle*period)*wallVel;
}
else {
cylinderWallPosX = cylinderHeight/2 + (t-period-cycle*period)*wallVel;
}
for (unsigned int i=0; i<num-1; i++) {
if (particle[i].pos.x > cylinderWallPosX) {
particle[i].vel.x = -abs(particle[i].vel.x) - wallVel;
}
if (particle[i].pos.x < cylinderWallNegX) {
particle[i].vel.x = abs(particle[i].vel.x);
}
if (sqrt(pow((particle[i].pos.y), 2) + pow((particle[i].pos.z), 2)) > cylinderRadius) {
float vectConst = 1/( pow(particle[i].pos.y, 2) + pow(particle[i].pos.z, 2) );
particle[i].vel.y = vectConst * (particle[i].vel.y * pow(particle[i].pos.z, 2) -
particle[i].vel.y * pow(particle[i].pos.y, 2) -
2 * particle[i].vel.z * particle[i].pos.y * particle[i].pos.z);
particle[i].vel.z = vectConst * (particle[i].vel.z * pow(particle[i].pos.y, 2) -
particle[i].vel.z * pow(particle[i].pos.z, 2) -
2 * particle[i].vel.y * particle[i].pos.y * particle[i].pos.z);
}
for (unsigned int j=i+1; j<num; j++) {
r = sqrt(pow((particle[i].pos.x - particle[j].pos.x), 2) +
pow((particle[i].pos.y - particle[j].pos.y), 2) +
pow((particle[i].pos.z - particle[j].pos.z), 2));
forceMag = k*(1/pow(r,7))*(1-(2*pow(sigma,6)/pow(r,6)));
forceX = forceMag * (particle[i].pos.x - particle[j].pos.x)/r;
forceY = forceMag * (particle[i].pos.y - particle[j].pos.y)/r;
forceZ = forceMag * (particle[i].pos.z - particle[j].pos.z)/r;
particle[i].vel.x = particle[i].vel.x + forceX*dt;
particle[i].vel.y = particle[i].vel.y + forceY*dt;
particle[i].vel.z = particle[i].vel.z + forceZ*dt;
particle[j].vel.x = particle[j].vel.x - forceX*dt;
particle[j].vel.y = particle[j].vel.y - forceY*dt;
particle[j].vel.z = particle[j].vel.z - forceZ*dt;
if (particle[i].vel.x > maxVel) {
//printf("vel.x:%f\n",particle[i].vel.x);
particle[i].vel.x = maxVel;
}
if (particle[i].vel.y > maxVel) {
particle[i].vel.y = maxVel;
}
if (particle[i].vel.z > maxVel) {
particle[i].vel.z = maxVel;
}
if (particle[i].vel.x < -maxVel) {
particle[i].vel.x = -maxVel;
}
if (particle[i].vel.y < -maxVel) {
particle[i].vel.y = -maxVel;
}
if (particle[i].vel.z < -maxVel) {
particle[i].vel.z = -maxVel;
}
}
particle[i].pos.x = particle[i].pos.x + particle[i].vel.x*dt;
particle[i].pos.y = particle[i].pos.y + particle[i].vel.y*dt;
particle[i].pos.z = particle[i].pos.z + particle[i].vel.z*dt;
fprintf(file, "%f,%f,%f,%f,%f,%f,%f\n",t,particle[i].pos.x,particle[i].pos.y,particle[i].pos.z,particle[i].vel.x,particle[i].vel.y,particle[i].vel.z);
}
if ((iteration % 50) == 0) {
printf("interation:%d\n",iteration);
printf("time:%g\n",t);
}
iteration++;
}
fclose(file);
diff = clock() - start;
int msec = diff * 1000 / CLOCKS_PER_SEC;
printf("Time taken %d seconds %d milliseconds\n", msec/1000, msec%1000);
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_history.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mmartin <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2014/02/09 18:06:15 by mmartin #+# #+# */
/* Updated: 2015/03/31 14:01:28 by mmartin ### ########.fr */
/* */
/* ************************************************************************** */
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include "libft.h"
#include "ft_history.h"
#include "ft_builtin.h"
t_history *ft_last_history(t_history *hist)
{
t_history *last;
last = hist;
while (last && last->prev)
last = last->prev;
return (last);
}
t_history *ft_first_history(t_history *hist)
{
t_history *first;
first = hist;
while (first && first->next)
first = first->next;
return (first);
}
static void ft_init_history(t_data *d)
{
if (d->history && d->history->next)
d->history = d->history->next;
if (d->last_hist == NULL)
d->last_hist = ft_last_history(d->history);
d->first_hist = ft_first_history(d->history);
d->last_hist->prev = d->first_hist;
d->first_hist->next = d->last_hist;
}
static int ft_open_hist(t_data *d)
{
int fd;
char *str;
char *ptr;
str = ft_getenv_list(d->my_env, "HOME");
if (!str)
return (-1);
ptr = str;
str = ft_strjoin(str + 5, "/.42sh_history");
free(ptr);
fd = open(str, O_CREAT | O_RDWR | O_APPEND, 0644);
free(str);
if (fd == -1)
return (-1);
else
return (fd);
}
void ft_history(t_data *d)
{
int fd;
char *ptr;
t_history *hist;
if ((fd = ft_open_hist(d)) == -1 || !d->line->len)
return ;
if (!(ptr = ft_strdup(d->line->str)))
return ;
write(fd, d->line->str, d->line->len);
hist = d->history;
ft_add_history(&hist, ptr);
d->history = hist;
ft_init_history(d);
write(fd, "\n", 1);
close(fd);
ft_strdel(&ptr);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.