language
large_stringclasses 1
value | text
stringlengths 9
2.95M
|
---|---|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* parser_tests.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gpouyat <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/05/24 11:31:14 by gpouyat #+# #+# */
/* Updated: 2017/07/30 22:47:06 by gpouyat ### ########.fr */
/* */
/* ************************************************************************** */
#include <tests/sh_tests.h>
/*
** @brief Main function to test the parser.
**
** @param av The input sent to the testing module
*/
void sh_testing_parser(char *const *av)
{
t_automaton automaton;
t_array tokens;
if (ft_strlen(av[0]) >= MAX_LEN_INPUT)
sh_exit_printf("line is too long: %zu, MAX is %zu", ft_strlen(av[0]),
MAX_LEN_INPUT);
else if (ft_strlen(av[0]) && !is_printstr(av[0]))
sh_exit_printf("line: contains non-ascii characters.");
if (lexer_init(&tokens) == NULL)
sh_exit_error("Error initialising tokens");
else if (automaton_init(&automaton) == NULL)
sh_exit_error("Error initialising automaton");
else if (lexer_lex(&tokens, av[0]) == E_RET_LEXER_OK)
{
if (parser_parse(&tokens) == E_RET_PARSER_OK)
{
ft_printf("Parser say OK\n");
exit(0);
}
sh_exit_error("Parser");
}
else
sh_exit_error("Fatal testing error: Couldn't catch the error.");
}
|
C
|
/*
** params.h for tetris in /home/raphael.goulmot/rendu/PSU_2016_tetris
**
** Made by Raphaël Goulmot
** Login <[email protected]>
**
** Started on Thu Mar 2 09:54:34 2017 Raphaël Goulmot
** Last update Sun Mar 19 18:45:40 2017 Raphaël Goulmot
*/
#include <stdlib.h>
#include <stdio.h>
#include <getopt.h>
#include "struct.h"
#include "utils.h"
#include "usage.h"
#include "commands.h"
static void (* const list_ptsFunction[])(char *o, t_world *i, char p) = {
&usage,
&debug,
&key_x,
&level,
&next,
&map
};
static const struct option long_options[] =
{
{"help", no_argument, 0, 0},
{"d", no_argument, 0, 1},
{"debug", no_argument, 0, 1},
{"kt", required_argument, 0, 2},
{"key-turn", required_argument, 0, 2},
{"kd", required_argument, 0, 3},
{"key-drop", required_argument, 0, 3},
{"kl", required_argument, 0, 4},
{"key-left", required_argument, 0, 4},
{"kr", required_argument, 0, 5},
{"key-right", required_argument, 0, 5},
{"kq", required_argument, 0, 6},
{"key-quit", required_argument, 0, 6},
{"kp", required_argument, 0, 7},
{"key-pause", required_argument, 0, 7},
{"l", required_argument, 0, 8},
{"level", required_argument, 0, 8},
{"w", no_argument, 0, 9},
{"without-next", no_argument, 0, 9},
{"max-size", required_argument, 0, 10},
{0, 0, 0, 0}
};
char check_params(char *str)
{
int i;
if ((i = 0) || !str || my_strlen(str) < 2)
return (0);
else if (str[0] == '-' && str[1] != '-')
while (str[i++])
{
if (str[i - 1] == '=')
return (0);
}
return (1);
}
void parse_commands(int argc, char **argv, t_world *world)
{
int i;
int opt;
i = 0;
world->name = argv[0];
while ((opt = getopt_long_only(argc, argv, "", long_options, &i)) != -1)
{
if (opt != '?' && check_params(argv[optind - 1]))
{
if (opt >= 2 && opt <= 7)
(*list_ptsFunction[2])(optarg, world, opt - 2);
else
(*list_ptsFunction[opt > 7 ? opt - 5 : opt])(optarg, world, 0);
}
else
exit (84);
}
if (optind < argc)
{
my_putstr_err("ERROR : Non-option elements : ");
while (optind < argc && (argv[optind] = stick_string(argv[optind], " ")))
my_putstr_err(argv[optind++]);
my_putstr_err("\n");
exit (84);
}
}
|
C
|
#include <stdio.h>
#include <wiringPi.h>
#include<unistd.h>
#define GPIO 12 //gpio 15 orange pi zero
int main()
{
int speed = 1500; //MINIMO 1000 MAXIMO 2000
wiringPiSetup();
pinMode (GPIO, OUTPUT);
//INICIO CONTROLADOR ESC
/*
Pulsos de 2000us durante 2.5 segundos
|--------| pulso de 2000us para indicar el pulso mas alto al controlador ESC
_______ 3.3v
| | |
| | |
| |__________________________________| 0 V
|------------------------------------------| 20000 us periodo del controlador ESC
2500 ms / 20 ms = 125 pulsos;
*/
for(int i=0;i<125;i++)
{
digitalWrite(GPIO, HIGH);
usleep(2000);//2ms (cambiar por 1000 si tu controlador se inicia al contrario)
digitalWrite(GPIO, LOW);
usleep(18000);//18ms
}
/*
Pulsos de 1000us durante 2.5 segundos
|----| pulso de 1000us para indicar el pulso mas bajo al controlador ESC
____ 3.3v
| | |
| | |
| |______________________________________| 0 V
|-------------------------------| 20000 us periodo del controlador ESC
2500 ms / 20 ms = 125 pulsos;
*/
for(int i=0;i<125;i++)
{
digitalWrite(GPIO, HIGH);
usleep(1000);//1ms (cambiar por 2000 si tu controlador se inicia al contrario)
digitalWrite(GPIO, LOW);
usleep(19000);//19ms
}
//FIN INICIO CONTROLADOR ESC
//Inicio Giro del motor
while(1)
{
digitalWrite(GPIO, HIGH);
usleep(speed);//us
digitalWrite(GPIO, LOW);
usleep(20000-speed);//us
}
return 0;
}
|
C
|
#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
/*
int dup2(int oldfd, int newfd);
dup2()
The dup2() system call performs the same task as dup(), but instead of
using the lowest-numbered unused file descriptor, it uses the file
descriptor number specified in newfd. If the file descriptor newfd was
previously open, it is silently closed before being reused.
The steps of closing and reusing the file descriptor newfd are per‐
formed atomically. This is important, because trying to implement
equivalent functionality using close(2) and dup() would be subject to
race conditions, whereby newfd might be reused between the two steps.
Such reuse could happen because the main program is interrupted by a
signal handler that allocates a file descriptor, or because a parallel
thread allocates a file descriptor.
Note the following points:
* If oldfd is not a valid file descriptor, then the call fails, and
newfd is not closed.
* If oldfd is a valid file descriptor, and newfd has the same value as
oldfd, then dup2() does nothing, and returns newfd.
RETURN VALUE
On success, these system calls return the new file descriptor. On
error, -1 is returned, and errno is set appropriately.
ERRORS
EBADF oldfd isn't an open file descriptor.
EBADF newfd is out of the allowed range for file descriptors (see the
discussion of RLIMIT_NOFILE in getrlimit(2)).
EBUSY (Linux only) This may be returned by dup2() or dup3() during a
race condition with open(2) and dup().
EINTR The dup2() or dup3() call was interrupted by a signal; see sig‐
nal(7).
EMFILE The per-process limit on the number of open file descriptors has
been reached (see the discussion of RLIMIT_NOFILE in getr‐
limit(2)).
*/
typedef struct {
int* data;
size_t size;
size_t capacity;
} Stack;
static Stack*
stack_new(void)
{
Stack* s = malloc(sizeof(Stack));
assert(s != NULL);
s->size = 0;
s->capacity = 64;
s->data = malloc(s->capacity * sizeof(int));
assert(s->data != NULL);
return s;
}
static int
stack_size(Stack* const s)
{
return s->size;
}
static void
stack_push(Stack* const s, const int item)
{
if (s->size == s->capacity) {
s->capacity *= 2;
s->data = realloc(s->data, s->capacity * sizeof(int));
assert(s->data != NULL);
}
s->data[s->size++] = item;
}
static int
stack_pop(Stack* const s)
{
return s->data[s->size--];
}
static void
stack_destroy(Stack* const s)
{
free(s->data);
free(s);
}
/**
* Note: I don't know of a way to satisfy the atomic requirement in userspace,
* so this implementation is subject to the race conditions mentioned
* in the man page.
*
* Also note that this will be subject to limits on the number of
* open file descriptors.
*/
static int
my_dup2(const int oldfd, const int newfd)
{
if (oldfd < 0 || newfd < 0) {
errno = EBADF;
return -1;
}
if (oldfd == newfd) {
return newfd;
}
int fd = dup(oldfd);
if (fd < 0) {
errno = EBADF;
return -1;
}
// oldfd is valid
close(fd);
// Silently ignore EBADF
if (close(newfd) < 0 && errno != EBADF) {
// errno will be set by close
return -1;
}
Stack* s = stack_new();
while ((fd = dup(oldfd)) != newfd) {
stack_push(s, fd);
}
// Now newfd is a dup of oldfd, and the stack contains all the
// intermediate dups
while (stack_size(s) > 0) {
fd = stack_pop(s);
close(fd);
}
stack_destroy(s);
s = NULL;
return newfd;
}
/*
Sample output:
$ ./a.out
total 0
lrwx------ 1 user group 64 Apr 8 20:56 0 -> /dev/pts/0
lrwx------ 1 user group 64 Apr 8 20:56 1 -> /dev/pts/0
lrwx------ 1 user group 64 Apr 8 20:56 2 -> /dev/pts/0
lr-x------ 1 user group 64 Apr 8 20:56 3 -> /dev/zero
total 0
lrwx------ 1 user group 64 Apr 8 20:56 0 -> /dev/pts/0
lrwx------ 1 user group 64 Apr 8 20:56 1 -> /dev/pts/0
lrwx------ 1 user group 64 Apr 8 20:56 2 -> /dev/pts/0
lr-x------ 1 user group 64 Apr 8 20:56 3 -> /dev/zero
lrwx------ 1 user group 64 Apr 8 20:56 42 -> /dev/pts/0
total 0
lrwx------ 1 user group 64 Apr 8 20:56 1 -> /dev/pts/0
lrwx------ 1 user group 64 Apr 8 20:56 2 -> /dev/pts/0
lr-x------ 1 user group 64 Apr 8 20:56 3 -> /dev/zero
lr-x------ 1 user group 64 Apr 8 20:56 4 -> /dev/zero
lr-x------ 1 user group 64 Apr 8 20:56 42 -> /dev/zero
*/
int
main(void)
{
const int TARGET_FD = 42;
char buffer[64] = {};
snprintf(buffer, sizeof(buffer) - 1, "ls -l /proc/%d/fd", getpid());
// Open some file
int fd1 = open("/dev/zero", O_RDONLY);
if (fd1 < 0) {
perror("open");
return 1;
}
system(buffer);
// Create a gap
int fd2 = dup2(1, TARGET_FD);
if (fd2 < 0) {
perror("dup2");
return 1;
}
system(buffer);
// Try to replace TARGET_FD with /dev/zero
int fd3 = my_dup2(fd1, TARGET_FD);
if (fd3 < 0) {
perror("my_dup2");
return 1;
}
system(buffer);
return 0;
}
|
C
|
//*H29年度/dsp2-1/5J06*//
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#define MAX_SIZE 16384
//#define M_PI 3.14159265359
typedef struct {
double re; //実部
double im; //虚部
} complex_t;
FILE * openFile();
FILE * openFile_2();
complex_t comp_add(complex_t in1, complex_t in2);
complex_t comp_sub(complex_t in1, complex_t in2);
complex_t comp_multiply(complex_t in1, complex_t in2);
complex_t comp_division(complex_t in1, complex_t in2);
complex_t comp_conjugate(complex_t in);
void twiddle_factor(complex_t *wnk, int n, double a);
void bit_r(int *bit, int N);
void convert_r(complex_t *in, int *bit, int N);
void fft(complex_t *in, complex_t *wnk, int N);
void power_spectral(complex_t *in1, complex_t *in2, complex_t *ps, int N);
int power(int n);
void cc(double *data[],int size1);
void correlation_function(complex_t *x1, complex_t *x2, complex_t *ps, int size, int N);
int main(){
int i, j, N, size1, size2, p;
complex_t x1[MAX_SIZE], x2[MAX_SIZE], ps[MAX_SIZE];
FILE *fp1, *fp2, *fq;
printf("\nH29 課題1 出席番号06\n");
printf("~使い方~\n");
printf("・読み込む2つのテキストファイルを同じディレクトリに置いて下さい\n");
printf("・自己相関または相互相関を求めテキストファイルを出力します\n");
printf("~実行環境~\n");
printf("OS : OS El Capitan (Version 10.11.6)\nプロセッサ : 1.7 GHz Intel Core i7\nメモリ : 8 GB 1600 MHz DDR3\n");
printf("1つ目のファイル名を入力: ");
fp1 = openFile();
printf("2つ目のファイル名を入力: ");
fp2 = openFile();
fq = openFile_2();
size1 = 0;
size2 = 0;
while((j = getc(fp1)) != EOF) if(j == '\n') size1++;
while((j = getc(fp2)) != EOF) if(j == '\n') size2++;
if(size1 != size2){
printf("error\n");
return 0;
}
//点数決定
p = power(size1*2);
N = pow(2, p);
// 構造体初期化
for(i=0;i<MAX_SIZE;i++){
x1[i].re = 0;
x1[i].im = 0;
x2[i].re = 0;
x2[i].im = 0;
ps[i].re = 0;
ps[i].im = 0;
}
//読み込みデータを構造体に代入
fseek(fp1, 0L, SEEK_SET);
fseek(fp2, 0L, SEEK_SET);
for(i=0;i<size1;i++) fscanf(fp1,"%lf", &x1[i].re);
for(i=0;i<size2;i++) fscanf(fp2,"%lf", &x2[i].re);
fclose(fp1);
fclose(fp2);
correlation_function(x1,x2,ps,size1,N);
for(i=0;i<size1;i++){
fprintf(fq, "%f\n", ps[i].re);
}
fclose(fq);
return 0;
}
FILE* openFile(){
char file[128];
// printf("Enter the input file name: ");
scanf("%s",file);
FILE *fp = fopen(file,"r");
if (fp==NULL) {
printf("can't open the input file\n");
exit(0);
}
return fp;
}
FILE* openFile_2(){
char file[128];
printf("出力ファイル名を入力: ");
scanf("%s",file);
FILE *fp = fopen(file,"w");
if (fp==NULL) {
printf("can't open the output file\n");
exit(0);
}
return fp;
}
complex_t comp_add(complex_t in1, complex_t in2){
complex_t res;
res.re = in1.re + in2.re;
res.im = in1.im + in2.im;
return res;
}
complex_t comp_sub(complex_t in1, complex_t in2){
complex_t res;
res.re = in1.re - in2.re;
res.im = in1.im - in2.im;
return res;
}
complex_t comp_multiply(complex_t in1, complex_t in2){
complex_t res;
res.re = (in1.re * in2.re) - (in1.im * in2.im);
res.im = (in1.re * in2.im) + (in1.im * in2.re);
return res;
}
complex_t comp_division(complex_t in1, complex_t in2){
complex_t res;
complex_t in2_copy = comp_conjugate(in2);
res = comp_multiply(in1, in2_copy);
res.re /= comp_multiply(in2, in2_copy).re;
res.im /= comp_multiply(in2, in2_copy).re;
return res;
}
complex_t comp_conjugate(complex_t in){
complex_t res;
res.re = in.re;
res.im = -1 * in.im;
return res;
}
void twiddle_factor(complex_t *wnk, int n, double a){
int i;
for(i=0;i<n;i++){
wnk[i].re = cos(a*2*M_PI/n*i);//回転子の値
wnk[i].im = sin(a*-2*M_PI/n*i);
}
}
void bit_r(int *bit, int N){
int r,i,j;
r = (int)(log(N)/log(2.0) + 0.5);
for(i=0;i<N;i++){
bit[i] = 0;
for(j=0;j<r;j++){
bit[i] += ((i >> j) & 1) << (r-j-1);
}
}
}
void convert_r(complex_t *in, int *bit, int N){
int i;
complex_t comp[N];
for(i=0;i<N;i++){
comp[i].re = in[i].re;
comp[i].im = in[i].im;
}
for(i=0;i<N;i++){
in[i].re = comp[bit[i]].re;
in[i].im = comp[bit[i]].im;
}
}
void fft(complex_t *in, complex_t *wnk, int N){
int r_big = 1, r_sma = N / 2; //初期値を与えておく
int i, j, k, in1, in2, nk, r;
complex_t dummy;
clock_t start, end;
r = (int)(log(N) / log(2.0) + 0.5);
start = clock();
for(i=0;i<r;i++){// ビット回繰り返し(段数回)
for(j=0;j<r_big;j++){//繰り返しが段々増える
for(k=0;k<r_sma;k++){//繰り返しが段々減る:(j+k)の合計=N/2回の繰り返し
in1 = r_big * 2 * k + j; //バタ上段の入力順番
in2 = in1 + r_big; //バタ下段の入力順番
nk = j * r_sma; //回転子の番号
dummy = comp_multiply(in[in2], wnk[nk]);//バタ入力下段×重みWnk
in[in2] = comp_sub(in[in1], dummy);//バタ演算の下段出力(そのまま次段の入力)
in[in1] = comp_add(in[in1], dummy); //バタ演算の上段出力(そのまま次段の入力)
}
}
r_big *= 2; // 2^i :1,2,4...N/2まで増加
r_sma /= 2; // 2^(r-1-i):N/2...4.2.1まで減少
}
end = clock();
printf( "処理時間:%lf[s]\n", (double)(end - start)/CLOCKS_PER_SEC);
}
void power_spectral(complex_t *in1, complex_t *in2, complex_t *ps, int N){
int i;
for(i=0;i<N;i++) ps[i].re = (in1[i].re * in2[i].re) + (in1[i].im * in2[i].im);
}
int power(int n){
return (int)ceil(log10(n) / log10(2));
}
void correlation_function(complex_t *x1, complex_t *x2, complex_t *ps, int size, int N){
int i;
int bit[MAX_SIZE];
complex_t r[MAX_SIZE];
for(i=0;i<MAX_SIZE;i++){
r[i].re = 0;
r[i].im = 0;
}
twiddle_factor(r, N, 1); //回転子生成
bit_r(bit,N); //ビットリバーサル
//データ入れ替え
convert_r(x1,bit,N);
convert_r(x2,bit,N);
//FFT
fft(x1,r,N);
fft(x2,r,N);
power_spectral(x1,x2,ps,N);
// IFFT
twiddle_factor(r, N, -1); //回転子生成
bit_r(bit,N); //ビットリバーサル
convert_r(ps,bit,N);
fft(ps,r,N);
for(i=0;i<N;i++) {
ps[i].re /= N * size;
ps[i].im /= N * size;
}
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#define BITS_PER_BYTE 8
void dec_to_bin(const unsigned char value)
{
char i = (BITS_PER_BYTE * sizeof(unsigned char));
char bit;
for (i -= 1; i >= 0; i--) {
bit = value >> i;
if (bit & 1) {
printf("1");
} else {
printf("0");
}
}
printf("\n");
}
int main(void)
{
unsigned char value1, value2, result;
scanf("%hhu %hhu", &value1, &value2);
dec_to_bin(value1);
result = value1 >> value2;
printf("%hhu deslocado %hhu bits a direita: ", value1, value2);
dec_to_bin(result);
result = value1 << value2;
printf("%hhu deslocado %hhu bits a esquerda: ", value1, value2);
dec_to_bin(result);
return 0;
}
|
C
|
#include "holberton.h"
/**
*add - two integers
*@x: number
*@z: number
*
*Return: return the sum
*/
int add(int x, int z)
{
return (x + z);
}
|
C
|
//
// Who to blame: Geoff Chesshire and Bill Henshaw
//
#include "MappedGrid.h"
#include "LineMapping.h"
#include "SquareMapping.h"
#include "BoxMapping.h"
#include "ReparameterizationTransform.h"
#include "UnstructuredMapping.h"
#include <algorithm>
#include "ParallelUtility.h"
#include "App.h"
#ifdef USE_STL
#include "RCVector.h"
RCVector_STATIC_MEMBER_DATA(MappedGrid)
#endif // USE_STL
// int MappedGrid::minimumNumberOfDistributedGhostLines=0;
//
// class MappedGrid:
//
// Public member functions:
//
// Default constructor.
//
// If numberOfDimensions_==0 (e.g., by default) then create a null
// MappedGrid. Otherwise, create a MappedGrid with the given
// number of dimensions.
//
MappedGrid::
MappedGrid(const Integer numberOfDimensions_) : GenericGrid()
{
className = "MappedGrid";
if( false )
{
rcData=NULL;
isCounted=false;
}
else
{
rcData = new MappedGridData(numberOfDimensions_);
isCounted = LogicalTrue;
rcData->incrementReferenceCount();
updateReferences();
}
parentChildSiblingInfo = NULL;
}
// *wdh* This function could be used to delay the creation of the rcData.
void MappedGrid::
init(int numberOfDimensions_)
{
assert( rcData==NULL );
rcData = new MappedGridData(numberOfDimensions_);
isCounted = LogicalTrue;
rcData->incrementReferenceCount();
updateReferences();
}
//
// Copy constructor. (Does a deep copy by default.)
//
MappedGrid::MappedGrid(
const MappedGrid& x,
const CopyType ct):
GenericGrid(x, ct) {
className = "MappedGrid";
switch (ct) {
case DEEP:
case NOCOPY:
rcData = (MappedGridData*)
((ReferenceCounting*)x.rcData)->virtualConstructor(ct);
isCounted = LogicalTrue;
rcData->incrementReferenceCount();
break;
case SHALLOW:
rcData = x.rcData;
isCounted = x.isCounted;
if (isCounted) rcData->incrementReferenceCount();
break;
} // end switch
updateReferences();
parentChildSiblingInfo = x.parentChildSiblingInfo;
}
//
// Constructor from a mapping.
//
MappedGrid::MappedGrid(Mapping& x):
GenericGrid() {
className = "MappedGrid";
rcData = new MappedGridData;
isCounted = LogicalTrue;
rcData->incrementReferenceCount();
rcData->gridType=x.getClassName()=="UnstructuredMapping" ? unstructuredGrid : structuredGrid;
updateReferences();
parentChildSiblingInfo = NULL;
reference(x);
}
MappedGrid::
MappedGrid(MappingRC& x)
{
className = "MappedGrid";
rcData = new MappedGridData;
isCounted = LogicalTrue;
rcData->incrementReferenceCount();
rcData->gridType=x.getClassName()=="UnstructuredMapping" ? unstructuredGrid : structuredGrid;
updateReferences();
parentChildSiblingInfo = NULL;
reference(x);
}
//
// Destructor.
//
MappedGrid::
~MappedGrid()
{
if (isCounted && rcData->decrementReferenceCount() == 0) delete rcData;
}
//
// Assignment operator. (Does a deep copy.)
//
MappedGrid& MappedGrid::
operator=(const MappedGrid& x)
{
// GenericGrid::operator=(x);
if( rcData==NULL && x.rcData!=NULL )
init(x.numberOfDimensions());
if (rcData != x.rcData)
{
if (rcData->getClassName() == x.rcData->getClassName())
{
// (ReferenceCounting&)*rcData = (ReferenceCounting&)*x.rcData;
rcData->equals(*x.rcData);
updateReferences();
}
else
{
MappedGrid& y = *(MappedGrid*)x.virtualConstructor();
reference(y); delete &y;
} // end if
} // end if
parentChildSiblingInfo = x.parentChildSiblingInfo;
return *this;
}
// ====================================================================================
// /Description:
// Equals operator plus options. This version is used when copying a GridCollection
// that has AMR grids -- in which case we do not want to make a deep copy of the Mapping.
//
// /options (input): (options & 2)==1 : do NOT copy the mapping
// ====================================================================================
MappedGrid& MappedGrid::
equals(const MappedGrid& x, int option /* =0 */ )
{
// GenericGrid::operator=(x);
if( rcData==NULL && x.rcData!=NULL )
init(x.numberOfDimensions());
if (rcData != x.rcData)
{
if (rcData->getClassName() == x.rcData->getClassName())
{
// (ReferenceCounting&)*rcData = (ReferenceCounting&)*x.rcData;
rcData->equals(*x.rcData,option);
updateReferences();
}
else
{
MappedGrid& y = *(MappedGrid*)x.virtualConstructor();
reference(y); delete &y;
} // end if
} // end if
parentChildSiblingInfo = x.parentChildSiblingInfo;
return *this;
}
//
// Make a reference. (Does a shallow copy.)
//
void MappedGrid::
reference(const MappedGrid& x)
{
GenericGrid::reference(x);
if (rcData != x.rcData)
{
if(isCounted && rcData->decrementReferenceCount() == 0)
delete rcData;
rcData = x.rcData;
isCounted = x.isCounted;
if (isCounted) rcData->incrementReferenceCount();
updateReferences();
} // end if
parentChildSiblingInfo = x.parentChildSiblingInfo;
}
void MappedGrid::
reference(MappedGridData& x)
{
GenericGrid::reference(x);
if( rcData != &x)
{
if (isCounted && rcData->decrementReferenceCount() == 0)
delete rcData;
rcData = &x;
isCounted = !x.uncountedReferencesMayExist();
if (isCounted) rcData->incrementReferenceCount();
updateReferences();
} // end if
}
MappedGrid::BoundaryFlagEnum MappedGrid::
boundaryFlag(int side, int axis ) const
{
return (BoundaryFlagEnum)rcData->boundaryFlag[side][axis];
}
//\begin{>>MappedGridInclude.tex}{\subsubsection{setMapping}}
void MappedGrid::
setMapping(Mapping& x)
// ==========================================================================
// /Description:
// Use a given mapping.
//\end{MappedGridInclude.tex}
//==========================================================================
{
reference(x);
}
//\begin{>>MappedGridInclude.tex}{\subsubsection{setMapping}}
void MappedGrid::
setMapping(MappingRC& x)
// ==========================================================================
// /Description:
// Use a given mapping.
//\end{MappedGridInclude.tex}
//==========================================================================
{
reference(x);
}
//\begin{>>MappedGridInclude.tex}{\subsubsection{setMinimumNumberOfDistributedGhostLines}}
void MappedGrid::
setMinimumNumberOfDistributedGhostLines( int numGhost )
// ==========================================================================
// /Description:
// On Parallel machines always add at least this many ghost lines on the arrays
// that are local to each processor.
//\end{MappedGridInclude.tex}
//==========================================================================
{
minimumNumberOfDistributedGhostLines=numGhost;
}
//\begin{>>MappedGridInclude.tex}{\subsubsection{getMinimumNumberOfDistributedGhostLines}}
int MappedGrid::
getMinimumNumberOfDistributedGhostLines()
// ==========================================================================
// /Description:
// On Parallel machines we always add at least this many ghost lines on the arrays
// that are local to each processor.
//\end{MappedGridInclude.tex}
//==========================================================================
{
return minimumNumberOfDistributedGhostLines;
}
void MappedGrid::
setNumberOfDimensions(const Integer& numberOfDimensions_)
{
assert( rcData!=NULL );
if (numberOfDimensions() != numberOfDimensions_) destroy(~NOTHING);
rcData->numberOfDimensions = numberOfDimensions_;
}
void MappedGrid::
setBoundaryCondition( const Integer& ks, const Integer& kd, const Integer& boundaryCondition_)
{
rcData->boundaryCondition(ks,kd) = boundaryCondition_;
// alter the boundaryFlag if appropriate
if( rcData->boundaryCondition(ks,kd)<=0 ||
rcData->boundaryFlag[ks][kd]!=MappedGridData::mixedPhysicalInterpolationBoundary )
{
rcData->boundaryFlag[ks][kd]=rcData->boundaryCondition(ks,kd) > 0 ? MappedGridData::physicalBoundary :
rcData->boundaryCondition(ks,kd)==0 ? MappedGridData::interpolationBoundary :
mapping().getIsPeriodic(kd)==Mapping::functionPeriodic ? MappedGridData::branchCutPeriodicBoundary :
MappedGridData::periodicBoundary;
}
}
void MappedGrid::
setBoundaryFlag( int side, int axis, MappedGridData::BoundaryFlagEnum bc )
// *** internal use only for now ***
{
rcData->boundaryFlag[side][axis]=bc;
}
void MappedGrid::
setBoundaryDiscretizationWidth(
const Integer& ks,
const Integer& kd,
const Integer& boundaryDiscretizationWidth_)
{ rcData->boundaryDiscretizationWidth(ks,kd) = boundaryDiscretizationWidth_; }
void MappedGrid::
setIsCellCentered(
const Integer& kd,
const Logical& isCellCentered_) {
if (isCellCentered(kd) != isCellCentered_) destroy(~NOTHING);
rcData->isCellCentered(kd) = isCellCentered_;
}
void MappedGrid::
setDiscretizationWidth(
const Integer& kd,
const Integer& discretizationWidth_)
{ rcData->discretizationWidth(kd) = discretizationWidth_; }
void MappedGrid::
setGridIndexRange(
const Integer& ks,
const Integer& kd,
const Integer& gridIndexRange_)
{
if (gridIndexRange(ks,kd) != gridIndexRange_) destroy(~NOTHING);
rcData->gridIndexRange(ks,kd) = gridIndexRange_;
}
void MappedGrid::
setNumberOfGhostPoints(
const Integer& ks,
const Integer& kd,
const Integer& numberOfGhostPoints_)
{
if (numberOfGhostPoints(ks,kd) != numberOfGhostPoints_)
destroy(~NOTHING);
rcData->numberOfGhostPoints(ks,kd) = numberOfGhostPoints_;
}
void MappedGrid::
setUseGhostPoints(const Logical& useGhostPoints_)
{
if (useGhostPoints() != useGhostPoints_) destroy(~NOTHING);
rcData->useGhostPoints = useGhostPoints_;
}
void MappedGrid::
setIsPeriodic( const Integer& axis, const Mapping::periodicType& isPeriodic_)
{
if (isPeriodic(axis) != (int)isPeriodic_) destroy(~NOTHING);
rcData->isPeriodic(axis) = isPeriodic_;
if( isPeriodic_==Mapping::functionPeriodic )
rcData->boundaryFlag[0][axis]=rcData->boundaryFlag[1][axis]=MappedGridData::branchCutPeriodicBoundary;
else if( isPeriodic_==Mapping::derivativePeriodic )
rcData->boundaryFlag[0][axis]=rcData->boundaryFlag[1][axis]=MappedGridData::periodicBoundary;
else if( isPeriodic_==Mapping::notPeriodic )
{
for( int side=Start; side<=End; side++ )
{
if( rcData->boundaryFlag[side][axis]==MappedGridData::branchCutPeriodicBoundary ||
rcData->boundaryFlag[side][axis]==MappedGridData::periodicBoundary )
rcData->boundaryFlag[side][axis]=MappedGridData::physicalBoundary;
}
}
}
void MappedGrid::
setSharedBoundaryFlag(
const Integer& ks,
const Integer& kd,
const Integer& sharedBoundaryFlag_)
{ rcData->sharedBoundaryFlag(ks,kd) = sharedBoundaryFlag_; }
void
MappedGrid::setSharedBoundaryTolerance(
const Integer& ks,
const Integer& kd,
const Real& sharedBoundaryTolerance_)
{ rcData->sharedBoundaryTolerance(ks,kd) = sharedBoundaryTolerance_; }
//
// Use a given mapping.
//
void MappedGrid::
reference(Mapping& x, bool forceIncompatible/*=false*/ )
{ //kkc 050120 added forceIncompatible for updating the grid when the mapping has changed significantly
rcData->gridType=x.getClassName()=="UnstructuredMapping" ? unstructuredGrid : structuredGrid;
Logical incompatible = x.getRangeDimension()!=mapping().getRangeDimension() || forceIncompatible;
incompatible = x.getClassName()!=mapping().getClassName(); // *wdh*
Integer kd, ks;
for (kd=0; kd<mapping().getRangeDimension(); kd++)
{
if( ( incompatible = (incompatible ||
x.getGridDimensions(kd) != mapping().getGridDimensions(kd) ||
x.getIsPeriodic(kd) != mapping().getIsPeriodic(kd) )) ) break;
for (ks=0; ks<2; ks++)
{
if ( (incompatible = (incompatible ||
x.getBoundaryCondition(ks,kd)!= mapping().getBoundaryCondition(ks,kd)||
mapping().getShare(ks,kd) != x.getShare(ks,kd) ) ) ) break;
}
} // end for, end if
mapping().reference(x);
if (incompatible)
{
// Fill out new dimensions with default data.
for (kd=numberOfDimensions(); kd<mapping().getRangeDimension(); kd++)
{
rcData->isCellCentered(kd) = LogicalFalse;
rcData->discretizationWidth(kd) = 3;
for (ks=0; ks<2; ks++)
{
rcData->boundaryDiscretizationWidth(ks, kd) = 3;
rcData->sharedBoundaryTolerance(ks, kd) = (Real).1;
rcData->numberOfGhostPoints(ks,kd)=rcData->gridType==structuredGrid ? (discretizationWidth(kd)-1)/2 : 0;
} // end for
} // end for
rcData->useGhostPoints = LogicalTrue;
rcData->numberOfDimensions = mapping().getRangeDimension();
// *wdh* 070301 -- for surface grids we allow share and bc for the extra axis
for (kd=0; kd<numberOfDimensions(); kd++)
{
for (ks=0; ks<2; ks++)
{
rcData->boundaryCondition(ks,kd) = mapping().getBoundaryCondition(ks,kd);
rcData->sharedBoundaryFlag(ks, kd) = mapping().getShare(ks,kd);
} // end for
} // end for
// *kkc --changed to accomodate surface grids for (kd=0; kd<numberOfDimensions(); kd++)
for (kd=0; kd<domainDimension(); kd++)
{
rcData->isPeriodic(kd) = mapping().getIsPeriodic(kd);
for (ks=0; ks<2; ks++)
{
rcData->boundaryFlag[ks][kd]=(rcData->boundaryCondition(ks,kd) > 0 ? MappedGridData::physicalBoundary :
rcData->boundaryCondition(ks,kd)==0 ? MappedGridData::interpolationBoundary :
mapping().getIsPeriodic(kd)==Mapping::functionPeriodic ?
MappedGridData::branchCutPeriodicBoundary : MappedGridData::periodicBoundary);
rcData->gridIndexRange(ks, kd) = ks * (mapping().getGridDimensions(kd) - 1);
} // end for
} // end for
// *kkc --changed to accomodate surface grids for (kd=numberOfDimensions(); kd<3; kd++)
for (kd=domainDimension(); kd<3; kd++)
{
rcData->isCellCentered(kd) = LogicalFalse;
rcData->discretizationWidth(kd) = 1;
rcData->isPeriodic(kd) = Mapping::derivativePeriodic;
for (ks=0; ks<2; ks++)
{
// rcData->boundaryCondition(ks, kd) = -1;
rcData->boundaryFlag[ks][kd]=MappedGridData::periodicBoundary;
rcData->boundaryDiscretizationWidth(ks, kd) = 1;
// rcData->sharedBoundaryFlag(ks, kd) = 0;
rcData->sharedBoundaryTolerance(ks, kd) = (Real)0.;
rcData->gridIndexRange(ks, kd) = 0;
rcData->numberOfGhostPoints(ks, kd) = 0;
} // end for
} // end for
// 104024 rcData->minimumEdgeLength = rcData->maximumEdgeLength = (Real)0.;
destroy(~NOTHING); update(NOTHING);
}
else
{
geometryHasChanged(~THEmask);
} // end if
}
void MappedGrid::
reference(MappingRC& x)
{
reference(*x.mapPointer);
}
//
// Break a reference. (Replaces with a deep copy.)
//
void MappedGrid::breakReference()
{
// GenericGrid::breakReference();
if (!isCounted || rcData->getReferenceCount() != 1) {
MappedGrid x = *this; // Uses the (deep) copy constructor.
reference(x);
} // end if
}
//
// Change the grid to be all vertex-centered.
//
void MappedGrid::changeToAllVertexCentered() {
if (!isAllVertexCentered()) {
const Integer newGeometry = isAllVertexCentered() ?
NOTHING : computedGeometry() & (
THEinverseCenterDerivative |
THEcenter |
THEcorner |
THEcenterDerivative |
THEcenterJacobian |
THEcellVolume |
THEcenterNormal |
THEcenterArea |
THEfaceNormal |
THEfaceArea |
THEcenterBoundaryNormal |
THEcenterBoundaryTangent );
for (Integer kd=0; kd<numberOfDimensions(); kd++)
rcData->isCellCentered(kd) = LogicalFalse;
// Force links between vertex and center data.
if (newGeometry) destroy(newGeometry);
update(newGeometry);
} // end if
}
//
// Change the grid to be all cell-centered.
//
void MappedGrid::
changeToAllCellCentered()
{
if (!isAllCellCentered())
{
const Integer newGeometry = isAllCellCentered() ?
NOTHING : computedGeometry() & (
THEinverseCenterDerivative |
THEcenter |
THEcorner |
THEcenterDerivative |
THEcenterJacobian |
THEcellVolume |
THEcenterNormal |
THEcenterArea |
THEfaceNormal |
THEfaceArea |
THEcenterBoundaryNormal |
THEcenterBoundaryTangent );
for (Integer kd=0; kd<numberOfDimensions(); kd++)
rcData->isCellCentered(kd) = LogicalTrue;
// Force links between vertex and corner data.
if (newGeometry) destroy(newGeometry);
update(newGeometry);
} // end if
}
//
// Check that the data structure is self-consistent.
//
void MappedGrid::
consistencyCheck() const {
GenericGrid::consistencyCheck();
if (rcData != GenericGrid::rcData) {
cerr << className << "::consistencyCheck(): "
<< "rcData != GenericGrid::rcData for "
<< getClassName() << " " << getGlobalID() << "." << endl;
assert(rcData == GenericGrid::rcData);
} // end if
}
//\begin{>>MappedGridInclude.tex}{\subsubsection{deltaX}}
int MappedGrid::
getDeltaX( Real dx[3] ) const
// ==========================================================================
// /Description:
// Return dx for rectangular grids, otherwise return dr
// /dx (output) : the grid spacing for a rectangular grid.
//\end{MappedGridInclude.tex}
//==========================================================================
{
real xab[2][3];
return getRectangularGridParameters( dx,xab );
}
//! Get delta x and corners of a rectangular grid.
/*!
\param dx :
\param xab : xab[side][axis] are the corners of the rectangular grid.
*/
int MappedGrid::
getRectangularGridParameters( Real dx[3], Real xab[2][3] ) const
{
real xa=0.,xb=1., ya=0.,yb=1., za=0., zb=1.;
real ra=0.,rb=1., sa=0.,sb=1., ta=0., tb=1.; // if reparameterized
bool reparameterized=false;
if( isRectangular() )
{
Mapping *mapPointer=mapping().mapPointer;
aString mapClassName = mapPointer->getClassName();
if( mapClassName=="ReparameterizationTransform" )
{
reparameterized=true;
ReparameterizationTransform & rt = (ReparameterizationTransform&)(*mapPointer);
// rt.getBounds(ra,rb,sa,sb,ta,tb ); // *wdh* 070415
rt.getBoundsForMultipleReparameterizations(ra,rb,sa,sb,ta,tb );
// get the Mapping that was reparameterized
mapPointer= rt.map2.mapPointer;
mapClassName = mapPointer->getClassName();
}
Mapping & map = *mapPointer;
if( numberOfDimensions()==1 && mapClassName=="LineMapping" )
{
LineMapping & sq = (LineMapping&) map;
sq.getPoints( xa,xb );
}
else if( numberOfDimensions()==2 && mapClassName=="SquareMapping" )
{
SquareMapping & sq = (SquareMapping&) map;
sq.getVertices( xa,xb,ya,yb );
}
else if( numberOfDimensions()==3 && mapClassName=="BoxMapping" )
{
BoxMapping & box = (BoxMapping&) map;
box.getVertices( xa,xb,ya,yb,za,zb);
}
else
{
printf("MappedGrid::deltaX:ERROR: mapping is rectangular but of unknown className=%s\n",
(const char*)map.getClassName());
Overture::abort("error");
}
}
if( !reparameterized )
{
xab[0][0]=xa;
xab[1][0]=xb;
xab[0][1]=ya;
xab[1][1]=yb;
xab[0][2]=za;
xab[1][2]=zb;
dx[0]=(xb-xa)*gridSpacing(0);
dx[1]=(yb-ya)*gridSpacing(1);
dx[2]=(zb-za)*gridSpacing(2);
}
else
{
xab[0][0]=xa+ra*(xb-xa);
xab[1][0]=xa+rb*(xb-xa);
xab[0][1]=ya+sa*(yb-ya);
xab[1][1]=ya+sb*(yb-ya);
xab[0][2]=za+ta*(zb-za);
xab[1][2]=za+tb*(zb-za);
dx[0]=(xb-xa)*(rb-ra)*gridSpacing(0);
dx[1]=(yb-ya)*(sb-sa)*gridSpacing(1);
dx[2]=(zb-za)*(tb-ta)*gridSpacing(2);
}
return 0;
}
//\begin{>>MappedGridInclude.tex}{\subsubsection{extendedRange}}
IntegerArray MappedGrid::
extendedRange() const
// ==========================================================================
// /Description:
// Return the extendedRange : index range plus extra lines for interpolation,
// including interpolation outside of mixed boundaries.
//\end{MappedGridInclude.tex}
//==========================================================================
{
#undef extendedRange
#define extendedRange(side,axis) pExtendedRange[(side)+2*(axis)]
IntegerArray range(2,3);
for( int axis=0; axis<3; axis++ )
for( int side=0; side<=1; side++)
range(side,axis)=rcData->extendedRange(side,axis);
return range;
}
//\begin{>>MappedGridInclude.tex}{\subsubsection{getName}}
aString MappedGrid::
getName() const
// ==========================================================================
// /Description:
// Get the name of the grid.
//\end{MappedGridInclude.tex}
//==========================================================================
{
return mapping().getName(Mapping::mappingName);
}
//\begin{>>MappedGridInclude.tex}{\subsubsection{isRectangular}}
bool MappedGrid::
isRectangular() const
// ==========================================================================
// /Description:
// Return true if the the grid rectangular.
//\end{MappedGridInclude.tex}
//==========================================================================
{
if( mapping().mapPointer!=NULL )
{
// MappedGrid has a mapping, check the type
return mapping().mapPointer->getMappingCoordinateSystem()==Mapping::rectangular;
}
return FALSE;
}
//\begin{>>MappedGridInclude.tex}{\subsubsection{displayComputedGeometry}}
int MappedGrid::
displayComputedGeometry(FILE *file /* =stdout */ ) const
// ==========================================================================
// /Description:
// Show which geometry arrays are built
//\end{MappedGridInclude.tex}
//==========================================================================
{
fPrintF(file,"---Computed geometry for %s:\n"
" mask=%s, inverseVertexDerivative=%s, inverseCenterDerivative=%s,\n"
" vertex=%s, center=%s, corner=%s, \n"
" vertexDerivative=%s, centerDerivative=%s, vertexJacobian=%s, \n"
" centerJacobian=%s, cellVolume=%s, centerNormal=%s \n"
" centerArea=%s, faceNormal=%s, faceArea=%s, \n"
" vertexBoundaryNormal=%s, centerBoundaryNormal=%s, centerBoundaryTangent=%s \n",
(const char *)getName(),
(computedGeometry() & THEmask ? "yes" : "no "),
(computedGeometry() & THEinverseVertexDerivative ? "yes" : "no "),
(computedGeometry() & THEinverseCenterDerivative ? "yes" : "no "),
(computedGeometry() & THEvertex ? "yes" : "no "),
(computedGeometry() & THEcenter ? "yes" : "no "),
(computedGeometry() & THEcorner ? "yes" : "no "),
(computedGeometry() & THEvertexDerivative ? "yes" : "no "),
(computedGeometry() & THEcenterDerivative ? "yes" : "no "),
(computedGeometry() & THEvertexJacobian ? "yes" : "no "),
(computedGeometry() & THEcenterJacobian ? "yes" : "no "),
(computedGeometry() & THEcellVolume ? "yes" : "no "),
(computedGeometry() & THEcenterNormal ? "yes" : "no "),
(computedGeometry() & THEcenterArea ? "yes" : "no "),
(computedGeometry() & THEfaceNormal ? "yes" : "no "),
(computedGeometry() & THEfaceArea ? "yes" : "no "),
(computedGeometry() & THEvertexBoundaryNormal ? "yes" : "no "),
(computedGeometry() & THEcenterBoundaryNormal ? "yes" : "no "),
(computedGeometry() & THEcenterBoundaryTangent ? "yes" : "no "));
return 0;
}
//\begin{>>MappedGridInclude.tex}{\subsubsection{sizeOf}}
real MappedGrid::
sizeOf(FILE *file /* = NULL */ ) const
// ==========================================================================
// /Description:
// Return number of bytes allocated by Oges; optionally print detailed info to a file
//
// /file (input) : optinally supply a file to write detailed info to. Choose file=stdout to
// write to standard output.
// /Return value: the number of bytes.
//\end{MappedGridInclude.tex}
//==========================================================================
{
assert( rcData!=NULL );
real size=sizeof(*this) + sizeof( *rcData );
if( rcData->mask !=NULL ) size+=rcData->mask->sizeOf();
if( rcData->inverseCenterDerivative!=NULL )
size+=rcData->inverseCenterDerivative->sizeOf();
if( rcData->inverseVertexDerivative!=NULL &&
(rcData->inverseCenterDerivative==NULL || isAllCellCentered()) ) // could be ref. to inverseCenterDerivative
size+=rcData->inverseVertexDerivative->sizeOf();
if( rcData->center!=NULL ) size+=rcData->center->sizeOf();
if( rcData->vertex!=NULL && (rcData->center==NULL || isAllCellCentered()) )
size+=rcData->vertex->sizeOf();
if( rcData->corner!=NULL &&
( (rcData->vertex==NULL && isAllCellCentered()) || isAllVertexCentered()) )
size+=rcData->corner->sizeOf();
if( rcData->centerDerivative!=NULL ) size+=rcData->centerDerivative->sizeOf();
if( rcData->vertexDerivative!=NULL && (rcData->centerDerivative==NULL || isAllCellCentered()) )
size+=rcData->vertexDerivative->sizeOf();
if( rcData->centerJacobian!=NULL ) size+=rcData->centerJacobian->sizeOf();
if( rcData->vertexJacobian!=NULL && (rcData->centerJacobian==NULL || isAllCellCentered()) )
size+=rcData->vertexJacobian->sizeOf();
if( rcData->cellVolume!=NULL ) size+=rcData->cellVolume->sizeOf();
if( rcData->centerNormal!=NULL ) size+=rcData->centerNormal->sizeOf();
if( rcData->centerArea!=NULL ) size+=rcData->centerArea->sizeOf();
if( rcData->faceNormal!=NULL ) size+=rcData->faceNormal->sizeOf();
if( rcData->faceArea!=NULL ) size+=rcData->faceArea->sizeOf();
for( int axis=0; axis<3; axis++ )
{
for( int side=0; side<=1; side++ )
{
if( rcData->centerBoundaryNormal[axis][side]!=NULL ) size+=rcData->centerBoundaryNormal[axis][side]->sizeOf();
if( rcData->vertexBoundaryNormal[axis][side]!=NULL &&
(rcData->centerBoundaryNormal[axis][side]==NULL || isAllCellCentered() ) )
size+=rcData->vertexBoundaryNormal[axis][side]->sizeOf();
if( rcData->centerBoundaryTangent[axis][side]!=NULL ) size+=rcData->centerBoundaryTangent[axis][side]->sizeOf();
if( rcData->pCenterBoundaryNormal[axis][side]!=NULL )
size+=rcData->pCenterBoundaryNormal[axis][side]->elementCount()*sizeof(real);
if( rcData->pVertexBoundaryNormal[axis][side]!=NULL &&
(rcData->pCenterBoundaryNormal[axis][side]==NULL || isAllCellCentered() ) )
size+=rcData->pVertexBoundaryNormal[axis][side]->elementCount()*sizeof(real);
if( rcData->pCenterBoundaryTangent[axis][side]!=NULL )
size+=rcData->pCenterBoundaryTangent[axis][side]->elementCount()*sizeof(real);
}
}
size+=(rcData->I1array.elementCount()+rcData->I2array.elementCount()+rcData->I3array.elementCount())*sizeof(int);
size+=mapping().sizeOf();
size+=rcData->boundaryCondition.elementCount()*sizeof(int);
size+=rcData->boundaryDiscretizationWidth.elementCount()*sizeof(int);
size+=rcData->boundingBox.elementCount()*sizeof(real);
size+=rcData->localBoundingBox.elementCount()*sizeof(real);
size+=rcData->gridSpacing.elementCount()*sizeof(real);
size+=rcData->isCellCentered.elementCount()*sizeof(int);
size+=rcData->discretizationWidth.elementCount()*sizeof(int);
size+=rcData->indexRange.elementCount()*sizeof(int);
size+=rcData->extendedIndexRange.elementCount()*sizeof(int);
size+=rcData->gridIndexRange.elementCount()*sizeof(int);
size+=rcData->dimension.elementCount()*sizeof(int);
size+=rcData->numberOfGhostPoints.elementCount()*sizeof(int);
size+=rcData->isPeriodic.elementCount()*sizeof(int);
size+=rcData->sharedBoundaryFlag.elementCount()*sizeof(int);
size+=rcData->sharedBoundaryTolerance.elementCount()*sizeof(real);
// 104024 size+=rcData->minimumEdgeLength.elementCount()*sizeof(real);
// 104024 size+=rcData->maximumEdgeLength.elementCount()*sizeof(real);
return size;
}
//
// "Get" and "put" database operations.
//
Integer MappedGrid::
get(const GenericDataBase& db,
const aString& name,
bool getMapping /* =true */ ) // for AMR grids we may not get the mapping.
{
Integer returnValue = rcData->get(db, name, getMapping);
updateReferences();
return returnValue;
}
Integer MappedGrid::
put(
GenericDataBase& db,
const aString& name,
bool putMapping /* = true */,
int geometryToPut /* = -1 */
) const
// geometryToPut : by default put computedGeometry
{
return rcData->put(db, name,putMapping,geometryToPut);
}
//
// Set references to reference-counted data.
//
void MappedGrid::updateReferences(const Integer what)
{
GenericGrid::reference(*rcData);
GenericGrid::updateReferences(what);
}
//
// Update the grid, sharing the data of another grid.
//
Integer MappedGrid::
update(
GenericGrid& x,
const Integer what,
const Integer how)
{
Integer upd = rcData->update(*((MappedGrid&)x).rcData, what, how);
updateReferences(what);
updateMappedGridPointers(what);
return upd;
}
Integer MappedGrid::
updateMappedGridPointers(const Integer what_)
//
// This routine assigns the "mappedGrid" pointer in the geometry grid functions
// that are being updated. This is not done by the update since it only knows
// the rcData pointer and not the MappedGrid pointer.
{
assert( rcData!=NULL );
int what=rcData->getWhatForGrid(what_);
if( what & THEmask )
rcData->mask->mappedGrid=this;
if( what & THEinverseVertexDerivative )
rcData->inverseVertexDerivative->mappedGrid=this;
if( what & THEinverseCenterDerivative )
rcData->inverseCenterDerivative->mappedGrid=this;
if( what & THEvertex )
rcData->vertex->mappedGrid=this;
if( what & THEcenter )
rcData->center->mappedGrid=this;
if( what & THEcorner )
rcData->corner->mappedGrid=this;
if( what & THEvertexDerivative )
rcData->vertexDerivative->mappedGrid=this;
if( what & THEcenterDerivative )
rcData->centerDerivative->mappedGrid=this;
if( what & THEvertexJacobian )
rcData->vertexJacobian->mappedGrid=this;
if( what & THEcenterJacobian )
rcData->centerJacobian->mappedGrid=this;
if( what & THEcellVolume )
rcData->cellVolume->mappedGrid=this;
if( what & THEcenterArea )
rcData->centerArea->mappedGrid=this;
if( what & THEfaceNormal )
rcData->faceNormal->mappedGrid=this;
if( what & THEvertexBoundaryNormal )
for( int axis=0; axis<numberOfDimensions(); axis++ )
for( int side=0; side<=1; side++ )
if( rcData->vertexBoundaryNormal[axis][side]!=NULL )
rcData->vertexBoundaryNormal[axis][side]->mappedGrid=this;
if( what & THEcenterBoundaryNormal )
for( int axis=0; axis<numberOfDimensions(); axis++ )
for( int side=0; side<=1; side++ )
if( rcData->centerBoundaryNormal[axis][side]!=NULL )
rcData->centerBoundaryNormal[axis][side]->mappedGrid=this;
if( what & THEcenterBoundaryTangent )
for( int axis=0; axis<numberOfDimensions(); axis++ )
for( int side=0; side<=1; side++ )
if( rcData->centerBoundaryTangent[axis][side]!=NULL )
rcData->centerBoundaryTangent[axis][side]->mappedGrid=this;
return 0;
}
//
// Destroy optional grid data.
//
void MappedGrid::
destroy(const Integer what) {
rcData->destroy(what);
updateReferences();
}
#ifdef ADJUST_FOR_PERIODICITY
//
// Adjust the inverted coordinates for periodicity.
//
void MappedGrid::adjustForPeriodicity(
const RealArray& r,
const LogicalArray& whereMask) {
const Range p(r.getBase(0), r.getBound(0));
for (Integer kd=0; kd<numberOfDimensions(); kd++) if (isPeriodic(kd)) {
where (whereMask && r(p,kd) < (Real)0.) r(p,kd) = r(p,kd) + (Real)1.;
where (whereMask && r(p,kd) > (Real)1. && r(p,kd) != (Real)10.)
r(p,kd) = r(p,kd) - (Real)1.;
} // end if, end for
}
#endif // ADJUST_FOR_PERIODICITY
//
// Adjust the inverted coordinates of boundary points
// in cases where the points lie on a shared boundary.
//
void MappedGrid::adjustBoundary(
MappedGrid& g2,
const Integer& ks1,
const Integer& kd1,
const RealArray& r2,
const LogicalArray& whereMask) {
//
// Check whether points on the (ks1,kd1) side of this grid at
// coordinates r2 of grid g2 are near a side of grid g2. If so
// and that side is a boundary shared with the side (ks1,kd1)
// of this grid then change r2 so that it it is exactly on that
// side of grid g2. Repeat for each side of grid g2.
//
#ifdef ADJUST_FOR_PERIODICITY
g2.adjustForPeriodicity(r2, whereMask);
#endif // ADJUST_FOR_PERIODICITY
const Range p(r2.getBase(0), r2.getBound(0));
for (Integer kd2=0; kd2<numberOfDimensions(); kd2++) {
if (boundaryCondition(ks1,kd1) > 0 && sharedBoundaryFlag(ks1,kd1)) {
if (g2.boundaryCondition(0,kd2) > 0 &&
sharedBoundaryFlag(ks1,kd1) == g2.sharedBoundaryFlag(0,kd2))
where (whereMask(p) && r2(p,kd2) < (Real).5)
r2(p,kd2) = (Real)0.;
if (g2.boundaryCondition(1,kd2) > 0 &&
sharedBoundaryFlag(ks1,kd1) == g2.sharedBoundaryFlag(1,kd2))
where (whereMask(p) && r2(p,kd2) > (Real).5)
r2(p,kd2) = (Real)1.;
} // end if
} // end for
}
//
// Compute the condition number of the mapping inverse.
//
// The condition number is the max norm (max absolute row sum) of the matrix
//
// [ 1/dr2 0 ] [ rx2 ry2 ] [ xr1 xs1 ] [ dr1 0 ]
// [ 0 1/ds2 ] [ sx2 sy2 ] [ yr1 ys1 ] [ 0 ds1 ]
//
void MappedGrid::getInverseCondition(
MappedGrid& g2,
const RealArray& xr1,
const RealArray& rx2,
const RealArray& condition,
const LogicalArray& whereMask) {
//
// Xr1 and rx2 are three-dimensional arrays containing the derivative of
// the mapping of this grid and the inverse derivative of the mapping of
// grid g2. Condition is a one-dimensional array to hold the results.
// Its length determines the number of points. The third dimension of
// xr1 and rx2 should be the same as the dimension of condition.
//
Range p(xr1.getBase(0), xr1.getBound(0));
if (numberOfDimensions() == 0) {
condition(p) = (Real)0.;
} else {
RealArray rowsum(p), dot(p);
where (whereMask)
for (Integer kd1=0; kd1<numberOfDimensions(); kd1++) {
rowsum = (Real)0.;
for (Integer kd2=0; kd2<numberOfDimensions(); kd2++) {
dot = (Real)0.;
for (Integer kd3=0; kd3<numberOfDimensions(); kd3++)
dot += rx2(p,kd1,kd3) * xr1(p,kd3,kd2);
rowsum += (gridSpacing(kd2) / g2.gridSpacing(kd1)) * abs(dot);
} // end for
condition(p) = max(condition, rowsum);
} // end for, end where
} // end if
}
//
// Specify the set of processes over which MappedGridFunctions are distributed.
// We now support only the specification of a contiguous range of process IDs.
//
void MappedGrid::specifyProcesses(const Range& range)
{
// we must destroy the geometry arrays before we can change the parallel distribution
destroy(MappedGrid::EVERYTHING);
rcData->specifyProcesses(range);
}
//
// Initialize the MappedGrid with the given number of dimensions.
//
void MappedGrid::initialize(const Integer& numberOfDimensions_) {
GenericGrid::initialize();
rcData->initialize(numberOfDimensions_);
}
//
// Stream output operator.
//
ostream& operator<<(ostream& s, const MappedGrid& g) {
return s
<< (GenericGrid&)g << endl
<< " numberOfDimensions() = "
<< g.numberOfDimensions() << endl
<< " boundaryCondition() = ["
<< g.boundaryCondition(0,0) << ":"
<< g.boundaryCondition(1,0) << ","
<< g.boundaryCondition(0,1) << ":"
<< g.boundaryCondition(1,1) << ","
<< g.boundaryCondition(0,2) << ":"
<< g.boundaryCondition(1,2) << "]" << endl
<< " boundaryDiscretizationWidth() = ["
<< g.boundaryDiscretizationWidth(0,0) << ":"
<< g.boundaryDiscretizationWidth(1,0) << ","
<< g.boundaryDiscretizationWidth(0,1) << ":"
<< g.boundaryDiscretizationWidth(1,1) << ","
<< g.boundaryDiscretizationWidth(0,2) << ":"
<< g.boundaryDiscretizationWidth(1,2) << "]" << endl
<< " boundingBox() = ["
<< g.boundingBox(0,0) << ":"
<< g.boundingBox(1,0) << ","
<< g.boundingBox(0,1) << ":"
<< g.boundingBox(1,1) << ","
<< g.boundingBox(0,2) << ":"
<< g.boundingBox(1,2) << "]" << endl
<< " gridSpacing() = ["
<< g.gridSpacing(0) << ","
<< g.gridSpacing(1) << ","
<< g.gridSpacing(2) << "]" << endl
<< " isAllCellCentered() = "
<< (g.isAllCellCentered() ? 'T' : 'F') << endl
<< " isAllVertexCentered() = "
<< (g.isAllVertexCentered() ? 'T' : 'F') << endl
<< " isCellCentered() = ["
<< (g.isCellCentered(0) ? 'T' : 'F') << ","
<< (g.isCellCentered(1) ? 'T' : 'F') << ","
<< (g.isCellCentered(2) ? 'T' : 'F') << "]" << endl
<< " discretizationWidth() = ["
<< g.discretizationWidth(0) << ":"
<< g.discretizationWidth(1) << ":"
<< g.discretizationWidth(2) << "]" << endl
<< " indexRange() = ["
<< g.indexRange(0,0) << ":"
<< g.indexRange(1,0) << ","
<< g.indexRange(0,1) << ":"
<< g.indexRange(1,1) << ","
<< g.indexRange(0,2) << ":"
<< g.indexRange(1,2) << "]" << endl
<< " extendedIndexRange() = ["
<< g.extendedIndexRange(0,0) << ":"
<< g.extendedIndexRange(1,0) << ","
<< g.extendedIndexRange(0,1) << ":"
<< g.extendedIndexRange(1,1) << ","
<< g.extendedIndexRange(0,2) << ":"
<< g.extendedIndexRange(1,2) << "]" << endl
<< " gridIndexRange() = ["
<< g.gridIndexRange(0,0) << ":"
<< g.gridIndexRange(1,0) << ","
<< g.gridIndexRange(0,1) << ":"
<< g.gridIndexRange(1,1) << ","
<< g.gridIndexRange(0,2) << ":"
<< g.gridIndexRange(1,2) << "]" << endl
<< " dimension() = ["
<< g.dimension(0,0) << ":"
<< g.dimension(1,0) << ","
<< g.dimension(0,1) << ":"
<< g.dimension(1,1) << ","
<< g.dimension(0,2) << ":"
<< g.dimension(1,2) << "]" << endl
<< " numberOfGhostPoints() = ["
<< g.numberOfGhostPoints(0,0) << ":"
<< g.numberOfGhostPoints(1,0) << ","
<< g.numberOfGhostPoints(0,1) << ":"
<< g.numberOfGhostPoints(1,1) << ","
<< g.numberOfGhostPoints(0,2) << ":"
<< g.numberOfGhostPoints(1,2) << "]" << endl
<< " useGhostPoints() = "
<< g.useGhostPoints() << endl
<< " isPeriodic() = ["
<< (g.isPeriodic(0) ? 'T' : 'F') << ","
<< (g.isPeriodic(1) ? 'T' : 'F') << ","
<< (g.isPeriodic(2) ? 'T' : 'F') << "]" << endl
<< " sharedBoundaryFlag() = ["
<< g.sharedBoundaryFlag(0,0) << ":"
<< g.sharedBoundaryFlag(1,0) << ","
<< g.sharedBoundaryFlag(0,1) << ":"
<< g.sharedBoundaryFlag(1,1) << ","
<< g.sharedBoundaryFlag(0,2) << ":"
<< g.sharedBoundaryFlag(1,2) << "]" << endl
<< " sharedBoundaryTolerance() = ["
<< g.sharedBoundaryTolerance(0,0) << ":"
<< g.sharedBoundaryTolerance(1,0) << ","
<< g.sharedBoundaryTolerance(0,1) << ":"
<< g.sharedBoundaryTolerance(1,1) << ","
<< g.sharedBoundaryTolerance(0,2) << ":"
<< g.sharedBoundaryTolerance(1,2) << "]" << endl;
// << " minimumEdgeLength() = ["
// << g.minimumEdgeLength(0) << ","
// << g.minimumEdgeLength(1) << ","
// << g.minimumEdgeLength(2) << "]" << endl
// << " maximumEdgeLength() = ["
// << g.maximumEdgeLength(0) << ","
// << g.maximumEdgeLength(1) << ","
// << g.maximumEdgeLength(2) << "]";
}
//
// class MappedGridData:
//
MappedGridData::MappedGridData(const Integer numberOfDimensions_):
GenericGridData() {
className = "MappedGridData";
refinementGrid=false;
partitionInitialized=false;
matrixPartitionInitialized=false;
shareGridWithMapping=true;
mask = NULL;
inverseVertexDerivative = NULL;
// inverseVertexDerivative2D = NULL;
// inverseVertexDerivative1D = NULL;
inverseCenterDerivative = NULL;
// inverseCenterDerivative2D = NULL;
// inverseCenterDerivative1D = NULL;
vertex = NULL;
// vertex2D = NULL;
// vertex1D = NULL;
center = NULL;
// center2D = NULL;
// center1D = NULL;
corner = NULL;
// corner2D = NULL;
// corner1D = NULL;
vertexDerivative = NULL;
// vertexDerivative2D = NULL;
// vertexDerivative1D = NULL;
centerDerivative = NULL;
// centerDerivative2D = NULL;
// centerDerivative1D = NULL;
vertexJacobian = NULL;
centerJacobian = NULL;
cellVolume = NULL;
centerNormal = NULL;
// centerNormal2D = NULL;
// centerNormal1D = NULL;
centerArea = NULL;
// centerArea2D = NULL;
// centerArea1D = NULL;
faceNormal = NULL;
// faceNormal2D = NULL;
// faceNormal1D = NULL;
faceArea = NULL;
// faceArea2D = NULL;
// faceArea1D = NULL;
for (Integer kd=0; kd<3; kd++) for (Integer ks=0; ks<2; ks++)
{
vertexBoundaryNormal[kd][ks] = NULL;
centerBoundaryNormal[kd][ks] = NULL;
centerBoundaryTangent[kd][ks] = NULL;
pVertexBoundaryNormal[kd][ks] = NULL; // serial array version
pCenterBoundaryNormal[kd][ks] = NULL; // serial array version
pCenterBoundaryTangent[kd][ks] = NULL; // serial array version
} // end for, end for
for ( int i=0; i<4; i++ )
unstructuredBoundaryConditionInfo[i] = unstructuredPeriodicBoundaryInfo[i] = 0;
initialize(numberOfDimensions_);
}
MappedGridData::MappedGridData(
const MappedGridData& x,
const CopyType ct):
GenericGridData() {
className = "MappedGridData";
refinementGrid=false;
partitionInitialized=false;
matrixPartitionInitialized=false;
shareGridWithMapping=true;
mask = NULL;
inverseVertexDerivative = NULL;
// inverseVertexDerivative2D = NULL;
// inverseVertexDerivative1D = NULL;
inverseCenterDerivative = NULL;
// inverseCenterDerivative2D = NULL;
// inverseCenterDerivative1D = NULL;
vertex = NULL;
// vertex2D = NULL;
// vertex1D = NULL;
center = NULL;
// center2D = NULL;
// center1D = NULL;
corner = NULL;
// corner2D = NULL;
// corner1D = NULL;
vertexDerivative = NULL;
// vertexDerivative2D = NULL;
// vertexDerivative1D = NULL;
centerDerivative = NULL;
// centerDerivative2D = NULL;
// centerDerivative1D = NULL;
vertexJacobian = NULL;
centerJacobian = NULL;
cellVolume = NULL;
centerNormal = NULL;
// centerNormal2D = NULL;
// centerNormal1D = NULL;
centerArea = NULL;
// centerArea2D = NULL;
// centerArea1D = NULL;
faceNormal = NULL;
// faceNormal2D = NULL;
// faceNormal1D = NULL;
faceArea = NULL;
// faceArea2D = NULL;
// faceArea1D = NULL;
for (Integer kd=0; kd<3; kd++)
for (Integer ks=0; ks<2; ks++)
{
vertexBoundaryNormal[kd][ks] = NULL;
centerBoundaryNormal[kd][ks] = NULL;
centerBoundaryTangent[kd][ks] = NULL;
pVertexBoundaryNormal[kd][ks] = NULL; // serial array version
pCenterBoundaryNormal[kd][ks] = NULL; // serial array version
pCenterBoundaryTangent[kd][ks] = NULL; // serial array version
} // end for, end for
for ( int i=0; i<4; i++ )
unstructuredBoundaryConditionInfo[i] = unstructuredPeriodicBoundaryInfo[i] = 0;
initialize(x.numberOfDimensions);
if (ct != NOCOPY) *this = x;
}
MappedGridData::~MappedGridData()
{
destroy(EVERYTHING); // *wdh* 981121 - fix a major leak
// do this for now
#ifdef USE_PPP
// for (Integer kd=0; kd<3; kd++) for (Integer ks=0; ks<2; ks++)
// {
// delete pVertexBoundaryNormal[kd][ks];
// delete pVertexBoundaryTangent[kd][ks];
// }
#endif
}
MappedGridData& MappedGridData::
operator=(const MappedGridData& x)
{
equals(x);
return *this;
}
// ====================================================================================
// /Description:
// Equals operator plus options. This version is used when copying a GridCollection
// that has AMR grids -- in which case we do not want to make a deep copy of the Mapping.
//
// /options (input): (options % 2)==1 : do NOT copy the mapping
// ====================================================================================
GenericGridData& MappedGridData::
equals(const GenericGridData& x_, int option /* =0 */ )
{
// printf("==========MappedGridData::equals: option=%i\n",option);
assert( x_.getClassName()=="MappedGridData" );
MappedGridData & x = (MappedGridData&)x_;
Integer upd = NOTHING, des = NOTHING, kd, ks;
GenericGridData::operator=(x);
numberOfDimensions = x.numberOfDimensions;
boundaryCondition = x.boundaryCondition;
for (kd=0; kd<3; kd++) for (ks=0; ks<2; ks++) boundaryFlag[ks][kd]=x.boundaryFlag[ks][kd];
boundaryDiscretizationWidth = x.boundaryDiscretizationWidth;
boundingBox = x.boundingBox;
localBoundingBox = x.localBoundingBox;
gridSpacing = x.gridSpacing;
isAllCellCentered = x.isAllCellCentered;
isAllVertexCentered = x.isAllVertexCentered;
isCellCentered = x.isCellCentered;
discretizationWidth = x.discretizationWidth;
indexRange = x.indexRange;
extendedIndexRange = x.extendedIndexRange;
for (kd=0; kd<3; kd++) for (ks=0; ks<2; ks++) extendedRange(ks,kd)=x.extendedRange(ks,kd);
gridIndexRange = x.gridIndexRange;
dimension = x.dimension;
numberOfGhostPoints = x.numberOfGhostPoints;
useGhostPoints = x.useGhostPoints;
isPeriodic = x.isPeriodic;
sharedBoundaryFlag = x.sharedBoundaryFlag;
sharedBoundaryTolerance = x.sharedBoundaryTolerance;
// minimumEdgeLength = x.minimumEdgeLength;
// maximumEdgeLength = x.maximumEdgeLength;
if( (option % 2 )==0 )
{
// printf(" MappedGridData::equals: option=%i copy mapping x.getName()=%s\n",
// option,(const char*)x.mapping.getName(Mapping::mappingName));
mapping = x.mapping;
}
else
{
// printf(" MappedGridData::equals: option=%i do not copy mapping x.getName()=%s\n",
// option,(const char*)x.mapping.getName(Mapping::mappingName));
}
refinementGrid = x.refinementGrid;
shareGridWithMapping = x.shareGridWithMapping;
gridType = x.gridType; // kkc 110403
// *wdh* 060723 -- Sometimes we do not want to to copy the partition, e.g. when we are copying from
// one parallel distribution to another.
// We need an option to indicate whether we should copy the partition.
// ?? partition is not copied?? partitionInitialized = x.partitionInitialized;
if (x.mask &&
x.mask ->grid == &x)
upd |= THEmask;
else des |= THEmask;
if (x.inverseVertexDerivative &&
x.inverseVertexDerivative->grid == &x)
upd |= THEinverseVertexDerivative;
else des |= THEinverseVertexDerivative;
if (x.inverseCenterDerivative &&
x.inverseCenterDerivative->grid == &x)
upd |= THEinverseCenterDerivative;
else des |= THEinverseCenterDerivative;
if (x.vertex &&
x.vertex ->grid == &x)
upd |= THEvertex;
else des |= THEvertex;
if (x.center &&
x.center ->grid == &x)
upd |= THEcenter;
else des |= THEcenter;
if (x.corner &&
x.corner ->grid == &x)
upd |= THEcorner;
else des |= THEcorner;
if (x.vertexDerivative &&
x.vertexDerivative ->grid == &x)
upd |= THEvertexDerivative;
else des |= THEvertexDerivative;
if (x.centerDerivative &&
x.centerDerivative ->grid == &x)
upd |= THEcenterDerivative;
else des |= THEcenterDerivative;
if (x.vertexJacobian &&
x.vertexJacobian ->grid == &x)
upd |= THEvertexJacobian;
else des |= THEvertexJacobian;
if (x.centerJacobian &&
x.centerJacobian ->grid == &x)
upd |= THEcenterJacobian;
else des |= THEcenterJacobian;
if (x.cellVolume &&
x.cellVolume ->grid == &x)
upd |= THEcellVolume;
else des |= THEcellVolume;
if (x.centerNormal &&
x.centerNormal ->grid == &x)
upd |= THEcenterNormal;
else des |= THEcenterNormal;
if (x.centerArea &&
x.centerArea ->grid == &x)
upd |= THEcenterArea;
else des |= THEcenterArea;
if (x.faceNormal &&
x.faceNormal ->grid == &x)
upd |= THEfaceNormal;
else des |= THEfaceNormal;
if (x.faceArea &&
x.faceArea ->grid == &x)
upd |= THEfaceArea;
else des |= THEfaceArea;
for (kd=0; kd<numberOfDimensions; kd++) for (ks=0; ks<2; ks++)
{
if( (x.vertexBoundaryNormal[kd][ks] && x.vertexBoundaryNormal[kd][ks]->grid == &x) ||
x.pVertexBoundaryNormal[kd][ks] )
upd |= THEvertexBoundaryNormal;
else
des |= THEvertexBoundaryNormal;
if( (x.centerBoundaryNormal[kd][ks] && x.centerBoundaryNormal[kd][ks]->grid == &x) ||
x.pCenterBoundaryNormal[kd][ks] )
upd |= THEcenterBoundaryNormal;
else
des |= THEcenterBoundaryNormal;
if( (x.centerBoundaryTangent[kd][ks] && x.centerBoundaryTangent[kd][ks]->grid == &x) ||
x.pCenterBoundaryTangent[kd][ks] )
upd |= THEcenterBoundaryTangent;
else
des |= THEcenterBoundaryTangent;
} // end for
// upd |= x.computedGeometry & (THEminMaxEdgeLength | THEboundingBox);
upd |= x.computedGeometry & (THEboundingBox);
if (upd &= ~des) update(upd, COMPUTEnothing); if (des) destroy(des);
// #ifdef USE_PPP
// Partitioning_Type & xPartition = x.partition;
// const intSerialArray & ps = partition.getProcessorSet();
// const intSerialArray & xps = xPartition.getProcessorSet();
// // display(ps,"partition.getProcessorSet()");
// // display(xps,"xPartition.getProcessorSet()");
// const bool sameParallelDistribution = ps.getLength(0)==xps.getLength(0) && max(abs(ps-xps))==0;
// #else
// const bool sameParallelDistribution = true;
// #endif
const bool sameParallelDistribution = hasSameDistribution(partition,x.partition);
const int nd=4;
Index Iv[4]; // null Index means copy all values.
if( mask && mask->grid == this)
{
if( sameParallelDistribution )
assign(*mask,*x.mask);
else
{
// mask->IntegerDistributedArray::operator = (*x.mask);
CopyArray::copyArray(*mask,Iv,*x.mask,Iv,nd);
}
mask ->updateToMatchGrid(*this);
} // end if
if( inverseVertexDerivative && inverseVertexDerivative->grid == this)
{
if( sameParallelDistribution )
assign(*inverseVertexDerivative,*x.inverseVertexDerivative);
else
{
// inverseVertexDerivative ->RealDistributedArray::operator = (*x.inverseVertexDerivative);
CopyArray::copyArray(*inverseVertexDerivative,Iv,*x.inverseVertexDerivative,Iv,nd);
}
inverseVertexDerivative ->updateToMatchGrid(*this);
} // end if
if( inverseCenterDerivative && inverseCenterDerivative->grid == this)
{
if( sameParallelDistribution )
assign(*inverseCenterDerivative,*x.inverseCenterDerivative);
else
{
// inverseCenterDerivative ->RealDistributedArray::operator = (*x.inverseCenterDerivative);
CopyArray::copyArray(*inverseCenterDerivative,Iv,*x.inverseCenterDerivative,Iv,nd);
}
inverseCenterDerivative ->updateToMatchGrid(*this);
} // end if
if( vertex && vertex->grid == this)
{
if( sameParallelDistribution )
assign(*vertex,*x.vertex);
else
{
// vertex->RealDistributedArray::operator = (*x.vertex);
CopyArray::copyArray(*vertex,Iv,*x.vertex,Iv,nd);
}
vertex->updateToMatchGrid(*this);
} // end if
if( center && center->grid == this)
{
if( sameParallelDistribution )
assign(*center,*x.center);
else
{
// center->RealDistributedArray::operator= (*x.center);
CopyArray::copyArray(*center,Iv,*x.center,Iv,nd);
}
center->updateToMatchGrid(*this);
} // end if
if( corner && corner->grid == this)
{
if( sameParallelDistribution )
assign(*corner,*x.corner);
else
{
// corner->RealDistributedArray::operator = (*x.corner);
CopyArray::copyArray(*corner,Iv,*x.corner,Iv,nd);
}
corner->updateToMatchGrid(*this);
} // end if
if( vertexDerivative && vertexDerivative->grid == this)
{
if( sameParallelDistribution )
assign(*vertexDerivative,*x.vertexDerivative);
else
{
// vertexDerivative->RealDistributedArray::operator = (*x.vertexDerivative);
CopyArray::copyArray(*vertexDerivative,Iv,*x.vertexDerivative,Iv,nd);
}
vertexDerivative ->updateToMatchGrid(*this);
} // end if
if( centerDerivative && centerDerivative->grid == this)
{
if( sameParallelDistribution )
assign(*centerDerivative,*x.centerDerivative);
else
{
// centerDerivative->RealDistributedArray::operator = (*x.centerDerivative);
CopyArray::copyArray(*centerDerivative,Iv,*x.centerDerivative,Iv,nd);
}
centerDerivative->updateToMatchGrid(*this);
} // end if
if( vertexJacobian && vertexJacobian->grid == this)
{
if( sameParallelDistribution )
assign(*vertexJacobian,*x.vertexJacobian);
else
{
// vertexJacobian->RealDistributedArray::operator = (*x.vertexJacobian);
CopyArray::copyArray(*vertexJacobian,Iv,*x.vertexJacobian,Iv,nd);
}
vertexJacobian->updateToMatchGrid(*this);
} // end if
if( centerJacobian && centerJacobian->grid == this)
{
if( sameParallelDistribution )
assign(*centerJacobian,*x.centerJacobian);
else
{
// centerJacobian->RealDistributedArray::operator = (*x.centerJacobian);
CopyArray::copyArray(*centerJacobian,Iv,*x.centerJacobian,Iv,nd);
}
centerJacobian->updateToMatchGrid(*this);
} // end if
if( cellVolume && cellVolume->grid == this)
{
if( sameParallelDistribution )
assign(*cellVolume,*x.cellVolume);
else
{
// cellVolume->RealDistributedArray::operator = (*x.cellVolume);
CopyArray::copyArray(*cellVolume,Iv,*x.cellVolume,Iv,nd);
}
cellVolume->updateToMatchGrid(*this);
} // end if
if( centerNormal && centerNormal->grid == this)
{
if( sameParallelDistribution )
assign(*centerNormal,*x.centerNormal);
else
{
// centerNormal->RealDistributedArray::operator = (*x.centerNormal);
CopyArray::copyArray(*centerNormal,Iv,*x.centerNormal,Iv,nd);
}
centerNormal->updateToMatchGrid(*this);
} // end if
if( centerArea && centerArea->grid == this)
{
if( sameParallelDistribution )
assign(*centerArea,*x.centerArea);
else
{
// centerArea->RealDistributedArray::operator = (*x.centerArea);
CopyArray::copyArray(*centerArea,Iv,*x.centerArea,Iv,nd);
}
centerArea->updateToMatchGrid(*this);
} // end if
if( faceNormal && faceNormal->grid == this)
{
if( sameParallelDistribution )
assign(*faceNormal,*x.faceNormal);
else
{
// faceNormal->RealDistributedArray::operator = (*x.faceNormal);
CopyArray::copyArray(*faceNormal,Iv,*x.faceNormal,Iv,nd);
}
faceNormal->updateToMatchGrid(*this);
} // end if
if( faceArea && faceArea->grid == this)
{
if( sameParallelDistribution )
assign(*faceArea,*x.faceArea);
else
{
// faceArea->RealDistributedArray::operator = (*x.faceArea);
CopyArray::copyArray(*faceArea,Iv,*x.faceArea,Iv,nd);
}
faceArea->updateToMatchGrid(*this);
} // end if
for (kd=0; kd<3; kd++) for (ks=0; ks<2; ks++)
{
if( vertexBoundaryNormal[kd][ks] && vertexBoundaryNormal[kd][ks]->elementCount() )
{
if( sameParallelDistribution )
assign(*vertexBoundaryNormal[kd][ks],*x.vertexBoundaryNormal[kd][ks]);
else
{
// vertexBoundaryNormal[kd][ks]->RealDistributedArray::operator= (*x.vertexBoundaryNormal[kd][ks]);
CopyArray::copyArray(*vertexBoundaryNormal[kd][ks],Iv,*x.vertexBoundaryNormal[kd][ks],Iv,nd);
}
vertexBoundaryNormal[kd][ks]->updateToMatchGrid(*this);
} // end if
if( centerBoundaryNormal[kd][ks] && centerBoundaryNormal[kd][ks]->elementCount() )
{
if( sameParallelDistribution )
assign(*centerBoundaryNormal[kd][ks],*x.centerBoundaryNormal[kd][ks]);
else
{
// centerBoundaryNormal[kd][ks]->RealDistributedArray::operator= (*x.centerBoundaryNormal[kd][ks]);
CopyArray::copyArray(*centerBoundaryNormal[kd][ks],Iv,*x.centerBoundaryNormal[kd][ks],Iv,nd);
}
centerBoundaryNormal[kd][ks]->updateToMatchGrid(*this);
} // end if
if( centerBoundaryTangent[kd][ks] && centerBoundaryTangent[kd][ks]->elementCount() )
{
if( sameParallelDistribution )
assign(*centerBoundaryTangent[kd][ks],*x.centerBoundaryTangent[kd][ks]);
else
{
// centerBoundaryTangent[kd][ks]->RealDistributedArray::operator= (*x.centerBoundaryTangent[kd][ks]);
CopyArray::copyArray(*centerBoundaryTangent[kd][ks],Iv,*x.centerBoundaryTangent[kd][ks],Iv,nd);
}
centerBoundaryTangent[kd][ks]->updateToMatchGrid(*this);
} // end if
// **** this next section is wrong -- in parallel the arrays may not be the same
// size since the parallel distributions could be different.
if( pVertexBoundaryNormal[kd][ks] && pVertexBoundaryNormal[kd][ks]->elementCount() )
{
// pVertexBoundaryNormal[kd][ks]->RealArray::operator= (*x.pVertexBoundaryNormal[kd][ks]);
RealArray & u = *pVertexBoundaryNormal[kd][ks];
const RealArray & v = *x.pVertexBoundaryNormal[kd][ks];
if( u.dimension(0)==v.dimension(0) &&
u.dimension(1)==v.dimension(1) &&
u.dimension(2)==v.dimension(2) )
{
u=v;
}
else
{
// ** fix this -- recompute ---
u.redim(0);
}
} // end if
if( pCenterBoundaryNormal[kd][ks] && pCenterBoundaryNormal[kd][ks]->elementCount() )
{
// pCenterBoundaryNormal[kd][ks]->RealArray::operator= (*x.pCenterBoundaryNormal[kd][ks]);
RealArray & u = *pCenterBoundaryNormal[kd][ks];
const RealArray & v = *x.pCenterBoundaryNormal[kd][ks];
if( u.dimension(0)==v.dimension(0) &&
u.dimension(1)==v.dimension(1) &&
u.dimension(2)==v.dimension(2) )
{
u=v;
}
else
{
// ** fix this -- recompute ---
u.redim(0);
}
} // end if
if( pCenterBoundaryTangent[kd][ks] && pCenterBoundaryTangent[kd][ks]->elementCount() )
{
// pCenterBoundaryTangent[kd][ks]->RealArray::operator= (*x.pCenterBoundaryTangent[kd][ks]);
RealArray & u = *pCenterBoundaryTangent[kd][ks];
const RealArray & v = *x.pCenterBoundaryTangent[kd][ks];
if( u.dimension(0)==v.dimension(0) &&
u.dimension(1)==v.dimension(1) &&
u.dimension(2)==v.dimension(2) )
{
u=v;
}
else
{
// ** fix this -- recompute ---
u.redim(0);
}
} // end if
} // end for
computedGeometry |= upd & x.computedGeometry;
return *this;
}
void MappedGridData::
reference(const MappedGridData& x)
{
cerr << "MappedGridData::reference(const MappedGridData&) was called!"
<< endl;
GenericGridData::reference(x);
}
void MappedGridData::breakReference() {
cerr << "MappedGridData::breakReference() was called!" << endl;
GenericGridData::breakReference();
}
void MappedGridData::consistencyCheck() const {
GenericGridData::consistencyCheck();
boundaryCondition .Test_Consistency();
boundaryDiscretizationWidth.Test_Consistency();
boundingBox .Test_Consistency();
localBoundingBox .Test_Consistency();
gridSpacing .Test_Consistency();
isCellCentered .Test_Consistency();
discretizationWidth .Test_Consistency();
indexRange .Test_Consistency();
extendedIndexRange .Test_Consistency();
gridIndexRange .Test_Consistency();
dimension .Test_Consistency();
numberOfGhostPoints .Test_Consistency();
isPeriodic .Test_Consistency();
sharedBoundaryFlag .Test_Consistency();
sharedBoundaryTolerance .Test_Consistency();
// minimumEdgeLength .Test_Consistency();
// maximumEdgeLength .Test_Consistency();
if (mask)
mask ->consistencyCheck();
if (inverseVertexDerivative)
inverseVertexDerivative ->consistencyCheck();
// if (inverseVertexDerivative2D)
// inverseVertexDerivative2D ->consistencyCheck();
// if (inverseVertexDerivative1D)
// inverseVertexDerivative1D ->consistencyCheck();
if (inverseCenterDerivative)
inverseCenterDerivative ->consistencyCheck();
// if (inverseCenterDerivative2D)
// inverseCenterDerivative2D ->consistencyCheck();
// if (inverseCenterDerivative1D)
// inverseCenterDerivative1D ->consistencyCheck();
if (vertex)
vertex ->consistencyCheck();
// if (vertex2D)
// vertex2D ->consistencyCheck();
// if (vertex1D)
// vertex1D ->consistencyCheck();
if (center)
center ->consistencyCheck();
// if (center2D)
// center2D ->consistencyCheck();
// if (center1D)
// center1D ->consistencyCheck();
if (corner)
corner ->consistencyCheck();
// if (corner2D)
// corner2D ->consistencyCheck();
// if (corner1D)
// corner1D ->consistencyCheck();
if (vertexDerivative)
vertexDerivative ->consistencyCheck();
// if (vertexDerivative2D)
// vertexDerivative2D ->consistencyCheck();
// if (vertexDerivative1D)
// vertexDerivative1D ->consistencyCheck();
if (centerDerivative)
centerDerivative ->consistencyCheck();
// if (centerDerivative2D)
// centerDerivative2D ->consistencyCheck();
// if (centerDerivative1D)
// centerDerivative1D ->consistencyCheck();
if (vertexJacobian)
vertexJacobian ->consistencyCheck();
if (centerJacobian)
centerJacobian ->consistencyCheck();
if (cellVolume)
cellVolume ->consistencyCheck();
if (centerNormal)
centerNormal ->consistencyCheck();
// if (centerNormal2D)
// centerNormal2D ->consistencyCheck();
// if (centerNormal1D)
// centerNormal1D ->consistencyCheck();
if (centerArea)
centerArea ->consistencyCheck();
// if (centerArea2D)
// centerArea2D ->consistencyCheck();
// if (centerArea1D)
// centerArea1D ->consistencyCheck();
if (faceNormal)
faceNormal ->consistencyCheck();
// if (faceNormal2D)
// faceNormal2D ->consistencyCheck();
// if (faceNormal1D)
// faceNormal1D ->consistencyCheck();
if (faceArea)
faceArea ->consistencyCheck();
// if (faceArea2D)
// faceArea2D ->consistencyCheck();
// if (faceArea1D)
// faceArea1D ->consistencyCheck();
for (Integer i=0; i<3; i++) for (Integer j=0; j<2; j++) {
if (vertexBoundaryNormal [i][j])
vertexBoundaryNormal [i][j]->consistencyCheck();
if (centerBoundaryNormal [i][j])
centerBoundaryNormal [i][j]->consistencyCheck();
if (centerBoundaryTangent[i][j])
centerBoundaryTangent[i][j]->consistencyCheck();
} // end for, end for
mapping .consistencyCheck();
I1array .Test_Consistency();
I2array .Test_Consistency();
I3array .Test_Consistency();
}
Integer MappedGridData::
get(const GenericDataBase& db,
const aString& name,
bool getMapping /* =true */ )
// ===========================================================================================
// /getMapping(input) for AMR grids we may not get the mapping.
// ===========================================================================================
{
Integer returnValue = 0, kd, ks;
GenericDataBase& dir = *db.virtualConstructor();
db.find(dir, name, getClassName());
returnValue |= GenericGridData::get(dir, "GenericGridData");
returnValue |= dir.get(numberOfDimensions, "numberOfDimensions");
const Integer computedGeometry0 = computedGeometry;
initialize(numberOfDimensions);
returnValue |= dir.get(boundaryCondition, "boundaryCondition");
int boundaryFlagReturnValue = dir.get((int*)boundaryFlag,"boundaryFlag",6);
returnValue |= boundaryFlagReturnValue;
returnValue |= dir.get(boundaryDiscretizationWidth,
"boundaryDiscretizationWidth");
returnValue |= dir.get(boundingBox, "boundingBox");
returnValue |= dir.get(gridSpacing, "gridSpacing");
#if defined GNU || defined __PHOTON || defined __DECCXX
{
Integer foo;
returnValue |= dir.get(foo, "isAllCellCentered");
isAllCellCentered = foo;
returnValue |= dir.get(foo, "isAllVertexCentered");
isAllVertexCentered = foo;
}
#else
returnValue |= dir.get(isAllCellCentered, "isAllCellCentered");
returnValue |= dir.get(isAllVertexCentered, "isAllVertexCentered");
#endif // defined GNU || defined __PHOTON || defined __DECCXX
returnValue |= dir.get(isCellCentered, "isCellCentered");
returnValue |= dir.get(discretizationWidth, "discretizationWidth");
returnValue |= dir.get(indexRange, "indexRange");
returnValue |= dir.get(extendedIndexRange, "extendedIndexRange");
int extendedRangeReturnValue = dir.get(pExtendedRange, "extendedRange",6);
returnValue |= extendedRangeReturnValue;
returnValue |= dir.get(gridIndexRange, "gridIndexRange");
returnValue |= dir.get(dimension, "dimension");
returnValue |= dir.get(numberOfGhostPoints, "numberOfGhostPoints");
#if defined GNU || defined __PHOTON || defined __DECCXX
{
Integer foo;
returnValue |= dir.get(foo, "useGhostPoints");
useGhostPoints = foo;
}
#else
returnValue |= dir.get(useGhostPoints, "useGhostPoints");
#endif // defined GNU || defined __PHOTON || defined __DECCXX
returnValue |= dir.get(isPeriodic, "isPeriodic");
returnValue |= dir.get(sharedBoundaryFlag, "sharedBoundaryFlag");
returnValue |= dir.get(sharedBoundaryTolerance, "sharedBoundaryTolerance");
// *wdh* 100424 returnValue |= dir.get(minimumEdgeLength, "minimumEdgeLength");
// *wdh* 100424 returnValue |= dir.get(maximumEdgeLength, "maximumEdgeLength");
returnValue |= dir.get(I1array, "I1");
returnValue |= dir.get(I2array, "I2");
returnValue |= dir.get(I3array, "I3");
I1 = I1array.getDataPointer() - I1array.getBase(0);
I2 = I2array.getDataPointer() - I2array.getBase(0);
I3 = I3array.getDataPointer() - I3array.getBase(0);
int temp;
// returnValue |= dir.get(temp,"gridType"); gridType=(GenericGrid::GridTypeEnum)temp;
if (!dir.get(temp,"gridType") )
gridType=(GenericGrid::GridTypeEnum)temp;
else // old grids usually are structured
{
printF("MappedGrid::get:Warning: gridType missing! Assuming it is a structuredGrid\n");
gridType=GenericGrid::structuredGrid;
}
if( !dir.get(shareGridWithMapping,"shareGridWithMapping") )
{
shareGridWithMapping=true;
}
if( boundaryFlagReturnValue!=0 )
{
// printf("filling in boundaryFlag\n");
for( kd=numberOfDimensions; kd<3; kd++ )
{
boundaryFlag[0][kd]=boundaryFlag[1][kd]=periodicBoundary;
}
for (kd=0; kd<numberOfDimensions; kd++)
{
for (ks=0; ks<2; ks++)
{
boundaryFlag[ks][kd]=boundaryCondition(ks,kd) > 0 ? physicalBoundary :
boundaryCondition(ks,kd)==0 ? interpolationBoundary :
isPeriodic(kd)==Mapping::functionPeriodic ? branchCutPeriodicBoundary : periodicBoundary;
}
}
}
if( extendedRangeReturnValue!=0 )
{
// printf("filling in extendedRange \n");
for( kd=numberOfDimensions; kd<3; kd++ )
{
extendedRange(0,kd)=extendedRange(1,kd)=0;
}
for (kd=0; kd<numberOfDimensions; kd++)
{
for (ks=0; ks<2; ks++)
{
extendedRange(ks,kd)=boundaryFlag[ks][kd]!=mixedPhysicalInterpolationBoundary ? extendedIndexRange(ks,kd):
indexRange(ks,kd) + (2*ks-1) * (discretizationWidth(kd) - 1) / 2 ;
}
} // end for
}
initializePartition();
if( getMapping )
{
if( false )
{
const intSerialArray & processorSet = partition.getProcessorSet();
printF("MappedGrid::get partition -> processors=[%i,%i]\n",
processorSet(processorSet.getBase(0)),processorSet(processorSet.getBound(0)));
}
// The mapping get the same partition as the MappedGrid. *wdh* 110820
// This partition is used for the grid in the Mapping and the grid points in the DataPointMapping
returnValue |= mapping.get(dir, "mapping", &partition);
}
MappedGridData::update((GenericGridData&)*this,
computedGeometry0 & EVERYTHING, COMPUTEnothing);
computedGeometry = computedGeometry0;
if (computedGeometry & THEmask)
returnValue |= mask ->get(dir, "mask");
// *******************
// initializePartition(); // *wdh* turned OFF 2011/08/22
// printF("MappedGridData:get mask.getGhostBoundaryWidth =[%i,%i]\n",
// mask->getGhostBoundaryWidth(0),mask->getGhostBoundaryWidth(1));
// *******************
if( computedGeometry & THEboundingBox )
{
// Now compute the local bounding box for the part of the grid on this processor
// -- base this on the extendedGridIndexRange (include periodic pts and ghost-pts on interp boundaries)
#ifdef USE_PPP
IntegerArray extendedGridIndexRange(2,3);
extendedGridIndexRange=gridIndexRange;
for( int side=Start; side<=End; side++ )
{
for( int axis=0; axis<numberOfDimensions; axis++ )
{
if( boundaryCondition(side,axis)==0 )
{
extendedGridIndexRange(side,axis)=extendedIndexRange(side,axis);
}
}
}
bool local=true;
mapping.getMapping().getBoundingBox(extendedGridIndexRange,gridIndexRange,localBoundingBox,local);
#else
localBoundingBox=boundingBox;
#endif
}
if (computedGeometry & THEinverseVertexDerivative)
returnValue |= inverseVertexDerivative->get(dir, "inverseVertexDerivative");
if (computedGeometry & THEinverseCenterDerivative)
returnValue |= inverseCenterDerivative->get(dir, "inverseCenterDerivative");
if (computedGeometry & THEvertex)
returnValue |= vertex ->get(dir, "vertex");
if (computedGeometry & THEcenter)
returnValue |= center ->get(dir, "center");
if (computedGeometry & THEcorner)
returnValue |= corner ->get(dir, "corner");
if (computedGeometry & THEvertexDerivative)
returnValue |= vertexDerivative ->get(dir, "vertexDerivative");
if (computedGeometry & THEcenterDerivative)
returnValue |= centerDerivative ->get(dir, "centerDerivative");
if (computedGeometry & THEvertexJacobian)
returnValue |= vertexJacobian ->get(dir, "vertexJacobian");
if (computedGeometry & THEcenterJacobian)
returnValue |= centerJacobian ->get(dir, "centerJacobian");
if (computedGeometry & THEcellVolume)
returnValue |= cellVolume ->get(dir, "cellVolume");
if (computedGeometry & THEcenterNormal)
returnValue |= centerNormal ->get(dir, "centerNormal");
if (computedGeometry & THEcenterArea)
returnValue |= centerArea ->get(dir, "centerArea");
if (computedGeometry & THEfaceNormal)
returnValue |= faceNormal ->get(dir, "faceNormal");
if (computedGeometry & THEfaceArea)
returnValue |= faceArea ->get(dir, "faceArea");
// *wdh* for (kd=0; kd<3; kd++)
for (kd=0; kd<numberOfDimensions; kd++)
{
for (ks=0; ks<2; ks++)
{
char normal_kd_ks[32];
if (computedGeometry & THEvertexBoundaryNormal)
{
sprintf(normal_kd_ks, "vertexBoundaryNormal[%d][%d]", kd, ks);
if( vertexBoundaryNormal[kd][ks]!=NULL )
returnValue |= vertexBoundaryNormal[kd][ks]->get(dir, normal_kd_ks);
else
returnValue |= dir.get(*pVertexBoundaryNormal[kd][ks],normal_kd_ks);
} // end if
if (computedGeometry & THEcenterBoundaryNormal)
{
sprintf(normal_kd_ks, "centerBoundaryNormal[%d][%d]", kd, ks);
if( centerBoundaryNormal[kd][ks]!=NULL )
returnValue |= centerBoundaryNormal[kd][ks]->get(dir, normal_kd_ks);
else
returnValue |= dir.get(*pCenterBoundaryNormal[kd][ks],normal_kd_ks);
} // end if
if (computedGeometry & THEcenterBoundaryTangent)
{
sprintf(normal_kd_ks, "centerBoundaryTangent[%d][%d]", kd, ks);
if( centerBoundaryTangent[kd][ks]!=NULL )
returnValue |= centerBoundaryTangent[kd][ks]->get(dir,normal_kd_ks);
else
returnValue |= dir.get(*pCenterBoundaryTangent[kd][ks],normal_kd_ks);
} // end if
} // end for
} // end for
delete &dir;
return returnValue;
}
Integer MappedGridData::
put(GenericDataBase& db,
const aString& name,
bool putMapping /* = true */,
int geometryToPut /* = -1 */
) const
// geometryToPut : by default put computedGeometry
{
// printf("\n ####### MG:put: geometryToPut on input = %i\n", geometryToPut);
Integer returnValue = 0;
if( geometryToPut==-1 )
{
geometryToPut=computedGeometry;
}
else
{
// The user has specified what to save but we can only save what has been computed:
geometryToPut= geometryToPut & computedGeometry;
// printf("\n ####### MG:put: computedGeometry = %i\n", computedGeometry);
// printf("\n ####### MG:put: computedGeometry & THEmask = %i\n",int(computedGeometry & THEmask));
// printf("\n ####### MG:put: geometryToPut & computedGeometry = %i\n", geometryToPut);
}
// printf("\n ####### MG:put: geometryToPut & THEmask = %i\n\n",int(geometryToPut & THEmask));
// printf("\n ####### MG:put: geometryToPut & THEivd = %i\n\n",int(geometryToPut & THEinverseVertexDerivative));
GenericDataBase& dir = *db.virtualConstructor();
db.create(dir, name, getClassName());
returnValue |= GenericGridData::put(dir, "GenericGridData", putMapping, geometryToPut );
returnValue |= dir.put(numberOfDimensions, "numberOfDimensions");
returnValue |= dir.put(boundaryCondition, "boundaryCondition");
returnValue |= dir.put((int*)boundaryFlag,"boundaryFlag",6);
returnValue |= dir.put(boundaryDiscretizationWidth,
"boundaryDiscretizationWidth");
returnValue |= dir.put(boundingBox, "boundingBox");
returnValue |= dir.put(gridSpacing, "gridSpacing");
#if defined GNU || defined __PHOTON || defined __DECCXX
{
Integer foo = isAllCellCentered;
returnValue |= dir.put(foo, "isAllCellCentered");
foo = isAllVertexCentered;
returnValue |= dir.put(foo, "isAllVertexCentered");
}
#else
returnValue |= dir.put(isAllCellCentered, "isAllCellCentered");
returnValue |= dir.put(isAllVertexCentered, "isAllVertexCentered");
#endif // defined GNU || defined __PHOTON || defined __DECCXX
returnValue |= dir.put(isCellCentered, "isCellCentered");
returnValue |= dir.put(discretizationWidth, "discretizationWidth");
returnValue |= dir.put(indexRange, "indexRange");
returnValue |= dir.put(extendedIndexRange, "extendedIndexRange");
returnValue |= dir.put(pExtendedRange, "extendedRange",6);
returnValue |= dir.put(gridIndexRange, "gridIndexRange");
returnValue |= dir.put(dimension, "dimension");
returnValue |= dir.put(numberOfGhostPoints, "numberOfGhostPoints");
#if defined GNU || defined __PHOTON || defined __DECCXX
{
Integer foo = useGhostPoints;
returnValue |= dir.put(foo, "useGhostPoints");
}
#else
returnValue |= dir.put(useGhostPoints, "useGhostPoints");
#endif // defined GNU || defined __PHOTON || defined __DECCXX
returnValue |= dir.put(isPeriodic, "isPeriodic");
returnValue |= dir.put(sharedBoundaryFlag, "sharedBoundaryFlag");
returnValue |= dir.put(sharedBoundaryTolerance, "sharedBoundaryTolerance");
// *wdh* 100424 returnValue |= dir.put(minimumEdgeLength, "minimumEdgeLength");
// *wdh* 100424 returnValue |= dir.put(maximumEdgeLength, "maximumEdgeLength");
returnValue |= dir.put(I1array, "I1");
returnValue |= dir.put(I2array, "I2");
returnValue |= dir.put(I3array, "I3");
returnValue |= dir.put((int)gridType,"gridType");
returnValue |= dir.put(shareGridWithMapping,"shareGridWithMapping");
if( putMapping )
returnValue |= mapping.put(dir, "mapping");
if (geometryToPut & THEmask)
returnValue |= mask ->put(dir, "mask");
if (geometryToPut & THEinverseVertexDerivative)
returnValue |= inverseVertexDerivative->put(dir, "inverseVertexDerivative");
if (geometryToPut & THEinverseCenterDerivative)
returnValue |= inverseCenterDerivative->put(dir, "inverseCenterDerivative");
if (geometryToPut & THEvertex)
returnValue |= vertex ->put(dir, "vertex");
if (geometryToPut & THEcenter)
returnValue |= center ->put(dir, "center");
if (geometryToPut & THEcorner)
returnValue |= corner ->put(dir, "corner");
if (geometryToPut & THEvertexDerivative)
returnValue |= vertexDerivative ->put(dir, "vertexDerivative");
if (geometryToPut & THEcenterDerivative)
returnValue |= centerDerivative ->put(dir, "centerDerivative");
if (geometryToPut & THEvertexJacobian)
returnValue |= vertexJacobian ->put(dir, "vertexJacobian");
if (geometryToPut & THEcenterJacobian)
returnValue |= centerJacobian ->put(dir, "centerJacobian");
if (geometryToPut & THEcellVolume)
returnValue |= cellVolume ->put(dir, "cellVolume");
if (geometryToPut & THEcenterNormal)
returnValue |= centerNormal ->put(dir, "centerNormal");
if (geometryToPut & THEcenterArea)
returnValue |= centerArea ->put(dir, "centerArea");
if (geometryToPut & THEfaceNormal)
returnValue |= faceNormal ->put(dir, "faceNormal");
if (geometryToPut & THEfaceArea)
returnValue |= faceArea ->put(dir, "faceArea");
// *wdh* for (Integer kd=0; kd<3; kd++)
for (Integer kd=0; kd<numberOfDimensions; kd++)
{
for (Integer ks=0; ks<2; ks++)
{
char normal_kd_ks[32];
if (geometryToPut & THEvertexBoundaryNormal)
{
sprintf(normal_kd_ks, "vertexBoundaryNormal[%d][%d]", kd, ks);
if( vertexBoundaryNormal[kd][ks]!=NULL )
returnValue |= vertexBoundaryNormal[kd][ks]->put(dir, normal_kd_ks);
else
returnValue |= dir.put(*pVertexBoundaryNormal[kd][ks],normal_kd_ks);
} // end if
if (geometryToPut & THEcenterBoundaryNormal)
{
sprintf(normal_kd_ks, "centerBoundaryNormal[%d][%d]", kd, ks);
if( centerBoundaryNormal[kd][ks]!=NULL )
returnValue |= centerBoundaryNormal[kd][ks]->put(dir, normal_kd_ks);
else
returnValue |= dir.put(*pCenterBoundaryNormal[kd][ks],normal_kd_ks);
} // end if
if (geometryToPut & THEcenterBoundaryTangent)
{
sprintf(normal_kd_ks, "centerBoundaryTangent[%d][%d]", kd, ks);
if( centerBoundaryTangent[kd][ks]!=NULL )
returnValue |= centerBoundaryTangent[kd][ks]->put(dir,normal_kd_ks);
else
returnValue |= dir.put(*pCenterBoundaryTangent[kd][ks],normal_kd_ks);
} // end if
} // end for
} // end for
delete &dir;
return returnValue;
}
void MappedGridData::
specifyProcesses(const Range& range)
{
if( false )
{
partition.SpecifyProcessorRange(range);
matrixPartition.SpecifyProcessorRange(range);
// for some reason we need to re-initialize the partition after changing the number of processors
// or otherwise the number of parallel ghost lines is missing
partitionInitialized=false;
matrixPartitionInitialized=false;
#ifdef USE_PPP
assert( partition.Internal_Partitioning_Object->Starting_Processor == range.getBase() );
assert( partition.Internal_Partitioning_Object->Ending_Processor == range.getBound() );
#endif
}
else
{
#ifdef USE_PPP
partition.Internal_Partitioning_Object->Starting_Processor=range.getBase();
partition.Internal_Partitioning_Object->Ending_Processor=range.getBound();
matrixPartition.Internal_Partitioning_Object->Starting_Processor=range.getBase();
matrixPartition.Internal_Partitioning_Object->Ending_Processor=range.getBound();
#endif
}
if( numberOfDimensions>0 )
initializePartition();
if( false )
{
#ifdef USE_PPP
const intSerialArray & processorSet = partition.getProcessorSet();
const int pStart=processorSet(processorSet.getBase(0)), pEnd=processorSet(processorSet.getBound(0));
printF("MappedGridData:specifyProcesses: range=[%i,%i], partition -> processors=[%i,%i], Starting_Processor=%i Ending_Processor=%i\n",
range.getBase(), range.getBound(),pStart,pEnd,
partition.Internal_Partitioning_Object->Starting_Processor,
partition.Internal_Partitioning_Object->Ending_Processor
);
#endif
}
}
void MappedGridData::
initialize(const Integer& numberOfDimensions_)
{
boundaryCondition .redim(2, 3);
boundaryDiscretizationWidth.redim(2, 3);
boundingBox .redim(2, 3);
localBoundingBox .redim(2, 3);
gridSpacing .redim(3);
isCellCentered .redim(3);
discretizationWidth .redim(3);
indexRange .redim(2, 3);
extendedIndexRange .redim(2, 3);
gridIndexRange .redim(2, 3);
dimension .redim(2, 3);
numberOfGhostPoints .redim(2, 3);
isPeriodic .redim(3);
sharedBoundaryFlag .redim(2, 3);
sharedBoundaryTolerance .redim(2, 3);
// minimumEdgeLength .redim(3);
// maximumEdgeLength .redim(3);
destroy(~NOTHING & ~GenericGridData::EVERYTHING);
numberOfDimensions = numberOfDimensions_;
isAllCellCentered = LogicalFalse;
isAllVertexCentered = LogicalTrue;
useGhostPoints = LogicalFalse;
gridType=GenericGrid::structuredGrid;
Integer kd, ks;
for (kd=0; kd<numberOfDimensions; kd++)
{
gridSpacing(kd) = (Real).1;
isCellCentered(kd) = LogicalFalse;
discretizationWidth(kd) = 3;
isPeriodic(kd) = Mapping::notPeriodic;
// minimumEdgeLength(kd) = (Real)0.;
// maximumEdgeLength(kd) = (Real)0.;
for (ks=0; ks<2; ks++)
{
boundaryCondition(ks,kd) = 1;
boundaryFlag[ks][kd] = physicalBoundary;
boundaryDiscretizationWidth(ks,kd) = 3;
boundingBox(ks,kd) = (Real)0.;
localBoundingBox(ks,kd) = (Real)0.;
sharedBoundaryFlag(ks,kd) = 0;
sharedBoundaryTolerance(ks,kd) = (Real).1;
gridIndexRange(ks,kd) =
indexRange(ks,kd) = ks * 10;
numberOfGhostPoints(ks,kd) =
(discretizationWidth(kd) - 1) / 2;
dimension(ks,kd) =
gridIndexRange(ks,kd) + (2 * ks - 1) * numberOfGhostPoints(ks,kd);
} // end for
if ((isCellCentered(kd) || isPeriodic(kd)) &&
indexRange(1,kd) > indexRange(0,kd)) indexRange(1,kd)--;
// extended index range moves the interpolation points to ghost points on interpolation
// sides (except for interpolation on sides with polar singularities.)
// *wdh* extendedRange: include ghost points on c-grid boundaries since we interpolate there.
for (ks=0; ks<2; ks++)
{
extendedIndexRange(ks,kd) =
max0(indexRange(0,kd) - numberOfGhostPoints(0,kd),
min0(indexRange(1,kd) + numberOfGhostPoints(1,kd),
boundaryCondition(ks,kd) == 0 && useGhostPoints
&& mapping.getTypeOfCoordinateSingularity(ks,kd)!=Mapping::polarSingularity ?
indexRange(ks,kd) + (2*ks-1) * (discretizationWidth(kd) - 1) / 2 :
indexRange(ks,kd)));
extendedRange(ks,kd)=boundaryFlag[ks][kd]!=mixedPhysicalInterpolationBoundary ? extendedIndexRange(ks,kd):
indexRange(ks,kd) + (2*ks-1) * (discretizationWidth(kd) - 1) / 2 ;
}
} // end for
for (kd=numberOfDimensions; kd<3; kd++)
{
gridSpacing(kd) = (Real)1.;
isCellCentered(kd) = LogicalFalse;
discretizationWidth(kd) = 1;
isPeriodic(kd) = Mapping::derivativePeriodic;
// minimumEdgeLength(kd) = (Real)0.;
// maximumEdgeLength(kd) = (Real)0.;
for (ks=0; ks<2; ks++) {
boundaryCondition(ks,kd) = -1;
boundaryFlag[ks][kd] = periodicBoundary;
boundaryDiscretizationWidth(ks,kd) = 1;
boundingBox(ks,kd) = (Real)0.;
localBoundingBox(ks,kd) = (Real)0.;
sharedBoundaryFlag(ks,kd) = 0;
sharedBoundaryTolerance(ks,kd) = (Real)0.;
indexRange(ks,kd) = 0;
extendedIndexRange(ks,kd) = 0;
extendedRange(ks,kd) = 0;
gridIndexRange(ks,kd) = 0;
dimension(ks,kd) = 0;
numberOfGhostPoints(ks,kd) = 0;
} // end for
} // end for
}
int MappedGridData::
getWhatForGrid(const int what_) const
// ============================================================================
// /Description:
// remove items from what that are not appropriate for the gridType:
// /Return type: a new value for 'what'
// ============================================================================
{
int what=what_;
if( gridType==MappedGrid::unstructuredGrid ) // here are things we can update on an unstructured grid
what&= THEmask | THEvertex | THEcenter | THEcorner | THEcenter | THEcorner |
THEcellVolume | THEfaceNormal | THEfaceArea | THEboundingBox |
THEcenterNormal | THEcenterArea;
return what;
}
void MappedGridData::
initializePartition()
// =======================================================================================
// /Description:
// Initialize the partition object.
// =======================================================================================
{
int debug=0;
if( !partitionInitialized )
{
assert( numberOfDimensions>0 );
const int myid=max(0,Communication_Manager::My_Process_Number);
// if( debug & 1 )
// printf("***** myid=%i MappedGrid:: initialize the partition with (internal) address %d ***** \n",
// myid,partition.getInternalPartitioningObject());
partitionInitialized=true;
partition.SpecifyDecompositionAxes(numberOfDimensions);
int kd;
for (kd=0; kd<numberOfDimensions; kd++)
{
int numGhost=max(MappedGrid::minimumNumberOfDistributedGhostLines,(discretizationWidth(kd)-1)/2);
// set partition axes and number of ghost line boundaries
if( debug & 1 )
printf("****MappedGridData::initializePartition(): myid=%i, numGhost=%i ***\n",myid,numGhost);
partition.partitionAlongAxis(kd, true, numGhost );
}
for (kd=numberOfDimensions; kd<MAX_ARRAY_DIMENSION; kd++)
partition.partitionAlongAxis(kd, false, 0);
}
if( !matrixPartitionInitialized )
{
// The matrix partition is for coefficient matrices
matrixPartitionInitialized=true;
matrixPartition.SpecifyDecompositionAxes(numberOfDimensions+1); // is this needed?
int kd;
kd=0;
matrixPartition.partitionAlongAxis(kd, false, 0);
for (kd=1; kd<=numberOfDimensions; kd++)
{
int numGhost=max(MappedGrid::minimumNumberOfDistributedGhostLines,(discretizationWidth(kd-1)-1)/2);
// set partition axes and number of ghost line boundaries
matrixPartition.partitionAlongAxis(kd, true, numGhost );
}
for (kd=numberOfDimensions+1; kd<MAX_ARRAY_DIMENSION; kd++)
matrixPartition.partitionAlongAxis(kd, false, 0);
}
}
Integer MappedGridData::
update(GenericGridData& x,
const Integer what_,
const Integer how)
{
int what=getWhatForGrid(what_);
Integer upd = GenericGridData::update(x, what, how);
MappedGridData& y = (MappedGridData&)x;
const Range all, d0 = numberOfDimensions;
Integer computeNeeded =
how & COMPUTEgeometry ? what :
how & COMPUTEgeometryAsNeeded ? what & ~computedGeometry :
NOTHING;
//
// Compute isAllVertexCentered, isAllCellCentered, indexRange,
// extendedIndexRange, dimension and gridSpacing from the current values
// of boundaryCondition, discretizationWidth, isPeriodic, isCellCentered,
// gridIndexRange numberOfGhostPoints and useGhostPoints.
//
isAllVertexCentered = isAllCellCentered = LogicalTrue;
Integer kd, ks;
for (kd=0; kd<numberOfDimensions; kd++) {
if ( isCellCentered(kd)) isAllVertexCentered = LogicalFalse;
if (!isCellCentered(kd)) isAllCellCentered = LogicalFalse;
for (ks=0; ks<2; ks++) {
indexRange(ks,kd) = gridIndexRange(ks,kd);
dimension(ks,kd) = gridIndexRange(ks,kd) +
(2 * ks - 1) * numberOfGhostPoints(ks,kd);
} // end for
if ((isCellCentered(kd) || isPeriodic(kd)) &&
indexRange(1,kd) > indexRange(0,kd)) indexRange(1,kd)--;
for (ks=0; ks<2; ks++)
{
extendedIndexRange(ks,kd) =
max0(indexRange(0,kd) - numberOfGhostPoints(0,kd),
min0(indexRange(1,kd) + numberOfGhostPoints(1,kd),
boundaryCondition(ks,kd) == 0 && useGhostPoints
&& mapping.getTypeOfCoordinateSingularity(ks,kd)!=Mapping::polarSingularity ?
indexRange(ks,kd) + (2*ks-1) * (discretizationWidth(kd) - 1) / 2 :
indexRange(ks,kd)));
extendedRange(ks,kd)=boundaryFlag[ks][kd]!=mixedPhysicalInterpolationBoundary ? extendedIndexRange(ks,kd):
indexRange(ks,kd) + (2*ks-1) * (discretizationWidth(kd) - 1) / 2 ;
}
gridSpacing(kd) = (Real)1. /
max0(1, gridIndexRange(1,kd) - gridIndexRange(0,kd));
} // end for
for (kd=numberOfDimensions; kd<3; kd++) {
for (ks=0; ks<2; ks++)
dimension(ks,kd) = indexRange(ks,kd) =
extendedIndexRange(ks,kd) = extendedRange(ks,kd) = gridIndexRange(ks,kd) =
numberOfGhostPoints(ks,kd) = 0;
gridSpacing(kd) = (Real)1.;
} // end for
//
// Compute the indirect addressing vectors. **** USED BY canInterpolate and the grid generator.
//
Integer i;
#define MAPPED_GRID_UPDATE_INDIRECT_ADDRESSING_VECTOR(I,Iarray,kd,pad) \
Iarray.redim(Range(indexRange(0,kd)-pad,indexRange(1,kd)+pad)); \
I = Iarray.getDataPointer() - Iarray.getBase(0); \
if (isPeriodic(kd)) { \
const Integer thePeriod = indexRange(1,kd) - indexRange(0,kd) + 1; \
for (i=indexRange(0,kd); i<=indexRange(1,kd); i++) \
I[i] = i; \
for (i=indexRange(1,kd)+1; i<=indexRange(1,kd)+pad; i++) \
I[i] = I[i-thePeriod]; \
for (i=indexRange(0,kd)-1; i>=indexRange(0,kd)-pad; i--) \
I[i] = I[i+thePeriod]; \
} else { \
for (Integer i=indexRange(0,kd)-pad; i<=indexRange(1,kd)+pad; i++) \
I[i] = i; \
}
MAPPED_GRID_UPDATE_INDIRECT_ADDRESSING_VECTOR(I1, I1array, 0, 16);
MAPPED_GRID_UPDATE_INDIRECT_ADDRESSING_VECTOR(I2, I2array, 1, 16);
MAPPED_GRID_UPDATE_INDIRECT_ADDRESSING_VECTOR(I3, I3array, 2, 16);
#undef MAPPED_GRID_UPDATE_INDIRECT_ADDRESSING_VECTOR
if (what & ( THEmask |
THEinverseVertexDerivative | THEinverseCenterDerivative |
THEvertex | THEcenter |
THEcorner | THEvertexDerivative |
THEcenterDerivative | THEvertexJacobian |
THEcenterJacobian | THEcellVolume |
THEcenterNormal | THEcenterArea |
THEfaceNormal | THEfaceArea |
THEvertexBoundaryNormal | THEcenterBoundaryNormal |
THEcenterBoundaryTangent )) {
//
// Compute the partitioning of distributed arrays.
//
initializePartition();
} // end if
if( gridType==MappedGrid::structuredGrid )
{
// note: The update function was split into two parts to give the compiler an easier time.
upd |= update1(y, what, how, computeNeeded) | update2(y, what, how, computeNeeded);
}
else
{
upd |= updateUnstructuredGrid(y, what, how, computeNeeded);
}
for (kd=0; kd<3; kd++)
{
// *wdh* box.convert(kd, isCellCentered(kd) ? IndexType::CELL : IndexType::NODE);
// *wdh* 010906: always make the box node centered since it corresponds to the grid vertices.
box.convert(kd, IndexType::NODE);
box.setSmall(kd,indexRange(0,kd)); box.setBig(kd,indexRange(1,kd));
} // end for
return upd | computeGeometry(computeNeeded, how);
}
#define MG_NEW ::new
Integer MappedGridData::
update1(MappedGridData& y,
const Integer& what,
const Integer& how,
Integer& computeNeeded)
// ==============================================================================================
//
// note: The update function was split into two parts to give the compiler an easier time.
// ==============================================================================================
{
Integer upd = 0;
const Range all, d0 = numberOfDimensions;
if (what & THEmask)
{
if (&y != this &&
y.mask &&
y.mask->elementCount())
{
if (mask == NULL)
{
// printf("new the mask (2)\n");
mask = MG_NEW IntegerMappedGridFunction;
}
mask->reference(*y.mask);
if (y.computedGeometry & THEmask)
{
computedGeometry |= THEmask;
}
else if (how & COMPUTEgeometryAsNeeded)
{
computedGeometry &= ~THEmask;
computeNeeded |= THEmask;
} // end if
}
else if (mask == NULL)
{
// printf("new the mask (1)\n");
mask = MG_NEW IntegerMappedGridFunction;
} // end if
if (mask ->updateToMatchGrid(*this) &
IntegerMappedGridFunction::updateResized)
{
*mask = ISghostPoint;
(*mask)(Range(extendedRange(0,0),extendedRange(1,0)),
Range(extendedRange(0,1),extendedRange(1,1)),
Range(extendedRange(0,2),extendedRange(1,2)))
= ISdiscretizationPoint;
mask->periodicUpdate();
if (how & COMPUTEgeometryAsNeeded)
computeNeeded |= THEmask;
computedGeometry &= ~THEmask;
upd |= THEmask;
} // end if
} // end if
if (what & THEinverseVertexDerivative)
{
if (&y != this &&
y.inverseVertexDerivative &&
y.inverseVertexDerivative->elementCount())
{
if (inverseVertexDerivative == NULL)
inverseVertexDerivative = MG_NEW RealMappedGridFunction;
inverseVertexDerivative->reference(*y.inverseVertexDerivative);
if (y.computedGeometry & THEinverseVertexDerivative)
{
computedGeometry |= THEinverseVertexDerivative;
}
else if (how & COMPUTEgeometryAsNeeded)
{
computedGeometry &= ~THEinverseVertexDerivative;
computeNeeded |= THEinverseVertexDerivative;
} // end if
}
else if(isAllVertexCentered && &y != this &&
y.inverseCenterDerivative &&
y.inverseCenterDerivative->elementCount())
{
if (inverseVertexDerivative == NULL)
inverseVertexDerivative = MG_NEW RealMappedGridFunction;
inverseVertexDerivative->reference(*y.inverseCenterDerivative);
if (y.computedGeometry & THEinverseCenterDerivative)
{
computedGeometry |= THEinverseVertexDerivative;
}
else if (how & COMPUTEgeometryAsNeeded)
{
computedGeometry &= ~THEinverseVertexDerivative;
computeNeeded |= THEinverseVertexDerivative;
} // end if
}
else if (isAllVertexCentered &&
inverseCenterDerivative &&
inverseCenterDerivative->elementCount())
{
if (inverseVertexDerivative == NULL)
inverseVertexDerivative = MG_NEW RealMappedGridFunction;
inverseVertexDerivative->reference(*inverseCenterDerivative);
if (computedGeometry & THEinverseCenterDerivative)
{
computedGeometry |= THEinverseVertexDerivative;
}
else if (how & COMPUTEgeometryAsNeeded)
{
computedGeometry &= ~THEinverseVertexDerivative;
computeNeeded |= THEinverseVertexDerivative;
} // end if
}
else if (inverseVertexDerivative == NULL)
{
inverseVertexDerivative = MG_NEW RealMappedGridFunction;
} // end if
if (inverseVertexDerivative ->updateToMatchGrid
(*this, all, all, all, d0, d0) &
RealMappedGridFunction::updateResized)
{
// if (numberOfDimensions <= 2)
// {
// if (inverseVertexDerivative2D == NULL)
// inverseVertexDerivative2D = MG_NEW RealMappedGridFunction;
// inverseVertexDerivative2D->reference
// (*inverseVertexDerivative);
// inverseVertexDerivative2D->updateToMatchGrid
// (*this, all, all, d0, d0);
// inverseVertexDerivative2D->setIsCellCentered(LogicalFalse);
// } // end if
// if (numberOfDimensions <= 1)
// {
// if (inverseVertexDerivative1D == NULL)
// inverseVertexDerivative1D = MG_NEW RealMappedGridFunction;
// inverseVertexDerivative1D->reference
// (*inverseVertexDerivative);
// inverseVertexDerivative1D->updateToMatchGrid
// (*this, all, d0, d0);
// inverseVertexDerivative1D->setIsCellCentered(LogicalFalse);
// } // end if
*inverseVertexDerivative = (Real)0.;
if (how & COMPUTEgeometryAsNeeded)
computeNeeded |= THEinverseVertexDerivative;
computedGeometry &= ~THEinverseVertexDerivative;
upd |= THEinverseVertexDerivative;
} // end if
inverseVertexDerivative ->setIsCellCentered(LogicalFalse);
} // end if
if (what & THEinverseCenterDerivative)
{
if (&y != this &&
y.inverseCenterDerivative &&
y.inverseCenterDerivative->elementCount())
{
if (inverseCenterDerivative == NULL)
inverseCenterDerivative = MG_NEW RealMappedGridFunction;
inverseCenterDerivative->reference(*y.inverseCenterDerivative);
if (y.computedGeometry & THEinverseCenterDerivative)
{
computedGeometry |= THEinverseCenterDerivative;
}
else if (how & COMPUTEgeometryAsNeeded)
{
computedGeometry &= ~THEinverseCenterDerivative;
computeNeeded |= THEinverseCenterDerivative;
} // end if
}
else if(isAllVertexCentered && &y != this &&
y.inverseVertexDerivative &&
y.inverseVertexDerivative->elementCount())
{
if (inverseCenterDerivative == NULL)
inverseCenterDerivative = MG_NEW RealMappedGridFunction;
inverseCenterDerivative->reference(*y.inverseVertexDerivative);
if (y.computedGeometry & THEinverseVertexDerivative)
{
computedGeometry |= THEinverseCenterDerivative;
}
else if (how & COMPUTEgeometryAsNeeded)
{
computedGeometry &= ~THEinverseCenterDerivative;
computeNeeded |= THEinverseCenterDerivative;
} // end if
}
else if (isAllVertexCentered &&
inverseVertexDerivative &&
inverseVertexDerivative->elementCount())
{
if (inverseCenterDerivative == NULL)
inverseCenterDerivative = MG_NEW RealMappedGridFunction;
inverseCenterDerivative->reference(*inverseVertexDerivative);
if (computedGeometry & THEinverseVertexDerivative)
{
computedGeometry |= THEinverseCenterDerivative;
}
else if (how & COMPUTEgeometryAsNeeded)
{
computedGeometry &= ~THEinverseCenterDerivative;
computeNeeded |= THEinverseCenterDerivative;
} // end if
}
else if (inverseCenterDerivative == NULL)
{
inverseCenterDerivative = MG_NEW RealMappedGridFunction;
} // end if
if (inverseCenterDerivative ->updateToMatchGrid
(*this, all, all, all, d0, d0) &
RealMappedGridFunction::updateResized)
{
// if (numberOfDimensions <= 2)
// {
// if (inverseCenterDerivative2D == NULL)
// inverseCenterDerivative2D = MG_NEW RealMappedGridFunction;
// inverseCenterDerivative2D->reference
// (*inverseCenterDerivative);
// inverseCenterDerivative2D->updateToMatchGrid
// (*this, all, all, d0, d0);
// } // end if
// if (numberOfDimensions <= 1)
// {
// if (inverseCenterDerivative1D == NULL)
// inverseCenterDerivative1D = MG_NEW RealMappedGridFunction;
// inverseCenterDerivative1D->reference
// (*inverseCenterDerivative);
// inverseCenterDerivative1D->updateToMatchGrid
// (*this, all, d0, d0);
// } // end if
*inverseCenterDerivative = (Real)0.;
if (how & COMPUTEgeometryAsNeeded)
computeNeeded |= THEinverseCenterDerivative;
computedGeometry &= ~THEinverseCenterDerivative;
upd |= THEinverseCenterDerivative;
} // end if
} // end if
if (what & THEvertex)
{
if (&y != this &&
y.vertex &&
y.vertex->elementCount())
{
if (vertex == NULL) vertex = MG_NEW RealMappedGridFunction;
vertex->reference(*y.vertex);
if (y.computedGeometry & THEvertex)
{
computedGeometry |= THEvertex;
}
else if (how & COMPUTEgeometryAsNeeded)
{
computedGeometry &= ~THEvertex;
computeNeeded |= THEvertex;
} // end if
}
else if (isAllVertexCentered && &y != this &&
y.center &&
y.center->elementCount())
{
if (vertex == NULL) vertex = MG_NEW RealMappedGridFunction;
vertex->reference(*y.center);
if (y.computedGeometry & THEcenter)
{
computedGeometry |= THEvertex;
}
else if (how & COMPUTEgeometryAsNeeded)
{
computedGeometry &= ~THEvertex;
computeNeeded |= THEvertex;
} // end if
}
else if (isAllCellCentered && &y != this &&
y.corner &&
y.corner->elementCount())
{
if (vertex == NULL) vertex = MG_NEW RealMappedGridFunction;
vertex->reference(*y.corner);
if (y.computedGeometry & THEcorner)
{
computedGeometry |= THEvertex;
}
else if (how & COMPUTEgeometryAsNeeded)
{
computedGeometry &= ~THEvertex;
computeNeeded |= THEvertex;
} // end if
}
else if (isAllVertexCentered &&
center && center->elementCount())
{
if (vertex == NULL) vertex = MG_NEW RealMappedGridFunction;
vertex->reference(*center);
if (computedGeometry & THEcenter)
{
computedGeometry |= THEvertex;
}
else if (how & COMPUTEgeometryAsNeeded)
{
computedGeometry &= ~THEvertex;
computeNeeded |= THEvertex;
} // end if
}
else if (isAllCellCentered &&
corner && corner->elementCount())
{
if (vertex == NULL) vertex = MG_NEW RealMappedGridFunction;
vertex->reference(*corner);
if (computedGeometry & THEcorner)
{
computedGeometry |= THEvertex;
}
else if (how & COMPUTEgeometryAsNeeded)
{
computedGeometry &= ~THEvertex;
computeNeeded |= THEvertex;
} // end if
}
else if (vertex == NULL)
{
vertex = MG_NEW RealMappedGridFunction;
} // end if
if( vertex->updateToMatchGrid(*this, all, all, all, d0) & RealMappedGridFunction::updateResized )
{
// if (numberOfDimensions <= 2)
// {
// if (vertex2D == NULL) vertex2D = MG_NEW RealMappedGridFunction;
// vertex2D ->reference(*vertex);
// vertex2D ->updateToMatchGrid
// (*this, all, all, d0);
// vertex2D ->setIsCellCentered(LogicalFalse);
// } // end if
// if (numberOfDimensions <= 1)
// {
// if (vertex1D == NULL) vertex1D = MG_NEW RealMappedGridFunction;
// vertex1D ->reference(*vertex);
// vertex1D ->updateToMatchGrid(*this, all, d0);
// vertex1D ->setIsCellCentered(LogicalFalse);
// } // end if
*vertex = (Real)0.;
if (how & COMPUTEgeometryAsNeeded)
computeNeeded |= THEvertex;
computedGeometry &= ~THEvertex;
upd |= THEvertex;
} // end if
vertex ->setIsCellCentered(LogicalFalse);
} // end if
if (what & THEcenter)
{
if (&y != this &&
y.center && y.center->elementCount())
{
if (center == NULL) center = MG_NEW RealMappedGridFunction;
center->reference(*y.center);
if (y.computedGeometry & THEcenter)
{
computedGeometry |= THEcenter;
}
else if (how & COMPUTEgeometryAsNeeded)
{
computedGeometry &= ~THEcenter;
computeNeeded |= THEcenter;
} // end if
}
else if (isAllVertexCentered && &y != this &&
y.vertex && y.vertex->elementCount())
{
if (center == NULL) center = MG_NEW RealMappedGridFunction;
center->reference(*y.vertex);
if (y.computedGeometry & THEvertex)
{
computedGeometry |= THEcenter;
}
else if (how & COMPUTEgeometryAsNeeded)
{
computedGeometry &= ~THEcenter;
computeNeeded |= THEcenter;
} // end if
}
else if (isAllVertexCentered &&
vertex && vertex->elementCount())
{
if (center == NULL) center = MG_NEW RealMappedGridFunction;
center->reference(*vertex);
if (computedGeometry & THEvertex)
{
computedGeometry |= THEcenter;
}
else if (how & COMPUTEgeometryAsNeeded)
{
computedGeometry &= ~THEcenter;
computeNeeded |= THEcenter;
} // end if
}
else if (center == NULL)
{
center = MG_NEW RealMappedGridFunction;
} // end if
if (center ->updateToMatchGrid
(*this, all, all, all, d0) &
RealMappedGridFunction::updateResized)
{
// if (numberOfDimensions <= 2)
// {
// if (center2D == NULL) center2D = MG_NEW RealMappedGridFunction;
// center2D ->reference(*center);
// center2D ->updateToMatchGrid
// (*this, all, all, d0);
// } // end if
// if (numberOfDimensions <= 1)
// {
// if (center1D == NULL) center1D = MG_NEW RealMappedGridFunction;
// center1D ->reference(*center);
// center1D ->updateToMatchGrid(*this, all, d0);
// } // end if
*center = (Real)0.;
if (how & COMPUTEgeometryAsNeeded)
computeNeeded |= THEcenter;
computedGeometry &= ~THEcenter;
upd |= THEcenter;
} // end if
} // end if
if (what & THEcorner)
{
if (&y != this &&
y.corner && y.corner->elementCount())
{
if (corner == NULL) corner = MG_NEW RealMappedGridFunction;
corner->reference(*y.corner);
if (y.computedGeometry & THEcorner)
{
computedGeometry |= THEcorner;
}
else if (how & COMPUTEgeometryAsNeeded)
{
computedGeometry &= ~THEcorner;
computeNeeded |= THEcorner;
} // end if
}
else if (isAllCellCentered && &y != this &&
y.vertex && y.vertex->elementCount())
{
if (corner == NULL) corner = MG_NEW RealMappedGridFunction;
corner->reference(*y.vertex);
if (y.computedGeometry & THEvertex)
{
computedGeometry |= THEcorner;
}
else if (how & COMPUTEgeometryAsNeeded)
{
computedGeometry &= ~THEcorner;
computeNeeded |= THEcorner;
} // end if
}
else if (isAllCellCentered &&
vertex && vertex->elementCount())
{
if (corner == NULL) corner = MG_NEW RealMappedGridFunction;
corner->reference(*vertex);
if (computedGeometry & THEvertex)
{
computedGeometry |= THEcorner;
}
else if (how & COMPUTEgeometryAsNeeded)
{
computedGeometry &= ~THEcorner;
computeNeeded |= THEcorner;
} // end if
}
else if (corner == NULL)
{
corner = MG_NEW RealMappedGridFunction;
} // end if
if (corner ->updateToMatchGrid
(*this, all, all, all, d0) &
RealMappedGridFunction::updateResized)
{
// if (numberOfDimensions <= 2)
// {
// if (corner2D == NULL) corner2D = MG_NEW RealMappedGridFunction;
// corner2D ->reference(*corner);
// corner2D ->updateToMatchGrid
// (*this, all, all, d0);
// for (Integer kd=0; kd<numberOfDimensions; kd++)
// corner2D ->setIsCellCentered
// (!isCellCentered(kd), kd);
// } // end if
// if (numberOfDimensions <= 1)
// {
// if (corner1D == NULL) corner1D = MG_NEW RealMappedGridFunction;
// corner1D ->reference(*corner);
// corner1D ->updateToMatchGrid(*this, all, d0);
// for (Integer kd=0; kd<numberOfDimensions; kd++)
// corner1D ->setIsCellCentered
// (!isCellCentered(kd), kd);
// } // end if
*corner = (Real)0.;
if (how & COMPUTEgeometryAsNeeded)
computeNeeded |= THEcorner;
computedGeometry &= ~THEcorner;
upd |= THEcorner;
} // end if
for (Integer kd=0; kd<numberOfDimensions; kd++)
corner ->setIsCellCentered
(!isCellCentered(kd), kd);
} // end if
if (what & THEvertexDerivative)
{
if (&y != this &&
y.vertexDerivative && y.vertexDerivative->elementCount())
{
if (vertexDerivative == NULL)
vertexDerivative = MG_NEW RealMappedGridFunction;
vertexDerivative->reference(*y.vertexDerivative);
if (y.computedGeometry & THEvertexDerivative)
{
computedGeometry |= THEvertexDerivative;
}
else if (how & COMPUTEgeometryAsNeeded)
{
computedGeometry &= ~THEvertexDerivative;
computeNeeded |= THEvertexDerivative;
} // end if
}
else if (isAllVertexCentered && &y != this &&
y.centerDerivative && y.centerDerivative->elementCount())
{
if (vertexDerivative == NULL)
vertexDerivative = MG_NEW RealMappedGridFunction;
vertexDerivative->reference(*y.centerDerivative);
if (y.computedGeometry & THEcenterDerivative)
{
computedGeometry |= THEvertexDerivative;
}
else if (how & COMPUTEgeometryAsNeeded)
{
computedGeometry &= ~THEvertexDerivative;
computeNeeded |= THEvertexDerivative;
} // end if
}
else if (isAllVertexCentered &&
centerDerivative && centerDerivative->elementCount())
{
if (vertexDerivative == NULL)
vertexDerivative = MG_NEW RealMappedGridFunction;
vertexDerivative->reference(*centerDerivative);
if (computedGeometry & THEcenterDerivative)
{
computedGeometry |= THEvertexDerivative;
}
else if (how & COMPUTEgeometryAsNeeded)
{
computedGeometry &= ~THEvertexDerivative;
computeNeeded |= THEvertexDerivative;
} // end if
}
else if (vertexDerivative == NULL)
{
vertexDerivative = MG_NEW RealMappedGridFunction;
} // end if
if (vertexDerivative ->updateToMatchGrid
(*this, all, all, all, d0, d0) &
RealMappedGridFunction::updateResized)
{
// if (numberOfDimensions <= 2)
// {
// if (vertexDerivative2D == NULL)
// vertexDerivative2D = MG_NEW RealMappedGridFunction;
// vertexDerivative2D ->reference(*vertexDerivative);
// vertexDerivative2D ->updateToMatchGrid
// (*this, all, all, d0, d0);
// vertexDerivative2D ->setIsCellCentered(LogicalFalse);
// } // end if
// if (numberOfDimensions <= 1)
// {
// if (vertexDerivative1D == NULL)
// vertexDerivative1D = MG_NEW RealMappedGridFunction;
// vertexDerivative1D ->reference(*vertexDerivative);
// vertexDerivative1D ->updateToMatchGrid
// (*this, all, d0, d0);
// vertexDerivative1D ->setIsCellCentered(LogicalFalse);
// } // end if
*vertexDerivative = (Real)0.;
if (how & COMPUTEgeometryAsNeeded)
computeNeeded |= THEvertexDerivative;
computedGeometry &= ~THEvertexDerivative;
upd |= THEvertexDerivative;
} // end if
vertexDerivative ->setIsCellCentered(LogicalFalse);
} // end if
if (what & THEcenterDerivative)
{
if (&y != this &&
y.centerDerivative && y.centerDerivative->elementCount())
{
if (centerDerivative == NULL)
centerDerivative = MG_NEW RealMappedGridFunction;
centerDerivative->reference(*y.centerDerivative);
if (y.computedGeometry & THEcenterDerivative)
{
computedGeometry |= THEcenterDerivative;
}
else if (how & COMPUTEgeometryAsNeeded)
{
computedGeometry &= ~THEcenterDerivative;
computeNeeded |= THEcenterDerivative;
} // end if
}
else if (isAllVertexCentered && &y != this &&
y.vertexDerivative && y.vertexDerivative->elementCount())
{
if (centerDerivative == NULL)
centerDerivative = MG_NEW RealMappedGridFunction;
centerDerivative->reference(*y.vertexDerivative);
if (y.computedGeometry & THEvertexDerivative)
{
computedGeometry |= THEcenterDerivative;
}
else if (how & COMPUTEgeometryAsNeeded)
{
computedGeometry &= ~THEcenterDerivative;
computeNeeded |= THEcenterDerivative;
} // end if
}
else if (isAllVertexCentered &&
vertexDerivative && vertexDerivative->elementCount())
{
if (centerDerivative == NULL)
centerDerivative = MG_NEW RealMappedGridFunction;
centerDerivative->reference(*vertexDerivative);
if (computedGeometry & THEvertexDerivative)
{
computedGeometry |= THEcenterDerivative;
}
else if (how & COMPUTEgeometryAsNeeded)
{
computedGeometry &= ~THEcenterDerivative;
computeNeeded |= THEcenterDerivative;
} // end if
}
else if (centerDerivative == NULL)
{
centerDerivative = MG_NEW RealMappedGridFunction;
} // end if
if (centerDerivative ->updateToMatchGrid
(*this, all, all, all, d0, d0) &
RealMappedGridFunction::updateResized)
{
// if (numberOfDimensions <= 2)
// {
// if (centerDerivative2D == NULL)
// centerDerivative2D = MG_NEW RealMappedGridFunction;
// centerDerivative2D ->reference(*centerDerivative);
// centerDerivative2D ->updateToMatchGrid
// (*this, all, all, d0, d0);
// } // end if
// if (numberOfDimensions <= 1)
// {
// if (centerDerivative1D == NULL)
// centerDerivative1D = MG_NEW RealMappedGridFunction;
// centerDerivative1D ->reference(*centerDerivative);
// centerDerivative1D ->updateToMatchGrid
// (*this, all, d0, d0);
// } // end if
*centerDerivative = (Real)0.;
if (how & COMPUTEgeometryAsNeeded)
computeNeeded |= THEcenterDerivative;
computedGeometry &= ~THEcenterDerivative;
upd |= THEcenterDerivative;
} // end if
} // end if
return upd;
}
Integer MappedGridData::
update2( MappedGridData& y,
const Integer& what,
const Integer& how,
Integer& computeNeeded)
{
Integer upd = 0;
const Range all, d0 = numberOfDimensions;
if (what & THEvertexJacobian)
{
if (&y != this &&
y.vertexJacobian && y.vertexJacobian->elementCount())
{
if (vertexJacobian == NULL)
vertexJacobian = MG_NEW RealMappedGridFunction;
vertexJacobian->reference(*y.vertexJacobian);
if (y.computedGeometry & THEvertexJacobian)
{
computedGeometry |= THEvertexJacobian;
}
else if (how & COMPUTEgeometryAsNeeded)
{
computedGeometry &= ~THEvertexJacobian;
computeNeeded |= THEvertexJacobian;
} // end if
}
else if (isAllVertexCentered && &y != this &&
y.centerJacobian && y.centerJacobian->elementCount())
{
if (vertexJacobian == NULL)
vertexJacobian = MG_NEW RealMappedGridFunction;
vertexJacobian->reference(*y.centerJacobian);
if (y.computedGeometry & THEcenterJacobian)
{
computedGeometry |= THEvertexJacobian;
}
else if (how & COMPUTEgeometryAsNeeded)
{
computedGeometry &= ~THEvertexJacobian;
computeNeeded |= THEvertexJacobian;
} // end if
}
else if (isAllVertexCentered &&
centerJacobian && centerJacobian->elementCount())
{
if (vertexJacobian == NULL)
vertexJacobian = MG_NEW RealMappedGridFunction;
vertexJacobian->reference(*centerJacobian);
if (computedGeometry & THEcenterJacobian)
{
computedGeometry |= THEvertexJacobian;
}
else if (how & COMPUTEgeometryAsNeeded)
{
computedGeometry &= ~THEvertexJacobian;
computeNeeded |= THEvertexJacobian;
} // end if
}
else if (vertexJacobian == NULL)
{
vertexJacobian = MG_NEW RealMappedGridFunction;
} // end if
if (vertexJacobian ->updateToMatchGrid(*this) &
RealMappedGridFunction::updateResized)
{
*vertexJacobian = (Real)1.;
if (how & COMPUTEgeometryAsNeeded)
computeNeeded |= THEvertexJacobian;
computedGeometry &= ~THEvertexJacobian;
upd |= THEvertexJacobian;
} // end if
vertexJacobian ->setIsCellCentered(LogicalFalse);
} // end if
if (what & THEcenterJacobian)
{
if (&y != this &&
y.centerJacobian && y.centerJacobian->elementCount())
{
if (centerJacobian == NULL)
centerJacobian = MG_NEW RealMappedGridFunction;
centerJacobian->reference(*y.centerJacobian);
if (y.computedGeometry & THEcenterJacobian)
{
computedGeometry |= THEcenterJacobian;
}
else if (how & COMPUTEgeometryAsNeeded)
{
computedGeometry &= ~THEcenterJacobian;
computeNeeded |= THEcenterJacobian;
} // end if
}
else if (isAllVertexCentered &&
y.vertexJacobian && y.vertexJacobian->elementCount())
{
if (centerJacobian == NULL)
centerJacobian = MG_NEW RealMappedGridFunction;
centerJacobian->reference(*y.vertexJacobian);
if (y.computedGeometry & THEvertexJacobian)
{
computedGeometry |= THEcenterJacobian;
}
else if (how & COMPUTEgeometryAsNeeded)
{
computedGeometry &= ~THEcenterJacobian;
computeNeeded |= THEcenterJacobian;
} // end if
}
else if (isAllVertexCentered &&
vertexJacobian && vertexJacobian->elementCount())
{
if (centerJacobian == NULL)
centerJacobian = MG_NEW RealMappedGridFunction;
centerJacobian->reference(*vertexJacobian);
if (computedGeometry & THEvertexJacobian)
{
computedGeometry |= THEcenterJacobian;
}
else if (how & COMPUTEgeometryAsNeeded)
{
computedGeometry &= ~THEcenterJacobian;
computeNeeded |= THEcenterJacobian;
} // end if
}
else if (centerJacobian == NULL)
{
centerJacobian = MG_NEW RealMappedGridFunction;
} // end if
if (centerJacobian ->updateToMatchGrid(*this) &
RealMappedGridFunction::updateResized)
{
// *centerJacobian = (Real)1.;
assign(*centerJacobian,1., nullIndex,nullIndex,nullIndex,nullIndex);
if (how & COMPUTEgeometryAsNeeded)
computeNeeded |= THEcenterJacobian;
computedGeometry &= ~THEcenterJacobian;
upd |= THEcenterJacobian;
} // end if
} // end if
if (what & THEcellVolume)
{
if (&y != this &&
y.cellVolume && y.cellVolume->elementCount())
{
if (cellVolume == NULL) cellVolume = MG_NEW RealMappedGridFunction;
cellVolume->reference(*y.cellVolume);
if (y.computedGeometry & THEcellVolume)
{
computedGeometry |= THEcellVolume;
}
else if (how & COMPUTEgeometryAsNeeded)
{
computedGeometry &= ~THEcellVolume;
computeNeeded |= THEcellVolume;
} // end if
}
else if (cellVolume == NULL)
{
cellVolume = MG_NEW RealMappedGridFunction;
} // end if
if (cellVolume ->updateToMatchGrid(*this) &
RealMappedGridFunction::updateResized)
{
*cellVolume = (Real)1.;
if (how & COMPUTEgeometryAsNeeded)
computeNeeded |= THEcellVolume;
computedGeometry &= ~THEcellVolume;
upd |= THEcellVolume;
} // end if
} // end if
if (what & THEcenterNormal)
{
if (&y != this &&
y.centerNormal && y.centerNormal->elementCount())
{
if (centerNormal == NULL) centerNormal = MG_NEW RealMappedGridFunction;
centerNormal->reference(*y.centerNormal);
if (y.computedGeometry & THEcenterNormal)
{
computedGeometry |= THEcenterNormal;
}
else if (how & COMPUTEgeometryAsNeeded)
{
computedGeometry &= ~THEcenterNormal;
computeNeeded |= THEcenterNormal;
} // end if
}
else if (centerNormal == NULL)
{
centerNormal = MG_NEW RealMappedGridFunction;
} // end if
if (centerNormal ->updateToMatchGrid
(*this, all, all, all, d0, d0) &
RealMappedGridFunction::updateResized)
{
// if (numberOfDimensions <= 2)
// {
// if (centerNormal2D == NULL)
// centerNormal2D = MG_NEW RealMappedGridFunction;
// centerNormal2D ->reference(*centerNormal);
// centerNormal2D ->updateToMatchGrid
// (*this, all, all, d0, d0);
// } // end if
// if (numberOfDimensions <= 1)
// {
// if (centerNormal1D == NULL)
// centerNormal1D = MG_NEW RealMappedGridFunction;
// centerNormal1D ->reference(*centerNormal);
// centerNormal1D ->updateToMatchGrid
// (*this, all, d0, d0);
// } // end if
*centerNormal = (Real)0.;
if (how & COMPUTEgeometryAsNeeded)
computeNeeded |= THEcenterNormal;
computedGeometry &= ~THEcenterNormal;
upd |= THEcenterNormal;
} // end if
} // end if
if (what & THEcenterArea)
{
if (&y != this &&
y.centerArea && y.centerArea->elementCount())
{
if (centerArea == NULL) centerArea = MG_NEW RealMappedGridFunction;
centerArea->reference(*y.centerArea);
if (y.computedGeometry & THEcenterArea)
{
computedGeometry |= THEcenterArea;
}
else if (how & COMPUTEgeometryAsNeeded)
{
computedGeometry &= ~THEcenterArea;
computeNeeded |= THEcenterArea;
} // end if
}
else if (centerArea == NULL)
{
centerArea = MG_NEW RealMappedGridFunction;
} // end if
if (centerArea ->updateToMatchGrid
(*this, all, all, all, d0) &
RealMappedGridFunction::updateResized)
{
// if (numberOfDimensions <= 2)
// {
// if (centerArea2D == NULL)
// centerArea2D = MG_NEW RealMappedGridFunction;
// centerArea2D ->reference(*centerArea);
// centerArea2D ->updateToMatchGrid
// (*this, all, all, d0);
// } // end if
// if (numberOfDimensions <= 1)
// {
// if (centerArea1D == NULL)
// centerArea1D = MG_NEW RealMappedGridFunction;
// centerArea1D ->reference(*centerArea);
// centerArea1D ->updateToMatchGrid(*this, all, d0);
// } // end if
*centerArea = (Real)1.;
if (how & COMPUTEgeometryAsNeeded)
computeNeeded |= THEcenterArea;
computedGeometry &= ~THEcenterArea;
upd |= THEcenterArea;
} // end if
} // end if
if (what & THEfaceNormal)
{
if (&y != this &&
y.faceNormal && y.faceNormal->elementCount())
{
if (faceNormal == NULL) faceNormal = MG_NEW RealMappedGridFunction;
faceNormal->reference(*y.faceNormal);
if (y.computedGeometry & THEfaceNormal)
{
computedGeometry |= THEfaceNormal;
}
else if (how & COMPUTEgeometryAsNeeded)
{
computedGeometry &= ~THEfaceNormal;
computeNeeded |= THEfaceNormal;
} // end if
}
else if (faceNormal == NULL)
{
faceNormal = MG_NEW RealMappedGridFunction;
} // end if
if (faceNormal ->updateToMatchGrid
(*this, all, all, all, d0, d0) &
RealMappedGridFunction::updateResized)
{
// if (numberOfDimensions <= 2)
// {
// if (faceNormal2D == NULL)
// faceNormal2D = MG_NEW RealMappedGridFunction;
// faceNormal2D ->reference(*faceNormal);
// faceNormal2D ->updateToMatchGrid
// (*this, all, all, d0, d0);
// for (Integer kd2=0; kd2<numberOfDimensions; kd2++)
// for (Integer kd1=0; kd1<numberOfDimensions; kd1++)
// faceNormal2D ->setIsCellCentered
// (!isCellCentered(kd2), kd1, kd2);
// } // end if
// if (numberOfDimensions <= 1)
// {
// if (faceNormal1D == NULL)
// faceNormal1D = MG_NEW RealMappedGridFunction;
// faceNormal1D ->reference(*faceNormal);
// faceNormal1D ->updateToMatchGrid
// (*this, all, d0, d0);
// for (Integer kd2=0; kd2<numberOfDimensions; kd2++)
// for (Integer kd1=0; kd1<numberOfDimensions; kd1++)
// faceNormal1D ->setIsCellCentered
// (!isCellCentered(kd2), kd1, kd2);
// } // end if
*faceNormal = (Real)0.;
if (how & COMPUTEgeometryAsNeeded)
computeNeeded |= THEfaceNormal;
computedGeometry &= ~THEfaceNormal;
upd |= THEfaceNormal;
} // end if
for (Integer kd2=0; kd2<numberOfDimensions; kd2++)
for (Integer kd1=0; kd1<numberOfDimensions; kd1++)
faceNormal ->setIsCellCentered
(!isCellCentered(kd2), kd1, kd2);
} // end if
if (what & THEfaceArea)
{
if (&y != this &&
y.faceArea && y.faceArea->elementCount())
{
if (faceArea == NULL) faceArea = MG_NEW RealMappedGridFunction;
faceArea->reference(*y.faceArea);
if (y.computedGeometry & THEfaceArea)
{
computedGeometry |= THEfaceArea;
}
else if (how & COMPUTEgeometryAsNeeded)
{
computedGeometry &= ~THEfaceArea;
computeNeeded |= THEfaceArea;
} // end if
}
else if (faceArea == NULL)
{
faceArea = MG_NEW RealMappedGridFunction;
} // end if
if (faceArea ->updateToMatchGrid
(*this, all, all, all, d0) &
RealMappedGridFunction::updateResized)
{
// if (numberOfDimensions <= 2)
// {
// if (faceArea2D == NULL)
// faceArea2D = MG_NEW RealMappedGridFunction;
// faceArea2D ->reference(*faceArea);
// faceArea2D ->updateToMatchGrid
// (*this, all, all, d0);
// for (Integer kd=0; kd<numberOfDimensions; kd++)
// faceArea2D ->setIsCellCentered
// (!isCellCentered(kd), kd);
// } // end if
// if (numberOfDimensions <= 1)
// {
// if (faceArea1D == NULL)
// faceArea1D = MG_NEW RealMappedGridFunction;
// faceArea1D ->reference(*faceArea);
// faceArea1D ->updateToMatchGrid(*this, all, d0);
// for (Integer kd=0; kd<numberOfDimensions; kd++)
// faceArea1D ->setIsCellCentered
// (!isCellCentered(kd), kd);
// } // end if
*faceArea = (Real)1.;
if (how & COMPUTEgeometryAsNeeded)
computeNeeded |= THEfaceArea;
computedGeometry &= ~THEfaceArea;
upd |= THEfaceArea;
} // end if
for (Integer kd=0; kd<numberOfDimensions; kd++)
faceArea ->setIsCellCentered
(!isCellCentered(kd), kd);
} // end if
#ifndef USE_PPP
// **** serial version ****
if (what & THEvertexBoundaryNormal)
{
for (Integer kd=0; kd<3; kd++)
for (Integer ks=0; ks<2; ks++)
if (kd < numberOfDimensions)
{
if (&y != this &&
y.vertexBoundaryNormal[kd][ks] &&
y.vertexBoundaryNormal[kd][ks]->elementCount())
{
if (vertexBoundaryNormal[kd][ks] == NULL)
vertexBoundaryNormal[kd][ks] = MG_NEW RealMappedGridFunction;
vertexBoundaryNormal[kd][ks]->reference(*y.vertexBoundaryNormal[kd][ks]);
if (y.computedGeometry & THEvertexBoundaryNormal)
{
computedGeometry |= THEvertexBoundaryNormal;
}
else if (how & COMPUTEgeometryAsNeeded)
{
computedGeometry &= ~THEvertexBoundaryNormal;
computeNeeded |= THEvertexBoundaryNormal;
} // end if
}
else if (isAllVertexCentered && &y != this &&
(vertexBoundaryNormal[kd][ks] == NULL ||
vertexBoundaryNormal[kd][ks]->elementCount() == 0) &&
(y.centerBoundaryNormal[kd][ks] &&
y.centerBoundaryNormal[kd][ks]->elementCount() != 0))
{
if (vertexBoundaryNormal[kd][ks] == NULL)
vertexBoundaryNormal[kd][ks] = MG_NEW RealMappedGridFunction;
vertexBoundaryNormal[kd][ks]->reference(*y.centerBoundaryNormal[kd][ks]);
if (y.computedGeometry & THEcenterBoundaryNormal)
{
computedGeometry |= THEvertexBoundaryNormal;
}
else if (how & COMPUTEgeometryAsNeeded)
{
computedGeometry &= ~THEvertexBoundaryNormal;
computeNeeded |= THEvertexBoundaryNormal;
} // end if
}
else if (isAllVertexCentered &&
(vertexBoundaryNormal[kd][ks] == NULL ||
vertexBoundaryNormal[kd][ks]->elementCount() == 0) &&
(centerBoundaryNormal[kd][ks] &&
centerBoundaryNormal[kd][ks]->elementCount() != 0))
{
if (vertexBoundaryNormal[kd][ks] == NULL)
vertexBoundaryNormal[kd][ks] = MG_NEW RealMappedGridFunction;
vertexBoundaryNormal[kd][ks]->reference(*centerBoundaryNormal[kd][ks]);
if (computedGeometry & THEcenterBoundaryNormal)
{
computedGeometry |= THEvertexBoundaryNormal;
}
else if (how & COMPUTEgeometryAsNeeded)
{
computedGeometry &= ~THEvertexBoundaryNormal;
computeNeeded |= THEvertexBoundaryNormal;
} // end if
}
else if (vertexBoundaryNormal[kd][ks] == NULL)
{
vertexBoundaryNormal[kd][ks] = MG_NEW RealMappedGridFunction;
} // end if
Range side[2];
side[0] = Range(RealMappedGridFunction::startingGridIndex,
RealMappedGridFunction::startingGridIndex);
side[1] = Range(RealMappedGridFunction::endingGridIndex,
RealMappedGridFunction::endingGridIndex);
if (vertexBoundaryNormal[kd][ks]->updateToMatchGrid(*this,
kd == 0 ? side[ks] : all, kd == 1 ? side[ks] : all,
kd == 2 ? side[ks] : all, d0) &
RealMappedGridFunction::updateResized)
{
*vertexBoundaryNormal[kd][ks] = (Real)0.;
if (how & COMPUTEgeometryAsNeeded)
computeNeeded |= THEvertexBoundaryNormal;
computedGeometry &= ~THEvertexBoundaryNormal;
upd |= THEvertexBoundaryNormal;
} // end if
vertexBoundaryNormal[kd][ks]->setIsCellCentered(LogicalFalse);
}
else if (centerBoundaryNormal[kd][ks])
{
delete centerBoundaryNormal[kd][ks];
centerBoundaryNormal[kd][ks] = NULL;
} // end if
} // end vertexBoundaryNormal
if (what & THEcenterBoundaryNormal)
{
for (Integer kd=0; kd<3; kd++)
for (Integer ks=0; ks<2; ks++)
if (kd < numberOfDimensions)
{
if (&y != this &&
y.centerBoundaryNormal[kd][ks] &&
y.centerBoundaryNormal[kd][ks]->elementCount())
{
if (centerBoundaryNormal[kd][ks] == 0)
centerBoundaryNormal[kd][ks] = MG_NEW RealMappedGridFunction;
centerBoundaryNormal[kd][ks]->reference(*y.centerBoundaryNormal[kd][ks]);
if (y.computedGeometry & THEcenterBoundaryNormal)
{
computedGeometry |= THEcenterBoundaryNormal;
}
else if (how & COMPUTEgeometryAsNeeded)
{
computedGeometry &= ~THEcenterBoundaryNormal;
computeNeeded |= THEcenterBoundaryNormal;
} // end if
}
else if (isAllVertexCentered && &y != this &&
(centerBoundaryNormal[kd][ks] == NULL ||
centerBoundaryNormal[kd][ks]->elementCount() == 0) &&
(y.vertexBoundaryNormal[kd][ks] &&
y.vertexBoundaryNormal[kd][ks]->elementCount() != 0))
{
if (centerBoundaryNormal[kd][ks] == NULL)
centerBoundaryNormal[kd][ks] = MG_NEW RealMappedGridFunction;
centerBoundaryNormal[kd][ks]->reference(*y.vertexBoundaryNormal[kd][ks]);
if (y.computedGeometry & THEvertexBoundaryNormal)
{
computedGeometry |= THEcenterBoundaryNormal;
}
else if (how & COMPUTEgeometryAsNeeded)
{
computedGeometry &= ~THEcenterBoundaryNormal;
computeNeeded |= THEcenterBoundaryNormal;
} // end if
}
else if (isAllVertexCentered &&
(centerBoundaryNormal[kd][ks] == NULL ||
centerBoundaryNormal[kd][ks]->elementCount() == 0) &&
(vertexBoundaryNormal[kd][ks] &&
vertexBoundaryNormal[kd][ks]->elementCount() != 0))
{
if (centerBoundaryNormal[kd][ks] == NULL)
centerBoundaryNormal[kd][ks] = MG_NEW RealMappedGridFunction;
centerBoundaryNormal[kd][ks]->reference(*vertexBoundaryNormal[kd][ks]);
if (computedGeometry & THEvertexBoundaryNormal)
{
computedGeometry |= THEcenterBoundaryNormal;
}
else if (how & COMPUTEgeometryAsNeeded)
{
computedGeometry &= ~THEcenterBoundaryNormal;
computeNeeded |= THEcenterBoundaryNormal;
} // end if
}
else if (centerBoundaryNormal[kd][ks] == NULL)
{
centerBoundaryNormal[kd][ks] = MG_NEW RealMappedGridFunction;
} // end if
Range side[2];
side[0] = Range(RealMappedGridFunction::startingGridIndex,
RealMappedGridFunction::startingGridIndex);
side[1] = Range(RealMappedGridFunction::endingGridIndex,
RealMappedGridFunction::endingGridIndex);
if (centerBoundaryNormal[kd][ks]->updateToMatchGrid(*this,
kd == 0 ? side[ks] : all, kd == 1 ? side[ks] : all,
kd == 2 ? side[ks] : all, d0) &
RealMappedGridFunction::updateResized)
{
*centerBoundaryNormal[kd][ks] = (Real)0.;
if (how & COMPUTEgeometryAsNeeded)
computeNeeded |= THEcenterBoundaryNormal;
computedGeometry &= ~THEcenterBoundaryNormal;
upd |= THEcenterBoundaryNormal;
} // end if
centerBoundaryNormal[kd][ks]->setIsCellCentered(LogicalFalse, kd);
}
else if (centerBoundaryNormal[kd][ks])
{
delete centerBoundaryNormal[kd][ks];
centerBoundaryNormal[kd][ks] = NULL;
} // end if
} // end if centerBoundaryNormal
if (what & THEcenterBoundaryTangent)
{
for (Integer kd=0; kd<3; kd++) for (Integer ks=0; ks<2; ks++)
{
if (numberOfDimensions > 1 && kd < numberOfDimensions)
{
if (&y != this &&
y.centerBoundaryTangent[kd][ks] &&
y.centerBoundaryTangent[kd][ks]->elementCount())
{
if (centerBoundaryTangent[kd][ks] == NULL)
centerBoundaryTangent[kd][ks] = MG_NEW RealMappedGridFunction;
centerBoundaryTangent[kd][ks]->reference(*y.centerBoundaryTangent[kd][ks]);
if (y.computedGeometry & THEcenterBoundaryTangent)
{
computedGeometry |= THEcenterBoundaryTangent;
}
else if (how & COMPUTEgeometryAsNeeded)
{
computedGeometry &= ~THEcenterBoundaryTangent;
computeNeeded |= THEcenterBoundaryTangent;
} // end if
}
else if (centerBoundaryTangent[kd][ks] == NULL)
{
centerBoundaryTangent[kd][ks] = MG_NEW RealMappedGridFunction;
} // end if
Range side[2], d0m = numberOfDimensions - 1;
side[0] = Range(RealMappedGridFunction::startingGridIndex,
RealMappedGridFunction::startingGridIndex);
side[1] = Range(RealMappedGridFunction::endingGridIndex,
RealMappedGridFunction::endingGridIndex);
if (centerBoundaryTangent[kd][ks]->updateToMatchGrid(*this,
kd == 0 ? side[ks] : all, kd == 1 ? side[ks] : all,
kd == 2 ? side[ks] : all, d0, d0m) &
RealMappedGridFunction::updateResized)
{
*centerBoundaryTangent[kd][ks] = (Real)0.;
if (how & COMPUTEgeometryAsNeeded)
computeNeeded |= THEcenterBoundaryTangent;
computedGeometry &= ~THEcenterBoundaryTangent;
upd |= THEcenterBoundaryTangent;
} // end if
centerBoundaryTangent[kd][ks]->setIsCellCentered(LogicalFalse, kd);
}
else if (centerBoundaryTangent[kd][ks])
{
delete centerBoundaryTangent[kd][ks];
centerBoundaryTangent[kd][ks] = NULL;
} // end if
}
} // end if centerBoundaryTangent
#else
// **** parallel version ****
if (what & THEvertexBoundaryNormal)
{
// const int myid=max(0,Communication_Manager::My_Process_Number);
// printf("MappedGrid::update2:myid=%i: computedGeometry & THEvertexBoundaryNormal=%i, "
// " &y==this = %i\n",
// myid,(int)((computedGeometry & THEvertexBoundaryNormal)!=0),
// int(&y==this));
if( mask==NULL )
{
printf("MappedGrid::update2:ERROR: you should build the mask before building the vertexBoundaryNormal.\n");
OV_ABORT("ERROR");
}
intSerialArray maskLocal; getLocalArrayWithGhostBoundaries(*mask,maskLocal);
// dim(0:1,0:2) will hold the dimensions of the local vertexBoundaryNormalArray
int pdim[6];
#define dim(side,axis) pdim[(side)+2*(axis)]
for (Integer kd=0; kd<3; kd++)for (Integer ks=0; ks<2; ks++)
{
if (kd < numberOfDimensions)
{
bool thisProcessorHasElements=false;
if( gridIndexRange(ks,kd)>=maskLocal.getBase(kd) && gridIndexRange(ks,kd)<=maskLocal.getBound(kd) )
{
thisProcessorHasElements=true;
for( int dir=0; dir<3; dir++ )
{
if( dir!=kd )
{
dim(0,dir)=maskLocal.getBase(dir);
dim(1,dir)=maskLocal.getBound(dir);
}
else
{
dim(0,dir)=gridIndexRange(ks,kd);
dim(1,dir)=gridIndexRange(ks,kd);
}
// numElements*=(dim(1,dir)-dim(0,dir)+1);
}
}
// printf("MappedGrid::update2:myid=%i: (ks,kd)=(%i,%i) pVertexBoundaryNormal=%i elementCount=%i"
// " thisProcessorHasElements=%i\n",
// myid,ks,kd,(pVertexBoundaryNormal[kd][ks]==NULL ? 0 : 1),
// (pVertexBoundaryNormal[kd][ks]==NULL ? 0 : pVertexBoundaryNormal[kd][ks]->elementCount()),
// (int)thisProcessorHasElements);
// fflush(0);
if( &y != this &&
y.pVertexBoundaryNormal[kd][ks] &&
y.pVertexBoundaryNormal[kd][ks]->elementCount() )
{
if( pVertexBoundaryNormal[kd][ks] == NULL )
pVertexBoundaryNormal[kd][ks] = MG_NEW realSerialArray;
pVertexBoundaryNormal[kd][ks]->reference(*y.pVertexBoundaryNormal[kd][ks]);
if (y.computedGeometry & THEvertexBoundaryNormal)
{
computedGeometry |= THEvertexBoundaryNormal;
}
else if( how & COMPUTEgeometryAsNeeded)
{
computedGeometry &= ~THEvertexBoundaryNormal;
computeNeeded |= THEvertexBoundaryNormal;
} // end if
}
else if( isAllVertexCentered && &y != this &&
(pVertexBoundaryNormal[kd][ks] == NULL ||
pVertexBoundaryNormal[kd][ks]->elementCount() == 0) &&
(y.pCenterBoundaryNormal[kd][ks] &&
y.pCenterBoundaryNormal[kd][ks]->elementCount() != 0))
{
if( pVertexBoundaryNormal[kd][ks] == NULL )
pVertexBoundaryNormal[kd][ks] = MG_NEW realSerialArray;
pVertexBoundaryNormal[kd][ks]->reference(*y.pCenterBoundaryNormal[kd][ks]);
if( y.computedGeometry & THEcenterBoundaryNormal )
{
computedGeometry |= THEvertexBoundaryNormal;
}
else if( how & COMPUTEgeometryAsNeeded )
{
computedGeometry &= ~THEvertexBoundaryNormal;
computeNeeded |= THEvertexBoundaryNormal;
} // end if
}
else if( isAllVertexCentered &&
(pVertexBoundaryNormal[kd][ks] == NULL ||
pVertexBoundaryNormal[kd][ks]->elementCount() == 0) &&
(pCenterBoundaryNormal[kd][ks] &&
pCenterBoundaryNormal[kd][ks]->elementCount() != 0))
{
if( pVertexBoundaryNormal[kd][ks] == NULL)
pVertexBoundaryNormal[kd][ks] = MG_NEW realSerialArray;
pVertexBoundaryNormal[kd][ks]->reference(*pCenterBoundaryNormal[kd][ks]);
if( computedGeometry & THEcenterBoundaryNormal)
{
computedGeometry |= THEvertexBoundaryNormal;
}
else if( how & COMPUTEgeometryAsNeeded)
{
computedGeometry &= ~THEvertexBoundaryNormal;
computeNeeded |= THEvertexBoundaryNormal;
} // end if
}
else if( pVertexBoundaryNormal[kd][ks] == NULL )
{
pVertexBoundaryNormal[kd][ks] = MG_NEW realSerialArray;
if (how & COMPUTEgeometryAsNeeded)
computeNeeded |= THEvertexBoundaryNormal;
computedGeometry &= ~THEvertexBoundaryNormal;
} // end if
else if( !( computedGeometry & THEvertexBoundaryNormal ) )
{
if (how & COMPUTEgeometryAsNeeded)
computeNeeded |= THEvertexBoundaryNormal;
}
if( !( computedGeometry & THEvertexBoundaryNormal ) && thisProcessorHasElements )
{
// Allocate space for the array if it is not already the correct size.
Range R[3];
for( int dir=0; dir<3; dir++ )
{
R[dir]=Range(dim(0,dir),dim(1,dir));
}
assert( pVertexBoundaryNormal[kd][ks]!=NULL );
realSerialArray & v = *pVertexBoundaryNormal[kd][ks];
bool resize=false;
for( int dir=0; dir<3; dir++ )
{
if( v.dimension(dir)!=R[dir] )
{
resize=true;
break;
}
}
if( resize )
{
v.resize(R[0],R[1],R[2],d0);
v=0.;
} // end if( resize )
}
}
else if( pVertexBoundaryNormal[kd][ks] ) // *wdh* 2011/08/21 -- this was pCenterBoundaryNormal ?!
{
delete pVertexBoundaryNormal[kd][ks];
pVertexBoundaryNormal[kd][ks] = NULL;
} // end if
} // end for ks,kd
if( computeNeeded & THEvertexBoundaryNormal )
{
// THEvertexBoundaryNormal was updated:
upd |= THEvertexBoundaryNormal;
}
// if( computeNeeded & THEvertexBoundaryNormal )
// {
// printf("MappedGrid::update2:myid=%i: *** Compute the vertexBoundaryNormal ***\n",myid);
// }
// else
// {
// printf("MappedGrid::update2:myid=%i: *** do NOT compute the vertexBoundaryNormal ***\n",myid);
// }
// fflush(0);
} // end vertexBoundaryNormal
if (what & THEcenterBoundaryNormal)
{
if( mask==NULL )
{
printf("MappedGrid::update2:ERROR: you should build the mask before building the centerBoundaryNormal.\n");
OV_ABORT("ERROR");
}
intSerialArray maskLocal; getLocalArrayWithGhostBoundaries(*mask,maskLocal);
// dim(0:1,0:2) will hold the dimensions of the local centerBoundaryNormalArray
int pdim[6];
#define dim(side,axis) pdim[(side)+2*(axis)]
for (Integer kd=0; kd<3; kd++)for (Integer ks=0; ks<2; ks++)
{
if (kd < numberOfDimensions)
{
bool thisProcessorHasElements=false;
if( gridIndexRange(ks,kd)>=maskLocal.getBase(kd) && gridIndexRange(ks,kd)<=maskLocal.getBound(kd) )
{
thisProcessorHasElements=true;
for( int dir=0; dir<3; dir++ )
{
if( dir!=kd )
{
dim(0,dir)=maskLocal.getBase(dir);
dim(1,dir)=maskLocal.getBound(dir);
}
else
{
dim(0,dir)=gridIndexRange(ks,kd);
dim(1,dir)=gridIndexRange(ks,kd);
}
// numElements*=(dim(1,dir)-dim(0,dir)+1);
}
}
if( &y != this &&
y.pCenterBoundaryNormal[kd][ks] &&
y.pCenterBoundaryNormal[kd][ks]->elementCount() )
{
if( pCenterBoundaryNormal[kd][ks] == 0)
pCenterBoundaryNormal[kd][ks] = MG_NEW realSerialArray;
pCenterBoundaryNormal[kd][ks]->reference(*y.pCenterBoundaryNormal[kd][ks]);
if( y.computedGeometry & THEcenterBoundaryNormal)
{
computedGeometry |= THEcenterBoundaryNormal;
}
else if( how & COMPUTEgeometryAsNeeded)
{
computedGeometry &= ~THEcenterBoundaryNormal;
computeNeeded |= THEcenterBoundaryNormal;
} // end if
}
else if( isAllVertexCentered && &y != this &&
(pCenterBoundaryNormal[kd][ks] == NULL ||
pCenterBoundaryNormal[kd][ks]->elementCount() == 0) &&
(y.pVertexBoundaryNormal[kd][ks] &&
y.pVertexBoundaryNormal[kd][ks]->elementCount() != 0))
{
if( pCenterBoundaryNormal[kd][ks] == NULL )
pCenterBoundaryNormal[kd][ks] = MG_NEW realSerialArray;
pCenterBoundaryNormal[kd][ks]->reference(*y.pVertexBoundaryNormal[kd][ks]);
if( y.computedGeometry & THEvertexBoundaryNormal)
{
computedGeometry |= THEcenterBoundaryNormal;
}
else if( how & COMPUTEgeometryAsNeeded)
{
computedGeometry &= ~THEcenterBoundaryNormal;
computeNeeded |= THEcenterBoundaryNormal;
} // end if
}
else if( isAllVertexCentered &&
(pCenterBoundaryNormal[kd][ks] == NULL ||
pCenterBoundaryNormal[kd][ks]->elementCount() == 0) &&
(pVertexBoundaryNormal[kd][ks] &&
pVertexBoundaryNormal[kd][ks]->elementCount() != 0))
{
if( pCenterBoundaryNormal[kd][ks] == NULL )
pCenterBoundaryNormal[kd][ks] = MG_NEW realSerialArray;
pCenterBoundaryNormal[kd][ks]->reference(*pVertexBoundaryNormal[kd][ks]);
if( computedGeometry & THEvertexBoundaryNormal)
{
computedGeometry |= THEcenterBoundaryNormal;
}
else if( how & COMPUTEgeometryAsNeeded)
{
computedGeometry &= ~THEcenterBoundaryNormal;
computeNeeded |= THEcenterBoundaryNormal;
} // end if
}
else if( pCenterBoundaryNormal[kd][ks] == NULL )
{
pCenterBoundaryNormal[kd][ks] = MG_NEW realSerialArray;
if (how & COMPUTEgeometryAsNeeded)
computeNeeded |= THEcenterBoundaryNormal;
computedGeometry &= ~THEcenterBoundaryNormal;
} // end if
else if( !( computedGeometry & THEcenterBoundaryNormal ) )
{
if (how & COMPUTEgeometryAsNeeded)
computeNeeded |= THEcenterBoundaryNormal;
}
if( !( computedGeometry & THEcenterBoundaryNormal ) && thisProcessorHasElements )
{
// Allocate space for the array if it is not already the correct size.
Range R[3];
for( int dir=0; dir<3; dir++ )
{
R[dir]=Range(dim(0,dir),dim(1,dir));
}
assert( pCenterBoundaryNormal[kd][ks]!=NULL );
realSerialArray & v = *pCenterBoundaryNormal[kd][ks];
bool resize=false;
for( int dir=0; dir<3; dir++ )
{
if( v.dimension(dir)!=R[dir] )
{
resize=true;
break;
}
}
if( resize )
{
v.resize(R[0],R[1],R[2],d0);
v=0.;
} // end if( resize )
}
}
else if( pCenterBoundaryNormal[kd][ks] )
{
delete pCenterBoundaryNormal[kd][ks];
pCenterBoundaryNormal[kd][ks] = NULL;
} // end if
} // end for ks,kd
if( computeNeeded & THEcenterBoundaryNormal )
{
// THEcenterBoundaryNormal was updated:
upd |= THEcenterBoundaryNormal;
}
} // end if centerBoundaryNormal
if (what & THEcenterBoundaryTangent)
{
if( mask==NULL )
{
printf("MappedGrid::update2:ERROR: you should build the mask before building the centerBoundaryTangent.\n");
OV_ABORT("ERROR");
}
intSerialArray maskLocal; getLocalArrayWithGhostBoundaries(*mask,maskLocal);
// dim(0:1,0:2) will hold the dimensions of the local vcenterBoundaryTangentArray
int pdim[6];
#define dim(side,axis) pdim[(side)+2*(axis)]
for (Integer kd=0; kd<3; kd++)for (Integer ks=0; ks<2; ks++)
{
if (numberOfDimensions > 1 && kd < numberOfDimensions)
{
bool thisProcessorHasElements=false;
if( gridIndexRange(ks,kd)>=maskLocal.getBase(kd) && gridIndexRange(ks,kd)<=maskLocal.getBound(kd) )
{
thisProcessorHasElements=true;
for( int dir=0; dir<3; dir++ )
{
if( dir!=kd )
{
dim(0,dir)=maskLocal.getBase(dir);
dim(1,dir)=maskLocal.getBound(dir);
}
else
{
dim(0,dir)=gridIndexRange(ks,kd);
dim(1,dir)=gridIndexRange(ks,kd);
}
// numElements*=(dim(1,dir)-dim(0,dir)+1);
}
}
if( &y != this &&
y.pCenterBoundaryTangent[kd][ks] &&
y.pCenterBoundaryTangent[kd][ks]->elementCount())
{
if( pCenterBoundaryTangent[kd][ks] == NULL)
pCenterBoundaryTangent[kd][ks] = MG_NEW realSerialArray;
pCenterBoundaryTangent[kd][ks]->reference(*y.pCenterBoundaryTangent[kd][ks]);
if( y.computedGeometry & THEcenterBoundaryTangent )
{
computedGeometry |= THEcenterBoundaryTangent;
}
else if( how & COMPUTEgeometryAsNeeded)
{
computedGeometry &= ~THEcenterBoundaryTangent;
computeNeeded |= THEcenterBoundaryTangent;
} // end if
}
else if( pCenterBoundaryTangent[kd][ks] == NULL )
{
pCenterBoundaryTangent[kd][ks] = MG_NEW realSerialArray;
if (how & COMPUTEgeometryAsNeeded)
computeNeeded |= THEcenterBoundaryTangent;
computedGeometry &= ~THEcenterBoundaryTangent;
} // end if
else if( !( computedGeometry & THEcenterBoundaryTangent ) )
{
if (how & COMPUTEgeometryAsNeeded)
computeNeeded |= THEcenterBoundaryTangent;
}
if( !( computedGeometry & THEcenterBoundaryTangent ) && thisProcessorHasElements )
{
// Allocate space for the array if it is not already the correct size.
Range R[3];
for( int dir=0; dir<3; dir++ )
{
R[dir]=Range(dim(0,dir),dim(1,dir));
}
assert( pCenterBoundaryTangent[kd][ks]!=NULL );
realSerialArray & v = *pCenterBoundaryTangent[kd][ks];
bool resize=false;
for( int dir=0; dir<3; dir++ )
{
if( v.dimension(dir)!=R[dir] )
{
resize=true;
break;
}
}
if( resize )
{
// to be consistent with the serial version which is a grid function with only 4 dimensions,
// we do the same thing here -- the last two dimensions are merged (*wdh* 061013)
// v.resize(R[0],R[1],R[2],d0,d0m);
Range d0m = numberOfDimensions - 1;
v.resize(R[0],R[1],R[2],d0.getLength()*d0m.getLength());
v=0.;
} // end if
}
}
else if( pCenterBoundaryTangent[kd][ks] )
{
delete pCenterBoundaryTangent[kd][ks];
pCenterBoundaryTangent[kd][ks] = NULL;
} // end if
} // end for ks,kd
if( computeNeeded & THEcenterBoundaryTangent )
{
// THEcenterBoundaryTangent was updated:
upd |= THEcenterBoundaryTangent;
}
} // end if centerBoundaryTangent
// ***** end parallel version *****
#endif
// if (what & ~computedGeometry & y.computedGeometry & THEminMaxEdgeLength && !(how & COMPUTEgeometry))
// {
// minimumEdgeLength = y.minimumEdgeLength;
// maximumEdgeLength = y.maximumEdgeLength;
// computeNeeded &= ~THEminMaxEdgeLength;
// computedGeometry |= THEminMaxEdgeLength;
// } // end if
if (what & ~computedGeometry & y.computedGeometry & THEboundingBox && !(how & COMPUTEgeometry))
{
boundingBox = y.boundingBox;
localBoundingBox = y.localBoundingBox; // Is this right ??
computeNeeded &= ~THEboundingBox;
computedGeometry |= THEboundingBox;
} // end if
return upd;
}
Integer MappedGridData::
updateUnstructuredGrid(MappedGridData& y,
const Integer& what,
const Integer& how,
Integer& computeNeeded)
// ================================================================================================
// /Description:
// Allocate space for any geometry arrays on a unstructured grid.
// Mark the flag computeNeeded for any geometry arrays that should be filled in.
// /y (input) : if &y==this then allocate space. If &y!=this then reference arrays to the one in y.
// /what (input) : bit flag of things to update.
// ================================================================================================
{
Integer upd = 0;
const Range all, d0 = numberOfDimensions;
if (what & THEmask)
{
// mask update stolen from update1, is this really correct here...?
if (&y != this &&
y.mask &&
y.mask->elementCount())
{
if (mask == NULL)
{
// printf("MG_NEW the mask (2)\n");
mask = MG_NEW IntegerMappedGridFunction;
}
mask->reference(*y.mask);
if (y.computedGeometry & THEmask)
{
computedGeometry |= THEmask;
}
else if (how & COMPUTEgeometryAsNeeded)
{
computedGeometry &= ~THEmask;
computeNeeded |= THEmask;
} // end if
}
else if (mask == NULL)
{
// printf("new the mask (1)\n");
mask = MG_NEW IntegerMappedGridFunction;
} // end if
if (mask ->updateToMatchGrid(*this) &
IntegerMappedGridFunction::updateResized)
{
*mask = ISghostPoint;
(*mask)(Range(extendedRange(0,0),extendedRange(1,0)),
Range(extendedRange(0,1),extendedRange(1,1)),
Range(extendedRange(0,2),extendedRange(1,2)))
= ISdiscretizationPoint;
mask->periodicUpdate();
if (how & COMPUTEgeometryAsNeeded)
computeNeeded |= THEmask;
computedGeometry &= ~THEmask;
upd |= THEmask;
} // end if
}
if (what & THEvertex)
{
if (&y != this &&
y.vertex &&
y.vertex->elementCount())
{
if (vertex == NULL) vertex = MG_NEW RealMappedGridFunction;
vertex->reference(*y.vertex);
if (y.computedGeometry & THEvertex)
{
computedGeometry |= THEvertex;
}
else if (how & COMPUTEgeometryAsNeeded)
{
computedGeometry &= ~THEvertex;
computeNeeded |= THEvertex;
} // end if
}
else if (isAllVertexCentered && &y != this &&
y.center &&
y.center->elementCount())
{
if (vertex == NULL) vertex = MG_NEW RealMappedGridFunction;
vertex->reference(*y.center);
if (y.computedGeometry & THEcenter)
{
computedGeometry |= THEvertex;
}
else if (how & COMPUTEgeometryAsNeeded)
{
computedGeometry &= ~THEvertex;
computeNeeded |= THEvertex;
} // end if
}
else if (isAllCellCentered && &y != this &&
y.corner &&
y.corner->elementCount())
{
if (vertex == NULL) vertex = MG_NEW RealMappedGridFunction;
vertex->reference(*y.corner);
if (y.computedGeometry & THEcorner)
{
computedGeometry |= THEvertex;
}
else if (how & COMPUTEgeometryAsNeeded)
{
computedGeometry &= ~THEvertex;
computeNeeded |= THEvertex;
} // end if
}
else if (isAllVertexCentered &&
center && center->elementCount())
{
if (vertex == NULL) vertex = MG_NEW RealMappedGridFunction;
vertex->reference(*center);
if (computedGeometry & THEcenter)
{
computedGeometry |= THEvertex;
}
else if (how & COMPUTEgeometryAsNeeded)
{
computedGeometry &= ~THEvertex;
computeNeeded |= THEvertex;
} // end if
}
else if (isAllCellCentered &&
corner && corner->elementCount())
{
if (vertex == NULL) vertex = MG_NEW RealMappedGridFunction;
vertex->reference(*corner);
if (computedGeometry & THEcorner)
{
computedGeometry |= THEvertex;
}
else if (how & COMPUTEgeometryAsNeeded)
{
computedGeometry &= ~THEvertex;
computeNeeded |= THEvertex;
} // end if
}
else if (vertex == NULL)
{
vertex = MG_NEW RealMappedGridFunction;
} // end if
if( vertex->updateToMatchGrid(*this, all, all, all, d0) & RealMappedGridFunction::updateResized )
{
*vertex = (Real)0.;
if (how & COMPUTEgeometryAsNeeded)
computeNeeded |= THEvertex;
computedGeometry &= ~THEvertex;
upd |= THEvertex;
} // end if
vertex ->setIsCellCentered(LogicalFalse);
} // end if
if (what & THEcenter)
{
if (&y != this &&
y.center && y.center->elementCount())
{
if (center == NULL) center = MG_NEW RealMappedGridFunction;
center->reference(*y.center);
if (y.computedGeometry & THEcenter)
{
computedGeometry |= THEcenter;
}
else if (how & COMPUTEgeometryAsNeeded)
{
computedGeometry &= ~THEcenter;
computeNeeded |= THEcenter;
} // end if
}
else if (isAllVertexCentered && &y != this &&
y.vertex && y.vertex->elementCount())
{
if (center == NULL) center = MG_NEW RealMappedGridFunction;
center->reference(*y.vertex);
if (y.computedGeometry & THEvertex)
{
computedGeometry |= THEcenter;
}
else if (how & COMPUTEgeometryAsNeeded)
{
computedGeometry &= ~THEcenter;
computeNeeded |= THEcenter;
} // end if
}
else if (isAllVertexCentered &&
vertex && vertex->elementCount())
{
if (center == NULL) center = MG_NEW RealMappedGridFunction;
center->reference(*vertex);
if (computedGeometry & THEvertex)
{
computedGeometry |= THEcenter;
}
else if (how & COMPUTEgeometryAsNeeded)
{
computedGeometry &= ~THEcenter;
computeNeeded |= THEcenter;
} // end if
}
else if (center == NULL)
{
center = MG_NEW RealMappedGridFunction;
} // end if
if (center->updateToMatchGrid(*this, all, all, all, d0) & RealMappedGridFunction::updateResized)
{
*center = (Real)0.;
if (how & COMPUTEgeometryAsNeeded)
computeNeeded |= THEcenter;
computedGeometry &= ~THEcenter;
upd |= THEcenter;
} // end if
} // end if
if (what & THEcorner)
{
if (&y != this &&
y.corner && y.corner->elementCount())
{
if (corner == NULL) corner = MG_NEW RealMappedGridFunction;
corner->reference(*y.corner);
if (y.computedGeometry & THEcorner)
{
computedGeometry |= THEcorner;
}
else if (how & COMPUTEgeometryAsNeeded)
{
computedGeometry &= ~THEcorner;
computeNeeded |= THEcorner;
} // end if
}
else if (isAllCellCentered && &y != this &&
y.vertex && y.vertex->elementCount())
{
if (corner == NULL) corner = MG_NEW RealMappedGridFunction;
corner->reference(*y.vertex);
if (y.computedGeometry & THEvertex)
{
computedGeometry |= THEcorner;
}
else if (how & COMPUTEgeometryAsNeeded)
{
computedGeometry &= ~THEcorner;
computeNeeded |= THEcorner;
} // end if
}
else if (isAllCellCentered &&
vertex && vertex->elementCount())
{
if (corner == NULL) corner = MG_NEW RealMappedGridFunction;
corner->reference(*vertex);
if (computedGeometry & THEvertex)
{
computedGeometry |= THEcorner;
}
else if (how & COMPUTEgeometryAsNeeded)
{
computedGeometry &= ~THEcorner;
computeNeeded |= THEcorner;
} // end if
}
else if (corner == NULL)
{
corner = MG_NEW RealMappedGridFunction;
} // end if
// The corner is a cell-centered grid function:
if( corner->updateToMatchGrid(*this,GridFunctionParameters::cellCentered,d0) &
RealMappedGridFunction::updateResized)
{
*corner = (Real)0.;
if (how & COMPUTEgeometryAsNeeded)
computeNeeded |= THEcorner;
computedGeometry &= ~THEcorner;
upd |= THEcorner;
} // end if
// for (Integer kd=0; kd<numberOfDimensions; kd++)
// corner->setIsCellCentered (!isCellCentered(kd), kd);
} // end if
/* ----
if( what & THEvertex )
{
if (&y != this &&
y.vertex &&
y.vertex->elementCount())
{
// reference the array to the one in y
if( vertex == NULL) vertex = MG_NEW RealMappedGridFunction;
vertex->reference(*y.vertex);
if (y.computedGeometry & THEvertex)
{
computedGeometry |= THEvertex;
}
else if (how & COMPUTEgeometryAsNeeded)
{
computedGeometry &= ~THEvertex;
computeNeeded |= THEvertex;
} // end if
}
else
{
if (vertex == NULL)
vertex = MG_NEW RealMappedGridFunction;
if( isAllVertexCentered && y.center && y.center.elementCount() )
{
vertex->reference(*y.center); // reference to the center array if it is there.
}
else if(vertex ->updateToMatchGrid(*this,all,d0) & RealMappedGridFunction::updateResized)
{
if (how & COMPUTEgeometryAsNeeded)
computeNeeded |= THEvertex;
computedGeometry &= ~THEvertex;
upd |= THEvertex;
} // end if
}
} // end if
if( what & THEcenter )
{
if (&y != this &&
y.center &&
y.center->elementCount())
{
// reference the array to the one in y
if( center == NULL) center = MG_NEW RealMappedGridFunction;
center->reference(*y.center);
if (y.computedGeometry & THEcenter)
{
computedGeometry |= THEcenter;
}
else if (how & COMPUTEgeometryAsNeeded)
{
computedGeometry &= ~THEcenter;
computeNeeded |= THEcenter;
} // end if
}
else if( vertex!=NULL )
{
center=vertex;
}
else if (center == NULL)
{
center = MG_NEW RealMappedGridFunction;
} // end if
if (center ->updateToMatchGrid(*this,all,d0) & RealMappedGridFunction::updateResized)
{
if (how & COMPUTEgeometryAsNeeded)
computeNeeded |= THEcenter;
computedGeometry &= ~THEcenter;
upd |= THEcenter;
} // end if
} // end if
---- */
return upd;
}
void MappedGridData::destroy(const Integer what)
{
#define MAPPED_GRID_DATA_DESTROY(x) if (x) { ::delete x; x = NULL; } // *wdh* 001121 don't use A++ delete
if (what & THEmask)
{
// if( mask )
// printf("delete the mask\n");
MAPPED_GRID_DATA_DESTROY(mask);
}
if (what & THEinverseVertexDerivative)
{
MAPPED_GRID_DATA_DESTROY(inverseVertexDerivative);
// MAPPED_GRID_DATA_DESTROY(inverseVertexDerivative2D);
// MAPPED_GRID_DATA_DESTROY(inverseVertexDerivative1D);
} // end if
if (what & THEinverseCenterDerivative)
{
MAPPED_GRID_DATA_DESTROY(inverseCenterDerivative);
// MAPPED_GRID_DATA_DESTROY(inverseCenterDerivative2D);
// MAPPED_GRID_DATA_DESTROY(inverseCenterDerivative1D);
} // end if
if (what & THEvertex)
{
MAPPED_GRID_DATA_DESTROY(vertex);
// MAPPED_GRID_DATA_DESTROY(vertex2D);
// MAPPED_GRID_DATA_DESTROY(vertex1D);
} // end if
if (what & THEcenter)
{
MAPPED_GRID_DATA_DESTROY(center);
// MAPPED_GRID_DATA_DESTROY(center2D);
// MAPPED_GRID_DATA_DESTROY(center1D);
} // end if
if (what & THEcorner)
{
MAPPED_GRID_DATA_DESTROY(corner);
// MAPPED_GRID_DATA_DESTROY(corner2D);
// MAPPED_GRID_DATA_DESTROY(corner1D);
} // end if
if (what & THEvertexDerivative)
{
MAPPED_GRID_DATA_DESTROY(vertexDerivative);
// MAPPED_GRID_DATA_DESTROY(vertexDerivative2D);
// MAPPED_GRID_DATA_DESTROY(vertexDerivative1D);
} // end if
if (what & THEcenterDerivative)
{
MAPPED_GRID_DATA_DESTROY(centerDerivative);
// MAPPED_GRID_DATA_DESTROY(centerDerivative2D);
// MAPPED_GRID_DATA_DESTROY(centerDerivative1D);
} // end if
if (what & THEvertexJacobian) MAPPED_GRID_DATA_DESTROY(vertexJacobian);
if (what & THEcenterJacobian) MAPPED_GRID_DATA_DESTROY(centerJacobian);
if (what & THEcellVolume) MAPPED_GRID_DATA_DESTROY(cellVolume);
if (what & THEcenterNormal)
{
MAPPED_GRID_DATA_DESTROY(centerNormal);
// MAPPED_GRID_DATA_DESTROY(centerNormal2D);
// MAPPED_GRID_DATA_DESTROY(centerNormal1D);
} // end if
if (what & THEcenterArea)
{
MAPPED_GRID_DATA_DESTROY(centerArea);
// MAPPED_GRID_DATA_DESTROY(centerArea2D);
// MAPPED_GRID_DATA_DESTROY(centerArea1D);
} // end if
if (what & THEfaceNormal)
{
MAPPED_GRID_DATA_DESTROY(faceNormal);
// MAPPED_GRID_DATA_DESTROY(faceNormal2D);
// MAPPED_GRID_DATA_DESTROY(faceNormal1D);
} // end if
if (what & THEfaceArea)
{
MAPPED_GRID_DATA_DESTROY(faceArea);
// MAPPED_GRID_DATA_DESTROY(faceArea2D);
// MAPPED_GRID_DATA_DESTROY(faceArea1D);
} // end if
if (what & THEvertexBoundaryNormal)
for (Integer kd=0; kd<3; kd++) for (Integer ks=0; ks<2; ks++)
{
MAPPED_GRID_DATA_DESTROY(vertexBoundaryNormal[kd][ks]);
MAPPED_GRID_DATA_DESTROY(pVertexBoundaryNormal[kd][ks]);
}
if (what & THEcenterBoundaryNormal)
for (Integer kd=0; kd<3; kd++) for (Integer ks=0; ks<2; ks++)
{
MAPPED_GRID_DATA_DESTROY(centerBoundaryNormal[kd][ks]);
MAPPED_GRID_DATA_DESTROY(pCenterBoundaryNormal[kd][ks]);
}
if (what & THEcenterBoundaryTangent)
for (Integer kd=0; kd<3; kd++) for (Integer ks=0; ks<2; ks++)
{
MAPPED_GRID_DATA_DESTROY(centerBoundaryTangent[kd][ks]);
MAPPED_GRID_DATA_DESTROY(pCenterBoundaryTangent[kd][ks]);
}
for ( int i=0; i<4; i++ )
{
if ( unstructuredBoundaryConditionInfo[i] )
{
delete unstructuredBoundaryConditionInfo[i];
unstructuredBoundaryConditionInfo[i] = NULL;
}
if (unstructuredPeriodicBoundaryInfo[i])
{
delete unstructuredPeriodicBoundaryInfo[i];
unstructuredPeriodicBoundaryInfo[i] = NULL;
}
}
#undef MAPPED_GRID_DATA_DESTROY
GenericGridData::destroy(what);
}
const IntegerArray *
MappedGridData::getUnstructuredBCInfo( int type )
{
if ( gridType==MappedGrid::structuredGrid ) // should this be an assertion?
return 0;
assert( mapping.getMapping().getClassName()=="UnstructuredMapping" );
assert( type>=UnstructuredMapping::Vertex && type<=UnstructuredMapping::Region );
UnstructuredMapping &umap = (UnstructuredMapping &)mapping.getMapping();
if (unstructuredBoundaryConditionInfo[type])
return unstructuredBoundaryConditionInfo[type];
unstructuredBoundaryConditionInfo[type] = new IntegerArray;
IntegerArray &bci = *unstructuredBoundaryConditionInfo[type];
std::string bcTag = std::string("__bcnum ")+UnstructuredMapping::EntityTypeStrings[type].c_str();
UnstructuredMapping::tag_entity_iterator git, git_end;
git = umap.tag_entity_begin(bcTag);
git_end = umap.tag_entity_end(bcTag);
int nbc = distance(git,git_end);
if ( !nbc )
return unstructuredBoundaryConditionInfo[type];
bci.resize(nbc,2);
int b=0;
for ( ; git!=git_end; git++, b++ )
{
bci(b,0) = git->e;
bci(b,1) = (long int)umap.getTagData(UnstructuredMapping::EntityTypeEnum(type), git->e, bcTag);
}
return unstructuredBoundaryConditionInfo[type];
}
namespace{
struct Cmp {
Cmp(IntegerArray &A_) : A(A_) { }
bool operator() ( int i, int j )
{ return A(i,0)<A(j,0); }
IntegerArray &A;
};
}
const IntegerArray *
MappedGridData::getUnstructuredPeriodicBC( int type )
{
if ( gridType==MappedGrid::structuredGrid ) // should this be an assertion?
return 0;
assert( mapping.getMapping().getClassName()=="UnstructuredMapping" );
assert( type>=UnstructuredMapping::Vertex && type<=UnstructuredMapping::Region );
UnstructuredMapping &umap = (UnstructuredMapping &)mapping.getMapping();
if ( unstructuredPeriodicBoundaryInfo[type] )
return unstructuredPeriodicBoundaryInfo[type];
unstructuredPeriodicBoundaryInfo[type] = new IntegerArray;
IntegerArray &pbc = *unstructuredPeriodicBoundaryInfo[type];
// periodic cells are marked in the unstructured mapping, we reconstruct
// periodicity info for other entities based on cell information
UnstructuredMapping::EntityTypeEnum cellType = UnstructuredMapping::EntityTypeEnum(umap.getDomainDimension());
UnstructuredMapping::EntityTypeEnum perType = UnstructuredMapping::EntityTypeEnum(type);
std::string perCellTag = std::string("periodic ") + UnstructuredMapping::EntityTypeStrings[cellType].c_str();
std::string bdyCellTag = std::string("boundary ") + UnstructuredMapping::EntityTypeStrings[cellType].c_str();
std::string ghostCellTag = std::string("Ghost ")+UnstructuredMapping::EntityTypeStrings[cellType].c_str();
std::string perTag = std::string("periodic ") + UnstructuredMapping::EntityTypeStrings[perType].c_str();
std::string bdyPerTag = std::string("boundary ") + UnstructuredMapping::EntityTypeStrings[perType].c_str();
std::string ghostPerTag = std::string("Ghost ")+UnstructuredMapping::EntityTypeStrings[perType].c_str();
int nPerCell = distance( umap.tag_entity_begin( perCellTag ), umap.tag_entity_end( perCellTag ) );
if ( nPerCell==0 )
return unstructuredPeriodicBoundaryInfo[type];
UnstructuredMapping::tag_entity_iterator git, git_end;
git = umap.tag_entity_begin(perCellTag);
git_end = umap.tag_entity_end(perCellTag);
// cook up an upper bound for the number of periodic boundary entities
int nPer = nPerCell;
if ( cellType!=perType )
{
nPer = 0;
for ( ; git!=git_end; git++ )
{
UnstructuredMappingAdjacencyIterator ai = umap.adjacency_begin(*git, perType);
nPer += ai.nAdjacent();
}
}
pbc.redim(nPer,2);
pbc = -1;
nPer = 0;
git = umap.tag_entity_begin(perCellTag);
ArraySimple<bool> found( umap.size(perType) );
found = false;
cout<<ghostPerTag<<endl;
for ( ; git!=git_end; git++ )
{
int ep = (long int)umap.getTagData(cellType, git->e, perCellTag);
if ( cellType == perType )
{
pbc(nPer,0) = git->e;
pbc(nPer,1) = ep;
nPer++;
}
else
{
UnstructuredMappingAdjacencyIterator ei, ei_end, epi;
epi = umap.adjacency_begin(cellType, ep, perType);
ei = umap.adjacency_begin(*git, perType);
ei_end = umap.adjacency_end(*git, perType);
assert(epi.nAdjacent()==ei.nAdjacent());
for ( ; ei!=ei_end; ei++, epi++ )
{
if ( umap.hasTag(perType, *ei, ghostPerTag) && !found(*ei) )
{
// typically we don't like this but
// should it be an assertion?
assert(!umap.hasTag(perType, *epi, ghostPerTag));
assert(!found(*ei));
pbc(nPer,0) = *ei;
pbc(nPer,1) = *epi;
found(*ei) = true;
nPer++;
}
}
}
}
pbc.resize(nPer,2);
IntegerArray perm(nPer);
perm.seqAdd(0,1);
Cmp cmp(pbc);
std::sort( &perm(0),&perm(0)+nPer, cmp );
IntegerArray unsorted;
unsorted = pbc;
for ( int i=0; i<nPer; i++ )
for ( int a=0; a<2; a++ )
pbc( i, a) = unsorted( perm(i), a);
// unsorted.display("unsorted");
// pbc.display("sorted");
return unstructuredPeriodicBoundaryInfo[type];
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_exit.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: tchicken <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/12/25 18:38:00 by jlyessa #+# #+# */
/* Updated: 2021/03/17 21:50:30 by tchicken ### ########.fr */
/* */
/* ************************************************************************** */
#include "minishell.h"
static int is_space(unsigned char c)
{
return (c == ' ' || c == '\n' || c == '\t' ||
c == '\v' || c == '\f' || c == '\r');
}
static int is_num(char *str)
{
while (is_space(*str))
str++;
if (*str == '-' || *str == '+')
str++;
while (*str)
{
if (!(*str >= '0' && *str <= '9') && !is_space(*str))
return (0);
str++;
}
return (1);
}
/*
** executes the exit command
**
** @param *all general structure
** @param *cmd command structure
** @return 0
*/
int ft_exit(t_all *all, t_cmd *cmd)
{
if (strs_size(cmd->argv) > 1)
{
bash_err("exit", "too many arguments", 0);
all->res = 1;
}
else if (ft_strncmp(cmd->argv[0], "", 1))
{
if (!is_num(cmd->argv[0]))
{
all->res = 2;
bash_err(cmd->argv[0], "numeric argument required", 0);
}
else
{
all->res = ft_atoi(cmd->argv[0]);
if (all->res > 255 || all->res < 0)
all->res = 1;
}
}
clear_all(all);
exit(all->res);
return (0);
}
|
C
|
#include "keyboard.h"
#include "ports.h"
#include "../cpu/isr.h"
#include "display.h"
#include "../kernel/util.h"
void print_letter(uint8_t scancode)
{
switch (scancode)
{
case 0x0:
print_string("ERROR");
break;
case 0x1:
print_string("ESC");
break;
case 0x2:
print_string("1");
break;
case 0x3:
print_string("2");
break;
case 0x4:
print_string("3");
break;
case 0x5:
print_string("4");
break;
case 0x6:
print_string("5");
break;
case 0x7:
print_string("6");
break;
case 0x8:
print_string("7");
break;
case 0x9:
print_string("8");
break;
case 0x0A:
print_string("9");
break;
case 0x0B:
print_string("0");
break;
case 0x0C:
print_string("-");
break;
case 0x0D:
print_string("+");
break;
case 0x0E:
print_string("Backspace");
break;
case 0x0F:
print_string("Tab");
break;
case 0x10:
print_string("Q");
break;
case 0x11:
print_string("W");
break;
case 0x12:
print_string("E");
break;
case 0x13:
print_string("R");
break;
case 0x14:
print_string("T");
break;
case 0x15:
print_string("Y");
break;
case 0x16:
print_string("U");
break;
case 0x17:
print_string("I");
break;
case 0x18:
print_string("O");
break;
case 0x19:
print_string("P");
break;
case 0x1A:
print_string("[");
break;
case 0x1B:
print_string("]");
break;
case 0x1C:
print_string("ENTER");
break;
case 0x1D:
print_string("LCtrl");
break;
case 0x1E:
print_string("A");
break;
case 0x1F:
print_string("S");
break;
case 0x20:
print_string("D");
break;
case 0x21:
print_string("F");
break;
case 0x22:
print_string("G");
break;
case 0x23:
print_string("H");
break;
case 0x24:
print_string("J");
break;
case 0x25:
print_string("K");
break;
case 0x26:
print_string("L");
break;
case 0x27:
print_string(";");
break;
case 0x28:
print_string("'");
break;
case 0x29:
print_string("`");
break;
case 0x2A:
print_string("LShift");
break;
case 0x2B:
print_string("\\");
break;
case 0x2C:
print_string("Z");
break;
case 0x2D:
print_string("X");
break;
case 0x2E:
print_string("C");
break;
case 0x2F:
print_string("V");
break;
case 0x30:
print_string("B");
break;
case 0x31:
print_string("N");
break;
case 0x32:
print_string("M");
break;
case 0x33:
print_string(",");
break;
case 0x34:
print_string(".");
break;
case 0x35:
print_string("/");
break;
case 0x36:
print_string("Rshift");
break;
case 0x37:
print_string("Keypad *");
break;
case 0x38:
print_string("LAlt");
break;
case 0x39:
print_string("Space");
break;
default:
print_string("Unknown key");
break;
}
}
static void keyboard_callback(registers_t *regs)
{
uint8_t scancode = port_byte_in(0x60);
print_letter(scancode);
print_nl();
}
uint8_t keyboard_key_return()
{
uint8_t scancode = port_byte_in(0x60);
return scancode;
}
void init_keyboard()
{
register_interrupt_handler(IRQ1, keyboard_callback);
}
void status_control()
{
int inf = 1;
while (inf)
{
uint8_t input = keyboard_key_return();
if (input == 0x1) // Esc
{
port_byte_out(0x60, 0x0);
break;
}
if (input == 0x1c) // Enter key
{
int offset = get_cursor();
uint8_t *vidmem = (uint8_t *)VIDEO_ADDRESS;
char character = vidmem[offset];
if (character == '-')
{
int row = get_offset_row(offset);
int col = get_offset_col(offset);
col = col - 10;
int new_offset = get_offset(col, row);
char new_character = vidmem[new_offset];
if (new_character == 'N')
{
col = col - 1;
print_string_at("OFF", col, row);
}
else
{
col = col - 1;
print_string_at("ON ", col, row);
}
set_cursor(offset);
}
port_byte_out(0x60, 0x0);
}
if (input == 0x48) // UP arrow
{
int offset = get_cursor();
int row = get_offset_row(offset);
if (row)
{
row = row - 1;
}
int col = get_offset_col(offset);
int new_offset = get_offset(col, row);
set_cursor(new_offset);
port_byte_out(0x60, 0x0);
}
if (input == 0x50) // DOWN arrow
{
int offset = get_cursor();
int row = get_offset_row(offset);
if (row != 24)
{
row = row + 1;
}
int col = get_offset_col(offset);
int new_offset = get_offset(col, row);
set_cursor(new_offset);
port_byte_out(0x60, 0x0);
}
if (input == 0x4b) // LEFT arrow
{
int offset = get_cursor();
int row = get_offset_row(offset);
int col = get_offset_col(offset);
if (col)
{
col = col - 1;
}
int new_offset = get_offset(col, row);
set_cursor(new_offset);
port_byte_out(0x60, 0x0);
}
if (input == 0x4d) // RIGHT arrow
{
int offset = get_cursor();
int row = get_offset_row(offset);
int col = get_offset_col(offset);
if (col != 79)
{
col = col + 1;
}
int new_offset = get_offset(col, row);
set_cursor(new_offset);
port_byte_out(0x60, 0x0);
}
}
}
int summary_control()
{
int inf = 1;
int flag;
port_byte_out(0x60, 0x0);
while (inf)
{
uint8_t input = keyboard_key_return();
if (input == 0x1) // Esc
{
port_byte_out(0x60, 0x0);
flag = 0;
break;
}
if (input == 0x1c) // Enter key
{
port_byte_out(0x60, 0x0);
flag = 1;
break;
}
if (input == 0x21) // F key
{
port_byte_out(0x60, 0x0);
flag = 2;
break;
}
}
return flag;
}
int get_int()
{
port_byte_out(0x60, 0x0);
int start_offset = get_cursor();
int start_col = get_offset_col(start_offset);
uint8_t key[10] = {0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0x0A, 0x0B};
char *val_char[10] = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "0"};
int val_int[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
int ret_val = 0;
int inf = 1;
int i;
while (inf)
{
uint8_t input = keyboard_key_return();
for (i = 0; i < 10; i++)
{
if (input == key[i]) // 0-9 keys
{
port_byte_out(0x60, 0x0);
print_string(val_char[i]);
ret_val = (ret_val * 10) + val_int[i];
}
}
if (input == 0x1C) // ENTER key
{
port_byte_out(0x60, 0x0);
print_nl();
return ret_val;
}
if (input == 0x0E) // Backspace key
{
port_byte_out(0x60, 0x0);
ret_val = ret_val / 10;
int offset = get_cursor();
int row = get_offset_row(offset);
int col = get_offset_col(offset);
if (col)
{
col = col - 1;
}
int new_offset = get_offset(col, row);
if (col == start_col - 1)
;
else
{
set_cursor(new_offset);
set_char_at_video_memory(' ', new_offset);
}
}
}
}
void esc_to_exit()
{
int inf = 1;
while (inf)
{
uint8_t input = keyboard_key_return();
if (input == 0x1) // Esc
{
port_byte_out(0x60, 0x0);
break;
}
}
}
void enter_to_contn()
{
int inf = 1;
while (inf)
{
uint8_t input = keyboard_key_return();
if (input == 0x1C) // Enter Key
{
port_byte_out(0x60, 0x0);
break;
}
}
}
|
C
|
#include <unistd.h>
int ft_atoi(char *s)
{
int i;
int sign;
int res;
sign = 1;
i = 0;
while (s[i] != 0 && ((s[i] >= 9 && s[i] <= 13) || s[i] == ' '))
i++;
if (s[i] == '-')
sign = -1;
if (s[i] == '-' || s[i] == '+')
i++;
if (s[i] == 0)
return (0);
res = 0;
while (s[i] != 0 && (s[i] >= '0' && s[i] <= '9'))
res = res * 10 + (s[i++] - '0');
return (res * sign);
}
void ft_putnbr(int n)
{
int i;
char c;
i = 0;
if (n < 0)
{
write(1, "-", 1);
n = -n;
}
if (n < 10)
{
c = n + '0';
write(1, &c, 1);
}
else
{
ft_putnbr(n / 10);
ft_putnbr(n % 10);
}
}
void tab_mult(int n)
{
int i;
i = 0;
while (++i < 10)
{
ft_putnbr(i);
write(1, " x ", 3);
ft_putnbr(n);
write(1, " = ", 3);
ft_putnbr(i * n);
write(1, "\n", 1);
}
}
int main(int argc, char **argv)
{
if (argc == 2)
tab_mult(ft_atoi(argv[1]));
else
write(1, "\n", 1);
return (0);
}
|
C
|
#include <stdio.h>
#include <inttypes.h>
int read_int();
float read_float();
void print_int(int out);
void print_float(float out);
int read_int() {
int ret = 0;
printf("Enter an integer: ");
scanf("%d", &ret);
return ret;
}
float read_float() {
float ret = 0.0f;
printf("Enter a floating point number: ");
scanf("%f", &ret);
return ret;
}
void print_int(int out) {
printf("%8d\n", out);
}
void print_float(float out) {
printf("%f\n", out);
}
uint64_t measure() {
volatile uint32_t a, d;
__asm__ __volatile__("rdtsc" : "=a"(a), "=d"(d));
return ((uint64_t)a | ((uint64_t)d << 32));
}
uint64_t g_ts;
void start_measurement() {
g_ts = measure();
}
void end_measurement() {
uint64_t t = measure() - g_ts;
printf(" --|--|--|--\n");
printf("Time: %" PRId64 " ticks\n", t);
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa_base.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: lspiess <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/11/04 19:09:42 by lspiess #+# #+# */
/* Updated: 2019/11/04 19:10:19 by lspiess ### ########.fr */
/* */
/* ************************************************************************** */
#include "convft.h"
#define NULLTER 1
char *ft_itoa_base(int n, int base)
{
int i;
char *s;
char buf[100];
char *ret;
s = "0123456789abcdef";
if (base == 10)
return (ft_itoa(n));
if (n == 0)
return (ft_strdup("0"));
ft_memset(buf, -1, 100);
buf[99] = '\0';
i = 98;
while (n)
{
buf[i] = s[n % base];
n /= base;
i--;
}
ret = ft_mmalloc(100 - i);
++i;
ret = ft_strcpy(ret, &(buf[i]));
return (ret);
}
char *ft_ltoa_base(long n, int base)
{
int i;
char *s;
char buf[100];
char *ret;
s = "0123456789abcdef";
if (base == 10)
return (ft_ltoa(n));
if (n == 0)
return (ft_strdup("0"));
ft_memset(buf, -1, 100);
buf[99] = '\0';
i = 98;
while (n)
{
buf[i] = s[n % base];
n /= base;
i--;
}
ret = ft_mmalloc(100 - i);
++i;
ret = ft_strcpy(ret, &(buf[i]));
return (ret);
}
char *ft_lltoa_base(long long n, int base)
{
int i;
char *s;
char buf[100];
char *ret;
s = "0123456789abcdef";
if (base == 10)
return (ft_lltoa(n));
if (n == 0)
return (ft_strdup("0"));
ft_memset(buf, -1, 100);
buf[99] = '\0';
i = 98;
while (n)
{
buf[i] = s[n % base];
n /= base;
i--;
}
ret = ft_mmalloc(100 - i);
++i;
ret = ft_strcpy(ret, &(buf[i]));
return (ret);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SIZE 20
int main()
{
int number[ SIZE ];
size_t i, a;
srand( time( NULL ) );
number[ 0 ] = rand() % 20 + 1;
for( i = 1; i < SIZE; i++ ){
a = i;
number[ i ] = rand() % 20 + 1;
while( a > 0){
if( number[ i ] == number[ a - 1] ){
number[ i ] = rand() % 20 + 1;
a = i + 1;
}
a--;
}
}
for( i = 0; i < SIZE; i++ ){
printf( "%d ", number[ i ] );
}
return 0;
}
|
C
|
/*
** malloc.h for malloc in /home/pennam_a/Systeme_unix/PSU_2015_malloc
**
** Made by antoine pennamen
** Login <[email protected]>
**
** Started on Wed Jan 27 14:36:05 2016 antoine pennamen
** Last update Sun Feb 14 22:31:26 2016 antoine pennamen
*/
#ifndef MALLOC_H_
# define MALLOC_H_
# include <unistd.h>
# include <string.h>
# define PAD (sizeof(void *) * 2)
# define SIZE_STRUCT (sizeof(struct s_malloc))
# define MY_PAD(size) (size + (((PAD - (size % PAD))) % PAD))
typedef struct s_malloc
{
struct s_malloc *next;
size_t _size;
char pad[8];
int free;
} t_malloc;
extern t_malloc *g_container;
void *malloc(size_t size);
void *realloc(void *ptr, size_t size);
void free(void *ptr);
void show_alloc_mem();
void *init_list(size_t size);
void *put_in_list(size_t size);
int check_sbrk(void *ptr, size_t size);
void *check_free(size_t size);
void *calloc(size_t nmemb, size_t size);
void *do_while(void *ptr, size_t size, t_malloc *tmp);
#endif /* !MALLOC_H_ */
|
C
|
// string_maker.c
#include "play.h"
#include <stdlib.h>
char *string_maker (char **board,int size) {
char *str ;
int i,j ;
str=malloc(((size*size)+1)*sizeof(char));
for ( i = 0 ; i < size ; i++ ) {
for ( j = 0 ; j < size ; j++ ) {
str[i*size+j]=board[i][j] ; // dimiourgise ena string gia kathe katastasi tou pinaka
}
}
str[size*size+1]='\0';
return str;
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include "image.h"
struct image_struct {
int dim;
int depth;
int *data;
};
struct image_struct *image_alloc(int dim, int depth) {
int len;
struct image_struct *res;
len = dim * dim * depth;
res = malloc(sizeof(struct image_struct));
res -> dim = dim;
res -> depth = depth;
res -> data = malloc(sizeof(int) * len);
return res;
}
int image_read_file(struct image_struct *s, const char *fname) {
FILE *fp;
int *data;
int in_buf[4];
fp = fopen(fname, "r");
if (fp == NULL)
return -1;
data = s -> data;
while ((in_buf[0] = fgetc(fp)) != EOF) {
in_buf[1] = fgetc(fp);
in_buf[2] = fgetc(fp);
in_buf[3] = fgetc(fp);
*data++ = (
((in_buf[0] & 0xFF) << 0) |
((in_buf[1] & 0xFF) << 8) |
((in_buf[2] & 0xFF) << 16) |
((in_buf[3] & 0xFF) << 24)
);
}
return 0;
}
void image_free(struct image_struct *s) {
free(s -> data);
free(s);
}
int image_get_len(struct image_struct *s) {
return s -> dim * s -> dim * s -> depth;
}
int image_get_dim(struct image_struct *s) {
return s -> dim;
}
int image_get_depth(struct image_struct *s) {
return s -> depth;
}
int *image_get_data_ptr(struct image_struct *s) {
return s -> data;
}
|
C
|
/*
cs50 2015
Scott Linne
pset2 Caesar cipher
encrypt a text string by k characters
*/
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
int main(int argc, char* argv[])
{
if(argc !=2 || atoi(argv[1]) < 0 )
{
printf("Enter a non-negative integer: Usage ./caesar k\n");
return 1;
}
int k = atoi(argv[1]);
char* p = GetString();
for(int i = 0; i < strlen(p); i++)
{
// print space characters litterally, do not encipher
if(p[i] == ' ')
{
printf(" ");
}
// if the character is not an alphacharacter, do not encipher it, print it literally
else if(!isalpha(p[i]))
{
printf("%c", p[i]);
}
// encipher alpha characters only
else
{
// formula to enciper uppercase characters
if(isupper(p[i]))
{
// set alpha characters to start from zero (A - A would be zero)
int letter = p[i]-'A';
// caesar cipher formula letter value plus cipher
int cipher = ((letter +k)%26)+'A';
printf("%c", cipher);
}
// formula to encipher lowercase characters
if(islower(p[i]))
{
// set alpha characters to start from zero (a - a would be zero)
int letter = p[i]-'a';
// caesar cipher formula letter value plus cipher
int cipher = ((letter +k)%26)+'a';
printf("%c", cipher);
}
}
}
printf("\n");
}
|
C
|
#include<stdio.h>
void fun()
{
int a[5],
int i;
for(i = 0; i < 5; i++)
printf("%d ",a[i]);
}
int main()
{
int a[5],i;
for(i = 0; i < 5; i++){
a[i] = i;
} fun();
return 0;
}
|
C
|
#include "ponto.h"
int main()
{
setlocale(LC_ALL, "");
int escolha;
char continuidade;
printf("O que você quer fazer?\n");
do{
printf("-digite 1 para criar tabela\n-digite 2 para listar tabelas\n-digite 3 para criar nova linha na tabela\n-digite 4 para listar todos os dados de uma tabela\n-digite 5 para procurar um valor na tabela\n-digite 6 para apagar a linha de uma tabela\n-digite 7 para apagar uma tabela\n-digite 8 para criar uma nova coluna em uma tabela já existente\n-digite 9 para apagar uma coluna de uma tabela\n-digite 10 para alterar um valor da tabela\n");
scanf("%d", &escolha);
switch (escolha)
{
case 1:
criar_tabela();
break;
case 2:
listar_tabela();
break;
case 3:
getchar();
listar_tabela();
criar_novaLinha();
break;
case 4:
getchar();
listar_dadosTabela();
break;
case 5:
getchar();
printf("existem essas tabelas:\n");
listar_tabela();
procurar_valor();
break;
case 6:
getchar();
apagar_linhaTabela();
break;
case 7:
getchar();
apagar_tabela();
break;
case 8:
getchar();
criar_novaColuna();
break;
case 9:
getchar();
apagar_coluna();
break;
case 10:
getchar();
alterar_valor();
break;
default:
printf("valor invalido\n");
break;
}
printf("Quer continuar? (s/n)\n");
scanf(" %c", &continuidade);
}while(continuidade == 's');
return 0;
}
|
C
|
#include <stdio.h>
int main(){
double width,length;
scanf("%ls",&width);
scanf("%lf",&length);
double ans1 = width*2;
double ans2 = length*2;
double ans = ans1+ans2
printf("%f %f", ans1, ans2);
//printf("Perimeter of rectangle = %.4f units",ans);
return 0;
}
|
C
|
#include <stdio.h>
#include <locale.h>
#include <wctype.h>
#include <wchar.h>
int main()
{
const wchar_t *orig = L"BAÑO";
wchar_t xfrm[64];
setlocale(LC_ALL, ""); // enable environment locale
int i = 0;
while (i < wcslen(orig))
{
xfrm[i] = towlower(orig[i]);
i++;
}
xfrm[i] = 0;
printf("orig: %ls, xfrm: %ls\n", orig, xfrm);
return 0;
}
|
C
|
#include "monty.h"
/**
* add - function to add the two
* @head: header of the file
* @line_number: line of the file
*/
void add(stack_t **head, unsigned int line_number)
{
stack_t *temp;
char *msg = "can't add, stack too short";
if (!head || !*head)
{
fprintf(stderr, "L%i: %s\n", line_number, msg);
free_dlistint(*head);
exit(EXIT_FAILURE);
}
temp = *head;
if ((*head)->next)
{
*head = (*head)->next;
(*head)->n += temp->n;
}
free(temp);
}
|
C
|
struct ColorRGB {
unsigned char r;
unsigned char g;
unsigned char b;
};
unsigned char clamp(double a){
if(a >= 255.0){
return 255;
}
else if(a <= 0.0){
return 0;
}
return (unsigned char)a;
}
struct ColorRGB * filterImage(struct ColorRGB pixels[],struct ColorRGB result[],int w, int h, int filterWidth, int filterHeight, double core[], double factor, double bias){
for(int x = 0; x < w; x++){
for(int y = 0; y < h; y++)
{
double red = 0.0, green = 0.0, blue = 0.0;
for(int filterY = 0; filterY < filterHeight; filterY++){
for(int filterX = 0; filterX < filterWidth; filterX++)
{
int imageX = (x - filterWidth / 2 + filterX + w) % w;
int imageY = (y - filterHeight / 2 + filterY + h) % h;
red += pixels[imageY * w + imageX].r * core[filterY*filterWidth+filterX];
green += pixels[imageY * w + imageX].g * core[filterY*filterWidth+filterX];
blue += pixels[imageY * w + imageX].b * core[filterY*filterWidth+filterX];
}
}
result[y * w + x].r = clamp(factor * red + bias);
result[y * w + x].g = clamp(factor * green + bias);
result[y * w + x].b = clamp(factor * blue + bias);
}
}
return result;
}
|
C
|
/*
* Sample skeleton source file.
*/
#include <avr/io.h>
#include <util/delay.h>
#include <stdlib.h>
#include "lib/serial/serial.h"
int main (void){
serial_init_b(BAUD);
uint8_t i = 0;
char c;
DDRB |= _BV(PINB0);
//Main program loop
while (1){
uint8_t b = serial_read_c(&c);
if (i != b){
PORTB |= _BV(PINB0);
i = 0xFF;
_delay_ms(100);
}
i++;
PORTB &= ~_BV(PINB0);
}
}
|
C
|
#include <stdio.h>
#include <math.h>
#define G 9.81
int main(){
float speedBeforeBounce;// ask it to the user
float speedAfterBounce;
float startHeight;
float endHeight;
float eps; // ask it to the user
float *heightPtr = NULL;
int nbrOfBouncing; // ask it to the user
int i;
do{
printf("Type a starting height : ");
scanf("%f",&startHeight);
}while(startHeight < 1);
heightPtr = &startHeight;
do{
printf("Type the bounce coeficient: ");
scanf("%f",&eps);
}while(eps > 0.99 || eps < 0);
printf("Type the number of bouncing : ");
scanf("%d",&nbrOfBouncing);
for(i = 0; i < nbrOfBouncing; i++){
//printf("Bouncing number %d\n",i);
speedBeforeBounce = sqrt(2*(*heightPtr)*G);
speedAfterBounce = eps * speedBeforeBounce;
*heightPtr = pow(speedAfterBounce,2) / (2*G);
}
printf("The height after %d bounce is %.2f\n",nbrOfBouncing,*heightPtr);
return 0;
}
|
C
|
#include<stdio.h>
float c,k,f;
int main()
{
printf("introduce una temperatura en °C: ");
scanf("%f",&c);
k = c+273.15;
f = (c*1.8)+32;
c = (f-32)/1.8;
printf("la temperatura en °k es: %f\n",k);
printf("la temperatura en °F es: %f\n",f);
printf("la temperatura en °C es: %f\n",c);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
typedef int ElemType;
int is_even(int n){
return (n % 2 == 0) ? 1 : 0;
}
int isBadserial(ElemType arr[],int start){
if(arr[start] == arr[start+1] && arr[start] == arr[start+2]){
return 1;
}else{
return 0;
}
}
void getKey(ElemType arr[],int start,int *k){
if(arr[start] == arr[start+1]){
arr[(*k)++] = arr[start];
}else if(arr[start] == arr[start+2]){
arr[(*k)++] = arr[start];
}else if(arr[start+1] == arr[start+2]){
arr[(*k)++] = arr[start+1];
}
}
int find_key_elem(ElemType arr[],int n,ElemType *elem){
int k,i;
int flag = 1;
if(n == 1){
*elem = arr[0];
return 1; //the key exists
}
if(n == 0){
*elem = 0;
return 0; //the key doesn't exist
}
k = 0;
if(is_even(n)){
for(i=0;i<n;i+=2){
if(arr[i] == arr[i+1]){
arr[k++] = arr[i]; //candidate element
}
}
return find_key_elem(arr,k,elem);
}else{ //odd
i = 0;
while(n > 0){
if(flag){ //haven't handled the group with three elements
if(isBadserial(arr,i)){ //three elements starting from i are equal
arr[k++] = arr[i]; //candidate element
i += 2;
n -= 2; //remain elements
}else{
getKey(arr,i,&k); //get the key from three elements
i += 3;
n -= 3;
flag = 0; //having handled the group with three element
}//if isBadserial
}else{//if flag
if(arr[i] == arr[i+1]){
arr[k++] = arr[i];
}
i += 2;
n -= 2;
}//if flag
}//while n
return find_key_elem(arr,k,elem);
}//if is_even
}
int main(){
ElemType arr[100],elem;
int i,n;
scanf("%d",&n);
for(i=0;i<n;i++){
scanf("%d",&arr[i]);
}
if(find_key_elem(arr,n,&elem)){
printf("key elem is %d\n",elem);
}else{
printf("no key in the arr\n");
}
return 0;
}
|
C
|
#include<stdio.h>
struct Martial {
int id;
char name[30];
int type;
int count;
};
struct Hero {
int id;
char name[30];
struct Martial martial;
char sex[20];
};
int main(int argc, char *argv[])
{
struct Hero hero = {1, "孙建春", {1, "少林", .count=10}, "男"};
printf("-------英雄属性-------\nID:\t%d\n姓名:\t%s\n派别:\t%s\n性别:\t%s\n", hero.id, hero.name, hero.martial.name, hero.sex);
return 0;
}
|
C
|
/*
** EPITECH PROJECT, 2019
** bootstrap_world
** File description:
** array_len.c
*/
#include <stdlib.h>
size_t array_len(void *array)
{
size_t len = 0;
void **ari_array = (void **)array;
if (!ari_array)
return (0);
while (ari_array[len])
len++;
return (len);
}
|
C
|
#define SUCCESS 0
#define INVALID_NULL_POINTER -1
#define OUT_OF_RANGE -2
typedef struct TStack TStack;
TStack *stack_create(int max); //Cria a pilha
int stack_free(TStack *st); //Libera a pilha
int stack_push(TStack *st, char a); //Insere na pilha (por ser um vetor, insere na ultima posição)
int stack_pop(TStack *st); //Remove um elemento (por ser um vetor, remove na ultima posição)
int stack_top(TStack *st, char *a); //Retorna o elemento que esta no topo da pilha
int stack_size(TStack *st); //Tamanho da pilha
int stack_empty(TStack *st); //Retorna 0 se a pilha esta vazia e retorna 1 caso contrario
|
C
|
#include "uls.h"
static void parse_year(time_t time,t_time *parsed_time, char *date) {
parsed_time->year = mx_strnew(4);
for (int i = 0; i < 4; i++)
parsed_time->year[i] = date[i + 20];
parsed_time->r_time = time;
}
t_time *mx_parse_ctime(time_t time, t_flags *flags) {
t_time *parsed_time = (t_time *)malloc(sizeof(t_time));
char *date = ctime(&time);
int i = 0;
parsed_time->mmdd = mx_strnew(6);
for (i = 0; i < 6; i++)
parsed_time->mmdd[i] = date[i + 4];
if (flags->f_tt) {
parsed_time->time = mx_strnew(8);
for (i = 0; i < 8; i++)
parsed_time->time[i] = date[i + 11];
}
else {
parsed_time->time = mx_strnew(5);
for (i = 0; i < 5; i++)
parsed_time->time[i] = date[i + 11];
}
parse_year(time, parsed_time, date);
return parsed_time;
}
|
C
|
/* Checks if type is 'c'/string , 'i'/integer or 'f'/float and if the length
is compatible with the given type */
int checkTypeLength( char type, int length ){
switch( type ){
case 'i':
case 'f':
if ( length != 4 ){
return -1; /* incompatible length */
}
break;
case 'c':
if ( length < 1 || length > 255 ){
return -1; /* incompatible length */
}
break;
default : /* invalid type */
return -1;
}
return 1;
}
/* Check if min <= number <= max */
int checkNumberLimits( int number, int min, int max ){
if( (number >= min) && (number <= max) ){
return 1;
}
else{
return -1;
}
}
|
C
|
/*
$ g++ server.c -o server
$ ./server
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <errno.h>
#include <string.h>
#include <arpa/inet.h>
#include <unistd.h>
struct item
{
int id;
char n[100];
int p;
int q;
};
int main(int argc, char *argv[])
{
int ssock, csock;
FILE *f;
struct item a;
int i = 0, n = -1;
unsigned int len;
int item_id, q;
struct sockaddr_in server, client;
if ((ssock = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
perror("socket: is not created");
exit(-1);
}
server.sin_family = AF_INET;
server.sin_port = htons(10000);
server.sin_addr.s_addr = INADDR_ANY;
bzero(&server.sin_zero, 0);
len = sizeof(struct sockaddr_in);
if ((bind(ssock, (struct sockaddr *)&server, len)) == -1)
{
perror("bind: ");
exit(-1);
}
if ((listen(ssock, 5)) == -1)
{
perror("listen: ");
exit(-1);
}
if ((csock = accept(ssock, (struct sockaddr *)&client, &len)) == -1)
{
perror("accept: ");
exit(-1);
}
recv(csock, &item_id, sizeof(item_id), 0);
recv(csock, &q, sizeof(q), 0);
f = fopen("item.txt", "r");
while (fscanf(f, "%d %s %s %d", &a.id, &a.n, &a.p, &a.q) != EOF)
{
if (a.id == item_id)
{
if (a.q >= q)
n = 1;
break;
}
}
send(csock, &n, sizeof(n), 0);
return 0;
}
|
C
|
/*
* Queue.c
*
* Created on: Feb 4, 2016
* Author: Paras
*/
# include <stdio.h>
int Q[5];
int front = -1;
int rear = -1;
int N = sizeof(Q)/sizeof(int);
int isEmpty(){
if (front == -1 && rear == -1) return 1;
else return 0;
}
int isFull(){
if ((rear+1)%N == front) return 1;
else return 0;
}
void enqueue(int x){
if (isFull()) return;
else if (isEmpty()){
front = rear = 0;
}
else{
rear = (rear+1)%N;
}
Q[rear] = x;
}
void dequeue(){
if (isEmpty()) return;
else if (front == rear){
front = rear = -1;
}
else{
front = (front+1)%N;
}
}
int frontQ(){
return Q[front];
}
void printQ(){
if (isEmpty()){
printf("Queue is empty.");
return;
}
printf("Here is your queue: ");
if (front == rear){
printf("%d", Q[front]);
}
else if(isFull()){
int idx = front;
for (int i=0; i < N; i++){
printf("%d", Q[idx]);
idx = (idx+1)%N;
}
}
else{
for (int i = front; i != (rear+1)%N; i=(i+1)%N){
printf("%d", Q[i]);
}
}
printf("\n");
return;
}
int main(){
enqueue(1);
enqueue(2);
enqueue(3);
enqueue(4);
dequeue();
dequeue();
enqueue(5);
enqueue(6);
printQ();
printf("%d", frontQ());
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include "quicksort.h"
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <sys/time.h>
void imprimeArreglo(int*,int);
int* crearArregloAleatorio(int);
int main(int argc, char **argv)
{
int i;
int* arr;
//para tener excel con quicksort recursivo habilitar la linea 21 y comentar '//' linea 22
//ademas habilitar linea 35 y comentar '//' linea 36
int file = open("quicksort_recursivo.csv", O_WRONLY | O_CREAT | O_TRUNC);
//int file = open("quicksort_iterativo.csv", O_WRONLY | O_CREAT | O_TRUNC);
char str[50];
struct timeval t1, t2;
double tiempo;
int n = 100;
//para mas datos en lugar de i<100 poner ejm i < 1000
for(i = 0; i < 6000; i++){
sprintf(str, "%d;", n);
write(file, str, strlen(str));
arr = crearArregloAleatorio(n);
gettimeofday(&t1, NULL);
quicksort_recursivo(arr,0,n-1);
//quicksort_iterativo(arr,n);
gettimeofday(&t2, NULL);
tiempo = (t2.tv_sec - t1.tv_sec)*1000 + (t2.tv_usec - t1.tv_usec)/1000.0;
sprintf(str, "%f\n", tiempo);
write(file, str, strlen(str));
free(arr);
n += 100;
}
close(file);
return 0;
}
void imprimeArreglo(int* arr, int n){
int i;
for(i = 0; i < n; i++){
printf("%d\t",arr[i]);
}
printf("\n");
}
int* crearArregloAleatorio(int n){
int* aux = (int*) malloc(sizeof(int) * n);
int i;
srand(time(0));
for(i = 0; i < n; i++){
aux[i] = rand();
}
return aux;
}
|
C
|
/* Autor : Alex Alves
Programa para calculo em arvore
*/
#include <stdio.h>
#include <string.h>
#include <mpi.h>
int main(void) {
int size; // quantidade maxima de processos
int rank; // numero do processo atual
int valor[8],local,divisor=2,difference=1,soma;
MPI_Status stat; // guarda o status
// Valores iniciais para cada processo
valor[0]= 5,valor[1]=2,valor[2]=-1, valor[3]= -3 ;
valor[4]= 6 , valor[5]= 5, valor[6]= -7, valor[7]=2;
// Inicia o MPI
MPI_Init(NULL, NULL);
// Pega o numero total de processos
MPI_Comm_size(MPI_COMM_WORLD, &size);
// pega o numero do processo atual
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
while( divisor<= 8) {
for(int IndiceCore=0;IndiceCore<8 ;IndiceCore= IndiceCore+divisor) {
if(rank==(IndiceCore+difference)){
//so ocorre na primeira linha da arvore
// local = Valor[IndiceCore+diferenca];
MPI_Send(&valor[IndiceCore+difference],1,MPI_INT,IndiceCore,0,MPI_COMM_WORLD);
printf(" Sou o processo %d enviei pro %d\n ",rank, IndiceCore);
}else if(rank==IndiceCore) {
// rank pares
//I_Reduce(&valor[IndiceCore],&soma,1,MPI_INT,MPI_SUM,0,MPI_COMM_WORLD);
MPI_Recv(&local,1,MPI_INT,IndiceCore+difference,0,MPI_COMM_WORLD,&stat);
valor[IndiceCore]=valor[IndiceCore]+local;
printf(" Sou o processo %d recebi o valor %d apos a soma ficou %d\n",rank,local, valor[IndiceCore]);
}
// MPI_Send(&Valores[i],1,MPI_INT,destino,0,MPI_COMM_WORLD);
//Core( IndiceCore) = Core( IndiceCore + difference);
}
divisor = divisor*2;
difference = difference *2;
}
if(rank==0){
printf("O processo %d terminou com o valor %d\n",rank,valor[0 ]);
}
//finalisa o MPI
MPI_Finalize();
return 0;
}
|
C
|
#include "ccv.h"
#include <sys/time.h>
unsigned int get_current_time()
{
struct timeval tv;
gettimeofday(&tv, 0);
return tv.tv_sec * 1000 + tv.tv_usec / 1000;
}
float __ccv_mod_2pi(float x)
{
while (x > 2 * CCV_PI)
x -= 2 * CCV_PI;
while (x < 0)
x += 2 * CCV_PI;
return x;
}
int main(int argc, char** argv)
{
ccv_dense_matrix_t* image = 0;
ccv_unserialize(argv[1], &image, CCV_SERIAL_GRAY | CCV_SERIAL_ANY_FILE);
unsigned int elapsed_time = get_current_time();
ccv_sift_param_t param;
param.noctaves = 3;
param.nlevels = 6;
param.up2x = 1;
param.edge_threshold = 10;
param.norm_threshold = 0;
param.peak_threshold = 0;
ccv_array_t* keypoints = 0;
ccv_sift(image, &keypoints, 0, 0, param);
printf("%d\n", keypoints->rnum);
ccv_dense_matrix_t* imx = ccv_dense_matrix_new(image->rows, image->cols, CCV_8U | CCV_C1, 0, 0);
memset(imx->data.ptr, 0, imx->rows * imx->step);
int i;
for (i = 0; i < keypoints->rnum; i++)
{
ccv_keypoint_t* kp = (ccv_keypoint_t*)ccv_array_get(keypoints, i);
int ix = (int)(kp->x + 0.5);
int iy = (int)(kp->y + 0.5);
imx->data.ptr[ix + iy * imx->step] = 255;
}
int len;
ccv_serialize(imx, "keypoint.png", &len, CCV_SERIAL_PNG_FILE, 0);
ccv_matrix_free(imx);
printf("elpased time : %d\n", get_current_time() - elapsed_time);
ccv_matrix_free(image);
ccv_garbage_collect();
image = 0;
ccv_unserialize("keypoint.png", &image, CCV_SERIAL_GRAY | CCV_SERIAL_ANY_FILE);
memset(image->data.ptr, 0, image->step * image->rows);
FILE* frame = fopen("box.frame", "r");
float x, y, s0, s1;
ccv_array_t* gtkp = ccv_array_new(10, sizeof(ccv_keypoint_t));
/*
int gt, dl;
fscanf(frame, "%d %d", >, &dl);
for (i = 0; i < gt; i++)
{
fscanf(frame, "%f %f %f %f", &y, &x, &s0, &s1);
int j;
float dummy;
for (j = 0; j < dl; j++)
fscanf(frame, "%f", &dummy);
ccv_keypoint_t nkp;
nkp.x = x;
nkp.y = y;
nkp.regular.scale = s0;
nkp.regular.angle = s1;
image->data.ptr[(int)(y + 0.5) * image->step + (int)(x + 0.5)] = 255;
ccv_array_push(gtkp, &nkp);
}
*/
while (fscanf(frame, "%f %f %f %f", &x, &y, &s0, &s1) != EOF)
{
image->data.ptr[(int)(y + 0.5) * image->step + (int)(x + 0.5)] = 255;
ccv_keypoint_t nkp;
nkp.x = x;
nkp.y = y;
nkp.regular.scale = s0;
nkp.regular.angle = s1;
ccv_array_push(gtkp, &nkp);
}
fclose(frame);
ccv_serialize(image, "mixkp.png", &len, CCV_SERIAL_PNG_FILE, 0);
int match = 0, angle_match = 0;
for (i = 0; i < keypoints->rnum; i++)
{
ccv_keypoint_t* kp = (ccv_keypoint_t*)ccv_array_get(keypoints, i);
double mind = 10000;
int j, minj = -1;
for (j = 0; j < gtkp->rnum; j++)
{
ccv_keypoint_t* gk = (ccv_keypoint_t*)ccv_array_get(gtkp, j);
if ((gk->x - kp->x) * (gk->x - kp->x) + (gk->y - kp->y) * (gk->y - kp->y) + __ccv_mod_2pi(gk->regular.angle - kp->regular.angle) < mind)
{
minj = j;
mind = (gk->x - kp->x) * (gk->x - kp->x) + (gk->y - kp->y) * (gk->y - kp->y) + __ccv_mod_2pi(gk->regular.angle - kp->regular.angle);
}
}
ccv_keypoint_t* gk = (ccv_keypoint_t*)ccv_array_get(gtkp, minj);
mind = (gk->x - kp->x) * (gk->x - kp->x) + (gk->y - kp->y) * (gk->y - kp->y);
if (mind < 0.05)
{
match++;
if (__ccv_mod_2pi(gk->regular.angle - kp->regular.angle) < 0.1)
angle_match++;
}
}
printf("%.2f%% keypoint matched within 0.05 pixel\n", (float)match * 100.0 / (float)keypoints->rnum);
printf("%.2f%% angle matched within 0.1 radius\n", (float)angle_match * 100.0 / (float)match);
ccv_array_free(keypoints);
ccv_array_free(gtkp);
ccv_matrix_free(image);
ccv_garbage_collect();
return 0;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
int main()
{
int n, *arr,i,j,k;
printf("Enter the number of element in the array-");
scanf("%d",&n);
arr=(int *)malloc(sizeof(n));
printf("Enter the array element-");
for(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(arr[i]==arr[j])
{
for(k=j;k<n;k++)
{
arr[k]=arr[k+1];
}
n=n-1;
}
}
}
printf("The distinct elements are-");
for(i=0;i<n;i++)
{
printf("%d",arr[i]);
}
}
|
C
|
#include <stdio.h>
int is_legal(int net[4][4],int n, int pos){
int x,y;
int i;
x = pos/n;
y = pos%n;
if(net[x][y]>0)
return 0;
i=x;
while(i>0){
i--;
if(net[i][y]==2)
return 0;
if(net[i][y]==1)
break;
}
i=x;
while(i<(n-1)){
i++;
if(net[i][y]==2)
return 0;
if(net[i][y]==1)
break;
}
i=y;
while(i>0){
i--;
if(net[x][i]==2)
return 0;
if(net[x][i]==1)
break;
}
i=y;
while(i<(n-1)){
i++;
if(net[x][i]==2)
return 0;
if(net[x][i]==1)
break;
}
return 1;
}
int find_next(int net[4][4],int n, int pos, int *x, int *y){
for(;pos<=(n*n-1);pos++){
if(is_legal(net,n,pos)){
*x = pos/n;
*y = pos%n;
return 1;
}
}
return 0;
}
int get_most(int net[4][4], int n, int house[8][2], int l){
int min_pos,x,y;
int tmp;
int max=0;
int check=0;
if(l==0)
min_pos = 0;
else
min_pos = n*house[l-1][0] + house[l-1][1] + 1;
while(min_pos<=(n*n-1) && find_next(net,n,min_pos,&x,&y)){
check++;
house[l][0]=x;
house[l][1]=y;
net[x][y]=2;
tmp = get_most(net,n,house,l+1);
max = (tmp>max)?tmp:max;
net[x][y]=0;
min_pos = n*x + y + 1;
}
if(check)
return max+1;
return 0;
}
int get_back(int net[4][4],int n,int house[8][2],int l){
if(l==0)
return 0;
net[house[l-1][0]][net[l-1][1]]=0;
return 1;
}
int main(){
int net[4][4];
int n;
char s[5];
int num=0;
int l=0;
int house_pos[8][2]={0};
int i,j;
while(1){
num = 0;
scanf("%d",&n);
if(!n)
break;
for(i=0;i<n;i++){
scanf("%s",s);
for(j=0;j<n;j++)
net[i][j] = (s[j]=='.')? 0:1;
}
num = get_most(net,n,house_pos,0);
printf("%d\n",num);
}
return 0;
}
|
C
|
/* File: effects.c */
/*
* The lingering spell effects code.
*
* Copyright (c) 2007
* Leon Marrick, Ben Harrison, James E. Wilson, Robert A. Koeneke
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 2. Parts may also be available under the
* terms of the Moria license. For more details, see "/docs/copying.txt".
*/
#include "angband.h"
/*
* Try to find space for a new effect, prepare the first available one.
*/
int effect_prep(void)
{
int i;
/* Get a new effect */
for (i = 0; i < z_info->x_max; i++)
{
/* Effect is not in use */
if (!x_list[i].index) break;
}
/* Effect array is completely filled */
if (i == z_info->x_max) return (-1);
/* We found some space */
else
{
/* Get this effect */
effect_type *x_ptr = &x_list[i];
/* Wipe it */
WIPE(x_ptr, effect_type);
}
/* Return the index */
return (i);
}
/*
* Adjust effects.
*
* Make various tweaks to effects to handle special conditions.
*/
static void adjust_effect(int x_idx)
{
/* Get this effect */
effect_type *x_ptr = &x_list[x_idx];
/* Paranoia -- no tweaking dead effects */
if (!x_ptr->index) return;
/* This effect has already been tweaked */
if (x_ptr->flags & (EF1_TWEAKED)) return;
/*
* Hack^Hack -- as wall spells must move orthogonally, they move
* more slowly when fired diagonally. Adjust both the lifespan
* and the rate of travel to compensate for this.
*/
if (x_ptr->index == EFFECT_WALL)
{
int dist = distance(x_ptr->y0, x_ptr->x0, x_ptr->y1, x_ptr->x1);
int dy = ABS(x_ptr->y0 - x_ptr->y1);
int dx = ABS(x_ptr->x0 - x_ptr->x1);
int diag_factor;
/* No distance */
if (!dy && !dx) return;
/* Get "diagonal factor" */
diag_factor = 10 * dist / MAX(dy, dx);
/* Adjust lifespan */
x_ptr->lifespan = (x_ptr->lifespan * diag_factor + 5) / 10;
/* Adjust rate of travel */
x_ptr->time_delay =
(x_ptr->time_delay * 10 + diag_factor / 2) / diag_factor;
}
/* This effect has been tweaked */
x_ptr->flags |= (EF1_TWEAKED);
}
/*
* Get (one of) the effects impacting the given grid.
*
* The lingering effect code can have multiple entries for a given grid
* at any one time. This may occur due to two different effects zapping
* the grid, or to the grid being zapped between effect turns. As long
* as a character or monster only gets zapped once when they enter a
* grid, regardless of the number of effects in that grid, this isn't a
* problem. If this changes, however, then we have to rewrite. We
* might also have to rebalance.
*/
int effect_grid_idx(int y, int x)
{
/* Start at the last record */
int i = effect_grid_n - 1;
/* Search for the grid (backwards) */
for (; i >= 0; i--)
{
/* We found the grid */
if ((effect_grid[i].y == y) && (effect_grid[i].x == x))
{
/* Return index of effect */
return (effect_grid[i].x_idx);
}
}
/* We did not find the grid -- remove effect marker XXX XXX */
cave_info[y][x] &= ~(CAVE_EFFT);
/* Return "no effect" */
return (-1);
}
/*
* Get the projection type (and thus the graphics) for an effect.
*
* This function is also responsible for cleaning up effect markers. XXX XXX
*/
int effect_grid_proj_type(int y, int x)
{
/* Start at the last record */
int i = effect_grid_n - 1;
/* Search for the grid (backwards) */
for (; i >= 0; i--)
{
/* We found the grid */
if ((effect_grid[i].y == y) && (effect_grid[i].x == x))
{
/* Return projection type of effect in this grid */
return (x_list[effect_grid[i].x_idx].type);
}
}
/* We did not find the grid -- remove effect marker XXX XXX */
cave_info[y][x] &= ~(CAVE_EFFT);
/* Return "no projection type" */
return (-1);
}
/*
* Sorting hook -- comp function -- array of elements four bytes in size.
*/
static bool ang_sort_comp_hook_effect_grids(const void *u, const void *v, int a, int b)
{
effect_grid_type *x_grid = (effect_grid_type*)(u);
/* Unused parameter */
(void)v;
/* Sort by y, then by x, in descending order */
if (x_grid[a].y > x_grid[b].y) return (TRUE);
if (x_grid[a].y < x_grid[b].y) return (FALSE);
return (x_grid[a].x >= x_grid[b].x);
}
/*
* Sorting hook -- swap function -- array of elements four bytes in size.
*/
static void ang_sort_swap_hook_effect_grids(void *u, void *v, int a, int b)
{
effect_grid_type *x_grid = (effect_grid_type*)(u);
effect_grid_type temp_grid;
/* Unused parameter */
(void)v;
/* Swap records */
COPY(&temp_grid, &x_grid[a], effect_grid_type);
COPY(&x_grid[a], &x_grid[b], effect_grid_type);
COPY(&x_grid[b], &temp_grid, effect_grid_type);
}
/*
* Remove all grids belonging to a given effect from the effect grid
* array, then sort and compact it.
*/
static void optimize_effect_array(int x_idx)
{
int i;
/* Remove all of the effect's markers and graphics */
for (i = 0; i < effect_grid_n; i++)
{
/* Get the grid */
effect_grid_type *xg_ptr = &effect_grid[i];
/* Grid belongs to this effect */
if (xg_ptr->x_idx == x_idx)
{
/* Save the grid */
int y = xg_ptr->y;
int x = xg_ptr->x;
/* Wipe this array entry */
WIPE(xg_ptr, effect_grid_type);
/*
* Refresh the graphics, remove marker if this was the
* only effect impacting this grid.
*/
lite_spot(y, x);
}
}
/* Select the sort method */
ang_sort_comp = ang_sort_comp_hook_effect_grids;
ang_sort_swap = ang_sort_swap_hook_effect_grids;
/* Sort the array (descending order by grid location) */
ang_sort(effect_grid, 0, effect_grid_n);
/* Work from the end of the array, compacting as we go */
for (i = effect_grid_n - 1; i >= 0; i--)
{
/* Ignore all records with zero y-values */
if (!effect_grid[i].y) effect_grid_n--;
}
}
/*
* Effect zaps a grid with lingering effect. Used for all effects that
* need to display graphics and affect monsters/the character/the dungeon
* between turns.
*
* Return "grid was projectable".
*/
bool do_effect_linger(int x_idx, int y, int x)
{
/* Get this effect */
effect_type *x_ptr = &x_list[x_idx];
/* Basic projection flags */
u32b flg = PROJECT_JUMP | PROJECT_KILL | PROJECT_ITEM | PROJECT_GRID;
/* Get caster (who gets exp, etc.) */
int who = ((x_ptr->flags & (EF1_CHARACTER)) ? -1 : 0);
/* Optional flags */
if (x_ptr->flags)
{
/* Affect only evil */
if (x_ptr->flags & (EF1_HURT_EVIL)) p_ptr->proj_mon_flags = (RF3_EVIL);
/* Hurt the character */
if (x_ptr->flags & (EF1_HURT_PLAY)) flg |= (PROJECT_PLAY);
}
/* Usually, do not affect non-projectable terrain */
if (!cave_project_bold(y, x) && !(flg & (PROJECT_PASS))) return (FALSE);
/* We have not run out of space in the effect grid array */
if (effect_grid_n < EFFECT_GRID_MAX-1)
{
/* Mark the grid */
cave_info[y][x] |= (CAVE_EFFT);
/* Store location and effect index */
effect_grid[effect_grid_n].y = y;
effect_grid[effect_grid_n].x = x;
effect_grid[effect_grid_n].x_idx = x_idx;
/* Another entry in the array */
effect_grid_n++;
}
/* Has hit the character */
if ((y == p_ptr->py) && (x == p_ptr->px))
{
/* Print messages XXX */
switch (x_ptr->type)
{
case GF_ACID: msg_print("You are covered in acid!"); break;
case GF_ELEC: msg_print("You are struck by lightning!"); break;
case GF_FIRE: msg_print("You are enveloped in fire!"); break;
case GF_COLD: msg_print("You are very cold!"); break;
case GF_POIS: msg_print("You are surrounded by poison!"); break;
case GF_PLASMA: msg_print("You are enveloped in electric fire!"); break;
case GF_HELLFIRE: msg_print("You are enveloped by Udun-fire!"); break;
case GF_ICE: msg_print("You are hit by shards of ice!"); break;
default: msg_print("You are hit!"); break;
}
}
/* Practice a skill */
if (x_ptr->practice_skill) skill_being_used = x_ptr->practice_skill;
/* Cast the spell */
(void)project(who, 0, y, x, y, x, x_ptr->power, x_ptr->type, flg, 0, 0);
/* Display lingering spell colors (require ability to see or illuminated effect in LOS) */
if ((player_can_see_bold(y, x)) ||
((x_ptr->flags & (EF1_SHINING)) && (player_has_los_bold(y, x))))
{
/* Redraw this grid */
lite_spot(y, x);
}
/* Success */
return (TRUE);
}
/*
* Process an individual effect.
*/
static void process_effect(int x_idx)
{
/* Get this effect */
effect_type *x_ptr = &x_list[x_idx];
int i, j, axis;
int y, x;
int y0, x0;
int grids = 0;
bool notice = FALSE; /* Assume nothing noticed */
/* Paranoia -- no processing dead effects */
if (!x_ptr->index) return;
/* Count down to next turn, return if not yet ready */
if (--x_ptr->time_count > 0) return;
/* Reset count */
x_ptr->time_count = x_ptr->time_delay;
/* If the effect has recently been "born", make various tweaks to it */
if (x_ptr->age == 0) adjust_effect(x_idx);
/* Clear graphics and effect markers from last iteration of this effect */
optimize_effect_array(x_idx);
/* Effects eventually "die" */
if (x_ptr->age >= x_ptr->lifespan)
{
/* Special message for clouds of death (they have no graphics) */
if (x_ptr->index == EFFECT_DEATH_CLOUD)
{
msg_print("The cloud of death dissipates.");
}
/* Effect is "dead" */
x_ptr->index = 0;
return;
}
/* Standard lingering clouds */
if (x_ptr->index == EFFECT_IRREGULAR_CLOUD)
{
/* We always fire a star and refresh the graphics */
u32b flg = PROJECT_STAR | PROJECT_BOOM;
int dam = 0;
int rad = x_ptr->power2;
int typ = x_ptr->type;
y = x_ptr->y0;
x = x_ptr->x0;
/* Add the kill flags */
flg |= PROJECT_GRID | PROJECT_ITEM | PROJECT_KILL | PROJECT_PLAY;
/* Damage equals power */
dam = x_ptr->power;
/* Cast a star */
(void)project(-1, rad, y, x, y, x, dam, typ, flg, 0, 0);
}
/* Advancing walls */
else if (x_ptr->index == EFFECT_WALL)
{
/* Get the direction of travel (angular dir is 2x this) */
int major_axis =
get_angle_to_target(x_ptr->y0, x_ptr->x0, x_ptr->y1, x_ptr->x1, 0);
/* Get the length of the wall on either side of the major axis */
int spread = x_ptr->power2;
/* Store target grid */
y = x_ptr->y1;
x = x_ptr->x1;
/* Calculate the projection path -- require orthogonal movement */
(void)project_path(99, x_ptr->y0, x_ptr->x0,
&y, &x, PROJECT_PASS | PROJECT_THRU | PROJECT_ORTH);
/* Require a working projection path */
if (path_n > x_ptr->age)
{
/* Remember delay factor */
int old_delay = op_ptr->delay_factor;
int zaps = 0;
/* Get center grid (walls travel one grid per turn) */
y0 = GRID_Y(path_g[x_ptr->age]);
x0 = GRID_X(path_g[x_ptr->age]);
/* Count grid */
grids++;
/* Set delay to half normal */
op_ptr->delay_factor /= 2;
/*
* If the center grid is both projectable and in LOS
* from the origin of the effect, zap it.
*/
if ((cave_project_bold(y0, x0)) &&
(los(x_ptr->y0, x_ptr->x0, y0, x0)))
{
(void)do_effect_linger(x_idx, y0, x0);
zaps++;
}
/* Notice visibility */
if (player_can_see_bold(y0, x0)) notice = TRUE;
/* If this wall spreads out from the origin, */
if (spread >= 1)
{
/* Get the directions of spread (angular dir is 150% of this) */
int minor_axis1 = (major_axis + 60) % 240;
int minor_axis2 = (major_axis + 180) % 240;
/* Process the left, then right-hand sides of the wall */
for (i = 0; i < 2; i++)
{
if (i == 0) axis = minor_axis1;
else axis = minor_axis2;
/* Get the target grid for this side */
get_grid_using_angle(axis, y0, x0, &y, &x);
/* If we have a legal target, */
if ((y != y0) || (x != x0))
{
/* Calculate the projection path */
(void)project_path(spread, y0, x0, &y, &x,
PROJECT_PASS | PROJECT_THRU);
/* Check all the grids */
for (j = 0; j < path_n; j++)
{
/* Get grid */
y = GRID_Y(path_g[j]);
x = GRID_X(path_g[j]);
/*
* If this grid is both projectable and in LOS
* from the origin of the effect, zap it.
*/
if ((cave_project_bold(y, x)) &&
(los(x_ptr->y0, x_ptr->x0, y, x)))
{
(void)do_effect_linger(x_idx, y, x);
zaps++;
}
/* Notice visibility */
if (player_can_see_bold(y, x)) notice = TRUE;
}
}
}
}
/* Kill wall if nothing got zapped this turn */
if (zaps == 0)
{
if (notice) msg_print("The spell fizzles out.");
x_ptr->age = 250;
}
/* Restore standard delay */
op_ptr->delay_factor = old_delay;
}
/* No working projection path -- kill the wall */
else
{
x_ptr->age = 250;
}
}
/* Seeker vortexes */
else if (x_ptr->index == EFFECT_SEEKER_VORTEX)
{
int dir;
int ty = 0, tx = 0;
/* Check around (and under) the vortex */
for (dir = 0; dir < 9; dir++)
{
/* Extract adjacent (legal) location */
y = x_ptr->y0 + ddy_ddd[dir];
x = x_ptr->x0 + ddx_ddd[dir];
/* Count passable grids */
if (cave_passable_bold(y, x)) grids++;
}
/*
* Vortexes only seek in open spaces. This makes them useful in
* rooms and not too powerful in corridors.
*/
if (grids >= 5) i = 85;
else if (grids == 4) i = 50;
else i = 0;
/* Seek out monsters */
if (rand_int(100) < i)
{
/* Try to get a target (nearest or next-nearest monster) */
get_closest_los_monster(randint(2), x_ptr->y0, x_ptr->x0,
&ty, &tx, FALSE);
}
/* No valid target, or monster is in an impassable grid */
if (((ty == 0) && (tx == 0)) || (!cave_passable_bold(ty, tx)))
{
/* Move randomly */
dir = randint(9);
}
/* Valid target in passable terrain */
else
{
/* Get change in position from current location to target */
int dy = x_ptr->y0 - ty;
int dx = x_ptr->x0 - tx;
/* Calculate vertical and horizontal distances */
int ay = ABS(dy);
int ax = ABS(dx);
/* We mostly want to move vertically */
if (ay > (ax * 2))
{
/* Choose between directions '8' and '2' */
if (dy > 0) dir = 8;
else dir = 2;
}
/* We mostly want to move horizontally */
else if (ax > (ay * 2))
{
/* Choose between directions '4' and '6' */
if (dx > 0) dir = 4;
else dir = 6;
}
/* We want to move up and sideways */
else if (dy > 0)
{
/* Choose between directions '7' and '9' */
if (dx > 0) dir = 7;
else dir = 9;
}
/* We want to move down and sideways */
else
{
/* Choose between directions '1' and '3' */
if (dx > 0) dir = 1;
else dir = 3;
}
}
/* Convert dir into a grid */
for (i = 0; i < 100; i++)
{
/* Extract adjacent (legal) location */
y = x_ptr->y0 + ddy[dir];
x = x_ptr->x0 + ddx[dir];
/* Require passable grids */
if (cave_passable_bold(y, x))
{
/* Try not to stay in place */
if ((y != x_ptr->y0) || (x != x_ptr->x0)) break;
}
/* Move randomly */
dir = randint(9);
}
/* Note failure */
if (i == 100)
{
y = x_ptr->y0;
x = x_ptr->x0;
}
/* Move the vortex */
x_ptr->y0 = y;
x_ptr->x0 = x;
/* Zap the new grid */
(void)do_effect_linger(x_idx, x_ptr->y0, x_ptr->x0);
}
/* Clouds of death */
else if (x_ptr->index == EFFECT_DEATH_CLOUD)
{
/* Player's current location is not the center of the cloud */
if ((p_ptr->py != x_ptr->y0) || (p_ptr->px != x_ptr->x0))
{
int dist = distance(p_ptr->py, p_ptr->px, x_ptr->y0, x_ptr->x0);
/* If distance between the two is > 1, weaken the cloud */
if (dist > 1)
{
/* Too much disruption -- kill the cloud */
if (dist >= x_ptr->power)
{
msg_print("Your violent motions tear apart the cloud of death.");
x_ptr->age = 250;
return;
}
/* Weaken the cloud */
else
{
x_ptr->power -= dist;
}
}
/* Re-center the cloud */
x_ptr->y0 = p_ptr->py;
x_ptr->x0 = p_ptr->px;
}
/* Fire a star-shaped cloud of death */
fire_star(GF_DEATH_CLOUD, 0, randint(x_ptr->power), x_ptr->power2);
}
/* Effects age */
x_ptr->age++;
}
/*
* Process effects.
*/
void process_effects(void)
{
int i;
/* Process all effects */
for (i = 0; i < z_info->x_max; i++)
{
/* Get this effect */
effect_type *x_ptr = &x_list[i];
/* Skip empty effects */
if (!x_ptr->index) continue;
/* Process effect */
process_effect(i);
}
}
|
C
|
/*
Name: <your name here>
Date: April 5, 2021
Desc: <fill me in>
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h> // Enables use of time()
#define MAX_SIZE 100
int getValuesFromUser(int array[]){
printf("Enter values with enter, with -99 as the ending signal.\n");
for(int i = 0; i < MAX_SIZE; i++){
int temp = 0;
scanf("%d", &temp);
if(temp == -99){
return i; // Return the current length of numbers they entered
}else{
array[i] = temp;
}
}
return MAX_SIZE;
}
int getRandomValues(int array[]){
int numValues = 0;
int minRand = 0;
int maxRand = 0;
printf("How many random numbers do you want? (1..100)\n");
scanf("%d", &numValues);
while(numValues < -1 || numValues > 100){
printf("Invalid entry, enter a value from 1..100\n");
scanf("%d", &numValues);
}
printf("What is the minimum random number you want?\n");
scanf("%d", &minRand);
printf("What is the maximum random number you want?\n");
scanf("%d", &maxRand);
for(int i = 0; i < numValues; i++){
array[i] = (rand() % (maxRand - minRand + 1)) + minRand;
}
return numValues;
}
void printArray(int array[], int length){
printf("\nArray contains: ");
for(int i = 0; i < length; i++){
printf("%d ", array[i]);
}
printf("\n");
}
void rotateArray(int array[], int length){
// We need length to know where to wrap
int last = array[length - 1];
for(int i = length - 2; i >= 0; i--){
array[i+1] = array[i];
}
array[0] = last;
}
void multiplyArray(int array[]){
int mult_value = 0;
printf("What do you want to multiply every element by?\n");
scanf("%d", &mult_value);
// I guess it's fine to multiply the entire array
for(int i = 0; i < MAX_SIZE; i++){
array[i] = array[i] * mult_value;
}
}
int main(){
srand((int)time(0)); // Unique seed
int choice = 0;
int values[MAX_SIZE];
int current_size = 0;
do {
printf("\nWhat do you want to do?\n");
printf("1) Exit\n");
printf("2) Enter up to 100 integers, end with -99.\n");
printf("3) Initialize with random numbers.\n");
printf("4) Print the array of values.\n");
printf("5) Rotate right by 1.\n");
printf("6) Multiply ?\n");
scanf("%d", &choice);
if (choice < 1 || choice > 6){
printf("Invalid choice!\n");
} else if(choice == 1){ // Exit
printf("Exiting program.\n");
} else if(choice == 2){ // Enter Values - Use -99 to signal the end of values.
current_size = getValuesFromUser(values);
} else if(choice == 3){ // Random Values - allow user to pick how many to fill with, min, and max rand should work with.
current_size = getRandomValues(values);
} else if(choice == 4){ // Print - However you want.
printArray(values, current_size);
} else if(choice == 5){ // Rotate - Move all values to the right, with the last element going to the first spot.
rotateArray(values, current_size);
} else if(choice == 6){ // Multiply - Allow the user to enter a number and change the list so the result
// is the original number multiplied by whatever they provided.
multiplyArray(values);
}
} while (choice != 1);
printf("Thanks for playing!\n");
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/time.h>
#define SIZE (512 * 1024 * 1024)
int main()
{
struct timeval begin, now;
double f0, f1, f2;
double sum;
char *buf;
int i;
gettimeofday(&begin, NULL); f0 = begin.tv_sec * 1000000 + begin.tv_usec;
printf("BEGIN:\t%lu:%lu\n", begin.tv_sec, begin.tv_usec);
buf = malloc(SIZE);
if (buf == NULL) {
printf("malloc failed\n");
exit(1);
}
gettimeofday(&now, NULL);
f1 = now.tv_sec * 1000000 + now.tv_usec;
printf("NOW:\t%lu:%lu\n", now.tv_sec, now.tv_usec);
for (i = 0; i < 20; i++) {
gettimeofday(&now, NULL);
f1 = now.tv_sec * 1000000 + now.tv_usec;
memset(buf, 0, SIZE);
gettimeofday(&now, NULL);
f2 = now.tv_sec * 1000000 + now.tv_usec;
printf("memset time: %.2f microsec\n", f2 - f1);
sum += f2 - f1;
}
printf("avg. memset time: %.2f microsec\n", sum / 20);
free(buf);
}
|
C
|
#include <stdio.h>
// Will test if an integer is even or odd.
// Returns 1 if odd and 0 if even. Will also print result to screen.
int is_odd(int num){
// Odd, not divisible by two
if(num % 2) {
printf("%d is odd\n", num);
return 1;
}
// Even, divisible by two
else {
printf("%d is even\n", num);
return 0;
}
}
// Will print which day the integer day corresponds to.
void print_day(int day){
switch(day){
case 1:
printf("Day = %d ==> It's Monday! \n", day);
break;
case 2:
printf("Day = %d ==> It's Tuesday! \n", day);
break;
default:
printf("Day = %d ==> Don't know which day it is... \n", day);
}
}
int main(void) {
int age = 23;
printf("Bjørn Fjukstad is %d years old \n", age);
int day;
int days_in_a_week = 7;
// Fjern /* og */ for å teste ut koden
// gjennom bruk av en for-løkke.
/*
for(day = 1; day <= days_in_a_week; day++){
print_day(day);
}
*/
day = 1;
while(day <= days_in_a_week){
print_day(day);
day++; // day = day + 1 , day += 1 is equivalent
}
int number;
int max_number = 50;
for(number = 1; number <= max_number; number++){
is_odd(number);
}
return 0;
}
|
C
|
/*
** echo.c for 42sh in /u/all/bereng_p/cu/rendu/SVN/svn/current/builtins
**
** Made by philippe berenguel
** Login <[email protected]>
**
** Started on Sat Mar 20 21:56:13 2010 philippe berenguel
** Last update Sat Mar 20 22:12:17 2010 philippe berenguel
*/
#include <stdlib.h>
#include <unistd.h>
#include "parser.h"
#include "lib_includes/aff.h"
#include "lib_includes/strings.h"
#include "lib_includes/free.h"
#include "lib_includes/xfunctions.h"
static const char gl_echo[][2] = {
{'\\', '\\'},
{'\a', 'a'},
{'\b', 'b'},
{'\f', 'f'},
{'\n', 'n'},
{'\r', 'r'},
{'\t', 't'},
{'\v', 'v'},
{0, 0}
};
static void echo_arg(char *arg, int *options, int *i)
{
int e;
options[0] = 0;
options[1] = 0;
if (arg == NULL || arg[0] != '-')
return ;
e = 1;
while (arg[e] != '\0')
{
if (arg[e] == 'n')
options[0] = 1;
else if (arg[e] == 'E')
options[1] = 0;
else if (arg[e] == 'e')
options[1] = 1;
else
{
options[0] = 0;
options[1] = 0;
return ;
}
e++;
}
(*i)++;
}
static void print_metachar(char *str)
{
int i;
i = 0;
while (gl_echo[i][0] != 0 && str[1] != gl_echo[i][1])
i++;
if (gl_echo[i][0] != 0)
my_putchar(gl_echo[i][0]);
else
xwrite(STDOUT_FILENO, str, 2);
}
int echo(char **cmd)
{
int i;
int e;
int options[2];
i = 1;
e = -1;
echo_arg(cmd[1], options, &i);
while (cmd[i])
{
if (e != -1)
my_putchar(' ');
e = 0;
while (cmd[i][e] != '\0')
{
if (options[1] == 1 && cmd[i][e] == '\\')
print_metachar(&cmd[i][e++]);
else
my_putchar(cmd[i][e]);
e++;
}
i++;
}
if (options[0] == 0)
my_putchar('\n');
return (EXIT_SUCCESS);
}
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include<string.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <pthread.h>
#include <errno.h>
#include <time.h>
#include <getopt.h>
char coins[21] = "0000000000XXXXXXXXX\0";
pthread_mutex_t lockArr = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t lockArr3[20];
int n=10000,p=100;
//method1
static void* person_str1(void *arg){
int res = 0;
if(pthread_mutex_lock(&lockArr)){
fprintf(stderr, "Lock failed in %s %s \n", __func__, strerror(errno));
}
//printf("job started : %s\n",coins);
for (int i = 0;i<n;i++){
for (int j =0;j<20;j++){
if (res = rand()%2){
coins[j] = '0';
}
else{
coins[j] = 'X';
}
}
}
//printf("job finished : %s\n",coins);
if (pthread_mutex_unlock(&lockArr)){
fprintf(stderr, "Unlock failed in %s %s \n", __func__, strerror(errno));
}
return NULL;
}
//method 2
static void* person_str2(void *arg){
int res = 0;
for (int i = 0;i<n;i++){
if(pthread_mutex_lock(&lockArr)){
fprintf(stderr, "Lock failed in %s %s \n", __func__, strerror(errno));
}
//printf("START %d",i);
for (int j =0;j<20;j++){
if (res = rand()%2){
coins[j] = '0';
}
else{
coins[j] = 'X';
}
}
//printf("STOP %d\n",i);
if (pthread_mutex_unlock(&lockArr)){
fprintf(stderr, "Unlock failed in %s %s \n", __func__, strerror(errno));
}
}
return NULL;
}
//method 3
static void* person_str3(void *arg){
int res = 0;
for (int i = 0;i<n;i++){
for (int j =0;j<20;j++){
if(pthread_mutex_lock(&lockArr3[j])){
fprintf(stderr, "Lock failed in %s %s \n", __func__, strerror(errno));
}
//printf(" Start %d",j);
if (res = rand()%2){
coins[j] = '0';
}
else{
coins[j] = 'X';
}
//printf(" STOP %d\n",j);
if (pthread_mutex_unlock(&lockArr3[j])){
fprintf(stderr, "Unlock failed in %s %s \n", __func__, strerror(errno));
}
}
}
return NULL;
}
//method to run 1st option
int run_meth1(){
int err;
pthread_t thread[p];
clock_t t1,t2;
printf("coins: %s (start - global lock)\n",coins);
t1 = clock();
for (int i=0;i<p;i++){
err = pthread_create(&thread[i],NULL,person_str1,NULL);
if (err){
fprintf(stderr,"failed to create thread: %s\n", strerror(err));
return EXIT_FAILURE;
}
}
for (int i=0;i<p;i++){
if(thread[i]){
err = pthread_join(thread[i],NULL);
if (err){
fprintf(stderr,"failed to join thread: %s\n", strerror(err));
}
}
}
t2 = clock();
printf("coins: %s (end - global lock)\n",coins);
printf("%d threads x %d flips: %f ms\n",p,n,(double)t2-(double)t1);
return EXIT_SUCCESS;
}
//method to run 2nd option
int run_meth2(){
int err;
pthread_t thread[p];
clock_t t1,t2;
printf("coins: %s (start - iteration lock)\n",coins);
t1 = clock();
for (int i=0;i<p;i++){
err = pthread_create(&thread[i],NULL,person_str2,NULL);
if (err){
fprintf(stderr,"failed to create thread: %s\n", strerror(err));
return EXIT_FAILURE;
}
}
for (int i=0;i<p;i++){
if(thread[i]){
err = pthread_join(thread[i],NULL);
if (err){
fprintf(stderr,"failed to join thread: %s\n", strerror(err));
}
}
}
t2 = clock();
printf("coins: %s (end - table lock)\n",coins);
printf("%d threads x %d flips: %f ms\n",p,n,(double)t2-(double)t1);
return EXIT_SUCCESS;
}
//method to run 3rd option
int run_meth3(){
for (int i =0;i<20;i++){
pthread_mutex_init(&lockArr3[i],NULL);
}
int err;
clock_t t1,t2;
pthread_t thread[p];
printf("coins: %s (start - coin lock)\n",coins);
t1 = clock();
for (int i=0;i<p;i++){
err = pthread_create(&thread[i],NULL,person_str3,NULL);
if (err){
fprintf(stderr,"failed to create thread: %s\n", strerror(err));
return EXIT_FAILURE;
}
}
for (int i=0;i<p;i++){
if(thread[i]){
err = pthread_join(thread[i],NULL);
if (err){
fprintf(stderr,"failed to join thread: %s\n", strerror(err));
}
}
}
t2 = clock();
printf("coins: %s (end - coin lock)\n",coins);
printf("%d threads x %d flips: %f ms\n",p,n,(double)t2-(double)t1);
return EXIT_SUCCESS;
}
int main(int argc, char *argv[]){
int opt;
srand(time(NULL));
while((opt = getopt(argc, argv, "n:p:")) > 0){
switch(opt){
case 'n':
if ((n = atoi(optarg)) <= 0) {
fprintf(stderr, "number of consumers must be > 0\n");
exit(EXIT_FAILURE);
}
break;
case 'p':
if ((p = atoi(optarg)) <= 0) {
fprintf(stderr, "number of consumers must be > 0\n");
exit(EXIT_FAILURE);
}
break;
}
}
if (run_meth1() == EXIT_FAILURE){
exit(EXIT_FAILURE);
}
if (run_meth2() == EXIT_FAILURE){
exit(EXIT_FAILURE);
}
if (run_meth3() == EXIT_FAILURE){
exit(EXIT_FAILURE);
}
return EXIT_SUCCESS;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *link;
};
typedef struct node *NODE;
NODE getnode()
{
NODE x;
x=(NODE)malloc(sizeof(NODE));
if(x==NULL)
printf("no memory space left\n");
return x;
}
NODE ifront(NODE root,int ele)
{
NODE temp;
temp=getnode();
temp->data=ele;
temp->link=root;
return temp;
}
void display(NODE root)
{
NODE curr;
if(root==NULL)
{
printf("list empty\n");
}
else
{
for(curr=root; curr!=NULL; curr=curr->link)
{
printf("%d\t",curr->data);
}
printf("\n");
}
}
NODE mergelist(NODE root1,NODE root2)
{
NODE curr1,curr2;
int i=1;
NODE newlist,temp,curr;
if(root1==NULL)
return root2;
if(root2==NULL)
return root1;
curr1=root1;
curr2=root2;
while(curr1!=NULL && curr2!=NULL)
{
if(curr1->data>curr2->data)
{
temp=getnode();
temp->data=curr2->data;
temp->link=NULL;
curr2=curr2->link;
}
else if(curr1->data<curr2->data)
{
temp=getnode();
temp->data=curr1->data;
temp->link=NULL;
curr1=curr1->link;
}
else
{
temp=getnode();
temp->data=curr1->data;
temp->link=NULL;
curr1=curr1->link;
curr2=curr2->link;
}
if(i==1)
{
i++;
newlist=temp;
curr=newlist;
}
else
{
curr->link=temp;
curr=curr->link;
}
}
while(curr1!=NULL)
{
temp=getnode();
temp->data=curr1->data;
temp->link=NULL;
curr->link=temp;
curr=curr->link;
curr1=curr1->link;
}
while(curr2!=NULL)
{
temp=getnode();
temp->data=curr2->data;
temp->link=NULL;
curr->link=temp;
curr=curr->link;
curr2=curr2->link;
}
return newlist;
}
int main()
{
NODE root1=NULL;
NODE root2=NULL;
NODE root=NULL;
int c,ele;
for(;;)
{
printf("enter 1 to insert an element in 1st list\n 2 to insert element in second list\n 3 to merge 2 list\n 4 to display\n");
scanf("%d",&c);
switch(c)
{
case 1:
printf("enter element to be inserted\n");
scanf("%d",&ele);
root1=ifront(root1,ele);
break;
case 2:
printf("enter element to be inserted\n");
scanf("%d",&ele);
root2=ifront(root2,ele);
break;
case 3:
root=mergelist(root1,root2);
break;
case 4:
display(root);
break;
default:
exit(0);
}
}
return 1;
}
|
C
|
#if ! defined( INPUT_STRING_PARSER_ )
#define INPUT_STRING_PARSER_
/***************************************************************************
*
* Mdulo de definio: ISP Input String Parser
*
* Arquivo gerado: input_string_parser.h
* Letras identificadoras: ISP
*
* Autores:
* - hg: Hugo Roque
*
* Histrico de evoluo:
* Verso Autor Data Observaes
* 1 hg 11/nov/2013 Parseia alguns tipos bsicos
*
* Descrio do mdulo
* Mdulo responsvel por parsear representaes de string para as instncias
* das estruturas.
*
***************************************************************************/
#if defined( INPUT_STRING_PARSER_OWN )
#define INPUT_STRING_PARSER_EXT
#else
#define INPUT_STRING_PARSER_EXT extern
#endif
#include "lista.h"
#include "modelo_peca.h"
/***** Declaraes exportadas pelo mdulo *****/
/***********************************************************************
*
* Tipo de dados: ISP Condies de retorno
*
*
* Descrio do tipo
* Condies de retorno das funes exportadas.
*
***********************************************************************/
typedef enum {
ISP_CondRetOK,
/* Concluiu corretamente */
ISP_CondRetNaoReconhecido,
/* A entrada no foi reconhecida */
ISP_CondRetFaltouMemoria,
/* Faltou memria ao tentar alocar algo */
} ISP_tpCondRet;
/***********************************************************************
*
* Funo: ISP Ler tipo movimento
*
* Descrio
* Recebe uma representao string do tipo de movimento e
* retorna o tipo correspondente.
*
* Parmetros
* tipoStr - Representao string do tipo.
* pTipo - Referncia usada para retornar o tipo correspondente.
*
* Condies de retorno
* ISP_CondRetOK
* ISP_CondRetFaltouMemoria
* ISP_CondRetNaoReconhecido
*
* Retorno por referncia
* pTipo - retorna o tipo de movimento correspondente string.
*
* Assertivas de entrada
* - pTipo um ponteiro vlido.
* - tipoStr uma representao reconhecida de tipo de movimento.
*
* Assertivas de saida
* - pTipo aponta para um tipo de movimento correspondente string tipoStr.
*
***********************************************************************/
ISP_tpCondRet ISP_LerTipoMovimento(char *tipoStr, MPEC_tpTipoMovimento *pTipo);
/***********************************************************************
*
* Funo: ISP Ler passos
*
* Descrio
* Recebe uma representao string de uma lista de passos e
* retorna a lista correspondente.
*
* Parmetros
* passosStr - Representao string da lista de passos.
* ppPassos - Referncia usada para retornar a lista correspondente.
*
* Condies de retorno
* ISP_CondRetOK
* ISP_CondRetFaltouMemoria
* ISP_CondRetNaoReconhecido
*
* Retorno por referncia
* ppPassos - retorna a lista correspondente string.
*
* Assertivas de entrada
* - ppPassos um ponteiro vlido.
* - passosStr uma representao reconhecida de lista de passos.
*
* Assertivas de saida
* - ppPassos aponta para a lista de passos correspondente string passosStr.
*
***********************************************************************/
ISP_tpCondRet ISP_LerPassos(char *passosStr, LIS_tppLista *ppPassos);
/***********************************************************************/
#undef INPUT_STRING_PARSER_EXT
/********** Fim do mdulo de definio: Input string parser **********/
#else
#endif
|
C
|
#include<stdio.h>
int ispallindrome (int num);
int main()
{
int num, result;
printf("\nEnter the number: ");
scanf("%d", &num);
printf("%d \n" , num);
result=ispallindrome (num );
if(result==1)
printf("%d is pallindrome number", num);
else
printf(" %d is not pallindrome number", num);
return 0;
}
int ispallindrome (int num)
{
int rnum=0, r,n;
n=num;
while (n>0)
{
r=n%10;
rnum=rnum*10+r;
n=n/10;
}
if(rnum==num)
return 1;
else
return 0;
}
|
C
|
/**************************************************************************//**
* @file sim900.c
* @brief SimCom SIM900 driver File
* @version V1.1
* @date 20.04.2014
*
* @note
* Copyright (C) 2014 Serg Sizov
*
******************************************************************************/
#include <sim900.h>
#include <stdint.h>
#include <stdlib.h>
#include <stdbool.h>
#include <CoOS.h>
#include "stm32f10x.h"
#include "stm32f10x_usart.h"
uint16_t bufCntr = 0;
void setAirLedPortAndPin(GPIO_TypeDef *ledPort, uint16_t ledPin) {
activityLedPort = ledPort;
activityLedPin = ledPin;
}
void switchActivityLed(uint8_t state) {
GPIO_WriteBit(activityLedPort, activityLedPin, state);
}
void sendChar(uint8_t c)
{
while (USART_GetFlagStatus(sim900USART, USART_FLAG_TC) == RESET);
USART_SendData(sim900USART, (uint8_t) c); /* Loop until the end of transmission */
}
void sendString(const char *str)
{
uint16_t i = 0;
while(str[i]) {
sendChar(str[i++]);
}
}
bool isBufferNotEmpty() {
return bufCntr > 0;
}
uint8_t sendCommand(const char *command) {
switchActivityLed(true);
sendString(command);
sendString("\r");
switchActivityLed(false);
return 0;
}
uint8_t sendCommandWithRepeat(const char *command, uint16_t count) {
uint16_t i;
for(i = 0; i < count; i++) {
sendCommand(command);
CoTickDelay(10);
}
}
uint8_t sendCommandWithWaitReceive(const char *command, const char *respStr, uint32_t timeout) {
sendCommand(command);
return waitReceive(respStr, timeout);
}
void USART2_IRQHandler(void) {
CoEnterISR();
if (USART_GetITStatus(sim900USART, USART_IT_RXNE)) {
if (bufCntr >= RX_BUFF_SIZE) {
bufCntr = 0;
}
sim900_rxbuff[bufCntr++] = USART_ReceiveData(sim900USART) & 0x7F;
}
CoExitISR();
}
void preReceive() {
switchActivityLed(true);
memset(sim900_rxbuff, '\0', RX_BUFF_SIZE);
bufCntr = 0;
USART_ITConfig(sim900USART, USART_IT_RXNE, ENABLE);
}
void postReceive() {
USART_ITConfig(USART2, USART_IT_RXNE, DISABLE);
switchActivityLed(false);
}
uint8_t waitReceive(const char *respStr, uint32_t timeout) {
char *p = 0;
char ch;
uint16_t i;
U64 startTick, currentTick, elapsedTicks, timeoutTick;
timeoutTick = (timeout * CFG_SYSTICK_FREQ) / 1000;
i = 0;
startTick = CoGetOSTime();
preReceive();
do {
if (isBufferNotEmpty()){
if (respStr) {
p = strstr(sim900_rxbuff, ERROR_STRING);
if(p > 0) {
postReceive();
return RS_ERROR; // error received
}
p = strstr(sim900_rxbuff, respStr);
if(p > 0) {
postReceive();
return RS_OK; // string to be checked was found
}
}
}
CoTickDelay(1);
currentTick = CoGetOSTime();
elapsedTicks = currentTick - startTick;
} while (elapsedTicks < timeoutTick);
postReceive();
if (i < (RX_BUFF_SIZE - 1)) {
return RS_TIMEOUT; // timeout
}
return RS_BUFFER_OVERFLOW; // rx buffer full
}
char * getReceivedData() {
return sim900_rxbuff;
}
void identifyModule() {
currentGSMState.imei = NULL;
if (sendCommandWithWaitReceive("AT+GSN", "OK", 200) == RS_OK) {
currentGSMState.imei = strtok(getReceivedData(), "\r\n");
}
}
void readCSQ() {
currentGSMState.csq = 0;
if (sendCommandWithWaitReceive("AT+CSQ", "OK", 200) == RS_OK) {
char *csqStr = strtok(getReceivedData(), "\r\n");
char *csq = strrchr(' ', csqStr);
currentGSMState.csq = atoi(strtok(csq, ","));
}
return (NULL);
}
|
C
|
#include<stdio.h>
void main()
{
int b[10],ct[10],at[10]={0},t[10],i,j,n,w[10],atat=0,awt=0;
printf("\nEnter n value:");
scanf("%d",&n);
printf("\nEnter burst time:");
for(i=0;i<n;i++)
{
printf("\nP[%d]:",i+1);
scanf("%d",&b[i]);
}
printf("\nEnter arrival time:");
for(i=0;i<n;i++)
{
printf("\nP[%d]:",i+1);
scanf("%d",&at[i]);
}
ct[0]=b[0]+at[0];
for(i=1;i<n;i++)
{
ct[i]=ct[i-1]+b[i];
}
for(i=0;i<n;i++)
{
t[i]=ct[i]-at[i];
w[i]=t[i]-b[i];
awt=awt+w[i];
atat=atat+t[i];
}
printf("Process Arrival Burst TurnAroundTime WaitingTime\n");
for(i=0;i<n;i++)
{
printf("P[%d]\t%d\t%d\t%d\t%d\n",i+1,at[i],b[i],t[i],w[i]);
}
awt=awt/n;
atat=atat/n;
printf("Average waiting time:%d\nAverage Turn around time:%d",awt,atat);
}
|
C
|
/* Take a list of positions and velocities for the two
10 Msun black holes. Using this, compute a and e
for the motion of the center of mass around the 10^4 Msun
black holes, a and e for the binary, and the relative
inclination of the binary to its superorbital plane. Units
are AU, yr, and Msun*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "constants.h"
#include "helio.h"
#include "delaunay.h"
void heltodel(double mu,struct helio *h,struct delaunay *d);
main()
{
int i,N=0;
double m1,m2,mu,t;
double x1,y1,z1,vx1,vy1,vz1;
double x2,y2,z2,vx2,vy2,vz2;
struct helio bCoords, cCoords;
struct delaunay bElem, cElem;
FILE *data1,*data2;
char buf[5000];
data1=fopen("body1.dat","r");
data2=fopen("body2.dat","r");
while((fgets(buf,5000,data1)) != NULL) {
N++;
}
rewind(data1);
m1=m2=10;
for (i=0; i<N; i++)
{
fscanf(data1,"%lg %lg %lg %lg %lg %lg %lg",
&t,&x1,&y1,&z1,&vx1,&vy1,&vz1);
fscanf(data2,"%lg %lg %lg %lg %lg %lg %lg",
&t,&x2,&y2,&z2,&vx2,&vy2,&vz2);
cCoords.x=(m1*x1+m2*x2)/(m1+m2);
cCoords.y=(m1*y1+m2*y2)/(m1+m2);
cCoords.z=(m1*z1+m2*z2)/(m1+m2);
cCoords.vx=(m1*vx1+m2*vx2)/(m1+m2);
cCoords.vy=(m1*vy1+m2*vy2)/(m1+m2);
cCoords.vz=(m1*vz1+m2*vz2)/(m1+m2);
bCoords.x=x1-x2;
bCoords.y=y1-y2;
bCoords.z=z1-z2;
bCoords.vx=vx1-vx2;
bCoords.vy=vy1-vy2;
bCoords.vz=vz1-vz2;
mu=(4*CONST_PI*CONST_PI)*(m1+m2); // G*Mtot in these units
heltodel(mu,&bCoords,&bElem);
mu=(4*CONST_PI*CONST_PI)*(m1+m2+1.0e5);
heltodel(mu,&cCoords,&cElem);
printf("%.16g %.16g %.16g %.16g %.16g %.16g %.16g\n",
t,bElem.sma,bElem.ecc,bElem.sma*(1.0-bElem.ecc),cElem.sma,cElem.ecc,bElem.inc-cElem.inc);
}
fclose(data1);
fclose(data2);
}
|
C
|
#include "ds18b20.h"
#include "misc.h"
#include "intrins.h"
bit ds_init()
{
bit i;
DS = 1;
_nop_();
DS = 0;
delay_ticks(75); //499.45us ҽϵ18B20ȫλ
DS = 1; //ͷ
delay_ticks(4); //ʱ37.95us ȴ18B20شź
i = DS;
delay_ticks(20); //141.95us
DS = 1;
_nop_();
return (i);
}
void write_byte(u8 dat)
{
u8 i;
for(i=0;i<8;i++)
{
DS = 0;
_nop_();//Щʱ
DS = dat & 0x01;
delay_ticks(10);//76.95us
DS = 1; //ͷһд
_nop_();
dat >>= 1;
}
}
u16 read_byte()
{
u8 i;
u16 ret = 0;
for(i = 0; i < 8; ++i)
{
DS = 0;
_nop_();
DS = 1;
_nop_();
ret = ret | ((u8)DS << i);
delay_ticks(10);
DS = 1;
_nop_();
}
return ret;
}
// get raw value of temperature, mul it with 0.0625
u16 ds18b20_read()
{
u16 i;
// config it to 9/10/11/12 bit_ mode
/* ds_init();
write_byte(0xcc);
write_byte(0x4e);
write_byte(0x7f);
write_byte(0xf7);
write_byte(0x7f);
ds_init();
write_byte(0xcc);
write_byte(0x48);*/
ds_init();
write_byte(0xcc); // skip rom
write_byte(0x44); // start measure
ds_init();
write_byte(0xcc); // skip rom
write_byte(0xbe); // read temp registers
delay_ticks(5);
i = read_byte();
i = ((u16)read_byte() << 8) | i;
return i;
}
// fraction part of temperature
u16 ds18b20_get_fra(u16 i)
{
return (i & 0x0f) * 625;
}
void ds18b20_init()
{
ds_init();
write_byte(0xcc); // skip rom
write_byte(0x44); // start measure
}
|
C
|
// using unsigned integer
#include <stdio.h>
#define SPEED_OF_LIGHT 299792458
int main(){
double travel_distance;
unsigned int cpu_freq, travel_distance2;
printf("Frequency of the CPU (Hz): ");
scanf("%d", &cpu_freq);
travel_distance = 1000.0 * SPEED_OF_LIGHT / cpu_freq;
printf("Electricity can travel %0.0lf millimeters in one cycle of a CPU that has a frequency of %d Hz.\n", travel_distance, cpu_freq);
travel_distance2 = (SPEED_OF_LIGHT / (cpu_freq / 1000));
printf("Using only integers, that is %u millimeters. \n", travel_distance2);
return 0;
}
|
C
|
#include <stdio.h>
void selectionSort(int length, int *data);
void printArray(int length, int *data);
int main(void) {
int data[] = { 4, 51, 31, 8, 20, 16, 37, 34, 3, 11, 7, 13, 21, 27, 1 };
int length = sizeof(data) / sizeof(data[0]);
printArray(length, data);
selectionSort(length, data);
}
void selectionSort(int length, int *data) {
int min;
int tmp;
for (int i = 0; i < length - 1; i++) {
min = i;
for (int j = i + 1; j < length; j++) {
if (data[min] > data[j]) {
min = j;
}
}
tmp = data[i];
data[i] = data[min];
data[min] = tmp;
printArray(length, data);
}
}
void printArray(int length, int *data) {
for (int i = 0; i < length; i++) {
printf("%d ", data[i]);
}
printf("\n");
}
|
C
|
/*
HEADER: CUG000.01;
TITLE: NearNeighbor, CheapArc;
DATE: Mar 89;
DESCRIPTION: Nearest Neighbor Tour Building Algorithm;
VERSION: 2.0;
FILENAME: NN.C;
SEE-ALSO: TSP.C, POPT.C, 2OPT.C, HYBRID.C, 3OPT.C, FN.C,
BOOLEAN.H, NODELIST.H, TSP.H,
BLDMTX.C, PRTMTX.C, TIME.C;
AUTHORS: Kevin E. Knauss;
*/
#include <stdio.h>
#include <boolean.h>
#include <nodelist.h>
#include <tsp.h>
long NearNeighbor (NumberOfVirteces, SavePath)
unsigned NumberOfVirteces;
NODE *SavePath;
{
unsigned ArcCost(), CheapArc();
long CircuitCost;
unsigned NewVirtex, ToIndex, CurrentVirtex, FromIndex;
BOOLEAN Available[MAXROWS][MAXCOLS];
NODE *Path;
CircuitCost = 0;
for ( FromIndex = 1; FromIndex <= NumberOfVirteces; FromIndex++) {
for ( ToIndex = 1; ToIndex <= NumberOfVirteces; ToIndex++)
Available [FromIndex][ToIndex] = TRUE;
Available [FromIndex][FromIndex] = FALSE;
}
/* STEP 1: Find virtex from which cheapest arc eminates */
CurrentVirtex = 1;
NewVirtex = CheapArc (CurrentVirtex, NumberOfVirteces, Available);
for ( FromIndex = 2; FromIndex <= NumberOfVirteces; FromIndex++) {
ToIndex = CheapArc (FromIndex, NumberOfVirteces, Available);
if (ArcCost (FromIndex, ToIndex) <
ArcCost (CurrentVirtex, NewVirtex)) {
CurrentVirtex = FromIndex;
NewVirtex = ToIndex;
}
}
/* STEP 2: Establish current virtex as base of path */
Path = SavePath;
Path->position = CurrentVirtex;
/* STEP 7 Init */
do {
/* STEP 3: Set all paths unavailable to the current virtex */
for ( FromIndex = 1; FromIndex <= NumberOfVirteces; FromIndex++)
Available [FromIndex][CurrentVirtex] = FALSE;
/* STEP 4: Add cheapest arc from current virtex to cost of path */
CircuitCost += ArcCost (CurrentVirtex, NewVirtex);
/* STEP 5: Add new virtex to path */
if ((Path->next = calloc (1, sizeof(NODE))) == NULL) {
printf("\n*******************************************");
printf("\n Execution Terminated - Insuficient Memory!");
printf("\n*******************************************\n\n");
exit(-1);
} else {
Path->next->prior = Path;
Path = Path->next;
Path->position = NewVirtex;
}
/* STEP 6: Establish the new virtex as the current virtex */
CurrentVirtex = NewVirtex;
/* STEP 7: Find the next virtex at the opposite end of the cheapest
arc from current virtex; if found, continue with step 3 */
NewVirtex = CheapArc (CurrentVirtex, NumberOfVirteces, Available);
} while (Available [CurrentVirtex][NewVirtex]);
/* STEP 8: Find the cost of the arc between the new current virtex and
the initial virtex in the path and add to cost of path */
SavePath->prior = Path;
Path->next = SavePath;
CircuitCost += ArcCost (CurrentVirtex, SavePath->position);
return (CircuitCost);
} /* NearNeighbor */
unsigned CheapArc (FromIndex, NumberOfVirteces, Available)
unsigned FromIndex, NumberOfVirteces;
BOOLEAN Available[MAXROWS][MAXCOLS];
{
unsigned ArcCost();
unsigned ToIndex, NewIndex;
for ( ToIndex = 1; ((ToIndex < NumberOfVirteces) &&
(!Available [FromIndex][ToIndex])); ToIndex++);
for ( NewIndex = ToIndex + 1; NewIndex <= NumberOfVirteces; NewIndex++)
if (Available [FromIndex][NewIndex])
if (ArcCost (FromIndex, NewIndex) < ArcCost (FromIndex, ToIndex))
ToIndex = NewIndex;
return (ToIndex);
} /* CheapArc */
|
C
|
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "tokenize.h"
char** tokenize_malloc(const char* str, const char* delim)
{
char** result;
char* token;
char* str_malloc;
char* str_copy;
char* delim_copy;
size_t temp_str_len = 0;
size_t token_count = 0;
if (str == NULL || strlen(str) < 1) {
result = (char**)malloc(sizeof(char*) * 1);
result[0] = (char*)malloc(sizeof(char) * 1);
result[0] = NULL;
return result;
}
temp_str_len = strlen(str);
str_malloc = (char*)malloc(sizeof(char) * (temp_str_len + 1));
str_copy = str_malloc;
strncpy(str_copy, str, temp_str_len);
str_copy[temp_str_len] = '\0';
if (delim == NULL || strlen(delim) < 1) {
result = (char**)malloc(sizeof(char*) * 2);
result[0] = (char*)malloc(sizeof(char) * (temp_str_len + 1));
strncpy(result[0], str_copy, temp_str_len);
result[0][temp_str_len] = '\0';
result[1] = NULL;
return result;
}
token = str_copy;
result = (char**)malloc(sizeof(char*) * strlen(str_copy));
while (*str_copy != '\0') {
delim_copy = (char*)delim;
while (*delim_copy != '\0') {
if (*str_copy == *delim_copy) {
*str_copy = '\0';
temp_str_len = strlen(token);
if (temp_str_len < 1U) {
token = str_copy + 1;
break;
}
result[token_count] = (char*)malloc(sizeof(char) * (temp_str_len + 1));
strncpy(result[token_count], token, temp_str_len);
result[token_count][temp_str_len] = '\0';
++token_count;
token = str_copy + 1;
break;
}
++delim_copy;
}
++str_copy;
if (*str_copy == '\0' && strlen(token) > 0) {
temp_str_len = strlen(token);
result[token_count] = (char*)malloc(sizeof(char) * (temp_str_len + 1));
strncpy(result[token_count], token, temp_str_len);
result[token_count][temp_str_len] = '\0';
++token_count;
}
}
free(str_malloc);
result[token_count] = NULL;
result = realloc(result, sizeof(char*) * (token_count + 1));
return result;
}
|
C
|
#include "lists.h"
/**
* insert_node - Inserts a new node
* @head: head of the linked list
* @number: number to be inserted
* Return: new inserted linked list
*/
listint_t *insert_node(listint_t **head, int number)
{
listint_t *temp, *temp2, *new_node;
new_node = malloc(sizeof(listint_t));
if (!new_node)
return (NULL);
new_node->n = number;
if (*head == NULL)
{
*head = new_node;
return (new_node);
}
if ((*head)->n >= number)
{
new_node->next = *head;
*head = new_node;
return (new_node);
}
temp = *head;
while (temp->next && temp->next->n <= number)
temp = temp->next;
temp2 = temp->next;
temp->next = new_node;
new_node->next = temp2;
return (new_node);
}
|
C
|
#include "head.h"
#include "work_que.h"
#include "factory.h"
//发送文件
int sendFile(int sendFd,char *fileName)
{
Train_t dataTrain;
int fileFd;
fileFd=open(fileName,O_RDONLY|O_CREAT);
ERROR_CHECK(fileFd,-1,"open");
//发送文件名
dataTrain.dataLen=strlen(fileName);
strcpy(dataTrain.data,fileName);//???用strcpy还是用别的
send(sendFd,&dataTrain,4+dataTrain.dataLen,0);
//发送文件大小
struct stat buf;
fstat(fileFd,&buf);
dataTrain.dataLen=sizeof(buf.st_size);
memcpy(dataTrain.data,&buf.st_size,dataTrain.dataLen);
send(sendFd,&dataTrain,4+dataTrain.dataLen,0);
//发送文件内容
while((dataTrain.dataLen=read(fileFd,dataTrain.data,1000)))
{
send(sendFd,&dataTrain,4+dataTrain.dataLen,0);
}
//发送文件结束标识符
send(sendFd,&dataTrain,4+dataTrain.dataLen,0);
close(fileFd);
return 0;
}
//接收文件
int recvFile(int recvFd)
{
//接收文件名
char fileName[128]={0};
int recvLen;
recvCycle(recvFd,4,&recvLen);
recvCycle(recvFd,recvLen,fileName);
//创建该文件名的文件
int fileFd;
fileFd=open(fileName,O_RDWR|O_CREAT,0666);
//接收文件大小
long fileSize;
recvCycle(recvFd,4,&recvLen);
recvCycle(recvFd,recvLen,&fileSize);
//接收文件内容
char buf[1000]={0};
while(1)
{
recvCycle(recvFd,4,&recvLen);
if(0==recvLen)//文件接收结束
{
break;
}
recvCycle(recvFd,recvLen,buf);
write(fileFd,buf,recvLen);
}
close(fileFd);
return 0;
}
|
C
|
#ifndef InstructionList_H
#define InstructionList_H
/**
@struct InstructionList
List of disassembled instructions from Static Analise
*/
struct InstructionList{
char* instruction; /// disassembled instruction in INTEL format
int number; ///offset of instruction from text section
int length; ///length of instruction
bool first; ///is true is if instruction is entry point, is false in another case
bool padding; ///is true is if instruction is padding, is false in another case
InstructionList* pointer; ///pointer to the next InstructionList
};
#endif
|
C
|
#include<stdio.h>
void main()
{
int integer, i, max, min, sum;
max = 32767; /*先假设当前的最大值max为C语言整型数的最小值*/
min = -32768; /*先假设当前的最小值min为C语言整型数的最大值*/
sum = 0; /*将求累加和变量的初值置为0*/
for (i = 1; i <= 10; i++) {
printf("Input number %d=", i);
scanf("%d", &integer); /*输入评委的评分*/
sum += integer; /*计算总分*/
if (integer > max) {
max = integer; /*通过比较筛选出其中的最高分*/
}
if (integer < min) {
min = integer; /*通过比较筛选出其中的最低分*/
}
}
printf("Canceled max score:%d\nCanceled min score:%d\n", max, min);
printf("Average score:%d\n", (sum - max - min) / 8); /*输出结果*/
getch();
return 0;
}
|
C
|
//Program to display the number entered the base and the converted number.
#include<stdio.h>
void main()
{
unsigned int num,num2,base,no_dig=0,p;
int i;
printf("Enter any positive integer and base: ");
scanf("%d %d",&num,&base);
printf("number=%d, base=%d, converted number= ",num,base);
num2=num;
do
{
no_dig++;
num2=num2/base;
}while (num2 != 0);
for( ;no_dig>0;no_dig--)
{
p=1;
for(i=no_dig-1;i>0;i--)
p=p*base;
if(base==16)
printf("%x",num/p);
else
printf("%d",num/p);
num=num%p;
}
printf("\n");
}
|
C
|
#include <stdio.h>
/*
* 6.6#10
* The semantic rules for the evaluation of a constant expression are the same as for
* nonconstant expressions.
*/
int i0 = 2 || 1/0;
int i1 = 0 && 1/0;
int i2 = 2 ? 1 : 1/0;
int i3 = 0 ? 1/0 : 1;
/* address of object: true or false? */
int *p0 = 0 && &i0;
int *p1 = &i0 && 0;
int *p2 = (int *)(1 || &i0);
int *p3 = (int *)(&i0 || 1);
int main(void)
{
printf("%d\n", i0);
printf("%d\n", i1);
printf("%d\n", i2);
printf("%d\n", i3);
printf("0x%lx\n", p0);
printf("0x%lx\n", p1);
printf("0x%lx\n", p2);
printf("0x%lx\n", p3);
return 0;
}
|
C
|
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#include "deck.h"
#define MAGIC 4459897
struct Deck{
CARD *m_deckArray;
size_t m_cardsNum;
int m_magicNum;
};
/* HELPER */
void SwapCards(CARD *_deck, size_t _a, size_t _b);
/* HELPER_END */
Deck *DeckCreate(size_t _numOfDecks)
{
Deck *_deckPtr;
CARD *_deckCardArr;
size_t index;
if(_numOfDecks == 0)
{
return NULL;
}
_deckPtr = malloc(sizeof(Deck));
if(_deckPtr == NULL)
{
return NULL;
}
_deckCardArr = malloc(sizeof(CARD) * NUM_OF_CARDS * _numOfDecks);
if(_deckCardArr == NULL)
{
free(_deckPtr);
return NULL;
}
for(index = 0; index < NUM_OF_CARDS * _numOfDecks; index++)
{
_deckCardArr[index] = index % NUM_OF_CARDS;
}
_deckPtr->m_deckArray = _deckCardArr;
_deckPtr->m_cardsNum = _numOfDecks * NUM_OF_CARDS;
_deckPtr->m_magicNum = MAGIC;
return _deckPtr;
}
void DeckDestroy(Deck *_deck)
{
if(_deck == NULL || _deck->m_magicNum != MAGIC)
{
return;
}
free(_deck->m_deckArray);
_deck->m_magicNum = 0;
free(_deck);
}
GAME_ERRORS DeckShuffle(Deck *_deck)
{
size_t i, j;
if(_deck == NULL || _deck->m_magicNum != MAGIC)
{
return POINTER_NOT_INITIALIZED;
}
srand ( time(NULL) );
for(i = _deck->m_cardsNum - 1; i > 0; i--)
{
SwapCards(_deck->m_deckArray, rand() % (i+1), i);
}
return OK;
}
GAME_ERRORS DeckCardDisribute(Deck *_deck, CARD *_card)
{
if(_deck == NULL || _deck->m_magicNum != MAGIC || _card == NULL)
{
return POINTER_NOT_INITIALIZED;
}
if(_deck->m_cardsNum == 0)
{
return EMPTY_DECK;
}
*_card = _deck->m_deckArray[_deck->m_cardsNum - 1];
(_deck->m_cardsNum)--;
return OK;
}
GAME_ERRORS IsDeckEmpty(Deck *_deck)
{
if(_deck == NULL || _deck->m_magicNum != MAGIC)
{
return POINTER_NOT_INITIALIZED;
}
if(_deck->m_cardsNum == 0)
{
return EMPTY_DECK;
}
return DECK_NOT_EMPTY;
}
GAME_ERRORS DeckGetNumOfCards(Deck *_deck, size_t *_cardNum)
{
if(_deck == NULL || _deck->m_magicNum != MAGIC || _cardNum == NULL)
{
return POINTER_NOT_INITIALIZED;
}
*_cardNum = _deck->m_cardsNum;
return OK;
}
/* TESTING */
void DeckPrint(Deck *_deck)
{
size_t i;
if(_deck == NULL || _deck->m_magicNum != MAGIC)
{
return;
}
for(i = 0; i < _deck->m_cardsNum; i++)
{
printf("%ld card is %d\n", i+1, _deck->m_deckArray[i]);
}
}
/* HELPER */
void SwapCards(CARD *_deck, size_t _a, size_t _b)
{
CARD temp = _deck[_a];
_deck[_a] = _deck[_b];
_deck[_b] = temp;
}
|
C
|
#include<stdio.h>
#include<string.h>
int main()
{
int i,n;
long long int a,b;
char str1[101],str2[6],str3[101],str4[6];
scanf("%d",&n);
for(i = 0;i < n;i++){
scanf("%s %s %s %s",str1,str2,str3,str4);
scanf("%lld %lld",&a,&b);
a += b;
if(str2[0]=='I'){
if(a%2==0)printf("%s\n",str3);
else printf("%s\n",str1);
}
else {
if(a%2==0)printf("%s\n",str1);
else printf("%s\n",str3);
}
}
return 0;
}
|
C
|
/*
* File: symtest.c
* ---------------
* This program tests the symbol table abstraction. The user
* types in command lines, which are assumed to be in one of
* the following forms:
*
* key Display the current value of key
* key = value Enter new value for key
* quit Exit from the program
*/
#include <stdio.h>
#include <ctype.h>
#include "genlib.h"
#include "strlib.h"
#include "simpio.h"
#include "symtab.h"
#include "scanadt.h"
/* Main program */
main()
{
symtabADT table;
scannerADT scanner;
string line, name, value;
table = NewSymbolTable();
scanner = NewScanner();
SetScannerSpaceOption(scanner, IgnoreSpaces);
while (TRUE) {
printf("-> ");
line = GetLine();
if (StringEqual(line, "quit")) break;
SetScannerString(scanner, line);
name = ReadToken(scanner);
if (MoreTokensExist(scanner)) {
if (!StringEqual(ReadToken(scanner), "=")) {
Error("Missing equal sign in assignment");
}
value = ReadToken(scanner);
if (MoreTokensExist(scanner)) {
Error("Statement contains additional data");
}
Enter(table, name, value);
} else {
value = Lookup(table, name);
if (value == UNDEFINED) {
printf("'%s' is undefined.\n", name);
} else {
printf("%s\n", value);
}
}
}
FreeSymbolTable(table);
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main() {
/*O comando while:
permite executar, repetidamente, um conjunto de comandos de acordo com uma condicao
//Forma geral:
while(condicao) {
conjunto de comandos
}
*/
int a, b;
printf("Digite dois valores inteiros: ");
scanf("%d %d", &a, &b);
while(a < b) {
a++;
printf("%d\n", a);
}
/*Exemplo de loop infinito, a condicao sempre é verdadeira
while(a < b) {
a--;
printf("%d\n", a);
}
*/
//Condicoes mais complexas
while(a < b && a > 0) {
a++;
printf("%d\n", a);
}
printf("Fim do programa");
system("pause");
return 0;
}
|
C
|
#include<stdio.h>
#include<string.h>
#define N 200
#define M 4
#define NAME 20
struct User
{
char account[NAME];
int password;
struct User *next;
};
struct info
{
char name[NAME];
int toInode;
struct info *next;
};
struct Block
{
int blockIsUsed;
struct info *p;
};
struct Inode
{
int inodeIsUsed;
int model; //1ļ 0Ŀ¼
int size; //ļС
int limit; //Ȩ
int block[N]; //ռblock
int nb; // һռüblock
};
struct Block m_block[N];
struct Inode m_inode[N];
struct User *users;
char account[NAME];
char access[NAME]="/";
int nowBlock=0;
void init()
{
int i;
char s;
struct User *u,*t;
FILE *fp;
users=(struct User *)malloc(sizeof(struct User));
users->next=NULL;
t=users;
for(i=0;i<N;i++)
{
m_block[i].blockIsUsed=0;
m_block[i].p=NULL;
m_inode[i].inodeIsUsed=0;
m_inode[i].model=0;
m_inode[i].nb=0;
}
m_inode[0].inodeIsUsed=1;
m_block[0].blockIsUsed=1;
m_inode[0].nb=1;
m_inode[0].block[0]=0;
nowBlock=0;
if((fp=fopen("user.txt","r"))==NULL)
{
printf("open user file failed!!!\n");
exit(0);
}
while(!feof(fp))
{
u=(struct User *)malloc(sizeof(struct User));
fscanf(fp,"%s %d ",u->account,&u->password);
u->next=NULL;
t->next=u;
t=u;
}
fclose(fp);
//printAccount();
}
int findEmptyBlock()
{
int i=0;
for(i=0;i<N;i++)
{
if(m_block[i].blockIsUsed==0)
{
m_block[i].blockIsUsed=1;
return i;
}
}
return -1;
}
int findEmptyInode()
{
int i=0;
for(i=0;i<N;i++)
{
if(m_inode[i].inodeIsUsed==0)
{
m_inode[i].inodeIsUsed=1;
return i;
}
}
return -1;
}
void login()
{
char acc[NAME];
struct User *p;
int pas=-1,pass;
fflush(stdin);
initOrder();
while(1)
{
printf("login:");
gets(acc);
printf("password:");
p=users->next;
while(p)
{
if(strcmp(acc,p->account)==0)
{
pas=p->password;
break;
}
p=p->next;
}
scanf("%d",&pass);
fflush(stdin);
if(pass==pas&&pas!=-1)
{
strcpy(account,acc);
printf("Login success\n\n");
return;
}else{
printf("Login incorrect\n\n");
}
}
}
void printAccount()
{
struct User *p;
p=users->next;
while(p)
{
printf("%s\t%d\n",p->account,p->password);
p=p->next;
}
}
void del(int i)
{
int j;
struct info *m,*n;
m_inode[i].inodeIsUsed=0;
m_inode[i].size=0;
for(j=0;j<m_inode[i].nb;j++)
{
m_block[m_inode[i].block[j]].blockIsUsed=0;
if(m_block[m_inode[i].block[j]].p!=NULL&&m_block[m_inode[i].block[j]].p->next!=NULL)
{
n=m_block[m_inode[i].block[j]].p->next;
while(n)
{
m=n;
n=n->next;
del(m->toInode);
free(m);
}
free(m_block[m_inode[i].block[j]].p);
}
}
m_inode[i].nb=0;
}
//ļ
void createFile(char myName[])
{
int size,emptyInode,i;
struct info *n=(struct info *)malloc(sizeof(struct info));
struct info *m;
//printf("ļС!!!");
//scanf("%d",&size);
size=2;//ĬļСΪ2block
emptyInode=findEmptyInode(m_inode);
//printf("\n\n%d\n\n\n%d",emptyInode,nowBlock);
m_inode[emptyInode].model=0;
m_inode[emptyInode].size=size;
m_inode[emptyInode].nb=2;
for(i=0;i<m_inode[emptyInode].nb;i++)
{
m_inode[emptyInode].block[i]=findEmptyBlock(m_block);
}
m=m_block[nowBlock].p;
if(m==NULL)
{
m_block[nowBlock].p=(struct info *)malloc(sizeof(struct info));
m_block[nowBlock].p->next=NULL;
m=m_block[nowBlock].p;
}
else
{
while(m->next)
m=m->next;
}
strcpy(n->name,myName);
n->toInode=emptyInode;
n->next=NULL;
m->next=n;
}
//Ŀ¼
void createCatalog(char myName[])
{
int emptyInode,emptyBlock;
struct info *n=(struct info *)malloc(sizeof(struct info));
struct info *m;
// ˴ҪļǷظ
//ҿ
emptyInode=findEmptyInode();
emptyBlock=findEmptyBlock();
//printf("\n\n%d\n\n\n%d",emptyInode,nowBlock);
m_inode[emptyInode].model=1;
m_inode[emptyInode].nb=1;
m_inode[emptyInode].block[0]=emptyBlock;
m=m_block[nowBlock].p;
if(m==NULL)
{
m_block[nowBlock].p=(struct info *)malloc(sizeof(struct info));
m_block[nowBlock].p->next=NULL;
m=m_block[nowBlock].p;
}
else
{
while(m->next)
m=m->next;
}
strcpy(n->name,myName);
n->toInode=emptyInode;
n->next=NULL;
m->next=n;
}
void printCatalog(int i)
{
struct info *m;
if(m_block[i].p!=NULL)
{
m=m_block[i].p->next;
while(m)
{
if(m_inode[m->toInode].model==1)
printf("%s`\t",m->name);
else
printf("%s\t",m->name);
m=m->next;
}
printf("\n");
}
else
{
printf("\n");
}
}
void printFile(int i)
{
printf("ļС:%d\tռ%dblock\t\n",m_inode[i].size,m_inode[i].nb);
}
char *getOrder(char all[])
{
int i,j=0;
char order[NAME];
char contents[NAME];
if(all[0]=='\0')
return "";
for(i=0;;i++)
{
if(all[i]=='\0'||all[i]==' ')
break;
order[i]=all[i];
}
order[i]='\0';
if(all[i]=='\0')
{
all[0]='\0';
}
else
{
i++;
for(i;all[i]!='\0';i++)
{
contents[j]=all[i];
j++;
}
contents[j]='\0';
strcpy(all,contents);
}
return order;
}
int find(char n[],int *tempBlock,char tempAccess[])
{
struct info *m;
m=m_block[*tempBlock].p;
if(m!=NULL)
{
m=m->next;
while(m)
{
if(strcmp(n,m->name)==0)
{
if(m_inode[m->toInode].model==1)
{
*tempBlock=m_inode[m->toInode].block[0];
strcat(tempAccess,n);
strcat(tempAccess,"/");
return 1;
}
else
{
printf("cannot open %s is not the catalog\n",n);
return 0;
}
}
m=m->next;
}
if(m==NULL)
{
printf("no %s catalog\n",n);
return 0;
}
}
else
{
printf("no %s catalog\n",n);
return 0;
}
}
void dealAccess(char contents[],int *u)
{
int i,j=0,h=0;
char temp[NAME];
int tempBlock;
char tempAccess[NAME];
if(contents[0]=='/') //·
{
tempBlock=0;
strcpy(tempAccess,"/");
if(contents[1]=='/')
{
strcpy(access,tempAccess);
nowBlock=tempBlock;
return;
}
for(j=1;contents[j]!='\0';j++)
{
if(contents[j]!='/')
{
temp[h++]=contents[j];
}
else
{
temp[h]='\0';
if(find(temp,&tempBlock,tempAccess))
{
h=0;
}
else
{
temp[0]='\0';
return;
}
}
}
if(contents[j]=='\0')
{
temp[0]='\0';
if(*u==-1)
{
strcpy(access,tempAccess);
nowBlock=tempBlock;
}
else
{
*u=tempBlock;
}
return;
}
}
else
{
j=0;
tempBlock=nowBlock;
strcpy(tempAccess,access);
for(i=0;contents[i]!='\0';i++)
{
if(contents[i]!='/')
{
temp[j]=contents[i];
j++;
}
else
{
temp[j]='\0';
if(strcmp(temp,"..")==0)
{
j=0;
printf("..");
}
else if(strcmp(temp,".")==0)
{
j=0;
}
else if(strcmp(temp,"")==0)
j=0;
else
{
if(find(temp,&tempBlock,tempAccess))
{
j=0;
}
}
}
}
if(*u==-1)
{
strcpy(access,tempAccess);
nowBlock=tempBlock;
}
else
{
*u=tempBlock;
}
}
}
void cdOrder(char contents[])
{
int i,j=0,h=0,u=-1;
char temp[NAME];
int tempBlock;
char tempAccess[NAME];
for(i=0;contents[i]!='\0';i++)
{
if(contents[i]==' ')
{
printf("%s :no this access\n",contents);
return;
}
}
dealAccess(contents,&u);
}
void lsOrder(char contents[])
{
if(contents[0]=='\0')
{
printCatalog(nowBlock);
}
else
{
printf("ʽ!\n");
}
}
void createOrder(char contents[],int flag)
{
int i,j=0;
char temp[NAME];
for(i=0;contents[i]!='\0';i++)
{
if(contents[i]==' ')
{
temp[j]='\0';
//ļǷϷ
if(isFind(temp,nowBlock))
{
printf("%s is exist\n",temp);
return;
}
if(flag==0)
createFile(temp);
else
createCatalog(temp);
j=0;
}
else
{
temp[j]=contents[i];
j++;
}
}
}
int isFind(char fileName[],int tempBlock)
{
struct info *m,*n;
if(m_block[tempBlock].p!=NULL)
{
m=m_block[tempBlock].p->next;
while(m)
{
if(strcmp(fileName,m->name)==0)
{
return 1;
}
m=m->next;
}
}
return 0;
}
void rmOrder(char contents[])
{
int i,j=0;
char str[NAME];
struct info *w,*e;
for(i=0;contents[i]!='\0';i++)
{
if(contents[i]==' ')
{
str[j]='\0';
j=0;
if(isFind(str,nowBlock))
{
if(m_block[nowBlock].p!=NULL)
{
w=m_block[nowBlock].p;
while(w->next)
{
if(strcmp(str,w->next->name)==0)
{
e=w->next;
w->next=e->next;
del(e->toInode);
free(e);
break;
}
w=w->next;
}
}
}
else
{
printf("no find %s file!\n",str);
}
}
else
{
str[j]=contents[i];
j++;
}
}
}
void saveUser()
{
FILE *fp;
struct User *p;
if((fp=fopen("user.txt","w"))==NULL)
{
printf("user file cannot open\n");
return;
}
p=users->next;
while(p)
{
fprintf(fp,"%s %d\n",p->account,p->password);
p=p->next;
}
fclose(fp);
}
int isFindUser(char na[])
{
struct User *m,*n;
m=users->next;
while(m)
{
if(strcmp(m->account,na)==0)
return 1;
m=m->next;
}
return 0;
}
void userOrder(char contents[],int flag)
{
int i,j=0,pas;
char na[NAME];
struct User *p,*m,*n;
for(i=0;contents[i]!='\0';i++)
{
if(contents[i]==' ')
{
printf("ʽ!\n");
return;
}
else
{
na[j]=contents[i];
j++;
}
}
na[j]='\0';
if(flag==0) //û
{
if(isFindUser(na))
{
printf("%s is exist\n",na);
return;
}
m=(struct User *)malloc(sizeof(struct User));
strcpy(m->account,na);
m->next=NULL;
printf("password:");
scanf("%d",&pas);
m->password=pas;
m->next=users->next;
users->next=m;
// if(users->next!=NULL)
// {
// p=users->next;
// while(p->next)
// {
// p=p->next;
// }
// p->next=m;
// }
// else
// {
// users->next=m;
// }
}
else
{
p=users;
if(strcmp(na,"kk")==0)
{
printf("kk user cannot del\n");
return;
}
if(strcmp(account,"kk")==0)
{
while(p->next)
{
if(strcmp(p->next->account,na)==0)
break;
p=p->next;
}
if(p->next==NULL)
{
printf("no this user..\n");
return;
}
n=p->next;
p->next=p->next->next;
free(n);
}
else
{
printf("Ȩ!!!\n");
}
}
printAccount();
saveUser();
}
void save()
{
FILE *fp;
fp=fopen("account.txt","w");
if(fp==NULL)
{
printf("cannot open %s file\n",account);
return;
}
}
void initOrder()
{
int i;
struct info *m,*n;
if(m_block[0].p!=NULL)
{
m=m_block[0].p->next;
while(m)
{
del(m->toInode);
m=m->next;
}
free(m_block[0].p);
m_block[0].p=NULL;
// while(m_block[0].p)
// {
// n=m_block[0].p;
// while(n->next)
// {
// n=n->next;
// }
// free(n);
// }
}
nowBlock=0;
strcpy(access,"/");
}
void main()
{
char order[NAME],all[NAME];
init();
//printAccount(users);
login();
while(1)
{
fflush(stdin);
printf("[%s@myShell %s]#",account,access);
gets(all);
strcpy(order,getOrder(all));
if(strcmp(order,"cd")==0)
{
if(all[0]!='\0')
{
strcat(all,"/");
cdOrder(all);
}
}
else if(strcmp(order,"ls")==0)
{
lsOrder(all);
}
else if(strcmp(order,"touch")==0)
{
if(all[0]!='\0')
{
strcat(all," ");
createOrder(all,0);
}
}
else if(strcmp(order,"rm")==0)
{
if(all[0]!='\0')
{
strcat(all," ");
rmOrder(all);
}
}
else if(strcmp(order,"mkdir")==0)
{
if(all[0]!='\0')
{
strcat(all," ");
createOrder(all,1);
}
}
else if(strcmp(order,"logout")==0)
{
login();
}
else if(strcmp(order,"exit")==0)
{
save();
exit(1);
}
else if(strcmp(order,"useradd")==0)
{
userOrder(all,0);
}
else if(strcmp(order,"userdel")==0)
{
userOrder(all,1);
}
else if(strcmp(order,"init")==0)
{
initOrder();
}
else if(strcmp(order,"clear")==0)
{
system("cls");
}
else if(strcmp(order,"users")==0)
{
printAccount();
}
}
}
|
C
|
/*
* Tutorial 4 Jeopardy Project for SOFE 3950U / CSCI 3020U: Operating Systems
*
* Copyright (C) 2015, <GROUP MEMBERS>
* All rights reserved.
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "questions.h"
// Initializes the array of questions for the game
void initialize_game(void)
{
// initialize each question struct and assign it to the questions array
char categories_list[NUM_QUESTIONS][MAX_LEN] = {
"programming",
"programming",
"programming",
"programming",
"algorithms",
"algorithms",
"algorithms",
"algorithms",
"databases",
"databases",
"databases",
"databases"
};
char questions_list[NUM_QUESTIONS][MAX_LEN] = {
"It is the most widely used systems programming language",
"It is the most widely used programming language for AI research",
"An example of this type of data would be a word in plain English",
"This type of fault is incredibly frustrating and difficult to debug",
"This sequence is when you add the previous 2 terms together to get the next term",
"The ___ algorithm imitates the evolutionary process",
"An algorithm that calls itself is known as:",
"A technique where you sequentially try every possible combination",
"Google's primary cloud storage suite",
"The industry standard database programming language ",
"All databses are comprised of these constructs to store data entries",
"The ____ key is used to uniquely identify entries in a database"
};
char answers_list[NUM_QUESTIONS][MAX_LEN] = {
"C",
"Python",
"String",
"Segfault",
"Fibbonacci",
"Genetic",
"Recursive",
"Brute-force",
"Drive",
"SQL",
"Table",
"Primary"
};
int values_list[NUM_QUESTIONS] = {
20,
50,
100,
200,
20,
50,
100,
200,
20,
50,
100,
200
};
for(int i = 0; i<NUM_QUESTIONS; i++){
strcpy(questions[i].question, &questions_list[i]);
strcpy(questions[i].answer, &answers_list[i]);
strcpy(questions[i].category, &categories_list[i]);
questions[i].value = values_list[i];
questions[i].answered = false;
}
}
// Displays each of the remaining categories and question dollar values that have not been answered
void display_categories(void)
{
// print categories and dollar values for each unanswered question in questions array
printf("\n");
for(int i = 0; i<NUM_QUESTIONS; i++){
if (questions[i].answered == false){
printf("%s %d\n", &questions[i].category, questions[i].value);
}
}
}
// Displays the question for the category and dollar value
void display_question(char *category, int value)
{
for(int i = 0; i<NUM_QUESTIONS; i++){
if (strcmp(questions[i].category, category)==0 && questions[i].value==value){
printf("%s", &questions[i].question);
}
}
}
// Returns true if the answer is correct for the question for that category and dollar value
bool valid_answer(char *category, int value, char *answer)
{
// Look into string comparison functions
for(int i = 0; i<NUM_QUESTIONS; i++){
if (strcmp(questions[i].category, category)==0 && questions[i].value==value){
bool result = strcmp(answer, questions[i].answer)-10 == 0;
return result;
}
}
return false;
}
// Returns true if the question has already been answered
bool already_answered(char *category, int value)
{
// lookup the question and see if it's already been marked as answered
for(int i = 0; i<NUM_QUESTIONS; i++){
if (strcmp(questions[i].category, category)==0 && questions[i].value==value && questions[i].answered==true){
return true;
}
}
return false;
}
bool all_answered_status() {
for(int i = 0; i < 12; i++)
if(questions[i].answered == false)
return false;
return true;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <unistd.h>
#define c 2 //numero di centri di cluster
#define n 4 //numero di punti totale in input
double m = 2.0; //fuzzification
#define d 2 //dimensioni spaziali
double epsilon = 0.001; //minima distanza per arrestare
double x[n][d];
double v[c][d];
double u[c][n];
double distanza(double a[d], double b[d]) {
double somma = 0;
int i;
for (i = 0; i < d; i++)
somma += pow(a[i] - b[i], 2);
return sqrt(somma);
}
double aggiorna() {
int i, j, k, l;
double esp = 2.0 / (m - 1);
for (i = 0; i < c; i++)
for (j = 0; j < n; j++) { /* calcolo u[i][j] */
double somma = 0;
double num = distanza(x[j], v[i]);
for (k = 0; k < c; k++) {
double den = distanza(x[j], v[k]);
double fraz = num / den;
somma += pow(fraz, esp);
}
u[i][j] = 1.0 / somma;
}
double max_diff = 0;
for (i = 0; i < c; i++) {
double den = 0;
for (j = 0; j < n; j++)
den += pow(u[i][j], m);
double diff = 0;
for (k = 0; k < d; k++) { /* calcolo v[i][k] */
double num = 0;
for (j = 0; j < n; j++)
num += pow(u[i][j], m) * x[j][k];
double old_v = v[i][k];
v[i][k] = num / den;
diff += pow(old_v - v[i][k], 2);
}
if (diff > max_diff) max_diff = diff;
}
return max_diff;
}
void scriviSituazione() {
int i, j;
printf("matrice U\n");
for (i = 0; i < c; i++) {
for (j = 0; j < n; j++)
printf("%lf ", u[i][j]);
printf("\n");
}
printf("\n");
printf("matrice V\n");
for (i = 0; i < c; i++) {
for (j = 0; j < d; j++)
printf("%lf ", v[i][j]);
printf("\n");
}
printf("\n");
/* scrivere un numero per avanzare */
scanf("%*d");
}
void test() {
int i, j;
double max_diff;
srand48(3);
x[0][0] = 1.0;
x[0][1] = 2;
x[1][0] = 1.1;
x[1][1] = 2;
x[2][0] = 8.0;
x[2][1] = 4;
x[3][0] = 7.9;
x[3][1] = 4.1;
for (i = 0; i < c; i++)
for (j = 0; j < d; j++)
v[i][j] = 10 * drand48() - 5;
scriviSituazione();
do {
max_diff = aggiorna();
scriviSituazione();
} while (max_diff > epsilon);
}
int main() {
test();
}
|
C
|
#include"init.h"
void print_word(pMod pmod_head)
{
int i,j;
char print_word[20]={'\0'};
printf("输入要查找的单词\n");
scanf("%s",print_word);
pCh palit;
if(print_word[0]<='z'&&print_word[0]>='a')
{
i=(print_word[0]-'a');
}
if(print_word[0]<='Z'&&print_word[0]>='A')
{
i=(print_word[0]-'A');
}
j=strlen(print_word);
for(palit=pmod_head->mod[i]->and[j]->next;palit!=pmod_head->mod[i]->
and[j];palit=palit->next)
{
if(strcmp(palit->ch,print_word)==0)
{
printf("word : %s,file : %d,time : %d \n",palit->ch,palit->word,palit->time);
}
}
}
|
C
|
/* CoreGraphics - CGPDFScanner.h
* Copyright (c) 2004-2008 Apple Inc.
* All rights reserved. */
#ifndef CGPDFSCANNER_H_
#define CGPDFSCANNER_H_
typedef struct CGPDFScanner *CGPDFScannerRef;
#include <CoreGraphics/CGPDFContentStream.h>
#include <CoreGraphics/CGPDFOperatorTable.h>
/* Create a scanner. */
CG_EXTERN CGPDFScannerRef CGPDFScannerCreate(CGPDFContentStreamRef cs,
CGPDFOperatorTableRef table, void *info)
CG_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_2_0);
/* Retain `scanner'. */
CG_EXTERN CGPDFScannerRef CGPDFScannerRetain(CGPDFScannerRef scanner)
CG_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_2_0);
/* Release `scanner'. */
CG_EXTERN void CGPDFScannerRelease(CGPDFScannerRef scanner)
CG_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_2_0);
/* Scan the content stream of `scanner'. Returns true if the entire stream
was scanned successfully; false if scanning failed for some reason (for
example, if the stream's data is corrupted). */
CG_EXTERN bool CGPDFScannerScan(CGPDFScannerRef scanner)
CG_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_2_0);
/* Return the content stream associated with `scanner'. */
CG_EXTERN CGPDFContentStreamRef CGPDFScannerGetContentStream(CGPDFScannerRef
scanner) CG_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_2_0);
/* Pop an object from the stack of `scanner' and return it in `value'. */
CG_EXTERN bool CGPDFScannerPopObject(CGPDFScannerRef scanner,
CGPDFObjectRef *value) CG_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_2_0);
/* Pop an object from the stack of `scanner' and, if it's a boolean, return
it in `value'. Return false if the top of the stack isn't a boolean. */
CG_EXTERN bool CGPDFScannerPopBoolean(CGPDFScannerRef scanner,
CGPDFBoolean *value) CG_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_2_0);
/* Pop an object from the stack of `scanner' and, if it's an integer, return
it in `value'. Return false if the top of the stack isn't an integer. */
CG_EXTERN bool CGPDFScannerPopInteger(CGPDFScannerRef scanner,
CGPDFInteger *value) CG_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_2_0);
/* Pop an object from the stack of `scanner' and, if it's a number, return
it in `value'. Return false if the top of the stack isn't a number. */
CG_EXTERN bool CGPDFScannerPopNumber(CGPDFScannerRef scanner, CGPDFReal *value)
CG_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_2_0);
/* Pop an object from the stack of `scanner' and, if it's a name, return it
in `value'. Return false if the top of the stack isn't a name. */
CG_EXTERN bool CGPDFScannerPopName(CGPDFScannerRef scanner, const char **value)
CG_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_2_0);
/* Pop an object from the stack of `scanner' and, if it's a string, return
it in `value'. Return false if the top of the stack isn't a string. */
CG_EXTERN bool CGPDFScannerPopString(CGPDFScannerRef scanner,
CGPDFStringRef *value) CG_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_2_0);
/* Pop an object from the stack of `scanner' and, if it's an array, return
it in `value'. Return false if the top of the stack isn't an array. */
CG_EXTERN bool CGPDFScannerPopArray(CGPDFScannerRef scanner,
CGPDFArrayRef *value) CG_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_2_0);
/* Pop an object from the stack of `scanner' and, if it's a dictionary,
return it in `value'. Return false if the top of the stack isn't a
dictionary. */
CG_EXTERN bool CGPDFScannerPopDictionary(CGPDFScannerRef scanner,
CGPDFDictionaryRef *value)
CG_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_2_0);
/* Pop an object from the stack of `scanner' and, if it's a stream, return
it in `value'. Return false if the top of the stack isn't a stream. */
CG_EXTERN bool CGPDFScannerPopStream(CGPDFScannerRef scanner,
CGPDFStreamRef *value) CG_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_2_0);
#endif /* CGPDFSCANNER_H_ */
|
C
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <signal.h>
#include <sys/shm.h>
#include <time.h>
#include <sys/wait.h>
#include <sys/sem.h>
#include <sys/types.h>
#include "my_library.h"
#include "errExit.h"
char FifoServer[20]="FIFOSERVER";
char FifoClient[20];
pid_t pid;
int shmidInt;
int *ptr_count;
int shmid;
struct mynode *ptr_vet;
int semid;
const int semkey=1;
const int shmkey=2;
const int shmkeyint=3;
#define SIZE 300
#define TIME 300
void sigHandler(int sing) {
//DEALLOCATING RESOURCES, KILLING SERVER AND KEYMANAGER
if(sing==SIGTERM){
if(pid>0){
if(unlink(FifoServer)==-1)
printf("\n<Server> Deleting %s error\n", FifoServer);
kill(pid,SIGTERM);
if(shmdt(ptr_vet)==-1)
errExit("\nshmdt error for ptr_vet");
if(shmctl(shmid,IPC_RMID,NULL)==-1)
errExit("\nshmctl error for shmid");
if(shmdt(ptr_count)==-1)
errExit("\nshmdt error for ptr_count");
if(shmctl(shmidInt,IPC_RMID,NULL)==-1)
errExit("\nshmctl error for shmidInt");
if(semctl(semid, 0,IPC_RMID))
errExit("semctl error for deleting semset");
wait(NULL);
exit(0);
}
else
exit(0);
}
}
int main (int argc, char *argv[]) {
struct Request req;
struct Response resp;
//BLOCKING ALL SIGNALS BUT SIGTERM
sigset_t mySet;
if(sigfillset(&mySet)==-1)
errExit("\nsigfillset server error");
if(sigdelset(&mySet, SIGTERM)==-1)
errExit("\nsigdelset server error");
if(sigprocmask(SIG_SETMASK, &mySet, NULL)==-1)
errExit("\nsigprocmask server error");
if (signal(SIGTERM,sigHandler) == SIG_ERR)
errExit("change signal handler failed");
//CREATING SEMAPHORES SET
semid=semget(semkey, 1, IPC_CREAT | S_IWUSR | S_IRUSR);
if (semid == -1)
errExit("semget failed");
unsigned short semInitVal[] = {1};
union semun arg;
arg.array = semInitVal;
if(semctl(semid, 0, SETALL, arg))
errExit("semctl SETALL failed");
//CREATING SHARED MEMORY
shmid=shmget(shmkey,SIZE*sizeof(struct mynode), IPC_CREAT | S_IRUSR | S_IWUSR );
if(shmid==-1)
errExit("\n<Server> shmget error for shmid");
ptr_vet=(struct mynode *)shmat(shmid,NULL,0);
if(ptr_vet==(void *)-1)
errExit("\n<Server> shmat tr_vet\n");
//creating count for helping managing the entries in the shared nemory
shmidInt=shmget(shmkeyint,sizeof(int), IPC_CREAT | S_IRUSR | S_IWUSR );
if(shmidInt==-1)
errExit("\n<Server> shmget error for shmidInt");
ptr_count=(int *)shmat(shmidInt,NULL,0);
if(ptr_count==(void *)-1)
errExit("\n<Server> shmat tr_vet\n");
*ptr_count=0;
//WELCOME
printf("Hi, I'm Server program!\n");
//CREATING KEY MANAGER
pid = fork();
if (pid == -1)
printf("KeyManager not created!");
if (pid==0)
{
int i=0;
while(1)
{
printf("\n\n\nPrinting database...");
//verifying if there are out-of-time entries
for(i=0;i<*ptr_count;i++){
if( ((time_t)time(NULL))-(time_t)(ptr_vet[i].time) >= TIME){
//swap with the last entry of ptr_vet
semOp(semid,0 ,-1);
if(*ptr_count!=1){
strcpy(ptr_vet[i].id,ptr_vet[*ptr_count-1].id);
ptr_vet[i].key=ptr_vet[*ptr_count-1].key;
ptr_vet[i].time=ptr_vet[*ptr_count-1].time;
i=i-1;
}
(*ptr_count)--;
semOp(semid,0,1);
}
else{
if((*ptr_count)!=0){
printf("\n------------------");
printf("\nEntry number: %i\nId: %s\nKey: %ld\nTime in shared memory: %ld",i+1,ptr_vet[i].id,ptr_vet[i].key,(long int)time(NULL)-ptr_vet[i].time);
printf("\n------------------\n");
}
}
}
if(*ptr_count==0)
printf("\nDatabase empty...\n\n");
else
printf("\n\n");
sleep(30);
}
}
//CREATING FIFOSERVER
int fd=mkfifo(FifoServer, O_CREAT | S_IRUSR | S_IWUSR);
if(fd==-1)
errExit("\n<Server> MkFifo error\n");
//OPENIG FIFOSERVER
int fs=open(FifoServer, O_RDONLY);
if(fs==-1)
errExit("\n<Server> Open fifo error\n");
//OPENIG FIFOSERVER FAKECLIENT
int fake_fs=open(FifoServer, O_WRONLY);
if(fake_fs==-1)
errExit("\n<Client fake> Open fifo error\n");
//READING FIFOSERVER
while(1)
{
int br=read(fs,&req,sizeof(struct Request));
if (sizeof(req)!=sizeof(struct Request))
printf("\n<Server> %s looks broken", FifoServer);
if (br!=sizeof(struct Request))
printf("\n<Server> looks like you haven't recived a struct Requst\n");
//OPENING FIFOCLIENT
strcpy(FifoClient,req.fifo_name);
int fc=open(FifoClient, O_WRONLY);
if(fc==-1)
errExit("\n<Server> Open fifo error\n");
//GENERATING KEY
resp.key=getkey(req.servizio);
strcpy(resp.id,req.id);
strcpy(resp.servizio,req.servizio);
semOp(semid, 0 , -1);
if(*ptr_count==SIZE){
resp.key=-1;
}
else if(resp.key!=0){
long int a=(long int)time(NULL);
struct mynode m;
m.key=resp.key;
m.time=a;
strcpy(m.id,resp.id);
ptr_vet[*ptr_count]=m;
*ptr_count=*ptr_count+1;
}
semOp(semid, 0 , 1);
//WRITING IN FIFOCLIENT
printf("\nWriting back to client...\n");
ssize_t wr=write(fc,&resp,sizeof(struct Response));
if(wr!=sizeof(struct Response)){
int prova=sizeof(struct Response);
printf("\n\nValore di wr: %li, valore di prova: %i\n\n", wr,prova);
char buff1[30];
strcpy(buff1,"");
sprintf(buff1,"\n<Server> write error\n");
errExit(buff1);
}
}
return 0;
}
|
C
|
#include<stdio.h>
int main(){
char str[3];
int n,p,m;
scanf("%d",&n);
int i,j;
int plus=0,min=0;
for(i=1;i<=n;i++){
scanf("%s",str);
for(j=0;j<3;j++){
switch(str[j]){
case '+':
plus++;
break;
case '-':
min++;
break;
}
}
}
p=plus/2;
m=min/2;
int b;
b=p-m;
printf("%d",b);
return 0;
}
|
C
|
int main()
{
int i;
double mid;
double height;
double width;
double sum = 0.0;
double area;
double t1;
double t2;
t1 = gettimeofday_sec();
width = 1.0 / ((double) 100000000);
#pragma omp parallel for reduction(+:sum)
for (i = 0; i < 100000000; i++)
{
mid = (i + 0.5) * width;
height = 4.0 / (1.0 + (mid * mid));
sum += height;
}
area = width * sum;
t2 = gettimeofday_sec();
printf("pi=%1.20lf\n", area);
printf("time=%lf [sec]\n", (double) (t2 - t1));
return 0;
}
|
C
|
// Project: Manhattan Massacre
// University of Lethbridge - CPSC3710
// Project Deadline: April 1, 2019
// Gideon Richter, Brett Dziedzic, Michelle Le, Sean Herridge-Berry
#include <stdlib.h>
#include <stdio.h>
#include <GL/glut.h>
// Struct building
// Defined to store characteristics of the building objects in the game
struct building
{
int health;
double x; //X-coor of building relative to block center
double z; //Z-coor of building relative to block center
double sideLength; //Side length of building
double height; //Height length of building
};
struct building build={3,-10,-10,25,25};
void init()
{
glClearColor (0.0, 0.0, 0.0, 0.0);
}
void drawObjects(GLenum mode)
{
if(mode == GL_SELECT)
glLoadName(1);
if (build.health ==3){
glColor3f(1.0, 0.0, 0.0);
glRectf(-10, -10, 10.0, 10.0);
printf("health = %d\n", build.health);
}
if (build.health ==2){
glColor3f(1.0, 0.0, 0.0);
glRectf(-5, -5, 5.0, 5.0);
printf("health = %d\n", build.health);
}
if (build.health ==1){
glColor3f(1.0, 0.0, 0.0);
glRectf(-1.0, -1.0, 1, 1);
printf("health = %d\n", build.health);
}
}
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
drawObjects(GL_RENDER);
glFlush();
}
/* processHits prints out the contents of the
* selection array.
*/
void processHits (GLint hits, GLuint buffer[])
{
unsigned int i, j;
GLint names, *ptr;
printf ("hits = %d\n", hits);
ptr = (GLint *) buffer;
for (i = 0; i < hits; i++) { /* for each hit*/
names = *ptr;
ptr+=3;
for (j = 0; j < names; j++) { /* for each name*/
if(*ptr==1) printf ("red rectangle\n");
else printf ("blue rectangle\n");
ptr++;
}
printf ("\n");
}
}
#define SIZE 512
void mouse(int button, int state, int x, int y)
{
GLuint selectBuf[SIZE];
GLint hits;
GLint viewport[4];
if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN)
{
glGetIntegerv (GL_VIEWPORT, viewport);
glSelectBuffer (SIZE, selectBuf);
glRenderMode(GL_SELECT);
glInitNames();
glPushName(0);
glMatrixMode (GL_PROJECTION);
glPushMatrix ();
glLoadIdentity ();
/* create 5x5 pixel picking region near cursor location */
gluPickMatrix ((GLdouble) x, (GLdouble) (viewport[3] - y),
0.5, 0.5, viewport);
gluOrtho2D (-20.0, 20.0, -20.0, 20.0);
drawObjects(GL_SELECT);
glMatrixMode (GL_PROJECTION);
glPopMatrix ();
glFlush ();
hits = glRenderMode (GL_RENDER);
build.health = build.health - hits;
processHits (hits, selectBuf);
glutPostRedisplay();
}
}
void reshape(int w, int h)
{
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D (-20.0, 20.0, -20.0, 20.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
/* Main Loop */
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize (500, 500);
glutInitWindowPosition (100, 100);
glutCreateWindow (argv[0]);
init ();
glutReshapeFunc (reshape);
glutDisplayFunc(display);
glutMouseFunc (mouse);
glutMainLoop();
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
char **s;
s = malloc(sizeof(char *));
char foo[] = "Hello World";
*s = foo;
/*
printf("s is %s\n", s);
// We could leave it like this, and it would not cause a segmentation fault.
// However, in that case s is a pointer and it outputs garbage
// Let's fix it too.
*/
printf("s is %s\n", *s);
s[0] = foo;
printf("s[0] is %s\n", s[0]);
return (0);
}
|
C
|
#include "gpio.h"
#include "uart.h"
#include <stdio.h>
#include <unistd.h>
ssize_t _write(int fd, const void *buf, size_t count)
{
char *letter = (char *)(buf);
for (int i = 0; i < count; i++)
{
uart_send(*letter);
letter++;
}
return count;
}
int main()
{
uart_init();
// Configure LED Matrix
for (int i = 4; i <= 15; i++)
{
GPIO->DIRSET = (1 << i);
GPIO->OUTCLR = (1 << i);
}
// Configure buttons
GPIO->PIN_CNF[17] = 0;
GPIO->PIN_CNF[26] = 0;
int sleep = 0;
int status = 0;
while (1)
{
if (!(GPIO->IN & (1 << 26)))
{
uart_send('b');
}
if (!(GPIO->IN & (1 << 17)))
{
uart_send('a');
}
char c = uart_read();
// Check if button B is pressed;
// turn on LED matrix if it is.
if (!status && c != '\0')
{
GPIO->OUTSET = (1 << 13);
GPIO->OUTSET = (1 << 14);
GPIO->OUTSET = (1 << 15);
status = 1;
}
// Check if button A is pressed;
// turn off LED matrix if it is.
else if (status && c != '\0')
{
GPIO->OUTCLR = (1 << 13);
GPIO->OUTCLR = (1 << 14);
GPIO->OUTCLR = (1 << 15);
status = 0;
}
sleep = 1000;
while (sleep)
{
sleep--;
}
//iprintf("The average grade in TTK%d was in %d and %d: %c\n\r",4235,2019,2018,'C');
}
return 0;
}
|
C
|
// This program sets the rounding mode and so must set this pragma to tell the
// compiler we will be using/modifying the floating point environment.
// Otherwise the program would be undefined (See 7.6.1 The FENV_ACCESS pragama
// - C11 specification).
#pragma STDC FENV_ACCESS ON
#ifdef KLEE
#include "klee/klee.h"
#endif
#include <assert.h>
#include <fenv.h>
#include <inttypes.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h> // For memcpy()
#ifndef BUG
#error BUG must be defined to be 0 or 1
#endif
typedef struct {
double rne;
double ru;
double rd;
double rz;
} Result;
void setRoundingMode(int rm) {
int result = fesetround(rm);
assert(result == 0);
int newRoundingMode = fegetround();
assert(newRoundingMode != -1);
assert(newRoundingMode == rm);
}
int isNaNOrInf(double d) {
return isnan(d) | isinf(d);
}
double toDouble(uint64_t data) {
assert(sizeof(uint64_t) == sizeof(double));
double initialValue = 0.0;
memcpy(&initialValue, &data, sizeof(double));
return initialValue;
}
uint64_t toBitsFromDouble(double d) {
assert(sizeof(uint64_t) == sizeof(double));
uint64_t toReturn;
memcpy(&toReturn, &d, sizeof(double));
return toReturn;
}
void printFloat(const char* lead, double d) {
printf("%s: %.40e (hexfloat: %a) (bits: 0x%" PRIx64 ")\n", lead, d, d, toBitsFromDouble(d));
fflush(stdout);
}
// This is a hack to prevent clang from optimizing
// the calls to sqrt() such that the rounding mode has
// no effect.
__attribute__((noinline)) double callSqrt(double d) {
double temp = sqrt(d);
return temp;
}
int main(int argc, char **argv) {
// This value should trigger the bug and was found using
// LibFuzzer.
double initialValue = 0x1.727782de12fafp-365;
#ifdef KLEE
klee_make_symbolic(&initialValue, sizeof(double), "initialValue");
#else
printFloat("Initial Value", initialValue);
#endif
if (isnan(initialValue) || isinf(initialValue)) {
// Not interesting here
return 0;
}
Result r;
setRoundingMode(FE_TONEAREST);
r.rne = callSqrt(initialValue);
setRoundingMode(FE_UPWARD);
r.ru = callSqrt(initialValue);
setRoundingMode(FE_DOWNWARD);
r.rd = callSqrt(initialValue);
setRoundingMode(FE_TOWARDZERO);
r.rz = callSqrt(initialValue);
#ifndef KLEE
printFloat("Result RNE", r.rne);
printFloat("Result RU ", r.ru);
printFloat("Result RD ", r.rd);
printFloat("Result RZ ", r.rz);
#endif
setRoundingMode(FE_TONEAREST);
// sqrt() of -ve number should give a NaN
if (initialValue < 0.0) {
assert(isnan(r.rne));
assert(isnan(r.ru));
assert(isnan(r.rd));
assert(isnan(r.rz));
return 0;
}
assert(!isNaNOrInf(r.rne));
assert(!isNaNOrInf(r.ru));
assert(!isNaNOrInf(r.rd));
assert(!isNaNOrInf(r.rz));
// sqrt() should not return a negative value so this should
// always hold.
assert(r.rd == r.rz);
#if !BUG
if ((r.ru * r.ru) != initialValue && !(r.ru == r.rd & r.ru == 0.0)) {
// InitialValue is not a perfect square and result wasn't zero
// (could happen because value being square rooted was very small
// or it was zero).
#else
if (1) {
#endif
assert(r.ru > r.rd);
}
#if !BUG
assert(r.rne == r.ru | r.rne == r.rd);
#else
assert(r.rne == r.ru);
#endif
return 0;
}
|
C
|
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <uv.h>
#ifdef _WIN32
#include <windows.h>
bool owns_tty(void)
{
HWND consoleWnd = GetConsoleWindow();
DWORD dwProcessId;
GetWindowThreadProcessId(consoleWnd, &dwProcessId);
return GetCurrentProcessId() == dwProcessId;
}
#else
bool owns_tty(void)
{
// TODO: Check if the process is the session leader
return true;
}
#endif
#define is_terminal(stream) (uv_guess_handle(fileno(stream)) == UV_TTY)
#define BUF_SIZE 0xfff
static void walk_cb(uv_handle_t *handle, void *arg) {
if (!uv_is_closing(handle)) {
uv_close(handle, NULL);
}
}
static void sigwinch_cb(uv_signal_t *handle, int signum)
{
int width, height;
uv_tty_t *tty = handle->data;
uv_tty_get_winsize(tty, &width, &height);
fprintf(stderr, "screen resized. rows: %d, columns: %d\n", height, width);
}
static void sigint_cb(uv_signal_t *handle, int signum)
{
bool *interrupted = handle->data;
if (*interrupted) {
uv_walk(uv_default_loop(), walk_cb, NULL);
return;
}
*interrupted = true;
fprintf(stderr, "interrupt received, press again to exit\n");
}
static void alloc_cb(uv_handle_t *handle, size_t suggested, uv_buf_t *buf)
{
buf->len = BUF_SIZE;
buf->base = malloc(BUF_SIZE);
}
static void read_cb(uv_stream_t *stream, ssize_t cnt, const uv_buf_t *buf)
{
if (cnt <= 0) {
uv_read_stop(stream);
return;
}
fprintf(stderr, "received data: ");
uv_loop_t write_loop;
uv_loop_init(&write_loop);
uv_tty_t out;
uv_tty_init(&write_loop, &out, 1, 0);
uv_write_t req;
uv_buf_t b = {.base = buf->base, .len = buf->len};
uv_write(&req, (uv_stream_t *)&out, &b, 1, NULL);
uv_run(&write_loop, UV_RUN_DEFAULT);
uv_close((uv_handle_t *)&out, NULL);
uv_run(&write_loop, UV_RUN_DEFAULT);
if (uv_loop_close(&write_loop)) {
abort();
}
free(buf->base);
}
int main(int argc, char **argv)
{
if (!is_terminal(stdin)) {
fprintf(stderr, "stdin is not a terminal\n");
exit(2);
}
if (!is_terminal(stdout)) {
fprintf(stderr, "stdout is not a terminal\n");
exit(2);
}
if (!is_terminal(stderr)) {
fprintf(stderr, "stderr is not a terminal\n");
exit(2);
}
bool interrupted = false;
fprintf(stderr, "tty ready\n");
uv_tty_t tty;
uv_tty_init(uv_default_loop(), &tty, fileno(stderr), 1);
uv_read_start((uv_stream_t *)&tty, alloc_cb, read_cb);
uv_signal_t sigwinch_watcher, sigint_watcher;
uv_signal_init(uv_default_loop(), &sigwinch_watcher);
sigwinch_watcher.data = &tty;
uv_signal_start(&sigwinch_watcher, sigwinch_cb, SIGWINCH);
uv_signal_init(uv_default_loop(), &sigint_watcher);
sigint_watcher.data = &interrupted;
uv_signal_start(&sigint_watcher, sigint_cb, SIGINT);
uv_run(uv_default_loop(), UV_RUN_DEFAULT);
fprintf(stderr, "tty done\n");
}
|
C
|
//
// pr_pset04_04:
//
// Write a program that requests your height in inches and your name, and then
// displays the information in the following form:
//
// Dabney, you are 6.208 feet tall
//
// Use type float, and use / for division. If you prefer, request the height
// in centimeters and display it in meters.
//
#include <stdio.h>
int main(void)
{
char name[20];
float height;
printf("Enter your name: ");
scanf("%s", name);
printf("Enter your height in centimeters: ");
scanf("%f", &height);
// Convert centimeters into meters.
height = height / 100.0;
printf("%s, you are %.2f meters tall.\n", name, height);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
struct node
{
int key;
struct node *left, *right;
};
int c=0;
// A utility function to create a new BST node
struct node* newNode(int item)
{
struct node* temp
= (struct node*)malloc(sizeof(struct node));
temp->key = item;
temp->left = temp->right = NULL;
return temp;
}
// A utility function to do inorder traversal of BST
void inorder(struct node* root)
{
if (root != NULL) {
inorder(root->left);
printf("%d ", root->key);
inorder(root->right);
}
}
struct node* search(struct node* root, int key)
{
// Base Cases: root is null or key is present at root
if (root == NULL || root->key==key)
return root;
// Key is greater than root's key
else if (root->key>key)
return search(root->right, key);
else// Key is smaller than root's key
return search(root->left, key);
}
// A utility function to insert a new node with given key in BST
struct node* insert(struct node* node, int key)
{
/* If the tree is empty, return a new node */
if (node == NULL)
return newNode(key);
/* Otherwise, recur down the tree */
if (key < node->key)
node->left = insert(node->left, key);
else
node->right = insert(node->right, key);
/* return the (unchanged) node pointer */
return node;
}
/* Given a non-empty binary search tree, return the node with minimum key value found in
that tree. Note that the entire tree does not need to be searched. */
struct node* minValueNode(struct node* node)
{
struct node* current = node;
/* loop down to find the leftmost leaf */
while (current && current->left != NULL)
current = current->left;
return current;
}
//Given a binary search tree and a key, this function deletes the key and returns the new root
struct node* deleteNode(struct node* root, int key)
{
// base case
if (root == NULL)
return root;
// If the key to be deleted
// is smaller than the root's
// key, then it lies in left subtree
if (key < root->key)
root->left = deleteNode(root->left, key);
// If the key to be deleted
// is greater than the root's
// key, then it lies in right subtree
else if (key > root->key)
root->right = deleteNode(root->right, key);
// if key is same as root's key,
// then This is the node
// to be deleted
else {
// node with only one child or no child
if (root->left == NULL) {
struct node* temp = root->right;
free(root);
return temp;
}
else if (root->right == NULL) {
struct node* temp = root->left;
free(root);
return temp;
}
// node with two children:
// Get the inorder successor
// (smallest in the right subtree)
struct node* temp = minValueNode(root->right);
// Copy the inorder
// successor's content to this node
root->key = temp->key;
// Delete the inorder successor
root->right = deleteNode(root->right, temp->key);
}
return root;
}
void min_max(struct node* node)
{
struct node* min=node;
struct node* max=node;
while(min->left!=NULL)
min=min->left;
while(max->right!=NULL)
max=max->right;
printf("\nThe minimum value present in the given BST is: %d ",min->key);
printf("\nThe maximum value present in the given BST is: %d ",max->key);
}
void kth_min(struct node* root, int k)
{
if(root==NULL)
return;
else
{
kth_min(root->left,k);
c++;
if(c==k)
printf("\nThe Kth minimum value in the BST for k=%d is: %d",k,root->key);
kth_min(root->right,k);
}
}
// Driver Code
int main()
{
/* Let us create a default BST
50
/ \
30 70
/ \ / \
20 40 60 80 */
struct node* root = NULL;
root = insert(root, 50);
root = insert(root, 30);
root = insert(root, 20);
root = insert(root, 40);
root = insert(root, 70);
root = insert(root, 60);
root = insert(root, 80);
printf("Inorder traversal of the default Binary Search Tree \n");
inorder(root);
printf("\nWelcome!\nPlease Enter\n1 - To insert element in the BST\n2 - To delete element in the BST\n3 - To determine the Minimum and maximum element in the BST\n4 - To determine the kth minimum element\nOr any other number to exit\n");
int choice;
scanf("%d",&choice);
int flag=0;
while(flag==0)
{
switch(choice)
{
case 1: if(root!=NULL)
{
printf("Enter the value to be inserted\n");
int t;
scanf("%d",&t);
struct node* temp=search(root,t);
if(temp==NULL)
{
insert(root,t);
printf("\nInserted\n");
printf("\nInorder traversal of the BST \n");
inorder(root);
printf("\n");
}
else
printf("Value already present\n");
}
break;
case 2: if(root!=NULL)
{
printf("Enter the value to be deleted\n");
int t;
scanf("%d",&t);
struct node* temp=search(root,t);
deleteNode(root,t);
printf("\nDeleted\n");
printf("\nInorder traversal of the BST \n");
inorder(root);
printf("\n");
}
break;
case 3: min_max(root);
printf("\n");
break;
case 4: printf("Enter the value of k\n");
int k;
scanf("%d",&k);
kth_min(root,k);
printf("\n");
break;
default:printf("\nThank You!\n");
flag=1;
}
if(flag==0)
{
printf("\nEnter Choice\n");
scanf("%d",&choice);
}
}
return 0;
}
|
C
|
#include <sys/utsname.h>
#include "g_unix.h"
/**
struct utsname
{
char sysname[65];
char nodename[65];
char release[65];
char version[65];
char machine[65];
char __domainname[65];
};
**/
int main(int argc ,char** argv)
{
struct utsname un;
if ( 0 > uname(&un) )
{
err_quit("%s:err",basename(argv[0]));
}
if ( argc == 1 )
{
printf("%s\n", un.sysname);
}
/**
else if( argc==2 && (0 ==strcmp(argv[1],"-a") ))
**/
else if( argc==2 && !strcmp(argv[1],"-a") )
{
printf("%s %s %s %s %s %s\n",
un.sysname,
un.nodename,
un.release,
un.version,
un.machine,
un.__domainname);
}
else if( argc==2 && !strcmp(argv[1],"-r") )
{
printf("%s\n", un.release);
}
else if( argc==2 && !strcmp(argv[1],"-v") )
{
printf("%s\n", un.version );
}
else if( argc==2 && !strcmp(argv[1],"-n") )
{
printf("%s\n", un.nodename );
}
else if( argc==2 && !strcmp(argv[1],"-m") )
{
printf("%s\n", un.machine);
}
else
{
printf( "无效选项\n" );
}
return 0;
}
|
C
|
#include<stdio.h>
#include<conio.h>
void main()
{
int n,s=0,d,x;
printf("Enter a Number");
scanf("%d",&n);
x=n;
while(n!=0)
{
d=n%10;
s=s+(d*d*d);
n=n/10;
}
if(s==x)
printf("%d is an armstrong number",x);
else
printf("%d is not an Armstrong Number",x);
getch();
}
|
C
|
/** Module Header **/
#include "system_timers.h"
/** Std C Headers **/
#include <string.h>
/** BBMC Headers **/
#include "uartStdio.h"
#include "cmdline.h"
/** Internal Data Types
*
*/
//TODO: add a timer state data type
/** Internal Data
*
*/
//TODO: add an internal static state for each timer
/** System Timer Functions
*
*/
int
timer_enable (unsigned int timer)
{
int ret;
if (timer == TIMER_RUN)
{
dev_timer_1_enable();
ret = 0;
}
else if (timer == TIMER_GOTO)
{
dev_timer_2_enable();
ret = 1;
}
else if (timer == TIMER_RMPI)
{
dev_timer_3_enable();
ret = 2;
}
else if (timer == TIMER_STOP)
{
dev_timer_4_enable();
ret = 3;
}
else
{
ret = -1;
}
return ret;
}
int
timer_disable (unsigned int timer)
{
int ret;
if (timer == TIMER_RUN)
{
dev_timer_1_disable();
ret = 0;
}
else if (timer == TIMER_GOTO)
{
dev_timer_2_disable();
ret = 1;
}
else if (timer == TIMER_RMPI)
{
dev_timer_3_disable();
ret = 2;
}
else if (timer == TIMER_STOP)
{
dev_timer_4_disable();
ret = 3;
}
else
{
ret = -1;
}
return ret;
}
int
timer_frequency_get (unsigned int timer, unsigned int *frequency)
{
return dev_timer_frequency_get (timer, frequency);
}
int
timer_frequency_set (unsigned int timer, double frequency)
{
unsigned int count;
if (frequency < 0)
{
return -1;
}
frequency = DMTIMER_SYSTEM_CLK_DEFAULT / frequency;
count = DMTIMER_COUNT_MAX - (unsigned int)frequency;
return dev_timer_frequency_set (timer, count);
}
int
timer_print (const char *format)
{
UARTprintf("\r\n%sControl Timer Configurations: \r\n", format);
unsigned int freq;
timer_frequency_get(TIMER_RUN, &freq);
UARTprintf("\r\n%stimer::run := %d Hz", format, freq);
timer_frequency_get(TIMER_GOTO, &freq);
UARTprintf("\r\n%stimer::goto := %d Hz", format, freq);
timer_frequency_get(TIMER_RMPI, &freq);
UARTprintf("\r\n%stimer::rmpi := %d Hz", format, freq);
timer_frequency_get(TIMER_STOP, &freq);
UARTprintf("\r\n%stimer::stop := %d Hz", format, freq);
CmdLineNewline(2);
return 0;
}
/**
*
*/
|
C
|
#ifndef buf_HEADER
#define buf_HEADER
/**
* buf creates a basic, generic buffer object for binary translator. If ownership
* of a buffer is going to be passed, it is best to pass it in a buf object.
*/
#include "object.h"
#include <stdint.h>
#include <stdlib.h>
struct buf {
struct object_header oh;
uint8_t * buf;
size_t length;
};
/**
* Create a buf object with a buffer of specified length.
* @param length The length of the buffer.
* @return An initialized buffer object with a buffer of size length.
*/
struct buf * buf_create (size_t length);
/**
* Delete a buffer object. You should not call this, call ODEL()
* @param buf The buf to delete.
*/
void buf_delete (struct buf * buf);
/**
* Copy a buffer object. You should not call this, call OCOPY()
* @param buf A pointer to the buf to copy.
* @return A copy of the given buf.
*/
struct buf * buf_copy (const struct buf * buf);
/**
* Get the length of the buf in bytes.
* @param buf The buf we want the length of.
* @return The length of the buf in bytes.
*/
size_t buf_length (const struct buf * buf);
/**
* Slices out a sub-portion of a given buf, and returns it in a new buf object.
* @param buf The buf we are slicing out of.
* @param offset An offset into the buf, in bytes, where our slice will begin.
* @param size The size of our slice in bytes.
* @return A pointer to a buf which contains the slice, or NULL if the slice
* would not fall within the bounds of this buf.
*/
struct buf * buf_slice (const struct buf * buf, size_t offset, size_t size);
/**
* Returns a pointer to the data contained within a buf.
* @param buf A pointer to the buf we want data out of.
* @param offset An offset into the buf, in bytes, to the data we want.
* @param size The number of bytes we want to retrieve from the buf.
* @return A pointer to the data, or NULL if the requested offset and size
* references data outside the bounds of the buf.
*/
const void * buf_get (const struct buf * buf, size_t offset, size_t size);
/**
* Sets data in the buf.
* @param buf The buf we are setting data in.
* @param offset An offset into the buf, in bytes, where this operation begins.
* @param length The length of the data we are setting, in bytes.
* @param data A pointer to the bytes we want to set in this buf.
* @return 0 on success, or non-zero on failure. This call will fail if the
* offset and length will cause data to be written outside the bounds of
* this buf.
*/
int buf_set (const struct buf * buf,
size_t offset,
size_t length,
const void * data);
#endif
|
C
|
/* QTɑMEMBER, INSERT, MIN, DELETẼvO
iPȃASYj */
#include <stdio.h>
#include <stdlib.h>
enum yn {yes, no}; /* ^f[^yn̒` */
enum LR {LEFT, RIGHT};
struct node /* \node̐錾 */
{
int element;
struct node *left;
struct node *right;
};
/* ̐錾 */
enum yn member(int x, struct node *init);
struct node *insert(int x, struct node *init);
int min(struct node *init);
struct node *delete(int x, struct node *init);
struct node *off(struct node *p);
void printpre(struct node *p);
void inorder(struct node *p);
main()
/* QT̏̃eXgvO */
{
struct node *init;
int i, x;
enum yn a;
init=NULL;
for(i=0; i<10; i++) init=insert((8-3*i)*(2-i/2), init);
init=insert(30, init);
init=insert(25, init);
init=insert(31, init);
init=insert(37, init);
printf("init = %p\n", init);
printf("inorder\n");
if(init != NULL) inorder(init);
printf("preorder\n");
if(init != NULL) printpre(init);
x=31;
a=member(x, init);
if(a==yes) printf("Yes: x = %d\n", x);
else printf("No: x = %d\n", x);
x=-2;
a=member(x, init);
if(a==yes) printf("Yes: x = %d\n", x);
else printf("No: x = %d\n", x);
x=min(init);
printf("min = %d\n", x);
x=16;
init=delete(x, init);
printf("deleted x = %d\n", x);
printf("init = %p\n", init);
if(init != NULL) printpre(init);
x=32;
init=delete(x, init);
printf("deleted x = %d\n", x);
printf("init = %p\n", init);
if(init != NULL) printpre(init);
x=37;
init=delete(x, init);
printf("deleted x = %d\n", x);
printf("init = %p\n", init);
if(init != NULL) printpre(init);
return(0);
}
enum yn member(int x, struct node *init)
/* initwQTx݂̑ */
{
struct node *q;
q=init; /* initTJn */
while(q!=NULL)
{
if(q->element == x) return(yes); /* x */
if(q->element < x) q = q->right;
else q = q->left;
}
return(no); /* x݂ */
}
struct node *insert(int x, struct node *init)
/* initwQTx}AinitXV */
{
struct node *p, *q, *r;
p=(struct node *)malloc(sizeof(struct node)); /* V|C^ */
q=init; /* initTJn */
if(init==NULL) init=p;
while(q!=NULL)
{
if(q->element == x) {free(p); return(init);} /* x͂łɑ */
r = q;
if(q->element < x) /* E̎q */
{
q = q->right;
if(q==NULL) r->right = p;
}
else /* ̎q */
{
q = q->left;
if(q==NULL) r->left = p;
}
}
p->element = x; /* x} */
p->left = p->right = NULL;
return(init);
}
int min(struct node *init)
/* initwQT̍ŏvfo */
{
struct node *q, *r;
q=init; /* 獶[̘H */
if(q==NULL) {printf("Error: Tree is empty.\n"); exit(1);} /* ͋ */
while(q!=NULL)
{
r = q; q = q->left;
}
return(r->element); /* ʂԂ */
}
struct node *delete(int x, struct node *init)
/* initwQTvfxAinit̍XV */
{
struct node *q, *r, *p; /* q͒T̃|C^Ar͂̐e */
int side; /* side==1: r̉E̎qqA0: ̎qq */
q=init; /* T̊Jn */
while(q!=NULL)
{
if(q->element == x) /* x̔ */
{
p=off(q); /* x̃ZqAq̕XV */
if(p==NULL) /* ͋ */
{
if(q==init) init=NULL; /* qinitłꍇ */
else /* ̑̏ꍇ */
{
if(side==1) r->right = NULL;
else r->left = NULL;
}
}
return(init); /* I */
}
r=q; /* T𑱂 */
if(r->element < x) {q = r->right; side=1;}
else {q = r->left; side=0;}
}
return(init);
}
struct node *off(struct node *p)
/* |C^pwߓ_Ap̕XV */
{
struct node *q, *r, *s; /* q͒T̃|C^Ar͂̐eAsr̐e */
int side;
if(p->left==NULL && p->right==NULL) return(NULL); /* p̎q͋ɋ */
if(p->left==NULL || p->right==NULL) /* p̎q̈ */
{
if(p->left == NULL) q=p->right; /* łȂp֏グ */
else q=p->left;
p->element = q->element;
p->left = q->left;
p->right = q->right;
return(p);
}
s=p; side=1; /* p̎q͋ɑ */
r = s->right; /* p̉E̍̕ŏvfT */
q = r->left;
while(q!=NULL)
{
s=r; side=0;
r = q; q = r->left;
}
p->element = r->element;
r=off(r); /* ŏvfȑGċAIs */
if(r==NULL) /* ȑꍇ */
{
if(side==1) s->right = NULL;
else s->left = NULL;
}
return(p);
}
void printpre(struct node *p)
/* Print all children of node *p in preorder. */
{
printf("p = %p, element = %d, left = %p, right = %p\n",
p, p->element, p->left, p->right);
if(p->left != NULL) printpre(p->left);
if(p->right != NULL) printpre(p->right);
return;
}
void inorder(struct node *p)
/* Print all children of node *p in inorder. */
{
if(p->left != NULL) inorder(p->left); /* ̎q̂Ȃ */
printf("p = %p, element = %d, left = %p, right = %p\n",
p, p->element, p->left, p->right); /* pwߓ_̏o */
if(p->right != NULL) inorder(p->right); /* E̎q̂Ȃ */
return;
}
|
C
|
#include <fcgi_stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>
#include <sys/dir.h>
#include "lib/paranoia/paranoia.h"
#include "cfg.h"
const char* css =
"#page{"
"background:rgba(137,232,148,.1);"
"padding:3px;"
"}"
"#path{"
"margin:3px;"
"}"
"#path a{"
"color:#000;"
"font-size:80%;"
"padding:2px 9px;"
"margin:3px 4px;"
"background:#89E894;"
"}"
"#path a:hover{"
"color:#89E894;"
"background:transparent;"
"}"
"#list{"
"width:100%;"
"padding-bottom:100px;"
"}"
"#list a{"
"color:#89E894;"
"display:block;"
"padding:0 4px;"
"}"
"#list a:hover{"
"color:#000;"
"background:#89E894;"
"}"
;
#define MAX_DEPTH 8
typedef struct {
char* start;
int length;
} node;
int myalphasort(const struct dirent** e1, const struct dirent** e2)
{
const char* a = (*e1)->d_name;
const char* b = (*e2)->d_name;
return strcasecmp(a, b);
}
void print_directory(const char* path)
{
char path_esc[escape_string(path, NULL)];
escape_string(path, path_esc);
char path_esc_x[strlen(path_esc)+1];
strcpy(path_esc_x, path_esc);
spaceplus(path_esc_x);
int i = 0;
int ni = 0;
int wl = 0;
node nodes[MAX_DEPTH];
node nodes_x[MAX_DEPTH];
for (; ni < MAX_DEPTH && i < strlen(path_esc)+1; i++) {
if (path_esc[i] == '/' || path_esc[i] == '\0') {
if (wl) {
nodes[ni].length = nodes_x[ni].length = wl;
ni++;
wl = 0;
}
} else {
if (!wl) {
nodes[ni].start = &path_esc[i];
nodes_x[ni].start = &path_esc_x[i];
}
wl++;
}
}
char loc[2048] = CFG_DIR_STORAGE "/";
strcat(loc, path);
struct dirent** namelist = NULL;
int n = scandir(loc, &namelist, 0, myalphasort);
if (n < 0) {
print_html_error("Unable to open the specified directory.");
} else {
DIR *d = opendir(loc);
/* Iterate through the top-level dir */
if ( d ) {
struct stat st;
/* The path */
printf("<div id=\"path\">");
printf("<a href=\"dat\">/</a>");
char path_x[2048];
char path_nox[2048];
char path_node[2048];
char path_node_x[2048];
for (int i = 0; i < ni; i++) {
strcpy(path_node, nodes[i].start);
path_node[nodes[i].length] = 0x00;
strcpy(path_node_x, nodes_x[i].start);
path_node_x[nodes_x[i].length] = 0x00;
if (strlen(path_nox))
strcat(path_nox, "/");
strcat(path_nox, path_node);
if (strlen(path_x))
strcat(path_x, "/");
strcat(path_x, path_node_x);
printf("<a href=\"dat?%s\">%s</a>", path_x, path_node);
}
printf("</div>");
/* File/directory list */
printf("<div id=\"list\">");
/* List subdirectories first */
for (i = 0; i < n ; i++) {
if (IS_DOT(namelist[i]->d_name)) continue; // Skip dots
fstatat(dirfd(d), namelist[i]->d_name, &st, 0);
if (S_ISDIR(st.st_mode)) {
char safe_name[escape_string(namelist[i]->d_name, NULL)];
escape_string(namelist[i]->d_name, safe_name);
char safe_name_x[strlen(safe_name) + 1];
strcpy(safe_name_x, safe_name);
spaceplus(safe_name_x);
if (strlen(path_x))
printf("<a class=\"d\" href=\"/dat?%s/%s\">□ %s</a>",
path_x, safe_name_x, safe_name);
else
printf("<a class=\"d\" href=\"/dat?%s\">□ %s</a>",
safe_name_x, safe_name);
}
}
/* Then list the files */
for (i = 0; i < n; i++) {
if (IS_DOT(namelist[i]->d_name)) continue; // Skip dots
fstatat(dirfd(d), namelist[i]->d_name, &st, 0);
if (S_ISREG(st.st_mode)) {
char safe_name[escape_string(namelist[i]->d_name, NULL)];
escape_string(namelist[i]->d_name, safe_name);
if (strlen(path_nox))
printf("<a class=\"f\" "
"href=\"/"CFG_DIR_STORAGE"/%s/%s\">■ %s</a>",
path_nox, safe_name, safe_name);
else
printf("<a class=\"f\" "
"href=\"/"CFG_DIR_STORAGE"/%s\">■ %s</a>",
safe_name, safe_name);
}
}
printf("</div>");
closedir(d);
}
}
}
int main(const int argc, char **args)
{
char* query = (getenv("QUERY_STRING")) ? getenv("QUERY_STRING")
: (argc > 1 ? args[1] : "");
url_decode(query);
/* Filter the input */
int i = 0, l = strlen(query);
for (; i < l; i++) {
/* No .. */
if (query[i] == '.' && query[i+1] == '.') {
query[i] = 0x00;
break;
}
/* Prevent from possible overflow within strcat */
if (i == 256) {
query[i] = 0x00;
break;
}
}
while (FCGI_Accept() >= 0) {
print_html_header("73 74 6F 72 61 67 65 00", css);
print_directory(query);
print_html_footer();
}
return 0;
}
|
C
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: slynn-ev <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/03/01 14:29:54 by slynn-ev #+# #+# */
/* Updated: 2018/03/02 12:45:26 by slynn-ev ### ########.fr */
/* */
/* ************************************************************************** */
#include "push_swap.h"
void free_all(t_stack *a, t_list *cmnd)
{
t_pslst *tmp;
t_list *tmp_a;
while (a->head)
{
tmp = a->head;
a->head = a->head->nxt;
free(tmp);
}
while (cmnd)
{
tmp_a = cmnd;
free(cmnd->content);
cmnd = cmnd->next;
free(tmp_a);
}
free(a->p);
}
int main(int ac, char **av)
{
t_stack a;
t_stack b;
t_list *cmnd;
build_stack(&a, &b, av, ac);
if (!(a.p = malloc(sizeof(t_pslst*) * ac)) ||
!(b.p = malloc(sizeof(t_pslst*) * ac)))
exit(1);
a.ac = ac;
b.ac = ac;
a.top = 0;
b.top = 0;
a.p[a.top] = NULL;
b.p[a.top] = NULL;
cmnd = solver(&a, &b);
while (cmnd != NULL)
{
ft_putstr((char *)cmnd->content);
cmnd = cmnd->next;
}
free(b.p);
free_all(&a, cmnd);
}
|
C
|
int mystrlen(char *str)
{
int counter = 0;
char *p = str;
while (*p)
{
p++;
counter++;
}
return counter;
}
char *mystrncpy(char *dest, char *source, int n)
{
int i;
char *p = dest;
for (i = 0; i < n; i++)
{
*dest = *source;
dest++;
source++;
}
return p;
}
char *mystrcpy(char *dest, char *source)
{
return mystrncpy(dest, source, strlen(source)+1);
}
char *mystrncat(char *dest, char *source, int n)
{
int len_dest = mystrlen(dest);
int i;
for (i = 0; i < n; i++)
{
dest[len_dest + i] = source[i];
}
dest[len_dest + n] = '\0';
return dest;
}
char *mystrcat(char *dest, char *source)
{
int len_dest = mystrlen(dest);
int i = 0;
while (source[i])
{
dest[len_dest + i] = source[i];
i++;
}
dest[len_dest + i] = source[i];
return dest;
}
int mystrcmp(char *s1, char *s2)
{
while ((*s1 == *s2) && (*s1 != '\0' || *s2 != '\0'))
{
s1++;
s2++;
}
return *s1 - *s2;
}
char *mystrchr(char *s, char c){
while(*s != c){
if(*s == 0){
return 0;
}
s++;
}
return s;
}
|
C
|
#include "../inc/down_task.h"
#include <pthread.h>
#include <curl/curl.h>
/*
* 为了达到能同时创建多个下载任务,采用多线程的方法进行
* 线程上限目前先约定为50
* */
int now_down_task_count = 0; //设计到数据同步访问
int prepare_down_task()
{
curl_global_init(CURL_GLOBAL_ALL);
return 0;
}
static size_t write_data(void *ptr, size_t size, size_t nmemb, void *stream)
{
size_t written = fwrite(ptr, size, nmemb, (FILE *)stream);
return written;
}
void *down_task(void *url)
{
/*
* 若正在下载任务数小于最大并行下载数限制,则直接创建新的下载线程;
* 若正在下载数大于限制数,将该任务扔到任务列表中去;
* 在每一个任务下载玩之后去任务列表中找出第一下进行下载。
* */
CURL *curl;
curl = curl_easy_init();
// char file_name[16], *url_out;
// strncpy(file_name, url, 16);
// url_out = (unsigned char *)(&url[16]);
//还需要用数据库的id对文件进行取名
char file_name[16]="abc\0";
FILE *fp = fopen(file_name, "wb");
if(fp == NULL)
{
fprintf(stderr, "fopen error\n");
}
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
curl_easy_perform(curl);
fclose(fp);
curl_easy_cleanup(curl);
return 0;
}
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include "utils.h"
#include "buildtext.h"
void print_usage(char *name) {
printf("Usage: %s [-u | -l | -r | -R | -a POSTFIX | -p PREFIX | -m COUNT]...\n", name);
}
void print_options() {
puts("Available options:");
puts(" -u Uppercase the input");
puts(" -l Lowercase the input");
puts(" -r Reverse the input");
puts(" -R Randomcase the input");
puts(" -a Append POSTFIX at the end of the input");
puts(" -p Prepend PREFIX at the start of the input");
puts(" -m Repeat the input COUNT times (negative COUNT means 0)");
puts(" -h Show this help text");
}
int main(int argc, char *argv[]) {
srand(time(NULL));
opterr = 0;
int opt;
while ((opt = getopt(argc, argv, "ulRra:p:m:")) != -1) {
if (opt == '?') {
print_usage(argv[0]);
if (optopt == 'h')
print_options();
return optopt != 'h';
}
}
char *line = NULL;
size_t len = 0;
while (read_line(&line, &len) != NULL) {
char *built_text = build_text(line, argc, argv);
puts(built_text);
free(built_text);
}
free(line);
return 0;
}
|
C
|
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Copyright 2013 Joshua C. Klontz *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); *
* you may not use this file except in compliance with the License. *
* You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
#ifndef LIKELY_FRONTEND_H
#define LIKELY_FRONTEND_H
#include <stddef.h>
#include <likely/runtime.h>
#include <likely/io.h>
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
/*!
* \defgroup frontend Frontend
* \brief Parse source code into an abstract syntax tree (\c likely/frontend.h).
* @{
*/
/*!
* \brief How to interpret a \ref likely_abstract_syntax_tree.
*
* Available options are listed in \ref likely_abstract_syntax_tree_types.
*/
typedef uint32_t likely_abstract_syntax_tree_type;
/*!
* \brief \ref likely_abstract_syntax_tree_type options.
*/
enum likely_abstract_syntax_tree_types
{
likely_ast_list = 0, /*!< likely_abstract_syntax_tree::atoms and likely_abstract_syntax_tree::num_atoms are accessible. */
likely_ast_atom = 1, /*!< likely_abstract_syntax_tree::atom and likely_abstract_syntax_tree::atom_len are accessible. */
likely_ast_operator = 2, /*!< A \ref likely_ast_atom identified as a operator during evaluation. */
likely_ast_operand = 3, /*!< A \ref likely_ast_atom identified as a operand during evaluation. */
likely_ast_integer = 4, /*!< A \ref likely_ast_atom identified as an integer during evaluation. */
likely_ast_real = 5, /*!< A \ref likely_ast_atom identified as a real during evaluation. */
likely_ast_string = 6, /*!< A \ref likely_ast_atom identified as a string during evaluation. */
likely_ast_type = 7, /*!< A \ref likely_ast_atom identified as a type during evaluation. */
likely_ast_invalid = 8, /*!< A \ref likely_ast_atom that could not be identified during evaluation. */
};
typedef struct likely_abstract_syntax_tree *likely_ast; /*!< \brief Pointer to a \ref likely_abstract_syntax_tree. */
typedef struct likely_abstract_syntax_tree const *likely_const_ast; /*!< \brief Pointer to a constant \ref likely_abstract_syntax_tree. */
/*!
* \brief An abstract syntax tree.
*
* The \ref likely_abstract_syntax_tree represents the final state of source code after tokenization and parsing.
* This structure is provided to the backend for code generation.
*
* The \ref likely_abstract_syntax_tree is designed as a node in a \a tree, where each node is either a list or an atom.
* A \a list is an array of \ref likely_ast which themselves are lists or atoms.
* An \a atom is a single-word string, also called a \a token.
* In tree-terminology a list is a \a branch, and an atom is a \a leaf.
*
* In Likely source code, parenthesis, periods and colons are used to construct lists, and everything else is an atom.
*
* \par Abstract Syntax Tree Construction
* | Function | Description |
* |---------------------------|---------------------------------|
* | \ref likely_atom | \copybrief likely_atom |
* | \ref likely_list | \copybrief likely_list |
* | \ref likely_lex | \copybrief likely_lex |
* | \ref likely_parse | \copybrief likely_parse |
* | \ref likely_lex_and_parse | \copybrief likely_lex_and_parse |
*
* \see \ref reference_counting
*/
struct likely_abstract_syntax_tree
{
union {
struct
{
const likely_ast * const atoms; /*!< \brief List elements. */
uint32_t num_atoms; /*!< \brief Length of \ref atoms. */
}; /*!< \brief Accessible when <tt>\ref type == \ref likely_ast_list</tt>. */
struct
{
const char * const atom; /*!< \brief <tt>NULL</tt>-terminated single-word token. */
uint32_t atom_len; /*!< \brief Length of \ref atom, excluding the <tt>NULL</tt>-terminator. */
}; /*!< \brief Accessible when <tt>\ref type != \ref likely_ast_list</tt>. */
}; /*!< \brief A list or an atom. */
likely_const_ast parent; /*!< \brief This node's predecessor, or \c NULL if this node is the root. */
uint32_t ref_count; /*!< \brief Reference count used by \ref likely_retain_ast and \ref likely_release_ast to track ownership. */
likely_abstract_syntax_tree_type type; /*!< \brief Interpretation of \ref likely_abstract_syntax_tree. */
uint32_t begin_line; /*!< \brief Source code beginning line number. */
uint32_t begin_column; /*!< \brief Source code beginning column number. */
uint32_t end_line; /*!< \brief Source code ending line number. */
uint32_t end_column; /*!< \brief Source code ending column number (inclusive). */
};
/*!
* \brief Construct a new atom from a string.
* \param[in] atom The string to copy for \ref likely_abstract_syntax_tree::atom.
* \param[in] atom_len The length of \p atom to copy, and the value for \ref likely_abstract_syntax_tree::atom_len.
* \return A pointer to the new \ref likely_abstract_syntax_tree, or \c NULL if \c malloc failed.
* \remark This function is \ref thread-safe.
* \see \ref likely_list
*/
LIKELY_EXPORT likely_ast likely_atom(const char *atom, uint32_t atom_len);
/*!
* \brief Construct a new list from an array of atoms.
* \note This function takes ownership of \p atoms. Call \ref likely_retain_ast for elements in \p atoms where you wish to retain a copy.
* \param[in] atoms The atoms to take for \ref likely_abstract_syntax_tree::atoms.
* \param[in] num_atoms The length of \p atoms, and the value for \ref likely_abstract_syntax_tree::num_atoms.
* \return A pointer to the new \ref likely_abstract_syntax_tree, or \c NULL if \c malloc failed.
* \remark This function is \ref thread-safe.
* \see \ref likely_atom
*/
LIKELY_EXPORT likely_ast likely_list(const likely_ast *atoms, uint32_t num_atoms);
/*!
* \brief Retain a reference to an abstract syntax tree.
*
* Increments \ref likely_abstract_syntax_tree::ref_count.
* \param[in] ast Abstract syntax tree to add a reference. May be \c NULL.
* \return \p ast.
* \remark This function is \ref reentrant.
* \see \ref likely_release_ast
*/
LIKELY_EXPORT likely_ast likely_retain_ast(likely_const_ast ast);
/*!
* \brief Release a reference to an abstract syntax tree.
*
* Decrements \ref likely_abstract_syntax_tree::ref_count.
* \param[in] ast Abstract syntax tree to subtract a reference. May be \c NULL.
* \remark This function is \ref reentrant.
* \see \ref likely_retain_ast
*/
LIKELY_EXPORT void likely_release_ast(likely_const_ast ast);
typedef struct likely_error *likely_err; /*!< \brief Pointer to a \ref likely_error. */
typedef struct likely_error const *likely_const_err; /*!< \brief Pointer to a constant \ref likely_error. */
/*!
* \brief A compilation error.
* \par Error Construction
* | Function | Description |
* |---------------------|---------------------------|
* | \ref likely_erratum | \copybrief likely_erratum |
*
* \see \ref reference_counting
*/
struct likely_error
{
likely_const_err parent; /*!< \brief Predecessor error, or \c NULL if this error is the root. */
uint32_t ref_count; /*!< \brief Reference count used by \ref likely_retain_err and \ref likely_release_err to track ownership. */
likely_const_ast where; /*!< \brief Location of the error. */
char what[]; /*!< \brief Error message. */
};
/*!
* \brief Signature of a function to call when a compilation error occurs.
* \see \ref likely_set_error_callback
*/
typedef void (*likely_error_callback)(likely_err err, void *context);
/*!
* \brief Construct a new error.
* \param[in] parent A previous error that caused this error. May be \c NULL.
* \param[in] where \ref likely_error::where.
* \param[in] format <tt>printf</tt>-style string to populate \ref likely_error::what.
* \return Pointer to a new \ref likely_error, or \c NULL if \c malloc failed.
* \remark This function is \ref reentrant.
*/
LIKELY_EXPORT likely_err likely_erratum(likely_const_err parent, likely_const_ast where, const char *format, ...);
/*!
* \brief Retain a reference to an error.
*
* Increments \ref likely_error::ref_count.
* \param[in] err Error to add a reference. May be \c NULL.
* \return \p err.
* \remark This function is \ref reentrant.
* \see \ref likely_release_err
*/
LIKELY_EXPORT likely_err likely_retain_err(likely_const_err err);
/*!
* \brief Release a reference to an error.
*
* Decrements \ref likely_error::ref_count.
* \param[in] err Error to subtract a reference. May be \c NULL.
* \remark This function is \ref reentrant.
* \see \ref likely_retain_err
*/
LIKELY_EXPORT void likely_release_err(likely_const_err err);
/*!
* \brief Assign the function to call when a compilation error occurs.
*
* By default, the error is converted to a string using \ref likely_err_to_string and printed to \c stderr.
* \param[in] callback The function to call when a compilation error occurs.
* \param[in] context User-defined data to pass to \p callback.
* \remark This function is \ref thread-safe.
*/
LIKELY_EXPORT void likely_set_error_callback(likely_error_callback callback, void *context);
/*!
* \brief Trigger a recoverable error.
*
* Calls the \ref likely_error_callback set by \ref likely_set_error_callback.
* \param[in] where Location of the error.
* \param[in] what Description of the error.
* \return \c false.
* \remark This function is \ref thread-safe.
* \see \ref likely_ensure
*/
LIKELY_EXPORT bool likely_throw(likely_const_ast where, const char *what);
/*!
* \brief Convert the error to a string suitable for printing.
* \param[in] err The error to convert to a string.
* \return A \ref likely_string.
* \remark This function is \ref thread-safe.
*/
LIKELY_EXPORT likely_mat likely_err_to_string(likely_err err);
/*!
* \brief Perform lexical analysis, converting source code into a list of tokens.
*
* The output from this function is usually the input to \ref likely_parse.
* \param[in] source Code from which to extract tokens.
* \param[in] file_type How to interpret \p source.
* \return A list of tokens extracted from \p source.
* \remark This function is \ref thread-safe.
* \see \ref likely_lex_and_parse
*/
LIKELY_EXPORT likely_ast likely_lex(const char *source, likely_file_type file_type);
/*!
* \brief Perform syntactic analysis, converting a list of tokens into an abstract syntax tree.
*
* The input to this function is usually the output from \ref likely_lex.
* \param[in] tokens List of tokens from which build the abstract syntax tree.
* \return An abstract syntax tree built from \p tokens.
* \remark This function is \ref thread-safe.
* \see \ref likely_lex_and_parse
*/
LIKELY_EXPORT likely_ast likely_parse(likely_const_ast tokens);
/*!
* \brief Convenient alternative to \ref likely_lex followed by \ref likely_parse.
* \par Implementation
* \snippet src/frontend.cpp likely_lex_and_parse implementation.
* \param[in] source Code from which to extract tokens and build the abstract syntax tree.
* \param[in] file_type How to interpret \p source when extracting tokens.
* \return An abstract syntax tree built from \p source.
* \remark This function is \ref thread-safe.
* \see \ref likely_ast_to_string \ref likely_lex_parse_and_eval
*/
LIKELY_EXPORT likely_ast likely_lex_and_parse(const char *source, likely_file_type file_type);
/*!
* \brief Convert an abstract syntax tree into a string.
*
* The opposite of \ref likely_lex_and_parse.
* The returned \ref likely_matrix::data is valid \ref likely_file_lisp code.
* \param[in] ast The abstract syntax tree to convert into a string.
* \param[in] depth Maximum levels of \p ast to print or \c -1 for all.
* Unprinted atoms are represented with a single space.
* \return A \ref likely_string.
* \remark This function is \ref thread-safe.
*/
LIKELY_EXPORT likely_mat likely_ast_to_string(likely_const_ast ast, int depth);
/*!
* \brief Compare two abstract syntax trees.
* \param[in] a Abstract syntax tree to be compared.
* \param[in] b Abstract syntax tree to be compared.
* \return <tt>-1 if (a < b), 0 if (a == b), 1 if (a > b)</tt>.
* \remark This function is \ref thread-safe.
*/
LIKELY_EXPORT int likely_ast_compare(likely_const_ast a, likely_const_ast b);
/*!
* \brief Returns true if the \ref likely_abstract_syntax_tree::atom is an assignment.
*
* \par Implementation
* \snippet src/frontend.cpp likely_is_definition implementation.
* \param[in] ast The abstract syntax tree to examine.
* \return \c true if \param ast is an assignment, \c false otherwise.
*/
LIKELY_EXPORT bool likely_is_definition(likely_const_ast ast);
/*!
* \brief Find the first \ref likely_abstract_syntax_tree::atom that isn't an assignment (=) operator.
*
* Searches using an in order traversal of \p ast.
* \param[in] ast The abstract syntax tree to traverse.
* \return The first \ref likely_abstract_syntax_tree::atom that isn't an assignment (=) operator.
* \remark This function is \ref thread-safe.
*/
LIKELY_EXPORT const char *likely_symbol(likely_const_ast ast);
/*!
* \brief Convert a \ref likely_type to a string.
*
* The opposite of \ref likely_type_from_string.
* The returned \ref likely_matrix::data is valid \ref likely_file_lisp code.
* \param[in] type The type to convert to a string.
* \return A \ref likely_string.
* \remark This function is \ref thread-safe.
*/
LIKELY_EXPORT likely_mat likely_type_to_string(likely_type type);
/*!
* \brief Convert a string to a \ref likely_type.
*
* The opposite of \ref likely_type_to_string.
* \par Implementation
* \snippet src/frontend.cpp likely_type_from_string implementation.
* \param[in] str String to convert to a \ref likely_type.
* \param[out] ok Successful conversion. May be \c NULL.
* \return A \ref likely_type from \p str on success, \ref likely_void otherwise.
* \remark This function is \ref thread-safe.
*/
LIKELY_EXPORT likely_type likely_type_from_string(const char *str, bool *ok);
/*!
* \brief Determine the appropriate \ref likely_type for a binary operation.
* \par Implementation
* \snippet src/frontend.cpp likely_type_from_types implementation.
* \param[in] a Type to be consolidated.
* \param[in] b Type to be consolidated.
* \return The appropriate \ref likely_type for an operation involving \p a and \p b.
* \remark This function is \ref thread-safe.
*/
LIKELY_EXPORT likely_type likely_type_from_types(likely_type a, likely_type b);
/*!
* \brief Construct a pointer type.
* \param[in] element_type Element type.
* \return Compound pointer type.
* \remark This function is \ref thread-safe.
* \see \ref likely_element_type
*/
LIKELY_EXPORT likely_type likely_pointer_type(likely_type element_type);
/*!
* \brief Retrieve the element type of a pointer.
* \param[in] pointer_type Compound pointer type.
* \return Element type.
* \remark This function is \ref thread-safe.
* \see \ref likely_pointer_type
*/
LIKELY_EXPORT likely_type likely_element_type(likely_type pointer_type);
/*!
* \brief Construct a struct type.
* \param[in] name Struct name.
* \param[in] member_types Member types. May be \c NULL if \p members is \c 0.
* \param[in] members Length of \p member_types.
* \return Compound struct type.
* \remark This function is \ref thread-safe.
* \see \ref likely_member_types
*/
LIKELY_EXPORT likely_type likely_struct_type(const char *name, const likely_type *member_types, uint32_t members);
/*!
* \brief Get the name of a struct.
* \param[in] struct_type Compoint struct type.
* \return Struct name as a \ref likely_string.
* \remark This function is \ref thread-safe.
* \see \ref likely_struct_type
*/
LIKELY_EXPORT likely_mat likely_struct_name(likely_type struct_type);
/*!
* \brief Get the number of members in a struct.
* \param[in] struct_type Compound struct type.
* \return The number of members in \p struct_type.
* \remark This function is \ref thread-safe.
* \see \ref likely_struct_type
*/
LIKELY_EXPORT uint32_t likely_struct_members(likely_type struct_type);
/*!
* \brief Retrieve the member types of a struct.
* \param[in] struct_type Compound struct type.
* \param[out] member_types Member types, large enough to hold \ref likely_struct_members elements. May be \c NULL if \ref likely_struct_members is \c 0.
* \remark This function is \ref thread-safe.
* \see \ref likely_struct_type
*/
LIKELY_EXPORT void likely_member_types(likely_type struct_type, likely_type *member_types);
/** @} */ // end of frontend
#ifdef __cplusplus
}
#endif // __cplusplus
#endif // LIKELY_FRONTEND_H
|
C
|
#include<stdio.h>
int prince[1<<16];
int princess[1<<16];
int mapping[1<<16];
int LIS[1<<16];
void solve(int testcaseNum){
// Scan in input
int n, p, q;
scanf("%d %d %d", &n, &p, &q);
// Reset the mapping and LIS array
for (int i = 0; i <= n*n; ++i){
mapping[i] = 0;
LIS[i] = 1<<30;
}
for (int i = 0; i <= p; ++i){
scanf("%d", &prince[i]);
}
for (int i = 0; i <= q; ++i){
scanf("%d", &princess[i]);
}
// OK make the mapping
// Now prince[i] can be transformed into an increasing sequence!
for (int i = 0; i <= p; ++i){
mapping[prince[i]] = i+1;
}
// Convert the princess array into the sequence
for (int i = 0; i <= q; ++i){
princess[i] = mapping[princess[i]];
}
// Lastly, find the LIS of the array
int LISLength = 0;
for (int i = 0; i <= q; ++i){
int lo = 0;
int hi = LISLength;
while (lo < hi){
int mid = (lo + hi)/2;
if (LIS[mid] < princess[i]){
lo = mid + 1;
}
else {
hi = mid;
}
}
LIS[hi] = princess[i];
if (hi == LISLength){
LISLength++;
}
}
printf("Case %d: %d\n", testcaseNum, LISLength);
}
int main(){
int testcases;
scanf("%d", &testcases);
for (int i = 1; i <= testcases; ++i){
solve(i);
}
return 0;
}
|
C
|
#include<stdio.h>
main()
{
int a,b;
//by user
scanf("%d %d",&a,&b);
a = a * b; // a = 10 * 5 = 50
b = a / b; // b = 50 / 5 = 10
a = a / b; // a = 50 / 10 = 5
printf("%d\n%d",a,b);
}
#include<stdio.h>
main()
{
int a,b;
//by user
scanf("%d %d",&a,&b);
a = a + b; // a = 10 + 5 = 15
b = a - b; // b = 15 - 5 = 10
a = a - b; // a = 15 - 10 = 5
printf("%d\n%d",a,b);
}
|
C
|
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <string.h>
#define MAX(a,b) (a>b? a:b)
int longestCommonSubsequence(char *a, char lenA, char *b, char lenB)
{
char i,j;
char **LCS = malloc(sizeof(char*) * lenA);
for(i=0; i<lenB;i++)
{
LCS[i] = malloc(sizeof(char) * lenB);
}
for(i=0; i<lenA;i++)
{
for(j=0;j<lenB;j++)
{
if(a[i] == b[j])
{
LCS[i][j] = 1 + LCS[i-1][j];
}
else
{
LCS[i][j] = MAX(LCS[i-1][j], LCS[i][j-1]);
}
}
}
return LCS[lenA-1][lenB-1];
}
int main()
{
return 0;
}
|
C
|
#include <stdio.h>
int pobierz_calkowita(void){
return 0;
}
float x;
double pobierz_rzeczywista(void){
printf("Podaj liczbe rzeczywista: ");
scanf("%f", &x);
return x;
}
|
C
|
#include <stdio.h>
#define M 4
#define N 6
void StampaColonne(int matrice[M][N]);
void StampaRighe(int matrice[M][N]);
int main()
{
int matrice[M][N] = {{11,12,13,14,15,16},{21,22,23,24,25,26},{31,32,33,34,35,36},{41,42,43,44,45,46}};
StampaRighe(matrice);
StampaColonne(matrice);
return 0;
}
void StampaColonne(int matrice[M][N])
{
int i, j;
for(i = 0; i < N; i++)
{
for(j = 0; j < M; j++) //cicliamo come se fosse una matrice normale solo cogli indici scambiati
printf("%d ", matrice[j][i]);
printf("\n");
}
return;
}
void StampaRighe(int matrice[M][N])
{
int i, j;
for(i = 0; i < M; i++)
{
for(j = 0; j < N; j++) //cicliamo come se fosse una matrice normale solo cogli indici scambiati
printf("%d ", matrice[i][j]);
printf("\n");
}
return;
}
|
C
|
#include "common.h"
int
tsocket(int type, const struct sockaddr_in *baddr)
{
int fd = socket(AF_INET, type | SOCK_NONBLOCK, 0);
if(fd < 0) goto onfail;
// Enable transparent & recvorigdstaddr.
int enable = 1;
if(setsockopt(fd, IPPROTO_IP, IP_TRANSPARENT, &enable, sizeof(int)) < 0 ||
setsockopt(fd, IPPROTO_IP, IP_RECVORIGDSTADDR, &enable, sizeof(int)) < 0)
goto onfail;
// Bind address.
if(baddr != NULL && bind(fd, (const struct sockaddr*) baddr, ADDRSIZE) < 0)
goto onfail;
return fd;
onfail:
if(fd > 0) close(fd);
return -1;
}
|
C
|
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/types.h>
#include<unistd.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<malloc.h>
#include<sys/uio.h>
#include<signal.h>
#include<netinet/in.h>
#define PORT 4401
static struct iovec* vr=NULL;
void sig_proccess(int signo);
void sig_pipe(int signo);
void process_conn_client(int clnt);
int main(void)
{
int sock_clnt;
struct sockaddr_in server_addr;
signal(SIGINT,sig_proccess);
signal(SIGPIPE,sig_pipe);
sock_clnt = socket(AF_INET,SOCK_STREAM,0);
if(sock_clnt < 0)
{
fprintf(stdout,"socket() error.\n");
return -1;
}
memset(&server_addr,0,sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
server_addr.sin_port = htons(PORT);
int tmp = inet_pton(AF_INET,"127.0.0.1",&server_addr.sin_addr);
if(tmp < 0)
puts("失败");
int res = connect(sock_clnt,(struct sockaddr*)&server_addr,sizeof(struct sockaddr));
if(res < 0)
{
puts("连接失败...\n");
return 0;
}
else
{
puts("连接成功....\n");
}
process_conn_client(sock_clnt);
close(sock_clnt);
return 0;
}
void sig_proccess(int signo)
{
printf("Catch a exit signal!\n");
free(vr);
_exit(0);
}
void sig_pipe(int signo)
{
printf("Catch a SIGPIPE signal!\n");
free(vr);
_exit(0);
}
void process_conn_client(int clnt)
{
ssize_t size = 0;
char buffer[30];
memset(buffer, 0 ,30);
struct iovec *r = (struct iovec *)malloc(3*sizeof(struct iovec));
if(!r)
{
puts("Not enough memory\n");
return ;
}
vr = r;
r[0].iov_base = buffer;
r[1].iov_base = buffer + 10;
r[2].iov_base = buffer + 20;
r[0].iov_len = r[1].iov_len = r[2].iov_len = 10;
int i =0;
while(1)
{
size = read(0,r[0].iov_base,10);
if(size > 0)
{
r[0].iov_len = size;
ssize_t a = writev(clnt,r,1);
printf("发送数据......%d\n",(int)a);
r[0].iov_len = r[1].iov_len = r[2].iov_len = 10;
size = readv(clnt,r,3);
for(i=0;i<3;i++)
{
if(r[i].iov_len > 0)
write(1,r[i].iov_base,r[i].iov_len);
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.