language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C
|
/** \file
*/
/*
\amodel apop_mixture The mixture model transformation: a linear combination of multiple models.
Generated via \ref apop_model_mixture.
Note that a kernel density is a mixture of a large number of homogeneous models, where each is typically centered around a point in your data. For such situations, \ref apop_kernel_density will be easier to use.
Use \ref apop_model_mixture to produce one of these models. In the examples below, some are generated from unparameterized input models with a form like
\code
apop_model *mf = apop_model_mixture(apop_model_copy(apop_normal), apop_model_copy(apop_normal));
Apop_model_add_group(mf, apop_mle, .starting_pt=(double[]){50, 5, 80, 5},
.step_size=3, .tolerance=1e-6);
apop_model_show(apop_estimate(dd, mf));
\endcode
One can also skip the estimation and use already-parameterized models as input to \ref apop_model_mixture, e.g.:
\code
apop_model *r_ed = apop_model_mixture(apop_model_set_parameters(apop_normal, 54.6, 5.87),
apop_model_set_parameters(apop_normal, 80.1, 5.87));
apop_data *wts = apop_data_falloc((2), 0.36, 0.64);
Apop_settings_add(r_ed, apop_mixture, weights, wts->vector);
printf("LL=%g\n", apop_log_likelihood(dd, r_ed));
\endcode
Notice that the weights vector has to be added after the model is set up. If none is given, then equal weights are assigned to all components of the mixture.
One can think of the estimation as a missing-data problem: each data point originated
in one distribution or the other, and if we knew with certainty which data point
came from which distribution, then the estimation problem would be trivial:
just generate the subsets and call <tt>apop_estimate(dataset1, model1)</tt>, ...,
<tt>apop_estimate(datasetn, modeln)</tt> separately. But the assignment of which
element goes where is unknown information, which we guess at using an E-M algorithm. The
standard algorithm starts with an initial set of parameters for the models, and assigns
each data point to its most likely model. It then re-estimates the
model parameters using their subsets. The standard algorithm, see e.g. <a
href="http://www.jstatsoft.org/v32/i06/paper">this PDF</a>, repeats until it arrives
at an optimum.
Thus, the log likelihood method for this model includes a step that allocates each data
point to its most likely model, and calculates the log likelihood of each observation
using its most likely model. [It would be a valuable extension to extend this to
not-conditionally IID models. Commit \c 1ac0dd44 in the repository had some notes on
this, now removed.] As a side-effect, it calculates the odds of drawing from each model
(the vector λ). Following the above-linked paper, the probability for a given
observation under the mixture model is its probability under the most likely model
weighted by the previously calculated λ for the given model.
Apohenia modifies this routine slightly because it uses the same maximum likelihood
back-end that most other <tt>apop_model</tt>s use for estimation. The ML search algorithm
provides model parameters, then the LL method allocates observations and reports a LL to
the search algorithm, then the search algorithm uses its usual rules to step to the next
candidate set of parameters. This provides slightly more flexibility in the search.
\li <b>Estimations of mixture distributions can be sensitive to initial conditions.</b>
You are encouraged to try a sequence random starting points for your model parameters.
Some authors recommend plotting the data and eyeballing a guess as to the model parameters.
Determining to which parts of a mixture to assign a data point is a
well-known hard problem, which is often not solvable--that information is basically lost.
\adoc Input_format The same data gets sent to each of the component models of the
mixture. Each row is an observation, and the estimation routine assumes that models are
conditionally IID (i.e., having chosen what component of the mixture the observation
comes from, its likelihood can be calculated independently of all other observations).
\adoc Settings \ref apop_mixture_settings
\adoc Parameter_format The parameters are broken out in a readable form in the
settings group, so your best bet is to use those. See the sample code for usage.<br>
The <tt>parameter</tt> element is a single vector piling up all elements, beginning
with the first $n-1$ weights, followed by an <tt>apop_data_pack</tt> of each model's
parameters in sequence. Because all elements are in a single vector, one could run a
maximum likelihood search for all components (including the weights) at once. Fortunately
for parsing, the <tt>log_likehood</tt>, <tt>estimate</tt>, and other methods unpack
this vector into its component parts for you.
\adoc RNG Uses the weights to select a component model, then makes a draw from that component.
The model's \c dsize (draw size) element is set when you set up the model in the
model's \c prep method (automatically called by \ref apop_estimate, or call it directly)
iff all component models have the same \c dsize.
\adoc Examples
The first example uses a text file \c faith.data, in the \c tests directory of the distribution.
\include faithful.c
\include hills2.c
*/
#include "apop_internal.h"
Apop_settings_copy(apop_mixture,
(*out->cmf_refct)++;
)
Apop_settings_free(apop_mixture,
if (!(--in->cmf_refct)) {
apop_model_free(in->cmf);
free(in->cmf_refct);
}
free(in->param_sizes);
)
Apop_settings_init(apop_mixture,
out->cmf_refct = calloc(1, sizeof(int));
(*out->cmf_refct)++;
)
//see apop_model_mixture in types.h
apop_model *apop_model_mixture_base(apop_model **inlist){
apop_model *out = apop_model_copy(apop_mixture);
int count=0;
for (apop_model **m = inlist; *m; m++) count++;
apop_mixture_settings *ms =Apop_settings_add_group(out, apop_mixture, .model_list=inlist,
.model_count=count, .param_sizes=malloc(sizeof(int)*count));
int dsize = inlist[0]->dsize;
for (int i=1; i< count && dsize > -99; i++) if (inlist[i]->dsize != dsize) dsize = -100;
if (dsize > -99) out->dsize = dsize;
ms->weights = gsl_vector_alloc(ms->model_count);
gsl_vector_set_all(ms->weights, 1./count);
return out;
}
void mixture_show(apop_model *m, FILE *out){
apop_mixture_settings *ms = Apop_settings_get_group(m, apop_mixture);
if (m->parameters){
fprintf(out, "Mixture of %i models, with weights:\n", ms->model_count);
apop_vector_print(ms->weights, .output_pipe=out);
} else fprintf(out, "Mixture of %i models, with unspecified weights\n", ms->model_count);
for (int i=0; i< ms->model_count; i++){
fprintf(out, "\n");
apop_model_print(ms->model_list[i], out);
}
}
static void mixture_prep(apop_data * data, apop_model *model){
apop_model_print_vtable_add(mixture_show, apop_mixture);
if (model->parameters) return;
apop_mixture_settings *ms = Apop_settings_get_group(model, apop_mixture);
model->parameters = apop_data_alloc();
int i=0;
for (apop_model **m = ms->model_list; *m; m++){
if (!(*m)->parameters) apop_prep(data, *m);
gsl_vector *v = apop_data_pack((*m)->parameters);
ms->param_sizes[i++] = v->size;
model->parameters->vector = apop_vector_stack(model->parameters->vector, v, .inplace='y');
gsl_vector_free(v);
}
if (!model->dsize) model->dsize = (*ms->model_list)->dsize;
}
void unpack(apop_model *min){
apop_mixture_settings *ms = Apop_settings_get_group(min, apop_mixture);
int posn=0, i=0;
if (!min->parameters) return; //Trusting user that the user has added already-esimated models.
for (apop_model **m = ms->model_list; *m; m++){
gsl_vector v = gsl_vector_subvector(min->parameters->vector, posn, ms->param_sizes[i]).vector;
apop_data_unpack(&v, (*m)->parameters);
posn+=ms->param_sizes[i++];
}
}
#define weighted_sum(fn) \
long double total=0; \
long double total_weight = apop_sum(ms->weights); \
size_t i=0; \
for (apop_model **m = ms->model_list; *m; m++) \
total += fn(d, *m) * gsl_vector_get(ms->weights, i++)/total_weight;
//The output is a grid of log likelihoods.
apop_data* get_lls(apop_data *d, apop_model *m){
apop_mixture_settings *ms = Apop_settings_get_group(m, apop_mixture);
Get_vmsizes(d); //maxsize
apop_data *out = apop_data_alloc(maxsize, ms->model_count);
for (int i=0; i< maxsize; i++){
Apop_row(d, i, onepoint);
for (int j=0; j< ms->model_count; j++){
double this_val = apop_log_likelihood(onepoint, ms->model_list[j]);
apop_data_set(out, i, j, this_val);
}
}
return out;
}
/* The trick to summing exponents: subtract the max:
let ll_M be the max LL. then
Σexp(ll) = exp(llM)*(exp(ll₁-llM)+exp(ll₂-llM)+exp(ll₃-llM))
One of the terms in the sum is exp(0)=1. The others are all less than one, and so we
are guaranteed no overflow. If any of them underflow, then that term must not have
been very important for the sum.
*/
static long double sum_exp_vector(gsl_vector const *onerow){
long double rowtotal = 0;
double best = gsl_vector_max(onerow);
for (int j=0; j<onerow->size; j++) rowtotal += exp(gsl_vector_get(onerow, j)-best);
rowtotal *= exp(best);
return rowtotal;
}
static long double mixture_log_likelihood(apop_data *d, apop_model *model_in){
apop_mixture_settings *ms = Apop_settings_get_group(model_in, apop_mixture);
Apop_stopif(!ms, model_in->error='p'; return GSL_NAN, 0, "No apop_mixture_settings group. "
"Did you set this up with apop_model_mixture()?");
if (model_in->parameters) unpack(model_in);
apop_data *lls = get_lls(d, model_in);
//reweight by last round's lambda
for (int i=0; i< lls->matrix->size2; i++){
Apop_col_v(lls, i, onecol);
gsl_vector_add_constant(onecol, gsl_vector_get(ms->weights, i));
}
//OK, now we need the λs, and then the max ll for each observation
/*
Draw probabilities are p₁/Σp p₂/Σp p₃/Σp (see equation (2) of the above pdf.)
But I have logs, and want to stay in log-format for as long as possible, to prevent undeflows and loss of precision.
*/
long double total_ll=0;
gsl_vector *ps = gsl_vector_alloc(lls->matrix->size2);
gsl_vector *cp = gsl_vector_alloc(lls->matrix->size2);
for (int i=0; i< lls->matrix->size1; i++){
Apop_row_v(lls, i, onerow);
total_ll += gsl_vector_max(onerow);
for (int j=0; j < onerow->size; j++){
gsl_vector_memcpy(cp, onerow);
gsl_vector_add_constant(cp, -gsl_vector_get(onerow, j));
gsl_vector_set(ps, j, 1./sum_exp_vector(cp));
}
gsl_vector_memcpy(onerow, ps);
Apop_stopif(fabs(apop_sum(onerow) - 1) > 1e-3, /*Warn user, but continue.*/, 0,
"One of the probability calculations is off: the total for the odds of drawing "
"from the %i mixtures is %g but should be 1.",
ms->model_count, fabs(apop_sum(onerow) - 1));
}
gsl_vector_free(cp);
gsl_vector_free(ps);
for (int i=0; i< lls->matrix->size2; i++){
Apop_col_v(lls, i, onecol);
gsl_vector_set(ms->weights, i, apop_sum(onecol)/lls->matrix->size1);
}
return total_ll;
}
static int mixture_draw (double *out, gsl_rng *r, apop_model *m){
apop_mixture_settings *ms = Apop_settings_get_group(m, apop_mixture);
OMP_critical (mixdraw)
if (!ms->cmf){
ms->cmf = apop_model_copy(apop_pmf);
ms->cmf->data = apop_data_alloc();
ms->cmf->data->weights = apop_vector_copy(ms->weights);
Apop_model_add_group(ms->cmf, apop_pmf, .draw_index='y');
}
double index;
Apop_stopif(apop_draw(&index, r, ms->cmf), return 1,
0, "Couldn't select a mixture element using the internal PMF over mixture elements.");
return apop_draw(out, r, ms->model_list[(int)index]);
}
static long double mixture_cdf(apop_data *d, apop_model *model_in){
Nullcheck_m(model_in, GSL_NAN)
Nullcheck_d(d, GSL_NAN)
apop_mixture_settings *ms = Apop_settings_get_group(model_in, apop_mixture);
unpack(model_in);
weighted_sum(apop_cdf);
return total;
}
static long double mixture_constraint(apop_data *data, apop_model *model_in){
apop_mixture_settings *ms = Apop_settings_get_group(model_in, apop_mixture);
long double penalty = 0;
unpack(model_in);
//check all component models.
for (apop_model **m = ms->model_list; *m; m++)
penalty += (*m)->constraint(data, *m);
if (penalty){
int posn=0, i=0;
for (apop_model **m = ms->model_list; *m; m++){
gsl_vector v = gsl_vector_subvector(model_in->parameters->vector, posn, ms->param_sizes[i]).vector;
apop_data_pack((*m)->parameters, &v);
posn+=ms->param_sizes[i++];
}
}
//weights are all positive?
gsl_vector v = gsl_vector_subvector(model_in->parameters->vector, 0, ms->model_count).vector;
penalty += apop_linear_constraint(&v);
return penalty;
}
apop_model *apop_mixture=&(apop_model){"Mixture of models", .prep=mixture_prep,
.constraint=mixture_constraint, .log_likelihood=mixture_log_likelihood,
.cdf=mixture_cdf, .draw=mixture_draw };
|
C
|
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main(void)
{
int num=0;
int * prime;
int flag=0;
printf("양수 입력 : ");
scanf("%d",&num);
prime=(int*)malloc(sizeof(int)*num-1);
prime[num-2]=0;
for(int i=2;i<num;i++)
{
prime[i-2]=i;
for(int j=2;j<i;j++)
{
if(i%j==0)
{
// printf(" i : %d, j : %d \n",i,j);
prime[i-2]=-1;
// printf("prime[%d] : %d\n", i,prime[i]);
break;
}
}
}
int space=0;
for(int i=0;i<num-2;i++)
{
if(prime[i]==-1)
{
printf("%5c",'X');
space++;
}else
{
printf("%5d",prime[i]);
space++;
}
if(space==5)
{
printf("\n");
space=0;
}
}
printf("\n");
}
|
C
|
/******************************************************************************
* Copyright (C) 2017 by Alex Fosdick - University of Colorado
*
* Redistribution, modification or use of this software in source or binary
* forms is permitted as long as the files maintain this copyright. Users are
* permitted to modify this and use it to learn about the field of embedded
* software. Alex Fosdick and the University of Colorado are not liable for any
* misuse of this material.
*
*****************************************************************************/
/**
* @file <Week 4 Assignment>
* @brief <My solution to Week 4 assignment>
*
* <I am taking "Introduction to Embedded Systems Software and development environments"
* course and this is my solution to "Peer-graded Assignment: Week 4 Application Assignment">
*
* @author <Frida Rojas>
* @date <Mar 14th 2021>
*
*/
#ifndef __STATS_H__
#define __STATS_H__
#endif /* __STATS_H__ */
#define BASE_16 (16)
#define BASE_10 (10)
#define BASE_2 (2)
#include <stdint.h> // Include Integer pre-defined types: "uint8_t", "int32_t" and "uint32_t"
#include "memory.h"
/**
* @brief My implementation of itoa
*
* Function to convert signed integer numbers of any base to ASCII representation and returns number of digits.
* For example,
* > input = -4096 to ASCII base 16 is output = "-1000\0"_(16). ASCII representation has 4 digits.
* > input = 123456 to ASCII base 16 is output = "123456\0"_(16). ASCII representation has 6 digits.
*
* @param data The number you wish to convert to ASCII.
* @param ptr Pointer that stores the converted character string.
* @param base The number base to support.
*
* @return uint8_t.
*/
uint8_t my_itoa(int32_t data, uint8_t * ptr, uint32_t base);
/**
* @brief My implementation of atoi
*
* Function to convert signed numbers in ASCII representation to signed integer numbers of a given base
* and return as a 32-bit signed integer.
* For example,
* > input = -4096 to ASCII base 16 is output = "-1000\0"_(16). ASCII representation has 4 digits.
* > input = 123456 to ASCII base 16 is output = "123456\0"_(16). ASCII representation has 6 digits.
*
* @param ptr The ASCII representation number you wish to convert to integer number.
* @param digits The number of digits within the ASCII representation.
* @param base The number base to support.
*
* @return int32_t.
*/
int32_t my_atoi(uint8_t * ptr, uint8_t digits, uint32_t base);
|
C
|
//
// main.c
// Minimum Spanning Tree
//
// Created by Swarup Ghosh on 07/11/19.
// Copyright © 2019 Swarup Ghosh. All rights reserved.
//
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include "charset.h"
int prims(int **graph, int len_vertices, int start_vertex) {
CHARSET v, s;
init(&v); init(&s);
CHARSET *v_s;
// insert all vertices to set
int iter = 0;
for(iter = 0; iter < len_vertices; iter++) {
insert(&v, iter);
}
// insert the starting vertex to set
insert(&s, start_vertex);
CHARSET tree;
init(&tree);
int iter1, iter2;
int min, tracker;
int from, to;
int ctr = 0;
int cost = 0;
while(true) {
v_s = difference(&v, &s);
min = INT_MAX;
for(iter1 = 0; iter1 < len_vertices; iter1++) {
from = element(&s, iter1);
if(from == -1) break;
for(iter2 = 0; iter2 < len_vertices; iter2++) {
to = element(v_s, iter2);
if(to == -1) break;
if(graph[from][to] < min) {
min = graph[from][to];
tracker = from * len_vertices + to;
}
}
}
insert(&s, tracker % len_vertices);
insert(&tree, tracker);
free(v_s);
if(min == INT_MAX) break;
cost += min;
ctr++;
}
printf("Minimum Spanning Tree.\n");
for(iter = 0; iter < len_vertices - 1; iter++) {
tracker = element(&tree, iter);
if(tracker == -1) break;
printf("(%d, %d) ", tracker / len_vertices, tracker % len_vertices);
}
printf("\n");
return cost;
}
int main() {
int **graph, len_vertices;
printf("Number of vertices? (integer expected) -> ");
scanf("%d", &len_vertices);
int iter_a, iter_b;
graph = malloc(sizeof(int*) * len_vertices);
for(iter_a = 0; iter_a < len_vertices; iter_a++) {
graph[iter_a] = malloc(sizeof(int) * len_vertices);
}
printf("Adjacency Matrix for weighted graph edges.\n0 indicates absence of edge.\n");
printf("(%d integers expected) -> \n", len_vertices * len_vertices);
for(iter_a = 0; iter_a < len_vertices; iter_a++) {
for(iter_b = 0; iter_b < len_vertices; iter_b++) {
scanf("%d", &graph[iter_a][iter_b]);
if(graph[iter_a][iter_b] == 0) graph[iter_a][iter_b] = INT_MAX;
}
}
int cost;
cost = prims(graph, len_vertices, 0);
printf("Spanning cost: %d\n", cost);
return 0;
}
|
C
|
#include <stdio.h>
#include <ctype.h>
#include <math.h>
#include <string.h>
#include <limits.h>
/* Chapter 5.1 */
/*
pointers cannot be applied to expressions constants or register variables
*/
/* Chapter 5.2 */
/*
*/
/* Chapter 5.3 */
/*
There is one difference between an array name and a pointer that must be kept in mind.
A pointer is a variable, so pa=a and pa++ are legal.
But an array name is not a variable; constructions like a=pa and a++ are illegal.
Passing a sub array
f(&a[2])
*/
#define BUFSIZE 100
/* buffer for ungetch */
char buf[BUFSIZE];
/* next free position in buf */
int bufp = 0;
int getch(void)
{
return (bufp > 0) ? buf[--bufp] : getchar();
}
int ungetch(int c)
{
if (bufp >= BUFSIZE)
{
printf("ungetch: too many characters\n");
return 1;
}
buf[bufp++] = c;
return 0;
}
/* getint: get next integer from input into *pn */
int getint(int *pn)
{
int c, sign;
while (isspace(c = getch())) /* skip white space */
;
if (!isdigit(c) && c != EOF && c != '+' && c != '-')
{
ungetch(c); /* it is not a number */
return 0;
}
sign = (c == '-') ? -1 : 1;
printf("sign is %d\n", sign);
if (c == '+' || c == '-')
{
printf("we are here\n");
c = getch();
}
for (*pn = 0; isdigit(c); c = getch())
{
*pn = 10 * *pn + (c - '0');
}
*pn *= sign;
if (c != EOF)
{
ungetch(c);
}
return c;
}
/* exercise 5-1 */
int exercise_five_one(int *pn)
{
int c, sign;
while (isspace(c = getch())) /* skip white space */
;
if (!isdigit(c) && c != EOF && c != '+' && c != '-')
{
ungetch(c); /* it is not a number */
return 0;
}
sign = (c == '-') ? -1 : 1;
printf("sign is %d\n", sign);
if (c == '+' || c == '-')
{
printf("we are here\n");
c = getch();
if(!isdigit(c))
{
printf("the\n");
ungetch(c);
return 0;
}
}
for (*pn = 0; isdigit(c); c = getch())
{
*pn = 10 * *pn + (c - '0');
}
*pn *= sign;
if (c != EOF)
{
ungetch(c);
}
return c;
}
/* Exercise 5-2. Write getfloat, the floating-point analog of getint. What type does getfloat return as its function value? */
int exercise_five_two(double *pn)
{
int c, sign, power;
double t;
power = 0;
while (isspace(c = getch())) /* skip white space */
;
if (!isdigit(c) && c != EOF && c != '+' && c != '-')
{
ungetch(c); /* it is not a number */
return 0;
}
sign = (c == '-') ? -1 : 1;
if (c == '+' || c == '-')
{
c = getch();
if(!isdigit(c))
{
ungetch(c);
return 0;
}
}
for (t = 0.0; isdigit(c); c = getch())
{
t = 10 * t + (c - '0');
}
if(c == '.')
{
c = getch();
for (; isdigit(c); c = getch())
{
t = 10 * t + (c - '0');
power++;
}
}
*pn = t;
printf("power is %d\n", power);
*pn = (sign * t) / pow(10, power);
if (c != EOF)
{
ungetch(c);
}
return c;
}
void exercise_five_one_tests(void)
{
printf("running 5-1\n");
int x, res;
if(!(res = exercise_five_one(&x)))
{
printf("the value is not a num\n");
}
else
{
printf("the number rxed is %d\n", x);
}
}
void exercise_five_two_tests(void)
{
printf("runnig 5-2\n");
double k;
exercise_five_two(&k);
printf("the number is %f\n", k);
}
/* Chapter 5-4 */
/*
It is not legal to add two pointers, or to multiply or divide or shift or mask them, or to add float or double to them, or even, except for void *, to assign a pointer of one type to a pointer of another type without a cast.
*/
/*
Exercise 5-3. Write a pointer version of the function strcat that we showed in Chapter 2: strcat(s,t) copies the string t to the end of s.
*/
void exercise_five_three(char *s, char *t)
{
int i, j;
for(; *s != '\0'; s++);
while((*s++ = *t++) != '\0');
}
void exercise_five_three_tests(void)
{
char s[] = "Hello";
char t[] = "W";
exercise_five_three(s, t);
printf("the concat is %s\n", s);
}
int my_strcomp(char *s, char *t)
{
for(; *s == *t; s++, t++)
{
if(*s == '\0')
{
return 0;
}
}
return *s - *t;
}
/*
Exercise 5-4. Write the function strend(s,t), which returns 1 if the string t occurs at the end of the string s, and zero otherwise.
assume |t| > |s|
*/
int exercise_five_four(char *s, char *t)
{
int s_len, t_len, i, j;
if(!s || !t)
{
/* strings are empty */
printf("here\n");
return 0;
}
s_len = strlen(s);
t_len = strlen(t);
for(i=s_len ,j=t_len; i >= 0 && j >= 0 && s[i] == t[j]; i--, j--);
return (j == -1) ? 1 : 0;
}
void exercise_five_four_tests(void)
{
int result;
/* finds the word */
char *s = "Hello World";
char *t = "World";
result = exercise_five_four(s, t);
printf("the first result is %d\n", result);
char *s2 = "Hello WOrld";
char *t2 = "World";
result = exercise_five_four(s2, t2);
printf("the second result is %d\n", result);
char *s3 = "Hello World";
char *t4 = "world";
result = exercise_five_four(s2, t2);
printf("the second result is %d\n", result);
}
/*
Exercise 5-5. 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.
*/
void my_strncpy(char *s, const char *t, int n)
{
for(; n > 0 && *t != '\0'; n--)
{
*s++ = *t++;
}
*s = '\0';
}
/*
concatenate at most n characters of string ct to string s, terminate s with ’\0’; return s.
*/
char *my_strncat(char *s, char *ct, int n)
{
char *temp = s;
/* find the end of the string s */
for(; *temp != '\0'; temp++);
/* copy ct to the end */
for(; n > 0 && (*temp++ = *ct++) != '\0'; n--)
{
}
*temp = '\0';
return s;
}
int my_strncmp(const char *cs, const char *ct, int n)
{
for(; (n > 0) && (*ct == *cs) && (*cs != '\0') && (*ct != '\0'); n--, ct++, cs++);
if(*cs == *ct)
{
return 0;
}
else if(*cs > *ct)
{
return 1;
}
else {
return -1;
}
}
void exercise_five_five_tests(void)
{
int result;
char buf[100];
char *t = "Hello";
my_strncpy(buf, t, 2);
printf("the string is %s\n", buf);
char buf_two[100] = "Hello";
char *k = " World";
my_strncat(buf_two, k, 6);
printf("the second is %s\n", buf_two);
char cs[] = "H";
char ct[] = "Howdy";
result = my_strncmp(cs, ct, 5);
printf("the result is %d\n", result);
}
void exercise_five_six(void);
/* Chapter 5.6 */
/* look at pointer_arrays.c */
/* Chapter 5.7 */
/*
More generally, only the first dimension (subscript) of an array is free; all the others have to be specified.
*/
static char daytab[2][13] = {
{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
{0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
};
/* day_of_year: set day of year from month & day */
int day_of_year(int year, int month, int day)
{
int i, leap;
/* check year */
if(year < 0)
{
printf("year cannot be negative\n");
return 0;
}
/* !(month >= 1 && month <= 12) */
if(!(month >= 1 && month <= 12))
{
printf("month is invalid\n");
return 0;
}
/* (day >= 1 && day <= 31) */
if(!(day >= 1 && day <= 31))
{
printf("day is invalid\n");
return 0;
}
leap = ((year%4 == 0) && (year%100 != 0)) || (year%400 == 0);
/* check if day is greater than max month */
if(day > daytab[leap][month]) {
printf("day is greater than max month day\n");
return 0;
}
for (i = 1; i < month; i++)
{
day += daytab[leap][i];
}
return day;
}
/* month_day: set month, day from day of year */
void month_day(int year, int yearday, int *pmonth, int *pday)
{
int i, leap;
if(!pmonth || !pday)
{
printf("the pointers are null\n");
return;
}
if(year < 0)
{
printf("year cannot be negative\n");
return;
}
if(yearday < 1 || yearday > 365)
{
printf("invalid yearday\n");
return;
}
leap = ((year%4 == 0) && (year%100 != 0)) || (year%400 == 0);
for (i = 1; yearday > daytab[leap][i]; i++)
{
yearday -= daytab[leap][i];
}
*pmonth = i;
*pday = yearday;
}
void exercise_five_eight_tests(void)
{
int year, month, day, yearday;
year = 2020;
month = 9;
day = 24;
yearday = day_of_year(year, month, day);
printf("the result of day_year is %d\n", yearday);
int pmonth, pday;
pmonth = pday = 0;
month_day(year, yearday, &pmonth, &pday);
printf("month is %d, day is %d\n", pmonth, pday);
}
/* Chapter 5.8 */
/* month_name: return name of n-th month */
char *month_name(int n)
{
static char *name[] = {
"Illegal month",
"January", "February", "March",
"April", "May", "June",
"July", "August", "September",
"October", "November", "December"
};
return (n < 1 || n > 12) ? name[0] : name[n];
}
void chapter_five_eight_tests(void)
{
int i;
for(i=0; i < 15; i++)
{
printf("the month is %s\n", month_name(i));
}
}
/* chapter 5.9 */
/*
conventional rectangular subscript calculation 20 * row +col
int a[10][20];
int *b[10];
b needs to be initialized explicitly
b's rows might might be of different lenghts => saves us space
*/
/* Exercise 5-9. Rewrite the routines day_of_year and month_day with pointers instead of indexing. */
int pday_of_year(int year, int month, int day)
{
int i, leap;
/* check year */
if(year < 0)
{
printf("year cannot be negative\n");
return 0;
}
/* !(month >= 1 && month <= 12) */
if(!(month >= 1 && month <= 12))
{
printf("month is invalid\n");
return 0;
}
/* (day >= 1 && day <= 31) */
if(!(day >= 1 && day <= 31))
{
printf("day is invalid\n");
return 0;
}
leap = ((year%4 == 0) && (year%100 != 0)) || (year%400 == 0);
/* check if day is greater than max month */
if(day > *((*(daytab+leap))+month)) {
printf("day is greater than max month day\n");
return 0;
}
for (i = 1; i < month; i++)
{
day += *((*(daytab+leap)) + i);
}
return day;
}
/* month_day: set month, day from day of year */
void pmonth_day(int year, int yearday, int *pmonth, int *pday)
{
int i, leap;
if(!pmonth || !pday)
{
printf("the pointers are null\n");
return;
}
if(year < 0)
{
printf("year cannot be negative\n");
return;
}
if(yearday < 1 || yearday > 365)
{
printf("invalid yearday\n");
return;
}
leap = ((year%4 == 0) && (year%100 != 0)) || (year%400 == 0);
for (i = 1; yearday > *((*(daytab+leap)) + i); i++)
{
yearday -= **(daytab + (13 * leap + i));
}
*pmonth = i;
*pday = yearday;
}
void exercise_five_nine_tests(void)
{
int year, month, day, yearday;
year = 2020;
month = 9;
day = 24;
yearday = pday_of_year(year, month, day);
printf("the result of day_year is %d\n", yearday);
int pmonth, pday;
pmonth = pday = 0;
month_day(year, yearday, &pmonth, &pday);
printf("month is %d, day is %d\n", pmonth, pday);
}
int main()
{
/* exercise 5-1 tests */
// exercise_five_one_tests();
/* exercise 5-2 tests */
// exercise_five_two_tests();
/* exercise 5-3 tests */
// exercise_five_three_tests();
/* exercise 5-4 tests */
// exercise_five_four_tests();
/* exercise 5-5 tests */
// exercise_five_five_tests();
/* exercise 5-8 tests */
// exercise_five_eight_tests();
/* chapter 5.8 tests */
// chapter_five_eight_tests();
/* exercise 5-9 tests */
//exercise_five_nine_tests();
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include "queue.h"
struct Node{
NumericItemP item;
struct Node* next;
};
void initQueue (Queue **queue) {
if (queue == NULL) return;
*queue = (Queue *)malloc(sizeof(Queue));
(*queue)->first = NULL;
(*queue)->last = NULL;
}
void append (Queue *queue, NumericItemP pVal) {
if (queue != NULL) {
struct Node *node = (struct Node *)malloc(sizeof(struct Node));
node->next = NULL;
int s = sizeof(int);
node->item = (NumericItemP)malloc(s);
memcpy(node->item, pVal, s);
if (queue->last != NULL) {
struct Node* q = queue->last;
q->next = node;
} else
queue->first = node;
queue->last = node;
}
}
void leave (Queue *queue) {
assert(!isEmpty(queue));
struct Node *n = queue->first;
if (n->next != NULL) {
queue->first = n->next;
n->next = NULL;
} else {
queue->first = NULL;
queue->last = NULL;
}
free(n->item);
free(n);
}
NumericItemP seekHead (const Queue * queue) {
assert(!isEmpty(queue));
return queue->first->item;
}
NumericItemP seekTail (const Queue * queue) {
assert(!isEmpty(queue));
return queue->last->item;
}
void printAll (const Queue * queue) {
struct Node *n;
fprintf(stdout, "queue is:\n");
n = queue->first;
while (n != NULL) {
fprintf(stdout, "\t%d\n", *(n->item));
n = n->next;
}
}
bool isEmpty (const Queue *queue) {
if (queue != NULL && queue->first == NULL && queue->last == NULL)
return true;
return false;
}
void clear (Queue * queue) {
if (!isEmpty(queue)) {
struct Node *q = queue->first;
queue->first = NULL;
queue->last = NULL;
struct Node *n;
while (q != NULL) {
n = q;
q = n->next;
n->next = NULL;
free(n->item);
free(n);
}
}
}
void destroyQueue(Queue **queue) {
if (queue == NULL) return;
if (*queue == NULL) return;
clear(*queue);
free(*queue);
}
|
C
|
//
// main.c
// Pointers Training
//
// Created by Mironov Oleg on 05.01.16.
// Copyright © 2016 Mironov Oleg. All rights reserved.
//
#include <stdio.h>
#include <stdlib.h>
void basicPointers();
void arrayPointers();
void stringPointers();
void heap();
int main(int argc, const char * argv[]) {
basicPointers();
arrayPointers();
stringPointers();
heap();
return 0;
}
void basicPointers() {
int tuna = 19;
int *pTuna = &tuna; //Reading tuna memory address to a pointer
printf("Address \t name \t Value \n");
printf("%p \t %s \t %d \n", pTuna, "tuna", tuna);
printf("%p \t %s \t %p \n", &pTuna, "tuna", pTuna);
printf("\n *pTuna: %d \n", *pTuna); //Dereferencing of a Pointer
*pTuna = 71; //Dereferencing of a Pointer
printf("\n *pTuna: %d \n", *pTuna);
}
void arrayPointers() {
int i;
int meatBalls[5] = {1,2,5,10,3};
for (i = 0; i < 5; i++) {
printf("meatBalls[%d] \t %p \t %d \n", i, &meatBalls[i], meatBalls[i]);
}
printf("\nmeatBalls %p\n", meatBalls);
printf("\n*meatBalls %d\n", *meatBalls);
printf("\n*(meatBalls + 2) %d\n", *(meatBalls+2)); //third emelent in the array dereferenced
}
void stringPointers() {
char movie1[] = "King Kong";
char *movie2 = "Indiana Jones";
puts(movie2);
movie2 = "New Movie";
puts(movie2);
char movie[20];
char *pMovie = movie;
fgets(pMovie, 20, stdin);
puts(pMovie);
}
void heap() {
int *points;
points = (int *) malloc(5 * sizeof(int));
free(points);
}
|
C
|
typedef char *VA;
typedef struct MemoryRegions
{
VA startAddr;
VA endAddr;
size_t size;
int isReadable, isWritable, isExecutable, isPrivate;
off_t offset;
unsigned int long device_id_major, device_id_minor, inode_number;
char name[1024];
} __attribute__((packed)) MemoryRegion;
char mtcp_readchar(int fd)
{
char c;
ssize_t rc;
do{
rc = read(fd, &c, 1);
}while(rc == -1);
if (rc <= 0) return 0;
return c;
}
char mtcp_readdec (int fd, VA *value)
{
char c;
unsigned long int v;
v = 0;
while (1) {
c = mtcp_readchar (fd);
if ((c >= '0') && (c <= '9')) c -= '0';
else break;
v = v * 10 + c;
}
*value = (VA)v;
return (c);
}
char mtcp_readhex(int fd, VA *value)
{
char c;
unsigned long int v;
v = 0;
while(1)
{
c = mtcp_readchar(fd);
if ((c >= '0') && (c <= '9')) c -= '0';
else if ((c >= 'a') && (c <= 'f')) c -= 'a' - 10;
else if ((c >= 'A') && (c <= 'F')) c -= 'A' - 10;
else break;
v = v * 16 + c;
}
*value = (VA)v;
return (c);
}
//read hex characters from the file into local variables
int readline (int fd, MemoryRegion *proc)
{
char c, r, w, x, p;
off_t offset;
unsigned long int device_id_major, device_id_minor, inode_number;
VA startAddr, endAddr;
int i;
c = mtcp_readhex(fd, &startAddr);
if (c != '-') return 0;
c = mtcp_readhex(fd, &endAddr);
if (c != ' ') return 0;
r = mtcp_readchar(fd);
if ((r != 'r') && (r != '-')) return 0;
w = mtcp_readchar(fd);
if ((w != 'w') && (w != '-')) return 0;
x = mtcp_readchar(fd);
if ((x != 'x') && (x != '-')) return 0;
p = mtcp_readchar(fd);
if ((p != 'p') && (p != 's')) return 0;
c = mtcp_readchar(fd);
if (c != ' ') return 0;
c = mtcp_readhex(fd, (VA *)&offset);
if (c != ' ') return 0;
c = mtcp_readhex(fd, (VA *)&device_id_major);
if (c != ':') return 0;
c = mtcp_readhex(fd, (VA *)&device_id_minor);
if (c != ' ') return 0;
c = mtcp_readdec(fd, (VA *)&inode_number);
if (c != ' ') return 0;
proc->startAddr = startAddr;
//printf("%p\t", proc->startAddr);
proc->endAddr = endAddr;
//printf("%p\t", proc->endAddr);
proc->size = endAddr - startAddr;
//printf("%ld\n", proc->size);
if (r == 'r')
proc->isReadable = 1;
else
proc->isReadable = 0;
//printf("%d\t", proc->isReadable);
if (w == 'w')
proc->isWritable = 1;
else
proc->isWritable = 0;
//printf("%d\t", proc->isWritable);
if (x == 'x')
proc->isExecutable = 1;
else
proc->isExecutable = 0;
//printf("%d\t", proc->isExecutable);
if (p == 'p')
proc->isPrivate = 1;
else
proc->isPrivate = 0;
//printf("%d\n", proc->isPrivate);
proc->offset = offset;
proc->device_id_major = device_id_major;
proc->device_id_minor = device_id_minor;
proc->inode_number = inode_number;
proc->name[0] = '\0';
while (c == ' ') c = mtcp_readchar (fd);
if (c == '/' || c == '[')
{ /* absolute pathname, or [stack], [vdso], etc. */
i = 0;
do {
proc->name[i++] = c;
if (i == sizeof proc->name) return 0;
c = mtcp_readchar (fd);
} while (c != '\n');
proc->name[i] = '\0';
}
return 1;
}
|
C
|
#include "hyperbolic_geodesics.h"
void companion_inverse(size_t nb_vectors, size_t nb_coordinates, double complex* v_all, double complex *p){
size_t i,j;
double complex aux;
for(i=0; i<nb_vectors; ++i){
aux = v_all[i];
for(j=0; j<nb_coordinates-1; ++j)
v_all[i + nb_vectors*j] = v_all[i+nb_vectors*(j+1)];
v_all[i+nb_vectors*(nb_coordinates-1)] = 0+0*I;
for(j=0; j<nb_coordinates; ++j)
v_all[i + nb_vectors*j] -= conj(p[nb_coordinates-j-1])*aux;
}
}
void companion(size_t nb_vectors, size_t nb_coordinates, double complex* v_all, double complex *p){
size_t i,j;
double complex aux;
for(i=0; i<nb_vectors; ++i){
aux = v_all[i+nb_vectors*(nb_coordinates-1)];
for(j=nb_coordinates-1; j>0; --j)
v_all[i+nb_vectors*j] = v_all[i+nb_vectors*(j-1)];
v_all[i] = 0+0*I;
for(j=0; j<nb_coordinates; ++j)
v_all[i + nb_vectors*j] -= p[j]*aux;
}
}
void monodromy(size_t n, size_t nb_vectors, size_t nb_coordinates, double complex* v_all,
double complex *p_zero, double complex *p_infinity){
if (n == 0)
// M_inf
companion(nb_vectors, nb_coordinates, v_all, p_infinity);
if (n == 1)
// M_0
companion_inverse(nb_vectors, nb_coordinates, v_all, p_zero);
if (n == 2){
// M_1 = M_0^-1 * M_inf^-1
companion_inverse(nb_vectors, nb_coordinates, v_all, p_infinity);
companion(nb_vectors, nb_coordinates, v_all, p_zero);
}
}
void monodromy_inverse(size_t n, size_t nb_vectors, size_t nb_coordinates, double complex* v_all,
double complex *p_zero, double complex *p_infinity){
if (n == 0)
// M_inf^-1
companion_inverse(nb_vectors, nb_coordinates, v_all, p_infinity);
if (n == 1)
// M_0^-1
companion(nb_vectors, nb_coordinates, v_all, p_zero);
if (n == 2){
// M_1^-1 = M_inf*M_0
companion_inverse(nb_vectors, nb_coordinates, v_all, p_zero);
companion(nb_vectors, nb_coordinates, v_all, p_infinity);
}
}
void monodromy_T(size_t nb_vectors, double complex* v_all){
size_t nb_coordinates = 4;
size_t i,j;
double complex res[4] = {0,0,0,0};
for(i=0; i<nb_vectors; ++i) {
res[0] = v_all[i];
res[1] = v_all[i] + v_all[i + nb_vectors * 1];
res[2] = v_all[i]/2 + v_all[i + nb_vectors * 1] + v_all[i + nb_vectors * 2];
res[3] = v_all[i]/6 + v_all[i + nb_vectors * 1]/2 + v_all[i + nb_vectors * 2] + v_all[i + nb_vectors * 3];
for(j=0; j<nb_coordinates; ++j)
v_all[i + nb_vectors * j] = res[j];
}
}
void monodromy_T_inverse(size_t nb_vectors, double complex* v_all){
size_t nb_coordinates = 4;
size_t i,j;
double complex res[4] = {0,0,0,0};
for(i=0; i<nb_vectors; ++i) {
res[0] = v_all[i];
res[1] = -v_all[i] + v_all[i + nb_vectors * 1];
res[2] = v_all[i]/2 - v_all[i + nb_vectors * 1] + v_all[i + nb_vectors * 2];
res[3] = -v_all[i]/6 + v_all[i + nb_vectors * 1]/2 - v_all[i + nb_vectors * 2] + v_all[i + nb_vectors * 3];
for(j=0; j<nb_coordinates; ++j)
v_all[i + nb_vectors * j] = res[j];
}
}
void monodromy_S(size_t nb_vectors, double complex* v_all, double complex C, double complex d){
size_t i;
for(i=0; i<nb_vectors; ++i)
v_all[i] -= C*v_all[i + nb_vectors * 1]/12 + d*v_all[i + nb_vectors * 3];
}
void monodromy_S_inverse(size_t nb_vectors, double complex* v_all, double complex C, double complex d){
size_t i;
for(i=0; i<nb_vectors; ++i)
v_all[i] += C*v_all[i + nb_vectors * 1]/12 + d*v_all[i + nb_vectors * 3];
}
void monodromy_ST(size_t nb_vectors, double complex* v_all, double complex C, double complex d){
monodromy_T(nb_vectors, v_all);
monodromy_S(nb_vectors, v_all, C, d);
}
void monodromy_ST_inverse(size_t nb_vectors, double complex* v_all, double complex C, double complex d){
monodromy_S_inverse(nb_vectors, v_all, C, d);
monodromy_T_inverse(nb_vectors, v_all);
}
void monodromy_TS(size_t nb_vectors, double complex* v_all, double complex C, double complex d){
monodromy_S(nb_vectors, v_all, C, d);
monodromy_T(nb_vectors, v_all);
}
void monodromy_TS_inverse(size_t nb_vectors, double complex* v_all, double complex C, double complex d){
monodromy_T_inverse(nb_vectors, v_all);
monodromy_S_inverse(nb_vectors, v_all, C, d);
}
void monodromy_CY_K(size_t n, size_t nb_vectors, double complex* v_all, double complex C, double complex d){
//Minf*M0*M1 = Id, M0*M1*Minf = Id, A*B*C = Id
if (n == 0)
monodromy_T(nb_vectors, v_all); // M0
if (n == 1)
monodromy_S(nb_vectors, v_all, C, d); // M1
if (n == 2)
monodromy_TS_inverse(nb_vectors, v_all, C, d); // Minf
}
void monodromy_CY_inverse_K(size_t n, size_t nb_vectors, double complex* v_all, double complex C, double complex d){
if (n == 0)
monodromy_T_inverse(nb_vectors, v_all);
if (n == 1)
monodromy_S_inverse(nb_vectors, v_all, C, d);
if (n == 2)
monodromy_TS(nb_vectors, v_all, C, d);
}
void monodromy_CY_zero_inv(size_t nb_vectors, double complex* v_all){
size_t i,j;
double complex res[4] = {0,0,0,0};
for(i=0; i<nb_vectors; ++i){
res[0] = 0;
for(j=0; j<3; ++j)
res[j+1] = v_all[i+nb_vectors*j];
res[0] -= 1*v_all[i+nb_vectors*3];
res[1] += 4*v_all[i+nb_vectors*3];
res[2] -= 6*v_all[i+nb_vectors*3];
res[3] += 4*v_all[i+nb_vectors*3];
for(j=0; j<4; ++j)
v_all[i + nb_vectors*j] = res[j];
}
}
void monodromy_CY_zero(size_t nb_vectors, double complex* v_all){
size_t i,j;
double complex res[4] = {0,0,0,0};
for(i=0; i<nb_vectors; ++i){
for(j=0; j<3; ++j)
res[j] = v_all[i+nb_vectors*(j+1)];
res[3] = 0;
res[0] += 4*v_all[i];
res[1] -= 6*v_all[i];
res[2] += 4*v_all[i];
res[3] -= 1*v_all[i];
for(j=0; j<4; ++j)
v_all[i + nb_vectors*j] = res[j];
}
}
void monodromy_CY_inf_inv(size_t nb_vectors, double complex* v_all, double complex a, double complex b){
size_t i,j;
double complex res[4] = {0,0,0,0};
for(i=0; i<nb_vectors; ++i){
for(j=0; j<3; ++j)
res[j] = v_all[i+nb_vectors*(j+1)];
res[3] = 0;
res[0] += a*v_all[i];
res[1] += b*v_all[i];
res[2] += a*v_all[i];
res[3] -= 1*v_all[i];
for(j=0; j<4; ++j)
v_all[i + nb_vectors*j] = res[j];
}
}
void monodromy_CY_inf(size_t nb_vectors, double complex* v_all, double complex a, double complex b){
size_t i,j;
double complex res[4] = {0,0,0,0};
for(i=0; i<nb_vectors; ++i){
res[0] = 0;
for(j=0; j<3; ++j)
res[j+1] = v_all[i+nb_vectors*j];
res[0] -= v_all[i+nb_vectors*3];
res[1] += a*v_all[i+nb_vectors*3];
res[2] += b*v_all[i+nb_vectors*3];
res[3] += a*v_all[i+nb_vectors*3];
for(j=0; j<4; ++j)
v_all[i + nb_vectors*j] = res[j];
}
}
void monodromy_CY_one(size_t nb_vectors, double complex* v_all, double complex a, double complex b){
monodromy_CY_inf_inv(nb_vectors, v_all, a, b);
monodromy_CY_zero_inv(nb_vectors, v_all);
}
void monodromy_CY_one_inv(size_t nb_vectors, double complex* v_all, double complex a, double complex b){
monodromy_CY_zero(nb_vectors, v_all);
monodromy_CY_inf(nb_vectors, v_all, a, b);
}
void monodromy_CY(size_t n, size_t nb_vectors, double complex* v_all, double complex a, double complex b){
//Minf*M0*M1 = Id, M0*M1*Minf = Id, A*B*C = Id
if (n == 0)
monodromy_CY_zero(nb_vectors, v_all); // M0
if (n == 1)
monodromy_CY_one(nb_vectors, v_all, a, b); // M1
if (n == 2)
monodromy_CY_inf(nb_vectors,v_all, a, b); // Minf
}
void monodromy_CY_inverse(size_t n, size_t nb_vectors, double complex* v_all, double complex a, double complex b){
//Minf*M0*M1 = Id, M0*M1*Minf = Id, A*B*C = Id
if (n == 0)
monodromy_CY_zero_inv(nb_vectors, v_all); // M0
if (n == 1)
monodromy_CY_one_inv(nb_vectors, v_all, a, b); // M1
if (n == 2)
monodromy_CY_inf_inv(nb_vectors, v_all, a, b); // Minf
}
|
C
|
#include <stdio.h>
main()
{
int *pnum;
int *pnum2;
int suma;
int num;
int num2;
num=0;
num2=0;
suma=0;
printf("Introduce un numero:");
scanf("%d",&num);
printf("Introduce otro numero:");
scanf("%d",&num2);
pnum=#
pnum2=&num2;
suma=*pnum+*pnum2;
printf("La suma de %d y %d es: %d", num,num2,suma);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
char *arg_directory = NULL;
char *arg_prefix = NULL;
if(argc != 3) {
fprintf(stderr, "usage: %s <directory> <prefix>\n", argv[0]);
exit(1);
}
//사용자로부터 임시파일을 생성할 디렉터리를 입력받음
//공백을 입력받는 경우 NULL을 저장하여 시스템이 설정
arg_directory = argv[1][0] != ' ' ? argv[1] : NULL;
//사용자로부터 임시파일의 접두어를 입력받음
arg_prefix = argv[2][0] != ' ' ? argv[2] : NULL;
//사용자 설정 임시파일 이름 반환
printf("created : %s\n", tempnam(arg_directory, arg_prefix));
exit(0);
}
|
C
|
#include <unittest.h>
#include SOURCE_C
/*
* rn2483_poll_gpio() marks all of the radio module GPIO pins that have been
* explicitely configured as
*/
static struct rn2483_desc_t radio_descriptor;
#include "rn2483_service_stubs.c"
static void reset (void)
{
sercom_uart_has_line_call_count = 0;
executed_state = (enum rn2483_state)-1;
radio_descriptor.waiting_for_line = 0;
sercom_uart_has_line_retval = 0;
// Reset all pins
for (enum rn2483_pin pin = 0; pin < RN2483_NUM_PINS; pin++) {
radio_descriptor.pins[pin].raw =
RN2483_PIN_DESC_MODE(RN2483_PIN_MODE_INPUT);
}
}
int main (int argc, char **argv)
{
// Run poll function when there are no pins that have been explicitly set as
// inputs.
{
reset();
radio_descriptor.state = RN2483_IDLE;
rn2483_poll_gpio(&radio_descriptor);
// Check that no pins where marked as dirty
for (enum rn2483_pin pin = 0; pin < RN2483_NUM_PINS; pin++) {
ut_assert(radio_descriptor.pins[pin].value_dirty == 0);
}
// Check that the driver state was not changed
ut_assert(radio_descriptor.state == RN2483_IDLE);
// Checl that the sercom_uart_has_line function was not called
ut_assert(sercom_uart_has_line_call_count == 0);
// Check that we ran the idle state right away
ut_assert(executed_state == RN2483_IDLE);
}
// Run poll function when pin 0 is an explicit input and pin 1 is an
// explicit ananlog input. Driver is currently in the process of a reception
// that must be cancled.
{
reset();
radio_descriptor.state = RN2483_RECEIVE;
radio_descriptor.pins[0].mode = RN2483_PIN_MODE_INPUT;
radio_descriptor.pins[0].mode_explicit = 1;
radio_descriptor.pins[1].mode = RN2483_PIN_MODE_ANALOG;
radio_descriptor.pins[1].mode_explicit = 1;
rn2483_poll_gpio(&radio_descriptor);
// Check that pins 0 and 1 have been marked as dirty
ut_assert(radio_descriptor.pins[0].value_dirty == 1);
ut_assert(radio_descriptor.pins[1].value_dirty == 1);
// Check that none of the other pins where marked as dirty
for (enum rn2483_pin pin = 2; pin < RN2483_NUM_PINS; pin++) {
ut_assert(radio_descriptor.pins[pin].value_dirty == 0);
}
// Check that the driver state was changed tp receive abost
ut_assert(radio_descriptor.state == RN2483_RECEIVE_ABORT);
// Checl that the sercom_uart_has_line function was not called
ut_assert(sercom_uart_has_line_call_count == 0);
// Check that we ran the receive abort state right away
ut_assert(executed_state == RN2483_RECEIVE_ABORT);
}
// Run poll function when pis 5 and 6 are an explicit inputs and pins 7 and
// 8 are explicit outputs. Driver is currently in the process of a reception
// that must be cancled.
{
reset();
radio_descriptor.state = RN2483_RECEIVE;
radio_descriptor.pins[5].mode = RN2483_PIN_MODE_INPUT;
radio_descriptor.pins[5].mode_explicit = 1;
radio_descriptor.pins[6].mode = RN2483_PIN_MODE_INPUT;
radio_descriptor.pins[6].mode_explicit = 1;
radio_descriptor.pins[7].mode = RN2483_PIN_MODE_OUTPUT;
radio_descriptor.pins[7].mode_explicit = 1;
radio_descriptor.pins[8].mode = RN2483_PIN_MODE_OUTPUT;
radio_descriptor.pins[8].mode_explicit = 1;
rn2483_poll_gpio(&radio_descriptor);
// Check that none of pins 0 through 4 have been marked dirty
for (enum rn2483_pin pin = 0; pin < 5; pin++) {
ut_assert(radio_descriptor.pins[pin].value_dirty == 0);
}
// Check that pins 5 and 6 have been marked as dirty
ut_assert(radio_descriptor.pins[5].value_dirty == 1);
ut_assert(radio_descriptor.pins[6].value_dirty == 1);
// Check that pins 7 and 8 are not marked dirty
ut_assert(radio_descriptor.pins[7].value_dirty == 0);
ut_assert(radio_descriptor.pins[8].value_dirty == 0);
// Check that none of the other pins where marked as dirty
for (enum rn2483_pin pin = 9; pin < RN2483_NUM_PINS; pin++) {
ut_assert(radio_descriptor.pins[pin].value_dirty == 0);
}
// Check that the driver state was changed tp receive abost
ut_assert(radio_descriptor.state == RN2483_RECEIVE_ABORT);
// Checl that the sercom_uart_has_line function was not called
ut_assert(sercom_uart_has_line_call_count == 0);
// Check that we ran the receive abort state right away
ut_assert(executed_state == RN2483_RECEIVE_ABORT);
}
return UT_PASS;
}
|
C
|
#include <stdio.h>
int main(){
int count,c = 0,n,temp,t,ans;
scanf("%d",&count);
while(c < count){
c++;
ans = 1;
scanf("%d",&n);
int T[n][n];
for(temp = 0;temp < n ;temp++){
for(t = 0;t < n;t++){
scanf("%d",&T[temp][t]);
}
}
for(temp = 0;temp < n;temp++){
for(t = temp;t < n;t++){
if((T[t][temp] != T[temp][t])){
ans = 0;
break;
}
}
}
if(ans == 1)printf("Test #%d: Symmetric.\n",c);
else printf("Test #%d: Non-symmetric.\n",c);
}
return 0;
}
|
C
|
#include <sys/types.h>
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define BUFFSIZE 32768
int
main(int argc, char **argv) {
char filename[80];
char buf[BUFFSIZE];
int n;
int name_length;
/* * * * given code * * * * */
while ((dirp = readdir(dp)) != NULL ){
printf("%s\n", dirp->d_name);
memset(filename, '\0', sizeof(filename));
strcpy(filename, dirp->d_name);
printf(" ** %s ", filename);
name_length = strlen(filename);
printf(" name_length=%d \n", name_length);
/* * * * * * * * * * * */
if (strstr(filename,".c\0") != NULL){ //test for .c only at end, only print if found
while ((n = read(filename, buf, BUFFSIZE)) > 0) {
//simple-cat code except read from filename instead of stdin
if (write(STDOUT_FILENO, buf, n) != n) {
fprintf(stderr, "write error\n");
exit(1);
}
}
if (n < 0) {
fprintf(stderr, "read error\n");
exit(1);
}
}
}
return(0);
}
|
C
|
/*5. Write a C program to read the data from hyper terminal and Print the
same on LCD panel.*/
#include<avr/io.h>
#include<avr/interrupt.h>
#include<util/delay.h>
#define PRT PORTA
#define RS 0
#define RW 1
#define EN 2
void delay_ms(int d);
void delay(int d);
void LCD_init(void);
void goto_LCD(unsigned char x,unsigned char y);
void lcd_command(unsigned char cmd);
void LCD_Data(unsigned char data);
void LCD_string(unsigned char *ptr);
unsigned char buff;
int i=0;
int j=1;
ISR(USART0_RX_vect)
{
/*PUT DATA INTO BUFFER*/
buff=UDR0;
i++;
if(i==17)
{
j=2;
i=1;
}
// return 0;
}
int main()
{
UBRR0L=12;
UCSR0B=(1<<RXEN0)|(1<<RXCIE);
UCSR0C=(3<<UCSZ00);
LCD_init();
goto_LCD(1,1);
LCD_string("start");
sei ();
while(1){
goto_LCD(i,j);
LCD_string(&buff);
}
}
void goto_LCD(unsigned char x,unsigned char y)
{
unsigned char arr[]= {0x80,0xc0};
lcd_command(arr[y-1] + (x-1));
delay_ms(100);
}
void lcd_command(unsigned char cmd)
{
PRT = ((PRT & 0x0F) | (cmd & 0xF0));
PRT &= (~(1<<RS));
PRT &= (~(1<<RW));
PRT |= (1<<EN);
delay_ms(1);
PRT &= (~(1<<EN));
delay_ms(20);
PRT = ((PRT & 0x0F) | (cmd <<4));
PRT |= (1<<EN);
delay_ms(1);
PRT &= (~(1<<EN));
}
void LCD_Data(unsigned char data)
{
PRT = ((PRT & 0x0F) | (data & 0xF0));
PRT |= ((1<<RS));
PRT &= (~(1<<RW));
PRT |= (1<<EN);
delay_ms(1);
PRT &= (~(1<<EN));
delay_ms(20);
PRT = ((PRT & 0x0F) | (data <<4));
PRT |= (1<<EN);
delay_ms(1);
PRT &= (~(1<<EN));
}
void LCD_string(unsigned char *ptr)
{
unsigned char i=0;
while(ptr[i] != 0)
{
LCD_Data(ptr[i]);
i++;
}
}
void LCD_init(void)
{
DDRA = 0xFF;
PRT &= (~(1<<EN));
delay_ms(2000);
lcd_command(0x33);
delay_ms(100);
lcd_command(0x32);
delay_ms(100);
lcd_command(0x0e);
delay_ms(100);
lcd_command(0x01);
delay_ms(1000);
lcd_command(0x06);
delay_ms(100);
}
void delay_ms(int d)
{
_delay_us(d);
}
void delay(int d)
{
_delay_ms(d);
}
|
C
|
// 2 05
#include <stdio.h>
int main(void)
{
int a[] = { 65,25,45,35,55 };
int i, j, tmp, n;
n = sizeof(a) / sizeof(int);
puts("---------------------");
puts(" * * ");
puts("---------------------");
//
puts(" ** **");
for (i = 0; i < n; i++)
printf("a[%d] = %d \n", i, a[i]);
// (Selection sort)
for (i = 0; i < n - 1; i++)
{
for (j = i + 2; j < n; j++) // j= i+2 == Ǿ -> İ
{
if (a[i] > a[j])
{
tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
}
}
//
puts(" \n ** ** ");
for (i = 0; i < n; i++)
printf("a[%d] = %d \n", i, a[i]);
puts("---------------------");
return 0;
}
|
C
|
/* mpu9250.c
* Control routines for Invensense MPU-9250 9-axis IMU
*/
#include "mpu9250.h"
// Read two sequential 8-bit registers and return the 16-bit value
// Assumes that the high byte is in the lower register (first to be read out)
s16 mpu_read_reg16(u8 addr)
{
// Send the address
XIic_Send(I2C_BASEADDR, I2C_IMU_ADDR, &addr, 1, XIIC_STOP);
// Receive the data
u8 bytes[2];
XIic_Recv(I2C_BASEADDR, I2C_IMU_ADDR, bytes, 2, XIIC_STOP);
// Return a 16-bit value
s16 val = (s16)bytes[0] << 8;
return(val | bytes[1]);
}
// Test the IMU
/*
while(1){
s16 accX = mpu_read_reg16(MPU_ACC_X);
s16 accY = mpu_read_reg16(MPU_ACC_Y);
s16 accZ = mpu_read_reg16(MPU_ACC_Z);
s16 gyroX = mpu_read_reg16(MPU_GYRO_X);
s16 gyroY = mpu_read_reg16(MPU_GYRO_Y);
s16 gyroZ = mpu_read_reg16(MPU_GYRO_Z);
printf("Acc X %5d Y %5d Z %5d Gyro X %5d Y %5d Z %5d\n",
accX, accY, accZ, gyroX, gyroY, gyroZ);
}
*/
|
C
|
#include "led.h"
#include <libopencm3/stm32/rcc.h>
#include <libopencm3/stm32/gpio.h>
void led_setup()
{
/* Enable GPIOC clock. */
rcc_periph_clock_enable(RCC_GPIOC);
/* Set GPIO13 (in GPIOC) to 'output push-pull'. */
gpio_set_mode(GPIOC, GPIO_MODE_OUTPUT_2_MHZ,
GPIO_CNF_OUTPUT_PUSHPULL, GPIO13);
gpio_set(GPIOC, GPIO13);
}
void led_write(uint8_t chan, uint16_t data)
{
(void) chan;
if(data & 1) {
gpio_clear(GPIOC, GPIO13);
} else {
gpio_set(GPIOC, GPIO13);
}
}
uint16_t led_read(uint8_t chan)
{
(void) chan;
uint16_t state = gpio_get(GPIOC, GPIO13);
return (state >> 13) & 1;
}
void led_handle(uint8_t chan, uint8_t cmd, uint16_t data)
{
(void) chan;
(void) cmd;
(void) data;
/* No custom commands, stubbed. */
}
const wmio_periph_t led_periph = {
.id = 1,
.setup = led_setup,
.write = led_write,
.read = led_read,
.handle = led_handle,
};
|
C
|
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
void md5_to_str(uint8_t *md5, uint32_t len, uint8_t *str)
{
int i=0;
for ( ; i<len; ++i)
{
snprintf(str, 3, "%02x", *(md5+i));
str += 2;
}
}
void str_to_md5(uint8_t *str, uint32_t len, uint8_t *md5)
{
int i=0;
for ( ; i<len; )
{
sscanf(str, "%02x", md5);
str += 2;
md5 += 1;
i += 2;
}
}
int main()
{
uint8_t *str = (uint8_t *)calloc(33, sizeof(uint8_t));
uint8_t *md5 = (uint8_t *)calloc(16, sizeof(uint8_t));
strcpy(str, "0000012345678abcdef0");
str_to_md5(str, 20, md5);
int i = 0;
for ( ; i<8; ++i)
{
printf("0x%02x ", *(md5+i));
}
printf("\n");
uint8_t str2[33];
str2[0] = 0;
md5_to_str(md5, 10, str2);
printf("str2 len is %d\n", strlen(str2));
printf("%s\n", str2);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void newp(const int el){
int mas[el];
int ch;
for(ch=0; ch<el;ch++){
mas[ch] = rand() % 100;
printf("%d ", mas[ch]);
}
}
int main(int argc, char *argv[]){
srand(time(NULL));
int bl;
scanf("%d", &bl);
newp(bl);
getchar();
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
#define MAX_COL 80
#define MAX_ROW 25
#define BREAK_COL 62
#define BREAK_COL_C 12
int c_row, c_col;
FILE *in, *out;
char *data = NULL;
void print_table(void);
void in_store(void);
void out_store(void);
void disp_store(void);
void clear_disp(void);
int main(void)
{
char command[4];
c_row = 4, c_col = 2;
print_table();
for (;;){
if (c_row == MAX_ROW){
c_row = 4;
print_table();
}
gotoxy(c_col, c_row);
textcolor(YELLOW);
cprintf("Input: ");
for (int i = 0; i < 3; i++){
command[i] = getch();
textcolor(RED);
gotoxy(9 + i, c_row);
cprintf("%c", command[i]);
if (command[i] == '\r'){
command[i] = '\0';
break;
}
}
command[3] = '\0';
if (strcmp(command, "i") == 0){
c_row++;
disp_store();
continue;
}
else if (strcmp(command, "ii") == 0){
c_row++;
in_store();
continue;
}
else if (strcmp(command, "iii") == 0){
c_row++;
out_store();
continue;
}
else if (strcmp(command, "iv") == 0)
return 0;
if (strcmp(command, "vi") == 0){
c_row++;
clear_disp();
continue;
}
else{
gotoxy(BREAK_COL_C + 4, c_row);
printf("Illegal command, try again.\n");
c_row++;
continue;
}
}
}
void print_table(void)
{
clrscr();
for (int i = 0; i < MAX_ROW; i++){
for (int j = 0; j < MAX_COL; j++){
if (i == 0 || i == MAX_ROW - 1 ||
(i == 2 && j != BREAK_COL - 1 && j != MAX_COL - 1 && j != 0))
printf("-");
else if (j == 0 || j == BREAK_COL - 1 || j == MAX_COL - 1 ||
(j == BREAK_COL_C && i != 0 && i != 2 && i != MAX_ROW - 1))
printf("|");
else
printf(" ");
}
}
gotoxy(BREAK_COL / 2 - 10, 2);
printf("Wareouse\tAuthor: HolmesQiao");
gotoxy(BREAK_COL + 7, 2);
printf("Command");
gotoxy(BREAK_COL + 10, 4);
printf("i");
gotoxy(BREAK_COL + 2, 5);
printf("Display the data");
gotoxy(BREAK_COL + 9, 7);
printf("ii");
gotoxy(BREAK_COL + 4, 8);
printf("Store goods");
gotoxy(BREAK_COL + 8, 10);
printf("iii");
gotoxy(BREAK_COL + 2, 11);
printf("Take out goods");
gotoxy(BREAK_COL + 9, 13);
printf("iv");
gotoxy(BREAK_COL + 8, 14);
printf("Quit");
gotoxy(BREAK_COL + 9, 16);
printf("vi");
gotoxy(BREAK_COL + 4, 17);
printf("clean screen");
}
void in_store(void)
{
if ((in = fopen("store_data.txt", "w")) == NULL){
printf("File cannot be opened");
exit(0);
}
char new_data[100];
gotoxy(BREAK_COL_C + 2, --c_row);
printf("Enter the goods to store: (modle num price)");
gotoxy(BREAK_COL_C + 2, (++c_row)++);
gets(new_data);
if (data == NULL){
data = (char *)malloc(sizeof(char));
strcpy(data ,new_data);
}
else
strcat(data, new_data);
fprintf(in, "%s", data);
fclose(in);
}
void out_store(void)
{
int value = 0;
if ((in = fopen("store_data.txt", "w")) == NULL){
printf("File cannot be opened\n");
exit(0);
}
char out_data[100];
gotoxy(BREAK_COL_C + 2, --c_row);
printf("Enter the goods to out: (modle remine_num)");
gotoxy(BREAK_COL_C + 2, (++c_row)++);
gets(out_data);
int data_len = strlen(data), out_len = strlen(out_data);
for (int i = 0 ; i < data_len - out_len + 1; i++){
if (data[i] == out_data[0]){
for (int j = i; j < i + out_len; i++){
if (data[j] == out_data[j - i])
value = 1;
else{
value = 0;
break;
}
}
if (value){
value = 0;
for (int k = i; k < i + out_len; k++){
if(data[i] == ' '){
i++;
value = 1;
}
if (value){
data[i] = out_data[k - i];
}
}
}
}
}
fprintf(in, "%s", data);
fclose(in);
}
void disp_store(void)
{
char ch;
clear_disp();
gotoxy(BREAK_COL_C + 2, c_row++);
printf("Model\tNUM\tPrice");
if ((out = fopen("store_data.txt", "r")) == NULL){
printf("File cannot be opened");
exit(0);
}
gotoxy(BREAK_COL_C + 2, c_row);
int i = 0;
while ((ch = getc(out)) != EOF){
if (ch == ' '){
printf("\t");
i++;
}
else
printf("%c", ch);
if (i == 3){
c_row++;
i = 0;
gotoxy(BREAK_COL_C + 2, c_row);
}
}
fclose(out);
}
void clear_disp(void)
{
for (int i = 4; i < MAX_ROW - 1; i++)
for (int j = BREAK_COL_C + 2; j < BREAK_COL - 1; j++){
gotoxy(j, i);
printf(" ");
}
c_col = 2;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int data;
struct node *next;
} Node;
void detect_removeLoop(Node *head)
{
Node *slow = head;
Node *fast = head;
while (slow && fast && fast->next)
{
slow = slow->next;
fast = fast->next->next;
if (slow == fast)
{
break;
}
}
if(slow == fast){
slow = head;
while(slow->next!=fast->next){
slow = slow->next;
fast = fast->next;
}
fast->next = NULL;
}
}
void print(struct node *temp){
while(temp!=NULL){
printf("%d ",temp->data);
temp = temp->next;
}
}
void main()
{
Node *first = (Node *)malloc(sizeof(Node));
Node *second = (Node *)malloc(sizeof(Node));
Node *third = (Node *)malloc(sizeof(Node));
Node *fourth = (Node *)malloc(sizeof(Node));
Node *fifth = (Node *)malloc(sizeof(Node));
Node *sixth = (Node *)malloc(sizeof(Node));
Node *seventh = (Node *)malloc(sizeof(Node));
first->data = 1;
first->next = second;
second->data = 2;
second->next = third;
third->data = 3;
third->next = fourth;
fourth->data = 4;
fourth->next = fifth;
fifth->data = 5;
fifth->next = sixth;
sixth->data = 6;
sixth->next = seventh;
seventh->data = 10;
seventh->next = third;
detect_removeLoop(first);
print(first);
}
|
C
|
#ifndef UTILS_H
#define UTILS_H
/*
* Function returns least common denominator of two numbers.
*/
int LeastCommonDenominator(int a, int b);
/*
* Function returns greatest common divisor of two numbers.
* Euclid's algorithm for integers is used.
*/
int GreatestCommonDivisor(int p, int q);
#endif /* UTILS_H */
|
C
|
#ifndef LIST_H
#define LIST_H
struct node {
char *name;
char *surname;
char *bdate;
char *email;
long int contact;
char *address;
struct node *next;
struct node *prev;
} ;
struct list {
struct node *head;
struct node *tail;
};
struct list *init(void);
struct node *create_node(char *n, char *s, char *b, char *e, long int c, char *a);
void insert_at_the_end(struct list *list, struct node *tmp);
void insert_at_the_beginning(struct list *list, struct node *tmp);
int length_list(struct list *list, struct node *h, struct node *t);
int two_string_compare(struct node *node1, struct node *node2);
struct node *finding_node(struct list *list, char *name, char *surname);
struct node* merge(struct node* a, struct node* b);
struct node* mergesort(struct node* head);
struct node* find_middle(struct node* head);
void remove_from_list(struct list *list, struct node *rmv);
void show_list(struct list* list);
void show_list_reverse(struct list* list);
void show_node(struct list *list, int i);
void show_node2(struct node *tmp);
void set_new_list(struct list* lista, struct node* head);
void delete_list(struct list *list);
#endif
|
C
|
/* ------------------------------------------------------------------------
phase4.c
University of Arizona South
Computer Science 452
@authors: Erik Ibarra Hurtado, Hassan Martinez, Victor Alvarez
------------------------------------------------------------------------ */
#include <stdlib.h>
#include <stdio.h>
#include <strings.h>
#include <usloss.h>
#include <phase1.h>
#include <phase2.h>
#include <phase3.h>
#include <phase4.h>
#include <usyscall.h>
#include <libuser.h>
#include <provided_prototypes.h>
#include "driver.h"
/* ------------------------- Prototypes ----------------------------------- */
int start3 (char *);
static int ClockDriver(char *);
static int DiskDriver(char *);
static void sleep(sysargs *);
static void disk_read(sysargs *);
static void disk_write(sysargs *);
static void disk_size(sysargs *);
int insert_sleep_q(driver_proc_ptr);
int remove_sleep_q(driver_proc_ptr);
int insert_disk_q(driver_proc_ptr);
int remove_disk_q(driver_proc_ptr);
void check_kernel_mode(char *);
void bug_flag(char *, bool, int);
/* -------------------------- Globals ------------------------------------- */
static int debugflag4 = 0;
static int running; /*semaphore to synchronize drivers and start3*/
static struct driver_proc Driver_Table[MAXPROC];
struct driver_proc empty_proc = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
driver_proc_ptr SleepQ = NULL;
int sleep_number = 0;
driver_proc_ptr DQ = NULL;
int DQ_number = 0;
bool exit_logic = false;
static int diskpids[DISK_UNITS];
static int num_tracks[DISK_UNITS];
static int sleep_semaphore;
static int disk_semaphore;
static int DQ_semaphore;
static int driver_sync_semaphore;
/* -------------------------- Functions ----------------------------------- */
/* start3 */
int start3(char *arg)
{
char name[128];
char termbuf[10];
int i;
int clockPID;
int pid;
int status;
/* Check kernel mode here */
check_kernel_mode("start3(): Not in kernel mode");
/* Assignment system call handlers */
bug_flag("start3(): sys_vec assignment.", false, 0);
sys_vec[SYS_SLEEP] = sleep;
sys_vec[SYS_DISKREAD] = disk_read;
sys_vec[SYS_DISKWRITE] = disk_write;
sys_vec[SYS_DISKSIZE] = disk_size;
/* Initialize the phase 4 process table */
bug_flag("start3(): process table.", false, 0);
for (int i = 0; i < MAXPROC; i++)
{
Driver_Table[i] = empty_proc;
Driver_Table[i].private_sem = semcreate_real(0);
}
/*
* Create clock device driver
* I am assuming a semaphore here for coordination. A mailbox can
* be used insted -- your choice.
*/
bug_flag("start3(): create semaphores.", false, 0);
sleep_semaphore = semcreate_real(1);
disk_semaphore = semcreate_real(0);
DQ_semaphore = semcreate_real(1);
running = semcreate_real(0);
driver_sync_semaphore = semcreate_real(1);
bug_flag("start3(): fork clock driver.", false, 0);
clockPID = fork1("Clock driver", ClockDriver, NULL, USLOSS_MIN_STACK, 2);
if (clockPID < 0)
{
console("start3(): Can't create clock driver\n");
halt(1);
}
/*
* Wait for the clock driver to start. The idea is that ClockDriver
* will V the semaphore "running" once it is running.
*/
bug_flag("start3(): semp on running sem.", false, 0);
semp_real(running);
/*
* Create the disk device drivers here. You may need to increase
* the stack size depending on the complexity of your
* driver, and perhaps do something with the pid returned.
*/
bug_flag("start3(): fork drisk drivers.", false, 0);
for (i = 0; i < DISK_UNITS; i++)
{
sprintf(termbuf, "%d", i);
sprintf(name, "DiskDriver%d", i);
diskpids[i] = fork1(name, DiskDriver, termbuf, USLOSS_MIN_STACK, 2);
if (diskpids[i] < 0)
{
console("start3(): Can't create disk driver %d\n", i);
halt(1);
}
}
bug_flag("start3(): semp on running sem x2.", false, 0);
semp_real(running);
semp_real(running);
/*
* Create first user-level process and wait for it to finish.
* These are lower-case because they are not system calls;
* system calls cannot be invoked from kernel mode.
* I'm assuming kernel-mode versions of the system calls
* with lower-case names.
*/
bug_flag("start3(): spawn start4 and wait on it.", false, 0);
pid = spawn_real("start4", start4, NULL, 8 * USLOSS_MIN_STACK, 3);
pid = wait_real(&status);
/* Zap the device drivers */
bug_flag("start3(): zap and join clock driver.", false, 0);
zap(clockPID); // clock driver
join(&status); /* for the Clock Driver */
bug_flag("start3(): 'zap' and join disk drivers", false, 0);
for (i = 0; i < DISK_UNITS; i++)
{
exit_logic = true;
bug_flag("start3(): semv disk_semaphore", false, 0);
semv_real(disk_semaphore);
bug_flag("start3(): join", false, 0);
join(&status);
}
/* quit state to join next. */
quit(0);
return 0;
} /* start3 */
/* ClockDriver */
static int ClockDriver(char *arg)
{
int result;
int status;
int current_time;
driver_proc_ptr proc_ptr, proc_to_wake;
/*
* Let the parent know we are running and enable interrupts.
*/
bug_flag("ClockDriver(): semv on running semaphore.", false, 0);
semv_real(running);
psr_set(psr_get() | PSR_CURRENT_INT);
while(! is_zapped())
{
result = waitdevice(CLOCK_DEV, 0, &status);
if (result != 0)
{
return 0;
}
/*
* Compute the current time and wake up any processes
* whose time has come.
*/
current_time = sys_clock();
proc_ptr = SleepQ;
while (proc_ptr != NULL)
{
proc_to_wake = proc_ptr;
proc_ptr = proc_ptr->next_ptr;
/* Check current time to wake time. */
if (current_time >= proc_to_wake->wake_time)
{
bug_flag("ClockDriver(): removing proc from SleepQ.", false, 0);
sleep_number = remove_sleep_q(proc_to_wake);
bug_flag("ClockDriver(): waking proc.", false, 0);
semv_real(proc_to_wake->private_sem);
}
}
}
/* quit state to join next. */
quit(0);
} /* ClockDriver */
/* DiskDriver */
static int DiskDriver(char *arg)
{
int unit = atoi(arg);
device_request my_request;
int result;
int status;
int counter;
int current_track;
int current_sector;
bug_flag("DiskDriver(): semv on running semaphore.", true, unit);
psr_set(psr_get() | PSR_CURRENT_INT);
driver_proc_ptr current_req;
bug_flag("DiskDriver(): started.", true, unit);
/* Get the number of tracks for this disk */
bug_flag("DiskDriver(): getting # of tracks for disk.", true, unit);
my_request.opr = DISK_TRACKS;
my_request.reg1 = &num_tracks[unit];
result = device_output(DISK_DEV, unit, &my_request);
if (result != DEV_OK)
{
console("DiskDriver (%d): did not get DEV_OK on DISK_TRACKS call\n", unit);
console("DiskDriver (%d): is the file disk%d present???\n", unit, unit);
halt(1);
}
waitdevice(DISK_DEV, unit, &status);
if (DEBUG4 && debugflag4)
{
console("DiskDriver(%d): tracks = %d\n", unit, num_tracks[unit]);
}
/* start3 driver running. */
semv_real(running);
bug_flag("DiskDriver(): enter while loop till zapped.", true, unit);
while (exit_logic != true)
{
/* Wait request from user. */
bug_flag("DiskDriver(): semp on disk semaphore to wait for requests.", true, unit);
semp_real(disk_semaphore);
/* Set next request for DiskQ. */
bug_flag("DiskDriver(): setting current_req = DQ.", true, unit);
current_req = DQ;
if (current_req != NULL)
{
/* Check disk_size request. */
bug_flag("DiskDriver(): checking current_req operation type.", true, unit);
if (current_req->operation == DISK_SIZE)
{
/* Critical region in. */
bug_flag("DiskDriver(): size - semP on dq_sem to enter critical region.", true, unit);
semp_real(DQ_semaphore);
DQ_number = remove_disk_q(current_req);
/* Critical region out. */
bug_flag("DiskDriver(): size - semV on DQ_sem to leave critical region.", true, unit);
semv_real(DQ_semaphore);
/* Wake up user. */
bug_flag("DiskDriver(): size - semV on private_sem to unblock proc.", true, unit);
semv_real(current_req->private_sem);
}
else
{
/* Critical region in. */
bug_flag("DiskDriver(): rw - semp on dq_sem to enter critical region.", true, unit);
semp_real(DQ_semaphore);
DQ_number = remove_disk_q(current_req);
/* Critical region out. */
bug_flag("DiskDriver(): rw - semV on DQ_sem to leave critical region.", true, unit);
semv_real(DQ_semaphore);
/* Critical region in for disk operations. */
bug_flag("DiskDriver(): rw - semp on driver_sync sem enter region.", true, unit);
semp_real(driver_sync_semaphore);
/* Adjust disk_seek. */
my_request.opr = DISK_SEEK;
my_request.reg1 = current_req->track_start;
result = device_output(DISK_DEV, current_req->unit, &my_request);
if (result != DEV_OK)
{
console("DiskDriver (%d): did not get DEV_OK on 1st DISK_SEEK call\n", unit);
console("DiskDriver (%d): is the file disk%d present???\n", unit, current_req->unit);
halt(1);
}
waitdevice(DISK_DEV, current_req->unit, &status);
/* Set read/write loop variables. */
current_track = current_req->track_start;
current_sector = current_req->sector_start;
counter = 0;
/* read/write operations. */
while (counter != current_req->num_sectors)
{
my_request.opr = current_req->operation;
my_request.reg1 = current_sector;
my_request.reg2 = ¤t_req->disk_buf[counter * DISK_SECTOR_SIZE];
result = device_output(DISK_DEV, current_req->unit, &my_request);
if (result != DEV_OK)
{
console("DiskDriver (%d): did not get DEV_OK on %d call\n", unit, current_req->operation);
console("DiskDriver (%d): is the file disk%d present???\n", unit, current_req->unit);
halt(1);
}
waitdevice(DISK_DEV, current_req->unit, &status);
current_req->status = status;
/* Check to finish reading/writing. */
counter++;
if (counter != current_req->num_sectors)
{
/* Update sector. */
current_sector++;
/* Test for sector's out of bound. */
if (current_sector >= DISK_TRACK_SIZE)
{
current_track = (current_track + 1) % num_tracks[unit];
current_sector = 0;
my_request.opr = DISK_SEEK;
my_request.reg1 = current_track;
result = device_output(DISK_DEV, current_req->unit, &my_request);
if (result != DEV_OK)
{
console("DiskDriver (%d): did not get DEV_OK on DISK_SEEK call\n", unit);
console("DiskDriver (%d): is the file disk%d present???\n", unit, current_req->unit);
halt(1);
}
waitdevice(DISK_DEV, current_req->unit, &status);
}
}
}
/* Critical region out. */
bug_flag("DiskDriver(): rw - semv on driver_sync sem leave region.", true, unit);
semv_real(driver_sync_semaphore);
}
/* Wake up user. */
bug_flag("DiskDriver(): rw - semv on private_sem to unblock proc.", true, unit);
semv_real(current_req->private_sem);
}
}
/* quit state to joing next. */
quit(0);
} /* DiskDriver */
/* sleep */
static void sleep(sysargs *args_ptr)
{
/* Temps. */
int seconds;
int result;
driver_proc_ptr current_proc;
current_proc = &Driver_Table[getpid() % MAXPROC];
/* Set value. */
seconds = (int) args_ptr->arg1;
/* Validating seconds can't have negative time. If so return.*/
if (seconds < 0)
{
result = -1;
args_ptr->arg4 = (void *) result;
return;
}
/* Enter critical region. */
bug_flag("sleep(): call semp on sleep_sem.", false, 0);
semp_real(sleep_semaphore);
bug_flag("sleep(): call insert_sleep_q.", false, 0);
sleep_number = insert_sleep_q(current_proc);
/* Save time for sleep. */
current_proc->wake_time = sys_clock();
current_proc->wake_time = (seconds * 1000000) + current_proc->wake_time;
bug_flag("sleep(): call semv on sleep_sem.", false, 0);
semv_real(sleep_semaphore);
bug_flag("sleep(): call semp on proccesse private sem to block it.", false, 0);
semp_real(current_proc->private_sem);
/* Set result arg4 to 0. */
result = 0;
args_ptr->arg4 = (void *) result;
return;
} /* sleep */
/* disk_read */
static void disk_read(sysargs *args_ptr)
{
/* Temps. */
int unit;
int track;
int first;
int sectors;
void *buffer;
int status;
int result = 0;
driver_proc_ptr current_proc;
current_proc = &Driver_Table[getpid() % MAXPROC];
buffer = args_ptr->arg1;
sectors = (int) args_ptr->arg2;
track = (int) args_ptr->arg3;
first = (int) args_ptr->arg4;
unit = (int) args_ptr->arg5;
/* Testing arguments. */
if (unit < 0 || unit > 1) //disk unit #
{
result = -1;
}
if (sectors < 0) //# of sectors to read
{
result = -1;
}
if (track < 0 || track >= num_tracks[unit]) //starting track #
{
result = -1;
}
if (first < 0 || first > 15) //starting sector #
{
result = -1;
}
/* Testing for error value. */
if (result == -1)
{
bug_flag("disk_read(): error value return. ", false, 0);
args_ptr->arg1 = (void *) result;
args_ptr->arg4 = (void *) result;
return;
}
/* Critical region in. */
bug_flag("disk_read(): call semP on DQ_semaphore.", false, 0);
semp_real(DQ_semaphore);
/* Drive request. */
current_proc->operation = DISK_READ;
current_proc->unit = unit; // which disk unit in read
current_proc->track_start = track; // starting track
current_proc->sector_start = first; // starting sector
current_proc->num_sectors = sectors; // # sectors
current_proc->disk_buf = buffer; // buffer
/* Insert DQ. */
DQ_number = insert_disk_q(current_proc);
/* Critical region out. */
bug_flag("disk_read(): call semV on DQ_sem.", false, 0);
semv_real(DQ_semaphore);
/* Send Disk Driver an entry in DQ. */
semv_real(disk_semaphore);
/* Wait Disk Driver to complete operations. */
bug_flag("disk_read(): call semp on proc's private sem to block it.", false, 0);
semp_real(current_proc->private_sem);
/* Set arg's values. */
status = current_proc->status;
args_ptr->arg1 = (void *) status;
args_ptr->arg4 = (void *) result;
return;
} /* disk_read */
/* disk_write */
static void disk_write(sysargs *args_ptr)
{
/* Temps. */
int unit;
int track;
int first;
int sectors;
void *buffer;
int status;
int result = 0;
int flag;
driver_proc_ptr current_proc;
current_proc = &Driver_Table[getpid() % MAXPROC];
buffer = args_ptr->arg1;
sectors = (int) args_ptr->arg2;
track = (int) args_ptr->arg3;
first = (int) args_ptr->arg4;
unit = (int) args_ptr->arg5;
/* Testing arguments. */
if (unit < 0 || unit > 1) //disk unit #
{
result = -1;
flag = 0;
}
if (sectors < 0) //# of sectors to read
{
result = -1;
flag = 1;
}
if (track < 0 || track >= num_tracks[unit]) //starting track #
{
result = -1;
flag = 2;
}
if (first < 0 || first > 15) //starting sector #
{
result = -1;
flag = 3;
}
/* Testing for error value. */
if (result == -1)
{
bug_flag("disk_write(): error (illegal value) = ", true, flag);
args_ptr->arg1 = (void *) result;
args_ptr->arg4 = (void *) result;
return;
}
/* Critical region in. */
bug_flag("disk_write(): call semp on DQ_sem.", false, 0);
semp_real(DQ_semaphore);
/* Drive request. */
current_proc->operation = DISK_WRITE;
current_proc->unit = unit; // which disk unit in write
current_proc->track_start = track; // starting track
current_proc->sector_start = first; // starting sector
current_proc->num_sectors = sectors; // # of sectors
current_proc->disk_buf = buffer; // buffer
/* Insert DQ. */
DQ_number = insert_disk_q(current_proc);
/* Critical region out. */
bug_flag("disk_write(): call semV on DQ_sem.", false, 0);
semv_real(DQ_semaphore);
/* Send Disk Driver an entry in DQ. */
semv_real(disk_semaphore);
/* Wait Disk Driver to complete operations. */
bug_flag("disk_write(): call semp on proc's private sem to block it.", false, 0);
semp_real(current_proc->private_sem);
/* Set arg's values. */
status = current_proc->status;
args_ptr->arg1 = (void *) status;
args_ptr->arg4 = (void *) result;
return;
} /* disk_write */
/* disk_size */
static void disk_size(sysargs *args_ptr)
{
/* Temps. */
int unit;
int sector;
int track;
int disk;
int result;
driver_proc_ptr current_proc;
current_proc = &Driver_Table[getpid() % MAXPROC];
/* Set value. */
unit = (int) args_ptr->arg1;
/* Testing input value. */
if (unit < 0 || unit > 1)
{
result = -1;
console("disk_size(): illegal value, unit < 0 or > 1.\n");
args_ptr->arg4 = (void *) result;
return;
}
/* Critical region in. */
bug_flag("disk_size_real(): call semP on DQ_sem.", false, 0);
semp_real(DQ_semaphore);
current_proc->operation = DISK_SIZE;
DQ_number = insert_disk_q(current_proc);
/* Critical region out. */
bug_flag("disk_size_real(): call semV on DQ_sem.", false, 0);
semv_real(DQ_semaphore);
/* Send Disk Driver an entry in DQ. */
semv_real(disk_semaphore);
/* Wait Disk Driver to complete operations. */
bug_flag("disk_size_real(): call semp on proc's private sem to block it.", false, 0);
semp_real(current_proc->private_sem);
/* Set arg's values. */
sector = DISK_SECTOR_SIZE;
track = DISK_TRACK_SIZE;
disk = num_tracks[unit];
result = 0;
args_ptr->arg1 = (void *) sector;
args_ptr->arg2 = (void *) track;
args_ptr->arg3 = (void *) disk;
args_ptr->arg4 = (void *) result;
return;
} /* disk_size */
/* insert_sleep_q */
int insert_sleep_q(driver_proc_ptr proc_ptr)
{
int num_sleep_procs = 0;
driver_proc_ptr walker;
walker = SleepQ;
if (walker == NULL)
{
/* process goes at front of SleepQ */
bug_flag("insert_sleep_q(): SleepQ was empty, now has 1 entry.", false, 0);
SleepQ = proc_ptr;
num_sleep_procs++;
}
else
{
bug_flag("insert_sleep_q(): SleepQ wasn't empty, should have > 1.", false, 0);
num_sleep_procs++; //starts at 1
while (walker->next_ptr != NULL) //counts how many are in Q already
{
num_sleep_procs++;
walker = walker->next_ptr;
}
walker->next_ptr = proc_ptr; //inserts proc to end of Q
num_sleep_procs++; //counts the insert
}
return num_sleep_procs;
} /* insert_sleep_q */
/* remove_sleep_q */
int remove_sleep_q(driver_proc_ptr proc_ptr)
{
int num_sleep_procs = sleep_number;
driver_proc_ptr walker, previous;
walker = SleepQ;
/* Critical region in. */
bug_flag("remove_sleep_q(): semp on sleep_sem.", false, 0);
semp_real(sleep_semaphore);
//if SleepQ is empty
if(num_sleep_procs == 0)
{
//console("remove_sleep_q(): SleepQ empty. Return.\n");
}
//elseif SleepQ has one entry
else if (num_sleep_procs == 1)
{
bug_flag("remove_sleep_q(): SleepQ had 1 entry, now 0.", false, 0);
SleepQ = NULL;
num_sleep_procs--;
}
//else SleepQ has > 1 entry
else
{
bug_flag("remove_sleep_q(): SleepQ had > 1 entry.", false, 0);
if (SleepQ == proc_ptr) //1st entry to be removed
{
SleepQ = walker->next_ptr;
proc_ptr->next_ptr = NULL;
num_sleep_procs--;
}
else //2nd entry or later to be removed
{
while (walker != proc_ptr)
{
previous = walker;
walker = walker->next_ptr;
}
previous->next_ptr = walker->next_ptr;
walker->next_ptr = NULL;
num_sleep_procs--;
}
}
/* Critical region out. */
bug_flag("remove_sleep_q(): semv on sleep_sem.", false, 0);
semv_real(sleep_semaphore);
return num_sleep_procs;
} /* remove_sleep_q */
/* insert_disk_q */
int insert_disk_q(driver_proc_ptr proc_ptr)
{
int num_disk_procs = 0;
driver_proc_ptr walker;
walker = DQ;
if (walker == NULL)
{
/* process goes at front of DQ */
bug_flag("insert_disk_q(): DQ was empty, now has 1 entry.", false, 0);
DQ = proc_ptr;
num_disk_procs++;
}
else
{
bug_flag("inset_disk_q(): DQ wasn't empty, should have > 1.", false, 0);
num_disk_procs++; //starts at 1
while (walker->next_dq_ptr != NULL) //counts how many are in Q already
{
num_disk_procs++;
walker = walker->next_dq_ptr;
}
walker->next_dq_ptr = proc_ptr; //inserts proc to end of Q
num_disk_procs++; //counts the insert
}
return num_disk_procs;
} /* insert_disk_q */
/* remove_disk_q */
int remove_disk_q(driver_proc_ptr proc_ptr)
{
int num_disk_procs = DQ_number;
driver_proc_ptr walker, previous;
walker = DQ;
//if DQ has one entry
if (num_disk_procs == 1)
{
bug_flag("remove_disk_q(): DQ had 1 entry, now 0.", false, 0);
DQ = NULL;
num_disk_procs--;
}
else
{
bug_flag("remove_disk_q(): DQ had > 1 entry.", false, 0);
DQ = walker->next_dq_ptr;
proc_ptr->next_dq_ptr = NULL;
num_disk_procs--;
}
return num_disk_procs;
} /* remove_disk_q */
/* checkKernelMode */
void check_kernel_mode(char * displaymsn)
{
if ((PSR_CURRENT_MODE & psr_get()) == 0) {
console("%s (%d)\n", displaymsn, getpid());
halt(1);
}
} /* checkKernelMode */
/* bug_flag */
void bug_flag(char * displaymsn, bool valuelogic, int value )
{
if(valuelogic == false)
{
if (DEBUG4 && debugflag4) {
console("%s\n", displaymsn);
}
}
if(valuelogic == true)
{
if (DEBUG4 && debugflag4) {
console("%s (%d)\n", displaymsn, value);
}
}
} /* bug_flag */
|
C
|
/*
Student Name=Sunil Giri
Subject=Programming Fundamentals
Roll No.=
Program=to calculate factorial using do while loop.
Lab No.=09
BCS Sem.=1st
Date=26 oct,2016
*/
#include<stdio.h>
//#include<conio.h>
int main(){
int n,fact,a;
g:
printf("Enter Number to calculate factorial:\n");
scanf("%d",&n);
a=1;
fact=1;
do
{
fact*=a;
a++;
}
while(a<=n);
printf("The factorial of %d is %d\n",n,fact);
goto g;
//getch();
return 0;
}
|
C
|
#include "common.h"
int print_table(hash_t array[])
{
int i;
hash_t *temp;
dulist *temp1;
for (i = 0; i < SIZE; i++)
{
temp = &array[i];//.word_link;
if(strcmp(temp->word,"#") == 0)
{
continue;
}
printf("index: %d\t", i);
// printf("num of files: %d\t",temp->no_of_files);
//printf("The word : ");
while(temp)
{
printf("The word ");
printf("'%s' is in %d files ", temp->word, temp->no_of_files);
temp1 = temp->tab_link;
while(temp1)
{
printf(" '%s', ", temp1->file_name);
printf("appearing %d times \t", temp1->wcnt);
temp1 = temp1->dlink;
}
printf("\n");
temp = temp->word_link;
}
printf("\n");
}
return SUCCESS;
}
|
C
|
#include "BST.c"
BST_Node * BST_New_Node(int item);
BST_Node * BST_Insert(BST_Node * node, int key);
BST_Node * BST_Search(BST_Node * root, int x);
BST_Node * BST_Min_Value(BST_Node * node);
BST_Node * BST_Remove(BST_Node * root, int x);
void BST_In_Order(BST_Node * root);
void BST_Preorder(BST_Node * node);
void BST_Postorder(BST_Node * node);
void Lancar_BST(unsigned Vetor[], unsigned Tamanho);
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <SDL/SDL.h>
#include "menu.h"
#include "config.h"
#include "structs.h"
#include "widget.h"
#include "cursor.h"
int main(int argc, char * argv[]){
initSDL(); // Starts the SDL
menu(); // Load main menu
SDL_Quit(); // After menu did its job, stops SDL
return(EXIT_SUCCESS);
}
int initSDL(){
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER) == -1){
perror("! Failed to initialise SDL");
exit(EXIT_FAILURE);
}
if ((screen = SDL_SetVideoMode(WIN_WIDTH, WIN_HEIGHT, 8, SDL_HWSURFACE | SDL_DOUBLEBUF)) == NULL){
perror("! Failed to initialise screen");
SDL_Quit();
exit(EXIT_FAILURE);
}
SDL_WM_SetCaption("Rhum 'n' Money", "Rhum 'n' Money");
SDL_ShowCursor(SDL_DISABLE);
return(1);
}
int menu(){
/* VARS */
widget * background;
widget * new_game;
widget * load_game;
widget * options;
widget * scores;
widget * credits;
widget * quit;
widget * w_curs;
cursor * curs;
widget * tmp;
SDL_Event event;
char cont = 1;
char select = 1;
/* LOAD */
background = WLoadIMG(FIXED, 0, 0, 0, "IMG/menu/background.bmp", NULL);
new_game = WLoadIMG(FIXED, 0, 10, 10, "IMG/menu/newgame.bmp", NULL);
load_game = WLoadIMG(FIXED, 0, 10, 90, "IMG/menu/loadgame.bmp", NULL);
options = WLoadIMG(FIXED, 0, 10, 170, "IMG/menu/options.bmp", NULL);
scores = WLoadIMG(FIXED, 0, 10, 250, "IMG/menu/scores.bmp", NULL);
credits = WLoadIMG(FIXED, 0, 10, 330, "IMG/menu/credits.bmp", NULL);
quit = WLoadIMG(FIXED, 0, 10, 410, "IMG/menu/quit.bmp", NULL);
w_curs = WLoadIMG(LOOP, 130, 0, 0, "IMG/cursor/cursor1.png", "IMG/cursor/cursor2.png", "IMG/cursor/cursor3.png", "IMG/cursor/cursor4.png", "IMG/cursor/cursor5.png", "IMG/cursor/cursor6.png", NULL);
/* ADD CONTENT TO BACKGROUND */
WAddContent(background, new_game);
WAddContent(background, load_game);
WAddContent(background, options);
WAddContent(background, scores);
WAddContent(background, credits);
WAddContent(background, quit);
WAddContent(background, w_curs);
/* CREATE THE CURSOR */
curs = WCreateCursor(w_curs, RIGHT);
WBlit(background);
SDL_Flip(screen);
/* EVENTS */
while(cont){
SDL_PollEvent(&event);
switch(event.type){
/* Left click */
case SDL_MOUSEBUTTONDOWN :
if (event.button.button = SDL_BUTTON_LEFT){
tmp = WArea(background, event.button.x, event.button.y);
if (tmp == new_game){
newGame();
}
if (tmp == load_game){
loadGame();
}
if (tmp == options){
showOptions();
}
if (tmp == scores){
showScores();
}
if (tmp == credits){
showCredits();
}
if (tmp == quit){
cont = 0;
}
}
break;
case SDL_QUIT :
cont = 0;
break;
/* Keyboard event */
case SDL_KEYDOWN :
switch (event.key.keysym.sym){
case SDLK_DOWN :
if (select < 6){
select ++;
}
break;
case SDLK_UP :
if (select > 1){
select --;
}
break;
case SDLK_RETURN :
switch (select){
case 1 :
newGame();
break;
case 2 :
loadGame();
break;
case 3 :
showOptions();
break;
case 4 :
showScores();
break;
case 5 :
showCredits();
break;
case 6 :
cont = 0;
break;
}
break;
}
break;
/* If the mouse moves... */
case SDL_MOUSEMOTION :
WMoveCursor(curs, event.button.x, event.button.y);
break;
}
event.type = 0;
/* Refresh */
WFlip(background);
WBlit(background);
SDL_Flip(screen);
}
/* FREE */
WFreeCursor(curs);
WFree(background);
return(1);
}
int newGame(){
printf("¤ Launching new game...\n");
return(1);
}
int loadGame(){
printf("¤ Loading old save...\n");
return(1);
}
void showOptions(){
printf("¤ Showing options...\n");
}
void showScores(){
printf("¤ Showing scores...\n");
}
void showCredits(){
printf("¤ Showing credits...\n");
}
|
C
|
#include "fifo.h"
// Tamar Bacalu & Mark Koszykowski
// ECE357 - Operating Systems Problem Set 6, 2C
void fifo_init(struct fifo *f) {
f->readInd = 0;
f->writeInd = 0;
sem_init(&f->mutex, 1);
sem_init(&f->empty, 0);
sem_init(&f->full, MYFIFO_BUFSIZ);
}
void fifo_wr(struct fifo *f, unsigned long d) {
sem_wait(&f->full);
while(!sem_try(&f->mutex)) {}
f->f[f->writeInd++] = d;
f->writeInd %= MYFIFO_BUFSIZ;
sem_inc(&f->empty);
sem_inc(&f->mutex);
}
unsigned long fifo_rd(struct fifo *f) {
unsigned long d;
sem_wait(&f->empty);
while(!sem_try(&f->mutex)) {}
d = f->f[f->readInd++];
f->readInd %= MYFIFO_BUFSIZ;
sem_inc(&f->full);
sem_inc(&f->mutex);
return d;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
/*Crie um aplicativo em C que pea um nmero inteiro ao usurio N e exiba o n-simo termo da srie de
Fibonacci, sabendo que o primeiro termo 0, o
segundo 1 e o prximo nmero sempre a soma dos dois anteriores.
Ex.: 0 1 1 2 3 5 8... Se o usurio digitar 4 o elemento da 4 posio o 2.*/
int main()
{
int n,i,enesimo, num1 = 0, num2 = 1;
printf("Digite um numero: ");
scanf("%d", &n);
//enesimo = num1 + num2;
printf("%d %d", num1, num2);
for(i=3; i<=n; i++)
{
enesimo = num1 + num2;
num1 = num2;
num2 = enesimo;
printf(" %d ",enesimo);
}
system("pause");
return 0;
}
|
C
|
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
struct node
{
int value;
struct node *next;
};
typedef struct node node_t;
void print_llist(node_t *head)
{
node_t *temp = head;
while (temp != NULL)
{
printf("%d - ", temp->value);
temp = temp->next;
}
printf("\n");
}
node_t *create_new_node(int value)
{
node_t *result = malloc(sizeof(node_t));
result->value = value;
result->next = NULL;
return result;
}
// what is happening here with ** pointer to a pointer???
node_t *insert_at_head(node_t **head, node_t *node_to_insert)
{
node_to_insert->next = *head;
*head = node_to_insert;
return node_to_insert;
}
// goes trough the list and returns pointer to the node
// that has the searched value
node_t *find_node(node_t *head, int val)
{
node_t *tmp = head;
while (tmp != NULL)
{
if (tmp->value == val)
return tmp;
}
return NULL;
}
int main(void)
{
node_t *head = NULL;
node_t *tmp;
for (size_t i = 0; i < 25; i++)
{
tmp = create_new_node(i);
head = insert_at_head(&head, tmp);
}
print_llist(head);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <curl/curl.h>
#include "services/info_service.h"
#define MAX 255
int main(int argc, char *argv[])
{
char *url = getenv("REST_URL");
CURL *curl;
CURLcode res;
printf("Connects to API URL: %s\n", url);
curl_global_init(CURL_GLOBAL_ALL);
curl = curl_easy_init();
bool run = true;
while (run)
{
if (curl)
{
char filename[MAX];
printf("Please enter the filename: \n");
scanf("%s", filename);
printf("Chosen file is: %s\n\n", filename);
char word[MAX];
printf("Please enter the word to search: \n");
scanf("%s", word);
printf("Chosen word is: %s\n\n", word);
char *response = post_info(curl, url, filename, word);
printf("Number of times the word %s is in %s: %s\n\n", word, filename, response);
free(response);
printf("If you want to end the process please press 'f' and enter, otherwise press only enter to continue.\n");
char end[1];
scanf("%s", end);
if(end[0] == 'f')
{
printf("Program Closed.\n");
run = false;
}
printf("\n");
}
}
curl_easy_cleanup(curl);
return 0;
}
void clean_stdin(void)
{
int c;
do {
c = getchar();
} while (c != '\n' && c != EOF);
}
|
C
|
#include "biblioteca.h"
#include <stdio.h>
int main()
{
int *vet1, *vet2, taman1, taman2, teste;
taman2 = 30;
taman1 = 30;
vet1 = (int *)calloc(taman1, sizeof(int));
vet2 = (int *)calloc(taman2, sizeof(int));
teste = EIgual(vet1, vet2, taman1, taman2);
if (teste == 1)
{
printf("Sao iguais!\n");
}
else
{
printf("Nao sao iguais!\n");
}
free(vet1);
free(vet2);
return 0;
}
|
C
|
#include <stdio.h>
int main(void)
{
int a=10;
if(a==1)
{
printf("a等于10");
}
else
{
printf("a不等于10");
}
return 0;
}
|
C
|
/*
* @lc app=leetcode id=53 lang=c
*
* [53] Maximum Subarray
*/
// @lc code=start
#define tsmax(a,b)\
({ __typeof__ (a) a_ = (a);\
__typeof__ (b) b_ = (b);\
a_ > b_ ? a_:b_; })
int maxSubArray(int* nums, int numsSize){
if (numsSize == 0) return 0;
// base case
int dp_0 = nums[0];
int dp_1 = 0, res = dp_0;
for (int i = 1; i < numsSize; i++) {
// dp[i] = max(nums[i], nums[i] + dp[i-1])
dp_1 = tsmax(nums[i], nums[i] + dp_0);
dp_0 = dp_1;
// calculate the maximum value
res = tsmax(res, dp_1);
}
return res;
}
// @lc code=end
|
C
|
#include <stdio.h>
int results[] = {1, 0, 0, 2, 10, 4, 40, 92, 352, 724};
int main(int argc, char * argv[]) {
int n = atoi(argv[1]);
printf("%d\n", results[n-1]);
return 0;
}
|
C
|
#include<stdio.h>
int main()
{
int c=1,i,count=0;
for(i=0;i<100;i++)
{
if(c<=100)
count++;
//else
//break;
printf("%d ",c);
c=c*2;
}
printf("\ncount=%d ",count);
return 0;
}
|
C
|
//Homework 1.21
#include <stdio.h>
#include <stdlib.h>
#include "files.h"
int tabcheck(int j, int n);
int main(int argc, const char* argv[])
{
FILE* fin;
FILE* fout;
int n;
int ok = openfiles(argc, argv, &fin, &fout, &n);
if(ok == 1)
{
printf("Error, Usage: ./detab input output n");
exit(1);
}
char c;
int i; // number of spaces
int k; // counter
int j = 0; // tab position
while((c = fgetc(fin)) != EOF)
{
if(c != ' ')
{
fputc(c, fout);
j = tabcheck(j, n);
if(c == '\n')
{
j = 0;
}
}
else
{
i = 1;
while((c = fgetc(fin)) == ' ')
{
++i;
}
for(k = n - j; k <= i; k = k + n)
{
fputc('\t', fout);
j = 0;
}
if(j == 0)
{
i = i - k + n;
}
for(k = 1; k <= i; ++k)
{
fputc(' ', fout);
j = tabcheck(j, n);
}
if(c == EOF)
{
break;
}
else
{
fputc(c, fout);
j = tabcheck(j, n);
if(c == '\n')
{
j = 0;
}
}
}
}
closefiles(fin, fout);
return 0;
}
int tabcheck(int j, int n)
{
if(j >= n)
return 1;
return ++j;
}
|
C
|
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "mytoc.h"
#include "saferFork.h"
#include <string.h>
#include <sys/wait.h>
#include <sys/stat.h>
int tokenLen(const char *token);
char *concat(char *str,char *cmd,int lenght, int cmdLenght);
int exitShell(char *input);
int numberOfTokens(char *tokens, char delim);
int main(int argc, char **argv, char** envp){
int exitshell = 1;
while(exitshell){
write(1,"$",1);
char *inp = (char*)malloc(100);//store user input
int bytesread = read(0,inp,100); //read user input
if(bytesread == 0)
exit(0);
exitshell = exitShell(inp);//check whether the user typed in exit to exit the shell
char **input = mytoc(inp,'\n');//get rid of new line character at the end of inp buffer
char **command;//store command
int child = saferFork();//create a child process using saferFork.c provided by Dr. Freudenthal
if(child == 0){//check if current process is a child, if it is start executing the command
if(input[0][0] == '/'){ //check if a path has been given
int lastToken = numberOfTokens(input[0],'/');//get position of command on given path
command = mytoc(input[0],'/');//tokenize the given path to get the command to be executed
char **cmd = mytoc(command[lastToken-1],' '); //create a vector of pointers containing the command
struct stat sb;
int found = stat(input[0],&sb);//check if command exists on path
if(found == 0){//if command exists, try executing it.
int retval = execve(input[0],cmd,envp);
fprintf(stderr, "%s: exect returned %d\n",command[0],retval);
}
}
//If a path has not been provided, shell will look for it using the PATH environment
command = mytoc(input[0],' ');
char *pathenv;
for(int i = 0; envp[i] != '\0'; i++){ //look for PATH environment
char **environment = mytoc(envp[i],'=');
if(strcmp(environment[0],"PATH") == 0){//check if PATH has been found
pathenv = environment[1];
}
}
char **listOfPaths = mytoc(pathenv,':');
int found;
int cmdLength = tokenLen(command[0]);
for(int i = 0; listOfPaths[i] != '\0'; i++){
int pathLength = tokenLen(listOfPaths[i]);
char *completePath = concat(listOfPaths[i],command[0],pathLength,cmdLength);//concatenate command to its corresponding path
struct stat sb;
found = stat(completePath,&sb);//check if command exists on path
if(found == 0){//if command exists, try executing it.
int retval = execve(completePath,command,envp);
fprintf(stderr, "%s: exect returned %d\n",command[0],retval);
}
}
}
int status;
waitpid(child,&status,0);// wait for child process to finish execution
}//while loop
return 0;
}
//concatante the command entered to its corresponding path in case a path was not given
char *concat(char *str,char *cmd,int lenght, int cmdLenght){
int totalLenght = lenght+cmdLenght;
char *tmp = (char*)malloc(totalLenght+1);
char *tempStr = tmp; //char destination d store in temp
int i = 0;
while (*str){ //while there is stuff in source copy it to the destination
*tmp++ = *str++;
}
*tmp++ = '/';
while (*cmd){ //while there is stuff in source copy it to the destination
*tmp++ = *cmd++;
}
*tmp++ = '\0';//store null character
return tempStr;
}
//exitShell function checks if "exit" has been entered by user in order to terminate shell
int exitShell(char *input){
char * exit = "exit";
int terminate = 1;
for(int i = 0; input[i] != '\0' && exit[i] != '\0'; i++){
if(input[i] == exit[i]){
terminate = 0;
}
else{
terminate = 1;
break;
}
}
return terminate;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
typedef struct node{
int value;
struct node *next;
} ListNode;
void printList(ListNode *head);
int removeNode(ListNode **ptrHead, int index);
ListNode * findNode(ListNode *head, int index);
int main()
{
ListNode *head = NULL, *temp;
int num;
printf("Enter a list of numbers, terminated by the value -1:\n");
scanf("%d", &num);
while (num != -1){
if (head == NULL){
// if Linked List currently empty
head = malloc(sizeof(ListNode));
temp = head;
} else {
// if Linked List is not empty
temp->next = malloc(sizeof(ListNode));
temp = temp->next;
}
// temp is the last node
temp->value = num;
temp->next = NULL;
scanf("%d", &num);
}
printf("Current list: ");
printList(head);
int askRemove;
printf("Node at which index to remove? (-1 to Exit): ");
scanf("%d", &askRemove);
while (askRemove != -1){
switch(removeNode(&head, askRemove)){
case 0: // successfully removed
printf("Successfully removed!\n");
break;
case -1: // unsuccessful removal
printf("Removal failed!\n");
break;
default:
printf("Error!\n");
break;
}
printList(head);
printf("Node at which index to remove? (-1 to Exit): ");
scanf("%d", &askRemove);
}
return 0;
}
void printList(ListNode *head){
ListNode *temp = head;
while (temp != NULL){
printf("%d ", temp->value);
temp = temp->next;
}
printf("\n");
}
ListNode * findNode(ListNode *head, int index){
ListNode *temp = head;
if (head == NULL || index < 0)
return NULL;
while (index > 0){
temp = temp->next;
if (temp == NULL)
return NULL;
index--;
}
return temp;
}
int removeNode(ListNode **ptrHead, int index){
// **ptrHead is the address of the first node
// *ptrHead is the first node
if (index < 0 || *ptrHead == NULL) // error if negative index chosen // no node
return -1;
else if (index == 0) // if first node chosen to be removed
(*ptrHead) = (*ptrHead)->next;
else {
ListNode *pre = findNode(*ptrHead, index-1), *cur;
if (pre == NULL || pre->next == NULL)
return -1; // current is the currentNode
else {
cur = pre->next->next;
pre->next = cur;
}
}
return 0;
}
|
C
|
// Implements a dictionary's functionality
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <stdbool.h>
#include <ctype.h>
#include "dictionary.h"
// Represents a node in a hash table
typedef struct node
{
char word[LENGTH + 1];
struct node *next;
}
node;
// Number of buckets in hash table
const unsigned int N = 1080;
unsigned int word_counter = 0;
// Hash table
node *table[N];
// Returns true if word is in dictionary else false
bool check(const char *word)
{
// searching hash value of word
int index = hash(word);
// pointing to table[index]
node *aux = table[index];
while (aux != NULL)
{
// if words are equal, return true
if (strcasecmp(word, aux->word) == 0)
{
return true;
}
aux = aux->next;
}
return false;
}
// Hashes word to a number
unsigned int hash(const char *word)
{
// hash function created by me a friend
int index = 0;
int len = strlen(word);
int first = 0, last = 0;
char *lettersLow = "abcdefghijklmnopqrstuvxwyz'";
char *lettersUp = "ABCDEFGHIJKLMNOPQRSTUVXWYZ'";
for (int i = 0; i < 27; i++)
{
if (word[0] == lettersLow[i] || word[0] == lettersUp[i])
{
first = i + 1;
break;
}
}
for (int i = 0; i < 27; i++)
{
if (word[len - 1] == lettersLow[i] || word[len - 1] == lettersUp[i])
{
last = i + 1;
break;
}
}
index = first * last;
for (int i = 1; i < len - 1; i++)
{
for (int j = 0; j < 27; j++)
{
if (word[i] == lettersLow[j] || word[i] == lettersUp[j])
{
index += j + 1;
}
}
}
return index;
}
// Loads dictionary into memory, returning true if successful else false
bool load(const char *dictionary)
{
// opening dictionary file
FILE *file = fopen(dictionary, "r");
if (!file || file == NULL)
{
return false;
}
char word[LENGTH + 1];
// scanning every word util the end of the file
while (fscanf(file, "%s", word) != EOF)
{
node *n = malloc(sizeof(node));
if (!n || n == NULL)
{
return false;
}
// copying word to node->word
strcpy(n->word, word);
n->next = NULL;
int index = hash(word);
n->next = table[index];
table[index] = n;
// counting words
word_counter++;
}
// closing file
fclose(file);
return true;
}
// Returns number of words in dictionary if loaded else 0 if not yet loaded
unsigned int size(void)
{
// just returning the amount of words colected by the load function
return word_counter;
}
// Unloads dictionary from memory, returning true if successful else false
bool unload(void)
{
// pointing to first node in the hash table
node *cursor = table[0];
for (int i = 0; i < N; i++)
{
cursor = table[i];
while (cursor != NULL)
{
node *tmp = cursor;
cursor = cursor->next;
free(tmp);
}
}
return true;
}
|
C
|
/*
* bmp085_tests.cpp
*
* Created: 2013-12-29 10:14:08
* Author: mikael
*/
#if BMP085_ENABLE==1
#include <avr/io.h>
#include <stdbool.h>
#include <util/delay.h>
#include <avr/pgmspace.h>
#include <stdio.h>
#include "../drivers/bmp085_driver.h"
#include "../drivers/TSL2561_driver.h"
#include "../device/i2c_bus.h"
#ifdef __cplusplus
extern "C" {
#endif
TSL2561_t light;
BMP085_t bmp085;
void bmp085_tests_setup()
{
TSL2561_init(&light, &i2c, TSL2561_ADDR_FLOAT, TSL2561_INTEGRATIONTIME_13MS, TSL2561_GAIN_16X);
}
bool bmp085_tests()
{
puts_P(PSTR("BMP085..."));
BMP085_init(&bmp085, Standard, &i2c);
float temperature = BMP085_readTemperature(&bmp085);
int32_t pressure = BMP085_readPressure(&bmp085);
int16_t temp = floor(temperature);
printf_P(PSTR("BMP085 Temperature: %d%cC\n"), temp, 0xB0);
printf_P(PSTR("BMP085 Pressure: %ld\n"), pressure);
puts_P(PSTR("TSL2561..."));
TSL2561_readChannels(&light);
uint16_t ch0 = TSL2561_getLuminosity(&light, TSL2561_FULLSPECTRUM);
uint16_t ch1 = TSL2561_getLuminosity(&light, TSL2561_INFRARED);
uint16_t ch2 = TSL2561_getLuminosity(&light, TSL2561_VISIBLE);
uint32_t lux = TSL2561_calculateLux(&light, ch0, ch1);
printf_P(PSTR("Full spectrum: %d\n"), ch0);
printf_P(PSTR("Infrared: %d\n"), ch1);
printf_P(PSTR("Visible: %d\n"), ch2);
printf_P(PSTR("lux: %ld\n"), lux);
return true;
}
#ifdef __cplusplus
}
#endif
#endif
|
C
|
/*
** EPITECH PROJECT, 2018
** interaction
** File description:
** rpg
*/
#include "rpg.h"
static void right_click(battle_t *battle)
{
if (!battle->fight[battle->id]->enemy_turn && battle->hero->select) {
if (battle->hero->spell_id != -1)
cast_spell_attack(battle);
else {
deplacement(battle);
attack(battle);
}
}
}
static void left_click(battle_t *battle)
{
sfVector2f pos;
for (int i = 0; i < 120; i++) {
pos = sfRectangleShape_getPosition
(battle->fight[battle->id]->map[i]);
if ((battle->mouse.x > pos.x && battle->mouse.x < pos.x + B_X)
&& (battle->mouse.y > pos.y && battle->mouse.y < pos.y + B_Y))
select_or_unselect(battle, i);
}
for (int i = 0; i < 4; i++) {
if (!battle->hero->spell[i]->unlock)
continue;
pos = sfRectangleShape_getPosition
(battle->hero->spell[i]->icone);
if ((battle->mouse.x > pos.x && battle->mouse.x < pos.x + 50)
&& (battle->mouse.y > pos.y && battle->mouse.y < pos.y + 50)) {
battle->hero->spell_id = i;
battle->hero->select = true;
}
}
}
void interaction(battle_t *battle, sfEvent *event)
{
if (event->type == sfEvtMouseButtonPressed) {
if (event->mouseButton.button == sfMouseLeft)
left_click(battle);
if (event->mouseButton.button == sfMouseRight)
right_click(battle);
}
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <malloc.h>
#include <string.h>
#define togglebit(v, bit) v = v ^ (1<<bit)
#define checkbit(a, v, bit) a = v & (1<<bit)
typedef struct {
char desc[60];
unsigned char potencia;
unsigned int estado;
}datos_t;
typedef struct{
datos_t inf;
int id;
}d_archivo_t;
struct pila{
datos_t dat;
struct pila *l;
};
void funcion (unsigned int, struct pila **);
void funcion (unsigned int id, struct pila **p){
FILE *fp, *fp2;
d_archivo_t bf, bf2;
unsigned int clave, i=0, j, a, b;
char *paux, pinv[60];
struct pila *aux;
if ((fp=fopen ("../ejercicio39/potencia.dat", "rb+"))==NULL){
printf ("\nNo se pudo abrir el archivo potencia.dat");
}else
{
fseek (fp, (long)sizeof (d_archivo_t)*(id-1), 0);
fread (&bf, sizeof (d_archivo_t), 1, fp);
if (bf.id==id){
paux=bf.inf.desc;
while (*paux && *paux!= ' '){
*paux ++;
i++;
}
*paux--;
for (j=0; j<i; j++){
pinv[j]=*paux;
*paux--;
}
pinv[i]=0;
printf ("\nLa primer palabra de descripcion invertida es: %s", pinv);
togglebit(bf.inf.estado, 3);
fseek (fp, (-1L)*sizeof(d_archivo_t), 1);
if (fwrite(&bf, sizeof(d_archivo_t), 1, fp)==1){
printf ("\nSe actualizo el registro en el archivo potencia.dat");
}else{
printf ("\nNo se pudo actualizar el registro");
}
checkbit(a, bf.inf.estado, 2);
checkbit(b, bf.inf.estado, 0);
if (a && b){
aux=(struct pila *)malloc (sizeof (struct pila));
aux->dat=bf.inf;
aux->l=*p;
*p=aux;
aux=NULL;
printf ("\nSe apilo el registro");
free (aux);
}else
{
if ((fp2=fopen("salida.dat", "ab+"))==0){
printf("\nError al abrir el archivo salida.dat");
}
else{
printf ("\nIngrese la clave para archivar este registro:\t");
fflush (stdin);
scanf ("%d", &clave);
fseek (fp2, 0L, 0);
fread (&bf2, sizeof (d_archivo_t), 1, fp2);
while (!feof(fp2)){
while (bf2.id == clave){
printf ("\nClave ya ingresada, ingrese uno nuevo: \t");
fflush (stdin);
scanf ("%d", &clave);
}
fread (&bf, sizeof (datos_t), 1, fp2);
}
bf.id = clave;
fseek (fp2, 0L, 2);
if ((fwrite (&bf, sizeof(d_archivo_t), 1, fp2))==1)
printf ("\nSe archivo el registro con clave: %.4d\n", bf.id);
}
fclose (fp2);
}
printf ("\nregistro archivado en salida.dat");
}else{
printf ("\nRegistro no encontrado");
}
}
fclose (fp);
return;
}
|
C
|
/*
* Copyright (c) 2011 ITE Tech. Inc. All Rights Reserved.
*/
/** @file
* USB HID Boot Protocol Mouse driver.
*
* @author Irene Lin
* @version 1.0
*/
#include <string.h>
#include "ite/itp.h"
#include "ite/ite_usbmouse.h"
#include "usb/ite_usb.h"
struct usb_mouse
{
char name[128];
struct usb_device* usbdev;
struct urb* irq;
signed char *data;
dma_addr_t data_dma;
};
static struct usb_mouse ctxt;
static usb_mouse_cb mouse_cb;
static struct usb_device_id usb_mouse_id_table[] =
{
{ USB_INTERFACE_INFO(3, 1, 2) },
{ USB_INTERFACE_INFO(0, 0, 0) } // end marker
};
static void usb_mouse_irq(struct urb *urb)
{
struct usb_mouse *mouse = urb->context;
int status;
switch (urb->status) {
case 0: /* success */
break;
case -ECONNRESET: /* unlink */
case -ENOENT:
case -ESHUTDOWN:
return;
/* -EPIPE: should clear the halt */
default: /* error */
goto resubmit;
}
#if defined(DUMP_CODE)
{
uint32_t i;
ithPrintf("\n");
for(i=0; i<4; i++)
ithPrintf(" %02d", mouse->data[i]);
ithPrintf("\n");
}
#endif
if(mouse_cb)
mouse_cb(mouse->data);
resubmit:
status = usb_submit_urb (urb);
if (status)
ithPrintf("[MOUSE] can't resubmit intr, status %d", status);
return;
}
static void* usb_mouse_probe(struct usb_interface *intf, const struct usb_device_id *id)
{
struct usb_device *dev = interface_to_usbdev(intf);
struct usb_host_interface *interface;
struct usb_endpoint_descriptor *endpoint;
struct usb_mouse *mouse = NULL;
int pipe, maxp;
int error = -ENOMEM;
interface = intf->cur_altsetting;
if (interface->desc.bNumEndpoints != 1)
{
error = -ENODEV;
goto end;
}
endpoint = &interface->endpoint[0].desc;
if (!usb_endpoint_is_int_in(endpoint))
{
error = -ENODEV;
goto end;
}
pipe = usb_rcvintpipe(dev, endpoint->bEndpointAddress);
maxp = usb_maxpacket(dev, pipe, usb_pipeout(pipe));
mouse = kzalloc(sizeof(struct usb_mouse), GFP_KERNEL);
if (!mouse)
goto fail1;
mouse->data = usb_alloc_coherent(dev, 8, GFP_ATOMIC, &mouse->data_dma);
if (!mouse->data)
goto fail1;
mouse->irq = usb_alloc_urb(0);
if (!mouse->irq)
goto fail2;
mouse->usbdev = dev;
dev->type = USB_DEVICE_TYPE_MOUSE;
if (dev->manufacturer)
strlcpy(mouse->name, dev->manufacturer, sizeof(mouse->name));
if (dev->product) {
if (dev->manufacturer)
strlcat(mouse->name, " ", sizeof(mouse->name));
strlcat(mouse->name, dev->product, sizeof(mouse->name));
}
if (!strlen(mouse->name))
{
ithPrintf(" %s \n", mouse->name);
ithPrintf(" USB HIDBP Mouse %04x:%04x \n",
le16_to_cpu(dev->descriptor.idVendor),
le16_to_cpu(dev->descriptor.idProduct));
}
usb_fill_int_urb(mouse->irq, dev, pipe, mouse->data,
(maxp > 8 ? 8 : maxp),
usb_mouse_irq, mouse, endpoint->bInterval);
mouse->irq->transfer_dma = mouse->data_dma;
mouse->irq->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
usb_set_intfdata(intf, mouse);
/** submit interrupt in urb */
error = usb_submit_urb(mouse->irq);
if(error)
goto fail2;
return mouse;
fail2:
usb_free_coherent(dev, 8, mouse->data, mouse->data_dma);
fail1:
mouse = NULL;
end:
if(error)
ithPrintf(" %s: error %d \n", __func__, error);
return mouse;
}
static void usb_mouse_disconnect(struct usb_interface *intf)
{
struct usb_mouse *mouse = usb_get_intfdata (intf);
usb_set_intfdata(intf, NULL);
if (mouse) {
usb_kill_urb(mouse->irq);
usb_free_urb(mouse->irq);
usb_free_coherent(interface_to_usbdev(intf), 8, mouse->data, mouse->data_dma);
kfree(mouse);
}
}
struct usb_driver usb_mouse_driver =
{
"usbmouse_driver", /** driver name */
0, /** flag */
usb_mouse_probe, /** probe function */
NULL, /** open function */
usb_mouse_disconnect, /** disconnect function */
NULL, /** ioctl */
usb_mouse_id_table, /** id table */
NULL,NULL /** driver_list */
};
int iteUsbMouseRegister(void)
{
INIT_LIST_HEAD(&usb_mouse_driver.driver_list);
return usb_register(&usb_mouse_driver);
}
int iteUsbMouseSetCb(usb_mouse_cb cb)
{
if(cb)
mouse_cb = cb;
}
|
C
|
/* ǽ 2 : fibonacciArray.c
ۼ : 2019. 04. 10 ~ 04. 12
ۼ : 2016153 缺
α : 迭 10 Ǻġ ϰ ϴ α
*/
#include <stdio.h> // ó
#define SIZE 10 // define ũ SIZE 10
void printArray(int arr[]); // 迭 ϴ printArrayԼ
void setFiboArray(int arr[]); // 迭 Ǻġ ϴ setFiboArrayԼ
int main(int argc, char* argv[]) { // mainԼ
int array[SIZE] = { 0 }; // ũⰡ 10 迭 index 0 ʱȭ
setFiboArray(array); // setFiboArrayԼ 迭 Ǻġ
printArray(array); // printArrayԼ 迭
system("pause"); // â Ȯ
return 0; // 0 ȯ
}
void setFiboArray(int arr[]) { // 迭 Ǻġ ϴ setFiboArrayԼ, 迭 Ű ´
int i; // ݺ
int temp1 = 0; // Ǻġ 1 2,3,4... ٲ ӽú1 ʱȭ
int temp2 = 1; // Ǻġ 2 3,4,5... ٲ ӽú2 ʱȭ
int sum = temp1 + temp2; // Ǻġ , 1װ 2 ʱȭ
arr[0] = temp1; // Ǻġ 1,2 迭 index
arr[1] = temp2;
for (i = 2; i < SIZE; i++) { // ݺ 迭 Ǻġ
sum = temp1 + temp2; // Ǻġ ʱȭ
arr[i] = sum; // i° 迭 i index
temp1 = temp2; // (i-2)° (i-1)° ʱȭ
temp2 = sum; // (i-1)° (i)° ʱȭ
}
}
void printArray(int arr[]) { // 迭 ϴ printArrayԼ, 迭 Ű ´.
int i; // ݺ
printf("° > \n[ "); // 迭
for (i = 0; i < SIZE; i++) { // ݺ ̿ 迭
printf("%d ", arr[i]);
}
printf("]\n"); // ٹٲ
}
|
C
|
#include "heap.h"
int get_parent_index(HEAP *queue, int i) {
return i >> 1;
}
int get_left_index(HEAP *queue, int i) {
return i << 1;
}
int get_right_index(HEAP *queue, int i) {
return (i << 1) + 1;
}
HUFF_NODE *item_of(HEAP *queue, int i) {
return queue->data[i];
}
bool is_empty(HEAP *queue) {
return queue->size == 0;
}
HEAP *create_heap() {
HEAP *new_heap = (HEAP*)malloc(sizeof(HEAP));
int i;
new_heap->size = 0;
for (i = 0; i <= 256; ++i) {
new_heap->data[i] = NULL;
}
return new_heap;
}
void swap(HUFF_NODE **x, HUFF_NODE **y) {
HUFF_NODE *aux = *x;
*x = *y;
*y = aux;
}
void min_heapify(HEAP *queue, int i) {
int biggest;
int left_index = get_left_index(queue, i);
int right_index = get_right_index(queue, i);
if (left_index <= queue->size && queue->data[left_index]->frequency < queue->data[i]->frequency) {
biggest = left_index;
} else {
biggest = i;
}
if (right_index <= queue->size && queue->data[right_index]->frequency < queue->data[biggest]->frequency) {
biggest = right_index;
}
if (queue->data[i]->frequency != queue->data[biggest]->frequency) {
swap(&queue->data[i], &queue->data[biggest]);
min_heapify(queue, biggest);
}
}
void print_heap(HEAP *queue) {
int i;
for (i = 1; i <= queue->size; ++i) {
printf("(%c, %lld) -> ", queue->data[i]->key, queue->data[i]->frequency);
}
printf("\n");
}
HUFF_NODE *dequeue(HEAP *queue) {
if (is_empty(queue)) {
printf("Heap Underflow! Cannot dequeue!\n");
return NULL;
} else {
HUFF_NODE *item = queue->data[1];
queue->data[1] = queue->data[queue->size];
--queue->size;
min_heapify(queue, 1);
return item;
}
}
void enqueue(HEAP *queue, HUFF_NODE *item) {
if (queue->size >= 100000) {
printf("Heap Overflow! Cannot enqueue!\n");
} else {
queue->data[++queue->size] = item;
int key_index = queue->size;
int parent_index = get_parent_index(queue, key_index);
while (parent_index >= 1 && queue->data[key_index]->frequency < queue->data[parent_index]->frequency) {
swap(&queue->data[key_index], &queue->data[parent_index]);
key_index = parent_index;
parent_index = get_parent_index(queue, key_index);
}
}
}
|
C
|
/******************************************
* ////Gomulu Sistemlerde String Islem Yapmayi Saglayan Kutuphane////
* Proje: OSKAR
* Derleme: Mustafa zelikrs
*
****/
#include <stdlib.h>
#define STRING_BUF_SIZE 50 // maximum Grsse vom String
#define USE_STR_FKT 1 // 0=nicht benutzen, 1=benutzen
#if USE_STR_FKT==1
#include <string.h>
#endif
char STRING_BUF[STRING_BUF_SIZE];
#define STRING_FLOAT_FAKTOR 1000 // 1000 = 3 Nachkommastellen
#define STRING_FLOAT_FORMAT "%d.%03d" // Formatierung
void UB_String_FloatToDezStr(float wert);
float UB_String_DezStringToFloat(unsigned char *ptr);
int16_t UB_String_DezStringToInt(char *ptr);
#if USE_STR_FKT==1
void UB_String_Mid(char *ptr, uint16_t start, uint16_t length);
void UB_String_Left(char *ptr, uint16_t length);
void UB_String_Right(char *ptr, uint16_t length);
#endif
void reverse(char s[]);
int itoa(int num, unsigned char* str, int len, int base);
char* ltoa( long value, char *string, int radix );
void UB_String_FloatToDezStr(float wert)
{
int16_t vorkomma;
uint16_t nachkomma;
float rest;
if((wert>32767) || (wert<-32767)) {
sprintf(STRING_BUF,"%s","OVF");
return;
}
vorkomma=(int16_t)(wert);
if(wert>=0) {
rest = wert-(float)(vorkomma);
}
else {
rest = (float)(vorkomma)-wert;
}
nachkomma = (uint16_t)(rest*(float)(STRING_FLOAT_FAKTOR)+0.5);
sprintf(STRING_BUF,STRING_FLOAT_FORMAT,vorkomma,nachkomma);
}
//--------------------------------------------------------------
// wandelt einn String in eine Float Zahl
// Bsp : String "123.457" wird zu Zahl 123.457
//--------------------------------------------------------------
float UB_String_DezStringToFloat(unsigned char *ptr)
{
float ret_wert=0.0;
ret_wert=atof((char const *)ptr);
return(ret_wert);
}
//--------------------------------------------------------------
// wandelt einn String in eine Integer Zahl
// Bsp : String "-1234" wird zu Zahl -1234
//--------------------------------------------------------------
int16_t UB_String_DezStringToInt(char *ptr)
{
int16_t ret_wert=0;
ret_wert=atoi(ptr);
return(ret_wert);
}
//--------------------------------------------------------------
// kopiert einen Teilstring
// Bsp : String "Hallo Leute",3,6 wird zu "lo Leu"
//--------------------------------------------------------------
#if USE_STR_FKT==1
void UB_String_Mid(char *ptr, uint16_t start, uint16_t length)
{
uint16_t i,m;
uint16_t cnt = 0;
if(length==0) return;
m=start+length;
if(m>strlen(ptr)) m=strlen(ptr);
for(i=start;i<m; i++) {
STRING_BUF[cnt] = ptr[i];
cnt++;
}
STRING_BUF[cnt]=0x00;
}
#endif
//--------------------------------------------------------------
// kopiert den linken Teil von einem String
// Bsp : String "Hallo Leute",3 wird zu "Hal"
//--------------------------------------------------------------
#if USE_STR_FKT==1
void UB_String_Left(char *ptr, uint16_t length)
{
if(length==0) return;
if(length>strlen(ptr)) length=strlen(ptr);
strncpy(STRING_BUF,ptr,length);
STRING_BUF[length]=0x00;
}
#endif
//--------------------------------------------------------------
// kopiert den rechten Teil von einem String
// Bsp : String "Hallo Leute",3 wird zu "ute"
//--------------------------------------------------------------
#if USE_STR_FKT==1
void UB_String_Right(char *ptr, uint16_t length)
{
uint16_t i,m,start;
uint16_t cnt = 0;
if(length==0) return;
m=strlen(ptr);
if(length>m) length=m;
start=m-length;
for(i=start;i<m; i++) {
STRING_BUF[cnt] = ptr[i];
cnt++;
}
STRING_BUF[cnt]=0x00;
}
#endif
void reverse(char s[])
{
int i, j;
char c;
for (i = 0, j = strlen(s)-1; i<j; i++, j--) {
c = s[i];
s[i] = s[j];
s[j] = c;
}
}
int itoa(int num, unsigned char* str, int len, int base)
{
int sum = num;
int i = 0;
int digit;
if (len == 0)
return -1;
do
{
digit = sum % base;
if (digit < 0xA)
str[i++] = '0' + digit;
else
str[i++] = 'A' + digit - 0xA;
sum /= base;
}while (sum && (i < (len - 1)));
if (i == (len - 1) && sum)
return -1;
str[i] = '\0';
reverse(str);
return 0;
}
char* ltoa( long value, char *string, int radix )
{
char tmp[33];
char *tp = tmp;
long i;
unsigned long v;
int sign;
char *sp;
if ( string == NULL )
{
return 0 ;
}
if (radix > 36 || radix <= 1)
{
return 0 ;
}
sign = (radix == 10 && value < 0);
if (sign)
{
v = -value;
}
else
{
v = (unsigned long)value;
}
while (v || tp == tmp)
{
i = v % radix;
v = v / radix;
if (i < 10)
*tp++ = i+'0';
else
*tp++ = i + 'A' - 10;
}
sp = string;
if (sign)
*sp++ = '-';
while (tp > tmp)
*sp++ = *--tp;
*sp = 0;
return string;
}
char* concat(char *s1, char *s2)
{
size_t len1 = strlen(s1);
size_t len2 = strlen(s2);
char *result = malloc(len1+len2+1);//+1 for the zero-terminator
//in real code you would check for errors in malloc here
memcpy(result, s1, len1);
memcpy(result+len1, s2, len2+1);//+1 to copy the null-terminator
return result;
}
|
C
|
#include <stdio.h>
int ft_str_is_printable(char *str);
int main(void)
{
char str1[] = " fdhhAAA | /%f1235`";
char str2[] = "ABCDE!á";
char str3[] = "aasr342AA433¬¬¬";
int validate;
validate = 0;
if (ft_str_is_printable(str1))
{
printf ("1ª string has printable chars only : %s\n", str1);
validate++;
}
if (ft_str_is_printable(str2))
{
printf ("2ª string has printable chars only: %s\n", str2);
validate++;
}
if (ft_str_is_printable(str3))
{
printf ("3ª string has printable chars only: %s\n", str3);
validate++;
}
if (validate == 1)
printf ("%d string with printable chars only.\n", validate);
else
printf ("%d strings with printable chars only.\n", validate);
return (0);
}
|
C
|
#include <stdio.h>
#include "hash.h"
main()
{
int ch,ret;
char key[20];
hashItem_t *p;
while(1)
{
printf("\n1.add Element to hash list");
printf("\n2.search Element in hash list");
printf("\n3.Exit");
printf("\nEnter choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:
p=(hashItem_t *)malloc(sizeof(hashItem_t));
ret=addToHashList(p);
printf("\n%d\n",ret);
break;
case 2:
printf("Enter the name:");
scanf("%s",key);
searchHashList(key);
break;
case 3:
exit(1);
}
}
}
|
C
|
#include <stdio.h>
/* strcmp: return <0 if s<t, 0 if s == t, >0 if s>t */
int strcmp1(char *s, char *t)
{
int i;
for (i = 0; s[i] == t[i]; i++)
if (s[i] == '\0')
return 0;
return s[i] - t[i];
}
int strcmp2(char *s, char *t)
{
for ( ; *s == *t; s++, t++)
if (*s == '\0')
return 0;
return *s - *t;
}
void main()
{
char *s = "sdklsld", *t = "sdkksdfsd";
printf("strcmp1(s, t):%d\n", strcmp1(s, t));
printf("strcmp2(s, t):%d\n", strcmp2(s, t));
}
|
C
|
#include <unistd.h>
int comp(char *s1, char c, int index)
{
int i;
i = 0;
while(i < index)
{
if(s1[i] == c)
return (1);
i++;
}
return (0);
}
void inter(char *s1,char *s2)
{
int i;
int j;
i = 0;
while(s1[i])
{
if(comp(s1,s1[i],i) == 0)
{
j = 0;
while(s2[j])
{
if (s1[i] == s2[j])
{
write( 1, &s1[i], 1);
break;
}
j++;
}
}
i++;
}
}
int main(int ac, char **av)
{
if (ac == 3)
{
inter(av[1], av[2]);
}
write( 1, "\n", 1);
return (0);
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<unistd.h>
int main()
{
int server_socket;
int error_check;
char server_message[256];
char ping[10];
struct sockaddr_in client_address;
socklen_t client_len;
client_len = sizeof(client_address);
server_socket = socket(AF_INET, SOCK_DGRAM, 0);
struct sockaddr_in server_address;
server_address.sin_family = AF_INET;
server_address.sin_port = htons(9002);
server_address.sin_addr.s_addr = INADDR_ANY;
error_check = bind(server_socket, (struct sockaddr *) &server_address, sizeof(server_address));
if(error_check == -1)
{
printf("Error while binding\n");
exit(1);
}
// get message from client 1
error_check = recvfrom(server_socket,server_message,sizeof(server_message),0, (struct sockaddr *) &client_address, &client_len);
if(error_check == -1)
{
printf("error receiving message from client.\n");
exit(1);
}
printf("Client sent character: %s\n", server_message);
// process the message and decrement the character sent by client 1
if(server_message[0] == 'a')
{
server_message[0] = 'z';
}
else if (server_message[0] == 'A')
{
server_message[0] == 'Z';
}
else
{
server_message[0] = server_message[0] - 1;
}
// client 2 pings so that its ip address and port can be known and response can be sent.
error_check = recvfrom(server_socket,ping,sizeof(ping),0, (struct sockaddr *) &client_address, &client_len);
if(error_check == -1)
{
printf("error receiving message from client.\n");
exit(1);
}
error_check = sendto(server_socket, server_message, sizeof(server_message), 0, (struct sockaddr *) &client_address, client_len);
if(error_check == -1)
{
printf("Error while sending message.\n");
exit(1);
}
printf("Server says I am done.\n");
close(server_socket);
return 0;
}
|
C
|
#include <stdio.h>
int main( void )
{
int num;
do
{
printf( "Enter a even number: " );
scanf( "%d", &num );
} while ( num % 2 != 0 );
puts( "Input accepted!" );
return 0;
}
|
C
|
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>
// use 4 for a quad processor, but try also with 1 and 2 threads
// to check the running time and the system load
// matrix dimension
#define dim 1024
int thread_count;
struct param {
int start_line, end_line;
};
int a[dim][dim], b[dim][dim], c[dim][dim];
void init_matrix(int m[dim][dim]) {
int i, j;
for (i = 0; i < dim; i++)
for (j = 0; j < dim; j++)
m[i][j] = rand() % 5;
}
void* thread_function(void *v) {
struct param *p = (struct param *) v;
int i, j, k;
for (i = p->start_line; i < p->end_line; i++)
for (j = 0; j < dim; j++) {
int s = 0;
for (k = 0; k < dim; k++)
s += a[i][k] * b[k][j];
c[i][j] = s;
}
}
int time_difference(struct timespec *start, struct timespec *finish,
long long int *difference) {
long long int ds = finish->tv_sec - start->tv_sec;
long long int dn = finish->tv_nsec - start->tv_nsec;
if(dn < 0 ) {
ds--;
dn += 1000000000;
}
*difference = ds * 1000000000 + dn;
return !(*difference > 0);
}
int main() {
struct timespec start, finish;
long long int time_elapsed;
int i;
int start_time, end_time;
printf("Enter the number of thread: ");
scanf("%d",&thread_count);
struct param params[thread_count];
pthread_t t[thread_count];
clock_gettime(CLOCK_MONOTONIC, &start);
init_matrix(a);
init_matrix(b);
for (i = 0; i < thread_count; i++) {
int code;
params[i].start_line = i * (dim / thread_count);
params[i].end_line = (i + 1) * (dim / thread_count);
code = pthread_create(&t[i], NULL, thread_function, ¶ms[i]);
if (code != 0)
printf("Error starting thread %d\n", i);
}
for (i = 0; i < thread_count; i++)
pthread_join(t[i], NULL);
printf("\nThe results is…\n");
for(int i=0; i<dim; i++) {
for(int j=0; j<dim; j++) {
printf("%d ", c[i][j]);
}
printf("\n");
}
clock_gettime(CLOCK_MONOTONIC, &finish);
time_difference(&start, &finish, &time_elapsed);
printf("Time taken was %lldns or %0.9lfs\n", time_elapsed,
(time_elapsed/1.0e9));
}
|
C
|
#ifndef LINKED_LIST_H
#define LINKED_LIST_H
#ifdef __cplusplus
extern "C" {
#endif
typedef void linked_list;
typedef void linked_list_iterator;
// linked list
linked_list * linked_list_new();
void linked_list_add(linked_list * ll, void * value);
void * linked_list_get(linked_list * ll, int i);
void linked_list_remove_last(linked_list *ll);
void linked_list_delete(linked_list *ll);
int linked_list_size(linked_list *ll);
// linked list iterator
linked_list_iterator * linked_list_iterator_new(linked_list *ll);
linked_list_iterator * linked_list_iterator_next(linked_list_iterator * iter);
void * linked_list_iterator_getvalue(linked_list_iterator *iter);
#ifdef __cplusplus
}
#endif
#endif /* LINKED_LIST_H */
|
C
|
/* flex integer type definitions */
#ifndef FLEXINT_H
#define FLEXINT_H
/* C99 systems have <inttypes.h>. Non-C99 systems may or may not. */
#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
/* C99 says to define __STDC_LIMIT_MACROS before including stdint.h,
* if you want the limit (max/min) macros for int types.
*/
#ifndef __STDC_LIMIT_MACROS
#define __STDC_LIMIT_MACROS 1
#endif
#include <inttypes.h>
typedef int8_t flex_int8_t;
typedef uint8_t flex_uint8_t;
typedef int16_t flex_int16_t;
typedef uint16_t flex_uint16_t;
typedef int32_t flex_int32_t;
typedef uint32_t flex_uint32_t;
#else
#if defined(__cplusplus) && __cplusplus >= 199711L
#include <stdint.h>
#endif
typedef signed char flex_int8_t;
typedef short int flex_int16_t;
typedef int flex_int32_t;
typedef unsigned char flex_uint8_t;
typedef unsigned short int flex_uint16_t;
typedef unsigned int flex_uint32_t;
/* Limits of integral types. */
#ifndef INT8_MIN
#define INT8_MIN (-128)
#endif
#ifndef INT16_MIN
#define INT16_MIN (-32767 - 1)
#endif
#ifndef INT32_MIN
#define INT32_MIN (-2147483647 - 1)
#endif
#ifndef INT8_MAX
#define INT8_MAX (127)
#endif
#ifndef INT16_MAX
#define INT16_MAX (32767)
#endif
#ifndef INT32_MAX
#define INT32_MAX (2147483647)
#endif
#ifndef UINT8_MAX
#define UINT8_MAX (255U)
#endif
#ifndef UINT16_MAX
#define UINT16_MAX (65535U)
#endif
#ifndef UINT32_MAX
#define UINT32_MAX (4294967295U)
#endif
#endif /* ! C99 */
#endif /* ! FLEXINT_H */
|
C
|
//
// zad_8.c
//
//
// Created by Student on 18.10.2017.
//
//
#include <stdio.h>
int silnia(int);
int main()
{
int a;
scanf("%d", &a);
printf("%d\n", silnia(a));
return 0;
}
int silnia(int a)
{
if(a == 0) return 1;
else return silnia(a-1)*a;
}
|
C
|
/* ================================================================== *
Universidade Federal de Sao Carlos - UFSCar, Sorocaba
Disciplina: Algoritmos e Programação 2
Lista 02 - Exercício 01 - Coeficiente Binomial
Instrucoes
----------
Este arquivo contem o codigo que auxiliara no desenvolvimento do
exercicio. Voce precisara completar as partes requisitadas.
* ================================================================== *
Dados do aluno:
RA: 743506
Nome: Andre Matheus Bariani Trava
* ================================================================== */
#include <stdio.h>
double coefbin(double n, double k);
double fat(double n);
int main()
{
double n, k, res;
scanf("%lf %lf", &n, &k);
res = coefbin(n, k);
printf("%.0lf\n", res);
return 0;
}
double coefbin(double n, double k)
{
return (fat(n)/(fat(k)*fat(n - k)));
}
double fat(double n)
{
if(n == 0)
return 1;
else if(n == 1)
return 1;
else
return n*fat(n-1);
}
|
C
|
/**************************************************************
1231번
jongtae0509
C
정확한 풀이코드 길이:268 byte(s)
수행 시간:0 ms
메모리 :1120 kb
****************************************************************/
#include<stdio.h>
int main()
{
int a,b;
char c;
scanf("%d %c %d",&a,&c,&b);
if(c=='+'){
printf("%d",a+b);
}
else if(c=='-'){
printf("%d",a-b);
}
else if(c=='/'){
printf("%.2lf",(double)a/b);
}
else if(c=='*'){
printf("%d",a*b);
}
}
|
C
|
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#define TAPE_SIZE (30000)
static char tape[TAPE_SIZE] = {0};
static size_t get_file_size(FILE *fp)
{
fseek(fp, 0L, SEEK_END);
size_t size = ftell(fp);
fseek(fp, 0L, SEEK_SET);
return size;
}
static char *read_content(const char *filename)
{
char *buffer;
FILE *fp = fopen(filename, "r");
if (fp == NULL)
exit(EXIT_FAILURE);
size_t file_size = get_file_size(fp);
buffer = (char *)calloc(file_size, sizeof(char));
if (buffer == NULL)
exit(EXIT_FAILURE);
fread(buffer, sizeof(char), file_size, fp);
fclose(fp);
return buffer;
}
void interpreter(char *program)
{
size_t op_num = -1, cell_num = 0;
char operator;
while ((operator= program[++op_num]) != '\0')
{
switch (operator)
{
case '+':
{
++tape[cell_num];
break;
}
case '-':
{
--tape[cell_num];
break;
}
case '>':
{
assert(cell_num < TAPE_SIZE);
cell_num++;
break;
}
case '<':
{
assert(cell_num >= 0);
--cell_num;
break;
}
case '.':
{
putchar(tape[cell_num]);
break;
}
case ',':
{
tape[cell_num] = getchar();
break;
}
case '[':
{
unsigned long nesting_level = 1;
if (tapr[cell_num] == 0)
{
while (nesting_level > 0)
{
operator= program[++op_num];
if (operator== ']')
{
--nesting_level;
}
else if (operator== '[')
{
++nesting_level;
}
}
}
break;
}
case ']':
{
unsigned long nesting_level = 1;
if (tape[cell_num] != 0)
{
while (nesting_level > 0)
{
operator= program[--op_num];
if (operator== ']')
{
++nesting_level;
}
else if (operator== '[')
{
--nesting_level;
}
}
}
break;
}
default:
break;
}
}
}
int main(int argc, char *argv[])
{
if (argc == 1)
return EXIT_FAILURE;
char *c = read_content(argc[1]);
interpreter(c);
system("pause");
return 0;
}
|
C
|
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// File name: pyramide.c
// Author: Jan K. Schiermer
// Created on: 27 Sep 2018
// Description:
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#include <stdio.h>
#define LIMIT 250
int main(void)
{
char ent_val[LIMIT];
int n;
printf("Enter a anything:");
for (n=0;n<LIMIT;n++)
{
scanf("%c",&ent_val[n]);
if (ent_val[n]=='\n')
break;
}
for (;n>-1;n--)
printf("%c",ent_val[n]);
return 0;
}
|
C
|
/** Inspired by the examples in
* https://www.kernel.org/doc/Documentation/networking/can.txt
*/
#include <sys/socket.h>
#include <net/if.h>
#include <linux/can.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char* argv[])
{
if (argc == 2) {
int s;
s = socket(PF_CAN, SOCK_RAW, CAN_RAW);
if (s != -1) {
struct sockaddr_can addr;
memset(&addr, 0, sizeof(addr));
addr.can_family = AF_CAN;
addr.can_ifindex = if_nametoindex(argv[1]);
if (addr.can_ifindex != 0) {
if (bind(s, (struct sockaddr*)&addr, sizeof(addr)) == 0) {
int n;
for (n=0; n<10; n++) {
struct can_frame frame;
if (read(s, &frame, sizeof(frame)) == sizeof(frame)) {
int i;
printf("0x%X %d ", frame.can_id & CAN_EFF_MASK, frame.can_dlc);
for (i=0; i<frame.can_dlc; i++) {
printf("0x%.2X ");
}
printf("\n");
} else {
perror("read() error");
}
}
} else {
perror("bind() error");
}
} else {
perror("if_nametoindex() error");
}
} else {
perror("socket() error");
}
} else {
printf("Help:\n");
printf(" %s <interface>\n", argv[0]);
}
return 0;
}
|
C
|
/*
** EPITECH PROJECT, 2021
** mylib
** File description:
** mylib
*/
#include "../../includes/client.h"
static int info_thread(connect_t *con)
{
if (con->status != THREAD_INFO)
return 0;
char *uuid = cjson_get_by_key(con->res, "uuid");
char *title = cjson_get_by_key(con->res, "title");
char *body = cjson_get_by_key(con->res, "body");
char *timestamp = cjson_get_by_key(con->res, "timestamp");
char *user_uuid = cjson_get_by_key(con->res, "user_uuid");
client_print_thread(uuid, user_uuid, atoi(timestamp), title, body);
free(uuid);
free(title);
free(body);
free(timestamp);
free(user_uuid);
return 1;
}
static int info_channel(connect_t *con)
{
if (con->status != CHANNEL_INFO)
return 0;
char *uuid = cjson_get_by_key(con->res, "uuid");
char *name = cjson_get_by_key(con->res, "name");
char *description = cjson_get_by_key(con->res, "description");
client_print_channel(uuid, name, description);
free(uuid);
free(name);
free(description);
return 1;
}
static int info_team(connect_t *con)
{
if (con->status != TEAM_INFO)
return 0;
char *uuid = cjson_get_by_key(con->res, "uuid");
char *name = cjson_get_by_key(con->res, "name");
char *description = cjson_get_by_key(con->res, "description");
client_print_team(uuid, name, description);
free(uuid);
free(name);
free(description);
return 1;
}
int info(connect_t *con)
{
int tot = 0;
tot += info_team(con);
tot += info_channel(con);
tot += info_thread(con);
return tot;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: fviolin <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/05/24 15:12:46 by fviolin #+# #+# */
/* Updated: 2016/05/24 15:36:26 by fviolin ### ########.fr */
/* */
/* ************************************************************************** */
#include "heap.h"
int main()
{
t_heap *heap;
heap = create_heap();
push_node(heap, 12);
push_node(heap, 11);
push_node(heap, 14);
push_node(heap, 8);
push_node(heap, 13);
push_node(heap, 7);
push_node(heap, 18);
push_node(heap, 6);
push_node(heap, 1);
push_node(heap, 10);
push_node(heap, 3);
printf("Value removed : %d\n", pop_node(heap));
printf("Value removed : %d\n", pop_node(heap));
printf("Value removed : %d\n", pop_node(heap));
printf("Value removed : %d\n", pop_node(heap));
printf("Value removed : %d\n", pop_node(heap));
printf("Value removed : %d\n", pop_node(heap));
printf("Value removed : %d\n", pop_node(heap));
printf("Value removed : %d\n", pop_node(heap));
printf("Value removed : %d\n", pop_node(heap));
printf("Value removed : %d\n", pop_node(heap));
printf("Value removed : %d\n", pop_node(heap));
free_heap(heap);
return 0;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#define BUF_SIZE 2048
long int
get_tail_pos(FILE* f, int tail_size){
fseek(f, 0, SEEK_END);
char buf[BUF_SIZE];
long int file_size = ftell(f);
long int pos = file_size;
int remaining_lines = tail_size - 1;
while(remaining_lines > 0){
int read_from;
if(pos < BUF_SIZE){
read_from = 0;
} else {
read_from = pos - BUF_SIZE;
}
fseek(f, read_from, SEEK_SET);
size_t elements_read = fread(buf, sizeof(char), BUF_SIZE, f);
for(int i=elements_read; i>=0; i--){
if(buf[i] == '\n'){
if(remaining_lines < 0) {
pos++;
break;
}
remaining_lines--;
}
pos--;
if(pos <= 0){
return pos;
}
}
}
return pos;
}
int
tail_efficace(char* path, int tail_size){
FILE* f = fopen(path, "r");
char buf[BUF_SIZE];
if(f == NULL){
return -1;
}
int tail_pos = get_tail_pos(f, tail_size);
fseek(f, tail_pos, SEEK_SET);
while(1){
size_t elements_read = fread(buf, sizeof(char), BUF_SIZE, f);
for(int i=0; i<elements_read; i++){
printf("%c", buf[i]);
}
if(elements_read < BUF_SIZE) break;
}
fclose(f);
return 0;
}
int
main(void){
tail_efficace("test.txt", 25);
}
|
C
|
/*
** EPITECH PROJECT, 2019
** prompt
** File description:
** key
*/
#include <string.h>
#include <unistd.h>
#include "prompt/keys.h"
#include "prompt/cursor.h"
int key_match(char const k1[4], char const k2[4])
{
for (int i = 0; i < 4; i++) {
if (k1[i] != k2[i])
return 0;
}
return 1;
}
char find_key(char c[4])
{
for (int i = 0; special_keys_code[i][0]; i++) {
if (key_match(c, special_keys_code[i]))
return (i + 1) * -1;
}
return '^';
}
char get_key(void)
{
char t[3] = {0, 0};
char c[4] = {0, 0, 0};
read(0, &c, 1);
if (IS_GETTABLE(c[0]))
return (c[0] != '\t') ? c[0] : ' ';
read(0, &t, 2);
c[1] = t[0];
c[2] = t[1];
return find_key(c);
}
int key_cursor(char key)
{
char keys_tab[] = {-1, -2, -3, -4, 1, 5, -5, -6, 0};
for (int i = 0; keys_tab[i]; i++) {
if (keys_tab[i] == key)
return i + 1;
}
return 0;
}
char *handle_special_keys(char *str, char key, cpos_t *pos, winsize_t *w)
{
char *(*funcs[])(char *, cpos_t *, winsize_t *) = {
&up_arrow, &left_arrow, &down_arrow,
&right_arrow, &goto_start, &goto_end,
&goto_start, &goto_end
};
int got = key_cursor(key) - 1;
if (got != -1)
str = funcs[got](str, pos, w);
return str;
}
|
C
|
/* ####################################################
Demo Array size
#######################################################*/
#include <stdio.h>
# define MONTHS 12
int int_array[100];
float float_array[100];
double double_array[100];
char * string_array[100];
int main() {
printf("Size of int array : %lu \n", sizeof(int_array));
printf("Size of float array : %lu \n", sizeof(float_array));
printf("Size of double array : %lu \n", sizeof(double_array));
printf("Size of string array : %lu \n", sizeof(string_array));
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <math.h>
#include "bit_array.h"
#include "eratosthenes.h"
#include "error.h"
int main(int argc, char *argv[]){
//printf("primes\n");
ba_create(pole, 202000000);
eratosthenes(pole);
unsigned long primes[11] = { 0, };
//printf("primes end");
//getchar();
/*printf("size : %lu\n", ba_size(pole));
printf("set 3.th bit to 1\n");
ba_set_bit(pole, 3, 1);
printf("lu: %lu\n", pole[1]);
printf("bit: %lu\n", ba_get_bit(pole, 3));
*/
for (unsigned long i = 2; i < ba_size(pole); i++){
if ((ba_get_bit(pole, i)) == 0){
// je prvocislo
primes[10] = i;
for (int i = 0; i < 10; i++){
primes[i] = primes[i + 1];
}
}
}
for (int i = 0; i < 10; i++){
printf("%lu\n", primes[i]);
}
//getchar();
return 0;
}
|
C
|
#include "c_threadpool.h"
void* pull_from_queue(void* arg){
Args* args = (Args*)arg;
int thread_id = args->thread_id;
Pool* pool = args->pool;
char *act = (pool->thread_active + thread_id);
//pop node from queue
xNode* queue_item;
while (1){
pthread_mutex_lock(&(pool->queue_guard_mtx));
while (!pool->queue.tail && !(*act)){
#if DEBUG_C_THREADPOOL
printf("thread %d is sleeping\n",thread_id);
#endif
if (!pool->remaining_work && !pool->queue.tail){
//if all work from other threads has been done
pthread_cond_signal(&(pool->block_main));
}
pthread_cond_wait(&pool->hold_threads, &(pool->queue_guard_mtx));
}
queue_item = pop_node_queue(&(pool->queue));
pthread_mutex_unlock(&(pool->queue_guard_mtx));
if(queue_item){
QueueObj* q_obj;
q_obj = (QueueObj*)queue_item->data;
function_ptr f = q_obj->func;
void* args = q_obj->args;
#if DEBUG_C_THREADPOOL
printf("thread %d is working\n",thread_id);
#endif
(*f)(args);
#if DEBUG_C_THREADPOOL
printf("thread %d has finished working\n",thread_id);
#endif
free(q_obj);
pool->remaining_work--;
*act = 0;
}
//break if signalled to terminate on empty queue and queue is empty
if (pool->exit_on_empty_queue && !pool->queue.tail && !pool->updating_queue)break;
}
pool->living_threads--;
#if DEBUG_C_THREADPOOL
printf("\033[1;31mExiting thread %d \033[0m\n",thread_id );
#endif
pthread_exit(NULL);
}
void push_to_queue(Pool* pool, function_ptr f, void* args, char block){
//this function is will be used to store a pointer to a function in a queue
//pointers must point to function of type void, which takes in a void*
pthread_mutex_lock(&(pool->queue_guard_mtx)); // lock mutex to access queue
pool->remaining_work++;
QueueObj* insert = (QueueObj*)malloc(sizeof(QueueObj));
insert->func =f;
insert->args = args; //this function can be called with:(*insert->func)(insert->args);
add_node((void*)insert ,&(pool->queue)); //push into pool queue
int i;
for (i = 0; i < pool->pool_size; i++){
if(*(pool->thread_active + i)){
*(pool->thread_active + i) = 1; //only wake one thread at a time
break;
}
}
pthread_mutex_unlock(&(pool->queue_guard_mtx));
#if DEBUG_C_THREADPOOL
printf("\033[1;32mfinished pushing\033[0m\n");
#endif
if(block){
#if DEBUG_C_THREADPOOL
printf("\nblocking main\n");
#endif
pthread_cond_broadcast(&(pool->hold_threads));
while(pool->remaining_work ){
pthread_cond_wait(&(pool->block_main), &(pool->mtx_spare));
}
pthread_mutex_unlock(&(pool->mtx_spare));
#if DEBUG_C_THREADPOOL
printf("unblocking main\n\n");
#endif
pool->updating_queue = 0;
pool->living_threads = pool->pool_size;
//now signal all threads which are not active to advance them past the cond_wait() block
if(pool->exit_on_empty_queue){
//wait for threads to exit if needed
memset(pool->thread_active, 1, pool->pool_size*sizeof(char)); //mark all threads as active to escape while loop
while(pool->living_threads)pthread_cond_broadcast(&(pool->hold_threads));
}
}
}
void prepare_push(Pool* pool, char exit_on_empty_queue){
pool->exit_on_empty_queue = exit_on_empty_queue;
pool->updating_queue = 1;
}
void init_pool(Pool* pool, char pool_size){
// this function initialises a threadpool pointer;
pool->pool_size = pool_size;
pool->remaining_work = 0;
//initialise the linkedlist queue used to push arguemnts into the pool
init_xLinkedList(&(pool->queue));
//initialse bool to mark whether or not the threads should terminate after the queue is empty
pool->updating_queue = 0;
//initialise the mutex that the main thread will use to guard items being pulled from this queue
pthread_mutex_init(&(pool->queue_guard_mtx), NULL);
//initialise variables for blocking main
pthread_mutex_init(&(pool->mtx_spare), NULL);
pthread_cond_init(&(pool->block_main), NULL);
pthread_cond_init(&(pool->hold_threads), NULL);
//initialise threads and cond variable
pool->threads_pointer = (pthread_t*)malloc(pool->pool_size * (sizeof(pthread_t)));
// init all threads to be marked as not running
pool->thread_active = (char*)calloc(pool->pool_size, pool->pool_size * sizeof(char));
pthread_t* thr_p = pool->threads_pointer;
//create pthread with pointer to pull function
//initialise cond variables for all threads
int i;
for(i=0; i < pool->pool_size; i++){
Args* new_args = (Args*)malloc(sizeof(Args)); //struct for args
new_args->thread_id = i;
new_args->pool = pool;
#if DEBUG_C_THREADPOOL
printf("created thread id = %d\n", i);
#endif
pthread_create(thr_p, NULL, pull_from_queue, (void *)(new_args)); // create threads
while((pool->hold_threads).__align == 2*i);
// this ensures that threads are created in order and each thread is created properly
//(pool->hold_threads).__align is incremented by 2 for every thread created.
//advance pointer
thr_p += sizeof(pthread_t);
}
}
void cleanup(Pool* pool){
//free() up memory that has been malloced
free(pool->threads_pointer);
free(pool->thread_active);
}
/*
void join_pool(Pool* pool){
//used for testing
pthread_t* thr_p = pool->threads_pointer;
int i;
for(i=0; i < pool->pool_size; i++){
pthread_join((*thr_p), NULL);
thr_p += sizeof(pthread_t);
}
}*/
|
C
|
#include<stdlib.h>
#include<stdio.h>
#define MAX 10
struct stack
{
int items[MAX];
int top;
};
void push(struct stack*, int);
int pop(struct stack*);
void list(struct stack*);
void main()
{
struct stack s;
int c=1, ch, n;
s.top=-1;
while(c)
{
printf("main menu");
printf("\n 1. Push the element");
printf("\n 2. Pop the element");
printf("\n 3. List all element");
printf("\n 4. Exit");
printf("\n Enter your choice=");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("Enter any number:");
scanf("%d", &n);
push(&s, n);
break;
case 2:
n= pop(&s);
printf("Deleted number=%d", n);
break;
case 3:
list(&s);
break;
case 4:
exit(0);
default:
printf("Invalid choice");
}
}
}
void push(struct stack *s, int x)
{
if(s->top==MAX-1)
{
printf("overflow");
return;
}
s->items[++(s->top)]=x;
}
int pop(struct stack*s)
{
if (s->top==-1)
{
printf("Underflow");
return-1;
}
return(s->items[s->top--]);
}
void list(struct stack *s)
{
int t;
if(s->top==-1)
{
printf("Empty");
return;
}
for(t=s->top;t>0;t--)
printf("%d",s->items[t]);
}
|
C
|
/*
* uC1_car.c
*
* Created: 11/30/2019 2:43:07 PM
* Author : aahun
*/
#define F_CPU 8000000UL
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <math.h>
#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>
#include <avr/eeprom.h>
#include <avr/portpins.h>
#include <avr/pgmspace.h>
#include "usart_ATmega1284.h"
#define Trigger_pin PA0 //this is for the Sonar sensor
//ultrasonic sensor global variable
int TimerOverflow = 0; // variable overflow for the SonarSensor
long count;
//double distance = 0.00;
int distance = 0;
//Radar Functions
ISR(TIMER1_OVF_vect)
{
TimerOverflow++; // Increment Timer Overflow count
}
void Radar(){
PORTA |= (1 << Trigger_pin); // Give 10us trigger pulse on trig. pin to HC-SR04
_delay_us(10);
PORTA &= (~(1 << Trigger_pin));
TCNT1 = 0; // Clear Timer counter
TCCR1B = 0x41; // Setting for capture rising edge, No pre-scaler
TIFR1 = 1<<ICF1; // Clear ICP flag (Input Capture flag)
TIFR1 = 1<<TOV1; // Clear Timer Overflow flag
//Calculate width of Echo by Input Capture (ICP) on PortD PD6
if ((TIFR1 & (1 << ICF1)) == 0); // Wait for rising edge
TCNT1 = 0; // Clear Timer counter
TCCR1B = 0x01; // Setting for capture falling edge, No pre-scaler
TIFR1 = 1<<ICF1; // Clear ICP flag (Input Capture flag)
TIFR1 = 1<<TOV1; // Clear Timer Overflow flag
TimerOverflow = 0; // Clear Timer overflow count
if ((TIFR1 & (1 << ICF1)) == 0); // Wait for falling edge
count = ICR1 + (65535 * TimerOverflow); // Take value of capture register
distance = (double)count / 760.47 ;
//distance = ((double)count / 466.47);
_delay_us(15000);
}
//FreeRTOS include files
#include "FreeRTOS.h"
#include "task.h"
#include "croutine.h"
unsigned char distFlag;
unsigned char temp;
// Distance SM
enum DistanceStates {dist_init,dist01} distance_state;
void Distance_Init(){
distance_state = dist_init;
}
void Distance_Tick(){
//Actions
switch(distance_state){
case dist_init:
distFlag = 0;
break;
case dist01:
Radar();
if(distance <= 35) {
distFlag = 1;
PORTB |= (1 << PB0); // PB0 goes high
}
else {
distFlag = 0;
PORTB &= ~(1 << PB0); // PD0 goes low
}
break;
default:
break;
}
//Transitions
switch(distance_state){
case dist_init:
distance_state = dist01;
break;
case dist01:
distance_state = dist01;
break;
default:
distance_state = dist_init;
break;
}
}
void DistanceOut() {
Distance_Init();
for(;;) {
Distance_Tick();
vTaskDelay(20);
}
}
void Distance(unsigned portBASE_TYPE Priority) {
xTaskCreate(DistanceOut,
(signed portCHAR *)"DistanceOut",
configMINIMAL_STACK_SIZE,
NULL,
Priority,
NULL );
}
// Distance SM
// Receive SM
enum ReceiveStates {re_init,re01} receive_state;
void Receive_Init(){
receive_state = re_init;
}
void Receive_Tick(){
//Actions
switch(receive_state){
case re_init:
temp = 0;
break;
case re01:
if(USART_HasReceived(1)) {
temp = USART_Receive(1);
USART_Flush(1);
}
break;
default:
break;
}
//Transitions
switch(receive_state){
case re_init:
receive_state = re01;
break;
case re01:
receive_state = re01;
break;
default:
receive_state = re_init;
break;
}
}
void ReceiveOut() {
Receive_Init();
for(;;) {
Receive_Tick();
vTaskDelay(1);
}
}
void Receive(unsigned portBASE_TYPE Priority) {
xTaskCreate(ReceiveOut,
(signed portCHAR *)"ReceiveOut",
configMINIMAL_STACK_SIZE,
NULL,
Priority,
NULL );
}
// Receive SM
// Drive SM
enum DriveStates {drive_init, stop, front, frontleft, frontright, left, right, rearleft, rearright, rear} drive_state;
void Drive_Init(){
drive_state = drive_init;
}
void Drive_Tick(){
//Actions
switch(drive_state){
case drive_init:
PORTC = 0;
break;
case stop:
PORTC = 0;
break;
case front:
PORTC = 0x55;
break;
case frontleft:
PORTC = 0x59;
break;
case frontright:
PORTC = 0x56;
break;
case left:
PORTC = 0x69;
break;
case right:
PORTC = 0x96;
break;
case rearleft:
PORTC = 0x9A;
break;
case rearright:
PORTC = 0x6A;
break;
case rear:
PORTC = 0xAA;
break;
default:
break;
}
//Transitions
switch(drive_state){
case drive_init:
drive_state = stop;
break;
case stop:
if(temp == 0) {
drive_state = stop;
}
else if(temp == 1 && !distFlag) {
drive_state = front;
}
else if(temp == 2 && !distFlag) {
drive_state = frontleft;
}
else if(temp == 3 && !distFlag) {
drive_state = frontright;
}
else if(temp == 4 && !distFlag) {
drive_state = left;
}
else if(temp == 5 && !distFlag) {
drive_state = right;
}
else if(temp == 6) {
drive_state = rearleft;
}
else if(temp == 7) {
drive_state = rearright;
}
else if(temp == 8) {
drive_state = rear;
}
else {
drive_state = stop;
}
break;
case front:
if(temp == 1 && !distFlag) {
drive_state = front;
}
else {
drive_state = stop;
}
break;
case frontleft:
if(temp == 2 && !distFlag) {
drive_state = frontleft;
}
else {
drive_state = stop;
}
break;
case frontright:
if(temp == 3 && !distFlag) {
drive_state = frontright;
}
else {
drive_state = stop;
}
break;
case left:
if(temp == 4 && !distFlag) {
drive_state = left;
}
else {
drive_state = stop;
}
break;
case right:
if(temp == 5 && !distFlag) {
drive_state = right;
}
else {
drive_state = stop;
}
break;
case rearleft:
if(temp == 6) {
drive_state = rearleft;
}
else {
drive_state = stop;
}
break;
case rearright:
if(temp == 7) {
drive_state = rearright;
}
else {
drive_state = stop;
}
break;
case rear:
if(temp == 8) {
drive_state = rear;
}
else {
drive_state = stop;
}
break;
default:
drive_state = drive_init;
break;
}
}
void DriveOut() {
Drive_Init();
for(;;) {
Drive_Tick();
vTaskDelay(1);
}
}
void Drive(unsigned portBASE_TYPE Priority) {
xTaskCreate(DriveOut,
(signed portCHAR *)"DriveOut",
configMINIMAL_STACK_SIZE,
NULL,
Priority,
NULL );
}
// Drive SM
int main(void) {
DDRA = 0x0F; PORTA = 0xF0;
DDRB = 0xFF; PORTB = 0x00;
DDRC = 0xFF; PORTC = 0x00;
DDRD = 0x00; PORTD = 0xFF;
TIMSK1 = (1 << TOIE1);
TCCR1A = 0;
sei();
initUSART(1);
//Radar();
//Start Tasks
Distance(1);
Receive(1);
Drive(1);
//RunSchedular
vTaskStartScheduler();
return 0;
}
|
C
|
#include <stdio.h>
#define INIT_VALUE -1
int findSubstring(char *str, char *substr);
int main()
{
char str[40], substr[40];
int result = INIT_VALUE;
printf("Enter the string: \n");
gets(str);
printf("Enter the substring: \n");
gets(substr);
result = findSubstring(str, substr);
if (result == 1)
printf("findSubstring(): Is a substring\n");
else if ( result == 0)
printf("findSubstring(): Not a substring\n");
else
printf("findSubstring(): An error\n");
return 0;
}
int findSubstring(char *str, char *substr)
{
/* Write your code here */
int substrlen = 0;
while (substr[substrlen] != '\0'){
substrlen++;
}
int i, strpos = 0, result = 1;
while (str[strpos] != '\0'){
for (i=0; i<substrlen; i++){
if (str[strpos+i] != substr[i])
result = 0;
}
if (result == 1)
return result;
else
strpos++;
}
return result;
}
|
C
|
#include<sys/ipc.h>
#include<sys/shm.h>
#include<sys/types.h>
#include<stdio.h>
#include<errno.h>
int main()
{
//int shmget(key_t key, size_t size, int shmflg)
int segment_id;
struct shmid_ds shmbuffer;
//create a new share menory object
segment_id = shmget(IPC_PRIVATE, 128, IPC_CREAT|IPC_EXCL|0600);
if(segment_id == -1)
{
perror("shmget error!");
return -1;
}
//int shmctl(int shmid, int cmd, struct shmid_ds *buf)
int ctl_id;
ctl_id = shmctl(segment_id, IPC_STAT, &shmbuffer);
if(ctl_id == -1)
{
perror("shmctl error!");
return -1;
}
printf("segment ID: %d\n", segment_id);
printf("Key: %d\n", (int)shmbuffer.shm_perm.__key);
printf("Mode: %d\n", (int)shmbuffer.shm_perm.mode);
printf("Onwer UID: %d\n", (int)shmbuffer.shm_perm.uid);
printf("Size: %d\n", (int)shmbuffer.shm_segsz);
printf("Number of atthchment: %d\n", (int)shmbuffer.shm_nattch);
}
|
C
|
#include <stdio.h>
#include <unistd.h>
#include <sys/time.h>
#include <sys/resource.h>
extern void random_length_task();
int main(int argc, char **argv) {
struct timeval tv;
int times = 10;
long long int last;
if (argc > 1)
sscanf(argv[1], "%d", ×);
srand(time(0));
// setpriority(PRIO_PROCESS, getpid(), -20);
gettimeofday(&tv, NULL);
last = tv.tv_usec;
while (times--) {
random_length_task();
while ((1000000 + tv.tv_usec - last) % 1000000 < 100000) {
// usleep(1);
gettimeofday(&tv, NULL);
}
last = tv.tv_usec;
}
return 0;
}
|
C
|
/* This is a naive implementation of Snelling's algorithm, ICS 1973 */
#include <stdio.h>
#include <stdlib.h>
#include "global.h"
#include "parser.h"
#include "driver.h"
#include "grammar.h"
static int trace = 1;
/* ACCESS ROUTINES */
static int
in_N(char n) {
int i;
for (i = 0; i < n_N; i++) {
if (N[i] == n) return 1;
}
return 0;
}
static int
in_T(char n) {
return !in_N(n); /* text has: "&& n != end" */
}
/* RECOGNIZER */
struct state {
int in_use;
int p; /* rule number */
int j; /* position of dot */
int f; /* start position */
int deleted_at; /* i at which deleted, > 0 */
#ifdef LONG
int F[MAX_n+1]; /* list of item start positions */
int n_F; /* number of elements in F */
#endif
};
static struct state
state(int p, int j, int f) {
struct state res;
res.in_use = 1;
res.p = p;
res.j = j;
res.f = f;
res.deleted_at = 0;
return res;
}
static int
are_equal_core_states(struct state s1, struct state s2) {
return (s1.p == s2.p && s1.j == s2.j);
}
static int
are_equal_states(struct state s1, struct state s2) {
return (are_equal_core_states(s1, s2) && s1.f == s2.f);
}
static basic_step_counter;
static char *
state2string(struct state s) {
static char res[MAX_j + 100];
char *p = res;
int i;
int deleted = 0;
if (!s.in_use) {
p += sprintf(p, "unused state");
return res;
}
if (s.p < 0) {
deleted = 1;
s.p = -s.p; /* it's a copy anyway */
}
p += sprintf(p, "%s%c -> ", (deleted ? "[" : " "), D[s.p]);
for (i = 0; i < bar[s.p]; i++) {
if (i == s.j) p += sprintf(p, ".");
p += sprintf(p, "%c", C[s.p][i+1]);
}
if (i == s.j) p += sprintf(p, ".");
i += 4;
while (i < MAX_j-2) {
p += sprintf(p, " ");
i++;
}
p += sprintf(p, "@ %d", s.f);
if (deleted) {
p += sprintf(p, "] %d", s.deleted_at);
}
return res;
}
static char marked[128]; /* non-terminal markers */
static void
unmark_all_N(void) {
int p;
for (p = 0; p < 128; p++) {
marked[p] = 0;
}
}
static struct state S[MAX_n+1][MAX_s];
static void
insert_state_before(struct state s, struct state *set) {
while (set->in_use) {
struct state tmp = *set;
*set++ = s;
s = tmp;
}
*set = s;
}
static void
add_state(const char *process, struct state s, struct state *set) {
/* since the algorithm is sensitive to the order of the items in S[i],
we keep items with the same core together, ordered by decreasing f
*/
if (trace) {
printf("%s added state %s to S[%d]\n",
process, state2string(s), (set - S[0]) / MAX_s);
}
basic_step_counter++;
while (set->in_use) {
if (are_equal_core_states(s, *set)) {
while ( set->in_use
&& are_equal_core_states(s, *set)
) {
if (s.f > set->f) {
insert_state_before(s, set);
return;
}
if (s.f == set->f) return;
if (s.f < set->f) {
set++;
}
}
insert_state_before(s, set);
return;
}
set++;
}
*set = s;
}
static void
dont_add_state(const char *process, struct state s, struct state *set) {
if (trace) {
printf("%s did not add state %s to S[%d]\n",
process, state2string(s), (set - S[0]) / MAX_s);
}
}
static void
print_S(void) {
int i;
for (i = 0; S[i][0].in_use; i++) {
int j;
printf("S[%d]:\n", i);
for (j = 0; S[i][j].in_use; j++) {
printf("\t%s\n", state2string(S[i][j]));
}
}
}
static void
PREDICTOR(int i, int p, int j, int f) {
if (!marked[C[p][j+1]]) {
int r;
for (r = 0; r <= d; r++) {
if (D[r] == C[p][j+1]) {
add_state("PREDICTOR ", state(r,0,i), S[i]);
marked[C[p][j+1]] = 1;
}
}
}
}
static void
SCANNER(int i, int p, int j, int f) {
if (C[p][j+1] == X[i+1]) {
add_state("SCANNER ", state(p, j+1, f), S[i+1]);
}
}
static int
in_S(int i, int p, int j, int f) {
int s;
for (s = 0; S[i][s].in_use; s++) {
if (are_equal_states(state(p, j, f), S[i][s])) return 1;
}
return 0;
}
static struct state *SbpF[MAX_s];
static void fill_SbpF_from(int p, int f);
static void
add_to_SbpF(struct state *s) {
int i;
/* see if it is already there */
for (i = 0; SbpF[i]; i++) {
if (are_equal_states(*s, *SbpF[i])) return;
}
SbpF[i++] = s;
SbpF[i++] = 0;
}
static void
fill_SbpF_from(int p, int i) {
/* Add all items of the form A -> ... .B ... @ f with B = D[p] to
SbpF, in decreasing f order.
Rather than sorting them for f, we generate them for f = i, i-1, ...
which is stupid but safe.
*/
int f;
for (f = i; f >= 0; f--) {
struct state *s;
for (s = &S[i][0]; s->in_use; s++) {
if ( /* it has the starting point we want */
s->f == f
&& /* it has the dot in front of the right NT */
C[s->p][s->j+1] == D[p] && in_N(D[p])
/* text has: C[p][j+1] == D[p] && in_N(D[p]) */
) {
add_to_SbpF(s);
}
}
}
}
static void
print_SbpF(const char *msg) {
int i;
printf("SbpF %s:\n", msg);
for (i = 0; SbpF[i]; i++) {
printf("\t%s\n", state2string(*SbpF[i]));
}
}
/* set of states added to S[i] by this call of the completer: */
static int n_Si; /* points to first free in S[i] at start of completer */
static void
begin_added_to_S_i(int i) {
for (n_Si = 0; S[i][n_Si].in_use; n_Si++) {
}
}
static int
added_to_S_i_by_this_completer_call(int i, int p1, int j1, int f1) {
int s;
for (s = n_Si; S[i][s].in_use; s++) {
if (are_equal_states(state(p1, j1, f1) , S[i][s]))
return 1;
}
return 0;
}
static void
print_added_to_S_i(int i) {
int s;
printf("added_to_S_i:\n");
for (s = n_Si; S[i][s].in_use; s++) {
printf("\t%s\n", state2string(S[i][s]));
}
}
static int
condition_1(int i, int p1, int j1, int f1) {
int f2;
for (f2 = f1+1; f2 <= i; f2++) {
if (added_to_S_i_by_this_completer_call(i,p1,j1+1,f2))
return 1;
}
return 0;
}
static int
condition_3(int i, int p1, int j1, int f1) {
int s;
printf("3)\n"); fflush(stdout); fflush(stderr);
for (s = 0; S[i][s].in_use; s++) {
int p2 = S[i][s].p;
int j2 = S[i][s].j;
int f2 = S[i][s].f;
if (j2 == bar[p2] && f2 == f1 && D[p1] == D[p2]) return 1;
}
printf("3)0\n"); fflush(stdout); fflush(stderr);
return 0;
}
static void
delete_state(const char *process, struct state *s, int i) {
/* The delete action should not shift the states in S[i], since S[i] is
being scanned by the overall loop. So we temporarily destroy the
state and compress afterwards.
*/
if (trace) {
printf("%s deleted state %s\n", process, state2string(*s));
}
/* make state unrecognizable */
s->p = -s->p; /* the state with p == 0 is never deleted */
s->deleted_at = i;
}
static void
possibilities_1_to_5(int i, struct state *s1) {
int p1 = s1->p;
int j1 = s1->j;
int f1 = s1->f;
/* we pass on the pointer to s1, since we may have to delete s1 */
if (trace) {
printf("referring back to %s in SbpF\n",
state2string(state(p1, j1, f1)));
}
#define _EARLEY
#ifndef EARLEY
printf("A\n"); fflush(stdout); fflush(stderr);
/* 1) */
if ( j1+1 == bar[p1] /* text has: bar[p] */
&& condition_1(i, p1, j1, f1)
) {
/* there is right recursivity */
delete_state("COMPLETER.1", s1, i);
dont_add_state("COMPLETER.1", state(p1, j1+1, f1), S[i]);
return;
}
printf("B\n"); fflush(stdout); fflush(stderr);
/* 2) */
if (in_S(i, p1, j1+1, f1)) {
printf("B1\n"); fflush(stdout); fflush(stderr);
print_added_to_S_i(i);
if (added_to_S_i_by_this_completer_call(i, p1, j1+1, f1)) {
printf("B2\n"); fflush(stdout); fflush(stderr);
/* there is an ambiguity */
delete_state("COMPLETER.2", s1, i);
}
dont_add_state("COMPLETER.2", state(p1, j1+1, f1), S[i]);
return;
}
printf("C\n"); fflush(stdout); fflush(stderr);
/* 3) */
if ( j1+1 == bar[p1] /* text has: bar[p] */
&& condition_3(i, p1, j1, f1)
) {
printf("C1\n"); fflush(stdout); fflush(stderr);
/* there is an ambiguity */
dont_add_state("COMPLETER.3", state(p1, j1+1, f1), S[i]);
return;
}
printf("D\n"); fflush(stdout); fflush(stderr);
/* 4) */
/* f-lists not implemented, so this reduces to case 5) */
#endif
printf("E\n"); fflush(stdout); fflush(stderr);
/* 5) */
add_state("COMPLETER.5", state(p1, j1+1, f1), S[i]);
if (j1+1 == bar[p1]) {
fill_SbpF_from(p1, f1);
}
}
static void
start_completer(int i) {
begin_added_to_S_i(i);
SbpF[0] = 0;
}
static void
end_completer(void) {
/* clean up deleted items */
/* not really needed ???? */
}
static void
COMPLETER(int i, int p, int j, int f) {
int s;
start_completer(i);
if (trace) {
printf("offered to COMPLETER at %d: %s\n",
i, state2string(state(p, j, f)));
}
/* for all states in SbpF */
fill_SbpF_from(p, f);
print_SbpF("after first entry");
for (s = 0; SbpF[s]; s++) {
printf("state in SbpF: %s\n", state2string(*SbpF[s]));
possibilities_1_to_5(i, SbpF[s]);
}
print_SbpF("at end");
end_completer();
}
static int
i_such_that_Si_is_empty(void) {
int i;
for (i = 0; i <= MAX_n; i++) {
if (!S[i][0].in_use) return i;
}
return MAX_n+1; /* cannot happen */
}
void
recognizer(void) {
int i;
int s;
/* 3.1.1. Initialisation */
add_state("INITIALISER", state(0, 0, 0), S[0]);
unmark_all_N();
i = 0;
basic_step_counter = 0;
/* 3.1.2. */
E: /* for every state <p,j,f> in S[i] */
printf("\nstarting processing S[%d]:\n", i);
for (s = 0; S[i][s].in_use; s++) {
int p = S[i][s].p;
int j = S[i][s].j;
int f = S[i][s].f;
if (j != bar[p] && in_N(C[p][j+1])) {
PREDICTOR(i, p, j, f);
}
if (j != bar[p] && in_T(C[p][j+1])) {
SCANNER(i, p, j, f);
}
if (j == bar[p]) {
COMPLETER(i, p, j, f);
}
/*
printf("after i = %d, s = %d\n", i, s);
print_S();
*/
}
unmark_all_N();
printf("ending processing S[%d]\n", i);
i = i+1;
if (i <= n+1) goto E;
/* 3.1.3. Termination */
if (are_equal_states(S[n+1][0], state(0, 2, 0))) {
printf("`%s' in L(G)\n", &X[1]);
}
i = i_such_that_Si_is_empty();
if (0 <= i && i <= n+1) {
printf("`%s' not in L(G), error at pos. %d\n", &X[1], i);
}
printf("n = %d, basic_step_counter = %d\n", n, basic_step_counter);
print_S();
}
|
C
|
/*!
* \file LivingColors.h
* \version 1.1
* \date 29-01-2009
* \author George Mathijssen, [email protected]
*
* Copyright (c) 2008, 2009 George Mathijssen
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* \internal
* Created: 03-10-2008
*/
#ifndef LIVINGCOLORS_H_
#define LIVINGCOLORS_H_
#include "CC2500.h"
#include "ColourConversion.h"
#include <inttypes.h>
#define MAXLAMPS 6
/*! \brief Class for interfacing with Philips LivingColors lamp.
*
* This class implements basic functions to communicate with the LivingColors lamp.
*/
/*!
* Initializes communication with the LivingColors lamp.
*/
void LivingColors_init();
/*!
* Returns the maximum number of storable lamps.
*
* \return Maximum number of lamps.
*/
unsigned char LivingColors_getMaxNumLamps();
/*!
* Returns the number of currently known lamps.
*
* \return Number of known adresses.
*/
unsigned char LivingColors_getNumLamps();
/*!
* Adds a lamp address to storage. Address must be 9 bytes long.
*
* \param[in] address Array holding lamp address.
* \return Lamp index for address or -1 on failure.
*/
char LivingColors_addLamp(unsigned char* address);
/*!
* Saves the address of lamp with given index in supplied array. Only fills array when index and
* address are valid.
*
* \param[in] index Lamp index, must be 0 <= index < getNumLamps().
* \param[in] address Array for lamp address, must be at least 9 bytes long.
* \return True if array is filled with valid address, false otherwise.
*/
uint8_t LivingColors_getLamp(unsigned char index, unsigned char* address);
/*!
* Tries to learn lamp addresses by snooping the commands which are sent by the official
* remote. The learning time period is about 5 seconds; hold the official remote very close
* to the board and press some commands (e.g. change colour, off, on).
*/
void LivingColors_learnLamps();
/*!
* Clears all lamp addresses.
*/
void LivingColors_clearLamps();
/*!
* Sets colour of lamp with given index. Updates colour only if lamp address is valid.
*
* \param[in] index Lamp index, must be 0 <= index < getNumLamps().
* \param[in] r Red value for lamp (0-255).
* \param[in] g Green value for lamp (0-255).
* \param[in] b Blue value for lamp (0-255).
*/
void LivingColors_setLampColourRGB(unsigned char index, unsigned char r, unsigned char g, unsigned char b);
/*!
* Sets colour of lamp with given index. Updates colour only if lamp address is valid.
*
* \param[in] index Lamp index, must be 0 <= index < getNumLamps().
* \param[in] h Hue value for lamp (0-255).
* \param[in] s Saturation value for lamp (0-255).
* \param[in] v Value value for lamp (0-255).
*/
void LivingColors_setLampColourHSV(unsigned char index, unsigned char h, unsigned char s, unsigned char v);
/*!
* Turns lamp with given index on and sets colour if lamp address is valid.
*
* \param[in] index Lamp index, must be 0 <= index < getNumLamps().
* \param[in] r Red value for lamp (0-255).
* \param[in] g Green value for lamp (0-255).
* \param[in] b Blue value for lamp (0-255).
*/
void LivingColors_turnLampOnRGB(unsigned char index, unsigned char r, unsigned char g, unsigned char b);
/*!
* Turns lamp with given index on and sets colour if lamp address is valid.
*
* \param[in] index Lamp index, must be 0 <= index < getNumLamps().
* \param[in] h Hue value for lamp (0-255).
* \param[in] s Saturation value for lamp (0-255).
* \param[in] v Value value for lamp (0-255).
*/
void LivingColors_turnLampOnHSV(unsigned char index, unsigned char h, unsigned char s, unsigned char v);
/*!
* Turns lamp with given index off if lamp address is valid.
*
* \param[in] index Lamp index, must be 0 <= index < getNumLamps();
*/
void LivingColors_turnLampOff(unsigned char index);
#endif
|
C
|
#include <stdbool.h>
typedef struct Stack {
int stack[20];
int size;
} Stack;
bool stack_empty(Stack* stack);
void push(Stack* stack, const int value);
void pop(Stack* stack);
int top(Stack* stack);
int size(Stack* stack);
void print(Stack* stack);
|
C
|
//Runtime:Runtime: 16 ms
//Beats 64.61%
int myAtoi(char* str) {
int value = 0, sign = 1;
while(*str == ' ') str++;
if(*str == '+' || *str == '-') {
sign = *str == '-' ? -1 : 1;
str++;
}
while(*str >= '0' && *str <= '9') {
if(value > INT_MAX / 10 || (value == INT_MAX / 10 && *str - '0' > 7)) return sign == 1 ? INT_MAX : INT_MIN;
value = value * 10 + (*str - '0');
str++;
}
return value * sign;
}
|
C
|
#include <stdio.h>
int main()
{
int n;
printf("請輸入班級人數:");
scanf("%d", &n);
int a = n / 12;
int b = n % 12;
printf("總共需要付%d元\n", a * 50 + b * 5);
return 0;
}
|
C
|
#include "livestock.h"
//Initializes a livestock struct with a name
struct Livestock * sub_809B454(struct Livestock *lstock, u8 *name, u32 *param, u32 age, u32 daysFed){
sub_809B12C(&lstock->animal, name, param, age);
lstock->daysFed = daysFed;
lstock->fed = FALSE;
lstock->unhappy = FALSE;
lstock->sick = FALSE;
lstock->unk_0x1D_0 = 0;
lstock->daysUnhappy = 0;
lstock->daysSick = 0;
lstock->currentOutdoorMinutes = 0;
lstock->totalOutdoorMinutes = 0;
return lstock;
}
//Initializes a livestock struct
struct Livestock * sub_809B4A4(struct Livestock *lstock, u32 *param, u32 age, u32 daysFed){
sub_809B1A4(&lstock->animal, param, age);
lstock->daysFed = daysFed;
lstock->fed = FALSE;
lstock->unhappy = FALSE;
lstock->sick = FALSE;
lstock->unk_0x1D_0 = 0;
lstock->daysUnhappy = 0;
lstock->daysSick = 0;
lstock->currentOutdoorMinutes = 0;
lstock->totalOutdoorMinutes = 0;
return lstock;
}
//Returns the number of days fed
u32 sub_809B4F4(struct Livestock *lstock){
return lstock->daysFed;
}
//Returns the fed flag
bool8 sub_809B4FC(struct Livestock *lstock){
return lstock->fed;
}
//Returns the unhappy flag
bool8 sub_809B504(struct Livestock *lstock){
return lstock->unhappy;
}
//Returns the sick flag
bool8 sub_809B50C(struct Livestock *lstock){
return lstock->sick;
}
//Returns the unknown 2bit value 0x1D_0
u8 sub_809B514(struct Livestock *lstock){
return lstock->unk_0x1D_0;
}
//Returns the current number of outdoor minutes
u32 sub_809B51C(struct Livestock *lstock){
return lstock->currentOutdoorMinutes;
}
//Returns the total number of outdoor minutes
u32 sub_809B524(struct Livestock *lstock){
return lstock->totalOutdoorMinutes;
}
//Returns a livestock's product level
u32 sub_809B538(struct Livestock *lstock){
u32 affection = sub_809B228(&lstock->animal);
//0-3 Hearts
if(affection <= 100)
return 0;
//4-7 Hearts
else if(affection <= 200)
return 1;
//Festival winner + 8-10 Hearts
else if(sub_809B218(&lstock->animal)){
//600 outdoor hours
if(sub_809B524(lstock) >= 36000)
return 4;
else
return 3;
}
//8-10 Hearts
return 2;
}
struct UnkStruct{
u32 _0;
u32 _4;
u32 _8;
u32 _C;
};
//Increases the number of current and total outdoor minutes
void sub_809B57C(struct Livestock *lstock, u32 param){
struct UnkStruct _struct;
u32 temp = lstock->currentOutdoorMinutes;
if (temp <= 510) {
u32 *ptr, *ptr2;
_struct._0 = temp + param;
_struct._4 = 511;
ptr2 = &_struct._4;
ptr = &_struct._0;
if (_struct._0 > _struct._4)
ptr = ptr2;
lstock->currentOutdoorMinutes = *ptr;
}
temp = lstock->totalOutdoorMinutes;
if (temp < 0xFFFF) {
u32 *ptr, *ptr2;
_struct._8 = temp + param;
_struct._C = 0xFFFF;
ptr2 = &_struct._C;
ptr = &_struct._8;
if (_struct._8 > _struct._C)
ptr = ptr2;
lstock->totalOutdoorMinutes = *ptr;
}
}
//Resets the current number of outdoor minutes
void sub_809B608(struct Livestock *lstock){
lstock->currentOutdoorMinutes = 0;
}
//Sets the sick flag
void sub_809B618(struct Livestock *lstock){
lstock->sick = TRUE;
}
//Clears the sick flag and days
void sub_809B624(struct Livestock *lstock, u32 param){
lstock->sick = FALSE;
lstock->daysSick = 0;
}
//Sets the unhappy flag
void sub_809B638(struct Livestock *lstock){
lstock->unhappy = TRUE;
}
//Clears the unhappy flag and days
void sub_809B644(struct Livestock *lstock, u32 param){
lstock->unhappy = FALSE;
lstock->daysUnhappy = 0;
}
//Sets the fed flag
void sub_809B65C(struct Livestock *lstock){
bool8 temp = lstock->fed;
if(!temp)
lstock->fed = TRUE;
}
NAKED
//Checks if you fed a livestock
void sub_809B674(struct Livestock *lstock, u8 *param){
asm_unified("\n\
push {r4, r5, r6, r7, lr}\n\
mov r7, r8\n\
push {r7}\n\
adds r5, r0, #0\n\
adds r7, r1, #0\n\
bl sub_809B2E8\n\
ldrb r2, [r5, #0x1c]\n\
lsls r0, r2, #0x1a\n\
lsrs r3, r0, #0x1f\n\
cmp r3, #0\n\
beq _0809B6AE\n\
lsls r0, r2, #0x1b\n\
lsrs r0, r0, #0x1b\n\
cmp r0, #0x1e\n\
bhi _0809B6A4\n\
adds r1, r0, #1\n\
movs r0, #0x1f\n\
ands r1, r0\n\
movs r0, #0x20\n\
rsbs r0, r0, #0\n\
ands r0, r2\n\
orrs r0, r1\n\
strb r0, [r5, #0x1c]\n\
_0809B6A4:\n\
ldrb r1, [r5, #0x1c]\n\
movs r0, #0x21\n\
rsbs r0, r0, #0\n\
ands r0, r1\n\
strb r0, [r5, #0x1c]\n\
_0809B6AE:\n\
ldrh r0, [r5, #0x1e]\n\
ldr r1, _0809B6DC @ =0xFFFFFE00\n\
ands r1, r0\n\
strh r1, [r5, #0x1e]\n\
ldrb r0, [r5, #0x1c]\n\
lsls r0, r0, #0x19\n\
cmp r0, #0\n\
bge _0809B6E0\n\
cmp r3, #0\n\
beq _0809B6FC\n\
bl sub_80D11E4\n\
movs r1, #0x64\n\
bl sub_80D0ED0\n\
ldrb r1, [r7]\n\
cmp r0, r1\n\
bge _0809B6FC\n\
ldrb r1, [r5, #0x1c]\n\
movs r0, #0x41\n\
rsbs r0, r0, #0\n\
ands r0, r1\n\
b _0809B6FA\n\
.align 2, 0\n\
_0809B6DC: .4byte 0xFFFFFE00\n\
_0809B6E0:\n\
cmp r3, #0\n\
bne _0809B6FC\n\
bl sub_80D11E4\n\
movs r1, #0x64\n\
bl sub_80D0ED0\n\
ldrb r1, [r7, #1]\n\
cmp r0, r1\n\
bge _0809B6FC\n\
ldrb r0, [r5, #0x1c]\n\
movs r1, #0x40\n\
orrs r0, r1\n\
_0809B6FA:\n\
strb r0, [r5, #0x1c]\n\
_0809B6FC:\n\
ldrb r0, [r5, #0x1c]\n\
lsls r0, r0, #0x19\n\
cmp r0, #0\n\
bge _0809B720\n\
ldrb r2, [r5, #0x1d]\n\
lsls r0, r2, #0x1b\n\
lsrs r1, r0, #0x1d\n\
cmp r1, #6\n\
bhi _0809B72A\n\
adds r1, #1\n\
movs r0, #7\n\
ands r1, r0\n\
lsls r1, r1, #2\n\
movs r0, #0x1d\n\
rsbs r0, r0, #0\n\
ands r0, r2\n\
orrs r0, r1\n\
b _0809B728\n\
_0809B720:\n\
ldrb r1, [r5, #0x1d]\n\
movs r0, #0x1d\n\
rsbs r0, r0, #0\n\
ands r0, r1\n\
_0809B728:\n\
strb r0, [r5, #0x1d]\n\
_0809B72A:\n\
ldrb r1, [r5, #0x1c]\n\
lsrs r0, r1, #7\n\
cmp r0, #0\n\
bne _0809B76E\n\
lsls r0, r1, #0x19\n\
cmp r0, #0\n\
bge _0809B76E\n\
ldrb r1, [r5, #0x1d]\n\
movs r0, #0x1c\n\
ands r0, r1\n\
cmp r0, #0\n\
beq _0809B74A\n\
lsls r0, r1, #0x1b\n\
lsrs r0, r0, #0x1d\n\
subs r4, r0, #1\n\
b _0809B74C\n\
_0809B74A:\n\
movs r4, #0\n\
_0809B74C:\n\
cmp r4, #6\n\
bls _0809B752\n\
movs r4, #6\n\
_0809B752:\n\
bl sub_80D11E4\n\
movs r1, #0x64\n\
bl sub_80D0ED0\n\
adds r1, r7, #2\n\
adds r1, r1, r4\n\
ldrb r1, [r1]\n\
cmp r0, r1\n\
bge _0809B76E\n\
ldrb r0, [r5, #0x1c]\n\
movs r1, #0x80\n\
orrs r0, r1\n\
strb r0, [r5, #0x1c]\n\
_0809B76E:\n\
ldrb r0, [r5, #0x1c]\n\
lsrs r1, r0, #7\n\
adds r3, r0, #0\n\
cmp r1, #0\n\
beq _0809B78C\n\
ldrb r2, [r5, #0x1d]\n\
lsrs r1, r2, #5\n\
cmp r1, #6\n\
bhi _0809B794\n\
adds r1, #1\n\
lsls r1, r1, #5\n\
movs r0, #0x1f\n\
ands r0, r2\n\
orrs r0, r1\n\
b _0809B792\n\
_0809B78C:\n\
ldrb r1, [r5, #0x1d]\n\
movs r0, #0x1f\n\
ands r0, r1\n\
_0809B792:\n\
strb r0, [r5, #0x1d]\n\
_0809B794:\n\
movs r0, #0\n\
mov r8, r0\n\
lsls r0, r3, #0x18\n\
cmp r0, #0\n\
bge _0809B7D0\n\
ldrb r1, [r5, #0x1d]\n\
movs r0, #0xe0\n\
ands r0, r1\n\
cmp r0, #0\n\
beq _0809B7AE\n\
lsrs r0, r1, #5\n\
subs r4, r0, #1\n\
b _0809B7B0\n\
_0809B7AE:\n\
movs r4, #0\n\
_0809B7B0:\n\
cmp r4, #4\n\
bls _0809B7B6\n\
movs r4, #4\n\
_0809B7B6:\n\
bl sub_80D11E4\n\
movs r1, #0x64\n\
bl sub_80D0ED0\n\
adds r1, r7, #0\n\
adds r1, #9\n\
adds r1, r1, r4\n\
ldrb r1, [r1]\n\
cmp r0, r1\n\
bge _0809B7D0\n\
movs r1, #2\n\
mov r8, r1\n\
_0809B7D0:\n\
mov r0, r8\n\
cmp r0, #0\n\
bne _0809B80E\n\
adds r4, r7, #0\n\
adds r4, #0x10\n\
adds r6, r7, #0\n\
adds r6, #0x20\n\
adds r0, r5, #0\n\
bl sub_809B220\n\
adds r1, r0, #0\n\
adds r0, r7, #0\n\
adds r0, #0x14\n\
b _0809B7F0\n\
_0809B7EC:\n\
adds r4, #4\n\
adds r0, r4, #4\n\
_0809B7F0:\n\
cmp r0, r6\n\
beq _0809B7FA\n\
ldrh r0, [r4, #4]\n\
cmp r0, r1\n\
bls _0809B7EC\n\
_0809B7FA:\n\
bl sub_80D11E4\n\
movs r1, #0x64\n\
bl sub_80D0ED0\n\
ldrb r4, [r4, #2]\n\
cmp r0, r4\n\
bge _0809B80E\n\
movs r1, #1\n\
mov r8, r1\n\
_0809B80E:\n\
ldrb r1, [r5, #0x1d]\n\
movs r0, #4\n\
rsbs r0, r0, #0\n\
ands r0, r1\n\
mov r1, r8\n\
orrs r0, r1\n\
strb r0, [r5, #0x1d]\n\
pop {r3}\n\
mov r8, r3\n\
pop {r4, r5, r6, r7}\n\
pop {r0}\n\
bx r0\n\
.align 2, 0\n\
");
}
/*
void sub_809B674(struct Livestock *lstock, u8 *param){
u8 fed, unhappy, sick;
u32 temp, index, val;
u8 *p1, *p2, *p3;
sub_809B2E8(&lstock->animal);
fed = lstock->fed;
if(fed){
if(lstock->daysFed < 31)
lstock->daysFed++;
lstock->fed = 0;
}
lstock->currentOutdoorMinutes = 0;
unhappy = lstock->unhappy;
if(unhappy){
if(fed){
if((s32)sub_80D0ED0(sub_80D11E4(), 100) < param[0]){
lstock->unhappy = 0;
}
}
}else{
if(!fed){
if((s32)sub_80D0ED0(sub_80D11E4(), 100) < param[1]){
lstock->unhappy = 1;
}
}
}
unhappy = lstock->unhappy;
if(unhappy){
temp = lstock->daysUnhappy;
if(temp < 7){
temp++;
lstock->daysUnhappy = temp;
}
}else{
lstock->daysUnhappy = 0;
}
sick = lstock->sick;
if(!sick){
unhappy = lstock->unhappy;
if(unhappy){
if(lstock->daysUnhappy > 0){
index = lstock->daysUnhappy - 1;
}else{
index = 0;
}
if(6 < index)
index = 6;
if((s32)sub_80D0ED0(sub_80D11E4(), 100) < param[2 + index]){
lstock->sick = 1;
}
}
}
sick = lstock->sick; //158
if(sick){
temp = lstock->daysSick;
if(temp < 7){
lstock->daysSick = temp + 1;
}
}else{
lstock->daysSick = 0;
}
val = 0;
sick = lstock->sick;
if(sick){
if(lstock->daysSick){
index = lstock->daysSick - 1;
}else{
index = 0;
}
if(4 < index){
index = 4;
}
if((s32)sub_80D0ED0(sub_80D11E4(), 100) < *(param + 9 + index)){
val = 2;
}
}
if(val == 0){
p1 = param + 16;
p2 = param + 32;
temp = sub_809B220(&lstock->animal);
p3 = param + 20;
while(p3 != p2 && (*(u16 *)(p1 + 4) <= temp)){
p1 = p1 + 4;
p3 = p1 + 4;
}
if ((s32)sub_80D0ED0(sub_80D11E4(), 100) < p1[2])
val = 1;
}
lstock->unk_0x1D_0 = val;
}
*/
|
C
|
#include <stdio.h>
struct
{
int a;
int b;
}paper,image;
void main(){
int t,p1,p2;
//printf("%c",'%');
scanf("%d %d %d %d",&image.a,&image.b,&paper.a,&paper.b);
while(image.a||image.b||paper.a||paper.b){
if(image.a<image.b&&paper.a>paper.b||(image.a>image.b&&paper.a<paper.b))
{
t=paper.a;paper.a=paper.b;paper.b=t;
}
//printf("%d %d %d %d",image.a,image.b,paper.a,paper.b);
p1=100*paper.a/image.a;//printf("%d",p1);
p2=100*paper.b/image.b;//printf("%d",p2);
if(p1>=100&&p2>=100) printf("100%%\n");
else {printf("%d",(p1<p2?p1:p2));printf("%c\n",'%'); }
scanf("%d %d %d %d",&image.a,&image.b,&paper.a,&paper.b);}
}
|
C
|
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
int main(int argc, char **argv) {
char buf[256], alpha[34], beta[34];
int j, plen, fd;
if (argc < 2) {
printf("usage: %s <keyfile>\n", argv[0]);
return 1;
}
if (strlen(argv[1]) > 256) {
fprintf(stderr, "keyfile length is > 256, go fish!\n");
return 0;
}
fd = open(argv[1], O_RDONLY);
if (fd < 0) {
perror(argv[1]);
return 0;
}
memset(buf, 0x0, sizeof(buf));
plen = read(fd, buf, strlen(argv[1]));
if (plen != strlen(argv[1])) {
if (plen < 0) {
perror(argv[1]);
}
printf("Sorry!\n");
return 0;
}
strncpy(alpha, (char *)crypt(argv[1], "$1$"), sizeof(alpha));
strncpy(beta, (char *)crypt(buf, "$1$"), sizeof(beta));
for(j = 0; j < strlen(alpha); j++) {
if (alpha[j] != beta[j]) {
printf("Sorry!\n");
return 0;
}
}
printf("All your base are belong to us!\n");
return 1;
}
|
C
|
#include "utils.h"
#define MAX 50
size_t strindex(char *s, char *t)
{
char *i, *j, *k;
for (i = s; *i != '\0'; i++)
{
for (j = i, k = t; *k != '\0' && *j == *k; j++, k++);
if ((size_t)(k - t) > 0 && *k == '\0')
{
return (size_t)(i - s);
}
}
return -1;
}
|
C
|
#include "lcd.h"
/*
* @function:数据不经过任何处理直接写进lcd屏幕
* @params:
*/
void write_lcd( char *bmp_buffer,
struct RGB *jpg_info,
char *fb,
struct fb_var_screeninfo *vinfo)
{
bzero(fb, vinfo->xres * vinfo->yres * 4);
int x,y;
for(y=0; y<vinfo->yres && y<jpg_info->height; y++)
{
for(x=0; x<vinfo->xres && x<jpg_info->width; x++)
{
//if(x%xrd == 0 && xrd != 0)continue;
unsigned long lcd_offset = (vinfo->xres * y + x) * 4;
unsigned long bmp_offset = (jpg_info->width * y + x) * jpg_info->bpp;
memcpy(fb + lcd_offset + vinfo->red.offset/8, bmp_buffer + bmp_offset + 0 ,1);
memcpy(fb + lcd_offset + vinfo->green.offset/8, bmp_buffer + bmp_offset + 1 ,1);
memcpy(fb + lcd_offset + vinfo->blue.offset/8, bmp_buffer + bmp_offset + 2 ,1);
}
}
}
/*
* @function:图片按倍数横向或者纵向缩小
* @params:
*/
void write_lcd_reduce( char *bmp_buffer,
struct RGB *jpg_info,
char *fb,
struct fb_var_screeninfo *vinfo,
int xrd,
int yrd,
int xb,
int yb)
{
bzero(fb, vinfo->xres * vinfo->yres * 4);
int x,y;
for(y=0; y < (vinfo->yres/yrd) && y<(jpg_info->height/yrd); y++)
{
for(x=0; x < (vinfo->xres/xrd) && x<(jpg_info->width/xrd); x++)
{
unsigned long lcd_offset = (vinfo->xres * (y + yb) + (x + xb)) * 4;
unsigned long bmp_offset = (jpg_info->width * y * yrd + x * xrd) * jpg_info->bpp;
memcpy(fb + lcd_offset + vinfo->red.offset/8, bmp_buffer + bmp_offset + 0 ,1);
memcpy(fb + lcd_offset + vinfo->green.offset/8, bmp_buffer + bmp_offset + 1 ,1);
memcpy(fb + lcd_offset + vinfo->blue.offset/8, bmp_buffer + bmp_offset + 2 ,1);
}
}
}
/*
* @function:自动匹配最适合尺寸(倍数缩小)
* @params:
*/
void write_lcd_auto_match( char *bmp_buffer,
struct RGB *jpg_info,
char *fb,
struct fb_var_screeninfo *vinfo,
int xb,
int yb)
{
bzero(fb, vinfo->xres * vinfo->yres * 4);
int x,y,xrd = 1, yrd = 1;
//判断和调整图片大小
while(1)
{
if(((jpg_info->width/xrd) > vinfo->xres ) || ((jpg_info->height/yrd) > vinfo->yres))
{
xrd++;
yrd++;
}
else
break;
}
//居中对其算法
xb = vinfo->xres/2 - jpg_info->width/xrd/2;
yb = vinfo->yres/2 - jpg_info->height/yrd/2;
for(y=0; y<(jpg_info->height/yrd); y++)
{
for(x=0; x<(jpg_info->width/xrd); x++)
{
unsigned long lcd_offset = (vinfo->xres * (y + yb) + (x + xb)) * 4;
unsigned long bmp_offset = (jpg_info->width * y * yrd + x * xrd) * jpg_info->bpp;
memcpy(fb + lcd_offset + vinfo->red.offset/8, bmp_buffer + bmp_offset + 0 ,1);
memcpy(fb + lcd_offset + vinfo->green.offset/8, bmp_buffer + bmp_offset + 1 ,1);
memcpy(fb + lcd_offset + vinfo->blue.offset/8, bmp_buffer + bmp_offset + 2 ,1);
}
}
}
|
C
|
// This program gives the output without declaring function prototype before main(),
// its possible only in case of int return type function.
#include<stdio.h>
char fun();
void main(){
int a = fun();
printf("a = %d", a); // o/p => 10 if int fun() was there, and gives error
// when other then int return type was there.
}
char fun()
{
return 'A';
}
// if we place char return type in place of int then we got an error, if
// you want to check that error then uncomment the below code and comment
// out the above fun() function.
// char fun()
// {
// return 10;
// }
// The reason of error with char return type below the main() without declaring
// the function prototype is the compiler assumes fuction at the time of calling
// as int return type and when called and if finds other return type then it gives
// an error
|
C
|
#include<stdio.h>
void main()
{
int gender,age,m,f;
printf("enter the age& gender of the person\n");
scanf("%d\n",&age);
if (gender==m,age>21)
{
printf("eligible to the marriage\n");
}
else
{
printf("not eligible to the marriage\n");
}
printf(t)
}
]
|
C
|
#include <stdio.h>
#define ElementType int
void swap(ElementType *x, ElementType *y)
{
ElementType temp;
temp = *x;
*x = *y;
*y = temp;
}
// get the left child of node under index with startup zero
int leftChildFromZero(int index)
{
return index * 2 + 1;
}
// percolating down the element when its value is greater than children (minimal heap)
//Attention: all of bh->elements starts from index 0
void percolateDownFromZero(int index, ElementType data[], int size)
{
ElementType temp;
int child;
for(temp = data[index]; leftChildFromZero(index) < size; index = child)
{
child = leftChildFromZero(index);
if(child < size - 1 && data[child] > data[child+1])
child++;
if(temp > data[child])
data[index] = data[child];
else
break;
}
data[index] = temp;
}
// we adopt ascending order to execute shellSorting operation
void heapSort(ElementType data[], int size)
{
int i;
for(i = size / 2; i >= 0; i--) // building the heap by percolating down
percolateDownFromZero(i, data, size);
for(i = size - 1; i > 0; i--) // delete the minimum element
{
swap(&data[0], &data[i]); // switch the minimal also the element with index 0 with the final element in the minimum heap
percolateDownFromZero(0, data, i);
}
}
void printBinaryHeapFromZero(ElementType data[], int size)
{
int i;
for(i = 0; i < size; i++)
{
printf("\n\t index[%d] = ", i);
if(i < size)
printf("%d", data[i]);
else
printf("NULL");
}
printf("\n");
}
int main()
{
int size;
int data[] = {150, 80, 40, 30, 10, 70, 110, 100, 20, 90, 60, 50, 120, 140, 130};
printf("\n\t=== test for building heap with {150, 80, 40, 30, 10, 70, 110, 100, 20, 90, 60, 50, 120, 140, 130} ===\n");
size = 15;
printf("\n\t=== before executing heap sorting ===\n");
printBinaryHeapFromZero(data, size);
heapSort(data, size);
printf("\n\t=== after executing heap sorting ===\n");
printBinaryHeapFromZero(data, size);
return 0;
}
|
C
|
#include <stdio.h>
#include <unistd.h>
#define PI 3.14
void foo(void)
{
printf("%s\n", __func__);
}
int bar(void)
{
return 100;
}
int main(void)
{
printf("Hello, world!\n");
printf("%f\n", PI);
foo();
printf("bar:%d\n", bar());
sleep(30);
return 0;
}
|
C
|
#include <stdio.h>
typedef struct rashika
{
int a;
} as;
int main(){
as a1;
struct rashika as;
as.a = 5;
as.a = 10;
a1.a = 5;
printf("%d\t%d ",a1.a,as.a);
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int max(int,int);
int *multiplicamatriz(int *,int **,int); // Funcin recursiva que multiplica matrices
int *suma(int *,int **,int); // suma de matrices
int *resta(int *,int **,int);// Resta de matrices
void libera(int **,int); // Libera memoria
int main()
{
int *mapa1,mapa2,*sol;
int f1,c1,f2,c2,a,b,m,m1;
scanf(" %d %d",&f1,&c1); // Tamao de la primera matriz
scanf(" %d %d",&f2,&c2); // Tamao de la segunda matriz
m1=max(f1,max(c1,max(f2,c2)));
for(m=1;m<m1;m*=2); // El tamao de las matrices cuadradas a multiplicar
//debe ser de la forma 2k, si no se completan con ceros.
mapa1=(int **)malloc(sizeof(int *)*m); // Se crea la primera matriz
for(a=0;a<m;a++)
{
mapa1[a]=(int *)malloc(sizeof(int)*m);
memset(mapa1[a],0,sizeof(int)*m);
}
for(a=0;a<f1;a++) // Se cogen los datos de la primera matriz.
for(b=0;b<c1;b++)
scanf(" %d",&mapa1[a][b]);
mapa2=(int **)malloc(sizeof(int *)*m); // Se crea la sedunda matriz.
for(a=0;a<m;a++)
{
mapa2[a]=(int *)malloc(sizeof(int)*m);
memset(mapa2[a],0,sizeof(int)*m);
}
for(a=0;a<f2;a++) // Se cogen los datos de la segunda matriz.
for(b=0;b<c2;b++)
scanf(" %d",&mapa2[a][b]);
sol=multiplicamatriz(mapa1,mapa2,m); // Se multiplican.
for(a=0;a<f1;a++) // Se imprime el resultado.
{
for(b=0;b<c2;b++)
printf("%d ",sol[a][b]);
printf("\n");
}
return(0);
}
int max(int a,int b)
{
return((a>b)?a:b);
}
int **multiplicamatriz(int **mapa1,int **mapa2,int num)
{
int *sol,M[8],f1,f2,aux,*aux2;
int *A[2][2],B[2][2],*C[2][2];
int a,q,w,r;
sol=(int **)malloc(sizeof(int *)*num);
for(a=0;a<num;a++)
sol[a]=(int *)malloc(sizeof(int)*num);
if(num==1)
{
sol[0][0]=mapa1[0][0]*mapa2[0][0];
return(sol);
}
// Crear las submatrices de A y B.
for(q=0;q<2;q++)
{
for(w=0;w<2;w++)
{
A[q][w]=(int *)malloc(sizeof(int *)(num/2));
for(a=0;a<num/2;a++)
{
A[q][w][a]=(int )malloc(sizeof(int)(num/2));
for(r=0;r<num/2;r++)
A[q][w][a][r]=mapa1[a+(num/2)*q][r+(num/2)*w];
}
B[q][w]=(int *)malloc(sizeof(int *)(num/2));
for(a=0;a<num/2;a++)
{
B[q][w][a]=(int )malloc(sizeof(int)(num/2));
for(r=0;r<num/2;r++)
B[q][w][a][r]=mapa2[a+(num/2)*q][r+(num/2)*w];
}
}
}
// Hallar las matrices M.
f1=resta(A[0][1],A[1][1],num/2);
f2=suma(B[1][0],B[1][1],num/2);
M[1]=multiplicamatriz(f1,f2,num/2);
libera(f1,num/2);
libera(f2,num/2);
f1=suma(A[0][0],A[1][1],num/2);
f2=suma(B[0][0],B[1][1],num/2);
M[2]=multiplicamatriz(f1,f2,num/2);
libera(f1,num/2);
libera(f2,num/2);
f1=resta(A[0][0],A[1][0],num/2);
f2=suma(B[0][0],B[0][1],num/2);
M[3]=multiplicamatriz(f1,f2,num/2);
libera(f1,num/2);
libera(f2,num/2);
f1=suma(A[0][0],A[0][1],num/2);
f2=B[1][1];
M[4]=multiplicamatriz(f1,f2,num/2);
libera(f1,num/2);
f1=A[1][1];
f2=resta(B[0][1],B[1][1],num/2);
M[5]=multiplicamatriz(f1,f2,num/2);
libera(f2,num/2);
f1=A[1][1];
f2=resta(B[1][0],B[0][0],num/2);
M[6]=multiplicamatriz(f1,f2,num/2);
libera(f2,num/2);
f1=suma(A[1][0],A[1][1],num/2);
f2=B[0][0];
M[7]=multiplicamatriz(f1,f2,num/2);
libera(f1,num/2);
// Hallar las submatrices de C.
C[0][0]=suma(M[1],M[2],num/2);
aux=C[0][0];
C[0][0]=resta(C[0][0],M[4],num/2);
aux2=C[0][0];
C[0][0]=suma(C[0][0],M[6],num/2);
libera(aux,num/2);
libera(aux2,num/2);
C[0][1]=suma(M[4],M[5],num/2);
C[1][0]=suma(M[6],M[7],num/2);
C[1][1]=resta(M[2],M[3],num/2);
aux=C[1][1];
C[1][1]=suma(C[1][1],M[5],num/2);
aux2=C[1][1];
C[1][1]=resta(C[1][1],M[7],num/2);
libera(aux,num/2);
libera(aux2,num/2);
for(a=1;a<=7;a++)
libera(M[a],num/2);
// Unir las submatrices de matrices C en sol.
for(q=0;q<num;q++)
for(w=0;w<num;w++)
sol[q][w]=C[q/(num/2)][w/(num/2)][q%(num/2)][w%(num/2)];
// Liberar las submatrices de A, B y C.
for(q=0;q<2;q++)
for(w=0;w<2;w++)
{
libera(A[q][w],num/2);
libera(B[q][w],num/2);
libera(C[q][w],num/2);
}
return(sol);
}
int **suma(int **mapa1,int **mapa2,int num)
{ // sumar mapa1 y mapa2.
int a,b;
int **sol;
sol=(int **)malloc(sizeof(int *)*num);
for(a=0;a<num;a++)
{
sol[a]=(int *)malloc(sizeof(int)*num);
for(b=0;b<num;b++)
sol[a][b]=mapa1[a][b]+mapa2[a][b];
}
return(sol);
}
int **resta(int **mapa1,int **mapa2,int num)
{ // Restar mapa2 de mapa1.
int **sol;
int a,b;
sol=(int **)malloc(sizeof(int *)*num);
for(a=0;a<num;a++)
{
sol[a]=(int *)malloc(sizeof(int)*num);
for(b=0;b<num;b++)
sol[a][b]=mapa1[a][b]-mapa2[a][b];
}
return(sol);
}
void libera(int **mapa,int num)
{
int a;
for(a=0;a<num;a++) // Liberar la tabla dinmica de 2D.
free(mapa[a]);
free(mapa);
}
|
C
|
#include <stdio.h>
// #include <stdlib.h>
void towers(int num, char frompeg, char topeg, char auxpeg)
{
if (num == 0)
return;
if (num == 1)
{
printf("Move disk 1 from %c peg to %c peg \n", frompeg, topeg);
return;
}
else
{
towers(num - 1, frompeg, auxpeg, topeg);
printf("Move disk %d from %c peg to %c peg \n", num, frompeg, topeg);
towers(num - 1, auxpeg, topeg, frompeg);
}
// printf(" %c %c %c ", frompeg, topeg, auxpeg);
}
void main()
{
int num;
printf("Enter no of Disks for Tower of Hanoi \n");
scanf("%d", &num);
printf("Sequence of moves for Tower of Hanoi \n");
towers(num, 'S', 'D', 'A');
}
|
C
|
// Use a switch case to convert newline and tab characters to visible chars
#include<stdio.h>
#include<stdlib.h>
#define MAX 100
void expand(char* s, char* t);
int main(void)
{
char s[MAX];
char t[MAX];
//Get input string from stdin
fgets(s, MAX, stdin);
expand(s, t);
puts(t);
}
void expand(char* s, char* t)
{
int j = 0;
char c;
for(int i = 0; s[i]!='\0'; i++)
{
switch (c = s[i]) {
case '\n':
t[i+j]='\\';
j++;
t[i+j]='n';
break;
case '\t':
t[i+j]='\\';
j++;
t[i+j]='t';
break;
default:
t[i+j]= c;
break;
}
}
}
|
C
|
#ifndef __LSTACK1_H
#define __LSTACK1_H
typedef struct lstack_st
{
void *bottom;
void *top;
int size;
int capacity;
}lstack_t;
// 初始化栈
int lstackInit(int size,int capacity, lstack_t **ls);
// 入栈
int lstackPush(lstack_t *ls, void *data);
// 出栈
int lstackPop(lstack_t *ls, void *data);
// 判断栈是否为空
int lstackEmpty(lstack_t *ls);
// 判断栈是否为满
int lstackFull(lstack_t *ls);
// 销毁
int lstackDestory(lstack_t *ls);
#endif
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <time.h>
#include "SDL.h"
#include "SDL_ttf.h"
#include "utilities.h"
#if (defined _WIN32) || (defined _WIN64)
#pragma warning(disable:4996)
#endif
int gGameover = 0;
char gMediaPath[256] = "";
SDL_Rect gMainWinRect = { 100, 100, 640, 480 };
SDL_Window * gMainWindow = NULL;
SDL_Renderer * gMainRenderer = NULL;
SDL_Color gBackgroundColor = { 0, 0, 0, 255 };
Uint32 gMyTimerEvent = (Uint32)-1;
static void cleanAll()
{
if( gMainRenderer )
SDL_DestroyRenderer(gMainRenderer), gMainRenderer = NULL;
if( gMainWindow )
SDL_DestroyWindow(gMainWindow), gMainWindow = NULL;
}
void initApp(int argc, char *argv[])
{
SDL_SetHint(SDL_HINT_IME_INTERNAL_EDITING, "1" );
SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS | SDL_INIT_TIMER );
//
if( ! (gMainWindow = SDL_CreateWindow(argv[0], gMainWinRect.x, gMainWinRect.y,
gMainWinRect.w, gMainWinRect.h, 0) ) ) {
printf("Error create SDL window\n");
cleanAll(); exit(-1);
}
// ƻ
if( ! (gMainRenderer = SDL_CreateRenderer(gMainWindow, -1,
SDL_RENDERER_ACCELERATED)) ) {
printf("Error create SDL Renderer\n");
cleanAll(); exit(-1);
}
// ʼ true type fontʹ
if ( TTF_Init() < 0 ) {
printf("Couldn't initialize TTF: %s\n",SDL_GetError());
cleanAll(); exit(-1);
}
}
void endApp()
{
TTF_Quit();
SDL_DestroyRenderer(gMainRenderer);
SDL_DestroyWindow(gMainWindow);
SDL_Quit();
}
typedef struct {
float x,y;
} Vec2f;
typedef struct {
Vec2f p[4];
} ClockPointer;
void drawline(Vec2f a, Vec2f b)
{
SDL_RenderDrawLine(gMainRenderer,
(int)a.x, (int)a.y, (int)b.x, (int)b.y);
}
void drawPointer(Vec2f p[])
{
int N = 30, k;
for( k = 0; k<=N; k++ )
{
float t = k/(float)N;
Vec2f v = {
t * p[1].x + (1-t) * p[3].x,
t * p[1].y + (1-t) * p[3].y};
drawline(p[0], v );
drawline(v , p[2]);
}
}
Vec2f rotate00(float angle, Vec2f p)
{
float cosa = (float)cos(angle);
float sina = (float)sin(angle);
Vec2f r = {
cosa * p.x - sina * p.y,
sina * p.x + cosa * p.y};
return r;
}
Vec2f rotate(Vec2f center, float angle, Vec2f p)
{
p.x -= center.x;
p.y -= center.y;
p = rotate00(angle,p);
p.x += center.x;
p.y += center.y;
return p;
}
void drawCircle(int cenx, int ceny, int radius)
{
int x0 = cenx+radius, y0 = ceny, N=100, k;
SDL_SetRenderDrawColor(gMainRenderer, 128, 128, 0, 255);
for( k=1; k<=N; k++ )
{
double angle = 2*M_PI / N * k;
int x = (int)(cenx + radius*cos(angle));
int y = (int)(ceny + radius*sin(angle));
SDL_RenderDrawLine(gMainRenderer, x0,y0,x,y);
x0 = x;
y0 = y;
}
}
void drawSolidCircle(int cenx, int ceny, int radius)
{
int k;
for( k=0; k<=radius; k++ )
{
int x = (int)sqrt((double)radius*radius-k*k);
SDL_RenderDrawLine(gMainRenderer, cenx-x, ceny+k, cenx+x, ceny+k);
SDL_RenderDrawLine(gMainRenderer, cenx-x, ceny-k, cenx+x, ceny-k);
}
}
void drawClock()
{
time_t rawtime = time(NULL);
struct tm tinfo = *localtime(&rawtime);
char tstr[64];
int clocksize = 160;
float cx = gMainWinRect.w/2.f;
float cy = gMainWinRect.h/2.f;
float y1 = 18, dx = 12, y2 = -130;
Vec2f p[4], pointer[3][4] = {
{{0, y1},{dx-6, 0},{0, y2 },{-dx+6, 0}},
{{0, y1},{dx-3, 0},{0, y2+15},{-dx+3, 0}},
{{0, y1},{dx, 0},{0, y2+30},{-dx, 0}}};
// draw clock
SDL_SetRenderDrawColor(gMainRenderer, 255, 255, 255, 255);
drawSolidCircle((int)cx, (int)cy, clocksize);
SDL_SetRenderDrawColor(gMainRenderer, 128, 128, 128, 255);
drawSolidCircle((int)cx, (int)cy, clocksize-5);
SDL_SetRenderDrawColor(gMainRenderer, 255, 255, 255, 255);
drawSolidCircle((int)cx, (int)cy, 8);
// rotate the pointer of second
// tinfo.tm_sec;
{
int k, j; double rotAngle[3] = {
tinfo.tm_sec/60.0*M_PI*2,
tinfo.tm_min/60.0*M_PI*2,
tinfo.tm_hour%12/12.f*M_PI*2};
for( j = 2; j>=0; j-- )
{
SDL_SetRenderDrawColor(gMainRenderer, 255*(j==0), 255*(j==1), 255*(j==2), 255);
for( k = 0; k<4; k++ ) {
p[k] = rotate00((float)rotAngle[j], pointer[j][k]);
p[k].x += cx;
p[k].y += cy;
}
drawPointer(p);
}
};
strftime(tstr, sizeof(tstr), "%c",&tinfo);
drawstring(tstr, gMainWinRect.w/5, gMainWinRect.h-50,
FullPath("/default/FreeSerif.ttf"), 32, Int2Color(0xFFFFFFFF) );
}
void display()
{
SDL_SetRenderDrawColor(gMainRenderer, gBackgroundColor.r,
gBackgroundColor.g, gBackgroundColor.b, gBackgroundColor.a);
SDL_RenderClear(gMainRenderer);
// draw some geometry shapes
drawClock();
// present the result
SDL_RenderPresent(gMainRenderer);
}
Uint32 timerCallback(Uint32 interval, void* param)
{
//display();
//printf("timer\n");
SDL_Event e;
e.type = gMyTimerEvent;
SDL_PushEvent(&e);
return interval;
}
void runMainLoop()
{
SDL_Event e; // ¼
SDL_TimerID timerID;
// עһʱ, һʱ
gMyTimerEvent = SDL_RegisterEvents(1);
timerID = SDL_AddTimer(1000, timerCallback, "this is my timer");
display();
while ( !gGameover )
{
while ( !gGameover && SDL_PollEvent(&e))
{
if((e.type == SDL_KEYUP && e.key.keysym.sym==SDLK_ESCAPE) ||
e.type == SDL_QUIT) //user close window or press ESC key
{
gGameover = 1; // ֹӦó
}
// other events ...
if ( e.type == gMyTimerEvent )
display();
}
// һЩ顣
SDL_Delay(10); // ʱ10msCPU
}
SDL_RemoveTimer( timerID );
}
int main(int argc, char *argv[])
{
if( argc>1 )
strcpy(gMediaPath, argv[1]);
else {
strcpy(gMediaPath, SDL_GetBasePath());
strcat(gMediaPath, "../../../Media");
}
printf("base path = %s\n", SDL_GetBasePath());
printf("media path = %s\n", gMediaPath);
initApp(argc,argv);
runMainLoop(); // Enter main loop
endApp();
return 0;
}
|
C
|
#include"method.h"
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
// .
#define MAX_BUF 512
typedef enum Player {
PLAYER_1,
PLAYER_2
};
char TTT_BOARD[3][3] = { { ' ',' ',' ' },{ ' ',' ',' ' },{ ' ',' ', ' ' } };
void show_board() {
printf(" 1 2 3\n");
printf(" +---+---+---+\n");
printf(" A l %c l %c l %c l\n", TTT_BOARD[0][0], TTT_BOARD[0][1], TTT_BOARD[0][2]);
printf(" +---+---+---+\n");
printf(" B l %c l %c l %c l\n", TTT_BOARD[1][0], TTT_BOARD[1][1], TTT_BOARD[1][2]);
printf(" +---+---+---+\n");
printf(" C l %c l %c l %c l\n", TTT_BOARD[2][0], TTT_BOARD[2][1], TTT_BOARD[2][2]);
printf(" +---+---+---+\n");
}
int set_play_order() {
int order;
srand(time(NULL));
order = rand() % 2;
return order;
}
void input_locate(int* play_order, char* player_name) {
int row, col;
printf("÷̾ %d - %s\n", *play_order + 1, player_name);
printf(" >> ");
scanf("%d", &row);
printf(" >> ");
scanf("%d", &col);
if (*play_order == PLAYER_1) {
TTT_BOARD[row - 1][col - 1] = 'O';
*play_order = PLAYER_2;
}
else {
TTT_BOARD[row - 1][col - 1] = 'X';
*play_order = PLAYER_1;
}
}
int is_finished() {
int i, winner = -1;
if (TTT_BOARD[0][0] == TTT_BOARD[1][1] && TTT_BOARD[0][0] == TTT_BOARD[2][2] && (TTT_BOARD[0][0] == 'O' || TTT_BOARD[0][0] == 'X')) {
winner = TTT_BOARD[1][1] == 'O' ? PLAYER_1 : PLAYER_2;
}
else if (TTT_BOARD[2][0] == TTT_BOARD[1][1] && TTT_BOARD[2][0] == TTT_BOARD[0][2] && (TTT_BOARD[2][0] == 'O' || TTT_BOARD[2][0] == 'X')) {
winner = TTT_BOARD[1][1] == 'O' ? PLAYER_1 : PLAYER_2;
}
else {
for (i = 0; i < 3; i++) {
if (TTT_BOARD[0][i] == TTT_BOARD[1][i] && TTT_BOARD[0][i] == TTT_BOARD[2][i] && (TTT_BOARD[0][i] == 'O' || TTT_BOARD[0][i] == 'X')) {
winner = TTT_BOARD[1][i] == 'O' ? PLAYER_1 : PLAYER_2;
break;
}
else if (TTT_BOARD[i][0] == TTT_BOARD[i][1] && TTT_BOARD[i][0] == TTT_BOARD[i][2] && (TTT_BOARD[i][0] == 'O' || TTT_BOARD[i][0] == 'X')) {
winner = TTT_BOARD[i][1] == 'O' ? PLAYER_1 : PLAYER_2;
break;
}
}
}
return winner;
}
int available_game() {
int i, j;
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
if (TTT_BOARD[i][j] == ' ') {
return 1;
}
}
}
return 0;
}
int problem_41() {
int play_order;
char player_name[2][MAX_BUF];
int winner;
srand(time(NULL));
printf("<< ƽ >> \n");
printf("÷̾ 1 ̸ Է >> ");
scanf("%s", player_name[PLAYER_1]);
printf("÷̾ 2 ̸ Է >> ");
scanf("%s", player_name[PLAYER_2]);
if (set_play_order() == 0) {
printf("÷̾ 1 - %s մϴ.\n", player_name[PLAYER_1]);
play_order = PLAYER_1;
}
else {
printf("÷̾ 2 - %s մϴ.\n", player_name[PLAYER_2]);
play_order = PLAYER_2;
}
do {
if (available_game() == 0) {
printf(" º\n");
return;
}
input_locate(&play_order, player_name[play_order]);
show_board();
} while ((winner = is_finished()) == -1);
printf("÷̾ %d - %s ¸\n", winner + 1, player_name[winner]);
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <assert.h>
#include "readData.h"
#include "invertedIndex.h"
#include "searchPagerank.h"
//Get Word List Graph
void invertedIndex(){
int numberURL = 0, wordCount = 0, NEWWORD;
char str[100];
WordList wordCountList = newWordList();
//Word List
char **wordList = (char **)malloc(sizeof(char *) * MAXIMUM);
for(int a = 0; a < MAXIMUM; a++){
wordList[a] = (char *)malloc(MAXIMUM * sizeof(char));
}
//Get URL
FILE *collection;
collection = fopen("collection.txt", "r");
while(fscanf(collection, "%s", str) != EOF) numberURL++;
fclose(collection);
//Create list of URL
char **URL = malloc(sizeof(char) * 100 * numberURL);
char **URLLink = malloc(sizeof(char) * 100 * numberURL);
getURLCollection(URL, URLLink, numberURL);
//Scan each file
for(int i = 0; i < numberURL; i++){
FILE *url;
char *currentURL = URLLink[i];
url = fopen(currentURL, "r");
//Skip Section 1
fscanf(url, "%s", &str);
while(strcmp(str, "Section-2") != 0) fscanf(url, "%s", &str);
//Scan text in each text
while(fscanf(url, "%s", &str) != EOF && (strcmp("#end",str) != 0)){
for(int a = 0; str[a]; a++){
str[a] = tolower(str[a]);
if((str[a] == ',')||(str[a] == '?')||(str[a] == '.')||(str[a] == ';')){
str[a] = '\0';
}
}
//Find if it's a duplicated word
NEWWORD = 1;
for(int m = 0; m < wordCount && NEWWORD == 1; m++){
if(strcmp(wordList[m],str) == 0){
if (inVList(wordCountList, m, URL[i]) == 0){
addLink(wordCountList, m, URL[i]);
}
NEWWORD = 0;
}
}
//New Word
if (NEWWORD == 1){
addLink(wordCountList, wordCount, URL[i]);
wordList[wordCount] = strdup(str);
wordCount++;
}
}
}
//Finalise wordCount
sortList(wordCountList, wordList, wordCount);
//Print Result
FILE *textFile;
textFile = fopen("invertedIndex.txt", "w");
for(int a = 0; a < wordCount; a++){
fprintf(textFile, "%s ", wordList[a]);
vLink current = wordCountList->connections[a];
while(current != NULL){
fprintf(textFile, "%s ", current->word);
current = current->next;
}
fprintf(textFile, "\n");
}
fclose(textFile);
free(wordList);
free(URL);
free(URLLink);
}
|
C
|
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
int main(){
printf("execl() function execution\n"); //print message
execl("/bin/ls", "ls", "-l", NULL); //do execl ls -l
printf("Error"); //print error if execl not working correctly
return 0;
}
|
C
|
/**************************************************************************//**
* \file infoflash.c
* \author Ben Boudaoud ([email protected])
* \date Dec 20, 2013
*
* \brief This file contains the TEMPO 4000 info flash management code
*
* This library provides a simple interface for reading and writing the MSP430
* info flash on 5xxx series devices. The A and B segments are used for storage
* of critical non-volatile data including system state and critical flags.
*****************************************************************************/
#include <msp430.h>
#include <string.h>
#include "infoflash.h"
#include "hal.h"
#include "util.h"
unsigned char infoRO = 0; ///< Info flash read only flag
/**************************************************************************//**
* \brief Initialize RAM copies of Info flash values
*
* Copy values from info flash into RAM-cached copies and run a validity
* check on the protected information (CID, calib, serials, ...)
*
* \retval 0 success
* \retval -1 validity check failure
*
* \sideeffect Sets #infoRO if validity check fails
*****************************************************************************/
int infoInit(void)
{
unsigned int checksum;
memcpy((void *)&_tempoInfoA, (void *)INFO_A_ADDR, sizeof(_tempoInfoA));
memcpy(&_tempoInfoB, (void *)INFO_B_ADDR, sizeof(_tempoInfoB));
if(_tempoInfoA.validityCode != INFO_VALID_CODE){
infoRO = 1;
return INFO_A_INVALID;
}
// Test validity of the stored info
checksum = fletcherChecksum((unsigned char *)&_tempoInfoB,
sizeof(_tempoInfoB) - sizeof(_tempoInfoB.checksum), 0);
if(_tempoInfoB.validityCode != INFO_VALID_CODE || checksum != _tempoInfoB.checksum) {
infoRO = 1;
return INFO_B_INVALID;
}
return INFO_VALID;
}
/**************************************************************************//**
* \brief Write RAM copy of critical flags back to info flash
*****************************************************************************/
static void _writeTempoInfoA()
{
unsigned int status;
_tempoInfoA.validityCode = INFO_VALID_CODE;
/// \todo decide whether to put a watchdog reset here
// MSP430 User guide stipulates that this entire process be protected
enter_critical(status);
if(FCTL3 | LOCKA) FCTL3 = (FWKEY + LOCKA);
else FCTL3 = FWKEY; // Clear Lock bit
FCTL1 = (FWKEY + ERASE); // Set Erase bit
*(unsigned char *)INFO_A_ADDR = 0; // Dummy write to erase flash segment
FCTL1 = (FWKEY + WRT); // Set WRT bit for write operation
memcpy((void *)INFO_A_ADDR, (const void *)&_tempoInfoA, sizeof(_tempoInfoA));
FCTL1 = FWKEY; // Clear WRT bit
FCTL3 = FWKEY + LOCK; // Set LOCK bit
exit_critical(status);
}
/**************************************************************************//**
* \brief Write RAM copy of info B structure back to info flash
*****************************************************************************/
static int _writeTempoInfoB()
{
unsigned int status;
_tempoInfoB.validityCode = INFO_VALID_CODE;
_tempoInfoB.checksum = fletcherChecksum((unsigned char *)&_tempoInfoB,(sizeof(_tempoInfoB) - sizeof(_tempoInfoB.checksum)), 0);
// MSP430 User guide stipulates that this entire process be protected
enter_critical(status);
FCTL3 = FWKEY; // Clear Lock bit
FCTL1 = FWKEY + ERASE; // Set Erase bit
*(unsigned char *)INFO_B_ADDR = 0; // Dummy write to erase flash segment
FCTL1 = (FWKEY + WRT); // Set WRT bit for write operation
memcpy((void *)INFO_B_ADDR, &_tempoInfoB, sizeof(_tempoInfoB));
FCTL1 = FWKEY; // Clear WRT bit
FCTL3 = FWKEY + LOCK; // Set LOCK bit
exit_critical(status);
if(memcmp(&_tempoInfoB, (void *)INFO_B_ADDR, sizeof(_tempoInfoB)) != 0) {
infoRO = 1;
infoSetInfoBFail();
return -1;
}
return 0;
}
/**************************************************************************//**
* \brief Check whether any critical condition flags are set in info flash
*
* \retval 0 Info valid
* \retval -1 Info A fails validity check (see #INFO_A_INVALID)
* \retval -3 Info A contians critical flags (see #INFO_CRITICAL)
*****************************************************************************/
int infoCheckCritical(void)
{
// Check info flash for critical previous system error flags
if(_tempoInfoA.validityCode == INFO_VALID_CODE) {
if(_tempoInfoA.evtQueueOvf == 1 || _tempoInfoA.highTemp == 1
|| _tempoInfoA.infoBFail == 1) {
return INFO_CRITICAL;
}
}
else return INFO_A_INVALID;
return INFO_VALID;
}
/**************************************************************************//**
* \brief Write the low voltage critical flag to info flash
*****************************************************************************/
void infoSetLowVoltage(void)
{
_tempoInfoA.lowVoltage = 1;
_writeTempoInfoA();
}
/**************************************************************************//**
* \brief Write the high temperature critical flag to info flash
*****************************************************************************/
void infoSetHighTemp(void)
{
_tempoInfoA.highTemp = 1;
_writeTempoInfoA();
}
/**************************************************************************//**
* \brief Write the event queue overflow critical flag to info flash
*****************************************************************************/
void infoSetEvtQueueOvf(void)
{
_tempoInfoA.evtQueueOvf = 1;
_writeTempoInfoA();
}
/**************************************************************************//**
* \brief Write the info flash SegmentB failure critical flag to info flash
*****************************************************************************/
void infoSetInfoBFail(void)
{
_tempoInfoA.infoBFail = 1;
_writeTempoInfoA();
}
/**************************************************************************//**
* \brief Clear all critical flags from the info flash
*****************************************************************************/
void infoClearCriticalFlags(void)
{
_tempoInfoA.lowVoltage = 0;
_tempoInfoA.highTemp = 0;
_tempoInfoA.evtQueueOvf = 0;
_tempoInfoA.infoBFail = 0;
_writeTempoInfoA();
}
/**************************************************************************//**
* \brief Update last session serial and time epoch to info flash
*
* \retval 0 success
* \retval -1 #infoRO and/or verification check failed
*
* \sideeffect Sets #infoRO if validity check fails
*****************************************************************************/
int infoUpdateLastSector(unsigned int lastSector, unsigned int lastSessSector, unsigned int epoch)
{
_tempoInfoB.lastSector = lastSector;
_tempoInfoB.lastSessSector = lastSessSector;
_tempoInfoB.currEpoch = epoch;
return _writeTempoInfoB();
}
/**************************************************************************//**
* \brief Retrieve last sector index from infoflash
*****************************************************************************/
unsigned int infoGetLastSector(void)
{
return _tempoInfoB.lastSector;
}
/**************************************************************************//**
* \brief Retrieve last session info sector index from infoflash
*****************************************************************************/
unsigned int infoGetLastSessSector(void)
{
return _tempoInfoB.lastSessSector;
}
/**************************************************************************//**
* \brief Retrieve last session serial from infoflash
*****************************************************************************/
unsigned int infoGetLastEpoch(void)
{
return _tempoInfoB.currEpoch;
}
/**************************************************************************//**
* \brief Retrieve card ID from infoflash
*
* \param[out] cid Card ID string (of length #CARD_ID_LEN)
*****************************************************************************/
void infoGetCardID(unsigned char * cid)
{
memcpy(cid, _tempoInfoB.cid, CARD_ID_LEN);
}
/**************************************************************************//**
* \brief Retrieve node ID from infoflash
*****************************************************************************/
unsigned int infoGetNodeID(void)
{
return _tempoInfoB.nodeID;
}
/**************************************************************************//**
* \brief Set card ID and re-init serials
*
* \note Intended for use when doing a card re-init or using new card
*
* \retval 0 success
* \retval -1 Verification check failed
*
* \sideeffect The calibration values will be cleared
* \sideeffect Sets #infoRO if validity check fails
*****************************************************************************/
int infoCardInit(unsigned char* cid, unsigned int nodeID, unsigned int lastSector, unsigned int lastSessSector, unsigned int timeEpoch)
{
memcpy(_tempoInfoB.cid, cid, CARD_ID_LEN);
_tempoInfoB.nodeID = nodeID;
_tempoInfoB.lastSector = lastSector;
_tempoInfoB.lastSessSector = lastSessSector;
_tempoInfoB.currEpoch = timeEpoch;
_tempoInfoB.validityCode = INFO_VALID_CODE;
return _writeTempoInfoB();
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.