language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C
|
/******************************************************************************
* Based on OriginalNQueensSolver.
*
* Removed field x since there is no real use for it
* Removed maxN and used n instead (use malloc to reserve int arrays on heap)
* Common subexpressions eliminated
* Symmetrie checking along the vertical middle line
* Use long number and bitmask as boolean array (n limited to 31 now)
*
*****************************************************************************/
#include <stdio.h>
#include <stdlib.h>
/* this is the actual board size to be used */
int n;
/* half of the board size */
int mid;
/* number of found solutions to the n-queens problem */
long count = 0L;
/* a[x] is true, if a queen can be placed in column x (x: 1..n)
We use here a int number and bitmask instead of int a[n + 1] */
int aInt = -2; // all bits 1 except at index 0
/* b[y+x] is true, if a queen can be placed in the diagonal which is covered
by the fields (x+k, y-k) for all k. "/" antidiagonal line
We use here a long number and bitmask instead of int b[2 * n + 1] */
long bLong = -4L; // all bits 1 except at index 0 and 1
/* c[y-x+n] is true, if a queen can be placed in the diagonal which is covered
by the fields (x+k, y+k) for all k. "\" diagonal line
We use here a long number and bitmask instead of int c[2 * n] */
long cLong = -2L; // all bits 1 except at index 0
/* Function prototypes */
void try1(int i, int mirrorExit);
void tryMid(int i, int j);
/*
* If we have odd number of n, then we have to do an extra run for the n/2 + 1
* column.
*/
void tryMid(int i, int j) {
// Common subexpressions
int aBitMask = 1 << j;
int bIndex = i + j;
int cIndex = i - j + n;
if ((aInt & aBitMask) && (bLong & (1L << (bIndex)))
&& (cLong & (1L << (cIndex)))) {
long bBitMask = 1L << (bIndex);
long cBitMask = 1L << (cIndex);
aInt &= ~aBitMask;
bLong &= ~bBitMask;
cLong &= ~cBitMask;
try1(i + 1, 1);
aInt |= aBitMask;
bLong |= bBitMask;
cLong |= cBitMask;
}
}
/*
* Search all solutions that start with a queen in the row i. If mirrorExit,
* then we do only columns 1..n/2 . With mirrorExit we control that only 1..n/2
* is checked on the first row, for all deeper rows we do as usual 1..n.
*/
void try1(int i, int mirrorExit) {
int j = 0;
// Common subexpressions
int bIndex = i;
int cIndex = i + n;
do {
j++;
if (mirrorExit && (j > mid)) {
// Do not count mirrored solutions.
return;
}
// Common subexpressions
bIndex++;
cIndex--;
int aBitMask = 1 << j;
if ((aInt & aBitMask) && (bLong & (1L << (bIndex)))
&& (cLong & (1L << (cIndex)))) {
long bBitMask = 1L << (bIndex);
long cBitMask = 1L << (cIndex);
aInt = aInt & ~aBitMask;
bLong = bLong & ~bBitMask;
cLong = cLong & ~cBitMask;
if (i < n) {
try1(i + 1, 0);
} else {
count++;
}
aInt = aInt | aBitMask;
bLong = bLong | bBitMask;
cLong = cLong | cBitMask;
}
} while (j != n);
}
int main(int argc, char *argv[]) {
if (argc <= 1 || (n = atoi(argv[1])) <= 0) {
n = 8;
}
mid = n >> 1; // mid = n/2
try1(1, 1);
// if we have odd n, we have to do column n/2 + 1 extra
if ((1 & n) == 1) {
tryMid(1, (mid + 1));
}
// add mirrored solutions (simply double count)
count = count << 1;
printf("%ld\n", count);
return 0;
}
|
C
|
/*
* Macro di root per analizzare i dati.
* Lanciare come:
*
* shell> root -l
* root[0] .L Analyze.C
* root[1] Analyze("nomeDelFile.root")
*/
void PlotMedia(const char* fileName, int j)
{
// apre file prende il TTree di nome "datatree" dal file
TFile* file = new TFile(fileName);
TTree* tree = (TTree*)file->Get("datatree");
// setta indirizzi delle variabili di interesse
Double_t ch0[1000],ch2[1000],ch4[1000],ch6[1000];
Int_t Nevent, Nsample;
tree->SetBranchAddress("ch0",&ch0);
tree->SetBranchAddress("ch2",&ch2);
tree->SetBranchAddress("ch4",&ch4);
tree->SetBranchAddress("ch6",&ch6);
tree->SetBranchAddress("nevent", &Nevent);
tree->SetBranchAddress("nsample",&Nsample);
tree->GetEntry(j);
Double_t v0[1000], v2[1000], v4[1000], v6[1000], time[1000];
for(int i=0;i<1000;i++){
v0[i]=0;
v2[i]=0;
v4[i]=0;
v6[i]=0;
}
for(int i=0;i<Nsample;i++){
v0[i]=ch0[i];
v2[i]=ch2[i];
v4[i]=ch4[i];
v6[i]=ch6[i];
time[i]=i;
}
TCanvas *cha0 = new TCanvas("cha0", "Canale 0");
cha0->Divide(2,2);
cha0->cd(1);
TGraph *antonio = new TGraph(Nsample, time, v0);
antonio->SetTitle("Canale 0");
antonio->Draw();
cha0->cd(2);
TGraph *gigetto = new TGraph(Nsample, time, v2);
gigetto->SetTitle("Canale 2");
gigetto->Draw();
cha0->cd(3);
TGraph *pablo = new TGraph(Nsample, time, v4);
pablo->SetTitle("Canale 4");
pablo->Draw();
cha0->cd(4);
TGraph *antoniocalabro = new TGraph(Nsample, time, v6);
antoniocalabro->SetTitle("Canale 6");
antoniocalabro->Draw();
}
|
C
|
// ȸ α
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
#include <Windows.h>
#include <time.h>
#include <mmsystem.h>
#pragma comment (lib ,"winmm.lib")
#pragma warning (disable:4996)
// ȸ α Define
#define NUM_OF_MEMBERS 200
#define NUM_OF_PRINT 20
#define TIME_OF_DELAY 77
#define CURTAIN_DELAY 37
#define STUDENTID_MAXCHAR 7
#define NAME_MAXCHAR 9
#define ADDRESS_MAXCHAR 41
#define CELLPHONE_MAXCHAR 15
// ȸ α ü
typedef struct Member {
int Studentnum; // й
char Name[NAME_MAXCHAR];
char Address[ADDRESS_MAXCHAR];
char Cellphone[CELLPHONE_MAXCHAR];
struct Member *prev; // Linked List
struct Member *next; // Linked List
} Member_t;
/*** ȸ α Լ ***/
// Main Ե Լ
void inputInfo(FILE *fp, Member_t *id); // data.txt ü
int mainMenu(int* error); // θ (Է°: , °: ð)
int inputMenu(void); // ð Է
int errorCheck(int check); // üũ
void mainmenuUI(void); // θ UI
void welcomeUI(); // ȭ UI
// 1. ȸ Լ
void headOfCase1(void); // ȸ
void printInfo(Member_t *id); // ü ִ ȸ
int pauseWithLeftRight(void); // , ȭ
int pauseWithLeft(void); // ȭ ( )
int pauseWithRight(void); // ȭ ( )
void choiceButton(int num); // ý ư On
void previousPageButton(void); // ư On
void nextPageButton(void); // ư On
void homePageButton(int check); // ư On
// 2. ȸ Լ
void case2(FILE *fp, Member_t *id); // 2. ȸ (ȸ ϵǸ maxnum +1)
void inputNewMember(FILE *fp, Member_t *id); // ο ȸ Է (Maxnum ȯ)
void findMaxStudentNum(Member_t *id, int *maxnum, int *maxstudentnum); // л ū й ˻
int validName(char *str, int key); // Էµ ̸ valid Ȯ
void validNameErrorOn(int key); // ߸ ̸ Է½ On
void validNameErrorOff(void); // ߸ ̸ Է½ Off
int validAddress(char *str, int menu); // Էµ ּ valid Ȯ
void validAddressErrorOn(int menu); // ߸ ּ Է½ On
void validAddressErrorOff(void); // ߸ ּ Է½ Off
int validCellphone(char a); // Էµ ȭȣ valid Ȯ
void validCellphoneErrorOn(void); // ߸ ȭȣ Է½ On
void validCellphoneErrorOff(void); // ߸ ȭȣ Է½ Off
int repeatCellphone(Member_t *id, char *str, int maxnum); // Էµ ȭȣ ߺ Ȯ
void repeatCellphoneErrorOn(int menu); // ߸ ȭȣ Է½ On
void repeatCellphoneErrorOff(void); // ߸ ȭȣ Է½ Off
void closeCase2(void); // ȸ ȭ
int inputMemberSave(void); // Է ȸ Ȯ
void case2UI(void); // ȸ UI
void case2CheckListUI(int menu); // ȸ ǻ UI
// 3. ȸ Լ
void deleteMemberInfo(Member_t *id); // 3. ȸ
void case3DeleteSearchOptionUI(void); // ȸ ˻ ɼ UI
int deleteInfo(Member_t *id, int i); // ȸ
void deleteLinkedList(Member_t *id, int i); // ȸ Linked List
void deleteCompleteUI(void); // ȸ UI
void deleteSearchInfoUI(Member_t *id, int i); // ȸ ȸ ˻ UI
// 4. ȸ Լ
void adjustMemberInfo(Member_t *id); // 4. ȸ
int searchInfoIDnum(Member_t *id, int idnum); // ȸ й ˻ (Է°: idnum й)
int searchStudentID(void); // ȸ ˻ ɼ й ˻
int searchName(char *name); // ȸ ˻ ɼ ̸ ˻
int searchCellphone(char *cellphone); // ȸ ˻ ɼ ȭȣ ˻
void errorSearchChoice(void); // ȸ ˻
void searchCancel(void); // ȸ ˻
void validStudentID(char studentID, int *i, int line, int row, int menu); // й valid Check
void validStudentIDError(int menu); // й valid Error On
int inputInfoYesOrNo(int i); // Է Ȯ (Է° i: ˻ or )
int searchInfoName(Member_t *id, char *name); // ȸ ̸ ˻
void case4PrintInfo(Member_t *id, int i); // ˻ ȸ
int adjustInfo(Member_t *id, int i); // ȸ
int adjustInfoMenuChoice(void); // ȸ ɼ
void adjustCell(int count); // ȸ Էâ (Է°: )
int insertStudentNum(int line, int row, int menu); // й Է Valid Check (Է°: ԷϿ ġ )
int insertName(int line, int row, char *name, int menu); // ̸ Է Valid Check
void adjustInfoInputStudentID(Member_t *id, int INDnum, int i); // й
int repeatStudentIDCheck(Member_t *id, int IDnum); // й ߺ Check
int printSameNameMember(Member_t *id, int *sameName, int j); // ̸ ȸ
void adjustInfoInputName(Member_t *id, int i); // ̸
int insertCellphone(int line, int row, char *name, int menu); // ȭȣ Է valid Check
int searchInfoCellphone(Member_t *id, char *cellphone); // ȭȣ ˻
void adjustInfoInputAddress(Member_t *id, int i); // ּ
void adjustInfoInputCellphone(Member_t *id, int i); // ȭȣ
void case4SearchOptionUI(void); // ȸ ˻ ɼ UI
// 5. ˻ Լ
void searchMemberInfo(Member_t *id); // 5. ȸ ˻
void case5SearchOptionUI(void); // ȸ ˻ ɼ ȭ
void searchInfo(Member_t *id, int i); // ȸ ˻
// 6. Լ
void saveFile(FILE *fp, Member_t *id); // Ǿ ִ Ϸ
void fileSaveUI(void); // UI
// 7. Լ
int saveCheck(void); // (ȯ: Է¿)
int checkSaveValue(void); // Է
void programCloseUI(void); // α UI
// Լ (consoleFuntion.c)
void gotoxy(int x, int y); // Է Ŀ ġ
void cursorOn(void); // Ŀ On
void cursorOff(void); // Ŀ Off
void textColor(int color); // ڻ
void warningYesOrNo(void); // Yes Ȥ No Error
void curtainEffect(void); // ȸ ˻ Ŀư ȭ ȿ
void lineClear(void); //
void printfAllNodes(Member_t *head); // Linked List ̿ؼ ȸ
void screenClearUp(); // ȭ ̵
void screenClearDelete(); // ȭ 찳
int stringComp(char *msg1, char *msg2);
|
C
|
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void computelps(char* pat, int* lps, int l)
{
int len = 0;
lps[0] = 0;
int i = 1;
while(i < l)
{
if(pat[i] == pat[len])
{
len++;
i++;
lps[i] = len;
}
else
{
if(len != 0)
{
len = lps[len-1];
}
else
{
lps[i] = 0;
i++;
}
}
}
}
void kmp(char* txt, char* pat)
{
int lt = strlen(txt);
int lp = strlen(pat);
int* lps = calloc(lp, sizeof(int));
computelps(pat, lps, lp);
int i = 0, j = 0;
while(i < lt)
{
if(txt[i] == pat[j])
{
i++;
j++;
}
if(j == lp)
{
printf("\n index = %d\n pattern = %s\n\n", i-j, txt+i-j);
j = lps[j-1];
}
else if(txt[i] != pat[j])
{
if(j != 0)
j = lps[j-1];
else
i++;
}
}
}
void main()
{
char txt[] = "Searching for string pattering ending here";
char pat[] = "ing";
kmp(txt, pat);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* print.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: obohosla <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/05/10 15:51:37 by obohosla #+# #+# */
/* Updated: 2017/05/13 18:20:52 by obohosla ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/ft_ls.h"
void ls_print2(t_lst *tmp_l, t_flg *flg)
{
int w;
int v;
v = 0;
w = 0;
if (!flg->a && flg->is)
v = 1;
ft_printf("%-*s", flg->w_md, tmp_l->mode);
ft_printf("%*d ", flg->w_lnk, tmp_l->link);
if (!flg->g)
ft_printf("%-*s ", flg->w_uid, tmp_l->uid);
ft_printf("%-*s ", flg->w_gid, tmp_l->gid);
if ((tmp_l->mode[0] == 'c') || (tmp_l->mode[0] == 'b'))
{
ft_printf(" %*d,", flg->w_mj, tmp_l->maj);
ft_printf("%*d ", flg->w_sz + v, tmp_l->min);
}
else
{
if (flg->is)
w = flg->w_mj + 2;
ft_printf("%*lld ", flg->w_sz + w + v, tmp_l->size);
}
ft_printf("%s ", tmp_l->date);
}
void ls_print(t_lst *bg_l, t_flg *flg, int i)
{
t_lst *tmp_l;
tmp_l = bg_l;
if ((flg->l || flg->g) && i)
ft_printf("total %lld\n", flg->blocks);
while (tmp_l)
{
if (flg->l || flg->g)
{
ls_print2(tmp_l, flg);
ls_print3color(tmp_l, flg);
ls_print_link(tmp_l);
}
else
ls_print3color(tmp_l, flg);
write(1, "\n", 1);
tmp_l = tmp_l->next;
}
}
void ls_print_link(t_lst *tmp_l)
{
char *s;
if (tmp_l->mode[0] == 'l')
{
s = ft_strnew(257);
readlink(tmp_l->fnm, s, 256);
ft_printf(" -> %s", s);
free(s);
}
}
void ls_print3color(t_lst *tmp_l, t_flg *flg)
{
if (flg->hg)
ls_print3color2(tmp_l);
else
ft_printf("%s", tmp_l->nm);
}
void ls_print3color2(t_lst *tmp_l)
{
if (tmp_l->mode[0] == 'd')
{
if (tmp_l->mode[8] == 'w' && tmp_l->mode[9] == 't')
ft_printf("{blackgreen}%s{eoc}", tmp_l->nm);
else if (tmp_l->mode[8] == 'w' && tmp_l->mode[9] != 't')
ft_printf("{blackbrown}%s{eoc}", tmp_l->nm);
else
ft_printf("{blue}%s{eoc}", tmp_l->nm);
}
else if (tmp_l->mode[0] == 'l')
ft_printf("{magenta}%s{eoc}", tmp_l->nm);
else if (tmp_l->mode[0] == 'c')
ft_printf("{bluebrown}%s{eoc}", tmp_l->nm);
else if (tmp_l->mode[0] == 'b')
ft_printf("{bluecyan}%s{eoc}", tmp_l->nm);
else if (tmp_l->mode[0] == 's')
ft_printf("{green}%s{eoc}", tmp_l->nm);
else if (tmp_l->mode[0] == 'p')
ft_printf("{brown}%s{eoc}", tmp_l->nm);
else if (tmp_l->mode[0] == '-' && (tmp_l->mode[3] == 'x'
|| tmp_l->mode[6] == 'x'))
ft_printf("{red}%s{eoc}", tmp_l->nm);
else
ft_printf("%s", tmp_l->nm);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
int value;
fp = fopen( "data.txt", "r" ); /* open for reading */
if ( fp == NULL ) /* check does file exist etc */
{
printf( "Cannot open data.txt for reading \n" );
exit(1); /* terminate program THERE IS A BETTER WAY TO DO THIS! */
}
fscanf( fp, "%d", &value );
while ( !feof(fp) ) {
printf( "%d | ", value );
for( int i = 0; i < value; i++ ) {
printf( "*" ); // could also use putchar( '*' );
}
printf( "\n" );
fscanf( fp, "%d", &value );
}
fclose(fp);
}
|
C
|
/*******************************************************************************
* File Name: debug.c
*
* Version: 1.0
*
* Description:
* This file contains the definiton for debug functions, using UART as communication
* medium. These function sends UART data to KitProg/PSoC 5LP, which enumerats as
* COM port on connected PC.
*
********************************************************************************
* Copyright 2015, Cypress Semiconductor Corporation. All rights reserved.
* You may use this file only in accordance with the license, terms, conditions,
* disclaimers, and limitations in the end user license agreement accompanying
* the software package with which this file was provided.
*******************************************************************************/
#include <debug.h>
/*******************************************************************************
* Function Name: SendBLEStatetoUART
********************************************************************************
* Summary:
* Sends the string to UART corresponding to the present BLE state
*
* Parameters:
* ble_state: current state of the BLE.
*
* Return:
* void
*
*******************************************************************************/
void SendBLEStatetoUART(CYBLE_STATE_T ble_state)
{
#if (DEBUG_ENABLED == 1)
/* Depending on current BLE state sent, place the string on UART */
switch(ble_state)
{
case CYBLE_STATE_STOPPED:
UART_UartPutString(" |BLE State: CYBLE_STATE_STOPPED ");
break;
case CYBLE_STATE_INITIALIZING:
UART_UartPutString(" |BLE State: CYBLE_STATE_INITIALIZING ");
break;
case CYBLE_STATE_CONNECTED:
UART_UartPutString(" |BLE State: CYBLE_STATE_CONNECTED ");
break;
case CYBLE_STATE_ADVERTISING:
UART_UartPutString(" |BLE State: CYBLE_STATE_ADVERTISING ");
break;
case CYBLE_STATE_SCANNING:
UART_UartPutString(" |BLE State: CYBLE_STATE_SCANNING ");
break;
case CYBLE_STATE_CONNECTING:
UART_UartPutString(" |BLE State: CYBLE_STATE_CONNECTING ");
break;
case CYBLE_STATE_DISCONNECTED:
UART_UartPutString(" |BLE State: CYBLE_STATE_DISCONNECTED ");
break;
default:
UART_UartPutString(" |BLE State: UNKNOWN STATE ");
break;
}
UART_UartPutCRLF(' ');
#else
ble_state = ble_state;
#endif
}
/*******************************************************************************
* Function Name: PrintNum
********************************************************************************
* Summary:
* Converts decimal number to characters in ASCII that can be printed on
* terminal.
*
* Parameters:
* num: number to be converted to string.
*
* Return:
* void
*
*******************************************************************************/
void PrintNum(uint8 num)
{
#if (DEBUG_ENABLED == 1)
uint8 temp[3];
temp[0] = num%10;
num = num/10;
temp[1] = num%10;
num = num/10;
temp[2] = num%10;
if(temp[2] == 0)
{
if(temp[1] == 0)
{
UART_UartPutChar('0' + temp[0]);
}
else
{
UART_UartPutChar('0' + temp[1]);
UART_UartPutChar('0' + temp[0]);
}
}
else
{
UART_UartPutChar('0' + temp[2]);
UART_UartPutChar('0' + temp[1]);
UART_UartPutChar('0' + temp[0]);
}
#else
num = num;
#endif
}
/*******************************************************************************
* Function Name: PrintHex
********************************************************************************
* Summary:
* Converts HEX number to characters in ASCII that can be printed on
* terminal.
*
* Parameters:
* num: HEX to be converted to string.
*
* Return:
* void
*
*******************************************************************************/
void PrintHex(uint8 num)
{
#if (DEBUG_ENABLED == 1)
uint8 temp[2];
temp[0] = num%16;
num = num/16;
temp[1] = num%16;
UART_UartPutString("0x");
if(temp[1] < 10)
{
UART_UartPutChar('0' + temp[1]);
}
else
{
UART_UartPutChar('A' + (temp[1] - 10));
}
if(temp[0] < 10)
{
UART_UartPutChar('0' + temp[0]);
}
else
{
UART_UartPutChar('A' + (temp[0] - 10));
}
#else
num = num;
#endif
}
/*******************************************************************************
* Function Name: HexToAscii
********************************************************************************
* Summary:
* Converts either the higher or lower nibble of a hex byte to its
* corresponding ASCII.
*
* Parameters:
* value - hex value to be converted to ASCII
* nibble - 0 = lower nibble, 1 = higher nibble
*
* Return:
* char - hex value for the value/nibble specified in the parameters
*
*******************************************************************************/
char HexToAscii(uint8 value, uint8 nibble)
{
#if (DEBUG_ENABLED == 1)
if(nibble == 1)
{
/* bit-shift the result to the right by four bits */
value = value & 0xF0;
value = value >> 4;
if (value >9)
{
value = value - 10 + 'A'; /* convert to ASCII character */
}
else
{
value = value + '0'; /* convert to ASCII number */
}
}
else if (nibble == 0)
{
/* extract the lower nibble */
value = value & 0x0F;
if (value >9)
{
value = value - 10 + 'A'; /* convert to ASCII character */
}
else
{
value = value + '0'; /* convert to ASCII number */
}
}
else
{
value = ' '; /* return space for invalid inputs */
}
return value;
#else
value = value;
nibble = nibble;
return(1);
#endif
}
/* [] END OF FILE */
|
C
|
#include <stdio.h>
long int factorial(int number);
void main() {
int number;
printf("Enter a positive number: ");
scanf(" %d", &number);
printf("The factorial of %d is %d\n", number, factorial(number));
}
long int factorial(int number) {
if(number >= 1)
return number * factorial(number - 1);
else
return 1;
}
|
C
|
#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
int main (int argc, string argv[]) {
if ( argc != 2 ) {
printf("ERROR: No argument detected\n");
return 1;
} else {
char* str = GetString();
int len = strlen(str);
int k = atoi(argv[1]);
k = k%26;
int p;
for (int i=0;i<len;i++) {
if ( isalpha(str[i]) ) {
p = str[i];
if ( p >= 65 && p <= 90 ){
p += k;
if ( p > 90) {
p -= 26;
}
} else if ( p >= 97 && p <= 122 ){
p += k;
if ( p > 122) {
p -= 26;
}
}
printf("%c", (char)p);
} else {
printf("%c", str[i]);
}
}
printf("\n");
return 0;
}
}
|
C
|
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
int main(int argc,char *argv[])
{
int fd;
if((fd=open(argv[1],O_RDWR|O_CREAT,0644))<0)
{
perror("Error for open");
return 1;
}
printf("fd=%d\n",fd);
int fd3;
if((fd3=open(argv[2],O_RDWR|O_CREAT,0644))<0)
{
perror("Error for open");
return 1;
}
int fd2=dup2(fd,fd3);//dup2()会将fd3指向的文件关闭。而使fd3可用。
printf("fd3=%d\n",fd3);
printf("fd2=%d\n",fd2);
write(fd,"A",1);
write(fd2,"B",1);
err:
close(fd);
return 0;
}
|
C
|
#include "get_next_line.h"
#include "libft/libft.h"
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
int ft_position_bis(char **save, char **line, int i)
{
int ret;
char *tic;
char *tac;
ret = 0;
while ((*save)[i] != '\n' && (*save)[i])
i++;
if ((*save)[i] == '\n')
ret = 1;
i++;
if (!*line)
*line = ft_strsub(*save, 0, i - 1);
else
{
tic = ft_strsub(*save, 0, i - 1);
*line = ft_strcat(*line, tic);
}
if ((*save)[i] == '\0')
tac = NULL;
else
tac = ft_strsub(*save, i, (ft_strlen(*save) - i));
free (*save);
*save = tac;
return (ret);
}
char *ft_realloc(char **save)
{
char *tmp;
tmp = *save;
if (!(*save = ft_strnew(ft_strlen(tmp) + (BUF_SIZE + 1))))
return (NULL);
ft_strcpy(*save, tmp);
free (tmp);
return (*save);
}
int ft_position(char **save, char **line)
{
int i;
char *tac;
int ret;
i = 0;
ret = 0;
if ((*save)[i] == '\n')
{
if (*line == NULL)
*line = ft_strsub(*save, 0, i);
ret = 1;
i++;
if ((*save)[i] == '\0')
tac = NULL;
else
tac = ft_strsub(*save, i, (ft_strlen(*save) - i));
free (*save);
*save = tac;
i = 0;
}
else
ret = ft_position_bis(save, line, i);
return (ret);
}
int ft_read(char *buf, char **save, int const fd, char **line)
{
int ret;
while ((ret = read(fd, buf, BUF_SIZE)) > 0)
{
buf[ret] = '\0';
if (*save == NULL)
{
free (*save);
if (!(*save = ft_strnew(BUF_SIZE + 1)))
return (-1);
}
if (!(*save = ft_realloc(save)))
return (-1);
ft_strncat(*save, buf, ret);
if (ft_position(save, line) == 1)
return (1);
}
free(buf);
return (ft_position(save, line));
}
int get_next_line(int const fd, char **line)
{
char *buf;
static char *save = NULL;
*line = NULL;
buf = ft_strnew(BUF_SIZE + 1);
if ((BUF_SIZE <= 0) || (fd < 0))
return (-1);
if (save == NULL)
{
if (!(save = ft_strnew(BUF_SIZE + 1)))
return (-1);
}
return(ft_read(buf, &save, fd, line));
}
int main(int argc, char **argv)
{
int fd;
char *line = NULL;
if (argc == 1)
{
ft_putstr("File name missing.");
return (1);
}
if (argc > 2)
{
ft_putstr("Too many arguments.");
return (1);
}
fd = open(argv[1], O_RDONLY);
while (get_next_line(fd, &line))
{
ft_putendl(line);
free(line);
}
if (close(fd) == -1)
{
ft_putstr("close error");
return (1);
}
return (0);
}
|
C
|
#include "holberton.h"
#include <stdlib.h>
#include <stdio.h>
/**
* _print_int_binary - Prints a int converted to binary
* @args: A list of variadic arguments
*
* Return: The number of printed digits
*/
int _print_int_binary(va_list args)
{
unsigned int x = 0;
int b = 0, new = 0;
new = va_arg(args, int);
x = new;
if (new < 0)
{
_putchar('1');
new = new * -1;
x = new;
b += 1;
}
while (x > 0)
{
x = x / 2;
b++;
}
_recursion_int_binary(new);
return (b);
}
/**
* _recursion_int_binary - Prints a binary
* @a: integer to print
*
*/
void _recursion_int_binary(int a)
{
unsigned int t;
t = a;
if (t / 2)
_recursion_int_binary(t / 2);
_putchar(t % 2 + '0');
}
|
C
|
/*
* @file list27.c
* @brief 読み込んだ整数値を3で割った剰余を表示
* @author mogi
* @date 2018/3/17
*/
#include <stdio.h>
int main(void){
int no;
printf("%d",&no);
switch(no % 3){
case 0 :puts("その数は3で割り切れます"); break;
case 1 :puts("その数を3で割った剰余は1です。"); break;
case 2 :puts("その数を3で割った剰余は2です。"); break;
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "pilha.h"
struct pilha {
int v[MAX];
int topo;
};
Pilha * cria_pilha () {
Pilha * p = (Pilha *) malloc (sizeof(Pilha));
if (p)
p->topo = 0;
return p;
}
int pilha_vazia (const Pilha *p) {
/*if (p->topo == 0)
return 1;
else
return 0;*/
return !p->topo;
}
int pilha_cheia (const Pilha *p) {
/*if (p->topo == MAX)
return 1;
else
return 0;*/
return (p->topo == MAX);
}
int push (int i, Pilha *p) {
if (pilha_cheia(p))
return 0;
/*p->v[p->topo] = i;
p->topo++;*/
p->v[p->topo++] = i;
return 1;
}
int pop (int *i, Pilha *p) {
if (pilha_vazia(p))
return 0;
/*p->topo--;
*i = p->v[p->topo];*/
*i = p->v[--p->topo];
return 1;
}
int tamanho (const Pilha *p) {
return p->topo;
}
int consulta_topo (const Pilha *p) {
if (!pilha_vazia(p))
return p->v[p->topo-1];
return -1;
}
void mostra_pilha (const Pilha *p) {
int i;
if (pilha_vazia(p))
printf ("esta vazia");
else
for (i=p->topo-1; i>=0; i--)
printf ("%d ", p->v[i]);
printf ("\n");
}
|
C
|
//
//
//
#include "driver/gpio.h"
static gpio_num_t dht11_pin;
static void dht11_delay_ms(uint16_t i) {
while (i--) {
os_delay_us(1000);
}
}
static void dht11_SetPinOutput(void) {
gpio_config_t config;
config.pin_bit_mask = (1 << dht11_pin);
config.mode = GPIO_MODE_OUTPUT_OD;
gpio_config(&config);
}
static void dht11_SetPinInput(void) {
gpio_config_t config;
config.pin_bit_mask = (1 << dht11_pin);
config.mode = GPIO_MODE_INPUT;
config.pull_up_en = GPIO_PULLUP_DISABLE;
config.pull_down_en = GPIO_PULLDOWN_DISABLE;
gpio_config(&config);
}
void dht11_Init(gpio_num_t data_pin) {
dht11_pin = data_pin;
}
int dht11_ReadHumiAndTemp(int *humi, int *temp) {
uint8_t data[5];
uint8_t i, j;
dht11_SetPinOutput();
gpio_set_level(dht11_pin, 0); // Pull down >18ms
delay_ms(20);
dht11_SetPinInput(); // Auto pull up
for (i=0;i<200;i++) {
if (gpio_get_level(dht11_pin)==0) break;
os_delay_us(1);
}
if (i >= 200) return -1;
for (i=0;i<200;i++) {
if (gpio_get_level(dht11_pin)==1) break;
os_delay_us(1);
}
if (i >= 200) return -2;
for (i=0;i<200;i++) {
if (gpio_get_level(dht11_pin)==0) break;
os_delay_us(1);
}
if (i >= 200) return -3;
for (j=0;j<40;j++) {
for (i=0;i<200;i++) {
if (gpio_get_level(dht11_pin)==1) break;
//os_delay_us(1);
}
if (i >= 200) return -4;
for (i=0;i<200;i++) {
if (gpio_get_level(dht11_pin)==0) break;
//os_delay_us(1);
}
if (i >= 200) return -5;
data[j/8] <<= 1;
if (i > 5) {
data[j/8] |= 0x01;
} else {
data[j/8] &= ~0x01;
}
}
if (((data[0] + data[1] + data[2] + data[3])&0xFF) != data[4]) {
return -6;
}
*humi = data[0];
*temp = data[2];
return 0;
}
|
C
|
#include<stdio.h>
int main() {
int a[100], n, i, j, temp;
printf("Enter how many numbers you want:\n");
scanf("%d", &n);
printf("Enter the %d elements:\n", n);
for (i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
printf("\n\tThe given array is:\n");
for (i = 0; i < n; i++) {
printf("\n\t\t%d", a[i]);
printf("n");
}
for (i = 0; i < n; i++) {
for (j = i + 1; j < n; j++) {
if (a[i] > a[j]) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
printf("\n\n\n\tThe sorted array using Bubble sorted:\n");
for (i = 0; i < n; i++) {
printf("\n\t\t%d", a[i]);
}
return 0;
}
|
C
|
#pragma once
#ifndef __BINARY_TREE
#define __BINARY_TREE
#define TRUE 1
#define FALSE 0
typedef int BTData;
typedef struct _node {
BTData data;
struct _node *left;
struct _node *right;
} Node;
typedef Node BTreeNode;
BTreeNode * MakeBTreeNode(void);
BTData GetData(BTreeNode * bt);
void SetData(BTreeNode * bt, BTData data);
BTreeNode * GetLeftSubTree(BTreeNode *bt);
BTreeNode * GetRightSubTree(BTreeNode *bt);
void MakeLeftSubTree(BTreeNode *main, BTreeNode *sub);
void MakeRightSubTree(BTreeNode *main, BTreeNode * sub);
#endif // !__BINARY_TREE
|
C
|
// namespace.h
#ifndef NAMESPACE_H
#define NAMESPACE_H
#include <stdio.h> // for printf()
#include <stdlib.h> // for EXIT_SUCCESS
#define UNIQUE_PREFIX_DEFAULT_NAMESPACE vector
#ifdef UNIQUE_PREFIX_NAMESPACE
#define UNIQUE_PREFIX_DOT_NAMESPACE UNIQUE_PREFIX_NAMESPACE
#endif
#ifndef UNIQUE_PREFIX_NAMESPACE
#define UNIQUE_PREFIX_DOT_NAMESPACE UNIQUE_PREFIX_DEFAULT_NAMESPACE
#endif
static int unique_prefix_push_back (void*, const void*);
static void* unique_prefix_at (void*, int);
typedef struct {
int (*const push_back)(void*, const void*);
void* (*const at)(void*, int);
} unique_prefix_namespace_struct;
extern unique_prefix_namespace_struct const UNIQUE_PREFIX_DOT_NAMESPACE;
unique_prefix_namespace_struct const UNIQUE_PREFIX_DOT_NAMESPACE = {
unique_prefix_push_back, unique_prefix_at
};
// From this point on could be in an implementation file.
static int unique_prefix_push_back (void* dest, const void* src) {
printf("in unique_prefix_push_back().\n");
return EXIT_SUCCESS;
}
static void* unique_prefix_at (void* dest, int n) {
printf ("in unique_prefix_at().\n");
}
#endif
|
C
|
#include <ti/devices/msp432p4xx/driverlib/driverlib.h>
// This function initializes all the peripherals
void initialize();
int main(void)
{
initialize();
while (1) {
// If the button is not pressed, turn the LED off
// We use PxIN and PxOUT for this
}
}
void initialize()
{
// step 1: Stop watchdog timer
// We do this at the beginning of all our programs for now.Later we learn more about it.
WDT_A_hold(WDT_A_BASE);
// step 2: Initializing LED1
// According to table 12.1 on page 678 of MSP432 User guide,
// to create an output, all you need is to write a 1 to PxDIR for the specific bit you want
// step 3: Initializing S1 (switch 1 or button 1)
// According to the table on page 678 of MSP432 User guide,
// to create an input with pull-up resistor, you need to do three things
// step 3.1: write a 0 to PxDIR for the specific bit you want
// step 3.2: write a 1 to PxREN for the specific bit you want
// step 3.3: write a 1 to PxOUT for the specific bit you want
}
|
C
|
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <asm/uaccess.h>
#include <linux/uaccess.h>
#include "modIO_define.h"
static int device_open(struct inode *, struct file*);
static int device_release(struct inode *, struct file *);
static ssize_t device_read(struct file *, char *, size_t, loff_t *);
static ssize_t device_write(struct file *, const char *, size_t, loff_t *);
static struct file_operations fops ={
.read = device_read,
.write = device_write,
.open = device_open,
.release = device_release
};
static int __init kern_modIO_init(void)
{
printk(KERN_EMERG "Loading modIO\n");
register_chrdev(251,"THIS MOD", &fops);
return 0;
}
static void __exit kern_modIO_exit(void)
{
unregister_chrdev(251,"THIS MOD");
printk(KERN_ALERT "Unloading modIO\n");
}
char msg_buf[BUF_LEN]; //buffer to receive message
int msg_len = 19;
char msg[20] = "Hello from inside";
int error_no; //for return value of copy_to_user and copy_from_user
static int device_open(struct inode *inode, struct file *file)
{
printk(KERN_ALERT "modIO is opened\n");
return 0;
}
static int device_release(struct inode *inode, struct file *file)
{
printk(KERN_ALERT "modIO is closed\n");
return 0;
}
static ssize_t device_read(struct file *filp, char *buf, size_t len, loff_t *off)
{
//issue by read() from userspace, we need to copy data to user
printk(KERN_ALERT "reading the device 101\n");
//we will copy to *buf (which is the pointer to the buffer in the user space), from char * msg, with length msg_len
error_no = copy_to_user(buf,msg,msg_len);
printk( KERN_INFO "%d char was put into buffer of Userland : %s\n",msg_len,msg);
return msg_len;
}
static ssize_t device_write(struct file *filp, const char *buf, size_t len, loff_t *off)
{
printk(KERN_ALERT "Writing to device\n");
//copy from the file to msg_buf with size of BUF_LEN
error_no = copy_from_user(msg_buf,buf,BUF_LEN);
printk(KERN_INFO "This was put in Motherland: %s\n",msg_buf);
return 1;
}
module_init(kern_modIO_init);
module_exit(kern_modIO_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR(AUTHOR);
MODULE_DESCRIPTION(DESC);
MODULE_VERSION(VER);
|
C
|
/* Problem 123 = 21035 */
#include <stdio.h>
#include "../algorithms.h"
#include "../list_math.h"
/* http://en.wikipedia.org/wiki/Modular_exponentiation */
long long list_modulus_power(long long base, long long exponent, long long modulus) {
long long result = 1;
struct list *multiplicand_list;
struct list *multiplier_list;
struct list *divisor = 0;
struct list *modulus_result;
struct list *modulus_list = list_from_number(modulus);
do {
if (exponent & 0x1) {
if (result) {
multiplicand_list = list_from_number(result);
multiplier_list = list_from_number(base);
divisor = 0;
list_multiply_list(multiplicand_list, multiplier_list, &divisor);
list_modulus_list(divisor, modulus_list, &modulus_result);
if (modulus_result->length) {
result = modulus_result->first->value;
if (modulus_result->length > 1) {
result *= (long long)pow(10, LIST_NUMBER_LENGTH);
result += modulus_result->last->value;
}
} else {
result = 0;
}
list_free(modulus_result);
list_free(multiplicand_list);
list_free(multiplier_list);
list_free(divisor);
}
}
if (base) {
multiplicand_list = list_from_number(base);
multiplier_list = list_from_number(base);
divisor = 0;
list_multiply_list(multiplicand_list, multiplier_list, &divisor);
list_modulus_list(divisor, modulus_list, &modulus_result);
if (modulus_result->length) {
base = modulus_result->first->value;
if (modulus_result->length > 1) {
base *= (long long)pow(10, LIST_NUMBER_LENGTH);
base += modulus_result->last->value;
}
} else {
base = 0;
}
list_free(modulus_result);
list_free(multiplicand_list);
list_free(multiplier_list);
list_free(divisor);
}
exponent >>= 1;
} while (exponent);
list_free(modulus_list);
return result;
}
int main() {
char *sieve = (char *)calloc(1000000, sizeof(char));
long long n;
long long primes[80000];
int count = 1;
long long remainder;
long long answer = 0;
sieve_primes(sieve, 1000000);
for (n = 2; n < 1000000; n++) {
if (!sieve[n]) {
primes[count++] = n;
}
}
free(sieve);
n = 1;
while (!answer) {
/*
remainder = (list_modulus_power(primes[n] - 1, n, primes[n] * primes[n]) +
list_modulus_power(primes[n] + 1, n, primes[n] * primes[n])) % (primes[n] * primes[n]);
*/
remainder = 2 * (n + 1) * primes[n];
if (remainder > 10000000000LL) {
answer = n + 1;
}
++n;
}
printf("%lld", answer);
return 0;
}
|
C
|
/*
* dict.h
*
* Created on: Apr 11, 2015
* Author: user
*/
#ifndef DICT_H_
#define DICT_H_
#endif /* DICT_H_ */
enum WordType{All, Animal, Fruit, Name};
struct Word{
WordType type;
char word[20];
};
struct Dict{
int size;
int capacity;
Word** wordArray;// a POINTER to a POINTER that points to a WORD
};
Dict *createDictionary(int capacity);
bool addWord(Dict *dic, const char *word, WordType type);
void deleteDictionary(Dict *dic);
void printDictionary(Dict *dic, WordType type=All);
|
C
|
// SPDX-License-Identifier: CC0-1.0
//
// SPDX-FileContributor: NightFox & Co., 2009-2011
//
// Water reflection effect (with scroll).
// http://www.nightfoxandco.com
#include <stdio.h>
#include <nds.h>
#include <filesystem.h>
#include <nf_lib.h>
// Wave effect variables
u16 mapa[32][24]; // Map
s16 bgx[192]; // X scroll of each line
s8 i[192]; // Movement control of each line
// Background control variables
s16 bg_x[4];
// Function that runs after a scanline is drawn. By modifying the values of the
// scroll registers it's possible to add a wave effect.
void hblank_handler(void)
{
u32 vline = REG_VCOUNT; // Get the current line
if ((vline >= 138) && (vline <= 159))
{
// If the current line is between 138 and 159, apply effect to layer 1
bgx[vline] += i[vline];
if ((bgx[vline] < 1) || (bgx[vline] > 63))
i[vline] *= -1;
NF_ScrollBg(0, 1, bg_x[1] + ((bgx[vline] / 8) - 4), 0);
}
if ((vline >= 160) && (vline <= 191))
{
// If the current line is between 160 and 191, apply effect to layer 0
bgx[vline] += i[vline];
if ((bgx[vline] < 1) || (bgx[vline] > (vline - 156)))
i[vline] *= -1;
NF_ScrollBg(0, 0, bg_x[0] + (((vline - 156) / 2) - bgx[vline]), 0);
}
}
int main(int argc, char **argv)
{
// Prepare a NitroFS initialization screen
NF_Set2D(0, 0);
NF_Set2D(1, 0);
consoleDemoInit();
printf("\n NitroFS init. Please wait.\n\n");
printf(" Iniciando NitroFS,\n por favor, espere.\n\n");
swiWaitForVBlank();
// Initialize NitroFS and set it as the root folder of the filesystem
nitroFSInit(NULL);
NF_SetRootFolder("NITROFS");
// Initialize 2D engine in both screens and use mode 0
NF_Set2D(0, 0);
NF_Set2D(1, 0);
// Initialize tiled backgrounds system
NF_InitTiledBgBuffers(); // Initialize storage buffers
NF_InitTiledBgSys(0); // Top screen
NF_InitTiledBgSys(1); // Bottom screen
// Load background files from NitroFS
NF_LoadTiledBg("bg/layer0", "layer0", 512, 256);
NF_LoadTiledBg("bg/layer1", "layer1", 512, 256);
NF_LoadTiledBg("bg/layer2", "layer2", 512, 256);
NF_LoadTiledBg("bg/layer3", "layer3", 512, 256);
NF_LoadTiledBg("bg/nfl", "nfl", 256, 256);
// Create top screen backgrounds
NF_CreateTiledBg(0, 3, "layer3");
NF_CreateTiledBg(0, 2, "layer2");
NF_CreateTiledBg(0, 1, "layer1");
NF_CreateTiledBg(0, 0, "layer0");
// Create bottom screen backgrounds
NF_CreateTiledBg(1, 3, "nfl");
// Initialize wave effect
s16 y = 0;
s8 inc = 1;
for (y = 138; y < 192; y++)
{
// Layer 1 calculations
if ((y >= 138) && (y <= 159))
{
bgx[y] = 32;
inc *= -1;
i[y] = inc;
}
// Layer 0 calculations
if ((y >= 160) && (y <= 191))
{
bgx[y] = (y - 156) / 2;
i[y] = inc;
inc *= -1;
}
}
// Register a function to be called after a screen line has been drawn (when
// the horizontal blanking period starts)
irqSet(IRQ_HBLANK, hblank_handler);
irqEnable(IRQ_HBLANK);
while (1)
{
scanKeys(); // Read keypad
u16 keys = keysHeld(); // Keys currently pressed
// Move background
if ((keys & KEY_LEFT) && (bg_x[0] > 8))
bg_x[0]--;
if ((keys & KEY_RIGHT) && (bg_x[0] < 247))
bg_x[0]++;
// Calculate parallax
bg_x[1] = bg_x[0] / 1.5;
bg_x[2] = bg_x[1] / 1.5;
bg_x[3] = bg_x[2] / 1.5;
// Wait for the screen refresh
swiWaitForVBlank();
// Scroll all backgrounds
NF_ScrollBg(0, 3, bg_x[3], 0);
NF_ScrollBg(0, 2, bg_x[2], 0);
NF_ScrollBg(0, 1, bg_x[1], 0);
NF_ScrollBg(0, 0, bg_x[0], 0);
}
return 0;
}
|
C
|
/*
* =====================================================================================
*
* Filename: strArray.c
*
* Description: when we assign string literals to char *, the strings themselves are allocated in read-only memory. However, the array string_array is allocated in read/write memory. This means that we can modify the pointers in the array, but we cannot modify the strings they point to.
*
* Version: 1.0
* Created: 12/10/19 22:06:05
* Revision: none
* Compiler: gcc
*
* Author: YOUR NAME (),
* Organization:
*
* =====================================================================================
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(void) {
char * str_array[] = {
"foo", "bar", "baz
}
char mod_array[][4] = {
"foo", "bar", "baz
}
/* The above is equivalent to
* char mod_array[][4] = {
* {'f', 'o', 'o', '\0'},
* {'b', 'a', 'r', '\0'},
* {'b', 'a', 'z', '\0'}
* };
*/
}
|
C
|
/* Assignment operators */
#include <stdio.h>
int main(){
/*
Guess the output of all calculations
*/
int x=2;
int y; int z;
x*=3+2;
printf("x=%d\n", x);
printf("Guess 10\n");
x*=y=z=4;
printf("x=%d\n", x);
printf("Guess 40\n");
x=y==z;
printf("x=%d\n", x);
printf("Guess 1\n");
return 0;
}
|
C
|
/*
* log.c
*
* Created on: Jan 2, 2016
* Author: mori
*/
#include "log.h"
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#define LOGGER_MAXLEN 250
#define LOGGER_TIMEOUT 10
void write_string(const char *data)
{
uint8_t temp[200] = {0};
strcpy(&temp, data);
temp[strlen(data)] = '\r';
temp[strlen(data)+1] = '\n';
CDC_Transmit_HS((uint8_t *)temp, strlen(temp));
//HAL_UART_Transmit(&hUartHandle, (uint8_t *)data, strlen(data), LOGGER_TIMEOUT);
}
void LOG(const char *__msg, ...)
{
char buffer[LOGGER_MAXLEN] = {0};
va_list ap;
va_start (ap, __msg);
vsprintf (buffer, __msg, ap);
va_end (ap);
write_string(buffer);
//write_string("\n");
}
void LOG1(const char *__msg, ...)
{
char buffer[LOGGER_MAXLEN] = {0};
va_list ap;
va_start (ap, __msg);
vsprintf (buffer, __msg, ap);
va_end (ap);
write_string(buffer);
}
void LOG_ARRAY1(const uint8_t *data, int size)
{
int i =0;
for(i = 0; i < size; ++i)
{
LOG1("%02X ", data[i]);
}
}
void LOG_ARRAY(const uint8_t *data, int size)
{
LOG_ARRAY1(data, size);
write_string("\r\n");
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "rfcn-fr.h"
int main()
{
FILE *fd;
char buf[200];
char r;
float ca_freq;
int i;
int band = 0;
float rfcn = -1;
int mode = 0;
float Band_Ca_Freq_Max;
float Band_Ca_Freq_Min;
float in_rfcn;
float out_ca_fr;
char cc;
do
{
printf("1: RFCN--->Carrier Frequency\n2: Carrier Frequency--->RFCN\n");
scanf("%d",&mode);
if(mode == 1)
{
printf("Input RFCN:");
scanf("%f",&in_rfcn);
for(i = 0;i<44;i++)
{
if((in_rfcn >= BAND(i).Range_Min) && (in_rfcn <= BAND(i).Range_Max))
{
out_ca_fr = BAND(i).F_low + (in_rfcn - BAND(i).N_offs)/10;
printf("Carrier Frequency: %.3f\nBand %d\n",out_ca_fr,i+1);
break;
}
}
}
if(mode == 2)
{
printf("Input Carrier Frequency:");
scanf("%f",&ca_freq);
for(i = 0;i<44;i++)
{
Band_Ca_Freq_Max = BAND(i).F_low + 0.1*(BAND(i).Range_Max - BAND(i).N_offs);
Band_Ca_Freq_Min = BAND(i).F_low + 0.1*(BAND(i).Range_Min - BAND(i).N_offs);
if((ca_freq >= Band_Ca_Freq_Min) && (ca_freq <= Band_Ca_Freq_Max))
{
rfcn = (ca_freq - BAND(i).F_low)*10 + BAND(i).N_offs;
if((rfcn >= BAND(i).Range_Min) && (rfcn <= BAND(i).Range_Max))
{
printf("RFCN: %.3f\nBand %d\n",rfcn,i+1);
break;
}else{
printf("Error\n");
}
}
}
if(rfcn == -1)
printf("Input Frequency Error\n");
}
printf("Input 'q' Quit,Other Continue:");
cc = getchar();
cc = getchar();
}while(cc != 'q');
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
struct node{
int data;
struct node *left;
struct node *right;
};
struct node *new_node(int data){
struct node *temp = (struct node*)malloc(sizeof(struct node));
temp->data = data;
temp->left=temp->right = NULL;
return temp;
}
void inOrder(struct node *root){
if(root!=NULL){
inOrder(root->left);
printf("%d ",root->data);
inOrder(root->right);
}
}
struct node *insert(struct node *root, int data){
if(root==NULL){
return new_node(data);
}
if(data < root->data){
root->left= insert(root->left, data);
}
if(data > root->data){
root->right = insert(root->right, data);
}
return root;
}
int main(){
struct node *root=NULL;
root = insert(root, 50);
insert(root, 30);
insert(root, 20);
insert(root, 40);
insert(root, 70);
insert(root, 60);
insert(root, 80);
inOrder(root);
return 0;
}
|
C
|
/*
char string
*/
#include <stdio.h>
#include <string.h>
int main()
{
char date[] = "Febur 8";
char *p;
p = date;
int a[5] = {3,4,7,8,1};
int *d;
d = a;
printf("date1: %s\n", date);
printf("date2: %s\n", p);
printf("a: %d\n", *d);
puts(date);
return 0;
}
|
C
|
/*
** my_put_nbr.c for my_put_nbr in /home/ayasch_d/rendu/Piscine_C_J03
**
** Made by Dan Ayasch
** Login <[email protected]>
**
** Started on Thu Oct 2 10:49:30 2014 Dan Ayasch
** Last update Wed Apr 29 13:32:45 2015 Dan Ayasch
*/
#include "list.h"
int my_putnbr(int nb)
{
int nombre;
if (nb >= 0)
{
nb = -nb;
}
else
my_putchar('-');
nombre = 1;
while (nb / nombre < -9)
nombre = nombre * 10;
while (nombre != 0)
{
my_putchar('0' - nb / nombre % 10);
nb = nb % nombre;
nombre = nombre / 10;
}
return (0);
}
|
C
|
#include <stdio.h>
#define N5;
int front=-1,rear=-1;
int deque[N];
void enqueuefront(int x){
if()(f==0&&R==N-1)||(front==rear+1))
{
printf("queue is full");
}
else if(front==-1&&rear==-1){
front=rear=0;
deque[Front]=x;
}
else if(front==0){
front=N-1;
deque[front]=x
}
else{
front--;
deque[front]=x;
}
}
void enqueuerear(int x){
if((front==0&&R=N-1)||(front==rear)){
printf("queue is full")
}
else if(front==-1&&rear==-1){
front=rear=0;
deque[rear]=x;
}
else if{
rear=0;
deque[rear]=x;
}
else{
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{ int s=0,l;
int a[100];
for(;;)
{
scanf("%d",&a[s]);
if(a[s]==" ")
break;
printf("%d",a[s]);
s++;
}
return 0;
}
|
C
|
#include "holberton.h"
/**
* print_numbers - prints number followd by a new line
*/
void print_numbers(void)
{
char num;
for (num = 48; num <= 57; num++)
{
_putchar (num);
}
_putchar ('\n');
}
|
C
|
/*
** kind_texture_perlin.c for kind_texture_perlin.c in /home/sabour_m//RTV/rt
**
** Made by mourad sabour
** Login <[email protected]>
**
** Started on Sun Jun 5 11:59:46 2011 mourad sabour
** Last update Sun Jun 5 12:08:18 2011 mourad sabour
*/
#include "rt.h"
#include "struct.h"
int get_marbre_color(double x, double y, t_perlin *perlin)
{
double value;
t_color result;
value = 1 - sqrt(fabs(sin(2 * PI * get_coherent_noise(x, y, perlin))));
result.rgb.red = perlin->c1.rgb.red * (1 - value)
+ perlin->c2.rgb.red * value;
result.rgb.green = perlin->c1.rgb.green * (1 - value)
+ perlin->c2.rgb.green * value;
result.rgb.blue = perlin->c1.rgb.blue * (1 - value)
+ perlin->c2.rgb.blue * value;
return (result.all);
}
int get_bois_color(double x, double y, t_perlin *perlin)
{
double value;
t_color result;
double f;
double seuil;
seuil = 0.2;
value = fmod(get_coherent_noise(x, y, perlin), seuil);
if (value > seuil / 2)
value = seuil / 2;
f = (1 - cos(PI * value / (seuil / 2))) / 2;
result.rgb.red = perlin->c1.rgb.red * (1 - f)
+ perlin->c2.rgb.red * f;
result.rgb.green = perlin->c1.rgb.green * (1 - f)
+ perlin->c2.rgb.green * f;
result.rgb.blue = perlin->c1.rgb.blue * (1 - f)
+ perlin->c2.rgb.blue * f;
return (result.all);
}
int get_standard_color(double x, double y, t_perlin *perlin)
{
double value;
value = get_coherent_noise(x, y, perlin);
if (value <= perlin->s1)
return (perlin->c1.all);
else if (value <= perlin->s2)
return (get_seuil2(perlin, value));
else if (value <= perlin->s3)
return (get_seuil3(perlin, value));
return (perlin->c3.all);
}
|
C
|
//Disjoint Sets
#include<stdio.h>
char Bs2[9]="";
char Bs1[9]="";
char UN[9]="",IN[9]="",DI[9]="";
void bitStringCreation(int U[],int S1[],int S2[],int k)
{
int ii=0,j=0,i=0;
for(i=0;i<k;i++)
{
if(U[i]==S1[ii])
{
ii++;
Bs1[i]='1';
}
else
{
Bs1[i]='0';
}
}
Bs1[i]='\0';
ii=0;
for(j=0;j<k;j++)
{
if(U[j]==S2[ii])
{
ii++;
Bs2[j]='1';
}
else
{
Bs2[j]='0';
}
}
Bs2[j]='\0';
printf("Bit String of Set1= %s",Bs1);
printf("\n\nBit String of Set2= %s",Bs2);
}
void Union(int k)
{
int i;
for(i=0;i<k;i++)
{
UN[i]=((Bs1[i]-'0')|(Bs2[i]-'0'))+'0';
}
UN[i]='\0';
printf("UNION = %s\n",UN);
}
void Intersection(int k)
{
int i;
for(i=0;i<k;i++)
{
IN[i]=((Bs1[i]-'0')&(Bs2[i]-'0'))+'0';
}
IN[i]='\0';
printf("INTERSECTION = %s\n",IN);
}
void Difference(int k)
{
int c,j;
char Comp[9]="";
printf("\npress 1:Set1-Set2,2:Set2-Set1\nEnter your Choice =");
scanf("%d",&c);
if(c==2)
{
for(int i=0;i<k;i++)
{
Comp[i]=(Bs1[i]=='1')?'0':'1';
}
for(j=0;j<k;j++)
{
DI[j]=((Bs2[j]-'0')&(Comp[j]-'0'))+'0';
}
DI[j]='\0';
}
else
{
for(int i=0;i<k;i++)
{
Comp[i]=(Bs2[i]=='1')?'0':'1';
}
for(j=0;j<k;j++)
{
DI[j]=((Bs1[j]-'0')&(Comp[j]-'0'))+'0';
}
DI[j]='\0';
}
printf("DIFFERENCE = %s\n",DI);
}
int main()
{
int ch,i=0,n1,n2,j,S1[10],S2[10];
int U[]={1,2,3,4,5,6,7,8};
printf("Enter the number of values of set1(U=1-8):\t");
scanf("%d",&n1);
printf("Enter the elements:\n");
for(i=0;i<n1;i++)
scanf("%d",&S1[i]);
printf("Enter the number of values of set2(U=1-8):\t");
scanf("%d",&n2);
printf("Enter the elements:\n");
for(j=0;j<n2;j++)
scanf("%d",&S2[j]);
i=sizeof(U)/4;
bitStringCreation(U,S1,S2,i);
printf("1-Union \n2->Intersection \n3->Difference \n4->Exit\n");
while(1)
{
printf("Enter your choice:\n");
scanf("%d",&ch);
switch(ch)
{
case 1:Union(i);
break;
case 2:Intersection(i);
break;
case 3:Difference(i);
break;
case 4:return 0;
break;
default:printf("Invalid Entry\n");
}
}
}
|
C
|
/* 153.
Scrivere una funzione che, a partire da due liste, ne costruisca una terza ottenuta alternando gli
elementi delle altre due.
*/
#include <stdio.h>
#include <stdlib.h>
/* struct fusione di list1 e list2 */
struct list3
{
int num;
struct list3 *bridge;
};
/* struct di interi da fondere con list1 */
struct list2
{
int num;
struct list2 *bridge;
};
/* struct di interi da fondere con list2 */
struct list1
{
int num;
struct list1 *bridge;
};
int main (int argc, char const *argv[])
{
int input; /* numero in inpu */
int out; /* flag */
int i, j; /* contatori */
struct list3 *origin3, *p3; /* setup di list3 */
struct list2 *origin2, *p2; /* setup di list2 */
struct list1 *origin1, *p1; /* setup di list1 */
out = 0;
i = j = 1;
origin3 = p3 = (struct list3 *) malloc (sizeof (struct list3));
origin2 = p2 = (struct list2 *) malloc (sizeof (struct list2));
origin1 = p1 = (struct list1 *) malloc (sizeof (struct list1));
/* assegnazione di input */
printf ("Inserire elemento [%2d] lista %d > ", i++, j);
scanf ("%d", &input);
/* list1 vuota */
if (!input)
p1->bridge = NULL;
/* list1 non vuota */
else
{
p1->num = input;
p1->bridge = (struct list1 *) malloc (sizeof (struct list1));
p1 = p1->bridge;
/* popolamento della struttura */
while (!out)
{
printf ("Inserire elemento [%2d] lista %d > ", i++, j);
scanf ("%d", &input);
if (!input)
{
out = 1;
p1->bridge = NULL;
}
else
{
p1->num = input;
p1->bridge = (struct list1 *) malloc (sizeof (struct list1));
p1 = p1->bridge;
}
}
}
/* assegnazione di input */
printf ("Inserire elemento [%2d] lista %d > ", i++, ++j);
scanf ("%d", &input);
out = 0;
i = 1;
/* list2 vuota */
if (!input)
p2->bridge = NULL;
/* list2 non vuota */
else
{
p2->num = input;
p2->bridge = (struct list2 *) malloc (sizeof (struct list2));
p2 = p2->bridge;
/* popolamento della struttura */
while (!out)
{
printf ("Inserire elemento [%2d] lista %d > ", i++, j);
scanf ("%d", &input);
if (!input)
{
out = 1;
p2->bridge = NULL;
}
else
{
p2->num = input;
p2->bridge = (struct list2 *) malloc (sizeof (struct list2));
p2 = p2->bridge;
}
}
}
/* creazione di list3 */
for (out = 0, p1 = origin1, p2 = origin2; !out;)
{
if (p1->bridge == NULL)
out = 1;
else if (p2->bridge == NULL)
out = 2;
else
{
p3->num = p1->num;
p1 = p1->bridge;
p3->bridge = (struct list3 *) malloc (sizeof (struct list3));
p3 = p3->bridge;
p3->num = p2->num;
p2 = p2->bridge;
p3->bridge = (struct list3 *) malloc (sizeof (struct list3));
p3 = p3->bridge;
}
}
/* filling della lista rimanente in caso una sia piu'grande dell'altra */
if (p1->bridge == NULL && p2->bridge == NULL)
p3->bridge = NULL;
else if (out == 1)
while (p2->bridge != NULL)
{
p3->num = p2->num;
p2 = p2->bridge;
p3->bridge = (struct list3 *) malloc (sizeof (struct list3));
p3 = p3->bridge;
}
else
while (p1->bridge != NULL)
{
p3->num = p1->num;
p1 = p1->bridge;
p3->bridge = (struct list3 *) malloc (sizeof (struct list3));
p3 = p3->bridge;
}
p3->bridge = NULL;
/* esito */
p3 = origin3;
printf ("Lista fusa > ");
while (p3->bridge != NULL)
{
printf ("%d -- ", p3->num);
p3 = p3->bridge;
}
printf ("\n");
return 0;
}
// Marco Fiorillo 18/10/2021
|
C
|
/*
* Filename: timer.c
* Description: this module provides 32bit timer using 16 bit hardware
* implementation Timer1. Module Also initializes additional timers (Timer0 and
* Timer2) and provides defines (T0_FREQ and T2_FREQ) for its frequencies.
*
* Created on: Aug 21, 2012
* Author: dart
*/
#include "timer.h"
#include <avr/interrupt.h>
#include <util/atomic.h>
/******************************************************************************
*** Module variables ***
******************************************************************************/
static volatile uint16_t timer1_msb = 0;
/******************************************************************************
*** Interrupt service routines ***
******************************************************************************/
ISR(TIMER1_OVF_vect) {
timer1_msb++;
}
/******************************************************************************
*** Public functions ***
******************************************************************************/
void timerInit(void){
// TODO: remove timer0 initialization (make sure timer is not used anywhere)
#if T0_FREQ == F_CPU
TCCR0B = _BV(CS00); /* NOTE: Specified again below with FOC0x bits */
#else
#error "Unsupported Timer0 configuration"
#endif
// Clear interrupt flag (just for case)
TIFR1 |= _BV(TOV1);
// Enable overflow interrupt
TIMSK1 |= _BV(TOIE1);
#if T1_FREQ == F_CPU
TCCR1B = _BV(CS10);
#else
#error "Unsupported Timer1 configuration"
#endif
#if T2_FREQ == F_CPU / 1024
TCCR2B = _BV(CS22) | _BV(CS21) | _BV(CS20);
#else
#error "Unsupported Timer2 configuration"
#endif
}
// Get current time
uint32_t timerGetTime(void) {
uint16_t msb;
uint16_t tcnt1;
ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
tcnt1 = TCNT1;
/* For the case when timer have already overflowed but corresponding ISR
* had no time to increment "timer1_msb" variable*/
if((TIFR1 & _BV(TOV1)) && tcnt1 < T1_FREQ * 20 / F_CPU) {
msb = timer1_msb + 1;
} else {
msb = timer1_msb;
}
}
return tcnt1 + ((uint32_t)msb << 16);
}
// Same as above but can only be called within interrupt context
uint32_t timerGetTimeUnsafe(void) {
uint16_t msb;
uint16_t tcnt1;
// ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
tcnt1 = TCNT1;
if((TIFR1 & _BV(TOV1)) && tcnt1 < T1_FREQ * 20 / F_CPU) {
msb = timer1_msb + 1;
} else {
msb = timer1_msb;
}
// }
return tcnt1 + ((uint32_t)msb << 16);
}
|
C
|
/*******************************************************************
ļ: 8λʾ(רڿ)
:
汾:
˵:
ޱؼ¼:
: 2008 7 21
********************************************************************/
#ifndef __disp_h__
#define __disp_h__
#include "xuxiuliang.h"
#define Port P0
/*****************************************************************/
void delay100us(uchar t);
void disp(uchar *p);
/**************************************
: void disp(uchar *p)
: 8λʾ ʾ8λ
ڲ: ָp,ʵʾӦʱ,ʵһtable[8],ȻtableΪַָ봫β,dsip(table)
ڲ:
ע: ,е,һȫֵ,ܴ,Ӧֵ
****************************************/
void disp(uchar *p)
{ uchar i,w=0x00;
for(i=0;i<8;i++)
{ Port=*(p+i)|w++<<4;
delay100us(5);
}
}
void delay100us(uchar t)
{
uchar j;
while(t--)
{
for (j=50 ;j>0;j--);
}
}
/***********************************************************************************
void main() //Ϊʵʱʵ,ɲв
{ uchar table[8]; //עĵֵһȫֵ
table[0]=0;table[1]=1;table[2]=2;table[3]=3;table[4]=4;table[5]=5;table[6]=6;table[7]=7;
while(1){disp(table);}
}
************************************************************************************/
#endif
|
C
|
#include <stdio.h>
#include <conio.h>
#include <math.h>
#include <stdlib.h>
#include <locale.h>
#include <time.h>
int main() {
setlocale(LC_ALL, "ua");
exOne();
printf("\n\n");
system("pause");
return 0;
}
int exOne() {
int a,b,c,cOne = 0,aOne = 0,bOne = 0;
printf("Введiть число A = ");
scanf("%d",&a);
printf("Введiть число B = ");
scanf("%d",&b);
printf("Введiть число C = ");
scanf("%d",&c);
bOne = b;
cOne = c;
aOne = a;
b = a;
c = bOne;
a = cOne;
printf("A = %d B = %d C = %d", a,b,c);
return 0;
}
|
C
|
#include</test/linkedlist/ll.h>
int add_node(node_t ** head, int num){
node_t * temp = * head;
node_t * node = (node_t *) malloc(sizeof(node_t));
node->data = num;
node->next = NULL;
if (*head == NULL){
*head = node;
//printf("print %d\n", (*head)->data);
return 1;
}
while (temp->next != NULL ){
temp = temp->next;
}
temp->next = node;
}
void print_list(node_t * head){
node_t * node = head;
int i = 1;
while (node != NULL){
printf("node #%d = %d\n", i++ , node->data);
node = node->next;
}
}
int add_lists(node_t * a,node_t * b, node_t ** sum){
node_t * tempA = a;
node_t * tempB = b;
node_t * newN;
//node_t * tempC = *sum;
node_t * old ;
int first = 1;
if ( a == NULL || b == NULL || *sum != NULL ){
printf("error\n");
return 0;
}
while ( tempA != NULL && tempB != NULL ){
newN = (node_t * )malloc(sizeof(node_t));
newN->next = NULL;
newN->data = 0;
if (tempA){
newN->data += tempA->data;
tempA = tempA->next;
}
if(tempB){
newN->data += tempB->data;
tempB = tempB->next;
}
if (first){
first = 0;
*sum = newN;
}
else {
old->next = newN;
}
old = newN;
}
}
int split_list(node_t * a, node_t ** odd, node_t ** even){
int i = 0;
node_t * nodeN;
node_t * lastO;
node_t * lastE;
node_t * tempa = a;
int firstE = 1;
int firstO = 1;
while ( tempa != NULL ){
nodeN = (node_t *)malloc(sizeof(node_t));
nodeN->data = tempa->data;
nodeN->next = NULL;
//odd
if (i ^= 0x1){
if (firstO){
firstO = 0;
*odd = nodeN;
}
else{
lastO->next = nodeN;
}
lastO = nodeN;
}
else {
if (firstE){
firstE = 0;
*even = nodeN;
}
else{
lastE->next = nodeN;
}
lastE = nodeN;
}
tempa = tempa->next;
}
}
int main(void){
int i = 0;
node_t * head1 = NULL;
node_t * head2 = NULL;
node_t * sum = NULL;
node_t * sume = NULL;
node_t * sumo = NULL;
while(i < 20){
add_node(&head1, i++);
}
print_list(head1);
while (i < 40){
add_node(&head2, i++);
}
print_list(head2);
add_lists(head1,head2,&sum);
print_list(sum);
split_list(sum, &sumo,&sume);
print_list(sumo);
print_list(sume);
return 1;
}
|
C
|
/************************************************************************************************************************
* Simple application that tries to execute machine code from many different memory locations.
*
* Francisco Soto <[email protected]>
************************************************************************************************************************/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/mman.h>
#include <signal.h>
#include <errno.h>
// Execute the given function pointer.
#define EXECUTE_FUNC(FROM, FUNC) \
printf("Executing machine code from "FROM": "); \
(FUNC)(); \
printf("Executed successfully.\n");
/****************************************************************************************************
* Machine code that returns the stack pointer upon entry on the function.
* Since this is defined globally and it is initialized it will end up in our data segment.
****************************************************************************************************/
unsigned char code[] = {
0x48, // 64 bit operand size prefix
0x89, 0xe0, // mov %rsp, %rax
0xc3 // ret
};
/****************************************************************************************************
* This is defined globally but it is NOT initialized so it will end up in our bss segment.
****************************************************************************************************/
unsigned char bss_code[sizeof(code)];
/* Segmentation fault handler */
void sigsegv_handler (int sig) {
printf("SIGSEGV recieved.\n");
exit(0);
}
/* Data bus error handler (usually occurs when accessing unmapped addressing space) */
void sigbus_handler (int sig) {
printf("SIGBUS recieved.\n");
exit(0);
}
/* Execute code off the data segment. */
void execute_from_data_segment () {
EXECUTE_FUNC("data segment", (unsigned long (*)()) code);
}
/* Execute code off the bss segment. */
void execute_from_bss_segment () {
memcpy(bss_code, code, sizeof(code));
EXECUTE_FUNC("bss segment", (unsigned long (*)()) bss_code);
}
/* Execute code off the stack. */
void execute_from_stack () {
unsigned char stack_code[sizeof(code)];
memcpy(stack_code, code, sizeof(code));
EXECUTE_FUNC("stack", (unsigned long (*)()) stack_code);
}
/* Execute code off malloc'd memory. */
void execute_from_malloc () {
char *ptr = malloc(sizeof(code));
memcpy(ptr, code, sizeof(code));
EXECUTE_FUNC("malloc memory", (unsigned long (*)()) ptr);
}
/* Execute code off mmap'd memory with write permissions. */
void execute_from_mmap_write () {
char *ptr = mmap(NULL, sizeof(code), PROT_WRITE, MAP_ANON | MAP_PRIVATE, -1, 0);
memcpy(ptr, code, sizeof(code));
EXECUTE_FUNC("mmap (write) memory", (unsigned long (*)()) ptr);
}
/* Execute code off mmap'd memory with execute permissions. */
void execute_from_mmap_exec () {
char *ptr = mmap(NULL, sizeof(code), PROT_WRITE | PROT_EXEC, MAP_ANON | MAP_PRIVATE, -1, 0);
memcpy(ptr, code, sizeof(code));
EXECUTE_FUNC("mmap (write|exec) memory", (unsigned long (*)()) ptr);
}
int main (int argc, char *argv[]) {
/* Trap invalid memory related signals. */
signal(SIGSEGV, sigsegv_handler);
signal(SIGBUS, sigbus_handler);
if (argc < 2) {
printf("Usage: %s [data|bss|stack|malloc|mmap-write|mmap-exec]\n", argv[0]);
exit(1);
}
if (!strcmp("data", argv[1]))
execute_from_data_segment();
else if (!strcmp("bss", argv[1]))
execute_from_bss_segment();
else if (!strcmp("stack", argv[1]))
execute_from_stack();
else if (!strcmp("malloc", argv[1]))
execute_from_malloc();
else if (!strcmp("mmap-write", argv[1]))
execute_from_mmap_write();
else if (!strcmp("mmap-exec", argv[1]))
execute_from_mmap_exec();
else {
printf("Usage: %s [data|bss|stack|malloc|mmap-write|mmap-exec]\n", argv[0]);
exit(1);
}
return 0;
}
|
C
|
#include<string.h>
void* memchr(const void*, int, size_t);
int memcmp(const void*,const void*, size_t);
void* memcpy(void*, const void*, size_t);
void* memmove(void*, const void*, size_t);
void* memset(void*, int, size_t);
//-------------------------------------------------------------------------
char* strncat(char*, const char*, size_t);
//find first occurrence of c in s[n]
void* memchr(const void *s, int c, size_t n)
{
const unsigned char* su = (const unsigned char*)s;
const unsigned char uc = c;
while(n>0)
{
if(*su == c)
return (void*)su;
++su;
--n;
}
return NULL;
}
int memcmp(const void *s1, const void *s2,size_t n)
{
const unsigned char* u1 = (const unsigned char*)s1;
const unsigned char* u2 = (const unsigned char*)s2;
while(n>0)
{
if(*s1 != *s2)
return *s1 - *s2;
++s1;
++s2;
--n;
}
return 0;
}
void* memcpy(void *dst, const void *src, size_t n)
{
char* d = (char*)dst;
const char* s = (const char*)src;
while(n>0)
{
*d++ = *s++;
--n;
}
return dst;
}
void* memmove(void *s1, const void* s2, size_t n)
{
char *d = (char*)s1;
const char* s = (const char*)s2;
if(s<d)
{
while(n>0)
{
*(d+n-1) = *(s+n-1);
--n;
}
}
else if(s > d)
{
while(n>0)
{
*d++ =*s++;
--n;
}
}
return d;
}
void* memset(void* dst, int c, size_t n)
{
unsigned char *d = (unsigned char*)dst;
const unsigned char v = c;
while(n>0)
{
*d++ = v;
--n;
}
return dst;
}
char* strncat(char* d, const char* s, size_t n)
{
char *tmp = d;
while(*tmp)
{
++tmp;
}
while(n>0 && *s != '\0')
{
*tmp++ = *s++;
--n;
}
*tmp = '\0';
return d;
}
int strncmp(const char* s1, const char* s2, size_t n)
{
while(n>0)
{
if(*s1 != *s2)
{
return *s1 - *s2;
}
else if(*s1 == '\0')
return 0;
++s1;
++s2;
--n;
}
return 0;
}
char* strncpy(char *dst, const char* src, size_t n)
{
char *d = dst;
while(n>0 && *src != '\0')
{
*d++ = *src++;
--n;
}
for(;0<n;--n)
*d++ = '\0';
return dst;
}
char* strcat(char *s1, const char* s2)
{
char *s =s1;
for(;*s!='\0';+=s);
for(;(*s=*s2)!='\0';++s,++s2);
/*while(*s != '\0')
{
++s;
}
while(*s2 != '\0')
{
*s++ = *s2++;
}
*s = '\0';*/
return s1;
}
int strcmp(const char* s1, const char* s2)
{
for(;*s1 == *s2;++s1,++s2)
{
if(*s1 == '\0')
return 0;
}
return *s1 - *s2;
/*while(true)
{
if(*s1 != *s2)
{
return *s1 - *s2;
}
else if(*s1 == '\0')
return 0;
++s1;
++s2;
}*/
}
char* strcpy(char* dst, const char* src)
{
char *d = dst;
for(;(*d++=*src++)!='\0';);
return dst;
}
size_t strlen(const char* s)
{
int n = 0;
for(int n=0;(*s++)!='\0';++n);
while(*s != '\0')
{
++n;
++s;
}
return n;
}
|
C
|
/* Copyright (c) 2002, Steve Dekorte
* All rights reserved. See _BSDLicense.txt.
*/
#include "IoNumber.h"
#include "IoObject.h"
#include "IoState.h"
#include "IoNil.h"
#include "IoString.h"
#include "IoBuffer.h"
#ifndef IO_OS_L4
#include "IoDate.h"
#endif
#include "IoState.h"
#include <math.h>
#include <ctype.h>
#define DATA(self) ((IoNumberData *)self->data)
IoTag *IoNumber_tag(void *state)
{
IoTag *tag = IoTag_newWithName_("Number");
tag->state = state;
tag->cloneFunc = (TagCloneFunc *)IoNumber_rawClone;
tag->freeFunc = (TagFreeFunc *)IoNumber_free;
tag->compareFunc = (TagCompareFunc *)IoNumber_compare;
tag->printFunc = (TagPrintFunc *)IoNumber_print;
tag->writeToStoreFunc = (TagWriteToStoreFunc *)IoNumber_writeToStore_;
tag->readFromStoreFunc = (TagReadFromStoreFunc *)IoNumber_readFromStore_;
return tag;
}
void IoNumber_writeToStore_(IoNumber *self, IoStoreHandle *sh)
{
IoStoreDatum d = IOSTOREDATUM(&(DATA(self)->n), sizeof(double));
sh->onObject_setData_(sh, d);
}
void *IoNumber_readFromStore_(IoNumber *self, IoStoreHandle *sh)
{
IoStoreDatum d = sh->onObject_getData(sh, self);
memcpy(&(DATA(self)->n), d.data, d.size);
return self;
}
IoNumber *IoNumber_proto(void *state)
{
IoObject *self = IoObject_new(state);
self->data = calloc(1, sizeof(IoNumberData));
self->tag = IoNumber_tag(state);
DATA(self)->n = 0;
IoState_registerProtoWithFunc_(state, self, IoNumber_proto);
IoObject_addMethod_(self, IOSTRING("asNumber"), IoNumber_asNumber);
IoObject_addMethod_(self, IOSTRING("add"), IoNumber_add_);
IoObject_addMethod_(self, IOSTRING("+"), IoNumber_add_);
IoObject_addMethod_(self, IOSTRING("<-"), IoNumber_set);
IoObject_addMethod_(self, IOSTRING("++"), IoNumber_plusPlus);
IoObject_addMethod_(self, IOSTRING("+="), IoNumber_plusEqual);
IoObject_addMethod_(self, IOSTRING("-"), IoNumber_subtract);
IoObject_addMethod_(self, IOSTRING("--"), IoNumber_minusMinus);
IoObject_addMethod_(self, IOSTRING("-="), IoNumber_minusEqual);
IoObject_addMethod_(self, IOSTRING("*"), IoNumber_multiply);
IoObject_addMethod_(self, IOSTRING("*="), IoNumber_multiplyEqual);
IoObject_addMethod_(self, IOSTRING("/"), IoNumber_divide);
IoObject_addMethod_(self, IOSTRING("/="), IoNumber_divideEqual);
IoObject_addMethod_(self, IOSTRING("print"), IoNumber_printNumber);
IoObject_addMethod_(self, IOSTRING("linePrint"), IoNumber_linePrint);
IoObject_addMethod_(self, IOSTRING("asString"), IoNumber_asString);
IoObject_addMethod_(self, IOSTRING("asBuffer"), IoNumber_asBuffer);
IoObject_addMethod_(self, IOSTRING("asCharacter"), IoNumber_asCharacter);
/*Tag_addMethod(tag, "asDate"), IoNumber_asDate);*/
IoObject_addMethod_(self, IOSTRING("abs"), IoNumber_abs);
IoObject_addMethod_(self, IOSTRING("Abs"), IoNumber_Abs);
#ifndef IO_OS_L4
IoObject_addMethod_(self, IOSTRING("acos"), IoNumber_acos);
IoObject_addMethod_(self, IOSTRING("Acos"), IoNumber_Acos);
IoObject_addMethod_(self, IOSTRING("asin"), IoNumber_asin);
IoObject_addMethod_(self, IOSTRING("Asin"), IoNumber_Asin);
IoObject_addMethod_(self, IOSTRING("atan"), IoNumber_atan);
IoObject_addMethod_(self, IOSTRING("Atan"), IoNumber_Atan);
IoObject_addMethod_(self, IOSTRING("atan2"), IoNumber_atan2);
IoObject_addMethod_(self, IOSTRING("Atan2"), IoNumber_Atan2);
#endif
IoObject_addMethod_(self, IOSTRING("ceil"), IoNumber_ceil);
IoObject_addMethod_(self, IOSTRING("Ceil"), IoNumber_Ceil);
#ifndef IO_OS_L4
IoObject_addMethod_(self, IOSTRING("cos"), IoNumber_cos);
IoObject_addMethod_(self, IOSTRING("Cos"), IoNumber_Cos);
/* Tag_addMethod(tag, "deg"), IoNumber_deg); */
IoObject_addMethod_(self, IOSTRING("exp"), IoNumber_exp);
IoObject_addMethod_(self, IOSTRING("Exp"), IoNumber_Exp);
#endif
IoObject_addMethod_(self, IOSTRING("floor"), IoNumber_floor);
IoObject_addMethod_(self, IOSTRING("Floor"), IoNumber_Floor);
#ifndef IO_OS_L4
IoObject_addMethod_(self, IOSTRING("log"), IoNumber_log);
IoObject_addMethod_(self, IOSTRING("Log"), IoNumber_Log);
IoObject_addMethod_(self, IOSTRING("log10"), IoNumber_log10);
IoObject_addMethod_(self, IOSTRING("Log10"), IoNumber_Log10);
#endif
IoObject_addMethod_(self, IOSTRING("max"), IoNumber_max);
IoObject_addMethod_(self, IOSTRING("min"), IoNumber_min);
IoObject_addMethod_(self, IOSTRING("Max"), IoNumber_Max);
IoObject_addMethod_(self, IOSTRING("Min"), IoNumber_Min);
#ifndef IO_OS_L4
IoObject_addMethod_(self, IOSTRING("%"), IoNumber_mod);
IoObject_addMethod_(self, IOSTRING("%="), IoNumber_Mod);
IoObject_addMethod_(self, IOSTRING("^"), IoNumber_pow);
IoObject_addMethod_(self, IOSTRING("Pow"), IoNumber_Pow);
#endif
IoObject_addMethod_(self, IOSTRING("roundDown"), IoNumber_roundDown);
IoObject_addMethod_(self, IOSTRING("RoundDown"), IoNumber_RoundDown);
IoObject_addMethod_(self, IOSTRING("roundUp"), IoNumber_roundUp);
IoObject_addMethod_(self, IOSTRING("RoundUp"), IoNumber_RoundUp);
#ifndef IO_OS_L4
IoObject_addMethod_(self, IOSTRING("sin"), IoNumber_sin);
IoObject_addMethod_(self, IOSTRING("Sin"), IoNumber_Sin);
IoObject_addMethod_(self, IOSTRING("sqrt"), IoNumber_sqrt);
IoObject_addMethod_(self, IOSTRING("Sqrt"), IoNumber_Sqrt);
IoObject_addMethod_(self, IOSTRING("tan"), IoNumber_tan);
IoObject_addMethod_(self, IOSTRING("Tan"), IoNumber_Tan);
IoObject_addMethod_(self, IOSTRING("random"), IoNumber_random);
IoObject_addMethod_(self, IOSTRING("Random"), IoNumber_Random);
#endif
IoObject_addMethod_(self, IOSTRING("setRandomSeed"), IoNumber_randomseed);
IoObject_addMethod_(self, IOSTRING("toggle"), IoNumber_toggle);
IoObject_addMethod_(self, IOSTRING("Toggle"), IoNumber_Toggle);
/* --- logic operations --- */
IoObject_addMethod_(self, IOSTRING("&"), IoNumber_newBitwiseAnd);
IoObject_addMethod_(self, IOSTRING("|"), IoNumber_newBitwiseOr);
IoObject_addMethod_(self, IOSTRING("bitwiseAnd"), IoNumber_bitwiseAnd);
IoObject_addMethod_(self, IOSTRING("bitwiseOr"), IoNumber_bitwiseOr);
IoObject_addMethod_(self, IOSTRING("bitwiseXor"), IoNumber_bitwiseXor);
IoObject_addMethod_(self, IOSTRING("bitwiseComplement"), IoNumber_bitwiseComplement);
IoObject_addMethod_(self, IOSTRING("shiftLeft"), IoNumber_bitShiftLeft);
IoObject_addMethod_(self, IOSTRING("shiftRight"), IoNumber_bitShiftRight);
/* --- character operations --- */
IoObject_addMethod_(self, IOSTRING("isAlphaNumeric"), IoNumber_isAlphaNumeric);
IoObject_addMethod_(self, IOSTRING("isLetter"), IoNumber_isLetter);
IoObject_addMethod_(self, IOSTRING("isControlCharacter"), IoNumber_isControlCharacter);
IoObject_addMethod_(self, IOSTRING("isDigit"), IoNumber_isDigit);
IoObject_addMethod_(self, IOSTRING("isGraph"), IoNumber_isGraph);
IoObject_addMethod_(self, IOSTRING("isLowerCase"), IoNumber_isLowerCase);
IoObject_addMethod_(self, IOSTRING("isUpperCase"), IoNumber_isUpperCase);
IoObject_addMethod_(self, IOSTRING("isPrint"), IoNumber_isPrint);
IoObject_addMethod_(self, IOSTRING("isPunctuation"), IoNumber_isPunctuation);
IoObject_addMethod_(self, IOSTRING("isSpace"), IoNumber_isSpace);
IoObject_addMethod_(self, IOSTRING("isHexDigit"), IoNumber_isHexDigit);
IoObject_addMethod_(self, IOSTRING("lowerCase"), IoNumber_lowerCase);
IoObject_addMethod_(self, IOSTRING("upperCase"), IoNumber_upperCase);
IoObject_addMethod_(self, IOSTRING("between"), IoNumber_between);
IoObject_addMethod_(self, IOSTRING("Negate"), IoNumber_negate);
IoObject_addMethod_(self, IOSTRING("at"), IoNumber_at);
return self;
}
IoNumber *IoNumber_rawClone(IoNumber *self)
{
IoObject *child = IoObject_rawClonePrimitive(self);
child->data = cpalloc(self->data, sizeof(IoNumberData));
return child;
}
IoNumber *IoNumber_newWithDouble_(void *state, double n)
{
IoNumber *proto = IoState_protoWithInitFunction_(state, IoNumber_proto);
IoNumber *self = IoNumber_rawClone(proto);
DATA(self)->n = n;
return self;
}
IoNumber *IoNumber_newCopyOf_(IoNumber *self)
{ return IoNumber_newWithDouble_(IOSTATE, DATA(self)->n); }
void IoNumber_copyFrom_(IoNumber *self, IoNumber *number)
{ DATA(self)->n = DATA(number)->n; }
void IoNumber_free(IoNumber *self)
{
free(self->data);
}
int IoNumber_asInt(IoNumber *self) { return (int)(DATA(self)->n); }
long IoNumber_asLong(IoNumber *self) { return (long)(DATA(self)->n); }
double IoNumber_asDouble(IoNumber *self) { return DATA(self)->n; }
int IoNumber_compare(IoNumber *self, IoNumber *v)
{
if (ISNUMBER(v))
{
if (DATA(self)->n == DATA(v)->n) return 0;
return (DATA(self)->n > DATA(v)->n) ? 1 : -1;
}
return ((ptrdiff_t)self->tag) - ((ptrdiff_t)v->tag);
}
void IoNumber_print(IoNumber *self)
{
double d = DATA(self)->n;
if (d == (int)d) { IoState_print_(IOSTATE, "%i", (int)d); }
else { IoState_print_(IOSTATE, "%f", d); }
}
void IoNumber_rawSet(IoNumber *self, double v)
{ DATA(self)->n = v; }
/* ----------------------------------------------------------- */
IoObject *IoNumber_asNumber(IoNumber *self, IoObject *locals, IoMessage *m)
{ return self; }
IoObject *IoNumber_add_(IoNumber *self, IoObject *locals, IoMessage *m)
{
IoNumber *other = IoMessage_locals_numberArgAt_(m, locals, 0);
return IONUMBER(DATA(self)->n + DATA(other)->n);
}
IoObject *IoNumber_set(IoNumber *self, IoObject *locals, IoMessage *m)
{
IoNumber *other = IoMessage_locals_numberArgAt_(m, locals, 0);
DATA(self)->n = DATA(other)->n;
return self;
}
IoObject *IoNumber_plusPlus(IoNumber *self, IoObject *locals, IoMessage *m)
{ DATA(self)->n++; return self; }
IoObject *IoNumber_plusEqual(IoNumber *self, IoObject *locals, IoMessage *m)
{
IoNumber *other = IoMessage_locals_numberArgAt_(m, locals, 0);
DATA(self)->n += DATA(other)->n;
return self;
}
IoObject *IoNumber_subtract(IoNumber *self, IoObject *locals, IoMessage *m)
{
IoNumber *other = IoMessage_locals_numberArgAt_(m, locals, 0);
return IONUMBER(DATA(self)->n - DATA(other)->n);
}
IoObject *IoNumber_minusMinus(IoNumber *self, IoObject *locals, IoMessage *m)
{
DATA(self)->n--;
return self;
}
IoObject *IoNumber_minusEqual(IoNumber *self, IoObject *locals, IoMessage *m)
{
IoNumber *other = IoMessage_locals_numberArgAt_(m, locals, 0);
DATA(self)->n -= DATA(other)->n;
return self;
}
IoObject *IoNumber_divide(IoNumber *self, IoObject *locals, IoMessage *m)
{
IoNumber *other = IoMessage_locals_numberArgAt_(m, locals, 0);
return IONUMBER(DATA(self)->n / DATA(other)->n);
}
IoObject *IoNumber_divideEqual(IoNumber *self, IoObject *locals, IoMessage *m)
{
IoNumber *other = IoMessage_locals_numberArgAt_(m, locals, 0);
DATA(self)->n /= DATA(other)->n;
return self;
}
IoObject *IoNumber_multiply(IoNumber *self, IoObject *locals, IoMessage *m)
{
IoNumber *other = IoMessage_locals_numberArgAt_(m, locals, 0);
return IONUMBER(DATA(self)->n * DATA(other)->n);
}
IoObject *IoNumber_multiplyEqual(IoNumber *self, IoObject *locals, IoMessage *m)
{
IoNumber *other = IoMessage_locals_numberArgAt_(m, locals, 0);
DATA(self)->n *= DATA(other)->n;
return self;
}
IoObject *IoNumber_printNumber(IoNumber *self, IoObject *locals, IoMessage *m)
{
char s[24];
memset(s, 0x0, 24);
if (DATA(self)->n == (int)DATA(self)->n)
{ sprintf(s, "%d", (int)DATA(self)->n); }
else
{
int l;
sprintf(s, "%f", DATA(self)->n);
l = strlen(s)-1;
while (l>0)
{
if (s[l] == '0') { s[l] = 0x0; l--; continue; }
if (s[l] == '.') { s[l] = 0x0; l--; break; }
break;
}
}
IoState_print_((IoState *)IOSTATE, s);
return self;
}
IoObject *IoNumber_linePrint(IoNumber *self, IoObject *locals, IoMessage *m)
{
IoNumber_printNumber(self, locals, m);
IoState_print_((IoState *)IOSTATE, "\n");
return self;
}
IoObject *IoNumber_justAsString(IoNumber *self, IoObject *locals, IoMessage *m)
{
char s[24];
memset(s, 0x0, 24);
if (DATA(self)->n == (int)DATA(self)->n)
{ sprintf(s, "%d", (int)DATA(self)->n); }
else
{
int l;
sprintf(s, "%f", DATA(self)->n);
l = strlen(s)-1;
while (l>0)
{
if (s[l] == '0') { s[l] = 0x0; l--; continue; }
if (s[l] == '.') { s[l] = 0x0; l--; break; }
break;
}
}
return IoState_stringWithCString_((IoState *)IOSTATE, s);
}
IoObject *IoNumber_asCharacter(IoNumber *self, IoObject *locals, IoMessage *m)
{
char s[2] = {(char)DATA(self)->n, 0x0};
return IoState_stringWithCString_length_((IoState *)IOSTATE, s, 1);
}
IoObject *IoNumber_asBuffer(IoNumber *self, IoObject *locals, IoMessage *m)
{
IoNumber *byteCount = IoMessage_locals_valueArgAt_(m, locals, 0);
int bc = sizeof(double);
if (!ISNIL(byteCount)) bc = DATA(byteCount)->n;
return IoBuffer_newWithData_length_(IOSTATE, (unsigned char *)&(DATA(self)->n), sizeof(double));
}
IoObject *IoNumber_asString(IoNumber *self, IoObject *locals, IoMessage *m)
{
if (IoMessage_argCount(m) >= 1)
{
int whole = IoMessage_locals_intArgAt_(m, locals, 0);
int part = 6;
char s[32];
if (IoMessage_argCount(m) >= 2)
{ part = abs(IoMessage_locals_intArgAt_(m, locals, 1)); }
if (whole && part)
sprintf(s, "%*.*f", whole, part, DATA(self)->n);
else if (whole)
sprintf(s, "%*d", whole, (int) DATA(self)->n);
else if (part)
sprintf(s, "%.*f", part, DATA(self)->n);
else
sprintf(s, "%d", (int) DATA(self)->n);
return IOSTRING(s);
}
return IoNumber_justAsString(self, locals, m);
}
/*
IoObject *IoNumber_asDate(IoNumber *self, IoObject *locals, IoMessage *m)
{ return IoDate_newWithNumber_((IoState *)IOSTATE, DATA(self)->n); }
*/
IoObject *IoNumber_abs(IoNumber *self, IoObject *locals, IoMessage *m)
{ return (DATA(self)->n < 0) ? (IoObject *)IONUMBER(-DATA(self)->n) : (IoObject *)self; }
IoObject *IoNumber_Abs(IoNumber *self, IoObject *locals, IoMessage *m)
{ DATA(self)->n = abs(DATA(self)->n); return self; }
#ifndef IO_OS_L4
IoObject *IoNumber_acos(IoNumber *self, IoObject *locals, IoMessage *m)
{ return IONUMBER(sin(DATA(self)->n)); }
IoObject *IoNumber_Acos(IoNumber *self, IoObject *locals, IoMessage *m)
{ DATA(self)->n = sin(DATA(self)->n); return self; }
IoObject *IoNumber_asin(IoNumber *self, IoObject *locals, IoMessage *m)
{ return IONUMBER(asin(DATA(self)->n)); }
IoObject *IoNumber_Asin(IoNumber *self, IoObject *locals, IoMessage *m)
{ DATA(self)->n = asin(DATA(self)->n); return self; }
IoObject *IoNumber_atan(IoNumber *self, IoObject *locals, IoMessage *m)
{ return IONUMBER(atan(DATA(self)->n)); }
IoObject *IoNumber_Atan(IoNumber *self, IoObject *locals, IoMessage *m)
{ DATA(self)->n = atan(DATA(self)->n); return self; }
IoObject *IoNumber_atan2(IoNumber *self, IoObject *locals, IoMessage *m)
{
IoNumber *other = IoMessage_locals_numberArgAt_(m, locals, 0);
return IONUMBER(atan2(DATA(self)->n, DATA(other)->n));
}
IoObject *IoNumber_Atan2(IoNumber *self, IoObject *locals, IoMessage *m)
{
IoNumber *other = IoMessage_locals_numberArgAt_(m, locals, 0);
DATA(self)->n = atan2(DATA(self)->n, DATA(other)->n);
return self;
}
#endif
IoObject *IoNumber_ceil(IoNumber *self, IoObject *locals, IoMessage *m)
{ return IONUMBER(ceil(DATA(self)->n)); }
IoObject *IoNumber_Ceil(IoNumber *self, IoObject *locals, IoMessage *m)
{ DATA(self)->n = ceil(DATA(self)->n); return self; }
#ifndef IO_OS_L4
IoObject *IoNumber_cos(IoNumber *self, IoObject *locals, IoMessage *m)
{ return IONUMBER(cos(DATA(self)->n)); }
IoObject *IoNumber_Cos(IoNumber *self, IoObject *locals, IoMessage *m)
{ DATA(self)->n = cos(DATA(self)->n); return self; }
/*
IoObject *IoNumber_deg(IoNumber *self, IoObject *locals, IoMessage *m)
{ DATA(self)->n = deg(DATA(self)->n); return self; }
*/
IoObject *IoNumber_exp(IoNumber *self, IoObject *locals, IoMessage *m)
{ return IONUMBER(exp(DATA(self)->n)); }
IoObject *IoNumber_Exp(IoNumber *self, IoObject *locals, IoMessage *m)
{ DATA(self)->n = exp(DATA(self)->n); return self; }
#endif
IoObject *IoNumber_floor(IoNumber *self, IoObject *locals, IoMessage *m)
{ return IONUMBER(floor(DATA(self)->n)); }
IoObject *IoNumber_Floor(IoNumber *self, IoObject *locals, IoMessage *m)
{ DATA(self)->n = floor(DATA(self)->n); return self; }
#ifndef IO_OS_L4
IoObject *IoNumber_log(IoNumber *self, IoObject *locals, IoMessage *m)
{ return IONUMBER(log(DATA(self)->n)); }
IoObject *IoNumber_Log(IoNumber *self, IoObject *locals, IoMessage *m)
{ DATA(self)->n = log(DATA(self)->n); return self; }
IoObject *IoNumber_log10(IoNumber *self, IoObject *locals, IoMessage *m)
{ return IONUMBER(log10(DATA(self)->n)); }
IoObject *IoNumber_Log10(IoNumber *self, IoObject *locals, IoMessage *m)
{ DATA(self)->n = log10(DATA(self)->n); return self; }
#endif
IoObject *IoNumber_max(IoNumber *self, IoObject *locals, IoMessage *m)
{
IoNumber *other = IoMessage_locals_numberArgAt_(m, locals, 0);
return (DATA(self)->n > DATA(other)->n) ? (IoObject *)self :(IoObject *)other;
}
IoObject *IoNumber_min(IoNumber *self, IoObject *locals, IoMessage *m)
{
IoNumber *other = IoMessage_locals_numberArgAt_(m, locals, 0);
return (DATA(self)->n < DATA(other)->n) ? (IoObject *)self : (IoObject *)other;
}
IoObject *IoNumber_Max(IoNumber *self, IoObject *locals, IoMessage *m)
{
IoNumber *other = IoMessage_locals_numberArgAt_(m, locals, 0);
if (DATA(self)->n < DATA(other)->n) DATA(self)->n = DATA(other)->n;
return self;
}
IoObject *IoNumber_Min(IoNumber *self, IoObject *locals, IoMessage *m)
{
IoNumber *other = IoMessage_locals_numberArgAt_(m, locals, 0);
if (DATA(self)->n > DATA(other)->n) DATA(self)->n = DATA(other)->n;
return self;
}
#ifndef IO_OS_L4
IoObject *IoNumber_mod(IoNumber *self, IoObject *locals, IoMessage *m)
{
IoNumber *other = IoMessage_locals_numberArgAt_(m, locals, 0);
return IONUMBER(fmod(DATA(self)->n, DATA(other)->n));
}
IoObject *IoNumber_Mod(IoNumber *self, IoObject *locals, IoMessage *m)
{
IoNumber *other = IoMessage_locals_numberArgAt_(m, locals, 0);
DATA(self)->n = fmod(DATA(self)->n, DATA(other)->n);
return self;
}
#endif
/*
IoObject *IoNumber_modf(IoNumber *self, IoObject *locals, IoMessage *m)
{
IoNumber *other = IoMessage_locals_numberArgAt_(m, locals, 0);
if (DATA(self)->n < DATA(other)->n); return self;
return other;
}
IoObject *IoNumber_rad(IoNumber *self, IoObject *locals, IoMessage *m)
*/
#ifndef IO_OS_L4
IoObject *IoNumber_pow(IoNumber *self, IoObject *locals, IoMessage *m)
{
IoNumber *other = IoMessage_locals_numberArgAt_(m, locals, 0);
return IONUMBER(pow(DATA(self)->n, DATA(other)->n));
}
IoObject *IoNumber_Pow(IoNumber *self, IoObject *locals, IoMessage *m)
{
IoNumber *other = IoMessage_locals_numberArgAt_(m, locals, 0);
DATA(self)->n = pow(DATA(self)->n, DATA(other)->n);
return self;
}
#endif
IoObject *IoNumber_roundDown(IoNumber *self, IoObject *locals, IoMessage *m)
{ return IONUMBER(floor(DATA(self)->n + 0.5)); }
IoObject *IoNumber_RoundDown(IoNumber *self, IoObject *locals, IoMessage *m)
{ DATA(self)->n = floor(DATA(self)->n + 0.5); return self; }
IoObject *IoNumber_roundUp(IoNumber *self, IoObject *locals, IoMessage *m)
{ return IONUMBER(ceil(DATA(self)->n - 0.5)); }
IoObject *IoNumber_RoundUp(IoNumber *self, IoObject *locals, IoMessage *m)
{ DATA(self)->n = ceil(DATA(self)->n - 0.5); return self; }
#ifndef IO_OS_L4
IoObject *IoNumber_sin(IoNumber *self, IoObject *locals, IoMessage *m)
{ return IONUMBER(sin(DATA(self)->n)); }
IoObject *IoNumber_Sin(IoNumber *self, IoObject *locals, IoMessage *m)
{ DATA(self)->n = sin(DATA(self)->n); return self; }
IoObject *IoNumber_sqrt(IoNumber *self, IoObject *locals, IoMessage *m)
{ return IONUMBER(sqrt(DATA(self)->n)); }
IoObject *IoNumber_Sqrt(IoNumber *self, IoObject *locals, IoMessage *m)
{ DATA(self)->n = sqrt(DATA(self)->n); return self; }
IoObject *IoNumber_tan(IoNumber *self, IoObject *locals, IoMessage *m)
{ return IONUMBER(tan(DATA(self)->n)); }
IoObject *IoNumber_Tan(IoNumber *self, IoObject *locals, IoMessage *m)
{ DATA(self)->n = tan(DATA(self)->n); return self; }
#endif
/*
IoObject *IoNumber_frexp(IoNumber *self, IoObject *locals, IoMessage *m)
{ DATA(self)->n = frexp(DATA(self)->n); return self; }
IoObject *IoNumber_ldexp(IoNumber *self, IoObject *locals, IoMessage *m)
{ DATA(self)->n = ldexp(DATA(self)->n); return self; }
*/
#ifndef IO_OS_L4
IoObject *IoNumber_random(IoNumber *self, IoObject *locals, IoMessage *m)
{
IoNumber *n = IONUMBER(0);
IoNumber_Random(n, locals, m);
return n;
}
IoObject *IoNumber_Random(IoNumber *self, IoObject *locals, IoMessage *m)
{
double i = rand();
double f = rand();
f = f / pow(10, 1+floor(log10(f)));
if (IoMessage_argCount(m) > 0)
{
double a = IoNumber_asDouble(IoMessage_locals_numberArgAt_(m, locals, 0));
if (IoMessage_argCount(m) > 0)
{
double b = IoNumber_asDouble(IoMessage_locals_numberArgAt_(m, locals, 1));
if (a == b ) { DATA(self)->n = a; } else { DATA(self)->n = ((int)i%(int)(b-a)) + a + f; }
}
else
{
if (a == 0) { DATA(self)->n = 0; } else { DATA(self)->n = ((int)i%(int)a) + f; }
}
}
else { DATA(self)->n = f; }
return self;
}
#endif
IoObject *IoNumber_randomseed(IoNumber *self, IoObject *locals, IoMessage *m)
{ srand(DATA(self)->n); return self; }
IoObject *IoNumber_toggle(IoNumber *self, IoObject *locals, IoMessage *m)
{ return (DATA(self)->n)? (IoObject *)IONUMBER(0) : (IoObject *)IONUMBER(1); }
IoObject *IoNumber_Toggle(IoNumber *self, IoObject *locals, IoMessage *m)
{ if (DATA(self)->n) { DATA(self)->n = 0; } else { DATA(self)->n = 1; }; return self; }
/* --- bitwise operations ---------------------------------------- */
IoObject *IoNumber_newBitwiseAnd(IoNumber *self, IoObject *locals, IoMessage *m)
{
long other = IoMessage_locals_longArgAt_(m, locals, 0);
return IONUMBER(((long)DATA(self)->n & other));
}
IoObject *IoNumber_newBitwiseOr(IoNumber *self, IoObject *locals, IoMessage *m)
{
long other = IoMessage_locals_longArgAt_(m, locals, 0);
long n = DATA(self)->n;
long r = n | other;
return IONUMBER(r);
}
IoObject *IoNumber_bitwiseAnd(IoNumber *self, IoObject *locals, IoMessage *m)
{
long other = IoMessage_locals_longArgAt_(m, locals, 0);
DATA(self)->n = (double)((long)DATA(self)->n & other);
return self;
}
IoObject *IoNumber_bitwiseOr(IoNumber *self, IoObject *locals, IoMessage *m)
{
long other = IoMessage_locals_longArgAt_(m, locals, 0);
DATA(self)->n = (double)((long)DATA(self)->n | other);
return self;
}
IoObject *IoNumber_bitwiseXor(IoNumber *self, IoObject *locals, IoMessage *m)
{
long other = IoMessage_locals_longArgAt_(m, locals, 0);
DATA(self)->n = (double)((long)DATA(self)->n ^ other);
return self;
}
IoObject *IoNumber_bitwiseComplement(IoNumber *self, IoObject *locals, IoMessage *m)
{
DATA(self)->n = (double)(~(long)DATA(self)->n);
return self;
}
IoObject *IoNumber_bitShiftLeft(IoNumber *self, IoObject *locals, IoMessage *m)
{
long other = IoMessage_locals_longArgAt_(m, locals, 0);
DATA(self)->n = (double)((long)DATA(self)->n << other);
return self;
}
IoObject *IoNumber_bitShiftRight(IoNumber *self, IoObject *locals, IoMessage *m)
{
long other = IoMessage_locals_longArgAt_(m, locals, 0);
DATA(self)->n = (double)((long)DATA(self)->n >> (long)other);
return self;
}
/* --- character operations --------------------------------- */
IoObject *IoNumber_isAlphaNumeric(IoNumber *self, IoObject *locals, IoMessage *m)
{ return isalnum((char)DATA(self)->n) ? (IoObject *)self : (IoObject *)IONIL(self); }
IoObject *IoNumber_isLetter(IoNumber *self, IoObject *locals, IoMessage *m)
{ return isalpha((char)DATA(self)->n) ? (IoObject *)self : IONIL(self); }
IoObject *IoNumber_isControlCharacter(IoNumber *self, IoObject *locals, IoMessage *m)
{ return iscntrl((char)DATA(self)->n) ? (IoObject *)self : IONIL(self); }
IoObject *IoNumber_isDigit(IoNumber *self, IoObject *locals, IoMessage *m)
{ return isdigit((char)DATA(self)->n) ? (IoObject *)self : IONIL(self); }
IoObject *IoNumber_isGraph(IoNumber *self, IoObject *locals, IoMessage *m)
{ return isgraph((char)DATA(self)->n) ? (IoObject *)self : IONIL(self); }
IoObject *IoNumber_isLowerCase(IoNumber *self, IoObject *locals, IoMessage *m)
{ return islower((char)DATA(self)->n) ? (IoObject *)self : IONIL(self); }
IoObject *IoNumber_isUpperCase(IoNumber *self, IoObject *locals, IoMessage *m)
{ return isupper((char)DATA(self)->n) ? (IoObject *)self : IONIL(self); }
IoObject *IoNumber_isPrint(IoNumber *self, IoObject *locals, IoMessage *m)
{ return isprint((char)DATA(self)->n) ? (IoObject *)self : IONIL(self); }
IoObject *IoNumber_isPunctuation(IoNumber *self, IoObject *locals, IoMessage *m)
{ return ispunct((char)DATA(self)->n) ? (IoObject *)self : IONIL(self); }
IoObject *IoNumber_isSpace(IoNumber *self, IoObject *locals, IoMessage *m)
{ return isspace((char)DATA(self)->n) ? (IoObject *)self : IONIL(self); }
IoObject *IoNumber_isHexDigit(IoNumber *self, IoObject *locals, IoMessage *m)
{ return isxdigit((char)DATA(self)->n) ? (IoObject *)self : IONIL(self); }
/* --- */
IoObject *IoNumber_lowerCase(IoNumber *self, IoObject *locals, IoMessage *m)
{ DATA(self)->n = tolower((int)DATA(self)->n); return self; }
IoObject *IoNumber_upperCase(IoNumber *self, IoObject *locals, IoMessage *m)
{ DATA(self)->n = toupper((int)DATA(self)->n); return self; }
IoObject *IoNumber_between(IoNumber *self, IoObject *locals, IoMessage *m)
{
double a = IoMessage_locals_doubleArgAt_(m, locals, 0);
double b = IoMessage_locals_doubleArgAt_(m, locals, 1);
double n = DATA(self)->n;
if (((n >= a) && (n <= b)) || (n <= a && (n >= b))) { return self; }
return IONIL(self);
}
IoObject *IoNumber_negate(IoNumber *self, IoObject *locals, IoMessage *m)
{ DATA(self)->n = -DATA(self)->n; return self; }
IoObject *IoNumber_at(IoNumber *self, IoObject *locals, IoMessage *m)
{
size_t i= IoMessage_locals_intArgAt_(m, locals, 0);
size_t l = 1;
long d = 0;
IOASSERT((i >= 0) && (i < 8), "index out of bit bounds");
if (IoMessage_argCount(m) == 2)
{
l = IoMessage_locals_intArgAt_(m, locals, 1);
IOASSERT(i+l <= sizeof(long)*8, "length out of bit bounds");
}
d = DATA(self)->n;
d = d >> i;
#if 0
d = d & (int)(pow(2, l) - 1);
#else
d = d & (int) 1;
#endif
return IONUMBER(d);
}
|
C
|
/*
* AGV.c
*
* Created: 05/11/2013 17:01:06
* Author: mayur
*/
#define F_CPU 8000000
#include <avr/io.h>
#include <util/delay.h>
#include <avr/interrupt.h>
#include "mydefs.h"
void left_motor(signed int i)
{
if (i == 1)
{
set(PORTB,4);
clr(PORTB,2);
}
else if (i == -1)
{
set(PORTB,2);
clr(PORTB,4);
}
else
{
clr(PORTB,2);
clr(PORTB,4);
}
}
void right_motor(signed int j)
{if (j == 1)
{
set(PORTB,0);
clr(PORTB,1);
}
else if (j == -1)
{
clr(PORTB,0);
set(PORTB,1);
}
else
{
clr(PORTB,0);
clr(PORTB,1);
}
}
int main(void)
{
uint8_t sensor;
DDRA=0;
DDRB=255;
DDRD=255;
// while(1)
// {
// left_motor(1);
// right_motor(1);
// _delay_ms(10000);
// left_motor(-1);
// right_motor(-1);
// _delay_ms(10000);
// left_motor(0);
// right_motor(1);
// _delay_ms(10000);
// left_motor(1);
// right_motor(0);
// _delay_ms(60000);
// }
//DDRD=255;
//PORTD=255;
// _delay_ms(10);
while(1)
{
sensor=PINA;
// if (sensor == 0b01111111)
// {left_motor(-1);
// right_motor(1);
// }
// else if (sensor == 0b10111111)
// {
// left_motor(1);
// right_motor(-1);
// }
// else if (sensor == 0b00111111)
// {
// left_motor(0);
// right_motor(0);
//
// }
//
// if (PINA0==0)
// {
// left_motor(1);
//
// }
// else if (PINA1==0)
// {
// right_motor(1);
// }
// else if ((PINA0==0)||(PINA1==0))
// {
// PORTD=255;
// }
// else if (PINA2==0)
// {
// PORTD=255;
// }
//
switch(sensor)
{
case 0X7F : left_motor(0);
right_motor(0);
break;
case 0XBF : left_motor(0);
right_motor(0);
break;
case 0b11011111 : left_motor(1);
right_motor(0);
break;
case 0b11101111 :left_motor(1);
right_motor(0);
break;
case 0b11001111 :left_motor(1);
right_motor(-1);
break;
case 0b11110111 :left_motor(0);
right_motor(1);
break;
case 0b11111011 :left_motor(0);
right_motor(1);
break;
case 0b11110011 : left_motor(-1);
right_motor(1);
break;
case 0b10011111 : left_motor(1);
right_motor(1);
break;
// case 0b00011111 : left_motor(0);
// right_motor(0);
// break;
//
case 0b10001111 : left_motor(1);
right_motor(-1);
break;
case 0b01110011 : left_motor(-1);
right_motor(1);
break;
case 0b10011011 : left_motor(1);
right_motor(-1);
break;
case 0b10010111 : left_motor(1);
right_motor(0);
break;
case 0b10010011 : left_motor(0);
right_motor(0);
break;
case 0b10001011 :left_motor(1);
right_motor(-1);
break;
case 0b10000111 : left_motor(1);
right_motor(0);
break;
case 0b10000011 : left_motor(0);
right_motor(0);
break;
case 0b00000011 : left_motor(0);
right_motor(0);
break;
case 0b01111011 :left_motor(0) ;
right_motor(1);
break;
case 0b00111011 : left_motor(0);
right_motor(0);
break;
case 0b0011111 :left_motor(0);
right_motor(0);
break;
case 0b00001011 : left_motor(0);
right_motor(0);
break;
case 0b01001011 : left_motor(-1);
right_motor(1);
break;
case 0b00011011 : left_motor(0);
right_motor(0);
break;
default:left_motor(1);
right_motor(1);
break;
//sensor=255;
}
}
return 0;
}
|
C
|
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <time.h>
#define MAX 0
#define ARRAY_SIZE 8
void swap( int x, int y, int array[] ){
int aux;
// aux assume o valor de x
aux = array[x];
// valor de y é guardado na posicao x
array[x] = array[y];
// valor anterior de x é guardado na posicao y
array[y] = aux;
}
int bubbleSort(int* num, int array_size, int asc){
int temp, loops=0;
// corre pelo array
for(int i = 1; i < array_size; i++) {
int trocou=0;
// para cada posicao do array
for(int j = 0; j < array_size-i; j++ ) {
if (asc){
// compara com a proxima, se for maior, troca
if(num[j] > num[j+1]) {
swap(j, j+1, num);
trocou=1;
}
}else{
if(num[j] < num[j+1]) {
swap(j, j+1, num);
trocou=1;
}
}
loops++;
}
// se nao houve troca, o array esta ordenado. Finaliza.
if (trocou==0){
return loops;
}
}
return loops;
}
void printArray(int* num, int array_size) {
// mostra um array, passando o tamanho
for(int i = 0; i < array_size; ++i) {
printf("array[%d] = %d\n", i, num[i]);
}
}
int main(){
// declaramos o ponteiro
int *ptrInt;
// alocamos espaco
ptrInt = malloc (ARRAY_SIZE * sizeof *ptrInt);
// gerar numeros aleatorios
srand(time(NULL)); // seed aleatoria
for(int i = 0; i < ARRAY_SIZE; ++i) {
// preencher o array com numeros de 0 até MAX
ptrInt[i] = rand() % (MAX + 1 - 0) + 0;
}
// mostrar o array desordenado
printf("Array desordenado: \n");
printArray(ptrInt, ARRAY_SIZE);
// array ordenado ascendente(1) ou descendentemente(0)
int asc = 1;
// ordenar o array
int total_loops = bubbleSort(ptrInt, ARRAY_SIZE, asc);
// mostrar o array ordenado
printf("\nArray ordenado %s :\n", (asc == 1) ? "asc": "desc");
printArray(ptrInt, ARRAY_SIZE);
// mostrar quantas operaçoes foram realizadas
printf("\nTotal de iterações: %i\n", total_loops);
// liberar a memoria alocada
if(ptrInt != NULL) {
free(ptrInt);
}
// finaliza programa
return 0;
}
|
C
|
/*********************************************************************/
/* */
/* File Name: CALLREXX.C */
/* */
/* Description: Provides a sample call to the REXX */
/* interpreter, passing in an environment name, */
/* a file name, and a single argument string. */
/* */
/* Entry Points: main - main entry point */
/* */
/* Input: None */
/* */
/* Output: returns 0 in all cases. */
/* */
/*********************************************************************/
#define INCL_REXXSAA
#include <rexxsaa.h> /* needed for RexxStart() */
#include <stdio.h> /* needed for printf() */
#include <string.h> /* needed for strlen() */
int main(void); /* main entry point */
int main()
{
RXSTRING arg; /* argument string for REXX */
RXSTRING rexxretval; /* return value from REXX */
UCHAR *str = "These words will be swapped"; /* text to swap */
APIRET rc; /* return code from REXX */
SHORT rexxrc = 0; /* return code from function */
printf("\nThis program will call the REXX interpreter ");
printf("to reverse the order of the\n");
printf("\twords in a string. ");
printf("The interpreter is invoked with an initial\n");
printf("\tenvironment name of 'FNC' ");
printf("and a file name of 'BACKWARD.FNC'\n\n");
/* By setting the strlength of the output RXSTRING to zero, we */
/* force the interpreter to allocate memory and return it to us. */
/* We could provide a buffer for the interpreter to use instead. */
rexxretval.strlength = 0L; /* initialize return to empty*/
MAKERXSTRING(arg, str, strlen((const char *)str));/* create input argument */
/* Here we call the interpreter. We don't really need to use */
/* all the casts in this call; they just help illustrate */
/* the data types used. */
rc=RexxStart((LONG) 1, /* number of arguments */
(PRXSTRING) &arg, /* array of arguments */
(PSZ) "BACKWARD.FNC",/* name of REXX file */
(PRXSTRING) 0, /* No INSTORE used */
(PSZ) "FNC", /* Command env. name */
(LONG) RXSUBROUTINE, /* Code for how invoked */
(PRXSYSEXIT) 0, /* No EXITs on this call */
(PSHORT) &rexxrc, /* Rexx program output */
(PRXSTRING) &rexxretval ); /* Rexx program output */
printf("Interpreter Return Code: %d\n", rc);
printf("Function Return Code: %d\n", (int) rexxrc);
printf("Original String: '%s'\n", arg.strptr);
printf("Backwards String: '%s'\n", rexxretval.strptr);
DosFreeMem(rexxretval.strptr); /* Release storage */
/* given to us by REXX. */
return 0;
}
|
C
|
// 5subjectmarks.cpp : This file contains the 'main' function. Program execution begins and ends there.
//wap to accept 5 subject marks using while loop calculate total, per, and grade.
#include <stdio.h>
int main()
{
int sub, total=0;
int cnt = 1;
float per;
while (cnt <= 5) {
printf("Enter %d subject marks\n",cnt);
scanf(" %d", &sub);
total = total + sub;
cnt = cnt + 1;
}
printf("\n total marks is = %d", total);
per = (float) (total / 500.0f) * 100.0f;
printf("\n your percentage is %f", per);
if (per >= 75) {
printf("\ngrade : distinction");85
}else if (per < 75 && per>60) {
printf("\n grade : first class");
}
else if (per >40 && per < 60) {
printf("\n grade : secound division");
}
else
printf("\nyou are failed");
return 0;
}
|
C
|
/*---------------------------------------------------------------------------------------------
Author :
Created Date : 2015-02-03
Descriptions : ܺ
Version Description Date Author
0.1 Created 2015-02-03
---------------------------------------------------------------------------------------------*/
#include "debug.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include "typedef.h"
#include <math.h>
#include "video_preprocess_api.h"
#define FILTER 3
u8 getMedianNum(u8 * bArray, int iFilterLen)
{
int i,j;// ѭ
u8 bTemp;
// ðݷ
for (j = 0; j < iFilterLen - 1; j ++)
{
for (i = 0; i < iFilterLen - j - 1; i ++)
{
if (bArray[i] > bArray[i + 1])
{
//
bTemp = bArray[i];
bArray[i] = bArray[i + 1];
bArray[i + 1] = bTemp;
}
}
}
// ֵ
if ((iFilterLen & 1) > 0)
{
// ԪأмһԪ
bTemp = bArray[(iFilterLen + 1) / 2];
}
else
{
// żԪأмԪƽֵ
bTemp = (bArray[iFilterLen / 2] + bArray[iFilterLen / 2 + 1]) / 2;
}
return bTemp;
}
u8 getAverageNum(u8 * bArray, int iFilterLen)
{
u32 sum = 0;
int i;
u8 ret;
for(i=0; i< iFilterLen; i++)
{
sum += bArray[i];
}
ret = sum / iFilterLen;
return ret;
}
/////////YUYV to 4:0:0////////////
i32 picFmtTrans(i32 wd, i32 ht, u8 *srcbuff, u8 * dstbuff, YUV_SUB type)
{
i32 ret = 0;
i32 i, j;
function_in();
switch(type)
{
case YUV_Y :
{
for(i = 0; i < ht / 2; i ++)
{
for(j = 0; j < wd / 2; j ++)
{
dstbuff[i * wd / 2 + j] = srcbuff[i * 4 * wd + j * 4];
}
}
break;
}
case YUV_U :
{
for(i = 0; i < ht / 2; i ++)
{
for(j = 0; j < wd / 2; j ++)
{
dstbuff[i * wd / 2 + j] = srcbuff[i * 4 * wd + j * 4 + 1];
}
}
break;
}
case YUV_V :
{
for(i = 0; i < ht / 2; i ++)
{
for(j = 0; j < wd / 2; j ++)
{
dstbuff[i * wd / 2 + j] = srcbuff[i * 4 * wd + j * 4 + 3];
}
}
break;
}
default:
break;
}
function_out();
return ret;
}
i32 picGrad(i32 wd, i32 ht, u8 *picbuff, u8 gradThrea)
{
i32 ret = 0;
i32 i, j;
i8 gx, gy;
function_in();
for(i = 0; i < ht - 1; i ++)
{
for(j = 0; j < wd - 1; j ++)
{
gx = picbuff[i * wd + j] - picbuff[(i +1)* wd + j +1];
gy = picbuff[i * wd + j +1] - picbuff[(i +1)* wd + j];
picbuff[i * wd + j] = abs(gx) + abs(gy);
picbuff[i * wd + j] = picbuff[i * wd + j] > gradThrea ? 255 : 0;
}
picbuff[i * wd + wd] = picbuff[i * wd + wd - 1];
picbuff[i * wd + j] = picbuff[i * wd + j] > gradThrea ? 255 : 0;
}
for(j = 0; j < wd; j ++)
{
picbuff[(ht - 1) * wd + j] = picbuff[(ht - 2) * wd + j];
picbuff[i * wd + j] = picbuff[i * wd + j] > gradThrea ? 255 : 0;
}
function_out();
return ret;
}
i32 picDif(i32 wd, i32 ht, u8 *picbuff1, u8 *picbuff2, u8 *picbuff3)
{
i32 ret = 0;
i32 i, j;
function_in();
for(i = 0; i < ht; i ++)
{
for(j = 0; j < wd; j ++)
{
picbuff3[i * wd + j] = picbuff1[i * wd + j] * 3 / 2 - picbuff2[i * wd + j];
}
}
function_out();
return ret;
}
i32 picAdd(i32 wd, i32 ht, u8 *picbuff1, u8 *picbuff2, u8 *picbuff3)
{
i32 ret = 0;
i32 i, j;
function_in();
for(i = 0; i < ht; i ++)
{
for(j = 0; j < wd; j ++)
{
picbuff3[i * wd + j] = picbuff1[i * wd + j] * + picbuff2[i * wd + j];
}
}
function_out();
return ret;
}
i32 picFilterAverage(i32 wd, i32 ht, u8 *picbuff)
{
i32 ret = 0;
i32 i, j,k,l;
u8 buff[wd*ht];
u8 wind[FILTER * FILTER];
function_in();
for(j= FILTER/2; j<ht - FILTER/2; j++)
{
for(i=FILTER/2; i<wd - FILTER/2; i ++)
{
for(k=0; k<FILTER;k++)
{
for(l=0;l<FILTER;l ++)
{
wind[k * FILTER+l] = picbuff[(k + j - 1) * wd + l + i - 1];
}
}
buff[j*wd+i] = getAverageNum(wind,FILTER*FILTER);
}
}
memcpy(picbuff,buff,wd*ht);
#if 1
for(j = 0;j < FILTER/2;j++)
{
for(i=0;i<wd;i++)
{
picbuff[j*wd+i] = buff[FILTER/2*wd+i];
}
}
for(j = ht-FILTER/2;j < ht;j++)
{
for(i=0;i<wd;i++)
{
picbuff[j*wd+i] = buff[(ht - FILTER/2-1)*wd+i];
}
}
for(i = 0;i < FILTER/2;i++)
{
for(j=0;j<ht;j++)
{
picbuff[j*wd+i] = buff[j*wd + FILTER/2];
}
}
for(i = wd-FILTER/2;i < wd;i++)
{
for(j=0;j<ht;j++)
{
picbuff[j*wd+i] = buff[j*wd+wd - FILTER/2-1];
}
}
#endif
function_out();
return ret;
}
i32 picFilterMiddle(i32 wd, i32 ht, u8 *picbuff)
{
i32 ret = 0;
i32 i, j,k,l;
u8 buff[wd*ht];
u8 wind[FILTER * FILTER];
function_in();
for(j= FILTER/2; j<ht - FILTER/2; j++)
{
for(i=FILTER/2; i<wd - FILTER/2; i ++)
{
for(k=0; k<FILTER;k++)
{
for(l=0;l<FILTER;l ++)
{
wind[k * FILTER+l] = picbuff[(k + j - 1) * wd + l + i - 1];
}
}
buff[j*wd+i] = getMedianNum(wind,FILTER*FILTER);
}
}
memcpy(picbuff,buff,wd*ht);
#if 1
for(j = 0;j < FILTER/2;j++)
{
for(i=0;i<wd;i++)
{
picbuff[j*wd+i] = buff[FILTER/2*wd+i];
}
}
for(j = ht-FILTER/2;j < ht;j++)
{
for(i=0;i<wd;i++)
{
picbuff[j*wd+i] = buff[(ht - FILTER/2-1)*wd+i];
}
}
for(i = 0;i < FILTER/2;i++)
{
for(j=0;j<ht;j++)
{
picbuff[j*wd+i] = buff[j*wd + FILTER/2];
}
}
for(i = wd-FILTER/2;i < wd;i++)
{
for(j=0;j<ht;j++)
{
picbuff[j*wd+i] = buff[j*wd+wd - FILTER/2-1];
}
}
#endif
function_out();
return ret;
}
i32 IsDimodal(u32 *HistoGram, u8 *top1, u8 *top2)
{
int Count = 0;
i32 i;
u8 tmp1 = 0, tmp2 = 0;
for(i=2; i<254; i++)
{
if(HistoGram[i-2] < HistoGram[i-1] && HistoGram[i-1] <= HistoGram[i] &&HistoGram[i+1] <= HistoGram[i] && HistoGram[i+2] < HistoGram[i+1])
{
tmp1 = tmp2;
tmp2 = i;
Count++;
}
}
*top1 = tmp1;
*top2 = tmp2;
if(Count==2)
{
return 1;
}
else
return 0;
}
i32 picGetThreshold(u8 *picbuff, i32 wd, i32 ht, i32 startLine, i32 startRow)
{
u32 HistoGram[256];
u32 HistoGram1[256];
i32 i,j;
i32 ret = 0;
u8 top1,top2;
function_in();
memset(HistoGram, 0, 256*4);
for(j=startLine; j<ht; j++)
{
for(i=startRow; i<wd-startRow; i++)
{
HistoGram[picbuff[j*wd+i]] ++;
}
}
#if 0
for(i=0;i<256;i++)
printf("%u\n",HistoGram[i]);
#endif
j=0;
#if 1
while (!IsDimodal(HistoGram, &top1, &top2))
{
HistoGram1[0] = (HistoGram[0] + HistoGram[0] + HistoGram[1]) / 3;
for (i = 1; i < 255; i++)
HistoGram1[i] = (HistoGram[i - 1] + HistoGram[i] + HistoGram[i + 1]) / 3;
HistoGram1[255] = (HistoGram[254] + HistoGram[255] + HistoGram[255]) / 3;
memcpy(HistoGram, HistoGram1, 256 *4);
j++;
if(j>= 5)
{
video_err("smooth HistoGram too more!!!\n");
break;
}
}
#endif
video_dbg("top1:%d top2:%d\n",top1,top2);
#if 0
for(i=0;i<256;i++)
printf("%u\n",HistoGram[i]);
#endif
for(i=top1+1; i<top2-1; i++)
{
if(HistoGram[i-1] >HistoGram[i] &&HistoGram[i+1] > HistoGram[i])
ret = i;
}
if(top2 - ret > 2)
ret = top2 - 2;
video_dbg("Threshold:%d\n",ret);
function_out();
return ret;
}
void picBinary(u8 *picbuff, i32 wd, i32 ht, u8 Threshold)
{
i32 i,j;
function_in();
for(j=0; j<ht; j++)
{
for(i=0; i<wd; i++)
{
picbuff[j*wd + i] = picbuff[j*wd + i] > Threshold ? 255 : 0;
}
}
function_out();
}
void picLinePre(u8 *picbuff, i32 wd, i32 ht)
{
i32 i,j;
i32 start=0,mid=0;
function_in();
for(j=0; j<ht; j++)
{
for(i=0; i<wd; i++)
{
if((picbuff[j*wd + i]==0)&&(start))
{
mid=(start+i)/2;
picbuff[j*wd + mid]=255;
start=0;
}
if(picbuff[j*wd + i]==255)
{
if(start==0)
start=i;
picbuff[j*wd + i]=0;
}
}
start=0;
}
function_out();
}
|
C
|
#include <string.h>
#include <stdio.h>
/* reference implementation
*
* char *
* __strncpy_chk (char *s1, const char *s2, size_t n, size_t s1len)
* {
* if (__builtin_expect (s1len < n, 0))
* __chk_fail ();
*
* return strncpy (s1, s2, n);
* }
*
* __fortify_function char *
* __NTH (strncpy (char *__restrict __dest, const char *__restrict __src, size_t __len))
* {
* return __builtin___strncpy_chk (__dest, __src, __len, __bos (__dest));
* }
*/
int main(int argc, char ** argv) {
char buffer[3] = {0};
#ifdef STATIC_CHECK
strncpy(buffer, "bonjour", 4);
#endif
{
char buffer[3] = {0};
strncpy(buffer, "bonjour", argc);
puts(buffer);
}
{
char buffer[3] = {0};
strncpy(buffer, "yo", 3);
puts(buffer);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <conio.h>
#define IMAGEM1 "somaP_1.bmp"
#define IMAGEM2 "somaP_2.bmp"
#define IMAGEM3 "ROTAO.bmp"
#pragma pack(push, 1)
struct{
char assinatura[2];
int sizefile;
short int reserved1;
short int reserved2;
int begin_img;
int sizeheader; //40bytes
int biwidth;
int biheight;
short int planes; //default=1
short int bpp;
int compression;
int size;
int biXPelsPerMeter; //resolucao horizontal
int biYPelsPerMeter; //resolucao vertical
int biClrUsed;
int biClrImportant;
//Paleta
unsigned char r[256];
unsigned char g[256];
unsigned char b[256];
unsigned char alpha[256];
} RegImagem;
//#pragma pack(pop)
float radiano = 2.0 * 3.1415 * 90 /360;
int main(){
FILE *arq1, *arq2, *arq3;
unsigned char **mat1, **mat2, **mat3;
unsigned char dado;
int lar, alt, inicio, i, j, soma;
if((arq1 = fopen(IMAGEM1,"rb")) == NULL){
printf("Arquivo nao encontrado\n");
getche();
exit(0);
}
if((arq2 = fopen(IMAGEM2,"rb")) == NULL){
printf("Arquivo nao encontrado\n");
getche();
exit(0);
}
arq3 = fopen(IMAGEM3,"wb");
fread(&RegImagem,sizeof(RegImagem),1,arq1);
alt = (int) (RegImagem.biheight);
lar = (int) (RegImagem.biwidth);
inicio = (int) (RegImagem.begin_img);
mat1 = malloc(sizeof(unsigned char*[alt]));
mat2 = malloc(sizeof(unsigned char*[alt]));
mat3 = malloc(sizeof(unsigned char*[alt]));
for(j = 0; j < alt; j++){
mat1[j] = malloc(sizeof(unsigned char[lar]));
mat2[j] = malloc(sizeof(unsigned char[lar]));
mat3[j] = malloc(sizeof(unsigned char[lar]));
}
printf("Matrizes Alocadas\n");
//=== Atribuicao dos valores p/as Matrizes
fseek (arq1, inicio, SEEK_SET);
fseek (arq2, inicio, SEEK_SET);
for(i=0; i<alt; i++)
for(j=0; j<lar; j++){
fread(&dado,sizeof(unsigned char),1,arq1);
mat1[i][j] = dado;
}
for(i=0; i<alt; i++)
for(j=0; j<lar; j++){
fread(&dado,sizeof(unsigned char),1,arq2);
mat2[i][j] = dado;
}
//=== A T E N O: Operaes nas Matrizes
for(i=1; i<alt-1; i++)
for(j=0; j<lar; j++){
int i2 = ceil(abs(i*cos(radiano) - j*sin(radiano)));
int j2 = ceil(abs(i*sin(radiano) + j*cos(radiano)));
// if( (mat1[i][j] > 100) || (mat2[i][j] > 100) )
mat3[i2][j2] = mat1[i][j];
}
//=== FIM
//=== Gravacao da nova Imagem
fwrite(&RegImagem, sizeof(RegImagem), 1, arq3);
for(i=0; i<alt; i++)
for(j=0; j<lar; j++)
fwrite (&mat3[i][j], sizeof(unsigned char), 1, arq3);
fclose(arq1);
fclose(arq2);
fclose(arq3);
for(i=0; i<alt; i++){
free(mat1[i]);
free(mat2[i]);
free(mat3[i]);
}
free(mat1);
free(mat2);
free(mat3);
printf("\nFim");
getch();
return 0;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <ajit_access_routines.h>
#include <core_portme.h>
#include <macros.h>
#include <frame_finder.h>
void initFrameFinder(FrameFinder* bds, uint8_t sat_id)
{
bds->sat_id = sat_id;
bds->collected_byte = 0;
bds->internal_counter = 0;
bds->fsm_state = LOOKING_FOR_PREAMBLE;
}
void recordBitInFrameFinder(FrameFinder* bds, uint32_t ms_index, uint8_t ch, uint8_t bit)
{
uint8_t cb = (bds->collected_byte << 1) | bit;
//PRINTF("In Frame finder sat %d ms=%d bit=%d cb=0x%x\n", bds->sat_id, ms_index, bit, cb);
switch(bds->fsm_state)
{
case LOOKING_FOR_PREAMBLE:
if(cb == 0x8b)
{
PRINTF("FrameSAT:%d %d 0x%x [preamble]\n",
bds->sat_id, ms_index-7,cb);
bds->internal_counter == 8;
bds->fsm_state = FRAME_IN_PROGRESS;
}
bds->collected_byte = cb;
break;
case FRAME_IN_PROGRESS:
bds->internal_counter++;
if((bds->internal_counter & 0x7) == 0)
{
PRINTF("FrameSAT:%d 0x%x\n",
bds->sat_id,cb);
}
if(bds->internal_counter == 300)
{
bds->fsm_state = LOOKING_FOR_PREAMBLE;
PRINTF("FrameSAT:%d 0x%x\n",
bds->sat_id,(cb << 4));
bds->collected_byte = 0;
bds->internal_counter = 0;
}
else
{
bds->collected_byte = cb;
}
break;
default:
break;
}
}
|
C
|
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<string.h>
//my_strncpy
void my_strncpy(char*p1, const char*p2, int sz)
{
while (sz && (*p1++ = *p2++))
{
sz--;
}
while (sz&&*p1)
{
*p1++ = '\0';
}
return p1;
}
int main()
{
char arr1[10] = { "abcdefg" };
char arr2[] = { "shuai" };
my_strncpy(arr1, arr2, 2);
printf("%s\n", arr1);
return 0;
}
|
C
|
/************************
Comentários Gerais:
- Implementar lista de prioridades (furar fila na função que recebe as entradas)
************************/
#include <stdio.h>
#include <malloc.h>
#include <string.h>
#include "lista.h"
/*************
FUNÇÕES
**************/
void IniciaAduana(int **patio)
{
int i;
for (i=0; i<5; i++)
{
patio[i] = NULL;
}
}
void LeConteiner(fila *tre, fila *cam)
{
int scan = 1;
conteiner *c;
while (scan != EOF)
{
c = malloc(sizeof(conteiner));
scan = scanf("%d", &c->entrada);
scan = scanf("%d", &c->aduana);
scan = scanf("%s", c->ID);
scan = scanf("%s", c->tipo);
c->proximo = NULL;
c->espera = 0;
if(scan != EOF)
{
if(strstr("TRE", c->tipo) != NULL) //Se for trem, insere na fila de trens, se não, na de caminhões
{
InsereFila(c, tre);
}
else
{
InsereFila(c, cam);
}
}
}
}
int main()
{
int i;
int tempo = 0;
int *patio[5];
int adicionado = 0;
conteiner *primeiro;
conteiner *aux;
fila *cam;
fila *tre;
// inicializa o ponteiro de ponteiros
IniciaAduana(patio);
cam = ConstroiFila();
tre = ConstroiFila();
// Recebe os conteiners e suas informações da entrada padrão
LeConteiner(tre, cam);
while (cam->primeiro != NULL || tre->primeiro != NULL || PatioVazio(patio) == 0)
{
// Aumenta o tempo de espera dos conteiners do patio
for (i=0; i<5; i++)
{
if (patio[i] != NULL)
{
aux = (conteiner*)patio[i];
aux->espera++;
}
}
/***************
CARREGA
***************/
adicionado = 0;
i = BuscaConteiner(patio); //Funcao que busca o conteiner a mais tempo no patio
aux = (conteiner*)patio[i];
if (aux != NULL)
{
// Se o tempo no pátio for maior que 20, ele irá pra linha de montagem
if (aux->espera >= aux->aduana)
{
printf("Carrega %d %s\n", tempo+3, aux->ID); //Já imprime com o tempo gasto no guindaste contabilizado
patio[i] = NULL;
adicionado = 1;
}
}
/***************
ENTRA
***************/
for (i=0; i<5; i++)
{
// Verifica se o primeiro da lista está apto a entrar no patio
if (tre->primeiro != NULL && tre->primeiro->entrada <= tempo && adicionado != 1)
{
// Procura uma posição vazia no pátio para colocar um conteiner apto
if (patio[i] == NULL)
{
printf("Entra %d %s\n", tempo+3, tre -> primeiro->ID);
patio[i] = (int*)primeiro;
RetiraPrimeiro(tre); //Assim que o conteiner for para o patio, é tirado da lista
adicionado = 1;
break; //Se tiver inserido no patio, sai do condicional
}
if (adicionado != 1)
tre -> primeiro->espera++;
}
if (cam->primeiro != NULL && cam->primeiro->entrada <= tempo && adicionado != 1)
{
if (patio[i] == NULL)
{
printf("Entra %d %s\n", tempo +3, tre -> primeiro -> ID);
patio[i] - (int*)primeiro;
RetiraPrimeiro(cam);
adicionado = 1;
break;
}
if (adicionado != 1)
cam->primeiro->espera++;
}
}
//Trata o tempo. Se o guindaste estiver em funcionamento, acresce em 3, pois apenas a chegada é tratada durante esse periodo, e esta já está implementada na fila
if (adicionado == 1)
{
tempo = tempo+3;
}
else
{
tempo++;
}
}
return 1;
}
|
C
|
/*ԼС*/
#include <stdio.h>
int hcf(int a,int b)
{
int r=0;
while(b!=0)
{
r=a%b;
a=b;
b=r;
}
return(a);
}
lcd(int u,int v,int h)
{
return(u*v/h);
}
main()
{
int u,v,h,l;
scanf("%d%d",&u,&v);
h=hcf(u,v);
printf("H.C.F=%d\n",h);
l=lcd(u,v,h);
printf("L.C.D=%d\n",l);
}
|
C
|
#include <stdio.h>
int main(int argc, char const *argv[])
{
char a = getchar();
printf("%c\n",
((a >= 'A' && a <= 'Z') || (a >= 'a' && a <= 'z'))
? ((a >= 'A' && a <= 'Z') ? (a - 'A' + 'a') : (a - 'a' + 'A'))
: a);
return 0;
}
|
C
|
#include <reg51.h>
#include <intrins.h>
#define LED_PORT P0 //ʾ
sbit LSP138A = P2^2; //λѡ
sbit LSP138B = P2^3;
sbit LSP138C = P2^4;
unsigned int ledNumVal, ledOut[8];
unsigned char code dispTab[] = {
~0xC0,~0xF9,~0xA4,~0xB0,~0x99,~0x92,~0x82,~0xF8,~0x80,~0x90,
~0x88,~0x83,~0xC6,~0xA1,~0x86,~0xbf,~0xc7,~0x8c,~0xc1, ~0xff, ~0xf7};
void systemInit()
{
TMOD = 0x00; //ģʽ0 13λ,8192 C/T = 0ڲϵͳṩ -- 12M12Ƶ 1us.
TH0 = (8192 - 1000)/32;
TL0 = (8192 - 1000)%32;
IE = 0x8a; //ʱж
TR0 = 1; //ʱ
}
void delay(unsigned int i)
{
char j;
for (; i > 0; --i)
for (j = 200; j > 0; --j);
}
int main()
{
systemInit();
while (1){
unsigned char i;
ledOut[0] = dispTab[ledNumVal%10000/1000];
ledOut[1] = dispTab[ledNumVal%1000/100];
ledOut[2] = dispTab[ledNumVal%100/10];
ledOut[3] = dispTab[ledNumVal%10];
for (i = 0; i < 8; ++i)
{
LED_PORT = ledOut[i];
switch(i){
case 0:LSP138A = 0; LSP138B = 0; LSP138C = 0;break;
case 1:LSP138A = 1; LSP138B = 0; LSP138C = 0;break;
case 2:LSP138A = 0; LSP138B = 1; LSP138C = 0;break;
case 3:LSP138A = 1; LSP138B = 1; LSP138C = 0;break;
case 4:LSP138A = 0; LSP138B = 0; LSP138C = 1;break;
case 5:LSP138A = 1; LSP138B = 0; LSP138C = 1;break;
case 6:LSP138A = 0; LSP138B = 1; LSP138C = 1;break;
case 7:LSP138A = 1; LSP138B = 1; LSP138C = 1;break;
}
delay(150);
}
}
return 0;
}
/*
* T0 1ms ж
*/
void T0zd(void) interrupt 1 /* жϺţ0: ⲿж1 1: Timer0ж 2: ⲿж2 3: Timer1ж 4: ж*/
{
TH0 = (8192 - 1000)/32;
TL0 = (8192 - 1000)%32;
++ledNumVal;
}
|
C
|
#include<stdio.h>
int main(){
float avg;
int tot=23;
int count=4;
avg=(float)tot/count;
printf("%f",avg);
}
|
C
|
// Based on example program from
// http://stackoverflow.com/q/1821806/101258
#include "write-png.h"
/* Attempts to save PNG to file; returns 0 on success, non-zero on error. */
int bitmap_save_to_png(RGBBitmap *bitmap, const char *path)
{
FILE *fp = fopen(path, "wb");
png_structp png_ptr = NULL;
png_infop info_ptr = NULL;
size_t x, y;
png_uint_32 bytes_per_row;
png_byte **row_pointers = NULL;
if (fp == NULL) return -1;
/* Initialize the write struct. */
png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if (png_ptr == NULL) {
fclose(fp);
return -1;
}
/* Initialize the info struct. */
info_ptr = png_create_info_struct(png_ptr);
if (info_ptr == NULL) {
png_destroy_write_struct(&png_ptr, NULL);
fclose(fp);
return -1;
}
/* Set up error handling. */
if (setjmp(png_jmpbuf(png_ptr))) {
png_destroy_write_struct(&png_ptr, &info_ptr);
fclose(fp);
return -1;
}
/* Set image attributes. */
png_set_IHDR(png_ptr,
info_ptr,
bitmap->width,
bitmap->height,
8,
PNG_COLOR_TYPE_RGB,
PNG_INTERLACE_NONE,
PNG_COMPRESSION_TYPE_DEFAULT,
PNG_FILTER_TYPE_DEFAULT);
/* Initialize rows of PNG. */
bytes_per_row = bitmap->width * bitmap->bytes_per_pixel;
row_pointers = png_malloc(png_ptr, bitmap->height * sizeof(png_byte *));
for (y = 0; y < bitmap->height; ++y) {
uint8_t *row = png_malloc(png_ptr, sizeof(uint8_t) * bytes_per_row);
row_pointers[y] = (png_byte *)row;
for (x = 0; x < bitmap->width; ++x) {
RGBPixel color = RGBPixelAtPoint(bitmap, x, y);
*row++ = color.red;
*row++ = color.green;
*row++ = color.blue;
}
}
/* Actually write the image data. */
png_init_io(png_ptr, fp);
png_set_rows(png_ptr, info_ptr, row_pointers);
png_write_png(png_ptr, info_ptr, PNG_TRANSFORM_IDENTITY, NULL);
/* Cleanup. */
for (y = 0; y < bitmap->height; y++) {
png_free(png_ptr, row_pointers[y]);
}
png_free(png_ptr, row_pointers);
/* Finish writing. */
png_destroy_write_struct(&png_ptr, &info_ptr);
fclose(fp);
return 0;
}
int bitmap_init(RGBBitmap *img, int width, int height)
{
img->width = width;
img->height = height;
img->bytes_per_pixel = 3;
img->pixels = calloc(1, sizeof(RGBPixel) * img->width * img->height);
return 0;
}
int bitmap_set(RGBBitmap *img, int x, int y, int r, int g, int b)
{
RGBPixel *pixel = RGBBufferAtPoint(img, x, y);
pixel->red = r;
pixel->green = g;
pixel->blue = b;
return 0;
}
void bitmap_fill(RGBBitmap *img, int r, int g, int b)
{
int x, y;
// TODO: could use pointers directly or even memcpy
// to make this faster
for (y = 0; y < img->height; y++) {
for (x = 0; x < img->width; x++) {
bitmap_set(img, x, y, r, g, b);
}
}
}
//int main()
//{
// const char path[] = "test.png";
// int status = 0, x, y;
// RGBBitmap img;
//
// bitmap_init(&img, 100, 100);
// for (y = 0; y < img.height; y++) {
// for (x = 0; x < img.height; x++) {
// bitmap_set(&img, x, y, 255, 255, 255);
// }
// }
// bitmap_set(&img, 50, 50, 0, 0, 255);
// bitmap_set(&img, 0, 0, 0, 0, 255);
// bitmap_set(&img, 99, 0, 0, 0, 255);
// bitmap_set(&img, 0, 99, 0, 0, 255);
// bitmap_set(&img, 99, 99, 0, 0, 255);
//
// status = bitmap_save_to_png(&img, path);
// if (!status){
// printf("Successfully saved %s\n", path);
// } else {
// printf("Unable to save %s\n", path);
// }
// return status;
//}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "funciones.h"
int main()
{
int num, fact1, fact2, resulFac;
float numero1=0;
float numero2=0;
float resultado;
int continuar=1;
while(continuar==1)
{
system("cls");
printf("\n - Calculadora - \n\n");
num=menu(numero1, numero2);
if(!(num>=1 && num<=9))
{
printf("Error. Ingrese el numero de una opcion: \n");
scanf("%d", &num);
}
switch(num)
{
case 1:
printf("Ingrese un numero: \n");
scanf("%f", &numero1);
continuar=1;
break;
case 2:
printf("Ingrese otro numero: \n");
scanf("%f", &numero2);
continuar=1;
break;
case 3:
resultado=sumar(numero1, numero2);
printf("La suma de %.2f + %.2f es: %.2f \n\n", numero1, numero2, resultado);
continuar=1;
getch();
break;
case 4:
resultado=restar(numero1, numero2);
printf("La resta de %.2f - %.2f es: %.2f \n\n", numero1, numero2, resultado);
continuar=1;
getch();
break;
case 5:
if(numero2==0)
{
printf("Error. No se puede dividir por cero.");
}
else
{
resultado=dividir(numero1, numero2);
printf("La division de %.2f / %.2f es: %.2f \n\n", numero1, numero2, resultado);
}
getch();
continuar=1;
break;
case 6:
resultado=multiplicar(numero1, numero2);
printf("La multiplicacion de %.2f * %.2f es: %.2f \n\n", numero1, numero2, resultado);
continuar=1;
getch();
break;
case 7:
fact1 = (int)numero1;
fact2 = (int)numero2;
if(fact1<=0)
{
printf("Error. Para calcular el factorial debe ingresar un numero positivo.\n");
}
else
{ resulFac=factorial(fact1);
printf("El factorial de %d es: %d \n", fact1, resulFac);
}
if(fact2<=0)
{
printf("Error. Para calcular el factorial debe ingresar un numero positivo.\n");
}
else
{ resulFac=factorial(fact2);
printf("El factorial de %d es: %d \n\n", fact2, resulFac);
}
continuar=1;
getch();
break;
case 8:
resultado=sumar(numero1, numero2);
printf("La suma de %.2f + %.2f es: %.2f \n", numero1, numero2, resultado);
resultado=restar(numero1, numero2);
printf("La resta de %.2f - %.2f es: %.2f \n", numero1, numero2, resultado);
if(numero2==0)
{
printf("Error. No se puede dividir por cero.\n");
}
else
{ resultado=dividir(numero1, numero2);
printf("La division de %.2f / %.2f es: %.2f \n", numero1, numero2, resultado);
}
resultado=multiplicar(numero1, numero2);
printf("La multiplicacion de %.2f * %.2f es: %.2f \n", numero1, numero2, resultado);
fact1 = (int)numero1;
fact2 = (int)numero2;
if(fact1<=0)
{
printf("Error. Para calcular el factorial ingrese un numero positivo.\n");
}
else
{ resulFac=factorial(fact1);
printf("El factorial de %d es: %d \n", fact1, resulFac);
}
if(fact2<=0)
{
printf("Error. Para calcular el factorial ingrese un numero positivo.\n");
}
else
{ resulFac=factorial(fact2);
printf("El factorial de %d es: %d \n\n", fact2, resulFac);
}
continuar=1;
getch();
break;
case 9:
continuar=0;
break;
}
}
return 0;
}
|
C
|
//
// clientCommands.c
// CloudClient
//
// Created by Lion User on 14/10/2012.
// Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const char list[][30] = {
"-exit", //0
"-registerNewAccount", //1
"-login", //2
"-help" //3
};
//---------------
// Messages
//---------------
/**
* Intro message for Client
* @return introduction message
*/
char* get_IntroMsg() {
char *message = "Welcome to Internix Cloud Service Client!\n\n"
"If you are a NEW USER, please register an account with us using:\n"
"-register user-name password\n\n"
"If you are a returning customer, please proceed to log in to your account using:"
"-login user-name password\n\n"
"If you need assistance at any point in time,\n"
"type -help to access list of commands available.\n\n"
"Thank you for choosing us as your cloud storage provider!\n"
"- Devs of Internix Cloud Services\n\n\n"
"Please wait while we connect you to our server...\n\n";
return message;
}
char* get_HelpList() {
char *listOfCommands = "List of Commands\n\n"
"-registerNewAccount user-name password || To register for a new account\n"
"-login user-name password || To log in to your existing account\n"
"-help || Returns a list of useful commands\n";
return listOfCommands;
}
/**
* For concatenating 2 strings
* @param sentence1
* @param sentence2
* @return concatenated string
*/
char* concatSentence(int command, char* sentence1, char* sentence2) {
char *output = malloc(1000 * sizeof(char));
sprintf(output, "%d ", command);
strcat(output, sentence1);
strcat(output, " ");
strcat(output, sentence2);
return output;
}
/**
* Verify the user inputs in the client by checking against a pre-determined list
* @return an integer that correspond to the command received.
*/
int verifyUserCommand(char* cmd) {
int ERROR = 404;
if(strcmp(cmd, list[0]) == 0) { //-exit
return 0;
} else if(strcmp(cmd, list[1]) == 0) { //-registerNewAccount USERNAME PASSWORD
return 1;
} else if(strcmp(cmd, list[2]) == 0) { //-login USERNAME PASSWORD
return 2;
} else if(strcmp(cmd, list[3]) == 0) { //-help
return 99;
}
return ERROR;
}
char* registerNewAccount() { //1
char *userInputCommand = malloc (1000 * (sizeof(char)));
char *userName = malloc(1000 * (sizeof(char)));
char *password = malloc(1000 * (sizeof(char)));
char *output = malloc(1000 * sizeof(char));
printf("Registering account...\n");
printf("Enter your desired username: ");
scanf("%s", userName);
printf("Enter a 6-digit password: ");
scanf("%s", password);
output = concatSentence(1,userName, password);
printf("Userid: %s Password: %s | Output from Main: %s\n",userName, password, output);
return output;
}
|
C
|
#include "/players/beck/rangers/Defs.h"
id(str){
return str == "pool" || str == "golds_gym_pool";
}
short(){ return "Golds Gym Pool"; }
is_pool(){return 1;}
long(){
write("This is the pool at the Golds Gym facilities.\n"+
"You can do your swimming and water running workouts here,\n"+
"or you can just lounge around and play if you want.\n"+
"");
if(!present(this_player(),this_object())){
write("You can dive into the pool by 'dive into pool'.\n");
write("You can climb into the pool by 'climb into pool'.\n");
write("You can throw a person in by 'throw <person>'.\n");
}
if(present(this_player(),this_object())){
write("To begin your workout type 'workout'.\n");
write("To get out just 'climb out'.\n");
}
}
init(){
if(!present(this_player(),this_object())){
add_action("throw","throw");
add_action("dive","dive");
add_action("climb_in","climb");
}
if(present(this_player(),this_object())){
add_action("workout","workout");
add_action("climb_out","climb");
add_action("splash","splash");
}
}
workout(){
COMM->workout();
return 1;
}
dive(str){
if(!str){ write("Where do you want to dive?\n"); return 1; }
if(str != "into pool"){
write("You can only dive into the pool.\n");
return 1;
}
write("You dive headfirst into the pool.\n");
say(this_player()->query_name()+" dives headfirst into the pool.\n");
tell_room(this_object(),this_player()->query_name()+" dives into the pool.\n");
move_object(this_player(), this_object());
command("look",this_player());
return 1;
}
climb_in(str){
if(!str){ write("Where do you want to climb?\n"); return 1; }
if(str != "into pool"){
write("You can only climb into the pool.\n");
return 1;
}
write("You climb slowly into the pool.\n");
say(this_player()->query_name()+" climbes into the pool.\n");
tell_room(this_object(),this_player()->query_name()+" climbes into the pool.\n");
move_object(this_player(), this_object());
command("look",this_player());
return 1;
}
climb_out(str){
if(!str){ write("Where do you want to climb?\n"); return 1; }
if(str != "out"){
write("You can only climb out.\n");
return 1;
}
write("You climb out of the pool.\n");
say(this_player()->query_name()+" climbes out of the pool.\n");
tell_room(environment(this_object()),this_player()->query_name()+" climbes out of the pool.\n");
move_object(this_player(), environment(this_object()));
command("look",this_player());
return 1;
}
throw(str){
object sucker;
if(!str){ write("Who do you want to throw in the pool?\n"); return 1; }
if(!present(str, environment(this_player()))){
write("That person is not here.\n");
return 1;
}
sucker = present(str, environment(this_player()));
if(present("RangerCommunicator",sucker)->QNoThrow() == 1){
write("You can't throw a person in while they are working out.\n");
return 1;
}
write("You throw "+sucker->query_name()+
" into the pool.\n");
say(this_player()->query_name()+" throws "+sucker->query_name()+
" into the pool.\n");
tell_room(this_object(),this_player()->query_name()+" throws "+
sucker->query_name()+" into the pool.\n");
move_object(sucker, this_object());
return 1;
}
splash(str){
if(!str){ write("Who do you want to throw in the pool?\n"); return 1; }
if(!present(str, environment(this_player()))){
write("That person is not here.\n");
return 1;
}
write("You splash "+present(str, environment(this_player()))->query_name()+
" in the face.\n");
say(this_player()->query_name()+" slashes "+present(str, environment(this_player()))->query_name()+
" in the face.\n");
return 1;
}
realm(){ return "NT"; }
query_no_fight(){ return 1; }
|
C
|
int main()
{
int row,col;
cin>>row>>col;
int a[100][100];
int (*aa)[100]=a;
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
cin>>a[i][j];
}
}
for(int i=0;i<col;i++)
{
int r=0;
int c=i;
while(r<=row-1&&c>=0)
{
cout<<*((*(aa+r))+c)<<endl;
r=r+1;
c=c-1;
}
}
for(int i=1;i<row;i++)
{
int r=i;
int c=col-1;
while(r<=row-1&&c>=0)
{
cout<<*((*(aa+r))+c)<<endl;
r=r+1;
c=c-1;
}
}
return 0;
}
|
C
|
/*
* AVR_HC-SR04_sensor.c
*
* Created: 31.12.2020 13:38:11
* Author : oxford
*/
#include <avr/io.h>
#include <util/delay.h>
#include <avr/interrupt.h>
#include <math.h>
#include "AVR_HC-SR04_sensor.h"
#include "mkuart.h"
/******************************** VARIABLES *******************************************************/
volatile uint16_t g_PrevCount = 0; //previous value of Timer1
volatile uint16_t g_PulseWidth = 0; //width of echo pulse from sensor, in uS (micro seconds)
volatile uint8_t g_measurement_flag = 1; //flag used in interruption, should be 1 at the beginning
/******************************** FUNCTIONS ********************************************************/
void TIMER1_init() //initializing of 16-bit Timer1
{
TCCR1B = (1<<CS11)|(1<<ICES1); //prescaler 8 and trigger on rising edge at the beginning
TIMSK1 = (1<<ICIE1); //Input Capture Mode on (interrupt from input)
}
/*****************************************************************************************************/
void HC_SR04_init() //initializing of sensor work
{
TIMER1_init();
USART_Init(__UBRR); //initializing USART transmision
TRIGGER_DIR |= TRIGGER_BIT; //setting trigger pin as output
}
/*****************************************************************************************************/
void measurement_start() //starting of measurement
{
TRIGGER_ON;
_delay_us(10); //high state by 10 us = triggering of measurement
TRIGGER_OFF;
}
/*****************************************************************************************************/
uint16_t measurement_value() //measured distance in cm
{
if (g_PulseWidth > 30000) //when PulseWidth is higher than sensor's range
{
return 10000;
}
else if (g_measurement_flag < 1) //checking if 2 edges passed
{
return 10000;
}
return g_PulseWidth/58;
}
/*****************************************************************************************************/
void measurement_value_UART() //sending measured distance in cm through UART
{
uint16_t dist = measurement_value();
if (dist > 9000) //when PulseWidth is higher than sensor range
{
uart_puts("Out of range!");
return;
}
uart_puts("Distance = ");
uart_putint(dist,10);
uart_puts("cm");
uart_putc(0x0a);
}
/***************************** INTERRUPTION ********************************************/
ISR(TIMER1_CAPT_vect ) //remember to enable global interrupts [sei();]
{
TCCR1B ^= (1<<ICES1); //changing of edge (falling/rising) reaction
uint16_t actual = fabs(ICR1);
g_PulseWidth = actual - g_PrevCount;
g_PrevCount = actual;
if (g_measurement_flag > 1) //automatic sending measured distance through UART, measurement value available only when 2 edges passed
{
measurement_value_UART();
g_measurement_flag -= 2; //deleting flag's status
}
g_measurement_flag ++;
}
|
C
|
#include "compression_biblio.h"
void decompressBmp(char *src, char *dst)
{
FILE *ficSource;
FILE *ficDestination;
typeEnTeteFichierBmp enTeteFic;
typeEnTeteImageBmp enTeteImg;
typeCouleur palette[NBCOULEURS];
int retour;
unsigned int tailleFicDest;
unsigned int tailleImgDest;
unsigned int typeCompression;
unsigned char repetition;
unsigned char valeurOctet;
unsigned char octet;
unsigned int nbOctet;
//ouverture du fichier source
ficSource = fopen(src, "r");
if (ficSource == NULL)
{
printf("src %s\n", strerror(errno));
exit(errno);
}
//ouverture du fichier destination
ficDestination = fopen(dst, "w+");
if (ficDestination == NULL)
{
printf("dst %s\n", strerror(errno));
exit(errno);
}
//lecture des en-tete fichier, image et palette du fichier source
retour = fread(&enTeteFic, sizeof (typeEnTeteFichierBmp), 1, ficSource);
if (retour != 1)
{
printf("src ef %s\n", strerror(errno));
exit(errno);
}
retour = fread(&enTeteImg, sizeof (typeEnTeteImageBmp), 1, ficSource);
if (retour != 1)
{
printf("src ei %s\n", strerror(errno));
exit(errno);
}
retour = fread(&palette, sizeof (typeCouleur), 256, ficSource);
if (retour != 256)
{
printf("src pal %s\n", strerror(errno));
exit(errno);
}
//ecriture des en-tete fichier, image et palette dans fichier destination
retour = fwrite(&enTeteFic, sizeof (typeEnTeteFichierBmp), 1, ficDestination);
if (retour != 1)
{
printf("%s\n", strerror(errno));
exit(errno);
}
retour = fwrite(&enTeteImg, sizeof (typeEnTeteImageBmp), 1, ficDestination);
if (retour != 1)
{
printf("%s\n", strerror(errno));
exit(errno);
}
retour = fwrite(palette, sizeof (typeCouleur), 256, ficDestination);
if (retour != 256)
{
printf("%s\n", strerror(errno));
exit(errno);
}
do {
retour = fread(&repetition, sizeof (repetition), 1, ficSource);
if (retour != 1)
{
if (!feof(ficSource))
{
printf("src repet %s\n", strerror(errno));
exit(errno);
}
}
retour = fread(&valeurOctet, sizeof (valeurOctet), 1, ficSource);
if (retour != 1)
{
printf("src val %s\n", strerror(errno));
exit(errno);
}
for (nbOctet = 0; nbOctet < repetition; nbOctet++)
{
retour = fwrite(&valeurOctet, sizeof (valeurOctet), 1, ficDestination);
if (retour != 1)
{
printf("dst val %s\n", strerror(errno));
exit(errno);
}
}
} while (repetition != 00 || valeurOctet != 01);
//fermer fichier source
retour = fclose(ficSource);
if (retour == EOF)
{
printf("%s\n", strerror(errno));
exit(errno);
}
//positionnement à la taille fichier
retour = fseek(ficDestination, 2, SEEK_SET);
if (retour == -1)
{
printf("%s\n", strerror(errno));
exit(errno);
}
tailleFicDest = sizeof (typeEnTeteFichierBmp) + sizeof (typeEnTeteImageBmp) + sizeof (typeCouleur)*256 + enTeteImg.largeur * enTeteImg.hauteur;
//ecriture sur taille fichier
retour = fwrite(&tailleFicDest, sizeof (tailleFicDest), 1, ficDestination);
if (retour != 1)
{
printf("dst modif taille %s\n", strerror(errno));
exit(errno);
}
//positionnement au type de compression
retour = fseek(ficDestination, 24, SEEK_CUR);
if (retour == -1)
{
printf("%s\n", strerror(errno));
exit(errno);
}
// ecriture du type compression (non compressé)
typeCompression = 0;
retour = fwrite(&typeCompression, sizeof (typeCompression), 1, ficDestination);
if (retour != 1)
{
printf("dst modif type %s\n", strerror(errno));
exit(errno);
}
//ecriture de la taille image
tailleImgDest = enTeteImg.largeur * enTeteImg.hauteur;
retour = fwrite(&tailleImgDest, sizeof (tailleImgDest), 1, ficDestination);
if (retour != 1)
{
printf("dst modif taille img %s\n", strerror(errno));
exit(errno);
}
//fermeture du fichier de destination
retour = fclose(ficDestination);
if (retour == EOF)
{
printf("%s\n", strerror(errno));
exit(errno);
}
}
void compressBmp(char *src, char *dst)
{
}
|
C
|
//#include<stdio.h>
//#include<stdlib.h>
//#include<string.h>
//int main()
//{
// char s[100];
// char *p, *q, *o;//p指向数字,q指向字母
// while (printf("输入字符串:"),rewind(stdin),gets(s) != NULL)
// {
// p = s; q = s + 1;
// char temp;
// while (*q != '\0'/*&& *p != '\0'*/)
// {
// while (*p >= '0'&&*p <= '9')
// {
// p++;
// q++;
// }
// temp = *p;
// if (*q >= '0'&&*q <= '9')
// {
// *p = *q;
// *q = temp;
// p++;
// o = p;
// while (o != q)
// {
// temp = *o;
// *o = *q;
// *q = temp;
// o++;
// }
// q++;
// }
// else
// {
// q++;
// }
// }
// printf("排序后:%s\n", s);
// /**q = '\0';*/
// memset(s, 0, sizeof(s));
// }
// system("pause");
// return 0;
//}
//将 字 符 串 中 的 空 格 替 换 成 “%020”
//#include<stdio.h>
//#include<stdlib.h>
//#include<string.h>
//int main()
//{
// char s[100];
// char *p,*q;
// char temp;
// while (printf("请输入带空格的字符串:"), gets(s) != NULL)
// {
// p = s;
// while (*p != '\0')
// {
// if (*p != ' ')
// {
// p++;
// }
// else
// {
// q = &s[strlen(s)-1];
// *(q + 4) = '\0';
// while (q != p )
// {
// *(q + 3) = *q;
// q--;
// }
// *p = '%';
// *(p + 1) = '0';
// *(p + 2) = '2';
// *(p + 3) = '0';
// p+=4;
//
// }
// }
// printf("%s\n", s);
// memset(s, 0, sizeof(s));
// }
// system("pause");
// return 0;
//}
//删除字符串中指定的字符。 例如 “abcdaefaghiagkl“ 删除‘a’, 以后
//#include<stdio.h>
//#include<stdlib.h>
//#include<string.h>
//int main()
//{
// char s[100];
// char *p, *q;
// while (printf("请输入带a的字符串:"), gets(s) != NULL)
// {
// p = s;
// while (*p != '\0')
// {
// if (*p != 'a')
// {
// p++;
// }
// else
// {
// q = p;
// while (*q != '\0')
// {
// *q = *(q + 1);
// q++;
// }
// p++;
// }
// }
// printf("删除a后的字符串:%s\n", s);
// memset(s, 0, sizeof(s));
// }
// system("pause");
// return 0;
//}
//删除一个数组中重复的元素
//#include<stdio.h>
//#include<stdlib.h>
//int main()
//{
// int arr[] = { 1,2,2,2,3,3,3,4,4,5,5,5,6,6,2 };
// int len = sizeof(arr) / sizeof(int);
// int i, j, k;
// for (i = 0; i < len - 2; ++i)
// {
// j = i + 1;
// while (j < len - 1)
// {
// if (arr[i] != arr[j])
// {
// j++;
// }
// else
// {
// for (k = j; k < len - 2; ++k)
// {
// arr[k] = arr[k + 1];
// }
// arr[k] = 0;
// len--;
// }
// }
// }
// for (i = 0; i < len - 1; ++i)
// {
// printf("%d ", arr[i]);
// }
// system("pause");
// return 0;
//}
//将 字 符 串 中 的 相 邻 的 多 余 空 格 去 掉
//#include<stdio.h>
//#include<stdlib.h>
//int main()
//{
// char s[100];
// char *p, *q;
// int ret = 0;
// while (printf("输入带多余空格的字符串:"), gets(s) != NULL)
// {
// p = s;
// while (*p != '\0')
// {
// if (*p != ' ')
// {
// ret = 1;
// p++;
// }
// else
// {
// if (1 == ret)
// {
// ret = 0;
// p++;
// }
// else
// {
// q = p;
// while (*q != '\0')
// {
// *q = *(q + 1);
// q++;
// }
// }
// }
// }
// printf("删除多余空格后:%s\n", s);
// memset(s, 0, sizeof(s));
// }
// system("pause");
// return 0;
//}
//求一个字符串数组的最大值和次大值 void big(char *arr[],int size ,char** big1,char** big2)
//#include<stdio.h>
//#include<string.h>
//#include<stdlib.h>
//void big(char *arr[], int size, char** big1, char** big2)
//{
//
// int i;
// for (i = 1; i < size ; ++i)
// {
// if (1 == strcmp(arr[i], *big1))
// {
// *big1 = arr[i];
// }
// }
// for (i = 1; i < size ; ++i)
// {
// if (1 == strcmp(arr[i], *big2) && arr[i] != *big1)
// {
// *big2 = arr[i];
// }
// }
// printf("最大值为%s,次大值为%s\n", *big1, *big2);
//}
//int main()
//{
// char *b[15] = { {"hello"},{"how"},{"world"},{"helloo"},{"however"},{"worldddd"} };
// char *big1=b[0], *big2=b[0];
// big(b, 6, &big1, &big2);
// system("pause");
// return 0;
//}
//大整数加法
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void jinWei(char *s,int i)//进位
{
if (0 == i && s[i] > '9')
{
int len ;
for (len = strlen(s); len > 1; --len)
{
s[len] = s[len - 1];
}
s[1] = s[0] - 10;
s[0] = '1';
}
else if (s[i] > '9')
{
s[i] = s[i] - 10;
s[i - 1]++;
}
}
void jieWei(char *s, int i)//借位
{
if (s[i] < '0' )
{
s[i] = s[i] + 10;
s[i - 1]--;
}
}
void myPlus(const char *s1, const char *s2, char *s3,int m,int n)//加法
{
int len3 = strlen(s3);
int i;
for (i = len3; i > 0; --i)
{
s3[i] = s3[i - 1];
}
s3[0] = s1[m] + s2[n] - 48;
}
void myMinus(const char *s1, const char *s2, char *s3, int m, int n)//减法
{
int len3 = strlen(s3);
int i;
for (i = len3; i > 0; --i)
{
s3[i] = s3[i - 1];
}
s3[0] = s1[m] - s2[n] + 48;
}
void sum(char *s1,char *s2, char *s3)
{
int len1 = strlen(s1), len2 = strlen(s2);
int ret = 0, i;
if ((s1[0] == '-'&&s2[0] == '-') || s1[0] != '-'&&s2[0] != '-') //两个正数相加,两个负数相加
{
if (s1[0] == '-'&&s2[0] == '-')
{
ret = 1; //记录这是两个负数,下面删除负号
for (i = 0; i < len1; ++i)
{
s1[i] = s1[i + 1];
}
for (i = 0; i < len2; ++i)
{
s2[i] = s2[i + 1];
}
}
while (len1 > 0 || len2 > 0) //开始做加法
{
if (len1 > 0 && len2 > 0)//从个位,十位,百位依次加赋值给s3
{
myPlus(s1, s2, s3, len1 - 1, len2 - 1);
len1--; len2--;
}
//若一个数比另外一个数长
else if (len1 <= 0 && len2 > 0)
{
myPlus("0", s2, s3, 0, len2 - 1);
len2--;
}
else if (len1 > 0 && len2 <= 0)
{
myPlus(s1, "0", s3, len1 - 1, 0);
len1--;
}//加法完毕
}
int len3;//下面进位s3
for (len3 = strlen(s3) - 1; len3 >= 0; --len3)
{
jinWei(s3, len3);
}
if (ret == 1) //若是两负数,加回负号
{
for (len3 = strlen(s3); len3 > 0; --len3)
{
s3[len3] = s3[len3 - 1];
}
s3[0] = '-';
s3[strlen(s3) - 1] = '\0';
}
}
else //一正一负
{
int big;
if (s1[0] == '-'&&s2[0] != '-')//去掉s1或s2的负号
{
big = 2;
for (i = 0; i < len1; ++i)
{
s1[i] = s1[i + 1];
}
len1--;
}
else if (s2[0] == '-'&&s1[0] != '-')
{
big = 1;
for (i = 0; i < len2; ++i)
{
s2[i] = s2[i + 1];
}
len2--;
}
char temp[50]; int te;
ret = 0;//记录有没有排序过
if (len1 < len2) //给s1s2排序,大的给s1,好做减法
{
strcpy(temp, s1);
strcpy(s1, s2);
strcpy(s2, temp);
te = len1; len1 = len2; len2 = te;
ret = 1;//表示有排序过
}
else if (len1 == len2)
{
for (i = 0; i < len1; ++i)
{
if (s1[i] < s2[i])
{
strcpy(temp, s1);
strcpy(s1, s2);
strcpy(s2, temp);
te = len1; len1 = len2; len2 = te;
ret = 1;
break;
}
else if(s1[i]>s2[i])
{
break;
}
}
}//排序结束,下面减法
while (len1 > 0 || len2 > 0)
{
if (len1 > 0 && len2 > 0)
{
myMinus(s1, s2, s3, len1 - 1, len2 - 1);
len1--; len2--;
}
else if (len1 > 0 && len2 <= 0)
{
myMinus(s1, "0", s3, len1 - 1, 0);
len1--;
}
}
//减法结束,下面借位
int len3, j;
for (len3 = strlen(s3) - 1; len3 >= 0; --len3)
{
jieWei(s3, len3);//借位
}
//s3前有零的情况,i记录有多少个零
for (i = 0; i < strlen(s3); ++i)
{
if (s3[i] != '0')
{
break;
}
}
if (i == strlen(s3)) //s3刚好全是零
{
s3[1] = '\0';
}
else
{
if (i != 0 )//有零的情况,把零去掉
{
for (j = 0; i < strlen(s3); ++j, ++i)
{
s3[j] = s3[i];
}
s3[j] = '\0';
}
if (ret + big == 2)//正数比负数小,要加回负号
{
for (len3 = strlen(s3); len3 > 0; --len3)
{
s3[len3] = s3[len3 - 1];
}
s3[0] = '-';
}
s3[strlen(s3)] = '\0';
}
}
}
int main()
{
char s1[50], s2[50], s3[60] = {0};
while (printf("输入两个整数(50位以内):\n"),rewind(stdin), gets(s1) != NULL && gets(s2) != NULL)
{
sum(s1, s2, s3);
printf("两数之和为:\n%s\n", s3);
memset(s3, 0, sizeof(s3));
}
system("pause");
return 0;
}
|
C
|
/*
* 文件名: mcat.c
* 描述: dup2 函数实现重定向
* bin/mcat + file (+ 为输入重定向))
* bin/mcat - file (- 为输出重定向)
* 完成日期: 2018年2月1日16:37
*/
#include "io.h"
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
int main(int argc, char* argv[])
{
int fd_in ,fd_out;
int flag = 0;
int i;
for(i=1; i<argc; i++){
if(!strcmp("+", argv[i])){
fd_in = open(argv[++i], O_RDONLY);
if(fd_in < 0){
perror("open error");
exit(EXIT_FAILURE);
}
// 将标准输入重定向到文件
if(dup2(fd_in, STDIN_FILENO) !=STDIN_FILENO){
perror("dup2 error");
exit(EXIT_FAILURE);
}
close(fd_in);
}else if(!strcmp("-", argv[i])){
fd_out = open(argv[++i], O_WRONLY|O_CREAT|O_TRUNC, 0777);
if(fd_out < 0){
perror("open error");
exit(EXIT_FAILURE);
}
// 将标准输出重定向到文件
if(dup2(fd_out, STDOUT_FILENO) != STDOUT_FILENO){
perror("dup2 error");
exit(EXIT_FAILURE);
}
close(fd_out);
}else{
flag = 1;
fd_in = open(argv[i], O_RDONLY);
if(fd_in < 0){
perror("open error");
exit(EXIT_FAILURE);
}
if(dup2(fd_in, STDIN_FILENO) !=STDIN_FILENO){
perror("dup2 error");
exit(EXIT_FAILURE);
}
copy(STDIN_FILENO, STDOUT_FILENO);
close(fd_in);
}
}
if(!flag){
copy(STDIN_FILENO, STDOUT_FILENO);
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
char v1,v2,buffer;
printf("Introduza 2 Caracteres\n");
scanf("%c %c",&v1, &v2);
printf("Valor introduzido : \n\n\t v1:%c | | v2:%c\n\n\n",v1,v2);
buffer = v1;
v1=v2;
v2=buffer;
printf("Valor trocado : \n\n\t v1:%c | | v2:%c\n\n",v1,v2);
return 0;
}
|
C
|
#include<stdio.h>
int main(){
int n;
int arr[100][100];
scanf("%d",&n);
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
scanf("%d",&arr[i][j]);
}
}
for(int i=0;i<n;i++){
for(int j=i+1;j<n;j++){
if(arr[i][j]!=arr[j][i]){
printf("Not Symmetric");return 0;
}
}
}
printf("Symmetric");
return 0;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define VERTEX_WAS_CHECKED -1
#define MAX_VERTEX_NUM 1000
typedef enum checkData {
badVertex,
success,
noInput,
impossibleToSort,
badNumOfLines,
badNumOfVertices,
badNumOfEdges
} resultOfWorking;
typedef struct edge {
int begin;
int end;
} edge;
int checkNumberOfEdges(const int numberOfEdges, const int numberOfVertices) {
return (numberOfEdges <= numberOfVertices * (numberOfVertices + 1) / 2);
}
int *initColumnsArray(const int numberOfVertices, const int numberOfEdges, const edge *listOfEdges) {
int *columns = malloc(sizeof(int) * numberOfVertices);
memset(columns, 0, numberOfVertices * sizeof(int));
for (int idx = 0; idx < numberOfEdges; ++idx) {
columns[listOfEdges[idx].end - 1]++;
}
return columns;
}
int *topologicalSort(const edge *vertexes, const int numberOfVertices, const int numberOfEdges, const edge *listOfEdges,
resultOfWorking *status) {
int *columns = initColumnsArray(numberOfVertices, numberOfEdges, listOfEdges);
int *answerList = malloc(sizeof(int) * numberOfVertices);
int answersIdx = 0;
while (answersIdx < numberOfVertices) {
int columnsIdx = 0;
int workingIdx = -1;
while (columnsIdx < numberOfVertices) {
if (columns[columnsIdx] == 0) {
workingIdx = columnsIdx;
break;
}
columnsIdx++;
if (columnsIdx == numberOfVertices) {
*status = impossibleToSort;
free(columns);
return answerList;
}
}
answerList[answersIdx] = workingIdx + 1;
columns[columnsIdx] = VERTEX_WAS_CHECKED;
for (int idx = 0; idx < numberOfEdges; ++idx) {
if (vertexes[idx].begin == workingIdx + 1) {
columns[vertexes[idx].end - 1]--;
}
}
answersIdx++;
}
free(columns);
return answerList;
}
void printAnswerList(const int *answerList, const int numberOfVertices) {
for (int idx = 0; idx < numberOfVertices; ++idx) {
printf("%d ", answerList[idx]);
}
}
int inputInitialValues(int *numberOfVertices, int *numberOfEdges) {
int haveNextInput = 0;
if (!scanf("%d", numberOfVertices)) {
fprintf(stderr, "No input!");
}
haveNextInput = scanf("%d", numberOfEdges);
return haveNextInput == 1;
}
int isBetweenBoundaries(const int checkingVertex, const int leftBoundary, const int rightBoundary) {
return (checkingVertex >= leftBoundary && checkingVertex <= rightBoundary);
}
void printIOException() {
printf("There is no input. Check your file to data");
}
edge *inputEdges(const int numberOfVertices, const int numberOfEdges, resultOfWorking *controlValueOfInputVertexes) {
edge *listOfEdges = malloc(sizeof(edge) * numberOfEdges);
resultOfWorking checkForCorrectData = success;
for (int idx = 0; idx < numberOfEdges; ++idx) {
edge currentVertexes;
int haveNextInput = 0;
if (!scanf("%d", ¤tVertexes.begin)) {
printIOException();
}
haveNextInput = scanf("%d", ¤tVertexes.end);
// если вводится число - то haveNextInput обязан равняться единице
if (haveNextInput != 1) {
*controlValueOfInputVertexes = noInput;
return listOfEdges;
}
if (!(isBetweenBoundaries(currentVertexes.begin, 1, numberOfVertices) &&
isBetweenBoundaries(currentVertexes.end, 1, numberOfVertices))) {
checkForCorrectData = badVertex;
continue;
}
listOfEdges[idx] = currentVertexes;
}
*controlValueOfInputVertexes = checkForCorrectData;
return listOfEdges;
}
void freeMemory(edge *listOfEdges, int *answerList) {
free(listOfEdges);
free(answerList);
}
void printMessageByStatus(const resultOfWorking status) {
switch (status) {
case badNumOfLines:
printf("bad number of lines");
break;
case badNumOfEdges:
printf("bad number of edges");
break;
case badNumOfVertices:
printf("bad number of vertices");
break;
case noInput:
printf("bad number of lines");
break;
case badVertex:
printf("bad vertex");
break;
case impossibleToSort:
printf("impossible to sort");
break;
default:
break;
}
}
int main(void) {
int numberOfVertices;
int numberOfEdges;
resultOfWorking status = success;
if (!inputInitialValues(&numberOfVertices, &numberOfEdges)) {
status = badNumOfLines;
} else if (!isBetweenBoundaries(numberOfVertices, 0, MAX_VERTEX_NUM)) {
status = badNumOfVertices;
} else if (!checkNumberOfEdges(numberOfEdges, numberOfVertices)) {
status = badNumOfEdges;
}
edge *listOfEdges = NULL;
int *answerList = NULL;
if (status == success) {
listOfEdges = inputEdges(numberOfVertices, numberOfEdges, &status);
}
if (status == success) {
answerList = topologicalSort(listOfEdges, numberOfVertices, numberOfEdges, listOfEdges, &status);
}
if (status == success) {
printAnswerList(answerList, numberOfVertices);
} else {
printMessageByStatus(status);
}
freeMemory(listOfEdges, answerList);
return EXIT_SUCCESS;
}
|
C
|
#include <stdio.h> //printf
#include <string.h> //memset
#include <stdlib.h> //exit(0);
#include <arpa/inet.h>
#include <netdb.h>
#include <sys/socket.h>
#include <fcntl.h> // for open
#include <unistd.h> // for close
#include <time.h>
// -------------------------------------- //
// --- ATTENTION! USE THIS TO LISTEN! --- //
// --- netcat -lu -p 8888 --- //
// -------------------------------------- //
#define BUFLEN 512 //Max length of buffer
#define PORT 51111 //The port on which to listen for incoming data
void die(char* s, int e)
{
printf(s,e);
perror(s);
exit(1);
}
char* buildOscMessage(char* address, int32_t number) {
return NULL;
}
int main(void)
{
const char* hostname="127.0.0.1"; /* localhost */
const char* portname="8888";
struct addrinfo hints;
memset(&hints,0,sizeof(hints));
hints.ai_family=AF_UNSPEC;
hints.ai_socktype=SOCK_DGRAM;
hints.ai_protocol=0;
hints.ai_flags=AI_ADDRCONFIG;
struct addrinfo* res=0;
int err=getaddrinfo(hostname,portname,&hints,&res);
if (err!=0) {
die("failed to resolve remote socket address (err=%d)",err);
}
int fd=socket(res->ai_family,res->ai_socktype,res->ai_protocol);
if (fd==-1) {
die("%s",err);
}
char* content = "sending udp packet\n";
//keep listening for data
while(1)
{
if (sendto(fd,content,strlen(content),0,
res->ai_addr,res->ai_addrlen)==-1) {
die("%s",err);
}
usleep(1000000);
}
close(fd);
return 0;
}
|
C
|
#ifndef CHARACTER_LIST
#define CHARACTER_LIST
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "character.h"
#include "equipment_array.h"
typedef struct linked_list {
character_t head;
struct linked_list *tail;
} linked_list_t;
typedef struct {
// Pointer to the __first__ element of the linked list
linked_list_t *first;
// Pointer to the __last__ element of the linked list;
linked_list_t *last;
} character_list_t;
character_list_t character_list_from_file(FILE *fp,
equipment_array_t *equipments);
character_list_t character_list_add_character(character_list_t characters,
character_t character);
character_list_t
character_list_remove_character_by_id(character_list_t characters, int id);
character_t character_list_find_character_by_id(character_list_t characters,
int id);
void character_list_print(character_list_t);
character_list_t character_list_new();
void character_list_free(character_list_t);
#endif
|
C
|
#include <stdio.h>
/* Създайте нов потребителски тип
към тип long long int. Използвайте го във функцията
printf, отпечатайте размера. */
int main(void){
typedef long long int t_lNum;
t_lNum num = 4000000000000;
printf("%lld\n", num);
t_lNum num1 = 3000000000000;
t_lNum *t_point;
t_point = &num1;
printf("%lld\n", *t_point);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int compresslength(char* input)
{
char letter = input[0];
int inputsize = 0;
int i = 0;
int lettercount = 1;
int length = 0;
while(letter != '\0') {
if( (letter >= 48 && letter <= 57) ) return -1;
if( (letter != input[i]) ) {
//Every part of the output string is going to have (letter)(number). If the letter count > 10, use the / 10 to increase length of output string.
length += 2 + (lettercount / 10);
lettercount = 1;
letter = input[i];
}
else {
i++;
lettercount++;
inputsize++;
}
}
if(length > inputsize)
return 0;
return length;
}
int compress(char *input)
{
char currletter = input[0];
char scanletter = input[0];
int charcounter = 0;
int inindex = 0;
while(scanletter != '\0') {
if(scanletter != currletter) {
printf("%c%i",currletter,charcounter);
currletter = scanletter;
charcounter = 0;
}
else {
inindex++;
charcounter++;
scanletter = input[inindex];
}
}
printf("%c%i\n",currletter, charcounter);
return 0;
}
int main(int argc, char** argv)
{
if(argc != 2) return 1;
char* input = argv[1];
int length = compresslength(input);
if(length == -1) {
puts("error");
return 0;
}
else if (length == 0) {
puts(input);
return 0;
}
else {
compress(input);
return 0;
}
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
struct node // Step 1 //
{
int data;
struct node *next;
}node2,node3,node4; // Step 2 and 3 and 4 //
struct node *start = NULL;
struct node *insert_beg(struct node *, int number);
struct node *del_all(struct node *);
struct node *display_nodes(struct node *);
struct node *sep_nodes(struct node *);
struct node *del_beg(struct node *);
int node_1;
int node_2;
int node_3;
int node_4;
int main()
{
srand(time(NULL));
int number;
int i;
for (i=0;i<30;i++) // Step 5 // Insert Node 30 //
{
number = (rand() % 30 + 1);
insert_beg(start,number);
}
display_nodes(start);
return 0;
}
struct node *insert_beg(struct node *start, int number) // Insert Node 1 //
{
struct node *ptr ,*new_node;
new_node = (struct node *)malloc(sizeof(struct node));
new_node -> data = number;
if (start == NULL)
{
new_node -> next = new_node;
start = new_node;
}
else
{
ptr = start;
while (ptr -> next != start)
{
ptr = ptr -> next;
}
ptr -> next = new_node;
new_node -> next = start;
start = new_node;
}
return start;
}
struct node *sep_nodes(struct node *start)
{
struct node *ptr;
if (ptr == NULL)
{
printf("Empty");
}
else
{
while (ptr -> next != start)
{
if (ptr -> data % 2) // Step 6 //
{
ptr -> data = node2.data;
ptr = ptr -> next;
node_2++;
}
else if (ptr -> data % 5) // Step 7 //
{
ptr -> data = node3.data;
ptr = ptr -> next;
node_3++;
}
else // Step 8 //
{
ptr -> data = node4.data;
ptr = ptr -> next;
node_4++;
}
node_1++;
}
}
};
struct node *display_nodes(struct node *start)
{
struct node *ptr;
if (start == NULL)
{
printf("Empty");
}
else
{
while(ptr -> next != start)
{
printf("Node 1: %d\t",ptr -> data);
printf("Node 2: %d\t",ptr -> node2.data);
printf("Node 3: %d\t",ptr -> node3.data);
printf("Node 4: %d\t",ptr -> node4.data);
ptr = ptr -> next;
}
}
printf("\n");
}
struct node *del_beg(struct node *start)
{
struct node *ptr;
ptr = start;
while(ptr ->next != start)
{
ptr = ptr -> next;
ptr -> next = start -> next;
free(start);
}
start = ptr -> next ;
};
struct node *del_all(struct node *start)
{
struct node *ptr;
ptr = start;
while(ptr -> next != start)
{
start = del_beg(start);
free(start);
}
return start;
}
|
C
|
#include<stdio.h>
#include<math.h>
main()
{
int k;
k=mul(7);
printf("%d",k);
}
int mul(int a)
{
int s;
if(a==1)
return (a);
s=a*mul(a-1);
return (s);
}
|
C
|
/*
* bagtest.c - test program for bag module
*
* usage: bagtest
* (no arguments)
* ouput:
* program prints the results of various tests of the
* bag module to stdout, while also informing the user
* of what the desired output is
* functions:
* > delete_func1: a sample delete function passed to the bag
* module which the module then uses to delete user input
* data that is statically allocated
* > delete_func2: a sample delete function passed to the bag
* module which the module then uses to delete user input
* data that is dynamically allocated
* stdin: none
* stdout: printed test results
* stderr: error messages
*
* Kyle Dotterrer, April 2016
============================================================================*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "bag.h"
void delete_func1(void *data);
void delete_func2(void *data);
int main(void)
{
bag_t *bag; // the bag
bag_t *fakebag = NULL; // invalid bag
void *extracted;
// initialize a new bag
bag = bag_new(delete_func1);
printf("creating new bag to hold statically allocated data\n");
if (bag == NULL) {
// inform user if error occurs
fprintf(stderr, "bag_new failed\n");
exit(1);
}
// insert some items into bag
// strings not dynamically allocated
bag_insert(bag, "data1");
bag_insert(bag, "data2");
bag_insert(bag, "data3");
bag_insert(bag, "data4");
bag_insert(bag, "data1");
// inform user of what was inserted
printf("insert item with 'data1' string literal\n");
printf("insert item with 'data2' string literal\n");
printf("insert item with 'data3' string literal\n");
printf("insert item with 'data4' string literal\n");
// bag accepts duplicates
printf("insert item with 'data1' string literal\n");
// perform some extractions
printf("extract returns %s\n", (char*) bag_extract(bag));
printf("extract returns %s\n", (char*) bag_extract(bag));
printf("extract returns %s\n", (char*) bag_extract(bag));
printf("extract returns %s\n", (char*) bag_extract(bag));
printf("extract returns %s\n", (char*) bag_extract(bag));
// should return null
printf("bag empty, extract returns %s\n", (char*) bag_extract(bag));
// delete entire data structure
bag_delete(bag);
printf("deletion of empty bag successful\n\n");
// initialize a new bag
bag = bag_new(delete_func2);
printf("creating new bag to hold dynamically allocated data\n");
if (bag == NULL) {
// inform us if error occurs
fprintf(stderr, "bag_new failed\n");
exit(1);
}
// create strings with dynamically allocated memory
char *data1 = malloc(strlen("data1"));
char *data2 = malloc(strlen("data2"));
char *data3 = malloc(strlen("data3"));
strcpy(data1, "data1");
strcpy(data2, "data2");
strcpy(data3, "data3");
// insert dynamically allocated strings into bag
bag_insert(bag, data1);
bag_insert(bag, data2);
bag_insert(bag, data3);
// inform user of what was inserted
printf("insert item with 'data1' dynamically allocated string\n");
printf("insert item with 'data2' dynamically allocated string\n");
printf("insert item with 'data3' dynamically allocated string\n");
// test extraction of dynamically allocated data
printf("extract returns %s\n", (char*) bag_extract(bag));
// delete entire data structure
bag_delete(bag);
printf("deletion of non-empty bag successful\n\n");
// test extraction from invalid bag
extracted = bag_extract(fakebag);
if (extracted == NULL)
printf("extraction from invalid bag returns NULL\n");
else
printf("extraction from invalid bag returns non-NULL\n");
exit(0);
}
/*
* delete_func1: example of delete function that
* handles user data that is not dynamically allocated,
* nothing needs to be done before item is freed
*/
void delete_func1(void *data)
{
;
}
/*
* delete_func2: example of delete function to
* handle data that is dynamically allocated,
* frees the data so that item can then be freed
*/
void delete_func2(void *data)
{
free(data);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_memccpy.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: bnoufel <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/02/08 16:04:21 by bnoufel #+# #+# */
/* Updated: 2020/02/08 19:49:38 by bnoufel ### ########.fr */
/* */
/* ************************************************************************** */
#include "mem.h"
/*
** @param void *dst
** @param void *src
** @param int c
** @param size_t n
** ft_memcpy() function copies n bytes from memory area src to memory area dst.
** If dst and src overlap, behavior is undefined.
** Applications in which dst and src might overlap should use memmove instead.
** The source and destination strings should not overlap,
** as the behavior is undefined.
************************* RETURN VALUES **********************************
** The ft_memcpy() function returns the original value of dst.
*/
void *ft_memccpy(void *dst, const void *src, int c, size_t n)
{
uint8_t *s1;
uint8_t *s2;
size_t i;
i = 0;
s1 = (uint8_t *)dst;
s2 = (uint8_t *)src;
while (i < n)
{
s1[i] = s2[i];
if (s2[i] == (uint8_t)c)
return (dst + i + 1);
i++;
}
return (NULL);
}
|
C
|
#include "inc/hw_types.h"
#include "utils/ustdlib.h"
#include "lfMotors.h"
#include "lfSensors.h"
#include "lfUtility.h"
#include "lfFollowBehavior.h"
#define MIN_COURSE_CORRECTION 2 // degrees
#define TURN_THRESHOLD 30 // cm
#define DRIVE_THRESHOLD 3 // inches
#define NOMINAL_DIST_CM DIST_25 // cm
#define MAX_DIST_TRAVEL_INCHES 6 // inches
void follow(DisplayArgs * const args)
{
IrDistance leftDist = args->distanceL;
IrDistance rightDist = args->distanceR;
if(leftDist < 0 || rightDist < 0)
{
return;
}
// Compute difference between the actual and goal distances in centimeters.
int leftDistToNominalCm = leftDist - NOMINAL_DIST_CM;
// abs() value of leftDistToTravel
// if(leftDistToNominalCm < 0)
// {
// leftDistToNominalCm = leftDistToNominalCm * -1.0;
// }
int rightDistToNominalCm = rightDist - NOMINAL_DIST_CM;
// abs() value of leftDistToTravel
// if(rightDistToNominalCm < 0)
// {
// rightDistToNominalCm = rightDistToNominalCm * -1.0;
// }
// Choose the minimum of the two distances to travel
int travelDistCm = MIN(leftDistToNominalCm, rightDistToNominalCm);
// Convert the travel distance from cm to inches.
int travelDistInches = intFloor(cmToInches(travelDistCm));
// Limit the distance that the robot can travel
if(travelDistInches > MAX_DIST_TRAVEL_INCHES)
{
travelDistInches = MAX_DIST_TRAVEL_INCHES;
}
else if(travelDistInches < -MAX_DIST_TRAVEL_INCHES)
{
travelDistInches = -MAX_DIST_TRAVEL_INCHES;
}
// Decide whether a slight course correction is needed
if(leftDistToNominalCm > rightDistToNominalCm &&
(leftDistToNominalCm - rightDistToNominalCm) > TURN_THRESHOLD)
{
// Turn right
turn(-MIN_COURSE_CORRECTION);
return;
}
else if(rightDistToNominalCm > leftDistToNominalCm &&
(rightDistToNominalCm - leftDistToNominalCm) > TURN_THRESHOLD)
{
// Turn left
turn(MIN_COURSE_CORRECTION);
return;
}
else
{
// Don't turn
}
// Only move forward/backward if travelDist falls within these ranges:
// -MAX_DIST_TRAVEL_INCHES <= travelDist <= -DIST_THRESHOLD < 0
// 0 < DIST_THRESHOLD <= travelDist <= MAX_DIST_TRAVEL_INCHES
//
// travelDistInches can be positive or negative, but the moveForward()
// and moveBackward() methods only expect positive numbers.
if(travelDistInches > DRIVE_THRESHOLD)
{
moveForward(travelDistInches, true);
}
else if(travelDistInches < -DRIVE_THRESHOLD)
{
moveBackward(-travelDistInches, true);
}
else
{
// Don't move
}
}
|
C
|
#include <clib/base_hdr.h>
#include <clib/stringlist.h>
#include <clib/string.h>
stringlist *stringlistCreate(stringlist *head, string *data, unsigned long index);
int stringlistEnd ( stringlist *current )
{
return ( current == NULL );
}
stringlist *stringlistNext ( stringlist *current )
{
if( current == NULL )
{
return current;
}
return current->next;
}
stringlist *stringlistBreak ( stringlist *current )
{
current = NULL;
return current;
}
void stringlistTraverse ( stringlist *head, stringlistTraverser traverser)
{
if( head != NULL )
{
if( traverser != NULL )
{
stringlist *cursor = head;
while( cursor != NULL )
{
traverser ( cursor );
cursor = cursor->next;
}
}
}
}
unsigned long stringlistLength ( stringlist *head )
{
unsigned long len = 0;
if( head == NULL )
{
return len;
}
stringlist *cursor = head;
while( cursor != NULL )
{
len++;
cursor = cursor->next;
}
return len;
}
void stringlistPrint ( stringlist *head, int count)
{
int idx = 0;
if( head != NULL )
{
stringlist *cursor = head;
while( cursor != NULL )
{
if( (count >= 0) && (idx == count) )
{
break;
}
if( cursor->data != NULL )
{
printf("%d ", cursor->index);
printStringLn ( cursor->data );
}
cursor = cursor->next;
idx++;
}
}else
{
printf ( "NULL\n" );
}
}
stringlist *stringlistAddFront ( stringlist *head, string *data)
{
stringlist *alist = stringlistCreate ( head, data, ( stringlistLength ( head ) + 1));
head = alist;
return head;
}
stringlist *stringlistAddBack ( stringlist *head, string *data)
{
if( head == NULL )
{
return stringlistAddFront (head, data);
}
stringlist *cursor = head;
while( cursor->next != NULL )
{
cursor = cursor->next;
}
stringlist *alist = stringlistCreate ( NULL, data, ( stringlistLength ( head ) + 1));
cursor->next = alist;
return head;
}
stringlist *stringlistRemoveFront ( stringlist *head )
{
if( head == NULL )
{
return head;
}
stringlist * cursor = head;
head = head->next;
cursor->next = NULL;
if( cursor == head )
{
head = NULL;
}
if( cursor->data != NULL )
{
cursor->data = deleteString(cursor->data);
}
free(cursor);
return head;
}
stringlist *stringlistRemoveBack ( stringlist *head )
{
if( head == NULL )
{
return head;
}
stringlist *cursor = head;
stringlist *back = NULL;
while( cursor->next != NULL )
{
back = cursor;
cursor = cursor->next;
}
if( back != NULL )
{
back->next = NULL;
}
if( cursor == head )
{
head = NULL;
}
if( cursor->data != NULL )
{
cursor->data = deleteString(cursor->data);
}
free(cursor);
return head;
}
stringlist *stringlistDestroy ( stringlist *head)
{
if( head == NULL )
{
return head;
}
stringlist *cursor = head;
head = NULL;
while( cursor != NULL )
{
cursor = stringlistRemoveFront(cursor);
}
return stringlistDestroy(cursor);
}
stringlist *stringlistSort ( stringlist *head )
{
if( head == NULL )
{
return head;
}
stringlist *x,*y,*e;
x = head;
head = NULL;
while( x != NULL )
{
e = x;
x = x->next;
if( head != NULL )
{
if( e->index > head->index )
{
y = head;
while( ( y->next != NULL ) && ( e->index > y->next->index ))
{
y = y->next;
}
e->next = y->next;
y->next = e;
}else
{
e->next = head;
head = e;
}
}else
{
e->next = NULL;
head = e;
}
}
return head;
}
stringlist * stringlistFindByIndex ( stringlist *head, unsigned long index)
{
if( head == NULL )
{
return NULL;
}
stringlist *cursor = head;
while( cursor != NULL )
{
if( cursor->index == index )
{
return cursor;
}
cursor = cursor->next;
}
return NULL;
}
stringlist *stringlistCreate(stringlist *head, string *data, unsigned long index)
{
stringlist * alist = NULL;
alist = (stringlist *) malloc(sizeof( stringlist ));
if( alist == NULL )
{
fprintf(stderr, "Out of memory\n");
exit(EXIT_FAILURE);
}
alist->index = index;
alist->data = data;
alist->next = head;
return alist;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>
#include <string.h>
#include "Communication.h"
/*CSCI311 project3 Zhao Xie
*This program is an interface, which will
*accept commands from the console and send
*them to the Server for execution. After
*executing the command, the Server will
*send the output to the Interface for display
*on the console.
*/
int
main(int argc,char *argv[]){
int toChild[2], toParent[2], status, n;
pid_t pid, return_pid;
char line[INFOSIZE],str1[10],str2[10];
if (pipe(toChild) < 0 || pipe(toParent) < 0)
printf("pipe error: %d/n",errno);
printf("Input command:\n");
if((pid = fork())<0){
printf("fork error: %d\n",errno);
}else if(pid>0){ /*parent*/
close(toChild[0]);
close(toParent[1]);
}else{ /*child*/
close(toChild[1]);
close(toParent[0]);
sprintf(str1,"%d",toChild[0]);
sprintf(str2,"%d",toParent[1]);
if (execl("./Server", "Server",str1,str2, NULL) < 0)
printf("execl error: %d/n",errno);
}
while (TRUE)
{
if(fgets(line, INFOSIZE, stdin) == NULL){
printf("fgets error\n");
printf("Input command(exit to quit):\n");
}else{
n = strlen(line);
if (write(toChild[1], line, n) != n)
printf("write error to pipe: %d/n",errno);
}
if ((n = read(toParent[0], line, INFOSIZE)) < 0)
printf("read error from pipe: %d/n",errno);
line[n] = 0; /* null terminate */
printf("response: %s",line);
if(strcmp(line,"Server complete.\n") == 0){
printf("Interface: child process (%d) completed.\n",pid);
break;
}
printf("Input command:\n");
}
/*checking the status of child*/
waitpid(pid,&status,WNOHANG);
printf("Interface: child process exit status = %d.\n",status);
printf("Interface: Complete.\n");
exit(0);
}
|
C
|
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
void citire(int v[], int n)
{
int i;
for (i = 0;i < n;i++) {
printf("v[%d] = ", i);
scanf("%d", &v[i]);
}
}
void egal(int v1[], int v2[], int n)
{
int i;
int egale = 1;
for (i = 0;i < n;i++) {
if (v1[i] != v2[i]) {
egale = 0;
}
}
if (egale)
printf("Elementele din v1 sunt egale cu cele din v2!\n");
else
printf("Elementele din v1 NU sunt egale cu cele din v2!\n");
}
int main() {
int n, v1[10], v2[10];
printf(" n = ");
scanf("%d", &n);
if (n >= 10) {
printf("\nNu indeplineste cerinta!\n\n");
exit(0);
}
printf("Citire vector1 : \n");
citire(v1, n);
printf("\n\n");
printf("Citire vector2 : \n");
citire(v2, n);
egal(v1, v2, n);
system("pause");
return 0;
}
|
C
|
#include "file.h"
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
// Implantation par tableau en file tournante
/*Conventions :
– Tête[F] pointe sur le premier élément à défiler
– Queue[F] pointe sur le premier emplacement libre
– Initialement Tête[F]=Queue[F]=0
– Longueur[F] retourne la taille maximale de F
– On dit que la File est vide si Tête[F]=Queue[F]
– On dit que la File est pleine si
Tête[F]=modulo(Queue[F]+1, longueur[F])//
*/
file creerFile() {
file f;
f.tete = 0;
f.queue = 0;
return f;
}
int fileVide(file * f) {
return (f->tete == f->queue);
}
int filePleine(file * f) {
return (f->tete == (f->queue+1)%MAXF);
}
int enfiler(file * f, int val) {
if(filePleine(f)) {
printf("Erreur : file pleine\n");
return 0;
} else {
f->tab[f->queue] = val;
f->queue = (f->queue+1)%MAXF;
return 1;
}
}
int defiler(file * f) {
int val;
if(fileVide(f)) {
return INT_MAX;
} else {
val = f->tab[f->tete]; // Récupère la valeur en tête
f->tete = (f->tete+1)%MAXF;
return val;
}
}
void afficherFile(file f) {
int i;
while((i=defiler(&f))!=INT_MAX) {
printf("%d\n", i);
}
}
|
C
|
/* File : usage.c */
#include <stdio.h>
int main () {
int a = 13, b = -9, i, *p = &a; // p is a pointer to int
for (i=0; i<10; i++) {
if ( *p > 0 ) {
p = &b ;
} else if ( *p < 0 ) {
p = &a ;
}
*p = *p + 1 ;
}
printf ( "The value of a and b are : %d and %d \n", a, b);
}
|
C
|
#include "utils.h"
#include "privilege_escalation.h"
int privilege_escalation(void) {
struct cred *new_cred;
if ((new_cred = prepare_creds ()) == NULL)
{
debug("Cannot prepare credentials");
return 0;
}
V(new_cred->uid) = V(new_cred->gid) = 0;
V(new_cred->euid) = V(new_cred->egid) = 0;
V(new_cred->suid) = V(new_cred->sgid) = 0;
V(new_cred->fsuid) = V(new_cred->fsgid) = 0;
commit_creds (new_cred);
return 1;
}
|
C
|
#include <stdio.h>
#include <time.h>
// experiment: two reverse functions reva(s) & revb(s)
// reva: simply assigns last string character to first and works towards middle
// revb: applies bubble sort with shift for iterations equal to length of s
// hypothesis: reva should be much faster than revb
// yh...
// reva: 1.375 seconds
// revb: 269.046 seconds
void reva(char[]);
void revb(char[]);
int main()
{
clock_t start, end;
double elapsed;
int relays = 10e5;
char s[] = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";
// time reva
start = clock();
for (int i = 0; i < relays; i++)
reva(s);
end = clock();
elapsed = (double)(end - start) / CLOCKS_PER_SEC;
printf("reva:\t%f\n", elapsed);
// time revb
start = clock();
for (int i = 0; i < relays; i++)
revb(s);
end = clock();
elapsed = (double)(end - start) / CLOCKS_PER_SEC;
printf("revb:\t%f\n", elapsed);
return 0;
}
void reva(char s[])
{
int l = 0;
while (s[l] != '\0')
l++;
char c;
int i, j;
for (i = 0, j = l - 1; i < j; i++, j--)
{
c = s[i];
s[i] = s[j];
s[j] = c;
}
}
void revb(char s[])
{
int l = 0;
while (s[l] != '\0')
l++;
char c;
for (int i = 0; i < l; i++)
{
for (int j = i % 2; j < (l - 1); j += 2)
{
c = s[j];
s[j] = s[j + 1];
s[j + 1] = c;
}
}
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_format_unsigneddecimal.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: statooin <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/07/29 05:56:31 by statooin #+# #+# */
/* Updated: 2020/07/29 05:56:34 by statooin ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
int ft_format_unsigneddecimal(t_format *pf_formats)
{
unsigned long long n;
if ((pf_formats->lengt & FLG_HH) != 0)
{
n = (unsigned char)va_arg(pf_formats->argus, unsigned int);
ft_format_uint(pf_formats, n);
}
else if ((pf_formats->lengt & FLG_H) != 0)
{
n = (unsigned short)va_arg(pf_formats->argus, unsigned int);
ft_format_uint(pf_formats, n);
}
else if ((pf_formats->lengt & FLG_LL) != 0 ||
(pf_formats->lengt & FLG_L) != 0)
{
n = va_arg(pf_formats->argus, unsigned long long);
ft_format_ullong(pf_formats, n);
}
else
{
n = (unsigned long long)va_arg(pf_formats->argus, unsigned int);
ft_format_uint(pf_formats, n);
}
return (1);
}
|
C
|
#include <stdio.h>
#include <malloc.h>
#include "ErrorCode.h"
#include "CException.h"
#include "Stack.h"
Stack *stackNew(int lengthOfStack)
{
Stack *stack = malloc(sizeof(Stack));
stack->buffer = malloc(sizeof(int) * lengthOfStack);
stack->size = 0;
stack->length = lengthOfStack;
return stack;
}
int stackisFull(Stack *stackPtr)
{
if(stackPtr->size > stackPtr->length)
return 0;
return 1;
}
void stackPush(Stack *stackPtr, int data)
{
stackPtr->buffer[stackPtr->size] = data;
stackPtr->size++;
if(!stackisFull(stackPtr))
Throw(ERR_STACK_FULL);
}
void StackDel(Stack *stack)
{
if(stack != NULL)
{
free(stack->buffer);
free(stack);
}
}
int stackisEmpty(Stack *stackPtr)
{
if(stackPtr->size == 0)
return 0;
return 1;
}
int stackPop(Stack *stackPtr)
{
int PopData;
if(!stackisEmpty(stackPtr))
Throw(ERR_STACK_EMPTY);
PopData = stackPtr->buffer[stackPtr->size-1];
stackPtr->size--;
return PopData;
}
|
C
|
//jbg@C@2@eLXgSSy[W@Tv2|3A͂AsȂB
//1423056@n糁@ā@2014/10/03
#include <stdio.h>
int main(){
printf("1+1=%d\n", 2);
printf("5-3=%d\n", 5-3);
printf("3*2=%d\n", 3*2);
printf("5/2=%d\n", 5/2);
printf("5%%2=%d\n", 5%2); //ƏŔA3͂ʼn
printf("1.5+1.4=%d\n", 1.5+1.4); //̌vZʂādijŏo
printf("1.5+1.4=%f\n", 1.5+1.4); //̌vZʂfŏo
printf("3+3=%d\n", 3+3);
printf("3+3=%3d\n", 3+3);
printf("1.5+1.4=%.2f\n", 1.5+1.4);
printf("1.5+1.4=%2.2f\n", 1.5+1.4);
printf("1.5+1.4=%4.2f\n",1.5+1.4);
printf("1.5+1.4=%5.2f\n",1.5+1.4);
printf("1.5+1.4=%6.2f\n",1.5+1.4);
return 0;
}
|
C
|
#include<stdio.h>
#include <string.h>
#include <stdlib.h>
#include <limits.h>
#define MAX_ELEMENTS_IN_ARRAY 100
#define error(...) (frpintf(stderr, __VA_ARGS__))
int read_array(int *array, size_t *array_size)
{
char div = ' ';
size_t element_count = 0;
while (div == ' ') {
if(scanf("%d%c", &array[element_count++], &div) < 2) {
error("Cannot read element");
return -32767;
}
}
*array_size = element_count;
return 0;
}
int set_parameters_values(int argv, char **argc, int *from, int *to)
{
if (argv < 2) {
return -1;
}
if (argv > 3) {
return -2;
}
int from_amount = 0;
int to_amount = 0;
for (int i = 1; i < argv; i++) {
if (strncmp(argc[i], "--from=", 7) == 0) {
from_amount++;
*from = (int)strtoll(argc[i] + 7, NULL, 10);
}
if (strncmp(argc[i], "--to=", 5) == 0) {
to_amount++;
*to = (int)strtoll(argc[i] + 5, NULL, 10);
}
}
if (from_amount > 1 || to_amount > 1) {
return -3;
}
if (from_amount == 0 && to_amount == 0) {
return -4;
}
return 0;
}
size_t count_swap(int const *first_array, int const *second_array, size_t arrays_size)
{
size_t swap_count = 0;
for (size_t i = 0; i < arrays_size; ++i) {
if (first_array[i] != second_array[i]) {
swap_count++;
}
}
return swap_count;
}
int create_new_array(int const *array, size_t array_size, int *new_array, size_t *new_size, int from, int to)
{
size_t new_element_count = 0;
for (size_t i = 0; i < array_size; ++i) {
if (array[i] > from && array[i] < to) {
new_array[new_element_count++] = array[i];
} else if (array[i] <= from) {
if (fprintf(stdout, "%d ", array[i]) < 0) {
error("Cannot write to stdout");
return -32767;
}
if (array[i] >= to) {
if (fprintf(stderr, "%d ", array[i]) < 0) {
error("Cannot write to stderr");
return -32767;
}
}
} else if (array[i] >= to) {
if (fprintf(stderr, "%d ", array[i]) < 0) {
error("Cannot write to stderr");
return -32767;
}
if (array[i] <= from) {
if (fprintf(stdout, "%d ", array[i]) < 0) {
error("Cannot write to stdout");
return -32767;
}
}
}
}
*new_size = new_element_count;
return 0;
}
void copy_array(int *dest, int const *src, size_t array_size)
{
for (size_t i = 0; i < array_size; ++i) {
dest[i] = src[i];
}
}
int main (int argv, char *argc[])
{
int from = INT_MIN;
int to = INT_MAX;
int errortype = set_parameters_values(argv, **argc, *from, *to);
if (errortype != 0)
{
return errortype;
}
size_t array_size = 0;
int *array = (int *)malloc(MAX_ELEMENTS_IN_ARRAY * sizeof(int));
if (array == NULL) {
error("Cannot allocate array");
return -32767;
}
int reading_result = read_array(array, &array_size);
if (reading_result != 0) {
return reading_result;
}
size_t new_array_size = 0;
int *new_array = (int *)malloc(MAX_ELEMENTS_IN_ARRAY * sizeof(int));
if (new_array == NULL) {
error("Cannot allocate new array");
return -32767;
}
int creating_status = create_new_array(array, array_size, new_array, &new_array_size, from, to);
if (creating_status != 0) {
return creating_status;
}
int *new_array_2 = (int *)malloc(new_array_size * sizeof(int));
if (new_array_2 == NULL) {
error("Cannot allocate new array(second)");
return -32767;
}
copy_array(new_array_2, new_array, new_array_size);
sort_array(new_array, new_array_size);
int swap_count = count_swap(new_array, new_array_2, new_array_size);
free(array);
free(new_array);
free(new_array_2);
return swap_count;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "WolframLibrary.h"
#define MAX(x, y) (((x) > (y)) ? (x) : (y))
#define MIN(x, y) (((x) < (y)) ? (x) : (y))
#define sqrt2 1.4142135623730951
//#define MAXDIM 500
DLLEXPORT mint WolframLibrary_getVersion( ) {
return WolframLibraryVersion;
}
DLLEXPORT int WolframLibrary_initialize( WolframLibraryData libData) {
return 0;
}
struct FitParams {
int nPrms;
double a;
double* b;
double* c;
double* d;
double* prms;
};
double sq(double in){
return in*in;
}
double* compute_gradient_LOCAL(struct FitParams dat)
{
int nPrms = dat.nPrms;
// if MAXDIM is not known at compile time
// then use dynamic variable arrays
#ifndef MAXDIM
#define MAXDIM nPrms
#endif
double prms[MAXDIM];
double a;
double b[MAXDIM];
double c[MAXDIM];
double d[MAXDIM*MAXDIM];
double* result = calloc(nPrms+1,sizeof(double));
//Copy data to stack
a = dat.a;
for(int i=0; i<nPrms; i++){
prms[i] = dat.prms[i];
b[i] = dat.b[i];
c[i] = dat.c[i];
}
for(int i=0; i<nPrms*nPrms; i++){
d[i] = dat.d[i];
}
double f0s[MAXDIM];
double f1s[MAXDIM];
double f2s[MAXDIM];
for(int i=0; i<nPrms; i++){
f0s[i] = (1 + cos(prms[i]))/2;
f1s[i] = sin(prms[i])/2;
f2s[i] = (1 - cos(prms[i]))/2;
}
//-------------------------------------------------------
// CALCULATE ENERGY
double aTerm, aProd;
aProd = 1.;
for(int i=0; i<nPrms; i++){
aProd = aProd * f0s[i];
}
aTerm = aProd * a;
double bTerm = 0.;
double cTerm = 0.;
for(int i=0; i<nPrms; i++){
bTerm += aProd/f0s[i]*f1s[i]*b[i];
cTerm += aProd/f0s[i]*f2s[i]*c[i];
}
double dTerm = 0.;
for(int i=0; i<nPrms; i++){
for(int j=i+1; j<nPrms; j++){
dTerm += aProd/f0s[i]/f0s[j]*f1s[i]*f1s[j]*d[j+nPrms*i];
}
}
double energy = aTerm + bTerm + cTerm + dTerm;
result[0] = energy;
//-------------------------------------------------------
double f0derivs[MAXDIM];
double f1derivs[MAXDIM];
double f2derivs[MAXDIM];
for(int i=0; i<nPrms; i++){
f0derivs[i] = -sin(prms[i])/2;
f1derivs[i] = cos(prms[i])/2;
f2derivs[i] = sin(prms[i])/2;
}
double aTermDerivs[MAXDIM];
for(int i=0; i<nPrms; i++){
aTermDerivs[i] = aProd/f0s[i]*f0derivs[i]*a;
}
double bTermDerivs[MAXDIM];
double cTermDerivs[MAXDIM];
for(int i=0; i<nPrms; i++){//gradient entries
bTermDerivs[i] = 0.;
cTermDerivs[i] = 0.;
for(int j=0; j<nPrms; j++){//B_j index j
if (i==j) {
bTermDerivs[i] += aProd/f0s[i]*f1derivs[i]*b[i];
cTermDerivs[i] += aProd/f0s[i]*f2derivs[i]*c[i];
}
else {
bTermDerivs[i] += aProd/f0s[i]/f0s[j]*f1s[j]*f0derivs[i]*b[j];
cTermDerivs[i] += aProd/f0s[i]/f0s[j]*f2s[j]*f0derivs[i]*c[j];
}
}
}
double dTermDerivs[MAXDIM];
for(int i=0; i<nPrms; i++){//gradient entries
dTermDerivs[i] = 0.;
for(int j=0; j<nPrms; j++){
for(int k=j+1; k<nPrms; k++){//D_{jk} index k//D_{jk} index k
if(i==j) {
dTermDerivs[i] += aProd/f0s[j]/f0s[k]*f1derivs[j]*f1s[k]*d[k+nPrms*j];
}
else if (i==k) {
dTermDerivs[i] += aProd/f0s[j]/f0s[k]*f1s[j]*f1derivs[k]*d[k+nPrms*j];
}
else {
dTermDerivs[i] += aProd/f0s[i]/f0s[j]/f0s[k]*f0derivs[i]*f1s[j]*f1s[k]*d[k+nPrms*j];
}
}
}
}
//--------------------------------
// RETURN RESULT
for(int i=0; i<nPrms; i++){
result[1+i] = aTermDerivs[i] + bTermDerivs[i] + cTermDerivs[i] + dTermDerivs[i];
}
return(result);
}
double* compute_variance_LOCAL(struct FitParams dat)
{
int nPrms = dat.nPrms;
// if MAXDIM is not known at compile time
// then use dynamic variable arrays
#ifndef MAXDIM
#define MAXDIM nPrms
#endif
double prms[MAXDIM];
double a;
double b[MAXDIM];
double c[MAXDIM];
double d[MAXDIM*MAXDIM];
double* result = calloc(1+2*nPrms+nPrms*nPrms,sizeof(double));
//Copy data to stack
a = dat.a;
for(int i=0; i<nPrms; i++){
prms[i] = dat.prms[i];
b[i] = dat.b[i];
c[i] = dat.c[i];
}
for(int i=0; i<nPrms*nPrms; i++){
d[i] = dat.d[i];
}
double f0s[MAXDIM];
double f1s[MAXDIM];
double f2s[MAXDIM];
for(int i=0; i<nPrms; i++){
f0s[i] = (1 + cos(prms[i]))/2;
f1s[i] = sin(prms[i])/2;
f2s[i] = (1 - cos(prms[i]))/2;
}
double aProd;
aProd = 1.;
for(int i=0; i<nPrms; i++){
aProd = aProd * f0s[i];
}
double f0derivs[MAXDIM];
double f1derivs[MAXDIM];
double f2derivs[MAXDIM];
for(int i=0; i<nPrms; i++){
f0derivs[i] = -sin(prms[i])/2;
f1derivs[i] = cos(prms[i])/2;
f2derivs[i] = sin(prms[i])/2;
}
double calA = 0.;
for(int i=0; i<nPrms; i++){
calA += sq(aProd/f0s[i]*f0derivs[i]);
}
result[0] = calA * a;
double calB[MAXDIM];
double calC[MAXDIM];
for(int j=0; j<nPrms; j++){//B_j index j
calB[j] = 0.;
calC[j] = 0.;
for(int i=0; i<nPrms; i++){//gradient entries
if (i==j) {
calB[j] += sq(aProd/f0s[i]*f1derivs[i]);
calC[j] += sq(aProd/f0s[i]*f2derivs[i]);
}
else {
calB[j] += sq(aProd/f0s[i]/f0s[j]*f1s[j]*f0derivs[i]);
calC[j] += sq(aProd/f0s[i]/f0s[j]*f2s[j]*f0derivs[i]);
}
}
result[j+1] = calB[j] * b[j];
result[j+1+nPrms] = calC[j] * c[j];
}
double calD[MAXDIM*MAXDIM];
for(int j=0; j<nPrms; j++){
for(int k=j+1; k<nPrms; k++){//D_{jk} index k//D_{jk} index k
calD[k+nPrms*j] = 0.;
for(int i=0; i<nPrms; i++){//gradient entries
if(i==j) {
calD[k+nPrms*j] += sq(aProd/f0s[j]/f0s[k]*f1derivs[j]*f1s[k]);
}
else if (i==k) {
calD[k+nPrms*j] +=sq(aProd/f0s[j]/f0s[k]*f1s[j]*f1derivs[k]);
}
else {
calD[k+nPrms*j] += sq(aProd/f0s[i]/f0s[j]/f0s[k]*f0derivs[i]*f1s[j]*f1s[k]);
}
}
result[1+2*nPrms + k+nPrms*j] = calD[k+nPrms*j] * d[k+nPrms*j];
}
}
return(result);
}
DLLEXPORT int compute_gradient(WolframLibraryData libData, mint Argc,
MArgument *Args, MArgument Res){
int err; // error code
MTensor m1; // input tensor
MTensor m2; // output tensor
mreal *argument1; // actual data of the input tensor
mreal *output; // data for the output tensor
mint nPrms;
m1 = MArgument_getMTensor(Args[0]);
nPrms = MArgument_getMTensor(Args[1]);
mint dimInput = libData->MTensor_getDimensions(m1);
mint dimOutput[1];
dimOutput[0] = nPrms + 1;
err = libData->MTensor_new(MType_Real, 1, dimOutput,&m2);
argument1 = libData->MTensor_getRealData(m1);
output = libData->MTensor_getRealData(m2);
int DoubleDataLength = nPrms*nPrms + 2*nPrms + 1 + nPrms;
double* DoubleData = calloc(DoubleDataLength,sizeof(double));
for(mint i = 0; i < DoubleDataLength; i++) {
DoubleData[i] = argument1[i];
}
struct FitParams dat;
dat.nPrms = (int) nPrms;
dat.a = DoubleData[0];
dat.b = &DoubleData[1];
dat.c = &DoubleData[1+nPrms];
dat.d = &DoubleData[1+2*nPrms];
dat.prms = &DoubleData[nPrms*nPrms+1+2*nPrms];
double* result = compute_gradient_LOCAL(dat);
for(mint i = 0; i < nPrms + 1; i++) {
output[i] = result[i];
}
MArgument_setMTensor(Res, m2);
free(DoubleData);
free(result);
return LIBRARY_NO_ERROR;
}
DLLEXPORT int compute_variance(WolframLibraryData libData, mint Argc,
MArgument *Args, MArgument Res){
int err; // error code
MTensor m1; // input tensor
MTensor m2; // output tensor
mreal *argument1; // actual data of the input tensor
mreal *output; // data for the output tensor
mint nPrms;
m1 = MArgument_getMTensor(Args[0]);
nPrms = MArgument_getMTensor(Args[1]);
mint dimInput = libData->MTensor_getDimensions(m1);
mint dimOutput[1];
dimOutput[0] = nPrms*nPrms + 2*nPrms + 1;
err = libData->MTensor_new(MType_Real, 1, dimOutput,&m2);
argument1 = libData->MTensor_getRealData(m1);
output = libData->MTensor_getRealData(m2);
int DoubleDataLength = nPrms*nPrms + 2*nPrms + 1 + nPrms;
double* DoubleData = calloc(DoubleDataLength,sizeof(double));
for(mint i = 0; i < DoubleDataLength; i++) {
DoubleData[i] = argument1[i];
}
struct FitParams dat;
dat.nPrms = (int) nPrms;
dat.a = DoubleData[0];
dat.b = &DoubleData[1];
dat.c = &DoubleData[1+nPrms];
dat.d = &DoubleData[1+2*nPrms];
dat.prms = &DoubleData[nPrms*nPrms+1+2*nPrms];
double* result = compute_variance_LOCAL(dat);
for(mint i = 0; i < nPrms*nPrms +2*nPrms + 1; i++) {
output[i] = result[i];
}
MArgument_setMTensor(Res, m2);
free(DoubleData);
free(result);
return LIBRARY_NO_ERROR;
}
|
C
|
#include <cblas.h>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
double *errors;
double a[] = {1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0};
double b[] = {2.0, 2.0, 2.0, 2.0, 1.0, 2.0, 2.0, 2.0, 2.0, 2.0};
int i;
errors = (double*)malloc(sizeof(double) * 10);
cblas_dgemv(10, a, b, errors);
i = 0;
while (i < 10)
{
printf("%f\n", errors[i]);
i++;
}
return (0);
}
|
C
|
/* Author: agonz250
* Partner(s) Name:
* Lab Section: 028
* Assignment: Lab # 8 Exercise #1
* Exercise Description: [optional - include for your own benefit]
*
* I acknowledge all content contained herein, excluding template or example
* code, is my own original work.
*/
#include <avr/io.h>
#ifdef _SIMULATE_
#include "simAVRHeader.h"
#endif
//adc stuff
void ADC_init() {
ADCSRA |= (1 << ADEN) | (1 << ADSC) | (1 << ADATE);
}
int main(void) {
/* Insert DDR and PORT initializations */
DDRA = 0x00; PORTA = 0xFF; // input
DDRB = 0xFF; PORTB = 0X00; //output
DDRD = 0xFF; PORTD = 0x00;
//unsigned char tmpC = 0x00;
unsigned char tmpD = 0x00;
unsigned short my_short = 0; //10 bit input from ADC
unsigned char my_char = 0;
//have to call this
ADC_init();
/* Insert your solution below */
while (1) {
//PORTA = ~PINA;
//Calculations
my_short = ADC; //10 bits to 8 bits
my_char = (char)my_short; //now 8 lower bits
tmpD = (char)(my_short >> 8); //Should be 2 upper bits
//Setting output
PORTB = my_char;
PORTD = tmpD;
}
return 1;
}
|
C
|
/**
* 连续输入字符串,请按长度为8拆分每个字符串后输出到新的字符串数组;
长度不是8整数倍的字符串请在后面补数字0,空字符串不处理。
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void output8C(char a[], int len)
{
int i = 0;
while (i < len)
{
printf("%c", a[i++]);
if ((i % 8) == 0)
printf("\n");
}
int left = 8 - i % 8;
if ((len % 8) != 0)
{
for (i = 0; i < left; ++i)
printf("0");
printf("\n");
}
}
int main()
{
char source[100];
gets(source);
output8C(source, strlen(source));
gets(source);
output8C(source, strlen(source));
}
|
C
|
/////////////////////////////////////////////////////////////////////////////
//
// Matthew Colliss
//
// 2d convolution with image and kernel
//
/////////////////////////////////////////////////////////////////////////////
#include "convolution.h"
void convolve(int target[],int kernal[],int kernalSize,int height,int width,IplImage *img)
{
//build 2d version if kernal
int kernal2D[kernalSize][kernalSize];
for(int i = 0; i < kernalSize;i++)
{
for(int j = 0; j < kernalSize;j++)
{
kernal2D[i][j] = kernal[(i * kernalSize) + j];
}
}
//create 2d matrix to temp hold results of convultion
int results[height][width];
//build 2d matrix rep of image data
//Initialise local variables
uchar* data = (uchar *)img->imageData;
int step = img->widthStep;
int image[height][width];
//build binary matrix representation of image
for(int i = 0; i < height;i++)
{
for(int j = 0; j < width; j++)
{
image[i][j] = data[(i*step) + j ];
//initialise results array while looping
results[i][j] = 0;
}
}
//iterate over all pixels
int margin = kernalSize / 2;
for(int i = margin;i < height-margin;i++)
{
for(int j = margin;j < width-margin;j++)
{
int sum = 0;
// memory release for img before exiting the application
for(int n = 0-margin;n <= 0 + margin; n++)
{
for(int m = 0-margin;m <= 0 + margin; m++)
{
if(m != 0 || n != 0)
{
sum += image[i + n][j + m] * kernal2D[margin - n][margin - m];
}
}
}
results[i][j] = sum;
}
}
//copy results into target image
for(int i = 0; i < height;i++)
{
for(int j = 0; j < width; j++)
{
target[(i * width) + j] = results[i][j];
}
}
}
|
C
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <errno.h>
#include <netdb.h>
#include <arpa/inet.h>
int main(int argc, char const *argv[])
{
int sockfd;
struct addrinfo hints, *results, *p;
struct sockaddr_in *ip_access;
int rv;
char hostname[200];
char ip[256];
char inputVal[256];
printf("Enter the domain name: ");
scanf("%s",inputVal);
strcpy(hostname,inputVal);
memset(&hints,0,sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
if((rv = getaddrinfo(hostname, "domain", &hints, &results)) != 0)
{
fprintf(stderr, "getaddrinfo: %s\n",gai_strerror(rv));
return 1;
}
for(p = results; p != NULL; p = p->ai_next)
{
ip_access = (struct sockaddr_in *) p->ai_addr;
printf("The IP adress is: %s \n",inet_ntoa(ip_access->sin_addr));
}
freeaddrinfo(results);
printf("\n");
return 0;
}
|
C
|
#include <stdio.h>
#include <math.h>
int main(){
long long value, hf, root, i , j;
int is_prime;
printf("Enter a number : ");
scanf("%lld", &value);
hf = (value / 2);
printf("Prime factors : ");
for(i = 2; i <= hf ; i = i+2){
if(i==4) --i;
//if i is dvisible
if(value % i == 0){
hf = value / i;
is_prime = 1;
root = sqrt(i);
//check up to root
for(j = 2; j <= root; ++j)
if(i % j == 0) is_prime = 0;
if(is_prime) printf("%lld ", i);
}
}
printf("\n");
}
|
C
|
set add_int(set s) {
return add(2 in add(1 in s));
// {1,2}
}
set add_float(set s) {
return add(5.4 in add(1.5 in s));
}
set add_set(set s) {
set newset;
newset = EMPTY;
return add(add_int(newset) in s);
//{{1,2}}
}
int main() {
set s;
s = EMPTY;
add_set(s);
// s = {{1,2}}
elem el;
exists(el in s);
// el is the set {1,2}
add_float(s);
// {1.5,5.4,{1,2}}
exists(el in s);
// el can be any of 1.5, 5.4 or {1,2}
add_int(s);
// add_int always returns {1,2} thus the set remains unchanged
// {1.5,5.4,{1,2}}
int acc; float accf;
acc = 0; accf = 0;
elem x;
forall(x in s) {
acc = acc + x; // when x is {1,2} the behaviour is undefined; this may raise an exception at runtime
accf = accf + x;
}
// this fixes the above
forall(x in s) {
if (!is_set(x)) {
acc = acc + x;
accf = accf + x;
}
}
// acc is 6; accf is 6.9
return 0.0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "hardware.h"
#include "bloc.h"
#include "common.h"
#include "volume.h"
#include "mbr.h"
#include "drive.h"
void execute(const char *name){
struct _cmd *c = commands;
while (c->name && strcmp (name, c->name))
c++;
(*c->fun)();
}
void boucleExec(void){
char name[64];
while (printf("> "), scanf("%s", name) == 1)
execute(name) ;
}
int main(void){
init();
load_mbr();
execute("help");
boucleExec();
return 0;
}
/*
int main (int argc, char **argv){
unsigned int i;
int bloc;
int rnd;
printf("Initialisation...\n");
init();
load_mbr();
printf("Fin Initialisation...\n");
do {
printf("Création new_bloc\n");
bloc = new_bloc();
printf("%i new_bloc()\n",bloc);
} while(bloc);
for(i=0; i<10; i++){
rnd = (rand() % 99) + 1;
printf("free_bloc(%i)\n",rnd);
free_bloc(rnd);
}
for(i=0; i<3; i++){
bloc = new_bloc();
printf("%i new_bloc()\n",bloc);
}
// and exit!
exit(EXIT_SUCCESS);
}
*/
|
C
|
#include <stdio.h>
#include <stdlib.h>
#define N 100
typedef struct {
int length;
int digits[N];
} BigDecimal;
void intToBigDecimal(int i, BigDecimal *d) {
d->length=0;
do {
d->digits[d->length]=i%10;
d->length++;
i/=10;
} while(i);
}
void shiftLeftBigDecimal(BigDecimal *d) {
int i;
for(i=d->length; i>0; i--) {
d->digits[i]=d->digits[i-1];
}
if(d->length>1||d->digits[0]!=0)
d->length++;
d->digits[0]=0;
}
void strToBigDecimal(char *str, BigDecimal *d) {
intToBigDecimal(0, d);
int count=0;
do {
shiftLeftBigDecimal(d);
count++;
d->digits[0]=*str-'0';
str++;
} while(*str!='\0');
printf("count: %d\n", count);
}
int compareBigDecimal(BigDecimal *d1, BigDecimal *d2) {
int i;
if(d1->length>d2->length)
return 1;
if(d2->length>d1->length)
return -1;
for(i=d1->length-1; i>=0; i--) {
if(d1->digits[i]>d2->digits[i])
return 1;
if(d2->digits[i]>d1->digits[i])
return -1;
}
return 0;
}
void show(BigDecimal *d) {
for(int i=d->length-1; i>=0; i--)
printf("%d", d->digits[i]);
printf("\n");
}
int main(int argc, char const *argv[])
{
BigDecimal *d=(BigDecimal *)malloc(sizeof(BigDecimal));
// intToBigDecimal(123456, d);
// show(d);
// shiftLeftBigDecimal(d);
// show(d);
// strToBigDecimal("99999999999999999999999999999999999999999999999999", d);
// show(d);
BigDecimal *d1=(BigDecimal *)malloc(sizeof(BigDecimal));
intToBigDecimal(123756, d);
intToBigDecimal(123156, d1);
printf("%d\n", compareBigDecimal(d, d1));
return 0;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#define TAM_VETOR 60
#define MAX_ALEATORIO 356
int main () {
int a[TAM_VETOR], b[TAM_VETOR], c[TAM_VETOR*2],freq[TAM_VETOR], i, j, k, tam_uniao=0, cont;
//Zerando todas as posies de tam_uniao
for (i=0; i<TAM_VETOR; i++ ){
freq[i]=0;
}
srand(time(NULL));
for (k=0; k<1000; k++) {
//Preenche o vetor A com valores aleatrios
for (i=0; i<TAM_VETOR; i++) {
a[i]=rand() % MAX_ALEATORIO;
}
//Preenche o vetor B com valores aleatrios
for (i=0; i<TAM_VETOR; i++) {
b[i]=rand() % MAX_ALEATORIO;
}
//Preenche o vetor C com valores de A e B
for (i=0; i<TAM_VETOR ; i++) {
c[i]=a[i];
c[TAM_VETOR+i]=b[i];
}
//Compara e imprimi apenas valores que nao se repetem
for (i=0; i<TAM_VETOR*2; i++) {
cont=0;
for (j=i; j>0 ; j-- ) {
if (c[i]==c[j])
cont=cont+1;
}
if (cont == 1)
tam_uniao++;
}
if (tam_uniao<TAM_VETOR)
freq[tam_uniao]=freq[tam_uniao]+1;
}
printf("Frequencia = ( ");
for (i=0; i<TAM_VETOR; i++) {
printf("%d, ");
}
printf(")\n\n");
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.