language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
|---|---|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct ident
{
char sigla[30];
char local[60];
char liga[61];
};
int main()
{
struct ident estacao[20];
struct ident comboio[30];
int opcao;
int qtdEstacao = 6, qtdComboio = 10;
while(1){
puts("MENU PRINCIPAL");
puts(" 1. Informacoes predefinidas");
puts(" 2. Adicionar informacoes");
puts(" 3. Sair ");
scanf("%i", &opcao);
switch(opcao)
{//INICIO SWITCH
case 1:
//Declaracao das nossas estacoes escolhidas (sua localizacao e sigla que a identifica)
strcpy(estacao[0].local,"Pemba");
strcpy(estacao[0].sigla,"PMB");
strcpy(estacao[1].local,"Nampula");
strcpy(estacao[1].sigla,"NPL");
strcpy(estacao[2].local,"Beira");
strcpy(estacao[2].sigla,"BR");
strcpy(estacao[3].local,"Maputo");
strcpy(estacao[3].sigla,"MPT");
strcpy(estacao[4].local,"Lichinga");
strcpy(estacao[4].sigla,"LCG");
strcpy(estacao[5].local,"Inhamabane");
strcpy(estacao[5].sigla,"IMN");
strcpy(comboio[0].sigla, "C0");
strcpy(comboio[1].sigla, "C1");
strcpy(comboio[2].sigla, "C2");
strcpy(comboio[3].sigla, "C3");
strcpy(comboio[4].sigla, "C4");
strcpy(comboio[5].sigla, "C5");
strcpy(comboio[6].sigla, "C6");
strcpy(comboio[7].sigla, "C7");
strcpy(comboio[8].sigla, "C8");
strcpy(comboio[9].sigla, "C9");
case 2:
puts("Pretendes adicionar novas estacoes ou novos comboios?");
puts(" 1. Estacao");
puts(" 2. Comboio");
scanf("%i", &opcao);
if(opcao == 1)
{
}
else if(opcao == 2)
{
}
else {
printf("Inseriu uma opcao inexistente");
getchar();
break;
}
case 3: break;
default: puts("Opcao invalida");
//FIM SWITCH
}
//Declaracao dos comboios por nos escolhidos (siglas)
for(int i=0; i<10; i++)
{
strcpy(comboio[i].sigla,"C");
}
for( int i =0; i<10; i++)
printf("%s\n\n",comboio[i].sigla);
getchar();
}
getchar();
return 0;
}
|
C
|
#include "common.h"
static char software_version[] = "$Id: done_handling.c,v 1.11 2010-09-22 07:03:59 freddy77 Exp $";
static void *no_unused_var_warn[] = { software_version, no_unused_var_warn };
/*
* This test try do discovery how dblib process token looking for state
* at every iteration. It issue a query to server and check
* - row count (valid number means DONE processed)
* - if possible to send another query (means state IDLE)
* - if error readed (means ERROR token readed)
* - if status present (PARAMRESULT token readed)
* - if parameter present (PARAM token readed)
* It try these query types:
* - normal row
* - normal row with no count
* - normal row without rows
* - error query
* - store procedure call with output parameters
*/
/* Forward declarations of the error handler and message handler. */
static int err_handler(DBPROCESS * dbproc, int severity, int dberr, int oserr, char *dberrstr, char *oserrstr);
static int msg_handler(DBPROCESS * dbproc, DBINT msgno, int msgstate, int severity, char *msgtext, char *srvname, char *procname,
int line);
static DBPROCESS *dbproc;
static int silent = 0;
static int check_idle = 0;
/* print functions adapted from src/dblib/dblib.c */
static const char *
prdbretcode(int retcode)
{
static char unknown[24];
switch(retcode) {
case REG_ROW: return "REG_ROW/MORE_ROWS";
case NO_MORE_ROWS: return "NO_MORE_ROWS";
case BUF_FULL: return "BUF_FULL";
case NO_MORE_RESULTS: return "NO_MORE_RESULTS";
case SUCCEED: return "SUCCEED";
case FAIL: return "FAIL";
default:
sprintf(unknown, "oops: %u ??", retcode);
}
return unknown;
}
static const char *
prretcode(int retcode)
{
static char unknown[24];
switch(retcode) {
case SUCCEED: return "SUCCEED";
case FAIL: return "FAIL";
case NO_MORE_RESULTS: return "NO_MORE_RESULTS";
default:
sprintf(unknown, "oops: %u ??", retcode);
}
return unknown;
}
static void
query(const char comment[])
{
if (comment)
printf("%s\n", comment);
sql_cmd(dbproc);
dbsqlexec(dbproc);
while (dbresults(dbproc) == SUCCEED) {
/* nop */
}
}
typedef const char* (*prfunc)(int);
static void
check_state(const char name[], prfunc print, int erc)
{
printf("State %-15s %-20s ", name, print(erc));
if (dbnumcols(dbproc) > 0)
printf("COLS(%d) ", dbnumcols(dbproc));
/* row count */
if (dbcount(dbproc) >= 0)
printf("ROWS(%d) ", (int) dbcount(dbproc));
silent = 1;
if (dbdata(dbproc, 1))
printf("DATA ");
silent = 0;
/* if status present */
if (dbretstatus(dbproc) == TRUE)
printf("STATUS %d ", (int) dbretstatus(dbproc));
/* if parameter present */
if (dbnumrets(dbproc) > 0)
printf("PARAMS ");
/*
* if possible to send another query
* NOTE this must be the last
*/
if (check_idle) {
silent = 1;
dbcmd(dbproc, "declare @i int ");
if (FAIL != dbsqlexec(dbproc))
printf("IDLE ");
silent = 0;
}
printf("\n");
}
static void
do_test(const char comment[])
{
int ret;
prfunc print_with = NULL;
if (comment)
printf("%s\n", comment);
sql_cmd(dbproc);
check_state("sqlexec ", prretcode, dbsqlexec(dbproc));
check_state("nextrow ", prdbretcode, dbnextrow(dbproc));
check_state("nextrow ", prdbretcode, dbnextrow(dbproc));
check_state("results ", prretcode, dbresults(dbproc));
check_state("nextrow ", prdbretcode, dbnextrow(dbproc));
check_state("nextrow ", prdbretcode, dbnextrow(dbproc));
check_idle = 0;
for (;;) {
ret = dbresults(dbproc);
check_state("results ", prretcode, ret);
if (ret != SUCCEED) {
print_with = prretcode;
break;
}
do {
ret = dbnextrow(dbproc);
check_state("nextrow ", prdbretcode, ret);
} while (ret == REG_ROW);
print_with = prdbretcode;
}
check_state("more results?", print_with, ret);
}
int
main(int argc, char *argv[])
{
const static int invalid_column_name = 207;
LOGINREC *login; /* Our login information. */
int i;
setbuf(stdout, NULL);
read_login_info(argc, argv);
if (dbinit() == FAIL)
exit(1);
dberrhandle(err_handler);
dbmsghandle(msg_handler);
#if 0
/*
* FIXME: Should be able to use the common err/msg handlers, but something about
* the IDLE checking causes them to fail. Not sure about purpose of IDLE checking.
* -- jkl January 2009
*/
dberrhandle(syb_err_handler);
dbmsghandle(syb_msg_handler);
#endif
login = dblogin();
DBSETLUSER(login, USER);
DBSETLPWD(login, PASSWORD);
DBSETLAPP(login, __FILE__);
dbproc = dbopen(login, SERVER);
dbloginfree(login);
if (!dbproc)
exit(1);
if (strlen(DATABASE))
dbuse(dbproc, DATABASE);
for (i=0; i < 6; i++)
query(NULL);
#if 0
check_state("setup done ", prretcode, erc);
printf("wasting results\n");
while ((erc = dbresults(dbproc)) == SUCCEED) {
while (dbnextrow(dbproc) == REG_ROW); /* no-op */
}
#endif
check_idle = 1;
do_test("normal row with rowcount on");
query("turn rowcount off");
do_test("normal row with rowcount off");
query("turn rowcount back on");
do_test("normal row without rows");
dbsetuserdata(dbproc, (BYTE*) &invalid_column_name);
do_test("error query");
do_test("stored procedure call with output parameters");
do_test("execute done2");
query("drop done_test");
query("drop done_test2");
dbexit();
return 0;
}
static int
err_handler(DBPROCESS * dbproc, int severity, int dberr, int oserr, char *dberrstr, char *oserrstr)
{
if (silent)
return INT_CANCEL;
fflush(stdout);
fprintf(stderr, "DB-Library error (severity %d):\n\t%s\n", severity, dberrstr);
if (oserr != DBNOERR)
fprintf(stderr, "Operating-system error:\n\t%s\n", oserrstr ? oserrstr : "(null)");
fflush(stderr);
return INT_CANCEL;
}
static int
msg_handler(DBPROCESS * dbproc, DBINT msgno, int msgstate, int severity, char *msgtext, char *srvname, char *procname, int line)
{
if (silent)
return 0;
fflush(stdout);
fprintf(stderr, "Msg %d, Level %d, State %d\n", (int) msgno, severity, msgstate);
if (strlen(srvname) > 0)
fprintf(stderr, "Server '%s', ", srvname);
if (procname && strlen(procname) > 0) {
fprintf(stderr, "Procedure '%s', ", procname);
if (line > 0)
fprintf(stderr, "Line %d", line);
}
fprintf(stderr, "\n\t%s\n", msgtext);
fflush(stderr);
return 0;
}
|
C
|
#pragma once
/*
M6: Ŀ
21 08 41 (21 41 ʼ 08 峤)
4D 36 (4D 36ʾϢM6Ϣ)
01 (Ϣǩ1-255ѭ)
01 (AGC)
01 00 (λָ2ֽ)
06 00 (Ŀ2ֽ)
8ֽ
*/
struct Msg_M6
{
const BYTE head[3] = { 0x21, 0x08, 0x41 }; // ͷ
const BYTE type[2] = { 0x4D, 0x36 }; // Ϣ
BYTE tag = 0; // Ϣǩ
BYTE agvno = 0; // AGV
UINT16 taskno = 0; //
UINT16 target = 0; // Ŀ
Msg_M6& operator=(const Msg_M6& m6) {
tag = m6.tag;
agvno = m6.agvno;
taskno = m6.taskno;
target = m6.target;
return *this;
}
};
/*
M1: ƶ·
21(ͷʼ־)10(峤) 41(ͷ־)
4D 31(M1)
01(Ϣǩ1-255)
01(AGC)
01 00(λM6һ)
01(Ŀ1-25)
00 02(߶κ,2Bһ)
00 03 00 04 00 05 00 ԭϲ57ֽ(0x39)ᳬ25
*/
struct Msg_M1
{
const BYTE head[3] = { 0x21, 0x39, 0x41 };
const BYTE type[2] = { 0x4D, 0x31 };
BYTE tag = 0;
BYTE agvno = 0;
UINT16 taskno = 0;
BYTE secnum = 0; // εĿ
UINT16 secno[25] = { 0 };
Msg_M1& operator=(const Msg_M1& m1) {
tag = m1.tag;
agvno = m1.agvno;
taskno = m1.taskno;
secnum = m1.secnum;
memcpy_s(secno, 50, m1.secno, 50);
return *this;
}
};
/*
M2:
21 08 41
4D 32(M2)
01(Ϣǩ1-255)
01(AGC)
01 00(λM6һ)
90 01()
*/
struct Msg_M2
{
const BYTE head[3] = { 0x21, 0x08, 0x41 };
const BYTE type[2] = { 0x4D, 0x32 };
BYTE tag = 0;
BYTE agvno = 0;
UINT16 taskno = 0;
UINT16 taskopcode = 0; //
Msg_M2& operator=(const Msg_M2& m2) {
tag = m2.tag;
agvno = m2.agvno;
taskno = m2.taskno;
taskopcode = m2.taskopcode;
return *this;
}
};
/*
E1: agvϱ 200ms
45 31
01
01 M1Ϣǩ
01 M2Ϣǩ
01 M6Ϣǩ
00 01 ǰ߶ξ(mm)
00 01 ǰκ
00 01 ǰ
00 01 agc״̬λ
01 agc
01 Ԥ
00 01 ǰٶmm/s
01 ƶ&
00 01 ǰ
21ֽ
*/
struct Msg_E1
{
const BYTE type[2] = { 0x45, 0x31 };
BYTE agvno = 0;
BYTE m1tag = 0;
BYTE m2tag = 0;
BYTE m6tag = 0;
UINT16 curDist = 0;
UINT16 curSec = 0;
UINT16 curPoint = 0;
UINT16 agcStatus = 0;
BYTE agcError = 0;
BYTE reserve = 0;
UINT16 curSpeed = 0;
BYTE moveOrOpt = 0;
UINT16 curTask = 0;
};
struct Msg_M1M2M6
{
Msg_M1 m1;
Msg_M2 m2;
Msg_M6 m6;
};
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <ctype.h> // isdigit ....
#include <getopt.h> // Pour les arguments
#include <pwd.h> // Pour la fonction getpwnam qui change le nom;
int myChown(int argc, char * argv[])
{
// Déclaration variable pour arguments
char opt; // Pour stocker les options passé en paramètre 1 à 1
char * options = "h" ; // Les options disponibles
int help = 0; // -h
char * ordre = NULL; // Stock l'argument owner:group que l'on "splittera" par la suite.
char * owner = NULL; // Stock le nouvelle utilisateur
char * group = NULL; // Stock de nouveau groupe
char * path = NULL; // Stock le chemin demandé
// Récupérer les options
while ((opt = getopt (argc, argv, options)) != -1)
{
switch(opt)
{
case '?':
printf("ERREUR : Un des paramètres n'est pas reconnu. Utiliser chown -h pour obtenir de l'aide. \n");
return 1;
break;
case 'h':
help = 1;
break;
/*default:
printf("ERREUR : Une erreur est survenu lors de la saisie des paramètres. \n");
return 1;
break;*/
}
}
if (help == 1) // Si -h
{
printf("Pour utiliser la fonction chown taper : chown [nomNouveauProprietaire:nomNouveauGroupe] [cheminDuFichier] \n");
printf("Astuce : vous pouvez concaténer les options : -l -a = -la \n \n");
printf("\t -h : Affiche l'aide. \n");
printf("\t \n");
printf("Exemples : \n");
printf("chown root test \t Le nouveau propriétaire de \"test\" est root\n");
printf("chown root:root test \t Le nouveau propriétaire est root, et \"test\" appartient au groupe de root \n");
printf("chown :root test \t Le nouveau groupe de \"test\" est celui de root\n");
return 0;
}
// Récupérer le répertoire et le mode
if (argc > 1)
{
int i;
for (i = 1; i<argc; i++)
{
switch(i)
{
case 1:
ordre = argv[i];
break;
case 2:
path = argv[i];
break;
}
}
}
if (path == NULL)
{
printf("ERREUR : Veuillez spécifier le nom d'un répertoire ou d'un fichier. Saisir chown -h pour obtenir de l'aide. \n");
return 1;
}
/* Coeur de la commande chown */
// Récupération des uid et gid du fichier
struct stat sb;
stat(path, &sb);
uid_t uid; // déclaration uid
gid_t gid; // déclaration gid
uid = sb.st_uid; // récupération de l'actuelle uid
gid = sb.st_gid; // récupération de l'actuelle gid
// Parsing de user & group
int i = 0;
if (ordre[0] != ':') // si n'est pas de type :user on récupère le owner
{
owner = malloc(255);
while(ordre[i] != '\0' && ordre[i] != ':') //Récupération de l'owner jusqu'à la rencontre de : ou \0.
{
owner[i] = ordre[i];
i++;
}
owner[i] = '\0';
}
if (ordre[i] == ':') //si on croise le séparateur : , on récupère le groupe
{
group = malloc(255);
int j = 0;
i++;
while(ordre[i] != '\0')
{
group[j] = ordre[i];
i++; j++;
}
group[j] = '\0';
}
// Récupération de l'uId;
struct passwd* own;
if (owner != NULL)
{
uid = atoi(owner);
if (!(own = getpwnam(owner)))
{
printf("ERREUR : Impossible d'obtenir l'uId du propriétaire : \"%s\" \n", owner);
return 1;
}
uid = own->pw_uid;
}
// Récupération du gId;
struct passwd* grp;
if (group != NULL)
{
gid = atoi(group);
if (!(grp = getpwnam(group)))
{
printf("ERREUR : Impossible d'obtenir le gId du groupe : \"%s\" \n", group);
return 1;
}
gid = grp->pw_gid;
}
//libération de l'espace alloué
free(group); free(owner);
// Changement du fichier
if (chown(path, uid, gid) != 0)
{
printf("ERREUR : Les modifications demandé sur le fichier n'ont pu être effectué.\n Assurez-vous d'avoir les droits nécéssaires. \n");
return 1;
}
printf("Les propriétaires du fichier \"%s\" ont correctement été changés.\n", path);
return 0;
}
int main(int argc, char * argv[])
{
myChown(argc, argv);
return 0;
}
|
C
|
// DDA
#include<stdio.h>
#include<graphics.h>
#include<math.h>
void DDA(int xa,int ya,int xb,int yb)
{
int dx=xb-xa;
int dy=yb-ya;
int step,k;
float xincrement,yincrement,x=xa,y=ya;
if(abs(dx)>abs(dy))
{
step=abs(dx);
}
else
{
step=abs(dy);
}
xincrement=dx/(float)step;
yincrement=dy/(float)step;
putpixel(x,y,RED);
for(k=0;k<step;k++)
{
x=x+xincrement;
y=y+yincrement;
putpixel(x,y,RED);
delay(50);
}
}
int main()
{
int gd = DETECT,gm;
initgraph(&gd,&gm," ");
DDA(50,80,40,150);
getch();
return 0;
}
|
C
|
#include<stdio.h>
#include<conio.h>
/*
syntax of tmpname function
char *tmpname(char *name)
*/
int main(){
char name[L_tmpnam+1];
tmpnam(name);
puts(name);
getch();
return 0;
}
|
C
|
/**
* @file save.h
* @brief save/restore facility amidst the choice tree
* @author Ben Blum
*/
#ifndef __LS_SAVE_H
#define __LS_SAVE_H
#include "estimate.h"
#include <sys/time.h>
struct ls_state;
struct hax;
struct save_state {
/* The root of the decision tree, or NULL if save_setjmp() was never
* called. */
struct hax *root;
/* If root is set, this points to the "current" node in the tree */
struct hax *current;
int next_tid;
/* Statistics */
uint64_t total_choice_poince;
uint64_t total_choices;
uint64_t total_jumps;
uint64_t total_triggers;
uint64_t depth_total;
/* Records the timestamp last time we arrived at a node in the tree.
* This is updated only during save_setjmp -- it doesn't need to be during
* save_longjmp because each longjmp is immediately after a call to setjmp
* on the last nobe in the previous branch. */
struct timeval last_save_time;
uint64_t total_usecs;
};
void abort_transaction(unsigned int tid, struct hax *h2, unsigned int code);
void save_init(struct save_state *);
void save_recover(struct save_state *, struct ls_state *, int new_tid);
/* Current state, and the next_tid/our_choice is about the next in-flight
* choice. */
void save_setjmp(struct save_state *, struct ls_state *,
int next_tid, bool our_choice, bool end_of_test,
bool is_preemption_point, unsigned int data_race_eip,
bool voluntary, bool xbegin);
/* If hax is NULL, then longjmps to the root. Otherwise, hax must be between
* the current choice point and the root (inclusive). */
void save_longjmp(struct save_state *, struct ls_state *, struct hax *);
void save_reset_tree(struct save_state *ss, struct ls_state *ls);
#endif
|
C
|
#include <linux/timer.h>
#include <linux/kthread.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/delay.h>
#include <linux/jiffies.h>
#include <linux/init.h>
#define TOUT 8000
static struct task_struct *spare;
static struct timer_list time_ex;
void timer_callback(struct timer_list *time)
{
printk(KERN_ALERT "Value of jiffie is : %lu\n", jiffies);
mod_timer(&time_ex,msecs_to_jiffies(TOUT));
}
int do_func(void *p)
{
while(!kthread_should_stop())
{
printk(KERN_ALERT "Inside kernel thread");
msleep(5000);
}
return 0;
}
static int jiffies_init(void)
{
printk(KERN_ALERT "Jiffie : %s\n", jiffies);
spare = kthread_run(do_func, NULL, "Thread");
timer_setup(&time_ex, timer_callback, 0);
mod_timer(&time_ex, jiffies+ msecs_to_jiffies(TOUT));
return 0;
}
static void jiffies_exit(void)
{
kthread_stop(spare);
del_timer(&time_ex);
printk(KERN_ALERT "jiffies exiting\n");
}
module_init(jiffies_init);
module_exit(jiffies_exit);
|
C
|
/*
* Oscar Hedblad
* COP3502, 0002
* Matchmaking Program
* Professor Marshall Tappen
*/
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <math.h>
/* My different prototypes */
int factorial(int n);
int matchScores(int perm[], int boysRating[][10], int girlsRatings[][10], int len);
int matchDifference(int perm[], int boysRating[][10], int girlsRatings[][10], int len);
void permute(int perm[], int len);
void copy(int x[],int y[], int numb);
void print(char boys[][20], char girls[][20], int perm[], int len);
int main() {
FILE* ifp;
ifp= fopen("matching.txt","r");
/* Makes sure that the file name entered exists */
if (ifp == NULL)
printf("Missing file, please check file name!");
/* Reads in first number at the top of .txt file */
int counter, F;
fscanf(ifp, "%d", &F);
/* For loop that determines the amount of times to be calculated */
for (counter = 1;counter <= F;counter++) {
/* Declaration of various variables */
int numb;
int girlsPermute[10], topPermute[10];
char boys[10][20], girls[10][20];
int boysRating[10][10], girlsRatings[10][10];
int topScore = 0, difference = 0;
/* Read in the number of pairs */
fscanf(ifp, "%d", &numb);
/* Initialize all girls permute to ZERO */
int i, j, verify = 0;
for (i = 0;i < numb;i++) {
girlsPermute[i] = i;
topPermute[i] = i;
}
/* Reads and scans all names and numbers (scores) */
for (i = 0;i < numb;i++){
fscanf(ifp, "%s", boys[i]);
}
for (i = 0;i < numb;i++){
fscanf(ifp, "%s", girls[i]);
}
for (i = 0;i < numb;i++){
for (j = 0;j < numb;j++){
fscanf(ifp, "%d", &boysRating[i][j]);
}
}
for (i = 0;i < numb;i++){
for (j = 0;j < numb;j++){
fscanf(ifp, "%d", &girlsRatings[i][j]);
}
}
/* For loop that checks and makes sure that the correct number of permutations is done */
for (i = 0;i < factorial(numb);i++) {
/* Updates scores and calls functions to calculate and determine which ratings are best */
int presentScore = matchScores(girlsPermute, boysRating, girlsRatings, numb);
int presentDifference = matchDifference(girlsPermute, boysRating, girlsRatings, numb);
/* If statement that correctly fixes any situation when a tie occurs */
if (verify && presentScore == topScore && presentDifference == difference){
}
/* If statement that updates the new current best suitable match */
if (presentScore > topScore || (presentScore == topScore && presentDifference < difference)) {
copy(topPermute, girlsPermute, numb);
topScore = presentScore;
difference = presentDifference;
}
/* Begins next permutation */
permute(girlsPermute, numb);
}
/* Prints out the Matching number and their maximum (top) score */
printf("Matching #%d: Maximum Score = %d.\n\n", counter, topScore);
print(boys, girls, topPermute, numb);
}
return 0;
}
/* Takes in lower case f, it then factorize the number to find total number of factorials */
int factorial(int f) {
if (f == 0)
return 1;
else
return f*factorial(f-1);
}
/* Intakes permutation array and its length, then makes the permutation */
void permute(int perm[], int len) {
/* Correctly identifies the spot that needs to SWAP. It then decrements to move to next index */
int i = len - 1;
while (i > 0 && perm[i] < perm[i - 1]) i--;
i--;
if (i == -1) return;
/* Swap index at [i] */
int k = len - 1;
while (k > i && perm[k]<perm[i]) k--;
/* Changes the numbers positions */
int temp = perm[i];
perm[i] = perm[k];
perm[k] = temp;
/* Swap temp variable from index [i +1] to [len - 1] in order to move correctly */
int q, w;
for (q = i + 1, w = len - 1;q < w;q++, w--) {
temp = perm[q];
perm[q] = perm[w];
perm[w] = temp;
}
}
/* Reads in both the boy/girl rating and the length of the boys array, then returns the score of matching boys and girls */
int matchScores(int perm[], int boysRating[][10], int girlsRatings[][10], int len) {
int p, score = 0;
for (p = 0;p < len;p++) {
/* If-else statement that updates the present score for the last counter and compares it to the lower of the two scores */
if (boysRating[p][perm[p]] <= girlsRatings[perm[p]][p]){
score += boysRating[p][perm[p]];
}
else
score += girlsRatings[perm[p]][p];
}
return score;
}
/* Final update of score to determine the "winning pair" */
int matchDifference(int perm[], int boysRating[][10], int girlsRatings[][10], int len) {
/* Subtraction that calculates the best matches */
int m, score = 0;
for (m = 0;m < len;m++)
score += (boysRating[m][perm[m]]-girlsRatings[perm[m]][m]);
return score;
}
/* Copies corresponding values of array Y into X. */
void copy(int x[],int y[], int numb) {
int i;
for (i = 0;i < numb;i++)
x[i] = y[i];
}
/* Takes in the length and names of the boy/girl array,
* and the permutation for the girls, then prints the most suitable boy-girl match.*/
void print(char boys[][20], char girls[][20], int perm[], int len) {
int z;
for (z = 0;z < len;z++)
printf("%s %s\n", boys[z], girls[perm[z]]);
printf("\n");
}
|
C
|
/* To compile normally
* gcc -Wall netset.c -o netset
*
* To compile with debugging info
* gcc -g -Wall netset.c -o netset
*/
/* Initial configuration
* - setup a working copy of INTERFACES_PATH that has NETDEV setup for dhcp
* - copy it to the location DHCP_CONFIG
*/
/* To add a new profile, do the following,
*
* after line 59 - add a name for the profile to be
* copy, paste and edit an else if group in interfaceLoad() to reflect a new profile
*
*/
/* Most interface options exec the following
* ifconfig netdevice xxx.xxx.xxx.xxx/yy
* ifconfig netdevice down
* ifconfig netdevice up
*/
// I suggest creating a hidden netset folder
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define BUFFER 1024
#define SUCCESS 0
#define ERR_USAGE -1
#define ERR_UNSUPPORTED_PROFILE -2
#define ERR_MALLOC_FAILURE -100
#define ERR_FOPEN_FAILURE -200
// Prototypes
int interfaceLoad(char *profile)
int setStatic(char *profile, char *dev_addr);
int writeConky(char *conky_profile, char *cpe_addr, char *username, char *password);
//------------------------------------
//-- Global Configuration options
//------------------------------------
static const char CONKY_FILEPATH[] = "/home/world/.netset/interface";
static const char DHCP_CONFIG[] = "/home/world/.netset/dhcp";
static const char INTERFACES_PATH[] = "/etc/network/interfaces";
static const char RESTART_NETWORK[] = "/etc/init.d/networking restart";
static const char NETDEV[] = "eth1";
int DO_CONKY = 1; // 1 to write info to file || 0 to not do it
//character strings for comparing
char *dhcp = "dhcp";
char *three = "365";
char *buffalo = "buffalo";
char *kc = "kc";
char *sonicwall = "sonicwall";
char *visionnet = "visionnet";
int main(int argc, char **argv){
if(argc != 2){
printf("\n");
printf("USAGE: %s <profile name>\n", argv[0]);
printf("(must be run with sudo)\n\n");
printf("profile names include \n");
printf("dhcp \n");
printf("365\n");
printf("buffalo\n");
printf("kc\n");
printf("sonicwall\n");
printf("visionnet\n");
printf("\n");
return ERR_USAGE;
}
int retcode = interfaceLoad(argv[1]);
if(retcode < 0){
printf("Looks like an error occured that may have prevented the program from succeeding\n");
printf("return code was %d\n", retcode);
}
return retcode;
} // End main
//strcmp returns 0 if strings are equal so
//the logic reads as if the two strings are equal
int interfaceLoad(char *profile)
{
if(strcmp (profile, three) == 0){
// profile options
char profile[] = "3650MHz";
char dev_addr[] = "192.168.254.252/24";
// conky options
char conky_profile[] = "3650MHz (Wimax)";
char username[] = "Operator";
char password[] = "wimax";
char cpe_addr[] = "192.168.254.251";
//do statics
setStatic(profile, dev_addr);
//do conky
if (DO_CONKY) {
writeConky(conky_profile, cpe_addr, username, password);
}
}
else if(strcmp (profile, buffalo) == 0){
// profile options
char profile[] = "Buffalo";
char dev_addr[] = "192.168.11.5/24";
// conky options
char conky_profile[] = "Buffalo";
char username[] = "root";
char password[] = "password";
char cpe_addr[] = "192.168.11.1";
//do statics
setStatic(profile, dev_addr);
//do conky
if (DO_CONKY) {
writeConky(conky_profile, cpe_addr, username, password);
}
}
else if(strcmp (profile, kc) == 0){
// profile options
char profile[] = "Kingdom City Radio";
char dev_addr[] = "192.168.254.252/24";
// conky options
char conky_profile[] = "3650MHz (Kingdom City)";
char username[] = "installer";
char password[] = "installer";
char cpe_addr[] = "192.168.254.251";
//do statics
setStatic(profile, dev_addr);
//do conky
if (DO_CONKY) {
writeConky(conky_profile, cpe_addr, username, password);
}
}
else if(strcmp (profile, sonicwall) == 0){
// profile options
char profile[] = "SonicWall";
char dev_addr[] = "192.168.168.168/24";
// conky options
char conky_profile[] = "SonicWall";
char username[] = "admin";
char password[] = "password";
char cpe_addr[] = "192.168.168.168";
//do statics
setStatic(profile, dev_addr);
//do conky
if (DO_CONKY) {
writeConky(conky_profile, cpe_addr, username, password);
}
}
else if(strcmp (profile, visionnet) == 0){
// profile options
char profile[] = "VisionNet";
char dev_addr[] = "192.168.1.5/24";
// conky options
char conky_profile[] = "VisionNet";
char username[] = "admin";
char password[] = "0123456789";
char cpe_addr[] = "192.168.1.254";
//do statics
setStatic(profile, dev_addr);
//do conky
if (DO_CONKY) {
writeConky(conky_profile, cpe_addr, username, password);
}
}
else if(strcmp (profile, dhcp) == 0)
{
//add in warnings
// - loss of network
// - do dhcp initial setup
char *com_backupConfig = NULL;
char *com_cpDHCPConfig = NULL;
char *com_restartNetwork = NULL;
char *com_devDown = NULL;
char *com_devUp = NULL;
char *buf = NULL;
int len;
// Setup buffer
buf = malloc(sizeof(char) * BUFFER + 1);
if(buf == NULL){
printf("Unable to allocate memory to work with\n");
return ERR_MALLOC_FAILURE;
}
// Compose command to backup old interface
sprintf(buf, "mv %s %s.old", INTERFACES_PATH,INTERFACES_PATH);
len = strlen(buf);
com_backupConfig = malloc(sizeof(char) * len + 1);
strcpy(com_backupConfig, buf);
// Compose command to bring in dhcp config
sprintf(buf, "cp %s %s", DHCP_CONFIG, INTERFACES_PATH);
len = strlen(buf);
com_cpDHCPConfig = malloc(sizeof(char) * len + 1);
strcpy(com_cpDHCPConfig, buf);
// Compose command to restart network
sprintf(buf, "%s", RESTART_NETWORK);
len = strlen(buf);
com_restartNetwork = malloc(sizeof(char) * len + 1);
strcpy(com_restartNetwork, buf);
// Compose command to bring device down
sprintf(buf, "ifconfig %s down", NETDEV);
len = strlen(buf);
com_devDown = malloc(sizeof(char) * len + 1);
strcpy(com_devDown, buf);
// Compose command to bring device up
sprintf(buf, "ifconfig %s up", NETDEV);
len = strlen(buf);
com_devUp = malloc(sizeof(char) * len + 1);
strcpy(com_devUp, buf);
// Do commands
printf("\n\n");
printf("DHCP Selected:\n");
printf("Moving %s to %s.old\n", INTERFACES_PATH, INTERFACES_PATH);
system(com_backupConfig);
printf("Copying %s to %s\n", DHCP_CONFIG, INTERFACES_PATH);
system(com_cpDHCPConfig);
printf("Restarting network: (%s\n", RESTART_NETWORK);
system(com_restartNetwork);
printf("Bringing %s down\n", NETDEV);
system(com_devDown);
printf("Bringing %s up\n", NETDEV);
system(com_devUp);
if (DO_CONKY) {
writeConky("DHCP", "N/A", "N/A", "N/A");
}
}//end if x - dhcp
else{
printf("Unsupported profile at this time!\n");
return ERR_UNSUPPORTED_PROFILE;
}
return SUCCESS;
}//end interfaceLoad
int setStatic(char *profile, char *dev_addr){
//needed variables
int len = 0;
char *buf = NULL;
char *com_setAddr = NULL;
char *com_devDown = NULL;
char *com_devUp = NULL;
printf("%s Selected:\n", profile);
// Setup buffer
buf = malloc(sizeof(char) * BUFFER + 1);
if(buf == NULL){
printf("Unable to allocate memory to work with\n");
return ERR_MALLOC_FAILURE;
}
// Compose command to set address
sprintf(buf, "ifconfig %s %s", NETDEV, dev_addr);
len = strlen(buf);
com_setAddr = malloc(sizeof(char) * len + 1);
strcpy(com_setAddr, buf);
// Compose command to bring device down
sprintf(buf, "ifconfig %s down", NETDEV);
len = strlen(buf);
com_devDown = malloc(sizeof(char) * len + 1);
strcpy(com_devDown, buf);
// Compose command to bring device up
sprintf(buf, "ifconfig %s up", NETDEV);
len = strlen(buf);
com_devUp = malloc(sizeof(char) * len + 1);
strcpy(com_devUp, buf);
// Exec commands
printf("Setting %s to %s\n", NETDEV, dev_addr);
system(com_setAddr);
printf("Bringing %s down\n", NETDEV);
system(com_devDown);
printf("Bringing %s up\n", NETDEV);
system(com_devUp);
return SUCCESS;
}//end setStatic
int writeConky(char *conky_profile, char *cpe_addr, char *username, char *password){
FILE *finterface;
finterface = fopen(CONKY_FILEPATH, "w");
if(finterface == NULL){
printf("Unable to open %s for writing\n", CONKY_FILEPATH);
return ERR_FOPEN_FAILURE;
}
fprintf(finterface, "%s\n", conky_profile);
fprintf(finterface, "%s\n", cpe_addr);
fprintf(finterface, "%s\n", username);
fprintf(finterface, "%s\n", password);
fclose(finterface);
return SUCCESS;
}
|
C
|
// 引数のある関数ポインタの練習
#include <stdio.h>
int max(int, int);
int min(int, int);
int main(void) {
int (*cmp)(int, int) = NULL; // cmpの初期化
int a = 1, b = 20;
cmp = max;
printf("%dと%dのうち、最大のものは%d\n", a, b, cmp(a, b));
cmp = min;
printf("%dと%dのうち、最小のものは%d\n", a, b, cmp(a, b));
return 0;
}
int max(int m, int n) {
if(m > n) {
return m;
}
return n;
}
int min(int m, int n) {
if(m < n) {
return m;
}
return n;
}
|
C
|
/* Name: Isaac DeMello
Date: 3/3/2016
File name: avg.c
Group: Woojin, Kyle */
#include<stdio.h>
main() //begin main
{
//initialize variables
int num = 0;
float avg;
int flag;
int sum = 0;
int div = 0;
//prompt user for first input
printf("Enter the first number to sum: \n");
scanf("%d", &num);
//open while loop A, ends with EOF
while(flag != EOF)
{
//prompt user for value of num
printf("Enter the next number to sum: \n");
sum = num + sum;
//check for EOF
flag = scanf("%d", &num);
//check for EOF or next entry
//div represents the value of the divisor
div = div + 1;
}
//final formula after loop ends
avg = sum /div;
//print result
printf("The average value is: %.2f\n", avg);
} //end of main
|
C
|
/**
* CSC369 Assignment 2
*
* This is the source/implementation file for your safe stop sign
* submission code.
*/
#include "safeStopSign.h"
/**
* @brief Broadcasts a condition variable and does error checking.
*
* @param cond pointer to the condition variable to initialize.
*/
static void broadcastConditionVariable(pthread_cond_t* cond);
/**
* @brief Waits for a condition variable and does error checking.
*
* @param cond pointer to the condition variable to initialize.
*/
static void waitConditionVariable(pthread_cond_t* cond, pthread_mutex_t* mutex);
void initSafeStopSign(SafeStopSign* sign, int count) {
initStopSign(&sign->base, count);
// TODO: Add any initialization logic you need.
// Initialize enterLanelocks, exitLaneLocks and exitLaneConditions
for (int i = 0; i < DIRECTION_COUNT; ++i) {
initMutex(&sign->enterLaneLocks[i]);
initMutex(&sign->exitLaneLocks[i]);
initConditionVariable(&sign->exitLaneConditions[i]);
}
// Initialize enterLaneTokens and exitLaneTokens
size_t size = sizeof(int) * DIRECTION_COUNT;
memset(sign->enterLaneTokens, 0, size);
memset(sign->exitLaneTokens, 0, size);
// Initialize quadrants
size = sizeof(int) * QUADRANT_COUNT;
memset(sign->quadrants, FALSE, size);
// Initialize goThroughStopSignLock and goThroughStopSignCondition
initMutex(&sign->goThroughStopSignLock);
initConditionVariable(&sign->goThroughStopSignCondition);
}
void destroySafeStopSign(SafeStopSign* sign) {
destroyStopSign(&sign->base);
// TODO: Add any logic you need to clean up data structures.
// Destory enterLaneLocks, exitLaneLocks and exitLaneConditions
for (int i = 0; i < DIRECTION_COUNT; ++i) {
pthread_mutex_destroy(&sign->enterLaneLocks[i]);
pthread_mutex_destroy(&sign->exitLaneLocks[i]);
pthread_cond_destroy(&sign->exitLaneConditions[i]);
}
// Destory goThroughStopSignLock and goThroughStopSignCondition
pthread_mutex_destroy(&sign->goThroughStopSignLock);
pthread_cond_destroy(&sign->goThroughStopSignCondition);
}
void runStopSignCar(Car* car, SafeStopSign* sign) {
// TODO: Add your synchronization logic to this function.
// Obtain lane and laneIndex for the given car
EntryLane* lane = getLane(car, &sign->base);
int laneIndex = getLaneIndex(car);
// Obtain the required quadrants for the given car
int quadrants[QUADRANT_COUNT];
int quadrantCount = getStopSignRequiredQuadrants(car, quadrants);
// Token of the given car
int token;
// ------------- Enter Lane -------------
pthread_mutex_lock(&sign->enterLaneLocks[laneIndex]);
// Obtain the token
token = sign->enterLaneTokens[laneIndex];
enterLane(car, lane);
// Increment the token for next car
++sign->enterLaneTokens[laneIndex];
unlock(&sign->enterLaneLocks[laneIndex]);
// -------- Go Through Stop Sign ---------
pthread_mutex_lock(&sign->goThroughStopSignLock);
// Are required quadrants all clear?
int canPass;
do {
canPass = TRUE;
for (int i = 0; i < quadrantCount; ++i) {
int j = quadrants[i];
if (sign->quadrants[j] == TRUE) {
canPass = FALSE;
break;
}
}
// Put the given car in wait
// if at least one required quadrant is not available
if (canPass == FALSE) {
waitConditionVariable(
&sign->goThroughStopSignCondition,
&sign->goThroughStopSignLock
);
}
} while (canPass == FALSE);
// Mark all required quadrants as occupied
for (int i = 0; i < quadrantCount; ++i) {
int j = quadrants[i];
sign->quadrants[j] = TRUE;
}
unlock(&sign->goThroughStopSignLock);
// -> Start going through
goThroughStopSign(car, &sign->base);
// <- Finish going through
pthread_mutex_lock(&sign->goThroughStopSignLock);
// Unmark all required quadrants
for (int i = 0; i < quadrantCount; ++i) {
int j = quadrants[i];
sign->quadrants[j] = FALSE;
}
// Notify other cars to give a try to go through intersection
broadcastConditionVariable(&sign->goThroughStopSignCondition);
unlock(&sign->goThroughStopSignLock);
// ------------- Exit Lane -------------
pthread_mutex_lock(&sign->exitLaneLocks[laneIndex]);
// Ensure the order by comparing tokens
// Put car in wait
// if its token not matches
while (token != sign->exitLaneTokens[laneIndex]) {
waitConditionVariable(
&sign->exitLaneConditions[laneIndex],
&sign->exitLaneLocks[laneIndex]
);
}
exitIntersection(car, lane);
// Increment token for next car
++sign->exitLaneTokens[laneIndex];
// Notify other cars to give a try to exit intersection
broadcastConditionVariable(&sign->exitLaneConditions[laneIndex]);
unlock(&sign->exitLaneLocks[laneIndex]);
}
static void broadcastConditionVariable(pthread_cond_t* cond) {
int returnValue = pthread_cond_broadcast(cond);
if (returnValue != 0) {
perror("Condition variable boardcast failed."
"@ " __FILE__ " : " LINE_STRING "\n");
}
}
static void waitConditionVariable(pthread_cond_t* cond, pthread_mutex_t* mutex) {
int returnValue = pthread_cond_wait(cond, mutex);
if (returnValue != 0) {
perror("Condition variable wait failed."
"@ " __FILE__ " : " LINE_STRING "\n");
}
}
|
C
|
//ECE471 Project
//Raspberry pi tank weather station beer getting beast
//Jason Millette
//11/26/18
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <unistd.h>
int main() {
system("/home/pi/RpiTank/./initDisplay.py"); //Initialize the SPI displays
system("/home/pi/RpiTank/./IP.py"); //Displays the IP address for webpage
int weatherPID = fork(); //Forks to run both programs simulaniously
if (weatherPID == 0) { // Child
while(1) {
system("/home/pi/RpiTank/./weather.py"); //Displays new weather data every two minutes
sleep(120);
}
}
else {
system("/home/pi/RpiTank/./meme.py"); //Parent runs Memes on Demand Button(trademark pending)
}
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* libft.h :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: achazal <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2015/07/26 02:55:27 by achazal #+# #+# */
/* Updated: 2015/07/26 02:55:29 by achazal ### ########.fr */
/* */
/* ************************************************************************** */
#include <unistd.h>
size_t ft_strlen(const char *str)
{
const char *ptr;
ptr = str;
while (*ptr)
ptr++;
return (ptr - str);
}
void ft_memset(char *str, char c, size_t len)
{
while (len--)
*str++ = c;
}
void ft_putnbr(int nb)
{
char buffer[12];
char *ptr;
if (nb == -2147483648)
write(1, "-2147483648", sizeof("-2147483648"));
else if (nb == 0)
write(1, "0", 1);
else
{
ptr = buffer + sizeof(buffer) - 1;
buffer[0] = 0;
if (nb < 0)
{
buffer[0] = 1;
nb = -nb;
}
while (nb > 0)
{
*ptr-- = nb % 10 + '0';
nb /= 10;
}
if (buffer[0])
*ptr-- = '-';
write(1, ptr + 1, sizeof(buffer) - (long)ptr + (long)buffer - 1);
}
}
int ft_atoi(const char *str)
{
int negatif;
int val;
if (*str == '-')
{
str++;
negatif = 1;
}
else
{
if (*str == '+')
str++;
negatif = 0;
}
val = 0;
while (*str >= '0' && *str <= '9')
val = val * 10 + (*str++) - '0';
return ((negatif) ? -val : val);
}
char *ft_strchr(const char *str, char c)
{
while (*str)
{
if (*str == c)
return ((char *)str);
str++;
}
return (NULL);
}
|
C
|
/*
Evaluation Of postfix Expression in C++
Input Postfix expression must be in a desired format.
Operands must be integers and there should be space in between two operands.
Only '+' , '-' , '*' and '/' operators are expected.
*/
#include <stdio.h>
#include <string.h>
int top = -1;
int stack[1000];
/* push the given data into the stack */
void pushstack(int num) {
stack[++top] = num;
}
/* Pop the top element from the stack */
int popstack() {
int d;
if (top == -1)
return -1;
d = stack[top];
stack[top] = 0;
top--;
return (d);
}
int main() {
char s[1000];
int i, d = -1, op1, op2, result;
/* Get the postfix expression from the user */
printf("Enter ur postfix expression:");
fgets(s, 100, stdin);
for (i = 0; i < strlen(s); i++) {
if (isdigit(s[i])) {
/*
* if the i/p char is digit, parse
* character by character to get
* complete operand
*/
d = (d == -1) ? 0 : d;
d = (d * 10) + (s[i] - 48);
continue;
}
if (d != -1) {
/* if the i/p is operand, push it into the stack */
pushstack(d);
}
if (s[i] == '+' || s[i] == '-'
|| s[i] == '*' || s[i] == '/') {
/*
* if the i/p is an operator, pop 2 elements
* from the stack and apply the operator
*/
op2 = popstack();
op1 = popstack();
if (op1 == -1 || op2 == -1)
break;
switch (s[i]) {
case '+':
result = op1 + op2;
/* push the result into the stack */
pushstack(result);
break;
case '-':
result = op1 - op2;
pushstack(result);
break;
case '*':
result = op1 * op2;
pushstack(result);
break;
case '/':
result = op1 / op2;
pushstack(result);
break;
}
}
d = -1;
}
if (top == 0)
printf("The corresponding Output:%d\n", stack[top]);
else
printf("u have given wrong postfix expression\n");
return 0;
}
|
C
|
#include<stdio.h>
#include<conio.h>
#include<string.h>
union student
{
char name[10];
int roll_no;
int marks;
};
void main()
{
union student s;
clrscr();
printf("The Size of Union is %u bytes",sizeof(s));
strcpy(s.name ,"Prashant"); //string function used
printf("\n The name is %s",s.name);
s.roll_no=12;
printf("\n The Roll No is =%d",s.roll_no);
s.marks=67;
printf("\n The Marks =%d",s.marks);
getch();
}
|
C
|
/*
** EPITECH PROJECT, 2018
** Evalxpr
** File description:
** make calcul with parenthese
*/
#include "include/my.h"
#include <stdlib.h>
int eval_expr(char const *str);
int ini_multiplicator(char *str);
int number(char **str);
int factors(char **str);
int summands(char **str);
int main(int ac, char const *av[])
{
if (ac == 2) {
my_put_nbr(eval_expr(av[1]));
my_putchar('\n');
return (0);
}
return (84);
}
|
C
|
/*
* @@name: target_mapper_map.1c
* @@type: C
* @@compilable: yes
* @@linkable: no
* @@expect: success
* @@version: omp_5.0
*/
#include <stdio.h>
#include <stdlib.h>
#define N 1000
typedef struct myvec {
size_t len;
double *data;
} myvec_t;
#pragma omp declare target mapper(myvec_t v) map(v, v.data [0:v.len])
void init(myvec_t *s);
int main() {
myvec_t s;
s.data = (double *)calloc(N, sizeof(double));
s.len = N;
#pragma omp target
init(&s);
printf("s.data[%d]=%lf\n", N - 1, s.data[N - 1]); // s.data[99]=99.000000
}
void init(myvec_t *s) {
for (int i = 0; i < s->len; i++)
s->data[i] = i;
}
|
C
|
// RUN: %tool "%s" > "%t"
// RUN: %diff %CORRECT "%t"
int bar(int a)
ensures \result == a + 1
{
return a + 1;
}
int foo() {
int x;
x = 0;
while(x < 20) invariant x <= 20 {
x = bar(x);
}
assert x == 20;
return 0;
}
|
C
|
#pragma once
void BubbleSort(int a[], int n)
{
int tmp = 0;
for (int i = 0; i < n-1; i++)
{
bool bFlag = false;
for (int j = 0; j < n-1-i; j++)
{
if (a[j]>a[j+1])
{
tmp = a[j];
a[j] = a[j + 1];
a[j + 1] = tmp;
bFlag = true;
}
}
if (!bFlag)
{
break;
}
}
}
// ðÿֱȽϣ滻
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "Lista2.h"
int main () {
Lista * p = lista_cria ();
lista_insere_inicio (p, elemento_cria("joao", "2222.2222", 2));
lista_insere_inicio (p, elemento_cria("pedro", "1111.1111", 1));
lista_insere_inicio (p, elemento_cria("ana", "6666.6666", 6));
lista_insere_posicao(p, elemento_cria("maria", "4444.4444", 4), 3);
lista_insere_posicao(p, elemento_cria("lia", "3333.33333", 3), 1);
lista_insere_final (p, elemento_cria("paulo", "9999.9999", 9));
lista_insere_posicao(p, elemento_cria("junior", "7777.7777", 4), 6);
int i;
for (i=1; i<=lista_obtem_tamanho(p); i++)
printf("[%d] %s\n", i, elemento_imprime(lista_obtem_elemento (p, i)));
Lista * q = lista_copia (p);
printf("[tamanho=%d]\n%s\n", lista_obtem_tamanho(q), lista_imprime(q));
lista_libera(p);
lista_libera(q);
return 0;
}
|
C
|
//Check if number id power of two
//So number should have only one set bit
//
//Idea is
//
//If output num & (num -1) is 0 i.e. we had only one bit set >> so number is power of two
//
//Keep dividing number by two till num is one and check if num%2 is non zero at any point
//Denotes num is not power of two else it is power of two
//
#include <stdio.h>
int PowerOfTwo(int num)
{
if(num < 1)//expecting number is >= 1
return 0;
return (!(num & (num-1)))?1:0;
}
int PowerOfTwo1(int num)
{
if(num < 1)////expecting number is >= 1
return 0;
while(num > 1)
{
if(num%2)
return 0;
num = num >> 1;
}
return 1;
}
int main()
{
int num = 0;
printf("Enter number \n");
scanf("%d", &num);
if(PowerOfTwo(num))
printf("YES\n");
else
printf("NO\n");
if(PowerOfTwo(num))
printf("YES\n");
else
printf("NO\n");
return 0;
}
|
C
|
// -*- compile-command: "gcc -o problem_026 problem_026.c -Wall" -*-
// Copyright (c) 2014 Michael Caldwell
#include <stdio.h>
int main()
{
printf("Project Euler - Problem 26:\n"
"Find the value of d < 1000 for which 1/d contains the longest recurring cycle.\n\n");
int n, i, m, j;
int number[5000] = {};
int answer[5000] = {};
int longest[2] = {};
int count = 0;
for (n=1 ; n<1000 ; n++)
{
// Clear out number
for (i=0 ; i<5000 ; i++)
number[i]=0;
number[0]=1;
// Divide 1 by n for whole array
for (i=0 ; i<5000 ; i++)
{
int tmp=number[i]/n, tmp2=tmp*n;
number[i] -= tmp2;
if (number[i] < n)
{
number[i+1] += number[i]*10;
number[i]=0;
}
answer[i]=tmp;
}
// Compare Results
int done=0;
for (i=3 ; i<4000 ; i++)
{
count=0;
for (m=i+1 ; m<4500 ; m++)
{
count++;
int candidate=0;
for (j=0 ; j+m<5000 ; j++)
if (answer[i+j] == answer[m+j])
candidate=1;
else
{
candidate=0;
break;
}
if (candidate == 1)
{
done = 1;
break;
}
}
if (done==1)
break;
}
// Keep track of longest cycle
if (count > longest[0] && done == 1)
{
longest[0]=count;
longest[1]=n;
/*
// DEBUG Print results!
printf("Repeat found: %i digits produced by 1/%i\n", longest[0], n);
printf("0.");
for (i=1 ; i<1000 ; i++)
{
if (i%count)
printf("%i", answer[i]);
else
printf(" %i", answer[i]);
}
printf("...\n");
*/
}
}
printf("Longest: 1/%d produced %i recurring digits\n", longest[1], longest[0]);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int Y (int a, int b) {
return b == 0 ? a : Y (b, a % b) ;
}
int main()
{
int a, b, c, d ;
char o ;
while (scanf("%d/%d%c%d/%d",&a, &b, &o, &c, &d) != EOF) {
int fz, fm ;
switch (o) {
case '-' : fz = a * d - b * c ; break ;
case '+' : fz = a * d + b * c ; break ;
}
fm = b * d ;
if (fz) {
if (abs(fz % fm)) {
if (fz>0) printf("%d/%d\n", fz / Y (fz, fm), fm / Y (fz, fm)) ;
else printf("%d/%d\n", - fz / Y (fz, fm), - fm / Y (fz, fm)) ;
}
else printf("%d\n", fz / fm) ;
}
else printf("0\n") ;
}
return 0;
}
|
C
|
//to print upper and lower triangular matrix//
#include<stdio.h>
int main()
{
int m,n,i,j,a[10][10],b[10][10],c[10][10];
printf("Please Enter Number of rows and coloums : ");
scanf("%d%d", &m,&n);
printf("Please Enter the Matrix Elements\n ");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
}
}
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
b[i][j]=0;
}
}
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
c[i][j]=0;
}
}
printf("the upper triangular matrix is :\n");
for(i=0;i<m;i++)
{
for(j= 0;j<n;j++)
{
if(j>=i)
{
b[i][j]=a[i][j];
printf("% d",b[i][j]);
}
else
{
printf(" 0");
}
}
printf("\n");
}
printf("the lower tringular matrix is :\n");
for(i=0;i<m;i++)
{
for(j= 0;j< n;j++)
{
if(i>=j)
{
c[i][j]=a[i][j];
printf("% d",c[i][j]);
}
else
{
printf(" 0");
}
}
printf("\n");
}
return 0;
}
|
C
|
#include <stdio.h>
int main(int argc, char *argv[])
{
int distance = 100;
float power = 2.345f;
double super_power = 56789.4532;
char initial = 'A';
char first_name[] = "Zed";
char last_name[] = "Shaw";
int number = 100;
printf("You are %d miles away.\n", distance);
printf("You have %f level of power.\n", power);
printf("You have %f awesome super powers.\n", super_power);
printf("I have an initial %c.\n", initial);
printf("I have a first name %s.\n", first_name);
printf("I have a last name %s.\n", last_name);
printf("My whole name is %s %c. %s.\n",
first_name, initial, last_name);
printf("\n");
printf("Now, I'll type number 100 in many different way:\n");
printf("As decimal (signed): %d\n", number);
printf("As decimal (unsigned): %u\n", number);
printf("As hexadecimal int: %x\n", number);
printf("As hexadecimal float: %a\n", (double)number);
printf("As octal: %o\n", number);
printf("As float: %.3f\n", (double)number);
printf("Scientific notation: %e\n", (double)number);
return 0;
}
|
C
|
//
// main.c
// barber
//
// Created by Takashii on 2021/5/28.
//
#include <stdio.h>
#include <pthread.h>
#include <time.h>
#include <unistd.h>
#include <semaphore.h>
#include <stdlib.h>
#define CHAIRNUM 5
sem_t cus,bar; //sem
int empty_chair;
int working_status ;
int waiting_cus ;
pthread_mutex_t mutex;
void * Barber() {
printf("no cus, barber sleep\n");
while (1) {
sem_wait(&cus); //@@@@@@@@@@@@@@@@@@@
pthread_mutex_lock(&mutex);
empty_chair ++;
waiting_cus --;
pthread_mutex_unlock(&mutex);
working_status =1;
printf("working now....\n");
// waiting_cus --;
sleep(3);
printf("work done\n");
working_status =0;
sem_post(&bar); //@@@@@@@@@@@@@@@@@@@@@@@@
if (waiting_cus ==0) {
printf("no cus, barber sleep\n");
}
}
}
void * Customer (void* arg){
int *temp = (int *)arg;
int cus_no = *temp;
pthread_mutex_lock(&mutex);
if (empty_chair >0) {
empty_chair --;
// printf("%d 'st customer comes in\n", cus_no);
sem_post(&cus);
if(working_status ==0 && waiting_cus ==0) {
printf("%d 'st customer ,wake up barber\n", cus_no);
waiting_cus ++;
}
else {
printf("%d 'st customer waits, now %d is waiting\n", cus_no, ++waiting_cus);
// waiting_cus ++;
}
pthread_mutex_unlock(&mutex);
sem_wait(&bar);
}
else {
printf("%d 's customer leave for no seat\n", cus_no);
pthread_mutex_unlock(&mutex);
}
}
int main(int argc, const char * argv[]) {
sem_init(&cus, 0, 0);
sem_init(&bar, 0, 1);
empty_chair = CHAIRNUM;
working_status =0;
waiting_cus = 0;
pthread_t barber;
pthread_t customer[CHAIRNUM * 10];
pthread_mutex_init(&mutex, 0);
pthread_create(&barber, NULL, Barber, NULL);
for (int i=0; i<CHAIRNUM * 10; i++) {
sleep(1);
int temp_cus_id = i+1;
pthread_create(&customer[i], NULL, Customer, &temp_cus_id);
}
pthread_join(barber, NULL);
for (int i=0; i<CHAIRNUM * 10; i++) {
pthread_join(customer[i], NULL);
}
}
|
C
|
// Prevent Visual Studio Intellisense from defining _WIN32 and _MSC_VER when we use
// Visual Studio to edit Linux or Borland C++ code.
#ifdef __linux__
# undef _WIN32
#endif // __linux__
#if defined(__GNUC__) || defined(__BORLANDC__)
# undef _MSC_VER
#endif // defined(__GNUC__) || defined(__BORLANDC__)
#include "OSMisc.h"
int main(int argc, char* argv[])
{
char szFileInPath[256];
char szFileOutPath[256];
FILE* filein = NULL;
FILE* fileout = NULL;
char szTemp[256];
char szName[256];
char line[4096];
unsigned int i = 0;
double latitude = 0, longitude = 0;
struct tm ts;
double t = 0;
// Temporary buffers for sscanf().
double utc = 0, date = 0;
int latdeg = 0, longdeg = 0;
double latmin = 0, longmin = 0;
char szlatdeg[3];
char szlongdeg[4];
char north = 0, east = 0;
double sog = 0, cog = 0;
int year = 0, month = 0, day = 0, hour = 0, minute = 0;
double second = 0;
if (argc != 2)
{
strcpy(szFileInPath, "lognav.txt");
printf("Warning : No parameter specified.\n");
printf("Usage : NMEA2CSV_WRSC2016 file.txt.\n");
printf("Default : NMEA2CSV_WRSC2016 %.255s.\n", szFileInPath);
}
else
{
sprintf(szFileInPath, "%.249s", argv[1]);
}
strcpy(szTemp, szFileInPath);
RemoveExtensionInFilePath(szTemp);
sprintf(szFileOutPath, "%.249s_wrsc2016.csv", szTemp);
strcpy(szName, szTemp);
RemovePathInFilePath(szName);
printf("Check and change if needed\n\n");
printf("Control Panel\\Regional and Language Options\\Customize\\Numbers\n\n");
printf("if you do not know if you should use a '.' or a ',' in floating points numbers\n\n");
printf("or a ';' or ',' in list separators.\n\n");
filein = fopen(szFileInPath, "r");
if (filein == NULL)
{
printf("Unable to open NMEA file.\n");
#ifdef _DEBUG
fprintf(stdout, "Press ENTER to continue . . . ");
(void)getchar();
#endif // _DEBUG
return EXIT_FAILURE;
}
fileout = fopen(szFileOutPath, "w");
if (fileout == NULL)
{
printf("Unable to create CSV file.\n");
fclose(filein);
#ifdef _DEBUG
fprintf(stdout, "Press ENTER to continue . . . ");
(void)getchar();
#endif // _DEBUG
return EXIT_FAILURE;
}
printf("Converting...\n");
i = 0;
memset(line, 0, sizeof(line));
while (fgets(line, sizeof(line), filein) != NULL)
{
utc = 0;
//date = 0;
//t = 0;
memset(szlatdeg, 0, sizeof(szlatdeg));
memset(szlongdeg, 0, sizeof(szlongdeg));
if (sscanf(line, "$GPRMC,%lf,A,%c%c%lf,%c,%c%c%c%lf,%c,%lf,%lf,%lf", &utc,
&szlatdeg[0], &szlatdeg[1], &latmin, &north,
&szlongdeg[0], &szlongdeg[1], &szlongdeg[2], &longmin, &east,
&sog, &cog, &date) == 13)
{
if (utc > 0)
{
hour = (int)utc/10000;
minute = (int)utc/100-hour*100;
second = (utc-hour*10000)-minute*100;
}
if ((strlen(szlatdeg) > 0)&&(strlen(szlongdeg) > 0))
{
latdeg = atoi(szlatdeg);
longdeg = atoi(szlongdeg);
// Convert GPS latitude and longitude in decimal.
latitude = (north == 'N')?(latdeg+latmin/60.0):-(latdeg+latmin/60.0);
longitude = (east == 'E')?(longdeg+longmin/60.0):-(longdeg+longmin/60.0);
}
if (date > 0)
{
day = (int)date/10000;
month = (int)date/100-day*100;
year = 2000+((int)date-day*10000)-month*100;
}
if (utc > 0)
{
if (date > 0)
{
memset(&ts, 0, sizeof(ts));
ts.tm_year = year;
ts.tm_mon = month;
ts.tm_mday = day;
ts.tm_hour = hour;
ts.tm_min = minute;
ts.tm_sec = (int)second;
ts.tm_year-=1900; // Conversion...
ts.tm_mon--; // Conversion...
t = _mkgmtime(&ts)+(second-(int)second);
}
else
{
t = hour*3600+minute*60+second;
}
}
if ((utc > 0)&&(strlen(szlatdeg) > 0)&&(strlen(szlongdeg) > 0)&&(date > 0))
{
fprintf(fileout, "%02d%02d%02d%02d,%d,%d\n", ts.tm_hour, ts.tm_min, ts.tm_sec, ts.tm_mday, (int)(10000000*latitude), (int)(10000000*longitude));
i++;
}
}
else
{
//printf("Skipping an invalid line in the nmea file.\n");
}
memset(line, 0, sizeof(line));
}
printf("Found %u positions.\n", i);
if (fclose(fileout) != EXIT_SUCCESS)
{
printf("Error closing CSV file.\n");
#ifdef _DEBUG
fprintf(stdout, "Press ENTER to continue . . . ");
(void)getchar();
#endif // _DEBUG
return EXIT_FAILURE;
}
if (fclose(filein) != EXIT_SUCCESS)
{
printf("Error closing NMEA file.\n");
fclose(fileout);
#ifdef _DEBUG
fprintf(stdout, "Press ENTER to continue . . . ");
(void)getchar();
#endif // _DEBUG
return EXIT_FAILURE;
}
#ifdef _DEBUG
fprintf(stdout, "Press ENTER to continue . . . ");
(void)getchar();
#endif // _DEBUG
return EXIT_SUCCESS;
}
|
C
|
/*
snake.h
*/
#include <stdlib.h>
#include <stdio.h>
#include "SDL.h"
#define X_GRID_LENGTH 20
#define Y_GRID_LENGTH 20
#define BLOCK_SIZE 15
#define X_WINDOW_POS 200
#define Y_WINDOW_POS 50
void initialize_sdl_resources();
void initalize_game_state();
void generate_food();
void render_game_state();
void update_trajectory();
void detect_collisions();
void print_game_state();
struct snakeBlock *initializeHead();
struct snakeBlock *insertHead();
struct snakeBlock *removeTail();
int update_game_state();
int isSnakeBlock();
int poll_user_input();
int isDirection();
struct snakeBlock
{
struct snakeBlock *next;
short x;
short y;
short x_pix;
short y_pix;
};
struct gameState
{
int user_input;
unsigned char trajectory;
unsigned char food_collision;
unsigned char wall_collision;
struct foodBlock
{
short x;
short y;
short x_pix;
short y_pix;
}food;
struct snakeBlock *head;
struct snakeBlock *tail;
};
enum snakeTrajectories { RIGHT, UP, LEFT, DOWN };
|
C
|
#include "pebble_os.h"
#include "outlined_text.h"
void draw_outlined_text(GContext* ctx, char* text, GFont font, GRect rect, GTextOverflowMode mode, GTextAlignment alignment, int outline_pixels, bool inverted) {
(inverted) ? graphics_context_set_text_color(ctx, GColorBlack) :
graphics_context_set_text_color(ctx, GColorWhite);
GRect volatile_rect = rect;
for (int i=0; i<outline_pixels; i++) {
volatile_rect.origin.x+=1;
graphics_text_draw(ctx,
text,
font,
volatile_rect,
mode,
alignment,
NULL);
}
volatile_rect = rect;
for (int i=0; i<outline_pixels; i++) {
volatile_rect.origin.y+=1;
graphics_text_draw(ctx,
text,
font,
volatile_rect,
mode,
alignment,
NULL);
}
volatile_rect = rect;
for (int i=0; i<outline_pixels; i++) {
volatile_rect.origin.x-=1;
graphics_text_draw(ctx,
text,
font,
volatile_rect,
mode,
alignment,
NULL);
}
volatile_rect = rect;
for (int i=0; i<outline_pixels; i++) {
volatile_rect.origin.y-=1;
graphics_text_draw(ctx,
text,
font,
volatile_rect,
mode,
alignment,
NULL);
}
(inverted) ? graphics_context_set_text_color(ctx, GColorWhite) :
graphics_context_set_text_color(ctx, GColorBlack);
graphics_text_draw(ctx,
text,
font,
rect,
mode,
alignment,
NULL);
}
|
C
|
#include <cs50.h>
#include <stdio.h>
int main(void)
{
printf("How old are you? \n");
int age = GetInt();
if (age>20)
{
printf("You can drink!\n");
}
if (age>17)
{
printf("You can vote!\n");
}
if (age>15)
{
printf("You can drive!\n");
}
else
{
printf("Some day, kid...\n");
}
}
|
C
|
/**
* Display the current date and time in three formats
*/
#include <stdio.h>
#include <time.h>
int int main(int argc, char const *argv[]) {
/* 1. 获得日历时间 */
time_t current = time(NULL);
struct tm *ptr;
char date_time[21];
int hour;
char am_or_pm;
return 0;
}
|
C
|
/*
* triangulo.c
*
* Created on: 28 sept 2021
* Author: juanm
*/
#include <stdio.h>
#include <stdlib.h>
#include "utn_biblioteca.h"
#include "triangulo_estructura.h"
#include "triangulo.h"
int trianguloCarga(eTrianguloEscaleno* triangulo)
{
int retorno=-1;
if(triangulo!=NULL)
{
while(retorno==-1)
{
if(pedirFloatAUsuario(&triangulo->ladoUno, 0, 100.00, 2, "Por favor ingrese el lado uno: \n", "Error!")==0)
{
printf("Se cargo el primer lado\n");
retorno=0;
}
else
{
printf("No se pudo cargar el lado\n");
break;
}
if(pedirFloatAUsuario(&triangulo->ladoDos, 0, 100.00, 2, "Por favor ingrese el lado dos: \n", "Error!")==0)
{
printf("Se cargo el segundo lado\n");
retorno=0;
}
else
{
printf("No se pudo cargar el lado\n");
break;
}
if(pedirFloatAUsuario(&triangulo->ladoTres, 0, 100.00, 2, "Por favor ingrese el lado tres: \n", "Error!")==0)
{
printf("Se cargo el tercer lado\n");
retorno=0;
}
else
{
printf("No se pudo cargar el lado\n");
break;
}
}
retorno=0; // solo si se cargan todos los lados bien retornamos 0
}
else
{
retorno=-1;
}
return retorno;
}
void trianguloMostrarPorValor(eTrianguloEscaleno triangulo)
{
printf("Lado uno: %f\nLado dos: %f\nLado tres: %f\n", triangulo.ladoUno,triangulo.ladoDos,triangulo.ladoTres);
}
void trianguloMostrarPorReferencia(eTrianguloEscaleno* triangulo)
{
printf("Lado uno: %f\nLado dos: %f\nLado tres: %f\n", triangulo->ladoUno,triangulo->ladoDos,triangulo->ladoTres);
}
|
C
|
/*++
Copyright (c) 1997 Microsoft Corporation
Module Name:
trie.c
Abstract:
Contains wrapper routines around the
fast & slow IP route lookup schemes
Author:
Chaitanya Kodeboyina (chaitk) 26-Nov-1997
Revision History:
--*/
#include "precomp.h"
#include "strie.h"
#include "ftrie.h"
UINT
CreateTrie(IN ULONG levels,
IN ULONG flags,
IN ULONG maxSTMemory,
IN ULONG maxFTMemory,
OUT Trie ** ppTrie)
/*++
Routine Description:
Initializes S-Trie(Slow Trie) and F-Trie(Fast Trie)
components in the trie [ wrapper structure ].
The Slow Trie component keeps all the routes, while
the Fast Trie keeps only a pointer the destination
that holds the list of all routes to the IP address
of the destination network and cache of best routes.
The flags parameter determines the trie's behavior,
and among other things if we are using a fast trie.
A fast trie (which is a fast copy of the slow trie)
enables faster route lookup, but needs more memory.
Arguments:
pTrie - Pointer to the trie to be initialized
levels - Bitmap of expanded levels in the F-Trie
flags - Flags that determine trie's behaviour
maxSTMemory - Limit on memory taken by the S-Trie
maxFTMemory - Limit on memory taken by the F-Trie
Return Value:
TRIE_SUCCESS or ERROR_TRIE_*
--*/
{
Trie *pTrie;
UINT nBytes;
UINT initStatus;
// Allocate memory for the tries
nBytes = sizeof(Trie) + sizeof(STrie);
if (flags & TFLAG_FAST_TRIE_ENABLED) {
nBytes += sizeof(FTrie);
}
*ppTrie = AllocMemory0(nBytes);
if (*ppTrie == NULL) {
return (UINT) ERROR_TRIE_RESOURCES;
}
pTrie = *ppTrie;
// Initialize the behavior flags
pTrie->flags = flags;
// Initialize the trie pointers
pTrie->sTrie = (STrie *) ((UCHAR *) pTrie +
sizeof(Trie));
pTrie->fTrie = NULL;
if (flags & TFLAG_FAST_TRIE_ENABLED) {
pTrie->fTrie = (FTrie *) ((UCHAR *) pTrie +
sizeof(Trie) +
sizeof(STrie));
}
// Initialize the Slow Component
if ((initStatus = InitSTrie(pTrie->sTrie,
maxSTMemory)) != TRIE_SUCCESS) {
} else if (!(flags & TFLAG_FAST_TRIE_ENABLED)) {
// Are we using the fast trie ?
return TRIE_SUCCESS;
} else if ((initStatus = InitFTrie(pTrie->fTrie,
levels,
maxFTMemory)) != TRIE_SUCCESS) {
// Initialize the Fast Component
} else {
return TRIE_SUCCESS;
}
// An error occurred - Clean up
// Clean up slow component
if (CleanupSTrie(pTrie->sTrie) != TRIE_SUCCESS)
return initStatus;
// Do we have a fast trie ?
if (!(pTrie->flags & TFLAG_FAST_TRIE_ENABLED))
return initStatus;
// Clean up fast component
if (CleanupFTrie(pTrie->fTrie) != TRIE_SUCCESS)
return initStatus;
// Zero the flags to be safe
pTrie->flags = 0;
return initStatus;
}
VOID
DestroyTrie(IN Trie * pTrie,
OUT UINT * status)
/*++
Routine Description:
Cleans up a trie if it is empty.
Arguments:
pTrie - Pointer to the trie
status - The Cleanup status
Return Value:
TRIE_SUCCESS or ERROR_TRIE_*
--*/
{
// Clean up slow component
if ((*status = CleanupSTrie(pTrie->sTrie)) != TRIE_SUCCESS)
return;
// Do we have a fast trie
if (!(pTrie->flags & TFLAG_FAST_TRIE_ENABLED))
return;
// Clean up fast component
if ((*status = CleanupFTrie(pTrie->fTrie)) != TRIE_SUCCESS)
return;
// Deallocate the trie memory
FreeMemory0(pTrie);
}
UINT
CALLCONV
InsertIntoTrie(IN Trie * pTrie,
IN Route * pIncRoute,
IN ULONG matchFlags,
OUT Route ** ppInsRoute,
OUT Route ** ppOldBestRoute,
OUT Route ** ppNewBestRoute)
/*++
Routine Description:
Inserts a route corresponding to an address
prefix into the slow trie. If this is a new
address prefix, then the corresponding dest
is added to the FTrie (if it is being used).
Arguments:
pTrie - Pointer to the Trie to insert into
pIncRoute - Pointer to the incoming route
matchFlags - Flags to direct route matching
ppInsRoute - Pointer to the route inserted
ppOldBestRoute - Best route before insertion
ppNewBestRoute - Best route after insertion
Return Value:
TRIE_SUCCESS or ERROR_TRIE_*
--*/
{
Dest *pOldBestDest;
Dest *pNewBestDest;
UINT retVal;
*ppOldBestRoute = *ppNewBestRoute = *ppInsRoute = NULL;
pOldBestDest = pNewBestDest = NULL;
// Insert into the slow trie
if ((retVal = InsertIntoSTrie(pTrie->sTrie,
pIncRoute,
matchFlags,
ppInsRoute,
&pOldBestDest,
&pNewBestDest,
ppOldBestRoute)) == TRIE_SUCCESS) {
// Insertion successful - return new route
*ppNewBestRoute = pNewBestDest->firstRoute;
#if _DBG_
Print("\n@ pInsRTE = %08x\n@ pOldBestRTE = %08x\n@ pOldBestDest = %08x\n@ pNewBestDest = %08x\n",
*ppInsRoute, *ppOldBestRoute, pOldBestDest, pNewBestDest);
#endif
// Are we using a fast trie ?
if (pTrie->flags & TFLAG_FAST_TRIE_ENABLED) {
// Did we have a new destination ?
if (pOldBestDest != pNewBestDest) {
// Tweak the fast trie
if ((InsertIntoFTrie(pTrie->fTrie,
*ppInsRoute,
pNewBestDest,
pOldBestDest)) != TRIE_SUCCESS) {
// Not enough memory in F-Trie
// Switch back to the S-Trie
pTrie->flags &= ~TFLAG_FAST_TRIE_ENABLED;
// And clean up the fast trie
CleanupFTrie(pTrie->fTrie);
return retVal;
}
}
}
}
return retVal;
}
UINT
CALLCONV
DeleteFromTrie(IN Trie * pTrie,
IN Route * pIncRoute,
IN ULONG matchFlags,
OUT Route ** ppDelRoute,
OUT Route ** ppOldBestRoute,
OUT Route ** ppNewBestRoute)
/*++
Routine Description:
Deletes a route corresponding to an address
prefix into the S-trie. If this is the last
route on dest, then dest is freed and it is
replaced in the F-Trie by the next best dest.
The route deleted is returned to the caller,
who is responsible for freeing its memory.
Arguments:
pTrie - Pointer to trie to delete from
pIncRoute - Pointer to the incoming route
matchFlags - Flags to direct route matching
ppDelRoute - Pointer to the route deleted
ppOldBestRoute - Best route before deletion
ppNewBestRoute - Best route after deletion
Return Value:
TRIE_SUCCESS or ERROR_TRIE_*
--*/
{
Dest *pOldBestDest;
Dest *pNewBestDest;
UINT retVal;
*ppDelRoute = *ppOldBestRoute = *ppNewBestRoute = NULL;
pOldBestDest = pNewBestDest = NULL;
// Delete from slow trie
if ((retVal = DeleteFromSTrie(pTrie->sTrie,
pIncRoute,
matchFlags,
ppDelRoute,
&pOldBestDest,
&pNewBestDest,
ppOldBestRoute)) == TRIE_SUCCESS) {
// Deletion successful - return new route
*ppNewBestRoute = pNewBestDest ? pNewBestDest->firstRoute : NULL;
#if _DBG_
Print("\n@ pDelRTE = %08x\n@ pOldBestRTE = %08x\n@ pOldBestDest = %08x\n@ pNewBestDest = %08x\n",
*ppDelRoute, *ppOldBestRoute, pOldBestDest, pNewBestDest);
#endif
// Are we using a fast trie ?
if (pTrie->flags & TFLAG_FAST_TRIE_ENABLED) {
// Was deleted route last one on dest ?
if (pOldBestDest != pNewBestDest) {
// Tweak the fast trie
retVal = DeleteFromFTrie(pTrie->fTrie,
*ppDelRoute,
pOldBestDest,
pNewBestDest,
NORMAL);
// Operation cannot fail
Assert(retVal == TRIE_SUCCESS);
}
}
// Reclaim route's memory - in the caller
// FreeRouteInSTrie(pTrie->sTrie, *ppDelRoute);
}
return retVal;
}
#if DBG
Dest *
SearchAddrInTrie(IN Trie * pTrie,
IN ULONG Addr)
/*++
Routine Description:
Search for an address in a trie
Arguments:
pTrie - Pointer to the trie to search
Addr - Pointer to addr being queried
Return Value:
Return best dest match for this address
--*/
{
Dest *pBestDest1, *pBestDest2;
#if _DBG_
// Just pretend that you are searching just one trie
if (pTrie->flags & TFLAG_FAST_TRIE_ENABLED)
Print("Looking up fast trie for %08x\n", Addr);
else
Print("Looking up slow trie for %08x\n", Addr);
#endif
pBestDest1 = SearchAddrInSTrie(pTrie->sTrie, Addr);
// Make sure that the S-Trie and F-Trie are consistent
if (pTrie->flags & TFLAG_FAST_TRIE_ENABLED) {
pBestDest2 = SearchAddrInFTrie(pTrie->fTrie, Addr);
Assert(pBestDest1 == pBestDest2);
}
// Return best dest returned (same by both operations)
return pBestDest1;
}
#else // DBG
#define SearchAddrInTrie(_pTrie_, _Addr_) \
(((_pTrie_)->flags & TFLAG_FAST_TRIE_ENABLED) \
? SearchAddrInFTrie((_pTrie_)->fTrie, _Addr_) \
: SearchAddrInSTrie((_pTrie_)->sTrie, _Addr_)) \
#endif // DBG
#if DBG
VOID
PrintTrie(IN Trie * pTrie,
IN UINT flags)
/*++
Routine Description:
Prints a trie to the console
Arguments:
pTrie - Pointer to the trie
Return Value:
None
--*/
{
// Print the Slow Trie
if (flags & SLOW)
PrintSTrie(pTrie->sTrie, flags & FULL);
// Is fast trie enabled
if (!(pTrie->flags & TFLAG_FAST_TRIE_ENABLED))
return;
// Print the Fast Trie
if (flags & FAST)
PrintFTrie(pTrie->fTrie, flags & FULL);
}
//
// Miscellaneous Helper Functions
//
VOID
PrintDest(IN Dest * dest)
{
Route *route;
UINT i;
if (NULL_DEST(dest)) {
Print("NULL dest\n");
} else {
route = dest->firstRoute;
Print("Dest: ");
PrintIPAddr(&DEST(route));
Print("/ %2d, Metric = %3lu\n", LEN(route), METRIC(route));
Print("Best Routes: \n");
for (i = 0; i < dest->numBestRoutes; i++) {
route = dest->bestRoutes[i];
Print("Route %d @ %p: ", i, route);
if (NULL_ROUTE(route)) {
Print("NULL Route\n");
} else {
Print("NHop = ");
PrintIPAddr(&NHOP(route));
Print(", IF = %08x\n", IF(route));
}
}
Print("\n");
}
}
VOID
PrintRoute(IN Route * route)
{
Print("Route: Len = %2d", LEN(route));
Print(", Addr = ");
PrintIPAddr(&DEST(route));
Print(", ");
Print("NHop = ");
PrintIPAddr(&NHOP(route));
Print(", IF = %08x", IF(route));
Print(", Metric = %3lu\n", METRIC(route));
}
VOID
PrintIPAddr(IN ULONG * addr)
{
UCHAR *addrBytes = (UCHAR *) addr;
UINT i;
if (addrBytes) {
for (i = 0; i < 4; i++) {
Print("%3d.", addrBytes[i]);
}
Print(" ");
} else {
Print("NULL Addr ");
}
}
#endif // DBG
|
C
|
#include "stdio.h"
#include "malloc.h"
#include "stdlib.h"
#include "stdbool.h"
struct Node{
int data;
struct Node *firstChild;
struct Node *nextSibling;
struct Node *parent;
bool isLocked;
int noOfLockedDecendent;
int operation;
};
bool lock(struct Node *node);
bool unLock(struct Node *node);
void addChild(int data,struct Node *parent);
struct Node *createNode(int,struct Node *);
struct Node *searchAddress(int data,struct Node *root);
void preOrderDisplay(struct Node *root);
int main(){
struct Node *root,*parent,*temp;
int data,c;
printf("/nEnter the first element: ");
scanf("%d",&data);
root=createNode(data,NULL);
parent=searchAddress(1,root);
addChild(2,parent);
addChild(3,parent);
addChild(4,parent);
addChild(5,parent);
parent=searchAddress(2,root);
addChild(6,parent);
addChild(7,parent);
parent=searchAddress(3,root);
addChild(8,parent);
addChild(9,parent);
parent=searchAddress(4,root);
addChild(10,parent);
parent=searchAddress(5,root);
addChild(11,parent);
addChild(12,parent);
while(1){
printf("\n1.Add Child\n2. Display\n3. Search\n4. To Lock\n5. To UnLock\nEnter choice: ");
scanf("%d",&c);
switch(c){
case 1:{
//printf("\nTo which node do you want to add: ");
//scanf("%d",&data);
//parent=searchAddress(data,root);
//if(parent==NULL){
// printf("\nNo Node found");
//}
//else{
// printf("\nEnter the Data: ");
// scanf("%d",&data);
//}
break;
}
case 2:{
preOrderDisplay(root);
break;
}
case 3:{
printf("\nTo which node do you want to search: ");
scanf("%d",&data);
parent=searchAddress(data,root);
printf("\nAddress=%d\nData=%d",parent,parent->data);
break;
}
case 4:{
printf("\nTo which node do you want to Lock: ");
scanf("%d",&data);
temp=searchAddress(data,root);
if(lock(temp)){
printf("\nTrue");
}else{
printf("\nFalse");
}
break;
}
case 5:{
printf("\nTo which node do you want to Lock: ");
scanf("%d",&data);
temp=searchAddress(data,root);
if(unLock(temp)){
printf("\nTrue");
}else{
printf("\nFalse");
}
break;
}
}
}
}
void addChild(int data,struct Node *parent){
struct Node *node=createNode(data,parent),*start;
if(parent->firstChild==NULL){
parent->firstChild=node;
}
else{
start=parent->firstChild;
while(start->nextSibling!=NULL){
start=start->nextSibling;
}
start->nextSibling=node;
}
}
struct Node *createNode(int data,struct Node *parent){
struct Node *node;
node=(struct Node *)malloc(sizeof(struct Node));
node->data=data;
node->firstChild=NULL;
node->nextSibling=NULL;
node->parent=parent;
node->isLocked=false;
node->noOfLockedDecendent=0;
node->operation=0;
return node;
}
void preOrderDisplay(struct Node *root){
printf("%d ",root->data);
if(root->firstChild!=NULL)
preOrderDisplay(root->firstChild);
if(root->nextSibling!=NULL)
preOrderDisplay(root->nextSibling);
}
struct Node *searchAddress(int data,struct Node *root){
struct Node *temp;
if(root==NULL)
return NULL;
if(data==root->data)
return root;
temp=searchAddress(data,root->firstChild);
if(temp!=NULL)
return temp;
temp=searchAddress(data,root->nextSibling);
return temp;
}
bool unLock(struct Node *node){
struct Node *temp=node;
if(temp->isLocked==false){//to check if it was locked or not
return false;
}
node->isLocked=false;//unlocking it
temp=node->parent;
while(temp!=NULL){
temp->noOfLockedDecendent--;
temp=temp->parent;
}//a loop traversing node's parents decrementing the number of locked decendent of its ancestor by 1 since it is unlocked now
return true;
}
bool lock(struct Node *node){
struct Node *temp;
if(node->isLocked==true){//to check if it was locked or not
return false;
}
node->operation+=1;
node->isLocked=true;//locking the node
temp=node->parent;
while(temp!=NULL){
temp->noOfLockedDecendent++;
temp=temp->parent;
}// a loop traversing its parents incrementing the number of locked decendent of its ancestor by 1 since it is locked now
if(node->noOfLockedDecendent>0){
unLock(node);
node->operation-=1;
return false;
}
temp=node->parent;
while(temp!=NULL){
if(temp->isLocked==true){
unLock(node);
node->operation-=1;
return false;
}
temp=temp->parent;
}
if(node->operation!=1){
temp=node->parent;
while(temp!=NULL){
temp->noOfLockedDecendent--;
temp=temp->parent;
}
node->operation-=1;
return false;
}
node->operation-=1;
return true;
}
|
C
|
#include "pohoncalc.h"
#include <stdio.h>
/* *** Konstruktor *** */
BinTree Tree(infotype Akar, BinTree L, BinTree R, BinTree P){
BinTree T;
T = AlokNode(Akar);
if(T != Nil){
Left(T) = L;
Right(T) = R;
Parent(T) = P;
return T;
}
else{
return Nil;
}
}
/* Menghasilkan sebuah pohon biner dari A, L, dan R, jika alokasi berhasil */
/* Menghasilkan pohon kosong (Nil) jika alokasi gagal */
void MakeTree(infotype Akar, BinTree L, BinTree R, BinTree P, BinTree *T){
*T = Tree(Akar,L,R,P);
}
/* I.S. Akar, L, R terdefinisi. P Sembarang */
/* F.S. Membentuk pohon P dengan Akar(P)=Akar, Left(P)=L, dan Right(P)=R
jika alokasi berhasil. P = Nil jika alokasi gagal. */
/* Manajemen Memory */
addrNode AlokNode(infotype X){
BinTree T;
T = (addrNode) malloc (sizeof(Node));
if(T != Nil){
Akar(T) = X;
Left(T) = Nil;
Right(T) = Nil;
Parent(T) = Nil;
return T;
}
else{
return Nil;
}
}
/* Mengirimkan addrNode hasil alokasi sebuah elemen */
/* Jika alokasi berhasil, maka addrNode tidak Nil, dan misalnya menghasilkan P,
maka Akar(P) = X, Left(P) = Nil, Right(P)=Nil */
/* Jika alokasi gagal, mengirimkan Nil */
void DealokNode(addrNode P){
free(P);
}
/* I.S. P terdefinisi */
/* F.S. P dikembalikan ke sistem */
/* Melakukan dealokasi/pengembalian addrNode P */
/* *** Predikat-Predikat Penting *** */
bool IsTreeEmpty(BinTree P){
return(P == Nil);
}
/* Mengirimkan true jika P adalah pohon biner kosong */
bool IsTreeOneElmt(BinTree P){
return((Right(P) == Nil) && (Left(P) == Nil));
}
/* Mengirimkan true jika P adalah pohon biner tidak kosong dan hanya memiliki 1 elemen */
bool IsUnerLeft(BinTree P){
return((Right(P) == Nil) && (Left(P) != Nil));
}
/* Mengirimkan true jika pohon biner tidak kosong P adalah pohon unerleft: hanya mempunyai subpohon kiri */
bool IsUnerRight(BinTree P){
return((Right(P) != Nil) && (Left(P) == Nil));
}
/* Mengirimkan true jika pohon biner tidak kosong P adalah pohon unerright: hanya mempunyai subpohon kanan*/
bool IsBiner(BinTree P){
return((Right(P) != Nil) && (Left(P) != Nil));
}
/* Mengirimkan true jika pohon biner tidak kosong P adalah pohon biner: mempunyai subpohon kiri dan subpohon kanan*/
/* *** Operasi lain *** */
void ChangeAkar(BinTree *P, infotype X, bool kiri){
addrNode M;
M = AlokNode(X);
if (*P != Nil){
if (kiri) {
Left(M) = *P;
}
else {
Right(M) = *P;
}
Parent(M) = Parent(*P);
Parent(*P) = M;
if (Parent(M) != Nil) {
if (Left(Parent(M)) == *P) {
Left(Parent(M)) = M;
}
else {
Right(Parent(M)) = M;
}
}
}
*P = M;
}
void AddDaun(BinTree *P, infotype X, bool Kiri){
addrNode M;
M = AlokNode(X);
if(IsTreeEmpty(*P)){
*P = M;
}
else{
if(Kiri){
Left(M) = Left(*P);
if(Left(M) != Nil){
Parent(Left(*P)) = M;
}
Left(*P) = M;
}
else{
Left(M) = Right(*P);
if(Left(M) != Nil){
Parent(Right(*P)) = M;
}
Right(*P) = M;
}
Parent(M) = *P;
}
}
/* I.S. P tidak kosong, X adalah salah satu daun Pohon Biner P */
/* F.S. P bertambah simpulnya, dengan Y sebagai anak kiri X (jika Kiri = true), atau
sebagai anak Kanan X (jika Kiri = false) */
/* Jika ada > 1 daun bernilai X, diambil daun yang paling kiri */
void PrintTree (BinTree T) {
if (IsTreeEmpty(T)) {
printf("[]");
}
else {
printf("[%.2f(%c)", (Akar(T)).value, (Akar(T)).operand);
PrintTree(Left(T));
printf(" ");
PrintTree(Right(T));
printf("]");
}
}
/* I.S. P terdefinisi */
/* F.S. Semua simpul P sudah dicetak secara preorder: akar, pohon kiri, dan pohon
kanan. Setiap pohon ditandai dengan tanda kurung buka dan kurung tutup (). */
/* Contoh: (a (b (d () ()) ()) (c () ())) */
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <locale.h>
#include <unistd.h>
#include "vendas.h"
#include "menu.h"
void imprimeVendas(TVendas Vendas){
limpezaDoBuffer();
printf("\nCodigo do produto comprado: ");
printf("%d\n", Vendas.codigo);
printf("\nCLiente: ");
printf("%s\n", Vendas.ID);
printf("Data da realização da venda: ");
printf("%d / %d / %d\n", Vendas.dataDaVenda.dia,
Vendas.dataDaVenda.mes, Vendas.dataDaVenda.ano);
if(Vendas.tipoDePagamento == 1)
printf("Tipo de pagamento: Á VISTA\n");
if (Vendas.tipoDePagamento == 2){
printf("Tipo de pagamento: Á PRAZO\n");
printf("Prazo para pagamento: ");
printf("%d/ %d/ %d\n", Vendas.prazoParaPagamento.dia,
Vendas.prazoParaPagamento.mes, Vendas.prazoParaPagamento.ano);
}
printf("Quantidade da venda: ");
printf("%d", Vendas.quantidadeDeVendas);
printf("\n Preço da venda: ");
printf("%f", Vendas.precoDaVenda);
printf("------------------------------------------\n");
printf("PRESSIONE ENTER PARA CONTINUAR!!!!");
getchar();
}
int lerVendas(TVendas *Vendas,ModuloClientes* ModuloClientes, ModuloProdutos *ModuloProdutos){
limparConsole();
printf("-------------------------------------------\n");
printf("--------***EFETUAR VENDA***-------------\n");
TCliente cliente;
TProdutos produto;
int indiceProduto;
int indiceCliente;
int feedbackCliente;
int feedbackProduto;
printf("Digite o CPF/CNPJ do cliente: ");
limpezaDoBuffer();
fgets(cliente.ID, TAM, stdin);
formatador(cliente.ID);
feedbackCliente = pesquisarCliente(*ModuloClientes, cliente);
if(feedbackCliente == -1){
limparConsole();
limpezaDoBuffer();
printf("Cliente não encontrado, saindo...\n");
printf("PRESSIONE ENTER PARA CONTINUAR\n");
getchar();
return -1;
}
printf("Digite o código do produto: ");
limpezaDoBuffer();
scanf("%d", &produto.codigoDoProd);
feedbackProduto = pesquisarProduto(*ModuloProdutos, produto);
if(feedbackProduto == -1){
limparConsole();
limpezaDoBuffer();
printf("Produto não encontrado, saindo...\n");
printf("PRESSIONE ENTER PARA CONTINUAR\n");
getchar();
return -1;
}
if(ModuloProdutos->listaDeProdutos[feedbackProduto].quantidadeProd == 0){
limparConsole();
limpezaDoBuffer();
printf("produto em falta! Impossivel concluír venda!!\n");
printf("PRESSIONE ENTER PARA CONTINUAR\n");
getchar();
return -1;
}
Vendas->codigo = produto.codigoDoProd;
strcpy(Vendas->ID, cliente.ID );
printf("Digite a data da realização da venda: \n");
printf("DIA: ");
scanf("%d", &Vendas->dataDaVenda.dia);
printf("MÊS: ");
scanf("%d", &Vendas->dataDaVenda.mes);
printf("ANO: ");
scanf("%d", &Vendas->dataDaVenda.ano);
printf("Digite o tipo de pagamento: 1 - vista 2- prazo \n");
scanf("%d", &Vendas->tipoDePagamento);
if(Vendas->tipoDePagamento == 2){
printf("----------Á PRAZO-------------\n");
printf("Digite o prazo da compra da compra: \n");
printf("DIA: ");
scanf("%d", &Vendas->prazoParaPagamento.dia);
printf("MÊS: ");
scanf("%d", &Vendas->prazoParaPagamento.mes);
printf("ANO: ");
scanf("%d", &Vendas->prazoParaPagamento.ano);
Vendas->tipoDePagamento = 2;
ModuloClientes->listaDeClientes[feedbackCliente].debitoRegistrado = 1;
}
if(Vendas->tipoDePagamento == 1){
printf("----------Á VISTA-------------\n");
Vendas->tipoDePagamento = 1;
}
printf("Digite a quantidade de produtos que deseja comprar: \n");
scanf("%d", &Vendas->quantidadeDeVendas);
ModuloProdutos->listaDeProdutos[feedbackProduto].quantidadeProd--;
Vendas->precoDaVenda=ModuloProdutos->listaDeProdutos[feedbackProduto].precoUnit * Vendas->quantidadeDeVendas;
return 0;
limparConsole();
}
void iniciarModuloVendas(ModuloVendas *ModuloVendas){
ModuloVendas->indice = 0;
}
void inserirVendas(ModuloVendas *ModuloVendas, TVendas Vendas){
if(ModuloVendas->indice < TAM){
ModuloVendas->vendasRealizadas[ModuloVendas->indice] = Vendas;
ModuloVendas->indice++;
}
}
int pesquisarVendas(ModuloVendas ModuloVendas, ModuloProdutos ModuloProdutos, ModuloClientes ModuloClientes,
TCliente Cliente, TProdutos Produtos){
int respostaCliente = pesquisarCliente(ModuloClientes, Cliente);
if( respostaCliente == -1){
printf("Cliente não encontrado\n");
return -1;
}
int respostaProdutos = pesquisarProduto(ModuloProdutos, Produtos);
if( respostaProdutos == -1){
printf("Produto não encontrado\n");
return -1;
}
for ( int i = 0; i < ModuloVendas.indice; i++){
if((strncmp(Cliente.ID, ModuloVendas.vendasRealizadas[i].ID, TAM) == 0)
&& ModuloVendas.vendasRealizadas[i].codigo == Produtos.codigoDoProd){
printf("Venda encontrada");
return i;
}
}
printf("Venda não encontrada");
return -1;
}
void imprimirTodasAsVendas(ModuloVendas Vendas){
limparConsole();
printf("Vendas: \n");
for(int i = 0; i < Vendas.indice; i++){
imprimeVendas(Vendas.vendasRealizadas[i]);
}
limpezaDoBuffer();
}
void alterarVenda(ModuloVendas* ModuloVendas, ModuloProdutos* ModuloProdutos, ModuloClientes* ModuloCliente, TCliente cliente,
TProdutos produtos){
limparConsole();
int respostaVendas = pesquisarVendas(*ModuloVendas, *ModuloProdutos, *ModuloCliente, cliente, produtos);
int respostaProdutos = pesquisarProduto(*ModuloProdutos, produtos);
int respostaClientes = pesquisarCliente(*ModuloCliente, cliente);
ModuloProdutos->listaDeProdutos[respostaProdutos].quantidadeProd++;
ModuloCliente->listaDeClientes[respostaClientes].debitoRegistrado == 0;
lerVendas(&ModuloVendas->vendasRealizadas[respostaVendas], ModuloCliente, ModuloProdutos);
imprimeVendas(ModuloVendas->vendasRealizadas[respostaVendas]);
}
void excluirVendas(ModuloVendas* ModuloVendas, ModuloClientes* ModuloClientes, ModuloProdutos* Produtos, TCliente cliente,
TProdutos produtos){
int resposta = pesquisarVendas(*ModuloVendas, *Produtos, *ModuloClientes, cliente, produtos);
for (int j = resposta; j < ModuloVendas->indice ; j++) {
ModuloVendas->vendasRealizadas[j] = ModuloVendas->vendasRealizadas[j + 1];
}
int respostaProdutos = pesquisarProduto(*Produtos, produtos);
int respostaClientes = pesquisarCliente(*ModuloClientes, cliente);
Produtos->listaDeProdutos[respostaProdutos].quantidadeProd++;
ModuloClientes->listaDeClientes[respostaClientes].debitoRegistrado == 0;
ModuloVendas->indice--;
printf("Venda excluída com sucesso! \n");
limpezaDoBuffer();
printf("PRESSIONE ENTER PARA CONTINUAR\n");
getchar();
}
|
C
|
#pragma once
#include <stdio.h>
#define MAX_VERTICES 5
#define INF 1000L
// ġ ܼ 2 迭
int weight[MAX_VERTICES][MAX_VERTICES] = {
{ 0, 16, INF, 25, INF },
{ 16, 0, 29, INF, INF },
{ INF, 29, 0, 12, 17 },
{ 25, INF, 12, 0, 22 },
{ INF, INF, 17, 22, 0 }
};
int selected[MAX_VERTICES]; //
int dist[MAX_VERTICES]; // Ʈ - ġ
//ּ dist ȯ
int get_min_vertex(int n) {
int v, i;
for (i = 0; i < n; i++) {
if (!selected[i]) { // 'ӽ'
v = i;
break;
}
}
for (i = 0; i < n; i++) {
if (!selected[i] && (dist[i] < dist[v])) v = i; // , ռ ϴ ӽ õ dist ӽ ü
}
return (v);
}
//s = , n =
void prim(int s, int n) {
int i, u, v;
//ʱȭ, dist INF(ǻ Ѵ, ſ ū )
for (u = 0; u < n; u++) {
dist[u] = INF; selected[u] = 0;
}
dist[s] = 0; //
for (i = 0; i < n; i++) { // ã
u = get_min_vertex(n); //ּ dist ȯ (= )
selected[u] = 1; // õǷ ߴٰ ǥ
if (dist[u] == INF) return; //
printf("%d ", u);
for (v = 0; v < n; v++) { // - ġ Ͽ dist üִ
if (weight[u][v] != INF) //ġ INF ƴϰ (= ϰ)
if (!selected[v] && weight[u][v] < dist[v]) //õ ʾҰ, ġ Ÿ ª
dist[v] = weight[u][v]; // dist ش
}
}
}
|
C
|
#include <stdlib.h> //rand, srand
#include <time.h> //time
#include <stdio.h>
int rambo(int min, int max);
int rambo(int min, int max){
return rand() % (max - min + 1) + min;
}
int main(){
srand((unsigned) time(NULL));
int qtd = 10;
while(qtd--)
printf("%d ", rambo(4, 7));
puts("");
}
|
C
|
#include<stdio.h>
void main()
{
int a=10;
int *p=&a;
float b=20;
float *q=&b;
void *ptr;
ptr=&a;
// ptr=&b;
printf("%p %p %p\n",p,q,ptr);
printf("%d %d\n",*p,*(int *)ptr);
printf("%f %f\n",*q,*(float *)ptr);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main() {
int n,i,j,old;
int *v;
scanf("%d",&n);
v=(int *) malloc(n*sizeof(int));
if (v==NULL) exit(-1);
for(i=0;i<n;i++) {
old=0;
for(j=0;j<i;j++) {
int k;
k=v[j];
v[j]=(old+v[j])%2;
old=k;
if (v[j]) printf("*"); else printf(".");
}
v[i]=1;
printf("*\n");
}
free(v);
return (0);
}
|
C
|
/*
* AD5252.c
*
* Created on: 12.02.2018
* Author: Erich Styger Local
*/
#include "Platform.h"
#include "AD5252.h"
#include "GI2C1.h"
#include "CLS1.h"
#include "UTIL1.h"
#define AD5252_I2C_ADDR 0b0101100 /* S01011xx */
#define AD5252_I2C_CMD (1<<7)
#define AD5252_I2C_REG (0<<7)
#define AD5252_I2C_EE (1<<5)
#define AD5252_I2C_RDAC (0<<5)
uint8_t AD5252_ReadEEMEMReg(AD5252_EEMEM_REG reg, uint8_t *val) {
uint8_t addr;
addr = reg | AD5252_I2C_REG | AD5252_I2C_EE;
*val = 0; /* init */
return GI2C1_ReadAddress(AD5252_I2C_ADDR, &addr, sizeof(addr), val, sizeof(uint8_t));
}
uint8_t AD5252_ReadRDACReg(AD5252_RDAC_REG reg, uint8_t *val) {
uint8_t addr;
addr = reg | AD5252_I2C_REG | AD5252_I2C_RDAC;
*val = 0; /* init */
return GI2C1_ReadAddress(AD5252_I2C_ADDR, &addr, sizeof(addr), val, sizeof(uint8_t));
}
uint8_t AD5252_WriteRDACReg(AD5252_RDAC_REG reg, uint8_t val) {
uint8_t addr;
addr = reg | AD5252_I2C_REG | AD5252_I2C_RDAC;
return GI2C1_WriteAddress(AD5252_I2C_ADDR, &addr, sizeof(addr), &val, sizeof(val));
}
uint8_t AD5252_WriteEEMEMReg(AD5252_EEMEM_REG reg, uint8_t val) {
uint8_t addr;
addr = reg | AD5252_I2C_REG | AD5252_I2C_EE;
return GI2C1_WriteAddress(AD5252_I2C_ADDR, &addr, sizeof(addr), &val, sizeof(val));
}
static uint8_t PrintHelp(const CLS1_StdIOType *io) {
CLS1_SendHelpStr((unsigned char*)"ad5252", (unsigned char*)"Group of ad5252 commands\r\n", io->stdOut);
CLS1_SendHelpStr((unsigned char*)" write rdac1|rdac3 <val>", (unsigned char*)"Write value to RDAC1 or RDAC3 register\r\n", io->stdOut);
CLS1_SendHelpStr((unsigned char*)" help|status", (unsigned char*)"Print help or status information\r\n", io->stdOut);
return ERR_OK;
}
static uint8_t PrintStatus(const CLS1_StdIOType *io) {
uint8_t buf[32];
uint8_t res, val;
CLS1_SendStatusStr((unsigned char*)"ad5252", (unsigned char*)"\r\n", io->stdOut);
res = AD5252_ReadRDACReg(AD5252_RDAC1, &val);
if (res==ERR_OK) {
UTIL1_Num8uToStr(buf, sizeof(buf), val);
UTIL1_strcat(buf, sizeof(buf), "\n");
} else {
UTIL1_strcpy(buf, sizeof(buf), "ERROR\n");
}
CLS1_SendStatusStr((unsigned char*)" RDAC1", buf, io->stdOut);
res = AD5252_ReadRDACReg(AD5252_RDAC3, &val);
if (res==ERR_OK) {
UTIL1_Num8uToStr(buf, sizeof(buf), val);
UTIL1_strcat(buf, sizeof(buf), "\n");
} else {
UTIL1_strcpy(buf, sizeof(buf), "ERROR\n");
}
CLS1_SendStatusStr((unsigned char*)" RDAC3", buf, io->stdOut);
res = AD5252_ReadEEMEMReg(AD5252_EEMEM1, &val);
if (res==ERR_OK) {
UTIL1_Num8uToStr(buf, sizeof(buf), val);
UTIL1_strcat(buf, sizeof(buf), "\n");
} else {
UTIL1_strcpy(buf, sizeof(buf), "ERROR\n");
}
CLS1_SendStatusStr((unsigned char*)" EMEM1", buf, io->stdOut);
res = AD5252_ReadEEMEMReg(AD5252_EEMEM3, &val);
if (res==ERR_OK) {
UTIL1_Num8uToStr(buf, sizeof(buf), val);
UTIL1_strcat(buf, sizeof(buf), "\n");
} else {
UTIL1_strcpy(buf, sizeof(buf), "ERROR\n");
}
CLS1_SendStatusStr((unsigned char*)" EMEM3", buf, io->stdOut);
res = AD5252_ReadEEMEMReg(AD5252_EEMEM4, &val);
if (res==ERR_OK) {
UTIL1_Num8uToStr(buf, sizeof(buf), val);
UTIL1_strcat(buf, sizeof(buf), "\n");
} else {
UTIL1_strcpy(buf, sizeof(buf), "ERROR\n");
}
CLS1_SendStatusStr((unsigned char*)" EMEM4", buf, io->stdOut);
res = AD5252_ReadEEMEMReg(AD5252_EEMEM5, &val);
if (res==ERR_OK) {
UTIL1_Num8uToStr(buf, sizeof(buf), val);
UTIL1_strcat(buf, sizeof(buf), "\n");
} else {
UTIL1_strcpy(buf, sizeof(buf), "ERROR\n");
}
CLS1_SendStatusStr((unsigned char*)" EMEM5", buf, io->stdOut);
res = AD5252_ReadEEMEMReg(AD5252_EEMEM6, &val);
if (res==ERR_OK) {
UTIL1_Num8uToStr(buf, sizeof(buf), val);
UTIL1_strcat(buf, sizeof(buf), "\n");
} else {
UTIL1_strcpy(buf, sizeof(buf), "ERROR\n");
}
CLS1_SendStatusStr((unsigned char*)" EMEM6", buf, io->stdOut);
/* \todo list EEMEM7 to EEMEM15 */
return ERR_OK;
}
uint8_t AD5252_ParseCommand(const unsigned char* cmd, bool *handled, const CLS1_StdIOType *io) {
uint8_t res = ERR_OK;
uint8_t val;
if (UTIL1_strcmp((char*)cmd, CLS1_CMD_HELP) == 0
|| UTIL1_strcmp((char*)cmd, "ad5252 help") == 0) {
*handled = TRUE;
return PrintHelp(io);
} else if ( (UTIL1_strcmp((char*)cmd, CLS1_CMD_STATUS)==0)
|| (UTIL1_strcmp((char*)cmd, "ad5252 status") == 0)
)
{
*handled = TRUE;
res = PrintStatus(io);
} else if (UTIL1_strncmp((char*)cmd, "ad5252 write rdac", sizeof("ad5252 write rdac")-1) == 0) {
AD5252_RDAC_REG reg;
cmd += sizeof("ad5252 write rdac")-1;
if (*cmd=='1') {
reg = AD5252_RDAC1;
} else if (*cmd=='3') {
reg = AD5252_RDAC3;
} else {
CLS1_SendStr("Unknown RDAC register number!\n", io->stdErr);
return ERR_FAILED;
}
cmd++;
res = UTIL1_ScanDecimal8uNumber(&cmd, &val);
if (res==ERR_OK) {
res = AD5252_WriteRDACReg(reg, val);
if (res!=ERR_OK) {
CLS1_SendStr("failed writing RDAC!\n", io->stdErr);
}
} else {
CLS1_SendStr("failed scanning number!\n", io->stdErr);
}
*handled = TRUE;
}
return res;
}
void AD5252_Init(void) {
}
|
C
|
#include "simpleCSVsorter.h"
// implementation
char get_type(char* val) {
if(strcmp(val, "color") == 0 || strcmp(val, "director_name") == 0 || strcmp(val, "actor_2_name") == 0 || strcmp(val, "genres") == 0 || strcmp(val, "actor_1_name") == 0 || strcmp(val, "movie_title") == 0 || strcmp(val, "actor_3_name") == 0 || strcmp(val, "plot_keywords") == 0 || strcmp(val, "movie_imdb_link") == 0 || strcmp(val, "language") == 0 || strcmp(val, "country") == 0 || strcmp(val, "content_rating") == 0) {
return STR;
}
else if(strcmp(val, "duration") == 0)
return INT;
return FLOAT;
}
void print_row(datarow* row) {
int i = 0;
for(i = 0; i < row->size; i++) {
printf("%s", row->cells[i].original);
if(i < row->size - 1) printf(",");
}
printf("\n");
}
void print_header(char** vals, int n) {
int i = 0;
for(i = 0; i < n; i++) {
printf("%s", vals[i]);
if(i < n - 1) printf(",");
}
printf("\n");
}
datarow create_datarow(cell* cells, int col_count) {
datarow row;
row.size = col_count;
row.cells = cells;
return row;
}
table* create_table() {
table* tab = (table*)malloc(sizeof(table));
tab->rows = (datarow*)malloc(TABLE_SIZE * sizeof(datarow));
tab->max_size = TABLE_SIZE;
tab->size = 0;
return tab;
}
void append(table* tab, datarow* row) {
if(tab->size < tab->max_size) {
tab->rows[tab->size] = *row;
tab->size++;
}
else {
datarow* temp = tab->rows;
tab->max_size *= 2;
tab->rows = (datarow*)malloc(tab->max_size * sizeof(datarow));
int i = 0;
for(i = 0; i < tab->size; i++)
tab->rows[i] = temp[i];
free(temp);
append(tab, row);
}
}
char** split_by_comma(char* line, int* len) {
int i = 0, prev_i = 0;
int count = 1;
int max_size = 1;
bool inside_quote = false;
int line_length = 0;
while(line[i] != '\0' && line[i] != '\n') {
if(line[i] == '"')
inside_quote = inside_quote ? false : true;
if(line[i] == ',' && inside_quote == false) {
count++;
max_size = max(max_size, i - prev_i);
prev_i = i;
}
i++;
line_length++;
}
inside_quote = false;
char** words = (char**)malloc(count * sizeof(char*));
for(i = 0; i < count; i++) {
words[i] = (char*)malloc(max_size * sizeof(char));
words[i][0] = '\0';
}
int curr_word = 0;
int curr_i = 0;
for(i = 0; i < line_length; i++) {
if(line[i] == '"')
inside_quote = inside_quote ? false : true;
if(line[i] == ',' && inside_quote == false) {
words[curr_word++][curr_i] = '\0';
curr_i = 0;
}
else {
words[curr_word][curr_i++] = line[i];
}
}
*len = count;
return words;
}
cell* get_cells(char** pre_cell, char data_type, int index, int len) {
int i = 0;
cell* cells = (cell*)malloc(len * sizeof(cell));
for(i = 0; i < len; i++) {
cells[i].original = pre_cell[i];
cells[i].is_empty = pre_cell[i][0] == '\0' ? true : false;
if(cells[i].is_empty) {
cells[i].str_len = 0;
}
if(i == index) {
cells[i].data_type = data_type;
int st = 0;
int end = 0;
while(pre_cell[i][st] == ' ' || pre_cell[i][st] == '\t' || pre_cell[i][st] == '"') st++;
while(pre_cell[i][end] != '\0') end++;
end--;
while(end > -1 && (pre_cell[i][end] == ' ' || pre_cell[i][end] == '\t' || pre_cell[i][end] == '"')) end--;
if(end <= st) cells[i].is_empty = true;
else {
cells[i].is_empty = false;
int j = 0;
cells[i].str_datum = (char*)malloc((end - st + 2) * sizeof(char));
for(j = st; j <= end; j++)
cells[i].str_datum[j - st] = pre_cell[i][j];
cells[i].str_datum[j - st] = '\0';
cells[i].str_len = end - st + 1;
if(data_type == INT)
cells[i].num_datum = atoi(cells[i].str_datum);
else if(data_type == FLOAT)
cells[i].f_datum = atof(cells[i].str_datum);
}
}
}
return cells;
}
int main(int argc, char* argv[]) {
if(argc < 3)
perror("incorrect arguments");
int i = 1;
char* header_to_sort = NULL;
for(i = 1; i < argc; i++) {
if(strcmp(argv[i], "-c") == 0) {
i++;
header_to_sort = argv[i];
}
}
char sort_type = get_type(header_to_sort);
char buff[BUFSIZ];
char *read = fgets(buff, sizeof buff, stdin);
int no_of_cols = 0;
char** headers = split_by_comma(buff, &no_of_cols);
int cell_index = -1;
for(i = 0; i < no_of_cols; i++) {
if(!strcmp(headers[i], header_to_sort)) {
cell_index = i;
break;
}
}
if(cell_index != -1) {
table* main_table = create_table();
main_table->header = headers;
read = fgets(buff, sizeof buff, stdin);
while(read != NULL) {
int nc = 0;
char** split_line = split_by_comma(buff, &nc);
cell* cells = get_cells(split_line, sort_type, cell_index, nc);
datarow row = create_datarow(cells, nc);
append(main_table, &row);
read = fgets(buff, sizeof buff, stdin);
}
datarow* sorted = mergesort(main_table->rows, cell_index, main_table->size);
print_header(headers, no_of_cols);
int j;
for(j = 0; j < main_table->size; ++j){
print_row(&(sorted[j]));
}
}
return 0;
}
|
C
|
//#include<stdio.h>
//#include<math.h>
//
//#define ERROR 1E-8
//
//
//
//double my_sin(double x)
//{
// double temp = x;
//
// double result = x;
//
// double i = 1;
//
// while (fabs(temp) > ERROR)
// {
// temp *= -(x * x);
// i++;
// temp /= i;
// i++;
// temp /= i;
// result += temp;
// }
//
// return result;
//}
//
//int main()
//{
// double temp = 0;
//
// double x = 0;
// printf("Put in x:\n");
// while (scanf_s("%lf", &x))
// {
// printf("sin(x)=%.9g\n", my_sin(x));
// printf("The error is %.9g\n", my_sin(x) - sin(x));
// }
// getchar(); getchar();
//}
|
C
|
/*Moje funkcje*/
#include <stdio.h>
#include <stdlib.h>
#include "mazelib.h"
#include "random.h"
#include <ncurses/curses.h>
/*F-a przyporzadkowuje punktowi, na ktory wskazuje wskaznik p, nowe
wspolrzedne a i b.
Poza tym rysuje ludzika w nowym miejscu*/
void Daj(int a, int b){
p->x = a;
p->y = b;
lab[b][a] = '@';
}
/*Pomocnicza f-a, ktora po prostu wypisuje mna ekran aktualne
wspolrzedne danego punktu.*/
void PiszPunkt(TPoint punkt){
printw("X = %d Y = %d\n",punkt.x, punkt.y);
}
/*F-a, ktora rysuje labirynt. Czyli tablice dwuwymiarowa lab.*/
void RysujLab(int **labirynt){
int i,j;
system("usleep 150000");
erase();
for(i = 0; i<=LabX; i++){
for(j = 0; j<=LabY; j++){
(lab[i][j] == '#') ? color_set(1,0) : color_set(2,0);
printw("%c",labirynt[i][j]);
}
printw("\n");
}
printw("\n");
color_set(3,0);
refresh();
}
/*F-a sprawdza, czy w danym punkcie jest sciana.
Jesli tak, to zwraca 1.*/
static bool CzySciana(TPoint punkt){
if(lab[punkt.y][punkt.x] == '#') return TRUE;
else return FALSE;
}
/*F-a sprawdza, czy w danym punkcie jest X.
Jesli tak, to zwraca 1.*/
static bool CzyZaznaczony(TPoint punkt){
if(lab[punkt.y][punkt.x] == 'X') return TRUE;
else return FALSE;
}
/*Jesli punkt jest pusty, to f-a go zaznacza.*/
static void Zaznacz(TPoint punkt){
int temp = lab[punkt.y][punkt.x];
if(temp == ' ') lab[punkt.y][punkt.x] = 'X';
}
/*Jesli w danym p-cie jest X, to f-a go wymazuje.*/
static void Odznacz(TPoint punkt){
int temp = lab[punkt.y][punkt.x];
if(temp == 'X') lab[punkt.y][punkt.x] = ' ';
}
/*Jesli p-t jest pusty, to f-a rysuje w nim ludka.*/
void RysujLudka(TPoint punkt){
int temp = lab[punkt.y][punkt.x];
if(temp == ' ') lab[punkt.y][punkt.x] = '@';
}
/*F-a losuje miejsce startu w labiryncie.*/
TPoint LosujMiejsceStartu(){
TPoint punkt;
punkt.x = punkt.y = 0;
Randomize();
while(lab[punkt.y][punkt.x] == '#'){
punkt.y = RandomInteger(1, LabX-1);
punkt.x = RandomInteger(1, LabY-1);
}
RysujLudka(punkt);
return punkt;
}
/*Jesli w p-cie jest ludzik, to f-a go wymazuje.*/
static void WymazLudka(TPoint punkt){
int temp = lab[punkt.y][punkt.x];
if(temp == '@') lab[punkt.y][punkt.x] = ' ';
}
/*F-a sprawdza, czy ludzik znalazl wyjscie z labiryntu.*/
static bool CzyKoniec(TPoint punkt){
if(punkt.x == LabY || punkt.y == LabX || punkt.x == 0 || punkt.y == 0) return TRUE;
else return FALSE;
}
/*Jest glowna f-a calego programu.
Rekrencyjnie znajduje wyjscie z labiryntu oraz przedstawia je graficznie na ekranie.*/
bool RozwLab(TPoint pt){
int i, check;
TPoint temp = pt;
check = 0;
if(CzyKoniec(pt) == TRUE){
RysujLudka(pt);
RysujLab(lab);
return TRUE;
}
if(CzyZaznaczony(pt) == TRUE) return FALSE;
RysujLudka(pt);
RysujLab(lab);
WymazLudka(pt);
Zaznacz(pt);
for(i = 1; i<=4; i++){
pt = temp;
check = 0;
switch (i) {
case 1:
pt.y--;
if(CzySciana(pt) == FALSE) {
if(RozwLab(pt) == TRUE) return TRUE;
else{
WymazLudka(pt);
}
}
break;
case 2:
pt.x++;
if(CzySciana(pt) == FALSE) {
if(RozwLab(pt) == TRUE) return TRUE;
else{
WymazLudka(pt);
}
}
break;
case 3:
pt.y++;
if(CzySciana(pt) == FALSE) {
if(RozwLab(pt) == TRUE) return TRUE;
else{
WymazLudka(pt);
}
}
break;
case 4:
pt.x--;
if(CzySciana(pt) == FALSE) {
if(RozwLab(pt) == TRUE) return TRUE;
else{
WymazLudka(pt);
}
}
break;
}
}
Odznacz(temp);
RysujLudka(temp);
RysujLab(lab);
return FALSE;
}
/*F-a sprawdza jaka jest wielkosc labiryntu w pliku.
Robi to po to, aby f-a BierzLab wiedziala, ile ma zaalokowac
miejsca w dwuwymiarowej tablicy lab.
NALEY USPRAWNI!
*/
static TPoint SkanujPlik(char *plik[]){
TPoint punkt;
int c,i,j;
FILE *fp;
i = j = 0;
punkt.x = 0;
punkt.y = 0;
fp = fopen(plik[1], "r");
if(fp == NULL) printw("BRAK PLIKU!!!");
else{
while((c = getc(fp)) != EOF){
if(c == 10){
i++;
j = 0;
}
else if(c!=' ' && c!='#' && c!='@' && c!='S')
return punkt;
else j++;
}
}
fclose(fp);
LabX = punkt.x = i;
LabY = punkt.y = j-1;
/* PiszPunkt(punkt);*/
return punkt;
}
/*F-a przydziela odp. duzo miejsca tablicy lab oraz wpisuje do niej labirynt z pliku.
NALEY USPRAWNI!*/
int BierzLab(char *plik[]){
TPoint punkt;
int c,i,j;
FILE *fp;
i = j = 0;
fp = fopen(plik[1], "r");
if(fp == NULL) printw("shit...");
else{
punkt = SkanujPlik(plik);
if(punkt.x == 0 && punkt.y == 0) return 0;
lab = malloc(sizeof(int*)*(punkt.x+1));
for(i = 0; i<=punkt.x+1; i++)
lab[i] = malloc(sizeof(int*)*punkt.y);
i = j = 0;
while((c = getc(fp)) != EOF){
if(c == 10){
i++;
j = 0;
}
else {
lab[i][j] = c;
j++;
}
}
}
return 1;
}
/*F-a sprawdza, ile jest X'w w labiryncie.
F-a ta jest pomocna, przy znajdywaniu najkrtszej drogi. */
static int IleX(){
int wynik = 0;
int i,j;
for(i = 0; i<= LabX; i++)
for(j = 0; j<=LabY; j++){
if(lab[i][j] == 'X') wynik++;
}
return wynik;
}
/*F-a dziaa na zasadzie f-i RozwLab(), tylko, e nigdy nie znajduje wyjcie z labiryntu,
aby przepada wszystkie cieki i dziki temu sprawdzi ktra jest najkrtsza. */
bool FindShortestPath(TPoint pt){
int i, check;
TPoint temp = pt;
check = 0;
if(CzyKoniec(pt) == TRUE){
RysujLudka(pt);
if(IleX() < LICZBA){
Kopiuj(lab, lab2);
LICZBA = IleX();
}
return 0;
}
if(CzyZaznaczony(pt) == TRUE) return FALSE;
RysujLudka(pt);
WymazLudka(pt);
Zaznacz(pt);
for(i = 1; i<=4; i++){
pt = temp;
check = 0;
switch (i) {
case 1:
pt.y--;
if(CzySciana(pt) == FALSE) {
if(FindShortestPath(pt) == TRUE) return TRUE;
else{
WymazLudka(pt);
}
}
break;
case 2:
pt.x++;
if(CzySciana(pt) == FALSE) {
if(FindShortestPath(pt) == TRUE) return TRUE;
else{
WymazLudka(pt);
}
}
break;
case 3:
pt.y++;
if(CzySciana(pt) == FALSE) {
if(FindShortestPath(pt) == TRUE) return TRUE;
else{
WymazLudka(pt);
}
}
break;
case 4:
pt.x--;
if(CzySciana(pt) == FALSE) {
if(FindShortestPath(pt) == TRUE) return TRUE;
else{
WymazLudka(pt);
}
}
break;
}
}
Odznacz(temp);
RysujLudka(temp);
/* RysujLab();*/
return 0;
}
/*F-a przekopiowuje labirynt z lab do lab2. */
void Kopiuj(int **labirynt1, int **labirynt2){
int i,j;
for(i = 0; i<= LabX; i++)
for(j = 0; j<=LabY; j++)
labirynt2[i][j] = labirynt1[i][j];
}
void SkasujX(int **labirynt){
int i,j,*temp;
for(i = 0; i<= LabX; i++)
for(j = 0; j<=LabY; j++){
temp = &labirynt[i][j];
if(*temp == 'X' || *temp == '@') *temp = 32;
}
}
int SzukajStartu(){
int i,j;
for(i = 0; i<= LabX; i++)
for(j = 0; j<= LabY; j++){
if(lab[i][j] == 'S'){
lab[i][j] = '@';
p->x = j;
p->y = i;
return 1;
}
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
typedef struct binary_tree binary_tree;
struct binary_tree {
int item;
int height;
binary_tree *left, *right;
};
binary_tree *create_empty_binary_tree() {
return NULL;
}
binary_tree *create_binary_tree(int item, binary_tree *left, binary_tree *right) {
binary_tree *new_bt = (binary_tree*) malloc(sizeof(binary_tree));
new_bt->item = item;
new_bt->height = 1;
new_bt->left = new_bt->right = NULL;
return new_bt;
}
int is_empty(binary_tree *bt) {
return bt == NULL;
}
int max(int a, int b) {
return (a > b) ? a : b;
}
int height(binary_tree *bt) {
if (bt == NULL) {
return -1;
} else {
return 1 + max(height(bt->left), height(bt->right));
}
}
binary_tree *add(binary_tree *root, int key) {
if (root == NULL) {
return create_binary_tree(key, NULL, NULL);
} if (key < root->item) {
root->left = add(root->left, key);
} else if (key > root->item) {
root->right = add(root->right, key);
} else {
return root;
}
root->height = 1 + max(height(root->left), height(root->right));
return root;
}
binary_tree *search(binary_tree *bt, int item) {
if ((bt == NULL) || (bt->item == item)) {
return bt;
} else if (bt->item > item) {
search(bt->left, item);
} else {
search(bt->right, item);
}
}
binary_tree *min_value_node(binary_tree *node) {
binary_tree *current = node;
while (current->left != NULL) {
current = current->left;
}
return current;
}
binary_tree *delete_node(binary_tree *root, int key) {
if (root == NULL) {
return root;
}
if (key < root->item) {
root->left = delete_node(root->left, key);
} else if(key > root->item) {
root->right = delete_node(root->right, key);
} else {
if (root->left == NULL) {
binary_tree *temp = root->right;
free(root);
return temp;
} else if (root->right == NULL) {
binary_tree *temp = root->left;
free(root);
return temp;
}
binary_tree *temp = min_value_node(root->right);
root->item = temp->item;
root->right = delete_node(root->right, temp->item);
}
root->height = 1 + max(height(root->left), height(root->right));
return root;
}
void print_tree(binary_tree *bt) {
if (!is_empty(bt)) {
printf("(");
printf("%d ", bt->item);
if (bt->left == NULL) {
printf("()");
} else {
print_tree(bt->left);
} if (bt->right == NULL) {
printf("()");
} else {
print_tree(bt->right);
}
printf(")");
}
}
int main() {
int i;
binary_tree *bt = create_empty_binary_tree();
// bt = add(bt, i);
// bt = search(bt, item);
// bt = delete_node(bt, i);
// print_tree(bt);
return 0;
}
|
C
|
typedef struct pair {
int x;
int y;
} MyPair;
volatile MyPair mypair;
volatile int k = 0;
void assignk(struct pair* p) {
p -> x = k;
p -> y = k;
return;
}
int main() {
for (;;) {
assignk(&mypair);
k = (k + 1) % 2;
};
return 0;
}
|
C
|
#include <stdio.h>
int main()
{
int a[5], i;
// initialization stage
for (i = 0; i < 5; i++)
a[i] = 1;
// visiting stage
for (i = 0; i < 5; i++)
printf("%d\n", a[i]);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int trespasos(int);
int main(void)
{
int argumento, res;
printf("Ingrese numero 1: ");
scanf("%d", &argumento);
fflush(stdin);
res = trespasos(argumento);
printf("Paso 1: %d\n\n", res);
printf("Ingrese numero 2: ");
scanf("%d", &argumento);
fflush(stdin);
res = trespasos(argumento);
printf("Paso 2: %d\n\n", res);
printf("Ingrese numero 3: ");
scanf("%d", &argumento);
fflush(stdin);
res = trespasos(argumento);
printf("Paso 3: %d\n", res);
return 0;
}
int trespasos (int a)
{
static int estado = 0;
static int resultado;
switch(estado)
{
case 0:
resultado = a;
break;
case 1:
resultado = resultado + a;
break;
case 2:
resultado = resultado * a;
break;
default:
break;
}
estado++;
return resultado;
}
|
C
|
#include<stdio.h>
#include<math.h>
double madhav_leibniz(int steps);
double euler_leibniz(int steps);
double euler_zeta(int steps);
double euler_zeta(steps) {
int k = 1 ;
double sum = 0.0 ;
while(k < steps) {
sum += 1.0 / (k*k);
k++;
}
/* pi^2/6 = series sum */
double pi = sqrt(6.0*sum);
printf("pi = %f euler zeta(2) for N = %d \n",pi,steps);
}
double euler_leibniz(steps) {
int k = 0 ;
double sum = 0.0 ;
while(k < steps ) {
sum+= 2.0 /((4*k+1)*(4*k+3)) ;
k++;
}
printf("pi = %f leibniz euler series for N = %d \n",sum*4.0,steps);
}
double madhav_leibniz(steps) {
int k = 0 ;
double sum = 0.0 ;
while(k < steps ) {
sum+= (pow(-1.0,k))/(2*k+1.0);
k++;
}
printf("pi = %f madhav leibniz series for N = %d \n",sum*4.0,steps);
}
int main() {
madhav_leibniz(1000);
euler_leibniz(1000);
euler_zeta(1000);
return 0 ;
}
|
C
|
#include <stdio.h>
#include <string.h>
void reverse(char s[]){
int c, i,j;
for(i = 0, j = strlen(s) -1; i<j;i++,j--){
c = s[i];
s[i] = s[j];
s[j] = c;
}
}
main(){
printf("x is x \n"),printf("y is y \n");
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
int err(const char *str, int line) {
perror(str);
printf("line %d: ", line);
exit(0);
}
static void * threadFunc(void *arg) {
int i;
printf("New thread started\n");
for(i = 1; ; i++) {
printf("loop %d\n", i);
sleep(1);
}
return NULL;
}
int main (void) {
pthread_t thr;
int s;
void *res;
s = pthread_create(&thr, NULL, threadFunc, NULL);
if(s != 0)
err("pthread_create", __LINE__);
//printf("\n1111\n");
sleep(3);
//printf("\n2222\n");
s = pthread_cancel(thr);
if(s != 0)
err("pthread_cancel", __LINE__);
s = pthread_join(thr, &res);
if(s != 0)
err("pthread_join", __LINE__);
if(res == PTHREAD_CANCELED)
printf("THread was canceled\n");
else
printf("THread was not canceled!\n");
exit(EXIT_SUCCESS);
}
|
C
|
/** @file Queue module of unsigned chars. */
#ifndef EHAL_QUEUE_H
#define EHAL_QUEUE_H
#ifdef EHAL_GLOBAL
#include "ehal_global.h"
#endif
#include <stdbool.h>
#include <stdint.h>
struct queue {
unsigned char *buff; /**< your buffer goes here. */
uint8_t sz; /**< number of elements in buff */
uint8_t s; /**< start, index of first element */
uint8_t ocupied; /**< number of ocupied bytes */
};
/** set user defined buffer to be the queue buffer. */
void queue_init (struct queue *q,
unsigned char *buff,
int sz);
/** returns how many bytes are in the queue. */
int queue_ocupied (struct queue *q);
/** returns non-zero if queue is full */
bool queue_isfull (struct queue *q);
/** returns non-zero if queue is empty */
bool queue_isempty (struct queue *q);
/** put data in the queue, return true for success */
bool queue_enq (struct queue *q, unsigned char data);
/** cp first element in the queue to *ret and remove it from queue */
bool queue_deq (struct queue *q, unsigned char *ret);
void queue_flush (struct queue *q);
/** same as before but without removing it */
bool queue_peaklast (struct queue *q, unsigned char *ret);
/** same as before but for the first element */
bool queue_peakfirst (struct queue *q, unsigned char *ret);
#endif /* #ifndef __QUEUE_H_ */
|
C
|
#include "../../includes/view/table.h"
/* ---------------//--------------- [Structs] ---------------//--------------- */
//[struct table]
struct table{
string *info; //Information of table -> Array of strings
string *titles; //Table titles -> Array of strings
string title_lines; //Title lines of table -> String
int lines; //Table lines -> Int
int columns; //Table columns -> Int
int size; //Table size -> Int
int number_of_pages; //Number of table pages -> Int
int lines_for_page; //Lines per page -> Int
int *biggest_length; //Biggest Length of columns -> Int
int buffer_size; //Buffer size of table -> Int
};
/* ---------------//--------------- [Private Functions] ---------------//--------------- */
//[Initialization function of string*]
static string *init_strings(int size){
string *ss = (string *)malloc(sizeof(string) * size);
if (ss == NULL){
abort();
}
int i;
for (i = 0; i < size; i++)
ss[i] = NULL;
return ss;
}
//[Destruction function of string*]
static void destroy_strings(string *ss, int size){
int i;
for (i = 0; i < size; i++)
free(ss[i]);
free(ss);
}
//[Realloc function of string*]
static string *reinit_strings(string *ss, int old_size, int new_size){
ss = (string *)realloc(ss, sizeof(string) * new_size);
if (ss == NULL){
abort();
}
int i;
for (i = old_size; i < new_size; i++)
ss[i] = NULL;
return ss;
}
//[Realloc function of int array (int* biggest_length of table)]
static int *reinit_biggest_length(int *bl, int old_size, int new_size){
bl = (int *)realloc(bl, sizeof(int) * new_size);
if (bl == NULL){
abort();
}
int i;
for (i = old_size; i < new_size; i++)
bl[i] = 0;
return bl;
}
//[Initialization function of int array (int* biggest_length of table)]
static int *init_biggest_length(int size){
int *bl = (int *)malloc(sizeof(int) * size);
if (bl == NULL){
abort();
}
int i;
for (i = 0; i < size; i++)
bl[i] = 0;
return bl;
}
//[Get biggest length of column of a struct table]
static int get_table_biggest_length_of_column(TABLE t, int c){
return t->biggest_length[c];
}
//[Set biggest length of column of a struct table]
static void set_table_biggest_length_of_column(TABLE t, int c, int length){
t->biggest_length[c] = length;
}
//[Increment a size of a struct table]
static void inc_table_size(TABLE t){
t->size += 1;
if(t->size == t->buffer_size){
t->info = reinit_strings(t->info,t->buffer_size,t->buffer_size*2);
t->buffer_size*=2;
}
}
//[Print a line of repetitions of c]
static void print_line(int size, char c){
int i;
for (i = 0; i < size; i++)
putchar(c);
}
//[Print a string]
static void print_string(string s, int size){
int size_string;
size_string = strlen(s);
int white_spaces;
white_spaces = (size - size_string) / 2;
print_line(white_spaces, ' ');
printf("%s", s);
int leftover;
leftover = size - white_spaces - size_string;
print_line(leftover, ' ');
}
//[Printf titles of a struct table]
static void print_titles(TABLE t){
putchar('|');
int c;
c = get_table_columns(t);
int i;
for (i = 0; i < c; i++){
print_string(t->titles[i], get_table_biggest_length_of_column(t, i) + 2);
putchar('|');
}
putchar('\n');
}
//[Printf line info of a struct table]
static void print_line_info(TABLE t, int l){
putchar('|');
int c;
c = get_table_columns(t);
int i;
for (i = 0; i < c; i++){
print_string(t->info[c * l + i], get_table_biggest_length_of_column(t, i) + 2);
putchar('|');
}
putchar('\n');
}
/* ---------------//--------------- [Public Functions] ---------------//--------------- */
/* [Initialization and destruction functions] */
//[Initialization function of struct table]
TABLE init_table(int buffer_size){
TABLE t = malloc(sizeof(struct table));
if (t == NULL){
abort();
}
set_table_columns(t, 0);
set_table_lines(t, 0);
set_table_lines_for_page(t, 0);
set_table_number_of_pages(t, 0);
set_table_size(t, 0);
if (buffer_size == 0)
t->buffer_size = 50000;
else
t->buffer_size = buffer_size;
t->info = init_strings(t->buffer_size);
t->titles = NULL;
t->biggest_length = NULL;
t->title_lines = NULL;
return t;
}
//[Destruction function of struct table]
void free_table(TABLE t){
if (t != NULL){
if (t->titles != NULL)
destroy_strings(t->titles, t->columns);
if (t->info != NULL)
destroy_strings(t->info, t->size);
if (t->biggest_length != NULL)
free(t->biggest_length);
if (t->title_lines != NULL)
free(t->title_lines);
free(t);
}
}
/* [getters and setters functions] */
//[Get size of a struct table]
int get_table_size(TABLE t){
return t->size;
}
//[Get lines of a struct table]
int get_table_lines(TABLE t){
return t->lines;
}
//[Get columns of a struct table]
int get_table_columns(TABLE t){
return t->columns;
}
//[Get number of pages of a struct table]
int get_table_number_of_pages(TABLE t){
return t->number_of_pages;
}
//[Get lines for page of a struct table]
int get_table_lines_for_page(TABLE t){
return t->lines_for_page;
}
//[Get column title of a struct table]
char *get_table_titles(TABLE t, int col){
char *s = strdup(t->titles[col]);
return s;
}
//[Get info of a struct table]
char *get_table_info(TABLE t, int i){
char *s = strdup(t->info[i]);
return s;
}
//[Get info of a struct table]
char *get_table_title_line(TABLE t){
char *s = strdup(t->title_lines);
return s;
}
//[Set size of a struct table]
void set_table_size(TABLE t, int size){
t->size = size;
}
//[Set lines of a struct table]
void set_table_lines(TABLE t, int lines){
t->lines = lines;
}
//[Set columns of a struct table]
void set_table_columns(TABLE t, int columns){
if (columns > 0){
if (t->columns > 0){
t->titles = reinit_strings(t->titles, t->columns, columns);
t->biggest_length = reinit_biggest_length(t->biggest_length, t->columns, columns);
}
else{
t->titles = init_strings(columns);
t->biggest_length = init_biggest_length(columns);
}
t->columns = columns;
}
else
t->columns = 0;
}
//[Set number of pages of a struct table]
void set_table_number_of_pages(TABLE t, int number_of_pages){
t->number_of_pages = number_of_pages;
}
//[Set lines for page of a struct table]
void set_table_lines_for_page(TABLE t, int lines_for_page){
t->lines_for_page = lines_for_page;
}
//[Set title lines of a struct table]
void set_title_lines(TABLE t, char* title){
t->title_lines = strdup(title);
}
//[Set default pages [10 lines for page] of a struct table]
void set_default_pages(TABLE t){
int lines, number_of_pages;
set_table_lines_for_page(t, 10);
lines = get_table_lines(t);
if (lines != 0){
number_of_pages = lines / 10;
if (lines%10 != 0) number_of_pages++;
}
else
number_of_pages = 1;
set_table_number_of_pages(t, number_of_pages);
}
/* [Increment and add functions] */
//[Increment lines of a struct table]
void inc_table_lines(TABLE t){
t->lines += 1;
}
//[Add a title to the column of a struct table]
void add_title_of_column(TABLE t, string s, int c){
if (c >= 0){
int title_size;
t->titles[c] = strdup(s);
title_size = strlen(t->titles[c]);
if (c >= get_table_columns(t))
set_table_columns(t, c + 1);
if (title_size > get_table_biggest_length_of_column(t, c))
set_table_biggest_length_of_column(t, c, title_size);
}
}
//[Add information to a struct table]
void add_info_string(TABLE t, string s){
int table_size, info_size, c;
table_size = get_table_size(t);
t->info[table_size] = strdup(s);
info_size = strlen(t->info[table_size]);
c = table_size % get_table_columns(t);
if (info_size > get_table_biggest_length_of_column(t, c))
set_table_biggest_length_of_column(t, c, info_size);
inc_table_size(t);
}
/* [Print functions] */
//[Print a struct table]
void print_page_of_table(TABLE t, int page){
int number_of_pages;
number_of_pages = t->number_of_pages;
if (page <= number_of_pages && page > 0){
int lines_for_page, c, cs, ls, length_table;
lines_for_page = t->lines_for_page;
cs = get_table_columns(t);
ls = get_table_lines(t);
for (length_table = 0, c = 0; c < cs; c++)
length_table += t->biggest_length[c] + 2;
length_table += cs + 1;
print_line(length_table, '-');
putchar('\n');
print_titles(t);
print_line(length_table, '-');
putchar('\n');
if (get_table_size(t) > 0){
int i;
for (i = (page - 1) * lines_for_page; (i < page * lines_for_page && i < ls); i++){
print_line_info(t, i);
print_line(length_table, '-');
putchar('\n');
}
if (t->title_lines != NULL)
printf("[%s]: %d\n", t->title_lines, ls);
if (number_of_pages > 1)
printf("Page %d of %d\n", page, number_of_pages);
}
}
else
printf("Não existe essa página\n");
}
/*
void show_review_text (TABLE t){
print_line(200,'-');
printf("\n");
print_string_coloured(get_table_titles(t, 0), "green");
print_string_coloured(get_table_info(t,0),"yellow");
printf("\n");
print_line(200, '-');
printf("\n");
print_string_coloured("On ","blue");
print_string_coloured(get_table_info(t,2),"yellow");
print_string_coloured(", the user ","blue");
print_string_coloured(get_table_info(t,1),"yellow");
print_string_coloured(" said about the business ","blue");
print_string_coloured(get_table_info(t,3),"yellow");
print_string_coloured(" :","blue");
printf("\n");
print_string_coloured(get_table_info(t,4),"green");
printf("\n");
print_line(200, '-');
printf("\n");
}
*/
|
C
|
/*
* File: main.c
* Author: protodev
* License: see LICENSE
*
* Created on February 18, 2016, 12:20 PM
*/
#include <arpa/inet.h>
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <X11/X.h>
#include <gtk-3.0/gtk/gtk.h>
#include <gdk/gdkkeysyms.h>
#include "main.h"
#include "ff2png.h"
char* isFarbfeldFile(char*);
void close_window(GtkWidget*, gpointer);
gboolean on_key_press(GtkWidget*, GdkEventKey*, gpointer);
void updateImage(void);
int main(int, char**);
GtkWidget *image;
GtkWidget *window;
GtkWidget *titlebar;
char **fileList;
int fileIndex = 0;
int filelistLength = 0;
char* prevTempFile;
/**
* @param the *file, may be NULL
* @return *file on success and NULL on failure
*/
char* isFarbfeldFile(char *file)
{
if (strlen(file) == 0) {
return NULL;
}
FILE *f = fopen(file, "r");
if (f == NULL) {
printf("empty file\n");
return NULL;
}
char *ext = strrchr(file, '.');
char *magic = calloc(8, 1);
/* read the farbfeld magic */
if (fread(magic, 1, 8, f) != 8) {
printf("invalid magic\n");
free(magic);
fclose(f);
return NULL;
}
if (ext && strcmp(ext + 1, "ff") == 0 &&
strcmp(magic, "farbfeld") == 0) {
free(magic);
fclose(f);
return file;
} else {
printf("invalid file - skipping\n");
free(magic);
fclose(f);
return NULL;
}
}
void close_window(GtkWidget *widget, gpointer window)
{
if (prevTempFile != NULL && strlen(prevTempFile) != 0) {
unlink(prevTempFile);
}
gtk_widget_destroy(window);
exit(0);
}
gboolean on_key_press(GtkWidget *widget, GdkEventKey *event, gpointer user_data)
{
switch (event->keyval) {
case GDK_KEY_Left:
fileIndex--;
if (fileIndex < 0) fileIndex = filelistLength - 1;
updateImage();
break;
case GDK_KEY_Right:
fileIndex++;
if (fileIndex >= filelistLength) fileIndex--;
updateImage();
break;
case GDK_KEY_q:
/* fall through */
case GDK_KEY_Q:
close_window(NULL, window);
break;
}
return FALSE;
}
void updateImage()
{
if (fileList == NULL || filelistLength == 0) {
exit(0);
}
char *pngFile = ff2png(fileList[fileIndex]);
// printf("pngFile: %s\n", pngFile);
// on click
gtk_image_set_from_file(GTK_IMAGE(image), pngFile);
if (prevTempFile != NULL && strlen(prevTempFile) != 0) {
unlink(prevTempFile);
}
prevTempFile = pngFile;
}
int main(int argc, char** argv)
{
gtk_init(&argc, &argv);
window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_title(GTK_WINDOW(window), "ffviewer");
gtk_window_set_resizable(GTK_WINDOW(window), TRUE);
gtk_window_set_wmclass(GTK_WINDOW(window), "ffviewer", "ffviewer");
gtk_window_set_default_size(GTK_WINDOW(window), 500, 500);
g_signal_connect(window, "delete_event", G_CALLBACK(close_window), NULL);
g_signal_connect(window, "key_press_event", G_CALLBACK(on_key_press), NULL);
GtkWidget *vbox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0);
image = gtk_image_new();
gtk_box_pack_start(GTK_BOX(vbox), image, TRUE, TRUE, 0);
//gtk_container_add(GTK_CONTAINER(window), image);
gtk_container_add(GTK_CONTAINER(window), vbox);
fileList = calloc(argc, sizeof(char*));
int index = 0;
int i = 1;
for (; i < argc; i++) {
char *f = isFarbfeldFile(argv[i]);
if (f != NULL) {
fileList[index] = f;
index++;
}
}
filelistLength = index;
updateImage();
gtk_widget_show_all(window);
gtk_widget_grab_focus(window);
gtk_main();
return(EXIT_SUCCESS);
}
|
C
|
/*
* defines.h
*
* Created: 13.09.2017 12:12:04
* Author: tobib
*/
#ifndef DEFINES_H_
#define DEFINES_H_
#include "usart.h"
#define F_CPU 16000000 // Clock frequency in Hz
enum {JOYSTICK_X, JOYSTICK_Y, SLIDER_LEFT, SLIDER_RIGHT, BUTTONS};
typedef enum { LEFT_BUTTON, RIGHT_BUTTON, JOY_BUTTON } button;
#define set_bit( reg, bit ) (reg |= (1 << bit))
#define clear_bit( reg, bit ) (reg &= ~(1 << bit))
#define test_bit( reg, bit ) (reg & (1 << bit))
#define loop_til_bit_is_set( reg, bit ) while( !test_bit( reg, bit ) )
//#define loop_until_bit_is_clear( reg, bit ) while( test_bit( reg, bit ) )
#define MAX(a,b) ((a < b) ? (b) : (a))
#define MIN(a,b) ((a > b) ? (b) : (a))
#define SGN(a) ((a) >= 0 ? 1 : -1)
#define SATURATE(x,low,high) ( MIN( MAX((x), (low)), (high) ) )
#endif /* DEFINES_H_ */
|
C
|
#ifndef MATHC_TYPES_UINT_H
#define MATHC_TYPES_UINT_H
#ifndef __cplusplus
#define static_assert _Static_assert
#endif
typedef union {
unsigned v[2];
struct {
unsigned v0, v1;
};
struct {
unsigned x, y;
};
struct {
unsigned r, g;
};
} uvec2;
static_assert(sizeof(uvec2) == sizeof(unsigned) * 2, "[Mathc] wrong expected size");
/** casts a unsigned * to a dereferenced uvec2 */
#define UVec2(vec) (*(uvec2 *) (vec))
/** casts a unsigned * to a dereferenced const uvec2 */
#define ConstUVec2(vec) (*(const uvec2 *) (vec))
typedef union {
unsigned v[4];
unsigned m[2][2];
uvec2 col[2];
struct {
unsigned v0, v1;
unsigned v2, v3;
};
struct {
unsigned m00, m01;
unsigned m10, m11;
};
} umat2;
static_assert(sizeof(umat2) == sizeof(unsigned) * 4, "[Mathc] wrong expected size");
/** casts a unsigned * to a dereferenced umata2 */
#define UMat2(mat) (*(umat2 *) (mat))
/** casts a unsigned * to a dereferenced const umata2 */
#define ConstUMat2(mat) (*(const umat2 *) (mat))
typedef union {
unsigned v[3];
struct {
unsigned v0, v1, v2;
};
uvec2 xy;
struct {
unsigned x;
union {
struct {
unsigned y, z;
};
uvec2 yz;
};
};
uvec2 rg;
struct {
unsigned r;
union {
struct {
unsigned g, b;
};
uvec2 gb;
};
};
} uvec3;
static_assert(sizeof(uvec3) == sizeof(unsigned) * 3, "[Mathc] wrong expected size");
/** casts a unsigned * to a dereferenced uvec3 */
#define UVec3(vec) (*(uvec3 *) (vec))
/** casts a unsigned * to a dereferenced const uvec3 */
#define ConstUVec3(vec) (*(const uvec3 *) (vec))
typedef union {
unsigned v[9];
unsigned m[3][3];
uvec3 col[3];
struct {
unsigned v0, v1, v2;
unsigned v3, v4, v5;
unsigned v6, v7, v8;
};
struct {
unsigned m00, m01, m02;
unsigned m10, m11, m12;
unsigned m20, m21, m22;
};
} umat3;
static_assert(sizeof(umat3) == sizeof(unsigned) * 9, "[Mathc] wrong expected size");
/** casts a unsigned * to a dereferenced umata3 */
#define UMat3(mat) (*(umat3 *) (mat))
/** casts a unsigned * to a dereferenced const umata3 */
#define ConstUMat3(mat) (*(const umat3 *) (mat))
typedef union {
unsigned v[4];
struct {
unsigned v0, v1, v2, v3;
};
uvec2 xy;
uvec3 xyz;
struct {
unsigned x;
union {
struct {
unsigned y;
union {
struct {
unsigned z, w;
};
uvec2 zw;
};
};
uvec2 yz;
uvec3 yzw;
};
};
uvec2 rg;
uvec3 rgb;
struct {
unsigned r;
union {
struct {
unsigned g;
union {
struct {
unsigned b, a;
};
uvec2 ba;
};
};
uvec2 gb;
uvec3 gba;
};
};
} uvec4;
static_assert(sizeof(uvec4) == sizeof(unsigned) * 4, "[Mathc] wrong expected size");
/** casts a unsigned * to a dereferenced uvec4 */
#define UVec4(vec) (*(uvec4 *) (vec))
/** casts a unsigned * to a dereferenced const uvec4 */
#define ConstUVec4(vec) (*(const uvec4 *) (vec))
typedef union {
unsigned v[16];
unsigned m[4][4];
uvec4 col[4];
struct {
unsigned v0, v1, v2, v3;
unsigned v4, v5, v6, v7;
unsigned v8, v9, v10, v11;
unsigned v12, v13, v14, v15;
};
struct {
unsigned m00, m01, m02, m03;
unsigned m10, m11, m12, m13;
unsigned m20, m21, m22, m23;
unsigned m30, m31, m32, m33;
};
} umat4;
static_assert(sizeof(umat4) == sizeof(unsigned) * 16, "[Mathc] wrong expected size");
/** casts a unsigned * to a dereferenced umata4 */
#define UMat4(mat) (*(umat4 *) (mat))
/** casts a unsigned * to a dereferenced const umata4 */
#define ConstUMat4(mat) (*(const umat4 *) (mat))
#endif //MATHC_TYPES_UINT_H
|
C
|
/* Write a function invert(x,p,n) that returns x
* with the n bits that begin at position p inverted,
* leaving the others unchanged */
#include <stdio.h>
#include "bits.h"
unsigned invert(unsigned, int, int);
int main()
{
unsigned tests[10] = {0x0, 0x1, 0x6, 0x3f, 0x25};
unsigned expected[][2] = {
{0x1, 0xe},
{0x0, 0xf},
{0x7, 0x8},
{0x3e, 0x31},
{0x24, 0x2b}
};
for (int i=0; i<5; i++) {
if (invert(tests[i], 0, 0) != tests[i])
printf("Test %d failed: expected 0x%x, got 0x%x\n", i, tests[i], invert(tests[i], 0, 0));
if (invert(tests[i], 0, 1) != expected[i][0])
printf("Test %d failed: expected 0x%x, got 0x%x\n", i, expected[i][0], invert(tests[i], 0, 1));
if (invert(tests[i], 3, 3) != expected[i][1])
printf("Test %d failed: expected 0x%x, got 0x%x\n", i, expected[i][1], invert(tests[i], 3, 3));
}
}
unsigned invert(unsigned x, int p, int n) {
unsigned inverted_bits = ~ getbits(x, p, n);
return setbits(x, p, n, inverted_bits);
}
|
C
|
#include <stdio.h>
int main(){
printf("Hello world\n");
//ushort
//int *x = 5;
//uint m = 6;
//printf("%d\n", x);
//printf("%u ", &x);
return 0;
}
/*int main(){
//ushort
int x = 5;
//uint m = 6;
printf("%d", x);
//printf("%u ", &x);
}
*/
|
C
|
/*_____________________________________________________________________________________________
Copyright 2011 Nishchay Mhatre
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
_____________________________________________________________________________________________ */
/*#####################################################################################
Bare metal hello world
#####################################################################################*/
#include"AT91SAM7X256.h" // H/W includes
#include<stdint.h> // Standard widths
// Control parameters
#define ALLISWELL 0
#define CRITICAL 160
// Sensor scaling parameters
#define SYS_ZERO 4
#define SYS_MAX 20
// Valve control command
#define OPEN 10
#define CLOSE 1
/* Hardware setup macro */
#define prvSetupHardware() /*Rev 1: Change1*/ \
{\
AT91C_BASE_AIC->AIC_EOICR = 0;\
AT91C_BASE_RTTC->RTTC_RTMR = (0x1)|(AT91C_RTTC_RTTRST);\
AT91C_BASE_PMC->PMC_PCER = (1 << AT91C_ID_PIOA);\
AT91C_BASE_PMC->PMC_PCER = (1 << AT91C_ID_PIOB);\
}
/*#####################################################################################
Read sensors and open valve : stubs
##################################################################################### */
int read_sensor()
{
uint32_t reading;
while ((AT91C_BASE_SPI1->SPI_SR & AT91C_SPI_RDRF) == 0);
reading= AT91C_BASE_SPI1->SPI_RDR & 0xFFFF;
return ( (reading-SYS_ZERO)*(CRITICAL / (SYS_MAX-SYS_ZERO )) ); // Scale
}
void valve(uint32_t action)
{
AT91C_BASE_SPI1->SPI_TDR = (action & 0xFFFF);
while ((AT91C_BASE_SPI1->SPI_SR & AT91C_SPI_TDRE) == 0);
return;
}
/*#####################################################################################
Main function. Payload of boot code.
##################################################################################### */
int main(void)
{
float a,b,c;
int status;
prvSetupHardware(); // Initial setup of board
while(1)
{
if ( (status=read_sensor()) >= CRITICAL )
valve(OPEN); // Emergency - full open
else if(status<SYS_ZERO)
valve(CLOSE); // Fail close
}
/*a = 3.14159;
b = 3.0;
while(1)
c = a*b;*/
}
|
C
|
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include "keyword.h"
#include "lex.h"
tok_t
get_next_token()
{
static char peek = ' ';
for (; peek == ' ' || peek == '\t';)
peek = fgetc(stdin);
if (isdigit(peek)) {
int num = 0;
do {
num = num * 10 + peek - '0';
peek = fgetc(stdin);
} while (isdigit(peek));
lex_item.id = TOK_NUM;
lex_item.num = num;
return TOK_NUM;
}
if (isalpha(peek)) {
id_table_item_t *nitem;
keyword_t kword;
char *s = NULL;
char *tmp;
int used, len;
len = used = 0;
do {
if (used >= len - 1) {
len += 64;
if ((tmp = realloc(s, len)) == NULL)
print_warn_and_die("realloc_err");
s = tmp;
}
s[used++] = peek;
peek = fgetc(stdin);
} while(isdigit(peek) || isalpha(peek));
//FIXME: now we cant have id with _
s[used++] = '\0';
if ((tmp = realloc(s, used)) == NULL)
print_warn_and_die("realloc_err");
s = tmp;
if ((kword = keyword_table_lookup(s)) != KEY_UNKNOWN) {
free(s);
lex_item.id = TOK_KEYWORD;
lex_item.op = kword;
return TOK_KEYWORD;
}
if ((nitem = id_table_lookup(s)) == NULL) {
nitem = malloc_or_die(sizeof(*nitem));
nitem->id = ID_UNKNOWN;
nitem->value = 0;
nitem->name = s;
id_table_insert(nitem);
} else {
free(s);
}
lex_item.id = TOK_ID;
lex_item.item = nitem;
return TOK_ID;
}
//FIXME:
// mb need flush peek in composite tokens
switch (peek) {
case '=':
peek = fgetc(stdin);
if (peek == '=') {
lex_item.id = lex_item.op = TOK_EQ;
peek = ' ';
return TOK_EQ;
}
lex_item.id = lex_item.op = TOK_AS;
return TOK_AS;
case '!':
peek = fgetc(stdin);
if (peek == '=') {
peek = ' ';
lex_item.id = lex_item.op = TOK_NEQ;
return TOK_NEQ;
}
lex_item.id = lex_item.op = TOK_NOT;
return TOK_NOT;
case '<':
peek = fgetc(stdin);
if (peek == '=') {
peek = ' ';
lex_item.id = lex_item.op = TOK_LE;
return TOK_LE;
}
lex_item.op = TOK_LO;
return TOK_LO;
case '>':
peek = fgetc(stdin);
if (peek == '=') {
peek = ' ';
lex_item.id = lex_item.op = TOK_GE;
return TOK_GE;
}
lex_item.id = lex_item.op = TOK_GR;
return TOK_GR;
case '&':
peek = fgetc(stdin);
if (peek == '&') {
peek = ' ';
lex_item.id = lex_item.op = TOK_L_AND;
return TOK_L_AND;
}
lex_item.id = lex_item.op = TOK_B_AND;
return TOK_B_AND;
case '|':
peek = fgetc(stdin);
if (peek == '|') {
peek = ' ';
lex_item.id = lex_item.op = TOK_L_OR;
return TOK_L_OR;
}
lex_item.id = lex_item.op = TOK_B_OR;
return TOK_B_OR;
case '(':
peek = ' ';
lex_item.id = lex_item.op = TOK_LPAR;
return TOK_LPAR;
case ')':
peek = ' ';
lex_item.id = lex_item.op = TOK_RPAR;
return TOK_RPAR;
case '[':
peek = ' ';
lex_item.id = lex_item.op = TOK_LBRACKET;
return TOK_LBRACKET;
case ']':
peek = ' ';
lex_item.id = lex_item.op = TOK_RBRACKET;
return TOK_RBRACKET;
case '{':
peek = ' ';
lex_item.id = lex_item.op = TOK_LBRACE;
return TOK_LBRACE;
case '}':
peek = ' ';
lex_item.id = lex_item.op = TOK_RBRACE;
return TOK_RBRACE;
case ',':
peek = ' ';
lex_item.id = lex_item.op = TOK_COMMA;
return TOK_COMMA;
case '+':
peek = ' ';
lex_item.id = lex_item.op = TOK_PLUS;
return TOK_PLUS;
case '-':
peek = ' ';
lex_item.id = lex_item.op = TOK_MINUS;
return TOK_MINUS;
case '*':
peek = ' ';
lex_item.id = lex_item.op = TOK_MUL;
return TOK_MUL;
case '/':
peek = ' ';
lex_item.id = lex_item.op = TOK_DIV;
return TOK_DIV;
case '\n':
peek = ' ';
lex_item.id = lex_item.op = TOK_EOL;
return TOK_EOL;
case EOF:
peek = ' ';
lex_item.id = lex_item.op = TOK_EOF;
return TOK_EOF;
}
peek = ' ';
lex_item.id = lex_item.op = TOK_UNKNOWN;
return TOK_UNKNOWN;
}
|
C
|
/*
* Stack.h:
* This module implements a stack (FIFO).
*
* Used to simulate recursion.
*/
#ifndef STACK_H_
#define STACK_H_
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
/*
* This struct represents the list of parameters needed for a recursive call,
* in order to find number of solutions to a board (i.e. supports exhaustive backtracking).
*/
typedef struct{
int i;
int j;
int lastUsed;
} Parameters;
/*
* This struct represents a Stack Node.
*/
typedef struct stackNode{
Parameters params;
struct stackNode *next;
} StackNode;
/*
* This struct represent a stack.
*/
typedef struct {
StackNode *top;
} Stack;
/*
* Initializes an empty stack.
*/
Stack* initialize();
/*
* Pushes a Parameters object (created from function parameters) to the stack.
*/
void push(int i, int j, int lastUsed, Stack *stk);
/*
* Removes the top from the stack.
* @pre - stack is not empty.
*/
Parameters pop(Stack *stk);
/*
* Removes the top from the stack, inserts it's fields to the references of i, j, lastUsed.
* @pre - stack is not empty.
*/
void popAndUpdate(Stack *stk, int *i, int *j, int *lastUsed);
/*
* Returns the element at the top of the stack.
* @pre - stack is not empty.
*/
Parameters top(Stack *stk);
/*
* Removes stack and all it's elements, frees all memory resources.
*/
void destroyStack(Stack *stk);
/*
* Returns 1 iff the stack is empty.
*/
int isEmpty(Stack *stk);
#endif /* STACK_H_ */
|
C
|
#include <stdio.h>
#include <time.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <stdlib.h>
#include <dlfcn.h>
#include "contact.h"
#include <unistd.h>
#include <errno.h>
#ifdef DYNLIB
contacts_unidb* (*d_cunidb_initialize)(int type);
void (*d_cunidb_free)(contacts_unidb* db);
struct contact_uninode* (*d_cunidb_add)(contacts_unidb* db, char* name, char* surname,
char* birthdate, char* email, char* phone, char* address); //returns an index of created element
void (*d_cunidb_remove)(contacts_unidb* db, struct contact_uninode* item);
struct contact_uninode* (*d_cunidb_get)(contacts_unidb* db, uint32_t index);
//iterator
void (*d_cunidb_iterator_reset)(contacts_unidb* db);
bool (*d_cunidb_iterator_empty)(contacts_unidb* db);
struct contact_uninode* (*d_cunidb_iterator_next)(contacts_unidb* db);
//finding functions
struct contact_uninode* (*d_cunidb_find)(contacts_unidb* db, char* name, char* surname,
char* birthdate, char* email, char* phone, char* address);
void (*d_cunidb_sort)(contacts_unidb* db, int sorttype);
void* contactlib;
void load_lib(){
contactlib = dlopen("./../lib/libcontact-shared.so", RTLD_LAZY);
if (!contactlib){
fprintf(stderr, "Fatal error: could not have loaded dynamic library: %s\n", dlerror());
exit(1);
}
d_cunidb_initialize = dlsym(contactlib, "cunidb_initialize");
d_cunidb_free = dlsym(contactlib, "cunidb_free");
d_cunidb_add = dlsym(contactlib, "cunidb_add");
d_cunidb_remove = dlsym(contactlib, "cunidb_remove");
d_cunidb_get = dlsym(contactlib, "cunidb_get");
d_cunidb_iterator_reset = dlsym(contactlib, "cunidb_iterator_reset");
d_cunidb_iterator_empty = dlsym(contactlib, "cunidb_iterator_empty");
d_cunidb_iterator_next = dlsym(contactlib, "cunidb_iterator_next");
d_cunidb_find = dlsym(contactlib, "cunidb_find");
d_cunidb_sort = dlsym(contactlib, "cunidb_sort");
}
void close_lib(){
dlclose(contactlib);
}
#endif
int parse_data(contacts_unidb* db, const char* filename){
FILE* file = fopen(filename, "r");
if (!file){
fprintf(stderr, "Fatal error: Could not have opened sample data file.\n");
exit(1);
}
char line[448];
int curr = 0, field_ndx = 0;
char* fields[6];
fgets(line, 448, file); //skip first line
while (fgets(line, 448, file)){
for (int i = 0; i < 6; i++) fields[i] = NULL;
fields[0] = line;
field_ndx = 1;
curr = 0;
while (line[curr] != '\0' && line[curr] != '\n')
{
if (line[curr] == ';') {
line[curr] = '\0';
fields[field_ndx] = line + curr + 1;
field_ndx++;
}
curr++;
}
#ifndef DYNLIB
cunidb_add(db, fields[0], fields[1], fields[2], fields[3], fields[4], fields[5]);
#else
(*d_cunidb_add)(db, fields[0], fields[1], fields[2], fields[3], fields[4], fields[5]);
#endif
}
fclose(file);
return 0;
}
void print_item(struct contact_uninode* item){
if (item)
printf("#%d %-12s %-12s %-10s %-12s %-12s %-12s\n", item->index, item->name, item->surname,
item->birthdate, item->email, item->phone, item->address);
}
struct timespec *ts_start, *ts_end;
struct rusage *ru_start, *ru_end;
void start_measuring(){
clock_gettime(CLOCK_REALTIME, ts_start);
getrusage(RUSAGE_SELF, ru_start);
}
void print_measured(){
clock_gettime(CLOCK_REALTIME, ts_end);
getrusage(RUSAGE_SELF, ru_end);
double real_delta_ms = (ts_end->tv_sec - ts_start->tv_sec)*1000.0
+ (ts_end->tv_nsec - ts_start->tv_nsec)/1000000.0;
double sys_delta_ms = (ru_end->ru_stime.tv_sec - ru_start->ru_stime.tv_sec)*1000
+ (ru_end->ru_stime.tv_usec - ru_start->ru_stime.tv_usec)/1000.0;
double usr_delta_ms = (ru_end->ru_utime.tv_sec - ru_start->ru_utime.tv_sec)*1000
+ (ru_end->ru_utime.tv_usec - ru_start->ru_utime.tv_usec)/1000.0;
printf(" \x1B[33m[real: %.4fms sys: %.4fms usr: %.4fms]\x1B[0m\n", real_delta_ms, sys_delta_ms, usr_delta_ms);
}
void test_cunidb(contacts_unidb* db){
printf("---------\nTESTING CUNIDB library\n-------\n");
if (!db){
printf("Fatal error: db has not been initialized!\n");
exit(1);
}
printf("Type: %s\n", db->type == CONTACT_UNIDB_BT ? "R&B Binary tree" : "Double-linked list");
ts_start = malloc(sizeof(struct timespec));
ts_end = malloc(sizeof(struct timespec));
ru_start = malloc(sizeof(struct rusage));
ru_end = malloc(sizeof(struct rusage));
start_measuring();
printf("=>Importing data...");
parse_data(db, "../sample1000.csv");
printf(" [+]");
print_measured();
start_measuring();
printf("=>Listing data...");
#ifndef DYNLIB
cunidb_iterator_reset(db);
int counter = 0;
while (!cunidb_iterator_empty(db)){
struct contact_uninode* tt = cunidb_iterator_next(db);
if (tt) counter++;
}
#else
(*d_cunidb_iterator_reset)(db);
int counter = 0;
while (!(*d_cunidb_iterator_empty)(db)){
struct contact_uninode* tt = (*d_cunidb_iterator_next)(db);
if (tt) counter++;
}
#endif
printf(" [%d items][+]", counter);
print_measured();
start_measuring();
printf("=>Adding item (to the end)...");
#ifndef DYNLIB
#ifndef BUGGED
struct contact_uninode* added =
cunidb_add(db, "Test", "Added", "01-01-2001",
"test@test.pl", "123456789", "TestCity, Test 15");
#else
struct contact_uninode* added = cunidb_get(db, 0);
cunidb_add(db, "Test", "Added", "01-01-2001",
"test@test.pl", "123456789", "TestCity, Test 15");
#endif
#else
struct contact_uninode* added =
(*d_cunidb_add)(db, "Test", "Added", "01-01-2001",
"test@test.pl", "123456789", "TestCity, Test 15");
#endif
printf(" [#%d][+]", added->index);
print_measured();
start_measuring();
struct contact_uninode* searched;
printf("=>Searching for first item from file... (optimistic)");
#ifndef DYNLIB
searched = cunidb_find(db, "H", "Bell", NULL, "hbell0@ezinearticles.com", NULL, NULL);
#else
searched = (*d_cunidb_find)(db, "H", "Bell", NULL, "hbell0@ezinearticles.com", NULL, NULL);
#endif
if (searched) {
printf(" [#%d][+]", searched->index);
}
else printf(" [not found]");
print_measured();
start_measuring();
printf("=>Searching for the last item from file... (pessimistic)");
#ifndef DYNLIB
searched = cunidb_find(db, "C", "Perez", NULL, NULL, NULL, NULL);
#else
searched = (*d_cunidb_find)(db, "C", "Perez", NULL, NULL, NULL, NULL);
#endif
if (searched) {
printf(" [#%d][+]", searched->index);
}
else printf(" [not found]");
print_measured();
start_measuring();
printf("=>Deleting random item #[2, n-1]...");
uint32_t ndx = (rand() % (added->index-1)) + 1;
#ifndef DYNLIB
cunidb_remove(db, cunidb_get(db, ndx));
#else
(*d_cunidb_remove)(db, (*d_cunidb_get)(db, ndx));
#endif
printf(" [#%d][+]", ndx);
print_measured();
start_measuring();
printf("=>Deleting first item (or root)... (optimistic)");
#ifndef DYNLIB
cunidb_remove(db, db->first);
#else
(*d_cunidb_remove)(db, db->first);
#endif
printf(" [+]");
print_measured();
start_measuring();
printf("=>Deleting last item (by index)... (pessimistic)");
#ifndef DYNLIB
cunidb_remove(db, cunidb_get(db, added->index-1));
#else
(*d_cunidb_remove)(db, (*d_cunidb_get)(db, added->index-1));
#endif
printf(" [+]");
print_measured();
start_measuring();
printf("=>Rebuilding database with surname sorting...");
#ifndef DYNLIB
cunidb_sort(db, CONTACT_UNIDB_SORT_SURNAME);
#else
(*d_cunidb_sort)(db, CONTACT_UNIDB_SORT_SURNAME);
#endif
printf(" [+]");
print_measured();
start_measuring();
printf("=>Listing data again (checking db consistency)...");
#ifndef DYNLIB
cunidb_iterator_reset(db);
counter = 0;
while (!cunidb_iterator_empty(db)){
struct contact_uninode* tt = cunidb_iterator_next(db);
if (tt) counter++;
}
#else
(*d_cunidb_iterator_reset)(db);
counter = 0;
while (!(*d_cunidb_iterator_empty)(db)){
struct contact_uninode* tt = (*d_cunidb_iterator_next)(db);
if (tt) counter++;
}
#endif
printf(" [%d items][+]", counter);
print_measured();
free(ts_start);
free(ts_end);
free(ru_end);
free(ru_start);
printf("-------\nTEST FINISHED\n--------\n\n");
}
int main(void){
time_t t;
srand((unsigned int)time(&t));
#ifdef DYNLIB
load_lib();
#endif
#ifndef DYNLIB
contacts_unidb* db = cunidb_initialize(CONTACT_UNIDB_DLL);
test_cunidb(db);
cunidb_free(db);
db = cunidb_initialize(CONTACT_UNIDB_BT);
test_cunidb(db);
cunidb_free(db);
#else
contacts_unidb* db = (*d_cunidb_initialize)(CONTACT_UNIDB_DLL);
test_cunidb(db);
(*d_cunidb_free)(db);
db = (*d_cunidb_initialize)(CONTACT_UNIDB_BT);
test_cunidb(db);
(*d_cunidb_free)(db);
#endif
#ifdef DYNLIB
close_lib();
#endif
return 0;
}
|
C
|
/*
题目:打印出所有的"水仙花数",所谓"水仙花数"是指一个三位数,其各位数字立方和等于该数 本身。
例如:153是一个"水仙花数",因为153=1的三次方+5的三次方+3的三次方。
程序分析:利用for循环控制100-999个数,每个数分解出个位,十位,百位。
*/
#include<stdio.h>
#include<math.h>
//输入一个整数,判断此整数是否为水仙花数,是则返回1,否则0
int judge(int number) {
int ge, shi, bai;
int forjudge1 = number;
bai = number / 100;//百位
number = number % 100;
shi = number / 10;//十位
ge = number % 10;//个位
int forjudge2 = pow(bai, 3) + pow(shi, 3) + pow(ge, 3);
if (forjudge1 == forjudge2)
return 1;
return 0;
}
int main()
{
int MIN,MAX,jud=1;;
scanf("%d %d",&MIN,&MAX);
for (int i = MIN; i < MAX; i++) {
int forjudge = judge(i);
if (forjudge == 1) {
printf(" %d ", i);
jud=0;
}
}
if(jud)
printf("no");
return 0;
}
|
C
|
#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <ctype.h>
#include <strings.h>
#include <errno.h>
#include "wrap.h"
#include <limits.h>
#include <poll.h>
#define SERV_IP "127.0.0.1"
#define SERV_PORT 6666
#define MAXLINE 1024
#define LISTENEQ 128
#define OPEN_MAX 1024
int main()
{
int i, maxi, listenfd, connfd, sockfd;
int nready;
ssize_t n;
char buf[MAXLINE];
struct pollfd client[OPEN_MAX];
struct sockaddr_in cliaddr, servaddr;
socklen_t clilen;
listenfd = Socket(AF_INET, SOCK_STREAM, 0);
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(SERV_PORT);
int opt = 1;
setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
Bind(listenfd, (struct sockaddr *)& servaddr, sizeof(servaddr));
Listen(listenfd, LISTENEQ);
client[0].fd = listenfd;
client[0].events = POLLRDNORM;
for(i = 1; i < OPEN_MAX; i++)
client[i].fd = -1;
maxi = 0;
while(1)
{
nready = Poll(client, maxi + 1, -1);
if(client[0].revents & POLLRDNORM)
{
clilen = sizeof(cliaddr);
connfd = Accept(listenfd, (struct sockaddr*)&cliaddr, &clilen);
for(i = 1; i < OPEN_MAX; i++)
if(client[i].fd < 0) {
client[i].fd = connfd;
break;
}
if(i == OPEN_MAX)
perr_exit("too many clients");
client[i].events = POLLRDNORM;
if(i > maxi)
maxi = i;
if(--nready <= 0)
continue;
}
for(i = 1; i <= maxi; i++)
{
if( (sockfd = client[i].fd) < 0)
continue;
if(client[i].revents & (POLLRDNORM | POLLERR))
{
if( (n = Read(sockfd, buf, MAXLINE)) < 0) {
if(errno == ECONNRESET){
Close(sockfd);
client[i].fd = -1;
} else
perr_exit("read error");
}
else if(n == 0) {
Close(sockfd);
client[i].fd = -1;
} else {
Writen(STDOUT_FILENO, buf, n);
for(int j = 0; j < n; j++)
buf[j] = toupper(buf[j]);
Writen(sockfd, buf, n);
}
if(--nready <= 0)
break;
}
}
}
return 0;
}
|
C
|
/*********************************************************************************
* Despina Patronas, Dpatrona
* 2021 Winter CSE 101 pa7
* Arithmetic.c
*********************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "List.h"
#include "BigInteger.h"
#define MAX_LEN 300
int main(int argc, char * argv[]) {
int len = 0;
FILE *in;
FILE *out;
// check command line for correct number of arguments
if( argc != 3 ){
printf("Usage: %s <input file> <output file>\n", argv[0]);
exit(1);
}
// open files for reading and writing
in = fopen(argv[1], "r");
if( !in ){
printf("Unable to open file %s for reading\n", argv[1]);
exit(1);
}
out = fopen(argv[2], "w");
if( !out ){
printf("Unable to open file %s for writing\n", argv[2]);
exit(1);
}
BigInteger A;
BigInteger B;
BigInteger S;
BigInteger P;
BigInteger Z;
//input the first Big Int
//=================================================
fscanf(in, "%d\n", &len);
char str[len+1];
fscanf(in, "%s\n", str );
A = stringToBigInteger(str);
printBigInteger(out, A); fprintf(out, "\n\n");
//input the second Big Int
//=================================================
fscanf(in, "%d\n", &len);
char str2[len+1];
fscanf(in, "%s\n", str2 );
B = stringToBigInteger(str2);
printBigInteger(out, B); fprintf(out, "\n\n");
// Arithmetic
//=================================================
//A+B
S = sum(A,B);
printBigInteger(out, S); fprintf(out, "\n\n");
//B-A
S = diff(A,B);
printBigInteger(out, S); fprintf(out, "\n\n");
//A-A
S = diff(A,A);
printBigInteger(out, S); fprintf(out, "\n\n");
//scalars
BigInteger Two = stringToBigInteger("2");
BigInteger Three = stringToBigInteger("3");
// BigInteger Nine = stringToBigInteger("9");
// BigInteger SixT = stringToBigInteger("16");
P = prod(Three,A); // 3A
Z = prod(Two, B); // 2B
//3A-2B
S = diff(P,Z);
printBigInteger(out, S); fprintf(out, "\n\n");
// A*B
P = prod(A,B);
printBigInteger(out, P); fprintf(out, "\n\n");
// Z = prod(A,A); // A*A = A^2
// printBigInteger(out, Z); fprintf(out, "\n\n");
// P = prod(B,B); // B*B = B^2
// printBigInteger(out, P); fprintf(out, "\n\n");
// Z = prod(Z,Z); // A^2*A^2 = A^4
// Z = prod(Nine,Z); // 9A^4
// printBigInteger(out, Z); fprintf(out, "\n\n");
// P = prod(P,P); //B^2*B^2 = B^4
// P = prod(P,B); //B^4*B = B^5
// S = sum(Z,P);
freeBigInteger(&A);
freeBigInteger(&B);
freeBigInteger(&S);
freeBigInteger(&P);
freeBigInteger(&Z);
freeBigInteger(&Two );
freeBigInteger(&Three);
// freeBigInteger(&Nine );
// freeBigInteger(&SixT );
fclose(in);
fclose(out);
return 0;
}
|
C
|
#include <stdio.h>
#define TAM 40
#define NUMSOCI 5
/*
M03.PROG-UF1:NF2
PT: Exercicis Estructures complexes.
Nombre: Luis Ramos Santos.
Fecha: 19/02/2018.
Descripcin:
Ex5.Crea un programa per realitzar la gesti dels socis d'un club.
L'estructura del soci t id_soci, nom i edat.
El programa tindr les segents funcions:
Alta soci
Consulta un soci
Consulta massiva (Mostra tots els socis)
Esborra soci
Ordenar per nmero
Ordenar per inicial del nom
Ordenar per edat
Eliminar tots els socis
Sortir
*/
typedef struct{
int id_soci;
char nom[TAM];
int edad;
}Soci;
typedef struct{
Soci lista[NUMSOCI];
int tam;
}Registro;
void getSoci(Soci *s)
{
//Definir una variable
printf("\n\376 Datos Personales |\n");
printf(" -----------------\n");
printf("\n\t\20 ID: ");
fflush(stdin);
scanf("%i",&s->id_soci);
printf("\n\t\20 Nombre: ");
fflush(stdin);
gets(s->nom);
printf("\n\t\20 Edad: ");
fflush(stdin);
scanf("%i",&s->edad);
}
/******PROTOTIPOS******/
void AltaSoci(Registro r[], int *tam);
void ConsultaSoci(Registro r[], int tam);
void MostraSoci(Registro r[], int tam);
void BorrarSoci(Registro r[], int *tam);
void Ordenar_Id(Registro r[], int tam);
void Ordenar_IniNom(Registro r[], int tam);
void Ordenar_edad(Registro r[], int tam);
void BorrarRegistros(Registro r[], int *tam);
/******MAIN******/
int main(){
Registro socio;
Registro socios[NUMSOCI];
int tam=0;
BorrarRegistros(&socio);
int opcion;
do
{
system("cls");
printf("\n\n\t\4 \4 \4 \4 \4 Bienvenido al Club \4 \4 \4 \4 \4\n\n");
printf("\t\t1. Alta socio\n\n");
printf("\t\t2. Consultar socio\n\n");
printf("\t\t3. Mostrar socios\n\n");
printf("\t\t4. Borrar socio\n\n");
printf("\t\t5. Ordenar por Id\n\n");
printf("\t\t6. Ordenar por inicial nombre\n\n");
printf("\t\t7. Ordenar por edad\n\n");
printf("\t\t8. Borrar todos los socios\n\n");
printf("\t\t9. Salir\n\n");
printf("\t\4 Introduzca su opcion: ");
fflush(stdin);
scanf("%i",&opcion);
switch(opcion)
{
case 1: system("cls");printf("\n\t\20 Agregando...\n\n");
AltaSoci(&socio);
system("pause");system("cls");
break;
case 2: system("cls");printf("\n\t\20 Mostrando...\n\n");
ConsultaSoci(socio);
system("pause");system("cls");
break;
case 3: system("cls");printf("\n\t\20 Mostrando...\n\n");
MostraSoci(socio);
system("pause");system("cls");
break;
case 4: system("cls");printf("\n\t\20 Borrando...\n\n");
BorrarSoci(socios,&tam);
system("pause");system("cls");
break;
case 5: system("cls");printf("\n\t\20 Ordenando...\n\n");
Ordenar_Id(socio);
system("pause");system("cls");
break;
case 6: system("cls");printf("\n\t\20 Ordenando...\n\n");
Ordenar_IniNom(socio);
system("pause");system("cls");
break;
case 7: system("cls");printf("\n\t\20 Ordenando...\n\n");
Ordenar_edad(socio);
system("pause");system("cls");
break;
case 8: system("cls");printf("\n\t\20 Borrando...\n\n");
BorrarRegistros(&socio);
printf("\n\t\t ----------\n");
printf("\t\t\4 Borrado! \4");
printf("\n\t\t ----------\n");
system("pause");system("cls");
break;
case 9: system("cls");printf("\n\t\20 Saliendo...\n\n");
printf("\t\4 Registraste %i socios\n\n",socio.tam);
printf("\n\t\t -----------------------\n");
printf("\t\t \3 Gracias por su visita \3 ");
printf("\n\t\t -----------------------\n\n\n");
system("pause");system("cls");
break;
default:printf("Error!!\n");break;
};
}while(opcion!=9);
return 0;
}
void AltaSoci(Registro r[], int *tam){
int ultima;
if(r->tam < NUMSOCI)
{
getSoci(&r->lista[ultima]);
r->tam=r->tam+1;
system("cls");
printf("\n\t\t -----------------\n");
printf("\t\t \4 Soci registrado \4");
printf("\n\t\t -----------------\n\n\n");
}
else
{
system("cls");
printf("\n\t\t ----------------------------------\n");
printf("\t\t\4 Alcanzo el limite de socios!!! \4\n");
printf("\t\t ----------------------------------\n\n\n");
system("pause");system("cls");
}
}
void ConsultaSoci(Registro r){
int id,i;
printf("\n\tDime el ID del soci a consultar: ");
scanf("%i",&id);
printf("\n\n\tBuscando el %i socio",id);
for(i=0;i<r.tam;i++){
if(r.lista[i].id_soci==id){
printf("\n\tID: %i\n",r.lista[i].id_soci);
printf("\n\tNombre: %s\n", r.lista[i].nom);
printf("\n\tEdad: %i\n", r.lista[i].edad);
}
}
}
void MostraSoci(Registro r){
int i ;
printf("\n\376 Numero de socios: %i \n\n\n",r.tam);
for(i=0; i<r.tam; i++)
{
printf("\t\20 ID %i\n",r.lista[i].id_soci);
printf("\t\20 Nombre: %s\n", r.lista[i].nom);
printf("\t\20 Edad: %i\n",r.lista[i].edad);
}
printf("\n\n");
}
void BorrarSoci(Registro r[],int *tam){
int id,i,pos;
printf("\n\tDime el ID del soci a borrar: ");
scanf("%i",&id);
pos=-1;
for(i=0;i<*tam;i++)
{
if(r->lista[i].id_soci==id) pos=i;
}
if(pos>=0)
{
for(i=pos;i<*tam -1 ;i++)
{
printf("\n\tSocio: %s\n",r->lista[i].id_soci);
printf("\n\tNombre: %s\n", r->lista[i].nom);
printf("\n\tEdad: %i\n", r->lista[i].edad);
}
*tam=*tam-1;
}
}
void Ordenar_Id(Registro r){
}
void Ordenar_IniNom(Registro r){
}
void Ordenar_edad(Registro r){
}
void BorrarRegistros(Registro *r){
r->tam=0;
}
|
C
|
/*
** EPITECH PROJECT, 2017
** bubble_sort.c
** File description:
** bubble_sort
*/
#include <criterion/criterion.h>
#include <unistd.h>
#include <stdio.h>
void my_swap(int *a, int *b)
{
int c;
c = *a;
*a = *b;
*b = c;
}
void swap_elem (int *array, int index1, int index2)
{
my_swap(&array[index1], &array[index2]);
}
void bubble_loop(int *array, int i, int size)
{
for (int j = 0; j < size-i-1; j++) {
if (array[j] > array [j + 1])
swap_elem(array, j, j + 1);
}
}
void bubble_sort_array(int *array, int size)
{
for(int i = 0; i < size -1; i++)
bubble_loop(array, i, size);
}
void print(int *array, int size)
{
int i;
for ( i=0; i < size; i++)
printf("%d", array[i]);
}
int main ()
{
int str[4] = { 9, 7, 5, 3};
bubble_sort_array(str, 4);
print(str, 4);
}
|
C
|
#include<stdio.h>
void move(int ,char ,char);
void hanoi(int ,char ,char ,char);
int index=0;
int main()
{
hanoi(2,'A','B','C');
return 0;
}
void move(int n,char x,char y)
{
printf("%dst move %c ---> %c \n",++index,x,y);
}
void hanoi(int n,char x,char y,char z)
{
if(n==1)
move(1,x,z);
else
{
hanoi(n-1,x,z,y);
move(n,x,z);
hanoi(n-1,y,x,z);
}
}
|
C
|
//
// gmVector.c
// MyOpenGLES
//
// Created by Archer_LJ on 14-7-10.
// Copyright (c) 2014年 Archer_LJ. All rights reserved.
//
#include <stdio.h>
#include <math.h>
#include "gmVector.h"
#include <string.h>
void InitgmVector2(gmVector2* vec)
{
memset(vec, 0, sizeof(gmVector2));
}
void InitgmVector3(gmVector3* vec)
{
memset(vec, 0, sizeof(gmVector3));
}
void InitgmVector4(gmVector4* vec)
{
memset(vec, 0, sizeof(gmVector4));
vec->w = 1.0f;
}
void gmVec3Normalize(gmVector3* out, gmVector3* in)
{
float f = in->x * in->x + in->y * in->y + in->z * in->z;
f = 1.0f / sqrt(f);
out->x = in->x * f;
out->y = in->y * f;
out->z = in->z * f;
}
void gmVec3CrossProduct(gmVector3* out, gmVector3* v1, gmVector3* v2)
{
gmVector3 result;
result.x = v1->y * v2->z - v1->z * v2->y;
result.y = v1->z * v2->x - v1->x * v2->z;
result.z = v1->x * v2->y - v1->y * v2->x;
*out = result;
}
|
C
|
//Проверка на целое, если рациональное число
//является целым, то «да», иначе «нет»
//Подключаемые модули отсутствуют
//int INT_Q_Z(struct RATIONAL a), где a - проверяемое число
//Функция возвращает 1, если проверяемое число целое, иначе 0
//Плотников Юрий - 5307
int INT_Q_Z(struct RATIONAL a)
{
if (a.denominator.number)
return (a.denominator.index == 1 && a.denominator.number[0] == 1)? 1 : 0;
return 1;
}
|
C
|
#include <stdio.h>
int main()
{
int n;
scanf("%d",&n);
if(n>=30 && n<=50)
printf("\nD");
else if(n>=51 && n<=60)
printf("\nC");
else if(n>=61 && n<=80)
printf("\nB");
else if(n>=81 && n<=100)
printf("\nA");
else
printf("\nInvalid Input");
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include<conio.h>
#define f(x) (exp(-(pow(x,2))))
int main()
{
int i,n;
float a,b,x[30],y[30],wedd=0,h;
printf("Enter the lower and upper limit:");
scanf("%f%f",&a,&b);
printf("Enter the number of intervals");
scanf("%d",&n);
h=((b-a)/n);
printf("\n h=%f",h);
x[0]=a;
for(i=0;i<=n;i++)
{
y[i]=f(x[i]);
x[i+1]=x[i]+h;
printf("\nx=%f y=%f",x[i],y[i]);
}
for(i=0;i<n-5;i+=6)
{
wedd=wedd+(3*h/10)*(y[i]+5*y[i+1]+y[i+2]+6*y[i+3]+y[i+4]+5*y[i+5]+y[i+6]);
printf("\ni=%d,y[%d]=%f,y[%d+1]=%f",i,i,y[i],i,y[i+1]);
}
printf("\n The result is:%f",wedd);
return 0;
}
|
C
|
/*
** EPITECH PROJECT, 2020
** programP1
** File description:
** navy
*/
#include "my.h"
general_t g;
void display_pid_p1(void)
{
pid_t pid = getpid();
my_putstr("my_pid: ");
display_nbr(pid);
my_putstr("waiting for enemy connection...\n\n");
}
void get_pid(int sig, siginfo_t *info, void *context)
{
kill(info->si_pid, SIGUSR2);
write(1, "enemy connected\n\n", 17);
g.pid_p2 = info->si_pid;
}
void connection_to_p2(Player *j)
{
struct sigaction sa = { 0 };
sa.sa_flags = SA_SIGINFO;
sa.sa_sigaction = get_pid;
sigaction(SIGUSR1, &sa, NULL);
pause();
j->pid_player2 = g.pid_p2;
}
int program_player1(Player *j, char *pos1)
{
int wog = 0;
display_pid_p1();
connection_to_p2(j);
wog = game_p1_pov(j, pos1);
return (wog);
}
|
C
|
/**
* @file
* @brief Relabels each connected component to guarantee a consistent map.
* @author Felipe Lemes Galvao
*/
#include <ift.h>
#include "iftSuperpixelFeatures.h"
#include "iftExperimentUtility.h"
int main(int argc, char* argv[]) {
if (argc < 3)
iftError("Usage: %s <input img> <output_img> [min_region_size]", "main", argv[0]);
iftImage *labelMap = iftReadImageByExt(argv[1]);
int minSize = (argc > 3) ? atol(argv[3]) : 0;
iftImage *res = iftForceLabelMapConnectivity(labelMap, minSize);
iftWriteImageByExt(res, argv[2]);
iftDestroyImage(&labelMap);
iftDestroyImage(&res);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main() {
int *p, n;
printf("Enter number of integers: ");
scanf("%d", &n);
p = (int *) malloc(n * sizeof(int));
if (p == NULL) {
printf("Unable to allocate memory. Exiting the program...\n");
exit(1);
}
/* exit(0) --> successful termination OR normal termination
exit(1) --> unsuccessful termination OR exceptional exit*/
for (int i = 0; i < n; i++) {
printf("Enter value #%d: ", i);
scanf("%d", p+i); // using p+i and not &(whatever) coz p points directly to the location
}
printf("\nContents of the array: \n");
for (int i = 0; i < n; ++i) {
printf("%4d", *(p+i));
}
int new_num = n + 3;
p = (int *) realloc(p, new_num * sizeof(int));
if (p == NULL) {
printf("Unable to allocate memory. Exiting the program...\n");
exit(1);
}
*(p+n) = 10;
*(p+n+1) = 20;
*(p+n+2) = 30;
printf("\n\nModified content of the array: \n");
for (int i = 0; i < new_num; ++i) {
printf("%4d", *(p+i));
}
free(p);
return 0;
}
|
C
|
#include <pads.pri>
static void Proto(p) { PutRemote(p); }
static void CheckProto( p ) { if( GetRemote() != p ) ProtoErr(); }
static long ShiftIn( bytes )
register bytes;
{
register long shifter = 0;
CheckProto( bytes );
while( bytes-- ) shifter = (shifter<<8) + (GetRemote()&0xFF);
return shifter;
}
long RcvLong() { return (long) ShiftIn( P_LONG ); }
short RcvShort() { return (short) ShiftIn( P_SHORT ); }
unsigned char RcvUChar() { return (unsigned char) ShiftIn( P_UCHAR ); }
static void ShiftOut( bytes, shifter )
register bytes;
register long shifter;
{
Proto( bytes );
do { PutRemote( (char)(shifter>>( (--bytes)*8 )) ); } while( bytes );
}
void SendLong(x) long x; { ShiftOut( P_LONG, (long) x ); }
void SendShort(x) short x; { ShiftOut( P_SHORT, (long) x ); }
void SendUChar(x) unsigned char x; { ShiftOut( P_UCHAR, (long) x ); }
char *RcvString( s0 )
char *s0;
{
register char *s = s0;
register unsigned char len;
CheckProto( P_STRING );
len = RcvUChar();
if( !s0 ) s = s0 = new char [len+1];
while( len-->0 ) *s++ = GetRemote();
*s = '\0';
return s0;
}
void SendString(s)
register char *s;
{
int len;
Proto( P_STRING );
len = strlen(s);
if( len > 255 ) len = 255;
SendUChar( len );
while( len-- ) PutRemote(*s++);
}
|
C
|
/*
* Hearthstone
* Copyright (C) 2005-2008 Hearthstone <http://www.hearthstone-project.com/>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "log.h"
#include "configfile.h"
#include "mutex.h"
#include "linkedlist.h"
#include "network.h"
#include "network_handlers.h"
#include "voice_channel.h"
#include <signal.h>
int running = 1;
void signal_handler(int s)
{
running = 0;
}
void status_updater_thread(void* unused)
{
float bandwidth_in = 0.0f;
float bandwidth_out = 0.0f;
int channels = 0;
int servers = 0;
while( running )
{
network_get_bandwidth_statistics( &bandwidth_in, &bandwidth_out );
channels = voice_get_channel_count();
servers = get_server_count();
// remember these are in bytes, so convert to kb
bandwidth_in /= 1000.0f;
bandwidth_out /= 1000.0f;
// dump to console
printf("\r| %02u servers | %05u channels | in: %04.2f KB/s | out: %04.2f KB/s |",
servers, channels, bandwidth_in, bandwidth_out );
vc_sleep(1000);
}
}
int main(int argc, char* argv[])
{
configfile_init();
if( configfile_parsecmdoverride(argc, argv) < 0 )
return -1;
log_open();
// read config file
if( configfile_load_config("ascent-voicechat.conf") < 0 )
{
// this needs to be cmd-line overrideable
log_write(ERROR, "FATAL: Could not open a valid config file. Exiting.");
return -1;
}
printf("Ascent Voicechat Server\n");
printf("Starting...\n");
if( network_init() < 0 )
{
log_write(ERROR, "FATAL: Network failed initialization.");
return -1;
}
printf("Binding sockets...\n");
if( voicechat_init_clientsocket() < 0 || voicechat_init_serversocket() < 0 )
{
log_write(ERROR, "FATAL: Could not bind sockets.");
return -1;
}
signal(SIGINT, signal_handler);
signal(SIGTERM, signal_handler);
#ifdef WIN32
signal(SIGBREAK, signal_handler);
#endif
printf("I/O Loop running...\n");
start_thread(status_updater_thread, NULL);
while(running)
{
network_io_poll();
}
printf("Shutting down...\n");
network_shutdown();
log_close();
return 0;
}
|
C
|
#include<stdio.h>
void main()
{
int r,*R,*a;
printf("enter r ");
scanf("%d",&r);
R=&r;
*a=3.14*(*R)*(*R);
printf("%d is area",*a);
}
|
C
|
/* using the stdlib.h library, we can execute terminal (bash) commands with the system() function -- for Unix/POSIX systems only*/
#include <stdio.h>
#include <stdlib.h>
int main()
{
system("echo \" Just a sample of the power this enables.\n \"");
printf("The above statement was executed by the echo command.\n");
// a sample of the power
system("mkdir folder");
system("touch folder/rep.c");
system("echo \"#include <stdio.h>\nint main(){printf(\\\"replication!!!!!!!!!!!!!\\\");return 0;}\" > folder/rep.c ");
system("gcc folder/rep.c -o folder/rep");
system("folder/rep");
return 0;
}
|
C
|
/*
** EPITECH PROJECT, 2017
** minishell.c
** File description:
** main.c
*/
#include <string.h>
size_t my_strlen(char *str)
{
size_t i = 0;
for (; str[i] != '\0'; i++);
return (i);
}
|
C
|
#include <stdio.h>
#include <string.h>
int mystrend(char *s, char *t);
int main()
{
char a[] = "football";
char b[] = "ball";
char c[] = "foot";
printf("strend(%s,%s): %i\n", a, b, mystrend(a,b));
printf("strend(%s,%s): %i\n", a, c, mystrend(a,c));
printf("strend(%s,%s): %i\n", c, a, mystrend(c,a));
printf("strend(%s,%s): %i\n", c, b, mystrend(c,b));
printf("strend(%s,%s): %i\n", b, b, mystrend(b,b));
printf("strend(%s,%s): %i\n", "", "", mystrend("",""));
return 0;
}
int mystrend(char *s, char *t)
{
int i, j;
if ((i = strlen(s)-1) < (j = strlen(t)-1))
return 0;
for (j; j > 0; i--, j--) {
if (*(s+i) != *(t+j))
return 0;
}
return 1;
}
|
C
|
#include<stdio.h>
void Fibonacci(int n);
main()
{
int k,n;
long int i=0,j=1,f;
printf("Enter the range of the Fibonacci series: ");
scanf("%d",&n);
printf("%d\n%d\n",0,1);
n=n-2;
fib(n);
}
void fib(int n)
{
static long int f=0,s=1,sum;
if(n>0)
{
sum=f+s;
f=s;
s=sum;
printf("%ld\n",sum);
fib(n-1);
}
}
|
C
|
#include <stdlib.h>
#include <aem/log.h>
#include "driver.h"
#include "display.h"
int liblcd_display_init(struct liblcd_display *disp, const struct liblcd_driver *driver, int param1, int param2, int param3, void *argv)
{
aem_assert(disp != NULL);
aem_assert(driver != NULL);
if (!liblcd_stream_ok(&disp->stream))
{
aem_logf_ctx(AEM_LOG_ERROR, "Not initializing display: no stream open. Call liblcd_stream_open_*(&disp.stream, ...) first.\n");
return 1;
}
aem_logf_ctx(AEM_LOG_NOTICE, "open display with driver %s\n", driver->name);
disp->driver = driver;
return disp->driver->init(disp, param1, param2, param3, argv);
}
int liblcd_display_close(struct liblcd_display *disp)
{
if (disp == NULL) return 0;
if (disp->driver != NULL)
{
aem_logf_ctx(AEM_LOG_NOTICE, "close display with driver %s\n", disp->driver->name);
disp->driver->close(disp);
}
else
{
aem_logf_ctx(AEM_LOG_WARN, "close display with no driver open\n");
}
liblcd_stream_close(&disp->stream);
return 0;
}
int liblcd_display_customchar(struct liblcd_display *disp, int i, const char def[8])
{
if (disp == NULL || disp->driver == NULL) return 1;
aem_logf_ctx(AEM_LOG_DEBUG, "define %d\n", i);
return disp->driver->customchar(disp, i, def);
}
int liblcd_display_mvstr(struct liblcd_display *disp, int y, int x, struct aem_stringslice s)
{
if (disp == NULL || disp->driver == NULL) return 1;
aem_logf_ctx(AEM_LOG_DEBUG, "%d, %d, %zd chars\n", y, x, aem_stringslice_len(&s));
return disp->driver->mvstr(disp, y, x, s);
}
int liblcd_display_backlight(struct liblcd_display *disp, int level)
{
if (disp == NULL || disp->driver == NULL) return 1;
aem_logf_ctx(AEM_LOG_DEBUG, "%d\n", level);
return disp->driver->backlight(disp, level);
}
int liblcd_display_contrast(struct liblcd_display *disp, int level)
{
if (disp == NULL || disp->driver == NULL) return 1;
aem_logf_ctx(AEM_LOG_DEBUG, "%d\n", level);
return disp->driver->contrast(disp, level);
}
int liblcd_display_cursor(struct liblcd_display *disp, enum liblcd_cursor_state state)
{
if (disp == NULL || disp->driver == NULL) return 1;
aem_logf_ctx(AEM_LOG_DEBUG, "%d\n", state);
return disp->driver->cursor(disp, state);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_printf_core.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: abeauvoi <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/09/02 13:02:32 by abeauvoi #+# #+# */
/* Updated: 2017/09/11 20:58:11 by abeauvoi ### ########.fr */
/* */
/* ************************************************************************** */
#include <unistd.h>
#include "ft_printf.h"
static void init_spec(t_ftpf_info *spec)
{
ft_bzero(spec, sizeof(t_ftpf_info));
spec->prec = -1;
spec->size = IS_INT;
}
static int exit_ft_printf(t_ftpf_buf *buffer, va_list *ap)
{
flush_buffer(buffer, buffer->current - buffer->start);
va_end(*ap);
return (buffer->done);
}
int ft_printf_core(const char *format, va_list *ap)
{
t_ftpf_info spec;
t_ftpf_buf buffer;
ft_bzero(buffer.start, BUF_SIZE + 1);
buffer.current = buffer.start;
buffer.end = buffer.start + BUF_SIZE;
buffer.done = 0;
buffer.fd = 1;
while (*format)
{
init_spec(&spec);
while (*format && *format != '%')
copy_to_buf(&buffer, *format++);
if (!*format ||
parse_one_spec(&format, ap, &spec, &buffer) == END_OF_FORMAT)
return (exit_ft_printf(&buffer, ap));
if (spec.flags & LEFT)
padding(&buffer, spec.width, ' ');
if (buffer.done == FAILURE)
return (FAILURE);
++format;
}
return (exit_ft_printf(&buffer, ap));
}
|
C
|
/* listen.c: thread to listen on a port and maintain connected fds */
/* there is a finite maximum number of fds -- once more are connected, */
/* old ones are closed */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include "listen.h"
#include "lib/packet.h"
#include "lib/pipemsg.h"
#include "lib/mgmt.h"
#include "lib/util.h"
#include "lib/pipemsg.h"
#include "lib/log.h"
#include "lib/ai.h"
/* returns the fd of the new listen socket, or -1 in case of error */
static int init_listen_socket (int version, int port, int local)
{
int isip6 = (version == 6);
int af = ((isip6) ? AF_INET6 : AF_INET);
int fd = socket (af, SOCK_STREAM, 0);
if (fd < 0) {
perror ("listen socket");
return -1;
}
/* allow us to reuse the port number immediately, rather than wait */
int option = 1;
if (setsockopt (fd, SOL_SOCKET, SO_REUSEADDR, &option, sizeof (int)) != 0)
perror ("setsockopt");
struct sockaddr_storage address;
struct sockaddr * ap = (struct sockaddr *) &address;
struct sockaddr_in * ap4 = (struct sockaddr_in *) ap;
struct sockaddr_in6 * ap6 = (struct sockaddr_in6 *) ap;
socklen_t addr_size = sizeof (address);
memset (&address, 0, addr_size);
if (isip6) {
ap6->sin6_family = AF_INET6;
if (local)
memcpy (&(ap6->sin6_addr), &(in6addr_loopback), sizeof (ap6->sin6_addr));
else
memcpy (&(ap6->sin6_addr), &(in6addr_any), sizeof (ap6->sin6_addr));
ap6->sin6_port = port;
addr_size = sizeof (struct sockaddr_in6);
} else {
ap4->sin_family = AF_INET;
if (local)
ap4->sin_addr.s_addr = htonl (INADDR_LOOPBACK);
else
ap4->sin_addr.s_addr = htonl (INADDR_ANY);
ap4->sin_port = port;
addr_size = sizeof (struct sockaddr_in);
}
int n = snprintf (log_buf, LOG_SIZE, "binding to ");
n += print_sockaddr_str (ap, addr_size, 1, log_buf + n, LOG_SIZE - n);
log_print ();
if (bind (fd, ap, addr_size) < 0) {
if (version == 6) {
perror ("bind");
n = snprintf (log_buf, LOG_SIZE,
"ipv%d unable to bind %d/%x(%d), maybe already running\n",
version, ntohs (port), ntohs (port), addr_size);
n += snprintf (log_buf + n, LOG_SIZE - n, "bind address is ");
n += print_sockaddr_str (ap, addr_size, 1, log_buf + n, LOG_SIZE - n);
log_print ();
} else {
snprintf (log_buf, LOG_SIZE,
"ipv%d unable to bind to %d/%x(%d), probably handled by ipv6\n",
version, ntohs (port), ntohs (port), addr_size);
log_print ();
}
return -1;
}
/* specify the maximum queue length */
if (listen (fd, 5) < 0) {
perror("listen");
return -1;
}
snprintf (log_buf, LOG_SIZE, "opened accept socket fd = %d, ip version %d\n",
fd, version);
log_print ();
return fd;
}
struct real_arg {
struct listen_info * info; /* struct listen_info is defined in listen.h */
int fd; /* listen socket for opening new connections */
};
static void * listen_loop (void * arg)
{
struct real_arg * ra = (struct real_arg *) arg;
snprintf (log_buf, LOG_SIZE, "started listen_loop, listen socket is %d\n",
ra->fd);
log_print ();
struct listen_info * info = ra->info;
/* allow the main thread to kill this thread at any time */
int notinteresting;
pthread_setcanceltype (PTHREAD_CANCEL_ASYNCHRONOUS, ¬interesting);
struct sockaddr_storage address;
struct sockaddr * ap = (struct sockaddr *) &address;
socklen_t addr_size = sizeof (address);
/* listen for connections, add them to the data structure */
int connection;
while ((connection = accept (ra->fd, ap, &addr_size)) >= 0) {
int off = snprintf (log_buf, LOG_SIZE,
"opened connection socket fd = %d port %d from ",
connection, ntohs (info->port));
/* sometimes an incoming IPv4 connection is recorded as an IPv6 connection.
* we want to record it as an IPv4 connection */
standardize_ip (ap, addr_size);
#ifdef DEBUG_PRINT
print_sockaddr_str (ap, addr_size, 1, log_buf + off, LOG_SIZE - off);
#else /* DEBUG_PRINT */
snprintf (log_buf + off, LOG_SIZE - off, "\n");
#endif /* DEBUG_PRINT */
log_print ();
int option = 1; /* disable Nagle algorithm if nodelay */
if ((ra->info->nodelay) &&
(setsockopt (connection, IPPROTO_TCP, TCP_NODELAY, &option,
sizeof (option)) != 0)) {
snprintf (log_buf, LOG_SIZE, "unable to set nodelay socket option\n");
log_print ();
}
struct addr_info addr;
sockaddr_to_ai (ap, addr_size, &addr);
listen_add_fd (info, connection, &addr);
if (info->callback != NULL)
info->callback (connection);
addr_size = sizeof (address); /* reset for next call to accept */
}
perror ("accept");
printf ("error calling accept (%d)\n", ra->fd);
return NULL;
}
void listen_init_info (struct listen_info * info, int max_fds, char * name,
int port, int local_only, int add_remove_pipe,
int nodelay, void (* callback) (int))
{
if (max_fds > 1024) {
printf ("using 1024 as the maximum number of open fds, %d is too large\n",
max_fds);
exit (1);
}
if (max_fds <= 0) {
printf ("invalid %d for max open fds\n", max_fds);
exit (1);
}
info->program_name = name;
info->port = port;
info->add_remove_pipe = add_remove_pipe;
info->num_fds = 0;
info->max_num_fds = max_fds;
info->fds = malloc_or_fail (max_fds * sizeof (int), "listen thread fds");
info->peers = malloc_or_fail (max_fds * sizeof (struct addr_info),
"listen thread peers");
info->used = malloc_or_fail (max_fds * sizeof (int), "listen thread used");
info->callback = callback;
info->nodelay = nodelay;
int i;
for (i = 0; i < max_fds; i++)
info->fds [i] = info->used [i] = info->peers [i].ip.ip_version = 0;
info->counter = 0;
pthread_mutex_init (&(info->mutex), NULL);
info->listen_fd6 = init_listen_socket (6, port, local_only);
info->listen_fd4 = init_listen_socket (4, port, local_only);
if (info->listen_fd6 < 0) {
snprintf (log_buf, LOG_SIZE, "unable to open IPv6 listener, exiting\n");
log_print ();
exit (1);
}
/* ipv4 may be handled under ipv6
if ((info->listen_fd4 < 0) || (info->listen_fd6 < 0)) {
snprintf (log_buf, LOG_SIZE, "unable to open IPv6 listener, exiting\n");
log_print ();
exit (1);
}
*/
struct real_arg * real_arg6 =
malloc_or_fail (sizeof (struct real_arg), "ip6 real arg");
real_arg6->info = info;
real_arg6->fd = info->listen_fd6;
if (pthread_create (&(info->thread6), NULL, listen_loop, real_arg6) != 0) {
perror ("listen6/pthread_create");
snprintf (log_buf, LOG_SIZE,
"unable to create listen thread for IP version 6, exiting\n");
log_print ();
exit (1);
}
if (info->listen_fd4 >= 0) {
/* printf ("allocating %ld bytes for 4\n", sizeof (struct real_arg)); */
struct real_arg * real_arg4 =
malloc_or_fail (sizeof (struct real_arg), "ip4 real arg");
/* printf ("allocated %ld bytes\n", sizeof (struct real_arg)); */
real_arg4->info = info;
real_arg4->fd = info->listen_fd4;
if (pthread_create (&(info->thread4), NULL, listen_loop, real_arg4) != 0) {
perror ("listen4/pthread_create");
snprintf (log_buf, LOG_SIZE,
"unable to create listen thread for IP version 4, exiting\n");
log_print ();
exit (1);
}
}
}
void listen_record_usage (struct listen_info * info, int fd)
{
int i;
if (info->counter + 1 == 0) { /* wrap around of counter value */
int decrement = info->counter - (info->counter / 16);
printf ("wrapping around counter values, decrement %d\n", decrement);
for (i = 0; i < info->num_fds; i++) {
printf ("%d: %d", i, info->used [i]);
if (decrement < info->used [i])
info->used [i] -= decrement;
else
info->used [i] = 0;
printf (" -> %d\n", info->used [i]);
}
info->counter = info->counter - decrement;
}
info->counter++;
for (i = 0; i < info->num_fds; i++)
if (info->fds [i] == fd)
info->used [i] = info->counter;
}
/* send a message describing my peers */
/* index is a peer to avoid sending, since it is itself */
static void send_peer_message (int fd, struct listen_info * info, int index)
{
if (info->num_fds <= 1) /* no peers to send */
return;
int npeers = info->num_fds;
if (npeers > 255)
npeers = 255;
int size = ALLNET_PEER_SIZE (0, npeers);
int hsize = ALLNET_SIZE (0);
int dsize = size - hsize;
int psize;
struct allnet_header * hp =
create_packet (dsize, ALLNET_TYPE_MGMT, 1, ALLNET_SIGTYPE_NONE,
NULL, 0, NULL, 0, NULL, NULL, &psize);
if (psize != size) {
snprintf (log_buf, LOG_SIZE,
"likely error: send_peer_message size %d, psize %d\n",
size, psize);
log_print ();
printf ("likely error: send_peer_message size %d, psize %d\n", size, psize);
exit (1); /* for now -- this should never happen! 2014/02/26 */
}
char * buffer = (char *) hp;
struct allnet_mgmt_header * mp =
(struct allnet_mgmt_header *) (buffer + ALLNET_SIZE (hp->transport));
mp->mgmt_type = ALLNET_MGMT_PEERS;
struct allnet_mgmt_peers * mpp =
(struct allnet_mgmt_peers *)
(((char *) mp) + sizeof (struct allnet_mgmt_header));
mpp->num_peers = 0;
int i;
for (i = 0; (i < info->num_fds) && (mpp->num_peers < 255); i++) {
if ((i != index) && (info->peers [i].ip.ip_version != 0)) {
struct internet_addr * iap = mpp->peers + ((mpp->num_peers)++);
*iap = info->peers [i].ip;
memset (iap->pad, 0, sizeof (iap->pad));
}
}
/* set priority to 0 since ignored on messages from a different machine */
if (! send_pipe_message (fd, buffer, size, 0))
printf ("unable to send peer message for %d peers\n", npeers);
}
/* if some fds are still available, return the next */
/* otherwise, return the index of the oldest FD, after closing it */
/* called with lock held */
/* if closing connection, send the list of peers before closing */
static int close_oldest_fd (struct listen_info * info)
{
if (info->num_fds < info->max_num_fds)
return info->num_fds++;
int i;
int min_index = 0;
for (i = 1; i < info->num_fds; i++)
if (info->used [i] < info->used [min_index])
min_index = i;
int fd = info->fds [min_index];
send_peer_message (fd, info, min_index);
if (info->add_remove_pipe)
remove_pipe (fd);
close (fd);
info->fds [min_index] = -1;
return min_index;
}
/* if closing connection, send the list of peers before closing */
void listen_add_fd (struct listen_info * info, int fd, struct addr_info * addr)
{
if ((info->num_fds >= info->max_num_fds) && (random () >= RAND_MAX / 2)) {
/* if full, half the time just send a peer message and close the fd */
send_peer_message (fd, info, -1);
close (fd); /* never added the pipe, so no need to remove it */
}
pthread_mutex_lock (&(info->mutex));
int index = close_oldest_fd (info);
info->fds [index] = fd;
if (addr != NULL)
info->peers [index] = *addr;
else
info->peers [index].ip.ip_version = 0;
if (info->add_remove_pipe)
add_pipe (fd);
pthread_mutex_unlock (&(info->mutex));
}
void listen_remove_fd (struct listen_info * info, int fd)
{
pthread_mutex_lock (&(info->mutex));
if (info->add_remove_pipe) {
remove_pipe (fd);
/* printf ("removed_pipe (%d)\n", fd); */
}
int i;
for (i = 0; i < info->num_fds; i++) {
if (info->fds [i] == fd) {
info->num_fds--;
if (i < info->num_fds)
info->fds [i] = info->fds [info->num_fds];
break; /* assume any fd only appears once */
}
}
pthread_mutex_unlock (&(info->mutex));
}
/* returned addr_info is statically allocated (until remove_fd is called),
* do not modify in any way. Returns NULL for no match */
struct addr_info * listen_fd_addr (struct listen_info * info, int fd)
{
struct addr_info * result = NULL;
pthread_mutex_lock (&(info->mutex));
int i;
for (i = 0; i < info->num_fds; i++) {
if (info->fds [i] == fd)
result = info->peers + i;
}
pthread_mutex_unlock (&(info->mutex));
return result;
}
int already_listening (struct addr_info * ai, struct listen_info * info)
{
int result = 0;
pthread_mutex_lock (&(info->mutex));
int i;
for (i = 0; (i < info->num_fds) && (! result); i++) {
if (same_ai (info->peers + i, ai))
result = 1;
}
pthread_mutex_unlock (&(info->mutex));
return result;
}
|
C
|
/* David Sedlák <xsedla1d>, Karel Hanák <xhanak34> */
#include <stdio.h>
#include <unistd.h>
#include <thread>
#include <queue>
#include <mutex>
#include <vector>
#include <iostream>
#include <string.h>
#include <regex>
using namespace std;
vector <mutex *> locks;
mutex *entered_chain_mutex, *finished_mutex;
bool line_ready = false, line_processed = false, thread_terminate = false;
int in_chain = 0, finished = 0;
char *line;
/* converts c++ string to null terminated array of chars (char *)*/
char *to_cstr(string a) {
char *str;
str = (char *)malloc(sizeof(char) * (a.length() + 1));
strcpy(str, a.c_str());
return str;
}
/* reads one line from input */
char *read_line(int *res) {
string line;
char *str;
if (getline(cin, line)) {
str = to_cstr(line);
*res = 1;
return str;
} else {
*res = 0;
return NULL;
}
}
/* implementation of worker thread */
void worker_thread(int ID, char *RE, char *REPL, int thread_count) {
char *buf;
int iteration = 0;
while (1) {
/* lock mutex for next thread in chain, no one is waiting for last thread */
if (ID != (thread_count - 1)) {
locks[ID]->lock();
}
/* thread ID is now part of the chain, increment shared counter of threads in chain */
entered_chain_mutex->lock();
in_chain++;
entered_chain_mutex->unlock();
while (!line_ready) {
if (thread_terminate) {
return;
}
}
/* make sure all threads are in the chain before entering the stage of unchaining */
while(in_chain != thread_count);
/**
* Wait for output of predecesing thread
* Thread with id 0 doesn't have to wait for anything
*/
if (!ID == 0) {
locks[ID - 1]->lock();
}
/* apply regex */
regex re1(RE);
string res = regex_replace(line, re1, REPL);
char *str = to_cstr(res);
/* print the output */
printf("%s\n", str);
free(str);
if (ID != (thread_count - 1)) {
locks[ID]->unlock();
} else {
/**
* last thread must set information about completing the line
* and set default value of shared variables
*/
in_chain = 0;
line_ready = false;
line_processed = true;
}
/* unlock mutex of predeceasing thread to be ready for next line */
if (ID != 0) {
locks[ID - 1]->unlock();
}
/* threads wait until the line is processed */
while(!line_processed);
finished_mutex->lock();
finished++;
finished_mutex->unlock();
}
}
int main(int argc, char **argv) {
if (argc < 3 || !((argc -1 ) % 2 == 0)) {
printf("Invalid arguments\n");
return EXIT_FAILURE;
}
/* turn of buffering */
setvbuf(stdout, NULL, _IONBF, 0);
setvbuf(stdin, NULL, _IONBF, 0);
int thread_count = (argc - 1) / 2;
int lock_count = thread_count - 1;
/* array of threads */
vector <thread *> threads;
/* try to create locks and threads */
try {
entered_chain_mutex = new mutex();
finished_mutex = new mutex();
locks.resize(lock_count);
for (int i = 0; i < lock_count; i++) {
mutex *new_zamek = new mutex();
locks[i] = new_zamek;
}
threads.resize(thread_count);
for(int i = 0; i < thread_count; i++){
thread *new_thread = new thread(worker_thread, i, argv[2 * i + 1], argv[2 * i + 2], thread_count);
threads[i] = new_thread;
}
} catch (bad_alloc&) {
fprintf(stderr, "Unable to allocate resources\n");
return(EXIT_FAILURE);
}
int res;
line = read_line(&res);
if (res) {
line_ready = true;
}
int processed = 0;
while (res) {
while(!line_processed);
free(line);
line = read_line(&res);
while (finished != thread_count);
finished = 0;
line_processed = false;
if (res) {
line_ready = true;
}
}
thread_terminate = true;
/* join and free threads */
for(int i = 0; i < thread_count; i++){
(*(threads[i])).join();
delete threads[i];
}
/* free locks */
delete entered_chain_mutex;
delete finished_mutex;
for(int i = 0;i < lock_count; i++){
delete locks[i];
}
return EXIT_SUCCESS;
}
|
C
|
/******************************************************
̸ : scanf_sprintf.c
ۼ :
뵵 : Ҹ Ȱ
******************************************************/
#include <stdio.h>
int main(void) // main() Լ
{
int x, y;
char data_in[20] = "50, 123";
char data_out[20];
sscanf(data_in, "%d%*c%d", &x, &y);
sprintf(data_out, "Է x=%d, y=%d\n", x, y);
puts(data_out);
return 0;
} // main() Լ
|
C
|
#include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char *argv[]) {
int op;
float num1, num2;
puts("Uma simples calculadora:");
puts("Escolha uma operacao \n1 + \n2 - \n3 * \n4 /");
scanf("%d",&op);
if(op==1){
fflush(stdin);
puts("Insira o primeiro numero a somar:");
scanf("%f",&num1);
puts("Insira o segundo numero a somar:");
scanf("%f",&num2);
printf("Res: %2.2f", num1 + num2);
}
else
if(op==2){
fflush(stdin);
puts("Insira o primeiro numero a subtrair:");
scanf("%f",&num1);
puts("Insira o segundo numero a subtrair:");
scanf("%f",&num2);
printf("Res: %2.2f", num1 - num2);
}else
if(op==3){
fflush(stdin);
puts("Insira o primeiro numero a multiplicar:");
scanf("%f",&num1);
puts("Insira o segundo numero a multiplicar:");
scanf("%f",&num2);
printf("Res: %2.2f", num1 * num2);
}else
if(op==4){
fflush(stdin);
puts("Insira o dividendo:");
scanf("%f",&num1);
puts("Insira um divisor diferente de 0:");
scanf("%f",&num2);
if(num2!=0){
printf("Res: %2.2f", num1 / num2);
}else{
printf("Dividendo Invalido\nBye!");
}
}else{
printf("Opcao Invalida\nBye!");
}
printf("\nBye!");
return 0;
}
|
C
|
#ifndef lcthw_list_h
#define lcthw_list_h
#include <stdlib.h>
/*
* struct ListNode
*
* The ListNode data structure represents the
* heart of the doubley linked list.
*
* It knows the memory address of the node to
* its left and the node to its right - this is
* why we can define the list as doubley linked.
*
* It is a robust data structure because it can hold
* a pointer to any data type.
*/
struct ListNode;
typedef struct ListNode {
struct ListNode *next;
struct ListNode *prev;
void *value;
} ListNode;
/*
* struct List
*
* The List is nothing more than a wrapper around
* an arbitrary number of ListNode structs.
*
* It has special knowledge of the nodes at
* the extreme left and extreme right - making access
* to those nodes particularly fast.
*
* It also keeps track of the total number of nodes it contains.
*/
typedef struct List {
int count;
ListNode *first;
ListNode *last;
} List;
List *List_Create();
void List_Destroy(List *list);
void List_Clear(List *list);
void List_Clear_Destroy(List *list);
#define List_Count(A) ((A)->count)
#define List_First(A) ((A)->first != NULL ? (A)->first->value : NULL)
#define List_Last(A) ((A)->last != NULL ? (A)->last->value : NULL)
void List_Push(List *list, void *value);
void *List_Pop(List *list);
void List_Unshift(List *list, void *value);
void *List_Shift(List *list);
void *List_Remove(List *list, ListNode *node);
#define LIST_FOREACH(L, S, M, V) \
ListNode *_node = NULL; \
ListNode *V = NULL; \
for(V = _node = L->S; _node != NULL; V = _node = _node->M)
#endif
|
C
|
#include "utils.h"
void get_token(char cmd[], char token[], int *idx, int size) {
/*
* generates the next token contained in cmd appearing after the idx
* Arguments:
* char cmd[] - the cmd string
* char token[] - the resultant token
* int *idx - pointer to the starting index in cmd
* int size - the max size of the cmd & token
*/
int i;
int comma=0; /* flag for detecting the first comma */
/* skip valid blanks after idx */
while(*idx<size-1 && ((!comma&&cmd[*idx]==',') || cmd[*idx]==' ' || cmd[*idx]=='\t') && cmd[*idx]!='\0') {
(*idx)++;
comma = 1;
}
/*
at this point, idx indicates one of the following:
i) first character of token (typical case)
ii) null char (end of the string)
iii) max size (end of the array)
*/
/* construct the token until the first delimiter is recognized */
i=0;
while(*idx<size-1 && i<size-1 && cmd[*idx]!=' ' && cmd[*idx]!='\t' && cmd[*idx]!='\0' && cmd[*idx]!=',') {
token[i] = cmd[*idx];
(*idx)++;
i++;
}
token[i] = '\0'; /* make token into a valid string */
}
void get_substr(char str[], char tok[], int lb, int ub) {
int i; /* scans tok */
int comma=0; /* flag for detecting the first comma */
int idx = lb; /* scans str */
/* skip valid blanks after idx */
while(idx<=ub && ((!comma&&str[idx]==',') || str[idx]==' ' || str[idx]=='\t') && str[idx]!='\0') {
idx++;
comma = 1;
}
/*
at this point, idx indicates one of the following:
i) first character of token (typical case)
ii) null char (end of the string)
iii) max size (end of the array)
*/
/* construct the token until the first delimiter is recognized */
i=0;
while(idx<=ub && str[idx]!=' ' && str[idx]!='\t' && str[idx]!='\0' && str[idx]!=',') {
tok[i] = str[idx];
idx++;
i++;
}
tok[i] = '\0'; /* make token into a valid string */
}
int hex_to_int(char digit) {
/*
* converts the hex char into int
* Arguments:
* char digit - hex in char
* Returns:
* the corresponding int if digit is a valid hex, and -1 otherwise
*/
if('0' <= digit && digit <= '9') return (int)(digit-'0');
else if('A' <= digit && digit <= 'F') return 10+(int)(digit-'A');
else if('a' <= digit && digit <= 'f') return 10+(int)(digit-'a');
else return -1;
}
int parse_op(char op[]) {
/*
* converts the hex string into int, if valid
* Arguments:
* char op[] - string consisting of hex digits
* Returns:
* the corresponding int if op is not null, -1 if null, and -2 if invalid
*/
int basis,idx,ret,valid=1;
const int len = strlen(op);
ret = 0;
basis = 1;
idx = len - 1; /* last idx of op */
while(idx>=0) {
/* check validity */
valid *= (('0'<=op[idx] && op[idx]<='9') || ('a'<=op[idx] && op[idx]<='f') || ('A'<=op[idx] && op[idx]<='F')) ? 1 : 0;
/* construct start address from op */
ret += hex_to_int(op[idx]) * basis;
basis *= 16;
idx--;
}
if(!valid) return -2;
else if(!len) return -1;
else return ret;
}
int parse_dec(char dec[]) {
// TODO returns -1 if invalid
int basis, sum, idx;
const int len = strlen(dec);
sum = 0;
basis = 1;
idx = len - 1;
while(idx>=0) {
if(dec[idx]<'0' || dec[idx]>'9') return -1;
sum += basis * (int)(dec[idx] - '0');
basis *= 10;
idx--;
}
return sum;
}
|
C
|
#include<stdio.h>
int main()
{
int a=2,b=3;
b=a++ + b--;
a=a-- + ++b;
b=a++ + --b;
printf("a=%d\nb=%d\n",a,b);
}
|
C
|
//
// Create Window
//
#include <SDL.h>
#include <stdio.h>
#ifdef PLATFORM_EMCC
#include <SDL_touch.h>
#include <emscripten.h>
#endif
int fpsCount = 0;
int debugCount = 0;
double debugTime = 0.0;
int _isQuit = 0;
int fps;
double capp_currentMilliSecound() {
return SDL_GetTicks();
}
void main_loop() {
SDL_Event event;
while (SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_QUIT:
_isQuit = 1;
break;
case SDL_MOUSEMOTION:
printf("mouse motion : %d %d\r\n", event.motion.x, event.motion.y);
break;
case SDL_MOUSEBUTTONDOWN:
printf("mouse down\r\n");
break;
case SDL_MOUSEBUTTONUP:
printf("mouse up\r\n");
break;
}
}
//
// fps
//
if(debugCount > 100) {
debugCount = 0;
double t = capp_currentMilliSecound();
double v = t - debugTime;
double x = v/1000.0;
fps = (int)100/x;
debugTime = t;
printf("FPS = %d\r\n", fps);
}
debugCount++;
}
void main_init() {
printf("called main_init() s\r\n");
SDL_Init( SDL_INIT_EVERYTHING );
SDL_Surface* screen = NULL;
screen = SDL_SetVideoMode( 640, 480, 0, SDL_HWSURFACE | SDL_DOUBLEBUF );
SDL_WM_SetCaption( "title", 0 );
SDL_Flip( screen );
printf("called main_init() e\r\n");
}
int isQuit() {
return _isQuit;
}
int main( int argc, char* args[] )
{
main_init();
int prevTime = SDL_GetTicks();
int currentTime = SDL_GetTicks();
int interval = 1000/60;
while(_isQuit == 0) {
main_loop();
if((currentTime-prevTime) < interval) {
SDL_Delay(interval-(currentTime-prevTime));
} else {
SDL_Delay(1);
}
}
SDL_Quit();
return 0;
}
|
C
|
#include <stdio.h>
#include <math.h>
#define CMAX 10
#define VMAX 10
int NC, NV, NOPTIMAL,P1,P2,XERR;
double TS[CMAX][VMAX];
void Data()
{
double R1,R2;
char R;
int I,J;
printf("\n SIMPLEX METHOD\n\n");
printf(" MAXIMIZE (Y/N) ? ");
scanf("%c", &R);
printf("\n NUMBER OF VARIABLES OF THE FUNCTION ? ");
scanf("%d", &NV);
printf("\n NUMBER OF CONSTRAINTS ? ");
scanf("%d", &NC);
if (R == 'Y' || R=='y')
R1 = 1.0;
else
R1 = -1.0;
printf("\n INPUT COEFFICIENTS OF THE FUNCTION:\n");
for (J = 1; J<=NV; J++)
{
printf(" #%d ? ", J);
scanf("%lf", &R2);
TS[1][J+1] = R2 * R1;
}
printf(" Right hand side ? ");
scanf("%lf", &R2);
TS[1][1] = R2 * R1;
for (I = 1; I<=NC; I++)
{
printf("\n CONSTRAINT #%d:\n", I);
for (J = 1; J<=NV; J++)
{
printf(" #%d ? ", J);
scanf("%lf", &R2);
TS[I + 1][J + 1] = -R2;
}
printf(" Right hand side ? ");
scanf("%lf", &TS[I+1][1]);
}
printf("\n\n RESULTS:\n\n");
for(J=1; J<=NV; J++) TS[0][J+1] = J;
for(I=NV+1; I<=NV+NC; I++) TS[I-NV+1][0] = I;
}
void Pivot();
void Formula();
void Optimize();
void Simplex()
{
e10:
Pivot();
Formula();
Optimize();
if (NOPTIMAL == 1) goto e10;
}
void Pivot()
{
double RAP,V,XMAX;
int I,J;
XMAX = 0.0;
for(J=2; J<=NV+1; J++)
{
if (TS[1][J] > 0.0 && TS[1][J] > XMAX)
{
XMAX = TS[1][J];
P2 = J;
}
}
RAP = 999999.0;
for (I=2; I<=NC+1; I++)
{
if (TS[I][P2] >= 0.0) goto e10;
V = fabs(TS[I][1] / TS[I][P2]);
if (V < RAP)
{
RAP = V;
P1 = I;
}
e10:
;
}
V = TS[0][P2];
TS[0][P2] = TS[P1][0];
TS[P1][0] = V;
}
void Formula()
{
;
int I,J;
for (I=1; I<=NC+1; I++)
{
if (I == P1) goto e70;
for (J=1; J<=NV+1; J++)
{
if (J == P2) goto e60;
TS[I][J] -= TS[P1][J] * TS[I][P2] / TS[P1][P2];
e60:
;
}
e70:
;
}
TS[P1][P2] = 1.0 / TS[P1][P2];
for (J=1; J<=NV+1; J++)
{
if (J == P2) goto e100;
TS[P1][J] *= fabs(TS[P1][P2]);
e100:
;
}
for (I=1; I<=NC+1; I++)
{
if (I == P1) goto e110;
TS[I][P2] *= TS[P1][P2];
e110:
;
}
}
void Optimize()
{
int I,J;
for (I=2; I<=NC+1; I++)
if (TS[I][1] < 0.0) XERR = 1;
NOPTIMAL = 0;
if (XERR == 1) return;
for (J=2; J<=NV+1; J++)
if (TS[1][J] > 0.0) NOPTIMAL = 1;
}
void Results()
{
int I,J;
if (XERR == 0) goto e30;
printf(" NO SOLUTION.\n");
goto e100;
e30:
for (I=1; I<=NV; I++)
for (J=2; J<=NC+1; J++)
{
if (TS[J][0] != 1.0*I) goto e70;
printf(" VARIABLE #%d: %f\n", I, TS[J][1]);
e70:
;
}
printf("\n ECONOMIC FUNCTION: %f\n", TS[1][1]);
e100:
printf("\n");
}
void main()
{
Data();
Simplex();
Results();
}
|
C
|
#ifndef _LINUX_RATELIMIT_H
#define _LINUX_RATELIMIT_H
#include <linux/param.h>
#include <linux/spinlock.h>
#define DEFAULT_RATELIMIT_INTERVAL (5 * HZ)
#define DEFAULT_RATELIMIT_BURST 10
struct ratelimit_state {
raw_spinlock_t lock; /* protect the state */
int interval;
int burst;
int printed;
int missed;
unsigned long begin;
};
#define DEFINE_RATELIMIT_STATE(name, interval_init, burst_init) \
\
struct ratelimit_state name = { \
.lock = __RAW_SPIN_LOCK_UNLOCKED(name.lock), \
.interval = interval_init, \
.burst = burst_init, \
}
static inline void ratelimit_state_init(struct ratelimit_state *rs,
int interval, int burst)
{
raw_spin_lock_init(&rs->lock);
rs->interval = interval;
rs->burst = burst;
rs->printed = 0;
rs->missed = 0;
rs->begin = 0;
}
extern struct ratelimit_state printk_ratelimit_state;
extern int ___ratelimit(struct ratelimit_state *rs, const char *func);
#define __ratelimit(state) ___ratelimit(state, __func__)
#ifdef CONFIG_PRINTK
#define WARN_ON_RATELIMIT(condition, state) \
WARN_ON((condition) && __ratelimit(state))
#define WARN_RATELIMIT(condition, format, ...) \
({ \
static DEFINE_RATELIMIT_STATE(_rs, \
DEFAULT_RATELIMIT_INTERVAL, \
DEFAULT_RATELIMIT_BURST); \
int rtn = !!(condition); \
\
if (unlikely(rtn && __ratelimit(&_rs))) \
WARN(rtn, format, ##__VA_ARGS__); \
\
rtn; \
})
#else
#define WARN_ON_RATELIMIT(condition, state) \
WARN_ON(condition)
#define WARN_RATELIMIT(condition, format, ...) \
({ \
int rtn = WARN(condition, format, ##__VA_ARGS__); \
rtn; \
})
#endif
#endif /* _LINUX_RATELIMIT_H */
|
C
|
#include <stdio.h>
int main()
{
char ch;
while((ch = getchar()) != '#') //ch = getchar()表达式的值为从键盘输入并存入到ch中的值,
{ //对于赋值表达式,左值的值即为表达式的值
putchar(ch);
}
return 0;
}
|
C
|
/* Chapter-6 Program to categorize a single character that is entered at the terminal
* Vasanth [02 September 2014] */
#include<stdio.h>
int main(void)
{
char c;
printf("Enter a single character:\n");
scanf("%c", &c);
if((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') )
printf("It's an alphabetic character.\n");
else if( c >= '0' && c <= '9' )
printf("It's a digit.\n");
else
printf("It's a special character.\n");
return 0;
}
Output:
Enter a single character:
V
It's an alphabetic character.
Enter a single character:
/
It's a special character.
Enter a single character:
5
It's a digit.
|
C
|
//
// Eric Jiang
// node.c
// OS_Problem-2
//
#include <stdio.h>
#include <stdbool.h>
/* struct for tree nodes*/
struct tree_node{
int children_no;
char name;
struct tree_node *left;
struct tree_node *right;
}typedef tree_node;
/* struct for creating new nodes */
struct tree_node* newNode(int children_no, char name){
struct tree_node *temp = (struct tree_node*)malloc(sizeof(struct tree_node));
temp->children_no = children_no;
temp->name = name;
temp->left = NULL;
temp->right = NULL;
return (temp);
}
bool hasleft(tree_node *n){
if(n->left != NULL)
return true;
else
return false;
}
bool hasright(tree_node *n){
if(n->right != NULL)
return true;
else
return false;
}
|
C
|
/*
the following checks numbers between 1-100 and finds all the prime numbers
*/
#include<stdio.h>
#define SIZE 100
main()
{
printf("PRIME NUMBERS\n-------------------\n");
int i,j,k;//counters for nested for loops
k=1;
//This algorthm requires the loops to start at 2
for(i=2;i<SIZE;i++)
{
for(j=2;j<i;j++)
{
if(i%j==0)
{
break; // this means its not a prime and can exit from inner loop
}//end if
}//end inner for
if(i==j)
{
printf("%d.\t",k);
printf("%d is a prime\n",i);
k++;
}//end if
}//end for
getch();
}//end main
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.