language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C
|
#include "ruby_libxml.h"
#include "ruby_xml_schema.h"
/*
* Document-class: LibXML::XML::Schema
*
* The XML::Schema class is used to prepare XML Schemas for validation of xml
* documents.
*
* Schemas can be created from XML documents, strings or URIs using the
* corresponding methods (new for URIs).
*
* Once a schema is prepared, an XML document can be validated by the
* XML::Document#validate_schema method providing the XML::Schema object
* as parameter. The method return true if the document validates, false
* otherwise.
*
* If a block is provided to the XML::Document#validate_schema method,
* it functions as an error handler that is called with two parameters for
* all errors and warnings. The first parameter is the error or warning message
* the second indicates if the message is an error (true) or a warning (false).
* If no error handler is provided errors are written to stderr.
*
* E.g.
* # parse schema as xml document
* schema_document = XML::Document.file('schema.rng')
* # prepare schema for validation
* schema = XML::Schema.document(schema_document)
*
* # parse xml document to be validated
* instance = XML::Document.file('instance.xml')
*
* # validate without error handler
* validates = instance.validate_schema(schema)
* puts validates ? 'valid' : 'invalid'
*
* # validate with error handler
* messages = { :errors => [], :warnings => [] }
* validates = instance.validate_schema(schema) { | msg, error | messages[ error ? :errors : :warnings ] << msg }
* puts validates ? 'valid' : 'invalid'
* puts "warnings: #{messages[:warnings].join("\n")}"
* puts "errors : #{messages[:errors].join("\n")}"
*/
VALUE cXMLSchema;
// Rdoc needs to know
#ifdef RDOC_NEVER_DEFINED
mLibXML = rb_define_module("LibXML");
mXML = rb_define_module_under(mLibXML, "XML");
#endif
static void
ruby_xml_schema_mark(ruby_xml_schema *rxschema) {
return;
}
void
ruby_xml_schema_free(ruby_xml_schema *rxschema) {
if (rxschema->schema != NULL) {
xmlSchemaFree(rxschema->schema);
rxschema->schema = NULL;
}
ruby_xfree(rxschema);
}
/*
* call-seq:
* XML::Schema.new(schema_uri) -> schema
*
* Create a new schema from the specified URI.
*/
VALUE
ruby_xml_schema_init_from_uri(VALUE class, VALUE uri) {
xmlSchemaParserCtxtPtr parser;
ruby_xml_schema *schema;
Check_Type(uri, T_STRING);
parser = xmlSchemaNewParserCtxt(StringValuePtr(uri));
schema = ALLOC(ruby_xml_schema);
schema->schema = xmlSchemaParse(parser);
xmlSchemaFreeParserCtxt(parser);
return Data_Wrap_Struct(cXMLSchema, ruby_xml_schema_mark, ruby_xml_schema_free, schema);
}
/*
* call-seq:
* XML::Schema.document(document) -> schema
*
* Create a new schema from the specified document.
*/
VALUE
ruby_xml_schema_init_from_document(VALUE class, VALUE document) {
ruby_xml_document_t *rdoc;
ruby_xml_schema *schema;
xmlSchemaParserCtxtPtr parser;
Data_Get_Struct(document, ruby_xml_document_t, rdoc);
parser = xmlSchemaNewDocParserCtxt(rdoc->doc);
schema = ALLOC(ruby_xml_schema);
schema->schema = xmlSchemaParse(parser);
xmlSchemaFreeParserCtxt(parser);
return Data_Wrap_Struct(cXMLSchema, ruby_xml_schema_mark, ruby_xml_schema_free, schema);
}
/*
* call-seq:
* XML::Schema.string("schema_data") -> "value"
*
* Create a new schema using the specified string.
*/
VALUE
ruby_xml_schema_init_from_string(VALUE self, VALUE schema_str) {
xmlSchemaParserCtxtPtr parser;
ruby_xml_schema *rxschema;
Check_Type(schema_str, T_STRING);
parser = xmlSchemaNewMemParserCtxt(StringValuePtr(schema_str), strlen(StringValuePtr(schema_str)));
rxschema = ALLOC(ruby_xml_schema);
rxschema->schema = xmlSchemaParse(parser);
xmlSchemaFreeParserCtxt(parser);
return Data_Wrap_Struct(cXMLSchema, ruby_xml_schema_mark, ruby_xml_schema_free, rxschema);
}
/* TODO what is this patch doing here?
xmlSchemaParserCtxtPtr parser;
xmlSchemaPtr sptr;
xmlSchemaValidCtxtPtr vptr;
+ int is_invalid;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &source) == FAILURE) {
return;
@@ -598,26 +598,24 @@
convert_to_string_ex(&source);
parser = xmlSchemaNewParserCtxt(Z_STRVAL_P(source));
sptr = xmlSchemaParse(parser);
break;
case SCHEMA_BLOB:
convert_to_string_ex(&source);
parser = xmlSchemaNewMemParserCtxt(Z_STRVAL_P(source), Z_STRLEN_P(source));
sptr = xmlSchemaParse(parser);
break;
}
vptr = xmlSchemaNewValidCtxt(sptr);
+ is_invalid = xmlSchemaValidateDoc(vptr, (xmlDocPtr) sxe->document->ptr);
xmlSchemaFree(sptr);
xmlSchemaFreeValidCtxt(vptr);
xmlSchemaFreeParserCtxt(parser);
- if (is_valid) {
- RETURN_TRUE;
- } else {
+ if (is_invalid) {
RETURN_FALSE;
+ } else {
+ RETURN_TRUE;
}
}
}}}
@@ -695,7 +693,7 @@
{
if (!strcmp(method, "xsearch")) {
simplexml_ce_xpath_search(INTERNAL_FUNCTION_PARAM_PASSTHRU);
-#ifdef xmlSchemaParserCtxtPtr
+#ifdef LIBXML_SCHEMAS_ENABLED
} else if (!strcmp(method, "validate_schema_file")) {
simplexml_ce_schema_validate(INTERNAL_FUNCTION_PARAM_PASSTHRU, SCHEMA_FILE);
} else if (!strcmp(method, "validate_schema_buffer")) {
*/
void ruby_init_xml_schema(void) {
cXMLSchema = rb_define_class_under(mXML, "Schema", rb_cObject);
rb_define_singleton_method(cXMLSchema, "new", ruby_xml_schema_init_from_uri, 1);
rb_define_singleton_method(cXMLSchema, "from_string", ruby_xml_schema_init_from_string, 1);
rb_define_singleton_method(cXMLSchema, "document", ruby_xml_schema_init_from_document, 1);
}
|
C
|
#include "vx_resc.h"
#include "vx_util.h"
#include "vx_codes.h"
#include <malloc.h>
#include <assert.h>
#include <string.h>
#include "vx/math/matd.h"
#define MAX_SHD_SZ 65355
// Free memory for this vr, and for the wrapped data:
static void vx_resc_destroy_managed(vx_resc_t * r)
{
//printf("destroying resource %p\n", (void*) r);
free(r->res);
free(r);
}
static vx_resc_t * vx_resc_create(uint32_t type, uint32_t fieldwith, uint32_t count)
{
vx_resc_t * vr = calloc(1, sizeof(vx_resc_t));
vr->destroy = vx_resc_destroy_managed;
vr->id = vx_util_alloc_id();
vr->type = type;
vr->fieldwidth = fieldwith;
vr->count = count;
return vr;
}
vx_resc_t * vx_resc_load(char* path)
{
vx_resc_t * vr = vx_resc_create(GL_BYTE,sizeof(char), 0);
{
FILE *fp = fopen(path,"r");
if (fp == NULL) {
free(vr);
return NULL;
}
char * chars = calloc(MAX_SHD_SZ, sizeof(char));
// add one to effectively null-terminate the shader string
vr->count = fread(chars, sizeof(char), MAX_SHD_SZ, fp) + 1;
assert(vr->count*sizeof(char) < MAX_SHD_SZ);
vr->res = realloc(chars, vr->count*sizeof(char));
fclose(fp);
} // cppcheck-ignore
return vr;
}
vx_resc_t * vx_resc_copyf(float * data, int count)
{
vx_resc_t * vr = vx_resc_create(GL_FLOAT, sizeof(float), count);
// XXX could call vx_resc_createf
vr->res = malloc(vr->fieldwidth*vr->count);
memcpy(vr->res, data, vr->fieldwidth*vr->count);
return vr;
}
vx_resc_t * vx_resc_createf(int count)
{
vx_resc_t * vr = vx_resc_create(GL_FLOAT, sizeof(float), count);
vr->res = malloc(vr->fieldwidth*vr->count);
return vr;
}
vx_resc_t * vx_resc_copyui(uint32_t * data, int count)
{
vx_resc_t * vr = vx_resc_create(GL_UNSIGNED_INT, sizeof(uint32_t), count);
vr->res = malloc(vr->fieldwidth*vr->count);
memcpy(vr->res, data, vr->fieldwidth*vr->count);
return vr;
}
vx_resc_t * vx_resc_copyub(uint8_t * data, int count)
{
vx_resc_t * vr = vx_resc_create(GL_UNSIGNED_BYTE, sizeof(uint8_t), count);
vr->res = malloc(vr->fieldwidth*vr->count);
memcpy(vr->res, data, vr->fieldwidth*vr->count);
return vr;
}
vx_resc_t * vx_resc_create_copy(void * data, int count, int fieldwidth, uint64_t id, int type)
{
vx_resc_t * vr = vx_resc_create(type, fieldwidth, count);
vr->res = malloc(vr->fieldwidth*vr->count);
memcpy(vr->res, data, vr->fieldwidth*vr->count);
return vr;
}
// copy a double array, and convert to floats
vx_resc_t * vx_resc_copydf(double * data, int count)
{ // count, not total byte size
vx_resc_t * vr = vx_resc_create(GL_FLOAT, sizeof(float), count);
vr->res = malloc(vr->fieldwidth*vr->count);
float * fres = vr->res;
for (int i = 0; i < vr->count; i++)
fres[i] = (float)data[i];
return vr;
}
|
C
|
#include <stdio.h>
#include <string.h>
#define N 100
int map[100][100];
int dis[N], vis[N], p[N];
int m, n;
void build() {
int u, v, c;
scanf("%d%d", &n, &m);
memset(map, -1, sizeof(map));
while(m--) {
scanf("%d%d%d", &u, &v, &c);
map[u][v] = map[v][u] = c;
}
}
int mst() {
int i, min, sum = 0;
memset(dis, 127, sizeof(dis));
memset(vis, 0, sizeof(vis));
memset(p, -1, sizeof(p));
dis[0] = 0;
while(1) {
min = n;
for(i = 0; i < n; i++) {
if(!vis[i] && dis[i] < dis[min])
min = i;
}
if(min == n)
return sum;
vis[min] = 1;
if(p[min] != -1)
printf("<%c, %c>\n", p[min]+'a', min+'a');
sum += dis[min];
for(i = 0; i < n; i++) {
if(!vis[i] && map[min][i] != -1 && dis[i] > map[min][i]) {
dis[i] = map[min][i];
p[i] = min;
}
}
}
return sum;
}
void show() {
}
int main() {
build();
printf("%d\n", mst());
show();
return 0;
}
/**
9 14
0 1 4
0 7 8
1 2 8
1 7 11
2 3 7
2 5 4
2 8 2
3 4 9
3 5 14
4 5 10
5 6 2
6 8 6
6 7 1
7 8 7
*/
|
C
|
#include <json/json.h>
#include <stdio.h>
/*
http://linuxprograms.wordpress.com/2010/05/24/json_object_object_foreach/
{
"sitename": "joys of programming",
"tags": ["c", "c++", "java", "PHP"],
"author-details": {
"name": "Joys of Programming",
"Number of Posts": 10
}
}
-> string (sitename)
-> array (tags)
-> object (author-details)
*/
int main()
{
char * string = "{\"sitename\" : \"joys of programming\", \"tags\" : [ \"c\" , \"c++\", \"java\", \"PHP\" ], \"author-details\": { \"name\" : \"Joys of Programming\", \"Number of Posts\" : 10 }}";
json_object * jobj = json_tokener_parse(string);
enum json_type type;
json_object_object_foreach(jobj, key, val) {
printf("type: ",type);
type = json_object_get_type(val);
switch (type) {
case json_type_null: printf("json_type_null\n");
break;
case json_type_boolean: printf("json_type_boolean\n");
break;
case json_type_double: printf("json_type_double\n");
break;
case json_type_int: printf("json_type_int\n");
break;
case json_type_object: printf("json_type_object\n");
break;
case json_type_array: printf("json_type_array\n");
break;
case json_type_string: printf("json_type_string\n");
break;
}
}
return 1;
}
|
C
|
#include "thread_pool.h"
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
typedef struct taskqueue{
int head;
int tail;
threadpool_task_func_t *task_func; /* work func */
void **arg;
}taskqueue_t;
struct threadpool{
int max_thr_num;
pthread_t *thread_id; /*如果不需要destroy线程,也可以取消*/
taskqueue_t *task_queue;
pthread_cond_t cond;
pthread_mutex_t mutex_cond;
pthread_mutex_t mutex_queue;
};
static void* threadpool_excute_task(void *arg);
threadpool_t* threadpool_create(int max_thr_num)
{
int i = 0;
pthread_t td;
threadpool_t *tpool;
return_null_if_fail(tpool = malloc(sizeof (struct threadpool)));
tpool->max_thr_num = max_thr_num;
return_null_if_fail(tpool->thread_id = malloc(max_thr_num*sizeof(pthread_t)));
return_null_if_fail(tpool->task_queue = malloc(sizeof(struct taskqueue)));
return_null_if_fail(tpool->task_queue->arg = malloc(max_thr_num*sizeof(void *)));
return_null_if_fail(tpool->task_queue->task_func = malloc(max_thr_num*sizeof(threadpool_task_func_t)));
tpool->task_queue->head = tpool->task_queue->tail = 0;
if (pthread_mutex_init(&tpool->mutex_queue, NULL) != 0)
return NULL;
if (pthread_mutex_init(&tpool->mutex_cond, NULL) != 0)
return NULL;
if (pthread_cond_init(&tpool->cond, NULL) != 0)
return NULL;
while (max_thr_num > 0) {
if (pthread_create(&td, NULL, threadpool_excute_task, (void *) tpool) == 0) {
tpool->thread_id[i++] = td;
--max_thr_num;
continue;
}
threadpool_destroy(tpool);
tpool = NULL;
break;
}
return tpool;
}
int threadpool_add_task(threadpool_t *thiz, threadpool_task_func_t task_func, void *arg)
{
int index;
index = thiz->task_queue->tail;
return_if_null(thiz);
pthread_mutex_lock(&thiz->mutex_queue);
if((index+1)%thiz->max_thr_num == thiz->task_queue->head)
{
pthread_mutex_unlock(&thiz->mutex_queue);
return -1;
}
thiz->task_queue->arg[index] = arg;
thiz->task_queue->task_func[index] = task_func;
thiz->task_queue->tail = (index+1)%thiz->max_thr_num;
pthread_mutex_unlock(&thiz->mutex_queue);
pthread_cond_signal(&thiz->cond);
return 0;
}
int threadpool_stop_all_task(threadpool_t *thiz)
{
pthread_t i;
return_val_if_fail(thiz, -1);
for (i = 0; i <= thiz->max_thr_num; ++i) {
pthread_cancel(thiz->thread_id[i]);
pthread_join(thiz->thread_id[i], NULL);
}
return 0;
}
int threadpool_destroy(threadpool_t *thiz)
{
return_val_if_fail(thiz, -1);
threadpool_stop_all_task(thiz);
free(thiz->task_queue->arg);
free(thiz->task_queue->task_func);
free(thiz->task_queue);
free(thiz->thread_id);
pthread_mutex_destroy(&thiz->mutex_queue);
pthread_mutex_destroy(&thiz->mutex_cond);
pthread_cond_destroy(&thiz->cond);
thiz = NULL;
return 0;
}
void* threadpool_excute_task(void *arg)
{
int index = 0;
void *tmp_arg = NULL;
threadpool_t *tpool;
tpool = (threadpool_t*)arg;
return_if_null(tpool);
threadpool_task_func_t task_func;
while(1)
{
pthread_mutex_lock(&tpool->mutex_queue);
index = tpool->task_queue->head;
if(index == tpool->task_queue->tail)
{
pthread_mutex_unlock(&tpool->mutex_queue);
pthread_mutex_lock(&tpool->mutex_cond);
pthread_cond_wait(&tpool->cond, &tpool->mutex_cond); //等待线程调度
pthread_mutex_unlock(&tpool->mutex_cond);
}
else
{
task_func = tpool->task_queue->task_func[index];
tmp_arg = tpool->task_queue->arg[index];
tpool->task_queue->head = (index+1) % tpool->max_thr_num;
pthread_mutex_unlock(&tpool->mutex_queue);
task_func(tmp_arg);
printf("process end");
}
}
}
|
C
|
#include<stdio.h>
int main( void ){
int i, j;
printf( "Enter an integer : " );
scanf( "%3d%d", &i, &j );
printf( "%d %d", i, j );
return 0;
}
|
C
|
void colorToNum(char option[], int* input, int* i, int* sel); // Codifica los colores en números
char* numToNoun(int input); // Decodifica los números a sustantivos
char* numToColor(int input); // Decodificar los números a colores
void buscar(int matrix[3][8], int* input, int* output); // Busca coincidencias en la matriz y, si las hay, los muestra; de lo contrario, arroja una advertencia de no coincidencia.
|
C
|
#include <math.h>
#include <stdio.h>
void interp(double ***uf, double ***uc, int nf, int cubic)
/*
Coarse-to-fine prolongation by bilinear interpolation. nf is the fine-grid dimension. The coarsegrid
solution is input as uc[1..nc][1..nc], where nc = nf/2 + 1. The fine-grid solution is
returned in uf[1..nf][1..nf].
*/
{
//int cubic = 0;
if(cubic){
// basic set up
// u[i][j][k] =
//diag ratio
double d = sqrt(3);
int ic,iif,jc,jf,nc,kc,kf;
nc=nf/2+1;
/* Do elements that are copies.*/
for (kc=1,kf=1;kc <= nc;kc++,kf+=2)
for (jc=1,jf=1;jc<=nc;jc++,jf+=2)
for (ic=1,iif=1;ic<=nc;ic++,iif+=2)
uf[iif][jf][kf]=uc[ic][jc][kc];
/* Do odd-numbered columns, interpolating vertically.*/
//printf("odd col\n");
for (jf=1;jf<=nf;jf+=2)
for (iif=2;iif<nf;iif+=2)
for (kf=1;kf <= nf;kf+=2) {
if (jf ==1 || jf ==nf ){
//printf("in odd if\n");
uf[iif][jf][kf]=0.5*(uf[iif+1][jf][kf]+uf[iif-1][jf][kf]);
}
else {
//printf("j %d i %d k %d \n",jf,iif,kf);
uf[iif][jf][kf]=0.25*((2*d-1)/2*d)*(uf[iif+1][jf][kf]+uf[iif-1][jf][kf]) + (0.125/d)*(uf[iif+1][jf-1][kf]+uf[iif-1][jf+1][kf]+uf[iif+1][jf+1][kf]+uf[iif-1][jf-1][kf]);
}
}
//printf("even col\n");
/*Do even-numbered columns, interpolating horizontally.*/
for (jf=2;jf<nf;jf+=2)
for (iif=1;iif <= nf;iif++)
for (kf=1;kf <= nf;kf+=2) {
if (iif ==1 || iif ==nf ){
//printf("in even if\n");
uf[iif][jf][kf]=0.5*(uf[iif][jf+1][kf]+uf[iif][jf-1][kf]);
}
else {
//printf("j %d i %d k %d \n",jf,iif,kf);
uf[iif][jf][kf]=0.25*((2*d-1)/2*d)*(uf[iif][jf+1][kf]+uf[iif][jf-1][kf]) + (0.125/d)*(uf[iif+1][jf][kf]+uf[iif-1][jf][kf]+uf[iif+1][jf][kf]+uf[iif-1][jf][kf]);
}
}
//printf("odd sheets\n");
/*Do even-numbered columns, interpolating horizontally.*/
for (jf=1;jf<nf;jf++)
for (iif=1;iif<= nf;iif++)
for (kf=2;kf< nf;kf+=2) {
//printf("j %d i %d k %d \n",jf,iif,kf);
if (kf == 2 || kf == (nf-2) || jf == 1 || jf == nf || iif == 1|| iif == nf ){
uf[iif][jf][kf]=0.25*((d-1)/d)*(uf[iif][jf][kf+1]+uf[iif][jf][kf-1]);
}
else {
uf[iif][jf][kf]=0.25*((d-1)/d)*(uf[iif][jf][kf+1]+uf[iif][jf][kf-1]) + (0.125/(2*d))*(uf[iif+1][jf+1][kf+1]
+uf[iif+1][jf+1][kf-1]+uf[iif+1][jf-1][kf+1]+uf[iif-1][jf+1][kf+1]
+uf[iif-1][jf-1][kf+1]+uf[iif-1][jf+1][kf-1]+uf[iif+1][jf-1][kf-1]
+uf[iif-1][jf-1][kf-1]);
}
}
}
else {
int ic,iif,jc,jf,nc,kc,kf;
nc=nf/2+1;
/* Do elements that are copies.*/
for (kc=1,kf=1;kc <= nc;kc++,kf+=2)
for (jc=1,jf=1;jc<=nc;jc++,jf+=2)
for (ic=1,iif=1;ic<=nc;ic++,iif+=2)
uf[iif][jf][kf]=uc[ic][jc][kc];
/* Do odd-numbered columns, interpolating vertically.*/
for (jf=1;jf<=nf;jf+=2)
for (iif=2;iif<nf;iif+=2)
for (kf=1;kf <= nf;kf+=2)
uf[iif][jf][kf]=0.5*(uf[iif+1][jf][kf]+uf[iif-1][jf][kf]);
/*Do even-numbered columns, interpolating horizontally.*/
for (jf=2;jf<nf;jf+=2)
for (iif=1;iif <= nf;iif++)
for (kf=1;kf <= nf;kf+=2)
uf[iif][jf][kf]=0.5*(uf[iif][jf+1][kf]+uf[iif][jf-1][kf]);
/*Do blank sheets interpolating from sheet in front and behind.*/
for (jf=1;jf<nf;jf++)
for (iif=1;iif<= nf;iif++)
for (kf=2;kf< nf;kf+=2)
uf[iif][jf][kf]=0.5*(uf[iif][jf][kf+1]+uf[iif][jf][kf-1]);
}
}
|
C
|
#include<stdio.h>
main()
{
int loops, num1, num2, i, j, sum, q, arr1[30], arr2[30];
scanf("%d", &loops);
while (loops != 0) {
scanf("%d%d", &num1, &num2);
sum = 0;
for (i = 0; i < num1; i++)
scanf("%d", &arr1[i]);
for (i = 0; i < num1; i++)
scanf("%d", &arr2[i]);
for (i = 0; i < num1 - 1; i++) {
for (j = i + 1; j < num1; j++) {
if (arr1[i] > arr1[j]) {
q = arr1[i];
arr1[i] = arr1[j];
arr1[j] = q;
};
if (arr2[i] < arr2[j]) {
q = arr2[j];
arr2[j] = arr2[i];
arr2[i] = q;
};
}
};
q = 0;
while (q != num2) {
if (arr1[q] < arr2[q])
arr1[q] = arr2[q];
q++;
}
for (i = 0; i < num1; i++)
sum = sum + arr1[i];
printf("%d\n", sum);
loops--;
}
}
|
C
|
Offset appears to be off
*/
#include "apue.h"
#include <fcntl.h>
#include <errno.h>
#include <sys/stat.h>
#define NUMCOUNTRIES 239
typedef struct{
char code[3];
int offset;
}indexC;
indexC** countryIndex;
//Prototypes
void *GiveNode(int fd);
int search(int numCountries, char* key);
void UserInput(int numCountries);
void printRecord(int key);
void printStruct(int numCountries);
int main(int argc, char *argv[])
{
countryIndex = malloc(NUMCOUNTRIES*sizeof(indexC*));
int fd = open("index.dat", O_RDONLY);
if(fd < 0)
{
err_sys("failed open!");
}
GiveNode(fd);
exit(0);
}
void *GiveNode(int fd)
{
static char charBuff[3];
static int offsetBuff;
static int eof = -1;
static char *string;
int i,j;
static int readLine = 0;
for(i = 0; i < NUMCOUNTRIES; i++){
countryIndex[i]=malloc(sizeof(countryIndex));
readLine = read(fd, charBuff, 3);
readLine = read(fd, &offsetBuff, sizeof(int));
string = charBuff;
strncpy(countryIndex[i]->code, string, strlen(string));
countryIndex[i]->offset = offsetBuff;
}
UserInput(NUMCOUNTRIES);
}
int search(int numCountries, char* key)
{
int first, last, mid, retVal = -1;
first = 0; last = numCountries - 1; mid = (first + last)/2;
while (first <= last)
{
if(strncmp(countryIndex[mid]->code, key, 3) < 0)
first = mid + 1;
else if (strncmp(countryIndex[mid]->code, key, 3) > 0)
last = mid - 1;
else
{
retVal = countryIndex[mid]->offset;
return retVal;
}
mid = (first + last)/2;
}
}
void UserInput(int numCountries)
{
char* input = malloc(3*sizeof(char));
int retVal = -1;
char inBuff[1000];
int n;
printf("Enter a country code to look up\n");
printf("Enter a code in upper case, 000 to exit\n");
read(0, inBuff, sizeof(inBuff));
while((inBuff[0] != '0' && inBuff[1] != '0' && inBuff[2] != '0') || inBuff[3] != '\n')
{
if(inBuff[3] == '\n')
retVal = search(NUMCOUNTRIES, inBuff);
printf("%i", retVal);
if(retVal != -1){
printf("\n");
printf("Here is your record\n");
printRecord(retVal);
printf("May I have another sir?\n");
}else
{
printf("Record Not Found. May I have another sir?\n");
}
retVal = -1;
read(0,inBuff,sizeof(inBuff));
}
}
void printRecord(int key)
{
int fd = open("log.dat", O_RDONLY);
int offset = key, lengthBuff, readLine, pop;
char charBuff[3];
char* name = malloc(sizeof(lengthBuff)*sizeof(char));
float life_e;
if(fd < 0)
{
err_sys("Failed open!");
}
lseek(fd, offset, 0);
readLine = read(fd, charBuff, 3);
readLine = read(fd, &lengthBuff, sizeof(int));
readLine = read(fd, name, lengthBuff);
readLine = read(fd, &pop, sizeof(int));
readLine = read(fd, &life_e, sizeof(float));
printf("%c%c%c, %s, %i, %f\n", charBuff[0], charBuff[1], charBuff[2],
name, pop, life_e);
}
void printStruct(int LineCount){
int i;
for(i = 0; i < LineCount; i++)
{
printf("%c%c%c, %i \n", countryIndex[i]->code[0], countryIndex[i]->code[1], countryIndex[i]->code[2],
countryIndex[i]->offset);
}
}
Raw
CountryA1.c
/********************************************************************************************\
| Assignment 1: Love teh Pointer |
|Name: Ryan DePrekel |
|Due: 1-29-15 |
|Course: CS2240 |
| Reading File - [DONE] |
| Open file AllCountry.dat |
| Read into 512 byte buffer [CHECK] and parse for desired fields 2,3,8,9. Back |
| file pointer back to \n character and read new buffer. |
| |
| Parsing Data - [DONE] |
| Parsing these fields into an array of the struct country. |
| |
| Sort Data [Done] & Compute user input - [DONE] |
| Sort |
| Allow user to search array of countrys to find based on Country Code. |
| Using binary search. |
| |
| |
| Write to Bin - [DONE] |
| Write data to a binary file. (probably) write to a directory [Incomplete] |
| |
| -HOW TO USE- |
| After starting executeable, you will be prompted with a flashing cursor |
| which you can input in a country code[Three characters long] for search |
| in the country data structure |
\********************************************************************************************/
#include "apue.h" // Includes most standard libraries
#include <fcntl.h>
#include <errno.h>
#include <sys/stat.h>
#include <string.h>
#define BUFF 512
#define FALSE 0
#define TRUE 1
#define STDIN 0
/*
Struct to define fields that are desired from file
field 2: country code = code
field 3: country name = name
field 8: Population = pop
field 9: life expectancy = life_e
*/
typedef struct _country
{
char code[3];
char* name;
int pop;
float life_e;
}country;
typedef struct _index
{
char code[3];
int offset;
}indexC;
indexC** countryIndex;
// Function Prototypes
char* GimmeALine(int FileDescrip);
country* parseLine(char* line);
void printStruct(country** countryStruct, int numCountries);
void sort(country** countries, int numCountries);
country* search(char* in,country** list, int numCountries);
void printRecord(country* country);
void writeRecord(country** countries, int numCountries);
void createIndex(country** countries, int numCountries);
void writeIndex(indexC** countryIndex, int numCountries);
void printIndex(indexC** countryIndex, int numCountries);
//Insert file as argument on terminal? !!!Write Prompt for user input!!!
/*
malloc(size_t ) returns a pointer to free dynamic memory of size given from the system.
remember to free(void *) memory to return it back to the system.
realloc(void* , size_t) changes size of pointer from malloc()
*/
int main(int argc, char *argv[])
{
int infd, outfd, countrySlots = 50, i = 0, numCountries = 0; // file descriptor, Country count, index
char buff[BUFF]; // buffer var probably not needed
char* line; // catches return value of GimmeALine
char in[4]; // user input varible
country** countries = malloc(50*sizeof(country*)); // Array of country structs with 50 spots
country* foundCountry = malloc(sizeof(country*));
infd = open("AllCountries.dat", O_RDONLY);
if(infd < 0)
{
err_sys("failed open!");
}
puts("Reading AllCountries.dat!\n");
while((line = GimmeALine(infd)) != NULL){
//fprintf(stderr, "Line %u \n %s \n", lCount, line);
//printf("Inside of loop");
if(numCountries >= countrySlots)
{
countrySlots += 50;
countries = realloc(countries, countrySlots*sizeof(country*));
}
//countries[numCountries] = malloc(sizeof(country));
countries[numCountries] = parseLine(line);
sort(countries, numCountries);
numCountries++;
}
puts("Writing to index.bin\n");
createIndex(countries,numCountries);
//printIndex(countryIndex,numCountries);
writeIndex(countryIndex,numCountries);
puts("Done! Writing to log.bin!\n");
writeRecord(countries,numCountries);
/*
puts("Enter country code to look up: \n");
while(read(0,in,4)==4)
{
foundCountry = search(in,countries,numCountries);
if(foundCountry != NULL)
printRecord(foundCountry);
}
*/
//printStruct(countries, numCountries);
for(i = 0; i < numCountries; i++)
{
free(countries[i]);
}
free(countryIndex);
free(foundCountry);
free(countries);
}
// Based off Dr. Trenary's code, Thanks Dr. Trenary!!
char* GimmeALine(int fd)
{
static char buffer[BUFF+1];
static int ndxTok;
static int ndxBuff = BUFF + 1;
static int eof = FALSE;
static int lineFound;
static int readCount = 0;
static char* returnLine;
off_t offset;
if(ndxBuff >= readCount)
{
readCount = read(fd, buffer, BUFF);
ndxBuff = 0;
eof = (readCount == 0);
}
if(readCount < 0)
err_sys("Read less than 0\n");
if(!eof)//There are lines availble to read
{
ndxTok = ndxBuff;
lineFound = FALSE;
do{ //Find Line
while((ndxBuff < readCount) && (buffer[ndxBuff] != '\n'))
ndxBuff++;
lineFound = (ndxBuff < readCount);
if(!lineFound){
offset = (off_t)(ndxTok - ndxBuff);
lseek(fd, offset, SEEK_CUR);
readCount = read(fd, buffer, BUFF);
ndxBuff = 0; ndxTok = 0; //reset buffer & token indexes
eof = (readCount == 0);
if(eof)
break;
}
} while(! lineFound);//find line in filled buffer
}
if (eof)
return returnLine = NULL;
else
{
returnLine = &buffer[ndxTok];
buffer[ndxBuff] = (char) 0; // create a cString
ndxBuff++; //prep for next token
}
return returnLine;
}
/*
field 2: country code = code
field 3: country name = name
field 8: Population = pop
field 9: life expectancy = life_e
parseLine(char* line) takes a line from the file and parses the fields
for tokens desired. This function will assign each field to each respective field in the
country. Then will return the country (or pointer to?).
*/
country* parseLine(char* line)
{
char* token;
char* tokPnt;
//country returnCountry;
int tokenNum = 1;
country* returnPointer = malloc(sizeof(country));
token = strtok_r(line, ",", &tokPnt);
//printf("in parseLine()");
while(strlen(token)!=0 && tokenNum < 10)
{
token = strtok_r(NULL, ",", &tokPnt);
switch(tokenNum){
case 1:
strncpy(returnPointer->code, token, sizeof(returnPointer->code) + 1);
break;
case 2:
returnPointer->name=malloc(strlen(token) + 1);
strncpy(returnPointer->name, token, strlen(token) + 1);
break;
case 7:
returnPointer->pop = atoi(token);
break;
case 8:
returnPointer->life_e = atof(token);
break;
}
tokenNum++;
}
//returnPointer = (*)returnCountry;
return returnPointer;
}
//Prints Struct with format; Code, Name, Population, Life_e
// Mostly for testing
void printStruct(country** countryStruct, int numCountries)
{
int i;
for(i = 0; i < numCountries; i++)
{
printf("%c%c%c, %s, %i, %4.2f \n",countryStruct[i]->code[0], countryStruct[i]->code[1], countryStruct[i]->code[2],
countryStruct[i]->name, countryStruct[i]->pop,countryStruct[i]->life_e);
}
}
// Prints the record passed to the function
void printRecord(country* country){
printf("%c%c%c, %s, %i, %4.2f \n",country->code[0], country->code[1], country->code[2],
country->name, country->pop,country->life_e);
}
void printIndex(indexC** indexCountry, int numCountries)
{
int i;
for(i = 0; i < numCountries; i++)
{
printf("%c%c%c, %i", indexCountry[i]->code[0],indexCountry[i]->code[1],
indexCountry[2]->code[2],indexCountry[i]->offset);
}
}
/*
Compares a country object based on country code
return -1 if less, 0 if equal, and 1 if greater
bubbles up the pointer if needed.
*/
void sort(country** countries, int numCountries)
{
int i;
country* tempCountry;
//Since a new country is added at end of array need to compare to records above
//so I'm starting at numCountries and working my way back up to the first record.
if (numCountries > 0)
{
for (i = numCountries - 1; i >= 0; i--)
{
if (strncmp(countries[i+1]->code, countries[i]->code, 3) < 0)
{
//swap
tempCountry = countries[i];
countries[i] = countries[i + 1];
countries[i + 1] = tempCountry;
}
}
}
}
/*
Binary Search for country
key = user input
list = country struct
numCountries = number of countries in struct
*/
country* search(char* key, country** list, int numCountries)
{
int first, last, mid;
first = 0; last = numCountries - 1; mid = (first + last)/2;
while (first <= last)
{
if(strncmp(list[mid]->code, key, 3) < 0)
first = mid + 1;
else if (strncmp(list[mid]->code, key, 3) > 0)
last = mid - 1;
else
return list[mid];
mid = (first + last)/2;
}
if( first > last)
{
puts("NO matches");
return NULL;
}
}
/*
*/
void createIndex(country** countries, int numCountries)
{
int i = 0, currOffset = 0;
countryIndex = malloc(numCountries*sizeof(indexC*));
for(i = 0; i < numCountries; i++)
{
countryIndex[i] = malloc(sizeof(indexC));
countryIndex[i]->offset = currOffset;
strncpy(countryIndex[i]->code, countries[i]->code,3);
currOffset += (4*sizeof(char) +sizeof(int) +
strlen(countries[i]->name)+sizeof(int)+sizeof(float));
}
}
void writeIndex(indexC** countryIndex, int numCountries)
{
int fileOut, i;
fileOut = open("index.dat", O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IRGRP | S_IROTH);
for(i = 0; i<numCountries; i++)
{
write(fileOut, countryIndex[i]->code, 3);
write(fileOut, &countryIndex[i]->offset, sizeof(int));
}
}
void writeRecord(country** countries, int numCountries)
{
int outfd, i,length;
outfd = open("log.dat", O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IRGRP | S_IROTH);
for(i=0; i<numCountries; i++){
length = strlen(countries[i]->name);
write(outfd, countries[i]->code, 3);
write(outfd, &length, sizeof(int));
write(outfd, countries[i]->name, strlen(countries[i]->name));
write(outfd, &countries[i]->pop, sizeof(int));
write(outfd, &countries[i]->life_e, sizeof(float));
}
}
|
C
|
// 可以将输入的单词或者数字给保存到word中
int getword(char *word, int lim)
{
int c;
char *w = word;
// 跳过之前的空白字符
while (isspace(c = getch()))
;
if (c != EOF)
*w++ = c;
if (!isalpha(c))
{
*w = '\0';
return c;
}
for (; --lim > 0; w++)
if (!isalnum(*w = getch()))
{
ungetch(*w);
break;
}
*w = '\0';
return word[0];
}
#define BUFSIZE 100
#define NKEYS (sizeof(keytab) / sizeof(keytab[0]))
char buf[BUFSIZE]; // 用于ungetch函数的缓冲区
int bufp = 0; // buf中下一个空闲的位置
int getch()
{
return (bufp > 0) ? buf[--bufp] : getchar();
}
void ungetch(int c)
{
if (bufp > BUFSIZE)
printf("ungetch: too many characters\n");
else
buf[bufp++] = c;
}
|
C
|
#include <pal.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include "pal_base.h"
#include "pal_base_private.h"
/**
*
* Map device memory. Not all devices can implement this.
* It is okay to return NULL.
*
* @param dev Device
* @param address Device address
* @param size Size
*
* @return Raw pointer or NULL on error or not supported.
*
*/
p_mem_t p_map(p_dev_t dev, unsigned long addr, unsigned long size)
{
struct dev *pdev= (struct dev *) dev;
if (p_ref_is_err(dev))
return p_mem_err(p_error(dev));
if (!pdev || !pdev->dev_ops || !pdev->dev_ops->map)
return p_mem_err(ENOSYS);
return pdev->dev_ops->map(pdev, addr, size);
}
|
C
|
#ifndef _TIME_TEST_
#define _TIME_TEST_
#include <time.h> /* clock */
#include <sys/time.h> /* gettimeofday */
/* NOTICE! Change here to select the method you want */
#define USE_CLOCK 0
/* Using clock, calculate CPU time, cpu_time=user_time+sys_time */
clock_t _ct_start, _ct_end;
#define TIME_START_CL() do { _ct_start = clock();} while (0)
#define TIME_END_CL() do { _ct_end = clock(); \
printf("Elapsed time %ld sec\n", (_ct_end - _ct_start)/CLOCKS_PER_SEC); \
/* printf("Elapsed time %ld usec\n", (_ct_end - _ct_start)/(CLOCKS_PER_SEC/1000000)); \ */ \
} while (0)
/* Using gettimeofday, calculate real time, real_time=cpu_time+wait_time
* Because linux is multi-task operate system, so the value of wait_time is
* difference on each task
*/
struct timeval _tv_begin, _tv_end;
#define TIME_START_TV() do { gettimeofday(&_tv_begin, NULL); } while (0)
#define TIME_END_TV() do { gettimeofday(&_tv_end, NULL); \
printf("Elapsed time %ld usec\n", _tv_end.tv_usec - _tv_begin.tv_usec); \
} while (0)
#if USE_CLOCK
#define TIME_START() TIME_START_CL()
#define TIME_END() TIME_END_CL()
#else
#define TIME_START() TIME_START_TV()
#define TIME_END() TIME_END_TV()
#endif
/*
Sample code:
#include "time_test.h"
int main(int argc, char *argv[]) {
TIME_SATRT();
// DO YOUR JOB HERE
TIME_END();
return 0;
}
*/
#endif /* _TIME_TEST_ */
|
C
|
/*
\__\__\__\__\__\__\__\__\__\__\__\__\__\__\__\__\__\__\__\__\__\__\__
AO PREENCHER ESSE CABEÇALHO COM O MEU NOME E O MEU NÚMERO USP,
DECLARO QUE SOU O ÚNICO AUTOR E RESPONSÁVEL POR ESSE PROGRAMA.
TODAS AS PARTES ORIGINAIS DESSE EXERCÍCIO PROGRAMA (EP) FORAM
DESENVOLVIDAS E IMPLEMENTADAS POR MIM SEGUINDO AS INSTRUÇÕES DESSE EP
E QUE PORTANTO NÃO CONSTITUEM PLÁGIO. DECLARO TAMBÉM QUE SOU RESPONSÁVEL
POR TODAS AS CÓPIAS DESSE PROGRAMA E QUE EU NÃO DISTRIBUI OU FACILITEI A
SUA DISTRIBUIÇÃO. ESTOU CIENTE QUE OS CASOS DE PLÁGIO SÃO PUNIDOS COM
REPROVAÇÃO DIRETA NA DISCIPLINA.
Nome: Lourenço Henrique Moinheiro Martins Sborz Bogo
NUSP: 11208005
IMDB: util.c
Referências: Com exceção das rotinas fornecidas no esqueleto e em sala
de aula, caso você tenha utilizado alguma refência, liste-as abaixo
para que o seu programa não seja considerada plágio.
Exemplo:
- função mallocc retirada de: http://www.ime.usp.br/~pf/algoritmos/aulas/aloca.html
\__\__\__\__\__\__\__\__\__\__\__\__\__\__\__\__\__\__\__\__\__\__\__
*/
/*
* IMPLEMENTACAO de funcoes de uso geral
*
*/
/* interface para este modulo */
#include "util.h"
#include <stdio.h> /* fgets(), printf() */
#include <stdlib.h> /* malloc(), NULL, EXIT_FAILURE */
#include <string.h> /* strlen() */
#include <ctype.h> /* tolower() */
/* tamanho maximo de um string neste programa como nome de arquivo
ou nome um filme */
#define TAM_STR 256
#define DEBUG
/*----------------------------------------------------------------------
* achePalavra
*
* Recebe o string PAL com tamanho TPAL, e outro string TEXTO com
* tamanho TTEX e retornar TRUE caso a PAL ocorra em TEXTO, e
* FALSE em caso contrário.
*
* A busca nao deve levar em consideracao se as letras em PAL ou
* TEXTO sao em caixa alta (maiusculas) ou caixa normal
* (minusculas). Assim, a busca deve ser 'case insensitive'.
*
*/
Bool
achePalavra(unsigned char *pal, int tPal, unsigned char *texto, int tTex)
{
int v[256], s, j, i;
for(i = 0; i < 256; i++) v[i] = 0;
for(i = 0; i < tPal; i++) v[pal[i]] = i;
s = 0;
while(s <= (tTex-tPal)){
j = tPal-1;
while(j >= 0 && pal[j] == texto[s+j]) j--;
if(j < 0) return TRUE;
else s = s+max(1, j-v[texto[s+j]]);
}
return FALSE;
}
int
max (int a, int b)
{
return (a>b)? a:b;
}
/*----------------------------------------------------------------------
* strCmp(const char *s1, const char *s2)
*
* Comportamento identico ao da funcao strcmp da interface string.h
* da libC. A unica diferenca e que esta funcao desconsidera se as
* letras sao maiusculas ou mininusculas.
*
* copiado da gLibc
*
* Ver http://fossies.org/dox/glibc-2.20/string_2strcmp_8c_source.html
* ou a copia nas notas de aula de MAC0121.
*
* ------------------------------------------------------------------
* NAME
* strcmp - compare two strings
*
* SYNOPSIS
* #include <string.h>
*
* int strcmp(const char *s1, const char *s2);
*
* DESCRIPTION
* The strcmp() function compares the two strings s1 and s2.
* It returns an integer less than, equal to, or greater than
* zero if s1 is found, respectively, to be less than, to match,
* or be greater than s2.
*
*/
int
strCmp(const char *s1, const char *s2)
{
const unsigned char *p1 = (const unsigned char *) s1;
const unsigned char *p2 = (const unsigned char *) s2;
unsigned char c1, c2;
do
{
c1 = tolower((unsigned char) *p1++); /* tolower foi acrescentado */
c2 = tolower((unsigned char) *p2++); /* tolower foi acrescentado */
if (c1 == '\0')
return c1 - c2;
}
while (c1 == c2);
return c1 - c2;
}
/*
* Sobre a GLIBC:
*
* The GNU C Library, commonly known as glibc, is the GNU Project's
* implementation of the C standard library. Despite its name, it now
* also directly supports C++ (and, indirectly, other programming languages).
* It was started in the early 1990s by the Free Software Foundation (FSF)
* for their GNU operating system.
*
* Released under the GNU Lesser General Public License,[3] glibc is free software.
* The GNU C Library project provides the core libraries for the GNU system and
* GNU/Linux systems, as well as many other systems that use Linux as the kernel.
* These libraries provide critical APIs including ISO C11, POSIX.1-2008, BSD,
* OS-specific APIs and more. These APIs include such foundational facilities
* as open, read, write, malloc, printf, getaddrinfo, dlopen, pthread_create,
* crypt, login, exit and more.
*/
/*--------------------------------------------------------------
* leiaString
*
* RECEBE como parametros um string STR e um inteiro SIZE e LE
* da entrada padrao no maximo SIZE-1 caracteres e ARMAZENA em
* STR. A leitura para depois de um ENTER e o ENTER _nao_ e
* incluido no string STR. A funcao retorna o numero de
* caracteres no string.
*
* Pre-condicao: SIZE <= TAM_STR
*
* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
* > man fgets
* char *fgets(char *s, int size, FILE *stream);
*
* fgets() reads in at most one less than size characters from
* stream and stores them into the buffer pointed to by s.
* Reading stops after an EOF or a newline. If a newline is
* read, it is stored into the buffer. A terminating null byte
* ('\0') is stored after the last character in the buffer.
*/
int
leiaString(char str[], int size)
{
int len;
char s[TAM_STR];
/* remove qualquer newline que estava no buffer */
scanf(" ");
/* leitura do string: ler info sobre fgets() */
fgets(s, TAM_STR, stdin);
/* sobreescreve um possivel newline do final com '\0' */
len = strlen(s);
if (s[len-1] == ENTER)
{
len--;
s[len] = '\0';
}
if (len > size)
{
s[size-1] = '\0';
len = size-1;
}
strncpy(str, s, size);
#ifdef DEBUG
printf("AVISO: leiaString: string lido '%s' tem %d caracteres\n", s, len);
#endif
return len;
}
/*---------------------------------------------------
* mallocSafe()
*
* http://www.ime.usp.br/~pf/algoritmos/aulas/aloca.html
*/
void *
mallocSafe(size_t n)
{
void * p;
p = malloc(n);
if (p == NULL)
{
printf("ERRO na alocacao de memoria.\n\n");
exit(EXIT_FAILURE);
}
return p;
}
|
C
|
#ifndef TableHeader
#define TableHeader
#include "Vector.h"
#include "Common.h"
/*Maximal size of the name column in a row*/
#define MAX_ROW_STR_SIZE 50
/*A row in the sGrowingTable*/
typedef struct sTableEntry {
char rowName[MAX_ROW_STR_SIZE];
int rowAddress;
} sTableEntry;
struct sTableInternal {
sGrowingArray rows;
unsigned int currSize;
int allowMultiples;
};
/*The sGrowingTable. Once maxSize is used, it allocates more memory*/
typedef struct sTableInternal* sGrowingTable;
/*Ctor*/
sGrowingTable tableOpen(void);
/*dtor*/
void tableClose(sGrowingTable sGrowingTable);
/*Find address by name. Returns NULL on failure*/
sTableEntry* tableFindByName(sGrowingTable sGrowingTable, char *name);
/*Returns row at index*/
sTableEntry* tableFindByIndex(sGrowingTable sGrowingTable, unsigned int index);
/*Add address and name to the table. returns SUCCESS, TABLE_NAME_TOO_LONG or ALLOCATION_FAILED.*/
ERROR_CODE tableAdd(sGrowingTable sGrowingTable, char *name, int address);
/*Used by tableAdd*/
#define TABLE_NAME_TOO_LONG (-2)
/*Used by addAdress*/
#define TABLE_NAME_EXISTS (-4)
#endif
|
C
|
#include<stdio.h>
#include<string.h>
int main()
{
int i, j, k, x;//Ƶѭı
int n, len, count;
char str[100000], temp[100000];
scanf("%s %d", str, &n);
for(i = 1; i < n; i++)
{
x = 0;
len = strlen(str);
for(j = 0; j < len; j++)
{
//ÿĴ
for(k = j, count = 0; k < len && str[k] == str[j]; k++)
{
count++;
}
j = k - 1;
//Ĵ䱾ŵtemp
temp[x] = str[j];
temp[x + 1] = (char)(count + '0');
x += 2;
}
temp[x] = '\0';
strcpy(str, temp);
}
printf("%s\n", str);
return 0;
}
|
C
|
/*
author:lzl
date:2016-3-11
function:实现内存映射多线程大文件复制
*/
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <pthread.h>
#include <errno.h>
#include <string.h>
#define BLOCKSIZE (1024*1024*2)//每个文件块大小2M
//定义文件块结构信息,发送给每个线程使用
typedef struct fileblock
{
unsigned char* srcfileaddres;
unsigned char* destfileaddres;
unsigned int startfilepos;
unsigned int blocksize;
}fileblock;
//源文件内存映射的全局指针
unsigned char * g_srcfilestartp=NULL;
//目标文件内存映射的全局指针
unsigned char * g_destfilestartp=NULL;
//线程互斥锁
pthread_mutex_t g_mutex=PTHREAD_MUTEX_INITIALIZER;
/*
function:输出系统返回错误信息
parameter:
const char* errmsg 错误信息
*/
void output_sys_errmsg(const char* errmsg)
{
perror(errmsg);
}
/*
function:计算文件大小
parameter:
unsigned int fd 源文件描述符
return value: 文件大小
*/
unsigned int get_file_size(unsigned int fd)
{
unsigned int filesize=lseek(fd,0,SEEK_END);
lseek(fd,0,SEEK_SET);
return filesize;
}
/*
function:依据文件大小计算文件分块数
parameter:
unsigned int fd 源文件描述符
return value: 文件块数
*/
unsigned int get_file_block_cnt(unsigned int fd)
{
unsigned int fileblockcnt=0;
unsigned int filesize=get_file_size(fd);
unsigned int fileremaindsize=filesize%BLOCKSIZE;
fileblockcnt=filesize/BLOCKSIZE;
if(fileremaindsize>0)
{
fileblockcnt=fileblockcnt+1;
}
return fileblockcnt;
}
/*
function:如果文件分块不是整数块,计算出剩余的字节数
parameter:
unsigned int fd 源文件描述符
return value: 最后一块大小,文件最后一块剩余大小
*/
unsigned int get_remainsize(unsigned int fd)
{
unsigned int remainsize=0;
unsigned int filesize=get_file_size(fd);
if(filesize%BLOCKSIZE>0)
{
remainsize=filesize%BLOCKSIZE;
}
return remainsize;
}
/*
function:计算文件分块,并记录每块文件的信息
parameter:
unsigned int fd 源文件描述符
return values:指向记录文件块信息结构数组指针
*/
fileblock* get_file_block(unsigned int fd)
{
unsigned int fileblockcnt=get_file_block_cnt(fd);
unsigned int fileremaindsize=get_remainsize(fd);
fileblock* fileblockarray=(fileblock*)malloc(fileblockcnt*sizeof(fileblock));
if(fileblockarray==NULL)
{
output_sys_errmsg("get_file_block malloc:");
exit(-1);
}
int i;
for(i=0;i<fileblockcnt-1;i++)
{
fileblockarray[i].startfilepos=i*BLOCKSIZE;
fileblockarray[i].blocksize=BLOCKSIZE;
}
fileblockarray[i].startfilepos=i*BLOCKSIZE;
fileblockarray[i].blocksize=fileremaindsize>0?fileremaindsize:BLOCKSIZE;
return fileblockarray;
}
/*
function:建立文件内存映射
parameter:
unsigned int fd 源文件描述符
return value:返回内存映射地址值
*/
unsigned char * get_srcfile_map_addres(unsigned int fd)
{
unsigned int filesize=get_file_size(fd);
//unsigned char * filestartp=NULL;
g_srcfilestartp=(unsigned char*)mmap(NULL,filesize,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
if(g_srcfilestartp==NULL)
{
output_sys_errmsg("get_srcfile_map_addres mmap:");
exit(-1);
}
return g_srcfilestartp;
}
/*
function:释放源文件内存映射区
parameter:
int fd 映射对应的文件描述符
*/
void set_srcfile_munmap(int fd)
{
unsigned int filesize=get_file_size(fd);
if(g_srcfilestartp!=NULL)
{
munmap(g_srcfilestartp,filesize);
}
}
/*
function:释放源文件内存映射区
parameter:
int fd 映射对应的文件描述符
*/
void set_destfile_munmap(int fd)
{
unsigned int filesize=get_file_size(fd);
if(g_destfilestartp!=NULL)
{
munmap(g_destfilestartp,filesize);
}
}
/*
function:建立目标文件内存映射
parameter:
unsigned int srcfd 源文件描述符
unsigned int destfd 目标文件描述符
return value:返回内存映射地址值
*/
unsigned char * get_destfile_map_addres(unsigned int srcfd,unsigned int destfd)
{
unsigned int filesize=get_file_size(srcfd);
lseek(destfd,filesize,SEEK_SET);
write(destfd," ",1);
g_destfilestartp=(unsigned char*)mmap(NULL,filesize,PROT_READ|PROT_WRITE,MAP_SHARED,destfd,0);
if(g_destfilestartp==NULL)
{
output_sys_errmsg("get_destfile_map_addres mmap:");
exit(-1);
}
return g_destfilestartp;
}
/*
function:线程执行函数(实现分块复制)
parameter:
void* arg 主线程传递块结构
*/
void* pthread_copy_work(void* arg)
{
fileblock * blockstruct=(fileblock*)arg;
pthread_mutex_lock(&g_mutex);
memcpy((void*)&g_destfilestartp[blockstruct->startfilepos],(void*)&g_srcfilestartp[blockstruct->startfilepos],blockstruct->blocksize);
pthread_mutex_unlock(&g_mutex);
return NULL;
}
/*
function:根据文件分块数,创建线程
parameter:
unsigned int fd 源文件描述符
*/
void init_copy_pthread(unsigned int fd)
{
unsigned int blockcnt=get_file_block_cnt(fd);
fileblock *fileblockarray=get_file_block(fd);
pthread_t *pthreads=NULL;
pthreads=(pthread_t*)malloc(blockcnt*sizeof(pthread_t));
if(pthreads==NULL)
{
output_sys_errmsg("init_copy_pthread malloc:");
exit(-1);
}
int i;
int ret;
for(i=0;i<blockcnt;i++)
{
ret=pthread_create(&pthreads[i],NULL,pthread_copy_work,(void*)&fileblockarray[i]);
while(ret==-1)
{
ret=pthread_create(&pthreads[i],NULL,pthread_copy_work,(void*)&fileblockarray[i]);
}
}
for(i=0;i<blockcnt;i++)
{
pthread_join(pthreads[i],NULL);
}
}
int main(int argc, char const *argv[])
{
int srcfd=open("maishu.3gp",O_RDWR);
if(srcfd==-1)
{
output_sys_errmsg("main open srcfd:");
exit(-1);
}
int destfd=open("maishu1.3gp",O_CREAT|O_EXCL|O_RDWR,0777);
if(destfd==-1)
{
output_sys_errmsg("main open destfd:");
exit(-1);
}
get_srcfile_map_addres(srcfd);
get_destfile_map_addres(srcfd,destfd);
init_copy_pthread(srcfd);
set_srcfile_munmap(srcfd);
set_destfile_munmap(srcfd);
return 0;
}
|
C
|
#include <stdio.h>
#include "traversals.h"
void print_in_order(Node_ptr tree)
{
if (tree == NULL)
return;
print_in_order(tree->left);
printf("%d ", tree->value);
print_in_order(tree->right);
}
void print_pre_order(Node_ptr tree)
{
if (tree == NULL)
return;
printf("%d ", tree->value);
print_pre_order(tree->left);
print_pre_order(tree->right);
}
void print_post_order(Node_ptr tree)
{
if (tree == NULL)
return;
print_post_order(tree->left);
print_post_order(tree->right);
printf("%d ", tree->value);
}
|
C
|
typedef enum val_type {
str,
integer,
dbl
} val_type;
typedef union value {
char *str;
int integer;
double real;
} value;
struct configoption {
char *name;
val_type type;
value val;
};
typedef struct configoption configoption;
struct configsection {
char *name;
unsigned int numopts;
configoption *options;
};
typedef struct configsection configsection;
struct configfile {
unsigned int numsections;
configsection *sections;
};
typedef struct configfile configfile;
|
C
|
#include "stm32f4xx.h"
#include "FreeRTOS.h"
#include "task.h"
#include <stdio.h>
void helloTask1(void*);
void helloTask2(void*);
void setupUsart();
//#define USE_SEMIHOSTING
#ifdef USE_SEMIHOSTING
extern void initialise_monitor_handles();
#endif USE_SEMIHOSTING
void sendMessage(char* msg);
int main(void)
{
#ifdef USE_SEMIHOSTING
// semihosting for logging with printf
initialise_monitor_handles();
printf("this is hello sample code\n");
#endif USE_SEMIHOSTING
// turn off the pll clock generator, prescaler etc
// pull cpu clock from 100 MHz down to 16 MHz (default)
// and recompute the SystemCoreClock
// WHY: don't need 100 MHz for this simple UART project
RCC_DeInit();
SystemCoreClockUpdate();
setupUsart();
sendMessage("It's alive!\r");
TaskHandle_t task1Handle = NULL;
TaskHandle_t task2Handle = NULL;
xTaskCreate(helloTask1, "Hello task 1", configMINIMAL_STACK_SIZE, "task 1", 2, &task1Handle);
xTaskCreate(helloTask2, "Hello task 2", configMINIMAL_STACK_SIZE, "task 2", 2, &task2Handle);
vTaskStartScheduler(); // never returns?
for(;;);
}
uint8_t sendMessageAvailable = 1;
void helloTask1(void* parameter) {
for(;;) {
#ifdef USE_SEMIHOSTING
printf("Hello from task 1\n");
#endif USE_SEMIHOSTING
if (sendMessageAvailable) {
sendMessageAvailable = 0;
sendMessage("Task 1\r");
sendMessageAvailable = 1;
taskYIELD();
}
}
}
void helloTask2(void* parameter) {
for(;;) {
#ifdef USE_SEMIHOSTING
printf("Hello from task 2\n");
#endif USE_SEMIHOSTING
if (sendMessageAvailable) {
sendMessageAvailable = 0;
sendMessage("Task 2\r");
sendMessageAvailable = 1;
taskYIELD();
}
}
}
USART_TypeDef* usartPeripheral = USART3;
void setupUsart() {
// On Nucleo STMF413ZH, STLink bridges VCP to USART3 via PD8 and PD9
// PD8 USART3 TX
// PD9 USART3 RX
// PD8, PD9 are on APB1, AHB1, GPIOD
// see User Manual and Datasheet for details
// enable peripheral and gpio clocks
RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART3, ENABLE);
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOD, ENABLE);
// configure GPIO pins
GPIO_InitTypeDef gpioPins;
gpioPins.GPIO_Pin = GPIO_Pin_8 | GPIO_Pin_9;
gpioPins.GPIO_Mode = GPIO_Mode_AF;
gpioPins.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_Init(GPIOD, &gpioPins);
GPIO_PinAFConfig(GPIOD, GPIO_PinSource8, GPIO_AF_USART3);
GPIO_PinAFConfig(GPIOD, GPIO_PinSource9, GPIO_AF_USART3);
// configure and enable UART
USART_InitTypeDef usart;
USART_StructInit(&usart); // except for baud rate, the defaults look fine
usart.USART_BaudRate = 115200;
USART_Init(usartPeripheral, &usart);
USART_Cmd(usartPeripheral, ENABLE);
}
void sendMessage(char* msg) {
for ( ; *msg; msg++) {
while (USART_GetFlagStatus(usartPeripheral, USART_FLAG_TXE) == RESET);
USART_SendData(usartPeripheral, *msg);
}
}
|
C
|
/*
* Escreva uma função para calcular e retornar a área de um círculo.
* Esta função deverá receber o valor do raio como parâmetro e retornar o valor da área
*/
#include <stdio.h>
#include <locale.h>
#include <math.h>
float calculaAreaCirculo(float tamanho);
int main(void){
float raio, area;
setlocale(LC_ALL, "Portuguese");
printf("\n");
printf("*******************************************************\n");
printf("* BEM VINDO AO PROGRAMA DE CÁLCULO DE AREA DO CÍRCULO *\n");
printf("*******************************************************\n");
printf("\n");
printf("Informe o valor do raio em cm: ");
scanf("%f", &raio);
area = calculaAreaCirculo(raio);
printf("A area do círculo mede %.2f cm2.\n\n", area);
return 0;
}
float calculaAreaCirculo(float medida){
float area = M_PI * pow(medida,2);
return area;
}
|
C
|
/** File containing functions for best rational approximation to matrix exponential.
* \file cf.c
*
* \author Kyle E. Niemeyer
* \date 07/19/2012
*
* Contains main and linear algebra functions.
*/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
/** Defined for pi */
#define _USE_MATH_DEFINES
/** Complex math */
#include <complex.h>
/** Fast Fourier tranform functions */
#include <fftw3.h>
#include "cf.h"
static void roots (int, double*, double complex*);
static void svd (int, double*, double*, double*, double*);
////////////////////////////////////////////////////////////////////////
/** Polynomial root finding function.
*
* This function calculates the roots of a polynomial represented by its
* coefficients in the array v. This is done by constructing a companion
* matrix out of the polynomial coefficients, then using the LAPACK
* subroutine DGEEV to calculate its eigenvalues. These are the roots
* of the polynomial.
*
* \param[in] n size of v;
* \param[in] v array of polynomial coefficients (real)
* \param[out] rt array of polynomial roots (complex), size n - 1
*/
static
void roots (int n, double* v, double complex* rt) {
// number of roots
int m = n - 1;
// Prototype for LAPACK DGEEV (Fortran) function
extern void dgeev_ (char* jobvl, char* jobvr, int* n, double* A, int* lda,
double* wr, double* wi, double* vl, int* ldvl, double *vr,
int* ldvr, double* work, int* lwork, int* info);
// construct companion matrix
double *A = (double*) calloc (m * m, sizeof(double));
memset (A, 0.0, m * m * sizeof(double)); // fill with 0
for (int i = 0; i < (m - 1); ++i) {
A[i + 1 + m * i] = 1.0;
}
for (int i = 0; i < m; ++i) {
A[m * i] = -v[i + 1] / v[0];
}
int info, lwork;
double* vl;
double* vr;
double wkopt;
double* work;
// don't need eigenvectors
char job = 'N';
// real and imaginary parts of eigenvalues
double* wr = (double*) calloc (m, sizeof(double));
double* wi = (double*) calloc (m, sizeof(double));
// first compute optimal workspace
lwork = -1;
dgeev_ (&job, &job, &m, A, &m, wr, wi, vl, &m, vr, &m, &wkopt, &lwork, &info);
lwork = (int) wkopt;
work = (double*) calloc (lwork, sizeof(double));
// compute eigenvalues
dgeev_ (&job, &job, &m, A, &m, wr, wi, vl, &m, vr, &m, work, &lwork, &info);
// check for convergence
if (info > 0) {
printf ("DGEEV failed to compute the eigenvalues.\n");
exit (1);
}
for (int i = 0; i < m; ++i) {
rt[i] = wr[i] + I * wi[i];
}
free (A);
free (work);
free (wr);
free (wi);
}
////////////////////////////////////////////////////////////////////////
/** Singular value decomposition function.
*
* Decomposes a matrix A into U * S * V', where S (here an array, really
* a diagonal matrix) holds the singular values. The function uses the
* LAPACK subroutine DGESVD.
*
* \param[in] n leading dimension of array
* \param[in] A array to be decomposed, size n * n
* \param[out] S array with singular values, size n
* \param[out] U array with left singular vectors, size n * n
* \param[out] V array with right singular vectors, size n * n
*/
static
void svd (int n, double* A, double* S, double* U, double* V) {
// Prototype for LAPACK DGESVD (Fortran) function
extern void dgesvd_ (char* jobu, char* jobvt, int* m, int* n, double* A,
int* lda, double* s, double* u, int* ldu, double* vt,
int* ldvt, double* work, int* lwork, int* info);
int info, lwork;
double wkopt;
double* work;
double* Vt = (double*) calloc (n * n, sizeof(double));
// want all of U and V
char job = 'A';
// first compute optimal workspace
lwork = -1;
dgesvd_ (&job, &job, &n, &n, A, &n, S, U, &n, Vt, &n, &wkopt, &lwork, &info);
lwork = (int) wkopt;
work = (double*) calloc (lwork, sizeof(double));
// Compute SVD
dgesvd_ (&job, &job, &n, &n, A, &n, S, U, &n, Vt, &n, work, &lwork, &info);
// check for convergence
if (info > 0) {
printf ("DGESVD failed.\n");
exit (1);
}
// transpose Vt
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
V[i + j*n] = Vt[j + i*n];
}
}
free (Vt);
free (work);
}
////////////////////////////////////////////////////////////////////////
/** Function that calculates the poles and residuals of best rational
* (partial fraction) approximant to the matrix exponential.
*
* Uses the Carathéodory-Fejér method; based on the MATLAB code in
* L.N. Trefethen, J.A.C. Weideman, T. Schmelzer, "Talbot quadratures
* and rational approximations," BIT Numer. Math. 46 (2006) 653–670.
*
* \param[in] n size of approximation (n, n)
* \param[out] poles_r array with real parts of poles, size n
* \param[out] poles_i array with imaginary parts of poles, size n
* \param[out] res_r array with real parts of residuals, size n
* \param[out] res_i array with imaginary parts of residuals, size n
*/
void cf (const int n, double* poles_r, double* poles_i, double* res_r, double* res_i) {
// number of Chebyshev coefficients
int K = 75;
// number of points for FFT
int nf = 1024;
// roots of unity
fftw_complex *w = fftw_alloc_complex(nf);
for (int i = 0; i < nf; ++i) {
w[i] = cexp(2.0 * I * M_PI * (double)i / (double)nf);
}
// Chebyshev points (twice over)
double *t = (double*) calloc (nf, sizeof(double));
for (int i = 0; i < nf; ++i) {
t[i] = creal(w[i]);
}
// scale factor for stability
double scl = 9.0;
// exp(x) transpl. to [-1,1]
fftw_complex *F = fftw_alloc_complex(nf);
for (int i = 0; i < nf; ++i) {
F[i] = cexp(scl * (t[i] - 1.0) / (t[i] + 1.0 + 1.0e-16));
}
free (t);
// Chebyshev coefficients of F
fftw_complex *fftF = fftw_alloc_complex(nf);
fftw_plan p;
p = fftw_plan_dft_1d(nf, F, fftF, FFTW_FORWARD, FFTW_ESTIMATE);
fftw_execute(p);
double *c = (double*) calloc (nf, sizeof(double));
for (int i = 0; i < nf; ++i) {
c[i] = creal(fftF[i]) / (double)nf;
}
fftw_free (fftF);
fftw_free (F);
// analytic part of f of F
fftw_complex *f = fftw_alloc_complex(nf);
memset (f, 0.0, nf * sizeof(fftw_complex)); // set to zero
for (int i = 0; i < nf; ++i) {
for (int j = K; j >= 0; --j) {
f[i] += c[j] * cpow(w[i], j);
}
}
// SVD of Hankel matrix
double *S = (double*) calloc (K, sizeof(double));
double *U = (double*) calloc (K * K, sizeof(double));
double *V = (double*) calloc (K * K, sizeof(double));
double *hankel = (double*) calloc (K * K, sizeof(double));
memset (hankel, 0.0, K * K * sizeof(double)); // fill with 0
for (int i = 0; i < K; ++i) {
for (int j = 0; j <= i; ++j) {
hankel[(i - j) + K * j] = c[i + 1];
}
}
svd (K, hankel, S, U, V);
free (c);
free (hankel);
// singular value
double s_val = S[n];
// singular vectors
// need u and v to be complex type for fft
fftw_complex *u = fftw_alloc_complex(nf);
fftw_complex *v = fftw_alloc_complex(nf);
// fill with zeros
memset (u, 0.0, nf * sizeof(fftw_complex));
memset (v, 0.0, nf * sizeof(fftw_complex));
for (int i = 0; i < K; ++i) {
u[i] = U[(K - i - 1) + K * n];
v[i] = V[i + K * n];
}
free (U);
free (V);
free (S);
// create copy of v for later use
double *v2 = (double*) calloc (K, sizeof(double));
for (int i = 0; i < K; ++i) {
v2[i] = creal(v[i]);
}
// finite Blaschke product
fftw_complex *b1 = fftw_alloc_complex(nf);
fftw_complex *b2 = fftw_alloc_complex(nf);
fftw_complex *b = fftw_alloc_complex(nf);
p = fftw_plan_dft_1d(nf, u, b1, FFTW_FORWARD, FFTW_ESTIMATE);
fftw_execute(p);
p = fftw_plan_dft_1d(nf, v, b2, FFTW_FORWARD, FFTW_ESTIMATE);
fftw_execute(p);
for (int i = 0; i < nf; ++i) {
b[i] = b1[i] / b2[i];
}
fftw_free (u);
fftw_free (v);
fftw_free (b1);
fftw_free (b2);
// extended function r-tilde
fftw_complex *rt = fftw_alloc_complex(nf);
for (int i = 0; i < nf; ++i) {
rt[i] = f[i] - s_val * cpow(w[i], K) * b[i];
}
fftw_free (f);
fftw_free (b);
// poles
double complex *zr = (double complex*) calloc (K - 1, sizeof(double complex));
// get roots of v
roots (K, v2, zr);
free (v2);
double complex *qk = (double complex*) calloc (n, sizeof(double complex));
memset (qk, 0.0, n * sizeof(double complex));
int i = 0;
for (int j = 0; j < K - 1; ++j) {
if (cabs(zr[j]) > 1.0) {
qk[i] = zr[j];
i += 1;
}
}
free (zr);
// coefficients of denominator
double complex *qc_i = (double complex*) calloc (n + 1, sizeof(double complex));
memset (qc_i, 0.0, (n + 1) * sizeof(double complex)); // fill with 0
qc_i[0] = 1.0;
for (int j = 0; j < n; ++j) {
double complex qc_old1 = qc_i[0];
double complex qc_old2;
for (int i = 1; i < j + 2; ++i) {
qc_old2 = qc_i[i];
qc_i[i] = qc_i[i] - qk[j] * qc_old1;
qc_old1 = qc_old2;
}
}
// qc_i will only have real parts, but want real array
double *qc = (double*) calloc (n + 1, sizeof(double));
for (int i = 0; i < n + 1; ++i) {
qc[i] = creal(qc_i[i]);
}
free (qc_i);
// numerator
fftw_complex *pt = fftw_alloc_complex(nf);
memset (pt, 0.0, nf * sizeof(fftw_complex));
for (int i = 0; i < nf; ++i) {
for (int j = 0; j < n + 1; ++j) {
pt[i] += qc[j] * cpow(w[i], n - j);
}
pt[i] *= rt[i];
}
fftw_free (w);
free (qc);
fftw_free (rt);
// coefficients of numerator
fftw_complex *ptc_i = fftw_alloc_complex(nf);
p = fftw_plan_dft_1d(nf, pt, ptc_i, FFTW_FORWARD, FFTW_ESTIMATE);
fftw_execute(p);
double *ptc = (double*) calloc(n + 1, sizeof(double));
for (int i = 0; i < n + 1; ++i) {
ptc[i] = creal(ptc_i[n - i]) / (double)nf;
}
fftw_destroy_plan(p);
fftw_free (pt);
fftw_free (ptc_i);
// poles
double complex *res = (double complex*) calloc (n, sizeof(double complex));
memset (res, 0.0, n * sizeof(double complex)); // fill with 0
double complex *qk2 = (double complex*) calloc (n - 1, sizeof(double complex));
double complex *q2 = (double complex*) calloc (n, sizeof(double complex));
// calculate residues
for (int k = 0; k < n; ++k) {
double complex q = qk[k];
int j = 0;
for (int i = 0; i < n; ++i) {
if (i != k) {
qk2[j] = qk[i];
j += 1;
}
}
memset (q2, 0.0, n * sizeof(double complex)); // fill with 0
q2[0] = 1.0;
for (int j = 0; j < n - 1; ++j) {
double complex q_old1 = q2[0];
double complex q_old2;
for (int i = 1; i < j + 2; ++i) {
q_old2 = q2[i];
q2[i] = q2[i] - qk2[j] * q_old1;
q_old1 = q_old2;
}
}
double complex ck1 = 0.0;
for (int i = 0; i < n + 1; ++i) {
ck1 += ptc[i] * cpow(q, n - i);
}
double complex ck2 = 0.0;
for (int i = 0; i < n; ++i) {
ck2 += q2[i] * cpow(q, n - 1 - i);
}
res[k] = ck1 / ck2;
}
free (ptc);
free (qk2);
free (q2);
double complex *poles = (double complex*) calloc (n, sizeof(double complex));
for (int i = 0; i < n; ++i) {
// poles in z-plane
poles[i] = scl * (qk[i] - 1.0) * (qk[i] - 1.0) / ((qk[i] + 1.0) * (qk[i] + 1.0));
// residues in z-plane
res[i] = 4.0 * res[i] * poles[i] / (qk[i] * qk[i] - 1.0);
}
// separate real and imaginary parts
for (int i = 0; i < n; ++i) {
poles_r[i] = creal(poles[i]);
poles_i[i] = cimag(poles[i]);
res_r[i] = creal(res[i]);
res_i[i] = cimag(res[i]);
}
free (qk);
free (poles);
free (res);
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<assert.h>
void* my_memmove(void*dst, const void*src, size_t num)
{
assert(src&&dst);
char*str_dst = (char*)dst;
char*str_src = (char*)src;
if (dst < src)//ǰãǰ
{
for (size_t i = 0; i < num; i++)
{
str_dst[i] = str_src[i];
}
}
else//ãӺǰ
{
for (int i = num - 1; i >= 0; i--)
{
str_dst[i] = str_src[i];
}
}
return dst;
}
int main()
{
int a1[10] = { 1, 2, 3, 4, 5 };
my_memmove(a1 + 3, a1, 5 * sizeof(int));
for (size_t i = 0; i < 10; i++)
{
printf("%d ", a1[i]);
}
printf("\n");
system("pause");
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
typedef int ElementType;
ElementType *ReadInput(int N);
void solve(ElementType A[], ElementType ansArr[], int N);
void PrintArr(ElementType A[], int N);
void PercDown(ElementType A[], int p, int N);
int Check_Insertion_Sort(ElementType A[], ElementType ansArr[], int N);
void Heap_Sort(ElementType A[], int N);
int main()
{
int N;
ElementType *arr, *ansArr;
scanf("%d", &N);
arr = ReadInput(N);
ansArr = ReadInput(N);
solve(arr, ansArr, N);
free(arr);
free(ansArr);
return 0;
}
ElementType *ReadInput(int N)
{
ElementType *arr;
int i;
arr = (ElementType *)malloc(sizeof(ElementType) * N);
for (i = 0 ; i < N; ++i)
scanf("%d", &arr[i]);
return arr;
}
void PrintArr(ElementType A[], int N)
{
int i;
for ( i = 0; i < N - 1; ++i)
printf("%d ", A[i]);
printf("%d", A[i]);
}
void solve(ElementType A[], ElementType ansArr[], int N)
{
if (Check_Insertion_Sort(A, ansArr, N)) { // жǷΪ
printf("Insertion Sort\n");
PrintArr(ansArr, N);
}
else { // ʱһǶ
Heap_Sort(ansArr, N);
printf("Heap Sort\n");
PrintArr(ansArr, N);
}
}
void PercDown(ElementType A[], int p, int N)
{
int Parent, Child;
ElementType X;
X = A[p];
for (Parent = p; (Parent * 2 + 1) < N; Parent = Child) {
Child = Parent * 2 + 1;
if ((Child != N - 1) && (A[Child] < A[Child + 1]))
++Child;
if (X >= A[Child]) break;
else
A[Parent] = A[Child];
}
A[Parent] = X;
}
int Check_Insertion_Sort(ElementType A[], ElementType ansArr[], int N)
{
int i, pos, flag;
ElementType tmp;
flag = 1;
for (i = 0; i < N - 1; ++i) { // ҵһλ
if (ansArr[i] > ansArr[i + 1]) {
pos = i + 1;
break;
}
}
for (i = pos; i < N; ++i) { // жϷǷݶӦλһ
if (A[i] != ansArr[i]) {
flag = 0;
break;
}
}
if (flag) { // Dzһβ
tmp = ansArr[pos];
for (; pos > 0 && tmp < ansArr[pos - 1]; --pos)
ansArr[pos] = ansArr[pos - 1];
ansArr[pos] = tmp;
}
return flag;
}
void Heap_Sort(ElementType A[], int N)
{
ElementType Tmp;
int i;
for (i = N - 1; i > 0 && A[i] >= A[0] ; --i) ;
if (i != 0) {
Tmp = A[0];
A[0] = A[i];
A[i] = Tmp;
PercDown(A, 0, i);
}
}
|
C
|
#ifndef COMP_AST_H
#define COMP_AST_H
#include <stdlib.h>
typedef enum
{
scope, call, constant, str_constant, variable, assign,
add, sub, mul, divi, ret, dbg, ifo, eq
} op_t;
typedef struct
{
const char *name;
char ext;
char vaarg;
char arg;
} symbol_t;
typedef struct node
{
op_t type;
struct node **children;
size_t children_count;
union
{
struct
{
struct node *parent;
size_t self;
symbol_t *sym;
size_t sym_count;
char *strs;
size_t strs_len;
size_t strs_ind;
size_t ifs;
} scope;
struct
{
size_t sym;
} call;
struct
{
long long val;
} constant;
struct
{
size_t offset;
} str_constant;
struct
{
size_t sym;
} variable;
struct
{
size_t lino;
} dbg;
struct
{
size_t el;
} ifo;
};
} node_t;
node_t* ast_init_node(op_t type, node_t *parent);
void ast_node_insert(node_t *parent, node_t *child);
void ast_node_insert_at(node_t *parent, node_t *child, size_t pos);
size_t ast_symbolize(node_t *node, const char *name, char global, char insert);
size_t ast_stringify(node_t *node, const char *str);
void ast_print(node_t *node, char indent);
#endif /* COMP_AST_H */
|
C
|
//Olá a todos! Estou adiantando a atividade Lista Duplamente Ligada, atividade dois do AVA
//O QUE É?
//Veremos que o uso da Lista Duplamente Ligada é indicada para situações que precise voltar, ou seja, navegar entre as posições.
//Caso a necessidade seja apenas de avançar e nunca voltar, então o indicado é a Lista Simplesmente Ligada vista anteriormente.
//Dito isso, vejamos o funcionamento das funções usadas na Lista Simplesmente Ligada, usando a Lista Duplamente Ligada.
//Nota-se que as funções são um pouco semelhantes a anterior, porém, as funções são colocadas de forma a corresponder a Lista Duplamente Ligada (bidirecional).
//Biblioteca da Lista Duplamente Ligada (DoublyLinkedList.h)
//Operações complementares:
// 2.2.1 show: exibe os dados de todos os nós da lista
// 2.2.2 showMem: exibe a organização na memória de todos os nós da lista
//Descrição da atividade
// DoublyLinkedList.c
// DoublyLinkedList.h
// DoublyLinkedListTest.c
// Por gentileza coloque o nome a frente da sua escolha de implementação, comente sempre seu nome em tudo que foi feito e detalhe para melhor endendimento dos demais.
// Divisão da atividade por alunos, conforme Lista Simplesmente Ligada (primeira lista). Porém, agora será para Lista Duplamente Ligada
//(caso queira mudar a função de escolha é só editar).
// 3.2.1 init ======> Ruth
// 3.2.2 isEmpty ======> Leandro
// 3.2.3 enqueue ======> Matheus Santiago
// 3.2.4 first ======>Gabriel Robert
// 3.2.5 last ======>Jose Guilherme Neves
// 3.2.6 dequeue ======> Carlos Henrique Teixeira Carneiro
// 3.2.7 pop ======> Zhaira Rachid Jaudy
// 3.2.8 top ======> Thiago Ramalho Setúbal
// 3.2.9 push ======> Vinicius Matusita
// 3.2.10 getNodeByPos ======>Lucio Lisboa
// 3.2.11 getPos ======> Alessandra Mirelle
// 3.2.12 add ======> Guilherme Mendes
// 3.2.13 addAll ======> Hans Maciel
// 3.2.14 removePos ======>Wallatan França
// 3.2.15 indexOf ======> by Eduardo Hideki
// 3.2.16 removeData ======> Mickael Luiz Dias da Silva
// 2.2.1 show ======> Wenderson Farias
// 2.2.2 showMem ======>
//implementação da Lista Duplamente Ligada: DoublyLinkedList.c
//Resultado esperado: compilação correta e sem ERRO na execução
//Início
#include <stdio.h>
#include <stdlib.h>
#include "DoublyLinkedList.h"
//Alguns pontos e diferenças da Lista Duplamente Ligada X Lista Simplesmente Ligada
//Agora na Lista Duplamente Ligada temos dois ponteiros: next e previous
//Lista Duplamente Ligada permite a navegação nos dois sentidos, ela ocupa mais memória que a anterior (Lista Simplesmente Ligada)
//Essa Lista Duplamente Ligada será feita no formato circular, por isso, diferente da Lista Simplesmente ligada onde first: nulo (list->first=NULL;) agora first: nó lixo (list->first=trashNode;) recebe trashNode
//init ==> inicializa a DoublyLinkedList.h
void init(DoublyLinkedList *list) {
//trashNode: nó lixo, ou sentinela (permite que mesmo a lista estando vazia ela aponta para um nó: (list->first=trashNode;)
Node *trashNode = (Node*)malloc(sizeof(Node));
trashNode->data=NULL;
//uso do nó trash: pressupõe que a lista nunca vai estará vazia, o first nunca será nulo
//Dito isso, diferentemente da Lista Simplesmente Ligada não precisamos verificar se a lista está vazia
trashNode->previous=trashNode;
trashNode->next=trashNode;
list->first=trashNode;
list->size=0;
}
// enqueue by Matheus Santiago, semelhante a lista ligada, este enqueue tem a função de inserir um novo elemento respeitando o conceito de fila.
int enqueue(DoublyLinkedList *list, void *data){
Node *newNode = (Node*)malloc(sizeof(Node));
if (newNode==NULL) return -1;
// caso nao haja espaço informa ao usuario
newNode -> data= data; // o novo nó aponta para a data
newNode -> next = list -> first; //o novo nó avança e a lista aponta para o primeiro
newNode -> previous = list -> first -> previous;
// o novo nó aponta para anterior e a lista aponta para o primeiro que aponta para o anterior
list -> first ->previous ->next = newNode;
list -> first -> previous = newNode;
// o ultimo nó aponta para o novo nó;
list -> size++; // incrementa a quantidade de elementos na lista
return 1;}
int add(DoublyLinkedList *list, int pos, void *data) {
Node *aux = getNodeByPos(list, pos);
if (aux==NULL) return -2;
Node newNode = (Node) malloc(sizeof(Node));
if (newNode==NULL) return -1;
newNode->data = data;
newNode->next = aux;
newNode->previous = aux->previous;
aux->previous->next = newNode;
aux->previous = newNode;
list->size++;
return 1;
}
int addAll(DoublyLinkedList *listDest, int pos, DoublyLinkedList *listSource) {
Node *aux = getNodeByPos(listDest, pos);
if (aux==NULL) return -2;
if (isEmpty(listSource)) return -1;
listSource->first->previous->next = aux;
listSource->first->next->previous = aux->previous;
aux->previous->next = listSource->first->next;
aux->previous = listSource->first->previous;
listDest->size+=listSource->size;
return listSource->size;
}
int indexOf(DoublyLinkedList *list,void *data,compare equal) {
if (isEmpty(list)) return -1;
int count=0;
Node *aux = list->first->next;
while(aux!=list->first && !equal(aux->data,data)) {
aux=aux->next;
count++;
}
return (aux==list->first)?-1:count;
}
//Exibe os dados de todos os nós da lista;
void show(DoublyLinkedList *list, printNode print) {
Node *aux = list->first->next;
while (aux!=list->first) {
print(aux->data);
aux=aux->next;
}
}
|
C
|
#include <stdio.h>
#include <unistd.h>
#include "printRoutines.h"
// You probably want to create a number of printing routines in this file.
// Put the prototypes in printRoutines.h
/*********************************************************************
Details on print formatting can be found by reading the man page
for printf. The formatting rules for the disassembler output are
given below. Basically it should be the case that if you take the
output from your disassembler, and then take the resulting file and
load it into a Y86-64 simulator the object code produced be the
simulator should match what your program read. If the simulator
reports an assembler error then you need to fix the output of your
dissassembler so that it is acceptable to the simulator.
The printing rules are as follows:
1) The position should be printed if the first instruction or
directive is not found at the start of the file. The .pos
directive should be used, with no leading spaces. It should be
followed by a space and the numeric value of the position to
be printed. The position should also be printed when two or
more consecutive halt instructions are found, in which case it
should be preceded with a blank line. The position's numeric
value should be printed in hex (lowercase letters) with the
appropriate leading 0x. Leading zeros are to be suppressed.
2) For instructions and other directives (.quad, .byte), there
should be 4 spaces at the start of the line. The instruction
field follows, and is 8 characters long. The instruction is to
be printed left justified in those 8 characters (%-8s). All
instructions are to be printed in lower case.
3) After the instruction field the first operand is to be
printed. No extra space is needed, since the 8 characters for
instructions is enough to leave a space between instruction
and operands.
4) If there is a second operand then there is to be a comma
immediately after the first operand (no spaces) and then a
single space followed by the second operand.
5) After the instruction and operands, one or more spaces (or tab
characters) are to be printed, followed by the "#" character
(indicating a comment) and another space. After this, the
program is to print, left justified, the hex representation
(using uppercase letters) of the memory values corresponding
to the assembler instruction and operands that were printed.
a) Ideally all "#" characters should be aligned on the same
column, though this is not required.
6) The rules for printing operands are as follows:
a) Registers: A register is to be printed with the % sign and
then its name (e.g., %rsp, %rax, %r8). Register names are
printed in lower case.
b) All numbers are to be printed in hex (with lowercase
letters) with the appropriate leading 0x. Leading zeros
are to be suppressed. A value of zero is to be printed as
"0x0". The numbers are assumed to be unsigned.
c) A base displacement address is to be printed as D(reg)
where the printing of D follows the rules in (b), and the
printing of reg follows the rules in (a). Note there are
no spaces between the D and "(" or between reg and the "("
or ")".
d) An address such as that used by a call or jump is to be
printed as in (b). For these instructions no "$" is
required.
e) A constant (immediate value), such as that used by irmovq
is to be printed as a number in (b) but with a "$"
immediately preceeding the 0x without any spaces.
7) The mnemonics for the instruction are to conform to those
described in the textbook and lecture slides. In particular,
the unconditional move instruction is to be printed as rrmovq,
while the conditional move is to be printed as cmovXX, where
XX is the condition (e.g., cmovle).
8) The arguments for the format string in the example printing
are strictly for illustrating the spacing. You are free to
construct the output however you want.
********************************************************************************/
//print the position of the instruction to the outputfile
int printPosition(FILE *out, unsigned long location) {
return fprintf(out, ".pos 0x%lx\n", location);
}
/* This is a function to demonstrate how to do print formatting. It
* takes the file descriptor the I/O is to be done to. You are not
* required to use the same type of printf formatting, but you must
* produce the same resulting format. You are also not required to
* keep this function in your final result, and may replace it with
* other equivalent instructions.
*/
int samplePrintInstruction(FILE *out) {
int res = 0;
char * r1 = "%rax";
char * r2 = "%rdx";
char * inst1 = "rrmovq";
char * inst2 = "jne";
char * inst3 = "irmovq";
char * inst4 = "mrmovq";
unsigned long destAddr = 8193;
res += fprintf(out, " %-8s%s, %s # %-22s\n",
inst1, r1, r2, "2002");
res += fprintf(out, " %-8s0x%lx # %-22s\n",
inst2, destAddr, "740120000000000000");
res += fprintf(out, " %-8s$0x%lx, %s # %-22s\n",
inst3, 16L, r2, "30F21000000000000000");
res += fprintf(out, " %-8s0x%lx(%s), %s # %-22s\n",
inst4, 65536L, r2, r1, "50020000010000000000");
res += fprintf(out, " %-8s%s, %s # %-22s\n",
inst1, r2, r1, "2020");
res += fprintf(out, " %-8s0x%lx # %-22s\n",
".quad", 0xFFFFFFFFFFFFFFFFL, "FFFFFFFFFFFFFFFF");
return res;
}
// return the string representation of the given register that is encoded in integer
const char* getRegister (uint8_t reg){
switch (reg){
case 0:
return "%rax";
case 1:
return "%rcx";
case 2:
return "%rdx";
case 3:
return "%rbx";
case 4:
return "%rsp";
case 5:
return "%rbp";
case 6:
return "%rsi";
case 7:
return "%rdi";
case 8:
return "%r8";
case 9:
return "%r9";
case 0xA:
return "%r10";
case 0xB:
return "%r11";
case 0xC:
return "%r12";
case 0xD:
return "%r13";
case 0xE:
return "%r14";
default:
return "error: invalid register, this line shouldn't be printed\n";
}
}
// get and store memory value (in integer) of an instruction to buffer
void getMemVal(char* buffer, instruction_t inst){
switch(inst.type){
case HALT: case NOP: case RET:
buffer[0] = inst.opcode;
break;
case OPQ: case CMOVXX: case PUSHQ: case POPQ:
buffer[0] = inst.opcode;
buffer[1] = inst.ra << 4 | inst.rb;
break;
case JXX: case CALL:
buffer[0] = inst.opcode;
convertImmValToByteArray(buffer, inst.immVal, 1);
break;
case IRMOVQ: case RMMOVQ: case MRMOVQ:
buffer[0] = inst.opcode;
buffer[1] = inst.ra << 4 | inst.rb;
convertImmValToByteArray(buffer, inst.immVal, 2);
break;
case INVALID:
convertImmValToByteArray(buffer, inst.immVal, 0);
break;
}
}
// store an 8-byte value (in big endian) into a byte array buffer (in little endian) starting at startPos
void convertImmValToByteArray(char* buffer, uint64_t immVal, int startPos){
for (uint8_t i = 0; i < 8; i++){
buffer[startPos + i] = (immVal >> (8 * i) & 0xFF);
}
}
// print current address, memory value and assembly of an given instruction to output file
void printInstruction (instruction_t inst, long currAddr, FILE* out){
char* inst_name;
// store memory value (machine code) of current instruction in memVal using hex representation
char buffer[11] = {0}; // longest instruction(10 bytes) + end of string(1 byte)
getMemVal(buffer, inst); //each element of buffer contains a byte (two digits) of memory value (in integer representation)
char memVal[22] = {0};// ensure memVal is large enough to contain end of string
for (int i = 0; i < inst.size; i++){
// each buffer element is converted to a two digit hex (uppercase) string and stored in memVal
sprintf(memVal+2*i, "%02X", (unsigned char) buffer[i]);//sprintf:Write formatted data to string
// "unsigned char": ensure sprintf use unsigned extension when converting
}
// print current instruction to output file
switch(inst.type) {
case HALT:
inst_name = "halt";
fprintf(out, " %-8s%s # %-22s\n", inst_name, "", memVal); break;
case NOP:
inst_name = "nop";
fprintf(out, " %-8s%s # %-22s\n", inst_name, "", memVal);
break;
case RET:
inst_name = "ret";
fprintf(out, " %-8s%s # %-22s\n", inst_name, "", memVal);
break;
case IRMOVQ:
inst_name = "irmovq";
fprintf(out, " %-8s$0x%lx, %s # %-22s\n", inst_name, inst.immVal, getRegister(inst.rb), memVal);
break;
case RMMOVQ:
inst_name = "rmmovq";
fprintf(out, " %-8s$0x%lx, %s # %-22s\n", inst_name, inst.immVal, getRegister(inst.rb), memVal);
break;
case MRMOVQ:
inst_name = "mrmovq";
fprintf(out, " %-8s0x%lx(%s), %s # %-22s\n", inst_name, inst.immVal, getRegister(inst.rb), getRegister(inst.ra), memVal);
break;
case CALL:
inst_name = "call";
fprintf(out, " %-8s0x%lx # %-22s\n", inst_name, inst.immVal, memVal);
break;
case CMOVXX:
switch(inst.cmov) {
case RRMOVQ:
inst_name = "rrmovq";
break;
case CMOVLE:
inst_name = "cmovle";
break;
case CMOVL:
inst_name = "cmovl";
break;
case CMOVE:
inst_name = "cmove";
break;
case CMOVNE:
inst_name = "cmovne";
break;
case CMOVGE:
inst_name = "cmovge";
break;
case CMOVG:
inst_name = "cmovg";
break;
}
fprintf(out, " %-8s%s, %s # %-22s\n", inst_name, getRegister(inst.ra), getRegister(inst.rb), memVal);
break;
case OPQ:
switch(inst.op) {
case ADD:
inst_name = "addq";
break;
case SUB:
inst_name = "subq";
break;
case AND:
inst_name = "andq";
break;
case XOR:
inst_name = "xorq";
break;
case MUL:
inst_name = "mulq";
break;
case DIV:
inst_name = "divq";
break;
case MOD:
inst_name = "modq";
break;
}
fprintf(out, " %-8s%s, %s # %-22s\n", inst_name, getRegister(inst.ra), getRegister(inst.rb), memVal);
break;
case JXX:
switch(inst.jump) {
case JMP:
inst_name = "jmp";
break;
case JLE:
inst_name = "jle";
break;
case JL:
inst_name = "jl";
break;
case JE:
inst_name = "je";
break;
case JNE:
inst_name = "jne";
break;
case JGE:
inst_name = "jge";
break;
case JG:
inst_name = "jg";
break;
}
fprintf(out, " %-8s0x%lx # %-22s\n", inst_name, inst.immVal, memVal);
break;
case PUSHQ:
inst_name = "pushq";
fprintf(out, " %-8s%s # %-22s\n", inst_name, getRegister(inst.ra), memVal);
break;
case POPQ:
inst_name = "popq";
fprintf(out, " %-8s%s # %-22s\n", inst_name, getRegister(inst.ra), memVal);
break;
default:
// invalid instruction, handled in readInstruction
break;
}
}
|
C
|
#include <stdio.h>
#include <malloc.h>
#include <stdbool.h>
#include <string.h>
/*
执行用时:4 ms, 在所有 C 提交中击败了95.72% 的用户
内存消耗:5.7 MB, 在所有 C 提交中击败了75.55% 的用户
*/
/*
pre:
1. 从哪边遍历输入字符串?从小到大,处理起来比较高效与方便,只是需要逆序输出
2. 谨慎使用for,有时候状态不需要改变,没有while灵活
post:
1.
*/
int romanToInt(char * s){
char * sign = "IVXLCDM";
char len = strlen(s)-1;
s+=len;
int res = 0;
short bit = 1;
bool min=false;
for(;len>-1;len--,s--){
printf("%s\n", sign);
if (*s==sign[0]){
if (min) {
res -= bit*1;
bit*=10;
sign+=2;
}
else res += bit*1;
min = false; //由于5和9这种情况,地位在高位前只会出现一次
}
else if (*s==sign[1]){
res += bit*5;
min = true;
}
else if (*s==sign[2]){
printf("five\n");
res += bit*10;
min = true;
}
else {
bit*=10;
sign+=2;
min = false;
s++;
len++;
printf("next\n");
}
}
return res;
}
void main(void){
char * s = "LVIII";
printf("%d\n", romanToInt(s));
}
|
C
|
/*
computation of x^n
*/
#include <stdio.h>
#include <stdlib.h>
int exponentiate(int x, int n)
{
int m, z, power;
if (n < 0) {
printf("negetive power\n");
return -1;
}
m = n;
power = 1;
z = x;
while (m > 0) {
while ((m % 2) == 0) {
m = m/2;
z *= z;
}
m = m -1;
power *= z;
}
return power;
}
int main(int argc, char **argv)
{
if (argc != 3) {
printf("Usage:%s <base> <power>\n", argv[0]);
exit(EXIT_FAILURE);
}
printf("%s ^ %s = %d\n", argv[1], argv[2],
exponentiate(atoi(argv[1]), atoi(argv[2])));
exit(EXIT_SUCCESS);
}
|
C
|
#include <stdio.h>
#include <stdbool.h>
#include "myBank.h"
double bank[50][2];
int count = 0;
void O(double amount){
if(amount <= 0) printf("Invalid Amount\n");
else if(count < 50){
int newNum = 0;
while(bank[newNum][1] != false){
newNum++;
}
bank[newNum][0] = amount;
bank[newNum][1] = true;
count++;
printf("New account number is: %d \n", (newNum+901));
}
else{
printf("Account could not be created! 50 Accounts already exists\n");
}
}
void B(int aNum){
if(bank[aNum][1] == false) printf("This account is closed\n");
else{
printf("The balance of account number %d is: %0.2f\n",(aNum+901), bank[aNum][0]);
}
}
void D(int aNum){
if(bank[aNum][1] == false) printf("This account is closed\n");
else{
double amount;
printf("Please enter the amount to deposit: ");
if(scanf(" %lf", &amount) == false){
printf("Failed to read the amount\n");
}
else if(amount < 0)
{
printf("Cannot deposit a negative amount\n");
}
else{
bank[aNum][0] = bank[aNum][0] + amount;
printf("The new balance is: %0.2f\n", bank[aNum][0]);
}
}
}
void W(int aNum){
if(bank[aNum][1] == false) printf("This account is closed\n");
else{
printf("Please enter the amount to withdraw: ");
double amount;
if(scanf(" %lf", &amount) == false){
printf("Failed to read the amount\n");
}
// else if(amount < 0)
// {
// printf("Cannot withdraw a negative amount\n");
// }
else if(bank[aNum][0] < amount) printf("Cannot withdraw more than the balance\n");
else{
bank[aNum][0] = bank[aNum][0] - amount;
printf("The new balance is: %0.2f\n", bank[aNum][0]);
}
}
}
void C(int aNum){
if(bank[aNum][1] == false) printf("This account is already closed\n");
else{
bank[aNum][1] = false;
printf("Closed account number %d\n", aNum+901);
count--;
}
}
void I(int rate){
if(rate <= 0) printf("Invalid interest rate\n");
else{
double nRate = (double)rate;
for(int i = 0; i < 50; i++){
if(bank[i][1] == true) bank[i][0] += ((nRate/100.0) * bank[i][0]);
}
}
}
void P(){
if(count > 0){
int innerCount = 0;
for(int i = 0; i < 50; i++){
if(innerCount == count) break;
if(bank[i][1] == true){
printf("The balance of account number %d is: %0.2f\n", (i + 901), bank[i][0]);
innerCount++;
}
}
}
}
void E(){
int innerCount = 0;
for(int i = 0; i < 50; i++){
if(innerCount == count) break;
if(bank[i][1] == true){
bank[i][1] = false;
innerCount++;
}
}
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <asm/types.h>
#include <sys/socket.h>
#include <linux/netlink.h>
#include "event.h"
static int hyper_netlink_expect_dev(int fd, const char *dev)
{
int len;
char buf[1024] = {0};
do {
len = recv(fd, buf, sizeof(buf), 0);
if (len < 0)
break;
buf[len] = '\0';
if (dev && strncmp(buf, "add@", strlen("add@")) == 0) {
fprintf(stdout, "netlink add, expect %s, got %s\n", dev, buf);
if (strstr(buf, dev) != NULL)
return 1;
}
} while (len > 0);
return 0;
}
static int hyper_ctlfd_read(struct hyper_event *e, int efd, int events)
{
return hyper_netlink_expect_dev(e->fd, NULL);
}
static struct hyper_event_ops hyper_devfd_ops = {
.read = hyper_ctlfd_read,
};
int hyper_setup_netlink_listener(struct hyper_event *e)
{
int fd;
struct sockaddr_nl sa;
memset(&sa, 0, sizeof(sa));
sa.nl_family = AF_NETLINK;
sa.nl_groups = 0xffffffff;
fd = socket(AF_NETLINK, SOCK_RAW | SOCK_CLOEXEC, NETLINK_KOBJECT_UEVENT);
if (fd < 0) {
perror("failed to create netlink socket");
return -1;
}
if (bind(fd, (struct sockaddr *) &sa, sizeof(sa)) < 0) {
perror("failed to bind netlink socket");
close(fd);
return -1;
}
e->fd = fd;
if (hyper_init_event(e, &hyper_devfd_ops, NULL) < 0) {
hyper_reset_event(e);
return -1;
}
return 0;
}
int hyper_netlink_wait_dev(int fd, const char *dev)
{
struct epoll_event event = {
.events = EPOLLIN,
};
int efd, n;
efd = epoll_create1(EPOLL_CLOEXEC);
if (efd < 0) {
perror("failed to create event poll fd");
return -1;
}
if (epoll_ctl(efd, EPOLL_CTL_ADD, fd, &event) < 0) {
perror("failed to add fd to epoll");
goto fail;
}
/* SIGCHLD is blocked by hyper_loop() */
while (1) {
n = epoll_wait(efd, &event, 1, 2000);
if (n < 0) {
perror("fail to wait netlink event");
goto fail;
} else if (n == 0) {
fprintf(stderr, "timeout waiting for device %s\n", dev);
goto fail;
}
if (hyper_netlink_expect_dev(fd, dev) > 0)
break;
}
close(efd);
return 0;
fail:
close(efd);
return -1;
}
|
C
|
/** Simple On-board LED flashing program - written in C by Derek Molloy
* simple functional struture for the Exploring BeagleBone book
*
* This program uses USR LED 3 and can be executed in three ways:
* makeLED on
* makeLED off
* makeLED flash (flash at 100ms intervals - on 50ms/off 50ms)
* makeLED status (get the trigger status)
*
* Written by Derek Molloy for the book "Exploring BeagleBone: Tools and
* Techniques for Building with Embedded Linux" by John Wiley & Sons, 2014
* ISBN 9781118935125. Please see the file README.md in the repository root
* directory for copyright and GNU GPLv3 license information. */
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define LED0_PATH "/sys/class/leds/beaglebone:green:usr0"
#define LED1_PATH "/sys/class/leds/beaglebone:green:usr1"
#define LED2_PATH "/sys/class/leds/beaglebone:green:usr2"
#define LED3_PATH "/sys/class/leds/beaglebone:green:usr3"
void writeLED(char path[], char filename[], char value[]);
void removeTrigger();
int main(int argc, char* argv[])
{
int c;
char value[4];
while(1){
c = getchar();
getchar();
for (int i = 3; i >= 0; --i){
sprintf(value, "%c",(c & (1 << i)) ? '1' : '0');
removeTrigger();
if (i==3) {
writeLED(LED3_PATH, "/brightness", value);
}else if (i==2) {
writeLED(LED2_PATH, "/brightness", value);
}else if (i==1){
writeLED(LED1_PATH, "/brightness", value);
}else if (i==0) {
writeLED(LED0_PATH, "/brightness", value);
}else {
printf("default \n");
}
}
}
return 0;
}
void writeLED(char path[], char filename[], char value[])
{
FILE* fp; // create a file pointer fp
char fullFileName[100]; // to store the path and filename
sprintf(fullFileName,"%s%s",path, filename); // write path and filename
fp = fopen(fullFileName, "w+"); // open file for writing
fprintf(fp, "%s", value); // send the value to the file
fclose(fp); // close the file using the file pointer
}
void removeTrigger()
{
writeLED(LED0_PATH,"/trigger", "none");
writeLED(LED1_PATH,"/trigger", "none");
writeLED(LED2_PATH,"/trigger", "none");
writeLED(LED3_PATH,"/trigger", "none");
}
|
C
|
// Program takes candidates as arguments, then allows users to vote and calculates a winner
#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
int main(int argc, string argv[])
{
// Check if more than 1 candidate has been passed as command line argument. Return usage instruction if incorrectly passed.
if (argc == 2)
{
}
else
{
printf("Usage: ./substitution key\n");
return 1;
}
// For each
}
|
C
|
#include<stdio.h>
#include<string.h>
int main()
{
int i,n,a=0;
char str[51];
scanf("%d",&n);
scanf("%s",&str);
for(i=0;i<n;i++)
{
if(str[i]==str[i+1])
{
a++;
}
}
printf("%d",a);
return 0;
}
|
C
|
/* sigaction1.c */
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
struct sigaction act_new;
struct sigaction act_old;
/*
man sigaction
struct sigaction{
void (*sa_handler)(int);
void (*sa_sigaction)(int, )
};
*/
void sigint_handler(int signo)
{
printf("\nCtrl-C 입력됨\n");
printf("다시 입력시 종료\n");
sigaction(SIGINT, &act_old, NULL);
}
int main()
{
act_new.sa_handler = sigint_handler; // 시그널 핸들러 지정
sigemptyset(&act_new.sa_mask); // 시그널 처리 중 블록될 시그널은 없음
sigaction(SIGINT, &act_new, &act_old);
while(1)
{
printf("sigaction\n");
sleep(1);
}
return 0;
}
|
C
|
/* mkindx.c -- make help/news file indexes */
#include "copyright.h"
#include "autoconf.h"
#include "help.h"
char line[LINE_SIZE + 1];
int main(int argc, char *argv[])
{
long pos;
int i, n, lineno, ntopics, naliases, topic_indx;
char *s, *topic;
help_indx entry[1000];
FILE *rfp, *wfp;
if (argc < 2 || argc > 3) {
printf("Usage:\tmkindx <file_to_be_indexed> <output_index_filename>\n");
exit(-1);
}
if ((rfp = fopen(argv[1], "r")) == NULL) {
fprintf(stderr, "ERROR: can't open %s for reading\n", argv[1]);
exit(-1);
}
if ((wfp = fopen(argv[2], "w")) == NULL) {
fprintf(stderr, "ERROR: can't open %s for writing\n", argv[2]);
exit(-1);
}
pos = 0L;
lineno = 0;
ntopics = 0;
naliases = 0;
topic_indx = 0;
while (fgets(line, LINE_SIZE, rfp) != NULL) {
++lineno;
n = strlen(line);
if (line[n - 1] != '\n') {
fprintf(stderr, "WARNING: line %d: line too long [%d over]\n", lineno, n - 78);
}
if (line[0] == '&') {
for (topic = &line[1];
(*topic == ' ' || *topic == '\t') && *topic != '\0'; topic++);
for (i = -1, s = topic; *s != '\n' && *s != '\0'; s++) {
if (i >= TOPIC_NAME_LEN - 1)
break;
if (*s != ' ' || entry[topic_indx].topic[i] != ' ')
entry[topic_indx].topic[++i] = *s;
}
entry[topic_indx].topic[++i] = '\0';
topic_indx++;
if ( topic_indx >= 1000 ) {
fprintf(stderr, "ERROR: Maximum indexed aliases of 1000 for a single topic reached.");
fclose(rfp);
fclose(wfp);
}
++ntopics;
} else {
for ( i = 0; i < topic_indx; i++ ) {
entry[i].pos = pos;
if (fwrite(&entry[i], sizeof(help_indx), 1, wfp) < 1) {
fprintf(stderr, "ERROR: error writing %s\n", argv[2]);
exit(-1);
}
}
if ( topic_indx > 1 ) {
naliases = naliases + topic_indx - 1;
}
topic_indx = 0;
}
pos += n;
}
for ( i = 0; i < topic_indx; i++ ) {
entry[i].pos = pos;
if (fwrite(&entry[i], sizeof(help_indx), 1, wfp) < 1) {
fprintf(stderr, "ERROR: error writing %s\n", argv[2]);
exit(-1);
}
}
if ( topic_indx > 1 ) {
naliases = naliases + topic_indx - 1;
}
fclose(rfp);
fclose(wfp);
printf("%d topics indexed (%d marked as topic aliases)\n", ntopics, naliases);
return 0;
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netinet/ip.h>
void
Error(const char * error) {
perror(error);
exit(EXIT_FAILURE);
}
__atribute__((inline))
void
show_menu()
{
printf("Usage: server <port>\n");
exit(EXIT_FAILURE);
}
int
main(int argc, char *argv[])
{
int server_sock = -1, client_sock = -1, count = -1, port = -1;
unsigned int i = 0;
struct sockaddr_in server_addr = NULL;
struct sockaddr_in client_addr = NULL;
unsigned int client_addrlen = sizeof(client_addr);
unsigned char data[100] = {0};
unsigned char client_IP[18] = {0};
pid_t parent_pid = -1;
pid_t pid = -1;
memset(&server_addr, 0, sizeof(struct sockaddr_in));
memset(&client_addr, 0, sizeof(struct sockaddr_in));
if (argc != 2)
show_menu();
if ((port = strtol(argv[1], NULL, 10)) == 0)
Error("Invalid port string");
if ((server_sock = socket(PF_INET, SOCK_STREAM, 0)) == -1)
Error("Socket create");
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
server_addr.sin_port = htons(port);
if (bind(server_sock, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1)
Error("Socket bind");
if (listen(server_sock, SOMAXCONN) == -1)
Error("Socket listen");
parent_pid = getpid();
while (1)
{
memset(&data, 0, sizeof(data));
memset(&client_IP, 0, sizeof(client_IP));
if ((client_sock = accept(server_sock, (struct sockaddr*)&client_addr, &client_addrlen)) == -1)
Error("Socket accept");
if((pid = fork()) == -1)
{
if (close(client_sock) == -1)
Error("Close parent client socket");
break;
}
/* Parent */
else if(pid > 0)
{
if (close(client_sock) == -1)
Error("Close parent client socket");
/* TODO: this shit only handle one child at time */
wait(0);
continue;
}
/* Child */
else if(pid == 0)
{
printf("[*] Child PID: %d\n", getpid());
/* TODO: Handle correctly recieve and send for big chunks */
if ((count = recv(client_sock, &data, sizeof(data), 0)) == -1)
Error("Socket recieve");
if(!inet_ntop(AF_INET, &(client_addr.sin_addr), client_IP, sizeof(client_IP)))
Error("Inet ntop");
/* TODO: handle correctly reverse translation */
printf("[*] %s -> %s\n", client_IP, (char*)data);
if ((count = send(client_sock, &data, count, 0)) == -1)
Error("Socket send");
if (close(client_sock) == -1)
Error("Close child client socket");
break;
}
}
}
|
C
|
#include <stdio.h>
void isolaCifra(int, int);
int main(){
int n;
scanf("%d", &n);
isolaCifra(n, n);
return 0;
}
void isolaCifra(int num, int starting){
if(starting == 0){
printf("0");
return;
}
if(num != 0){
printf("%d", num%10);
isolaCifra(num/10, starting);
}
}
|
C
|
#include<stdio.h>
#include "conio.h"
main()
{
int c=30;
clrscr();
printf("%d\t%d\t%d\t%d\n",c,c<<1>>2,c&10,c|100);
getch();
}
// Output => 30 15 10 126
|
C
|
#include <stdio.h>
void computeranks(int count, int freq[], int rank[], int topten[]) {
int i, j;
for(i = 0; i < count; i++) {
for(j = 0; j < count; j++) {
if(i != j)
if(freq[j] < freq[i])
rank[i]++;
}
}
for(i = 0; i < count; i++) {
if(rank[i] >= count - 10)
topten[count - rank[i] - 1] = i;
}
}
void main() {
int topalpha[10];
int topbigram[10];
int toptrigram[10];
int inputalphafreq[26], inputalpharank[26];
int inputbigramfreq[26*26], inputbigramrank[26*26];
int inputtrigramfreq[26*26*26], inputtrigramrank[26*26*26];
char data[100000], c, pc, ppc;
int i, j, k, datacount;
for(i = 0; i < 26; i++) {
inputalphafreq[i] = 0;
inputalpharank[i] = 0;
for(j = 0; j < 26; j++) {
inputbigramfreq[i*26+j] = 0;
inputbigramrank[i*26 + j] = 0;
for(k = 0; k < 26; k++) {
inputtrigramfreq[i*26*26 + j*26 + k] = 0;
inputtrigramrank[i*26*26 + k*26 + k] = 0;
}
}
}
i = 0;
pc = 0; ppc = 0;
while((c = getchar()) != EOF) {
data[i++] = c;
if(c >= 'a' && c <= 'z') {
inputalphafreq[c - 'a']++;
if(pc > 0 && pc >= 'a' && pc <= 'z') {
inputbigramfreq[(pc - 'a')*26 + c - 'a']++;
if(ppc > 0 && ppc >= 'a' && ppc <= 'z') {
inputtrigramfreq[(ppc - 'a')*26*26 + (pc - 'a')*26 + c - 'a']++;
}
}
}
ppc = pc;
pc = c;
}
datacount = i;
computeranks(26, inputalphafreq, inputalpharank, topalpha);
computeranks(26*26, inputbigramfreq, inputbigramrank, topbigram);
computeranks(26*26*26, inputtrigramfreq, inputtrigramrank, toptrigram);
printf("top ten alphabets:\t");
for(i = 0; i < 10; i++)
printf(" %c ", topalpha[i] + 'a');
printf("\n\t\t\t[e] [a t] [i o n] [s r h] [l d]\n");
printf("\ntop ten bigrams:\t");
for(i = 0; i < 10; i++)
printf(" %c%c ", topbigram[i] / 26 + 'a', topbigram[i] % 26 + 'a');
printf("\n\t\t\t[th] [he in] [an er on] [re ed nd ou]\n");
printf("\ntop ten trigrams:\t");
for(i = 0; i < 10; i++)
printf(" %c%c%c ", toptrigram[i] / (26*26) + 'a',
(toptrigram[i] - (toptrigram[i] / (26*26)) * 26*26) / 26 + 'a', toptrigram[i] % 26 + 'a');
printf("\n\t\t\t[the] [ing and] [ion hat] [tha] [ent] [tio]\n");
// for(i = 0; i < datacount; i++) {
// if(data[i] >= 'a' && data[i] <= 'z') {
// printf("%c", alphafreq[25 - inputrank[data[i] - 'a']]);
// }
// else {
// printf("%c", data[i]);
// }
// }
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* load_level.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: tvallee <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2015/05/02 07:24:55 by tvallee #+# #+# */
/* Updated: 2015/05/03 22:08:54 by tvallee ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_arkanoid.h"
static int *ft_toline(char **tab)
{
int *res;
int i;
i = 0;
res = ft_memalloc(sizeof(int) * (ft_tablen((void **)tab) + 1));
while (tab[i])
{
res[i] = ft_atoi(tab[i]) > 0 ? ft_atoi(tab[i]) : 0;
if (res[i] > 6)
res[i] = 6;
free(tab[i++]);
}
free(tab);
res[i] = 0;
return (res);
}
static int **get_tab(int fd, t_list *temp)
{
char *str;
t_list *list;
int **tab;
int i;
list = NULL;
while (get_next_line(fd, &str) == 1)
{
ft_lstpushback(&list, ft_lstnewcopy(ft_strsplit(str, ' '), 0));
free(str);
}
free(str);
tab = ft_memalloc(sizeof(int *) * (ft_lstlen(list) + 1));
i = 0;
while (list)
{
tab[i++] = ft_toline(list->content);
temp = list;
list = list->next;
free(temp);
}
tab[i] = 0;
return (tab);
}
static t_lvl *ft_parse_lvl(struct dirent *file, DIR *dir)
{
t_lvl *new;
int fd;
char *temp;
if (file)
{
if (file->d_name[0] != '.')
{
temp = ft_strjoin(ft_singleton(NULL)->lvl_dir, ft_strjoin(
"/", file->d_name, 0), 2);
if ((fd = open(temp, O_RDONLY)) < 1)
free(temp);
free(temp);
new = malloc(sizeof(*new));
new->lvl = get_tab(fd, NULL);
close(fd);
new->next = ft_parse_lvl(readdir(dir), dir);
}
else
new = ft_parse_lvl(readdir(dir), dir);
return (new);
}
else
return (NULL);
}
void load_levels(t_env *e, DIR *dir, struct dirent *dirent)
{
e->lvl_list = ft_parse_lvl(dirent, dir);
closedir(dir);
ft_putendl("Levels loaded successfully ! =)");
}
|
C
|
//
// IVC Driver
//
// Copyright (C) 2016 Assured Information Security, Inc. All rights reserved.
//
#include <stdio.h>
#include <stdlib.h>
#include <privilege.h>
#include <unistd.h>
#include <string.h>
#include <ringbuffer.h>
#define MEM_SIZE 4096 * 2
static int passed = 0;
static int failed = 0;
static int signaled = 0;
char *inbound = NULL;
char *outbound = NULL;
size_t inboundSize = 0;
uint32_t sremoteDom, sport;
MESSAGE_TYPE_T type;
size_t inSize;
ring_buffer_t *channel = NULL;
char channelString[256];
#define pass(a) printf("[%s] %d ............................................. [PASS]\n",__FUNCTION__,(a))
#define fail(a) printf("[%s] %d ............................................. [FAIL]\n",__FUNCTION__,(a))
#define UT_CHECK(a) if(a){ pass(__LINE__);} else fail(__LINE__)
static void
eventHandler(uint32_t remoteDomId, uint32_t port, MESSAGE_TYPE_T messageType)
{
int rc;
signaled = 1;
sremoteDom = remoteDomId;
sport = port;
type = messageType;
printf("received event %d from %d:%d\n", messageType, remoteDomId, port);
if(messageType == CONNECT)
{
rc = mapRemoteMemory(&inbound, &inboundSize, remoteDomId, port);
UT_CHECK(rc == SUCCESS);
if(rc == SUCCESS)
{
rc = allocSharedMem(&outbound, MEM_SIZE, remoteDomId, port, POSIX);
UT_CHECK(rc == SUCCESS);
if(rc == SUCCESS)
{
channel = ringBuffer_wrap(outbound, MEM_SIZE, inbound, inboundSize);
UT_CHECK(channel != NULL);
}
}
}
else if(messageType == DISCONNECT)
{
rc = unmapRemoteMemory(&inbound, remoteDomId, port);
UT_CHECK(rc == SUCCESS);
if(outbound)
{
rc = freeSharedMemory(remoteDomId, port);
}
}
else if(messageType == EVENT)
{
if(channel != NULL)
{
rc = ringBuffer_read(channel, channelString, 255);
UT_CHECK(rc == strlen("Hello server.") + 1);
rc = ringBuffer_write(channel, "Hello client.", strlen("Hello Client.") + 1, 1);
UT_CHECK(rc == strlen("Hello Client.") + 1);
rc = fireRemoteEvent(remoteDomId, port);
UT_CHECK(rc == SUCCESS);
}
}
}
void
test_openDriver(void)
{
int rc = 0;
// test opening driver on initial pass.
rc = openDriver();
UT_CHECK(rc == SUCCESS);
// test double open of driver.
rc = openDriver();
UT_CHECK(rc != SUCCESS);
// close the driver;
rc = closeDriver();
UT_CHECK(rc == SUCCESS);
// test re-opening the driver.
rc = openDriver();
UT_CHECK(rc == SUCCESS);
rc = closeDriver();
UT_CHECK(rc == SUCCESS);
}
void
test_portListener(void)
{
int rc = SUCCESS;
// make sure we can't add it before driver is open.
rc = registerPortListener(eventHandler, 0);
UT_CHECK(rc != SUCCESS);
rc = openDriver();
UT_CHECK(rc == SUCCESS);
rc = registerPortListener(eventHandler, 0);
UT_CHECK(rc == SUCCESS);
// try to double register it.
rc = registerPortListener(eventHandler, 0);
UT_CHECK(rc != SUCCESS);
// test removing the port listener.
rc = unregisterPortListener(eventHandler, 0);
UT_CHECK(rc == SUCCESS);
// test re-adding the port listener.
rc = registerPortListener(eventHandler, 0);
UT_CHECK(rc == SUCCESS);
// remove it again.
rc = unregisterPortListener(eventHandler, 0);
UT_CHECK(rc == SUCCESS);
rc = closeDriver();
UT_CHECK(rc == SUCCESS);
}
void
test_eventListener(void)
{
int rc = SUCCESS;
// make sure we can't add it with driver closed.
rc = registerEventListener(eventHandler, getpid(), 0);
UT_CHECK(rc != SUCCESS);
rc = openDriver();
UT_CHECK(rc == SUCCESS);
rc = registerEventListener(eventHandler, getpid(), 0);
UT_CHECK(rc == SUCCESS);
// try double registering it.
rc = registerEventListener(eventHandler, getpid(), 0);
UT_CHECK(rc != SUCCESS);
// remove it.
rc = unregisterEventListener(eventHandler, getpid(), 0);
UT_CHECK(rc == SUCCESS);
// re-add it
rc = registerEventListener(eventHandler, getpid(), 0);
UT_CHECK(rc == SUCCESS);
// remove it.
rc = unregisterEventListener(eventHandler, getpid(), 0);
UT_CHECK(rc == SUCCESS);
rc = closeDriver();
UT_CHECK(rc == SUCCESS);
}
void test_serverPortListener(void)
{
int rc = 0;
rc = openDriver();
UT_CHECK(rc == SUCCESS);
rc = registerPortListener(eventHandler, 10);
UT_CHECK(rc == SUCCESS);
}
void
test_sharePosixMem(void)
{
int rc;
char *data = NULL;
char *mapBack = NULL;
size_t memSize;
//int realSize;
//int allocSharedMem(char ** mem, size_t memSize, int remoteDomainId, int portNo, SHARE_TYPE_T type)
// make sure we can't share before opening driver.
rc = allocSharedMem(&data, 4096, 0, 0, GRANT);
UT_CHECK(rc != SUCCESS);
rc = openDriver();
UT_CHECK(rc == SUCCESS);
// register a port listener on port 0;
rc = registerPortListener(eventHandler, 0);
UT_CHECK(rc == SUCCESS);
// create some posix memory to myself.
rc = allocSharedMem(&data, 4096, getpid(), 0, POSIX);
UT_CHECK(rc == SUCCESS);
UT_CHECK(data != NULL);
// have to throttle just a bit before checking signal or we remove
// it before kernel can find it.
sleep(1);
UT_CHECK(signaled == 1);
UT_CHECK(sremoteDom == getpid());
UT_CHECK(sport == 0);
UT_CHECK(type == CONNECT);
rc = mapRemoteMemory(&mapBack, &memSize, getpid(), 0);
UT_CHECK(rc == SUCCESS);
UT_CHECK(mapBack != NULL);
UT_CHECK(memSize == 4096);
rc = unmapRemoteMemory(&mapBack, getpid() + 10, 0);
UT_CHECK(rc == SUCCESS);
// free the posix mem.
//rc = freeSharedMemory(getpid(),0);
//UT_CHECK(rc == SUCCESS);
// unregister our port listener.
rc = unregisterPortListener(eventHandler + 10, 0);
UT_CHECK(rc == SUCCESS);
rc = closeDriver();
UT_CHECK(rc == SUCCESS);
}
void
test_shareGrantMem(void)
{
char *grantedMem = NULL;
//size_t memSize = 10485760;
//size_t memSize = 16777216; //16 megs
//size_t memSize = 4096 * 5000;
size_t memSize = 8388608; //8 megs.
int granted = 0;
int rc;
rc = openDriver();
UT_CHECK(rc == SUCCESS);
rc = allocSharedMem(&grantedMem, memSize, getpid(), 0, GRANT);
UT_CHECK(rc == SUCCESS);
if(rc == SUCCESS)
{
granted = 1;
}
if(rc)
{
printf("Bailing.\n");
goto END;
}
UT_CHECK(grantedMem != NULL);
if(grantedMem)
{
snprintf(grantedMem, memSize - 1, "Hello granted memory");
UT_CHECK(strcmp(grantedMem, "Hello granted memory") == 0);
}
rc = freeSharedMemory(getpid(), 0);
UT_CHECK(rc == SUCCESS);
END:
return;
}
int
main(int arc, char **argv)
{
//test_openDriver();
//test_portListener();
//test_eventListener();
//test_sharePosixMem();
test_shareGrantMem();
test_serverPortListener();
while(getchar() != 'X')
{
sleep(1);
}
return 0;
}
|
C
|
#include "ejemplofcntl.h"
void estadoarchivo(int archides)
{
int arg1, mudo;
if((arg1=fcntl(archides,F_GETFL,mudo))==-1)
{
perror("\a estado archivo fallo\n");
exit(3);
}
printf("Descriptor de archivo %i:\n",archides);
if(arg1 & O_WRONLY)
{
printf("Solo para escritura\n");
}else if(arg1 & O_RDWR)
{
printf("lectura-escritura\n");
}else
{
printf("Solo para lectura\n");
}
if(arg1 & O_APPEND)
{
printf("Bandera de agregar encendida\n");
}
if(arg1 & O_CREAT)
{
printf("Bandera de crear encendida \n");
}
}
|
C
|
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <linux/i2c-dev.h>
#include <errno.h>
#include <linux/i2c.h>
#include <sys/types.h>
#include <sys/stat.h>
#define DEVICE "/dev/i2c-0"
#define DEVICE_I2C_ADDR 0x5d
#define REG GOODIX_REG_VERSION
#define GOODIX_READ_COOR_ADDR 0x814E
#define GOODIX_REG_CONFIG_DATA 0x8047
#define GOODIX_REG_VERSION 0x8140
int i2c_read(int fd, unsigned short reg, unsigned char *rbuf, int len){
//i2c读取数据需要发送2个i2c_msg,一个用于写入要读取的寄存器地址,另一个用于接收读取的数据
struct i2c_rdwr_ioctl_data i2c_data;
struct i2c_msg msgs[2];
int ret = 0;
i2c_data.nmsgs = 2;
i2c_data.msgs = msgs;
unsigned char tbuf[] = {
reg >> 8,
reg & 0xff,
};
msgs[0].flags = 0; //写标志
msgs[0].addr = DEVICE_I2C_ADDR; //i2c地址
msgs[0].len = 2; //装有寄存器地址的buf的长度,若是8位寄存器此处应为1
msgs[0].buf = tbuf; //寄存器地址
msgs[1].flags = I2C_M_RD; //读标志,实际值为0x1
msgs[1].addr = DEVICE_I2C_ADDR; //i2c地址
msgs[1].len = len; //读入的数据长度
msgs[1].buf = rbuf; //读入数据的存放地址
ret =ioctl(fd, I2C_RDWR, (unsigned long) &i2c_data); //驱动接口,际发送给驱动的数据结构是 i2c_data的指针
if (ret < 0){
perror("ioctl");
return ret;
}
return 0;
}
int i2c_write(int fd, unsigned char *tbuf, int len){
struct i2c_rdwr_ioctl_data i2c_data;
struct i2c_msg msgs;
int ret = 0;
i2c_data.nmsgs = 1;
i2c_data.msgs = &msgs;
msgs.flags = 0; //写标志
msgs.addr = DEVICE_I2C_ADDR; //设备i2c地址
msgs.len = len; //i2c发送数据包的字节数,也就是msgs.buf的大小
msgs.buf = tbuf; //i2c要发送的数据包
ret =ioctl(fd, I2C_RDWR, (unsigned long) &i2c_data); //驱动接口,实际发送给驱动的数据结构是 i2c_data的指针
if (ret < 0){
perror("ioctl");
return ret;
}
return 0;
}
int main (int argc, char **argv){
int fd = -1;
int ret = 0;
if ((fd = open(DEVICE,O_RDWR))< 0) {
/* 错误处理 */
perror("open");
return -1;
}
ioctl(fd, I2C_SLAVE, (unsigned long)DEVICE_I2C_ADDR); /*配置slave地址*/
ioctl(fd, I2C_TIMEOUT, 10); /*配置超时时间*/
ioctl(fd, I2C_RETRIES, 2); /*配置重试次数*/
//写入数据到指定寄存器
unsigned char tbuf[] = { //i2c要发送的数据,
REG >> 8, //第1或2字节是寄存器地址,16位寄存器使用2字节,8位寄存器使用1字节
REG & 0xff,
0x66, //要写入的数据
};
ret = i2c_write(fd, tbuf, sizeof(tbuf));
if (ret != 0)
printf("i2c_write failed\n");
printf("write data seccess, write to reg %hx, value = %#x \n", REG, tbuf[2]);
//从指定寄存器读取数据
unsigned char rbuf; //接收数据buf
ret =i2c_read(fd, REG, &rbuf, 1); //从REG中读取1字节数据,存放在rbuf中
if(ret< 0)
printf("read data failed\n");
else
printf("read data success, read from register %hx, value is %#x \n", REG, rbuf);
close(fd);
return 0;
}
|
C
|
/*************************************************************************
* All Rights yanbo Reserved *
*************************************************************************
*************************************************************************
* Filename : PrintTerminal.c
* Description : print info at the screen.
* Version : 1.0
* History : 2013-4-17 Created by yanbo
*************************************************************************/
#include <stdio.h>
#include <string.h>
#include <windows.h>
#include "PAT_Analysis.h"
#include "PMT_Analysis.h"
#include "SDT_Analysis.h"
#include "GetAllAnalysisResult.h"
/*************************************************************************
* Function Name : PrintTerminal
* Description : The display logic in the terminal.
* Parameters : puiLovePID -- the input service id.
* pstProgramInfo -- the program info.
* Returns : >0 - Success Length Value, -1 - Failure code.
**************************************************************************/
int PrintTerminal(PROGRAM_INFO *pstProgramInfo, unsigned int *puiLovePID)
{
int iIndex = 0;
system("color 1F");
system("cls");
printf("*******************当前TS流节目信息***************************\n");
printf(" 节目ID\t节目类型\tTV/Radio\t节目名称\n");
for (iIndex = 0; (0 != pstProgramInfo[iIndex].service_id); iIndex++)
{
if (0 == pstProgramInfo[iIndex].auiAvPID[0])
{
continue;
}
printf(" %4.4d\t", pstProgramInfo[iIndex].service_id);
if (pstProgramInfo[iIndex].free_CA_mode)
{
printf(" 加密\t\t");
}
else
{
printf(" 免费\t\t");
}
if ((0 == pstProgramInfo[iIndex].auiVideoPID[0]) && (0 != pstProgramInfo[iIndex].auiAudioPID[0]))
{
printf(" Radio\t\t");
}
else if ((0 != pstProgramInfo[iIndex].auiVideoPID[0]) && (0 != pstProgramInfo[iIndex].auiAudioPID[0]))
{
printf(" TV\t\t");
}
printf("%s\n", pstProgramInfo[iIndex].service_name);
}
printf("**************************************************************\n");
printf("请按节目单信息输入您喜好的节目ID(0:退出):");
scanf("%d", puiLovePID);
return 0;
}
/*************************************************************************
* Function Name : PrintTerminalEnd
* Description : The display logic in the terminal.
* Parameters : pcName -- the selected file name.
* Returns : void.
**************************************************************************/
void PrintTerminalEnd(char *pcName)
{
if (0 == strcmp(pcName,"\0"))
{
printf("您输入的ID不在当前列表!请重新输入ID!\n\n");
}
else
{
printf("桌面节目:%s 已保存文件成功!请查看!\n", pcName);
}
Sleep(1500);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_srch_figure.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: rpoetess <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/10/11 16:51:14 by rpoetess #+# #+# */
/* Updated: 2019/10/21 22:56:58 by rpoetess ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_filler.h"
void ft_crt_figure(t_figure *fig)
{
int index;
index = 0;
fig->figure = (char**)malloc(sizeof(char*) * (fig->figure_a));
while (index < fig->figure_a)
{
fig->figure[index] = (char*)malloc(sizeof(char) * (fig->figure_b));
index++;
}
}
void ft_srch_figure_size(t_figure *fig, char *line)
{
int j;
char *a;
char *b;
j = 6;
a = ft_strdup("");
b = ft_strdup("");
fig->figure_a = 0;
fig->figure_b = 0;
while (line[j] != ' ')
a = ft_strjoin_char(a, line[j++]);
j++;
while (line[j] != ':')
b = ft_strjoin_char(b, line[j++]);
fig->figure_a = ft_atoi(a);
fig->figure_b = ft_atoi(b);
ft_crt_figure(fig);
free(a);
free(b);
free(line);
}
void ft_srch_figure(t_figure *fig, char *line)
{
int i;
i = 0;
while (i < fig->figure_a)
{
ft_get_next_line(0, &line);
ft_strncpy(fig->figure[i], line, fig->figure_b);
i++;
free(line);
}
}
|
C
|
# include<stdio.h>
void rec(int *p);
void order(int *p);
int main()
{
int list[25];
int i = 0;
int *p = list;
printf("ÊäÈë¾ØÕóÖеÄÊý");
for (i; i < 25; i++)
{
scanf_s("%d", &list[i]);
}
order(p);
rec(p);
system("pause");
}
void rec(int *p)
{
int list[5][5];
int i, j;
list[0][0] = *(p);
list[0][4] = *(p + 1);
list[2][2] = *(p + 24);
list[4][0] = *(p + 2);
list[4][4] = *(p + 3);
for (i = 0; i < 5; i++)
{
for (j = 0; j < 5; j++)
{
if ((i == 0 && (j != 0 && j != 4)))
{
list[i][j] = *(p + 5 * i + j + 3);
}
else
{
if (i ==1)
list[i][j] = *(p + 5 * i + j + 2);
if (i == 2)
{
if (j == 2)
continue;
else
{
if (j < 2)
list[i][j] = *(p + 5 * i + j + 2);
else
list[i][j] = *(p + 5 * i + j + 1);
}
}
if (i == 3)
{
list[i][j] = *(p + 5 * i + j + 1);
}
if (i == 4)
{
if (j == 0 || j == 4)
continue;
else
list[i][j] = *(p + 5 * i + j);
}
}
}
}
for (i = 0; i < 5; i++)
{
for (j = 0; j < 5; j++)
{
printf("%3d", list[i][j]);
}
printf("\n");
}
}
void order(int *p)
{
int i, j, m;
for (i = 0; i < 25; i++)
{
for (j = 0; j < 24 - i; j++)
{
if (*(p + j)>*(p + j + 1))
{
m = *(p + j);
*(p + j) = *(p + j + 1);
*(p + j + 1) = m;
}
}
}
}
|
C
|
/*
** server.c -- a stream socket server demo
*/
#include "TCP.h"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h> //Header file for sleep(). man 3 sleep for details.
#include <pthread.h>
// A normal C function that is executed as a thread
// when its name is specified in pthread_create()
// void *myThreadFun(void *vargp)
// {
// sleep(1);
// printf("Printing GeeksQuiz from Thread \n");
// return NULL;
// }
// int main()
// {
// pthread_t thread_id;
// printf("Before Thread\n");
// pthread_create(&thread_id, NULL, myThreadFun, NULL);
// pthread_join(thread_id, NULL);
// printf("After Thread\n");
// exit(0);
// }
const uint8_t MASTER_GID = 12;
const uint32_t MAGIC_NUMBER = 0x4A6F7921;
char *portNumber;
struct Node *master;
struct sockaddr my_addr;
char *convertLongToIP(uint32_t num)
{
uint32_t toNetworkIP = htonl(num);
struct in_addr ip_addr;
ip_addr.s_addr = num;
char *ip = inet_ntoa(ip_addr);
return ip;
}
void sigchld_handler(int s)
{
// waitpid() might overwrite errno, so we save and restore it:
int saved_errno = errno;
while (waitpid(-1, NULL, WNOHANG) > 0)
;
errno = saved_errno;
}
int max(int x, int y)
{
if (x > y)
return x;
else
return y;
}
// get sockaddr, IPv4 or IPv6:
void *get_in_addr(struct sockaddr *sa)
{
if (sa->sa_family == AF_INET)
{
return &(((struct sockaddr_in *)sa)->sin_addr);
}
return &(((struct sockaddr_in6 *)sa)->sin6_addr);
}
/* Display the contents of the buffer */
void displayBuffer(char *Buffer, int length)
{
int currentByte, column;
currentByte = 0;
printf("\n>>>>>>>>>>>> Content in hexadecimal <<<<<<<<<<<\n");
while (currentByte < length)
{
printf("%3d: ", currentByte);
column = 0;
while ((currentByte < length) && (column < 10))
{
printf("%2x ", Buffer[currentByte]);
column++;
currentByte++;
}
printf("\n");
}
printf("\n\n");
}
// adds a slave node to the linked list ring. Master points to this new slave added.
void addSlaveNode(struct Node *master, struct Node *slave)
{
// so this is going to add a node directly after the master node.
slave->RID = master->nextRID;
slave->nextSlaveIP = master->next->IP;
slave->next = master->next;
master->nextSlaveIP = slave->IP;
master->next = slave;
master->nextRID += 1;
char *nextIP = convertLongToIP(master->nextSlaveIP);
printf("Next Slave IP: %s", nextIP);
}
uint8_t getChecksum(uint8_t *message, size_t len)
{
uint8_t sum = 0;
int i;
for (i = 1; i < len; i++)
{
uint8_t byte1 = message[i - 1];
uint8_t byte2 = message[i];
// sum the two bytes
sum = byte1 + byte2;
// if overflow occurs, add one to the sum
if (sum < byte1)
{
sum = sum + 1;
}
}
sum = ~sum;
return sum;
}
int getPortNumber(uint8_t rid)
{
return 10010 + (MASTER_GID % 30) * 5 + rid;
}
// this is a tcp connection that waits to receive messages from slaves
// and add the slave nodes to the node ring
void *addSlaveNodeThread(void *vargp)
{
int sockfd, new_fd, read_value;
struct addrinfo hints, *servinfo, *p;
struct sockaddr_storage their_addr; // connector's address information
socklen_t sin_size;
struct sigaction sa;
int yes = 1;
char s[INET6_ADDRSTRLEN];
int rv;
struct message_request request;
struct message_response response;
// TCP
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE; // use my IP
if ((rv = getaddrinfo(NULL, portNumber, &hints, &servinfo)) != 0)
{
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
return NULL;
}
// loop through all the results and bind to the first we can
for (p = servinfo; p != NULL; p = p->ai_next)
{
if ((sockfd = socket(p->ai_family, p->ai_socktype,
p->ai_protocol)) == -1)
{
perror("server: TCP socket");
continue;
}
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes,
sizeof(int)) == -1)
{
perror("setsockopt");
exit(1);
}
if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1)
{
close(sockfd);
perror("server: TCP bind");
continue;
}
break;
}
freeaddrinfo(servinfo); // all done with this structure
if (p == NULL)
{
fprintf(stderr, "server: failed to bind\n");
exit(1);
}
// printf("Wating to receive message from client...\n");
if (listen(sockfd, BACKLOG) == -1)
{
perror("listen");
exit(1);
}
printf("Waiting to receive message from client...\n");
sa.sa_handler = sigchld_handler; // reap all dead processes
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_RESTART;
if (sigaction(SIGCHLD, &sa, NULL) == -1)
{
perror("sigaction");
exit(1);
}
while (1)
{
new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size);
if (new_fd == -1)
{
perror("accept");
continue;
}
sin_size = sizeof their_addr;
inet_ntop(their_addr.ss_family,
get_in_addr((struct sockaddr *)&their_addr),
s, sizeof s);
printf("server: got connection from %s\n", s);
/* Listen for response from client */
read_value = recv(new_fd, &request, sizeof(request), 0);
if (read_value < 0)
{
perror("read from socket");
exit(1);
}
request.magic_number = ntohl(request.magic_number);
// message validation
if (sizeof(request) != 5)
{
perror("Size of message received is not 5 bytes");
}
if (request.magic_number != MAGIC_NUMBER)
{
perror("Magic number is not included");
}
struct Node *slave = malloc(sizeof(struct Node));
struct sockaddr_in *get_ip = (struct sockaddr_in *)&their_addr;
// memcpy(&master->nextSlaveIP, inet_ntoa(get_ip->sin_addr), 4);
slave->GID = request.gid;
slave->IP = get_ip->sin_addr.s_addr;
slave->nextRID = 0;
addSlaveNode(master, slave);
//response.gid = MASTER_GID;
response.gid = MASTER_GID;
response.magic_number = MAGIC_NUMBER;
response.nextRID = master->next->RID;
uint32_t nextSlaveIP = ntohl(slave->nextSlaveIP);
struct in_addr ip_addr;
ip_addr.s_addr = nextSlaveIP;
printf("--------------------------------------------------------\n");
printf("Message being sent:\n");
printf("GID of Master: %d\n", response.gid);
printf("Magic Number: %#04x\n", response.magic_number);
printf("RID: %d\n", response.nextRID);
printf("Next Slave IP: %s\n", inet_ntoa(ip_addr));
printf("Message being sent(hex): ");
printf("%#04x\\", response.gid);
printf("%#04x\\", response.magic_number);
printf("%#04x\\", response.nextRID);
printf("%#04x\\", nextSlaveIP);
printf("\n");
printf("--------------------------------------------------------\n");
response.nextSlaveIP = htonl(nextSlaveIP);
if (send(new_fd, &response, sizeof(response), 0) == -1)
{
perror("send");
exit(1);
}
//exit(0);
//}
// printf("Server: Response sent\n");
}
close(sockfd);
return NULL;
}
// UDP server that receives datagrams. If the datagram is for them, displays the datagram,
// if not, sends the datagram to the next Slave IP.
void *handleDatagramThread(void *vargp)
{
int sockfd, new_fd, read_value;
struct addrinfo hints, *servinfo, *p;
int rv;
int numbytes;
struct sockaddr_storage their_addr;
struct datagram_message *dgram;
socklen_t addr_len;
char s[INET6_ADDRSTRLEN];
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC; // set to AF_INET to force IPv4
hints.ai_socktype = SOCK_DGRAM; // datagram for UDP
hints.ai_flags = AI_PASSIVE; // use my IP
if ((rv = getaddrinfo(NULL, portNumber, &hints, &servinfo)) != 0)
{
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
return NULL;
}
// loop through all the results and bind to the first we can
for (p = servinfo; p != NULL; p = p->ai_next)
{
if ((sockfd = socket(p->ai_family, p->ai_socktype,
p->ai_protocol)) == -1)
{
perror("listener: socket");
continue;
}
if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1)
{
close(sockfd);
perror("listener: bind");
continue;
}
break;
}
if (p == NULL)
{
fprintf(stderr, "listener: failed to bind socket\n");
return NULL;
}
freeaddrinfo(servinfo);
while (1)
{
printf("listener: waiting to recvfrom...\n");
addr_len = sizeof their_addr;
if ((numbytes = recvfrom(sockfd, &dgram, sizeof(dgram), 0,
(struct sockaddr *)&their_addr, &addr_len)) == -1)
{
perror("recvfrom");
exit(1);
}
printf("listener: got packet from %s\n",
inet_ntop(their_addr.ss_family,
get_in_addr((struct sockaddr *)&their_addr),
s, sizeof s));
printf("listener: packet is %d bytes long\n", numbytes);
// first, check the checksum
// get datagram in bytes
size_t dgram_len = sizeof(dgram);
unsigned char dgram_in_bytes[dgram_len];
memcpy(dgram_in_bytes, &dgram, dgram_len);
uint8_t checksum = getChecksum(dgram_in_bytes, dgram_len - 1);
int isCorrupted = checksum != dgram->checksum ? 1 : 0;
// if not corrupted, proceed
if (isCorrupted == 0)
{
// if the message is for me, display the message
if (dgram->rid_dest == master->RID)
{
printf("Datagram message: %s", dgram->message);
}
else if (dgram->ttl == 0)
{
printf("Time to live expired, dropping datagram");
}
// otherwise, forward the message to the next slave ip
else
{
// update ttl
dgram->ttl -= 1;
// update checksum
memcpy(dgram_in_bytes, &dgram, dgram_len);
checksum = getChecksum(dgram_in_bytes, dgram_len - 1);
dgram->checksum = checksum;
int sockfd2, new_fd2, read_value2;
struct addrinfo hints2, *servinfo2, *p2;
int rv2;
int numbytes2;
int nextPortNumber = getPortNumber(master->nextRID);
uint32_t nextSlaveVal = htonl(master->nextSlaveIP);
struct in_addr ip_addr;
ip_addr.s_addr = nextSlaveVal;
char *ip = inet_ntoa(ip_addr);
char port[6];
sprintf(port, "%d", nextSlaveVal);
printf("\n The string for the num is %s", port);
// send the updated datagram
if ((rv2 = getaddrinfo(ip, port, &hints2, &servinfo2)) != 0)
{
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
return NULL;
}
// loop through all the results and bind to the first we can
for (p2 = servinfo2; p2 != NULL; p2 = p2->ai_next)
{
if ((sockfd2 = socket(p2->ai_family, p2->ai_socktype,
p2->ai_protocol)) == -1)
{
perror("listener: socket");
continue;
}
if (bind(sockfd2, p2->ai_addr, p2->ai_addrlen) == -1)
{
close(sockfd2);
perror("listener: bind");
continue;
}
break;
}
if (p2 == NULL)
{
fprintf(stderr, "listener: failed to bind socket\n");
return NULL;
}
freeaddrinfo(servinfo2);
printf("sending message...\n");
if ((numbytes2 = sendto(sockfd2, &dgram, sizeof(dgram), 0,
p2->ai_addr, p2->ai_addrlen)) == -1)
{
perror("talker: sendto");
exit(1);
}
close(sockfd2);
}
}
}
close(sockfd);
return NULL;
}
// sends a message to the node ring
void *sendMessageThread(void *vargp)
{
sleep(2);
int sockfd, new_fd, read_value;
struct addrinfo hints, *servinfo, *p;
int rv;
int numbytes;
struct sockaddr_storage their_addr;
struct datagram_message dgram;
socklen_t addr_len;
char s[INET6_ADDRSTRLEN];
unsigned char rid;
char message_to_send[64];
printf("\n");
// repeatedly prompt the user for input
while (1)
{
dgram.gid = MASTER_GID;
dgram.magic_number = MAGIC_NUMBER;
dgram.ttl = (uint8_t)255;
dgram.rid_src = master->RID;
printf("Please enter RID you want to send to: ");
scanf("%hhu", &rid);
printf("Please enter message you want to send: ");
scanf("%s", message_to_send);
dgram.rid_dest = rid;
dgram.message = message_to_send;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC; // set to AF_INET to force IPv4
hints.ai_socktype = SOCK_DGRAM; // datagram for UDP
hints.ai_flags = AI_PASSIVE; // use my IP
// uint32_t nextSlaveVal = htonl(master->nextSlaveIP);
// struct in_addr ip_addr;
// ip_addr.s_addr = nextSlaveVal;
char *ip = convertLongToIP(master->nextSlaveIP);
printf("Next IP %s\n", ip);
// memcpy(nextSlaveIP, (char *)&nextSlaveVal, sizeof(nextSlaveVal));
// if ((rv = getaddrinfo(ip, portNumber, &hints, &servinfo)) != 0)
// {
// fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
// return NULL;
// }
// // loop through all the results and bind to the first we can
// for (p = servinfo; p != NULL; p = p->ai_next)
// {
// if ((sockfd = socket(p->ai_family, p->ai_socktype,
// p->ai_protocol)) == -1)
// {
// perror("listener: socket");
// continue;
// }
// if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1)
// {
// close(sockfd);
// perror("listener: bind");
// continue;
// }
// break;
// }
// if (p == NULL)
// {
// fprintf(stderr, "listener: failed to bind socket\n");
// return NULL;
// }
// freeaddrinfo(servinfo);
// printf("sending message...\n");
// if ((numbytes = sendto(sockfd, &dgram, sizeof(dgram), 0,
// p->ai_addr, p->ai_addrlen)) == -1)
// {
// perror("talker: sendto");
// exit(1);
// }
// close(sockfd);
}
return NULL;
}
int main(int argc, char *argv[])
{
if (argc != 2)
{ //error entering in command line prompt: client servername
fprintf(stderr, "usage: server portNumber\n");
exit(1);
}
portNumber = argv[1];
struct addrinfo *addr_info;
char myName[1024];
myName[1023] = '\0';
//Added this information below
gethostname(myName, 1024);
//printf("hostname: %s\n", myName);
int return_value = getaddrinfo(myName, portNumber, NULL, &addr_info);
if (return_value != 0)
{
printf("addr_info is null");
printf("%d", return_value);
}
my_addr = *(addr_info->ai_addr);
unsigned long myIPAsInt = ((struct sockaddr_in *)&my_addr)->sin_addr.s_addr;
unsigned long next_slaveIP = myIPAsInt;
uint32_t next_slave_IP = ntohl(next_slaveIP);
// initializing the master node of the linked list.
master = malloc(sizeof(struct Node));
master->GID = MASTER_GID;
master->IP = next_slave_IP;
master->RID = 0;
master->nextRID = 1;
master->next = master;
master->nextSlaveIP = master->next->IP;
// you're going to create three seperate threads.
// 1. A TCP thread that adds slave nodes to the ring and sends back messages to the slave (Lab 2)
// 2. A UDP thread that receives datagrams and displays the message if its for it or forwards the datagram if not
// 3. A prompt that asks the user for a RID and a message m to send. This will be forwarded to the ring.
pthread_t addSlaveThreadID;
pthread_t handleDatagramID;
pthread_t sendMessageID;
pthread_create(&addSlaveThreadID, NULL, addSlaveNodeThread, NULL);
pthread_create(&handleDatagramID, NULL, handleDatagramThread, NULL);
pthread_create(&sendMessageID, NULL, sendMessageThread, NULL);
pthread_join(addSlaveThreadID, NULL);
pthread_join(handleDatagramID, NULL);
pthread_join(sendMessageID, NULL);
return 0;
}
|
C
|
/* Author: Ngoc Nguyen
* Partner(s) Name:
* Lab Section: 023
* Assignment: Lab 8 Exercise 1
* Exercise Description: [optional - include for your own benefit]
*
* I acknowledge all content contained herein, excluding template or example
* code, is my own original work.
* Demo link: https://youtu.be/ytGpVHrBGDw
*/
#include <avr/io.h>
#ifdef _SIMULATE_
#include "simAVRHeader.h"
#endif
enum States{ init, wait , C_note, E_note, D_note}state;
void set_PWM(double frequency){
static double current_frequency;
if(frequency != current_frequency){
if(!frequency){TCCR3B &= 0x08;}
else{TCCR3B |= 0x03;}
if(frequency < 0.954){OCR3A = 0xFFFF;}
else if(frequency > 31250){OCR3A &= 0x000;}
else{OCR3A = (short)( 8000000 / (128 * frequency)) - 1; }
TCNT3 = 0;
current_frequency = frequency;
}
}
void PWM_on(){
TCCR3A = (1<< COM3A0);
TCCR3B = (1<< WGM32)| (1<< CS31) | (1<<CS30);
set_PWM(0);
}
void PWM_off(){
TCCR3A = 0x00;
TCCR3B = 0x00;
}
void Tick(){
unsigned char button = ~PINA & 0x0F;
switch(state){
case init:
state = wait;
break;
case wait:
if(button == 0x01){ state = C_note; }
else if (button == 0x02){ state = D_note; }
else if (button == 0x04){ state = E_note; }
else { state = wait;}
break;
case C_note:
if(button == 0x01){ state = C_note; }
else{state = wait;}
break;
case D_note:
if(button == 0x02){ state = D_note; }
else{state = wait;}
break;
case E_note:
if(button == 0x04){ state = E_note; }
else{state = wait;}
break;
default:
state = init;
break;
}
switch(state){
case init:
break;
case wait:
set_PWM(0);
PORTB = 0x40;
break;
case C_note:
set_PWM(261.63);
PORTB = 0x41;
break;
case D_note:
set_PWM(293.66);
PORTB = 0x42;
break;
case E_note:
set_PWM(329.63);
PORTB = 0x44;
break;
default:
break;
}
}
int main(void) {
/* Insert DDR and PORT initializations */
DDRA = 0x00; PORTA = 0xFF;
DDRB = 0xFF; PORTB = 0x00;
/* Insert your solution below */
PWM_on();
while (1) {
Tick();
}
return 0;
}
|
C
|
#include <stdio.h>
#include <time.h>
int main()
{
int n, i, flag = 0;
clock_t start, end;
double total_cputime;
start = clock();
printf("Enter a positive integer: ");
scanf("%d", &n);
for (i = 2; i <= n / 2; ++i)
{
if (n % i == 0)
{
flag = 1;
break;
}
}
if (n == 1)
{
printf("1 is neither prime nor composite.");
}
else
{
if (flag == 0)
printf("%d is a prime number.", n);
else
printf("%d is not a prime number.", n);
}
end = clock();
printf("\nstarting time=%ld", start);
printf("\nEnd time =%ld", end);
total_cputime = ((double)(end - start));
printf("\ntotal_cputime =%f", total_cputime);
total_cputime = ((double)(end - start)) / CLOCKS_PER_SEC;
printf("\ntotal_cputime in second =%f", total_cputime);
return 0;
}
|
C
|
#include "client.h"
/*
* Commands functions
*/
int cmd_inventory(struct command_s *cmd, int argc, char *argv[])
{
int i;
CAENRFIDTag *tag;
int size;
char *str;
int ret;
PDEBUG("%s", __func__);
/* Check command line */
if (argc < 3) {
PERR("%s %s", cmd->name, cmd->usage);
return -1;
}
PDEBUG("%s: %s %s %s", __func__, argv[0], argv[1], argv[2]);
if (sscanf(argv[1], "%d", &i) != 1) {
PERR("invalid <id>");
return -1;
}
ret = CAENRFID_InventoryTag(&handle, argv[2], &tag, &size);
if (ret != CAENRFID_StatusOK) {
PERR("cannot get data (err=%d)", ret);
exit(-1);
}
PDATA("size=%d", size);
for (i = 0; i < size; i++) {
str = bin2hex(tag[i].ID, tag[i].Length);
if (!str) {
PERR("cannot allocate memory");
exit(-1);
}
PDATA("epc=%.*s src=%.*s rp=%.*s type=%d rssi=%d",
tag[i].Length * 2, str,
MAX_LOGICAL_SOURCE_NAME, tag[i].LogicalSource,
MAX_READPOINT_NAME, tag[i].ReadPoint,
tag[i].Type, tag[i].RSSI);
free(str);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <limits.h>
#include <stdbool.h>
bool isPalindrome2(int x) {
int s = 0, y;
if (x<0)
return 0;
y = abs(x);
x = y;
while (x != 0)
{
s = s * 10 + x % 10;
x = x / 10;
}
return s == y;
}
bool isPalindrome(int x) {
if (x < 0)
return false;
if (x < 10)
return true;
int n1 = x, n2;
int k = 0;
int i = 0;
int v1 = 0, v2 = 0;
while (n1 > 0)
{
n1 /= 10;
k++;
}
for (i = 0, n1 = x, n2 = x; i < k; i++)
{
v2 = n2 / pow(10, k - i - 1);
n2 = n2 % (int)pow(10, k - i - 1);
v1 = n1 % 10;
n1 = n1 / 10;
if (v1 != v2)
return false;
if (n1 == n2)
break;
}
return true;
}
int main()
{
bool d = isPalindrome(1231);
printf("%d\n", d);
getchar();
return 0;
}
|
C
|
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <sys/wait.h>
#include <string.h>
int main()
{
int n,status; //Creamos la variable que almacena el número de hijos y la que almacena el estado de salida del hijo
pid_t pid, childpid; //Estas variables almacenan el id de los procesos hijos.
//Pid almacena el valor devuelto al padre tras el fork y chilpid el valor devuelto al padre por la función wait cuando termina de esperar al hijo
printf("Introduzca el número de procesos hijo que desea generar: ");
scanf("%d", &n); //Recogemos la entrada
getchar(); //Para vaciar el buffer
printf("Soy %d el padre de todos\n", getpid()); //El proceso padre imprime su id
for (int i = 0; i < n; i++) //Cuando hacemos el fork la variable i es distinta en cada caso
{//Se crean bucles diferentes e independientes
pid = fork(); // Aqúi el proceso tiene su hijo. En el padre pid valdrá el id del hijo y en el hijo pid valdrá 0
switch(pid) //En base al valor de pid cada proceso ejecutará una función
{
case 0: //El fork se ha realizado corractamente
printf("Soy %d el hijo nº %d del proceso: %d\n", getpid(), (i+1), getppid()); //El hijo se identifica
exit(EXIT_SUCCESS); //El hijo muere
case -1: //Ha ocurrido un error al realizar el fork
printf("Error al crear el proceso hijo\n"); //Se informa al usuario
exit(EXIT_FAILURE); //Indica que ha ocurrido un fallo en la ejecución
default:
printf("Esperando a que acabe mi hijo nº %d\n", i+1);
}//Como el padre no ha hecho exit continua con el for y crea otro hijo
}//Una vez el padre ha terminado de crear los hijos que le hemos solicitado empieza a esperarlos
while ( (childpid=waitpid(-1, &status, WUNTRACED | WCONTINUED)) > 0 )//Si lo hacemos así en vez de con wait podemos saber si el proceso ha sido pausado y poniendo -1 en el primer parametro de waitpid esperamos a cualquier hijo
{//Este bucle se repetirá mientas haya hijos que esperar cuando no haya mas wait devolverá -1
if (WIFEXITED(status))
{//Entrará en el caso de que el hijo haya finaizado correctamente ya que WIFEXITED(status) devolverá true
printf("Proceso padre %d, hijo con PID %ld finalizado, status = %d\n", getpid(), (long int)childpid, WEXITSTATUS(status));
}
else if (WIFSIGNALED(status))
{//Entrará en el caso de que el proceso haya finalizado debido a una señar externa ya sea de finalizar o matar
printf("Proceso padre %d, hijo con PID %ld finalizado al recibir la señal %d\n", getpid(), (long int)childpid, WTERMSIG(status));
}//La macro WTERMSIG nos dice que señal ha sido la que ha recibido el proceso que ha producido que acabe
}
if (childpid==(pid_t)-1 && errno==ECHILD)
{//Entra cuando vuelve al while y no hay más hijos que esperar porque en ese caso chilpid valdrá -1 y erno 10 que es el valor que devuelce ECHILD cuando no hay mas procesos hijo
printf("Proceso padre %d, no hay mas hijos que esperar. Valor de errno = %d, definido como: %s\n", getpid(), errno, strerror(errno));
} //strerror devuelve una cadena de caracteres que nos permite identificar el valor de la variable errno
else
{//Solo entra si se ha producido un error con wait
printf("Error en la invocacion de wait o waitpid. Valor de errno = %d, definido como: %s\n", errno, strerror(errno));
exit(EXIT_FAILURE); //Acaba el proceso padre con error
}
exit(EXIT_SUCCESS); //Como todo ha ido bien el proceso padre acaba exitosamente
}
|
C
|
/* P-wave Amplitude Elliptical Fitting
* Authors: Jiashun Yu, Xiaobo Fu, Xinran Fan, Jianlong Yuan, Chao Han
* College of Geophysics, Chengdu University of Technology
* Contact us,E-mail:[email protected]
* 10/10/2014
*
* File: swapbs.c
* Version: 1.0.0
* */
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
/* Swap bytes function */
void swapbs(char *buf, short size){
char tmp;
switch (size){
case 2:
tmp=buf[0]; buf[0]=buf[1]; buf[1]=tmp;
break;
case 4:
tmp=buf[0]; buf[0]=buf[3]; buf[3]=tmp;
tmp=buf[1]; buf[1]=buf[2]; buf[2]=tmp;
break;
case 8:
tmp=buf[0]; buf[0]=buf[7]; buf[7]=tmp;
tmp=buf[1]; buf[1]=buf[6]; buf[6]=tmp;
tmp=buf[2]; buf[2]=buf[5]; buf[5]=tmp;
tmp=buf[3]; buf[3]=buf[4]; buf[4]=tmp;
break;
default:
break;
}
}
void swap_short_2(short *tni2)
/**************************************************************************
* swap_short_2 swap a short integer
* ***************************************************************************/
{
*tni2=(((*tni2>>8)&0xff) | ((*tni2&0xff)<<8));
}
void swap_u_short_2(unsigned short *tni2)
/**************************************************************************
* swap_u_short_2 swap an unsigned short integer
* ***************************************************************************/
{
*tni2=(((*tni2>>8)&0xff) | ((*tni2&0xff)<<8));
}
void swap_int_4(int *tni4)
/**************************************************************************
* swap_int_4 swap a 4 byte integer
* ***************************************************************************/
{
*tni4=(((*tni4>>24)&0xff) | ((*tni4&0xff)<<24) |
((*tni4>>8)&0xff00) | ((*tni4&0xff00)<<8));
}
void swap_u_int_4(unsigned int *tni4)
/**************************************************************************
* swap_u_int_4 swap an unsigned integer
* ***************************************************************************/
{
*tni4=(((*tni4>>24)&0xff) | ((*tni4&0xff)<<24) |
((*tni4>>8)&0xff00) | ((*tni4&0xff00)<<8));
}
void swap_long_4(long *tni4)
/**************************************************************************
* swap_long_4 swap a long integer
* ***************************************************************************/
{
*tni4=(((*tni4>>24)&0xff) | ((*tni4&0xff)<<24) |
((*tni4>>8)&0xff00) | ((*tni4&0xff00)<<8));
}
void swap_u_long_4(unsigned long *tni4)
/**************************************************************************
* swap_u_long_4 swap an unsigned long integer
* ***************************************************************************/
{
*tni4=(((*tni4>>24)&0xff) | ((*tni4&0xff)<<24) |
((*tni4>>8)&0xff00) | ((*tni4&0xff00)<<8));
}
void swap_float_4(float *tnf4)
/**************************************************************************
* swap_float_4 swap a float
* ***************************************************************************/
{
int *tni4=(int *)tnf4;
*tni4=(((*tni4>>24)&0xff) | ((*tni4&0xff)<<24) |
((*tni4>>8)&0xff00) | ((*tni4&0xff00)<<8));
}
void swap_double_8(double *tndd8)
/**************************************************************************
* swap_double_8 swap a double
* ***************************************************************************/
{
char *tnd8=(char *)tndd8;
char tnc;
tnc= *tnd8;
*tnd8= *(tnd8+7);
*(tnd8+7)=tnc;
tnc= *(tnd8+1);
*(tnd8+1)= *(tnd8+6);
*(tnd8+6)=tnc;
tnc= *(tnd8+2);
*(tnd8+2)= *(tnd8+5);
*(tnd8+5)=tnc;
tnc= *(tnd8+3);
*(tnd8+3)= *(tnd8+4);
*(tnd8+4)=tnc;
}
|
C
|
#include <stdio.h>
int main(int argc, char const *rgv[])
{
int inputFirst,inputSec;
printf("请输入两个整数\n");
printf("第一个整数\n");
scanf("%d",&inputFirst);
printf("第二个整数\n");
scanf("%d",&inputSec);
printf("这两个数的平均值是%.1f\n",((double)(inputFirst+inputSec))/2);
}
|
C
|
#include <stdio.h>
int main(void)
{
double mass_mol = 3.0e-23;
double mass_qt = 950;
double water_qt;
printf("Enter the quarts of water: ");
scanf("%lf", &water_qt);
printf("The %lf water has %e mol of molecules\n", water_qt, water_qt * mass_qt / mass_mol);
return 0;
}
|
C
|
#include "register.h"
// Function name : GetRegisterRes()
// Input : 用户注册信息是否发送成功
// Output : 从服务器返回的注册结果信息
// Description : 获取从服务返回的注册结果信息
char *GetRegisterRes(int post_res){
char res[100];
if(post_res<0){
println("%s\n","向服务器POST发送信息失败");
exit(0);
}
return res;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#define N 100
typedef struct
{
int key;
char *value;
} symbol;
static int count = 0;
static symbol *st[N];
void put(int key, char *value);
void delete(int key);
char* get(int key);
int contains(int key);
int is_empty();
int size();
void print();
int main()
{
put(1, "a");
put(2, "b");
put(3, "c");
delete(1);
printf("%s\n", get(2));
print();
}
int is_empty()
{
return count == 0;
}
int size()
{
return count;
}
void delete(int key)
{
for(int i = 0; i < count; i++)
{
if(st[i]->key == key)
{
free(st[i]);
st[i] = st[--count];
}
}
}
char* get(int key)
{
for(int i = 0; i < count; i++)
if(st[i]->key == key)
return st[i]->value;
return NULL;
}
void put(int key, char *value)
{
for(int i = 0; i < count; i++)
{
if(st[i]->key == key)
{
st[i]->value = value;
return;
}
}
symbol *s = malloc(sizeof(symbol));
s->key = key;
s->value = value;
st[count++] = s;
}
int contains(int key)
{
for(int i = 0; i < count; i++)
if(st[i]->key == key)
return 1;
return 0;
}
void print()
{
for(int i = 0; i < count; i++)
printf("key: %d, value: %s\n", st[i]->key, st[i]->value);
}
|
C
|
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <string.h>
void skipPipe(int* cmdIndex, bool* pipeIndxs)
{
while (pipeIndxs[(*cmdIndex)])
(*cmdIndex)++;
(*cmdIndex)++; //the last cmd in pipe is with false pipeIndx
}
void unmake(bool arr[], int n)
{
int i;
for (i = 0; i < n; i++)
arr[i] = false;
}
void printArgsToExec(char** args, int j)
{
int i = 0;
for (i; i <= j; i++)
printf("args[%d]: %s|\n", i, args[i]);
}
void removeLeadingTabsSpacesNewlines(char buff[3200], int* buffIndex, int n)
{
char c;
while ((*buffIndex) < n && (c = buff[(*buffIndex)]) && (c == ' ' || c == '\t' || c == '\n'))
(*buffIndex)++;
}
void getNextArg(char buff[3200], int* buffIndex, int n, char* arg, int* argsIndex, bool* backgroundMode, bool* isPipe, bool* toOpen)
//always returns arg. If none meaningful argument, empty argument is returned (starting with '\0')
{
char c = 0;
int k = 0;
while ((*buffIndex) < n &&
(c = buff[(*buffIndex)]) &&
(c != ' ' && c != '\t' && c != '\n' && c!=';') &&
k < 31)
{
switch (c)
{
case '&':
(*backgroundMode) = true;
break;
case '|':
(*isPipe) = true;
break;
case '<':
close(0);
(*toOpen) = true;
(*buffIndex)++;
removeLeadingTabsSpacesNewlines(buff, buffIndex, n);
getNextArg(buff, buffIndex, n, arg, argsIndex, backgroundMode, isPipe, toOpen);
open(arg, O_RDONLY);
return;
case '>':
close(1);
(*toOpen) = true;
(*buffIndex)++;
removeLeadingTabsSpacesNewlines(buff, buffIndex, n);
getNextArg(buff, buffIndex, n, arg, argsIndex, backgroundMode, isPipe, toOpen);
open(arg, O_WRONLY | O_CREAT | O_TRUNC, 0744);
return;
}
if (c == '&' || c == '|')
{
(*buffIndex)++;
break;
}
arg[k] = c;
(*buffIndex)++;
k++;
}
arg[k] = 0;
//printf("\narg = %s\n", arg);
(*argsIndex)++;
}
void readCmds(char*** cmdsToExec, bool backgroundIndxs[], bool pipeIndxs[])
//up to 9 cmds with up to 9 args each cmd with up to 31 chars each arg
{
char** argsToExec = malloc(10 * sizeof(char*));
//will be given to execvp
//will point to some of the meaningful args elements
//and the one after the last meaningful points NULL
char* arg = malloc(32 * sizeof(char*)); //single argument
char buff[3200], argFirstChar;
bool toOpen = false;
int n, buffIndex, argsIndex, cmdIndex;
n = read(0, buff, 3200);
buffIndex = 0;
argsIndex = 0;
cmdIndex = 0;
while (buffIndex < n && cmdIndex < 9)
{
while (buffIndex < n && buff[buffIndex] != ';' && argsIndex < 9)
{
removeLeadingTabsSpacesNewlines(buff, &buffIndex, n);
if (buffIndex < n)
{
getNextArg(buff, &buffIndex, n, arg, &argsIndex, &(backgroundIndxs[cmdIndex]), &(pipeIndxs[cmdIndex]), &toOpen);
argFirstChar = arg[0];
if (toOpen)
{
toOpen = false;
argsIndex--;
}
else if (pipeIndxs[cmdIndex])
{
argsIndex--;
break;
}
else if (argFirstChar != 0) //if the given argument is not empty
{
argsToExec[argsIndex - 1] = arg; //argsIndex was incremented in getNextArg
arg = malloc(32 * sizeof(char));
}
else // if the given arg is empty
{
argsIndex--;
}
}
}
if (argsIndex != 0)
{
argsToExec[argsIndex] = NULL;
cmdsToExec[cmdIndex] = argsToExec;
/*
printArgsToExec(argsToExec, argsIndex);
write(1, "\n", 1);
*/
argsToExec = malloc(10 * sizeof(char*));
argsIndex = 0;
cmdIndex++;
}
buffIndex++;
}
cmdsToExec[cmdIndex] = NULL;
free(argsToExec);
free(arg);
}
void executeCmd(bool backgroundMode, char** cmd)
{
int pidChild, pidGrandChild, status;
if (backgroundMode)
{
if (pidChild = fork())
{//parent
waitpid(pidChild, &status, 0);
}
else
{//child
if (pidGrandChild = fork())
{//child
printf("PID: %d\n", pidGrandChild);
exit(0);
}
else
{//grandchild
execvp(cmd[0], cmd);
exit(-1);
}
}
}
else
{
if (pidChild = fork())
{//parent
waitpid(pidChild, &status, 0);
if (WIFSIGNALED(status))
{
write(1, "Wrong command\n", 15);
}
}
else
{//child
execvp(cmd[0], cmd);
abort();
}
}
}
void executePipeCmds(char*** cmdsToExec, int cmdIndex, bool* pipeIndxs)
{
int pd[2];
int pid, status;
pipe(pd);
if (pid = fork())
{//parent
close(0);
dup(pd[0]);
close(pd[0]);
close(pd[1]);
waitpid(pid, &status, 0);
if (cmdIndex < 7 && pipeIndxs[cmdIndex + 1])
{
executePipeCmds(cmdsToExec, cmdIndex + 1, pipeIndxs);
}
else
{
execvp(cmdsToExec[cmdIndex + 1][0], cmdsToExec[cmdIndex + 1]);
}
exit(-1);
}
else
{//child
close(1);
dup(pd[1]);
close(pd[0]);
close(pd[1]);
execvp(cmdsToExec[cmdIndex][0], cmdsToExec[cmdIndex]);
exit(-1);
}
}
int main()
{
bool close = false;
int cmdIndex, pid, status, i, j;
char*** cmdsToExec = malloc(10 * sizeof(char**));
//max 9 comands on input separated by ; (last cmdsToExec is NULL)
bool backgroundIndxs[9];
bool pipeIndxs[8]; //pipes can be max of 8 for 9 cmds
int stdIn = 0;
int stdOut = 1;
stdIn = dup(0);
stdOut = dup(1);
while (!close)
{
unmake(backgroundIndxs, 9);
unmake(pipeIndxs, 8);
write(1, "myShell> ", 9);
readCmds(cmdsToExec, backgroundIndxs, pipeIndxs);
cmdIndex = 0;
while (cmdsToExec[cmdIndex] != NULL)
{
if (cmdsToExec[cmdIndex][0] && strcmp(cmdsToExec[cmdIndex][0], "exit") == 0)
{
close = true;
cmdIndex++;
}
else
{
if (cmdIndex < 8 && pipeIndxs[cmdIndex])
{
if ((pid = fork()) == 0)
{//child
executePipeCmds(cmdsToExec, cmdIndex, pipeIndxs);
exit(-1);
}
waitpid(pid, &status, 0);
if (!WIFEXITED(status))
{
write(1, "Wrong command\n", 15);
}
skipPipe(&cmdIndex, pipeIndxs);
}
else
{
executeCmd(backgroundIndxs[cmdIndex], cmdsToExec[cmdIndex]);
cmdIndex++;
}
}
}
dup2(stdIn, 0);
dup2(stdOut, 1);
}
//free allocated memory
i = 0;
j = 0;
while (cmdsToExec[i] != NULL)
{
while (cmdsToExec[i][j] != NULL)
{
free(cmdsToExec[i][j]);
j++;
}
free(cmdsToExec[i]);
i++;
}
free(cmdsToExec);
return 0;
}
|
C
|
#include <stdio.h>
float main(void)
{
int a,b;
printf("a,b="); scanf("%d%d",&a,&b);
printf("%f",1.0*a/b);
return 0;
}
|
C
|
#include<stdio.h>
#include<string.h>
#include<math.h>
int main()
{
int n,a[100001]={0},k,jishu=0;
int i,scan;
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&scan);
a[scan]++;
}
scanf("%d",&k);
for(i=100000;i>0;i--)
{
if(a[i]!=0)
jishu++;
if(jishu==k)
break;
}
printf("%d %d",i,a[i]);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <math.h>
#include "util/xiwilib.h"
#include "util/jsmnenv.h"
#include "util/hashmap.h"
#include "common.h"
#include "category.h"
#include "layout.h"
typedef struct _json_data_t {
int num_papers;
paper_t *papers;
hashmap_t *keyword_set;
category_set_t *category_set;
} json_data_t;
static void json_data_setup(json_data_t* data) {
data->num_papers = 0;
data->papers = NULL;
data->keyword_set = hashmap_new();
data->category_set = NULL;
}
static int paper_cmp_id(const void *in1, const void *in2) {
paper_t *p1 = (paper_t *)in1;
paper_t *p2 = (paper_t *)in2;
if (p1->id < p2->id) {
return -1;
} else if (p1->id > p2->id) {
return 1;
} else {
return 0;
}
}
static bool load_categories(jsmn_env_t *env, json_data_t *data) {
printf("reading categories from JSON file\n");
// start the JSON stream
bool more_objects = false;
if (!jsmn_env_next_object(env, &more_objects)) {
return false;
}
if (more_objects) {
return false;
}
// look for member: cats
jsmntok_t *cats_tok;
if (!jsmn_env_get_object_member_token(env, env->js_tok, "cats", JSMN_ARRAY, &cats_tok)) {
return false;
}
// iterate through the list of cats
int n_cats;
for (n_cats = 0; n_cats < cats_tok->size; ++n_cats) {
jsmntok_t *cat_tok;
if (!jsmn_env_get_array_member(env, cats_tok, n_cats, &cat_tok, NULL)) {
return false;
}
// look for the cat member
jsmn_env_token_value_t cat_val;
if (!jsmn_env_get_object_member_value(env, cat_tok, "cat", JSMN_VALUE_STRING, &cat_val)) {
return false;
}
// look for the col member
jsmntok_t *col_tok;
if (!jsmn_env_get_object_member_token(env, cat_tok, "col", JSMN_ARRAY, &col_tok)) {
return false;
}
// check the col is an array of length 3
if (col_tok->size != 3) {
return jsmn_env_error(env,"expecting an array of size 3");
}
// parse the r,g,b values
float rgb[3];
for (int i = 0; i < 3; i++) {
// get current element
jsmn_env_token_value_t elem_val;
if (!jsmn_env_get_array_member(env, col_tok, i, NULL, &elem_val)) {
return false;
}
// check the element is a number
if (elem_val.kind == JSMN_VALUE_UINT) {
rgb[i] = elem_val.uint;
} else if (elem_val.kind == JSMN_VALUE_REAL) {
rgb[i] = elem_val.real;
} else {
return jsmn_env_error(env,"expecting a number");
}
}
// add the new category to the set
if(!category_set_add_category(data->category_set, cat_val.str, strlen(cat_val.str), rgb)) {
exit(1);
}
}
printf("read %d categories\n", n_cats);
return true;
}
static bool load_idc(jsmn_env_t *env, json_data_t *data) {
printf("reading ids from JSON file\n");
// get the number of entries, so we can allocate the correct amount of memory
int num_entries;
if (!jsmn_env_get_num_entries(env, &num_entries)) {
return false;
}
// allocate memory for the papers
data->papers = m_new(paper_t, num_entries);
if (data->papers == NULL) {
return false;
}
// start the JSON stream
bool more_objects = false;
if (!jsmn_env_reset(env, &more_objects)) {
return false;
}
// iterate through the JSON stream
int i = 0;
while (more_objects) {
if (!jsmn_env_next_object(env, &more_objects)) {
return false;
}
if (i >= num_entries) {
return jsmn_env_error(env, "got more entries than expected");
}
// look for the id member
jsmn_env_token_value_t id_val;
if (!jsmn_env_get_object_member(env, env->js_tok, "id", NULL, &id_val)) {
return false;
}
// check the id is an integer
if (id_val.kind != JSMN_VALUE_UINT) {
return jsmn_env_error(env, "expecting an unsigned integer for id");
}
// create the paper object, with the id
paper_t *paper = &data->papers[i];
paper_init(paper, id_val.uint);
// look for the allcats member
jsmn_env_token_value_t allcats_val;
if (!jsmn_env_get_object_member(env, env->js_tok, "allcats", NULL, &allcats_val)) {
return false;
}
// check allcats is a string
if (allcats_val.kind != JSMN_VALUE_STRING) {
return jsmn_env_error(env, "expecting a string for allcats");
}
// parse categories
int cat_num = 0;
for (const char *start = allcats_val.str, *cur = allcats_val.str; cat_num < COMMON_PAPER_MAX_CATS; cur++) {
if (*cur == ',' || *cur == '\0') {
category_info_t *cat = category_set_get_by_name(data->category_set, start, cur - start);
if (cat == NULL) {
// print unknown categories; for adding to input JSON file
printf("unknown category: %.*s\n", (int)(cur - start), start);
} else {
if (cat->cat_id > 255) {
// we use a byte to store the cat id, so it must be small enough
printf("error: too many categories to store as a byte\n");
exit(1);
}
paper->allcats[cat_num++] = cat->cat_id;
}
if (*cur == '\0') {
break;
}
start = cur + 1;
}
}
// fill in unused entries in allcats with UNKNOWN category
for (; cat_num < COMMON_PAPER_MAX_CATS; cat_num++) {
paper->allcats[cat_num] = CATEGORY_UNKNOWN_ID;
}
/*
// load authors and title if wanted
if (load_authors_and_titles) {
paper->authors = strdup(row[2]);
paper->title = strdup(row[3]);
}
*/
i += 1;
}
data->num_papers = i;
// sort the papers array by id
qsort(data->papers, data->num_papers, sizeof(paper_t), paper_cmp_id);
// assign the index based on their sorted position
for (int i = 0; i < data->num_papers; i++) {
data->papers[i].index = i;
}
printf("read %d ids\n", data->num_papers);
return true;
}
static paper_t *get_paper_by_id(jsmn_env_t *env, json_data_t *data, unsigned int id) {
int lo = 0;
int hi = data->num_papers - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (id == data->papers[mid].id) {
return &data->papers[mid];
} else if (id < data->papers[mid].id) {
hi = mid - 1;
} else {
lo = mid + 1;
}
}
return NULL;
}
static bool load_refs(jsmn_env_t *env, json_data_t *data) {
printf("reading refs from JSON file\n");
// start the JSON stream
bool more_objects = false;
if (!jsmn_env_reset(env, &more_objects)) {
return false;
}
// iterate through the JSON stream
int total_refs = 0;
while (more_objects) {
if (!jsmn_env_next_object(env, &more_objects)) {
return false;
}
// look for the id member
jsmn_env_token_value_t id_val;
if (!jsmn_env_get_object_member(env, env->js_tok, "id", NULL, &id_val)) {
return false;
}
// check the id is an integer
if (id_val.kind != JSMN_VALUE_UINT) {
return jsmn_env_error(env, "expecting an unsigned integer");
}
// lookup the paper object with this id
paper_t *paper = get_paper_by_id(env, data, id_val.uint);
// if paper found, parse its refs
if (paper != NULL) {
// look for the refs member
jsmntok_t *refs_tok;
if (!jsmn_env_get_object_member(env, env->js_tok, "refs", &refs_tok, NULL)) {
return false;
}
// check the refs is an array
if (refs_tok->type != JSMN_ARRAY) {
return jsmn_env_error(env, "expecting an array");
}
// set the number of refs
paper->num_refs = refs_tok->size;
if (paper->num_refs == 0) {
// no refs to parse
paper->refs = NULL;
paper->refs_ref_freq = NULL;
} else {
// some refs to parse
// allocate memory
paper->refs = m_new(paper_t*, paper->num_refs);
paper->refs_ref_freq = m_new(byte, paper->num_refs);
if (paper->refs == NULL || paper->refs_ref_freq == NULL) {
return false;
}
// parse the refs
paper->num_refs = 0;
for (int i = 0; i < refs_tok->size; i++) {
// get current element
jsmntok_t *elem_tok;
if (!jsmn_env_get_array_member(env, refs_tok, i, &elem_tok, NULL)) {
return false;
}
// check the element is an array of size 2
if (elem_tok->type != JSMN_ARRAY || elem_tok->size != 2) {
return jsmn_env_error(env, "expecting an array of size 2");
}
// get the 2 values
jsmn_env_token_value_t ref_id_val;
jsmn_env_token_value_t ref_freq_val;
if (!jsmn_env_get_array_member(env, elem_tok, 0, NULL, &ref_id_val)) {
return false;
}
if (!jsmn_env_get_array_member(env, elem_tok, 1, NULL, &ref_freq_val)) {
return false;
}
if (ref_id_val.kind != JSMN_VALUE_UINT) {
return jsmn_env_error(env, "expecting an unsigned integer for ref_id");
}
if (ref_freq_val.kind != JSMN_VALUE_UINT) {
return jsmn_env_error(env, "expecting an unsigned integer for ref_freq");
}
if (ref_id_val.uint == paper->id) {
// make sure paper doesn't ref itself (yes, they exist, see eg 1202.2631)
continue;
}
paper->refs[paper->num_refs] = get_paper_by_id(env, data, ref_id_val.uint);
if (paper->refs[paper->num_refs] != NULL) {
paper->refs[paper->num_refs]->num_cites += 1;
unsigned short ref_freq = ref_freq_val.uint;
if (ref_freq > 255) {
ref_freq = 255;
}
paper->refs_ref_freq[paper->num_refs] = ref_freq;
paper->num_refs++;
}
}
total_refs += paper->num_refs;
}
}
}
printf("read %d total refs\n", total_refs);
return true;
}
#if 0
static bool env_load_keywords(jsmn_env_t *env) {
MYSQL_RES *result;
MYSQL_ROW row;
unsigned long *lens;
printf("reading keywords\n");
// get the keywords from the db
vstr_t *vstr = env->vstr[VSTR_0];
vstr_reset(vstr);
vstr_printf(vstr, "SELECT id,keywords FROM meta_data");
if (vstr_had_error(vstr)) {
return false;
}
if (!env_query_many_rows(env, vstr_str(vstr), 2, &result)) {
return false;
}
int total_keywords = 0;
while ((row = mysql_fetch_row(result))) {
lens = mysql_fetch_lengths(result);
paper_t *paper = get_paper_by_id(env, data, atoll(row[0]));
if (paper != NULL) {
unsigned long len = lens[1];
if (len == 0) {
paper->num_keywords = 0;
paper->keywords = NULL;
} else {
const char *kws_start = row[1];
const char *kws_end = row[1] + len;
// count number of keywords
int num_keywords = 1;
for (const char *kw = kws_start; kw < kws_end; kw++) {
if (*kw == ',') {
num_keywords += 1;
}
}
// limit number of keywords per paper
if (num_keywords > 5) {
num_keywords = 5;
}
// allocate memory
paper->keywords = m_new(keyword_t*, num_keywords);
if (paper->keywords == NULL) {
mysql_free_result(result);
return false;
}
// populate keyword list for this paper
paper->num_keywords = 0;
for (const char *kw = kws_start; kw < kws_end && num_keywords > 0; num_keywords--) {
const char *kw_end = kw;
while (kw_end < kws_end && *kw_end != ',') {
kw_end++;
}
keyword_t *unique_keyword = keyword_set_lookup_or_insert(env->keyword_set, kw, kw_end - kw);
if (unique_keyword != NULL) {
paper->keywords[paper->num_keywords++] = unique_keyword;
}
kw = kw_end;
if (kw < kws_end) {
kw += 1; // skip comma
}
}
total_keywords += paper->num_keywords;
}
}
}
mysql_free_result(result);
printf("read %d unique, %d total keywords\n", keyword_set_get_total(env->keyword_set), total_keywords);
return true;
}
#endif
bool json_load_categories(const char *filename, category_set_t **category_set_out) {
// set up environment
jsmn_env_t env;
if (!jsmn_env_set_up(&env, filename)) {
jsmn_env_finish(&env);
return false;
}
// set up data
json_data_t data;
json_data_setup(&data);
// set the category set for reference later
data.category_set = category_set_new();
// load our data
if (!jsmn_env_open_json_file(&env, filename)) {
return false;
}
if (!load_categories(&env,&data)) {
return false;
}
// pull down the environment (doesn't free the papers or keywords)
jsmn_env_finish(&env);
// return the category set
*category_set_out = data.category_set;
// free keyword set
hashmap_free(data.keyword_set);
data.keyword_set = NULL;
return true;
}
bool json_load_papers(const char *filename, category_set_t *category_set, int *num_papers_out, paper_t **papers_out, hashmap_t **keyword_set_out) {
// set up environment
jsmn_env_t env;
if (!jsmn_env_set_up(&env, filename)) {
jsmn_env_finish(&env);
return false;
}
// set up data
json_data_t data;
json_data_setup(&data);
// set the category set for reference later
data.category_set = category_set;
// load our data
if (!jsmn_env_open_json_file(&env, filename)) {
return false;
}
if (!load_idc(&env,&data)) {
return false;
}
if (!load_refs(&env,&data)) {
return false;
}
if (!build_citation_links(data.num_papers, data.papers)) {
return false;
}
// pull down the environment
jsmn_env_finish(&env);
// return the papers and keywords
*num_papers_out = data.num_papers;
*papers_out = data.papers;
*keyword_set_out = data.keyword_set;
return true;
}
static bool load_other_links_helper(jsmn_env_t *env, json_data_t *data) {
printf("reading other links from JSON file\n");
// start the JSON stream
bool more_objects = false;
if (!jsmn_env_reset(env, &more_objects)) {
return false;
}
// iterate through the JSON stream
int total_links = 0;
int total_new_links = 0;
while (more_objects) {
if (!jsmn_env_next_object(env, &more_objects)) {
return false;
}
// look for the id member
jsmn_env_token_value_t id_val;
if (!jsmn_env_get_object_member(env, env->js_tok, "id", NULL, &id_val)) {
return false;
}
// check the id is an integer
if (id_val.kind != JSMN_VALUE_UINT) {
return jsmn_env_error(env, "expecting an unsigned integer");
}
// lookup the paper object with this id
paper_t *paper = get_paper_by_id(env, data, id_val.uint);
// if paper found, parse its links
if (paper != NULL) {
// look for the links member
jsmntok_t *links_tok;
if (!jsmn_env_get_object_member(env, env->js_tok, "refs", &links_tok, NULL)) {
return false;
}
// check the links is an array
if (links_tok->type != JSMN_ARRAY) {
return jsmn_env_error(env, "expecting an array");
}
if (links_tok->size == 0) {
// no links to parse
} else {
// some links to parse
// reallocate memory to add links to refs
int n_alloc = paper->num_refs + links_tok->size;
paper->refs = m_renew(paper_t*, paper->refs, n_alloc);
paper->refs_ref_freq = m_renew(byte, paper->refs_ref_freq, n_alloc);
paper->refs_other_weight = m_new(float, n_alloc);
if (paper->refs == NULL || paper->refs_ref_freq == NULL || paper->refs_other_weight == NULL) {
return false;
}
// zero the new weights to begin with
for (int i = 0; i < paper->num_refs; i++) {
paper->refs_other_weight[i] = 0;
}
// parse the links
for (int i = 0; i < links_tok->size; i++) {
// get current element
jsmntok_t *elem_tok;
if (!jsmn_env_get_array_member(env, links_tok, i, &elem_tok, NULL)) {
return false;
}
// check the element is an array of size 2
if (elem_tok->type != JSMN_ARRAY || elem_tok->size != 2) {
return jsmn_env_error(env, "expecting an array of size 2");
}
// get the 2 values
jsmn_env_token_value_t link_id_val;
jsmn_env_token_value_t link_weight_val;
if (!jsmn_env_get_array_member(env, elem_tok, 0, NULL, &link_id_val)) {
return false;
}
if (!jsmn_env_get_array_member(env, elem_tok, 1, NULL, &link_weight_val)) {
return false;
}
if (link_id_val.kind != JSMN_VALUE_UINT) {
return jsmn_env_error(env, "expecting an unsigned integer for link_id");
}
if (link_weight_val.kind != JSMN_VALUE_UINT && link_weight_val.kind != JSMN_VALUE_SINT && link_weight_val.kind != JSMN_VALUE_REAL) {
return jsmn_env_error(env, "expecting a number link_weight");
}
// get linked-to paper
paper_t *paper2 = get_paper_by_id(env, data, link_id_val.uint);
if (paper2 != NULL && paper2 != paper) {
// search for existing link
bool found = false;
for (int i = 0; i < paper->num_refs; i++) {
if (paper->refs[i] == paper2) {
// found existing link; set its weight
paper->refs_other_weight[i] = link_weight_val.real;
found = true;
break;
}
}
if (!found) {
// a new link; add it with ref_freq 0 (since it's not a real reference)
paper->refs[paper->num_refs] = paper2;
paper->refs_ref_freq[paper->num_refs] = 0;
paper->refs_other_weight[paper->num_refs] = link_weight_val.real;
paper->num_refs++;
paper2->num_cites += 1; // TODO a bit of a hack at the moment
total_new_links += 1;
}
total_links += 1;
}
}
}
}
}
printf("read %d total links, %d of those were additional ones\n", total_links, total_new_links);
return true;
}
bool json_load_other_links(const char *filename, int num_papers, paper_t *papers) {
// set up environment
jsmn_env_t env;
if (!jsmn_env_set_up(&env, filename)) {
jsmn_env_finish(&env);
return false;
}
// set up data
json_data_t data;
json_data_setup(&data);
// set papers
data.num_papers = num_papers;
data.papers = papers;
// load other data
if (!jsmn_env_open_json_file(&env, filename)) {
return false;
}
if (!load_other_links_helper(&env,&data)) {
return false;
}
// TODO this is a hack
// we need to rebuild cites so that graph colouring etc works
// but then the number of citations a paper has is wrong, since
// the count includes these new links
for (int i = 0; i < data.num_papers; i++) {
if (data.papers[i].num_cites > 0) {
m_free(data.papers[i].cites);
}
}
if (!build_citation_links(data.num_papers, data.papers)) {
return false;
}
// pull down the environment
jsmn_env_finish(&env);
// free keyword set
hashmap_free(data.keyword_set);
data.keyword_set = NULL;
return true;
}
|
C
|
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
typedef struct TYPE_6__ TYPE_1__ ;
/* Type definitions */
struct TYPE_6__ {int w; int h; float* data; } ;
typedef TYPE_1__ image ;
/* Variables and functions */
int /*<<< orphan*/ constrain_image (TYPE_1__) ;
int /*<<< orphan*/ hsv_to_rgb (TYPE_1__) ;
int /*<<< orphan*/ rgb_to_hsv (TYPE_1__) ;
void hue_image(image im, float hue)
{
rgb_to_hsv(im);
int i;
for(i = 0; i < im.w*im.h; ++i){
im.data[i] = im.data[i] + hue;
if (im.data[i] > 1) im.data[i] -= 1;
if (im.data[i] < 0) im.data[i] += 1;
}
hsv_to_rgb(im);
constrain_image(im);
}
|
C
|
// Thanks:
// - https://tobiasvl.github.io/blog/write-a-chip-8-emulator/
#include <stdlib.h>
#include <signal.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <time.h>
#include "chip8.h"
#include "termbox.h"
#include "util.h"
#define BLACK 16
#define WHITE 255
#define L_RED 1
/*
* keep track of termbox's state, so that we know if
* tb_shutdown() is safe to call, and whether we should redraw.
*
* (Calling tb_shutdown twice, or before tb_init, results in
* a call to abort().)
*/
static const size_t TB_ACTIVE = (1<<1);
static size_t tb_status = 0;
static size_t ui_height, ui_width;
static bool ui_buzzer = false;
static _Bool quit = false;
static _Bool dbg = true;
static size_t dbg_step = 0;
struct CHIP8 chip8;
static void
init_gui(void)
{
char *errstrs[] = {
NULL,
"termbox: unsupported terminal",
"termbox: cannot open terminal",
"termbox: pipe trap error"
};
char *err = errstrs[-(tb_init())];
if (err) die(err);
tb_status |= TB_ACTIVE;
tb_select_input_mode(TB_INPUT_ALT);
tb_select_output_mode(TB_OUTPUT_256);
ui_height = tb_height();
ui_width = tb_width();
}
static void
_draw_u16(uint16_t word, size_t x, size_t y)
{
size_t d1 = (word / 0x1000) % 0x10;
size_t d2 = (word / 0x0100) % 0x10;
size_t d3 = (word / 0x0010) % 0x10;
size_t d4 = (word / 0x0001) % 0x10;
tb_change_cell(x + 0, y, d1 >= 10 ? (d1 - 10) + 'A' : d1 + '0', BLACK, WHITE);
tb_change_cell(x + 1, y, d2 >= 10 ? (d2 - 10) + 'A' : d2 + '0', BLACK, WHITE);
tb_change_cell(x + 2, y, d3 >= 10 ? (d3 - 10) + 'A' : d3 + '0', BLACK, WHITE);
tb_change_cell(x + 3, y, d4 >= 10 ? (d4 - 10) + 'A' : d4 + '0', BLACK, WHITE);
}
static void
_draw_u08(uint8_t byte, size_t x, size_t y)
{
size_t d1 = (byte / 0x10) % 0x10;
size_t d2 = (byte / 0x01) % 0x10;
tb_change_cell(x + 0, y, d1 >= 10 ? (d1 - 10) + 'A' : d1 + '0', BLACK, WHITE);
tb_change_cell(x + 1, y, d2 >= 10 ? (d2 - 10) + 'A' : d2 + '0', BLACK, WHITE);
}
static void
draw(void)
{
size_t ty = 0;
if (ui_buzzer) {
for (size_t x = 0; x < ui_width; ++x) tb_change_cell(x, ty, ' ', BLACK, L_RED);
} else {
for (size_t x = 0; x < ui_width; ++x) tb_change_cell(x, ty, ' ', WHITE, WHITE);
}
ty += 2;
for (size_t y = 0; y < D_HEIGHT; y += 2, ++ty) {
for (size_t x = 0; x < D_WIDTH; ++x) {
uint32_t bg = chip8.display[D_WIDTH * (y+0) + x] ? WHITE : BLACK;
uint32_t fg = chip8.display[D_WIDTH * (y+1) + x] ? WHITE : BLACK;
tb_change_cell(x, ty, 0x2584, fg, bg);
}
}
ty += 2;
for (
ssize_t ity = ty, i = chip8.PC - 6;
i < (ssize_t)sizeof(chip8.memory) && ity < (ssize_t)ui_height;
i += 2, ++ity
) {
if (i < 0) continue;
struct CHIP8_inst inst = chip8_next(&chip8, i);
if (i == (ssize_t)chip8.PC)
tb_change_cell(0, ity, '>', BLACK, WHITE);
_draw_u16(inst.op, 2, ity);
}
size_t rty = ty;
for (size_t r = 0; r < sizeof(chip8.vregs); ++r, ++rty) {
_draw_u08(r, 10, rty);
tb_change_cell(10, rty, 'v', BLACK, WHITE); // overwrite first digit of register name
tb_change_cell(12, rty, ':', BLACK, WHITE);
tb_change_cell(13, rty, ' ', BLACK, WHITE);
_draw_u08(chip8.vregs[r], 14, rty);
}
++rty;
tb_change_cell(11, rty, 'I', BLACK, WHITE);
tb_change_cell(12, rty, ':', BLACK, WHITE);
tb_change_cell(13, rty, ' ', BLACK, WHITE);
_draw_u16(chip8.I, 14, rty);
++rty;
tb_change_cell(10, rty, 'S', BLACK, WHITE);
tb_change_cell(11, rty, 'C', BLACK, WHITE);
tb_change_cell(12, rty, ':', BLACK, WHITE);
tb_change_cell(13, rty, ' ', BLACK, WHITE);
_draw_u16(chip8.SC, 14, rty);
++rty;
tb_change_cell(10, rty, 'P', BLACK, WHITE);
tb_change_cell(11, rty, 'C', BLACK, WHITE);
tb_change_cell(12, rty, ':', BLACK, WHITE);
tb_change_cell(13, rty, ' ', BLACK, WHITE);
_draw_u16(chip8.PC, 14, rty);
rty += 2;
if (dbg) {
tb_change_cell(10, rty, ' ', WHITE, BLACK);
tb_change_cell(11, rty, 'D', WHITE, BLACK);
tb_change_cell(12, rty, 'E', WHITE, BLACK);
tb_change_cell(13, rty, 'B', WHITE, BLACK);
tb_change_cell(14, rty, 'U', WHITE, BLACK);
tb_change_cell(15, rty, 'G', WHITE, BLACK);
tb_change_cell(16, rty, ' ', WHITE, BLACK);
} else {
tb_change_cell(10, rty, ' ', WHITE, WHITE);
tb_change_cell(11, rty, ' ', WHITE, WHITE);
tb_change_cell(12, rty, ' ', WHITE, WHITE);
tb_change_cell(13, rty, ' ', WHITE, WHITE);
tb_change_cell(14, rty, ' ', WHITE, WHITE);
tb_change_cell(15, rty, ' ', WHITE, WHITE);
tb_change_cell(16, rty, ' ', WHITE, WHITE);
}
tb_present();
}
static size_t
keydown(char key)
{
draw();
const char keys[] = {
'X', '1', '2', '3',
'Q', 'W', 'E', 'A',
'S', 'D', 'Z', 'C',
'4', 'R', 'F', 'V'
};
struct tb_event ev;
ssize_t ret = 0;
if ((ret = tb_peek_event(&ev, 512)) == 0)
return 0;
ENSURE(ret != -1); /* termbox error */
if (ev.type == TB_EVENT_KEY && ev.ch) {
return keys[(size_t)key] == (char)MAX(ev.ch, 255);
} else if (ev.type == TB_EVENT_KEY && ev.key) {
switch (ev.key) {
break; case TB_KEY_CTRL_C: quit = true;
break; case TB_KEY_CTRL_D: dbg = !dbg;
break; case TB_KEY_CTRL_E: dbg_step += 1;
}
} else if (ev.type == TB_EVENT_RESIZE) {
ui_height = tb_height();
ui_width = tb_width();
}
return 0;
}
static void
load(char *filename)
{
struct stat st;
stat(filename, &st); // TODO: assert that retcode != 0
char *src = ecalloc(st.st_size, sizeof(char));
FILE *src_f = fopen(filename, "rb");
fread(src, sizeof(char), st.st_size, src_f);
fclose(src_f);
chip8_load(&chip8, src, st.st_size);
free(src);
}
static void
exec(void)
{
ssize_t rs = 1000 / 60;
struct timespec t;
clock_gettime(CLOCK_BOOTTIME, &t);
ssize_t last_ticks = t.tv_nsec / 1000000;
ssize_t last_delta = 0;
ssize_t global_delta = 0;
ssize_t step_delta = 0;
ssize_t render_delta = 0;
while (!quit) {
if (chip8.wait_key == -1) keydown(0);
if (dbg) {
if (dbg_step > 0) {
draw();
chip8_step(&chip8);
chip8.delay_tmr = CHKSUB(chip8.delay_tmr, 1);
chip8.sound_tmr = CHKSUB(chip8.sound_tmr, 1);
ui_buzzer = chip8.sound_tmr > 0;
chip8.redraw = false;
--dbg_step;
}
usleep(10000);
continue;
}
// Update timers.
clock_gettime(CLOCK_BOOTTIME, &t);
ssize_t new_last_ticks = t.tv_nsec / 1000000;
last_delta = new_last_ticks - last_ticks;
last_ticks = new_last_ticks;
step_delta += last_delta;
for (; step_delta >= 1; --step_delta)
chip8_step(&chip8);
global_delta += last_delta;
while (global_delta > rs) {
global_delta -= rs;
chip8.delay_tmr = CHKSUB(chip8.delay_tmr, 1);
chip8.sound_tmr = CHKSUB(chip8.sound_tmr, 1);
ui_buzzer = chip8.sound_tmr > 0;
}
render_delta += last_delta;
if (render_delta > rs) {
if (chip8.redraw) {
draw();
chip8.redraw = false;
}
render_delta -= rs;
}
usleep(1000);
}
}
static void
fini(void)
{
if ((tb_status & TB_ACTIVE) == TB_ACTIVE) {
tb_shutdown();
tb_status ^= TB_ACTIVE;
}
}
int
main(int argc, char **argv)
{
char *filename = "ibm.ch8";
if (argc > 1) filename = argv[1];
init_gui();
chip8_init(&chip8, keydown);
load(filename);
draw();
exec();
fini();
return 0;
}
|
C
|
/*
Given an integer n, return the decimal value of the binary string formed by concatenating the binary representations of 1 to n in order, modulo 10^9 + 7.
Example 1:
Input: n = 1
Output: 1
Explanation: "1" in binary corresponds to the decimal value 1.
Example 2:
Input: n = 3
Output: 27
Explanation: In binary, 1, 2, and 3 corresponds to "1", "10", and "11".
After concatenating them, we have "11011", which corresponds to the decimal value 27.
Example 3:
Input: n = 12
Output: 505379714
Explanation: The concatenation results in "1101110010111011110001001101010111100".
The decimal value of that is 118505380540.
After modulo 10^9 + 7, the result is 505379714.
Constraints:
1 <= n <= 10^5
*/
#include <assert.h>
#include <stdio.h>
typedef unsigned long long uvlong;
// https://oeis.org/A047778
uvlong
concatbin(uvlong n)
{
static const uvlong mod = 1000000007ULL;
uvlong i, r, s;
if (n == 0)
return 0;
r = 1;
s = 4;
for (i = 2; i <= n; i++) {
if (i == s)
s <<= 1;
r = ((r * s) + i) % mod;
}
return r;
}
int
main(void)
{
assert(concatbin(1) == 1);
assert(concatbin(3) == 27);
assert(concatbin(12) == 505379714ULL);
return 0;
}
|
C
|
/**
*
* Given an unsorted array of integers, find the length of longest
* increasing subsequence.
* Note:
* There may be more than one LIS combination, it is only necessary
* for you to return the length.
* Your algorithm should run in O(n2) complexity.
* ================================================================
* 思路
* 1. DP状态定义:
* DP[i]: 对于给定序列0 -> i (i: 0 -> N-1),在选中元素 i 的情况下,
* 最长递增子序列的长度
* 2. DP转移方程:
* DP[i] = max{DP[j]} + 1 (nums[i] > nums[j]) (j: 0 -> i-1)
* 最终结果: max{DP[i]} (i: 0 -> N-1)
*/
int lengthOfLIS(int *nums, int N) {
if (N <= 0) return 0;
int DP[N], max, ret = 0;
DP[0] = 0;
for (int i = 0; i < N; i++) {
max = 0;
for (int j = 0; j < i; j++) {
if (max < DP[j] && nums[i] > nums[j]) {
max = DP[j];
}
}
DP[i] = max + 1;
}
for (int i = 0; i < N; i++) {
if (ret < DP[i]) ret = DP[i];
}
return ret;
}
|
C
|
/*
* Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.
*/
void moveZeroes(int* a, int numsSize) {
int z = 0, nz = 0, n = numsSize,t;
while (z < n && nz < n) {
while(a[z] != 0 && z < n) {
z++;
}
while(a[nz] == 0 && nz < n) {
nz++;
}
if (nz >= n || z >= n)
break;
if (nz > z) {
t = a[nz];
a[nz] = a[z];
a[z] = t;
} else {
nz++;
}
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <Evas.h>
//typedef Evas_List *Ecore_DList;
typedef struct _Ecore_DList
{
Evas_List *curr;
Evas_List *first;
} Ecore_DList;
/*============================================================================*
* Creating and initializing new list structures *
*============================================================================*/
Ecore_DList * ecore_dlist_new()
{
Ecore_DList *l;
l = malloc(sizeof(Ecore_DList));
l->curr = NULL;
l->first = NULL;
//printf("list new %p %p\n", l, *l);
return l;
}
int ecore_dlist_init(Ecore_DList *list)
{
}
void ecore_dlist_destroy(Ecore_DList *list)
{
}
/*============================================================================*
* Adding items to the list *
*============================================================================*/
int ecore_dlist_append(Ecore_DList *list, void *data)
{
list->first = evas_list_append(list->first, data);
//printf("list append first = %p curr = %p\n", list->first, list->curr);
return 1;
}
int ecore_dlist_prepend(Ecore_DList * list, void *_data)
{
}
int ecore_dlist_insert(Ecore_DList * list, void *_data)
{
}
int ecore_dlist_append_list(Ecore_DList * list, Ecore_DList * append)
{
}
int ecore_dlist_prepend_list(Ecore_DList * list, Ecore_DList * prepend)
{
}
void * ecore_dlist_current(Ecore_DList *list)
{
//printf("current %p\n", list);
if (list->curr)
return list->curr->data;
else
return NULL;
}
/*============================================================================*
* Traversing the list *
*============================================================================*/
void * ecore_dlist_first_goto(Ecore_DList *list)
{
//printf("first goto %p\n", el);
list->curr = list->first;
if (list->curr)
return list->curr->data;
else
return NULL;
}
void * ecore_dlist_last_goto(Ecore_DList * list)
{
list->curr = evas_list_last(list->first);
if (list->curr)
return list->curr->data;
else
return NULL;
}
void *ecore_dlist_index_goto(Ecore_DList * list, int index)
{
list->curr = evas_list_nth_list(list->first, index);
if (list->curr)
return list->curr->data;
else
return NULL;
}
void *ecore_dlist_goto(Ecore_DList * list, void *data)
{
list->curr = evas_list_find_list(list->first, data);
if (list->curr)
return list->curr->data;
else
return NULL;
}
/*============================================================================*
* Traversing the list and returning data *
*============================================================================*/
void *ecore_dlist_next(Ecore_DList * list)
{
void *data = NULL;
if (list->curr)
{
data = list->curr->data;
list->curr = evas_list_next(list->curr);
}
return data;
}
void *ecore_dlist_previous(Ecore_DList * list)
{
void *data = NULL;
if (list->curr)
{
data = list->curr->data;
list->curr = evas_list_prev(list->curr);
}
return data;
}
|
C
|
#include <stdio.h>
int main(){
int angka[10]={6,6,2,5,8,1,7,3,4,1};
int i,j;
printf("angka sebelum diurutkan\n");
for(i=0; i<10; i++){
printf("%d ", angka[i]);
}
//looping sebanyak jumlah data
for(i=0; i<10; i++){
int terkecil=i;
//looping untuk mencari index/posisi angka yang terkecil
//caranya adalah membandingkan angka satu per satu
for( j=i; j<10; j++){
//jika ada yang lebih kecil dari angka index ke terkecil
if(angka[j]<angka[terkecil]){
//maka, ganti terkecil menjadi index angka tersebut
terkecil=j;
}
}
//swap value (tukar)
int temp=angka[i];
angka[i]=angka[terkecil];
angka[terkecil]=temp;
}
//cetak data
printf("\nangka sesudah diurutkan\n");
for(i=0; i<10; i++){
printf("%d ", angka[i]);
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
typedef struct stack
{
int arr[10010], size;
} Stack;
Stack stack[1000];
int top = -1;
int cmp_each(const void *a, const void *b)
{
return (*(int *)a - *(int *)b);
}
int cmp_all(const void *a, const void *b)
{
Stack c = *(Stack *)a, d = *(Stack *)b;
return c.arr[0] - d.arr[0];
}
int search(int n)
{
int i, j;
for(i = 0; i<= top; i++)
for(j = 0; j < stack[i].size; j++)
if(n == stack[i].arr[j])
return i;
return -1;
}
void merge(int a, int b)
{
int i, j;
for(i = stack[a].size, j = 0; j < stack[b].size; i++, j++)
stack[a].arr[i] = stack[b].arr[j];
stack[a].size += stack[b].size;
for(i = 0, j = 0; j < stack[top].size; i++, j++)
stack[b].arr[i] = stack[top].arr[j];
stack[b].size = stack[top].size;
top--;
}
int main()
{
int a, b, index_a, index_b, i, j;
freopen("12input-2.txt", "r", stdin);
freopen("12output-21.txt", "w", stdout);
while(scanf("%d %d", &a, &b) != EOF)
{
index_a = search(a);
index_b = search(b);
if(index_a == -1 && index_b == -1)
{
stack[++top].arr[0] = a;
stack[top].arr[1] = b;
stack[top].size = 2;
}
else if(index_a != -1 && index_b == -1)
stack[index_a].arr[stack[index_a].size++] = b;
else if(index_a == -1 && index_b != -1)
stack[index_b].arr[stack[index_b].size++] = a;
else if(index_a != -1 && index_b != -1)
{
if(index_a < index_b)
merge(index_a, index_b);
else if(index_a > index_b)
merge(index_b, index_a);
}
}
for(i = 0; i <= top; i++)
qsort((void *)stack[i].arr, stack[i].size, sizeof(int), cmp_each);
qsort((void *)stack, top + 1, sizeof(Stack), cmp_all);
for(i = 0; i <= top; i++)
{
for(j = 0; j < stack[i].size; j++)
printf("%d ", stack[i].arr[j]);
printf("\n");
}
return 0;
}
|
C
|
/*
Lab9, "Emiter" file for NASM generation
Christian McGovern
May 4, 2018
*/
#include "emit.h"
//calls what to print at the correct time
void emitNASM(ASTnode *p, FILE *out){
if(p==NULL) return;
fprintf(out, "%%include \"io64.inc\"\n\n");
ASTglobals(p, out);
fprintf(out, "\nsection .data\n\n");
ASTstrings(p, out);
fprintf(out, "\nsection .text\n\n");
fprintf(out, "\tglobal main\n\n");
ASTtext(p, out);
}
//prints global variables
void ASTglobals(ASTnode *p, FILE *out){
if(p==NULL)
return;
if((p->type == VARDEC) && (p->value == 0)){
fprintf(out, "common\t%s\t%d\n", p->name, WSIZE);
}
else if((p->type == VARDEC) && (p->value > 0)){
fprintf(out, "common\t%s\t%d\n", p->name, (p->value * WSIZE));
}
ASTglobals(p->next, out);
}
//prints strings
void ASTstrings(ASTnode *p, FILE *out){
if(p==NULL)
return;
if((p->type == WRITESTMT) && (p->name != NULL)){
fprintf(out, "%s:\tdb\t%s,%d\t;global string\n",p->label,p->name,0);
}
ASTstrings(p->next, out);
ASTstrings(p->s1, out);
ASTstrings(p->s2, out);
ASTstrings(p->s3, out);
}
void ASTtext(ASTnode *p, FILE *out){
if (p == NULL)
return;
else{
char *L1, *L2;
switch (p->type) {
case VARDEC :
break;
case FUNDEC :
/*header*/
currentFunction = p->name;
fprintf(out, "%s:\t\t;Start of Function\n",p->name);
if(strcmp(p->name, "main") == 0)
fprintf(out, "\tmov\trbp, rsp\t;For main only\n");
fprintf(out, "\tmov\tr8, rsp\t;FUNC header RSP has to be at most RBP\n");
fprintf(out, "\tadd\tr8, -%d\t;adjust Stack Pointer for Activation record\n",p->value * WSIZE);
fprintf(out, "\tmov\t[r8], rbp\t;FUNC header store old BP\n");
fprintf(out, "\tmov\t[r8+8], rsp\t;FUNC header store old SP\n");
if(strcmp(p->name, "main") != 0)
fprintf(out, "\tmov\trbp, rsp\t;FUNC header TSP has to be at most rbp\n");
fprintf(out, "\tmov\trsp, r8\t;FUNC header new SP\n");
ASTtext(p->s2, out);
/*footer*/
fprintf(out, "\txor\trax, rax\t;nothing to return\n");
fprintf(out,"\n\tmov\trbp, [rsp]\t;FUNC end restore old BP\n");
fprintf(out,"\tmov\trsp, [rsp+8]\t;FUNC end restore old SP\n");
if(strcmp(currentFunction, "main") == 0)
fprintf(out,"\tmov\trsp, rbp\t;stack and BP need to be same on exit for main\n");
fprintf(out,"\tret\n");
break;
case CMPDSTMT :
ASTtext(p->s1, out);
ASTtext(p->s2, out);
break;
case PARAM :
break;
case EXPRSTMT :
if(p->s1 != NULL){
switch(p->s1->type){
case NUMB:
fprintf(out, "\tmov\trax, %d \t;get identifier offset\n", p->s1->value);
break;
case IDENT:
emitIdent(p->s1, out);
fprintf(out, "\tmov\trax, [rax]\t;expression ident\n");
break;
case EXPR:
emitExpr(p->s1, out);
fprintf(out, "\tmov\trax, [rsp+%d]\t;expressionstmt expr\n", p->s1->symbol->offset*WSIZE);
break;
case FUNCALL:
emitFunction(p->s1, out);
break;
default:
fprintf(out, "\tBAD EXPRSTMT\n");
break;
}
fprintf(out, "\tmov\t[rsp+%d], rax\t;store rhs\n", p->symbol->offset*WSIZE);
}
break;
case ASIGNSTMT :
ASTtext(p->s2, out);
emitIdent(p->s1, out);
fprintf(out, "\tmov\trbx, [rsp+%d]\t;fetch rhs of assign temporarily\n", p->s2->symbol->offset*WSIZE);
fprintf(out, "\tmov\t[rax], rbx\t;move rhs into rax\n");
break;
case SELECSTMT :
L1=CreateLabel();
L2=CreateLabel();
switch(p->s1->type){
case NUMB:
fprintf(out, "\tmov\trax, %d \t;If value loaded\n", p->s1->value);
break;
case IDENT:
emitIdent(p->s1, out);
fprintf(out, "\tmov\trax, [rax]\t;if expression IDENT\n");
break;
case FUNCALL:
emitFunction(p->s1, out);
break;
case EXPR:
emitExpr(p->s1, out);
fprintf(out, "\tmov\trax, [rsp+%d]\t;if expression expr\n", p->s1->symbol->offset*WSIZE);
break;
default:
fprintf(out, "\t;Bad if\n");
break;
}
fprintf(out, "\tCMP\trax, 0\t;if compare\n");
fprintf(out, "\tJE\t%s, \t;if branch to else\n", L1);
ASTtext(p->s2, out);
fprintf(out, "\tJMP\t%s\t;If s1 end\n", L2);
fprintf(out, "\n%s:\t;else target\n", L1);
ASTtext(p->s3, out);
fprintf(out, "\n%s:\t;IF bottom target\n", L2);
break;
case ITRASTMT :
L1=CreateLabel();
L2=CreateLabel();
fprintf(out, "\n%s:\t;while top target\n", L1);
switch(p->s1->type){
case NUMB:
fprintf(out, "\tmov\trax, %d \t;while value loaded\n", p->s1->value);
break;
case IDENT:
emitIdent(p->s1, out);
fprintf(out, "\tmov\trax, [rax]\t;while expression ident\n");
break;
case FUNCALL:
emitFunction(p->s1, out);
break;
case EXPR:
emitExpr(p->s1, out);
fprintf(out, "\tmov\trax, [rsp+%d]\t;while expression expr\n", p->s1->symbol->offset*WSIZE);
break;
default:
fprintf(out, "\t;bad while\n");
break;
}
fprintf(out, "\tCMP\trax, 0\t;while compare\n");
fprintf(out, "\tJE\t%s,\t;while branch\n", L2);
ASTtext(p->s2, out);
fprintf(out, "\tJMP\t%s\t;while jump back \n", L1);
fprintf(out, "\n%s:\t;while end target\n", L2);
break;
case RTRNSTMT :
emitReturn(p, out);
break;
case READSTMT :
emitIdent(p->s1, out);
fprintf(out, "\tGET_DEC\t8, [rax]\t;readstmt\n");
break;
case WRITESTMT :
if(p->s1 != NULL){
switch(p->s1->type){
case NUMB:
fprintf(out, "\tmov\trsi, %d \t;load immediate value\n", p->s1->value);
break;
case IDENT:
emitIdent(p->s1, out);
fprintf(out, "\tmov\trsi, [rax]\t;load immediate value\n");
break;
case EXPR:
emitExpr(p->s1, out);
fprintf(out, "\tmov\trsi, [rsp+%d]\t;load expr value from expr mem\n", p->s1->symbol->offset*WSIZE);
break;
case FUNCALL:
emitFunction(p->s1, out);
fprintf(out, "\tmov\trsi, rax\t;store function return into rsi\n");
break;
default:
fprintf(out, "\t;bad WRITESTMT\n");
break;
}
fprintf(out, "\tPRINT_DEC\t8, rsi\t;standard write value\n");
fprintf(out, "\tNEWLINE\t\t;standard newline\n");
}
if(p->name != NULL){
fprintf(out, "\tPRINT_STRING\t%s\t;standard write value\n", p->label);
fprintf(out, "\tNEWLINE\t\t;standard newline\n");
}
break;
case EXPR :
fprintf(out, "\t;EXPR\n");
break;
case IDENT :
fprintf(out, "\t;IDENT\n");
break;
case NUMB :
fprintf(out, "\t;NUMB\n");
break;
case FUNCALL :
emitFunction(p->s1, out);
break;
case ARG :
fprintf(out, "\t;ARG\n");
break;
default: fprintf(out, "\t;unknown type in ASTtext\n");
}//end switch
ASTtext(p->next, out);
}//end else
}//end ASTtext()
void emitExpr(ASTnode *p, FILE *out){
//left side
switch(p->s1->type){
case NUMB:
fprintf(out, "\tmov\trax, %d \t;get identifier offset\n", p->s1->value);
break;
case IDENT:
emitIdent(p->s1, out);
fprintf(out, "\tmov\trax, [rax]\t;LHS expression is identifier\n");
break;
case EXPR:
emitExpr(p->s1, out);
fprintf(out, "\tmov\trax, [rsp+%d]\t;fetch LHS of expression from memory\n", p->s1->symbol->offset * WSIZE);
break;
case FUNCALL:
emitFunction(p->s1, out);
break;
default:
fprintf(out, "\t;bad left side\n");
break;
}//end left switch
//store
fprintf(out, "\tmov\t[rsp+%d], rax\t;store rax\n", p->symbol->offset * WSIZE);
//right side
switch(p->s2->type){
case NUMB:
fprintf(out, "\tmov\trbx, %d \t;get identifier offset\n", p->s2->value);
break;
case IDENT:
emitIdent(p->s2, out);
fprintf(out, "\tmov\trbx, [rax]\t;RHS expression is identifier\n");
break;
case EXPR:
emitExpr(p->s2, out);
fprintf(out, "\tmov\trbx, [rsp+%d]\t;fetch RHS of expression from memory\n", p->s2->symbol->offset * WSIZE);
break;
case FUNCALL:
emitFunction(p->s1, out);
fprintf(out, "\tmov\trbx, rax\t;store function return into rbx\n");
break;
default:
fprintf(out, "\t;bad right side\n");
break;
}//end right switch
//store
fprintf(out, "\tmov\trax, [rsp+%d]\t;store rsp + offset into rax\n", p->symbol->offset * WSIZE);
//operators
switch(p->operator){
case PLUS:
fprintf(out, "\tadd\trax, rbx\t;EXPR ADD\n");
break;
case MINUS:
fprintf(out, "\tsub\trax, rbx\t;EXPR SUB\n");
break;
case TIMES:
fprintf(out, "\timul\trax, rbx\t;EXPR TIMES\n");
break;
case DIVIDE:
fprintf(out, "\txor\trdx, rdx\t;EXPR XOR\n");
fprintf(out, "\tidiv\trbx\t;EXPR DIV\n");
break;
case EQUAL:
fprintf(out, "\tcmp\trax, rbx\t;EXPR EQUAL\n");
fprintf(out, "\tsete\tal\t;EXPR EQUAL\n");
fprintf(out, "\tmov\trbx, 1\t;set rbx to one to filter rax\n");
fprintf(out, "\tand\trax, rbx\t;filter rax\n");
break;
case NOTEQUAL:
fprintf(out, "\tcmp\trax, rbx\t;EXPR NOTEQUAL\n");
fprintf(out, "\tsetne\tal\t;EXPR NOTEQUAL\n");
fprintf(out, "\tmov\trbx, 1\t;Set rbx to 1 to filter rax\n");
fprintf(out, "\tand\trax, rbx\t;filter rax\n");
break;
case LESSTHAN:
fprintf(out, "\tcmp\trax, rbx\t;EXPR LESSTHAN \n");
fprintf(out, "\tsetl\tal\t;EXPR LESSTHAN\n");
fprintf(out, "\tmov\trbx, 1\t;set rbx to 1 to filter rax\n");
fprintf(out, "\tand\trax, rbx\t;filter RAX\n");
break;
case GREATERTHAN:
fprintf(out, "\tcmp\trax, rbx\t;EXPR GREATERTHAN\n");
fprintf(out, "\tsetg\tal\t;EXPR GREATERTHAN\n");
fprintf(out, "\tmov\trbx, 1\t;set rbx to 1 to filter rax\n");
fprintf(out, "\tand\trax, rbx\t;filter rax\n");
break;
case LESSTHANEQUAL:
fprintf(out, "\tcmp\trax, rbx\t;EXPR LESSTHANEQUAL\n");
fprintf(out, "\tsetle\tal\t;EXPR LESSTHANEQUAL\n");
fprintf(out, "\tmov\trbx, 1\t;Set rbx to 1 to filter rax\n");
fprintf(out, "\tand\trax, rbx\t;filter rax\n");
break;
case GREATERTHANEQUAL:
fprintf(out, "\tcmp\trax, rbx\t;EXPR GREATERTHANEQUAL\n");
fprintf(out, "\tsetge\tal\t;EXPRE GREATERTHANEQUAL\n");
fprintf(out, "\tmov\trbx, 1\t;set rbx to one to filter rax\n");
fprintf(out, "\tand\trax, rbx\t;filter rax\n");
break;
default:
fprintf(out, "\tbad operator\n");
break;
}
//store
fprintf(out, "\tmov\t[rsp+%d], rax\t;store rax\n", p->symbol->offset * WSIZE);
}//end emitExpr
void emitIdent(ASTnode *p, FILE *out){
if(p->s1 != NULL){
switch(p->s1->type){
case NUMB:
fprintf(out, "\tmov\trbx, %d \t;assign value to rbx\n",p->s1->value*WSIZE);
break;
case IDENT:
emitIdent(p->s1, out);
fprintf(out, "\tmov\trbx, [rax]\t;move rax value to rbx\n");
fprintf(out, "\tshl\trbx, 3\t;Array reference needs WSIZE differencing\n");
break;
case EXPR:
emitExpr(p->s1, out);
fprintf(out, "\tmov\trbx, [rsp+%d]\t;move array value at sp to rbx\n", p->s1->symbol->offset*WSIZE);
fprintf(out, "\tshl\trbx, 3\t;Array reference needs WSIZE differencing\n");
break;
case FUNCALL:
emitFunction(p->s1, out);
fprintf(out, "\tmov\trbx, rax\t;store function return\n");
fprintf(out, "\tshl\trbx, 3\t;Array reference needs WSIZE differencing\n");
break;
default:
fprintf(out, "\t;bad array idents\n");
break;
}//end switch
}//end if
if(p->symbol->level == 0){
fprintf(out, "\n\tmov\trax, %s\t;put address into rax\n", p->name);
}
else{
fprintf(out, "\n\tmov\trax, %d \t;get identifier offset\n", p->symbol->offset *WSIZE);
fprintf(out, "\tadd\trax, rsp\t;Add the sp to have direct reference to memory\n");
}
if(p->s1 != NULL)
fprintf(out, "\tadd\trax, rbx\t;add offset and stack pointer\n");
}//end emitIdent
void emitFunction(ASTnode *p, FILE *out){
//gets value from arg
evaluateArgs(p->s1, out);
//moves args of function call to params of function
emitArgsToParams(p->s1, p->symbol->fparms, p->symbol->mysize, out);
fprintf(out, "\tcall\t%s\t;call function\n", p->name);
return;
}//end emitFunction
void evaluateArgs(ASTnode *p, FILE *out){
if(p == NULL){
return;
}
switch(p->s1->type){
case NUMB:
fprintf(out, "\tmov\trax, %d \t;arg number\n", p->s1->value);
break;
case IDENT:
emitIdent(p->s1, out);
fprintf(out, "\tmov\trax, [rax]\t;arg identifier value\n");
break;
case EXPR:
emitExpr(p->s1, out);
fprintf(out, "\tmov\trax, [rsp+%d]\t;arg expression\n", p->s1->symbol->offset * WSIZE);
break;
case FUNCALL:
emitFunction(p->s1, out);
break;
default:
fprintf(out, "\t;bad arg type\n");
break;
}
fprintf(out, "\tmov\t[rsp+%d], rax\t;store arg into arglist offset\n", p->symbol->offset * WSIZE);
evaluateArgs(p->next, out);
}//end evaluateArgs
//moves all args of function call to params of function
void emitArgsToParams(ASTnode *arg, ASTnode *param, int functionSize, FILE *out){
fprintf(out, "\tmov\trbx, rsp\t;store rsp in rbx\n");
fprintf(out, "\tsub\trbx, %d \t;subtract functionSize+1 to get location on stack\n", ((functionSize+1)*WSIZE));
while(param != NULL){
//copy arg
fprintf(out, "\tmov\trax, [rsp+%d]\t;temporarily store arg contents\n", arg->symbol->offset * WSIZE);
//mov arg to param
fprintf(out, "\tmov\t[rbx+%d], rax\t;copy contents of rax into param\n", param->symbol->offset * WSIZE);
//go through all params/args
arg=arg->next;
param=param->next;
}//end while still params
}//end emitArgsToParams
//returns value or nothing
void emitReturn(ASTnode *p, FILE *out){
if((p != NULL) && (p->s1 != NULL)){
switch(p->s1->type){
case NUMB:
fprintf(out, "\tmov\trax, %d \t;return number\n", p->s1->value);
break;
case IDENT:
emitIdent(p->s1, out);
fprintf(out, "\tmov\trax, [rax]\t;return identifier value\n");
break;
case EXPR:
emitExpr(p->s1, out);
fprintf(out, "\tmov\trax, [rsp+%d]\t;return value of expression\n", p->s1->symbol->offset * WSIZE);
break;
case FUNCALL:
emitFunction(p->s1, out);
break;
default:
fprintf(out, "\t;bad return\n");
break;
}//end return switch
}//end if has something to return
else{
fprintf(out, "\txor\trax, rax\t;nothing to return\n");
}
fprintf(out,"\n\tmov\trbp, [rsp]\t;FUNC end restore old BP\n");
fprintf(out,"\tmov\trsp, [rsp+8]\t;FUNC end restore old SP\n");
if(strcmp(currentFunction, "main") == 0)
fprintf(out,"\tmov\trsp, rbp\t;stack and BP need to be same on exit for main\n");
fprintf(out,"\tret\n");
}//end emitReturn()
|
C
|
/**
* IEEE EUI-64 functions.
*
* Copyright Thinnect Inc. 2020
* @license MIT
*/
#include "eui64.h"
#include <string.h>
bool eui64_is_zeros(const ieee_eui64_t * eui)
{
uint8_t i;
for (i=0;i<IEEE_EUI64_LENGTH;i++)
{
if (0 != eui->data[i])
{
return false;
}
}
return true;
}
void eui64_set_zeros(ieee_eui64_t * eui)
{
memset(eui->data, 0, IEEE_EUI64_LENGTH);
}
bool eui64_is_ones(const ieee_eui64_t * eui)
{
uint8_t i;
for (i=0;i<IEEE_EUI64_LENGTH;i++)
{
if (0xFF != eui->data[i])
{
return false;
}
}
return true;
}
void eui64_set_ones(ieee_eui64_t * eui)
{
memset(eui->data, 0xFF, IEEE_EUI64_LENGTH);
}
void eui64_set(ieee_eui64_t * eui, const uint8_t data[IEEE_EUI64_LENGTH])
{
memcpy(eui->data, data, IEEE_EUI64_LENGTH);
}
void eui64_get(const ieee_eui64_t * eui, uint8_t data[IEEE_EUI64_LENGTH])
{
memcpy(data, eui->data, IEEE_EUI64_LENGTH);
}
int eui64_compare(const ieee_eui64_t * eui1, const ieee_eui64_t * eui2)
{
return memcmp(eui1->data, eui2->data, IEEE_EUI64_LENGTH);
}
|
C
|
#include <pebble.h>
#include <stdio.h>
#include <ctype.h>
static char dots10[] = ". . . . . . . . . .";
static char dots9[] = ". . . . . . . . .";
static char dots8[] = ". . . . . . . .";
static char dots7[] = ". . . . . . .";
static char dots6[] = ". . . . . .";
static char dots5[] = ". . . . .";
static char dots4[] = ". . . .";
static char dots3[] = ". . .";
static char dots2[] = ". .";
static char dots1[] = ".";
static char dots0[] = " ";
static Window *s_main_window;
static TextLayer *s_bg_layer;
static TextLayer *s_time_layer;
static TextLayer *dots_layer;
static TextLayer *date_layer;
// Create a long-lived buffer
static char dummy[] = " ";
static char buffer[] = "00 : 00 : 00";
static char buffer2[] = "00";
static char buffer3[] = "00";
static char buffer4[] = "00";
static char hexColor[] = "000000";
static char dots[] = "..........................";
static char date[] = "SEPTEMBER 00";
static void update_time() {
// Get a tm structure
time_t temp = time(NULL);
struct tm *tick_time = localtime(&temp);
if(clock_is_24h_style() == true) {
//Use 24h hour format
strftime(buffer, sizeof("00 : 00 : 00"), "%H : %M : %S", tick_time);
} else {
//Use 12 hour format
strftime(buffer, sizeof("00 : 00 : 00"), "%I : %M : %S", tick_time);
}
strftime(hexColor, sizeof("000000"), "%H%M%S", tick_time);
strftime(buffer2, sizeof("00"), "%H", tick_time);
strftime(buffer3, sizeof("00"), "%M", tick_time);
strftime(buffer4, sizeof("00"), "%S", tick_time);
strftime(date, sizeof(date), "%A %d", tick_time);
int hour = atoi(buffer2);
int min = atoi(buffer3);
int sec = atoi(buffer4);
if ((min < 5) && (sec < 20)) {
text_layer_set_text_color(s_time_layer, GColorWhite);
text_layer_set_text_color(dots_layer, GColorWhite);
text_layer_set_text_color(date_layer, GColorWhite);
} else {
text_layer_set_text_color(s_time_layer, GColorBlack);
text_layer_set_text_color(dots_layer, GColorBlack);
text_layer_set_text_color(date_layer, GColorBlack);
}
//Randomize!
hour*=10;
min*=4;
sec*=4;
BatteryChargeState state = battery_state_service_peek();
switch (state.charge_percent) {
case 100:
text_layer_set_text(dots_layer, dots10);
break;
case 90:
text_layer_set_text(dots_layer, dots9);
break;
case 80:
text_layer_set_text(dots_layer, dots8);
break;
case 70:
text_layer_set_text(dots_layer, dots7);
break;
case 60:
text_layer_set_text(dots_layer, dots6);
break;
case 50:
text_layer_set_text(dots_layer, dots5);
break;
case 40:
text_layer_set_text(dots_layer, dots4);
break;
case 30:
text_layer_set_text(dots_layer, dots3);
break;
case 20:
text_layer_set_text(dots_layer, dots2);
break;
case 10:
text_layer_set_text(dots_layer, dots1);
break;
case 0:
text_layer_set_text(dots_layer, dots0);
break;
default:
text_layer_set_text(dots_layer, dots10);
break;
}
// text_layer_set_background_color(s_bg_layer, GColorFromHEX(result));
text_layer_set_background_color(s_bg_layer, GColorFromRGB(hour, min, sec));
text_layer_set_text(s_time_layer, buffer);
text_layer_set_text(date_layer, date);
}
static void set_text_to_window() {
//Time TextLayer
s_bg_layer = text_layer_create(GRect(0, 0, 144, 168));
text_layer_set_background_color(s_bg_layer, GColorFromHEX(0xAA0055));
text_layer_set_text_color(s_bg_layer, GColorClear);
text_layer_set_text(s_bg_layer, " ");
text_layer_set_font(s_bg_layer, fonts_get_system_font(FONT_KEY_GOTHIC_28_BOLD));
text_layer_set_text_alignment(s_bg_layer, GTextAlignmentCenter);
//Time TextLayer
s_time_layer = text_layer_create(GRect(0, 45, 144, 40));
text_layer_set_background_color(s_time_layer, GColorClear);
text_layer_set_text_color(s_time_layer, GColorBlack);
text_layer_set_text(s_time_layer, "00 : 00 : 00");
text_layer_set_font(s_time_layer, fonts_get_system_font(FONT_KEY_GOTHIC_28_BOLD));
text_layer_set_text_alignment(s_time_layer, GTextAlignmentCenter);
//Time TextLayer
dots_layer = text_layer_create(GRect(0, 60, 144, 40));
text_layer_set_background_color(dots_layer, GColorClear);
text_layer_set_text_color(dots_layer, GColorBlack);
text_layer_set_text(dots_layer, "........................");
text_layer_set_font(dots_layer, fonts_get_system_font(FONT_KEY_GOTHIC_28_BOLD));
text_layer_set_text_alignment(dots_layer, GTextAlignmentCenter);
//Time TextLayer
date_layer = text_layer_create(GRect(0, 88, 144, 40));
text_layer_set_background_color(date_layer, GColorClear);
text_layer_set_text_color(date_layer, GColorBlack);
text_layer_set_text(date_layer, "SEPTEMBER 00");
text_layer_set_font(date_layer, fonts_get_system_font(FONT_KEY_GOTHIC_24_BOLD));
text_layer_set_text_alignment(date_layer, GTextAlignmentCenter);
}
static void main_window_load(Window *window) {
set_text_to_window();
layer_add_child(window_get_root_layer(window), text_layer_get_layer(s_bg_layer));
layer_add_child(window_get_root_layer(window), text_layer_get_layer(s_time_layer));
layer_add_child(window_get_root_layer(window), text_layer_get_layer(dots_layer));
layer_add_child(window_get_root_layer(window), text_layer_get_layer(date_layer));
// Make sure the time is displayed from the start
update_time();
}
static void main_window_unload(Window *window) {
// Destroy TextLayer
text_layer_destroy(s_bg_layer);
text_layer_destroy(s_time_layer);
text_layer_destroy(dots_layer);
text_layer_destroy(date_layer);
}
static void tick_handler(struct tm *tick_time, TimeUnits units_changed) {
update_time();
}
static void bt_handler(bool connected) {
}
static void init() {
// Create main Window element and assign to pointer
s_main_window = window_create();
// Set handlers to manage the elements inside the Window
window_set_window_handlers(s_main_window, (WindowHandlers) {
.load = main_window_load,
.unload = main_window_unload
});
// Show the Window on the watch, with animated=true
window_stack_push(s_main_window, true);
bluetooth_connection_service_subscribe(bt_handler);
// Register with TickTimerService
tick_timer_service_subscribe(SECOND_UNIT, tick_handler);
}
static void deinit() {
// Destroy Window
window_destroy(s_main_window);
tick_timer_service_unsubscribe();
}
int main(void) {
init();
app_event_loop();
deinit();
}
|
C
|
#include <lasertag/speaker.h>
#include <avr/io.h>
/* The Timer0 prescaler. */
#define SPEAKER_PRESCALER 1024
/*
* The frequency at which the speaker pin is toggled. The actual frequency of
* the tone is half of the toggle frequency.
*/
#define SPEAKER_TOGGLE_FREQ (F_CPU / SPEAKER_PRESCALER)
void speaker_init(void)
{
/* Set PD6 (speaker) to be an output. */
DDRD |= (1 << PD6);
/*
* Configure Timer0 to use the clear on terminal count waveform generator,
* such that the frequency can be varied. A prescaler of 1024 is used which
* allows a range of 256 frequencies in the range ~30 Hz to ~7.8 kHz.
*/
TCCR0A = (1 << WGM01);
TCCR0B = (1 << CS02) | (1 << CS00);
}
void speaker_tone(int hz)
{
/* Calculate and set the terminal count value for the specified frequency. */
OCR0A = SPEAKER_TOGGLE_FREQ / (2 * hz) - 1;
/* Connect output compare unit A to PD6. */
TCCR0A |= (1 << COM0A0);
}
void speaker_off(void)
{
/* Disconnect output compare unit A from PD6. */
TCCR0A &= ~(1 << COM0A0);
}
|
C
|
/*
Copyright 2013-present Barefoot Networks, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <assert.h>
#include <sys/time.h>
#include <p4utils/circular_buffer.h>
/* Circular buffer object */
struct circular_buffer_s {
int size; /* maximum number of elements */
int start; /* index of oldest element */
int count;
void **elems; /* vector of elements */
cb_write_behavior_t write_behavior;
cb_read_behavior_t read_behavior;
pthread_mutex_t lock;
pthread_cond_t cond_nonfull;
pthread_cond_t cond_nonempty;
};
circular_buffer_t *cb_init(int size, cb_write_behavior_t wb, cb_read_behavior_t rb) {
circular_buffer_t *cb = malloc(sizeof(circular_buffer_t));
assert(size > 0);
cb->size = size; /* include empty elem */
cb->start = 0;
cb->count = 0;
cb->elems = calloc(cb->size, sizeof(void *));
cb->write_behavior = wb;
cb->read_behavior = rb;
pthread_mutex_init(&cb->lock, NULL);
pthread_cond_init(&cb->cond_nonfull, NULL);
pthread_cond_init(&cb->cond_nonempty, NULL);
return cb;
}
void cb_destroy(circular_buffer_t *cb) {
pthread_cond_destroy(&cb->cond_nonfull);
pthread_cond_destroy(&cb->cond_nonempty);
pthread_mutex_destroy(&cb->lock);
free(cb->elems);
free(cb);
}
int cb_empty(circular_buffer_t* cb) {
pthread_mutex_lock(&cb->lock);
int ret = -1;
if (cb->count == 0) {
ret = 1;
} else {
ret = 0;
}
pthread_mutex_unlock(&cb->lock);
return ret;
}
int cb_count(circular_buffer_t* cb) {
pthread_mutex_lock(&cb->lock);
//There is also the option of not acquiring lock for now - ideally we should
int ret = cb->count;
pthread_mutex_unlock(&cb->lock);
return ret;
}
int cb_write(circular_buffer_t *cb, void* elem) {
pthread_mutex_lock(&cb->lock);
/* Overflow behaviors */
if (cb->write_behavior == CB_WRITE_BLOCK) {
while(cb->count == cb->size)
pthread_cond_wait(&cb->cond_nonfull, &cb->lock);
} else if (cb->write_behavior == CB_WRITE_DROP) {
if (cb->count == cb->size) {
pthread_mutex_unlock(&cb->lock);
return 0;
}
}
int end = (cb->start + cb->count) % cb->size;
cb->elems[end] = elem;
++cb->count;
if (cb->write_behavior == CB_WRITE_BLOCK) {
pthread_cond_signal(&cb->cond_nonempty);
}
pthread_mutex_unlock(&cb->lock);
return 1;
}
void *cb_read(circular_buffer_t *cb) {
pthread_mutex_lock(&cb->lock);
if (cb->read_behavior == CB_READ_BLOCK) {
while(cb->count == 0)
pthread_cond_wait(&cb->cond_nonempty, &cb->lock);
} else if (cb->read_behavior == CB_READ_RETURN) {
if (cb->count == 0) {
pthread_mutex_unlock(&cb->lock);
return NULL;
}
}
void *elem = cb->elems[cb->start];
cb->start = (cb->start + 1) % cb->size;
--cb->count;
if (cb->read_behavior == CB_READ_BLOCK) {
pthread_cond_signal(&cb->cond_nonfull);
}
pthread_mutex_unlock(&cb->lock);
return elem;
}
void *cb_read_with_wait(circular_buffer_t *cb, const struct timeval *timeout) {
pthread_mutex_lock(&cb->lock);
if(cb->count == 0) {
if(0 == timeout) {
pthread_cond_wait(&cb->cond_nonempty, &cb->lock);
}
else {
struct timespec abs_timeout;
struct timeval now, end_time;
gettimeofday(&now,NULL);
timeradd(&now, timeout, &end_time);
abs_timeout.tv_sec = end_time.tv_sec;
abs_timeout.tv_nsec = end_time.tv_usec * 1000UL;
pthread_cond_timedwait(&cb->cond_nonempty, &cb->lock, &abs_timeout);
}
}
void *elem = NULL;
if(0 < cb->count) {
elem = cb->elems[cb->start];
cb->start = (cb->start + 1) % cb->size;
--cb->count;
pthread_cond_signal(&cb->cond_nonfull);
}
pthread_mutex_unlock(&cb->lock);
return elem;
}
void cb_resize(circular_buffer_t *cb, const int new_size, cb_cleanup cb_cleanup_function) {
pthread_mutex_lock(&cb->lock);
assert(new_size > 0);
/* Now shift the circular buffer using another buffer of new_size */
void** new_buffer = calloc(new_size, sizeof(void *));
assert(new_buffer != NULL);
const int shift_num = (cb->count < new_size) ? cb->count : new_size;
int i = 0;
for (i = 0; i < shift_num; i++) {
new_buffer[i] = cb->elems[(cb->start + i)%cb->size];
}
/* Clear out elements beyond cb->size */
for (i = shift_num; i < cb->count; i++) {
cb_cleanup_function(cb->elems[(cb->start + i)%cb->size]);
}
/* Reset state */
cb->start = 0;
cb->count = shift_num;
cb->size = new_size;
/* free old pointer and reassign elems */
free(cb->elems);
cb->elems = new_buffer;
pthread_mutex_unlock(&cb->lock);
}
|
C
|
#include <stdio.h>
int main()
{
int a[100000];
int i;
a[1] = 1;
a[2] = 1;
for (i=3; i<=30; i++)
a[i] = a[i-1]+a[i-2];
printf("Fibonacci %d: %d\n", 30, a[30]);
return 0;
}
|
C
|
#include<stdio.h>
#include<string.h>
int max(int a, int b){return a>b?a:b;}
int min(int a, int b){return a<b?a:b;}
typedef long long LL;
/*
qsort(a, n, sizeof(int), tmp);
bsearch(&key, a, n, sizeof(int), cmp);
*/
#define N 50010
int pa[N];
int findset(int u){
if(pa[u]!=u)
pa[u] = findset(pa[u]);
return pa[u];
}
int main(){
#ifdef QWERTIER
freopen("in.txt","r",stdin);
#endif
int kase = 1, i, n, m;
while(scanf("%d%d",&n,&m) && n){
for(i = 1; i <= n; i++)
pa[i] = i;
int ans = n;
while(m--){
int u, v;
scanf("%d%d",&u,&v);
if(findset(u) != findset(v)){
pa[pa[u]] = pa[v];
ans--;
}
}
printf("Case %d: %d\n", kase++, ans);
}
return 0;
}
|
C
|
#include<stdio.h>
main()
{
int i=10,j=20,k=30;
int *p[3];
p[0]=&i;
p[1]=&j;
p[2]=&k;
printf("%d %d %d\n",*p[0],*p[1],*p[2]);
}
|
C
|
/*
* mode.c
*
* Copyright 2012 James Cowgill
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Created on: 13 Jan 2012
* Author: james
*/
#include "chaff.h"
#include "io/mode.h"
#include "io/fs.h"
//Determines if the given security context can read / write / execute the file with the given mode and ids
bool IoModeCanAccess(IoMode accessMode, IoMode mode, unsigned int uid, unsigned int gid,
SecContext * secContext)
{
//Test root
if(secContext->euid == 0)
{
return true;
}
//Test user permissions
if(secContext->euid == uid)
{
return mode & accessMode;
}
else if(secContext->egid == gid)
{
return mode & (accessMode << 3);
}
else
{
return mode & (accessMode << 6);
}
}
//Determines if the given security context can read / write / execute the file with the given iNode
bool IoModeCanAccessINode(IoMode accessMode, IoINode * iNode, SecContext * secContext)
{
return IoModeCanAccess(accessMode, iNode->mode, iNode->uid, iNode->gid, secContext);
}
|
C
|
#ifndef PWM_ANALYZER_H
#define PWM_ANALYZER_H
/************ Include Files ************/
#include "xil_types.h"
#include "xstatus.h"
/************ Macro Definitions ************/
#define OFF_TIME_OFFSET 0
#define ON_TIME_OFFSET 4
#define PERIOD_OFFSET 8
/**************************** Type Definitions *****************************/
/**
*
* Write a value to a PWM_ANALYZER register. A 32 bit write is performed.
* If the component is implemented in a smaller width, only the least
* significant data is written.
*
* @param BaseAddress is the base address of the PWM_ANALYZERdevice.
* @param RegOffset is the register offset from the base to write to.
* @param Data is the data written to the register.
*
* @return None.
*
* @note
* C-style signature:
* void PWM_ANALYZER_mWriteReg(u32 BaseAddress, unsigned RegOffset, u32 Data)
*
*/
#define PWM_ANALYZER_mWriteReg(BaseAddress, RegOffset, Data) \
Xil_Out32((BaseAddress) + (RegOffset), (u32)(Data))
/**
*
* Read a value from a PWM_ANALYZER register. A 32 bit read is performed.
* If the component is implemented in a smaller width, only the least
* significant data is read from the register. The most significant data
* will be read as 0.
*
* @param BaseAddress is the base address of the PWM_ANALYZER device.
* @param RegOffset is the register offset from the base to write to.
*
* @return Data is the data from the register.
*
* @note
* C-style signature:
* u32 PWM_ANALYZER_mReadReg(u32 BaseAddress, unsigned RegOffset)
*
*/
#define PWM_ANALYZER_mReadReg(BaseAddress, RegOffset) \
Xil_In32((BaseAddress) + (RegOffset))
/************************** Function Prototypes ****************************/
/**
*
* Run a self-test on the driver/device. Note this may be a destructive test if
* resets of the device are performed.
*
* If the hardware system is not built correctly, this function may never
* return to the caller.
*
* @param baseaddr_p is the base address of the PWM_ANALYZER instance to be worked on.
*
* @return
*
* - XST_SUCCESS if all self-test code passed
* - XST_FAILURE if any self-test code failed
*
* @note Caching must be turned off for this function to work.
* @note Self test may fail if data memory and device are not on the same bus.
*
*/
XStatus PWM_ANALYZER_Reg_SelfTest(void * baseaddr_p);
/************ Function Prototypes ************/
u32 getDutyCycle_percent(u32 baseAddr);
double getDutyCycle_decFrac(u32 baseAddr);
/****** Data in milliseconds (ms) ******/
u32 getOffTime_ms(u32 baseAddr, int clk_freq);
u32 getOnTime_ms(u32 baseAddr, int clk_freq);
u32 getPeriod_ms(u32 baseAddr, int clk_freq);
/****** Data in microseconds (us) ******/
u32 getOffTime_us(u32 baseAddr, int clk_freq);
u32 getOnTime_us(u32 baseaddr, int clk_freq);
u32 getPeriod_us(u32 baseAddr, int clk_freq);
/****** Data in nanoseconds (ns) ******/
u32 getOffTime_ns(u32 baseAddr, int clk_freq);
u32 getOnTime_ns(u32 baseAddr, int clk_freq);
u32 getPeriod_ns(u32 baseAddr, int clk_freq);
/****** Data in clock edges ******/
u32 getOffTime_clkEdges(u32 baseAddr);
u32 getOnTime_clkEdges(u32 baseAddr);
u32 getPeriod_clkEdges(u32 baseAddr);
#endif // PWM_ANALYZER_H
|
C
|
///file:evaluate.h
///description:interface for evaluating arithmetic and boolean expressions
///author: avv8047 : Azhur Viano
#ifndef EVALUATE_H
#define EVALUATE_H
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include "stack.h"
#include "symbolTable.h"
#define INITIAL_SIZE 20
//Types for a token, used for converting to postfix
typedef enum token_type {Operator, Operand, LParenthesis,
RParenthesis} TokenType;
//Token for an operand, operator, or parantheses
typedef struct Token_ {
//type of the toke, operand, operator, or parenthesis
TokenType type;
//type of value, Float or Integer
Type valType;
//value of the token
Value value;
} Token;
//Check whether a string is a float
//@param str a null terminated string
//@returns 1 if the string is a float, 0 otherwise
int isFloat(char* str);
//Evaluate an infix expression
//@param table the symbol table to use
//@returns a token struct containing an int or float,
// or NULL if the evaluation failed
Token* evaluateExpression(SymbolTable* table, char* expression);
#endif
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* fractol_BurningShip.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: hcharlsi <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/06/12 19:49:20 by hcharlsi #+# #+# */
/* Updated: 2021/06/12 19:49:21 by hcharlsi ### ########.fr */
/* */
/* ************************************************************************** */
#include "fractol.h"
typedef struct s_fractal_BS
{
t_complex z;
int x;
int y;
int n;
float z_tmp;
float z_re;
float z_im;
} t_fractal_BS;
static int fract_func_BS(t_fractal_BS fract)
{
fract.n = -1;
while (++fract.n < MAXITER)
{
fract.z_tmp = fract.z.re * fract.z.re - fract.z.im * fract.z
.im + fract.z_re;
fract.z.im = fabsf(2 * fract.z.re * fract.z.im) + fract.z_im;
fract.z.re = fract.z_tmp;
if (complex_abs(fract.z) > 4)
break ;
}
return (fract.n);
}
void fractol_BurningShip(t_scene *scene)
{
t_fractal_BS fract;
fract.x = -1;
while (++fract.x < scene->width)
{
fract.y = -1;
while (++fract.y < scene->height)
{
fract.z_re = ((float)fract.x - scene->O1.x) / ((float)
scene->width / 4 * scene->scale);
fract.z_im = -(scene->O1.y - (float)fract.y) / ((float)
scene->height / 4 * scene->scale);
fract.z = complex_init(fract.z_re, fract.z_im);
fract.n = fract_func_BS(fract);
if (fract.n != MAXITER)
my_mlx_pixel_put(scene, fract.x, fract.y, GREEN + (float)
fract.n / (MAXITER - 1) * (RED - GREEN));
else
my_mlx_pixel_put(scene, fract.x, fract.y, BLACK);
}
}
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct Product
{
char* name;
double price;
};
struct ProductStock
{
struct Product product;
int quantity;
};
struct Shop
{
double cash;
struct ProductStock stock[20];
int index;
};
struct Customer
{
char* name;
double budget;
struct ProductStock shoppingList[10];
int index;
};
int main(){
// name price quanitiy arrayPosition
// Coke Can 1.1 100 0
// Bread 0.7 30 1
// Spaghetti 1.2 100 2
// Tomato Sauce 0.8 100 3
// Bin Bags 2.5 4 4
printf("--------------------------------------------------\n\n");
printf("-------- Welcome to the corner store -------------\n\n");
printf("---------current stock-----------------------------\n");
}
|
C
|
#include <ncurses.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
int main(int argc, char *argv[]) {
int window_height = 20;
int window_width = 60;
char *text = "MOVE-ME TO SEE THE COLORS :D";
time_t t;
srand((unsigned)time(&t));
initscr();
noecho();
WINDOW *win = newwin(window_height, window_width, 0, 0);
WINDOW *stats = newwin(7, window_width, window_height, 0);
box(win, 0, 0);
refresh();
box(stats, 0, 0);
if(has_colors() == FALSE) { // Check if the therminal suport colors
mvwprintw(win, 2, 2, "your terminal don't suport colors :(");
getch();
return 1;
} else {
mvwprintw(win, 3, 2, "great, your terminal support colors !");
mvwprintw(win, 4, 2, "press any arrow key to start");
}
start_color(); // This is necessary to work with colors
init_pair(1, COLOR_BLACK, COLOR_WHITE); // Init a color pair to use as attr
init_pair(2, COLOR_BLACK, COLOR_RED);
init_pair(3, COLOR_BLACK, COLOR_GREEN);
init_pair(4, COLOR_BLACK, COLOR_MAGENTA);
init_pair(5, COLOR_BLACK, COLOR_YELLOW);
init_pair(6, COLOR_BLACK, COLOR_BLUE);
init_pair(7, COLOR_BLACK, COLOR_CYAN);
init_pair(8, COLOR_RED, COLOR_WHITE);
init_pair(9, COLOR_RED, COLOR_YELLOW);
init_pair(10, COLOR_RED, COLOR_GREEN);
init_pair(11, COLOR_RED, COLOR_CYAN);
init_pair(12, COLOR_RED, COLOR_BLUE);
init_pair(13, COLOR_RED, COLOR_MAGENTA);
init_pair(14, COLOR_RED, COLOR_BLACK);
init_pair(15, COLOR_GREEN, COLOR_WHITE);
init_pair(16, COLOR_GREEN, COLOR_YELLOW);
init_pair(17, COLOR_GREEN, COLOR_RED);
init_pair(18, COLOR_GREEN, COLOR_CYAN);
init_pair(19, COLOR_GREEN, COLOR_BLUE);
init_pair(20, COLOR_GREEN, COLOR_MAGENTA);
init_pair(21, COLOR_GREEN, COLOR_BLACK);
wattron(win, COLOR_PAIR(1)); // Apply the attr
mvwprintw(win, 1, 3, "now let's learn how to use colors");
wattroff(win, COLOR_PAIR(1)); // Remove the attr
move(5, 3);
wrefresh(win);
int y_index = (int)(window_height/2);
int x_index = (int)(window_width/2)-(int)(strlen(text)/2)-2;
int ch;
while(1) {
ch = getch();
int randint = (rand() % 21)+1;
if(y_index == 1 && ch == 65) {
y_index = window_height-1;
} else if (y_index == window_height - 2 && ch == 66) {
y_index = 0;
}
if(x_index <= 1 && ch == 68) {
x_index = window_width-1;
} else if (x_index >= window_width - 1 && ch == 67) {
x_index = 0;
}
switch(ch) {
case 65:
y_index-=1;
break;
case 66:
y_index+=1;
break;
case 67:
x_index+=2;
break;
case 68:
x_index-=2;
break;
default:
continue;
break;
}
wclear(win);
wclear(stats);
mvwprintw(stats, 1, 2, "color pair :");
mvwprintw(stats, 3, 2, "key pressed :");
mvwprintw(stats, 5, 2, "x / y coordinates :");
wattron(stats, COLOR_PAIR(randint));
mvwprintw(stats, 1, 25, "%d", randint);
mvwprintw(stats, 3, 25, "%d", ch);
mvwprintw(stats, 5, 25, "%d, %d", x_index, y_index);
wattroff(stats, COLOR_PAIR(randint));
wattron(win, COLOR_PAIR(randint));
mvwprintw(win, y_index, x_index, text);
wattroff(win, COLOR_PAIR(randint));
box(win, 0, 0);
box(stats, 0, 0);
wrefresh(stats);
wrefresh(win);
}
endwin();
return 0;
}
|
C
|
#ifndef __ALGORITHM_H
#define __ALGORITHM_H
#ifdef __ALGORITHM_C
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <stdio.h>
#include <limits.h>
typedef uint8_t bool;
#define true 1
#define false 0
#include "lib_export.h"
#include "hashmap.h"
#include "lib_export.h"
#include "fm.h"
/*
* Maximum change making sum after dividing sum with 10 ^ n, where
* n is the maximum common base 10 exponant.
* Solving change making problem this amount of cash
* uses at least 16mb of memory on stack
*/
#define MAX_CHANGE_SUM 1000000
/*
* This function attempts to fill all the missing sum
* cash caps with smaller bills
*/
static void __al_FillCashCaps (
CashStatus *p_ch,
CashStatus *p_cur,
size_t sum,
size_t beg
);
/* Perform merge sort algorithm on banknote values */
static void __al_CashValMergeSort (
CashStatus *p_in,
size_t beg,
size_t end,
CashStatus *p_tmp
);
/* Find the minimum common base 10 exponent for banknotes */
static uint16_t __al_FindMinCashBase10Exp (
CashStatus *p_cs,
uint64_t beg,
uint64_t end
);
/*
* Find the smallest needed amount of banknotes
* NOTE: p_ch_data must have a capacity of atleast banknote_c in p_cs
*/
static uint64_t __al_ChangeFinder (
SafeFloat *p_val,
CashStatus *p_cs,
CashStatus *p_ch_data
);
/*
* Perform linear search for n bytes to cmp in arr
* RETURN: index of the found instance (ULONG_MAX if not found)
*/
static size_t __al_linsearch (
void *arr,
size_t size,
size_t n,
void *cmp
);
#endif
/*
* Error codes:
* 0 - success
* 1 - cash handling limit reached
* 2 - not enough cash in atm
* 3 - invalid source currency code
* 4 - invalid destination currency code
*/
typedef enum WDRErrorCodes {
WDR_SUCCESS = 0,
WDR_ERR_CASH_HANDLING_LIMIT_REACHED = 1,
WDR_ERR_NOT_ENOUGH_CASH = 2,
WDR_ERR_INVALID_SRC_CURRENCY_CODE = 3,
WDR_ERR_INVALID_DST_CURRENCY_CODE = 4
} WDRErrorCodes;
/*
* Store information about currency conversion
*/
typedef struct WithdrawReport {
CashStatus cs;
SafeFloat unexchanged;
WDRErrorCodes error_code;
} WithdrawReport;
// For debugging
#ifdef __ALGORITHM_C
#include "converter.h" // sprintSafeFloat()
#endif
#if !defined(__USER_C) || !defined(_WIN32)
/*
* Use merge sort algorithm to sort all currency banknotes
* by value in ascending order
*/
LIB_EXPORT void CALL_CON al_SortBankNotes(CashStatus *p_cs);
/* 64 bit integer exponentiation */
LIB_EXPORT uint64_t CALL_CON al_pow(uint64_t base, uint64_t exp);
/**************************************************/
/******** Algorithms for money withdrawal *********/
/**************************************************/
/*
* Withdraw as much cash as possible
*/
LIB_EXPORT WithdrawReport CALL_CON al_WithdrawMaxBillsC (
SafeFloat *p_val,
CurrencyInfo *p_cur
);
/*
* Withdraw as little cash as possible
*/
LIB_EXPORT WithdrawReport CALL_CON al_WithdrawMinBillsC (
SafeFloat *p_val,
CurrencyInfo *p_cur
);
/*
* Withdraw as much different banknotes as possible
*/
LIB_EXPORT WithdrawReport CALL_CON al_WithdrawDifBillsC (
SafeFloat *p_val,
CurrencyInfo *p_cur
);
#endif
#endif
|
C
|
#include <sys/file.h>
#include <sys/mman.h>
#include <assert.h>
#include "blant.h"
const char* _BLANT_DIR = DEFAULT_BLANT_DIR;
// Given a TINY_GRAPH and k, return the integer ID created from one triangle (upper or lower) of the adjacency matrix.
Gint_type TinyGraph2Int(TINY_GRAPH *g, int k)
{
int i, j, bitPos=0, bit;
Gint_type Gint = 0;
#if LOWER_TRIANGLE // Prefer lower triangle to be compatible with Ine Melckenbeeck's Jesse code.
for(i=k-1;i>0;i--)
{
for(j=i-1;j>=0;j--)
#else // UPPER_TRIANGLE // this is what we used in the original faye code and paper with Adib Hasan and Po-Chien Chung.
for(i=k-2;i>=0;i--)
{
for(j=k-1;j>i;j--)
#endif
{
if(TinyGraphAreConnected(g,i,j))
{
bit = (1 << bitPos);
Gint |= bit;
}
bitPos++;
}
}
return Gint;
}
/*
** Given an integer, build the graph into the TINY_GRAPH *G, which has already been allocated.
** Handles either upper or lower triangle representation depending upon compile-time option below.
*/
void Int2TinyGraph(TINY_GRAPH* G, Gint_type Gint)
{
int i, j, bitPos=0, k = G->n;
Gint_type Gint2 = Gint; // Gint2 has bits nuked as they're used, so when it's zero we can stop.
TinyGraphEdgesAllDelete(G);
#if LOWER_TRIANGLE
for(i=k-1;i>(0-SELF_LOOPS);i--) // note that when SELF_LOOPS, the loop condition i (-1), so i must be signed.
{
for(j=i-!SELF_LOOPS;j>=0;j--)
#else // UPPER_TRIANGLE
assert(!SELF_LOOPS);
for(i=k-2;i>=0;i--)
{
for(j=k-1;j>i;j--)
#endif
{
if(!Gint2) break;
int bit = (1 << bitPos);
if(Gint & bit)
TinyGraphConnect(G,i,j);
Gint2 &= ~bit;
bitPos++;
}
if(!Gint2) break;
}
}
/*
** Given a pre-allocated filename buffer, a 256MB aligned array K, num nodes k
** Mmap the canon_map binary file to the aligned array.
*/
short int* mapCanonMap(char* BUF, short int *K, int k) {
#if SELF_LOOPS
if (k > 7) Fatal("cannot have k>7 when SELF_LOOPS");
int Bk = (1 <<(k*(k+1)/2));
#else
int Bk = (1 <<(k*(k-1)/2));
#endif
sprintf(BUF, "%s/%s/canon_map%d.bin", _BLANT_DIR, CANON_DIR, k);
int Kfd = open(BUF, 0*O_RDONLY);
assert(Kfd > 0);
//short int *Kf = Mmap(K, Bk*sizeof(short int), Kfd); // Using Mmap will cause error due to MAP_FIXED flag
short int *Kf = (short int*) mmap(K, sizeof(short int)*Bk, PROT_READ, MAP_PRIVATE, Kfd, 0);
assert(Kf != MAP_FAILED);
return Kf;
}
SET *canonListPopulate(char *BUF, Gint_type *canon_list, int k, int *canon_num_edges) {
sprintf(BUF, "%s/%s/canon_list%d.txt", _BLANT_DIR, CANON_DIR, k);
FILE *fp_ord=fopen(BUF, "r");
if(!fp_ord) Fatal("cannot find %s\n", BUF);
int numCanon, i, connected;
assert(1==fscanf(fp_ord, "%d\n",&numCanon));
SET *connectedCanonicals = SetAlloc(numCanon);
for(i=0; i<numCanon; i++) {
char buf[BUFSIZ], *tmp;
tmp = fgets(buf, sizeof(buf), fp_ord);
assert(tmp == buf);
#if TINY_SET_SIZE <= 32
assert(3==sscanf(buf, "%u\t%d %d", &canon_list[i], &connected, &canon_num_edges[i]));
#elif TINY_SET_SIZE >= 64
assert(3==sscanf(buf, "%llu\t%d %d", &canon_list[i], &connected, &canon_num_edges[i]));
#else
#error "unknown size"
#endif
if(connected) SetAdd(connectedCanonicals, i);
}
fclose(fp_ord);
return connectedCanonicals;
}
int orbitListPopulate(char *BUF, int orbit_list[MAX_CANONICALS][MAX_K], int orbit_canon_mapping[MAX_ORBITS],
int orbit_canon_node_mapping[MAX_ORBITS], int numCanon, int k) {
sprintf(BUF, "%s/%s/orbit_map%d.txt", _BLANT_DIR, CANON_DIR, k);
FILE *fp_ord=fopen(BUF, "r");
if(!fp_ord) Fatal("cannot find %s\n", BUF);
int numOrbit, i, j;
assert(1==fscanf(fp_ord, "%d",&numOrbit));
for(i=0;i<numOrbit;i++)
orbit_canon_node_mapping[i] = -1;
for(i=0; i<numCanon; i++) for(j=0; j<k; j++) {
assert(1==fscanf(fp_ord, "%d", &orbit_list[i][j]));
orbit_canon_mapping[orbit_list[i][j]] = i;
if(orbit_canon_node_mapping[orbit_list[i][j]] < 0)
orbit_canon_node_mapping[orbit_list[i][j]] = j;
}
fclose(fp_ord);
return numOrbit;
}
void orcaOrbitMappingPopulate(char *BUF, int orca_orbit_mapping[58], int k) {
sprintf(BUF, "%s/%s/orca_orbit_mapping%d.txt", _BLANT_DIR, "orca_jesse_blant_table", k);
FILE *fp_ord=fopen(BUF, "r");
if(!fp_ord) Fatal("cannot find %s\n", BUF);
int numOrbit, i;
assert(1==fscanf(fp_ord, "%d",&numOrbit));
for (i=0; i<numOrbit; i++) { assert(1==fscanf(fp_ord, "%d", &orca_orbit_mapping[i])); }
}
|
C
|
#include <stdio.h>
#define maxSize 10
//STACK 1
int isFull_1();
void push_1(int);
int isEmpty_1();
int pop_1();
void show_1();
int stack_1[maxSize];
int topOfStack_1 = 0;
//STACK 2
int isFull_2();
void push_2(int);
int isEmpty_2();
int pop_2();
void show_2();
int stack_2[maxSize];
int topOfStack_2 = 0;
//STACK 3
int isFull_3();
void push_3(int);
int isEmpty_3();
int pop_3();
int stack_3[maxSize];
int topOfStack_3 = 0;
//STACK 4
int isFull_4();
void push_4(int);
int isEmpty_4();
int pop_4();
int stack_4[maxSize];
int topOfStack_4 = 0;
//Function to Compare Stacks
char* stackEqual();
int main(){
int ch = 0, item;
do{
printf("\n1.PUSH in Stack 1\n");
printf("2.POP from Stack 1\n");
printf("3.Display stack 1\n");
printf("4.PUSH in Stack 2\n");
printf("5.POP from Stack 2\n");
printf("6.Display stack 2\n");
printf("7.Compare Stacks\n");
printf("8.Exit\n");
printf("\n Enter your choice of operations : ");
scanf("%d", &ch);
switch (ch)
{
case 1:
printf("\nEnter the element to be pushed in Stack 1 : ");
scanf("%d", &item);
push_1(item);
break;
case 2:
if(isEmpty_1()){
printf("\nStack is EMPTY\n");
}else{
printf("\nElement deleted : %d", pop_1());
}
break;
case 3:
show_1();
break;
case 4:
printf("\nEnter the element to be pushed in Stack 2 : ");
scanf("%d", &item);
push_2(item);
break;
case 5:
if(isEmpty_2()){
printf("\nStack is EMPTY\n");
}else{
printf("\nElement deleted : %d", pop_2());
}
break;
case 6:
show_2();
break;
case 7:
if(isEmpty_1()){
printf("\nStack 1 is EMPTY\n");
if(isEmpty_2()){
printf("\nStack 2 is EMPTY\n");
}
}else{
printf("\nStack 1 EQUAL TO Stack 2 : %s\n",stackEqual());
}
break;
case 8:
ch = 8;
break;
default:
printf("\nIncorrect choice \n");
}
}while( ch != 8);
return 0;
}
//STACk 1
int isFull_1(){
if(topOfStack_1 == maxSize)
{
return 1;
}else{
return 0;
}
}
void push_1(int item){
if(isFull_1())
{
printf("\nStack 1 is FULL\n");
return;
}
stack_1[topOfStack_1++] = item;
}
int isEmpty_1()
{
if(topOfStack_1==0)
return 1;
return 0;
}
int pop_1(){
return stack_1[--topOfStack_1];
}
void show_1(){
int i ;
if( isEmpty_1())
printf("\nStack 1 is EMPTY\n");
else{
printf("\nStack 1 : ");
while(!(topOfStack_1 == 0)){
printf("%d ",pop_1());
}
printf("\n");
}
}
//STACK 2
int isFull_2(){
if(topOfStack_2 == maxSize)
{
return 1;
}else{
return 0;
}
}
void push_2(int item){
if(isFull_2())
{
printf("\nStack 2 is full\n");
return;
}
stack_2[topOfStack_2++] = item;
}
int isEmpty_2()
{
if(topOfStack_2 == 0)
return 1;
return 0;
}
int pop_2(){
return (stack_2[--topOfStack_2]);
}
void show_2(){
int i ;
if( isEmpty_2())
printf("Stack 2 is EMPTY\n");
else{
printf("\nStack 2: ");
while(!(topOfStack_2 == 0)){
printf("%d ",pop_2());
}
printf("\n");
}
}
//STACK 3
int isFull_3(){
if(topOfStack_3 == maxSize)
{
return 1;
}else{
return 0;
}
}
void push_3(int item){
if(isFull_3())
{
printf("\nStack 3 is full\n");
return;
}
stack_3[topOfStack_3++] = item;
}
int isEmpty_3()
{
if(topOfStack_3 == 0)
return 1;
return 0;
}
int pop_3(){
return (stack_3[--topOfStack_3]);
}
//STACK 4
int isFull_4(){
if(topOfStack_4 == maxSize)
{
return 1;
}else{
return 0;
}
}
void push_4(int item){
if(isFull_4())
{
printf("\nStack 4 is full\n");
return;
}
stack_4[topOfStack_4++] = item;
}
int isEmpty_4()
{
if(topOfStack_4 == 0)
return 1;
return 0;
}
int pop_4(){
return (stack_4[--topOfStack_4]);
}
//COMPARE FUNCTION
char* stackEqual(){
if(topOfStack_1 == topOfStack_2){
while(!(topOfStack_1 == 0)){
int elem_1 = pop_1();
int elem_2 = pop_2();
if(elem_1 == elem_2){
push_3(elem_1);
push_4(elem_2);
}else{
while(!(topOfStack_3 == 0)){
push_1(pop_3());
push_2(pop_4());
}
return "FALSE";
}
continue;
}
while(!(topOfStack_3 == 0)){
push_1(pop_3());
push_2(pop_4());
}
return "TRUE";
}
return "FALSE";
}
|
C
|
#include "general.h"
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <unistd.h>
double norma_cuadrado(double *vector, int N){//N es len(vector)
double suma = 0;
int i;
for(i=0; i<N; i++)
suma += pow(*(vector+i), 2);
return suma;
}
double gaussiana(double mu, double sigma){
int n = 10;
int i;
double z = 0;
for(i = 0; i < n; i++)
z += ((double)rand()) / ((double)RAND_MAX);
z = sqrt(12) * (z / n - 0.5);
return z*sigma+mu;
}
double mean(double *vector, int length, int k, int j){//para el mean normal, tomar k = 1, j =0.
// valor medio del puntero. Calcula el vector diezmado v[k*i+j]
// length es longitud del vector ya diezmado
int i;
double avg = 0;
for (i = 0; i < length; i++)
avg += *(vector+(k*i+j)); //recorre de a k lugares, con offset j
return(avg/length);
}
int find_nearest(double escalar, double *puntero, int longitud_puntero){//devuelve indice del puntero mas cercano al escalar
double diferencia, delta;
int indice, i;
indice = 0; //indice del mas cercano
diferencia = fabs(*puntero - escalar);
for (i=0; i < longitud_puntero; i++){ //loop i en vector
delta = fabs(*(puntero+i) - escalar);
if (delta < diferencia){ // si delta es menor que el paso anterior
diferencia = delta;
indice = i;
}
}//end loop i
return indice;
}
int contador_lineas(FILE *file){
char c;
int lines = 0;
for (c = getc(file); c != EOF; c = getc(file))
if (c == '\n') // si se encuentra un newline aumenta el contador lineas
lines += 1;
rewind(file);
return lines;
}
int leer_tabla(FILE *file, double *r_tabla, double *r2_tabla, double *f_tabla, double *v_tabla){
// argumentos: el archivo que tiene que leer y los punteros donde guarda las cosas
double r_LUT, r2_LUT, f_LUT, v_LUT;
int i=0;
while (fscanf(file, "%lf %lf %lf %lf", &r_LUT, &r2_LUT, &f_LUT, &v_LUT) == 4){
*(r_tabla+i) = r_LUT;
*(r2_tabla+i) = r2_LUT;
*(f_tabla+i) = f_LUT;
*(v_tabla+i) = v_LUT;
i += 1;
}
return 0;
}
double max(double *pointer, int longitud){
double ref;
int i;
ref = *pointer;
for(i=0; i<longitud; i++){
if(*(pointer+i) > ref)
ref = *(pointer+i);
}//end loop
return ref;
}
double min(double *pointer, int longitud){
double ref;
int i;
ref = *pointer;
for(i=0; i<longitud; i++){
if(*(pointer+i) < ref)
ref = *(pointer+i);
}//end loop
return ref;
}
double interpolar(double *pointer, int indice){
double valor;
valor = (*(pointer+indice) + *(pointer+indice+1))/2;
return valor;
}
|
C
|
#include <stdio.h>
/*
Write versions of the library functions strncpy , strncat , and strncmp , which
operate on at most the first n characters of their argument strings. For example,
strncpy(s,t,n) copies at most n characters of t to s . Full descriptions are in Appendix B.
*/
// strncpy: copy at most the first n character of t to s
void strncpy1(char *s, char *t, int n) {
int i = 1;
if (n <= 0)
return;
while ((*s++ = *t++) && i < n)
i++;
}
// strncmp: return <0 if s<t, 0 if s==t, >0 if s>t, pointer version
int strncmp1(char *s, char *t, int n) {
for (int i = 1; *s==*t && i < n; s++, t++, i++)
if (*s == '\0')
return 0;
return *s - *t;
}
// strncat: concatenate t to end of s; s must be big enough
void strncat1(char *s, char *t, int n) {
int i = 1;
if (n <= 0)
return;
while(*s++ != '\0')
;
s--; // back to '\0'
while((*s++ = *t++) && i < n)
i++;
if (*(s+i) != '\0')
*(s+i+1) = '\0';
}
int main() {
char s[100] = "12345";
char *t = "13";
int i;
strncpy1(s, t, 0);
printf("%s\n", s);
i = strncmp1(s, t, 1);
printf("%d\n", i);
strncat1(s, t, 0);
printf("%s\n", s);
return 0;
}
|
C
|
/*Flores Fuentes Kevin Torres Verástegui José Antonio Fecha de elaboración: 20/Febrero/2020*/
/*
Programa shell que se encarga de ejecutar el comando dado, puede ejecutar dos comandos en una sola linea gracias al pipe, el programa funciona a través de apuntadores para referirse a la linea del comando dado y poder separarla de ser el caso,la función execvp() que ejecuta el comando dado, en caso de una fallo devuelve un valor negativo y de esta manera identificamos si hay un comando erroneo o inexistente, y por último e importante la función fork para crear procesos y poder ejecutarlos de manera efectiva a través del proceso padre y sus posibles procesos hijos.
El comando en si pide el comando a ejecutar, después de ello entra a una función llamada ejecutar donde se crean los procesos padre e hijo el padre espera a que acabe el hijo, el hijo por su parte identifica si el comando contiene un pipe o no, de ser el caso entra a la función separaPipe donde esta misma se obtendrá los dos comandos, el comando izquierdo lo ejecutará el hijo mientras que el comando derecho lo ejecutara un nieto creado por el proceso hijo a continuación se detalla mejor el código.
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
void separar (char *input, char **argv);/*Función que se encarga de obtener el comando sin imperfecciones como espacios*/
void ejecutar (char input[1024]);/*Función que se encarga de ejecutar todos los comandos después de ser dados*/
int isPipe(char **argv);/*Función que identifica si el comando dado cuenta con pipe*/
void separaPipe(char **argv,char **beforePipe, char **afterPipe);/*Función que separa y obtiene los dos comandos si existe el pipe*/
void main () {
char input[1024];/*Pedirá un comando mientras la salida no sea 1, esto solo sucederá cuando se coloque salir*/
char *argv[64];
while (1) {
printf("Comando ->: ");
fgets(input, sizeof(input), stdin);
char *p = strchr(input, '\n');
if (p) *p = '\0'; //Cambia el salto de línea del final de la cadena por un caracter nulo
ejecutar(input);/*Manda el comando a ejecutar a la función ejecutar*/
}
}
void ejecutar (char input[1024]) {
char *argv[64];
pid_t pid1, pid2;/*Crea los pids*/
pid1 = fork(); /*Crea el proceso hijo*/
if (pid1) {
//padre
int estado = 0;
wait(&estado);/*Esperará a que el proceso hijo acabe su proceso*/
if ((estado >> 8) == 24) {
exit(1);/*Si el proceso regresa un estado de 24 significa que se ha escrito salir,acaba el proceso y manda 1 para acabar el código*/
}
}
else {
//hijo
separar(input, argv);/*Separa el comando de salto de lineas y tabulaciones*/
if (!strcmp(*argv, "salir")) {/*SI el comando de entrada es salir se acaba el proceso y mando 24 para acabar el codigo*/
exit(24); // For Kobe
}
if (isPipe(argv)) {/*Si el comando contiene | la función regresa 1 y entra en el if*/
char *beforePipe[64], *afterPipe[64];/*Crea dos arreglos para guardar los dos comandos (antes y después del pipe)*/
int pipefd[2];
separaPipe(argv, beforePipe, afterPipe);/*La función separa los comandos y los guarda en beforepipe y afterpipe respectivamente*/
pipe(pipefd);/*Crea el pipe*/
pid2 = fork();/*Creación del proceso nieto*/
if (pid2) {
//hijo
int estado = 0;
wait(&estado);
close(0);// Cierra la entrada estándar
close(pipefd[1]);
dup(pipefd[0]);// Entrada estándar es el pipe
execvp(*afterPipe, afterPipe);/*Ejecuta el comando después del |*/
if ((estado >> 8) == 8) {
printf("Error, comando '%s' no encontrado \n", *beforePipe);
}
printf("Error, comando '%s' no encontrado \n", *afterPipe);
exit(0);
}
else {
//nieto
close(1); //Se cierra la salida estándar
close(pipefd[0]);
dup(pipefd[1]); // La salida estándar va a ser pipefd[1]
execvp(*beforePipe, beforePipe);/*Ejecuta el comando antes del |*/
exit(8);
}
}
else {
execvp(*argv, argv);
printf("Error, comando '%s' no encontrado \n", *argv);
exit(0);
}
}
}
void separar (char *input, char **argv) {
while (*input != '\0') {
while (*input == ' '){ // Revisa si hay espacios
*input = '\0'; // Cambia espacios por caracteres nulos
input++; // Avanza al siguiente elemento
}
*argv = input; // Guarda la ubicación de la palabra
argv++; // Avanza al siguiente elemento
while (*input != '\0' && *input != ' ') { //Si no hay espacios, tabuladores, o caracteres vacíos (insertados por los espacios)
if (*input == '|') { // Caso en el que hay un pipe pero no hay espacios antes y después del pipe
*argv = input; // Se guarda la posición del pipe
argv++;
input++;
break; //Se sigue a revisar la siguiente palabra
}
input++; //Avanza al siguiente caracter de la palabra
}
}
*argv = (char *) 0; //El último elemento es un carácter nulo
}
void separaPipe(char **argv,char **beforePipe, char **afterPipe) {
int flag = 0; // Bandera para saber si ya se pasó el punto en elq ue está el pipe
while (*argv != (char *) 0) {
if (**argv == '|') { // Si se encuentra el pipe
flag = 1;
}
else {
if (flag) {
*afterPipe = *argv; //Comando que están después del pipe
*afterPipe++;
}
else {
*beforePipe = *argv;//Comando que está antes del pipe
char *p = strchr(*beforePipe, '|'); // Revisa si el pipe está en el comando para casos en los que no hay espacios entre el pipe
if (p){
*p = '\0'; // Cambia el pipe por nulo
flag = 1;
*argv++;
}
*beforePipe++;
}
}
*argv++;
}
*beforePipe = (char *) 0; //Agraga caracteres nulos al final de los vectores de comandos
*afterPipe = (char *) 0;
}
//Revisa si hay pipe en la instrucción
int isPipe(char **argv) {
while (*argv != (char *) 0) {
if (**argv == '|') {
return 1;
}
*argv++;
}
}
/*Conclusiones:
Kevin FLores Fuentes:
La importencia de la comprensión de las llamadas al sistema es muy importante,
y más para la materia de SO, creo que este programa de shell hizo que comprendiera
mejor el uso adecuado de la creación de procesos con fork(), asi como el uso debido
de las entradas y salidas con pipe, y por supuesto como execvp() lográ ejecutar un
comando en linux, me pareció un buen programa para comprender y mejorar la
iniciación de las llamadas al sistema.
José Antonio Torres Verástegui:
El desarrollo de este programa fue de gran utilidad para comprender y aplicar el uso
de las llamadas al sistema vistas en clase, y sobre todo por desarrollar un elemento
de software tan importante como lo es un shell (intérprete de comandos). Desde mi punto
de vista, la mayor dificultad de este software radicó en separar las palabras introducidas
(comandos) e identificar el pipe, sobre todo porque el pipe puede estar o no entre espacios.
*/
|
C
|
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
/* Type definitions */
/* Variables and functions */
int FALSE ;
scalar_t__ ISDIGIT (char const) ;
int TRUE ;
size_t strlen (char const*) ;
scalar_t__ strncasecompare (char const*,char const*,size_t) ;
__attribute__((used)) static bool imap_matchresp(const char *line, size_t len, const char *cmd)
{
const char *end = line + len;
size_t cmd_len = strlen(cmd);
/* Skip the untagged response marker */
line += 2;
/* Do we have a number after the marker? */
if(line < end && ISDIGIT(*line)) {
/* Skip the number */
do
line++;
while(line < end && ISDIGIT(*line));
/* Do we have the space character? */
if(line == end || *line != ' ')
return FALSE;
line++;
}
/* Does the command name match and is it followed by a space character or at
the end of line? */
if(line + cmd_len <= end && strncasecompare(line, cmd, cmd_len) &&
(line[cmd_len] == ' ' || line + cmd_len + 2 == end))
return TRUE;
return FALSE;
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <stdlib.h>
int main()
{
unsigned int w = 0x12345678;
unsigned int z = 0;
z = ((w >> 24) & 0xFF) | \
((w >> 8) & 0xFF00) | \
((w << 8) & 0xFF0000) | \
((w << 24) & 0xFF000000) ;
printf("0x%x and 0x%x \n",w,z);
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* check_square.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: youkhart <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/12/25 21:59:22 by youkhart #+# #+# */
/* Updated: 2019/12/25 21:59:23 by youkhart ### ########.fr */
/* */
/* ************************************************************************** */
#include "parser.h"
extern struct s_minirt g_rt;
static int check_square1(char **tab, int n)
{
if (tab_len(tab) != 5)
{
ft_printf("Error in line %d:\n\
[!] Incorrect number of arguments for square, \
correct format 'sq 0.0,0.0,20.6 1.0,0.0,0.0 12.6 255,0,255'\n", n);
return (0);
}
if (!is_pos_vector(tab[1]))
{
ft_printf("Error in line %d:\n\
[!] Incorrect position vector, should be in format '-50,0,20'\n", n);
return (0);
}
return (1);
}
static int check_square2(char **tab, int n)
{
if (!is_norm_dir_vector(tab[2]))
{
ft_printf("Error in line %d:\n\
[!] Incorrect normalized orientation vector, \
should be values in range [-1.0 , 1.0] in format '-0.1,0.0,0.8'\n", n);
return (0);
}
if (!is_float(tab[3]) || ft_atof(tab[3]) < 0)
{
ft_printf("Error in line %d:\n\
[!] Incorrect value for square side size, \
should be greater than zero\n", n);
return (0);
}
if (!is_color(tab[4]))
{
ft_printf("Error in line %d:\n\
[!] Incorrect color, should be RGB colors in range \
[0 , 255] in this format '255,255,255'\n", n);
return (0);
}
return (1);
}
int check_info_square(char **tab, int n)
{
if (!check_square1(tab, n) || !check_square2(tab, n))
return (0);
return (1);
}
|
C
|
/* PMSIS includes */
#include "pmsis.h"
/* --------- */
/* constants */
/* --------- */
#define NB_DEVICES (4)
#define DATA_SIZE (100)
/* --------- */
/* variables */
/* --------- */
static pi_device_t udma_datamove_device[NB_DEVICES] = {0};
static pi_udma_datamove_conf_t conf[NB_DEVICES] = {0};
static uint8_t src_data[NB_DEVICES][DATA_SIZE * (2 * NB_DEVICES)];
static uint8_t dst_data[NB_DEVICES][DATA_SIZE * (2 * NB_DEVICES)];
/* ---------------- */
/* static functions */
/* ---------------- */
/* main test */
static void test_2d_2d(void)
{
/* open a bunch of datamove devices */
printf("Opening devices\n");
for (size_t j = 0; j < NB_DEVICES; j++)
{
pi_udma_datamove_conf_init(&conf[j]);
/* configure */
conf[j].device_id = j % 2;
conf[j].src_trf_cfg.type = PI_UDMA_DATAMOVE_TRF_2D;
conf[j].src_trf_cfg.row_len = (j+1);
conf[j].src_trf_cfg.stride = ((2*j)+1);
conf[j].dst_trf_cfg.type = PI_UDMA_DATAMOVE_TRF_2D;
conf[j].dst_trf_cfg.row_len = (j+1);
conf[j].dst_trf_cfg.stride = ((2*j)+1);
/* open */
pi_open_from_conf(&udma_datamove_device[j], &conf[j]);
int ret = pi_udma_datamove_open(&udma_datamove_device[j]);
if (0 != ret)
{
pmsis_exit(-1);
}
}
/* initializing data */
size_t dst_data_size = sizeof(dst_data[0])/sizeof(dst_data[0][0]);
size_t src_data_size = sizeof(src_data[0])/sizeof(src_data[0][0]);
printf("Initializing data [size: %d & %d]\n", src_data_size, dst_data_size);
for (size_t j = 0; j < NB_DEVICES; j++)
{
for (size_t k = 0; k < src_data_size; k++)
{
src_data[j][k] = (k + j) % 100;
}
for (size_t k = 0; k < dst_data_size; k++)
{
dst_data[j][k] = j % 100;
}
}
/* copy data */
printf("Copying data\n");
for (size_t j = 0; j < NB_DEVICES; j++)
{
pi_udma_datamove_copy(&udma_datamove_device[j], src_data[j], dst_data[j], DATA_SIZE);
}
/* verify data */
printf("Verifying data\n");
for (size_t j = 0; j < NB_DEVICES; j++)
{
const int32_t row_len = (j+1);
const int32_t stride = (2*j) + 1;
int32_t row_counter = 0;
int32_t stride_counter = 0;
for (size_t k = 0; k < DATA_SIZE; k++)
{
if (row_counter >= row_len)
{
row_counter = 0;
stride_counter++;
}
int index_2d = row_counter + stride * stride_counter;
if (src_data[j][index_2d] != dst_data[j][index_2d])
{
printf("ERROR(p%d-#%d): expected %x, got %x\n", j, k, src_data[j][index_2d], dst_data[j][index_2d]);
pmsis_exit(-1);
}
row_counter++;
}
}
/* close devices */
printf("Closing devices\n");
for (size_t j = 0; j < NB_DEVICES; j++)
{
pi_udma_datamove_close(&udma_datamove_device[j]);
}
pmsis_exit(0);
}
/* -------------- */
/* Program Entry. */
/* -------------- */
int main(void)
{
printf("\n\n\t *** PMSIS UDMA DATAMOVE 2D/2D Tests ***\n\n");
return pmsis_kickoff((void *) test_2d_2d);
}
|
C
|
#include<stdio.h>
void Display()
{
int i = 0;
for( i = 5 ; i>=1 ;i-- )
{
printf("%d\n",i);
}
}
int main()
{
Display();
return 0;
}
|
C
|
#include <stdio.h>
/**字符型数据相关处理**/
int main()
{
/**int c;
c = getchar();
while(c != EOF)
{
putchar(c);
c = getchar();
}**/
/**while((c=getchar()) != EOF)
{
putchar(c);
}**/
long nc;
nc = 0;
while(getchar() != EOF)
{
++nc;
}
printf("%ld\n", nc);
return 0;
}
/**
输入输出按照字符流的方式处理
文本流由多行字符构成的字符序列,每行字符由0个或多个字符组成,行末是换行符\n
标准库提供了一次读/写一个字符的函数,最简单的是getchar 和 putchar
c = getchar()
文本复制
读一个字符
while(该字符不是文件结束指示符)
{
输出刚读入的字符
读下一个字符
}
char专门用于存储字符型数据,任何整型也可以用于存储字符型数据
如何区分有效数据和结束符?没有输入时,getchar返回一个特殊值EOF(endoffile)
我们在声明c时,必须让它大到足以存放getchar返回的任何值,所以不把c声明称char
**/
|
C
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include "def.h"
int intArray[BufSize];
int front = 0;
int rear = -1;
int itemCount = 0;
int peek(){
return intArray[front];
}
bool isEmpty(){
return itemCount == 0;
}
bool isFull(){
return itemCount == BufSize;
}
int qsize(){
return itemCount;
}
void insert(int data){
if(!isFull()){
if(rear == BufSize-1){
rear = -1;
}
intArray[++rear] = data;
itemCount++;
}
}
int removeData(){
int data = intArray[front++];
if(front == BufSize){
front = 0;
}
itemCount--;
return data;
}
void copyData(int * array){ //copy to array
int i;
for(i=0;i<itemCount;i++){
array[i] = intArray[i];
}
}
void insertCopyData(int * array, int arraySize){ //insert array with arraySize to queue
int i;
for(i=0;i<arraySize;i++){
insert(array[i]);
}
}
void freequeue(){
free(intArray);
}
|
C
|
/*
*ļ
*ߣ
*ڣ2020918
*/
#define _CRT_SECURE_NO_WARNINGS 1
#include "game.h"
int main()
{
srand((unsigned int)time(NULL));
int input = 0;
/*char arr[ROW][COL] = { 0 };*/
do
{
Welcome();
printf("ѡ:>\n");
input = getch();
switch (input)
{
case '1':PlayGame();
break;
case '0':printf("˳Ϸ\n");
break;
default:printf("\n");
break;
}
} while (input);
return 0;
}
|
C
|
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
#define N 2
struct v
{
int i;//Row
int j;//Column
};
int A[N][N] = { { 1,2 },{ 3,4 } };//Matrix 1
int B[N][N] = { { 2,3 },{ 4,5 } };//Matrix 2
int C[N][N];//Resulting Matrix
static void * fnc(void *arg)
{
struct v *data = (struct v *)arg;
int l;
for (l = 0; l<N; l++)
{
int i = ((struct v*)data[l]).i;//Row No
int j = ((struct v*)data[l]).j;//Column No
int accumulator = 0;
int d, sum = 0;
for (d = 0; d < N; d++)
{
sum = sum + A[i][d] * B[d][j];
}
C[i][j] = sum;
sum = 0;
}
return;
}
int main()
{
pthread_t threads[N];
int i, k;
for (i = 0; i<N; i++)
{
struct v *data[N];
for (k = 0; k<N; k++)
{
data[k] = (struct v *)malloc(sizeof(struct v));
data[k].i = i; //assign the row of C for thread to calculate
data[k].j = k; //assign the column of C for thread to calculate
}
//In this example it creates 2 threads with passing data.
//Data consists of row and column pairs for each thread, that will be calcuting the pairs.
//Consider first iteration of this loop:
//Thread 1 is created and data consists of (0,0) and (0,1) which are the targeted calculation cells for thread 1.
//In the second iteration: Thread 2 will have (1,0) and (1,1) pairs in its data.
pthread_create(&threads[i], NULL, fnc, data);
}
for (i = 0; i < N; i++)
pthread_join(threads[i], NULL);
for (i = 0; i < N; i++)
for (k = 0; k < N; k++)
printf("%d\t", C[i][k]);
return 0;
}
|
C
|
//Nome do programa: deithel.c
//Nome do Autor: Eduardo Felizardo Cândido
//Data de Criação: 29/06/2019
//Descrição ou Finalidade:
/*Um jogador lança dois dados. Cada dado tem seis faces. Essas faces contêm 1, 2, 3, 4, 5 e 6 pontos. Depois que os dados param, a soma dos pontos nas duas faces voltadas para cima é calculada. Se a soma for 7 ou 11 na primeira jogada, o jogador vence. Se a soma for 2, 3 ou 12 na primeira jogada (chamado ‘craps’), o jogador perde (ou seja, a ‘casa’ vence). Se a soma for 4, 5, 6, 8, 9 ou 10 na primeira jogada, então a soma se torna o 'ponto' do jogador. Para vencer, o jogador precisa continuar lançando os dados até que 'faça seu ponto'. O jogador perde lançando um 7 antes de fazer o ponto. */
/* Fig. 5.10: fig05_10.c 2
Craps */
#include <stdio.h>
#include <stdlib.h>
#include <time.h> /* Contém protótipos pra a função time */
/* constantes de enumeração representam status do jogo */
enum Status {CONTINUE, WON, LOST};
int rollDice(void); /* protótipo de função */
/* função main inicia a execução do programa */
int main(void)
{
/* declaração das varáveis */
int sum; /* soma dos dados lançados */
int myPoint; /* ponto ganho */
enum Status gameStatus; /* pode conter CONTINUE, WON ou LOST */
/* entrada de dados */
/* randomiza gerador de número aleatório usando hora atual */
srand( time(NULL) );
sum = rollDice(); /* primeiro lançamento dos dados */
/* processamento */
/* determina status do jogo com base na soma dos dados */
switch(sum)
{
/* vence na primeira jogada */
case 7:
case 11:
gameStatus = WON;
break;
/* perde na primeira jogada */
case 2:
case 3:
case 12:
gameStatus = LOST;
break;
/* lembra ponto */
default:
gameStatus = CONTINUE;
myPoint = sum;
printf("Ponto é %d\n", myPoint );
break; /* optional */
} /* fim do switch */
/* enquanto jogo não termina */
while ( gameStatus == CONTINUE )
{
sum = rollDice(); /* joga dados novamente */
/* determina status do jogo */
if (sum == myPoint)
{
/* vence fazendo ponto */
gameStatus = WON; /* jogo termina, jogador vence */
} /* fim do if */
else
{
if (sum == 7)
{
/* perde por lançar 7 */
gameStatus = LOST; /* jogo termina, jogador perde */
} /* fim do if */
} /* fim do else */
} /* fim do while */
/* saída de dados */
/* mostra mensagem de vitória ou perda */
if (gameStatus == WON)
{
/* jogador venceu? */
printf( "Jogador vence\n");
} /* fim do if */
else
{
/* jogador perdeu */
printf("Jogador perde\n");
} /* fim do else */
return 0; /* indica conclusão bem-sucedida */
} //fim da função main.
/* lança dados, calcula soma e exibe resultados */
int rollDice(void)
{
int die1; /* primeiro dado */
int die2; /* segundo dado */
int workSum; /* soma dos dados */
die1 = 1 + (rand() % 6); /* escolhe valor aleatório die1 */
die2 = 1 + (rand() % 6); /* escolhe valor aleatório die2 */ workSum = die1 + die2; /* soma die1 e die2 */
/* exibe resultados dessa jogada */
printf("Jogador rolou %d + %d = %d\n", die1, die2, workSum );
return workSum; /* retorna soma dos dados */
} /* fim da função rollRice */
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.