language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C
|
#include <stdio.h>
#include <stdlib.h>
int main()
{int x,y,c,a;
for(x=1;x<=6;++x){
for(y=1;y<=6,y<=x,y!=x;++y){
for(c=1;c<=6,c<=y,c!=y;++c){
for(a=1;a<=6,a<=c,a!=x,a!=y,a!=c;++a){
}
printf("\n %d%d%d%d",x,y,c,a);
}
printf("\n");
}
}
}
|
C
|
#include <stdio.h>
#include <math.h>
int main(){
double x,y;
printf("Enter a number");
scanf("%lf",&x);
y=sqrt(x);
printf("squart root of a number=%lf",y);
}
|
C
|
// pow function demo program
#include <stdio.h>
#include <math.h> // Files can be included in any order
main()
{
printf("%g \n" , pow(2 , 3)); // 8
printf("%g \n" , pow(-2 , -3)); // -2 ^ -3
printf("%g \n" , pow(10 , -2)); // 10 ^ -2 = 0.01
printf("%g \n" , pow(2 , pow(3 , 2))); // 2 ^ 3 ^ 2 = 2 ^ 9 = 512
printf("%d \n" , pow(3 , 4)); // garbage value due to wrong format
}
/*
1) Function in function is called nested function.
2) Inner function is executed before outer function.
3) pow function always returns float result.
4) %f or %g must be used for pow function but not %d
*/
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
#include <math.h>
int main(argc, argv)
int argc;
char* argv[];
{
int myid, numprocs;
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &numprocs);
MPI_Comm_rank(MPI_COMM_WORLD, &myid);
struct {
int intRank;
double doubleRank;
} newStruct;
int blockLength[2];
MPI_Aint displacements[2];
MPI_Aint addresses[3];
MPI_Datatype typeList[2];
MPI_Datatype newType;
typeList[0] = MPI_INT;
typeList[1] = MPI_DOUBLE;
blockLength[0] = blockLength[1] = 1;
MPI_Address(&newStruct, &addresses[0]);
MPI_Address(&(newStruct.intRank), &addresses[1]);
MPI_Address(&(newStruct.doubleRank), &addresses[2]);
displacements[0] = addresses[1] - addresses[0];
displacements[1] = addresses[2] - addresses[0];
MPI_Type_struct(2, blockLength, displacements, typeList, &newType);
MPI_Type_commit(&newType);
if (myid == 0) {
newStruct.intRank = 100;
newStruct.doubleRank = 1.0055;
MPI_Send(&newStruct, 1, newType, 1, 0, MPI_COMM_WORLD);
printf("I %d send to %d data, int = %d, double = %f\n", myid, myid + 1, newStruct.intRank, newStruct.doubleRank);
}
else {
MPI_Recv(&newStruct, 1, newType, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
printf("I %d recieve from %d data, int = %d, double = %f\n", myid, myid - 1, newStruct.intRank, newStruct.doubleRank);
}
MPI_Finalize();
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
void agendador();
void agendar_por_horario();
void agendar_por_hora_restante();
void cancela();
int main(int argc, char *argv[]) {
int opcao;
for(;;){
system("cls");
printf("============MENU DE AGENDA PARA O WINDOWS DESLIGAR============\n");
printf("Voc deseja:\n 1-Agendar horario para desligar:\n 2-Cancelar horario agendado:\n 3-Outra para sair do programa.\n");//menu criado pra navegar entre as opes que esto nas funoes
scanf("%i",&opcao);//pega a opo do menu
getchar();
switch(opcao){
case 1:
agendador();
break;
case 2:
cancela();
break;
default:
return 0;
break;
}}
}
void cancela(){
char comando[30]="shutdown -a";
printf("agendamento cancelado cancelado!");
system(comando);
}
void agendador(){
int opcao;
printf("============MENU DE AGENDA PARA O WINDOWS DESLIGAR OU REINICIAR============\n");
printf("Voc deseja:\n 1-Agendar por horario:\n 2-Agendar por horas restantes:\n 3-Para voltar ao menu principal:\n");//menu criado pra navegar entre as opes que esto nas funoes
scanf("%i",&opcao);//pega a opo do menu
getchar();
switch(opcao){
case 1:
agendar_por_horario();
break;
case 2:
agendar_por_hora_restante();
break;
default:
return 0;
break;
}
}
void agendar_por_horario(){
int hora=0;
int hora2=0;
int minuto=0;
int minuto2=0;
int i,c=0;
char horas[3];
char minutos[3];
char horario[9];
char comando[30]="shutdown -s -t ";
_strtime(horario);//funo pra pegar a data atual do sistema e colocar na variavel
strncpy (horas,horario,2);
horas[2]='\0';
for(i=3;i<5;i++){
minutos[c]=horario[i];
c=c+1;
}
minutos[2]='\0';
FILE *saida; //ponteiro para o arquivo txt de saida relatorio.txt
FILE *saida2; //ponteiro para o arquivo txt de saida relatorio.txt
saida = fopen("processando.txt", "w");
fprintf(saida,"%s ",horas);
fprintf(saida,"%s",minutos);
fclose(saida);
saida2=fopen("processando.txt","r");
fscanf(saida2,"%i",&hora2);
fscanf(saida2,"%i",&minuto2);
fclose(saida2);
/* puts(horas);
printf("\n");
puts(minutos);
printf("\n");
puts(horario);
printf("\n");
printf("hora: %i e minuto %i",hora2,minuto2);
getchar();*/
printf("qual a hora DE HOJE que deseja agendar? exemplo 16 ou 17\n");
scanf("%i",&hora);
getchar();
printf("digite os minutos agora: exemplo 40\n");
scanf("%i",&minuto);
getchar();
if(hora>24){
printf("hora invalida alterada para 23 horas");
hora=23;
}
if(minuto>60){
printf("hora invalida alterada para 00 minutos.");
minuto=23;
}
if(hora==24 && minuto>1){
printf("Horario invalido foi convertido pra 00:00");
hora=00;
minuto=00;
}
hora=hora2-hora;
if(minuto>minuto2){
minuto=minuto-minuto2;
}
else{
minuto=minuto2-minuto;
}
hora=hora*60;
hora=hora*60;
minuto=minuto*60;
hora=hora+minuto;
if(hora<0){
hora=hora*-1;
}
// FILE *saida; //ponteiro para o arquivo txt de saida relatorio.txt
saida = fopen("processando.txt", "w");
fprintf(saida,"%i",hora);
fclose(saida);
// FILE *saida2; //ponteiro para o arquivo txt de saida relatorio.txt
saida2 = fopen("processando.txt", "r");
fgets(horario,40,saida2);//pega informao do arquivo
fclose(saida2);
strcat(comando,horario);
system(comando);
}
void agendar_por_hora_restante(){
int opcao;
int tempo;
char tempo1[40];
char comando[30]="shutdown -s -t ";
printf("deseja agendar por hor, minutos ou segundos?\n");
printf(" 1-Agendar por hora:\n 2-Agendar por minutos:\n 3-Agendar por segundos:\n 4-Sair para o menu:\n");
scanf("%i",&opcao);
FILE *saida; //ponteiro para o arquivo txt de saida relatorio.txt
FILE *saida2; //ponteiro para o arquivo txt de saida relatorio.txt
getchar();
switch(opcao){
case 1:
printf("Quantas horas daqui ate que o desligamento? exemplo 4\n");
scanf("%d",&tempo);
getchar();
tempo = tempo * 60;
tempo = tempo * 60;
saida = fopen("processando.txt", "w");
fprintf(saida,"%i",tempo);
fclose(saida);
saida2 = fopen("processando.txt", "r");
fgets(tempo1,40,saida2);//pega informao do arquivo
fclose(saida2);
strcat(comando,tempo1);
system(comando);
break;
case 2:
printf("Quantos minutos daqui ate que o desligamento? exemplo 160\n");
scanf("%d",&tempo);
getchar();
tempo = tempo * 60;
itoa(tempo,tempo1,40);
// FILE *saida; //ponteiro para o arquivo txt de saida relatorio.txt
saida = fopen("processando.txt", "w");
fprintf(saida,"%i",tempo);
fclose(saida);
// FILE *saida2; //ponteiro para o arquivo txt de saida relatorio.txt
saida2 = fopen("processando.txt", "r");
fgets(tempo1,40,saida2);//pega informao do arquivo
fclose(saida2);
strcat(comando,tempo1);
system(comando);
break;
case 3:
printf("Quantas segundos daqui ate que o desligamento? exemplo 40\n");
scanf("%d",&tempo);
// FILE *saida; //ponteiro para o arquivo txt de saida relatorio.txt
saida = fopen("processando.txt", "w");
fprintf(saida,"%i",tempo);
fclose(saida);
// FILE *saida2; //ponteiro para o arquivo txt de saida relatorio.txt
saida2 = fopen("processando.txt", "r");
fgets(tempo1,40,saida2);//pega informao do arquivo
fclose(saida2);
strcat(comando,tempo1);
system(comando);
break;
}
return 0;
}
|
C
|
/* Software to print out version and implementation information */
#include <spr-defs.h>
#include "mor1kx-defs.h"
#include "printf.h"
#include "cpu-utils.h"
int main(void)
{
unsigned long reg;
printf("mor1kx version check software\n");
// Check if we have the AVR
reg = mfspr(SPR_CPUCFGR);
if (reg & SPR_CPUCFGR_AVRP)
{
reg = mfspr(SPR_AVR);
printf("OR1K %d.%d rev%d compliant CPU detected\n",
(reg & SPR_AVR_MAJ)>>SPR_AVR_MAJ_OFF,
(reg & SPR_AVR_MIN)>>SPR_AVR_MIN_OFF,
(reg & SPR_AVR_REV)>>SPR_AVR_REV_OFF);
}
// Check for the version regsiter
reg = mfspr(SPR_VR);
if (!(reg & SPR_VR_UVRP))
{
printf("No updated version register detected\n");
printf("This probably means your CPU doesn't conform to the OR1K 1.0 spec and doesn't have useful version registers.\n");
printf("Dumping VR and exiting\n");
printf("VR = %08x\n", reg);
return 0;
}
/* Check the CPUID */
reg = mfspr(SPR_VR2);
switch(((reg & SPR_VR2_CPUID)>>SPR_VR2_CPUID_OFF)&0xff)
{
case SPR_VR2_CPUID_OR1KSIM:
printf("or1ksim CPU detected. Version field: %06x\n", reg & SPR_VR2_VER);
break;
case SPR_VR2_CPUID_MOR1KX:
printf("mor1kx CPU detected. Version field: %06x\n", reg & SPR_VR2_VER);
break;
case SPR_VR2_CPUID_OR1200:
printf("OR1200 CPU detected. Version field: %06x\n", reg & SPR_VR2_VER);
break;
case SPR_VR2_CPUID_ALTOR32:
printf("AltOr32 CPU detected. Version field: %06x\n", reg & SPR_VR2_VER);
break;
case SPR_VR2_CPUID_OR10:
printf("OR10 CPU detected. Version field: %06x\n", reg & SPR_VR2_VER);
break;
default:
printf("Unknown CPU detected. Version field: %06x\n", reg & SPR_VR2_VER);
break;
}
// If it was an mor1kx CPU implementation we can check the details
if ((((reg & SPR_VR2_CPUID)>>SPR_VR2_CPUID_OFF)&0xff)==SPR_VR2_CPUID_MOR1KX)
{
// The following defines come from mor1kx-defs.h
printf("mor1kx ");
switch (reg & MOR1KX_VR2_PIPEID)
{
case MOR1KX_VR2_PIPEID_CAPPUCCINO:
printf("cappuccino");
break;
case MOR1KX_VR2_PIPEID_ESPRESSO:
printf("espresso");
break;
case MOR1KX_VR2_PIPEID_PRONTOESPRESSO:
printf("prontoespresso");
break;
default:
printf("unknown");
break;
}
printf(" pipeline implementation detected\n");
}
// Check if the implementation-specific registers (ISRs) are present
reg = mfspr(SPR_CPUCFGR);
/*
if (reg & SPR_CPUCFGR_ISRP)
{
}
*/
report(0x8000000d);
return 0;
}
|
C
|
#include<omp.h>
#include<stdio.h>
main()
{
int x,y,z,tid;
x=3;y=5,z=4;
#pragma omp parallel firstprivate(x,y) private(z,tid)
{
tid=omp_get_thread_num();
printf("A : In thread %d : (x,y,z)=(%d,%d,%d).\n",tid,x,y,z);
++x; ++y; ++z;
printf("B : In thread %d : (x,y,z)=(%d,%d,%d).\n",tid,x,y,z);
}
}
|
C
|
/*
* sequence.c
*
* Created: 25/04/2018 18:58:38
* Author: Dima
*/
#include "sequence.h"
struct sequence
{
int current_index; // current index of the sequence
int *random_pattern; // an array of integers to be filled up with random numbers
};
sequence_t sequence_create()
{
sequence_t seq = (sequence_t)malloc(sizeof(sequence_t)); // allocating memory
seq->random_pattern =(int) malloc(sizeof(int)); // allocating memory for array
seq->current_index = 0; //set the index at the beginning of the array
return seq;
}
void sequence_destroy(sequence_t seq)
{
free(seq);
return;
}
void fill_random_sequence(sequence_t self, int size)
{
//if there is already memory allocated by this pointer
//clean it up
if (self->random_pattern)
free(self->random_pattern);
self->current_index = 0; // set the current index to 0(zero)
self->random_pattern = malloc(size*sizeof(int)); // allocating necessary memory
//filling up the array with random numbers
for(int i = 0; i < size; i++)
self->random_pattern[i] = rand()%7;
return;
}
int get_next(sequence_t self)
{
// return the value at the current index
//incrementing index afterwards
return *(self->random_pattern + self->current_index++);
}
void reset_index(sequence_t self)
{
//resetting current index to 0 again
self->current_index = 0;
return;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
struct ListNode {
int val;
struct ListNode *next;
};
int main()
{
return 0;
}
struct ListNode* removeElements(struct ListNode* head, int val) {
struct ListNode* q = (struct ListNode*)malloc(sizeof(struct ListNode));
q->next= head;
struct ListNode* p = q;
while(p->next != NULL)
{
if(p->next->val == val)
{
struct ListNode* l;
l = p->next;
p->next = l->next;
free(l);
}
else
p = p->next;
}
p = q->next;
free(q);
return p;
}
|
C
|
#include "mygrep.h"
/**
* This function interprets grep patterns
* @return 0 if successful, -1 otherwise
**/
int mypattern(char * pattern, char * patfile){
if (pattern[0]=='\0'){
if (patfile[0]=='\0'){
printf("Invalid usage\n");
return -1;}
FILE *file = fopen(patfile, "r");
if(file !=NULL) {
pattern = (char *)malloc(sizeof(char)*640);
fgets(pattern, 640, file);
fclose(file);}}
int pos = 0;
int i = 0;
int temp;
char c;
char **pattern_grid = (char **) malloc(sizeof(char *));
pattern_grid[i] = (char *) malloc(sizeof(char)*255);
set(pattern_grid[i++],'.');
while(pattern[pos]){
c = pattern[pos];
switch(c){
case '[':
temp = range(&(pattern[pos]),pattern_grid[i-1]);
if(temp!=-1)
pos += temp;
else{
printf("Invalid syntax: %s\n",pattern);
pos = -2;
}
break;
case '\\':
if(pattern[++pos]){
char oct[4];
if(isDigit(pattern[pos])&&isDigit(pattern[pos+1])&&isDigit(pattern[pos+2])){
oct[0] = '\\';
oct[1] = pattern[pos++];
oct[2] = pattern[pos++];
oct[3] = pattern[pos];
pattern_grid[i-1][otoc(oct)] = '1';
}else
pattern_grid[i-1][pattern[pos]] = '1';
}else{
printf("Invalid syntax: %s\n",pattern);
pos = -2;
}
break;
default:
pattern_grid[i-1][pattern[pos]] = '1';
break;}
++pos;
if(pattern[pos]){
char **newgrid = (char **)realloc(pattern_grid,(i+1)*sizeof(char *));
pattern_grid = newgrid;
pattern_grid[i] = (char *) malloc(sizeof(char)*255);
set(pattern_grid[i++],'.');
}
}
return myfilter(pattern_grid, i);
}
/**
* NAME:
* mypattern -
*
* SYNOPSIS:
* ./mypattern
*
* DESCRIPTION:
*
* -
**/
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <drinkmachine.h>
#include <stdbool.h>
//I created this drinkMachineDriver file separately from drinkmachine.c or drinkmachine.h, so there will be a lot overlaps.
//So dear grader, you only need to read this file and my drinkmachine.h
//Thanks for your hard work.
DrinkMachine *test;
int i;//for loops of input
int instruction;//this is for user input
double *ch;//this is for the output of the function purchase.
//I have to use a pointer because there is not "pass by reference" in C.
const int INVALID_INDEX=-1;
int id;
float amount;
enum buy{PURCHASED=1, INVALID, NOT_AVAILABLE, INSUFFICIENT_FUNDS};//this is for the function purchase
DrinkItem *pDrink;
enum buy result;
//below are all the required functions
DrinkMachine * create(void)
{
FILE * infile;
DrinkMachine * drink1;
infile=fopen("drink_machine.txt","r");
if (!infile)
{
puts("Error opening file");
return NULL;
}
drink1=calloc(1,sizeof(DrinkMachine));
if (drink1==NULL)
{
puts("Error allocating");
return NULL;
}
fscanf(infile,"%d",&(drink1->numDrinkItems));
drink1->version=1;
drink1->location=INVALID_INDEX;
drink1->dkitem = calloc(drink1->numDrinkItems,sizeof(DrinkItem));
if (drink1->dkitem==NULL)
{
puts("Error allocating");
return NULL;
}
for (i=0;i<drink1->numDrinkItems;i++)
{
fscanf(infile,"%s",&(drink1->dkitem[i].name));
fscanf(infile,"%f",&(drink1->dkitem[i].price));
fscanf(infile,"%d",&(drink1->dkitem[i].numofdrinks));
drink1->dkitem[i].id=i+1;
//this has a problem if I use the char* instead of char
//Why can't I fscanf separately instead of as a whole line?
}
fclose(infile);
fflush(stdout);
return (drink1);
}
void destroy(DrinkMachine * dmashine1)
{
for (i=0;i<dmashine1->numDrinkItems;i++)
free(dmashine1->dkitem);
free(dmashine1);
}
DrinkItem * firstDrink(DrinkMachine * DrinkMachine)
{
DrinkMachine->location=0;
if (&(DrinkMachine->dkitem[0])==NULL)
return NULL;
else
return &(DrinkMachine->dkitem[0]);
}
DrinkItem * nextDrink(DrinkMachine *DrinkMachine)
{
if (DrinkMachine->location==INVALID_INDEX)
return NULL;
else
DrinkMachine->location=(DrinkMachine->location)+1;
if ((DrinkMachine->location)<(DrinkMachine->numDrinkItems))
return &(DrinkMachine->dkitem[DrinkMachine->location]);
else
{
DrinkMachine->location=INVALID_INDEX;
return NULL;
}
}
int items(DrinkMachine *DrinkMachine)
{
return DrinkMachine->numDrinkItems;
}
bool available(DrinkMachine *DrinkMachine,int id)
{
int difference;
int num;
num=DrinkMachine->numDrinkItems;
if (id>num || id<=0)
return 0;
else
{
difference=DrinkMachine->dkitem[id-1].numofdrinks-DrinkMachine->dkitem[id-1].drinkspurchased;
if (difference>=1)
return 1;
else
return 0;
}
}
double cost(DrinkMachine *DrinkMachine,int id)
{
int num;
num=DrinkMachine->numDrinkItems;
if (id>num || id<=0)
return 0;
else
return DrinkMachine->dkitem[id-1].price;
}
enum buy purchase(DrinkMachine *DrinkMachine,int id, double moneyspent, double *change)
{
int num,difference;
num=DrinkMachine->numDrinkItems;
if (id>num || id<=0)
return 2;
else
{if (moenyspent<=0)
return 2;
else
difference=DrinkMachine->dkitem[id-1].numofdrinks-DrinkMachine->dkitem[id-1].drinkspurchased;
if (difference<=0)
return 3;
else
if (moneyspent < DrinkMachine->dkitem[id-1].price)
return 4;
else
{
*change=moneyspent-(DrinkMachine->dkitem[id-1].price);
(DrinkMachine->dkitem[id-1].drinkspurchased)++;
return 1;
}
}
}
void dumpDrinkMachine(DrinkMachine *DrinkMachine)
{
DrinkItem *pDrink;
printf("%s","ID");
printf("%12s","Name");
printf("%13s","price");
printf("%11s","Qty");
printf("%12s\n","Sold");
for (pDrink=firstDrink(test);pDrink!=NULL;pDrink=nextDrink(test))
{
printf("%d",pDrink->id);
printf("%15s",pDrink->name);
printf("%15.2f",pDrink->price);
printf("%10d",pDrink->numofdrinks);
printf("%10d\n",pDrink->drinkspurchased);
}
}
int main(void)
{
//first save the address of my machine to test
test=create();
ch=calloc(1,sizeof(double));//allocate some memory for the changes produced by the function purchase
fflush(stdout);
//I will use a do-while loop for my user interface. The program will not exit unless the user inputs 0
do
{
dumpDrinkMachine(test);
printf("%s\n","Enter a drink id for the drink you want to purchase or 0 to quit. ");
fflush(stdout);
scanf("%d",&instruction);
if (instruction==0)//exit if the user enters 0
{
dumpDrinkMachine(test);
printf("%s\n", "Thank you for using the drink machine.");
free(test);
return EXIT_SUCCESS;
}
else
{
id=items(test);//get the number of the types of drinks available
if (instruction>id || instruction<=0)// in case if the user enter an invalid id
printf("%s\n", "The drink id is not valid.");
else
{
printf("%s\n", "Enter the amount for the purchase (up to $2.00):");
fflush(stdout);
scanf("%f",&amount);
fflush(stdout);
if (available(test,instruction)==0)
{
printf("%s\n", "Sorry, we are out of your drink. Please select another drink ");
fflush(stdout);
}
else
if (amount>2)//in case the user put too much money
{
printf("%s\n","The amount entered is not valid. ");
fflush(stdout);
}
else
{
ch=calloc(1,sizeof(double));
result=purchase(test,instruction,amount,ch);
printf("%d\n",result);
if (result==1)
{if (*ch==0.00)
{printf("%s\n","Your drink has been purchased.");
fflush(stdout);
}
else
{
printf("%s","Your drink has been purchased. Your change is $ " );
printf("%0.2f\n",*ch);
fflush(stdout);
}}
if (result==3)
{
printf("%s\n", "Sorry, we are out of your drink. Please select another drink.");
fflush(stdout);
}
if (result==4)
{
printf("%s","The amount you entered is insufficient to purchase the drink. The price is ");
printf("%.2f\n",cost(test,instruction));
fflush(stdout);
}
}
}
}
}
while (instruction !=0);
return EXIT_SUCCESS;
}
|
C
|
/*
A program to implement vigenere's cipher.
It take the keyword as an cmd line arg and plaintext from user
and process it to print a scrambled version of plain text.
*/
#include <D:\CS50\cs50.h>
#include <stdio.h>
#include <ctype.h>
int main(int argc, string argv[]) //int main(int argc, string argv[])
{
//check no of arguments = 2 or not
if (argc != 2)
{
printf("Usage: ./vigenere keyword\n");
return 1;
}
// validate argument - each character should be alphabet
int count = 0; //to count the no of letters in keyword
for (int i = 0; argv[1][i] != '\0'; i++)
{
count++;
if(!(isalpha(argv[1][i])))
{
printf("Usage: ./vigenere keyword\n");
return 2;
}
}
// Input plaintext
string text = get_string("plaintext: ");
// Cipher's Implementation --->
for (int i = 0, j = 0; text[i] != '\0'; i++) // iterate over every letter of plaintext, j represents keyword's letter's postion
{
int key;
if(isupper(argv[1][j]))
key = ( (int) argv[1][j] ) % ( (int) 'A' ); //find the key as a = 0,
else if(islower(argv[1][j])) //b = 1, c = 2......
key = ( (int) argv[1][j] ) % ( (int) 'a' ); //type casting from char to int
int shift;
if(isupper(text[i]))
{
shift = text[i] + key;
while(shift > 'Z') // wraping from above Z
shift = ('A' - 1) + (shift % 'Z'); // implicit casting from char to int
text[i] = shift;
if(j < count - 1)
j++;
else
j = 0;
}
else if(islower(text[i]))
{
shift = text[i] + key;
while(shift > 'z') // wraping from above z
shift = ('a' - 1) + (shift % 'z'); // implicit casting from char to int
text[i] = shift;
if(j < count - 1)
j++;
else
j = 0;
}
}
// printing ciphertext --->
printf("ciphertext: %s\n", text);
return 0;
}
|
C
|
/*---------------------------------------------------------------------------
|
| Evaluates unary, binary and ternary arithmetic and logical expressions
|
| See 'C:\SPJ1\swr\tiny1\TOS1 Guide rev.nn.pdf'
|
|--------------------------------------------------------------------------*/
#include "common.h"
#include "wordlist.h"
#include "sysobj.h"
#include "class.h"
#include "tiny1util.h"
#include "arith.h"
#include "tty_ui.h"
#include "romstring.h"
#include "util.h"
// Operator list; the 1st is a dummy (null) value
typedef enum
{
op_Null,
op_Assign, op_AssignPlus, op_AssignMinus, op_AssignMul,
op_Plus, op_Minus,
op_Equal, op_Neq, op_Greater, op_GreaterEq, op_Less, op_LessEq,
op_Mul, op_Div,
op_And, op_Or,
op_Min, op_Max
} E_Operators;
PRIVATE U8 CONST operators[] = "n = += -= *= + - == != > >= < <= * / && || min max";
#define _OpIsAssignment(op) ((op) >= op_Assign && (op) <= op_AssignMul)
/*-----------------------------------------------------------------------------------------
|
| isComparision()
|
| Returns 1 if 'op' is an arithmetic comparision e.g > (greater)
|
------------------------------------------------------------------------------------------*/
PRIVATE BIT isComparision(U8 op)
{
return op >= op_Equal && op <= op_LessEq;
}
/*-----------------------------------------------------------------------------------------
|
| resultIsBoolean()
|
| Returns 1 if 'op' returns a boolean.
|
------------------------------------------------------------------------------------------*/
PRIVATE BIT resultIsBoolean(U8 op)
{
return isComparision(op) || op == op_And || op == op_Or;
}
extern float GetArgScale(U8 *args);
/*-----------------------------------------------------------------------------------------
|
| eval2()
|
| Returns result of 'left' 'operator' 'right' e.g 4 - 1 returns 3. If 'operator' is
| a logical then returns 1 if results is true, else 0
|
| For arithmetic operators eval2() clips the results into an integer (S16).
|
| If the operator is not recognised then returns 0.
|
------------------------------------------------------------------------------------------*/
PRIVATE S16 eval2(S16 left, S16 right, U8 operator)
{
switch( operator )
{
case op_Plus:
return AplusBS16(left, right);
case op_Minus:
return AminusBS16(left, right);
case op_Equal:
return left == right;
case op_Neq:
return left != right;
case op_Greater:
return left > right;
case op_GreaterEq:
return left >= right;
case op_Less:
return left < right;
case op_LessEq:
return left <= right;
case op_Mul:
return MulS16ToS16(left, right);
case op_Div:
return left / right;
case op_And:
return left && right;
case op_Or:
return left || right;
case op_Min:
return MinS16(left, right);
case op_Max:
return MaxS16(left, right);
default:
return 0;
}
}
/*-----------------------------------------------------------------------------------------
|
| binaryExprScale()
|
| Return scaling for binary expression 'expr' of the for 'arg1 operator arg2'.
|
| If either of 'arg1' or 'arg2' are objects and if either has a scale then the value
| returned will be that scale. If not then returns scale = 1.0
|
------------------------------------------------------------------------------------------*/
PRIVATE float binaryExprScale(U8 *expr)
{
return
GetArgScale( // Return the scale of the the arg...
(U8*)Str_GetNthWord( // which is the nth word of ...
expr, // 'expr', and 'nth' is..
GetArgScale(expr) == 1.0 // If the scale of the 1st arg is 1.0
? 2 // the 3rd word of 'expr' (i.e the 2nd arg)
: 0 )); // else the 1st word of 'expr' (i.e the 1st arg)
}
/*-----------------------------------------------------------------------------------------
|
| getBinaryOperator()
|
| Search 'expr' from the 2nd token onward and return the first binary operator found.
| Returns one of 'E_Operators'. If no operator found then returns 'op_Null' = 0.
|
------------------------------------------------------------------------------------------*/
PRIVATE U8 getBinaryOperator(U8 *expr)
{
U8 op;
if( (op = Str_FindWord(_StrConst(operators), Str_GetNthWord(expr,1))) == _Str_NoMatch)
{ return op_Null; }
else
{ return op; }
}
/*-----------------------------------------------------------------------------------------
|
| GetExprIO()
|
| Return IO formatter for binary expression 'expr' of the for 'arg1 operator arg2'.
|
------------------------------------------------------------------------------------------*/
extern S_ObjIO CONST * GetArgIO(U8 *args);
PRIVATE S_ObjIO CONST * GetExprIO(U8 *expr)
{
S_ObjIO CONST * io;
U8 c;
if( resultIsBoolean( getBinaryOperator(expr) )) // Operator returns boolean?
{ return 0; } // then result is logical (unscaled)
else // else examine the operands
{
for(c = 0; c <= 4; c += 2) // For each operand, 0th, 2nd, 4th args
{
if( (io = GetArgIO((U8*)Str_GetNthWord(expr,c))) ) // This operand has an IO spec?
{ return io; } // then return with this IO spec.
}
return 0;
}
}
/*-----------------------------------------------------------------------------------------
|
| mulDiv2Float()
|
| Return a * b if operator is 'multiply', else a / b.
|
| This handles FP operations where at least one arg is a literal.
|
------------------------------------------------------------------------------------------*/
PRIVATE S16 mulDiv2Float(float a, float b, U8 operator)
{
return
ClipFloatToInt(
operator == op_Mul
? a * b
: a / b );
}
/*-----------------------------------------------------------------------------------------
|
| evalExpr2()
|
| Evaluates binary expression string of the form "arg1 operator arg2 .... [raw]" OR
| evaluates just the values of a variable or literal "arg1"
|
| If one of arg1 or arg2 is a variable with an IO scale and the other arg is a literal
| number then the literal is scaled to the variable UNLESS 'raw' is part of 'expr'.
| E.g with voltages scaled as mV
| "SupplyV > 13.1V" or "SupplyV > 13100 raw" are equivalent
|
| arg1, arg2 can be variables with two different scales but their internal (integer) values
| are compared directly; there is no rescaling.
|
| An empty expression always returns false (0).
|
| If 'expr' isn't legal then returns 0.
|
|
------------------------------------------------------------------------------------------*/
PRIVATE S16 evalExpr2(U8 *expr, float scale)
{
U8 operator, argCnt;
float s1, s2;
if( (argCnt = Str_WordCnt(expr)) == 0 ) // empty?
{
return 0; // then return 0 (false)
}
else if( argCnt == 1 ) // just one arg?
{
return UI_GetScalarArg(expr, 0, scale); // then read it
}
else // else assume its a binary expression
{ // read the operator (the 2nd word)
if( !(operator = getBinaryOperator(expr)) ) // operator not legal?
{
return 0; // then return 0
}
if(operator == op_Mul || operator == op_Div) // multiplication or division?
{
if( !ReadASCIIToFloat(expr, &s1 ) )
{
if( !ReadASCIIToFloat((U8*)Str_GetNthWord(expr, 2), &s2) )
{ return 0; }
else
{ s1 = Obj_ReadScalar(GetObj(expr)); }
}
else
{
if( !ReadASCIIToFloat((U8*)Str_GetNthWord(expr, 2), &s2) )
{ s2 = Obj_ReadScalar(GetObj(Str_GetNthWord(expr, 2))); }
}
return mulDiv2Float(s1, s2, operator);
}
else // else not multiplication or division
{
if( binaryExprScale(expr) != 1.0 )
{ scale = binaryExprScale(expr); } // get expression scale if one implied by the variables
return
eval2(
UI_GetScalarArg((U8*)expr, 0, scale),
UI_GetScalarArg((U8*)expr, 2, scale),
operator); // return result.
}
}
}
/*-----------------------------------------------------------------------------------------
|
| evalExpr2SelfScale()
|
------------------------------------------------------------------------------------------*/
PRIVATE S16 evalExpr2SelfScale(U8 *expr)
{
return evalExpr2(expr, 1.0);
}
/*-----------------------------------------------------------------------------------------
|
| EvalExpr()
|
| Evaluates an expression, returns the result in the internal units implied by the
| arguments.
|
------------------------------------------------------------------------------------------*/
PUBLIC S16 EvalExpr(U8 *expr)
{
U8 op1, op2, argCnt;
float scale, f1, f2;
S_Obj CONST *obj;
S16 n;
if( (argCnt = Str_WordCnt(expr)) == 0 ) // An empty expression?
{
return 0; // An empty expression always returns false
}
if( !(op1 = getBinaryOperator(expr)) ) // no legal operator?
{
return UI_GetScalarArg(expr, 0, 1.0); // then evaluate 1st arg only
}
if( _OpIsAssignment(op1) ) // 1st arg is assignment?
{
if( (obj = GetObj(expr)) == 0 ) // 1st arg isn't an object? (it must be)
{ return 0; }
else if( !Obj_IsWritableScalar(obj) ) // 1st arg isn't writable? (it must be)
{ return 0; }
else // else 1st arg is valid l-value
{
n = evalExpr2( // Get the 2nd arg, which is the eval of...
(U8*)Str_GetNthWord(expr,2), // ...the remainder of the expression
GetArgScale(expr));
if(op1 == op_AssignPlus) // '+=" ?
{ n = AplusBS16(Obj_ReadScalar(obj), n); } // the l-value is incremented by 2nd arg
else if(op1 == op_AssignMinus) // '-='?
{ n = AminusBS16(Obj_ReadScalar(obj), n); } // then l-value is decremented by arg
else if(op1 == op_AssignMul) // '*='?
{ n = MulS16ToS16(Obj_ReadScalar(obj), n); } // then l-value is multipled by arg
else // else '='
{} // so 'l-value' will be set to 2nd arg
Obj_WriteScalar(obj, n); // write the l-value (Scalar)
return n; // and return the resulting value (of the modified l-value)
}
}
else // else 1st arg isn't assignment
{
if( !(op2 = getBinaryOperator((U8*)Str_GetNthWord(expr,2))) ) // No 2nd operator?
{
return evalExpr2SelfScale(expr); // then its a binary expression - evaluate it
}
else // else its ternary expression
{
if( resultIsBoolean(op1) ) // 1st operator returns a boolean? ...
{ // then must evaluate right-to-left
scale = // Scale for the whole expression is....
GetObj(expr) != 0 // If 1st arg is an object
? GetArgScale(expr) // then that object determines the scale
: binaryExprScale((U8*)Str_GetNthWord(expr,2)); // else remaining 2 terms determine the scale
return // Return the ternary expression result which is....
eval2( // the binary combination of...
UI_GetScalarArg((U8*)expr, 0, scale), // the value of the 1st arg
evalExpr2( // with the result of binary combination of
(U8*)Str_GetNthWord(expr,2), // the 2nd, 3rd args with their operator
scale),
op1); // all combined using the 1st operator
}
else // else 1st arg is arithmetic
{ // so evaluate left-to-right
if(op2 == op_Mul || op2 == op_Div) // Multiply or divide?
{
if( ReadASCIIToFloat((U8*)Str_GetNthWord(expr, 4), &f1) ) // 3rd arg is a literal number
{
/* ****** COMPILER BUG
This expression gives error
mulDiv2Float(evalExpr2SelfScale(expr), f1, op2))
evaluates instead to
mulDiv2Float(evalExpr2SelfScale(expr), evalExpr2SelfScale(expr), op2))
i.e the 1st parm is passed twice.
Workaround is 'f2 = evalExpr2SelfScale(expr)' then
mulDiv2Float(f2, f1, op2)
*/
f2 = evalExpr2SelfScale(expr);
return mulDiv2Float(f2, f1, op2); // then mul/divide this 3rd by result of 1st and 2nd
}
else
{
return eval2(evalExpr2SelfScale(expr), UI_GetScalarArg(expr, 4, 1.0), op2);
}
}
else
{
return
eval2(
evalExpr2SelfScale(expr),
UI_GetScalarArg(
expr,
4,
isComparision(op2) // Scale to apply to 3rd arg is.... If 2nd arg is a comparsion?
? 1.0 // then result is unscaled
: binaryExprScale(expr)), // else it's scale flows from the 1st 2 args
op2);
}
}
}
}
}
/*-----------------------------------------------------------------------------------------
|
| UI_Eval()
|
| Evaluates an expression, prints the result.
|
------------------------------------------------------------------------------------------*/
PUBLIC U8 CONST Eval_Help[] = "\
Usage: eval <expr> prints ""= expression_value""\r\n\
highest =(assigment) == <> > < >= <= + - * / &(and) |(or) lowest\r\n\
\r\n\
3 + 67 = 70\r\n\
8 / 2 = 4\r\n\
8 / 2.1 = 4 (integer aritmetic)\r\n\
SupplyV > 10 = 1 (true)\r\n\
v1 = 20 = 20 (v1 is set to 20)\r\n\
v1 = v2 - 3\r\n\
";
PUBLIC U8 UI_Eval( U8 *args )
{
UI_PrintScalar(EvalExpr(args), GetExprIO(args), _UI_PrintScalar_AppendUnits );
return 1;
}
// ----------------------------------- eof ------------------------------------------------
|
C
|
void addDays(char *date,int days,char *newDate)
{
int d1,m1,y1,d2,m2,y2;
int j1,x,j2,k;
splitDate(date,&y1,&m1,&d1);
j1=julian(d1,m1,y1);
x= isLeap(y1) ? 366-j1 : 365-j1;
if(days<=x)
{
j2=j1+days;
y2=y1;
}
else
{
days=days-x;
y2=y2+1;
k=isLeap(y2) ? 366 :365;
while(days>=k)
{
if(isLeap(y2))
days=days-366;
else
days=days-365;
y2++;
k=isLeap(y2) ? 366 : 365;
}
j2=days;
}
revJulian(j2,y2,&d2,&m2);
formDate(newDate,y2,m2,d2);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <semaphore.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <pthread.h>
#define BUFFSIZE 1024
#define NBUFF 8
struct {
struct {
char data[BUFFSIZE];
ssize_t n;
} buff[NBUFF];
sem_t mutex;
sem_t nempty;
sem_t nstored;
} shared;
static int fd = 0;
static void *producer(void *arg)
{
int i;
for (i = 0; ; )
{
sem_wait(&shared.nempty);
sem_wait(&shared.mutex);
sem_post(&shared.mutex);
shared.buff[i].n = read(fd, shared.buff[i].data, BUFFSIZE);
if (shared.buff[i].n == 0)
{
sem_post(&shared.nstored);
return NULL;
}
if (++i >= NBUFF)
i = 0;
sem_post(&shared.nstored);
}
return NULL;
}
static void *consumer(void *arg)
{
int i;
for (i = 0; ; )
{
sem_wait(&shared.nstored);
sem_wait(&shared.mutex);
sem_post(&shared.mutex);
if (shared.buff[i].n == 0)
{
return NULL;
}
write(STDOUT_FILENO, shared.buff[i].data, shared.buff[i].n);
if (++i >= NBUFF)
i = 0;
sem_post(&shared.nempty);
}
return NULL;
}
static void usage(const char *proc)
{
fprintf(stdout, "usage: %s <pathname>\n", proc);
exit(0);
}
int main(int argc, char *argv[])
{
int ret = 0;
pthread_t tid_producer;
pthread_t tid_consumer;
if (argc != 2)
usage(argv[0]);
fd = open(argv[1], O_RDONLY);
if (fd == -1)
{
fprintf(stderr, "%s open failed: %s\n", argv[1], strerror(errno));
exit(1);
}
sem_init(&shared.mutex, 0, 1);
sem_init(&shared.nempty, 0, NBUFF);
sem_init(&shared.nstored, 0, 0);
pthread_setconcurrency(2);
pthread_create(&tid_producer, NULL, producer, NULL);
pthread_create(&tid_consumer, NULL, consumer, NULL);
pthread_join(tid_producer, NULL);
pthread_join(tid_consumer, NULL);
sem_destroy(&shared.mutex);
sem_destroy(&shared.nstored);
sem_destroy(&shared.nempty);
return ret;
}
|
C
|
//
// This file was generated by the Retargetable Decompiler
// Website: https://retdec.com
//
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
// ------------------- Function Prototypes --------------------
int32_t __divdi3(void);
int32_t __udivdi3(void);
int32_t abs32(int32_t a1);
int32_t abs64(int32_t a1, int32_t a2);
int32_t sat_adds32b_var1(uint32_t a1, int32_t a2);
int32_t sat_adds32b_var2(int32_t a1, int32_t a2);
int32_t sat_adds32b_var3(int32_t a1, int32_t a2);
int32_t sat_adds64b(uint32_t a1, int32_t a2, int32_t a3, int32_t a4);
int32_t sat_addu32b(int32_t a1, uint32_t a2);
int32_t sat_addu64b(int32_t a1, int32_t a2, uint32_t a3, uint32_t a4);
int32_t sat_divs32b(int32_t a1, uint32_t a2);
int32_t sat_divs64b(int32_t a1, int32_t a2, int32_t a3, int32_t a4);
int32_t sat_divu32b(uint32_t a1, uint32_t a2);
int32_t sat_divu64b(int32_t a1, int32_t a2, int32_t a3, int32_t a4);
int32_t sat_muls32b(int32_t a1, int32_t a2);
int32_t sat_mulu32b(uint32_t a1, uint32_t a2);
int32_t sat_subs32b(int32_t a1, int32_t a2);
int32_t sat_subs64b(uint32_t a1, int32_t a2, uint32_t a3, int32_t a4);
int32_t sat_subu32b(uint32_t a1, uint32_t a2);
int32_t sat_subu64b(uint32_t a1, uint32_t a2, uint32_t a3, uint32_t a4);
int32_t sgn32(int32_t a1);
int32_t sgn64(uint32_t a1, int32_t a2);
// ------------------------ Functions -------------------------
// Address range: 0x8049070 - 0x804929c
int main(int argc, char ** argv) {
// 0x8049070
printf("sat_addu32b(0x%08x,0x%08x) = 0x%08x\n", -1, 3, sat_addu32b(-1, 3));
printf("sat_subu32b(0x%08x,0x%08x) = 0x%08x\n", 1, 3, sat_subu32b(1, 3));
printf("sat_mulu32b(0x%08x,0x%08x) = 0x%08x\n", -1, 3, sat_mulu32b(-1, 3));
printf("sat_divu32b(0x%08x,0x%08x) = 0x%08x\n", -1, 3, sat_divu32b(-1, 3));
int32_t v1 = sat_adds32b_var3(0x7fffffff, 2); // 0x80490fd
int32_t v2 = sat_adds32b_var2(0x7fffffff, 2); // 0x804910d
printf("sat_adds32b(0x%08x,0x%08x) = 0x%08x 0x%08x 0x%08x\n", 0x7fffffff, 2, sat_adds32b_var1(0x7fffffff, 2), v2, v1);
printf("sat_subs32b(0x%08x,0x%08x) = 0x%08x\n", -0x80000000, 2, sat_subs32b(-0x80000000, 2));
printf("sat_muls32b(0x%08x,0x%08x) = 0x%08x\n", 0x7fffffff, 2, sat_muls32b(0x7fffffff, 2));
printf("sat_divs32b(0x%08x,0x%08x) = 0x%08x\n", -0x80000000, -1, sat_divs32b(-0x80000000, -1));
printf("abs32(0x%08x) = 0x%08x\n", -16, abs32(-16));
printf("sgn32(0x%08x) = 0x%08x\n", 3, sgn32(3));
uint32_t v3 = sat_addu64b(0, 0, 0, 0); // 0x80491e2
uint32_t v4 = sat_subu64b(0, 0, 0, 0) + v3; // 0x8049200
uint32_t v5 = v4 + sat_divu64b(0, 0, 1, 0); // 0x8049214
uint32_t v6 = v5 + sat_adds64b(0, 0, 0, 0); // 0x8049228
uint32_t v7 = v6 + sat_subs64b(0, 0, 0, 0); // 0x804923c
uint32_t v8 = v7 + sat_divs64b(0, 0, 1, 0); // 0x804924b
uint32_t v9 = v8 + abs64(0, 0); // 0x8049260
uint32_t v10 = sgn64(0, 0); // 0x8049266
uint32_t v11 = v10 + v9; // 0x804926e
int32_t v12 = v5 < v4 ? 11 : 10; // 0x8049240
if ((v12 + ((int32_t)(v4 < v3) || 6) + (int32_t)(v6 < v5) + (int32_t)(v7 < v6) + (int32_t)(v8 < v7) + (int32_t)(v9 < v8) + (int32_t)(v11 < v10) || v11 ^ 42) == 0) {
// 0x804928a
puts("not reached");
}
// 0x804927d
return 0;
}
// Address range: 0x80493c0 - 0x80493cd
int32_t sat_addu32b(int32_t a1, uint32_t a2) {
uint32_t v1 = a2 + a1; // 0x80493c4
return v1 < a2 ? -1 : v1;
}
// Address range: 0x80493d0 - 0x80493e5
int32_t sat_subu32b(uint32_t a1, uint32_t a2) {
// 0x80493d0
return a1 >= a2 ? a1 - a2 : 0;
}
// Address range: 0x80493f0 - 0x80493fb
int32_t sat_divu32b(uint32_t a1, uint32_t a2) {
// 0x80493f0
return a1 / a2;
}
// Address range: 0x8049400 - 0x8049415
int32_t sat_mulu32b(uint32_t a1, uint32_t a2) {
uint64_t v1 = (int64_t)a2 * (int64_t)a1; // 0x8049405
return (int32_t)(v1 < 0xffffffff ? v1 : 0xffffffff);
}
// Address range: 0x8049420 - 0x8049442
int32_t sat_addu64b(int32_t a1, int32_t a2, uint32_t a3, uint32_t a4) {
uint32_t v1 = a3 + a1; // 0x804942a
uint32_t v2 = a4 + a2; // 0x804942e
return v1 < a3 ? v2 + (int32_t)(v1 < a3) <= a4 : v2 < a4 ? -1 : v1;
}
// Address range: 0x8049450 - 0x8049484
int32_t sat_subu64b(uint32_t a1, uint32_t a2, uint32_t a3, uint32_t a4) {
bool v1 = a1 < a3 ? a2 - a4 != -1 | a4 - (int32_t)(bool)(a1 < a3) > a2 : a2 < a4; // 0x804946b
return !v1 ? a1 - a3 : 0;
}
// Address range: 0x8049490 - 0x80494ac
int32_t sat_divu64b(int32_t a1, int32_t a2, int32_t a3, int32_t a4) {
// 0x8049490
return __udivdi3();
}
// Address range: 0x80494b0 - 0x80494e9
int32_t sat_adds32b_var1(uint32_t a1, int32_t a2) {
int32_t v1 = a2 + a1; // 0x80494c0
int32_t v2 = (a2 >> 31) + a1 / 0x80000000 + (int32_t)(v1 < a1); // 0x80494c2
int32_t v3 = v2 + (int32_t)(v1 < 0); // 0x80494cf
int32_t v4 = v3 > 0 == ((int32_t)(v1 < 0) - v3 & v3) < 0 ? v1 : 0x7fffffff; // 0x80494d1
int32_t v5 = v3 > 0 == ((int32_t)(v1 < 0) - v3 & v3) < 0 ? v2 : 0; // 0x80494d4
int32_t v6 = v4 <= -1; // 0x80494e1
int32_t v7 = v5 - v6; // 0x80494e1
int32_t result = v7 < 0 == ((v7 - (int32_t)(v4 > -1) ^ v5) & (v5 ^ v6)) < 0 ? v4 : -0x80000000; // 0x80494e5
return result;
}
// Address range: 0x80494f0 - 0x804951b
int32_t sat_adds32b_var2(int32_t a1, int32_t a2) {
int32_t result = a2 + a1; // 0x80494f8
if ((a2 ^ a1) > -1 == (result ^ a1) < 0) {
// 0x8049510
return a1 < 0 ? -0x80000000 : 0x7fffffff;
}
// 0x8049505
return result;
}
// Address range: 0x8049520 - 0x8049545
int32_t sat_adds32b_var3(int32_t a1, int32_t a2) {
int32_t v1 = a2 + a1; // 0x804952b
int32_t v2 = a1 < 0 ? -0x80000000 : 0x7fffffff; // 0x8049531
return (v2 ^ a2 | a2 ^ -0x80000000 ^ v1) >= 0 ? v2 : v1;
}
// Address range: 0x8049550 - 0x8049576
int32_t sat_subs32b(int32_t a1, int32_t a2) {
int32_t v1 = a1 - a2; // 0x804955e
int32_t v2 = a1 < 0 ? -0x80000000 : 0x7fffffff; // 0x8049562
return ((v2 ^ a2) & (v1 ^ v2)) < 0 ? v2 : v1;
}
// Address range: 0x8049580 - 0x804959f
int32_t sat_divs32b(int32_t a1, uint32_t a2) {
int32_t v1 = (int32_t)(bool)((a2 + 1 | a1 ^ -0x80000000) == 0) + a1; // 0x8049598
return (0x100000000 * (int64_t)(v1 >> 31) | (int64_t)v1) / (int64_t)a2;
}
// Address range: 0x80495a0 - 0x80495c9
int32_t sat_muls32b(int32_t a1, int32_t a2) {
uint64_t v1 = (int64_t)a2 * (int64_t)a1; // 0x80495a5
int32_t v2 = v1; // 0x80495a5
int32_t result = v2; // 0x80495b2
if (v2 >> 31 != (int32_t)(v1 / 0x100000000)) {
// 0x80495b4
result = (a2 ^ a1) < 0 ? -0x80000000 : 0x7fffffff;
}
// 0x80495c5
return result;
}
// Address range: 0x80495d0 - 0x8049615
int32_t sat_adds64b(uint32_t a1, int32_t a2, int32_t a3, int32_t a4) {
uint32_t v1 = a3 + a1; // 0x80495e9
int32_t v2 = a2 < 0 ? -0x80000000 : 0x7fffffff;
return (a4 + a2 + (int32_t)(v1 < a1) ^ -0x80000000 | a4) < 0 ? v1 : v2;
}
// Address range: 0x8049620 - 0x804965d
int32_t sat_subs64b(uint32_t a1, int32_t a2, uint32_t a3, int32_t a4) {
int32_t v1 = a2 < 0 ? -0x80000000 : 0x7fffffff;
return (a2 - a4 + (int32_t)(a1 < a3) & a4) >= 0 ? a1 - a3 : v1;
}
// Address range: 0x8049660 - 0x80496ba
int32_t sat_divs64b(int32_t a1, int32_t a2, int32_t a3, int32_t a4) {
// 0x8049660
return __divdi3();
}
// Address range: 0x80496c0 - 0x80496cc
int32_t abs32(int32_t a1) {
// 0x80496c0
return a1 < 0 ? -a1 : a1;
}
// Address range: 0x80496d0 - 0x80496ec
int32_t abs64(int32_t a1, int32_t a2) {
// 0x80496d0
return -(((int32_t)(bool)(a1 != 0) + a2)) < 0 ? a1 : -a1;
}
// Address range: 0x80496f0 - 0x8049701
int32_t sgn32(int32_t a1) {
// 0x80496f0
return (int32_t)(bool)(a1 >= 0 == (a1 != 0)) - (int32_t)(bool)(a1 < 0);
}
// Address range: 0x8049710 - 0x8049737
int32_t sgn64(uint32_t a1, int32_t a2) {
uint32_t v1 = a2 >> 31; // 0x804971d
return (int32_t)(v1 - a2 + (int32_t)(v1 < a1) < 0) - (int32_t)(a2 < 0);
}
// Address range: 0x8049740 - 0x8049741
int32_t __divdi3(void) {
// 0x8049740
int32_t result; // 0x8049740
return result;
}
// Address range: 0x8049880 - 0x8049881
int32_t __udivdi3(void) {
// 0x8049880
int32_t result; // 0x8049880
return result;
}
// --------------- Dynamically Linked Functions ---------------
// int printf(const char * restrict format, ...);
// int puts(const char * s);
// --------------------- Meta-Information ---------------------
// Detected compiler/packer: gcc (11.1.1)
// Detected functions: 23
|
C
|
#include "menger.h"
/**
* menger - draws a 2D Menger Sponge
* @level: is the level of the Menger Sponge to draw
*/
void menger(int level)
{
int row, column, size;
char Char;
size = pow(3, level);
for (row = 0; row < size; row++)
{
for (column = 0; column < size; column++)
{
Char = characters(row, column);
printf("%c", Char);
}
printf("\n");
}
}
/**
* characters - draws a character
* @row: number of row
* @column: number of columns
* Return: character # or empty
*/
char characters(int row, int column)
{
while (row || column)
{
if (row % 3 == 1 && column % 3 == 1)
return (' ');
row /= 3;
column /= 3;
}
return ('#');
}
|
C
|
//
// Created by PetnaKanojo on 12/02/2018.
//
#include "mystd.h"
#include "trieTree.h"
#include "mylib.h"
/*************************************
Function: initTrieTreeNode
Description: init the smallest of a node in the trieTree
Input:
word: the character.
isWord: whether it is the end of a complete word.
Return:
pnode: means this constructed node.
***************************************/
Node initTrieTreeNode(char * word, bool isWord) {
Node pnode = (Node)malloc(sizeof(struct TrieNode));
if (pnode) {
strcpy(pnode->word, word);
pnode->isWord = isWord;
pnode->child = NULL;
pnode->childNum = 0;
}
return pnode;
}
Node buildTreeNode(Node root, char *string) {
bool isWord = *(string + 3) == '\n' || *(string + 3) == '\0' || *(string + 3) == '\r';
char *tmpStr = charcpy(string);
Node node = initTrieTreeNode(tmpStr, isWord);
free(tmpStr);
if (root->childNum == 0)
root->child = (Node * )malloc(sizeof(struct TrieNode));
else
root->child = (Node * )realloc(root->child, sizeof(struct TrieNode) * (root->childNum + 1));
root->child[root->childNum] = node;
root->childNum++;
return node;
}
Node updateTreeNode(Node node, char *string) {
if (node->isWord == false)
node->isWord = *(string + 3) == '\n' || *(string + 3) == '\0' || *(string + 3) == '\r';
return node;
}
/*************************************
Function: buildTrieTree
Description: according to the string, to build up the trie tree
Input:
root: trie tree root
string: string to insert the tree
Return:
void
***************************************/
void buildTrieTree(Node root, char * string) {
while((*string != '\0') && (*string != '\n') && (*string != '\r')) { // whether it is a whole word
Node child;
bool found = false;
char *tmpStr = charcpy(string);
for (int i = 0; i < root->childNum; i++) {
if (root->child[i] && (strcmp(root->child[i]->word,tmpStr) == 0)) {
found = true;
child = updateTreeNode(root->child[i], string);
}
}
free(tmpStr);
if (!found)
child = buildTreeNode(root, string);
root = child;
string += 3;
}
}
Node createTrieTreeRoot() {
Node root = initTrieTreeNode(" ", false);
return root;
}
/*************************************
Function: findNode
Description: find whether node is in the trie tree
Input:
root: trie tree root
string: name of the node
Return:
found (bool)
***************************************/
bool findNode (Node root, char * string) {
bool found = false;
Node child;
while((*string != '\r') && (*string != '\n') && (*string != '\0') && (*string)) {// whether it is a whole word
char *tempStr = charcpy(string);
for (int i = 0; i < root->childNum; i++) {
if ((root->child[i]) && strcmp(root->child[i]->word, tempStr) == 0) {
child = root->child[i];
root = child;
found = true;
break;
} else {
found = false;
if (i == root->childNum - 1) {
return found;
}
}
}
string += 3;
if (((*string != '\r') && (*string != '\n') && (*string != '\0')) && (root->childNum == 0)) {
found = false;
free(tempStr);
break;
}
free(tempStr);
}
if (!found) {
return false;
} else {
return (root->isWord) ? true : false;
}
}
/*************************************
Function: addNewWord
Description: addNewWord to the Trie Tree && dict
Input:
root: trie tree root
string: word to add
fileName: dictFile Name
Return:
void
***************************************/
void addNewNode (Node root, char * string, char * fileName) {
FILE *fp;
if ((fp = fopen(fileName, "a")) == NULL) {
printf("FILE: open %s wrong", fileName);
} else {
buildTrieTree(root, string);
//todo inspect the end of the file to add '\n'
fwrite(string, 3*sizeof(char), strlen(string) / 3, fp);
fwrite("\n", sizeof(char), 1, fp);
fclose(fp);
printf("%s 添加成功\n", string);
}
}
void Delete(char* filename, int n){
FILE *fp1, *fp2;
char c[100];
int del_line, temp = 1;
fp1 = fopen(filename, "r");
del_line = n;
fp2 = fopen("temp.txt", "w");
while (fgets(c, 100, fp1) != NULL) {
if (temp != del_line) {
fputs(c, fp2);
}
temp++;
}
fputs("\n", fp2);
fclose(fp1);
fclose(fp2);
//remove original file
remove(filename);
//rename the file temp.txt to original name
rename("temp.txt", filename);
}
/*************************************
Function: removeWord
Description: removeWord from the Trie Tree && dict
Input:
root: trie tree root
string: word to add
fileName: dictFile Name
Return:
void
Notes: use function Delete()
***************************************/
void removeNode (Node root, char * string, char * fileName) {
FILE *fp;
char result[100];
int rowNum = 1;
if ((fp = fopen(fileName, "r")) == NULL) {
printf("FILE: %s not open\n", fileName);
} else {
while(fgets(result, 100, fp) != NULL) {
// 处理result
if (rowNum < 217145) {
result[strlen(result) - 2] ='\0';
} else {
result[strlen(result) - 1] ='\0';
}
if (strcmp(result, string) == 0) {
//printf("%s row num is: %d\n", string , rowNum);
break;
}
rowNum++;
}
printf("%d\n", rowNum);
Delete(fileName, rowNum);
printf("REMOVE DONE\n");
}
}
|
C
|
#include <stdio.h>
#include <conio.h>
#include <string.h>
int main() {
char cadena[20]="-Hoy-es-lunes-.";
int longitud, i;
longitud = strlen(cadena); //longitud de la cadena
printf("\nPALABRA ALREVEZ: ");
for(i=longitud;i>=0;i--){
printf("%c",cadena[i]);
}
return 0;
}
|
C
|
#pragma warning(disable : 4996)
#include <stdio.h>
int main(void)
{
int a, b;
scanf_s("%d %d", &a, &b);
// 0 :
// 1 :
printf("%d %d", a && b, a || b);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <dirent.h>
#include <curses.h>
#include <string.h>
#include <fcntl.h>
#include <ctype.h>
#include <sys/stat.h>
#include <sys/mman.h>
#define flechaArriba 0x1B5B41
#define flechaAbajo 0x1B5B42
#define flechaDerecha 0x1B5B43
#define flechaIzquierda 0x1B5B44
#define enter 10
/*** VARIABLES GLOBALES ***/
struct s_dir {
int tipo;
char *nombre;
} res[128];
int fd; // Archivo a leer
int fs; //Tamaño del archivo
/*** DECLARACIÓN DE FUNCIONES ***/
int leeChar();
int leerDirectorio(char *cwd);
char *hazLinea(char *base, int dir);
char *mapFile(char *filePath);
void pantallaArchivo(char *map, int base);
//char *navegarDirectorios(char *cwdLogin, char *cwd, int i);
int main() {
int j = 0, k = 0; //Variables auxiliares
int c;
int i = 0; //Número de posición del elemento en la pantalla
int pos = 0; //Número de posición del elemento del directorio
int longDir = 0; //Número de elementos que tiene el directorio
int maxPantalla = 10; //Número de elementos máximo que puedo ver en la pantalla
int offset = 0; //A partir de qué directorio estoy viendo en pantalla
int x = 9; //Coordenada x del mapeo del archivo
int y = 0; //Cordenada y del mapeo del archivo
char *cwd; //Ruta del directorio
char *map; //Nombre de archivo
long l;
initscr(); //Determina el tipo de la terminal
raw();
noecho(); //Inhabilita mostrar el caracter leido
cbreak(); //Desabilita el line buffering
cwd = getcwd(NULL,0); //Obtener la ruta actual
longDir = leerDirectorio(cwd); //Obtener la longitud del directorio y su contenido
do {
for (j=0; j < maxPantalla && (j + offset) < longDir ; j++) {
if (j == i) {
attron(A_REVERSE);
}
mvprintw(5+j,5,res[j+offset].nombre);
attroff(A_REVERSE);
}
move(5+i,5);
refresh();
c = leeChar();
switch(c) {
case flechaArriba:
if (i > 0 ){
i += -1;
} else {
if (offset > 0) {
offset -= 1;
} else {
offset = (longDir > maxPantalla) ? longDir - maxPantalla : 0;
i = (longDir > maxPantalla) ? maxPantalla - 1 : longDir - 1 ;
}
clear();
}
pos = offset + i;
break;
case flechaAbajo:
if(longDir <= maxPantalla){
i = (pos == longDir-1) ? 0 : i + 1;
} else {
if (pos == longDir-1){ //Si se ha llegado al último elemento del directorio
offset = 0;
i = 0;
} else {
if(i == maxPantalla - 1){ //Si llegó al número máximo de elementos en pantalla
offset += i;
i = 0;
} else{
i += 1;
}
}
clear();
}
pos = offset + i;
break;
case enter:
offset = 0;
clear();
if(strcmp("..", res[pos].nombre) == 0){ //Si es un directorio ".." regresa a un directorio padre
char *aux = strrchr(cwd, '/'); //Encuetra el último caracter "/"
if(aux != cwd) {
*aux = 0;
} else {
*(aux+1) = 0;
}
longDir = leerDirectorio(cwd);
i = 0; pos = 0;
clear();
} else if(res[pos].tipo == DT_DIR) { //Si es un directorio
strcat(cwd, "/");
strcat(cwd,res[pos].nombre); //Otener el directorio al que se quiere mover
longDir = leerDirectorio(cwd); //Obtener la longitud del directorio y su contenido
i = 0; pos = 0;
clear();
} else { //Si es un archivo
clear();
map = mapFile(res[pos].nombre);
if (map == NULL) {
exit(EXIT_FAILURE);
}
for(int k= 0; k<25; k++) {
// Haz linea, base y offset
char *linea = hazLinea(map,k*16);
mvprintw(k,0,linea);
}
refresh();
do{
move(0+y,x);
c = leeChar();
switch(c){
case flechaArriba:
if(y > 0){
y -= 1;
}
break;
case flechaAbajo:
if(y < 24) {
y += 1;
} else {
move(28,10);
addstr("Máximo");
/*if (fs > (25*16) && offset < (fs/16)){
offset += 1;
} else {
y = 0;
offset = 0;
clear();
}
pantallaArchivo(map,offset*16);*/
}
break;
case flechaDerecha:
if(x > 8 && x < 72) {
x = (x < 56) ? x + 3 : x + 1;
} else {
if (x > 60 && y < 24) {
y += 1; x = 9;
}
}
break;
case flechaIzquierda:
if(x > 10) {
x = (x > 57) ? x - 1 : x - 3;
}
break;
default:
// Verificar si estamos en la parte hexadecimal o decimal
if(x < 56){
//Verficar que sea un dígito hexadecimal
char n = tolower(c);
if((n >= '0' && n <= '9') || (n >= 'a' && n <= 'f')) {
char c1 = leeChar();
char n1 = tolower(c1);
if((n1 >= '0' && n1 <= '9') || (n1 >= 'a' && n1 <= 'f')) {
char hd[3];
hd[0] = n;
hd[1] = n1;
hd[2] = 0;
l = strtol(hd, NULL, 16);
map[(offset + y)*16+x] = l;
pantallaArchivo(map, offset*16);
} else { //En caso de ser un caracter inválido
move(28,10);
addstr("Caracter inválido");
}
} else { //En caso de ser un caracter inválido
move(28,10);
addstr("Caracter inválido");
}
} else {
char c1 = leeChar();
map[(offset + y)*16+x] = l;
if (isprint(c1)) {
sprintf(&map[offset + y*16 + x],"%c",c1);
}
else {
sprintf(&map[offset + y*16 + x],".");
}
}
break;
}
} while(c!=24);
close(fd);
clear();
i = 0; pos = 0;
}
//cwd = navegarDirectorios(cwdLogin, cwd, i);
break;
default:
//Nada
break;
}
move(2,10);
printw("i: %d pos: %d Offset %d Directorio actual: %s Leí %d", i, pos, offset, cwd, c);
move(25,10);
printw("Para salir presione 'q'");
} while (c != 'q');
endwin();
return 0;
//memcpy
//destino, fuente, cuánto voy a copiar
}
int leeChar() {
int chars[5];
int ch,i=0;
nodelay(stdscr, TRUE);
while((ch = getch()) == ERR); // Espera activa
ungetch(ch);
while((ch = getch()) != ERR) {
chars[i++]=ch;
}
//convierte a numero con todo lo leido
int res=0;
for(int j=0;j<i;j++) {
res <<=8;
res |= chars[j];
}
return res;
}
int leerDirectorio(char *cwd){
DIR *dir = opendir(cwd);
struct dirent *dp;
int i = 0;
while((dp=readdir(dir)) != NULL) {
res[i].tipo = dp->d_type;
res[i].nombre=dp->d_name;
i++;
}
closedir(dir);
return i;
}
char *hazLinea(char *base, int dir) {
char linea[100]; // La linea es mas pequeña
int o=0;
// Muestra 16 caracteres por cada linea
o += sprintf(linea,"%08x ",dir); // offset en hexadecimal
for(int i=0; i < 4; i++) {
unsigned char a,b,c,d;
a = base[dir+4*i+0];
b = base[dir+4*i+1];
c = base[dir+4*i+2];
d = base[dir+4*i+3];
o += sprintf(&linea[o],"%02x %02x %02x %02x ", a, b, c, d);
}
for(int i=0; i < 16; i++) {
if (isprint(base[dir+i])) {
o += sprintf(&linea[o],"%c",base[dir+i]);
}
else {
o += sprintf(&linea[o],".");
}
}
sprintf(&linea[o],"\n");
return(strdup(linea));
}
char *mapFile(char *filePath) {
//Abrir archivo
fd = open(filePath, O_RDWR);
if (fd == -1) {
perror("Error abriendo el archivo");
return(NULL);
}
//Mapea el archivo
struct stat st;
fstat(fd,&st);
fs = st.st_size;
char *map = mmap(0, fs, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (map == MAP_FAILED) {
close(fd);
perror("Error mapeando el archivo");
return(NULL);
}
return map;
}
void pantallaArchivo(char *map, int base) {
for(int i = 0; i<25; i++) {
// Haz linea, base y offset
char *l = hazLinea(map,base+i*16);
move(i,0);
addstr(l);
}
refresh();
}
/*char *navegarDirectorios(char *cwdLogin, char *cwd, int i){
}*/
|
C
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "ringbuffer.h"
/* retturn: 1-empty, 0-not empty */
int ringbuf_empty(struct ringbuffer *ringbuf)
{
if(ringbuf == NULL)
return -1;
return (ringbuf->len == 0 ? 1 : 0);
}
/* retturn: 1-full, 0-not full */
int ringbuf_full(struct ringbuffer *ringbuf)
{
if(ringbuf == NULL)
return -1;
return (ringbuf->len == ringbuf->size ? 1 : 0);
}
/* return: read byte conut */
int ringbuf_read(struct ringbuffer *ringbuf, void *buf, int len)
{
int tmplen = 0;
int retlen = 0;
if(ringbuf == NULL || buf == 0)
return -1;
if(ringbuf->len == 0)
return 0;
if(ringbuf->head > ringbuf->tail)
{
tmplen = (len <= ringbuf->head - ringbuf->tail ? len : ringbuf->head - ringbuf->tail);
memcpy(buf, ringbuf->buf +ringbuf->tail, tmplen);
ringbuf->tail += tmplen;
retlen = tmplen;
}
else
{
if(ringbuf->size -ringbuf->tail >= len)
{
memcpy(buf, ringbuf->buf +ringbuf->tail, len);
ringbuf->tail = (ringbuf->tail +len) % ringbuf->size;
retlen = len;
}
else
{
tmplen = ringbuf->size -ringbuf->tail;
memcpy(buf, ringbuf->buf +ringbuf->tail, tmplen);
ringbuf->tail = 0;
retlen = tmplen;
tmplen = (len -retlen <= ringbuf->head ? len -retlen : ringbuf->head);
memcpy(buf +retlen, ringbuf->buf +0, tmplen);
ringbuf->tail += tmplen;
retlen += tmplen;
}
}
ringbuf->len -= retlen;
return retlen;
}
/* return: write byte conut */
int ringbuf_write(struct ringbuffer *ringbuf, void *buf, int len)
{
int tmplen = 0;
int retlen = 0;
if(ringbuf == NULL || buf == 0 || len<0)
return -1;
if(ringbuf->len == ringbuf->size || len == 0)
return 0;
if(ringbuf->head >= ringbuf->tail)
{
if(ringbuf->size - ringbuf->head >= len)
{
memcpy(ringbuf->buf +ringbuf->head, buf, len);
ringbuf->head = (ringbuf->head +len) % ringbuf->size;
retlen = len;
}
else
{
tmplen = ringbuf->size -ringbuf->head;
memcpy(ringbuf->buf +ringbuf->head, buf, tmplen);
ringbuf->head = 0;
retlen += tmplen;
tmplen = (len -retlen <= ringbuf->tail ? len -retlen : ringbuf->tail);
memcpy(ringbuf->buf +0, buf +retlen, tmplen);
ringbuf->head += tmplen;
retlen += tmplen;
}
}
else
{
tmplen = (len <= ringbuf->tail -ringbuf->head -1 ? len : ringbuf->tail -ringbuf->head);
memcpy(ringbuf->buf +ringbuf->head, buf, tmplen);
ringbuf->head += tmplen;
retlen = tmplen;
}
ringbuf->len += retlen;
return retlen;
}
int ringbuf_datalen(struct ringbuffer *ringbuf)
{
if(ringbuf == NULL)
return -1;
return ringbuf->len;
}
int ringbuf_space(struct ringbuffer *ringbuf)
{
return (ringbuf->size - ringbuf->len);
}
int ringbuf_size(struct ringbuffer *ringbuf)
{
if(ringbuf == NULL)
return -1;
return ringbuf->size;
}
int ringbuf_reset(struct ringbuffer *ringbuf)
{
if(ringbuf == NULL)
return -1;
ringbuf->head = 0;
ringbuf->tail = 0;
ringbuf->len = 0;
return 0;
}
int ringbuf_init(struct ringbuffer *ringbuf, int size)
{
if(ringbuf == NULL || size <= 0)
return -1;
memset(ringbuf, 0, sizeof(struct ringbuffer));
ringbuf->buf = malloc(size);
if(ringbuf->buf == NULL)
return -1;
ringbuf->size = size;
ringbuf->head = 0;
ringbuf->tail = 0;
return 0;
}
void ringbuf_deinit(struct ringbuffer *ringbuf)
{
if(ringbuf == NULL)
return ;
free(ringbuf->buf);
memset(ringbuf, 0, sizeof(struct ringbuffer));
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <unistd.h>
const char AsciiTableHeaderStr[] = " | CHAR | HEX | DEC | BINARY |";
const char AsciiTableHeaderSep[] = " +------+------+-----+----------+";
unsigned int AsciiTableHeaderStrLen =
sizeof(AsciiTableHeaderStr) / sizeof(char);
struct ScreenSize {
int Columns;
int Rows;
};
struct ScreenSize getScreenSizeOrDefault() {
struct winsize Ws;
struct ScreenSize Ret = {80, 24};
if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &Ws)) {
return Ret;
}
Ret.Columns = Ws.ws_col;
Ret.Rows = Ws.ws_row;
return Ret;
}
void printBits(unsigned char Value) {
for (int Shift = 0; Shift < 8; Shift++) {
printf("%c", ((Value << Shift) & 0x80) ? '1' : '0');
}
}
const char *getAsciiCharRepr(unsigned char Value) {
if (Value < 33) {
static const char *AsciiRepr[33] = {
"NULL", "SOH ", "STX ", "ETX ", "EOT ", "ENQ ", "ACK ",
"'\\a'", "'\\b'", "'\\t'", "'\\n'", "'\\v'", "'\\f'", "'\\r'",
"SO ", "SI ", "DLE ", "DC1 ", "DC2 ", "DC3 ", "DC4 ",
"NAK ", "SYN ", "ETB ", "CAN ", "EM ", "SUB ", "ESC ",
"FS ", "GS ", "RS ", "US ", "' ' "};
return AsciiRepr[Value];
}
if (Value < 127) {
static char Buf[] = "'c' ";
Buf[1] = Value;
return Buf;
}
if (Value == 127) {
return "DEL ";
}
return "'.' ";
}
void printChar(unsigned char Value) { printf("%s", getAsciiCharRepr(Value)); }
void printTableHeader(int NumTables) {
for (int Idx = 0; Idx < NumTables; Idx++) {
printf("%s", AsciiTableHeaderStr);
}
printf("\n");
for (int Idx = 0; Idx < NumTables; Idx++) {
printf("%s", AsciiTableHeaderSep);
}
printf("\n");
}
void printTableRow(unsigned char Value) {
printf(" | ");
printChar(Value);
printf(" | %02X | %03d | ", Value, Value);
printBits(Value);
printf(" |");
}
void printTableRows(int NumTables, int Start, int End) {
const int RowsPerTable = (End - Start) / NumTables + 1;
for (int Value = Start; Value < Start + RowsPerTable; Value++) {
for (int TableIdx = 0; (Value + RowsPerTable * TableIdx) <= End;
TableIdx++) {
printTableRow(Value + RowsPerTable * TableIdx);
}
printf("\n");
}
}
void printAsciiTable(int MaxNumTables, int Start, int End) {
const int MinRowsPerTable = (End - Start) / MaxNumTables + 1;
const int NumTables = (End - Start) / MinRowsPerTable + 1;
printTableHeader(NumTables);
printTableRows(NumTables, Start, End);
}
int main(int Argc, char *Argv[]) {
int CharStart = 0, CharEnd = 127;
if (Argc == 2) {
if (strcmp(Argv[1], "-h") == 0) {
printf("usage:\n"
" ascii -h - Print this help screen\n"
" ascii - Print entire table [0, 127]\n"
" ascii <char value> - Print only character with given value\n"
" ascii <start> <end> - Print table for [start, end]\n"
" ascii -c <char> - Print value for given character\n");
return 0;
}
CharStart = CharEnd = atoi(Argv[1]);
} else if (Argc == 3) {
if (strcmp(Argv[1], "-c") == 0) {
CharStart = CharEnd = (unsigned char)Argv[2][0];
} else {
CharStart = atoi(Argv[1]);
CharEnd = atoi(Argv[2]);
}
}
if (CharStart < 0 || CharStart > 255 || CharEnd < 0 || CharEnd > 255 ||
CharStart > CharEnd) {
CharStart = 0;
CharEnd = 127;
}
struct ScreenSize Size = getScreenSizeOrDefault();
const int MaxNumTables = Size.Columns / AsciiTableHeaderStrLen;
printAsciiTable(MaxNumTables, CharStart, CharEnd);
return 0;
}
|
C
|
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include<dirent.h>
#include<sys/wait.h>
#include<stdio.h>
#include<string.h>
//fungsi untuk mempersingkat fork
void eksekusi(char perintah[],char *arg[]){
int status;
pid_t child_id;
child_id=fork();
if(child_id==0){
printf("%s",perintah);
execv(perintah,arg);
}
else{
((wait(&status))>0);
}
}
//buat menghapus string index-4 / .jpg
char* cut(char *arr){
int n,i;
char* cuts;
for(i=0;arr[i]!='\0';i++);
n=i-4+1;
if(n<1) return NULL;
cuts=(char*)malloc(n*sizeof(char));
for(i=0;i<n-1;i++)
cuts[i]=arr[i];
cuts[i]='\0';
return cuts;
}
int main() {
pid_t pid1;
int status;
pid1 = fork();
//child tidak berhasil dibuat
if(pid1<0){
exit(EXIT_FAILURE);
}
//child berhasil dibuat
if(pid1==0){
//membuat folder untuk menyimpan ekstrak
char *argv[]={"mkdir","-p","/home/abdunnafi25/modul2/petshop",NULL};
eksekusi("/bin/mkdir",argv);
//while((wait(NULL))>0);
//unzip pets.zip lalu di extract ke folder petshop
char *argv2[]={"unzip","-q","pets.zip","-d","/home/abdunnafi25/modul2/petshop",NULL};
execv("/usr/bin/unzip",argv2);
}
//remove file yg ga penting
while((wait(NULL))>0);
printf("coba\n");
//Membuka direktori yang telah terdapat file ekstrak
DIR *dir=opendir("/home/abdunnafi25/modul2/petshop");
struct dirent *dent;
if(dir!=NULL){
while((dent=readdir(dir))!=NULL){
//hidden file
//Membandingkan string jika terdapat . maka kontinue
if(strcmp(dent->d_name,".")==0 || strcmp(dent->d_name,"..")==0) continue;
if(fork()==0) continue;
else if(dent->d_type==DT_DIR){
char fileName[100]="/home/abdunnafi25/modul2/petshop/";
//Menggabungkan folder dengan file yang tidak penting
strcat(fileName,dent->d_name);
//Menghapus file tidak penting
char *argv[]={"rm","-rf",fileName,NULL};
eksekusi("/bin/rm",argv);
exit(EXIT_SUCCESS);
}
char *cutss=cut(dent->d_name); //menghilangkan.jpg
//membagi string menjadi beberapa bagian dengan pemisah _
//untuk foto yg ada 2 pet(dipisahin _)
char *photos;
while(photos=strtok_r(cutss,"_",&cutss)){
int i=0;
char pet[30], pName[30], pAge[30];
char *ph=photos;
char *photo;
//Memisahkan string dengan pemisah;
while(photo=strtok_r(ph,";",&ph)){
if(i==0){
//buat folder sesuai nama pets
char files[80]="/home/abdunnafi25/modul2/petshop/";
strcat(files,photo);
char *argv[]={"mkdir","-p",files,NULL};
eksekusi("/bin/mkdir",argv);
strcpy(pet,photo);
}
if(i==1){
//Mengcopy isi dari arrat photo ke array nama pets
strcpy(pName,photo);
}
if(i==2){
//Mencopy isi index 3 ke umurnya pets
strcpy(pAge,photo);
}
i++;
}
//nama folder setelah dipisah ke masing2 folder
while((wait(NULL))>0);
char fileku[80];
strcpy(fileku,"/home/abdunnafi25/modul2/petshop/");
strcat(fileku,dent->d_name);
//file destination
char dest[80];
strcpy(dest,"/home/abdunnafi25/modul2/petshop/");
strcat(dest,pet);
strcat(dest,"/");
strcat(dest,pName);
strcat(dest,".jpg");
char *argv[]={"cp",fileku,dest,NULL};
eksekusi("/bin/cp",argv);
//keterangan.txt di masing2 folder pets
char file[50];
strcpy(file,"/home/abdunnafi25/modul2/petshop/");
strcat(file,pet);
strcat(file,"/keterangan.txt");
//isi file keterangan.txt
char ch[50];
strcat(ch,"nama : ");
strcat(ch,pName);
strcat(ch,"\numur: ");
strcat(ch,pAge);
strcat(ch,"tahun\n\n");
//buat keterangan.txt
FILE *fp;
fp=fopen(file,"a");
fputs(ch,fp);
fclose(fp);
}
//remove setelah pindah ke folder masing2
char hapus[60]="/home/abdunnafi25/modul2/petshop/";
strcat(hapus,dent->d_name);
char *args[]={"rm",hapus,NULL};
execv("/bin/rm",args);
}
closedir(dir);
}
return 0;
}
|
C
|
#include <stdio.h>
/* Գв汾2 */
int main(int argc, char *argv[])
{
while(--argc){
//printf("%s%s", *++argv, argc>1?" ":"\n");
printf(argc>1?"%s ":"%s\n", *++argv);
}
return 0;
}
|
C
|
//
// Created by AmFlint on 2/16/2020.
//
#include "strconv.h"
int* get_ascii_codes()
{
int start = 48, i = 0;
int ascii_codes[10];
while(i < 10)
{
ascii_codes[i] = start + i;
i++;
}
return ascii_codes;
}
int atoi(char* string)
{
int ascii_codes[10] = get_ascii_codes();
}
char* itoa(int number)
{
int ascii_codes[10] = get_ascii_codes();
int i = 0;
char* number_to_string;
while(number > 0)
{
int current_digit = number % 10;
// Add current digit to string
number /= 10;
}
}
|
C
|
#include <stdbool.h>
void _if(bool value, void (*func1)(), void (*func2)())
{
if(value)
func1();
else
func2();
}
|
C
|
// moverobots.c
// by Chris Minich
// cfminich@gmail.com
/***
consolidate(array, count)
When multiple robots are at the same location, they have collided.
We need to sort the array, and check consecutive elements for matching locations.
Once we have a match, we add a new mine to the mine array.
Then, see if there is one or two more matches, setting all robot[] matches to non-positive values.
After we have looked through entire robot array and we're done matching, proceed to...
Delete all robot array members that have non-positive values.
*/
void consolidate(int* arr, int* arr_count)
{
int temp, xx;
int count = 0;
if (tracemode) trace(robot, 1);
for(int i=0; i<*arr_count; i++) // Sort ascending
for(int j=i+1; j<*arr_count; j++)
if (arr[j]<arr[i])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
if (tracemode) trace(robot, 2);
for(int i=0; i<*arr_count; i++) // Look for duplicates
for(int j=i+1; j<*arr_count; j++)
if ((arr[j] == arr[i]) && (arr[j] > 0))
{
xx = arr[j];
if ( init == 0 ) // create another mine, add points
{
mine[minecount++] = xx;
points = points + 10;
}
int k;
if ( i < j ) k = i; else k = j;
while ( ( arr[k] == xx ) && ( k < *arr_count ) ) // mark for deletion
arr[k++] = -33; // any non-positive value is fine
}
for(int i=0; i<*arr_count; i++) // delete any array elements with a non-positive value
if(arr[i] > 0)
{
arr[count++] = arr[i];
}
*arr_count = count;
if (tracemode)
{
trace(robot, 3);
trace(mine, 4);
}
}
void sortRobots(void)
{
consolidate(robot, &robotcount);
if(robotcount<1) finishLevel();
// printStats();
}
void moveRobots()
{
if(advanceRobots()) // moves each robot
{
if (!alive) return;
sortRobots();
if (alive == 1) refreshboard();
}
else
{
y = oldy;
x = oldx;
}
}
/***
advanceRobots()
compute new position for each robot and check to see if robot has caught the human
if player has pressed 's' for safeMode (then player believes the human is safe)
if robot catches player, call youLose()
if NOT in safe mode and robot catches player, then return 0 (don't actually move the robots)
after computing all the new robot positions, count them, deleting any robot that ran into a mine
if all robots are destroyed, call finishLevel()
*/
int advanceRobots()
{
int count = 0;
int i, j, roboty, robotx;
int caught = 0;
int captor;
for(i=0; i<robotcount; i++) // copy all robot positions
clone[i] = robot[i];
for(i=0; i<robotcount; i++) // Move robots
{
roboty = abs(robot[i] / 100);
robotx = abs(robot[i] - (roboty * 100));
if(y<roboty) roboty = roboty - 1;
if(y>roboty) roboty = roboty + 1;
if(x<robotx) robotx = robotx - 1;
if(x>robotx) robotx = robotx + 1;
robot[i] = roboty * 100 + robotx;
if((!caught) && (robot[i] == y * 100 + x)) // the robot caught the man
{
caught = 1;
hit = 'x';
captor = i;
}
for(j=0; j<minecount; j++) // see if new positions are = to any mines
if(mine[j] == robot[i]) robot[i] = 0;
}
if((caught) && (safeMode == 1))
{
youLose(captor);
}
else
{
if((caught) && (safeMode == 0)) // player DID NOT press 's', so DON'T kill player
{
for(i=0; i<robotcount; i++) robot[i] = clone[i];
return(0); // don't need to refresh the board
}
for(i=0; i<robotcount; i++) // delete any robots that ran into a mine
if(robot[i] > 0) robot[count++] = robot[i]; // go to next
robotcount = count;
if(robotcount<1)
finishLevel();
}
return(1);
}
|
C
|
#include "xy_config.h"
void NVIC_Config(void); //Ӻ
/*
ܣ豸ʼ
βΣ
ֵ
ע
*/
void XY_driver_init(void)
{
NVIC_Config(); //ж
bsp_InitTimer(); //ϵͳζʱãжϣ Freertos ṩ
USART1_Config(9600); //ڳʼ ʣ9600 printf
}
/*
ܣӡϵͳʣÿʱӵ
βΣ
ֵ
ע
*/
void Get_System_clock_freequency(void)
{
//һRCC_ClocksTypeDef Ľṹ
RCC_ClocksTypeDef get_rcc_clock;
//RCC_GetClocksFreqȡϵͳʱ״̬
RCC_GetClocksFreq(&get_rcc_clock);
XY_DEBUG("ϵͳеƵΪ %d ϵͳHCLKƵΪ %d \r\n",get_rcc_clock.SYSCLK_Frequency,get_rcc_clock.HCLK_Frequency);
}
/*************************************************************** Ӻ ***********************************************/
/*
ܣжȼ ȼ3
β:
ֵ
ע
*/
void NVIC_Config(void)
{
NVIC_InitTypeDef NVIC_InitStructure;
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_3);
NVIC_Init(&NVIC_InitStructure);
}
|
C
|
// WII-MAZE Skeleton code written by Jason Erbskorn 2007
// Edited for ncurses 2008 Tom Daniels
// Updated for Esplora 2013 TeamRursch185
// Updated for DualShock 4 2016 Rursch
// Headers
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <ncurses/ncurses.h>
#include <unistd.h>
// Mathematical constants
#define PI 3.14159
// Screen geometry
// Use ROWS and COLS for the screen height and width (set by system)
// MAXIMUMS
#define NUMCOLS 100
#define NUMROWS 72
// Character definitions taken from the ASCII table
#define AVATAR 'A'
#define WALL '*'
#define EMPTY_SPACE ' '
// 2D character array which the maze is mapped into
char MAZE[NUMROWS][NUMCOLS];
// POST: Generates a random maze structure into MAZE[][]
//You will want to use the rand() function and maybe use the output %100.
//You will have to use the argument to the command line to determine how
//difficult the maze is (how many maze characters are on the screen).
void generate_maze(int difficulty);
// PRE: MAZE[][] has been initialized by generate_maze()
// POST: Draws the maze to the screen
void draw_maze(void);
// PRE: 0 < x < COLS, 0 < y < ROWS, 0 < use < 255
// POST: Draws character use to the screen and position x,y
void draw_character(int x, int y, char use);
// PRE: -1.0 < x_mag < 1.0
// POST: Returns tilt magnitude scaled to -1.0 -> 1.0
// You may want to reuse the roll function written in previous labs.
float calc_roll(float x_mag);
// Main - Run with './ds4rd.exe -t -g -b' piped into STDIN
int main(int argc, char* argv[])
{
if (argc <2) { printf("You forgot the difficulty\n"); return 1;}
int difficulty = atoi(argv[1]); // get difficulty from first command line arg
// setup screen
initscr();
refresh();
// Generate and draw the maze, with initial avatar
int x = 50; //Center of the screen
int y = 0; //Top of the screen
generate_maze(difficulty);
draw_maze();
draw_character(x, y , AVATAR);
// Read gyroscope data to get ready for using moving averages.
int t, b1, b2, b3, b4;
double ax, ay, az, gx, gy, gz;
int endLoop = 0;
// Event loop
do
{
// Read data, update average
scanf("%d, %lf, %lf, %lf, %lf, %lf, %lf, %d, %d, %d, %d", &t, &ax, &ay, &az, &gx, &gy, &gz, &b1, &b2, &b3, &b4 );
// Is it time to move? if so, then move avatar
if(t - endLoop > 200)
{
y -= 1;
endLoop = t;
draw_character(x, y, AVATAR);
}
} while(y < NUMROWS); // Change this to end game at right time
// Print the win message
endwin();
printf("YOU WIN!\n");
return 0;
}
// PRE: 0 < x < COLS, 0 < y < ROWS, 0 < use < 255
// POST: Draws character use to the screen and position x,y
//THIS CODE FUNCTIONS FOR PLACING THE AVATAR AS PROVIDED.
//
// >>>>DO NOT CHANGE THIS FUNCTION.<<<<
void draw_character(int x, int y, char use)
{
mvaddch(y,x,use);
refresh();
}
void generate_maze(int difficulty)
{
int i, j;
for(i = 0 ; i < NUMCOLS; i++)
{
for(j = 0; j < NUMROWS; j++)
{
if(rand() % 100 >= difficulty)
{
MAZE[i][j] = ' ';
}
else
{
MAZE[i][j] = '*';
}
}
}
}//End generate_maze function
void draw_maze()
{
int i, j;
for(i = 0; i < NUMCOLS; i++)
{
for(j = 0; j < NUMROWS; j++)
{
draw_character(i, j , MAZE[i][j]);
}
}
}
|
C
|
/*
* list.c
Joel Wolfrath 2013
*
* Linked list function implementations
*/
#include <lib/list.h>
extern uint32_t debug;
/* Add the node to the end of the list */
void list_add(struct w_listnode* head, struct w_listnode* node){
struct w_listnode* it = head;
while(it->next)
it = NEXT_NODE(it);
it->next = node;
}
/* Remove the node passed as an argument */
struct w_listnode* list_remove(struct w_listnode* head, struct w_listnode* node){
struct w_listnode* del = head->next;
/* Sanity check */
if(del == NULL)
return NULL;
if(del == node){
head->next = del->next;
return del;
}
while(NEXT_NODE(del) != node)
del = NEXT_NODE(del);
struct w_listnode* prev = del;
del = prev->next;
prev->next = del->next;
return del;
}
|
C
|
#include<stdio.h>
struct wordstr
{
char word[100];
int len;
};
struct wordstr wordstring[100];
char* largestword(char *rstr)
{
int i,iword,jword,wordlen,g;
wordlen=0;
iword=0;
jword=0;
for(i=0;rstr[i]!='\0';i++)
{
if((rstr[i]==' ')||(rstr[i]=='.'))
{
if(wordlen)
{
wordstring[iword].word[jword]='\0';
wordstring[iword].len=wordlen;
iword++;
}
wordlen=0;
jword=0;
}
else
{
wordstring[iword].word[jword]=rstr[i];
wordlen++;
jword++;
}
}
if(wordlen)
{
wordstring[iword].word[jword]='\0';
wordstring[iword].len=wordlen;
}
g=iword;
while(iword+1)
{
if(wordstring[iword].len>wordstring[g].len)
g=iword;
iword--;
}
return wordstring[g].word;
}
int main()
{
char str[100];
printf("\nEnter a string:");
scanf("%[^\n]",str);
printf("\nYou have entered:\n");
puts(str);
puts("\nThe largest word is:\n");
puts(largestword(str));
return 0;
}
|
C
|
/* sort.c */
#include "global.h"
#include "sort.h"
/* Descending order. */
void quickSortDouble (int* index, double* order, int l, int r)
{
int i;
if (l < r)
{
i = partDouble (index, order, l, r);
quickSortDouble (index, order, l, i-1);
quickSortDouble (index, order, i+1, r);
}
}
/* Ascending order. */
void quickSortInt (int* index, int* order, int l, int r)
{
int i;
if (l < r)
{
i = partInt (index, order, l, r);
quickSortInt (index, order, l, i-1);
quickSortInt (index, order, i+1, r);
}
}
int partInt (int* index, int* order, int l, int r)
{
int i, j, t2;
int t1;
int pivot = order[l];
i = l;
j = r + 1;
while (1)
{
do
{
++i;
}
while (order[i] <= pivot && i <= r);
do
{
--j;
}
while (order[j] > pivot);
if (i >= j)
{
break;
}
t1 = order[i];
t2 = index[i];
order[i] = order[j];
index[i] = index[j];
order[j] = t1;
index[j] = t2;
}
t1 = order[l];
t2 = index[l];
order[l] = order[j];
index[l] = index[j];
order[j] = t1;
index[j] = t2;
return j;
}
int partDouble (int* index, double* order, int l, int r)
{
int i, j, t2;
double t1;
double pivot = order[l];
i = l;
j = r + 1;
while (1)
{
do
{
++i;
}
while (order[i] >= pivot && i <= r);
do
{
--j;
}
while (order[j] < pivot);
if (i >= j)
{
break;
}
t1 = order[i];
t2 = index[i];
order[i] = order[j];
index[i] = index[j];
order[j] = t1;
index[j] = t2;
}
t1 = order[l];
t2 = index[l];
order[l] = order[j];
index[l] = index[j];
order[j] = t1;
index[j] = t2;
return j;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
void selectionSort(int array[], int size) {
int i, j, swapper, position;
for (i = 0; i < size - 1; i++){
position = i; //first element
for (j = i + 1; j < size; j++){
if (array[position] > array[j])
position = j;
}
if (position != i){
swapper = array[i];
array[i] = array[position];
array[position] = swapper;
}
}
}
int find_smaller(int x, int y) {
if (x < y)
return x;
else
return y;
}
void mergeForTile(int array[], int subarray1[], int subarray2[], int subsize1, int subsize2) {
int i, j, k;
for (i = 0, j = 0, k = 0; i < subsize1 && j < subsize2; k++) {
if (subarray1[i] <= subarray2[j]) {
array[k] = subarray1[i];
i++;
} else {
array[k] = subarray2[j];
j++;
}
}
for (i; i < subsize1; i++, k++)
array[k] = subarray1[i];
for (j; j < subsize2; j++, k++)
array[k] = subarray2[j];
}
void merge(int array[], int p, int q, int r) {
int i, j, k;
int n1 = q - p + 1;
int n2 = r - q;
int subarray1[n1], subarray2[n2];
for (i = 0; i < n1; i++)
subarray1[i] = array[p + i];
for (j = 0; j < n2; j++)
subarray2[j] = array[q + 1 + j];
for (i = 0, j = 0, k = p; i < n1 && j < n2; k++) {
if (subarray1[i] <= subarray2[j]) {
array[k] = subarray1[i];
i++;
} else {
array[k] = subarray2[j];
j++;
}
}
for (i; i < n1; i++, k++)
array[k] = subarray1[i];
for (j; j < n2; j++, k++)
array[k] = subarray2[j];
}
void mergeSort(int array[], int p, int r) {
if (p < r) {
int q = (p + r) / 2;
mergeSort(array, p, q);
mergeSort(array, q + 1, r);
merge(array, p, q, r);
}
}
void bottomUpMergeSort(int array[], int size) {
int subarray_size, index_start;
for (subarray_size = 1; subarray_size <= size - 1; subarray_size = subarray_size * 2) {
for (index_start = 0; index_start < size - 1; index_start = index_start + subarray_size * 2) {
int index_middle = index_start + subarray_size - 1;
int index_end = find_smaller(index_start + subarray_size * 2 - 1, size - 1);
merge(array, index_start, index_middle, index_end);
}
}
}
void tiledMergeSort (int array[], int size) {
int subsize1, subsize2;
if (size % 2 == 0) {
subsize1 = size / 2;
subsize2 = size / 2;
} else {
subsize1 = size / 2 + 1;
subsize2 = size / 2;
}
int subarray1[subsize1], subarray2[subsize2], i, j;
for (i = 0; i < subsize1; i++)
subarray1[i] = array[i];
for (j = 0, i = subsize1; j < subsize2; i++, j++)
subarray2[j] = array[i];
selectionSort(subarray1, subsize1);
selectionSort(subarray2, subsize2);
mergeForTile(array, subarray1, subarray2, subsize1, subsize2);
}
int main() {
srand(time(NULL));
int size, i, j;
size = pow(2, 16);
int array[size];
//ascending
//for (i = 0, i < size; i < size; i++)
// array[i] = i;
//descending
//for (i = 0, j = size; i < size; i++, --j)
// array[i] = j;
//random
for (i = 0; i < size; i++)
array[i] = rand();
/*printf("Original: \n");
for (i = 0; i < size; i++)
printf("%d\t", array[i]);*/
//SORTING METHOD HERE
//mergeSort(array, 0, size);
//bottomUpMergeSort(array, size);
tiledMergeSort(array, size);
/*printf("\nSorted: \n");
for (i = 0; i < size; i++)
printf("%d\t", array[i]);*/
return 0;
}
|
C
|
class Solution {
public:
string convertToBase7(int num) {
string res;
long num0 = num;
if(num0<0) num0 = -num0;
do{
res.push_back(num0%7+'0');
num0/=7;
}while(num0);
if(num < 0) res.push_back('-');
reverse(res.begin(), res.end());
return res;
}
};
|
C
|
#include<stdio.h>
main()
{
char a;
int sum=0;
for (; ;)
{
printf("Enter any character_",&a);
scanf(" %c",&a);
sum=sum+1;
if(a=='z')
break;
}
printf("number of characters = %d",sum);
}
|
C
|
#include <ctype.h>
#include "./Calculator/getch.c"
#define SIZE 100
int getch(void);
void ungetch(int);
int n, arr[SIZE], getint(int *);
int cnt;
int main(int argc, char const *argv[])
{
for(n=0; n<SIZE && getint(&arr[n]) != EOF;n++)
{
cnt++;
};
for(int i=0; i<cnt; ++i)
{
printf("%d\n", arr[i]);
}
return 0;
}
int getint(int *pn)
{
int c;
while(isspace(c = getch()))
;
if(!isdigit(c) && c != EOF && c != '+'
&& c != '-')
{
ungetch(c);
return 0;
}
int sign = (c == '-') ? -1:1;
if(c == '+' || c == '-')
c = getch();
for(*pn=0; isdigit(c); c=getch())
*pn = 10*(*pn)+(c-'0');
*pn *= sign;
if(c != EOF)
ungetch(c);
return c;
}
|
C
|
#include <stdio.h>
#include <unistd.h>
int main() {
int n = 10;
printf("主进程号pid: %d\n", getpid());
pid_t pid = fork();
if (pid > 0) {
printf("父进程的返回值: %d\n", pid);
printf("父进程pid: %d\n", getpid());
printf("父进程ppid: %d\n", getppid());
printf("父进程n值修改前: %d\n", n);
n += 10;
printf("父进程n值修改后: %d\n", n);
} else
{
printf("子进程的返回值: %d\n", pid);
printf("子进程pid: %d\n", getpid());
printf("子进程ppid: %d\n", getppid());
printf("子进程n值修改前: %d\n", n);
n += 100;
printf("子进程n值修改后: %d\n", n);
}
for ( int i = 0; i < 3; i++ ) {
printf("i = %d\n", i);
}
return 0;
}
/*
主进程号pid: 17723
父进程的返回值: 17724
父进程pid: 17723
父进程ppid: 16419
父进程n值修改前: 10
父进程n值修改后: 20
i = 0
i = 1
i = 2
子进程的返回值: 0
子进程pid: 17724
子进程ppid: 1
子进程n值修改前: 10
子进程n值修改后: 110
i = 0
i = 1
i = 2
*/
|
C
|
#include <stdio.h>
int bissexto(int n){
if(n%4==0){
if((n%100==0) && (n%400!=0))
return 0;
else{
return 1;
}
}
return 0;
}
int main(void)
{ int x;
scanf("%d", &x);
printf("A %d\n", bissexto(x));
}
|
C
|
#pragma once
// - ;
double**CreateMatr(int sizeI, int sizeJ);
// - ;
void DeleteMatr(double **ptr, int sizeI);
//-
void InputMatr(double **ptr, int sizeI, int sizeJ);
//-
void OutputMatr(double **ptr, int sizeI, int sizeJ);
// - random;
void RandMatr(double **ptr, int sizeI, int sizeJ);
// ;
double SumRow(double **ptr, int NowRow, int sizeJ);
// ;
double SumCol(double **ptr, int sizeI, int NumCol);
// min
double MinElem(double**ptr, int sizeI, int sizeJ);
// max
double MaxElem(double**ptr, int sizeI, int sizeJ);
// - ;
double** AddRowEnd(double**ptr, int& sizeI, int sizeJ);
// - ;
void AddColEnd(double**ptr, int sizeI, int& sizeJ);
// - ;
void DelRowEnd(double **ptr, int& sizeI, int sizeJ);
// - ;
void DelColEnd(double **ptr, int sizeI, int& sizeJ);
|
C
|
#include "shell.h"
/**
* _strcpy - copies the string pointed to by src,
* @dest: destnation poiter to take value
* @src: array poited that gets copied
* Description: copies string pointed to by src,
* Return: dest
*/
char *_strcpy(char *dest, char *src)
{
int i;
for (i = 0; src[i] != '\0'; i++)
dest[i] = src[i];
dest[i] = '\0';
return (dest);
}
/**
*_strchr - locates a character in a string
*@s: string
*@c: string
*Return: a pointer to the first occurrence of character c in the string s
*or NULL if character is not found
*/
char *_strchr(char *s, char c)
{
int count;
for (count = 0; s[count] != '\0'; count++)
{
if (s[count] == c)
return (s + count);
}
if (s[count] == c)
return (s + count);
return (0);
}
/**
*_strcat - concatenates two strings
*@dest: Destination of the new string
*@src: Source of the string
*Return: Return dest
*/
char *_strcat(char *dest, char *src)
{
int i = 0, j;
while (*(dest + i))
{
i++;
}
for (j = 0; *(src + j); j++, i++)
{
*(dest + i) = *(src + j);
}
*(dest + i) = '\0';
return (dest);
}
/**
* _strdup - returns a pointer to a newly allocated space in memory
* which contains a copy of the string given as a parameter
* @str: string
* Return: Pointer to the duplicate, NULL if it fails
*/
char *_strdup(char *str)
{
int con1, lon, con2;
char *fundup;
if (str == 0)
return (NULL);
for (con1 = 0; str[con1] != '\0'; con1++)
;
lon = con1;
fundup = malloc(sizeof(char) * lon + 1);
if (fundup == 0)
return (NULL);
for (con2 = 0; con2 < lon; con2++)
fundup[con2] = str[con2];
fundup[lon] = str[lon];
return (fundup);
}
|
C
|
#include<stdio.h>
int main(){
char * hello="Hello, World\n";
printf("%s", hello);
return 0;
}
|
C
|
// Calculate Net price
#include <stdio.h>
void main()
{
int qty, price, amount, discount, tax,gross_amount,net_price;
printf("Enter quantity : ");
scanf("%d",&qty);
printf("Enter price : ");
scanf("%d",&price);
amount = qty * price;
discount = amount * 0.10;
gross_amount = amount - discount;
tax = gross_amount * 0.12;
net_price = gross_amount + tax;
printf("\nAmount : %d", amount);
printf("\n - Discount : %d", discount);
printf("\n ---------");
printf("\nGross Amount : %d", gross_amount);
printf("\n + Tax : %d", tax);
printf("\n ---------");
printf("\nNet Price : %d", net_price);
}
|
C
|
#include <stdio.h>
int main()
{
const int target = 200;
int coins[] = {1, 2, 5, 10, 20, 50, 100, 200};
// initialise array to all zeros, first value as 1
int n[target];
for (int i = 0; i <= target; i++) n[i] = 0;
n[0] = 1;
for (int i = 0; i <= 8; i++) {
for (int j = coins[i]; j <= target; j++) {
n[j] += n[j - coins[i]];
}
}
printf("%i\n", n[target]);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "stack.h"
// Define a new NULL stack pointer and return it
// Constructor that initializes an empty stack pointer
STACK new_stack() {
STACK new = NULL;
return new;
}
/* Add one more element
* Setter for pushing a value onto the stack
1. Allocate memory for a new stack and return the address of the new stack (what function malloc() does);
2. Set the value in the new stack to "val";
3. Set the head of the new stack to s;
It means the new stack is now pointing to the next stack, which was the first stack before;
4. Reset address s to address new, which means s is pointing to the newly pushed stack.
*/
void push_stack(STACK *s, SVALUE val) {
// Use STACK *s instead of just STACK s because we do want to change the address in pointer s, not the address in the copy of s
STACK new = (STACK) malloc(sizeof(struct stack));
new->data = val;
new->head = *s;
*s = new;
}
/*
* Remove the first element and return the value in the removed stack
* Getter for popping a value off the stack
1. Define temporay variable SVALUE (int) val and STACK temp;
2. Check whether s points to NULL. If yes, it means s is already the head in the very bottom stack. Set "val" to -1;
3. Otherwise, set "val" equal to the data value in the first stack that we are trying to remove now;
4. Set "temp" to address s, which is like making a copy of address s;
4. Set the address in s to the head address first stack, so now s is pointing to the second stack;
5. Free the memory of the address in temp, which is the first stack;
6. Return the value in the deleted stack.
*/
SVALUE pop_stack(STACK *s) {
// Use STACK *s instead of just STACK s for the same reason in push_stack
SVALUE val;
STACK temp;
if (*s == NULL) {
val = -1;
}
else {
val = (*s)->data;
temp = (*s);
*s = (*s)->head;
free(temp);
}
return val;
}
// Printer for svalue
void print_svalue(SVALUE val) {
printf("%d", val);
}
/* Printer for stack
* Print each element from up to bottom
*/
void print_stack(STACK s) {
while (s->head != NULL) {
print_svalue(s->data);
printf("\t");
s = s->head;
}
print_svalue(s->data);
printf("\n");
}
/* Slightly different, but also works
* Printer for stack
* No need to do "print_svalue(s->data)" again after while loop, but would leave an unused tab at the end of the line
void print_stack(STACK s) {
while (s != NULL) {
print_svalue(s->data);
printf("\t");
s = s->head;
}
puts("");
}
*/
|
C
|
//Written By Pragik Timsina
//Find the Factorial of a Given Number N.
#include <stdio.h>
#include <conio.h>
void main()
{
long int n,i,f=1;
clrscr();
printf("Enter the Number\n");
scanf("%ld",&n);
for (i=1;i<=n;i++)
{
f=f*i;
}
printf("The factorial of %ld is %ld",n,f);
getch();
}
|
C
|
#include <stdio.h>
#include "ex6.h"
void main (){
int x = 12988181;
int y = ddd (x);
printf("%d", y);
x = 32988181;
y = ddd (x);
printf("\n%d", y);
x = 31982289;
y = ddd (x);
printf("\n%d", y);
int a = 5;
int b = 32;
int c = 99;
x = soma1SePar (a);
y = soma1SePar (b);
int z = soma1SePar (c);
printf("\n%d \n%d \n%d", x, y, z);
a = 2;
b = 1;
c = 55;
x = parOuImpar (a);
y = parOuImpar (b);
z = parOuImpar (c);
printf ("\n%d \n%d \n%d", x, y, z);
}
|
C
|
void ft_putnbr(int nb);
int main()
{
int nb;
nb = -2147483648;
ft_putnbr(nb);
}
|
C
|
#include<stdio.h>
#include<math.h>
double tfun(char a, double f);
int sqr(int sq);
int cange(void);
int main(void){
int b = 1, w = 1, sq;
double f, s, ans, ans2, k;
char a, c, d, e, fun;
/*eはエンター読み取り専用*/
/*平方根*/
printf("平方根を求めたい場合は's'を、電卓機能を使いたい場合はそれ以外をを入力してください。\n");
scanf("%c", &fun);
if(fun == '\n'){
scanf("%c", &fun);
}
if(fun == 's'){
printf("平方根を求めたい数を整数で入力してください。\n");
scanf("%d", &sq);
sqr(sq);
return 0;
}
/*電卓*/
printf("1つめの数を入力してください。三角関数を使用したい場合は使いたい関数の頭文字を入力したい角度の先頭につけて入力してください。\n使わない場合は数の先頭に n をつけてください。\n");
scanf("%1c", &e);
scanf("%1c", &a);
scanf("%lf", &f);
for(;a == '\n';){
printf("もう一度入力してください。\n");
scanf("%1c", &a);
scanf("%lf", &f);
}
for(;a != 's' && a != 'c' && a != 't' && a != 'n';){
printf("s c t n のどれかを入力してください。\n");
scanf("%1c", &e);
scanf("%1c", &a);
scanf("%lf", &f);
}
/*一文字目*/
f = tfun(a, f);
/*二文字目(繰り返し開始)*/
for(s = 0 ; b == 1;){
printf("演算子を入力してください。(+ - * /)\n");
scanf("%1c", &c);
for(;c != '+'&& c != '-' && c != '*' && c != '/';){
printf("+ - * /のどれかを入力してください。\n");
scanf("%1c", &c);
}
/*二文字目(読み取り)*/
printf("1つ目と同様にして2つ目の数を入力してください。\n");
scanf("%1c", &e);
scanf("%1c", &d);
scanf("%lf", &s);
for(;d == '\n';){
printf("qwertyuiop\n");
scanf("%1c", &d);
scanf("%lf", &s);
scanf("%c", &e);
}
for(;d != 's' && d != 'c' && d != 't' && d != 'n';){
printf("もう一度入力してください。\ns c t n のどれかを入力してください。\n");
scanf("%1c", &d);
scanf("%lf", &s);
scanf("%c", &e);
}
s = tfun(d, s);
/*演算*/
switch(c){
case'+':{
ans = f + s;
break;
}
case'-':{
ans = f - s;
break;
}
case'*':{
ans = f * s;
break;
}
case'/':{
if(s == 0){
printf("0で割り算はできません。もう一度始めからやり直してください。\n");
b = 0;
w = 0;
break;
}
ans = f / s;
break;
}
}
if(w != 0){
printf("%lf %c %lf =%lf\n平方根を求めたい場合は2を\n計算を続ける場合は1を\nやめる場合は0を入力してください。\n", f, c, s, ans);
scanf("%1d", &b);
if(b == 1){
f = ans;
}
if(b == 2){
cange();
}
}
}
return 0;
}
/*三角関数処理*/
double tfun(char a, double f){
switch(a){
case 's':{
f = f * M_PI / 180;
f = sin(f);
break;
}
case'c':{
f = f * M_PI / 180;
f = cos(f);
break;
}
case't':{
f = f * M_PI / 180;
f = tan(f);
break;
}
}
return f;
}
/*平方根*/
int sqr(int sq){
double k;
int a;
k = sqrt(sq);
printf("%dの平方根は%lfです。\n", sq, k);
printf("電卓を使用したい場合は1を、終了する場合は0を入力してください。\n");
scanf("%d", &a);
if(a == 1){
main();
}
return 0;
}
/*メインに乗り換え*/
int cange(void){
main();
return 0;
}
|
C
|
#include <stdio.h>
int main(void)
{
char lowercase[26];
char ch;
int count;
for (count = 0,ch = 'a'; count < 26,ch <= 'z'; count++,ch++) {
lowercase[count] = ch;
}
for (count = 0; count < 26; count++) {
printf("%c ", lowercase[count]);
}
return 0;
}
|
C
|
/*
* UserProgram.c
*
* Created on: 11 de jun de 2018
* Author: Gabriel
*/
/* Includes ------------------------------------------------------------------*/
#include "UserProgram.h"
/* User ScanTime selection */
int ScanTimeLimit()
{
int TimeLimit = 25;
return TimeLimit;
}
/* User program space */
void CallUserProgram(int Digital_Analog, int Digital_Input, int *Output)
{
*Output = *Output | 15;
/* Check input 0 */
if((Digital_Input & 1) == 0)
{
*Output = 1;
}
/* Check input 1 */
if((Digital_Input & 2) == 0)
{
*Output = 2;
}
/* Check input 2 */
if((Digital_Input & 4) == 0)
{
*Output = 4;
}
/* Check input 3 */
if((Digital_Input & 8) == 0)
{
*Output = 8;
}
/* Check all digital inputs */
if(Digital_Input == 0)
{
// *Output = *Output | 12;
}
/* Check analog input */
if(Digital_Analog >= 250)
{
*Output = *Output = 0;
}
else if ((Digital_Analog >= 110) && (Digital_Analog <= 135))
{
*Output = *Output = 9;
}
}
|
C
|
/*~!exp.c*/
/* Name: exp.c Part No.: _______-____r
*
* Copyright 1992 - J B Systems, Morrison, CO
*
* The recipient of this product specifically agrees not to distribute,
* disclose, or disseminate in any way, to any one, nor use for its own
* benefit, or the benefit of others, any information contained herein
* without the expressed written consent of J B Systems.
*
* RESTRICTED RIGHTS LEGEND
*
* Use, duplication, or disclosure by the Government is subject to
* restriction as set forth in paragraph (b) (3) (B) of the Rights
* in Technical Data and Computer Software Clause in DAR 7-104.9
* (a).
*/
#ident "@(#)nbclib:exp.c 1.1"
/*
* exp returns the exponential function of its double-precision argument.
* Returns ERANGE error and value 0 if argument too small,
* value HUGE if argument too large.
* Algorithm and coefficients from Cody and Waite (1980).
* Calls ldexp.
*/
#include <math.h>
#include <values.h>
#include <errno.h>
static double p[] = {
0.31555192765684646356e-4,
0.75753180159422776666e-2,
0.25000000000000000000e0,
}, q[] = {
0.75104028399870046114e-6,
0.63121894374398503557e-3,
0.56817302698551221787e-1,
0.50000000000000000000e0,
};
/*
#ifdef ieee
*/
static double rval;
/*
#endif
*/
double
exp(x)
register double x;
{
register double y;
register int n;
struct exception exc;
exc.arg1 = x;
if (x < 0)
x = -x;
if (x < X_EPS) /* use first term of Taylor series expansion */
return (1.0 + exc.arg1);
exc.name = "exp";
if (exc.arg1 <= LN_MINDOUBLE) {
if (exc.arg1 == LN_MINDOUBLE) /* protect against roundoff */
#ifdef ieee
{
asm (" lw 0,=x'7bcfffff'");
asm (" lw 1,=x'ffffffff'");
asm (" std 0,_rval");
return (rval); /* causing ldexp to underflow */
}
#else
#ifdef USE_ASM
/* for gould, min double value */
{
asm (" lw 0,=x'00100000'");
asm (" lw 1,=x'000000ca'");
asm (" std 0,_rval");
return (rval); /* causing ldexp to underflow */
}
#else
return (MINDOUBLE); /* causing ldexp to underflow */
#endif
#endif
exc.type = UNDERFLOW;
exc.retval = 0.0;
if (!matherr(&exc))
errno = ERANGE;
return (exc.retval);
}
if (exc.arg1 >= LN_MAXDOUBLE) {
if (exc.arg1 == LN_MAXDOUBLE) /* protect against roundoff */
return (MAXDOUBLE); /* causing ldexp to overflow */
exc.type = OVERFLOW;
exc.retval = HUGE;
if (!matherr(&exc))
errno = ERANGE;
return (exc.retval);
}
n = (int)(x * M_LOG2E + 0.5);
y = (double)n;
_REDUCE(int, x, y, 0.693359375, -2.1219444005469058277e-4);
if (exc.arg1 < 0) {
x = -x;
n = -n;
}
y = x * x;
x *= _POLY2(y, p);
return (ldexp(0.5 + x/(_POLY3(y, q) - x), n + 1));
}
|
C
|
/**
* @file gameentities.h
*
* @author Killax-D | Dylan DONNE
*
* @brief GameEntities contains all the entities defined in game (Items Entities & IA Entities)
*
* This file contains all declarations and function regarding GameEntities
*
*/
#ifndef GAMEENTITIES_H
#define GAMEENTITIES_H
#include "gameitemsentities.h"
#include "gameiaentities.h"
#include "gameitems.h"
#include "assets.h"
#define MAX_ENTITIES_ITEMS 10 /**< The number of GameItemsEntities present in game */
// ITEM ENTITY ID
#define ITEM_ENGINE_KEY_ENTITY 0
#define ITEM_MAGNET_CARD_BLUE_ENTITY 1
#define ITEM_MAGNET_CARD_GREEN_ENTITY 2
#define ITEM_MAGNET_CARD_RED_ENTITY 3
#define ITEM_CELL_KEY_ENTITY 4
#define ITEM_BOMB_ENTITY 5
#define ITEM_ROPE_ENTITY 6
#define ITEM_AMMONIUM_NITRATE_ENTITY 7
#define ITEM_USB_KEY_ENTITY 8
#define ITEM_MAGNET_CARD_YELLOW_ENTITY 9
#define MAX_ENTITIES_IA 11 /**< The number of GameIAEntities present in game */
typedef struct GameEntities {
GameItemsEntities * itemsEntities[MAX_ENTITIES_ITEMS]; /**< The GameItemsEntities List */
GameIAEntities * iaEntities[MAX_ENTITIES_IA]; /**< The GameIAEntities List */
} GameEntities;
/**
* Initialize some variables of a GameEntities
* @param gameEntities The GameEntities to initialize
* @param gameItems All the Item present in Game
* @param assets The Assets manager to retrieve required assets
*/
void GameEntities_init(GameEntities * gameEntities, GameItems * gameItems, Assets * assets);
/**
* Update all the entities present in the Game
* @param game The Game to retrieve data
* @param gameEntities The GameEntities to update
* @param delta The delta time between the previous frame and the current
*/
void GameEntities_update(Game * game, GameEntities * gameEntities, float delta);
/**
* Control all the entities present in the Game
* @param game The Game to retrieve data
* @param gameEntities The GameEntities to update
*/
void GameEntities_control(Game * game, GameEntities * gameEntities);
/**
* Draw all GameEntities with Raylib
* @param gameEntities The GameEntities to draw
*/
void GameEntities_draw(GameEntities * gameEntities);
#endif
|
C
|
#include <stdio.h>
//t.cn/E9lOOZQ
int fanxushu(int x){
while(x!=0){
if(x%10==7) return 1;
x/=10;
}
return -1;
}
int ifrel2seven(int x){
// printf("%d",fanxushu(x));
if((x%7==0)||(fanxushu(x)==1)) return 1;
else return -1;
}
main(){
int b=0;
scanf("%d",&b);
int x,sum=0;
for(x=0;x<=b;x++){
// printf("%d",ifrel2seven(x));
if(ifrel2seven(x)==-1){
sum+=x*x;
}
}
printf("%d\n",sum);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#define true 1
#define false 0
#define _MAX_ELEMENTOS_ 1000
typedef int bool;
typedef struct aux
{
int id;
float prioridade;
struct aux* ant;
struct aux* prox;
} ELEMENTO, * PONT;
typedef struct
{
int maxElementos;
PONT fila;
PONT* arranjo;
} FILADEPRIORIDADE, * PFILA;
// as funcoes
bool aumentarPrioridade(PFILA,int,float);
bool consultarPrioridade(PFILA,int,float*);
PFILA criarFila(int);
bool inserirElemento(PFILA,int,float);
bool reduzirPrioridade(PFILA,int,float);
PONT removerElemento(PFILA);
int tamanho(PFILA);
// outras funcoes
void exibirLog(PFILA);
bool trocaPrioridade(PFILA, int, float);
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <stdbool.h>
#include "../src/zsorted_hash.h"
// generate strings of random ASCII characters 64 to 126
// between 5 and 20 characters
static char *random_string()
{
size_t length, ii;
char *str;
length = rand() % 15 + 5;
str = malloc((length + 1) * sizeof(char));
for (ii = 0; ii < length; ii++) {
str[ii] = rand() % 62 + 64;
}
str[length] = '\0';
return str;
}
static void zsorted_hash_set_test()
{
size_t size, ii;
char **keys, **vals;
struct ZSortedHashTable *hash_table;
size = 100;
hash_table = zcreate_sorted_hash_table();
keys = malloc(size * sizeof(char *));
vals = malloc(size * sizeof(char *));
for (ii = 0; ii < size; ii++) {
keys[ii] = random_string();
vals[ii] = random_string();
zsorted_hash_set(hash_table, keys[ii], (void *) vals[ii]);
}
assert(zsorted_hash_count(hash_table) == size);
for (ii = 0; ii < size; ii++) {
assert(strcmp((char *) zsorted_hash_get(hash_table, keys[ii]), vals[ii]) == 0);
}
for (ii = 0; ii < size; ii++) {
free(keys[ii]);
free(vals[ii]);
}
free(keys);
free(vals);
zfree_sorted_hash_table(hash_table);
}
static void zsorted_hash_delete_test()
{
size_t size, ii;
char **keys, **vals;
struct ZSortedHashTable *hash_table;
size = 100;
hash_table = zcreate_sorted_hash_table();
keys = malloc(size * sizeof(char *));
vals = malloc(size * sizeof(char *));
for (ii = 0; ii < size; ii++) {
keys[ii] = random_string();
vals[ii] = random_string();
zsorted_hash_set(hash_table, keys[ii], (void *) vals[ii]);
}
assert(zsorted_hash_count(hash_table) == size);
for (ii = 0; ii < 7 * size / 8; ii++) {
zsorted_hash_delete(hash_table, keys[ii]);
}
for (ii = 0; ii < size; ii++) {
if (ii < 7 * size / 8) {
assert(zsorted_hash_get(hash_table, keys[ii]) == NULL);
} else {
assert(strcmp((char *) zsorted_hash_get(hash_table, keys[ii]), vals[ii]) == 0);
}
}
assert(zsorted_hash_count(hash_table) == size - 7 * size / 8);
for (ii = 0; ii < size; ii++) {
free(keys[ii]);
free(vals[ii]);
}
free(keys);
free(vals);
zfree_sorted_hash_table(hash_table);
}
static void zsorted_hash_exists_test()
{
struct ZSortedHashTable *hash_table;
hash_table = zcreate_sorted_hash_table();
zsorted_hash_set(hash_table, "hello", (void *) "world");
zsorted_hash_set(hash_table, "nothing", NULL);
assert(zsorted_hash_exists(hash_table, "hello") == true);
assert(zsorted_hash_exists(hash_table, "nothing") == true);
assert(zsorted_hash_get(hash_table, "nothing") == NULL);
assert(zsorted_hash_exists(hash_table, "nope") == false);
zfree_sorted_hash_table(hash_table);
}
static void ziterator_test()
{
size_t size, ii;
char **keys, **vals;
struct ZSortedHashTable *hash_table;
struct ZIterator *iterator;
size = 100;
hash_table = zcreate_sorted_hash_table();
keys = malloc(size * sizeof(char *));
vals = malloc(size * sizeof(char *));
for (ii = 0; ii < size; ii++) {
keys[ii] = random_string();
vals[ii] = random_string();
zsorted_hash_set(hash_table, keys[ii], (void *) vals[ii]);
}
zsorted_hash_delete(hash_table, keys[0]);
zsorted_hash_delete(hash_table, keys[20]);
zsorted_hash_delete(hash_table, keys[size - 1]);
zsorted_hash_set(hash_table, keys[90], (void *) vals[90]);
iterator = zcreate_iterator(hash_table);
for (ii = 1; ii < size - 1; ii++) {
if (ii != 20) {
assert(ziterator_exists(iterator) == true);
assert(strcmp(ziterator_get_key(iterator), keys[ii]) == 0);
assert(strcmp((char *) ziterator_get_val(iterator), vals[ii]) == 0);
ziterator_next(iterator);
}
}
assert(ziterator_exists(iterator) == false);
assert(ziterator_get_key(iterator) == NULL);
assert(ziterator_get_val(iterator) == NULL);
ziterator_next(iterator);
ziterator_prev(iterator);
for (ii = size - 2; ii > 0; ii--) {
if (ii != 20) {
assert(ziterator_exists(iterator) == true);
assert(strcmp(ziterator_get_key(iterator), keys[ii]) == 0);
assert(strcmp((char *) ziterator_get_val(iterator), vals[ii]) == 0);
ziterator_prev(iterator);
}
}
assert(ziterator_exists(iterator) == false);
assert(ziterator_get_key(iterator) == NULL);
assert(ziterator_get_val(iterator) == NULL);
for (ii = 0; ii < size; ii++) {
free(keys[ii]);
free(vals[ii]);
}
free(keys);
free(vals);
zfree_iterator(iterator);
zfree_sorted_hash_table(hash_table);
}
int main()
{
zsorted_hash_set_test();
zsorted_hash_delete_test();
zsorted_hash_exists_test();
ziterator_test();
return 0;
}
|
C
|
#ifndef SILO_GATE_CODE
#define SILO_GATE_CODE
#include <stdio.h>
#include "silo_node.h"
#include "silo_gate.h"
#include "silo_simulate.h"
inline SIGNAL NodeReadInput(NODE * node, PORTID portid) {
return node->input[portid];
}
void GateADD(NODE * node) {
SIGNAL a, b, c;
a = NodeReadInput(node, 0);
b = NodeReadInput(node, 1);
c.value = a.value + b.value;
c.state = -1;
SendSignal(node->output[0], c);
return;
}
void GateSUB(NODE * node) {
SIGNAL a, b, c;
a = NodeReadInput(node, 0);
b = NodeReadInput(node, 1);
c.value = a.value - b.value;
c.state = -1;
SendSignal(node->output[0], c);
return;
}
void GateMUL(NODE * node) {
SIGNAL a, b, c;
a = NodeReadInput(node, 0);
b = NodeReadInput(node, 1);
c.value = a.value * b.value;
c.state = -1;
SendSignal(node->output[0], c);
return;
}
void GateDIV(NODE * node) {
SIGNAL a, b, c;
a = NodeReadInput(node, 0);
b = NodeReadInput(node, 1);
c.value = a.value / b.value;
c.state = -1;
SendSignal(node->output[0], c);
return;
}
void GateMOD(NODE * node) {
SIGNAL a, b, c;
a = NodeReadInput(node, 0);
b = NodeReadInput(node, 1);
c.value = a.value % b.value;
c.state = -1;
SendSignal(node->output[0], c);
return;
}
void GateAND(NODE * node) {
SIGNAL a, b, c;
a = NodeReadInput(node, 0);
b = NodeReadInput(node, 1);
c.value = a.value & b.value;
c.state = -1;
SendSignal(node->output[0], c);
return;
}
void GateIOR(NODE * node) {
SIGNAL a, b, c;
a = NodeReadInput(node, 0);
b = NodeReadInput(node, 1);
c.value = a.value | b.value;
c.state = -1;
SendSignal(node->output[0], c);
return;
}
void GateEOR(NODE * node) {
SIGNAL a, b, c;
a = NodeReadInput(node, 0);
b = NodeReadInput(node, 1);
c.value = a.value ^ b.value;
c.state = -1;
SendSignal(node->output[0], c);
return;
}
void GateROL(NODE * node) {
SIGNAL a, b, c;
a = NodeReadInput(node, 0);
b = NodeReadInput(node, 1);
c.value = a.value << b.value;
c.state = -1;
SendSignal(node->output[0], c);
return;
}
void GateROR(NODE * node) {
SIGNAL a, b, c;
a = NodeReadInput(node, 0);
b = NodeReadInput(node, 1);
c.value = a.value >> b.value;
c.state = -1;
SendSignal(node->output[0], c);
return;
}
void GateMUX(NODE * node) {
}
#endif
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<time.h>
void main()
{
float Total_HoldingCost[30], Daily_Demand[30], Monthly_Demand[30], Initial_Inventory[30], Final_Inventory[30], Holding_Cost[30], THC;
float PDF[6]= {0.1,0.2,0.2,0.3,0.1,0.1};
float CDF[6]= {0,0,0,0,0,0};
CDF[0]= PDF[0];
int i, j, DAY;
for(i=1; i<sizeof(PDF); i++)
CDF[i]= PDF[i]+CDF[i-1];
int RAND_NO[30];
float RAND_NUM[30];
srand(time(NULL));
printf("\nRandom Numbers\n\n");
for(i=0;i<30;i++){
printf("%3d|",i+1);
}
printf("\n");
for(i=0;i<30;i++){
RAND_NO[i]=rand() % 100;
printf("%3d|",RAND_NO[i]);
}
printf("\n");
Initial_Inventory[0]=3;
Total_HoldingCost[-1]=0;
THC=0;
for(DAY=0; DAY<30; DAY++){
for(j=0; j<sizeof(CDF); j++){
RAND_NUM[DAY]=(float)RAND_NO[DAY]/100;
if((float)RAND_NUM[DAY]<CDF[j]){
Monthly_Demand[DAY]=j;
Daily_Demand[DAY]=(float)j/30;
break;
}
}
Final_Inventory[DAY]=Initial_Inventory[DAY]-Daily_Demand[DAY];
if(Final_Inventory[DAY]>=0){
Holding_Cost[DAY]=Final_Inventory[DAY]/30;
Initial_Inventory[DAY+1]=Final_Inventory[DAY];
}
else{
Holding_Cost[DAY]=0;
Initial_Inventory[DAY+1]=0;
}
Total_HoldingCost[DAY]=Total_HoldingCost[DAY-1]+Holding_Cost[DAY];
THC= THC+Holding_Cost[DAY];
}
printf("\n| %4s | %6s | %6s | %8s | %8s | %8s | %8s | %8s | %8s |\n","#Day","Init Inv","RandNo","RandNum","MonthDem","DailyDem","FinalInv","HoldCost","T H Cost");
for(DAY=0;DAY<30;DAY++)
printf("\n| %4d | %6f | %6d | %f | %f | %f | %f | %f | %f |",DAY+1,Initial_Inventory[DAY],RAND_NO[DAY],RAND_NUM[DAY],Monthly_Demand[DAY],Daily_Demand[DAY],Final_Inventory[DAY],Holding_Cost[DAY],Total_HoldingCost[DAY]);
printf("\nTotal Holding Cost = %f per month",THC);
printf("\nTotal Holding Cost = %f per day",(float)THC/30);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: agalavan <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/12/06 15:00:07 by agalavan #+# #+# */
/* Updated: 2017/12/23 14:33:22 by agalavan ### ########.fr */
/* */
/* ************************************************************************** */
#include "fillit.h"
/*
** This function prints error massage and exit the program
*/
void error_and_exit(void)
{
ft_putstr("error\n");
exit(-1);
}
/*
** Find minimum possible square to satisfy number of figures
*/
void find_square(void)
{
int count;
int res;
t_fig *tmp;
int max_x;
int max_y;
tmp = g_head;
count = lst_count_elem();
res = count * 4;
while (ft_sqrt(res) == 0)
res++;
g_edge = ft_sqrt(res);
move_all_figs_left_up(g_head);
/* In this part we are checking the longest
side of each figure and if one of them longer than
current g_edge value we increase g_edge. */
while (tmp)
{
max_x = find_max_coordinate(tmp->x);
max_y = find_max_coordinate(tmp->y);
if (max_x >= max_y && max_x >= g_edge)
g_edge = max_x + 1;
else if (max_y > max_x && max_y >= g_edge)
g_edge = max_y + 1;
tmp = tmp->next;
}
}
void begin_validation(char *buff)
{
int len;
len = 0;
while (buff[len] != '\0')
len++;
/* Validate amount of figures.
Each figure must have 20 signs + \n between every two figures,
but not after last figure in the file. That is why len + 1 */
if ((len + 1) % 21 != 0)
error_and_exit();
/* continue validation in next function */
parse_buffer(buff);
}
/*
** The program is divided into 3 basic parts.
** First - read from file and validation.
** Second part - solve tetris algirithm.
** Third - print results.
*/
int main(int argc, char **argv)
{
char buff[BUF_SIZE];
int read_bytes;
int fd;
read_bytes = 0;
if (argc != 2)
{
ft_putstr("usage: ./fillit source_file\n");
return (-1);
}
if ((fd = open(argv[1], O_RDONLY, 0)) == -1)
error_and_exit();
/* BEGIN VALIDATION */
ft_bzero(buff, BUF_SIZE);
while ((read_bytes = read(fd, buff, BUF_SIZE)) > 0)
if (read_bytes < 20 || read_bytes > 545)
error_and_exit();
begin_validation(buff);
/* START SOLVING */
find_square();
tetris_solve(g_head);
/* PRINT RESULT */
print_result_map(g_head);
return (0);
}
|
C
|
#include <stdio.h>
int A[10] = { 0,1,3,6,11,17 };
int H[10] = { 0,2,5,1,5,0 };
int airtel(int);
int airtel(int n)
{
int i,k;
int m[7];
int cost=0;
m[0] = 0;
for (i = 1; i < n; i++)
{
m[i] = 999999;
for (k = 0; k < i; k++)
{
cost = m[k] + H[k] + A[i - k];
if (m[i] > cost)
m[i] = cost;
}
}
printf("%d", m[n-1]);
}
int main()
{
int n;
printf("15010994 \n");
scanf("%d", &n);
airtel(n);
}
|
C
|
#include<stdio.h>
int main()
{
int m, n, a, num, i=0;
printf("Enter range in which you want to print Armstrong Numbers: ");
scanf("%d %d", &m, &n);
for(m;m<=n;m++)
{
i=0;
num=m;
while(num)
{
a = num%10;
num /= 10;
i += (a*a*a);
}
if(i==m)
{
printf("%d\n",m);
}
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
main()
{
printf("%5s\n","abcd");
printf("%5s\n","abcdef");
printf("%-5s\n","abc");
printf("%5.2s\n","abcde");
printf("%-5.2s\n","abcde");
getchar();
getchar();
}
|
C
|
/*
* $Id: glob.c,v 1.16 2008-07-27 03:18:38 haley Exp $
*/
/************************************************************************
* *
* Copyright (C) 2000 *
* University Corporation for Atmospheric Research *
* All Rights Reserved *
* *
* The use of this Software is governed by a License Agreement. *
* *
************************************************************************/
/*
* glob.c
*
* Author John Clyne
*
* Date Mon Apr 23 13:07:50 MDT 1990
*
* perform filname expansion on a string using the shell
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <ncarg/c.h>
#include "glob.h"
static int to_child[2],
to_parent[2]; /* pipes for talking to spawned process */
static char ackString[80];
const char Magic[] = "NCARG_GRAPHICS_MAGIC_COOKIE";
const int magicLen = (sizeof(Magic) / sizeof(Magic[0]));
#define SMALL_MALLOC_BLOCK 10
/*
* talkto
* [internal]
*
* set up communictions between invoking process and the desired
* command; stderr of command is sent to /dev/null
* on entry
* **argv : name of command to talk to
* on exit
* to_child[1] : fd for writing to spawned process
* to_parent[0] : fd for reading from spawned process
*/
static void talkto(argv)
char **argv;
{
int pid;
FILE *fp;
if (pipe(to_child) < 0) {
perror((char *) NULL);
exit(1);
}
if (pipe(to_parent) < 0) {
perror((char *) NULL);
exit(1);
}
if ((pid = fork()) == 0) { /* the child process */
fp = fopen("/dev/null", "a");
(void) close(fileno(stdin)); /* close child's stdin */
(void) dup(to_child[0]); /* redirect stdin from pipe*/
(void) close(fileno(stdout)); /* close child's stdout */
(void) dup(to_parent[1]); /* redirect stdout to pipe*/
(void) close(fileno(stderr)); /* close child's stderr */
(void) dup(fileno(fp)); /* redirect stderr to bit-buck*/
(void) close(to_child[0]); /* close the pipes */
(void) close(to_child[1]);
(void) close(to_parent[0]);
(void) close(to_parent[1]);
(void) fclose(fp);
/*
* exec the command to talk to
*/
(void) execvp(argv[0], argv);
perror((char *) NULL); /* shouldn't get here */
exit(1);
}
else if (pid < 0) {
perror((char *) NULL);
(void) exit(1);
}
/* we're the parent */
return;
}
/*
* glob
* [exported]
*
* perform filename expansion on a string. glob allocates memory as
* necessary and returns a pointer to that memory. glob uses the command
* specified by the enviroment variable "SHELL" to do expansion. If
* SHELL is not set glob uses /bin/sh by default.
* on entry
* *string : the string
* on exit
* ***r_argv : a list of files expanded by the shell
* *r_argc : size of r_argv
*/
void glob(string, r_argv, r_argc)
const char *string;
char ***r_argv;
int *r_argc;
{
static short is_init = 0;
static char **argv;
static int argc;
static int args; /* memory alloced to argv */
static char inBuf[4*BUFSIZ];
char outbuf[1024];
char *cptr;
int nbytes;
char *shell_argv[3];
char *t, *s;
*r_argv = NULL;
*r_argc = argc = 0;
/*
* perform one time initialization
*/
if (!is_init) {
/*
* try and find out what shell the user like so we can spawn
* it to parse it to do globbing.
*/
if ((shell_argv[0] = getenv ("SHELL")) == NULL) {
shell_argv[0] = "/bin/sh"; /* default */
}
shell_argv[1] = NULL;
/*
* if using csh then use csh with the fast option, '-f'
*/
/*SUPPRESS 624*/
t = (t = strrchr(shell_argv[0], '/')) ? ++t : shell_argv[0];
if ((strcmp(t, "csh") == 0) || (strcmp(t, "tcsh") == 0)) {
shell_argv[1] = "-f";
shell_argv[2] = NULL;
}
else if (strcmp(t, "ksh") == 0) {
shell_argv[1] = "-p";
shell_argv[2] = NULL;
}
talkto(shell_argv); /* spawn shell to talk to */
is_init = 1;
argv = (char **) malloc(SMALL_MALLOC_BLOCK * sizeof(char **));
if (! argv) {
perror("malloc()");
return;
}
args = SMALL_MALLOC_BLOCK;
sprintf(ackString, "/bin/echo %s\n", Magic);
}
if ((strlen(outbuf) + strlen(string) + 1) >= sizeof(outbuf)) {
(void) fprintf(stderr, "Line too long: %s\n", string);
return;
}
/*
* build command to send to the shell.
*/
(void) strcpy(outbuf, "/bin/echo ");
(void) strcat(outbuf, string);
(void) strcat(outbuf, "\n");
/*
* send "echo whatever" to shell. Also send a \001 so we get an
* ack back. We need that ack in case the string send doen't
* generate a responce to stdout. i.e. a shell error
*/
(void) write(to_child[1], outbuf, strlen(outbuf));
(void) write(to_child[1], ackString, strlen(ackString));
/*
* read in output from shell
*/
nbytes = 0;
while (1) { /* read until receive ack or buffer is full */
cptr = inBuf + nbytes;
nbytes += read(to_parent[0], cptr, sizeof(inBuf) - nbytes);
if ((s = strstr(inBuf, Magic)) || nbytes == sizeof(inBuf)) {
*s = '\0';
break;
}
}
if (nbytes == sizeof(inBuf)) {
inBuf[nbytes-1] = '\0';
}
if (strlen(inBuf) == 0) {
return; /* no match */
}
/*
* replace terminating newline with a null terminator
*/
/*SUPPRESS 624*/
if (s = strchr(inBuf, '\n')) {
*s = '\0';
}
/*
* null terminate and assigne a poiner to each arg in inBuf
*/
cptr = inBuf;
argv[argc++] = cptr; /* point to first arg */
while(*cptr) {
if (isspace(*cptr)) {
*cptr = '\0';
if (argc >= args) { /* enough memory ? */
args += SMALL_MALLOC_BLOCK;
argv = (char **) realloc ((char *) argv,
(unsigned) (args * sizeof (char **)));
}
argv[argc++] = cptr+1;
}
cptr++;
}
*r_argv = argv;
*r_argc = argc;
}
|
C
|
#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include "util.h"
// Returns true if arr1[0..n-1] and arr2[0..m-1]
// contain same elements.
bool arrays_are_equal(uint8_t * p_arr1, uint8_t * p_arr2, uint8_t n, uint8_t m)
{
if (n != m)
return false;
for (uint8_t i = 0; i < n; i++)
if (p_arr1[i] != p_arr2[i])
return false;
return true;
}
bool IPs_are_equal(uint8_t * ip1, uint8_t * ip2)
{
return arrays_are_equal(ip1, ip2, 4, 4);
}
int32_t dict_find_index(dict_t dict, const uint8_t *key) {
for (int32_t i = 0; i < dict->len; i++) {
if (!memcmp((uint8_t *)dict->entry[i].key, (const uint8_t *)key, 6)) {
return i;
}
}
return -1;
}
int32_t dict_find(dict_t dict, const uint8_t *key, int32_t def) {
int32_t idx = dict_find_index(dict, key);
return idx == -1 ? def : dict->entry[idx].value;
}
void dict_add(dict_t dict, const uint8_t *key, int32_t value) {
int32_t idx = dict_find_index(dict, key);
if (idx != -1) {
dict->entry[idx].value = value;
return;
}
if (dict->len == dict->cap) {
dict->cap *= 2;
dict->entry = realloc((void *)dict->entry, dict->cap * sizeof(dict_entry_t));
}
strncpy((uint8_t *)&(dict->entry[dict->len].key[0]), strdup(key), 6);
dict->entry[dict->len].value = value;
dict->len++;
}
dict_t dict_new(void) {
dict_s proto = {0, 10, malloc(10 * sizeof(dict_entry_t))};
dict_t d = malloc(sizeof(dict_s));
*d = proto;
return d;
}
void dict_free(dict_t dict) {
for (int32_t i = 0; i < dict->len; i++) {
free((void *)dict->entry[i].key);
}
free(dict->entry);
free(dict);
}
|
C
|
/*
#include <stdio.h>
#include <stdlib.h>
//ֱӵrand()ɵһԵģһ41 18467 6334Ժÿ41 18467 6334
//ֵһ£ԺɴжõһεݡʱҪʹã
//ķΧΪ0-RAND_MAX,<stdlib>жRAND_MAXֵΪ21474836472^31 - 1--intΧ-2^31+1 - 2^31
int main()
{
int x1 = rand();
int x2 = rand();
int x3 = rand();
printf("%d %d %d ", x1, x2, x3);
return 0;
}
*/
//0-100rand%100
//10-10010+rand%90
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
//һsrand()йءڵrand()ǰsrand()ӣseed
// δsrand(), rand()ڵʱԶΪ1ΪûӣÿӶԶֵͬ1rand()ֵһ
//srand() void srand ((unsigned int) seed);
//ͨgeypid()time(0)ķֵseedtime(0)ĻҪͷļ#include<time.h>
//time(0)صǰUnixʱΪӸʱ1970010100ʱ0000(ʱ1970010108ʱ0000)ڵ
//time(0)%(60)õǰ
//time%(60*60)/60
//time%(60*60*24)/3600ΪʱСʱ (time%(60*60*24)/3600 + 8)%24 תɱʱСʱ
//һ3430 6567 19015, ڶ3564 21268 30550, 3662 16040 9419
int main()
{
srand((unsigned int) time(0)); //ֻ#include<time.h>srand((unsigned int) time(0))ɡ //time(0)ijɳ1ÿһ
int x1 = rand();
int x2 = rand();
int x3 = rand();
printf("%d %d %d", x1, x2, x3);
return 0;
}
|
C
|
/* Project Euler Problem #4 */
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
char
palindrome(char *str) {
int len = strlen(str);
if (len%2 != 0)
return 0;
int i;
for (i=0; i<len/2; i++) {
if (str[i] != str[len-i-1]) {
return 0;
}
}
return 1;
}
int
main()
{
int n = 1000;
int prod;
char str[100];
int pal = 1;
int i, j;
for (i=1; i<n; i++) {
for (j=i; j<n; j++) {
prod = i*j;
sprintf(str, "%d", prod);
if (palindrome(str)) {
if (prod > pal)
pal = prod;
}
}
}
// display result
printf("%d\n", pal);
return 0;
}
|
C
|
int choice,e;
do
{
display menu 1.peek 2.push 3.pop 4.exit
printf("enter your choice");
take input in choice variable
switch(choice){
case 1:
//call peek function
break;
case 2:
//call push function
break;
case 3:
//call pop function
break;
case 4:
//call exit(0) function
break;
}while(1);
return=0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
//孤儿进程:父进程已经退出了 子进程还在运行
//孤儿进程最终会被1号init进程收养
//pstree -p | less
int main(void)
{
pid_t pid = 0;
pid = fork();
//子进程
if (0 == pid)
{
while(1)
{
printf("getppid: %d hello world..\n", getppid());
sleep(1);
}
exit(0);
}
printf("pid = %d\n", getpid());
printf("The parent process if end of life...\n");
return 0;
}
|
C
|
#include<stdio.h>
#include<windows.h>
#include<time.h>
int main()
{
int a[100], N, i, j, temp, num, mid, start, end, even_count = 0, odd_count = 0;
printf("Enter array size: ");
scanf("%d", &N);
printf("Elements: ");
for(i = 0; i < N; i++)
{
scanf("%d", &a[i]);
}
for(i = 0; i < N; i++)
{
for(j = i ; j > 0; j--)
{
if(a[j - 1] > a[j])
{
temp = a[j - 1];
a[j - 1] = a[j];
a[j] = temp;
}
}
}
printf("\nOutput:\nEven: ");
for(i = 0; i < N; i++)
{
if(a[i] % 2 == 0)
{
printf("%d ", a[i]);
even_count++;
}
}
printf("\nOdd: ");
for(i = 0; i < N; i++)
{
if(a[i] % 2 != 0)
{
printf("%d ", a[i]);
odd_count++;
}
}
printf("\n\nEnter the Element you are looking for: ");
scanf("%d", &num);
start = 0;
end = N - 1;
mid = (start + end) / 2;
while(a[mid] != num && start <= end)
{
if(num > a[mid])
{
start = mid + 1;
}
else
{
end = mid - 1;
}
mid = (start + end) / 2;
}
if(a[mid] == num)
{
if(num % 2 == 0)
{
printf("%d found in the even list\n", num);
}
else if(num % 2 != 0)
{
printf("%d found in the odd list\n", num);
}
}
else
{
printf("%d not found\n", num);
}
printf("\nNumber of Elements in the Even list: %d\n", even_count);
printf("\nNumber of Elements in the Odd list: %d\n\n", odd_count);
}
|
C
|
#include "hash_tables.h"
/**
* hash_table_create - create a hash table
* @size: size of the array
*
* Return: pointer to the new array
*/
hash_table_t *hash_table_create(unsigned long int size)
{
hash_table_t *hasht = NULL;
hasht = malloc(sizeof(hash_node_t));
if (!hasht)
return (NULL);
hasht->size = size;
hasht->array = (hash_node_t **) malloc(size * sizeof(hash_node_t *));
if (!hasht->array)
return (NULL);
return (hasht);
}
|
C
|
#include<stdio.h>
int main()
{
int n,k,s=1,i;
scanf("%d %d",&n,&k);
for( i=1;i<=k;i++)
{
s=s*n;
}
printf("%d",s);
return 0;
}
|
C
|
#include "calcul.h"
void addition(int n1[400], int n2[400], int result[400]){
for (short i = 0; i < 200; i = i+1){
int temp = result[399-i];
result[399-i] = (result[399-i] + n1[399-i] + n2[399-i]) % 10;
result[399-(i+1)] = (n1[399-i] + n2[399-i] + temp) / 10;
}
}
void soustraction(int n1[400], int n2[400], int result[400]){
for (short i = 0; i < 200; i = i+1){
int temp = result[399-i];
result[399-i] = (result[399-i] + n1[399-i] + 10 - n2[399-i]) % 10;
if (n1[399-i] - n2[399-i] + temp < 0)
result[399-(i+1)] = -1;
}
}
void multiplication(int n1[400], int n2[400], int result[400]){
for (short i = 0; i < 200; i = i+1){
for (short j = 0; j < 200; j = j+1){
int temp = result[399-j-i];
result[399-j-i] = (result[399-j-i] + n1[399-j] * n2[399-i]) % 10;
result[399-(j+1)-i] = result[399-(j+1)-i] + (temp + n1[399-j] * n2[399-i]) / 10 ;
}
}
}
void division(int n1[400], int n2[400], int result[400]){
int copy_n1[400];
for (short j = 0; j < 400; j = j+1){
copy_n1[j] = n1[j];
}
short size_n1 = size(n1);
for (short i = 399-size_n1+size(n2)+1; i < 400; i = i+1){
int temp1[400] = {0};
if (size(n2) < size_n1){
for (short j = 0; j <= size(n2); j = j+1){
temp1[399-size(n2)+j] = copy_n1[399-size_n1+1+j];
}
}
else {
for (short j = 0; j < 400; j = j+1){
temp1[j] = copy_n1[j];
}
}
while (!negative_difference(temp1, n2)){
int temp[400] = {0};
soustraction(temp1, n2, temp);
for (short j = 0; j < 400; j = j+1){
temp1[j] = temp[j];
temp[j] = 0;
}
result[i] = result[i] + 1;
}
for (short j = 0; j <= size(n2); j = j+1){
copy_n1[399-size_n1+1+j] = temp1[399-size(n2)+j];
}
for (short j = 0; j < 400; j = j+1){
temp1[j] = 0;
}
size_n1 = size_n1 - 1;
}
organize(result);
}
void modulo(int n1[400], int n2[400], int result[400]){
for (short j = 0; j < 400; j = j+1){
result[j] = n1[j];
}
short size_n1 = size(n1);
for (short i = 399-size_n1+size(n2)+1; i < 400; i = i+1){
int temp1[400] = {0};
if (size(n2) < size_n1){
for (short j = 0; j <= size(n2); j = j+1){
temp1[399-size(n2)+j] = result[399-size_n1+1+j];
}
}
else {
for (short j = 0; j < 400; j = j+1){
temp1[j] = result[j];
}
}
while (!negative_difference(temp1, n2)){
int temp[400] = {0};
soustraction(temp1, n2, temp);
for (short j = 0; j < 400; j = j+1){
temp1[j] = temp[j];
temp[j] = 0;
}
}
for (short j = 0; j <= size(n2); j = j+1){
result[399-size_n1+1+j] = temp1[399-size(n2)+j];
}
for (short j = 0; j < 400; j = j+1){
temp1[j] = 0;
}
size_n1 = size_n1 - 1;
}
}
|
C
|
#include <stdio.h>
#include <assert.h>
#include <string.h>
#include "util.h"
#include "errormsg.h"
#include "symbol.h"
#include "absyn.h"
#include "types.h"
#include "helper.h"
#include "env.h"
#include "semant.h"
// TODO: nil handling.
// TODO: break handling.
// TODO: cycle detection. (16)
// TODO: () exp (12,20,43)
/*Lab4: Your implementation of lab4*/
static char str_ty[][12] = {
"ty_record", "ty_nil", "ty_int", "ty_string",
"ty_array", "ty_name", "ty_void"};
//In Lab4, the first argument exp should always be **NULL**.
typedef void* Tr_exp;
struct expty {
Tr_exp exp;
Ty_ty ty;
};
struct expty expTy(Tr_exp exp, Ty_ty ty) {
struct expty e;
e.exp = exp;
e.ty = ty;
return e;
}
// Return the actual type under nameTy,
// except nameTy(name, recordTy) and nameTy(name, arrayTy).
Ty_ty actual_ty(Ty_ty ty) {
Ty_ty t = ty;
while(get_ty_type(t) == Ty_name) {
//printf("***(actual_ty)name ty kind: %s\n", str_ty[t->kind]);
//Ty_ty temp = t->u.name.ty;
Ty_ty temp = get_namety_ty(t);
if (!temp || get_ty_type(temp) == Ty_record || get_ty_type(temp) == Ty_array)
break;
t = temp;
}
return t;
}
// Compare two types.
// For int, string types etc., compare their kind.
// For array and record type (in namety form), directly compare then in pointers.
bool tyEqual(Ty_ty a, Ty_ty b) {
printf("enter here\n");
Ty_ty tya = actual_ty(a);
printf("enter here1\n");
Ty_ty tyb = actual_ty(b);
printf("enter here2\n");
switch(tya->kind) {
case Ty_nil: {
if (tya->kind == tyb->kind)
return TRUE;
// nil, record
if (tyb->kind == Ty_name &&
get_namety_ty(tyb) &&
get_namety_ty(tyb)->kind == Ty_record)
return TRUE;
return FALSE;
}
case Ty_int:
case Ty_string:
case Ty_void: {
if (tya->kind == tyb->kind)
return TRUE;
return FALSE;
}
// use pointers to compare Ty_name(array and record).
case Ty_name: {
printf("enter here3\n");
if (tya == tyb) {
printf("enter here4\n");
return TRUE;
}
printf("enter here5\n");
// (a, NULL) = (c, NULL)
if (!get_namety_ty(tya))
return FALSE;
// record, nil
if (get_namety_ty(tya)->kind == Ty_record && tyb->kind == Ty_nil) {
printf("we should return true;\n");
return TRUE;
}
printf("we should return false;\n");
return FALSE;
}
default:
return FALSE;
}
}
bool isROVar(S_table venv, A_var v) {
if (v->kind == A_simpleVar) {
S_symbol simple = get_simplevar_sym(v);
E_enventry enventry = (E_enventry)S_look(venv, simple);
if (enventry && enventry->kind == E_varEntry && enventry->readonly == 1)
return TRUE;
}
return FALSE;
}
// turn a list of params in func dec to tyList in the params order.
Ty_tyList makeFormalTyList(S_table tenv, A_fieldList params) {
A_fieldList fieldList = params;
Ty_tyList tyList = NULL;
if (fieldList && fieldList->head) {
Ty_ty ty = transTy(tenv, A_NameTy(fieldList->head->pos, fieldList->head->typ));
if (!ty) {
/* error */
return NULL;
}
tyList = Ty_TyList(ty, NULL);
fieldList = fieldList->tail;
}
Ty_tyList temp = tyList;
while (fieldList && fieldList->head) {
Ty_ty ty = transTy(tenv, A_NameTy(fieldList->head->pos, fieldList->head->typ));
if (!ty) {
/* error */
return NULL;
}
temp->tail = Ty_TyList(ty, NULL);
temp = temp->tail;
fieldList = fieldList->tail;
}
return tyList;
}
// turn a A_ty type into Ty_ty type, peel nameTy
Ty_ty transTy(S_table tenv, A_ty a) {
switch(a->kind) {
case A_nameTy: {
/* 1. find this type in tenv
* 2. return the type (iterate until single namety)
*/
printf("enter transTy-nameTy.\n");
//printf("namety's ty name: %s\n", S_name(get_ty_name(a)));
Ty_ty ty = (Ty_ty)S_look(tenv, get_ty_name(a));
//if (ty) printf("***name ty kind: %s\n", str_ty[ty->kind]);
if (!ty) {
/* error message */
EM_error(a->pos, "undefined type %s", S_name(get_ty_name(a)));
return NULL;
}
ty = actual_ty(ty);
//printf("enter here.\n");
switch (ty->kind) {
case Ty_nil: {
ty = Ty_Nil();
break;
}
case Ty_int: {
ty = Ty_Int();
break;
}
case Ty_string: {
ty = Ty_String();
break;
}
case Ty_void: {
ty = Ty_Void();
break;
}
default: ;
}
/* return format:
* (newly created)Ty_nil, Ty_int, Ty_string, Ty_void
* (pointers)Ty_name(name, Ty_record), Ty_name(name, Ty_array)
*/
return ty;
}
case A_recordTy: {
printf("enter transTy-recordTy.\n");
// should place them in the right order.
A_fieldList record = get_ty_record(a);
Ty_fieldList ty_fieldList = NULL;
if (record && record->head) {
A_field field = record->head;
//printf("***%s\n",S_name(field->name));
Ty_ty fieldTy = transTy(tenv, A_NameTy(field->pos, field->typ));
if (!fieldTy) {
/* error */
return Ty_Record(ty_fieldList);
}
Ty_field ty_field = Ty_Field(field->name, fieldTy);
//printf("***ty kind: %s\n", str_ty[ty_field->ty->kind]);
ty_fieldList = Ty_FieldList(ty_field, NULL);
record = record->tail;
}
Ty_fieldList temp = ty_fieldList;
while (record && record->head) {
A_field field = record->head;
//printf("***%s\n",S_name(field->name));
Ty_ty fieldTy = transTy(tenv, A_NameTy(field->pos, field->typ));
if (!fieldTy) {
/* error */
return Ty_Record(ty_fieldList);
}
Ty_field ty_field = Ty_Field(field->name, fieldTy);
temp->tail = Ty_FieldList(ty_field, NULL);
temp = temp->tail;
//temp = temp->tail;
//temp = Ty_FieldList(ty_field, NULL);
//printf("***record field: %s\n", S_name(temp->head->name));
record = record->tail;
}
temp = ty_fieldList;
while (temp) {
//printf("record field: %s\n", S_name(temp->head->name));
temp = temp->tail;
}
return Ty_Record(ty_fieldList);
}
case A_arrayTy: {
printf("enter transTy-arrayTy.\n");
S_symbol array = get_ty_array(a);
return Ty_Array(transTy(tenv, A_NameTy(a->pos, array)));
/* error condition: transTy returns NULL */
}
default: ;
}
}
struct expty transExp(S_table venv, S_table tenv, A_exp a) {
switch(a->kind) {
case A_seqExp: {
printf("enter transExp-seqExp.\n");
A_expList seq = get_seqexp_seq(a);
if (!seq)
return expTy(NULL, Ty_Void());
while (seq && seq->head && seq->tail) {
transExp(venv, tenv, seq->head);
//printf("finish here\n");
seq = seq->tail;
}
// here found a bug.
// TODO: let in expseq end, the expseq can is zero or more exps.
// but the (expseq) have two or more exps.
return transExp(venv, tenv, seq->head);
}
case A_varExp: {
printf("enter transExp-varExp.\n");
return transVar(venv, tenv, a->u.var);
}
case A_nilExp: {
printf("enter transExp-nilExp.\n");
return expTy(NULL, Ty_Nil());
}
case A_intExp: {
printf("enter transExp-intExp.\n");
return expTy(NULL, Ty_Int());
}
case A_stringExp: {
printf("enter transExp-stringExp.\n");
return expTy(NULL, Ty_String());
}
case A_callExp: {
printf("enter transExp-callExp.\n");
// find the label in venv, compare argument types
S_symbol func = get_callexp_func(a);
A_expList args = get_callexp_args(a);
E_enventry enventry = (E_enventry)S_look(venv, func);
if (!enventry || enventry->kind != E_funEntry) {
EM_error(a->pos, "undefined function %s", S_name(func));
return expTy(NULL, Ty_Int());
}
Ty_tyList formals = get_func_tylist(enventry);
Ty_ty result = get_func_res(enventry);
A_expList expList = args;
Ty_tyList tyList = formals;
while (expList && expList->head) {
if (!(tyList && tyList->head)) {
EM_error(expList->head->pos, "too many params in function %s", S_name(func));
return expTy(NULL, Ty_Int());
}
struct expty paramTy = transExp(venv, tenv, expList->head);
if (!tyEqual(paramTy.ty, tyList->head)) {
EM_error(expList->head->pos, "para type mismatch");
return expTy(NULL, Ty_Int());
}
tyList = tyList->tail;
expList = expList->tail;
}
// fewer params
if (tyList) {
EM_error(a->pos, "(transExp-callexp)Function params not match(fewer).");
return expTy(NULL, Ty_Int());
}
return expTy(NULL, result);
}
case A_opExp: {
printf("enter transExp-opExp.\n");
A_oper oper = get_opexp_oper(a);
struct expty left = transExp(venv, tenv, get_opexp_left(a));
struct expty right = transExp(venv, tenv, get_opexp_right(a));
if (oper == A_plusOp || oper == A_minusOp || oper == A_timesOp || oper == A_divideOp) {
if (get_expty_kind(left) != Ty_int)
EM_error(get_opexp_leftpos(a), "integer required");
if (get_expty_kind(right) != Ty_int)
EM_error(get_opexp_rightpos(a), "integer required");
return expTy(NULL, Ty_Int());
}
if (oper == A_ltOp || oper == A_leOp || oper == A_gtOp || oper == A_geOp) {
if (!(get_expty_kind(left) == Ty_int || get_expty_kind(left) == Ty_string)) {
EM_error(get_opexp_leftpos(a), "integer or string required");
}
if (!(get_expty_kind(right) == Ty_int || get_expty_kind(right) == Ty_string)) {
EM_error(get_opexp_rightpos(a), "integer or string required");
}
if (!tyEqual(left.ty, right.ty))
EM_error(get_opexp_rightpos(a), "same type required");
return expTy(NULL, Ty_Int());
//TODO: what will happen when compare between two strings?
}
if (oper == A_eqOp || oper == A_neqOp) {
if (!((get_expty_kind(left) == Ty_int ||
get_expty_kind(left) == Ty_string ||
get_expty_kind(left) == Ty_nil ||
get_expty_kind(left) == Ty_name)
&& tyEqual(left.ty, right.ty))) {
//TODO: in this func, expty in transExp must return types which can be decided equal or not.
// or write another function to do this. This is finally on transVar. Think about when encountering
// record and array type. Better to return a nametype? Or should them all be nametype?
// This also has something to do with typedec..
EM_error(get_opexp_rightpos(a), "same type required");
}
return expTy(NULL, Ty_Int());
}
EM_error(get_opexp_leftpos(a), "(transExp-opexp)type not match");
return expTy(NULL, Ty_Int());
}
case A_recordExp: {
printf("enter transExp-recordExp.\n");
S_symbol typ = get_recordexp_typ(a);
A_efieldList fields = get_recordexp_fields(a);
Ty_ty ty = transTy(tenv, A_NameTy(a->pos, typ));
if (!ty || ty->kind != Ty_name || ((Ty_ty)get_namety_ty(ty))->kind != Ty_record) {
//EM_error(a->pos, "(transExp-recordExp)no such record id");
// (ins) without error twice.
return expTy(NULL, Ty_Nil()); // or nil?? what does nil do?
}
// Ty_ty whatever = (Ty_ty)get_namety_ty(ty);
// printf("is this record type?: %s\n", str_ty[whatever->kind]);
Ty_fieldList record = ((Ty_ty)get_namety_ty(ty))->u.record;
A_efieldList efieldList = fields;
Ty_fieldList fieldList = record;
while (efieldList && efieldList->head) {
// assume they are in the same order..
// but they are not.
if(!(fieldList && fieldList->head)) {
EM_error(a->pos, "(transExp-recordExp)too many params");
return expTy(NULL, Ty_Nil()); // or nil?? what does nil do?
}
//printf("efieldList:%s\n", S_name(efieldList->head->name));
//printf("fieldList:%s\n", S_name(fieldList->head->name));
if (strcmp(S_name(efieldList->head->name), S_name(fieldList->head->name))) {
EM_error(a->pos, "(transExp-recordExp)names not match");
return expTy(NULL, Ty_Nil()); // or nil?? what does nil do?
}
struct expty fieldExpTy = transExp(venv, tenv, efieldList->head->exp);
if (!tyEqual(fieldExpTy.ty, fieldList->head->ty)) {
EM_error(a->pos, "(transExp-recordExp)types not match");
return expTy(NULL, Ty_Nil()); // or nil?? what does nil do?
}
efieldList = efieldList->tail;
fieldList = fieldList->tail;
}
if (fieldList) {
EM_error(a->pos, "(transExp-recordExp)fewer params");
return expTy(NULL, Ty_Nil()); // or nil?? what does nil do?
}
printf("finish recordExp\n");
return expTy(NULL, ty); // return nameTy
}
case A_arrayExp: {
printf("enter transExp-arrayExp.\n");
S_symbol typ = get_arrayexp_typ(a);
A_exp size = get_arrayexp_size(a);
A_exp init = get_arrayexp_init(a);
Ty_ty ty = transTy(tenv, A_NameTy(a->pos, typ));
if (!ty || ty->kind != Ty_name || ((Ty_ty)get_namety_ty(ty))->kind != Ty_array) {
EM_error(a->pos, "(transExp-arrayexp)no such array id");
return expTy(NULL, Ty_Nil());// TODO
}
struct expty sizety = transExp(venv, tenv, size);
struct expty initty = transExp(venv, tenv, init);
if (sizety.ty->kind != Ty_int) {
EM_error(size->pos, "(transExp-arrayexp)size type wrong");
return expTy(NULL, Ty_Nil());// TODO
}
if (!tyEqual(initty.ty, ((Ty_ty)get_namety_ty(ty))->u.array)) {
EM_error(init->pos, "type mismatch");
return expTy(NULL, Ty_Nil());// TODO
}
return expTy(NULL, ty);
}
case A_assignExp: {
printf("enter transExp-assignExp.\n");
A_var var = get_assexp_var(a);
A_exp exp = get_assexp_exp(a);
struct expty lhsTy = transVar(venv, tenv, var);
if (isROVar(venv, var)) {
// hacking. In loop body, the var cannot be assigned.
EM_error(a->pos, "loop variable can't be assigned");
return expTy(NULL, Ty_Void());
}
//printf("finish transExp-assignExp: transVar.\n");
struct expty rhsTy = transExp(venv, tenv, exp);
if (!tyEqual(lhsTy.ty, rhsTy.ty))
EM_error(a->pos, "unmatched assign exp");
return expTy(NULL, Ty_Void());
}
case A_ifExp: {
printf("enter transExp-ifExp.\n");
A_exp test = get_ifexp_test(a);
A_exp then = get_ifexp_then(a);
A_exp elsee = get_ifexp_else(a);
struct expty testTy = transExp(venv, tenv, test);
if (testTy.ty->kind != Ty_int) {
EM_error(test->pos, "(transExp-ifexp)test condition return wrong type.");
return expTy(NULL, Ty_Void());
}
struct expty thenTy = transExp(venv, tenv, then);
// printf("thenTy: %s\n", str_ty[thenTy.ty->kind]);
// Ty_ty whatever = get_namety_ty(thenTy.ty);
// if (whatever) printf("this is not null.\n");
// printf("under thenTy: %s\n", str_ty[whatever->kind]);
if (!elsee) {
if (thenTy.ty->kind != Ty_void)
EM_error(then->pos, "if-then exp's body must produce no value");
return expTy(NULL, Ty_Void());
}
struct expty elseTy = transExp(venv, tenv, elsee);
printf("elseTy: %s\n", str_ty[elseTy.ty->kind]);
if (!tyEqual(thenTy.ty, elseTy.ty)) {
EM_error(elsee->pos, "then exp and else exp type mismatch");
return expTy(NULL, Ty_Void());
}
return expTy(NULL, thenTy.ty);
}
case A_whileExp: {
printf("enter transExp-whileExp.\n");
A_exp test = get_whileexp_test(a);
A_exp body = get_whileexp_body(a);
struct expty testTy = transExp(venv, tenv, test);
struct expty bodyTy = transExp(venv, tenv, body);
if (testTy.ty->kind != Ty_int)
EM_error(test->pos, "(transExp-whileexp)test condition return wrong type.");
if (bodyTy.ty->kind != Ty_void)
EM_error(body->pos, "while body must produce no value");
return expTy(NULL, Ty_Void());
}
case A_forExp: {
printf("enter transExp-forExp.\n");
S_symbol var = get_forexp_var(a);
A_exp lo = get_forexp_lo(a);
A_exp hi = get_forexp_hi(a);
A_exp body = get_forexp_body(a);
struct expty loTy = transExp(venv, tenv, lo);
struct expty hiTy = transExp(venv, tenv, hi);
if (loTy.ty->kind != Ty_int)
EM_error(lo->pos, "for exp's range type is not integer");
//return expTy(NULL, Ty_Void()); continue running !
if (hiTy.ty->kind != Ty_int)
EM_error(hi->pos, "for exp's range type is not integer");
//return expTy(NULL, Ty_Void()); continue running !
S_beginScope(venv);
S_enter(venv, var, E_ROVarEntry(loTy.ty));
struct expty bodyTy = transExp(venv, tenv, body);
if (bodyTy.ty->kind != Ty_void)
EM_error(body->pos, "(transExp-forExp)body must have no return values.");
S_endScope(venv);
return expTy(NULL, Ty_Void());
}
case A_breakExp: {
printf("enter transExp-breakExp.\n");
//TODO??how to handle this??
return expTy(NULL, Ty_Void());
}
case A_letExp: {
printf("enter transExp-letExp.\n");
A_decList decList = get_letexp_decs(a);
A_exp body = get_letexp_body(a);
S_beginScope(venv);
S_beginScope(tenv);
//printf("enter here!\n");
while (decList && decList -> head) {
transDec(venv, tenv, decList->head);
decList = decList->tail;
}
//printf("after transDec!\n");
struct expty bodyTy = transExp(venv, tenv, body);
S_endScope(tenv);
S_endScope(venv);
return bodyTy;
}
default: printf("no match kind\n");//return expTy(NULL, Ty_Void());
}
}
void transDec(S_table venv, S_table tenv, A_dec d) {
switch (d->kind) {
case A_varDec: {
printf("enter transDec-varDec.\n");
A_exp init = get_vardec_init(d);
S_symbol var = get_vardec_var(d);
S_symbol typ = get_vardec_typ(d);
struct expty initTy = transExp(venv, tenv, init);
//printf("here\n");
//printf("%s\n", str_ty[initTy.ty->kind]);
if (strcmp(S_name(typ), "")) {
Ty_ty ty = transTy(tenv, A_NameTy(d->pos, typ));
// TODO: this part also requires transTy and transExp
// results the same in record and array type.
if (!ty) {
return;
}
if (!tyEqual(initTy.ty, ty)) {
EM_error(init->pos, "type mismatch");
//return; do not return directly
}
} else {
//printf("here\n");
if (initTy.ty->kind == Ty_nil)
EM_error(init->pos, "init should not be nil without type specified");
//printf("here\n");
}
S_enter(venv, var, E_VarEntry(initTy.ty));
break;
}
case A_typeDec: {
printf("enter transDec-typeDec.\n");
char* decHistory[32]; // TODO: not big enough though
int cnt = 0;
A_nametyList nametyList = get_typedec_list(d);
// enter all dec of name type
while (nametyList && nametyList->head) {
int i;
for (i = 0; i < cnt; i++) {
// equivalent to history entry
if (!strcmp(S_name(nametyList->head->name), decHistory[i])) {
EM_error(d->pos, "two types have the same name");
return;
}
}
S_enter(tenv, nametyList->head->name, Ty_Name(nametyList->head->name, NULL));
decHistory[cnt] = S_name(nametyList->head->name);
cnt ++;
//printf("nametyList->head->name: %s\n", S_name(nametyList->head->name));
nametyList = nametyList->tail;
}
printf("after first part of typedec!\n");
nametyList = get_typedec_list(d);
while (nametyList && nametyList->head) {
A_namety namety = nametyList->head;
printf("looking for namety->name: %s\n", S_name(namety->name));
Ty_ty ty = (Ty_ty)S_look(tenv, namety->name);
printf("lhsTy: %s\n", str_ty[ty->kind]);
printf("under lhsTy: %s\n", S_name(ty->u.name.sym));
Ty_ty whatever = get_namety_ty(ty);
if (!whatever) printf("NOne\n");
if (get_ty_type(ty) != Ty_name)
EM_error(namety->ty->pos, "(transDec-typeDec)error.");
Ty_ty typeTy = transTy(tenv, namety->ty);
// printf("rhsTy: %s\n", str_ty[typeTy->kind]);
// printf("under rhsTy: %s\n", S_name(typeTy->u.name.sym));
// Ty_ty whatever2 = get_namety_ty(typeTy);
// if (!whatever2) printf("NOne\n");
if (!typeTy) {
/* error */
return;
}
if (tyEqual(typeTy, ty)) {
EM_error(namety->ty->pos, "illegal type cycle");
return;
}
printf("enterhere\n");
ty->u.name.ty = typeTy;
// translate A_ty to Ty_ty.
// TODO: how? translate to which step? if we have type a = b, type c = a,
// should we return for c nameTy(a) or nameTy(b)?
// Then one day if we compare a's type with c's type, can we safely return OK?
nametyList = nametyList->tail;
}
// TODO: cycle detection.
//printf("after typedec!\n");
break;
}
case A_functionDec: {
/* 1. enter all function in venv with params and return type (if have)
* 2. for each func, begin scope
* 3. enter params into venv
* 4. transExp, check whether return type is equivalent
* 5. endscope
*/
printf("enter transDec-functionDec.\n");
char* decHistory[32]; // TODO: not big enough though
int cnt = 0;
A_fundecList fundecList = get_funcdec_list(d);
while (fundecList && fundecList->head) {
A_fundec fundec = fundecList->head;
int i;
for (i = 0; i < cnt; i++) {
// equivalent to history entry
if (!strcmp(S_name(fundec->name), decHistory[i])) {
EM_error(d->pos, "two functions have the same name");
return;
}
}
Ty_ty resultTy = Ty_Void();
//printf("resultTy: %s\n", S_name(fundec->result));
if (strcmp(S_name(fundec->result), "")) {
resultTy = transTy(tenv, A_NameTy(fundec->pos, fundec->result));
if (!resultTy)
EM_error(fundec->pos, "(transDec-func)result type not found.");
}
Ty_tyList formalTys = makeFormalTyList(tenv, fundec->params);
//printf("enter venv of fundec: %s\n", S_name(fundec->name));
S_enter(venv, fundec->name, E_FunEntry(formalTys, resultTy));
decHistory[cnt] = S_name(fundec->name);
cnt ++;
fundecList = fundecList->tail;
}
fundecList = get_funcdec_list(d);
while (fundecList && fundecList->head) {
A_fundec fundec = fundecList->head;
//printf("dec ing in fundec: %s\n", S_name(fundec->name));
E_enventry enventry = (E_enventry)S_look(venv, fundec->name);
if (!enventry || enventry->kind != E_funEntry)
{/* error message */printf("I can't find the func in the dec process!\n");}
Ty_tyList formalTys = get_func_tylist(enventry);
Ty_ty resultTy = get_func_res(enventry);
S_beginScope(venv);
{
A_fieldList l;
Ty_tyList t;
for (l = fundec->params, t = formalTys; l; l = l->tail, t = t->tail) {
S_enter(venv, l->head->name, E_VarEntry(t->head));
}
}
struct expty bodyTy = transExp(venv, tenv, fundec->body);
if (!tyEqual(bodyTy.ty, resultTy)) {
//printf("bodyTy: %s, resultTy: %s\n", str_ty[bodyTy.ty->kind], str_ty[resultTy->kind]);
if (resultTy->kind == Ty_void)
EM_error(fundec->pos, "procedure returns value");
else
EM_error(fundec->pos, "(transDec-func)result type is incorrect.");
}
S_endScope(venv);
fundecList = fundecList->tail;
}
break;
}
default: ;
}
}
// actual ty of var
struct expty transVar(S_table venv, S_table tenv, A_var v) {
switch(v->kind) {
case A_simpleVar: {
printf("enter transVar-simpleVar.\n");
S_symbol simple = get_simplevar_sym(v);
E_enventry enventry = (E_enventry)S_look(venv, simple);
if (enventry && enventry->kind == E_varEntry) {
Ty_ty temp = get_varentry_type(enventry); ////
//printf("%s\n", str_ty[temp->kind]);
//printf("here\n");
return expTy(NULL, actual_ty(get_varentry_type(enventry)));
} else {
EM_error(v->pos, "undefined variable %s", S_name(get_simplevar_sym(v)));
return expTy(NULL, Ty_Int());
}
}
case A_fieldVar: {
printf("enter transVar-fieldVar.\n");
A_var var = get_fieldvar_var(v);
struct expty fieldVarTy = transVar(venv, tenv, var);
if (fieldVarTy.ty->kind != Ty_name){
/* error */;
EM_error(v->pos, "not a record type");
return expTy(NULL, Ty_Nil());
}
Ty_ty ty = get_namety_ty(fieldVarTy.ty);
if (ty->kind != Ty_record) {
/* error */;
EM_error(v->pos, "not a record type");
return expTy(NULL, Ty_Nil());
}
S_symbol sym = get_fieldvar_sym(v);
Ty_fieldList fieldList = ty->u.record;
while (fieldList && fieldList->head) {
Ty_field field = fieldList->head;
if (field->name == sym) // TODO: is this right?
return expTy(NULL, actual_ty(field->ty));
fieldList = fieldList->tail;
}
EM_error(v->pos, "field %s doesn't exist", S_name(sym));
return expTy(NULL, Ty_Int());
// TODO: what should I return for rec1.nam := "asd"?
}
case A_subscriptVar: {
printf("enter transVar-subscriptVar.\n");
//TODO: shall we detect overflow exception?
A_var var = get_subvar_var(v);
struct expty subscriptVarTy = transVar(venv, tenv, var);
if (subscriptVarTy.ty->kind != Ty_name) {
/* error */;
EM_error(v->pos, "array type required");
return expTy(NULL, Ty_Nil());
}
Ty_ty ty = get_namety_ty(subscriptVarTy.ty);
if (ty->kind != Ty_array) {
/* error */;
EM_error(v->pos, "array type required");
return expTy(NULL, Ty_Nil());
}
return expTy(NULL, actual_ty(get_ty_array(ty)));
}
default: ;
}
}
void SEM_transProg(A_exp exp) {
S_table tenv = E_base_tenv();
S_table venv = E_base_venv();
transExp(venv, tenv, exp);
}
|
C
|
// C program to generate random numbers
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include<time.h>
// Driver program
int main(void)
{
// This program will create different sequence of
// random numbers on every program run
// Use current time as seed for random generator
srand(time(0));
//srand(10);
const int LEN = 10;
int arr[LEN];
memset(arr, 0, LEN*sizeof(arr[0]));
int i;
for(i = 0; i<50000; i++) {
//printf(" %d ", rand());
arr[rand()%LEN]++;
}
printf("\n");
int j;
for(j = 0; j < LEN; j++) {
printf(" %d ", arr[j]);
}
printf("\n");
return 0;
}
|
C
|
#include <stdio.h>
/*m row,n columns*/
int a[4][5] = {
{1,2,3,4,5},
{6,7,8,9,10},
{11,12,13,14,15},
{16,17,18,19,20},
//{21,22,23,24,25}
};
int showMatrix(int m,int n);
int main(int argc, char *argv[]) {
showMatrix(4,5);
}
int showMatrix(int m,int n) {
int i=0,j=0,p=0,q=0;
p=m-1;
q=n-1;
for(;p&&q;p--,q--,i++,j++) {
while (j<q) {
printf(" %d_[%d %d]",a[i][j],i,j);
j++;
}
while (i<p) {
printf(" %d_[%d %d]",a[i][j],i,j);
i++;
}
while (j>m-p-1) {
printf(" %d_[%d %d]",a[i][j],i,j);
j--;
}
while (i>n-q-1) {
printf(" %d_[%d %d]",a[i][j],i,j);
i--;
}
if(i==p||j==q)printf(" %d_[%d %d]",a[i][j],i,j);
printf("\n------p=%d q=%d i=%d j=%d------\n",p,q,i,j);
}
}
|
C
|
#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/kobject.h>
#include <linux/string.h>
#include <linux/sysfs.h>
#include <linux/fs.h>
#include <linux/uaccess.h>
#include <asm/io.h>
#define DEV_MAJOR 0 /* 动态申请主设备号 */
#define DEV_NAME "red_led" /*led设备名字 */
/* GPIO虚拟地址指针 */
static void __iomem *IMX6U_CCM_CCGR1;
static void __iomem *SW_MUX_GPIO1_IO04;
static void __iomem *SW_PAD_GPIO1_IO04;
static void __iomem *GPIO1_DR;
static void __iomem *GPIO1_GDIR;
static int foo;
static ssize_t foo_show(struct kobject *kobj, struct kobj_attribute *attr,
char *buf)
{
return sprintf(buf, "%d\n", foo);
}
static ssize_t foo_store(struct kobject *kobj, struct kobj_attribute *attr,
const char *buf, size_t count)
{
int ret;
ret = kstrtoint(buf, 10, &foo);
if (ret < 0)
return ret;
return count;
}
static struct kobj_attribute foo_attribute =
__ATTR(foo, 0664, foo_show, foo_store);
static ssize_t led_show(struct kobject *kobj, struct kobj_attribute *attr,
char *buf)
{
int var;
if (strcmp(attr->attr.name, "led") == 0)
var =123;
return sprintf(buf, "%d\n", var);
}
static ssize_t led_store(struct kobject *kobj, struct kobj_attribute *attr,
const char *buf, size_t count)
{
if (strcmp(attr->attr.name, "led") == 0){
if(!memcmp(buf,"on",2)) {
iowrite32(0 << 4, GPIO1_DR);
} else if(!memcmp(buf,"off",3)) {
iowrite32(1 << 4, GPIO1_DR);
}
}
return count;
}
static struct kobj_attribute led_attribute =
__ATTR(led, 0664, led_show, led_store);
static struct attribute *attrs[] = {
&foo_attribute.attr,
&led_attribute.attr,
NULL, /* need to NULL terminate the list of attributes */
};
static struct attribute_group attr_group = {
.attrs = attrs,
};
static struct kobject *led_kobj;
static int __init led_init(void)
{
int retval;
/* GPIO相关寄存器映射 */
IMX6U_CCM_CCGR1 = ioremap(0x20c406c, 4);
SW_MUX_GPIO1_IO04 = ioremap(0x20e006c, 4);
SW_PAD_GPIO1_IO04 = ioremap(0x20e02f8, 4);
GPIO1_GDIR = ioremap(0x0209c004, 4);
GPIO1_DR = ioremap(0x0209c000, 4);
/* 使能GPIO1时钟 */
iowrite32(0xffffffff, IMX6U_CCM_CCGR1);
/* 设置GPIO1_IO04复用为普通GPIO*/
iowrite32(5, SW_MUX_GPIO1_IO04);
/*设置GPIO属性*/
iowrite32(0x10B0, SW_PAD_GPIO1_IO04);
/* 设置GPIO1_IO04为输出功能 */
iowrite32(1 << 4, GPIO1_GDIR);
/* LED输出高电平 */
iowrite32(1<< 4, GPIO1_DR);
/* 创建一个kobject对象*/
led_kobj = kobject_create_and_add("led_kobject", NULL);
if (!led_kobj)
return -ENOMEM;
/* 为kobject设置属性文件*/
retval = sysfs_create_group(led_kobj, &attr_group);
if (retval)
kobject_put(led_kobj);
return retval;
return 0;
}
static void __exit led_exit(void)
{
/* 取消映射 */
iounmap(IMX6U_CCM_CCGR1);
iounmap(SW_MUX_GPIO1_IO04);
iounmap(SW_PAD_GPIO1_IO04);
iounmap(GPIO1_DR);
iounmap(GPIO1_GDIR);
/* 注销字符设备驱动 */
kobject_put(led_kobj);
}
module_init(led_init);
module_exit(led_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("embedfire ");
MODULE_DESCRIPTION("led_module");
MODULE_ALIAS("led_module");
|
C
|
#include<stdio.h>
int main()
{
int num,a,multi=0,i;
printf("\n enter the number:");
scanf("%d",&num);
a=num;
for(i=num;multi=1;i++)
{
if(i%10==0)
{
multi=1;
break;
}
}
if(multi==1)
{
printf("\n the nearest multiple of %d is %d ",a,i);
return 0;
}
}
|
C
|
//
// quicksort.h
// Quick sort is based on the divide-and-conquer approach based on the idea of choosing one element as a pivot element and partitioning the array around it such that:
// Left side of pivot contains all the elements that are less than the pivot element Right side contains all elements greater than the pivot
// It reduces the space complexity and removes the use of the auxiliary array
//
// Created by Anoja Rajalakshmi on 9/6/17.
// Copyright © 2017 Anoja Rajalakshmi. All rights reserved.
//
#ifndef quicksort_h
#define quicksort_h
/* Utitlity function to sort array A[] */
void quickSort(char *, int, int);
int partition(char *, int, int);
void swap(char *, char *);
#endif /* quicksort_h */
|
C
|
//ʤΪ16ϴʳbug,
// ܵ20
//
#pragma warning(disable:4996)
#include <stdio.h>
#include<Windows.h>
#include<time.h>
#include<conio.h>
#include<stdlib.h>
int head, tail;
int score = 0;
int gamespeed = 300;//Ϸٶ
int win = 16;//ʤ
int change_model(char qi[22][22], int zb[2][20], char dir) {
int x = 0, y = 0;
if (dir == 72) {
//up
x = zb[0][head] - 1;
y = zb[1][head];
}
else if (dir == 80) {
//down
x = zb[0][head] + 1;
y = zb[1][head];
}
else if (dir == 75) {
//left
x = zb[0][head];
y = zb[1][head] - 1;
}
else if (dir == 77) {
x = zb[0][head];
y = zb[1][head] + 1;
}
//ײ///////////////////////////////////////
if (qi[x][y] == 'o') {
give_food(qi);
if (tail == 0) {
tail = 19;
}
else { tail = (tail - 1) % 20; }
score++;
}
if (qi[x][y] == '-' || qi[x][y] == '*' || qi[x][y] == '|') return 0;
/////////////////////////////////////////
qi[zb[0][tail]][zb[1][tail]] = ' ';
tail = (tail + 1) % 20;
qi[zb[0][head]][zb[1][head]] = '*';
head = (head + 1) % 20;
zb[0][head] = x;
zb[1][head] = y;
qi[zb[0][head]][zb[1][head]] = '#';
return 1;
}
int give_food(char qi[22][22]) {
srand(time(0));
int x = rand() % 20 + 1;
int y = rand() % 20 + 1;
if (qi[x][y] = ' ') {
qi[x][y] = 'o';
}
else {
give_food(qi);
}
return 0;
}
int main() {
//ʼ//////////////////////////////////////
int tcsZB[2][20];
for (int i = 0;i <= 3;++i) {
tcsZB[0][i] = 1;//y
tcsZB[1][i] = i + 1;//x
}
head = 3;
tail = 0;
char tcsQipan[22][22];
for (int i = 1;i <= 20;++i) {
for (int j = 1;j <= 20;++j) {
tcsQipan[i][j] = ' ';
}
}
for (int i = 0;i <= 21;++i) {
tcsQipan[0][i] = '-';
tcsQipan[21][i] = '-';
}
for (int i = 1;i <= 20;++i) {
tcsQipan[i][0] = '|';
tcsQipan[i][21] = '|';
}
for (int i = 1;i <= 3;++i) {
tcsQipan[1][i] = '*';
}
tcsQipan[1][4] = '#';
give_food(tcsQipan);
///////////////////////////////////////////////////////////////
int direction = 77;
while (direction != 'Q') {
system("cls");
for (int i = 0;i <= 21;++i) {
for (int j = 0;j <= 21;++j) {
printf("%c", tcsQipan[i][j]);
}
printf("\n");
}
printf("your score is:%d", score);
if (score == win) {
direction = 'Q';
printf("\n\nCongratulations!\nYou win the game!\n");
}
///////////////////////////////////////////////////////////////
int timeover = 1;
long start = clock();
while (!kbhit() && (timeover = clock() - start<= gamespeed));
if (timeover) {
getch();
direction = getch();
}
/*else {
direction = direction;
}*/
if (!change_model(tcsQipan, tcsZB, direction)) {
direction = 'Q';
}
}
system("pause");
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
struct Student{
int number;
int moral;
int intelligence;
};
void Sort(struct Student arr[], int length, int high);
int Compare(struct Student s1, struct Student s2, int high);
int CompareInSameLvl(struct Student s1, struct Student s2);
void Heapify(struct Student arr[], int length, int pos, int high);
void Swap(struct Student* s1, struct Student* s2);
int main()
{
int n, low, high, i;
scanf("%d%d%d", &n, &low, &high);
struct Student arr[n];
for(i = 0; i < n; i++){
scanf("%d%d%d", &arr[i].number, &arr[i].moral, &arr[i].intelligence);
}
//Ԥ¼ȡƵβ
for(i = 0; i < n;){
if(arr[i].moral < low || arr[i].intelligence < low){
Swap(&arr[i], &arr[n -1]);
n--;
} else {
i++;
}
}
Sort(arr, n, high);
printf("%d\n", n);
for(i = 0; i < n; i++){
printf("%d %d %d\n", arr[i].number, arr[i].moral, arr[i].intelligence);
}
return 0;
}
//ǵܵݷΧ 10^5 ö
void Sort(struct Student arr[], int length, int high){
int i;
for(i = length - 1; i >= 0; i--){
Heapify(arr, length, i, high);
}
while(length > 1){
Swap(&arr[0], &arr[length - 1]);
length--;
Heapify(arr, length, 0, high);
}
return;
}
void Heapify(struct Student arr[], int length, int pos, int high){
int child = 2*pos + 1;
if(child < length){
if(child + 1 < length && Compare(arr[child], arr[child +1], high) > 0){
child++;
}
if(Compare(arr[pos], arr[child], high) > 0){
Swap(&arr[pos], &arr[child]);
}
Heapify(arr, length, child, high);
}
return;
}
int Compare(struct Student s1, struct Student s2, int high){
if(s1.moral >= high && s1.intelligence >= high){
if(s2.moral >= high && s2.intelligence >= high){
return CompareInSameLvl(s1, s2);
} else {
return 1;
}
} else if (s1.moral >= high) {
if(s2.moral >= high && s2.intelligence >= high) {
return -1;
} else if (s2.moral >= high) {
return CompareInSameLvl(s1, s2);
} else {
return 1;
}
} else if (s1.moral >= s1.intelligence) {
if(s2.moral >= high){
return -1;
} else if (s2.moral >= s2.intelligence){
return CompareInSameLvl(s1, s2);
} else {
return 1;
}
} else {
if(s2.moral >= high || s2.moral >= s2.intelligence){
return -1;
} else {
return CompareInSameLvl(s1, s2);
}
}
}
int CompareInSameLvl(struct Student s1, struct Student s2){
if((s1.intelligence + s1.moral) > (s2.intelligence + s2.moral)){
return 1;
} else if ((s1.intelligence + s1.moral) < (s2.intelligence + s2.moral)){
return -1;
} else {
if(s1.moral > s2.moral){
return 1;
} else if(s1.moral < s2.moral){
return -1;
} else {
if(s1.number <= s2.number){
return 1;
} else {
return -1;
}
}
}
}
void Swap(struct Student* s1, struct Student* s2){
if(s1->intelligence == s2->intelligence && s1->number == s2->number
&& s1->moral == s2->moral){
return;
}
struct Student temp = *s1;
*s1 = *s2;
*s2 = temp;
return;
}
|
C
|
#include "../m_pd.h"
#include <math.h>
#include <string.h>
#include "ringmods.h"
#ifdef NT
#pragma warning( disable : 4244 )
#pragma warning( disable : 4305 )
#endif
#define PI 3.141592653589793
#define TWOPI 6.283185307179586
/* ------------------------ vdpll~ ----------------------------- */
/*
phase locked loop object.
several options for phase detection circuit:
-ideal ring modulator (four-quadrant multiplier)
-analog-style ringmod, taken from mutable instruments' Warps
-digital-style ringmod, taken from mutable instruments' Warps
-XOR (1-bit ring modulator)
ARGUMENTS:
-first argument sets internal frequency. Defaults to 1000 Hz.
-second argument sets k. Defaults to 0.
-third agument sets cutoff frequency. Defaults to 1 Hz.
-fourth argument sets phase detector type. Defaults to ideal.
INLET:
-signal in is the control signal to lock phase to
-control-rate data determines internal frequency
OUTLETS:
-the internal oscillator
-the internal phase (useful for controlling arbitrary wavetable)
TODO:
-try other filter implementations
*/
static t_class *vdpll_tilde_class;
typedef struct _vdpll_tilde
{
t_object x_obj; /* obligatory header */
t_float intern_freq, intern_freq_target, cutoff, cutOverFs, cutOverFs_target, k, k_target;
float fs_delta;
float last_lop_out, last_out;
double phase;
enum phase_detector_type {
ideal, //0
analog, //1
digital, //2
xor //3
} pdType;
t_outlet*phasor_out;
} t_vdpll_tilde;
// onepole lowpass
// REQUIRES MANUAL INPUT OF LAST OUTPUT.
// PRE-COMPUTE 1/FS * CUTOFF
float lop(float in, float out_z1, float cutOverFs)
{
float x = exp(-TWOPI * cutOverFs);
float a0 = 1.f - x;
float b1 = -x;
float out = a0 * in - b1 * out_z1;
return out;
}
static void vdpll_tilde_post(t_vdpll_tilde *x)
{
post("cutOverFs is %f", x->cutOverFs);
post("k is %f", x->k);
post("intern_freq is %f", x->intern_freq);
switch (x->pdType)
{
case 0: post("phase detection method is ideal ring modulator (multiplier)");
break;
case 1: post("phase detection method is analog ring modulator");
break;
case 2: post("phase detection method is digital ring modulator");
break;
case 3: post("phase detection method is xor ring modulator");
break;
}
}
static void vdpll_tilde_set_freq(t_vdpll_tilde *x, t_floatarg freq)
{
x->intern_freq_target = freq;
//post("intern_freq_target is %f", x->intern_freq_target);
}
static void vdpll_tilde_set_k(t_vdpll_tilde *x, t_floatarg k)
{
if (k > 10000.f)
{
k = 10000.f;
post("k maxed out");
}
x->k_target = (float)k;
//post("k_target is %f", x->k_target);
}
static void vdpll_tilde_set_cutoff(t_vdpll_tilde *x, t_floatarg cutoff)
{
cutoff = cutoff * (cutoff > 0.f);
x->cutoff = cutoff;
x->cutOverFs_target = (float)cutoff * (float)x->fs_delta;
}
static void vdpll_tilde_set_phase_detector(t_vdpll_tilde *x, t_float type)
{
if ((type >= 0) && (type < 4))
x->pdType = (int)(floor(type));
else
post("enter 0 for 'ideal', 1 for 'analog', 2 for 'digital', or 3 for 'xor'");
}
static t_int *vdpll_tilde_perform(t_int *w)
{
// x,
// input vector
// main output vector
// phase output vector
// blocksize
t_vdpll_tilde *x = (t_vdpll_tilde *)(w[1]);
t_float *master = (t_float *)(w[2]);
t_float *vco_out = (t_float *)(w[3]);
t_float *phase_out = (t_float *)(w[4]);
int n = (int)(w[5]);
float modulatorOut;
float phase = x->phase;
// copy from struct only once per block
float last_lop_out = x->last_lop_out;
float fs_delta = x->fs_delta;
while (n--)
{
if (x->intern_freq != x->intern_freq_target)
x->intern_freq += (x->intern_freq_target - x->intern_freq);
if (x->k != x->k_target)
x->k += (x->k_target - x->k);
if (x->cutOverFs != x->cutOverFs_target)
x->cutOverFs += (x->cutOverFs_target - x->cutOverFs);
switch (x->pdType)
{
case 0: // ideal ringmod
{
modulatorOut = x->last_out * *master;
break;
}
case 1:
{
modulatorOut = analog_ringmod(x->last_out, *master, 0.f);
break;
}
case 2:
{
modulatorOut = digital_ringmod(x->last_out, *master, 0.f);
break;
}
case 3:
{
float onebit_master = (*master > 0.f) ? 1.f : -1.f;
float onebit_intern = (x->last_out > 0.f) ? 1.f : -1.f;
// XOR
modulatorOut = (onebit_intern != onebit_master) * 2.f - 1.f;
break;
}
}
// filter the modulator output to isolate DC component.
last_lop_out = lop(modulatorOut, last_lop_out, x->cutOverFs);
float phaseinc = (x->intern_freq * x->fs_delta) + (last_lop_out * x->k * x->intern_freq * x->fs_delta);
phaseinc = phaseinc < 0.5f ? phaseinc : 0.5f;
phaseinc = phaseinc > -0.5f ? phaseinc : -0.5f;
phase += phaseinc;
// wrap between 0 and 1
while (phase >= 1.f)
phase -= 1.f;
while (phase < 0)
phase += 1.f;
float f = *(master++);
x->last_out = cos(phase * TWOPI);
*vco_out++ = x->last_out;
*phase_out++ = phase;
}
x->last_lop_out = last_lop_out;
x->phase = phase;
return (w+6);
}
/* called to start DSP. Here we call Pd back to add our perform
routine to a linear callback list which Pd in turn calls to grind
out the samples. */
static void vdpll_tilde_dsp(t_vdpll_tilde *x, t_signal **sp)
{
x->fs_delta = 1.0f / sp[0]->s_sr;
x->cutOverFs = x->cutoff * x->fs_delta;
// RESET FILTER STATES TOO
x->last_lop_out = 0.f;
x->last_out = 0.f;
dsp_add(vdpll_tilde_perform,
5, // number of items
x,
sp[0]->s_vec, // input vector
sp[1]->s_vec, // output vector
sp[2]->s_vec, // output vector
sp[0]->s_n); // blocksize
}
static void *vdpll_tilde_new(t_float freq, t_float k, t_float cut, t_float type)
{
t_vdpll_tilde *x = (t_vdpll_tilde *)pd_new(vdpll_tilde_class);
outlet_new(&x->x_obj, gensym("signal"));
x->phasor_out = outlet_new(&x->x_obj, &s_signal);
x->intern_freq = 1000.f;
x->k = 1000.f;
x->cutoff = 1;
x->pdType = ideal;
//============================================================
x->intern_freq= freq;
x->intern_freq_target = freq;
x->k = k;
x->k_target = k;
x->cutoff = cut;
x->cutOverFs = cut / 44100.f;
x->cutOverFs_target = cut / 44100.f;
if ((type >= 0) && (type < 4))
x->pdType = (int)(floor(type));
else
post("enter 0 for 'ideal', 1 for 'analog', 2 for 'digital', or 3 for 'xor'");
//============================================================
return (x);
}
/* this routine, which must have exactly this name (with the "~" replaced
by "_tilde) is called when the code is first loaded, and tells Pd how
to build the "class". */
void vdpll_tilde_setup(void)
{
vdpll_tilde_class = class_new(gensym("vdpll~"), (t_newmethod)vdpll_tilde_new, 0,
sizeof(t_vdpll_tilde), 0, A_DEFFLOAT, A_DEFFLOAT, A_DEFFLOAT, A_DEFFLOAT, 0);
class_addbang(vdpll_tilde_class, (t_method)vdpll_tilde_post);
class_addmethod(vdpll_tilde_class, (t_method)vdpll_tilde_set_freq, gensym("frequency"), A_FLOAT, 0);
class_addmethod(vdpll_tilde_class, (t_method)vdpll_tilde_set_k, gensym("k"), A_FLOAT, 0);
class_addmethod(vdpll_tilde_class, (t_method)vdpll_tilde_set_cutoff, gensym("cutoff"), A_FLOAT, 0);
class_addmethod(vdpll_tilde_class, (t_method)vdpll_tilde_set_phase_detector, gensym("detector"), A_FLOAT, 0);
/* this is magic to declare that the leftmost, "main" inlet
takes signals; other signal inlets are done differently... */
CLASS_MAINSIGNALIN(vdpll_tilde_class, t_vdpll_tilde, intern_freq);
/* here we tell Pd about the "dsp" method, which is called back
when DSP is turned on. */
class_addmethod(vdpll_tilde_class, (t_method)vdpll_tilde_dsp, gensym("dsp"), 0);
class_sethelpsymbol(vdpll_tilde_class, gensym("vdpll~"));
}
|
C
|
#ifndef QUEUE_H
#define QUEUE_H
typedef struct Node
{
int jobNumber;
float time;
struct Node* next;
}Node;
typedef struct Queue
{
struct Node* front;
struct Node* last;
unsigned int size;
}Queue;
void initQueue(Queue* queue);
float front(Queue* queue);
float last(Queue* queue);
void EnQueue(Queue* queue, int jobNumber, float time);
Node* DeQueue(Queue* queue);
#endif // QUEUE_H
|
C
|
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
int main(int argc, char const *argv[])
{
if (argc < 2)
{
printf("Digite na forma: %s <n><número de usuários>\n",argv[0] );
return 1;
}
setuid(0);
char buf[100];
sprintf(buf, "bash questao08.sh %s", argv[1]);
system(buf);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
void handler(int num) {
int status;
pid_t pid = waitpid(-1, &status, WNOHANG);
if (WIFEXITED(status)){
printf("child pid %d, exit with code: %d \n", pid, WEXITSTATUS(status));
}
}
int main() {
int child_pid;
int pid;
signal(SIGCHLD, handler);
if (pid = fork()) {
// father
child_pid = pid;
printf("I am father, child_pid = %d \n", child_pid);
//父进程不用等待,做自己的事情吧~
for (int i = 0; i < 10; i++) {
printf("Do parent things.\n");
sleep(1);
}
exit(0);
} else {
// child
printf("I am child \n");
sleep(2);
exit(0);
}
printf("exit \n");
return 0;
}
|
C
|
/**************************************************************************/
/*!
@file wma_u16.c
@author Nguyen Quang Huy, Nguyen Thien Tin
@brief A simple moving average filter using uint16_t values
@code
// Declare a data buffer 8 values wide
uint16_t wma_buffer[8];
uint8_t wma_weight[8] = {8, 8, 16, 16, 32, 32, 128, 255};
// Now declare the filter with the window size and a buffer pointer
wma_u16_t wma = { .k = 0,
.size = 8,
.avg = 0,
.weight = wma_weight,
.buffer = wma_buffer };
// Initialise the moving average filter
if (wma_u16_init(&wma))
{
printf("Something failed during filter init!\n");
}
// Add some values
wma_u16_add(&wma, 10);
wma_u16_add(&wma, 20);
wma_u16_add(&wma, 30);
wma_u16_add(&wma, 35);
wma_u16_add(&wma, 11);
wma_u16_add(&wma, 35);
wma_u16_add(&wma, 30);
wma_u16_add(&wma, 20); // We should have an avg value starting here
wma_u16_add(&wma, 3);
wma_u16_add(&wma, 10);
printf("WINDOW SIZE : %d\n", wma.size);
printf("TOTAL SAMPLES : %d\n", wma.k);
printf("CURRENT AVG : %d\n", wma.avg);
printf("\n");
@endcode
@section LICENSE
Software License Agreement (BSD License)
Copyright (c) 2013, K. Townsend (microBuilder.eu)
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holders nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**************************************************************************/
#include "wma_u16.h"
/**************************************************************************/
/*!
@brief Initialises the wma_u16_t instance
@param[in] wma
Pointer to the wma_u16_t instance that includes the
window size, a pointer to the data buffer,
the current average (the output value), etc.
*/
/**************************************************************************/
err_t wma_u16_init ( wma_u16_t *wma )
{
/* Check if the window size is valid (!= 0 and is a power of 2) */
if (0 == wma->size) return ERROR_UNEXPECTEDVALUE;
wma->avg = 0;
wma->k = 0;
wma->sum_weight = 0;
for (uint16_t i = 0; i < wma->size; i++)
{
wma->sum_weight += wma->weight[i];
}
return ERROR_NONE;
}
/**************************************************************************/
/*!
@brief Adds a new value to the wma_u16_t instances
@param[in] wma
Pointer to the wma_u16_t instances
@param[in] x
Value to insert
*/
/**************************************************************************/
void wma_u16_add(wma_u16_t *wma, uint16_t x)
{
uint16_t *pSource = wma->buffer + wma->k % wma->size;
/* Add new value into the data buffer of the filter */
*pSource = x;
/* Increase the total samples processed */
wma->k++;
/* Wait for 'window-size' worth of samples before averaging */
if (wma->k < wma->size)
return;
/* Recalculate the total value over the entire buffer */
uint32_t total = 0;
uint16_t current_pos = wma->k % wma->size;
for (uint16_t i = 0; i < wma->size; i++)
{
total += wma->buffer[(i + current_pos) % wma->size] * wma->weight[i];
}
/* Update the current average value */
wma->avg = (uint16_t)(total / wma->sum_weight);
}
|
C
|
/*
THIS FUNCTION TESTS OPEN FILE, PRINTING THE BUFFER AFTER READING!
I'M USING /FILE2.TXT BECAUSE IT HAS MORE THAN ONE CLUSTER, TURNING THE EXAMPLE MORE INTERESTING, BECAUSE IT SHOWS THE
CASE IN WHICH WE START FROM THE MIDDLE OF A CLUSTER AND CONTINUE IN THE NEXT ONE
YOU CAN TEST OTHER FILES FROM THE HD CHANGIN THE CHAR *FILE CONTENT =)
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../include/aux.h"
#include "../include/t2fs.h"
#include "../include/utils.h"
int main(){
structures_init(); //just because I'm using the partitionInfo variable before the first call for the T2FS library
printf("FIRST I AM ALLOCATING A REALLY LARGE BUFFER (10*CLUSTER SIZE)\n");
char *buffer = (char *)malloc(sizeof(char)*(SECTOR_SIZE*partitionInfo->SectorsPerCluster)*10);
char *file = "file2.txt\0";
printf("NOW I WILL OPEN %s\n", file);
int handle = open2(file);
if(handle == -1){
printf("PROBLEM OPENING THE FILE :(\n DID YOU CHANGED THE .DAT FILE?\n");
}else{
printf("\nNOW I WILL START THE READINGS\n\n");
int position = 0;
printf(".\n\nASKING TO READ %08x BYTES FROM POSITION %08x\n", 30, position);
int size = read2(handle, buffer, 30);
printf("NUMBER OF BYTES READ: %08x\n", size);
printf("NEW HANDLE POSITION: %08x\n", OPEN_FILES[handle].currentPointer);
printf("content inside buffer:\n%s\n", buffer);
position = (SECTOR_SIZE*partitionInfo->SectorsPerCluster+1);
printf(".\n\nASKING TO READ %08x BYTES FROM POSITION %08x\n", 430, position);
seek2(handle, position);
size = read2(handle, buffer, 430);
printf("NUMBER OF BYTES READ: %08x\n", size);
printf("NEW HANDLE POSITION: %08x\n", OPEN_FILES[handle].currentPointer);
printf("content inside buffer:\n%s\n", buffer);
position = 0;
printf(".\n\nASKING TO READ %08x BYTES FROM POSITION %08x\n", 1025, position);
seek2(handle, 0);
size = read2(handle, buffer, 1025);
printf("NUMBER OF BYTES READ: %08x\n", size);
printf("NEW HANDLE POSITION: %08x\n", OPEN_FILES[handle].currentPointer);
printf("content inside buffer:\n%s\n", buffer);
printf(".\n\nASKING TO READ %08x BYTES FROM POSITION %08x\n", OPEN_FILES[handle].record->bytesFileSize, position);
seek2(handle, 0);
size = read2(handle, buffer, OPEN_FILES[handle].record->bytesFileSize);
printf("NUMBER OF BYTES READ: %08x\n", size);
printf("NEW HANDLE POSITION: %08x\n", OPEN_FILES[handle].currentPointer);
printf("content inside buffer:\n%s\n", buffer);
printf(".\n\nASKING TO READ %08x BYTES FROM POSITION 0\n", OPEN_FILES[handle].record->bytesFileSize*10);
seek2(handle, 0);
size = read2(handle, buffer, OPEN_FILES[handle].record->bytesFileSize*10);
printf("NUMBER OF BYTES READ: %08x\n", size);
printf("NEW HANDLE POSITION: %08x\n", OPEN_FILES[handle].currentPointer);
printf("content inside buffer:\n%s\n", buffer);
//printf_directory(ROOT, 10);
/*seek2(handle, -1);
read2(handle, buffer, 1025);*/
}
return 0;
}
|
C
|
/*
* linkedlist.c
*
* Copyright (c) 2016-2019 Tim <and-joy@qq.com>
* All rights reserved.
*/
#include <stdlib.h>
#include <string.h>
#define AWE_LOG_TAG "linkedlist"
#include "awe/log.h"
#include "awe/atomic.h"
#include "awe/linkedlist.h"
static awe_linked_obj* linked_obj_create(awe_object *obj){
awe_linked_obj *e = awe_mallocz(sizeof(awe_linked_obj));
e->_object = obj;
return e;
}
static inline void linked_obj_free(awe_linked_obj *obj){
awe_free(obj);
}
awe_status_t awe_linkedlist_init(awe_linkedlist *list, awe_object_autorelease_proc *proc){
INIT_LIST_HEAD(&list->_linkedhead);
list->_release_proc = proc;
list->_size = 0;
return AWE_OK;
}
static inline void linkedlist_addtolist(awe_linkedlist *list, awe_linked_obj *obj){
list_add_tail(&obj->_head, &list->_linkedhead);
++list->_size;
}
static inline awe_object* linkedlist_rmfromlist(awe_linkedlist *list, awe_linked_obj *obj){
list_del(&obj->_head);
--list->_size;
awe_object *o = obj->_object;
linked_obj_free(obj);
return o;
}
static inline void linkedlist_delfromlist(awe_linkedlist *list, awe_linked_obj *obj){
list_del(&obj->_head);
--list->_size;
list->_release_proc(&obj->_object);
linked_obj_free(obj);
}
awe_status_t awe_linkedlist_add(awe_linkedlist *list, awe_object *obj){
awe_linked_obj *o = linked_obj_create(obj);
atomic_fetch_add(&obj->_refs, 1);
linkedlist_addtolist(list, o);
return AWE_OK;
}
awe_object* awe_linkedlist_removeFirst(awe_linkedlist *list){
if(list_empty(&list->_linkedhead)){
return NULL;
}
awe_linked_obj *obj = list_entry(list->_linkedhead.next, awe_linked_obj, _head);
return linkedlist_rmfromlist(list, obj/*, false*/);
}
awe_object* awe_linkedlist_remove(awe_linkedlist *list,
bool (*equals)(awe_object *e, void* context), void* context){
awe_linked_obj *obj = NULL;
struct list_head *pos = NULL;
struct list_head *tmp = NULL;
list_for_each_safe(pos, tmp, &list->_linkedhead)
{
obj = list_entry(pos, awe_linked_obj, _head);
if(equals(obj->_object, context)){
return linkedlist_rmfromlist(list, obj/*, false*/);
}
}
return NULL;
}
awe_status_t awe_linkedlist_del(awe_linkedlist *list, awe_object *obj){
awe_linked_obj *o = NULL;
struct list_head *pos = NULL;
struct list_head *tmp = NULL;
list_for_each_safe(pos, tmp, &list->_linkedhead)
{
o = list_entry(pos, awe_linked_obj, _head);
if(o->_object == obj){
linkedlist_delfromlist(list, o/*, true*/);
return AWE_OK;
}
}
return -1;
}
awe_status_t awe_linkedlist_del2(awe_linkedlist *list, struct list_head *pos){
awe_linked_obj *obj = list_entry(pos, awe_linked_obj, _head);
linkedlist_delfromlist(list, obj/*, true*/);
return AWE_OK;
}
awe_status_t awe_linkedlist_del3(awe_linkedlist *list,
bool (*equals)(awe_object *e, void* context), void* context){
awe_linked_obj *obj = NULL;
struct list_head *pos = NULL;
struct list_head *tmp = NULL;
list_for_each_safe(pos, tmp, &list->_linkedhead)
{
obj = list_entry(pos, awe_linked_obj, _head);
if(equals(obj->_object, context)){
linkedlist_delfromlist(list, obj/*, true*/);
return AWE_OK;
}
}
return -1;
}
bool awe_linkedlist_contains(awe_linkedlist *list, awe_object *obj){
awe_linked_obj *o = NULL;
struct list_head *pos = NULL;
list_for_each(pos, &list->_linkedhead)
{
o = list_entry(pos, awe_linked_obj, _head);
if(o->_object == obj){
return true;
}
}
return false;
}
void awe_linkedlist_clear(awe_linkedlist *list){
awe_linked_obj *obj = NULL;
struct list_head *pos = NULL;
struct list_head *tmp = NULL;
list_for_each_safe(pos, tmp, &list->_linkedhead)
{
obj = list_entry(pos, awe_linked_obj, _head);
linkedlist_delfromlist(list, obj/*, true*/);
}
list->_size = 0;
}
int32_t awe_linkedlist_size(awe_linkedlist *list){
return list->_size;
}
awe_object* awe_linkedlist_getFirst(awe_linkedlist *list){
if(list_empty(&list->_linkedhead)){
return NULL;
}
awe_linked_obj *obj = list_entry(list->_linkedhead.next, awe_linked_obj, _head);
return obj->_object;
}
awe_object* awe_linkedlist_getLast(awe_linkedlist *list){
if(list_empty(&list->_linkedhead)){
return NULL;
}
awe_linked_obj *obj = list_entry(list->_linkedhead.prev, awe_linked_obj, _head);
return obj->_object;
}
awe_object* awe_linkedlist_get(awe_linkedlist *list,
bool (*equals)(awe_object *e, void* context), void* context){
awe_linked_obj *obj = NULL;
struct list_head *pos = NULL;
struct list_head *tmp = NULL;
list_for_each_safe(pos, tmp, &list->_linkedhead)
{
obj = list_entry(pos, awe_linked_obj, _head);
if(equals(obj->_object, context)){
return obj->_object;
}
}
return NULL;
}
awe_object* awe_linkedlist_getByIndex(awe_linkedlist *list, int index){
struct list_head *pos = NULL;
int i = 0;
list_for_each(pos, &list->_linkedhead){
if(i++ == index){
return list_entry(pos, awe_linked_obj, _head)->_object;
}
}
return NULL;
}
void awe_linkedlist_forEach(awe_linkedlist *list,
bool (*callback)(struct list_head *pos, awe_object *e, void* context),
void* context){
awe_linked_obj *obj = NULL;
struct list_head *pos = NULL;
struct list_head *tmp = NULL;
list_for_each_safe(pos, tmp, &list->_linkedhead)
{
obj = list_entry(pos, awe_linked_obj, _head);
if(!callback(pos, obj->_object, context)){
return;
}
}
}
bool linkedlist_item_equals(awe_object *obj, void* context){
return obj == (awe_object*)context;
}
|
C
|
//
// Point.h
// AnyViewer
//
// Created by Aomei on 2021/9/9.
//
#ifndef Point_h
#define Point_h
struct CPoint
{
CPoint() : x(0), y(0) {}
CPoint(int x_, int y_) : x(x_), y(y_) {}
inline void Clear() { x = 0; y = 0; }
inline void setPoint(int x_, int y_) { x = x_; y = y_; }
inline void move(int deltaX, int deltaY) { x += deltaX; y += deltaY; }
bool IsEqualTo(const CPoint *other) const { return x == other->x &&
y == other->y; }
int x;
int y;
};
#endif /* Point_h */
|
C
|
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
sig_atomic_t sigusr1_count = 0;
sig_atomic_t sigusr2_count = 0;
void handler1(int signal_number)
{
++sigusr1_count;
}
void handler2(int signal_number)
{
++sigusr2_count;
}
int main()
{
struct sigaction sa1;
struct sigaction sa2;
int count = 0;
printf("This is sigaction\n");
memset(&sa1, 0, sizeof(sa1));
memset(&sa2, 0, sizeof(sa2));
sa1.sa_handler = &handler1;
sa2.sa_handler = &handler2;
sigaction(SIGUSR1, &sa1, NULL);
sigaction(SIGUSR2, &sa2, NULL);
while(count < 10)
{
sleep(1);
count++;
}
printf("SIGUSR1 was raised %d times\n", sigusr1_count);
printf("SIGUSR2 was raised %d times\n", sigusr2_count);
return 0;
}
|
C
|
/**
*--------------------------------------------------------------------\n
* HSLU T&A Hochschule Luzern Technik+Architektur \n
*--------------------------------------------------------------------\n
*
* \brief C Template for the MC Car
* \file
* \author Christian Jost, christian.jost@hslu.ch
* \date 12.09.2014
*
* \b Language: Ansi-C \n\n
* \b Target: MC-Car \n
*
* \par Description:
*
* $Id: main.c 904 2014-09-12 10:58:43Z chj-hslu $
*--------------------------------------------------------------------
*/
#include "platform.h" /* include peripheral declarations */
void initPorts(void)
{
// bitwise
PTFDD_PTFDD0 = 1; // set pin 0 port F = OUT (LED B FL)
PTFDD_PTFDD1 = 1; // set pin 1 port F = OUT (LED R FL)
PTCDD_PTCDD4 = 1; // set pin 4 port C = OUT (LED G FL)
/* same with bytemask
PTFDD = PTFDD | 0x01; // set pin 0 port F = OUT (LED B FL)
PTFDD = PTFDD | 0x02; // set pin 1 port F = OUT (LED R FL)
PTCDD = PTCDD | 0x0F; // set pin 4 port C = OUT (LED G FL)
*/
}
void set_B_FL(void)
{
// bitwise
PTFD_PTFD0 = 0; // set pin 0 port F = ON
PTFD_PTFD1 = 1; // set pin 1 port F = OFF
PTCD_PTCD4 = 1; // set pin 4 port C = OFF
/* same with bytemask
PTFD = PTFD & 0xFE; // set pin 0 port F = ON
PTFD = PTFD | 0x02; // set pin 1 port F = OFF
PTCD = PTCD | 0x0F; // set pin 4 port C = OFF
*/
}
void main(void)
{
initPorts();
set_B_FL();
EnableInterrupts; // enable interrupts
for(;;)
{
__RESET_WATCHDOG(); // feeds the dog
}
}
|
C
|
//
// bit_1.h
// Test2019
//
// Created by Denys Risukhin on 2/2/20.
// Copyright © 2020 DenysRisukhin. All rights reserved.
//
#ifndef bit_1_h
#define bit_1_h
#pragma mark - 1_1
0110 + 0010 = 1000
0011 * 0101 = 1111
0011 + 0010 = 0101
0011 * 0011 = 1001
0110 - 0011 = 0011
1101 >> 2 = 0011
1000 - 0110 = 0010
1101 ^ 0101 = 1000
0110 + 0110 = 1100
// 0110 + 0110 = 0110 * 2 - что эквивалентно смещению 0110 влево на 1
0100 * 0011 = 1100
// 0100 = 4 поэтому можно умножить 0011 на 4
// что эквивалентно сдвигу в лево на 2 бита
// тоесть 0011 сдвигает влево на 2 бита и получаем 1100
1101 ^ (~1101) = 1111
// ^ для бита и его ~ всегда 1
// поэтому a^(~a) всегда дает последовательность 1-иц
1011 & (~0 << 2) = 1000
// ~0 - это последовательность 1-иц
// ~0 << 2 - это последовательность 1-иц за которыми идут 00
// & полученного числа с другим числом сбрасывает 2 правых бита // этого числа
#pragma mark - 1_2
// сущ закономерность соответствия степенией 2-ки и 2-го представления числа
2^0 = 0000 0001
2^1 = 0000 0010
// используем |
(0) 0000 0000 |(2^5) 0010 0000 = 0010 0000
(32) 0010 0000 |(2^7) 1000 0000 = 1010 0000
#pragma mark - 1_3
// используем xor(исключающее или) с маской
// 1 в маске изменит бит на противоположные в независимости от предыдущего состояния
// 0 не меняет бит независимо от предыдущего состояния
101 11101 ^ 111 00000 = 010 11101
#endif /* bit_1_h */
|
C
|
#include "porteiro.h"
/**
* ATENÇÃO: Você pode adicionar novas funções com PUBLIC para serem usadas por
* outros arquivos e adicionar a assinatura da função no .h referente.
*/
/*============================================================================*
* Definição das variáveis globais (publicas ou privadas) *
*============================================================================*/
PRIVATE int jogadores_saindo;
PRIVATE sem_t catraca;
PRIVATE sem_t checklist;
PRIVATE pthread_mutex_t porta;
PRIVATE jogador_t * jogador_saindo;
/*============================================================================*
* porteiro_checklist() *
*============================================================================*/
/**
* @brief Jogador notifica termino ao porteiro.
*/
PUBLIC void porteiro_checklist(jogador_t * jogador)
{
jogador->status = JOGADOR_SAINDO;
pthread_mutex_lock(&porta);
jogadores_saindo++;
pthread_mutex_unlock(&porta);
sem_wait(&catraca);
jogador_saindo = jogador;
sem_post(&checklist);
}
/*============================================================================*
* verifica_checklist() *
*============================================================================*/
/**
* @brief Verifica se existem jogadores que saíram e
* que precisam desalocar os seus recursos.
*/
PRIVATE void verifica_checklist(void)
{
pthread_mutex_lock(&porta);
while (jogadores_saindo > 0)
{
pthread_mutex_unlock(&porta);
/* Espera jogador assinar o checklist. */
sem_wait(&checklist);
/* Verfica que é um jogador válido. */
assert(jogador_saindo);
/* Jogadores não podem fazer checklist se não terminaram. */
assert(jogador_saindo->status == JOGADOR_SAINDO);
/* Espera jogador terminar. */
pthread_join(jogador_saindo->tid, NULL);
/* Limpa jogador. */
jogador_cleanup(jogador_saindo);
/* Libera memória do jogador. */
free(jogador_saindo);
/* Limpa variável global. */
jogador_saindo = NULL;
/* Conta jogador que saiu. */
sim->jogadores_destruidos++;
/* Libera catraca. */
sem_post(&catraca);
pthread_mutex_lock(&porta);
/* Anota saída do jogador. */
jogadores_saindo--;
}
pthread_mutex_unlock(&porta);
}
/*============================================================================*
* Responsabilidades do Porteiro. *
*============================================================================*/
/**
* @brief Operações do Porteiro.
*/
PUBLIC void * porteiro_fn(void * arg)
{
int tamanho_grupo;
int total_jogadores;
jogador_t * jogador;
plog("[porteiro] Iniciou!\n");
total_jogadores = 2 * params->jogadores_por_equipe * params->partidas_max;
while (total_jogadores > 0)
{
tamanho_grupo = aleatorio(params->grupo_min, params->grupo_max);
plog("[porteiro] Gerou um grupo de %d jogadores\n", tamanho_grupo);
/* Criar jogadores do grupo. */
for (int i = 0; i < tamanho_grupo && total_jogadores > 0; ++i, --total_jogadores)
{
jogador = (jogador_t *) malloc(sizeof(jogador_t));
jogador_setup(jogador, sim->jogadores_criados++);
pthread_create(&jogador->tid, NULL, jogador_fn, (void *) jogador);
}
/* Dorme um pouco. */
msleep(aleatorio(params->delay_min, 2 * params->delay_max));
/* Verifica se algum jogador já saiu. */
verifica_checklist();
}
/* Espera todos os jogadores saírem. */
while (sim->jogadores_criados > sim->jogadores_destruidos)
verifica_checklist();
assert(sim->jogadores_criados == sim->jogadores_destruidos);
return (NULL);
}
/*============================================================================*
* porteiro_setup() *
*============================================================================*/
/**
* @brief Configura o porteiro.
*/
PUBLIC void porteiro_setup(void)
{
jogadores_saindo = 0;
jogador_saindo = NULL;
sem_init(&checklist, 0, 0);
sem_init(&catraca, 0, 1);
pthread_mutex_init(&porta, NULL);
}
/*============================================================================*
* porteiro_cleanup() *
*============================================================================*/
/**
* @brief Limpa porteiro.
*/
PUBLIC void porteiro_cleanup(void)
{
sem_destroy(&checklist);
sem_destroy(&catraca);
pthread_mutex_destroy(&porta);
}
|
C
|
#include <stdio.h>
#include <string.h> // necess'ario para strcmp
int main(void)
{
char str1[4] = "abc";
char str2[4] = "abc";
char str3[15] = "Curso de C";
char str4[15] = "Curso de Java";
int retorno;
int retorno2;
retorno = strcmp(str1, str2); // gera um valor inteiro, 0, valor positivo ou valor negativo
retorno2 = strncmp(str3,str4,10);
printf("Retorno = %d \n", retorno);
printf("Retorno2 = %d \n", retorno2);
return 0;
}
|
C
|
/* Anotações Next Level Week:
- Pilares do metodo: Foco, Prática e Grupo
-TypeScript: javascript com "super poderes", permite incluir tipagens no código, algo que facilita reconhecer
o formato das variáveis, argumentos de funções que eu esteja usando.
OBS.: pesquise intelliSense
- usa inferência de tipos, o que indica que na maior parte dos casos o TS reconhece o tipo de dado que estou usando.
- pode diminuir a produtividade no começo
- usar TS NÃO significa transformar o código JS em JAVA ou C#
- TS é bastante usado sim.
- TS é baseado em JS, um não substitui o outro.
- Node só entende JS
Aula 1:
- criando o server: crie a pasta server e usando o terminal digite: npm init -y (o y evita de perguntar as infos do server)
- instalação express, que lida com rotas
- instalação npm install @types/express -D(dependencia de desenvolvimento, que só é usada enquanto estiver desenvolvendo)
(a definição de tipos do express não será mais necessária quando a aplicação entrar em produção)
- instalação npm install ts-node: node para typescript
- instalação npm install typescript -D
- execução do script: npx ts-node <caminho do server>
- execução do npx tsc(typescript) --init: cria o arquivo de configurações do TS, que define quais features do TS eu desejo usar
- instalação npm install ts-node-dev -D (para que cada alteração no código não necessite uma interrupção e ativação do server)
- inclusão do comando npx ts-node-dev src/server.ts no package.json na parte de scripts(não precisa incluir o npx)
== use npm run <nome_script> para rodar o script
- React = biblioteca(ou até framework, por vezes) para construção de interfaces,
que é usada para construção de SPAs(single page applications),
o elimina a necessidade de refresh da página toda, e permite
incluir somente o que for necessário a pagina.
> dividido em react, reactJS, react native;
> nele, TUDO fica dentro do JavaScript
> faz live reload. A cada alteração no código a página sofre um refresh
> fornece:
> maior organização do código por componentização da aplicação(retorna componentes para ela que podem ser elementos HTML).
> divisão de responsabilidades: back end fica com a regra de négocio e o front com a interface
> uma API, múltiplos clientes
- criação do projeto em react com template para TS: npx create-react-app web --template=typescript
Aula 2:
- instalação npm install knex(para o banco de dados)
knex:
- cuidado com a ordem das tabelas contidas na pasta migrations,
porque nao posso criar a tabela 02 sem antes ter a 00 e 01.
- para usar/testar as tabelas criadas use o knexfile:
- npx knex --knexfile knexfile.ts migrate:latest
- instale a extensão sqlite no vs code digite crtl+shift+p e digite sqlite e selecione SQLite: Open Database
- seeds: servem para popular as bases de dados com dados iniciais
- criação da pasta seeds e adição do arquivo create_items.ts;
- npx knex --knexfile knexfile.ts seed:run
- CORS: define quais urls/endereços externos tem acesso a minha aplicação
- instalação npm install cors
- para resolver a questao de tipos com cors: npm install @types/cors -D
- acesse o unsplash para pegar uma imagem com o tema market
- caso precise fazer uma query:
- clique com o botão direito em uma tabela e selecione new query e depois no arquivo que abrir use:
DELETE FROM point_items;
DELETE FROM points;
- ctrl+shift+p : selecione run query
Aula 3:
- limpeza dos arquivos
- React pode ser usado para fazer quase qualquer tipo de interface
- React é feito a partir do JS, então tudo que é mostrado/montado na tela é feito atraves do JS
- o index.tsx é o primeiro arquivo carregado pelo React
- Na maioria das vezes o conteudo do projeto está todo dentro da única div do index.html
- exemplo de uso do emmet no vs code:
digite: div#app>ul>li*5 e uma div com id=app e uma lista com 5 elementos será criada
- JSX: possibilita escrever HTML dentro do JS ou TS
- arquivos .jsx ou .tsx contem tanto html quanto js ou ts
-* COMPONENTIZAÇÃO: ato de separar a aplicação em partes/blocos menores reutilizáveis e replicáveis
- Criação de componentes no react: arquivo Header.tsx
- Propriedades no react: infos que vao dentro dos componentes
- Estados: informações mantidas pelo proprio componente
- Imutabilidade:
- variavel de estado não pode ser alterada diretamente.
o que pode ser feito é criar um novo estado com as informações que eu quero
- gera melhorias de performance da aplicação
- instalação npm install react-icons
- instalação npm install react-router-dom
- instalação npm install @types/react-router-dom -D (durante a produção tudo é convertido para JS, que nao tem tipagem)
- para os mapas será usado o leaflet que é uma biblioteca opensource de mapas interativos que usa JS
- instalação npm install react-leaflet
- instalação npm install leaflet
- instalação npm install axios ==> faz as requisições a api
- opcionais:
- instalação extensão react dev tool: reconhece os sites que usam react
- instalação extensão wapplyzer
- fonte fira code (para simbolos no vs code):
- executar powershell como admin e digitar chocolatey install firacode-ttf
- ctrl+shift+p -> preferencias e acrescente:
"editor.fontFamily": "Fira Code",
"editor.fontLigatures": true,
- pesquise typescript react cheat sheet ==> principais formas de integrar typescript com react
- criar uma página que mostra que o cadastro foi bem sucedido: FEITO
Aula 4:
*/
|
C
|
// Globals
int gbPrintPrimes = false;
// BEGIN OMP
int gnThreadsMaximum = 0 ;
int gnThreadsActive = 0 ; // 0 = auto detect; > 0 manual # of threads
// END OMP
int parse_args( const int nArg, const char *aArg[] )
{
int iArg = 1;
for( iArg = 1; iArg < nArg; iArg++ )
{
const char *pArg = aArg[ iArg ];
if (pArg[0] == '-' )
{
#if defined(_OPENMP)
if (pArg[1] == 'j')
{
if (pArg[2])
{
printf( "Syntax for threads is:\n-j #\n" );
exit( 0 );
}
iArg++;
if (iArg > nArg)
{
printf( "Invalid # of threads to use.\n" );
exit( 0 );
}
gnThreadsActive = atoi( aArg[ iArg ] );
if (gnThreadsActive < 0)
gnThreadsActive = 0;
if (gnThreadsActive > gnThreadsMaximum)
gnThreadsActive = gnThreadsMaximum;
}
else
#endif
if( (strcmp( pArg, "-help" ) == 0)
|| (strcmp( pArg,"--help" ) == 0)
|| (strcmp( pArg,"-?" ) == 0))
{
printf(
"Syntax: [options] [max]\n"
"Find primes between 0 and max. (Default is 10000000)\n"
"\n"
"Options:\n"
" -help Display command line arguments\n"
#if defined(_OPENMP)
" -j # Use # threads. (Default is %d threads.)\n"
#endif
" -table Print table of primes. (Default is OFF.)\n"
#if defined(_OPENMP)
, gnThreadsMaximum
#endif
);
exit( 0 );
}
else
if (strcmp( pArg, "-table" ) == 0)
{
gbPrintPrimes = true;
}
}
else
break;
}
return iArg;
}
void Pause()
{
fflush( stdout );
(void) getchar(); // C/C++ crap on Win32/Win64 doesn't detect ESC (0x1B)
}
|
C
|
//1.дunsigned int reverse_bit(unsigned int value);
//ķֵvalueĶλģʽҷתֵ
//
//磺
//32λ25ֵиλ
//00000000000000000000000000011001
//ת2550136832
//10011000000000000000000000000000
//أ
//2550136832
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <math.h>
unsigned int reverse_bit(unsigned int value)
{
int arr[32] = {0};
int i = 0;
int n = value;
unsigned int ret = 0;
for(i=0; i<32; i++)
{
arr[i] = (n&1);
n = n>>1;
//printf("%d ",arr[i]);
}
for(i=0; i<32; i++)
{
if(1 == arr[i])
{
ret = ret + (unsigned int)pow(2.0,(31-i));
}
}
return ret;
}
int main()
{
unsigned int n = 0;
scanf("%d",&n);
printf("%u\n",reverse_bit(n));
return 0;
}
|
C
|
//
//
//
#include "buffer.h"
struct buffer_t {
apr_allocator_t *allocator;
apr_memnode_t *node;
int offset;
};
static void buffer_tidy(buffer_t *self)
{
if (buffer_len(self) == 0)
buffer_clear(self);
else
{
int total = self->node->endp - (char *)self->node - APR_MEMNODE_T_SIZE;
if (self->offset > (total + 1)/2)
{
memcpy((char *)self->node - APR_MEMNODE_T_SIZE, buffer_ptr(self), buffer_len(self));
self->node->first_avail -= self->offset;
self->offset = 0;
}
}
}
buffer_t *buffer_make(apr_pool_t *pool, int max)
{
buffer_t *buf = apr_palloc(pool, sizeof(*buf));
buf->allocator = apr_pool_allocator_get(pool);
buf->node = apr_allocator_alloc(buf->allocator, max);
buf->offset = 0;
return buf;
}
void buffer_resize(buffer_t *self, int avail)
{
int size, new_size;
apr_memnode_t *new_node;
if (buffer_available(self) >= avail)
return;
size = buffer_len(self);
new_size = size + avail;
new_node = apr_allocator_alloc(self->allocator, new_size);
memcpy((char *)new_node + APR_MEMNODE_T_SIZE, buffer_ptr(self), size);
apr_allocator_free(self->allocator, self->node);
self->node = new_node;
self->offset = 0;
}
void buffer_clear(buffer_t *self)
{
self->node->first_avail = (char *)self->node + APR_MEMNODE_T_SIZE;
self->offset = 0;
}
void buffer_consume(buffer_t *self, int size)
{
self->offset += size;
buffer_tidy(self);
}
int buffer_len(buffer_t *self)
{
return self->node->first_avail - (char *)self->node - APR_MEMNODE_T_SIZE - self->offset;
}
apr_byte_t *buffer_ptr(buffer_t *self)
{
return (apr_byte_t *)self->node + APR_MEMNODE_T_SIZE + self->offset;
}
int buffer_available(buffer_t *self)
{
return (int)(self->node->endp - self->node->first_avail);
}
void buffer_put_byte(buffer_t *self, apr_byte_t b)
{
*self->node->first_avail++ = b;
}
void buffer_put_data(buffer_t *self, apr_byte_t *data, int size)
{
memcpy(self->node->first_avail, data, size);
self->node->first_avail += size;
}
//apr_status_t buffer_file_read(buffer_t *self, apr_file_t *file, apr_size_t len);
//apr_status_t buffer_file_write(buffer_t *self, apr_file_t *file);
apr_status_t buffer_socket_recv(buffer_t *self, apr_socket_t *sock)
{
apr_status_t rs;
apr_size_t len = buffer_available(self);
char *space = self->node->first_avail;
rs = apr_socket_recv(sock, space, &len);
if (rs != 0)
return rs;
self->node->first_avail += (int)len;
return 0;
}
apr_status_t buffer_socket_send(buffer_t *self, apr_socket_t *sock)
{
apr_status_t rs;
apr_size_t len = buffer_len(self);
rs = apr_socket_send(sock, (char *)buffer_ptr(self), &len);
if (rs != 0)
return rs;
self->offset += (int)len;
buffer_tidy(self);
return 0;
}
//EOF
|
C
|
#include "lc3.h"
#include <stdio.h>
#include <stdlib.h>
/*Phansa Chaonpoj
Samantha Shoecraft
problem 2
lc3.c - implement the instructions add, and, not, trap, ld, st,
jmp, and br as a lc3 simulator.
*/
// you can define a simple memory module here for this program
unsigned short memory[32]; // 32 words of memory enough to store simple program
//changes data, passed in by reference.
void aluFunction(int opcode, ALU_p alu);
int main(int argc, char* argv[]) {
//making change to code test
short int com_in;
if (argc > 1){
sscanf(argv[1],"%hX", &com_in);//takes command from command line
struct cpu_s cpu1;//creating cpu
CPU_p cpu = &cpu1;//creating pointer to cpu
cpu->pc =0;
memory[0] = com_in;
cpu->reg[1] = FIVE;
cpu->reg[2] = FIVETEEN;
cpu->reg[3] = ZERO;
memory[5] = 42;
controller(cpu);
}
}
int controller (CPU_p cpu)
{
struct alu_s alus;
ALU_p alu = &alus;
// check to make sure both pointers are not NULL
if (cpu == NULL || memory == NULL){
return 1;
}
// do any initializations here
unsigned int opcode, state, Rd, Rs1, Rs2, immed, immed7, PCoff9; // fields for the IR
state = FETCH;
for (;;) { // efficient endless loop
switch (state)
{
case FETCH: // microstates 18, 33, 35 in the book
printf("Here in FETCH\n");
cpu->MAR = cpu->pc;//ms 18
//moving memory at pc into instruction register 33
cpu->MDR = memory[cpu->pc];
// get memory[PC] into IR - memory is a global array
cpu->ir = memory[cpu->pc];
// increment PC- ms 18
if (cpu->pc < 31)
{
cpu->pc ++;
} else
{
cpu->pc = 0;
}
printf("Microstate 18, MAR is %d pc is now : %d", cpu->MAR, cpu->pc);
printf("\nMicrostate 33, MDR is 0X%hX", cpu->MDR);
printf("\nMicroState 35, Contents of IR = %04X\n", cpu->ir);
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// put printf statements in each state and microstate to see that it is working
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
state = DECODE;
break;
case DECODE: // microstate 32
// get the fields out of the IR
printf("Im in decode ");
opcode = (cpu->ir >> OPP_LSB) & ~(~0 << (OPP_MSB-OPP_LSB+1));//for instruction
//destination register
Rd= (cpu->ir >> DR_LSB) & ~(~0 << (DR_MSB-DR_LSB+1));
//printf("\nDestination register is: %d", Rd);
//first source register /baseR
Rs1= (cpu->ir >> SR_LSB) & ~(~0 << (SR_MSB-SR_LSB+1));
printf("\nSource register 1 is : %d", Rs1);
//second source register
Rs2= (cpu->ir >> SR2_LSB) & ~(~0 << (SR2_MSB-SR2_LSB+1));
//printf("\nSource register 2 is : %d", Rs2);
PCoff9 = (cpu->ir >> 0) & ~(~0 << (8-0 +1));
//printf("\n PCoff9 is : %d", PCoff9);
immed = (cpu->ir >> IMMED_LSB) & ~(~0 << (IMMED_MSB-IMMED_LSB+1));
immed7 = (cpu->ir >> 0) & ~(~0 << (7-0+1));
//printf("\nimmed is : %d", immed);
CC = (cpu->ir >> 5) & ~(~0 << (5-5 +1));
// make sure opcode is in integer form
BEN = ((cpu->ir >> 11) & ~(~0 << (11-11+1)) && N) + ((cpu->ir >> 10) & ~(~0 << (10-10+1)) && Z) +((cpu->ir >> 9) & ~(~0 << (9-9+1)) && P);
printf("\nMicrostate 32, BEN is :%d Opcode is : %d\n", BEN, opcode);
// hint: use four unsigned int variables, opcode, Rd, Rs, and immed7
// extract the bit fields from the IR into these variables
state = EVAL_ADDR;
break;
case EVAL_ADDR: // Look at the LD instruction to see microstate 2 example
printf("I'm evaluating the address\n");
switch (opcode) {
// different opcodes require different handling
// compute effective address, e.g. add sext(immed7) to register
case ADD:
break;
case AND:
break;
case NOT:
break;
case TRAP://15
cpu->MAR = (immed7 & cpu->reg[2]);
printf("Microstate 15 Trap,MAR : %hX\n", cpu->MAR);
break;
case LD:
cpu->MAR = cpu->pc + PCoff9;
printf("Microstate 2 LD, MAR : %hX\n", cpu->MAR);
break;
case ST:
cpu->MAR = cpu->pc + PCoff9;
printf("Microstate 3 ST, MAR : %hX\n", cpu->MAR);
break;
case JMP:
cpu->pc = cpu->reg[Rs1];
printf("Microstate 12 JMP, pc : %hX\n", cpu->pc);
break;
case BR:
//if(BEN){
cpu->pc += PCoff9;
printf("Microstate 0 BR, pc : %hX\n", cpu->pc);
//}
break;
default:
break;
}
state = FETCH_OP;
break;
case FETCH_OP: // Look at ST. Microstate 23 example of getting a value out of a register
printf("I'm in fetch_op\n");
switch (opcode) {
// get operands out of registers into A, B of ALU
// or get memory for load instr.
case ADD:
alu->a = cpu->reg[Rs1];
int choice = (cpu->ir >> 5) & ~(~0 << (5-5 +1));
if(choice)
{
alu->b = immed;
}
else{
alu->b = cpu->reg[Rs2];
}
break;
case AND:
alu->a = cpu->reg[Rs1];
int choice2 = (cpu->ir >> 5) & ~(~0 << (5-5 +1));
if(choice2)
{
alu->b = immed;
}
else
{
alu->b = cpu->reg[Rs2];
}
break;
case NOT:
alu->a = cpu->reg[Rs1];
alu->b = 0;
break;
case TRAP:
break;
case LD:
break;
case ST:
cpu->MDR = cpu->reg[Rs1];
printf("Microstate 23, MDR: %hX\n", cpu->MDR);
break;
case JMP:
break;
case BR:
break;
default:
break;
}
state = EXECUTE;
break;
case EXECUTE: // Note that ST does not have an execute microstate
switch (opcode) {
// do what the opcode is for, e.g. ADD
// in case of TRAP: call trap(int trap_vector) routine, see below for TRAP x25 (HALT)
case ADD:
aluFunction(ADD, alu); //passing in the pointer of alu to do the add op
break;
case AND:
//passing in the pointer of alu to do the and operation .
aluFunction(AND, alu);
break;
case NOT:
//passing in the pointer of alu to do the not operation .
aluFunction(NOT, alu);
break;
case TRAP: //the rest of the functions should be empty.
cpu->MDR = memory[cpu->MAR];
cpu->reg[7] = cpu->pc;
printf("Microstate 28 Trap, MDR : %hX R7: %hX\n", cpu->MDR, cpu->reg[7]);
break;
case LD:
cpu->MDR= memory[cpu->MAR];
printf("Microstate 25 MDR: %hX\n", cpu->MDR);
break;
case ST:
break;
case JMP:
break;
case BR:
break;
default:
break;
}
state = STORE;
break;
case STORE: // Look at ST. Microstate 16 is the store to memory
printf("I'm in store!\n");
switch (opcode) {
// write back to register or store MDR into memory
case ADD:
cpu->reg[Rd] = alu->r;
setCC(cpu->reg[Rd]);
printf("Microstate 1, Add, DR %hx contains %hd\n", Rd , cpu->reg[Rd]);
break;
case AND:
cpu->reg[Rd] = alu->r;
setCC(cpu->reg[Rd]);
printf("Microstate 5, And, DR: %hX\n", cpu->reg[Rd]);
break;
case NOT:
cpu->reg[Rd] = alu->r;
setCC(cpu->reg[Rd]);
printf("Microstate 9, NOT, DR: %hX\n", cpu->reg[Rd]);
break;
case TRAP:
cpu->pc = cpu->MDR;
printf("Microstate 30 PC: %hX\n", cpu->pc);
break;
case LD:
cpu->reg[Rd] = cpu->MDR;
setCC(cpu->reg[Rd]);
printf("Microstate 27 DR: %hX\n", cpu->reg[Rd]);
break;
case ST:
memory[cpu->MAR] = cpu->MDR;
printf("Microstate 16 memory %hx : %hx\n", cpu->MAR, cpu->MDR);
break;
case JMP:
break;
case BR:
break;
default:
break;
}
// do any clean up here in prep for the next complete cycle
state = FETCH;
return 0;
break;
}
}
}
/* Passed in by reference of alu. */
void aluFunction(int opcode, ALU_p alu){
if(opcode == ADD)
{
alu->r = alu->a + alu->b ;
printf("a: %d, b: %d, r: %d\n", alu->a, alu->b, alu->r);
}
else if(opcode == AND)
{
//temp for bit shifting
alu->r = alu->a&alu->b;
printf("a: %hd, b: %hd, r: %hd\n", alu->a, alu->b, alu->r);
}
else if(opcode == NOT)
{
alu->r = ~(alu->a);
printf("a: %hd, b: %hd, r: %hd\n", alu->a, alu->b, alu->r);
//if it's in register b then use this '
//alu->r = ~(alu->b);
}
}
void setCC(int result){
if (result <0 ){
N = 1;
Z = 0;
P = 0;
}else if (result == 0){
Z =1;
N =0;
P = 0;
}else {
P = 1;
N = 0;
Z = 0;
}
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* parser.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: sbruen <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/01/21 17:52:38 by sbruen #+# #+# */
/* Updated: 2019/02/02 19:20:38 by sbruen ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
#include <limits.h>
void pars_flags(char *str, t_mods *mods)
{
if (*str == '-')
mods->minus = 1;
else if (*str == '+')
mods->plus = 1;
else if (*str == ' ')
mods->space = 1;
else if (*str == '#')
mods->sharp = 1;
else if (*str == '0')
mods->zero = 1;
}
int num_counter(long int num)
{
int i;
i = 0;
while (num)
{
num /= 10;
i++;
}
return (i);
}
int pars_width(char *str, t_mods *mods)
{
int i;
mods->width = ft_atoi(str);
i = num_counter(mods->width);
return (i);
}
int pars_precision(char *str, t_mods *mods)
{
int i;
mods->precision = ft_atoi(str);
i = num_counter(mods->precision);
return (i);
}
void pars_length(char *str, t_mods *mods)
{
if (*str == 'h')
{
mods->l = 0;
mods->up_l = 0;
if (mods->h > 1)
return ;
mods->h = mods->h + 1;
}
if (*str == 'l')
{
mods->h = 0;
mods->up_l = 0;
if (mods->l > 1)
return ;
mods->l = mods->l + 1;
}
if (*str == 'L')
{
mods->h = 0;
mods->l = 0;
if (mods->up_l > 0)
return ;
mods->up_l = 1;
}
}
void init_list(t_mods *mods)
{
mods->minus = 0;
mods->plus = 0;
mods->space = 0;
mods->sharp = 0;
mods->zero = 0;
mods->width = 0;
mods->precision = -1;
mods->h = 0;
mods->l = 0;
mods->up_l = 0;
mods->count = 0;
mods->type = 0;
}
int my_strchr(char *s, char c)
{
while (*s)
{
if (*s == c)
return (1);
s++;
}
return (0);
}
void priorities(t_mods *mods, long int num)
{
if (mods->space)
if (mods->plus || num < 0)
mods->space = 0;
if (mods->zero)
if (mods->minus || mods->precision >= 0)
mods->zero = 0;
if (num == 0 && mods->precision == 0)
{
mods->zero = 0;
mods->count = 0;
}
}
char *parser(t_mods *mods, char *p, va_list ap)
{
int i;
while (*p)
{
if (*p == '%')
{
init_list(mods);
p++;
}
else if (my_strchr("-+ #", *p))
{
pars_flags(p, mods);
p++;
}
else if (*p == '0')
{
mods->zero = 1;
p++;
}
else if (ft_isdigit(*p))
{
i = pars_width(p, mods);
p += i;
}
else if (*p == '.')
{
p++;
if (ft_isdigit(*p))
{
while (*p == '0')
p++;
i = pars_precision(p, mods);
p += i;
}
else
mods->precision = 0;
}
else if (*p == 'h' || *p == 'l' || *p == 'L')
{
pars_length(p, mods);
p++;
}
else if (my_strchr("diuoxXfFeEgGaAcsSpn%", *p))
{
mods->type = *p;
printer(mods, ap);
break ;
}
else
{
mods->count = 1;
mods->plus = 0;
handle_precision(ft_strdup(""), mods, 0);
while (*p != '%' && *p)
{
ft_putchar(*p);
p++;
print_len++;
}
}
}
return (p);
}
int ft_printf(char *format, ...)
{
va_list aptr;
char *p;
t_mods *mods;
mods = (t_mods *)malloc(sizeof(t_mods));
va_start(aptr, format);
print_len = 0;
p = format;
while(*p)
{
if (*p == '%')
p = parser(mods, p, aptr);
else
{
ft_putchar(*p);
print_len++;
}
p++;
}
va_end(aptr);
return (print_len);
}
/*
int main(void)
{
int a;
int b;
a = ft_printf("M:%-+3.4d\n", -3456);
b = printf("L:%-+3.4d\n", -3456);
printf("MY=%d LB=%d\n", a, b);
}*/
|
C
|
#include <stdio.h>
#define DEBUG
#define ALPHABET_LEN 255
char StrOriginal[] = "On a dark deseart highway, cool wind in my hair.";
char StrKey[] = "wind";
char* ForceSearch(char text[], char key[])
{
// ここを実装する
int text_len,key_len,start,pos;
text_len,key_len=0;
while(1){
if(text[text_len]=='\0'){
break;
}
text_len++;
}
text_len=text_len-1;
while(1)
{
if(key[key_len]=='\0'){
break;
}
key_len++;
}
key_len=key_len-1;
for (start = 0; start+key_len<=text_len; start++)
{
for(pos=0;pos!=key_len;pos++)
{
if( text[start+pos]!=key[pos])
{
break;
}
}
if (pos=key_len&&text[start+pos]==key[pos])
{
return &text[start];
}
}
return NULL;
}
char* BMSearch(char text[], char key[])
{
// ここを実装する
int text_len,key_len,index,pos,t,i,z=0;
text_len=0;
i=0;
t=0;
while(1)
{
if(text[text_len]=='\0')
{
break;
}
text_len++;
}
text_len=text_len-1;
key_len=0;
while(1)
{
if(key[key_len]=='\0')
{
break;
}
key_len++;
}
char table[256];
for(z=0;z<256;z++)
{
table[z]=key_len;
}
for(z=key_len;z>0;z--)
{
table[key[z-1]]=i;
i++;
}
index=key_len-1;
while (index<=text_len)
{
for(pos=key_len-1;pos>=0;pos--)
{
if (text[index]==key[pos] )
{
if (pos==0&&text[index]==key[pos])
{
return &text[index];
}
}
else
{
break;
}
index--;
}
if(index+table[text[index]]<t)
{
index=index+1;
}
else
{
index=index+table[text[index]];
}
t=index;
}
return NULL;
}
int main(void)
{
char* str;
str = ForceSearch(StrOriginal, StrKey);
printf("Force Search. Find keyword at:%s\n", str);
str = BMSearch(StrOriginal, StrKey);
printf("BM Search. Find keyword at:%s\n", str);
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.