blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 2
247
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
57
| license_type
stringclasses 2
values | repo_name
stringlengths 4
111
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
58
| visit_date
timestamp[ns]date 2015-07-25 18:16:41
2023-09-06 10:45:08
| revision_date
timestamp[ns]date 1970-01-14 14:03:36
2023-09-06 06:22:19
| committer_date
timestamp[ns]date 1970-01-14 14:03:36
2023-09-06 06:22:19
| github_id
int64 3.89k
689M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 25
values | gha_event_created_at
timestamp[ns]date 2012-06-07 00:51:45
2023-09-14 21:58:52
⌀ | gha_created_at
timestamp[ns]date 2008-03-27 23:40:48
2023-08-24 19:49:39
⌀ | gha_language
stringclasses 159
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 7
10.5M
| extension
stringclasses 111
values | filename
stringlengths 1
195
| text
stringlengths 7
10.5M
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
181d64b2fe4ebf5f5e29b9a71f8ac9e918dc9161
|
9140a0b8b2f06eaae48d4e8604cbd11d7ff38b9c
|
/TextureMap.h
|
acff4c6471d8f507a806a2b25f71de9334e0c062
|
[] |
no_license
|
rossig7/RayTracer
|
9bbc0fc5da615a697667083bf6bb21395dadc983
|
f3ddd7545144e053672b8c166800272ceff57fc6
|
refs/heads/master
| 2020-03-27T16:41:59.549849
| 2013-12-04T23:02:16
| 2013-12-04T23:02:16
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,542
|
h
|
TextureMap.h
|
#ifndef _TEXTUREMAP_H
#define _TEXTUREMAP_H
#include <string>
#include <fstream>
#include "Color.h"
using namespace std;
class TextureMap
{
public:
int x_res,y_res;
Color** ColorMap;
TextureMap()
{
}
void TextureMapRead(string file_name)
{
FILE *fp;
if (!(fp = fopen(file_name.c_str(), "rb")))
return;
unsigned char header[54];
fread(header, sizeof(unsigned char), 54, fp);
x_res=y_res=0;
for(int i=18;i<=21;i++)
{
y_res+=header[i]*pow(256,i-18);
}
for(int i=22;i<=25;i++)
{
x_res+=header[i]*pow(256,i-22);
}
ColorMap=(Color**)malloc(sizeof(Color*)*x_res+sizeof(Color)*x_res*y_res);
Color* start_position=(Color*)(ColorMap+x_res);
for(int i=0;i<x_res;i++)
ColorMap[i]=start_position+i*y_res;
//(Color*)malloc(sizeof(Color)*y_res);
//unsigned char* image=(unsigned char*)malloc(sizeof(unsigned char)*x_res*y_res*3);
//fread(image, sizeof(unsigned char), (size_t)(long)x_res * y_res * 3, fp);
for(int i=0;i<x_res;i++)
{
for(int j=0;j<y_res;j++)
{
unsigned char image[3];
fread(image, sizeof(unsigned char), 3, fp);
ColorMap[i][j].setColorRed(image[2]/255.0);
ColorMap[i][j].setColorGreen(image[1]/255.0);
ColorMap[i][j].setColorBlue(image[0]/255.0);
//if(image!=NULL)
//delete(image);
//int k=(i*y_res+j)*3;
//ColorMap[i][j].setColorRed(image[k]/255.0);
//ColorMap[i][j].setColorGreen(image[k+1]/255.0);
//ColorMap[i][j].setColorBlue(image[k+2]/255.0);
}
}
//free(image);
//fclose(fp);
//fclose(fp);
//delete(header);
//int k=0;
//fstream input(file_name,ios::in);
//unsigned char temp_byte;
//x_res=0;
//y_res=0;
//for(int i=0;i<54;i++)
//{
// if(i==18)
// {
// for(;i<=21;i++)
// {
// input>>temp_byte;
// y_res=y_res+temp_byte*pow(256,i-18);
// }
// cout<<y_res<<" ";
// i--;
// }
// else if(i==22)
// {
// for(;i<=25;i++)
// {
// input>>temp_byte;
// x_res=x_res+temp_byte*pow(256,i-22);
// }
// cout<<x_res<<" texture bmp\n";
// i--;
// }
// else
// {
// input>>temp_byte;
// }
//}
//ColorMap=new Color*[x_res];
//for(int i=0;i<x_res;i++)
// ColorMap[i]=new Color[y_res];
//for(int i=0;i<x_res;i++)
//{
// for(int j=0;j<y_res;j++)
// {
// Color new_color;
// unsigned char temp_red_byte,temp_blue_byte,temp_green_byte;
// input>>temp_red_byte>>temp_green_byte>>temp_blue_byte;
// new_color.setColorRed(temp_red_byte/255.0);
// //input>>temp_byte;
// new_color.setColorGreen(temp_green_byte/255.0);
// //input>>temp_byte;
// new_color.setColorBlue(temp_blue_byte/255.0);
// new_color.setColorSpecial(0);
// if(temp_red_byte==31&&temp_green_byte==31&&temp_blue_byte==39)
// int k=0;
// if(i==(x_res-1)&&j==(y_res-1))
// int m=0;
// ColorMap[i][j]=new_color;
// }
//}
//input.close();
}
double getBilinearInterpolate(double left_up,double left_down, double right_up, double right_down, double s, double t)
{
return left_up*(1-s)*(1-t)+left_down*s*(1-t)+right_up*(1-s)*t+right_down*s*t;
}
Color GetColor(double x, double y)
{
double dot_x=x;
double dot_y=y;
if(dot_x>0)
{
while(dot_x-1>0)
dot_x-=1;
}
else if(dot_x<0)
{
do
{
dot_x+=1;
} while (dot_x<0);
}
if(dot_y>0)
{
while(dot_y-1>0)
dot_y-=1;
}
else if(dot_y<0)
{
do
{
dot_y+=1;
} while (dot_y<0);
}
dot_x=dot_x*(x_res-1);
dot_y=dot_y*(y_res-1);
int floor_x=int(dot_x);
int ceil_x=(floor_x+1)>=x_res?x_res-1:floor_x+1;
int floor_y=int(dot_y);
int ceil_y=(floor_y+1)>=y_res?y_res-1:floor_y+1;
Color left_up=ColorMap[floor_x][floor_y];
Color left_down=ColorMap[ceil_x][floor_y];
Color right_up=ColorMap[floor_x][ceil_y];
Color right_down=ColorMap[ceil_x][ceil_y];
Color result_color;
double s=dot_x-floor_x;
double t=dot_y-floor_y;
result_color.setColorRed(getBilinearInterpolate(left_up.getColorRed(),left_down.getColorRed(),right_up.getColorRed(),right_down.getColorRed(),s,t));
result_color.setColorGreen(getBilinearInterpolate(left_up.getColorGreen(),left_down.getColorGreen(),right_up.getColorGreen(),right_down.getColorGreen(),s,t));
result_color.setColorBlue(getBilinearInterpolate(left_up.getColorBlue(),left_down.getColorBlue(),right_up.getColorBlue(),right_down.getColorBlue(),s,t));
result_color.setColorSpecial(0);
return result_color;
}
Color GetColor(MyTexture t)
{
return GetColor(t.ReturnU(),t.ReturnV());
}
};
#endif
|
313b738fe78f4a8b4727da7fd540a446c61b27c1
|
c5e945ac82daa7f0238a9bb0cda3cfbfd7154054
|
/ashell.cpp
|
ffd0e917c2d6d371fbe29d826311fa56573c0f93
|
[] |
no_license
|
darrylbckhm/ecs150_project_1
|
c3a898460c74be5dc66fa201575cd0556be3d06f
|
a1540ed45100c37aa37161ea614454b252647eb0
|
refs/heads/master
| 2021-01-13T07:06:23.881500
| 2017-02-10T23:40:40
| 2017-02-10T23:40:40
| 81,616,627
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 20,357
|
cpp
|
ashell.cpp
|
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <termios.h>
#include <ctype.h>
#include <string.h>
#include <string>
#include <iostream>
#include <list>
#include <iterator>
#include <dirent.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <vector>
#include <sstream>
#include "ashell.h"
using namespace std;
string formatString(char* raw_input_string)
{
string str = raw_input_string;
string buf;
istringstream ss(str);
//loop through raw input to add spaces where necessary
//all code from here to the second while loop is of similar format
size_t pos = str.find_first_of("|"); //index of first pipe character found
while (pos != string::npos)
{
if(str[pos - 1] != ' ') //if the character before the pipe isn't a space
{
str.insert(pos, " "); //add a space before the pipe
++pos; //increment back to current pipe index
}
if(str[pos + 1] != ' ') //if the character after the pipe isn't a space
{
str.insert(pos + 1, " "); //add a space after the pipe
pos = str.find_first_of("|", pos + 2); //search string for another pipe
continue;
}
pos = str.find_first_of("|", pos + 1); //if there are spaces, search for another pipe
}
pos = str.find_first_of("<");
while (pos != string::npos)
{
if(str[pos - 1] != ' ')
{
str.insert(pos, " ");
++pos;
}
if(str[pos + 1] != ' ')
{
str.insert(pos + 1, " ");
pos = str.find_first_of("<", pos + 2);
}
pos = str.find_first_of('<', pos + 1);
}
pos = str.find_first_of(">");
while (pos != string::npos)
{
if(str[pos - 1] != ' ')
{
str.insert(pos, " ");
++pos;
}
if(str[pos + 1] != ' ')
{
str.insert(pos + 1, " ");
pos = str.find_first_of(">", pos + 2);
}
pos = str.find_first_of('>', pos + 1);
}
pos = str.find_first_of("\\");
while (pos != string::npos)
{
if(str[pos - 1] != ' ')
{
str.insert(pos, " ");
++pos;
}
if(str[pos + 1] != ' ')
{
str.insert(pos + 1, " ");
pos = str.find_first_of("\\", pos + 2);
}
pos = str.find_first_of('\\', pos + 1);
}
return str;
} // formats string to be parsed by spaces
void createPipe() //http://tldp.org/LDP/lpg/node11.html
{
}
pid_t newChild()
{
pid_t pid = fork();
return pid;
}
void pwd(pid_t* pid, int* status)
{
write(1, get_working_dir().c_str(), get_working_dir().size());
write(1, "\n", 1);
}
void ff(pid_t* pid, int* status, vector<string> cmdStr, const char* dirname, int level, int end) //source: http://stackoverflow.com/questions/8436841/how-to-recursively-list-directories-in-c-on-linux
{
DIR *dir;
struct dirent *entry;
string absStem;
if(level == 0)
absStem = dirname;
const char* file = cmdStr[1].c_str();
// try to open directory
if (!(dir = opendir(dirname)))
{
write(1, "Failed to open directory.\n", 26);
return;
}
if (!(entry = readdir(dir))) //if directory is readable
{
write(1, "Failed to open directory.\n", 26);
return;
}
while ((entry = readdir(dir)) != NULL)
{
if (entry->d_type == DT_DIR)
{
char path[1024];
int len = strlen(dirname) + 1 + strlen(entry->d_name);
string s1(dirname);
string s2(entry->d_name);
string tmp = s1 + "/" + s2;
strcpy(path, tmp.c_str());
path[len] = 0;
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
continue;
// continue to search directory for next file
ff(pid, status, cmdStr, path, level + 1, ++end);
end--;
}
else // if not a directory
{
char* fname = entry->d_name;
if(!strcmp(fname, file))
{
write(1, dirname, sizeof(dirname));
write(1, "/", 1);
write(1, file, sizeof(file));
write(1, "\n", 1);
}
}
}
closedir(dir);
if (end == 0)
exit(0);
}
void cd(vector<string> cmdStr)
{
const char* path;
if(cmdStr.size() == 1)
path = getenv("HOME");
else
path = cmdStr[1].c_str();
string tmp = path;
if(isADirectory(&tmp))
{
chdir(path);
}
else
{
write(1,"Error changing directory.\r\n", 27);
}
}
bool isADirectory(string* path)
{
const char* tmp = (*path).c_str();
struct stat path_stat;
stat(tmp, &path_stat);
return S_ISDIR(path_stat.st_mode);
}
vector<vector<string> >* tokenize(string formattedString, vector<vector<string> >* all_tokens, vector<string>* redirectTokens) //source: 4
{
//vector<vector<string> > all_tokens;
vector<string> cmdTokens;
//size_t pos = 0;
//const char* str = formattedString.c_str();
//int size = strlen(str); // variable for the size of formattedString
char cstr[1024]; // char array to hold formattedString
string tmp = formattedString.substr(0, formattedString.size() - 1);
strcpy(cstr, tmp.c_str()); // copy bytes from str to the new array
int escape = 0;
int input = 0;
int output = 0; // true when escape character is seen
int numPipes = 0;
int numRedir = 0;
char* token;
(*redirectTokens)[0] = "";
(*redirectTokens)[1] = "";
token = strtok(cstr, " ");
while(token != NULL)
{
string tmp = token;
if(tmp.compare(">") == 0) // if a backslash is found, set escape to true
{
++numRedir;
output = 1;
}
else if(tmp.compare("<") == 0) // if a backslash is found, set escape to true
{
++numRedir;
input = 1;
}
else if(tmp.compare("\\") == 0) // if a backslash is found, set escape to true
{
escape = 1;
}
else if(input)
{
(*redirectTokens)[0] = tmp;
input = 0;
}
else if(output)
{
(*redirectTokens)[1] = tmp;
output = 0;
}
else if(escape) //if escape is true add a space and the current token to the last element of cmdTokens
{
cmdTokens.back().append(" ");
cmdTokens.back().append(tmp);
cmdTokens.back().append("\0");
escape = 0; //set escape to false for next token
}
else if(tmp.compare("|") == 0) //if there is a pipe add this command vector to the vector of vectors
{
++numPipes;
all_tokens->push_back(cmdTokens);
cmdTokens.clear(); //clear vector for next command string
}
else //otherwise, add this token to the current command vector
{
cmdTokens.push_back(tmp);
cmdTokens.back().append("\0");
}
token = strtok(NULL, " ");
}
all_tokens->push_back(cmdTokens);
cmdTokens.clear();
//for(size_t i = 0; i < all_tokens->size(); i++)
//for(size_t j = 0; j < (*all_tokens)[i].size(); j++)
//cout << (*all_tokens)[i][j] << endl;
return all_tokens;
}
void ls(int* status, vector<string> cmdStr) //source used: #2,3
{
DIR *dir;
struct dirent *dp;
string path;
// if just ls
if (cmdStr.size() == 1)
{
path = ".";
}
else // if directory specified
{
path = cmdStr[1];
}
// checks if specified argument is a file or nonexistent
if(isADirectory(&path))
{
dir = opendir(path.c_str());
// reads dir
while((dp = readdir(dir)) != NULL)
{
// create full pathname
string filename = dp->d_name;
string working_directory = get_working_dir();
string path = working_directory + "/" + filename;
if (cmdStr.size() == 2)
path = working_directory + "/" + cmdStr[1] + "/" + filename;
// grab permissions info and fill in permissions
struct stat file_stats;
stat(path.c_str(), &file_stats);
mode_t mode = file_stats.st_mode;
char permissions[11] = "----------";
if (S_ISDIR(mode)) permissions[0] = 'd';
// using source: #4
if (mode & S_IRUSR) permissions[1] = 'r';
if (mode & S_IWUSR) permissions[2] = 'w';
if (mode & S_IXUSR) permissions[3] = 'x';
if (mode & S_IRGRP) permissions[4] = 'r';
if (mode & S_IWGRP) permissions[5] = 'w';
if (mode & S_IXGRP) permissions[6] = 'x';
if (mode & S_IROTH) permissions[7] = 'r';
if (mode & S_IWOTH) permissions[8] = 'w';
if (mode & S_IXOTH) permissions[9] = 'x';
permissions[10] = '\0';
write(1, permissions, strlen(permissions));
write(1, " ", 1);
write(1, filename.c_str(), filename.length());
write(1, "\n", 1);
}
}
else
{
write(1, "Failed to open directory ", 24);
write(1, " \"", 1);
write(1, path.c_str(), sizeof(path));
write(1, "\n", 1);
}
exit(0);
}
void downHistory(list<string>* commands, int* commands_current_index, char *raw_input_string, int* raw_input_string_index)
{
if (commands->size() == 0)
{
write(1, "\a", 1);
return;
}
// increment if at beginning of list
if (*commands_current_index == 0)
{
(*commands_current_index)++;
}
// check if at end of command list (at prompt)
if ((int)(*commands).size() == *commands_current_index)
{
write(1, "\a", 1);
for (int i = 0; i < *raw_input_string_index; i++)
{
write(1, "\b \b", 3);
}
*raw_input_string_index = 0;
}
else
{
// start at beginning of commands list and move to index
// move index to the later command
list<string>::iterator iter = (*commands).begin();
advance(iter, *(commands_current_index));
(*commands_current_index)++;
for (int i = 0; i < *raw_input_string_index; i++)
{
write(1, "\b \b", 3);
}
string raw_command = *iter;
string command = raw_command.substr(0, raw_command.size()-1); // source used: #3
write(1, command.c_str(), command.size());
strcpy(raw_input_string, command.c_str());
*raw_input_string_index = command.size();
fflush(stdout);
}
}
void upHistory(list<string>* commands, int* commands_current_index, char *raw_input_string, int* raw_input_string_index)
{
// nothing in commands, exit and do nothing
if (commands->size() == 0)
{
write(1, "\a", 1);
return;
}
// check if any commands in history or if current spot in history is at top
if (*commands_current_index == 0)
{
(*commands_current_index)++;
write(1, "\a", 1);
}
// start at beginning of commands list and move to one before
// the current index. then move the index to the earlier command
list<string>::iterator iter = (*commands).begin();
advance(iter, (*commands_current_index)-1);
(*commands_current_index)--;
for (int i = 0; i < *raw_input_string_index; i++)
{
write(1, "\b \b", 3);
}
string raw_command = *iter;
string command = raw_command.substr(0, raw_command.size()-1); // source used: #3
write(1, command.c_str(), command.size());
strcpy(raw_input_string, command.c_str());
*raw_input_string_index = command.size();
}
void commandHistory(char* raw_input, list<string>* commands, int* commands_current_index, char *raw_input_string, int* raw_input_string_index)
{
// skip second escape character and check which arrow it is
read(0, raw_input, 1);
read(0, raw_input, 1);
// Up Arrow => 0x1B 0x5B 0x41
// Down Arrow => 0x1B 0x5B 0x42
// source used: #1
if (*raw_input == 0x41)
{
upHistory(commands, commands_current_index, raw_input_string, raw_input_string_index);
}
else if (*raw_input == 0x42)
{
downHistory(commands, commands_current_index, raw_input_string, raw_input_string_index);
}
}
bool processInput(char* raw_input, list<string>* commands, int* commands_current_index,
char* raw_input_string, int* raw_input_string_index, vector<vector<string> >* all_tokens, vector<string>* redirectTokens)
{
if (*raw_input == 0x1B)
{
commandHistory(raw_input, commands, commands_current_index, raw_input_string, raw_input_string_index);
return true;
}
else if (*raw_input == 0x7F)
{
if (*raw_input_string_index > 0)
{
write(1, "\b \b", 3);
(*raw_input_string_index)--;
}
else
{
write(1, "\a", 1);
}
return true;
}
else
{
return writeInput(raw_input, commands, commands_current_index, raw_input_string, raw_input_string_index, all_tokens, redirectTokens);
}
}
void runCommand(char* raw_input_string, vector<vector<string> >* all_tokens, vector<string>* redirectTokens)
{
// calculate pipes and children
int num_children = all_tokens->size();
int num_pipes = num_children - 1;
// create pipes and add to array
int pipes[num_pipes][2];
for (int i = 0; i < num_pipes; i++) //for all pipes created
{
int fd[2]; // create int array for file descriptors
pipe(fd); // open pipe
pipes[i][0] = fd[0]; // hook up file descriptor output to pipe
pipes[i][1] = fd[1]; // hook up file descriptor input to pipe
}
// iterate through command and fork each
int child_num = 0;
vector<vector<string> >::iterator itr;
dup2(STDOUT_FILENO,3);
for (itr = all_tokens->begin(); itr != all_tokens->end(); itr++) //for all commands entered
{
vector<string> tokens = *itr;
string cmd = tokens[0];
const char* input_file = (*redirectTokens)[0].c_str();
const char* output_file = (*redirectTokens)[1].c_str();
pid_t pid;
pid = newChild();
int status;
// if child
if (pid == 0)
{
// if more than one pipe
if (num_pipes > 0)
{
// if first command, hook up to first pipe
if (child_num == 0)
{
if (strcmp(input_file, ""))
{
int fd = open(input_file, O_RDONLY); //open and return file descriptor for given input file
dup2(fd, 0); // creates a copy of the file descriptor fd and hooks it to stdin
close(fd); //
}
dup2(pipes[0][1], 1);
}
// else hook up to pipe before and after
else
{
dup2(pipes[child_num - 1][0], 0);
if (child_num != num_children - 1)
{
dup2(pipes[child_num][1], 1);
}
else
{
if (strcmp(output_file, "")) //if redirect input
{
mode_t mode = S_IRUSR | S_IWUSR;
int fd = open(output_file, O_WRONLY | O_CREAT | O_TRUNC, mode );
dup2(fd, 1);
close(fd);
}
}
}
}
else
{
if (strcmp(input_file, "")) //if redirect output
{
int fd = open(input_file, O_RDONLY);
dup2(fd, 0);
close(fd);
}
if (strcmp(output_file, ""))
{
mode_t mode = S_IRUSR | S_IWUSR;
int fd = open(output_file, O_WRONLY | O_CREAT | O_TRUNC, mode );
dup2(fd, 1);
close(fd);
}
}
if(cmd == "ls")
{
ls(&status, tokens);
}
else if(cmd == "cd")
{
cd(tokens);
}
else if(cmd == "pwd")
{
pwd(&pid, &status);
}
else if(cmd == "ff")
{
const char* dirname;
if(tokens.size() == 2)
dirname = ".";
else
dirname = tokens[2].c_str();
ff(&pid, &status, tokens, dirname, 0, 0);
}
else
{
char* argv[tokens.size() + 1];
/*strcpy could be problematic*/
for (size_t i = 0; i < tokens.size(); i++)
{
argv[i] = (char *)malloc(sizeof(tokens[i]) + 1);
strcpy(argv[i], tokens[i].c_str());
//argv[i] = (char)malloc(sizeof(tokens[i]) + 1);
//const char* tmp = tokens[i].c_str();
//size_t size = sizeof(char) * strlen(tmp);
//memcpy(argv[i], tmp, size);
}
argv[tokens.size()] = NULL;
for (int i = 0; i < num_pipes; i++)
{
close(pipes[i][0]);
close(pipes[i][1]);
}
execvp(argv[0], argv);
exit(0);
}
}
else
{
child_num++;
}
}
for (int i = 0; i < num_pipes; i++)
{
close(pipes[i][0]);
close(pipes[i][1]);
}
for (int i = 0; i < num_children; i++)
{
int status;
wait(&status);
}
dup2(3, STDOUT_FILENO);
}
void addHistory(list<string>* commands, int* commands_current_index, char* raw_input_string, int* raw_input_string_index)
{
string command(raw_input_string);
// if commands history full, remove the oldest
if ((*commands).size() == 10)
(*commands).pop_front();
// add command to end of history list
(*commands).push_back(command);
*commands_current_index = (*commands).size();
// write(1, raw_input_string, raw_input_string_index);
// reset index to zero for new input
*raw_input_string_index = 0;
}
bool writeInput(char* raw_input, list<string>* commands, int* commands_current_index,
char* raw_input_string, int* raw_input_string_index, vector<vector<string> >* all_tokens, vector<string>* redirectTokens)
{
// write input character out for user to see
write(1, raw_input, 1);
//copy char to input string
raw_input_string[(*raw_input_string_index)++] = *raw_input;
// on enter, end string and display back to screen
if (*raw_input == '\n')
{
raw_input_string[(*raw_input_string_index)] = '\0';
//*tokens = tokenize(raw_input_string);
if (strcmp(raw_input_string, "exit\n") == 0)
return false;
else
{
addHistory(commands, commands_current_index, raw_input_string, raw_input_string_index);
all_tokens = tokenize(formatString(raw_input_string), all_tokens, redirectTokens);
runCommand(raw_input_string, all_tokens, redirectTokens);
(*all_tokens).clear();
}
writePrompt();
}
return true;
}
char readInput(char* raw_input)
{
struct termios SavedTermAttributes;
// set to noncanonical mode, treat input as characters
// instead of lines ending on newline or EOF
set_non_canonical_mode(STDIN_FILENO, &SavedTermAttributes);
char tmp;
read(0, &tmp, 1);
if(tmp == 0x04)
exit(0);
else
{
if(tmp == 0x7C)
//createPipe();
return *raw_input = tmp;
}
return *raw_input = tmp;
}
string get_working_dir()
{
//string working_directory = string(getcwd());
char getcwd_buff[100];
getcwd(getcwd_buff, 100);
string working_directory = string(getcwd_buff);
return working_directory;
}
void reset_canonical_mode(int fd, struct termios *savedattributes)
{
tcsetattr(fd, TCSANOW, savedattributes);
}
void set_non_canonical_mode(int fd, struct termios *savedattributes)
{
struct termios TermAttributes;
// make sure stdin is a terminal
if (!isatty(fd))
{
write(2, "Not a terminal.\n", 16);
exit(0);
}
// save the terminal attributes so we can restore them later
tcgetattr(fd, savedattributes);
// set the terminal modes
tcgetattr (fd, &TermAttributes);
TermAttributes.c_lflag &= ~(ICANON | ECHO); // clear ICANON and ECHO
TermAttributes.c_cc[VMIN] = 1;
TermAttributes.c_cc[VTIME] = 0;
tcsetattr(fd, TCSAFLUSH, &TermAttributes);
}
void writePrompt()
{
// set prompt
string working_directory = get_working_dir();
size_t last_slash = working_directory.find_last_of("/");
string last_folder = working_directory.substr(last_slash, working_directory.length()-1);
if (working_directory.length() > 16)
{
working_directory = "/..." + last_folder;
}
write(1, working_directory.c_str(), working_directory.length());
write(1, "%", 1);
}
int main(int argc, char* argv[])
{
struct termios SavedTermAttributes;
// set to noncanonical mode, treat input as characters
// instead of lines ending on newline or EOF
set_non_canonical_mode(STDIN_FILENO, &SavedTermAttributes);
list<string> commands;
vector<vector<string> > all_tokens;
//bool redirect_output, redirect_input;
string output_file, input_file;
vector<string> redirectTokens;
redirectTokens.push_back("");
redirectTokens.push_back("");
//createPipe();
int commands_current_index = 0;
writePrompt();
char raw_input_string[128];
int raw_input_string_index = 0;
char raw_input = readInput(&raw_input);
while(processInput(&raw_input, &commands, &commands_current_index, raw_input_string, &raw_input_string_index, &all_tokens, &redirectTokens))
{
raw_input = readInput(&raw_input);
}
return 0;
}
|
ce0d0b5d02315593e43a420174f13d49bee2c33f
|
b62fc53933ced085303d2c2958c422c369e91f14
|
/Renderer/thread_utility.h
|
237b1ccb25b5bef953cb9ede5d6f62b555df5240
|
[] |
no_license
|
kouei/renderer
|
435bbfc377026e17a0a98f8569114afa2f56f19f
|
ae51ff32161e85011664c1fc4fcd02b23b7569c6
|
refs/heads/master
| 2021-07-02T16:22:28.202200
| 2018-12-12T04:49:35
| 2018-12-12T04:49:35
| 161,432,944
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,006
|
h
|
thread_utility.h
|
#ifndef _THREAD_UTILITY_
#define _THREAD_UTILITY_
#include <atomic>
namespace THREAD_UTILITY
{
using std::atomic_flag;
struct AtomicFlagObject
{
AtomicFlagObject() noexcept;
AtomicFlagObject(const AtomicFlagObject & rhs) = delete;
AtomicFlagObject(AtomicFlagObject && rhs) = delete;
AtomicFlagObject & operator= (const AtomicFlagObject & rhs) = delete;
AtomicFlagObject & operator= (AtomicFlagObject && rhs) = delete;
~AtomicFlagObject() noexcept;
operator atomic_flag & () noexcept;
operator const atomic_flag & () const noexcept;
atomic_flag flag;
};
struct AtomicFlagGuard
{
AtomicFlagGuard(atomic_flag & _flag) noexcept;
AtomicFlagGuard(const AtomicFlagGuard & rhs) = delete;
AtomicFlagGuard(AtomicFlagGuard && rhs) = delete;
AtomicFlagGuard & operator= (const AtomicFlagGuard & rhs) = delete;
AtomicFlagGuard & operator= (AtomicFlagGuard && rhs) = delete;
~AtomicFlagGuard() noexcept;
atomic_flag & flag;
};
};
#endif
|
55b235f186e1e93d57ca81b41ddf2d41ac8ee6b5
|
48d18b39e52d84d98faa2f8a51c87a22f3fed126
|
/lib/LaserCmd.cpp
|
0eba77aa473f518757af442d09a11f2f36ea42cb
|
[] |
no_license
|
swapneel001/PickByLight_RPI
|
1a34b2c5e3ca9973e15291a513bc86c004a23cd1
|
6be5955ea533e64fadfa965c5d6275a0f08e1239
|
refs/heads/master
| 2023-06-16T10:22:29.193329
| 2021-07-23T04:11:54
| 2021-07-23T04:11:54
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 327
|
cpp
|
LaserCmd.cpp
|
#include "LaserCmd.h"
LaserCmd::LaserCmd() {
wiringPiSetupGpio();
}
void LaserCmd::setPin(int pin, int val) {
digitalWrite(pin, val);
}
void LaserCmd::setupPins(std::vector<int> gpio_pins) {
for (int i : gpio_pins) {
setOutput(i);
}
}
void LaserCmd::setOutput(int pin) {
pinMode(pin, OUTPUT);
}
|
0ed847dd4786fec4a70f14abaf912d76f743cc18
|
45dcea2198639eaf93829def76eff51d47a05bea
|
/native-library/src/util_classes/download_result_details.hpp
|
72bed3db8551fbf811d2e83e1c408b37a3d0dad0
|
[
"Apache-2.0"
] |
permissive
|
KennyWZhang/Anjay-java
|
46f0757f2b507e98e245f4a6edc22888f18e3c11
|
35880a981ae4f7fb766e86e2daaefa7ea76dd39c
|
refs/heads/master
| 2023-04-19T10:48:48.153780
| 2021-05-12T14:11:03
| 2021-05-12T14:11:03
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,823
|
hpp
|
download_result_details.hpp
|
/*
* Copyright 2020-2021 AVSystem <avsystem@avsystem.com>
*
* 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.
*/
#pragma once
#include <unordered_map>
#include "../jni_wrapper.hpp"
#include "./accessor_base.hpp"
#include <anjay/download.h>
namespace utils {
struct DownloadResultDetails {
static constexpr auto Name() {
return "com/avsystem/anjay/AnjayDownload$ResultDetails";
}
static jni::Local<jni::Object<DownloadResultDetails>>
into_java(jni::JNIEnv &env, avs_error_t details) {
if (details.category != AVS_ERRNO_CATEGORY) {
return from_string(env, "UNKNOWN");
}
static std::unordered_map<uint16_t, std::string> MAPPING{
{ AVS_EADDRNOTAVAIL, "DNS_RESOLUTION_FAILED" },
{ AVS_ECONNABORTED, "REMOTE_RESOURCE_NO_LONGER_VALID" },
{ AVS_ECONNREFUSED, "SERVER_RESPONDED_WITH_RESET" },
{ AVS_ECONNRESET, "CONNECTION_LOST" },
{ AVS_EINVAL, "FAILED_TO_PARSE_RESPONSE" },
{ AVS_EIO, "INTERNAL_ERROR" },
{ AVS_EMSGSIZE, "MESSAGE_TOO_LARGE" },
{ AVS_ENOMEM, "OUT_OF_MEMORY" },
{ AVS_ETIMEDOUT, "TIMEOUT" },
};
auto mapped_to = MAPPING.find(details.code);
if (mapped_to == MAPPING.end()) {
return from_string(env, "UNKNOWN");
}
return from_string(env, mapped_to->second);
}
static jni::Local<jni::Object<DownloadResultDetails>>
into_java(jni::JNIEnv &env, int details) {
static std::unordered_map<int, std::string> MAPPING{
{ 132, "NOT_FOUND" },
{ 161, "NOT_IMPLEMENTED" },
{ 404, "NOT_FOUND" },
{ 501, "NOT_IMPLEMENTED" }
};
auto mapped_to = MAPPING.find(details);
if (mapped_to == MAPPING.end()) {
return from_string(env, "UNKNOWN");
}
return from_string(env, mapped_to->second);
}
private:
static jni::Local<jni::Object<DownloadResultDetails>>
from_string(jni::JNIEnv &env, const std::string &name) {
auto clazz = jni::Class<DownloadResultDetails>::Find(env);
return clazz.Get(
env, clazz.GetStaticField<jni::Object<DownloadResultDetails>>(
env, name.c_str()));
}
};
} // namespace utils
|
c8c2305c880799d887ab362f11c785fb0cd35a7b
|
cab611aa969a9f09bc3a40e72d31daf809b12119
|
/Pandu/PanduBulletPhysics/PANDUClock.h
|
a378f50e15be143b2401d500e7698c05d6d71cc8
|
[] |
no_license
|
ParagDrunkenMonster/PanduEngine
|
c5196c4d69b31c1eee8eb4b392ebb60afcb2c086
|
176ea70826ad12dfc75c6943cd093317dee6e2bf
|
refs/heads/master
| 2020-06-18T18:07:56.693506
| 2020-04-04T10:19:25
| 2020-04-04T10:19:25
| 74,749,406
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 927
|
h
|
PANDUClock.h
|
/********************************************************************
filename: PANDUClock
author: Parag Moni Boro
purpose: Game Engine created for learning
*********************************************************************/
#ifndef __PANDUClock_h__
#define __PANDUClock_h__
#include "LinearMath/btQuickprof.h"
namespace Pandu
{
class Clock
{
private:
btClock m_BulletClock;
public:
Clock(){}
~Clock(){}
/// Resets the initial reference time.
inline void Reset() { m_BulletClock.reset(); }
/// Returns the time in ms since the last call to reset or since
/// the btClock was created.
inline unsigned long int GetTimeMilliseconds() { return m_BulletClock.getTimeMilliseconds(); }
/// Returns the time in us since the last call to reset or since
/// the Clock was created.
inline unsigned long int GetTimeMicroseconds() { return m_BulletClock.getTimeMicroseconds(); }
};
}
#endif
|
2d38dda18ae223f1af75f4da727a5d60fcbaa36d
|
8fbaded48dc445d8475ba16254ae9bc6c429a03d
|
/common.h
|
951aa4a82b5a29d0b63f8f06a8c1bfbd1f05eb69
|
[] |
no_license
|
a2824256/EVA-Qt-Beta
|
5f6fd64e23cdbf7074cae0e54bcfc6d8bbd2a057
|
13446d0044859e99eaabe3247ef588412329af52
|
refs/heads/master
| 2020-12-05T10:47:09.956386
| 2020-01-18T07:08:33
| 2020-01-18T07:08:33
| 232,085,456
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 580
|
h
|
common.h
|
#ifndef COMMON_H
#define COMMON_H
#include <string.h>
#include <QtWidgets>
//公共设置类库
class Common
{
public:
Common();
static QString _medicalNumber;
static QString _tips;
static QString _OS;
static bool _isLog;
static QString _multimediaFolderPath;
static QString _model;
static QString _softwareVersion;
static QString _hardwareVersion;
static QString _language;
static QString _serialNumber;
static QString _batchNumber;
static QString _password;
};
void Qlog(QString log);
void updatePath();
#endif // COMMON_H
|
b9ab0b79ef88f5821d32d97cb4ea217f2bbc2fb1
|
4d7652e60c744a2f650319e6edbabd50d7429678
|
/使用C++和Qt读配置文件,写MySQL/src/common/turntomainrole.h
|
e7d78fc7d48edbc07ea9e13ca304e43cc997fa6e
|
[] |
no_license
|
clw5180/My_C_Project
|
74667d7a872a15c9d95d6909b8fec2b6e144399b
|
9499b618567fb340a8ade95b891c4ab8f83b5814
|
refs/heads/master
| 2020-05-31T14:46:14.847069
| 2019-06-30T08:42:21
| 2019-06-30T08:42:21
| 190,335,900
| 0
| 1
| null | null | null | null |
GB18030
|
C++
| false
| false
| 578
|
h
|
turntomainrole.h
|
//turntomainrole.h
#ifndef _TURNTOMAINROLE_H_
#define _TURNTOMAINROLE_H_
#include <qthread.h>
#include <qmutex.h>
class CTurntoMainRole : public QThread
{
public:
CTurntoMainRole();
virtual ~CTurntoMainRole();
bool IsToMainRole();
void BeginToMainRole();
void EndToMainRole();
protected:
virtual void run();
bool DoToMainRole();
void EndToMainTime();
private:
QMutex s_mtxToMain;
bool s_toMainRole;//是否切换为主角色
double s_toMainTime;//切换为主角色的时间
};
extern CTurntoMainRole g_toMainRoleMgr;
#endif
|
5aa7b6e7efefc501f5815f81eceec75a3fb450c1
|
d02dd66f3418c63e2dd90d5cfb914c7b3c94c6e4
|
/huffmanencoding.cpp
|
dc1d7df8b50ed82f2dfa2dca5917b78e99a32eab
|
[] |
no_license
|
Di-ken/Lossless-Data-Compression
|
aa29843e376be2518410d55ee897571d4bd0972d
|
443fb326c4b238e031f03167ef20e5bbb1656c45
|
refs/heads/master
| 2022-01-23T05:46:54.091630
| 2018-04-19T19:12:42
| 2018-04-19T19:12:42
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,605
|
cpp
|
huffmanencoding.cpp
|
#include<bits/stdc++.h>
#include "bitChar.h"
#include "HuffmanTree.h"
using namespace std;
#define ul unsigned long
string text;
ul f[257];
char fpath[200] ,nfile[200] , newfile[200]={'E',':'} ,freqfile[200];
ul getsize(char *filename)
{
streampos begin,end;
ifstream myfile (filename, ios::binary);
begin = myfile.tellg();
myfile.seekg (0, ios::end);
end = myfile.tellg();
myfile.close();
return end-begin;
}
void filesave()
{
int i;
for(i=strlen(fpath)-1;i>=0;i--)
{
if(fpath[i]==92) break;
}
int k=0;
for(int j=i;fpath[j]!='.';j++)
nfile[k++]=fpath[j];
nfile[k]='\0';
strcat(newfile,nfile);
strcpy(freqfile,newfile);
strcat(newfile,".dat");
strcat(freqfile,".freq");
ofstream of1(newfile) , of2(freqfile);
bitChar bchar;
for(int j=0;j<257;j++)
{
if(freqof(j))
of2<<j<<" "<<freqof(j)<<endl;
}
of2.close();
string encoded="";
for(ul j=0;j<text.length();j++)
{
int x=text[j];
encoded+=codeof(text[j]);
}
bchar.setBITS(encoded);
bchar.insertBits(of1);
of1.close();
}
int main()
{
printf("Enter File path to compress:");
cin>>fpath;
clock_t tStart = clock();
ifstream ifs(fpath);
char ch;
text="";
while(!ifs.eof())
{
ifs.get(ch);
f[ch]++;
text+=ch;
}
ifs.close();
populatepq(f);
cout<<"Compressing file....."<<endl;
buildHuffmanTree();
treetraversal(root,0);
filesave();
cout<<"Original size..."<<getsize(fpath)<<" bytes."<<endl;
cout<<"Size after compression..."<<getsize(newfile)<<" bytes."<<endl;
printf("Time taken to compress: %.2fs\n", (double)(clock() - tStart)/CLOCKS_PER_SEC);
}
|
f294a17a6671e5023349605f2446f95567724cd4
|
5fca9ab6310f854b655d318b50efa7fc83ad22f8
|
/service_router/doc/RegistryServiceIf.h
|
4f82069b5733640a2f10a34f74cc40c9f646083d
|
[
"Apache-2.0"
] |
permissive
|
algo-data-platform/PredictorService
|
4a73dbdac2bd1d72c18f53073fe80afbb4160bba
|
a7da427617885546c5b5e07aa7740b3dee690337
|
refs/heads/main
| 2023-03-11T17:08:35.351356
| 2021-02-24T08:46:08
| 2021-02-24T08:46:08
| 321,256,115
| 3
| 5
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 727
|
h
|
RegistryServiceIf.h
|
struct Service {
std::string ip;
int port;
std::string name;
};
/*
* 服务注册接口
*
* 服务注册分为注册列表、可用列表,可用列表主要是用来做服务的完美启动、停机设计
*/
class RegistryServiceIf {
// 向注册中心注册
virtual void register(Service service) = 0;
// 从注册中心摘除服务
virtual void unregister(Service service) = 0;
// 变更服务状态为可用,客户端可调用的服务
virtual void available(Service service) = 0;
// 将服务变为不可用状态,但是心跳探测还会继续
virtual void unavailable(Service service) = 0;
// 返回所有注册的服务列表
virtual std::vector<Service> getRegisteredServices() = 0;
};
|
a947386c3cd24fad729b3d110e06fda9ed360f1d
|
e7dec8a39537adb16fb83f33f03c4ccfd305997f
|
/tp2/main.cpp
|
2c5baf90e417d053a7769fff96db9fda791482db
|
[] |
no_license
|
tomasmussi/concurrentes
|
e7c53bdba35a93a98332d75b92548f86f1881117
|
d461a8c6219c6f006eb3f595108a5d71f9339c40
|
refs/heads/master
| 2021-01-18T18:36:35.779949
| 2017-11-30T04:28:40
| 2017-11-30T04:28:40
| 100,519,233
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,035
|
cpp
|
main.cpp
|
#include <iostream>
#include <cstring>
#include <sstream>
#include "Servidor.h"
#include "Cliente.h"
#include "Administrador.h"
int parse_int(char* arg) {
std::istringstream ss(arg);
int x;
std::stringstream s;
if (!(ss >> x) and x != MONEDA and x != TIEMPO) {
std::cout << "Tipo de cliente no reconocido. Debe ser " << TIEMPO << " (Tiempo) o bien " << MONEDA << " (Moneda)" << std::endl;
return -1;
}
return x;
}
int main(int argc, char* argv[]) {
if (argc < 2) {
std::cout << "Debe especificar cliente, administrador o servidor de la siguiente manera:" << std::endl;
std::cout << "Cliente de clima: 'c 1 BSAS'" << std::endl;
std::cout << "Cliente de monedas: 'c 2 USD'" << std::endl;
std::cout << "Administrador: 'a'" << std::endl;
std::cout << "Servidor: 's'" << std::endl;
return -1;
}
char opt = argv[1][0];
if (opt == 'c') {
// Cliente
if (argc != 4) {
std::cout << "Para ejecutar un cliente debe especificar qué tipo de consulta se quiere hacer de la siguiente manera:" << std::endl;
std::cout << "Cliente de clima: 'c 1 BSAS'" << std::endl;
std::cout << "Cliente de monedas: 'c 2 USD'" << std::endl;
return -3;
}
int tipoCliente = parse_int(argv[2]);
if (tipoCliente == -1) return -4;
Cliente c(tipoCliente, argv[3]);
c.ejecutar();
} else if (opt == 'a') {
// Administrador
Administrador a;
a.ejecutar();
} else if (opt == 's') {
// Servidor
Servidor s;
s.ejecutar();
} else {
std::cout << "Opcion no reconocida. Debe ejecutar de la siguiente manera:" << std::endl;
std::cout << "Cliente de clima: 'c 1 BSAS'" << std::endl;
std::cout << "Cliente de monedas: 'c 2 USD'" << std::endl;
std::cout << "Administrador: 'a'" << std::endl;
std::cout << "Servidor: 's'" << std::endl;
return -2;
}
return 0;
}
|
03f0b4220be3a428edea7c41d8afd7fdf09c4313
|
8d898a03e5b15f4a4e4524c6c28c2b5b27b45ca8
|
/Tree_sort/main.cpp
|
f6f1eee2e1ef24fccf8141e777e6e479aca869d5
|
[] |
no_license
|
FOAna/algorithm-library
|
badc28c5ab8f83a456972af4149dcefcdf8ffc15
|
613e3f2492b80d2e8d80c500b47d8e6ed5dddb92
|
refs/heads/main
| 2023-07-29T13:08:55.485787
| 2021-09-16T17:56:13
| 2021-09-16T17:56:13
| 407,251,261
| 0
| 0
| null | null | null | null |
MacCyrillic
|
C++
| false
| false
| 1,060
|
cpp
|
main.cpp
|
#include"Trees.h"
void main ()
{
int n,a,k=2,udal;//n - это количество чисел в дереве; a - это числа, вводимые пользователем; k - это количество чисел в дереве без первого;
//udal - это элемент, который нужно удалить.
Tree *root=new Tree, *per;
setlocale(0,"Russian");
cout<<"\n ¬ведите количество чисел, которыми вы хотите заполнить дерево. ";
cin>>n;
cout<<"\n ¬ведите число.";
cin>>a;
root=Root(a);
while (k<=n)
{
cout<<"\n ¬ведите число.";
cin>>a;
per=root;
Child(a,per);
k++;
}
cout<<"\n ƒвоичное дерево:\n";
Vyvod(0,n,0,root);
cout<<"\n ¬ведите число, которое хотите удалить из дерева. ";
cin>>udal;
root=Del(udal,root);
cout<<"\n ƒвоичное дерево без элемента, который вы хотели удалить:\n";
Vyvod(0,n,0,root);
system("pause");
}
|
108ad2905b8c4d83c667255370712defa765ee05
|
08b8cf38e1936e8cec27f84af0d3727321cec9c4
|
/data/crawl/squid/hunk_1923.cpp
|
c3a675f01e1dc85af787f1191b749597fa97b326
|
[] |
no_license
|
ccdxc/logSurvey
|
eaf28e9c2d6307140b17986d5c05106d1fd8e943
|
6b80226e1667c1e0760ab39160893ee19b0e9fb1
|
refs/heads/master
| 2022-01-07T21:31:55.446839
| 2018-04-21T14:12:43
| 2018-04-21T14:12:43
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 354
|
cpp
|
hunk_1923.cpp
|
static
void header_mangler_dump_replacement(StoreEntry * entry, const char *option,
- const header_mangler &m, const char *name)
+ const headerMangler &m, const char *name)
{
if (m.replacement)
storeAppendPrintf(entry, "%s %s %s\n", option, name, m.replacement);
|
948b31d59534581416392125b57b409ce9264eef
|
0ba672d85df06c158c700855793c80c5b76fbeb0
|
/acmicpc/cpp/9468.cc
|
c3ddd78358503e0ab44ef3a8b6aa6a6a5f128edb
|
[] |
no_license
|
jhnaldo/problem-solving
|
6b986a6d19cfe293c5e148e101fe2a7f88a4e45e
|
b4fec804b25d88a94cb65a8981f744b290849c1d
|
refs/heads/master
| 2022-07-23T14:06:39.727661
| 2022-07-07T11:17:40
| 2022-07-07T11:17:40
| 122,852,274
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 413
|
cc
|
9468.cc
|
#include <stdio.h>
int main(){
int t;
scanf("%d", &t);
while(t--){
int k, i, before, count = 0;
int arr[15];
scanf("%d", &k);
scanf("%d", &before);
for (i = 1; i < 15; i++){
int cur;
scanf("%d", &cur);
if (cur < before) count++;
before = cur;
}
printf("%d %d\n", k, count);
}
return 0;
}
|
beed8a35d4f4e1bf47fb9b5484d0773230718910
|
f45e2b74be8ed7d0fa6b3813a3149b65489ba64b
|
/SFunction/JanusSFunction.cpp
|
9f59a6fe61ac648ce8ee24727325cc8bf1eb5bc7
|
[
"MIT"
] |
permissive
|
fltdyn/Janus
|
8e7230aa2556e15ad232a2cf0e11b8100663768a
|
51b6503c291fc0789edaf130962c4c22c8293628
|
refs/heads/master
| 2023-04-01T15:20:17.009699
| 2023-03-20T01:35:41
| 2023-03-20T01:35:41
| 217,967,268
| 12
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 11,374
|
cpp
|
JanusSFunction.cpp
|
//
// DST Janus Library (Janus DAVE-ML Interpreter Library)
//
// Defence Science and Technology (DST) Group
// Department of Defence, Australia.
// 506 Lorimer St
// Fishermans Bend, VIC
// AUSTRALIA, 3207
//
// Copyright 2005-2021 Commonwealth of Australia
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify,
// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
// OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
//
#define S_FUNCTION_NAME JanusSFunction
#define S_FUNCTION_LEVEL 2
#include <set>
#include <string>
#include <simstruc.h>
#include <Janus/Janus.h>
using namespace std;
// #define DEBUG_PRINT( ...) printf( __VA_ARGS__)
#define DEBUG_PRINT( ...)
template<typename _Kty, class _Pr = std::less<_Kty>, class _Alloc = std::allocator<_Kty>>
std::set<_Kty,_Pr,_Alloc> exclusive_to_first( std::set<_Kty,_Pr,_Alloc> s1, const std::set<_Kty,_Pr,_Alloc>& s2)
{
for ( auto it = s1.begin(); it != s1.end(); ) {
if ( s2.find( *it) == s2.end()) {
++it;
}
else {
it = s1.erase( it);
}
}
return s1;
}
enum PARAMS
{
PARAM_XML_FILENAME,
PARAM_INDVARS,
PARAM_DEPVARS,
PARAM_COUNT
};
enum POINTERS
{
JANUS,
INDVARIDS,
DEPVARIDS,
INDVARS,
DEPVARS,
POINTER_COUNT
};
static void mdlInitializeSizes( SimStruct* S)
{
ssSetNumSFcnParams( S, PARAM_COUNT);
if ( ssGetNumSFcnParams( S) != ssGetSFcnParamsCount( S)) return;
ssSetSFcnParamTunable( S, PARAM_XML_FILENAME, SS_PRM_NOT_TUNABLE);
ssSetSFcnParamTunable( S, PARAM_INDVARS, SS_PRM_NOT_TUNABLE);
ssSetSFcnParamTunable( S, PARAM_DEPVARS, SS_PRM_NOT_TUNABLE);
ssSetNumContStates( S, 0);
ssSetNumDiscStates( S, 0);
// Get number of independent variables
const mxArray* indvarArray = ssGetSFcnParam( S, PARAM_INDVARS);
if ( mxGetClassID( indvarArray) == mxCHAR_CLASS) {
const int nIndVars = mxGetM( indvarArray);
DEBUG_PRINT( "nIndVars: %d\n", nIndVars);
if ( !ssSetNumInputPorts( S, 1)) return;
ssSetInputPortWidth( S, 0, nIndVars);
ssSetInputPortRequiredContiguous( S, 0, false);
ssSetInputPortDirectFeedThrough( S, 0, 1);
}
else {
if ( !ssSetNumInputPorts( S, 0)) return;
}
// Get number of dependent variables
const mxArray* depvarArray = ssGetSFcnParam( S, PARAM_DEPVARS);
if ( mxGetClassID( depvarArray) != mxCHAR_CLASS) {
// ssSetErrorStatus( S, "Dependent varIDs must be a string array.");
return;
}
const int nDepVars = mxGetM( depvarArray);
DEBUG_PRINT( "nDepVars: %d\n", nDepVars);
if ( !ssSetNumOutputPorts( S, 1)) return;
ssSetOutputPortWidth( S, 0, nDepVars);
ssSetNumSampleTimes( S, 1);
ssSetNumRWork( S, 0);
ssSetNumIWork( S, 0);
ssSetNumPWork( S, POINTER_COUNT);
ssSetNumModes( S, 0);
ssSetNumNonsampledZCs( S, 0);
ssSetOptions( S, 0);
/*ssSetOptions( S, SS_OPTION_USE_TLC_WITH_ACCELERATOR | SS_OPTION_WORKS_WITH_CODE_REUSE);
ssSetSupportedForCodeReuseAcrossModels( S, 1);*/
}
static void mdlInitializeSampleTimes( SimStruct* S)
{
ssSetSampleTime( S, 0, INHERITED_SAMPLE_TIME);
ssSetOffsetTime( S, 0, 0.0);
ssSetModelReferenceSampleTimeInheritanceRule( S, INHERITED_SAMPLE_TIME);
}
#define MDL_START
static void mdlStart( SimStruct* S)
{
if ( ssGetNumOutputPorts( S) == 0) return;
ssGetPWork(S)[JANUS] = new janus::Janus;
janus::Janus* janus = static_cast<janus::Janus*>( ssGetPWork(S)[JANUS]);
ssGetPWork(S)[INDVARS] = new vector<janus::VariableDef*>;
vector<janus::VariableDef*>* indVars = static_cast<vector<janus::VariableDef*>*>( ssGetPWork(S)[INDVARS]);
ssGetPWork(S)[DEPVARS] = new vector<janus::VariableDef*>;
vector<janus::VariableDef*>* depVars = static_cast<vector<janus::VariableDef*>*>( ssGetPWork(S)[DEPVARS]);
int status, n;
//
// Get filename and read into Janus
//
const mxArray* filenameArray = ssGetSFcnParam( S, PARAM_XML_FILENAME);
const size_t filenameLength = mxGetM( filenameArray) * mxGetN( filenameArray) + 1;
char* filename = static_cast<char*>( calloc( filenameLength, sizeof( char)));
status = mxGetString( filenameArray, filename, filenameLength);
DEBUG_PRINT( "filename: %s\n", filename);
if ( status) {
// ssSetErrorStatus( S, "XML filename could not be read");
return;
}
try {
janus->setXmlFileName( filename);
free( filename);
}
catch ( std::exception &excep) {
ssSetErrorStatus( S, excep.what());
free( filename);
return;
}
//
// Get independent variables
//
if ( ssGetNumInputPorts( S) != 0) {
const mxArray* indvarArray = ssGetSFcnParam( S, PARAM_INDVARS);
const int nIndVars = mxGetM( indvarArray);
char** indVarIDs = static_cast<char**>( calloc( nIndVars, sizeof( char*)));
const int indVarLength = mxGetM( indvarArray) * mxGetN( indvarArray) + 1;
char* indVarBuf = static_cast<char*>( calloc( indVarLength, sizeof( char)));
status = mxGetString( indvarArray, indVarBuf, indVarLength);
if ( status) {
ssWarning( S, "Independent varID strings are truncated.");
}
n = mxGetN( indvarArray);
for ( int var = 0; var < nIndVars; ++var) {
indVarIDs[var] = static_cast<char*>( calloc( n + 1, sizeof( char)));
int i = 0;
for ( ; i < n; ++i) {
if ( indVarBuf[var + nIndVars * i] == ' ') break;
indVarIDs[var][i] = indVarBuf[var + nIndVars * i];
}
DEBUG_PRINT( "%d\t", i);
indVarIDs[var][i] = '\0';
DEBUG_PRINT( "indVarIDs[%d]: %s\n", var, indVarIDs[var]);
}
ssSetPWorkValue( S, INDVARIDS, indVarIDs);
free( indVarBuf);
// Sanity check variables
set<string> janusInputVars;
const janus::VariableDefList& varDefList = janus->getVariableDef();
for ( auto& v : varDefList) {
if ( v.isInput()) janusInputVars.insert( v.getVarID());
}
set<string> thisInputVars;
for ( int i = 0; i < nIndVars; ++i) {
thisInputVars.insert( indVarIDs[i]);
}
const set<string> janusOnlyInputs = exclusive_to_first( janusInputVars, thisInputVars);
if ( !janusOnlyInputs.empty()) {
string errorMessage = "The following input variables are expected by the dataset:\n";
for ( const string& s : janusOnlyInputs) errorMessage += s + "\n";
ssWarning( S, errorMessage.c_str());
}
set<string> badInputs;
for ( const string& s : thisInputVars) {
auto v = janus->findVariableDef( s);
if ( v && !v->isInput()) badInputs.insert( s);
}
if ( !badInputs.empty()) {
string errorMessage = "The following input variables are not marked as inputs within the dataset:\n";
for ( const string& s : badInputs) errorMessage += s + "\n";
ssWarning( S, errorMessage.c_str());
}
// Store varids
for ( int i = 0; i < nIndVars; ++i) {
indVars->push_back( janus->findVariableDef( indVarIDs[i]));
}
}
else {
ssSetPWorkValue( S, INDVARIDS, nullptr);
}
//
// Get dependent variables
//
const mxArray* depvarArray = ssGetSFcnParam( S, PARAM_DEPVARS);
const int nDepVars = mxGetM( depvarArray);
char** depVarIDs = static_cast<char**>( calloc( nDepVars, sizeof( char*)));
const int depVarLength = mxGetM( depvarArray) * mxGetN( depvarArray) + 1;
char* depVarBuf = static_cast<char*>( calloc( depVarLength, sizeof( char)));
status = mxGetString( depvarArray, depVarBuf, depVarLength);
if ( status) {
ssWarning( S, "Dependent varID strings are truncated.");
}
n = mxGetN( depvarArray);
for ( int var = 0; var < nDepVars; ++var) {
depVarIDs[var] = static_cast<char*>( calloc( n + 1, sizeof( char)));
int i = 0;
for ( ; i < n; ++i) {
if ( depVarBuf[var + nDepVars * i] == ' ') break;
depVarIDs[var][i] = depVarBuf[var + nDepVars * i];
}
DEBUG_PRINT( "%d\t", i);
depVarIDs[var][i] = '\0';
DEBUG_PRINT( "depVarIDs[%d]: %s\n", var, depVarIDs[var]);
}
ssSetPWorkValue( S, DEPVARIDS, depVarIDs);
free( depVarBuf);
// Sanity check variables
set<string> badOutputs;
for ( int i = 0; i < nDepVars; ++i) {
if ( !janus->findVariableDef( depVarIDs[i])) badOutputs.insert( depVarIDs[i]);
}
if ( !badOutputs.empty()) {
string errorMessage = "The following output variables are not provided by the dataset:\n";
for ( const string& s : badOutputs) errorMessage += s + "\n";
ssWarning( S, errorMessage.c_str());
}
// Store varids
for ( int i = 0; i < nDepVars; ++i) {
depVars->push_back( janus->findVariableDef( depVarIDs[i]));
}
}
static void mdlOutputs( SimStruct *S, int_T tid)
{
vector<janus::VariableDef*>* indVars = static_cast<vector<janus::VariableDef*>*>( ssGetPWork(S)[INDVARS]);
vector<janus::VariableDef*>* depVars = static_cast<vector<janus::VariableDef*>*>( ssGetPWork(S)[DEPVARS]);
if ( ssGetNumInputPorts( S) != 0) {
InputRealPtrsType uPtrs = ssGetInputPortRealSignalPtrs( S,0);
for ( size_t i = 0; i < indVars->size(); ++i) {
if ( indVars->at( i)) indVars->at( i)->setValueMetric( *uPtrs[i]);
}
}
char** depVarIDs = static_cast<char**>( ssGetPWork(S)[DEPVARIDS]);
const mxArray* depvarArray = ssGetSFcnParam( S, PARAM_DEPVARS);
const int nDepVars = mxGetM( depvarArray);
real_T* y = ssGetOutputPortRealSignal( S, 0);
for ( int i = 0; i < depVars->size(); ++i) {
if ( depVars->at( i)) y[i] = depVars->at( i)->getValueMetric();
}
}
static void mdlTerminate( SimStruct *S)
{
janus::Janus* janus = static_cast<janus::Janus*>( ssGetPWork(S)[JANUS]);
delete janus;
vector<janus::VariableDef*>* indVars = static_cast<vector<janus::VariableDef*>*>( ssGetPWork(S)[INDVARS]);
delete indVars;
vector<janus::VariableDef*>* depVars = static_cast<vector<janus::VariableDef*>*>( ssGetPWork(S)[DEPVARS]);
delete depVars;
void* pIndVarIDs = ssGetPWork(S)[INDVARIDS];
if ( pIndVarIDs) {
char** indVarIDs = static_cast<char**>( pIndVarIDs);
const mxArray* indvarArray = ssGetSFcnParam( S, PARAM_INDVARS);
const int nIndVars = mxGetM( indvarArray);
for ( int i = 0; i < nIndVars; ++i) free( indVarIDs[i]);
free( indVarIDs);
}
char** depVarIDs = static_cast<char**>( ssGetPWork(S)[DEPVARIDS]);
const mxArray* depvarArray = ssGetSFcnParam( S, PARAM_DEPVARS);
const int nDepVars = mxGetM( depvarArray);
for ( int i = 0; i < nDepVars; ++i) free( depVarIDs[i]);
free( depVarIDs);
}
#ifdef MATLAB_MEX_FILE /* Is this file being compiled as a MEX-file? */
#include <simulink.c> /* MEX-file interface mechanism */
#else
#include "cg_sfun.h" /* Code generation registration function */
#endif
|
389e06cf3bb5f1a71bae362aa6f1b7389b7ced57
|
f7842b28f8cc6ba8badfaac0346bc288e4b12f59
|
/settings.cpp
|
5bb6cff23f91e0c5a2814c3efc6e7ae8c58511b3
|
[] |
no_license
|
pavlosun/solxd
|
7e38f795ff060c6862e43ff24a371b5fff891062
|
a9f592c74c0a1b92fb16f6ee46ce9be024f4d068
|
refs/heads/master
| 2021-05-31T11:56:02.615712
| 2015-04-13T02:59:41
| 2015-04-13T02:59:41
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 10,792
|
cpp
|
settings.cpp
|
/**************************************************************************
**
** This settings.cpp file is part of SolXd software.
**
** Copyright (C) 2015 Pavlo Solntsev
**
** SolXd is free software: you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation, either version 3 of the License, or
** (at your option) any later version.
**
** Foobar is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with Foobar. If not, see <http://www.gnu.org/licenses/>.
**
**************************************************************************/
#include "settings.h"
#include "ui_settings.h"
#include <QFileDialog>
#include <QFontDialog>
#include <QDebug>
Settings::Settings(QWidget *parent) :
QWidget(parent),
ui(new Ui::Settings)
{
ui->setupUi(this);
hide();
connect(ui->pushButtonAdd1,SIGNAL(clicked()),this,SLOT(addPath1()));
connect(ui->pushButtonAdd2,SIGNAL(clicked()),this,SLOT(addPath2()));
connect(ui->pushButtonAdd3,SIGNAL(clicked()),this,SLOT(addPath3()));
connect(ui->pushButtonDBAdd,SIGNAL(clicked()),this,SLOT(addDBPath()));
connect(ui->pushButton_addviewwr,SIGNAL(clicked()),this,SLOT(addviewer()));
connect(ui->pushButton_addtexteditor,SIGNAL(clicked()),this,SLOT(addtexteditor()));
connect(ui->pushButtonDelete1,SIGNAL(clicked()),this,SLOT(deletePath1()));
connect(ui->pushButtonDelete2,SIGNAL(clicked()),this,SLOT(deletePath2()));
connect(ui->pushButtonDelete3,SIGNAL(clicked()),this,SLOT(deletePath3()));
connect(ui->pushButtonDBDelete,SIGNAL(clicked()),this,SLOT(deleteDBPath()));
connect(ui->pushButton_deleteviewer,SIGNAL(clicked()),this,SLOT(deleteviewer()));
connect(ui->pushButton_deletetexteditor,SIGNAL(clicked()),this,SLOT(deletetexteditor()));
connect(ui->lineeditPath1,SIGNAL(textChanged(QString)),this,SLOT(path1manualchange(QString)));
connect(ui->lineeditPath2,SIGNAL(textChanged(QString)),this,SLOT(path2manualchange(QString)));
connect(ui->lineeditPath3,SIGNAL(textChanged(QString)),this,SLOT(path3manualchange(QString)));
connect(ui->lineEdit_viewer,SIGNAL(textChanged(QString)),this,SLOT(viewerpathchanged(QString)));
connect(ui->lineEdit_texteditor,SIGNAL(textChanged(QString)),this,SLOT(texteditorchanged(QString)));
connect(ui->pushButtonOk,SIGNAL(clicked()),this,SLOT(ok_button_clicked()));
connect(ui->pushButtonCancel,SIGNAL(clicked()),this,SLOT(close()));
connect(ui->spinBox_iconsize,SIGNAL(valueChanged(int)),parent,SLOT(setToolbarIcons(int)));
connect(ui->pushButton_font,SIGNAL(clicked()),this,SLOT(font_button_clicked()));
connect(ui->checkBox_shelxle,SIGNAL(stateChanged(int)),this,SLOT(shelxlecheckchanged(int)));
connect(ui->checkBox_olex2,SIGNAL(stateChanged(int)),this,SLOT(olex2checkchanged(int)));
settings = new QSettings( QSettings::IniFormat, QSettings::UserScope ,PROGRAM_NAME,PROGRAM_NAME ,this);
if(settings->contains("IndexPath1"))
{
path1 = settings->value("IndexPath1").toString();
ui->lineeditPath1->setText(path1);
listpath.append(path1);
}
if(settings->contains("IndexPath2"))
{
path2 = settings->value("IndexPath2").toString();
ui->lineeditPath2->setText(path2);
listpath.append(path2);
}
if(settings->contains("IndexPath3"))
{
path3 = settings->value("IndexPath3").toString();
ui->lineeditPath3->setText(path3);
listpath.append(path3);
}
if (settings->contains("ShelXle")) {
shelxlecheck = settings->value("ShelXle").toBool();
ui->checkBox_shelxle->setChecked(shelxlecheck);
}
if (settings->contains("Olex2")) {
olex2check = settings->value("Olex2").toBool();
ui->checkBox_olex2->setChecked(olex2check);
}
if(settings->contains("PathDB"))
{
pathDB = settings->value("PathDB").toString();
ui->lineEditDB->setText(pathDB);
}
else
ui->lineEditDB->setText(QDir::homePath());
if (settings->contains("ViewerPath")) {
viewerpath = settings->value("ViewerPath").toString();
ui->lineEdit_viewer->setText(viewerpath);
}
if (settings->contains("TextEditorPath")) {
texteditorpath = settings->value("TextEditorPath").toString();
ui->lineEdit_texteditor->setText(texteditorpath);
}
if (settings->contains("ToolBarSize")) {
toolbarsize = settings->value("ToolBarSize").toInt();
ui->spinBox_iconsize->setValue(toolbarsize);
emit toolbarIconsChanged(toolbarsize);
}
if (settings->contains("item.font.family")) {
lwfont.setFamily(settings->value("item.font.family").toString());
lwfont.setPointSize(settings->value("item.font.size").toInt());
// qDebug() << "File = " << __FILE__ << " Line " << __LINE__ << "Point size = " << settings->value("item.font.size").toInt();
lwfont.setBold(settings->value("item.font.bold").toBool());
lwfont.setItalic(settings->value("item.font.italic").toBool());
}
ui->pushButton_font->setText(lwfont.family()+", "+QString::number(lwfont.pointSize()));
emit fontChanged(lwfont);
}
Settings::~Settings()
{
delete settings;
delete ui;
}
void Settings::ok_button_clicked()
{
listpath.clear();
if(!path1.isEmpty())
{
settings->setValue("IndexPath1", path1);
listpath.append(path1);
}
if(!path2.isEmpty())
{
settings->setValue("IndexPath2", path2);
listpath.append(path2);
}
if(!path3.isEmpty())
{
settings->setValue("IndexPath3", path3);
listpath.append(path3);
}
if(!pathDB.isEmpty())
settings->setValue("PathDB", pathDB);
if (!viewerpath.isEmpty()) {
settings->setValue("ViewerPath",viewerpath);
}
if (!texteditorpath.isEmpty()) {
settings->setValue("TextEditorPath",texteditorpath);
}
int tbsize(ui->spinBox_iconsize->value());
if (tbsize != toolbarsize)
settings->setValue("ToolBarSize",tbsize);
settings->setValue("ShelXle",shelxlecheck);
settings->setValue("Olex2",olex2check);
// Save font for QListWidget
settings->setValue("item.font.family", lwfont.family());
settings->setValue("item.font.size", lwfont.pointSize());
settings->setValue("item.font.bold", lwfont.bold());
settings->setValue("item.font.italic", lwfont.italic());
// End font saving
settings->sync();
close();
}
void Settings::addPath1()
{
QString startDir;
if (path1.isEmpty())
startDir = QDir::homePath();
else
startDir = path1;
path1 = QFileDialog::getExistingDirectory(this, tr("Select Indexing Directory"),
startDir,
QFileDialog::ShowDirsOnly
| QFileDialog::DontResolveSymlinks);
ui->lineeditPath1->setText(path1);
}
void Settings::addPath2()
{
QString startDir;
if (path2.isEmpty())
startDir = QDir::homePath();
else
startDir = path2;
path2 = QFileDialog::getExistingDirectory(this, tr("Select Indexing Directory"),
startDir,
QFileDialog::ShowDirsOnly
| QFileDialog::DontResolveSymlinks);
ui->lineeditPath2->setText(path2);
}
void Settings::addPath3()
{
QString startDir;
if (path3.isEmpty())
startDir = QDir::homePath();
else
startDir = path3;
path3 = QFileDialog::getExistingDirectory(this, tr("Select Indexing Directory"),
startDir,
QFileDialog::ShowDirsOnly
| QFileDialog::DontResolveSymlinks);
ui->lineeditPath3->setText(path3);
}
void Settings::addDBPath()
{
pathDB = QFileDialog::getExistingDirectory(this, tr("Select location of the database "),
QDir::homePath(),
QFileDialog::ShowDirsOnly
| QFileDialog::DontResolveSymlinks);
ui->lineEditDB->setText(pathDB);
}
void Settings::addviewer()
{
viewerpath = QFileDialog::getOpenFileName(this, tr("Viewer Path"),
QDir::homePath(),
tr(""));
ui->lineEdit_viewer->setText(viewerpath);
}
void Settings::addtexteditor()
{
texteditorpath = QFileDialog::getOpenFileName(this, tr("Text Editor Path"),
QDir::homePath(),
tr(""));
ui->lineEdit_texteditor->setText(texteditorpath);
}
void Settings::deletePath1()
{
ui->lineeditPath1->clear();
path1.clear();
settings->remove("IndexPath1");
}
void Settings::deletePath2()
{
ui->lineeditPath2->clear();
path2.clear();
settings->remove("IndexPath2");
}
void Settings::deletePath3()
{
ui->lineeditPath3->clear();
path3.clear();
settings->remove("IndexPath3");
}
void Settings::deleteDBPath()
{
ui->lineEditDB->clear();
pathDB.clear();
settings->remove("PathDB");
}
void Settings::deleteviewer()
{
ui->lineEdit_viewer->clear();
viewerpath.clear();
settings->remove("ViewerPath");
}
void Settings::deletetexteditor()
{
ui->lineEdit_texteditor->clear();
texteditorpath.clear();
settings->remove("TextEditorPath");
}
void Settings::shelxlecheckchanged(int i)
{
if (i == Qt::Checked) {
shelxlecheck = true;
} else {
shelxlecheck = false;
}
}
void Settings::olex2checkchanged(int i)
{
if (i == Qt::Checked) {
olex2check = true;
} else {
olex2check = false;
}
}
void Settings::font_button_clicked()
{
qDebug("START on_pushButton_font_clicked() function");
bool ok;
QFont temp(lwfont);
// QFontDialog fontdialog(lwfont,this);
lwfont = QFontDialog::getFont(&ok, temp, this);
if (ok) {
ui->pushButton_font->setText(lwfont.family()+", "+QString::number(lwfont.pointSize()));
emit fontChanged(lwfont);
qDebug("Call inside IF");
}
qDebug("END on_pushButton_font_clicked() function");
}
|
4027e2c4478c4dd3dc395010ee49321432da326c
|
7883b69c2f5c3c4608c0bece407bb675f577e91a
|
/src/interface/usb.h
|
bbf99e7a2bf2526d6eab4ff7aadfe6f5161d051a
|
[
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
sniedetzki/vi-firmware
|
89c5cf89d7b13e99311ad6bae75781307f865b7a
|
cb7458b1539e6abda2359802856189fc7eba8e15
|
refs/heads/master
| 2021-01-18T13:18:03.662901
| 2014-01-30T18:16:09
| 2014-01-30T18:23:17
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,463
|
h
|
usb.h
|
#ifndef _USBUTIL_H_
#define _USBUTIL_H_
#ifdef __PIC32__
#include "chipKITUSBDevice.h"
#endif // __PIC32__
#include <string.h>
#include <stdint.h>
#include "util/bytebuffer.h"
#define USB_BUFFER_SIZE 64
#define USB_SEND_BUFFER_SIZE 512
#define MAX_USB_PACKET_SIZE_BYTES USB_BUFFER_SIZE
namespace openxc {
namespace interface {
namespace usb {
/* Public: a container for a VI USB device and associated metadata.
*
* inEndpoint - The address of the endpoint to use for IN transfers, i.e. device
* to host.
* inEndpointSize - The packet size of the IN endpoint.
* outEndpoint - The address of the endpoint to use for out transfers, i.e. host
* to device.
* outEndpointSize - The packet size of the IN endpoint.
* configured - A flag that indicates if the USB interface has been configured
* by a host. Once true, this will not be set to false until the board is
* reset.
* allowRawWrites - if raw CAN messages writes are enabled for a bus and this is
* true, accept raw write requests from the USB interface.
*
* sendQueue - A queue of bytes to send over the IN endpoint.
* receiveQueue - A queue of unprocessed bytes received from the OUT endpoint.
* device - The UsbDevice attached to the host - only used on PIC32.
*/
typedef struct {
uint8_t inEndpoint;
uint8_t inEndpointSize;
uint8_t outEndpoint;
uint8_t outEndpointSize;
bool configured;
bool allowRawWrites;
QUEUE_TYPE(uint8_t) sendQueue;
QUEUE_TYPE(uint8_t) receiveQueue;
// This buffer MUST be non-local, so it doesn't get invalidated when it
// falls off the stack
uint8_t sendBuffer[USB_SEND_BUFFER_SIZE];
#ifdef __PIC32__
char receiveBuffer[MAX_USB_PACKET_SIZE_BYTES];
USBDevice device;
USB_HANDLE deviceToHostHandle;
USB_HANDLE hostToDeviceHandle;
#endif // __PIC32__
} UsbDevice;
/* Public: Perform platform-agnostic USB initialization.
*/
void initializeCommon(UsbDevice*);
/* Public: Initializes the USB controller as a full-speed device with the
* configuration specified in usb_descriptors.c. Must be called before
* any other USB fuctions are used.
*/
void initialize(UsbDevice*);
/* Public: Pass the next OUT request message to the callback, if available.
*
* Checks if the input handle is not busy, indicating the presence of a new OUT
* request from the host. If a message is available, the callback is notified
* and the endpoint is re-armed for the next USB transfer.
*
* device - The CAN USB device to arm the endpoint on.
* callback - A function that handles USB in requests. The callback should
* return true if a message was properly received and parsed.
*/
void read(UsbDevice* device, bool (*callback)(uint8_t*));
/* Public: Send any bytes in the outgoing data queue over the IN endpoint to the
* host.
*
* This function may or may not be blocking - it's implementation dependent.
*/
void processSendQueue(UsbDevice* device);
/* Public: Send a USB control message on EP0 (the endponit used only for control
* transfers).
*
* data - An array of up bytes up to the total size of the endpoint (64 bytes
* for USB 2.0)
* length - The length of the data array.
*/
void sendControlMessage(uint8_t* data, uint8_t length);
/* Public: Disconnect from host and turn off the USB peripheral
* (minimal power draw).
*/
void deinitialize(UsbDevice*);
} // namespace usb
} // namespace interface
} // namespace openxc
#endif // _USBUTIL_H_
|
90cec3cd916fa14a9b7d7b1804f773039ba55787
|
6f51beb8825917e9626ddaf2ce60c3c3f451e665
|
/oop/public_private/main.cpp
|
e6fc45296b37dd23b167ab4f56168651e954f7bf
|
[] |
no_license
|
Andyt-Nguyen/c-basics
|
ca5d08faf0ead410f258f1265df13660cee011ed
|
3522197855deb46adfb81b59e73b228d93d0806d
|
refs/heads/master
| 2020-04-16T07:50:00.284205
| 2019-09-05T08:37:32
| 2019-09-05T08:37:32
| 165,401,073
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 616
|
cpp
|
main.cpp
|
#include <iostream>
#include <string>
using namespace std;
class Player {
private:
string name {"Frank"};
int health;
int xp;
public:
void talk(string text_to_say) {
cout << name << " says " << text_to_say << endl;
}
};
int main() {
Player *andy = new Player();
// andy->name= "Andy"; // will return error because this member is private
// andy->xp = 12; // will return error because this member is private
// andy->health = 100; // will return error because this member is private
andy->talk("hey what's up?");
return 0;
}
|
033e640f88748309041dda3fa7f5b664d7d9eb56
|
dbd759663b6f5d90da258aaeab5998c131d054a4
|
/project-euler/problem_307.cpp
|
3f2f7b9c12a1de72699c2d72ceaac334c28b12ea
|
[
"Apache-2.0"
] |
permissive
|
sihrc/Personal-Code-Bin
|
9c0005993dfbd371f51e86ab525b3d4a9ac7a218
|
91a894a68606151d2381cf8f25709b997df00011
|
refs/heads/master
| 2020-02-26T15:13:33.960604
| 2014-04-28T16:02:28
| 2014-04-28T16:02:28
| 13,988,578
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 454
|
cpp
|
problem_307.cpp
|
/*
Chip Defects
Problem 307
k defects are randomly distributed amongst n integrated-circuit chips produced by a factory (any number of defects may be found on a chip and each defect is independent of the other defects).
Let p(k,n) represent the probability that there is a chip with at least 3 defects.
For instance p(3,7) 0.0204081633.
Find p(20 000, 1 000 000) and give your answer rounded to 10 decimal places in the form 0.abcdefghij
*/
|
126c65a54f9bddabc1239e0b9e369a0955e424b3
|
b9bd29b459477bf0658465085532670117a1d6f9
|
/Input/SpecialIOGame/SpecialIOGame/main.cpp
|
b112eee0564a95bbd989dc188a74a045b8c70a62
|
[] |
no_license
|
WHofstra/Special_Input-Output_01
|
5a50147ec1f854f2a3e31223ea4b54f87063be8f
|
ad14fc74c94dc2d92e5198b198b0054ee69519d3
|
refs/heads/master
| 2021-02-11T08:16:53.700173
| 2020-04-21T22:00:24
| 2020-04-21T22:00:24
| 244,471,500
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,580
|
cpp
|
main.cpp
|
#include <iostream>
#include <SFML/Graphics.hpp>
#include <list>
#include "Stage.h"
#include "StageDisplay.h"
#include "Player.h"
#include "Controller.h"
int main()
{
//Set Window Resolution to Super Nintendo Entertainment System/Super Famicom
const int WIN_WIDTH = 512;
const int WIN_HEIGHT = 448;
//Define Server Info
std::string serverUrl = "http://29980.hosts2.ma-cloud.nl";
std::string filePath = "/bewijzenmap/SpIO/test.json";
//Create Window
sf::RenderWindow window(sf::VideoMode(WIN_WIDTH, WIN_HEIGHT), "Special Output",
sf::Style::Titlebar | sf::Style::Close); //No Resizing Possible
//Set Controller
Controller* controller = new Controller(&serverUrl, &filePath, &window);
//Define Stages
std::list<Stage*> stages = { new Stage(Stage::StageName::DONUT_PLAINS),
new Stage(Stage::StageName::MARIO_CIRCUIT),
new Stage(Stage::StageName::BOWSERS_CASTLE) };
//Define Texture Character Sprite References
sf::Texture objectTexture;
if (!objectTexture.loadFromFile("Assets/CharacterSprites.png"))
{
return EXIT_FAILURE;
}
objectTexture.setSmooth(true);
//Define Characters
Player* player = new Player(WIN_WIDTH / 2, WIN_HEIGHT / 2, 0,
Character::CType::WALUIGI, &objectTexture, controller);
player->SetBoundaries(&window);
//List Iterator Pointing to Start of List
std::list<Stage*>::iterator sIt = stages.begin();
//Display Stage
StageDisplay* stageDisplay = new StageDisplay(*sIt, &window, WIN_WIDTH/2, WIN_HEIGHT/2);
//std::cout << stageDisplay->GetStageName() << std::endl; //For Debug Purposes
//Start Game Loop
//while (gameRunning) //Use This for OpenGL Rendering
while(window.isOpen())
{
//Update
player->Update();
controller->Update();
sf::Event event;
while (window.pollEvent(event))
{
//Close Window or Press 'Shift + Esc' to Quit.
if (event.type == sf::Event::Closed ||
(event.type == sf::Event::KeyPressed && (event.key.shift && event.key.code == sf::Keyboard::Escape)))
{
//gameRunning = false; //Use This for OpenGL Rendering
window.close();
}
//Check Key Input
else if (event.type == sf::Event::KeyPressed)
{
player->GetPlayerControllerPress(&event);
}
//Check Key Release
else if (event.type == sf::Event::KeyReleased)
{
player->GetPlayerControllerRelease(&event);
}
}
//Clear Window
window.clear();
//Draw
window.draw(stageDisplay->GetStageWindowDisplay());
window.draw(player->GetWindowSpriteDisplay());
window.draw(player->GetWindowPlaneDisplay());
//Display Window
window.display();
}
return 0;
}
|
cc1e9d792507836f7cd3b3201c8d4758231ea357
|
63e36fef281e6ca1d1fce7fde86d95c88459505c
|
/src/xinterpreter.cpp
|
45a750a58a41330e37bc00428feaa2eb44f23a4e
|
[
"BSD-3-Clause"
] |
permissive
|
jupyter-xeus/xeus-python
|
58fd2f83febfa96e9425cd9c5fdbf099a41c2f01
|
f87c29cab41a1ff9ea3524e5c0af328a0449f71e
|
refs/heads/main
| 2023-08-05T08:58:18.172029
| 2023-04-27T13:42:24
| 2023-04-27T13:42:24
| 152,753,394
| 329
| 52
|
BSD-3-Clause
| 2023-04-21T09:59:20
| 2018-10-12T13:18:30
|
C++
|
UTF-8
|
C++
| false
| false
| 11,681
|
cpp
|
xinterpreter.cpp
|
/***************************************************************************
* Copyright (c) 2018, Martin Renou, Johan Mabille, Sylvain Corlay, and *
* Wolf Vollprecht *
* Copyright (c) 2018, QuantStack *
* *
* Distributed under the terms of the BSD 3-Clause License. *
* *
* The full license is in the file LICENSE, distributed with this software. *
****************************************************************************/
#include <algorithm>
#include <fstream>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "nlohmann/json.hpp"
#include "xeus/xinterpreter.hpp"
#include "xeus/xsystem.hpp"
#include "pybind11/functional.h"
#include "pybind11_json/pybind11_json.hpp"
#include "xeus-python/xinterpreter.hpp"
#include "xeus-python/xeus_python_config.hpp"
#include "xeus-python/xtraceback.hpp"
#include "xeus-python/xutils.hpp"
#include "xcomm.hpp"
#include "xkernel.hpp"
#include "xdisplay.hpp"
#include "xinput.hpp"
#include "xinternal_utils.hpp"
#include "xstream.hpp"
namespace py = pybind11;
namespace nl = nlohmann;
using namespace pybind11::literals;
namespace xpyt
{
interpreter::interpreter(bool redirect_output_enabled /*=true*/, bool redirect_display_enabled /*=true*/)
: m_redirect_output_enabled{redirect_output_enabled}, m_redirect_display_enabled{redirect_display_enabled}
{
xeus::register_interpreter(this);
}
interpreter::~interpreter()
{
}
void interpreter::configure_impl()
{
if (m_release_gil_at_startup)
{
// The GIL is not held by default by the interpreter, so every time we need to execute Python code we
// will need to acquire the GIL
m_release_gil = gil_scoped_release_ptr(new py::gil_scoped_release());
}
py::gil_scoped_acquire acquire;
py::module sys = py::module::import("sys");
py::module logging = py::module::import("logging");
py::module display_module = get_display_module();
py::module traceback_module = get_traceback_module();
py::module stream_module = get_stream_module();
py::module comm_module = get_comm_module();
py::module kernel_module = get_kernel_module();
// Old approach: ipykernel provides the comm
sys.attr("modules")["ipykernel.comm"] = comm_module;
// New approach: we provide our comm module
sys.attr("modules")["comm"] = comm_module;
instanciate_ipython_shell();
m_ipython_shell_app.attr("initialize")();
m_ipython_shell = m_ipython_shell_app.attr("shell");
// Setting kernel property owning the CommManager and get_parent
m_ipython_shell.attr("kernel") = kernel_module.attr("XKernel")();
m_ipython_shell.attr("kernel").attr("comm_manager") = comm_module.attr("CommManager")();
// Initializing the DisplayPublisher
m_ipython_shell.attr("display_pub").attr("publish_display_data") = display_module.attr("publish_display_data");
m_ipython_shell.attr("display_pub").attr("clear_output") = display_module.attr("clear_output");
// Initializing the DisplayHook
m_displayhook = m_ipython_shell.attr("displayhook");
m_displayhook.attr("publish_execution_result") = display_module.attr("publish_execution_result");
// Needed for redirecting logging to the terminal
m_logger = m_ipython_shell_app.attr("log");
m_terminal_stream = stream_module.attr("TerminalStream")();
m_logger.attr("handlers") = py::list(0);
m_logger.attr("addHandler")(logging.attr("StreamHandler")(m_terminal_stream));
// Initializing the compiler
m_ipython_shell.attr("compile").attr("filename_mapper") = traceback_module.attr("register_filename_mapping");
m_ipython_shell.attr("compile").attr("get_filename") = traceback_module.attr("get_filename");
if (m_redirect_output_enabled)
{
redirect_output();
}
}
nl::json interpreter::execute_request_impl(int /*execution_count*/,
const std::string& code,
bool silent,
bool store_history,
nl::json user_expressions,
bool allow_stdin)
{
py::gil_scoped_acquire acquire;
nl::json kernel_res;
// Reset traceback
m_ipython_shell.attr("last_error") = py::none();
// Scope guard performing the temporary monkey patching of input and
// getpass with a function sending input_request messages.
auto input_guard = input_redirection(allow_stdin);
py::object ipython_res = m_ipython_shell.attr("run_cell")(code, "store_history"_a=store_history, "silent"_a=silent);
// Get payload
kernel_res["payload"] = m_ipython_shell.attr("payload_manager").attr("read_payload")();
m_ipython_shell.attr("payload_manager").attr("clear_payload")();
if (m_ipython_shell.attr("last_error").is_none())
{
kernel_res["status"] = "ok";
kernel_res["user_expressions"] = m_ipython_shell.attr("user_expressions")(user_expressions);
}
else
{
py::list pyerror = m_ipython_shell.attr("last_error");
xerror error = extract_error(pyerror);
if (!silent)
{
publish_execution_error(error.m_ename, error.m_evalue, error.m_traceback);
}
kernel_res["status"] = "error";
kernel_res["ename"] = error.m_ename;
kernel_res["evalue"] = error.m_evalue;
kernel_res["traceback"] = error.m_traceback;
}
return kernel_res;
}
nl::json interpreter::complete_request_impl(
const std::string& code,
int cursor_pos)
{
py::gil_scoped_acquire acquire;
nl::json kernel_res;
py::list completion = m_ipython_shell.attr("complete_code")(code, cursor_pos);
kernel_res["matches"] = completion[0];
kernel_res["cursor_start"] = completion[1];
kernel_res["cursor_end"] = completion[2];
kernel_res["metadata"] = nl::json::object();
kernel_res["status"] = "ok";
return kernel_res;
}
nl::json interpreter::inspect_request_impl(const std::string& code,
int cursor_pos,
int detail_level)
{
py::gil_scoped_acquire acquire;
nl::json kernel_res;
nl::json data = nl::json::object();
bool found = false;
py::module tokenutil = py::module::import("IPython.utils.tokenutil");
py::str name = tokenutil.attr("token_at_cursor")(code, cursor_pos);
try
{
data = m_ipython_shell.attr("object_inspect_mime")(
name,
"detail_level"_a=detail_level
);
found = true;
}
catch (py::error_already_set& e)
{
// pass
}
kernel_res["data"] = data;
kernel_res["metadata"] = nl::json::object();
kernel_res["found"] = found;
kernel_res["status"] = "ok";
return kernel_res;
}
nl::json interpreter::is_complete_request_impl(const std::string& code)
{
py::gil_scoped_acquire acquire;
nl::json kernel_res;
py::object transformer_manager = py::getattr(m_ipython_shell, "input_transformer_manager", py::none());
if (transformer_manager.is_none())
{
transformer_manager = m_ipython_shell.attr("input_splitter");
}
py::list result = transformer_manager.attr("check_complete")(code);
auto status = result[0].cast<std::string>();
kernel_res["status"] = status;
if (status.compare("incomplete") == 0)
{
kernel_res["indent"] = std::string(result[1].cast<std::size_t>(), ' ');
}
return kernel_res;
}
nl::json interpreter::kernel_info_request_impl()
{
nl::json result;
result["implementation"] = "xeus-python";
result["implementation_version"] = XPYT_VERSION;
/* The jupyter-console banner for xeus-python is the following:
__ _____ _ _ ___
\ \/ / _ \ | | / __|
> < __/ |_| \__ \
/_/\_\___|\__,_|___/
xeus-python: a Jupyter lernel for Python
*/
std::string banner = ""
" __ _____ _ _ ___\n"
" \\ \\/ / _ \\ | | / __|\n"
" > < __/ |_| \\__ \\\n"
" /_/\\_\\___|\\__,_|___/\n"
"\n"
" xeus-python: a Jupyter kernel for Python\n"
" Python ";
banner.append(PY_VERSION);
#ifdef XEUS_PYTHON_PYPI_WARNING
banner.append("\n"
"\n"
"WARNING: this instance of xeus-python has been installed from a PyPI wheel.\n"
"We recommend using a general-purpose package manager instead, such as Conda/Mamba."
"\n");
#endif
result["banner"] = banner;
result["debugger"] = true;
result["language_info"]["name"] = "python";
result["language_info"]["version"] = PY_VERSION;
result["language_info"]["mimetype"] = "text/x-python";
result["language_info"]["file_extension"] = ".py";
result["help_links"] = nl::json::array();
result["help_links"][0] = nl::json::object({
{"text", "Xeus-Python Reference"},
{"url", "https://xeus-python.readthedocs.io"}
});
result["status"] = "ok";
return result;
}
void interpreter::shutdown_request_impl()
{
}
nl::json interpreter::internal_request_impl(const nl::json& content)
{
py::gil_scoped_acquire acquire;
std::string code = content.value("code", "");
nl::json reply;
// Reset traceback
m_ipython_shell.attr("last_error") = py::none();
try
{
exec(py::str(code));
reply["status"] = "ok";
}
catch (py::error_already_set& e)
{
// This will grab the latest traceback and set shell.last_error
m_ipython_shell.attr("showtraceback")();
py::list pyerror = m_ipython_shell.attr("last_error");
xerror error = extract_error(pyerror);
publish_execution_error(error.m_ename, error.m_evalue, error.m_traceback);
error.m_traceback.resize(1);
error.m_traceback[0] = code;
reply["status"] = "error";
reply["ename"] = error.m_ename;
reply["evalue"] = error.m_evalue;
reply["traceback"] = error.m_traceback;
}
return reply;
}
void interpreter::redirect_output()
{
py::module sys = py::module::import("sys");
py::module stream_module = get_stream_module();
sys.attr("stdout") = stream_module.attr("Stream")("stdout");
sys.attr("stderr") = stream_module.attr("Stream")("stderr");
}
void interpreter::instanciate_ipython_shell()
{
m_ipython_shell_app = py::module::import("xeus_python_shell.shell").attr("XPythonShellApp")();
}
}
|
80bbeef102de828e3c39409c95c177ad4959a868
|
4eef5340be2eb04c1165215fe68a0d2f448b2e4c
|
/include/gpio.h
|
74b6043b8d9685c339ed577aa9fc4c020925bb66
|
[
"MIT"
] |
permissive
|
marangisto/stm32f4
|
5b9aede29bc0567b5ed8d9732a03586a3e0e2d56
|
9e27131a147d30eb1acec4ccbd45b9c3986e90ea
|
refs/heads/master
| 2020-05-24T22:02:35.596475
| 2019-06-16T13:03:06
| 2019-06-16T13:03:06
| 187,489,482
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,822
|
h
|
gpio.h
|
#pragma once
#include <stm32f4.h>
namespace stm32f4
{
namespace gpio
{
using namespace device;
enum gpio_port_t { PA, PB, PC, PD, PE, PH };
enum gpio_pin_t
{ PA0, PA1, PA2, PA3, PA4, PA5, PA6, PA7, PA8, PA9, PA10, PA11, PA12, PA13, PA14, PA15
, PB0, PB1, PB2, PB3, PB4, PB5, PB6, PB7, PB8, PB9, PB10, PB11, PB12, PB13, PB14, PB15
, PC0, PC1, PC2, PC3, PC4, PC5, PC6, PC7, PC8, PC9, PC10, PC11, PC12, PC13, PC14, PC15
, PD0, PD1, PD2, PD3, PD4, PD5, PD6, PD7, PD8, PD9, PD10, PD11, PD12, PD13, PD14, PD15
, PE0, PE1, PE2, PE3, PE4, PE5, PE6, PE7, PE8, PE9, PE10, PE11, PE12, PE13, PE14, PE15
, PH0, PH1, PH2, PH3, PH4, PH5, PH6, PH7, PH8, PH9, PH10, PH11, PH12, PH13, PH14, PH15
};
static inline constexpr gpio_port_t pin_port(gpio_pin_t p)
{
return static_cast<gpio_port_t>(static_cast<int>(p) >> 4);
}
static inline constexpr int pin_bit(gpio_pin_t p)
{
return static_cast<int>(p) & 0xf;
}
enum output_type_t { push_pull, open_drain };
enum output_speed_t { low_speed = 0x0, medium_speed = 0x1, high_speed = 0x3 };
enum input_type_t { floating, pull_up, pull_down };
template<gpio_port_t PORT> struct port_traits {};
template<> struct port_traits<PA>
{
typedef gpioa_t gpio_t;
static inline gpio_t& gpio() { return GPIOA; }
static inline void setup() { RCC.AHB1ENR |= BV(rcc_t::AHB1ENR_GPIOAEN); }
};
template<> struct port_traits<PB>
{
typedef gpiob_t gpio_t;
static inline gpio_t& gpio() { return GPIOB; }
static inline void setup() { RCC.AHB1ENR |= BV(rcc_t::AHB1ENR_GPIOBEN); }
};
template<> struct port_traits<PC>
{
typedef gpioc_t gpio_t;
static inline gpio_t& gpio() { return GPIOC; }
static inline void setup() { RCC.AHB1ENR |= BV(rcc_t::AHB1ENR_GPIOCEN); }
};
template<> struct port_traits<PD>
{
typedef gpiod_t gpio_t;
static inline gpio_t& gpio() { return GPIOD; }
static inline void setup() { RCC.AHB1ENR |= BV(rcc_t::AHB1ENR_GPIODEN); }
};
template<> struct port_traits<PE>
{
typedef gpioe_t gpio_t;
static inline gpio_t& gpio() { return GPIOE; }
static inline void setup() { RCC.AHB1ENR |= BV(rcc_t::AHB1ENR_GPIOEEN); }
};
template<> struct port_traits<PH>
{
typedef gpioh_t gpio_t;
static inline gpio_t& gpio() { return GPIOH; }
static inline void setup() { RCC.AHB1ENR |= BV(rcc_t::AHB1ENR_GPIOHEN); }
};
template<gpio_pin_t PIN>
struct pin_t
{
enum moder { input_mode, output_mode, alternate_mode, analog_mode };
typedef typename port_traits<pin_port(PIN)>::gpio_t gpio_t;
static_assert(pin_bit(PIN) < 16, "pin_t bit out of range");
static inline gpio_t& gpio() { return port_traits<pin_port(PIN)>::gpio(); }
static const uint8_t bit_pos = pin_bit(PIN);
static const uint32_t bit_mask = BV(bit_pos);
};
template<gpio_pin_t PIN>
class output_t
{
public:
template<output_type_t output_type = push_pull, output_speed_t speed = low_speed>
static inline void setup()
{
port_traits<pin_port(PIN)>::setup();
pin::gpio().MODER |= pin::output_mode << (pin::bit_pos*2);
if (speed != low_speed)
pin::gpio().OSPEEDR |= speed << (pin::bit_pos*2);
if (output_type == open_drain)
pin::gpio().OTYPER |= pin::bit_mask;
}
static inline void set() { pin::gpio().BSRR = pin::bit_mask; }
static inline void clear() { pin::gpio().BSRR = pin::bit_mask << 16; }
static inline bool read() { return (pin::gpio().ODR & pin::bit_mask) != 0; }
static inline void write(bool x) { x ? set() : clear(); }
static inline void toggle() { write(!read()); }
private:
typedef pin_t<PIN> pin;
};
template<gpio_pin_t PIN>
class input_t
{
public:
template<input_type_t input_type = floating>
static inline void setup()
{
port_traits<pin_port(PIN)>::setup();
pin::gpio().MODER |= pin::input_mode << (pin::bit_pos*2);
if (input_type != floating)
pin::gpio().PUPDR |= input_type << (pin::bit_pos*2);
}
static inline bool read() { return (pin::gpio().IDR & pin::bit_mask) != 0; }
private:
typedef pin_t<PIN> pin;
};
namespace internal
{
enum alt_fun_t { AF0, AF1, AF2, AF3, AF4, AF5, AF6, AF7 };
enum alternate_function_t
{ CAN_RX
, CAN_TX
, CEC
, COMP1_OUT
, COMP2_OUT
, CRS_SYNC
, EVENTOUT
, I2C1_SCL
, I2C1_SDA
, I2C1_SMBA
, I2C2_SCL
, I2C2_SDA
, I2S1_CK
, I2S1_MCK
, I2S1_SD
, I2S1_WS
, IR_OUT
, MCO
, SPI1_MISO
, SPI1_MOSI
, SPI1_NSS
, SPI1_SCK
, SPI2_MISO
, SPI2_MOSI
, SPI2_NSS
, SPI2_SCK
, SWCLK
, SWDIO
, TIM14_CH1
, TIM15_BKIN
, TIM15_CH1
, TIM15_CH1N
, TIM15_CH2
, TIM16_BKIN
, TIM16_CH1
, TIM16_CH1N
, TIM17_BKIN
, TIM17_CH1
, TIM17_CH1N
, TIM1_BKIN
, TIM1_CH1
, TIM1_CH1N
, TIM1_CH2
, TIM1_CH2N
, TIM1_CH3
, TIM1_CH3N
, TIM1_CH4
, TIM1_ETR
, TIM2_CH1_ETR
, TIM2_CH2
, TIM2_CH3
, TIM2_CH4
, TIM3_CH1
, TIM3_CH2
, TIM3_CH3
, TIM3_CH4
, TIM3_ETR
, TSC_G1_IO1
, TSC_G1_IO2
, TSC_G1_IO3
, TSC_G1_IO4
, TSC_G2_IO1
, TSC_G2_IO2
, TSC_G2_IO3
, TSC_G2_IO4
, TSC_G3_IO2
, TSC_G3_IO3
, TSC_G3_IO4
, TSC_G4_IO1
, TSC_G4_IO2
, TSC_G4_IO3
, TSC_G4_IO4
, TSC_G5_IO1
, TSC_G5_IO2
, TSC_G5_IO3
, TSC_G5_IO4
, TSC_G6_IO1
, TSC_G6_IO2
, TSC_G6_IO3
, TSC_G6_IO4
, TSC_SYNC
, USART1_CK
, USART1_CTS
, USART1_RTS
, USART1_RX
, USART1_TX
, USART2_CK
, USART2_CTS
, USART2_RTS
, USART2_RX
, USART2_TX
, USART3_CTS
, USART4_RTS
, USART4_RX
, USART4_TX
, USART6_RX
, USART6_TX
};
template<gpio_pin_t PIN, alternate_function_t ALT>
struct alt_fun_traits {};
#define ALT_FUN_TRAIT(PIN, ALT_FUN, AFNO) \
template<> struct alt_fun_traits<PIN, ALT_FUN> \
{ \
static inline alt_fun_t AF() { return AFNO; } \
}
#if defined(STM32F411)
#include "gpio/stm32f411.h"
#endif
template<gpio_pin_t PIN, alternate_function_t ALT>
class alternate_t
{
public:
template<output_speed_t speed = low_speed>
static inline void setup()
{
port_traits<pin_port(PIN)>::setup();
pin::gpio().MODER |= pin::alternate_mode << (pin::bit_pos*2);
if (speed != low_speed)
pin::gpio().OSPEEDR |= speed << (pin::bit_pos*2);
if (pin::bit_pos < 8)
pin::gpio().AFRL |= alt_fun_traits<PIN, ALT>::AF() << (pin::bit_pos*4);
else
pin::gpio().AFRH |= alt_fun_traits<PIN, ALT>::AF() << ((pin::bit_pos-8)*4);
}
// FIXME: consider overloads with pull-up, open-drain, speed, etc.
private:
typedef pin_t<PIN> pin;
};
}
}
}
|
9c0f47c6828354c8565d9f02d2a815cf3fd43f90
|
87e0226d3978e6c5897e762a9606370c22fe2e2d
|
/CPP/explore/ReverseList.cpp
|
eb6a7234592da7edcbf1a43e4f52ff2c8452a411
|
[] |
no_license
|
tenglin2/LeetCode
|
cd3fb75be71843b49ca0e07256bc02757c66fec6
|
25a3ce9ba297dab0bdf1f085cfc4266edb08c7d0
|
refs/heads/master
| 2020-05-30T03:00:15.661614
| 2020-01-20T15:24:33
| 2020-01-20T15:24:33
| 189,506,524
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 782
|
cpp
|
ReverseList.cpp
|
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
#include <cstdlib>
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution
{
public:
ListNode *reverseList(ListNode *head)
{
ListNode *currentNode = head;
ListNode *prev = NULL;
ListNode *next;
ListNode *newHead;
while (currentNode != NULL)
{
// Now the tail...
if (currentNode->next == NULL)
newHead = currentNode;
next = currentNode->next;
currentNode->next = prev;
prev = currentNode;
currentNode = next;
}
// Problem is that it iterates to null, not tail.
return newHead;
}
};
|
4d6d44ebd7761d6dfcdbd80a7f93e2e184f83a6a
|
a821662a42f3d3784c89aa1cb9d8dc94f5a4e2e5
|
/搜索/1016.cpp
|
66b6a2467a469d3342ac7dd90e0bde42912cdd85
|
[] |
no_license
|
Jaycebox/acm
|
a9cfed70b02f2b4986ca718012b89cf8ff89b2b2
|
da98380cad31e7280e14fd33be2191d2a58439b7
|
refs/heads/master
| 2021-01-25T05:08:58.849848
| 2017-07-30T06:08:38
| 2017-07-30T06:08:38
| 93,507,806
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,057
|
cpp
|
1016.cpp
|
//dfs,加一减一,多练,好题
//素数环
#include <iostream>
#include <math.h>
#include <string.h>
using namespace std;
const int mmax = 100;
int n;
int visit[25];
int a[25];
bool isprime(int n)
{
double k = sqrt(n);
for(int i = 2; i<=k;i++)
{
if(!(n%i)) return 0;
}
return 1;
}
void dfs(int x)//x为循环节
{
if(x == n && isprime(a[n-1]+1))
{
for(int i = 0; i< n-1; i++)
{
printf("%d ",a[i]);
}
printf("%d\n",a[n-1]);
}
for(int i = 2; i <= n; i++)//可以奇偶判断一下//1已有
{
if(visit[i] == 0)
{
if(isprime(a[x-1]+i))//为减一
{
visit[i] = 1;
a[x] = i;
dfs(x+1);
visit[i] = 0;
}
}
}
}
int main()
{
int t = 0;
memset(visit,0,sizeof(visit));
while(scanf("%d",&n) == 1)
{
a[0] = 1;
t++;
printf("Case %d:\n",t);
dfs(1);
printf("\n");
}
return 0;
}
|
412069a4d4b3e2560b3ae6ca960927d7e1300996
|
0bb5d96d6b9e844b4ce33efdc791ac2800a267a6
|
/ksdb.cpp
|
77367bef3e0f97d1ea1257d3eed38ec326f5ba79
|
[] |
no_license
|
labhmanmohan25/Classical-Codes
|
c701fa9086015aa38b898b05524344e88bd57146
|
a127e362f8bec8f4b6635d6882ae4d40f5058492
|
refs/heads/master
| 2022-11-20T20:25:46.643457
| 2020-07-28T14:34:05
| 2020-07-28T14:34:05
| 283,234,467
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,002
|
cpp
|
ksdb.cpp
|
#include<bits/stdc++.h>
//One implementation to rule them all?
#define db double
#define ll long long int
#define ld long long double
//#define int long long int
#define ull unsigned long long
#define fi first
#define se second
#define rep(i,a,n) for(int i=a;i<n;i++)
#define repr(i,n,b) for(int i=n;i>=b;i--)
#define endl '\n'
#define mem(a,b) memset(a, b, sizeof a)
#define mkp make_pair
#define pb push_back
#define max3(a,b,c) max(a,max(b,c))
#define min3(a,b,c) min(a,min(b,c))
#define w(t) int t; cin>>t; while(t--)
#define all(a) a.begin(), a.end()
#define sz(a) int((a).size())
#define debug(x) cerr << #x << " = " << x << endl;
//Bitwise
#define isOn(S, j) (S & (1<<j))
#define setBit(S, j) (S |= (1<<j))
#define clearBit(S, j) (S &= ~(1<<j))
#define toggleBit(S, j) (S ^= (1<<j))
#define lowBit(S) (S & (-S))
#define setAll(S, n) (S = (1<<n)-1)
#define turnOffLastBit(S) ((S) & (S-1))
#define turnOnLastZero(S) ((S) | (S+1))
//Can use tuples in C++17
using namespace std;
typedef vector < int > vii;
typedef vector < ll > vll;
typedef vector < vii > vvi;
typedef pair < int,int > pii;
template <class T> using min_heap = priority_queue<T,vector<T>,greater<T> >;
template <class T> using max_heap = priority_queue<T>;
const db PI = 2*acos(0.0);
const int INF = 0x3f3f3f3f;
const ll LINF = (ll)2e18;
db eps = 0.000001;
ll mod = 998244353; //(1e9+7)
void print(vector <int> &arr){
for(int i=0;i<arr.size();i++)
cout<<arr[i]<<" ";
cout<<endl;
}
void printll(vector <ll> &arr){
for(int i=0;i<arr.size();i++)
cout<<arr[i]<<" ";
cout<<endl;
}
ll ncr(ll n, ll r)
{
r=min(r,n-r);
ll A[r],i,j,B[r];
iota(A,A+r,n-r+1);
iota(B,B+r,1);
ll g;
for(i=0;i<r;i++)
for(j=0;j<r;j++)
{
if(B[i]==1)
break;
g=__gcd(B[i], A[j] );
A[j]/=g;
B[i]/=g;
}
ll ans=1;
for(i=0;i<r;i++)
ans=(ans*A[i]%mod);
return ans;
}
const int SIZE=2000008;
bool judgePermutation(int a[], int n){
static int used[SIZE+1];
for(int i = 1; i <= n; i++) used[i] = 0;
for(int i = 0; i < n; i++) used[a[i]] = 1;
for(int i = 1; i <= n; i++) {
if(!used[i]) return 0;
}
return 1;
}
bool check(string s, int k, int index){
rep(i,index-k,index+k+1){
if(i==index) continue;
if(i>=0 && i<sz(s)){
if(s[i]=='1') return false;
}
}
return true;
}
int main(){
//CONDITION && cout << "YES" || cout << "NO"; cout << '\n';
//////////////////////////////////////////////////////////////////////
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cerr.tie(NULL);
//For fast IO
/////////////////////////////////////////////////////////////////////
// std::cout.unsetf ( std::ios::floatfield ); // floatfield not set
// std::cout.precision(10);
// freopen("input.txt","r",stdin);
// freopen("output.txt","w",stdout);
w(t){
int n,k,cnt=0,f=1;
cin>>n>>k;
string s;
cin>>s;
rep(i,0,n){
if(s[i]=='1') f=0;
}
if(f){
int cnt=0;
cnt+=(n/(k+1));
if(n%(k+1)) cnt++;
cout<<cnt<<endl;
}
else{
int i1=0,i2=n-1;
while(s[i1]!='1') i1++;
while(s[i2]!='1') i2--;
//cout<<i1<<" "<<i2<<endl;
rep(i,i1,i2+1){
int j=i;
if(s[i]=='1') continue;
while(j<=i2 && s[j]=='0') j++;
int l=j-i;
//cout<<i<<" "<<l<<" "<<j<<endl;
cnt+=(l-(k))/(k+1);
i=j;
}
//cout<<i1<<" "<<i2<<endl;
int l1=max(0,i1-k), l2=max(0,n-1-i2-k);
//cout<<l1<<" "<<l2<<endl;
int cnt1=0,cnt2=0;
cnt1+=(l1/(k+1));
if(l1%(k+1)) cnt1++;
cnt2+=(l2/(k+1));
if(l2%(k+1)) cnt2++;
cout<<cnt+cnt1+cnt2<<endl;
}
}
return 0;
}
|
5e5705b14591b789323d71fa5e6d627e62f51186
|
cabb9cc7ece0e2aa14c1f30d8f593ffb7a5fef64
|
/Classes/df/types.h
|
23b85355bce24998de3d6783a6a7cf34aae5d660
|
[] |
no_license
|
atom-chen/jzhall
|
50b0844ad501717e47c04365fea6924eb0043dd2
|
9ab4d32ec02f342e6ac84b43c5791011ce62421e
|
refs/heads/master
| 2020-07-03T10:06:21.891623
| 2019-03-19T02:02:40
| 2019-03-19T02:02:40
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,906
|
h
|
types.h
|
#ifndef _types_H_
#define _types_H_
//////////////////////////////////////////////////////////////
#include <assert.h>
#include <stdio.h>
#include <string>
#include <set>
#include <map>
#include <unordered_map>
#include <vector>
#include <iostream>
#include <fstream>
#include <cmath>
#include <algorithm>
#include <deque>
#include <iomanip>
#include <list>
#include <sstream>
//#include <basetyps.h>
#include <assert.h>
#include <stdarg.h>
#ifndef ASSERT
#define ASSERT(f) assert(f)
#endif
///////////////////////////////////////////////////////////////////////////////////////
typedef signed char int8;
typedef signed short int16;
typedef signed int int32;
typedef long long int64;
typedef unsigned char uint8;
typedef unsigned short uint16;
typedef unsigned int uint32;
typedef unsigned long long uint64;
typedef unsigned char byte;
typedef unsigned int uint;
typedef unsigned short word;
typedef unsigned int dword;
typedef long long longlong;
typedef unsigned long long handle;
#define TRUE 1
#define FALSE 0
//typedef wchar_t wchar;
//#ifdef _UNICODE
// typedef std::wstring tstring;
// typedef wchar tchar;
//#else
// typedef std::string tstring;
// typedef char tchar;
//#endif
#ifdef _WIN32
#define LLSTRING "%I64d"
#define ULLSTRING "%U64d"
#else
#define LLSTRING "%lld"
#define ULLSTRING "%llu"
#endif
#define makeword(a, b) ((word)(((byte)(((longlong)(a)) & 0xff)) | ((word)((byte)(((longlong)(b)) & 0xff))) << 8))
#define makelong(a, b) ((long)(((word)(((longlong)(a)) & 0xffff)) | ((dword)((word)(((longlong)(b)) & 0xffff))) << 16))
#define loword(l) ((word)(((longlong)(l)) & 0xffff))
#define hiword(l) ((word)((((longlong)(l)) >> 16) & 0xffff))
#define lobyte(w) ((byte)(((longlong)(w)) & 0xff))
#define hibyte(w) ((byte)((((longlong)(w)) >> 8) & 0xff))
//////////////////////////////////////////////////////////////////////////
// 功能函数
inline std::string toString(unsigned int value)
{
static char szTemp[256];
sprintf(&szTemp[0], "%u", value);
return szTemp;
}
inline std::string toString(int value)
{
static char szTemp[256];
sprintf(&szTemp[0], "%d", value);
return szTemp;
}
inline std::string toString(float value)
{
static char szTemp[256];
sprintf(&szTemp[0], "%.1f", value);
return szTemp;
}
inline std::string toString(int64 value)
{
static char szTemp[256];
sprintf(&szTemp[0], LLSTRING, value);
return szTemp;
}
static std::string stringFormatC(const char* format, ...)
{
static char szTemp[1024];
va_list vlist;
va_start(vlist, format);
vsprintf(&szTemp[0], format, vlist);
va_end(vlist);
return szTemp;
} //
#define stringFormat(format, ...) stringFormatC(format.c_str(), ##__VA_ARGS__)
template<typename T>
inline T tmin(const T& a, const T& b)
{
return a < b ? a : b;
}
template<typename T>
inline T tmax(const T& a, const T& b)
{
return a < b ? b : a;
}
//
//inline const std::wstring& toStringW(int value)
//{
// static std::wstring str;
// str.resize(128, L'\0');
// _snwprintf(&str[0], 128, L"%d", value);
// return str;
//}
//
//static std::string w2s(const std::wstring& ws)
//{
// std::string curLocale = setlocale(LC_ALL, 0); // curLocale = "C";
// setlocale(LC_ALL, "chs");
// size_t len = ws.size() * 2 + 1;
// std::string result;
// result.resize(len, '\0');
//
// wcstombs_s(&len, &result[0], len, ws.c_str(), len);
// setlocale(LC_ALL, curLocale.c_str());
// return result;
//}
//
//static std::wstring s2w(const std::string& s)
//{
// std::string curLocale = setlocale(LC_ALL, "chs");
// size_t len = s.size() + 1;
// std::wstring result;
// result.resize(len, L'\0');
// mbstowcs_s(&len, &result[0], len, s.c_str(),len);
// setlocale(LC_ALL, curLocale.c_str());
// return result;
//}
//////////////////////////////////////////////////////////////////////////
// 宏定义
#define countarray(ary) (sizeof(ary)/sizeof(ary[0]))
#define zeromemory(x, size) memset(x, 0, size)
//
//#ifdef _UNICODE
// #define t2s(text) w2s(text)
// #define t2w(text) tstring(text)
// #define s2t(text) s2w(text)
// #define w2t(text) tstring(text)
// #define T_T(str) L##str
// #define toString toStringW
//
// #define tstrcpyn(dst, src, len) wcscpy_s(dst, len, src)
// #define tstrcpy(dst, src) wcscpy(dst, src)
// #define tstrlen(str) wcslen(str)
// #define tstrcmp(str1, str2) wcscmp(str1, str2)
//
//#else
// #define t2s(text) tstring(text)
// #define t2w(text) s2w(text)
// #define s2t(text) tstring(text)
// #define w2t(text) s2w(text)
// #define T_T(str) str
// #define toString toStringA
//
// #define tstrcpyn(dst, src, len) strcpy_s(dst, len, src)
// #define tstrcpy(dst, src) strcpy(dst, src)
// #define tstrlen(str) strlen(str)
// #define tstrcmp(str1, str2) strcmp(str1, str2)
//#endif
///////////////////////////////////////////////////////////////////////////////////////
#endif // _types_H_
|
4ce54fd6ffeabf6c57a717b9175acc8249d22619
|
6eed490d4a785fe1fd7470b7095f44fea5bc5f7b
|
/CMatrix.cpp
|
f2c2ed1e3b051df653e15b04b66959a161531f60
|
[] |
no_license
|
CaseySmalley/CMD-3D-Graphics
|
ef344e2745cc240a56936ccd39770b3cb49e73a2
|
58b80242e8bbeb6fa876643eb440493c27bd3f85
|
refs/heads/master
| 2020-07-02T22:08:50.754832
| 2016-11-30T20:12:00
| 2016-11-30T20:12:00
| 74,280,243
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 21,006
|
cpp
|
CMatrix.cpp
|
#include <iostream>
#include "CMatrix.h"
// This class was made to perform the 4x4 Matrix calculations nessecary for 3D rendering
// Matrix Layout
// X Y Z 0 <- Local X Axis
// X Y Z 0 <- Local Y Axis
// X Y Z 0 <- Local Z Axis
// X Y Z 1 <- World Position
CMatrix::CMatrix() {
this->identity();
}
//
void CMatrix::zero() {
this->m_data[0] = 0.0f;
this->m_data[1] = 0.0f;
this->m_data[2] = 0.0f;
this->m_data[3] = 0.0f;
this->m_data[4] = 0.0f;
this->m_data[5] = 0.0f;
this->m_data[6] = 0.0f;
this->m_data[7] = 0.0f;
this->m_data[8] = 0.0f;
this->m_data[9] = 0.0f;
this->m_data[10] = 0.0f;
this->m_data[11] = 0.0f;
this->m_data[12] = 0.0f;
this->m_data[13] = 0.0f;
this->m_data[14] = 0.0f;
this->m_data[15] = 0.0f;
}
void CMatrix::identity() {
this->m_data[0] = 1.0f;
this->m_data[1] = 0.0f;
this->m_data[2] = 0.0f;
this->m_data[3] = 0.0f;
this->m_data[4] = 0.0f;
this->m_data[5] = 1.0f;
this->m_data[6] = 0.0f;
this->m_data[7] = 0.0f;
this->m_data[8] = 0.0f;
this->m_data[9] = 0.0f;
this->m_data[10] = 1.0f;
this->m_data[11] = 0.0f;
this->m_data[12] = 0.0f;
this->m_data[13] = 0.0f;
this->m_data[14] = 0.0f;
this->m_data[15] = 1.0f;
}
void CMatrix::inverse() {
float tmpData [16];
float det = 0.0f;
tmpData[0] = this->m_data[5] * this->m_data[10] * this->m_data[15] -
this->m_data[5] * this->m_data[11] * this->m_data[14] -
this->m_data[9] * this->m_data[6] * this->m_data[15] +
this->m_data[9] * this->m_data[7] * this->m_data[14] +
this->m_data[13] * this->m_data[6] * this->m_data[11] -
this->m_data[13] * this->m_data[7] * this->m_data[10];
tmpData[4] = -this->m_data[4] * this->m_data[10] * this->m_data[15] +
this->m_data[4] * this->m_data[11] * this->m_data[14] +
this->m_data[8] * this->m_data[6] * this->m_data[15] -
this->m_data[8] * this->m_data[7] * this->m_data[14] -
this->m_data[12] * this->m_data[6] * this->m_data[11] +
this->m_data[12] * this->m_data[7] * this->m_data[10];
tmpData[8] = this->m_data[4] * this->m_data[9] * this->m_data[15] -
this->m_data[4] * this->m_data[11] * this->m_data[13] -
this->m_data[8] * this->m_data[5] * this->m_data[15] +
this->m_data[8] * this->m_data[7] * this->m_data[13] +
this->m_data[12] * this->m_data[5] * this->m_data[11] -
this->m_data[12] * this->m_data[7] * this->m_data[9];
tmpData[12] = -this->m_data[4] * this->m_data[9] * this->m_data[14] +
this->m_data[4] * this->m_data[10] * this->m_data[13] +
this->m_data[8] * this->m_data[5] * this->m_data[14] -
this->m_data[8] * this->m_data[6] * this->m_data[13] -
this->m_data[12] * this->m_data[5] * this->m_data[10] +
this->m_data[12] * this->m_data[6] * this->m_data[9];
tmpData[1] = -this->m_data[1] * this->m_data[10] * this->m_data[15] +
this->m_data[1] * this->m_data[11] * this->m_data[14] +
this->m_data[9] * this->m_data[2] * this->m_data[15] -
this->m_data[9] * this->m_data[3] * this->m_data[14] -
this->m_data[13] * this->m_data[2] * this->m_data[11] +
this->m_data[13] * this->m_data[3] * this->m_data[10];
tmpData[5] = this->m_data[0] * this->m_data[10] * this->m_data[15] -
this->m_data[0] * this->m_data[11] * this->m_data[14] -
this->m_data[8] * this->m_data[2] * this->m_data[15] +
this->m_data[8] * this->m_data[3] * this->m_data[14] +
this->m_data[12] * this->m_data[2] * this->m_data[11] -
this->m_data[12] * this->m_data[3] * this->m_data[10];
tmpData[9] = -this->m_data[0] * this->m_data[9] * this->m_data[15] +
this->m_data[0] * this->m_data[11] * this->m_data[13] +
this->m_data[8] * this->m_data[1] * this->m_data[15] -
this->m_data[8] * this->m_data[3] * this->m_data[13] -
this->m_data[12] * this->m_data[1] * this->m_data[11] +
this->m_data[12] * this->m_data[3] * this->m_data[9];
tmpData[13] = this->m_data[0] * this->m_data[9] * this->m_data[14] -
this->m_data[0] * this->m_data[10] * this->m_data[13] -
this->m_data[8] * this->m_data[1] * this->m_data[14] +
this->m_data[8] * this->m_data[2] * this->m_data[13] +
this->m_data[12] * this->m_data[1] * this->m_data[10] -
this->m_data[12] * this->m_data[2] * this->m_data[9];
tmpData[2] = this->m_data[1] * this->m_data[6] * this->m_data[15] -
this->m_data[1] * this->m_data[7] * this->m_data[14] -
this->m_data[5] * this->m_data[2] * this->m_data[15] +
this->m_data[5] * this->m_data[3] * this->m_data[14] +
this->m_data[13] * this->m_data[2] * this->m_data[7] -
this->m_data[13] * this->m_data[3] * this->m_data[6];
tmpData[6] = -this->m_data[0] * this->m_data[6] * this->m_data[15] +
this->m_data[0] * this->m_data[7] * this->m_data[14] +
this->m_data[4] * this->m_data[2] * this->m_data[15] -
this->m_data[4] * this->m_data[3] * this->m_data[14] -
this->m_data[12] * this->m_data[2] * this->m_data[7] +
this->m_data[12] * this->m_data[3] * this->m_data[6];
tmpData[10] = this->m_data[0] * this->m_data[5] * this->m_data[15] -
this->m_data[0] * this->m_data[7] * this->m_data[13] -
this->m_data[4] * this->m_data[1] * this->m_data[15] +
this->m_data[4] * this->m_data[3] * this->m_data[13] +
this->m_data[12] * this->m_data[1] * this->m_data[7] -
this->m_data[12] * this->m_data[3] * this->m_data[5];
tmpData[14] = -this->m_data[0] * this->m_data[5] * this->m_data[14] +
this->m_data[0] * this->m_data[6] * this->m_data[13] +
this->m_data[4] * this->m_data[1] * this->m_data[14] -
this->m_data[4] * this->m_data[2] * this->m_data[13] -
this->m_data[12] * this->m_data[1] * this->m_data[6] +
this->m_data[12] * this->m_data[2] * this->m_data[5];
tmpData[3] = -this->m_data[1] * this->m_data[6] * this->m_data[11] +
this->m_data[1] * this->m_data[7] * this->m_data[10] +
this->m_data[5] * this->m_data[2] * this->m_data[11] -
this->m_data[5] * this->m_data[3] * this->m_data[10] -
this->m_data[9] * this->m_data[2] * this->m_data[7] +
this->m_data[9] * this->m_data[3] * this->m_data[6];
tmpData[7] = this->m_data[0] * this->m_data[6] * this->m_data[11] -
this->m_data[0] * this->m_data[7] * this->m_data[10] -
this->m_data[4] * this->m_data[2] * this->m_data[11] +
this->m_data[4] * this->m_data[3] * this->m_data[10] +
this->m_data[8] * this->m_data[2] * this->m_data[7] -
this->m_data[8] * this->m_data[3] * this->m_data[6];
tmpData[11] = -this->m_data[0] * this->m_data[5] * this->m_data[11] +
this->m_data[0] * this->m_data[7] * this->m_data[9] +
this->m_data[4] * this->m_data[1] * this->m_data[11] -
this->m_data[4] * this->m_data[3] * this->m_data[9] -
this->m_data[8] * this->m_data[1] * this->m_data[7] +
this->m_data[8] * this->m_data[3] * this->m_data[5];
tmpData[15] = this->m_data[0] * this->m_data[5] * this->m_data[10] -
this->m_data[0] * this->m_data[6] * this->m_data[9] -
this->m_data[4] * this->m_data[1] * this->m_data[10] +
this->m_data[4] * this->m_data[2] * this->m_data[9] +
this->m_data[8] * this->m_data[1] * this->m_data[6] -
this->m_data[8] * this->m_data[2] * this->m_data[5];
det = this->m_data[0] * tmpData[0] + this->m_data[1] * tmpData[4] + this->m_data[2] * tmpData[8] + this->m_data[3] * tmpData[12];
if (det == 0.0f) return;
det = 1.0f / det;
this->m_data[0] = tmpData[0] * det;
this->m_data[1] = tmpData[1] * det;
this->m_data[2] = tmpData[2] * det;
this->m_data[3] = tmpData[3] * det;
this->m_data[4] = tmpData[4] * det;
this->m_data[5] = tmpData[5] * det;
this->m_data[6] = tmpData[6] * det;
this->m_data[7] = tmpData[7] * det;
this->m_data[8] = tmpData[8] * det;
this->m_data[9] = tmpData[9] * det;
this->m_data[10] = tmpData[10] * det;
this->m_data[11] = tmpData[11] * det;
this->m_data[12] = tmpData[12] * det;
this->m_data[13] = tmpData[13] * det;
this->m_data[14] = tmpData[14] * det;
this->m_data[15] = tmpData[15] * det;
}
void CMatrix::rotateX(float angle) {
CMatrix tmp;
tmp.m_data[5] = cos(angle);
tmp.m_data[6] = -sin(angle);
tmp.m_data[9] = sin(angle);
tmp.m_data[10] = cos(angle);
(*this) *= tmp;
}
void CMatrix::rotateY(float angle) {
CMatrix tmp;
tmp.m_data[0] = cos(angle);
tmp.m_data[2] = sin(angle);
tmp.m_data[8] = -sin(angle);
tmp.m_data[10] = cos(angle);
(*this) *= tmp;
}
void CMatrix::rotateZ(float angle) {
CMatrix tmp;
tmp.m_data[0] = cos(angle);
tmp.m_data[1] = -sin(angle);
tmp.m_data[4] = sin(angle);
tmp.m_data[5] = cos(angle);
(*this) *= tmp;
}
void CMatrix::translate(float x,float y,float z) {
this->m_data[12] += x;
this->m_data[13] += y;
this->m_data[14] += z;
}
void CMatrix::translate(CVector &v) {
(*this) += v;
}
void CMatrix::rotate(CVector &v) {
this->rotateX(v.getX());
this->rotateY(v.getY());
this->rotateZ(v.getZ());
}
void CMatrix::copy(CMatrix &m) {
float* data = m.getData();
this->m_data[0] = data[0];
this->m_data[1] = data[1];
this->m_data[2] = data[2];
this->m_data[3] = data[3];
this->m_data[4] = data[4];
this->m_data[5] = data[5];
this->m_data[6] = data[6];
this->m_data[7] = data[7];
this->m_data[8] = data[8];
this->m_data[9] = data[9];
this->m_data[10] = data[10];
this->m_data[11] = data[11];
this->m_data[12] = data[12];
this->m_data[13] = data[13];
this->m_data[14] = data[14];
this->m_data[15] = data[15];
}
void CMatrix::toConsole() {
std::cout << this->m_data[0] << "," << this->m_data[1] << "," << this->m_data[2] << "," << this->m_data[3] << std::endl
<< this->m_data[4] << "," << this->m_data[5] << "," << this->m_data[6] << "," << this->m_data[7] << std::endl
<< this->m_data[8] << "," << this->m_data[9] << "," << this->m_data[10] << "," << this->m_data[11] << std::endl
<< this->m_data[12] << "," << this->m_data[13] << "," << this->m_data[14] << "," << this->m_data[15] << std::endl;
}
float* CMatrix::getData() {
return this->m_data;
}
// Mathmatic Operators Matrix - Matrix
CMatrix CMatrix::operator+(CMatrix &m) {
CMatrix tmp;
float* data = m.getData();
tmp.m_data[0] = this->m_data[0] + data[0];
tmp.m_data[1] = this->m_data[1] + data[1];
tmp.m_data[2] = this->m_data[2] + data[2];
tmp.m_data[3] = this->m_data[3] + data[3];
tmp.m_data[4] = this->m_data[4] + data[4];
tmp.m_data[5] = this->m_data[5] + data[5];
tmp.m_data[6] = this->m_data[6] + data[6];
tmp.m_data[7] = this->m_data[7] + data[7];
tmp.m_data[8] = this->m_data[8] + data[8];
tmp.m_data[9] = this->m_data[9] + data[9];
tmp.m_data[10] = this->m_data[10] + data[10];
tmp.m_data[11] = this->m_data[11] + data[11];
tmp.m_data[12] = this->m_data[12] + data[12];
tmp.m_data[13] = this->m_data[13] + data[13];
tmp.m_data[14] = this->m_data[14] + data[14];
tmp.m_data[15] = this->m_data[15] + data[15];
return tmp;
}
CMatrix CMatrix::operator+=(CMatrix &m) {
float* data = m.getData();
this->m_data[0] = this->m_data[0] + data[0];
this->m_data[1] = this->m_data[1] + data[1];
this->m_data[2] = this->m_data[2] + data[2];
this->m_data[3] = this->m_data[3] + data[3];
this->m_data[4] = this->m_data[4] + data[4];
this->m_data[5] = this->m_data[5] + data[5];
this->m_data[6] = this->m_data[6] + data[6];
this->m_data[7] = this->m_data[7] + data[7];
this->m_data[8] = this->m_data[8] + data[8];
this->m_data[9] = this->m_data[9] + data[9];
this->m_data[10] = this->m_data[10] + data[10];
this->m_data[11] = this->m_data[11] + data[11];
this->m_data[12] = this->m_data[12] + data[12];
this->m_data[13] = this->m_data[13] + data[13];
this->m_data[14] = this->m_data[14] + data[14];
this->m_data[15] = this->m_data[15] + data[15];
return (*this);
}
CMatrix CMatrix::operator-(CMatrix &m) {
CMatrix tmp;
float* data = m.getData();
tmp.m_data[0] = this->m_data[0] - data[0];
tmp.m_data[1] = this->m_data[1] - data[1];
tmp.m_data[2] = this->m_data[2] - data[2];
tmp.m_data[3] = this->m_data[3] - data[3];
tmp.m_data[4] = this->m_data[4] - data[4];
tmp.m_data[5] = this->m_data[5] - data[5];
tmp.m_data[6] = this->m_data[6] - data[6];
tmp.m_data[7] = this->m_data[7] - data[7];
tmp.m_data[8] = this->m_data[8] - data[8];
tmp.m_data[9] = this->m_data[9] - data[9];
tmp.m_data[10] = this->m_data[10] - data[10];
tmp.m_data[11] = this->m_data[11] - data[11];
tmp.m_data[12] = this->m_data[12] - data[12];
tmp.m_data[13] = this->m_data[13] - data[13];
tmp.m_data[14] = this->m_data[14] - data[14];
tmp.m_data[15] = this->m_data[15] - data[15];
return tmp;
}
CMatrix CMatrix::operator-=(CMatrix &m) {
float* data = m.getData();
this->m_data[0] = this->m_data[0] - data[0];
this->m_data[1] = this->m_data[1] - data[1];
this->m_data[2] = this->m_data[2] - data[2];
this->m_data[3] = this->m_data[3] - data[3];
this->m_data[4] = this->m_data[4] - data[4];
this->m_data[5] = this->m_data[5] - data[5];
this->m_data[6] = this->m_data[6] - data[6];
this->m_data[7] = this->m_data[7] - data[7];
this->m_data[8] = this->m_data[8] - data[8];
this->m_data[9] = this->m_data[9] - data[9];
this->m_data[10] = this->m_data[10] - data[10];
this->m_data[11] = this->m_data[11] - data[11];
this->m_data[12] = this->m_data[12] - data[12];
this->m_data[13] = this->m_data[13] - data[13];
this->m_data[14] = this->m_data[14] - data[14];
this->m_data[15] = this->m_data[15] - data[15];
return (*this);
}
CMatrix CMatrix::operator*(CMatrix &m) {
CMatrix tmp;
float* tmpData = tmp.getData();
float* data = m.getData();
tmpData[0] = this->m_data[0]*data[0] + this->m_data[1]*data[4] + this->m_data[2]*data[8] + this->m_data[3]*data[12];
tmpData[1] = this->m_data[0]*data[1] + this->m_data[1]*data[5] + this->m_data[2]*data[9] + this->m_data[3]*data[13];
tmpData[2] = this->m_data[0]*data[2] + this->m_data[1]*data[6] + this->m_data[2]*data[10] + this->m_data[3]*data[14];
tmpData[3] = this->m_data[0]*data[3] + this->m_data[1]*data[7] + this->m_data[2]*data[11] + this->m_data[3]*data[15];
tmpData[4] = this->m_data[4]*data[0] + this->m_data[5]*data[4] + this->m_data[6]*data[8] + this->m_data[7]*data[12];
tmpData[5] = this->m_data[4]*data[1] + this->m_data[5]*data[5] + this->m_data[6]*data[9] + this->m_data[7]*data[13];
tmpData[6] = this->m_data[4]*data[2] + this->m_data[5]*data[6] + this->m_data[6]*data[10] + this->m_data[7]*data[14];
tmpData[7] = this->m_data[4]*data[3] + this->m_data[5]*data[7] + this->m_data[6]*data[11] + this->m_data[7]*data[15];
tmpData[8] = this->m_data[8]*data[0] + this->m_data[9]*data[4] + this->m_data[10]*data[8] + this->m_data[11]*data[12];
tmpData[9] = this->m_data[8]*data[1] + this->m_data[9]*data[5] + this->m_data[10]*data[9] + this->m_data[11]*data[13];
tmpData[10] = this->m_data[8]*data[2] + this->m_data[9]*data[6] + this->m_data[10]*data[10] + this->m_data[11]*data[14];
tmpData[11] = this->m_data[8]*data[3] + this->m_data[9]*data[7] + this->m_data[10]*data[11] + this->m_data[11]*data[15];
tmpData[12] = this->m_data[12]*data[0] + this->m_data[13]*data[4] + this->m_data[14]*data[8] + this->m_data[15]*data[12];
tmpData[13] = this->m_data[12]*data[1] + this->m_data[13]*data[5] + this->m_data[14]*data[9] + this->m_data[15]*data[13];
tmpData[14] = this->m_data[12]*data[2] + this->m_data[13]*data[6] + this->m_data[14]*data[10] + this->m_data[15]*data[14];
tmpData[15] = this->m_data[12]*data[3] + this->m_data[13]*data[7] + this->m_data[14]*data[11] + this->m_data[15]*data[15];
return tmp;
}
CMatrix CMatrix::operator*=(CMatrix &m) {
float tmpData [16];
float* data = m.getData();
tmpData[0] = this->m_data[0]*data[0] + this->m_data[1]*data[4] + this->m_data[2]*data[8] + this->m_data[3]*data[12];
tmpData[1] = this->m_data[0]*data[1] + this->m_data[1]*data[5] + this->m_data[2]*data[9] + this->m_data[3]*data[13];
tmpData[2] = this->m_data[0]*data[2] + this->m_data[1]*data[6] + this->m_data[2]*data[10] + this->m_data[3]*data[14];
tmpData[3] = this->m_data[0]*data[3] + this->m_data[1]*data[7] + this->m_data[2]*data[11] + this->m_data[3]*data[15];
tmpData[4] = this->m_data[4]*data[0] + this->m_data[5]*data[4] + this->m_data[6]*data[8] + this->m_data[7]*data[12];
tmpData[5] = this->m_data[4]*data[1] + this->m_data[5]*data[5] + this->m_data[6]*data[9] + this->m_data[7]*data[13];
tmpData[6] = this->m_data[4]*data[2] + this->m_data[5]*data[6] + this->m_data[6]*data[10] + this->m_data[7]*data[14];
tmpData[7] = this->m_data[4]*data[3] + this->m_data[5]*data[7] + this->m_data[6]*data[11] + this->m_data[7]*data[15];
tmpData[8] = this->m_data[8]*data[0] + this->m_data[9]*data[4] + this->m_data[10]*data[8] + this->m_data[11]*data[12];
tmpData[9] = this->m_data[8]*data[1] + this->m_data[9]*data[5] + this->m_data[10]*data[9] + this->m_data[11]*data[13];
tmpData[10] = this->m_data[8]*data[2] + this->m_data[9]*data[6] + this->m_data[10]*data[10] + this->m_data[11]*data[14];
tmpData[11] = this->m_data[8]*data[3] + this->m_data[9]*data[7] + this->m_data[10]*data[11] + this->m_data[11]*data[15];
tmpData[12] = this->m_data[12]*data[0] + this->m_data[13]*data[4] + this->m_data[14]*data[8] + this->m_data[15]*data[12];
tmpData[13] = this->m_data[12]*data[1] + this->m_data[13]*data[5] + this->m_data[14]*data[9] + this->m_data[15]*data[13];
tmpData[14] = this->m_data[12]*data[2] + this->m_data[13]*data[6] + this->m_data[14]*data[10] + this->m_data[15]*data[14];
tmpData[15] = this->m_data[12]*data[3] + this->m_data[13]*data[7] + this->m_data[14]*data[11] + this->m_data[15]*data[15];
this->m_data[0] = tmpData[0];
this->m_data[1] = tmpData[1];
this->m_data[2] = tmpData[2];
this->m_data[3] = tmpData[3];
this->m_data[4] = tmpData[4];
this->m_data[5] = tmpData[5];
this->m_data[6] = tmpData[6];
this->m_data[7] = tmpData[7];
this->m_data[8] = tmpData[8];
this->m_data[9] = tmpData[9];
this->m_data[10] = tmpData[10];
this->m_data[11] = tmpData[11];
this->m_data[12] = tmpData[12];
this->m_data[13] = tmpData[13];
this->m_data[14] = tmpData[14];
this->m_data[15] = tmpData[15];
return (*this);
}
CMatrix CMatrix::operator/(CMatrix &m) {
CMatrix tmp;
CMatrix res;
tmp.copy(m);
tmp.inverse();
res = (*this) * tmp;
return res;
}
CMatrix CMatrix::operator/=(CMatrix &m) {
CMatrix tmp;
tmp.copy(m);
tmp.inverse();
(*this) *= tmp;
return (*this);
}
// Matrix - Vector Operators
CMatrix CMatrix::operator+(CVector &v) {
CMatrix tmp;
tmp.copy(*this);
float* data = tmp.getData();
data[12] += v.getX();
data[13] += v.getY();
data[14] += v.getZ();
return tmp;
}
CMatrix CMatrix::operator+=(CVector &v) {
this->m_data[12] += v.getX();
this->m_data[13] += v.getY();
this->m_data[14] += v.getZ();
return (*this);
}
CMatrix CMatrix::operator-(CVector &v) {
CMatrix tmp;
tmp.copy(*this);
float* data = tmp.getData();
data[12] -= v.getX();
data[13] -= v.getY();
data[14] -= v.getZ();
return tmp;
}
CMatrix CMatrix::operator-=(CVector &v) {
this->m_data[12] -= v.getX();
this->m_data[13] -= v.getY();
this->m_data[14] -= v.getZ();
return (*this);
}
CMatrix CMatrix::operator*(CVector &v) {
CMatrix tmp;
tmp.copy(*this);
float* data = tmp.getData();
data[12] *= v.getX();
data[13] *= v.getY();
data[14] *= v.getZ();
return tmp;
}
CMatrix CMatrix::operator*=(CVector &v) {
this->m_data[12] *= v.getX();
this->m_data[13] *= v.getY();
this->m_data[14] *= v.getZ();
return (*this);
}
CMatrix CMatrix::operator/(CVector &v) {
CMatrix tmp;
tmp.copy(*this);
float* data = tmp.getData();
data[12] /= v.getX();
data[13] /= v.getY();
data[14] /= v.getZ();
return tmp;
}
CMatrix CMatrix::operator/=(CVector &v) {
this->m_data[12] /= v.getX();
this->m_data[13] /= v.getY();
this->m_data[14] /= v.getZ();
return (*this);
}
|
4f9dd43cd5ac7dc8b7ca053e9eaf14ae88db874e
|
d6a44781f557c1ce33db7caecec14ec37675211e
|
/giskard_suturo_parser/test/giskard_suturo_parser/gpp.cpp
|
f3acd26e4dd91cf5e21b86a1c75413d91870ca3d
|
[] |
no_license
|
suturo16/manipulation
|
1884a916358f377315072860e9800817a9b3b0c6
|
5c5e7e7902b610e880934ab6945551c6fd490962
|
refs/heads/master
| 2021-01-12T17:42:52.114579
| 2017-09-29T02:54:22
| 2017-09-29T02:54:22
| 71,626,532
| 0
| 2
| null | 2017-09-29T02:04:19
| 2016-10-22T08:24:25
|
C++
|
UTF-8
|
C++
| false
| false
| 19,664
|
cpp
|
gpp.cpp
|
/*
* Copyright (C) 2015 Georg Bartels <georg.bartels@cs.uni-bremen.de>
*
* This file is part of giskard.
*
* giskard is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <gtest/gtest.h>
#include <giskard_suturo_parser/parser.h>
#include <giskard_suturo_parser/utils.h>
#include <giskard_core/giskard_core.hpp>
using namespace giskard_suturo;
using namespace giskard_core;
class GiskardPPTest : public ::testing::Test
{
protected:
virtual void SetUp() {
parser.reset();
}
virtual void TearDown(){}
GiskardPPParser parser;
};
TEST_F(GiskardPPTest, matchTest) {
SpecPtr scalar = instance<DoubleConstSpec>(1.0);
SpecPtr vector = instance<VectorConstructorSpec>();
SpecPtr rotation = instance<RotationQuaternionConstructorSpec>(0.0,0.0,0.0,1.0);
SpecPtr frame = instance<FrameConstructorSpec>(instance<VectorConstructorSpec>(), instance<RotationQuaternionConstructorSpec>(0.0,0.0,0.0,1.0));
SpecPtr str = instance<ConstStringSpec>("lol");
DoubleSpecPtr d;
VectorSpecPtr v;
RotationSpecPtr r;
FrameSpecPtr f;
StringSpecPtr s;
EXPECT_TRUE(matches(scalar, d));
EXPECT_FALSE(matches(scalar, v));
EXPECT_FALSE(matches(scalar, r));
EXPECT_FALSE(matches(scalar, f));
EXPECT_FALSE(matches(scalar, s));
EXPECT_FALSE(matches(vector, d));
EXPECT_TRUE(matches(vector, v));
EXPECT_FALSE(matches(vector, r));
EXPECT_FALSE(matches(vector, f));
EXPECT_FALSE(matches(vector, s));
EXPECT_FALSE(matches(rotation, d));
EXPECT_FALSE(matches(rotation, v));
EXPECT_TRUE(matches(rotation, r));
EXPECT_FALSE(matches(rotation, f));
EXPECT_FALSE(matches(rotation, s));
EXPECT_FALSE(matches(frame, d));
EXPECT_FALSE(matches(frame, v));
EXPECT_FALSE(matches(frame, r));
EXPECT_TRUE(matches(frame, f));
EXPECT_FALSE(matches(frame, s));
EXPECT_FALSE(matches(str, d));
EXPECT_FALSE(matches(str, v));
EXPECT_FALSE(matches(str, r));
EXPECT_FALSE(matches(str, f));
EXPECT_TRUE(matches(str, s));
}
TEST_F(GiskardPPTest, typeEqualityTest) {
DoubleSpecPtr scalar1 = instance<DoubleConstSpec>(1.0);
DoubleSpecPtr scalar2 = instance<DoubleConstSpec>(7.0);
VectorSpecPtr vector1 = instance<VectorConstructorSpec>();
VectorSpecPtr vector2 = instance<VectorConstructorSpec>();
RotationSpecPtr rotation1 = instance<RotationQuaternionConstructorSpec>(0.0,0.0,0.0,1.0);
RotationSpecPtr rotation2 = instance<RotationQuaternionConstructorSpec>(1.0,0.0,0.0,0.0);
FrameSpecPtr frame1 = instance<FrameConstructorSpec>(instance<VectorConstructorSpec>(), instance<RotationQuaternionConstructorSpec>(0.0,0.0,0.0,1.0));
FrameSpecPtr frame2 = instance<FrameConstructorSpec>(instance<VectorConstructorSpec>(), instance<RotationQuaternionConstructorSpec>(0.0,0.0,1.0,0.0));
StringSpecPtr str1 = instance<ConstStringSpec>("lol");
StringSpecPtr str2 = instance<ConstStringSpec>("bla");
HardConstraintSpecPtr hardC1 = instance<HardConstraintSpec>(scalar1, scalar1, scalar1);
HardConstraintSpecPtr hardC2 = instance<HardConstraintSpec>(scalar2, scalar2, scalar2);
ControllableConstraintSpecPtr controllableC1 = instance<ControllableConstraintSpec>(scalar1, scalar1, scalar1, str1);
ControllableConstraintSpecPtr controllableC2 = instance<ControllableConstraintSpec>(scalar2, scalar2, scalar2, str2);
SoftConstraintSpecPtr softC1 = instance<SoftConstraintSpec>(scalar1, scalar1, scalar1, scalar1, str1);
SoftConstraintSpecPtr softC2 = instance<SoftConstraintSpec>(scalar2, scalar2, scalar2, scalar2, str2);
std::vector<SpecPtr> ld1 {scalar1};
std::vector<SpecPtr> ld2 {scalar2};
std::vector<SpecPtr> ld3 {vector2};
SpecPtr list1 = instance<ConstListSpec>(ld1);
SpecPtr list2 = instance<ConstListSpec>(ld2);
SpecPtr list3 = instance<ConstListSpec>(ld3);
std::vector<SpecPtr> ld4 {list1};
std::vector<SpecPtr> ld5 {list2};
std::vector<SpecPtr> ld6 {list3};
SpecPtr list4 = instance<ConstListSpec>(ld4);
SpecPtr list5 = instance<ConstListSpec>(ld5);
SpecPtr list6 = instance<ConstListSpec>(ld6);
EXPECT_TRUE(typesAreEqual(scalar1, scalar2));
EXPECT_FALSE(typesAreEqual(scalar1, vector1));
EXPECT_FALSE(typesAreEqual(scalar1, rotation1));
EXPECT_FALSE(typesAreEqual(scalar1, frame1));
EXPECT_FALSE(typesAreEqual(scalar1, str1));
EXPECT_FALSE(typesAreEqual(scalar1, hardC1));
EXPECT_FALSE(typesAreEqual(scalar1, controllableC1));
EXPECT_FALSE(typesAreEqual(scalar1, softC1));
EXPECT_FALSE(typesAreEqual(scalar1, list1));
EXPECT_TRUE(typesAreEqual(vector1, vector2));
EXPECT_FALSE(typesAreEqual(vector1, rotation1));
EXPECT_FALSE(typesAreEqual(vector1, frame1));
EXPECT_FALSE(typesAreEqual(vector1, str1));
EXPECT_FALSE(typesAreEqual(vector1, hardC1));
EXPECT_FALSE(typesAreEqual(vector1, controllableC1));
EXPECT_FALSE(typesAreEqual(vector1, softC1));
EXPECT_FALSE(typesAreEqual(vector1, list1));
EXPECT_TRUE(typesAreEqual(rotation1, rotation2));
EXPECT_FALSE(typesAreEqual(rotation1, frame1));
EXPECT_FALSE(typesAreEqual(rotation1, str1));
EXPECT_FALSE(typesAreEqual(rotation1, hardC1));
EXPECT_FALSE(typesAreEqual(rotation1, controllableC1));
EXPECT_FALSE(typesAreEqual(rotation1, softC1));
EXPECT_FALSE(typesAreEqual(rotation1, list1));
EXPECT_TRUE(typesAreEqual(frame1, frame2));
EXPECT_FALSE(typesAreEqual(frame1, str1));
EXPECT_FALSE(typesAreEqual(frame1, hardC1));
EXPECT_FALSE(typesAreEqual(frame1, controllableC1));
EXPECT_FALSE(typesAreEqual(frame1, softC1));
EXPECT_FALSE(typesAreEqual(frame1, list1));
EXPECT_TRUE(typesAreEqual(str1, str2));
EXPECT_FALSE(typesAreEqual(str1, hardC1));
EXPECT_FALSE(typesAreEqual(str1, controllableC1));
EXPECT_FALSE(typesAreEqual(str1, softC1));
EXPECT_FALSE(typesAreEqual(str1, list1));
EXPECT_TRUE(typesAreEqual(hardC1, hardC2));
EXPECT_FALSE(typesAreEqual(hardC1, controllableC1));
EXPECT_FALSE(typesAreEqual(hardC1, softC1));
EXPECT_FALSE(typesAreEqual(hardC1, list1));
EXPECT_TRUE(typesAreEqual(controllableC1, controllableC2));
EXPECT_FALSE(typesAreEqual(controllableC1, softC1));
EXPECT_FALSE(typesAreEqual(controllableC1, list1));
EXPECT_TRUE(typesAreEqual(softC1, softC2));
EXPECT_FALSE(typesAreEqual(softC1, list1));
EXPECT_TRUE(typesAreEqual(list1, list2));
EXPECT_FALSE(typesAreEqual(list1, list3));
EXPECT_TRUE(typesAreEqual(list1, list2));
EXPECT_FALSE(typesAreEqual(list1, list3));
EXPECT_FALSE(typesAreEqual(list1, list4));
EXPECT_TRUE(typesAreEqual(list4, list5));
EXPECT_FALSE(typesAreEqual(list4, list6));
}
TEST_F(GiskardPPTest, parseType) {
DoubleSpecPtr d;
VectorSpecPtr v;
RotationSpecPtr r;
FrameSpecPtr f;
SpecPtr tempD = parser.parseType(GiskardPPParser::sScalar);
SpecPtr tempV = parser.parseType(GiskardPPParser::sVec3);
SpecPtr tempR = parser.parseType(GiskardPPParser::sRotation);
SpecPtr tempF = parser.parseType(GiskardPPParser::sFrame);
EXPECT_TRUE(matches(tempD, d));
EXPECT_TRUE(matches(tempV, v));
EXPECT_TRUE(matches(tempR, r));
EXPECT_TRUE(matches(tempF, f));
}
TEST_F(GiskardPPTest, parseDeclaration) {
EXPECT_ANY_THROW(parser.parseDeclaration("bla "));
EXPECT_ANY_THROW(parser.parseDeclaration("frame"));
EXPECT_ANY_THROW(parser.parseDeclaration("bla foo"));
DeclPtr decl;
ASSERT_NO_THROW(decl = parser.parseDeclaration("scalar foo"));
DoubleSpecPtr d;
EXPECT_TRUE(matches(decl->type, d));
EXPECT_EQ("foo", decl->name);
}
TEST_F(GiskardPPTest, parseLiteral) {
SpecPtr expr;
ASSERT_NO_THROW( expr = parser.parseLiteral("10"));
DoubleConstSpecPtr d;
ASSERT_TRUE(matches(expr, d));
EXPECT_EQ(10.0, d->get_value());
ASSERT_NO_THROW( expr = parser.parseLiteral("vec3(1,2,3)"));
VectorConstructorSpecPtr v;
ASSERT_TRUE(matches(expr, v));
VectorSpecPtr vec = instance<VectorConstructorSpec>(double_const_spec(1.0), double_const_spec(2.0), double_const_spec(3.0));
EXPECT_TRUE(vec->equals(*v));
}
TEST_F(GiskardPPTest, parseFactor) {
try {
parser.parseNamedExpression("someScalar = 5 * 4");
parser.parseNamedExpression("someVector = vec3(1,0,0)");
parser.parseNamedExpression("someRotation = rotation(vec3(0,0,1), 1.57)");
parser.parseNamedExpression("someFrame = frame(rotation(0,0,0,1), vec3(0,0,1))");
} catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
FAIL();
}
SpecPtr expr;
ASSERT_NO_THROW(expr = parser.parseFactor("-someScalar"));
DoubleSubtractionSpecPtr d;
EXPECT_TRUE(matches(expr, d));
ASSERT_NO_THROW(expr = parser.parseFactor("someScalar"));
DoubleReferenceSpecPtr dref;
EXPECT_TRUE(matches(expr, dref));
ASSERT_NO_THROW(expr = parser.parseFactor("-someVector"));
VectorDoubleMultiplicationSpecPtr v;
EXPECT_TRUE(matches(expr, v));
ASSERT_NO_THROW(expr = parser.parseFactor("someVector"));
VectorReferenceSpecPtr vref;
EXPECT_TRUE(matches(expr, vref));
}
TEST_F(GiskardPPTest, parseTerm) {
try {
parser.parseNamedExpression("scal1 = 3");
parser.parseNamedExpression("scal2 = 5");
parser.parseNamedExpression("vec1 = vec3(1,0,0)");
parser.parseNamedExpression("vec2 = vec3(0,0,1)");
parser.parseNamedExpression("rot1 = rotation(vec1, 0.5)");
parser.parseNamedExpression("rot2 = rotation(vec2, 0.5)");
parser.parseNamedExpression("frame1 = frame(rot1, vec2)");
parser.parseNamedExpression("frame2 = frame(rot2, vec2)");
} catch (const std::exception& e) {
std::cout << e.what() << std::endl;
FAIL();
}
EXPECT_ANY_THROW(parser.parseTerm("scal1 * "));
EXPECT_ANY_THROW(parser.parseTerm("* scal1"));
EXPECT_ANY_THROW(parser.parseTerm("scal1 * rot1"));
EXPECT_ANY_THROW(parser.parseTerm("rot1 * scal1"));
EXPECT_ANY_THROW(parser.parseTerm("scal1 * frame1"));
EXPECT_ANY_THROW(parser.parseTerm("frame1 * scal1"));
EXPECT_ANY_THROW(parser.parseTerm("vec1 * rot1"));
EXPECT_ANY_THROW(parser.parseTerm("vec1 * frame1"));
EXPECT_ANY_THROW(parser.parseTerm("scal1 / "));
EXPECT_ANY_THROW(parser.parseTerm("/ scal1"));
EXPECT_ANY_THROW(parser.parseTerm("scal1 / rot1"));
EXPECT_ANY_THROW(parser.parseTerm("rot1 / scal1"));
EXPECT_ANY_THROW(parser.parseTerm("rot1 / rot2"));
EXPECT_ANY_THROW(parser.parseTerm("scal1 / frame1"));
EXPECT_ANY_THROW(parser.parseTerm("frame1 / scal1"));
EXPECT_ANY_THROW(parser.parseTerm("frame1 / frame2"));
EXPECT_ANY_THROW(parser.parseTerm("vec1 / rot1"));
EXPECT_ANY_THROW(parser.parseTerm("vec1 / frame1"));
SpecPtr scalMul;
ASSERT_NO_THROW(scalMul = parser.parseTerm("scal1 * scal2"));
DoubleMultiplicationSpecPtr smul;
EXPECT_TRUE(matches(scalMul, smul));
SpecPtr scalDiv;
ASSERT_NO_THROW(scalDiv = parser.parseTerm("scal1 / scal2"));
DoubleDivisionSpecPtr sdiv;
EXPECT_TRUE(matches(scalDiv, sdiv));
SpecPtr scalVecMul1;
ASSERT_NO_THROW(scalVecMul1 = parser.parseTerm("scal1 * vec1"));
VectorDoubleMultiplicationSpecPtr vsmul;
ASSERT_TRUE(matches(scalVecMul1, vsmul));
SpecPtr scalVecMul2;
ASSERT_NO_THROW(scalVecMul2 = parser.parseTerm("vec1 * scal1"));
ASSERT_TRUE(matches(scalVecMul2, vsmul));
EXPECT_TRUE(scalVecMul1->equals(*scalVecMul2));
SpecPtr vecDot;
ASSERT_NO_THROW(vecDot = parser.parseTerm("vec1 * vec2"));
VectorDotSpecPtr vdot;
EXPECT_TRUE(matches(vecDot, vdot));
SpecPtr vecRot;
ASSERT_NO_THROW(vecRot = parser.parseTerm("rot1 * vec1"));
VectorRotationMultiplicationSpecPtr vrot;
EXPECT_TRUE(matches(vecRot, vrot));
SpecPtr vecFrame;
ASSERT_NO_THROW(vecFrame = parser.parseTerm("frame1 * vec1"));
VectorFrameMultiplicationSpecPtr vframe;
EXPECT_TRUE(matches(vecFrame, vframe));
SpecPtr rotMul;
ASSERT_NO_THROW(rotMul = parser.parseTerm("rot1 * rot2"));
RotationMultiplicationSpecPtr rmul;
EXPECT_TRUE(matches(rotMul, rmul));
SpecPtr frameMul;
ASSERT_NO_THROW(frameMul = parser.parseTerm("frame1 * frame2"));
FrameMultiplicationSpecPtr fmul;
EXPECT_TRUE(matches(frameMul, fmul));
}
TEST_F(GiskardPPTest, parseExpression) {
try {
parser.parseNamedExpression("scal1 = 3");
parser.parseNamedExpression("scal2 = 5");
parser.parseNamedExpression("vec1 = vec3(1,0,0)");
parser.parseNamedExpression("vec2 = vec3(0,0,1)");
parser.parseNamedExpression("rot1 = rotation(vec1, 0.5)");
parser.parseNamedExpression("rot2 = rotation(vec2, 0.5)");
parser.parseNamedExpression("frame1 = frame(rot1, vec2)");
parser.parseNamedExpression("frame2 = frame(rot2, vec2)");
} catch (const std::exception& e) {
std::cout << e.what() << std::endl;
FAIL();
}
EXPECT_ANY_THROW(parser.parseExpression("scal1 + "));
EXPECT_ANY_THROW(parser.parseExpression("+ scal1"));
EXPECT_ANY_THROW(parser.parseExpression("scal1 + vec1"));
EXPECT_ANY_THROW(parser.parseExpression("vec1 + scal1"));
EXPECT_ANY_THROW(parser.parseExpression("scal1 + rot1"));
EXPECT_ANY_THROW(parser.parseExpression("rot1 + scal1"));
EXPECT_ANY_THROW(parser.parseExpression("scal1 + frame1"));
EXPECT_ANY_THROW(parser.parseExpression("frame1 + scal1"));
EXPECT_ANY_THROW(parser.parseExpression("vec1 + rot1"));
EXPECT_ANY_THROW(parser.parseExpression("vec1 + frame1"));
EXPECT_ANY_THROW(parser.parseExpression("scal1 - "));
EXPECT_ANY_THROW(parser.parseExpression("scal1 - vec1"));
EXPECT_ANY_THROW(parser.parseExpression("vec1 - scal1"));
EXPECT_ANY_THROW(parser.parseExpression("scal1 - rot1"));
EXPECT_ANY_THROW(parser.parseExpression("rot1 - scal1"));
EXPECT_ANY_THROW(parser.parseExpression("scal1 - frame1"));
EXPECT_ANY_THROW(parser.parseExpression("frame1 - scal1"));
EXPECT_ANY_THROW(parser.parseExpression("vec1 - rot1"));
EXPECT_ANY_THROW(parser.parseExpression("vec1 - frame1"));
SpecPtr scalAdd;
ASSERT_NO_THROW(scalAdd = parser.parseExpression("scal1 + scal2"));
DoubleAdditionSpecPtr sadd;
EXPECT_TRUE(matches(scalAdd, sadd));
SpecPtr scalSub;
ASSERT_NO_THROW(scalSub = parser.parseExpression("scal1 - scal2"));
DoubleSubtractionSpecPtr ssub;
EXPECT_TRUE(matches(scalSub, ssub));
SpecPtr vecAdd;
ASSERT_NO_THROW(vecAdd = parser.parseExpression("vec1 + vec2"));
VectorAdditionSpecPtr vadd;
EXPECT_TRUE(matches(vecAdd, vadd));
SpecPtr vecSub;
ASSERT_NO_THROW(vecSub = parser.parseExpression("vec1 - vec2"));
VectorSubtractionSpecPtr vsub;
EXPECT_TRUE(matches(vecSub, vsub));
giskard_core::Scope scope;
SpecPtr execOrder1, execOrder2, execOrder3, execOrder4;
ASSERT_NO_THROW(execOrder1 = parser.parseExpression("4 + 2 * 3"));
ASSERT_NO_THROW(execOrder2 = parser.parseExpression("4 * 2 + 3"));
ASSERT_NO_THROW(execOrder3 = parser.parseExpression("(4 + 2) * 3"));
ASSERT_NO_THROW(execOrder4 = parser.parseExpression("4 * (2 + 3)"));
DoubleSpecPtr eo1, eo2, eo3, eo4;
ASSERT_TRUE(matches(execOrder1, eo1));
ASSERT_TRUE(matches(execOrder2, eo2));
ASSERT_TRUE(matches(execOrder3, eo3));
ASSERT_TRUE(matches(execOrder4, eo4));
KDL::Expression<double>::Ptr expr1 = eo1->get_expression(scope);
KDL::Expression<double>::Ptr expr2 = eo2->get_expression(scope);
KDL::Expression<double>::Ptr expr3 = eo3->get_expression(scope);
KDL::Expression<double>::Ptr expr4 = eo4->get_expression(scope);
EXPECT_EQ(10.0, expr1->value());
EXPECT_EQ(11.0, expr2->value());
EXPECT_EQ(18.0, expr3->value());
EXPECT_EQ(20.0, expr4->value());
}
TEST_F(GiskardPPTest, parseNamedExpression) {
EXPECT_ANY_THROW(parser.parseNamedExpression("stuff"));
EXPECT_ANY_THROW(parser.parseNamedExpression("stuff = "));
SpecPtr expr;
ASSERT_NO_THROW(expr = parser.parseExpression("4 * 6 + 9"));
ScopeEntry s;
ASSERT_NO_THROW(s = parser.parseNamedExpression("stuff = 4 * 6 + 9"));
EXPECT_EQ("stuff", s.name);
EXPECT_TRUE(s.spec->equals(*expr));
}
TEST_F(GiskardPPTest, parseImportStatement) {
EXPECT_ANY_THROW(parser.parseImportStatement("bla"));
EXPECT_ANY_THROW(parser.parseImportStatement("import "));
EXPECT_ANY_THROW(parser.parseImportStatement("import \"stuff.gpp\" as"));
EXPECT_ANY_THROW(parser.parseImportStatement("import \"stuff.gpp\" as \"lol\""));
ImportPtr import1;
ASSERT_NO_THROW(import1 = parser.parseImportStatement("import \"stuff.gpp\""));
EXPECT_EQ("stuff.gpp", import1->path);
EXPECT_TRUE(import1->alias.empty());
ImportPtr import2;
ASSERT_NO_THROW(import2 = parser.parseImportStatement("import \"stuff.gpp\" as lol"));
EXPECT_EQ("stuff.gpp", import2->path);
EXPECT_EQ("lol", import2->alias);
}
TEST_F(GiskardPPTest, parseMemberAccess) {
try {
parser.parseNamedExpression("vec1 = vec3(1,0,0)");
parser.parseNamedExpression("rot1 = rotation(vec1, 0.5)");
parser.parseNamedExpression("frame1 = frame(rot1, vec1)");
} catch (const std::exception& e) {
std::cout << e.what() << std::endl;
FAIL();
}
SpecPtr xOf, yOf, zOf, posOf, rotOf;
ASSERT_NO_THROW(xOf = parser.parseMemberAccess("vec1.x"));
ASSERT_NO_THROW(yOf = parser.parseMemberAccess("vec1.y"));
ASSERT_NO_THROW(zOf = parser.parseMemberAccess("vec1.z"));
ASSERT_NO_THROW(posOf = parser.parseMemberAccess("frame1.pos"));
ASSERT_NO_THROW(rotOf = parser.parseMemberAccess("frame1.rot"));
DoubleXCoordOfSpecPtr xptr;
DoubleYCoordOfSpecPtr yptr;
DoubleZCoordOfSpecPtr zptr;
VectorOriginOfSpecPtr pptr;
OrientationOfSpecPtr rptr;
EXPECT_TRUE(matches(xOf, xptr));
EXPECT_TRUE(matches(yOf, yptr));
EXPECT_TRUE(matches(zOf, zptr));
EXPECT_TRUE(matches(posOf, pptr));
EXPECT_TRUE(matches(rotOf, rptr));
}
TEST_F(GiskardPPTest, parseFunctionDefinition) {
EXPECT_ANY_THROW(parser.parseFunctionDefinition("def"));
EXPECT_ANY_THROW(parser.parseFunctionDefinition("def f(scalar x) { return x; }"));
FnDefPtr f1, f2;
EXPECT_NO_THROW(f1 = parser.parseFunctionDefinition("def scalar f(scalar x) { return x; }"));
EXPECT_NO_THROW(f2 = parser.parseFunctionDefinition("def scalar f(scalar x, vec3 v, frame f) { return x; }"));
EXPECT_TRUE(!!f1->getLocalSpec("x"));
EXPECT_TRUE(!!f2->getLocalSpec("x"));
EXPECT_TRUE(!!f2->getLocalSpec("v"));
EXPECT_TRUE(!!f2->getLocalSpec("f"));
}
TEST_F(GiskardPPTest, functionCall) {
FnDefPtr function;
try {
parser.parseNamedExpression("superA = 5");
function = parser.parseFunctionDefinition("def scalar f(scalar x) { sqA = superA * superA; rVal = sqA * x; return rVal; }");
} catch (const std::exception& e) {
std::cout << e.what() << std::endl;
FAIL();
}
SpecPtr fnCall;
EXPECT_NO_THROW(fnCall = parser.parseExpression("f(2)"));
DoubleReferenceSpecPtr retRef;
ASSERT_TRUE(matches(fnCall, retRef));
EXPECT_EQ("f(2.000000)", retRef->get_reference_name());
AdvancedScopePtr scope = parser.getTopScope();
EXPECT_TRUE(!!scope->getLocalSpec("f(scalar)::sqA"));
EXPECT_TRUE(!!scope->getLocalSpec("f(2.000000)::x"));
EXPECT_TRUE(!!scope->getLocalSpec("f(2.000000)::rVal"));
EXPECT_TRUE(!!scope->getLocalSpec("f(2.000000)"));
}
TEST_F(GiskardPPTest, StringSpecTest) {
EXPECT_NO_THROW(parser.parseNamedExpression("str1 = \"abc\""));
SpecPtr expr;
StringSpecPtr str;
EXPECT_NO_THROW(expr = parser.parseExpression("str1 + \"123\""));
ASSERT_TRUE(matches(expr, str));
EXPECT_EQ("abc123", str->get_value());
}
TEST_F(GiskardPPTest, LoadFile) {
try {
QPControllerSpec qpSpec = parser.parseFromFile("test_controller.gpp");
QPController controller = generate(qpSpec);
} catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
FAIL();
}
}
|
781c1919ded8bb0e8c271912f265d53f9503db0d
|
e022061af1d19f2719e0b0faae61131f0f4f3e04
|
/MNIST_CNN_Training_Application/MNIST_CNN_Training_Application.cpp
|
e3441b0c6d96142de77535aaa6222c64da61b6f4
|
[] |
no_license
|
pirosm1/MNIST_Training
|
6bef94c97086f945bca231817c72d08a27b3ea92
|
7cf4594a69da16f1f994b5ebcf1a99d9e2a44fc2
|
refs/heads/master
| 2020-05-19T15:20:26.066468
| 2019-05-10T08:06:12
| 2019-05-10T08:06:12
| 185,083,167
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 7,698
|
cpp
|
MNIST_CNN_Training_Application.cpp
|
// MNIST_CNN_Training_Application.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include "pch.h"
#include <chrono>
#include <iostream>
#include <fstream>
#include <string>
#include "MNISTReader.h"
#include "ForwardPropagator.h"
#include "BackwardPropagator.h"
void printUsage();
void printTestImage(std::vector<uint8_t> image);
int maxIndex(std::vector<float> values);
int main(int argc, char *argv[])
{
std::ifstream trainingImageFile, trainingLabelFile;
if (argc != 5) {
printUsage();
return 1;
}
const std::string trainingImageFileName = argv[1];
const std::string trainingLabelFileName = argv[2];
const std::string testingImageFileName = argv[3];
const std::string testingLabelFileName = argv[4];
auto reader = std::make_unique<MNISTReader>();
// read training images into memory
std::vector<std::vector<uint8_t>> imageVector = reader->getImageVector(trainingImageFileName);
// Read training labels into memory for comparison later
std::vector<uint8_t> labelVector = reader->getLabelVector(trainingLabelFileName);
// read testing images into memory
std::vector<std::vector<uint8_t>> testingImageVector = reader->getImageVector(testingImageFileName);
// Read testing labels into memory for comparison later
std::vector<uint8_t> testingLabelVector = reader->getLabelVector(testingLabelFileName);
const bool verbose = false;
const int sizeOfInput = 28;
const int sizeOfFilter = 5;
const int sizeOfFeature = 24;
const int sizeOfMaxPool = 12;
const int sizeOfPoolingWindow = 2;
const int numberOfFeatures = 8;
const int numberOfFullyConnectedNodes = 45;
const int numberOfOutputs = 10;
const float learningRate = 0.1f;
const int numberOfEpochs = 10;
// Initialize the ForwardPropagator
auto fp = std::make_unique<ForwardPropagator>();
fp->setSizeOfInput(sizeOfInput);
fp->setSizeOfFilter(sizeOfFilter);
fp->setSizeOfFeature(sizeOfFeature);
fp->setSizeOfMaxPool(sizeOfMaxPool);
fp->setSizeOfPoolingWindow(sizeOfPoolingWindow);
fp->setNumberOfFeatures(numberOfFeatures);
fp->setNumberOfFullyConnectedNodes(numberOfFullyConnectedNodes);
fp->setNumberOfOutputs(numberOfOutputs);
fp->randomInitialization();
auto bp = std::make_unique<BackwardPropagator>();
bp->setSizeOfInput(sizeOfInput);
bp->setSizeOfFilter(sizeOfFilter);
bp->setSizeOfFeature(sizeOfFeature);
bp->setSizeOfMaxPool(sizeOfMaxPool);
bp->setSizeOfPoolingWindow(sizeOfPoolingWindow);
bp->setNumberOfFeatures(numberOfFeatures);
bp->setNumberOfFullyConnectedNodes(numberOfFullyConnectedNodes);
bp->setNumberOfOutputs(numberOfOutputs);
bp->setLearningRate(learningRate);
int batchSize = 64;
// for each e
for (int i = 0; i < numberOfEpochs; i++) {
auto epoch_start = std::chrono::steady_clock::now();
std::cout << "Epoch " << i << " Training started:" << std::endl << std::endl;
int correct = 0;
long long totalBackPropagationTime = 0;
for (int j = 0; j < imageVector.size(); j++) {
std::vector<float> outputs = fp->forwardPropagation(imageVector[j]);
if (verbose) {
std::cout << "Epoch: " << i << "\tDatapoint #: " << j << std::endl;
std::cout << "Answer: " << unsigned(labelVector[j]) << "\tPrediction: " << maxIndex(outputs) << std::endl;
for (int z = 0; z < numberOfOutputs; z++)
std::cout << z << ": " << outputs[z] << " ";
std::cout << std::endl;
}
if (unsigned(labelVector[j]) == maxIndex(outputs))
correct++;
if (verbose) {
std::cout << correct << "/" << (j + 1) << " - " << (float)correct / (j + 1) * 100 << "% correct" << std::endl;
}
bp->setConvolutionalLayerWeights(fp->getConvolutionalLayerWeights());
bp->setConvolutionalLayerBases(fp->getConvolutionalLayerBases());
bp->setMaxPoolingLayer(fp->getMaxPoolingLayer());
bp->setFullyConnectedLayer(fp->getFullyConnectedLayer());
bp->setFullyConnectedLayerWeights(fp->getFullyConnectedLayerWeights());
bp->setFullyConnectedLayerBases(fp->getFullyConnectedLayerBases());
bp->setOutputLayerWeights(fp->getOutputLayerWeights());
bp->setOutputLayerBases(fp->getOutputLayerBases());
auto start = std::chrono::steady_clock::now();
bp->backwardPropagation(imageVector[j], outputs, labelVector[j], verbose);
auto end = std::chrono::steady_clock::now();
long long time = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
totalBackPropagationTime += time;
if (verbose) {
std::cout << "Back propogation completed in (ms): " << std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() << std::endl;
std::cout << "Average time (ms): " << totalBackPropagationTime / (j + 1) << std::endl;
std::cout << std::endl;
}
fp->setConvolutionalLayerWeights(bp->getNewConvolutionalLayerWeights());
fp->setConvolutionalLayerBases(bp->getNewConvolutionalLayerBases());
fp->setFullyConnectedLayerWeights(bp->getNewFullyConnectedLayerWeights());
fp->setFullyConnectedLayerBases(bp->getNewFullyConnectedLayerBases());
fp->setOutputLayerWeights(bp->getNewOutputLayerWeights());
fp->setOutputLayerBases(bp->getNewOutputLayerBases());
}
// print to weight file
std::ostringstream fileName;
fileName << "weight_values_" << i << ".txt";
std::ofstream weightFile(fileName.str());
if (weightFile.is_open()) {
fp->printWeightValues(weightFile, false);
weightFile.close();
}
auto epoch_end = std::chrono::steady_clock::now();
std::cout << "Epoch " << i << " Training Finished: " << (float)correct / imageVector.size() * 100 << "% correct" << std::endl;
std::cout << "Seconds Elapsed: " << std::chrono::duration_cast<std::chrono::seconds>(epoch_end - epoch_start).count() << std::endl;
std::cout << "Average time (ms): " << totalBackPropagationTime / imageVector.size() << std::endl;
std::cout << std::endl;
int testsCorrect = 0;
// Test CNN at the end of each epoch
std::cout << "Epoch " << i << " Testing Starting: " << std::endl;
for (int j = 0; j < testingImageVector.size(); j++) {
std::vector<float> outputs = fp->forwardPropagation(testingImageVector[j]);
if (unsigned(testingLabelVector[j]) == maxIndex(outputs))
testsCorrect++;
}
std::cout << "Epoch " << i << " Testing Finished: " << (float)testsCorrect / testingImageVector.size() * 100 << "% correct" << std::endl;
std::cout << std::endl;
}
return 0;
}
void printUsage() {
using namespace std;
cout << "Usage:" << endl;
cout << "\tprog <path-to-training-image-ubyte-file> <path-to-training-label-ubyte-file> <path-to-testing-image-ubyte-file> <path-to-testing-label-ubyte-file>" << endl;
}
void printTestImage(std::vector<uint8_t> image) {
std::ofstream testImageFile("testImage.txt");
for (int i = 0; i < image.size(); i++) {
testImageFile << unsigned(image[i]) << " ";
if ((i + 1) % 28 == 0)
testImageFile << std::endl;
}
}
int maxIndex(std::vector<float> values) {
float max = values[0];
int maxIndex = 0;
for (int i = 1; i < values.size(); i++) {
if (values[i] > max) {
max = values[i];
maxIndex = i;
}
}
return maxIndex;
}
// Run program: Ctrl + F5 or Debug > Start Without Debugging menu
// Debug program: F5 or Debug > Start Debugging menu
// Tips for Getting Started:
// 1. Use the Solution Explorer window to add/manage files
// 2. Use the Team Explorer window to connect to source control
// 3. Use the Output window to see build output and other messages
// 4. Use the Error List window to view errors
// 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project
// 6. In the future, to open this project again, go to File > Open > Project and select the .sln file
|
26c31c44f302e53c59e51eb909b3e0ea9b2cb947
|
5a38d56fbbbb9c10f4182501c617e01de7d565c0
|
/CPP/0985_delivery.cpp
|
7b7ec8c252cc4124fddcd3fb1a3787b84c785a9a
|
[] |
no_license
|
tanmaysahay94/Algorithm
|
3551a84723bbcc76eb3cc776a9ba3ba256941123
|
142b1e471a467cd2124300f638fb8817d20b7959
|
refs/heads/master
| 2021-07-05T22:11:36.027616
| 2021-06-12T20:08:37
| 2021-06-12T20:08:37
| 20,177,690
| 0
| 3
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,277
|
cpp
|
0985_delivery.cpp
|
#include <bits/stdc++.h>
using namespace std;
const int maxk = 1e5 + 5;
const int maxn = 1e5 + 5;
int n, m, k;
set<int> toVisit;
vector<int> G[maxn], GR[maxn], edgeFrom[maxn], edgeFromComponent[maxn];
vector<int> vis(maxn), inComponent(maxn), edgeCountHelper(maxn);
stack<int> S;
vector<pair<int, int> > edges, cIDordering;
vector<vector<int> > components;
void dfs1(int v)
{
if (vis[v])
return;
vis[v] = 1;
for (auto u: G[v])
dfs1(u);
S.push(v);
}
void dfs2(int v, vector<int>& c, int cid)
{
if (vis[v])
return;
vis[v] = 1;
c.push_back(v);
inComponent[v] = cid;
for (auto e: edgeFrom[v])
edgeFromComponent[cid].push_back(e);
for (auto u: GR[v])
dfs2(u, c, cid);
}
void init()
{
for (int i = 0; i < maxn; i++)
G[i].clear(), GR[i].clear(), edgeFrom[i].clear(), edgeFromComponent[i].clear(), vis[i] = 0, inComponent[i] = -1, edgeCountHelper[i] = 0;
components.clear();
cIDordering.clear();
toVisit.clear();
}
int main()
{
int t;
scanf("%d", &t);
while (t--)
{
init();
scanf("%d%d%d", &n, &m, &k);
for (int i = 0; i < k; i++)
{
int city;
scanf("%d", &city);
toVisit.insert(city);
}
for (int i = 0; i < m; i++)
{
int x, y;
scanf("%d%d", &x, &y);
if (x == y)
continue;
edges.push_back(make_pair(x, y));
G[x].push_back(y);
GR[y].push_back(x);
edgeFrom[x].push_back(i);
}
for (int i = 1; i <= n; i++)
if (not vis[i])
dfs1(i);
vis.clear(); vis.resize(maxn);
int componentID = 0;
while (not S.empty())
{
vector<int> component;
int v = S.top();
S.pop();
if (vis[v])
continue;
dfs2(v, component, componentID);
componentID++;
sort(component.begin(), component.end());
components.push_back(component);
}
cIDordering.resize(0); cIDordering.resize(componentID);
for (int i = 0; i < componentID; i++)
cIDordering[i].first = 0, cIDordering[i].second = i;
for (int i = 0; i < (int) edges.size(); i++)
{
int u = edges[i].first, v = edges[i].second;
if (inComponent[u] != inComponent[v])
cIDordering[inComponent[v]].first++, edgeCountHelper[inComponent[v]]++;
}
multiset<pair<int, int> > ms;
for (int i = 0; i < componentID; i++)
ms.insert(cIDordering[i]);
vector<int> topo;
while (not ms.empty())
{
pair<int, int> foo = *(ms.begin());
ms.erase(ms.begin());
int cno = foo.second;
topo.push_back(cno);
map<int, int> thingsToChange;
for (auto eno: edgeFromComponent[cno])
{
int to = edges[eno].second;
int toComp = inComponent[to];
if (toComp != cno)
thingsToChange[toComp]--;
}
for (auto bar: thingsToChange)
{
int cnoChanged = bar.first;
int diff = bar.second;
multiset<pair<int, int> >::iterator help = ms.find(make_pair(edgeCountHelper[cnoChanged], cnoChanged));
pair<int, int> pertinent = *help;
ms.erase(help);
pertinent.first = max(0, pertinent.first + diff);
edgeCountHelper[cnoChanged] = pertinent.first;
ms.insert(pertinent);
}
}
vector<int> ans;
for (int i = 0; i < (int) topo.size(); i++)
{
int cno = topo[i];
for (int j = 0; j < (int) components[cno].size(); j++)
if (toVisit.count(components[cno][j]))
ans.push_back(components[cno][j]);
}
for (auto A: ans)
printf("%d ", A);
puts("");
}
return 0;
}
|
c209bd5c084c68835d4b5236edeb3002abb5cf68
|
089d5b084b83b9cec2374c3ca8c5902ea47084f1
|
/assn3/retreat3.cpp
|
761367f08fcd303ffbc8a0a58a84ec12a37e54a0
|
[] |
no_license
|
choisium/CSED331
|
a04b9d6e25b5577a2e3d6a198350ad94e7d7258f
|
f6435dcae6ab1f21529cb6441bd4a27b2a7b44fd
|
refs/heads/main
| 2023-06-09T20:17:10.828258
| 2021-07-05T00:50:23
| 2021-07-05T00:50:23
| 345,906,639
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,052
|
cpp
|
retreat3.cpp
|
#include <stdio.h>
#include <vector>
#include <limits.h>
#include <utility>
using namespace std;
typedef struct Edge {
int idx;
int node1;
int node2;
unsigned int length;
bool visited;
} Edge;
typedef struct Node {
int idx;
int order;
int root_order;
vector<Edge *> edge_list;
} Node;
void explore(int current_idx, int parent_idx, Node graph[], unsigned int& shortest_bridge, int& time) {
Node& current = graph[current_idx];
current.root_order = current.order = ++time;
// printf("current start - current: %d, parent: %d, order: %d\n", current_idx, parent_idx, current.order);
for (unsigned int i = 0; i < current.edge_list.size(); i++) {
Edge* e = current.edge_list[i];
Node& child = graph[e->node1 == current_idx? e->node2: e->node1];
// printf("loop - current: %d, child: %d, visited: %d\n", current_idx, child.idx, e->visited);
// if this edge is already visited, it came from parent. Pass it.
if (e->visited) continue;
e->visited = 1;
// this adjacent vertex was never been visited
if (child.order == INT_MAX) {
// printf("explore child - current: %d, child: %d, visited: %d(%d)\n", current_idx, child.idx, e->visited, graph[current_idx].edge_list[i]->visited);
explore(child.idx, current_idx, graph, shortest_bridge, time);
// printf("explore child end - current: %d, child: %d, visited: %d\n", current_idx, child.idx, e->visited);
}
// update root order if child's root order is smaller than current one
if (current.root_order > child.root_order) {
current.root_order = child.root_order;
}
// update shortest bridge
if (current.order < child.root_order && shortest_bridge > e->length) {
shortest_bridge = e->length;
}
// } else if (current.order > child.root_order) {
// // printf("update root order: current: %d, child: %d, root_order: %d\n", current_idx, child.idx, child.root_order);
// current.root_order = child.root_order;
// }
}
// printf("current end - current: %d, parent: %d, root_order: %d\n", current_idx, parent_idx, current.root_order);
}
int main() {
// get the number of testcases
int testcases;
scanf("%d", &testcases);
for(int t = 0; t < testcases; t++) {
// get the number of vertices and edges
int n, m;
scanf("%d %d", &n, &m);
Node graph[30000];
for (int i = 0; i < n; i++) {
graph[i].idx = i;
graph[i].order = INT_MAX;
graph[i].root_order = INT_MAX;
// printf("%d - %lud\n", i, graph[i].edge_list.size());
for (int j = 0; j < graph[i].edge_list.size(); j++) {
delete graph[i].edge_list[j];
}
graph[i].edge_list.clear();
graph[i].edge_list.shrink_to_fit();
}
int idx = 0;
Edge* e;
// create graph as adjacency list
for (int i = 0; i < m; i++) {
int u, v, l;
scanf("%d %d %d", &u, &v, &l);
e = new Edge();
e->idx = idx++;
e->node1 = u;
e->node2 = v;
e->length = l;
e->visited = 0;
graph[u].edge_list.push_back(e);
graph[v].edge_list.push_back(e);
}
unsigned int shortest_bridge = INT_MAX;
int time = 0;
// for (int i = 0; i < n; i++) {
// printf("%d-th row: ", i);
// vector<Edge*> edges = graph[i].edge_list;
// for (int j = 0; j < edges.size(); j++) {
// Edge e = *edges[j];
// printf("%d-%d(l: %d) ", e.node1, e.node2, e.length);
// }
// printf("\n");
// }
explore(0, -1, graph, shortest_bridge, time);
if (shortest_bridge == INT_MAX) {
printf("-1\n");
} else {
printf("%d\n", shortest_bridge);
}
}
}
|
c0289958b63af334915bc553339b8818c8e8625d
|
918b55cbd94e7cb5f92c2b2053841ee2a2d2d129
|
/source/Tests/Bit/Tests.h
|
b4ce10f6906c5fc8667be79a5c90795076f05cda
|
[
"MIT"
] |
permissive
|
chenghanpeng/microjit
|
9764bdff8e9458f42723a1be8cfb2bd925716a51
|
b9a13aef7c15c69164d0232dc32d5852f92330e5
|
refs/heads/master
| 2022-03-27T13:08:45.189919
| 2018-04-29T13:57:37
| 2018-04-29T13:57:37
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 70
|
h
|
Tests.h
|
#pragma once
#include "Config.h"
namespace Bit {
bool bitTests();
}
|
3e727b80fb0dd35be4fb12a8d96bf0a1d1bf8a70
|
038fe5aba23f430e47cbac451ae1029bd1ff47c5
|
/Base/Macros.hpp
|
61f28b153ad983bc826bcd5ccb6d25d1c327b6a4
|
[
"MIT"
] |
permissive
|
lxq2537664558/ctnorth
|
aa164c6244780a2a3c36467a4d1e3b641b792871
|
9c33359eced067f9eb639187d2d4dd6378332ae7
|
refs/heads/master
| 2021-01-20T01:35:43.614562
| 2017-04-17T20:18:30
| 2017-04-17T20:18:30
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,239
|
hpp
|
Macros.hpp
|
// Useful macros
// Author(s): iFarbod <ifarbod@outlook.com>
//
// Copyright (c) 2015-2017 CTNorth Team
//
// Distributed under the MIT license (See accompanying file LICENSE or copy at
// https://opensource.org/licenses/MIT)
#pragma once
// Bit manipulation
#define BITMASK_SET(a, b) (a |= b)
#define BITMASK_RESET(a, b) (a &= ~(b))
#define BITMASK_FLIP(a, b) (a ^= b)
#define BITMASK_TEST(a, b) ((a & b) != 0)
#define CALC_BITMASK(n) (u32(1 << n))
#define CALC_BITMASK8(n) (u8(1 << n))
#define CALC_BITMASK16(n) (u16(1 << n))
#define ARRAY_LENGTH(arr) (sizeof(arr) / sizeof(arr[0]))
#define ARRAY_SIZE(arr) (sizeof(arr) / sizeof(*arr))
#define SAFE_DELETE(memory) { delete memory; memory = nullptr; }
#define SAFE_RELEASE(p) { if ( (p) ) { (p)->Release(); (p) = nullptr; } }
#define SAFE_DELETE_ARRAY(memory) { if(memory) { delete [] memory; memory = nullptr; }
#define SAFE_FREE(memory) { if (memory) { free(memory); memory = nullptr; } }
#define METERS_TO_FEET(x) (x * 3.280839895)
#ifdef _WIN32
#define DIRECTORY_SEPARATOR_CHAR "\\"
#else
#define DIRECTORY_SEPARATOR_CHAR "/"
#endif
// Declspec
#define DLLEXPORT __declspec(dllexport)
#define DLLIMPORT __declspec(dllimport)
#define NAKED __declspec(naked)
|
90887ad61723799da73d32af1fe136383503d5b8
|
8e4afdd17e5307b9736549b7fd39e1ec7424a78d
|
/futures/join.h
|
6dd06aef90afc3c61b472dfbce000105725b19f3
|
[
"MIT"
] |
permissive
|
cfo82/asyncpp
|
8d8abce8a857a9885eab69be2dbf5a348645c117
|
5dcdb2fe12e21f89663207c448fc07a0ac673f9a
|
refs/heads/master
| 2021-01-23T15:52:29.973741
| 2014-12-17T20:55:11
| 2014-12-17T20:55:11
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,866
|
h
|
join.h
|
/*
* This file is part of the asyncpp Library release under the MIT license.
*
* Copyright (c) 2014 Christian Oberholzer
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifndef FUTURES_JOIN_H
#define FUTURES_JOIN_H
#include "future.h"
#include "../templatelibrary/templatelist.h"
#include "../templatelibrary/templatelistdeclaration.h"
#include "../templatelibrary/templatelistcontainer.h"
#if (!defined(_MSC_VER) && __cplusplus < 201103L) || (defined(_MSC_VER) && _MSC_VER < 1800 && _MSC_FULL_VER != 170051025) // 170051025 == ctp nov 2012
#else
namespace futures {
namespace impl {
template <typename SchedulerT, typename ValueContainer>
class JoinState
{
public:
InterlockedInteger counter;
ValueContainer values;
Future<SchedulerT, ValueContainer> future;
};
template <typename CurrentT, typename RestT>
struct InternalCreateReturnTypeList
{
typedef TemplateList<
typename CurrentT::return_t,
typename InternalCreateReturnTypeList<typename RestT::current_t, typename RestT::rest_t>::type_t
> type_t;
};
template <typename CurrentT>
struct InternalCreateReturnTypeList<CurrentT, EmptyTemplateList>
{
typedef TemplateList<
typename CurrentT::return_t,
EmptyTemplateList
> type_t;
};
template <typename... FuturesT>
struct CreateReturnTypeList
{
typedef typename TemplateListDeclaration<FuturesT...>::type_t futures_list_t;
typedef TemplateListContainer<
typename InternalCreateReturnTypeList<typename futures_list_t::current_t, typename futures_list_t::rest_t>::type_t
> type_t;
};
template <typename JoinStateT, int index, typename CurrentFutureT, typename... RestFuturesT>
struct CreateFutureContinuations
{
static void Create(
JoinStateT* join_state,
CurrentFutureT future,
RestFuturesT... rest
)
{
future.Then([join_state](CurrentFutureT::return_t value) {
//printf("X\n");
join_state->values.SetData<index>(value);
if (join_state->counter.Decrement() <= 0)
{ join_state->future.Set(std::move(join_state->values)); }
});
CreateFutureContinuations<JoinStateT, index+1, RestFuturesT...>::Create(join_state, rest...);
}
};
template <typename JoinStateT, int index, typename CurrentFutureT>
struct CreateFutureContinuations<JoinStateT, index, CurrentFutureT>
{
static void Create(
JoinStateT* join_state,
CurrentFutureT future
)
{
future.Then([join_state](CurrentFutureT::return_t value) {
//printf("Y\n");
join_state->values.SetData<index>(value);
if (join_state->counter.Decrement() <= 0)
{ join_state->future.Set(std::move(join_state->values)); }
});
}
};
template <typename CurrentFutureT, typename... RestFuturesT>
struct GetSchedulerTypeFromFuturePack
{
typedef typename CurrentFutureT::scheduler_t scheduler_t;
static scheduler_t* GetScheduler(CurrentFutureT future, RestFuturesT... rest)
{
return future.GetScheduler();
}
};
} // namespace impl
template <typename... FuturesT>
Future<
typename impl::GetSchedulerTypeFromFuturePack<FuturesT...>::scheduler_t,
typename impl::CreateReturnTypeList<FuturesT...>::type_t
>
join(
FuturesT... futures
)
{
typedef typename impl::GetSchedulerTypeFromFuturePack<FuturesT...>::scheduler_t scheduler_t;
typedef typename TemplateListDeclaration<FuturesT...>::type_t futures_list_t;
typedef typename impl::CreateReturnTypeList<FuturesT...>::type_t return_parameter_list_t;
typedef impl::JoinState<scheduler_t, return_parameter_list_t> join_state_t;
auto result_future = Future<scheduler_t, return_parameter_list_t>(impl::GetSchedulerTypeFromFuturePack<FuturesT...>::GetScheduler(futures...));
auto state = new join_state_t();
state->counter.SetValue(futures_list_t::Size);
state->future = result_future;
impl::CreateFutureContinuations<join_state_t, 0, FuturesT...>::Create(state, futures...);
return result_future;
}
} // namespace futures
#endif
#endif // FUTURES_JOIN_H
|
2ee4aa5dd35c6c282fd08497872856696522cd5e
|
48e9ac838cf02b92c55afae2b1cafe8d39c7d0bd
|
/Snowglobe/Snowglobe/Tri.cpp
|
f9653ee3e33996d56a676153630337a867cc2109
|
[] |
no_license
|
gwgrisk/msc-hull-snowglobe
|
37d164a649c66c55ba1e43abb3b38a3b121ff820
|
d27a1e3482f426778bd82024788307c085256b31
|
refs/heads/master
| 2020-03-30T10:58:57.529443
| 2013-02-20T17:16:47
| 2013-02-20T17:16:47
| 41,352,979
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,108
|
cpp
|
Tri.cpp
|
#include "stdafx.h"
#include "Tri.h"
#include <AntiMatter\AppLog.h>
#include <comdef.h>
Tri::Tri() :
m_bInitialized ( false ),
m_pVertices ( NULL ),
m_pdwIndices ( NULL ),
m_rBaseLength ( 10.0f ),
m_rHeight ( 5.0f ),
m_nVertCount ( 0 ),
m_nIndexCount ( 0 )
{
m_bInitialized = Initialize();
}
Tri::Tri( const float rBaseLength, const float rHeight ):
m_bInitialized ( false ),
m_pVertices ( NULL ),
m_pdwIndices ( NULL ),
m_rBaseLength ( rBaseLength ),
m_rHeight ( rHeight ),
m_nVertCount ( 0 ),
m_nIndexCount ( 0 )
{
m_bInitialized = Initialize();
}
Tri::Tri( const Tri & r ) :
m_bInitialized ( false ),
m_pVertices ( NULL ),
m_pdwIndices ( NULL ),
m_rBaseLength ( r.m_rBaseLength ),
m_rHeight ( r.m_rHeight ),
m_nVertCount ( 0 ),
m_nIndexCount ( 0 )
{
if( r.Initialized() )
{
m_bInitialized = Initialize();
}
}
Tri & Tri::operator=( const Tri & r )
{
if( this != &r )
{
if( m_bInitialized )
Uninitialize();
m_rBaseLength = r.m_rBaseLength;
m_rHeight = r.m_rHeight;
if( r.Initialized() )
m_bInitialized = Initialize();
}
return *this;
}
Tri::~Tri()
{
Uninitialize();
}
bool Tri::Initialize()
{
if( m_bInitialized )
return true;
using AntiMatter::AppLog;
using std::string;
HRESULT hr = S_OK;
m_nVertCount = 3;
m_nIndexCount = 3;
hr = GenerateVertices( &m_pVertices );
if( ! SUCCEEDED(hr) )
{
AppLog::Ref().LogMsg(
"Tri::Initialize() failed to GenerateVertices(): %s",
_com_error(hr).ErrorMessage()
);
Uninitialize();
return false;
}
hr = GenerateIndices( &m_pdwIndices );
if( ! SUCCEEDED(hr) )
{
AppLog::Ref().LogMsg(
"Tri::Initialize() failed to GenerateIndices(): %s",
_com_error(hr).ErrorMessage()
);
Uninitialize();
return false;
}
m_bInitialized = true;
return true;
}
void Tri::Uninitialize()
{
if( ! m_bInitialized )
return;
m_bInitialized = false;
if( m_pVertices )
{
delete [] m_pVertices;
m_pVertices = NULL;
}
if( m_pdwIndices )
{
delete [] m_pdwIndices;
m_pdwIndices = NULL;
}
m_rBaseLength = 0.0f;
m_rHeight = 0.0f;
m_nVertCount = 0;
m_nIndexCount = 0;
}
// IGeometry
HRESULT Tri::GenerateVertices( CustomVertex** ppVertices )
{
if( m_bInitialized )
return E_UNEXPECTED;
if( ! ppVertices )
return E_INVALIDARG;
*ppVertices = new (std::nothrow) CustomVertex[m_nVertCount];
if( ! *ppVertices )
return E_OUTOFMEMORY;
// vertices
(*ppVertices)[1].m_Position[X] = 0.0f; // tip top
(*ppVertices)[1].m_Position[Y] = m_rHeight / 2.0f;
(*ppVertices)[1].m_Position[Z] = 0.0f;
(*ppVertices)[1].m_Position[X] = -m_rBaseLength / 2.0f; // lower left corner
(*ppVertices)[1].m_Position[Y] = 0.0f;
(*ppVertices)[1].m_Position[Z] = -m_rHeight /2.0f;
(*ppVertices)[2].m_Position[X] = m_rBaseLength / 2.0f; // lower right corner
(*ppVertices)[2].m_Position[Y] = 0.0f;
(*ppVertices)[2].m_Position[Z] = -m_rHeight /2.0f;
// texture coords
(*ppVertices)[0].m_TexCoords[U] = 0.0f;
(*ppVertices)[0].m_TexCoords[V] = 1.0f;
(*ppVertices)[1].m_TexCoords[U] = 1.0f;
(*ppVertices)[1].m_TexCoords[V] = 1.0f;
(*ppVertices)[2].m_TexCoords[U] = 1.0f;
(*ppVertices)[2].m_TexCoords[V] = 0.0f;
// normals
// per vertex colours ( all set white )
for( int n = 0; n < m_nVertCount; n ++ )
{
(*ppVertices)[n].m_Normal[X] = 0.0f;
(*ppVertices)[n].m_Normal[Y] = 1.0f;
(*ppVertices)[n].m_Normal[Z] = 0.0f;
(*ppVertices)[n].m_Colour[R] = 1.0f;
(*ppVertices)[n].m_Colour[G] = 1.0f;
(*ppVertices)[n].m_Colour[B] = 1.0f;
(*ppVertices)[n].m_Colour[A] = 1.0f;
}
return S_OK;
}
HRESULT Tri::GenerateIndices( unsigned short** ppIndices )
{
if( m_bInitialized )
return E_UNEXPECTED;
if( ! ppIndices )
return E_INVALIDARG;
*ppIndices = new (std::nothrow) unsigned short[m_nIndexCount];
if( ! *ppIndices )
return E_OUTOFMEMORY;
(*ppIndices)[0] = 0;
(*ppIndices)[1] = 1;
(*ppIndices)[2] = 2;
return S_OK;
}
|
ab398b096625a63a6d5beda65e038b9c73abb8b6
|
215dd7a6798c341e3b7b51f5b8880859db40aec8
|
/OrderingSystem/cookbookiteminfo.h
|
ca4e340a14ed01523073eab0dbccbf7962376f75
|
[] |
no_license
|
dousp1220/OrderingSystem
|
1cf60212948fbcf554328115ae9bfecfcd7c9a0d
|
a189f8e8008da3aeed2e45d0a6fa326b7c9db554
|
refs/heads/master
| 2020-03-25T13:46:03.203831
| 2018-09-20T04:17:00
| 2018-09-20T04:17:00
| 143,841,929
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 321
|
h
|
cookbookiteminfo.h
|
#ifndef COOKBOOKITEMINFO_H
#define COOKBOOKITEMINFO_H
#include <QString>
#include "sqlUtils/entity/menuitementity.h"
/**
* @brief The CookBookItemInfo class
* 菜品信息(菜品展示使用)
*/
class CookBookItemInfo : public menuItemEntity
{
public:
CookBookItemInfo();
};
#endif // COOKBOOKITEMINFO_H
|
3d02b71f77fbad4f2f509398e546873713e53e4a
|
6c712b00801a92664e9249534354645a1b6992c3
|
/Software/DomAlgoServer/src/Synapsis/Sensor/Sensor.cpp
|
ba9708de29ef27976a13c3c9b6bc81239f8473dc
|
[] |
no_license
|
Gleeno/DomAlgo
|
0821cbadf1d77d43a3e2f2f8cba3600310a79ed7
|
663b2b247d26e9a69b356ae5223bdf2eaa99ca18
|
HEAD
| 2016-08-12T22:23:53.723398
| 2016-04-11T08:33:16
| 2016-04-11T08:33:16
| 48,537,618
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,590
|
cpp
|
Sensor.cpp
|
/*
* File: Sensor.cpp
* Author: Matteo Di Carlo
* Created on January 28, 2016, 4:03 PM
*
* Copyright (C) 2016 Matteo Di Carlo - www.gleeno.com
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Sensor.hpp"
Sensor::Sensor(std::string id, sensType type, std::string name, std::string ip) {
this->id = id;
this->type = type;
this->name = name;
this->ip = ip;
}
Sensor::Sensor() {
}
Sensor::~Sensor() {
}
sensType Sensor::getType() {
return this->type;
}
std::string Sensor::getId() {
return this->id;
}
std::string Sensor::getIp() {
return this->ip;
}
std::string Sensor::getName() {
return this->name;
}
int Sensor::getWifiSignal() {
return this->wifiSignal;
}
//get general values
Json::Value Sensor::getDataSensor() {
Json::Value data;
// get all sensor datas
data["ip"] = getIp();
data["name"] = getName();
data["id"] = getId();
data["type"] = std::to_string((int) getType());
return data;
}
|
78a6b1b2f50cd826581c1e3f4dc31573541da010
|
797372ba760b2a1f21400f52a08b5e191b1cc52b
|
/FPCC++Assignment/CustomerLinkedList.h
|
02bca98056b41ba3d4aea771976623509042e517
|
[] |
no_license
|
kathrynaj7/BankApplication
|
11c071a13de8de9ad413d781a0b68a6873f9dfe1
|
37a83b7d9f8065ed30e948e33ed6f66cc8ad97e0
|
refs/heads/master
| 2021-01-01T16:25:36.911532
| 2014-03-23T17:06:33
| 2014-03-23T17:06:33
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,358
|
h
|
CustomerLinkedList.h
|
// CustomerLinkedList.h
// Linked list of Customers
#ifndef CUSTOMERLINKEDLIST_H
#define CUSTOMERLINKEDLIST_H
#include <iostream>
#include "CustomerNode.h"
class CustomerLinkedList
{
private:
CustomerNode *head, *current, *newCustomer;
public:
CustomerLinkedList()
{
head = NULL;
current = NULL;
}
~CustomerLinkedList()
{
}
void addCustomerNode(Customer* newData)
{
newCustomer = new CustomerNode(newData);
// Add customer to the start of the list if there is no head already
if(head == NULL)
{
head = newCustomer;
head->next = NULL;
}
else
{
// End of the list
current = head;
while(current ->next != NULL)
{
current = current -> next;
}
// Add to end
current -> next = newCustomer;
newCustomer-> next = NULL;
}
}
void removeCustomerNode(string name)
{
CustomerNode *current, *temp;
current = head;
bool found = false;
// If the list is empty
if(current != NULL)
{
// Find customer by searching through
// or until the list ends
while(current -> data != NULL || !found)
{
// If input matches, remove customer
if(name == current -> data -> showName())
{
// If head
if(current == head)
{
// If head is the only node
if(current -> next == NULL)
{
current -> data -> ~Customer();
free(current);
head = NULL;
current = NULL;
cout << name << " was deleted";
found = true;
system("PAUSE");
}
// If there are more nodes than head
else
{
head = current -> next;
current -> data->~Customer();
free(current);
cout << name << " was deleted";
found = true;
system("PAUSE");
}
}
// If node is not head
else{
// Remove and reshuffle
if(current->next!=NULL)
{
temp = current->next;
current->data->~Customer();
free(current);
current = head;
while(current->next!=NULL)
{
current = current->next;
}
current->next = temp;
}
// If node is at the end
else
{
temp = current;
current->data->~Customer();
free(current);
current = head;
while(current->next!=temp)
{
current = current->next;
}
current->next = NULL;
}
// Found changed to true
found = true;
cout << name << " was deleted";
system("PAUSE");
}
}
if(!found)
{
if(current->next==NULL)
{
break;
}
else
{
current = current->next;
}
}
else{break;}
}
//If boolean remains false, print customer not found message
if (!found)
{
cout << "Customer does not exist\n";
system("PAUSE");
}
}
else
{
// If not found, print
cout << "There are no customers";
system("PAUSE");
}
}
void printAccounts(string name)
{
CustomerNode *current;
current=head;
bool found = false;
if(head!= NULL)
{
while(current->data!=NULL || !found)
{
if(name == current->data->showName())
{
current->data->printAccounts();
found = true;
break;
}
if(!found)
{
if(current->next==NULL)
{
break;
}
else
{
current = current->next;
}
}
}
if (!found)
{
cout << "Customer Not Found\n";
}
}
else
{
cout << "There are no customers in the system";
}
}
void printCustomers()
{
CustomerNode* current;
current=head;
//Empty list
if(current == NULL)
{
cout << "There are no customers\n";
}
else
{
while(current!=NULL)
{
current->data->printInfoCustomer();
current->data->printAccountsInfo();
current=current->next;
}
cout << "\n";
system("PAUSE");
}
}
CustomerNode* findCustomerNode(string name)
{
CustomerNode *current, *temp;
current=head;
bool found = false;
if(current != NULL)
{
while(current->data!=NULL || !found)
{
if(name == current->data->showName())
{
return current;
}
if(!found)
{
if(current->next==NULL)
{
break;
}
else
{
current = current->next;
}
}
else{break;}
}
if (!found)
{
return NULL;
}
}
else
{
return NULL;
}
}
};
#endif
|
452546497590144b2994e6961dacc875d4cbba18
|
1bd0f68866a8504a774387823664fe54de1b6bf5
|
/src/SymbolicModel.hh
|
20494a76ca6e437a9525ce498629bd41ea1b1db4
|
[
"MIT"
] |
permissive
|
MehrdadZareian/GAMARA
|
8d1f9dc26d856ef60d0060b1be328dbf502759e1
|
85428ae55a0cb8ae541d6db668307cacc3899cee
|
refs/heads/master
| 2023-07-08T06:15:33.343091
| 2021-08-09T07:07:12
| 2021-08-09T07:07:12
| 341,169,040
| 1
| 0
| null | 2021-05-17T12:50:33
| 2021-02-22T10:56:32
|
Jupyter Notebook
|
UTF-8
|
C++
| false
| false
| 7,707
|
hh
|
SymbolicModel.hh
|
/*
* SymbolicModel.hh
*
* created: Jan 2017
* author: Matthias Rungger
*/
/** @file **/
#ifndef SYMBOLICMODEL_HH_
#define SYMBOLICMODEL_HH_
#include <iostream>
#include <vector>
#include "SymbolicSet.hh"
/** @namespace scots **/
namespace scots {
/**
* @class SymbolicModel
*
* @brief Compute the transition function of a symbolic model as BDD using the growth bound.
*
* See
* - the manual in <a href="./../../manual/manual.pdf">manual.pdf</a>
* - http://arxiv.org/abs/1503.03715 for theoretical background
*
**/
template<class state_type, class input_type>
class SymbolicModel {
private:
/* print progress to the console (default m_verbose=true) */
bool m_verbose=true;
/* SymbolicSet conaining the BDD vars of the pre */
const SymbolicSet m_pre;
/* SymbolicSet conaining the BDD vars of the inputs */
const SymbolicSet m_input;
/* SymbolicSet conaining the BDD vars of the post */
const SymbolicSet m_post;
/* measurement error bound */
std::unique_ptr<double[]> m_z;
void progress(const abs_type& i, const abs_type& N, abs_type& counter) {
if(!m_verbose)
return;
if(((double)i/(double)N*100)>counter){
if(counter==0)
std::cout << "loop: ";
if((counter%10)==0)
std::cout << counter;
else if((counter%2)==0)
std::cout << ".";
counter++;
}
std::flush(std::cout);
if(i==(N-1))
std::cout << "100\n";
}
public:
/* @cond EXCLUDE from doxygen*/
/* destructor */
~SymbolicModel() = default;
/* deactivate standard constructor */
SymbolicModel() = delete;
/* cannot be copied or moved */
SymbolicModel(SymbolicModel&&) = delete;
SymbolicModel(const SymbolicModel&) = delete;
SymbolicModel& operator=(SymbolicModel&&)=delete;
SymbolicModel& operator=(const SymbolicModel&)=delete;
/* @endcond */
/**
* @brief Construct SymbolicModel with the SymbolicSet representing the
* state alphabet (pre and post) and input alphabet
**/
SymbolicModel(const SymbolicSet& pre,
const SymbolicSet& input,
const SymbolicSet& post) :
m_pre(pre), m_input(input), m_post(post),
m_z(new double[m_pre.get_dim()]()) {
/* default value of the measurement error
* (heurisitc to prevent rounding errors)*/
for(int i=0; i<m_pre.get_dim(); i++)
m_z[i]=m_pre.get_eta()[i]/1e10;
}
template<class F1, class F2>
BDD compute_gb(const Cudd& manager, F1& system_post, F2& radius_post, size_t& no_trans) {
return compute_gb(manager, system_post, radius_post, [](const abs_type&) noexcept {return false;}, no_trans);
}
/**
* @brief computes the transition function
*
* @param [in] manager - Cudd manager
*
* @param [in] system_post - lambda expression as defined in Abstraction::compute_gb
*
* @param [in] radius_post - lambda expression as defined in Abstraction::compute_gb
*
* @param [in] avoid - lambda expression as defined in Abstraction::compute_gb
*
* @param [out] no_trans - number of transitions
*
* @result a BDD encoding the transition function as boolean function over
* the BDD var IDs in m_pre, m_input, m_post
**/
template<class F1, class F2, class F3>
BDD compute_gb(const Cudd& manager, F1& system_post, F2& radius_post, F3&& avoid, size_t& no_trans) {
/* number of cells */
abs_type N=m_pre.size();
/* number of inputs */
abs_type M=m_input.size();
/* state space dimension */
int dim=m_pre.get_dim();
/* for display purpose */
abs_type counter=0;
/* variables for managing the post */
std::vector<abs_type> lb(dim); /* lower-left corner */
std::vector<abs_type> ub(dim); /* upper-right corner */
/* radius of hyper interval containing the attainable set */
state_type eta;
state_type r;
/* state and input variables */
state_type x;
input_type u;
/* for out of bounds check */
state_type lower_left;
state_type upper_right;
/* copy data from m_state_alphabet */
for(int i=0; i<dim; i++) {
eta[i]=m_pre.get_eta()[i];
lower_left[i]=m_pre.get_lower_left()[i];
upper_right[i]=m_pre.get_upper_right()[i];
}
/* the BDD to encode the transition function */
BDD tf = manager.bddZero();
/* is post of (i,j) out of domain ? */
bool out_of_domain;
/* loop over all cells */
for(abs_type i=0; i<N; i++) {
BDD bdd_i = m_pre.id_to_bdd(i);
/* is i an element of the avoid symbols ? */
if(avoid(i)) {
continue;
}
/* loop over all inputs */
for(abs_type j=0; j<M; j++) {
BDD bdd_j = m_input.id_to_bdd(j);
/* get center x of cell */
m_pre.itox(i,x);
/* cell radius (including measurement errors) */
for(int k=0; k<dim; k++)
r[k]=eta[k]/2.0+m_z[k];
/* current input */
m_input.itox(j,u);
/* integrate system and radius growth bound */
/* the result is stored in x and r */
radius_post(r,x,u);
system_post(x,u);
/* determine the cells which intersect with the attainable set:
* discrete hyper interval of cell indices
* [lb[0]; ub[0]] x .... x [lb[dim-1]; ub[dim-1]]
* covers attainable set */
for(int k=0; k<dim; k++) {
/* check for out of bounds */
double left = x[k]-r[k]-m_z[k];
double right = x[k]+r[k]+m_z[k];
if(left <= lower_left[k]-eta[k]/2.0 || right >= upper_right[k]+eta[k]/2.0) {
out_of_domain=true;
break;
}
/* integer coordinate of lower left corner of post */
lb[k] = static_cast<abs_type>((left-lower_left[k]+eta[k]/2.0)/eta[k]);
/* integer coordinate of upper right corner of post */
ub[k] = static_cast<abs_type>((right-lower_left[k]+eta[k]/2.0)/eta[k]);
}
if(out_of_domain) {
out_of_domain=false;
continue;
}
/* compute BDD of post */
BDD bdd_k = m_post.interval_to_bdd(manager,lb,ub);
/* add to transition function */
tf = tf | (bdd_i & bdd_j & bdd_k);
}
/* print progress */
progress(i,N,counter);
}
/* count number of transitions */
size_t nvars = m_pre.get_no_bdd_vars() +
m_input.get_no_bdd_vars() +
m_post.get_no_bdd_vars();
no_trans=tf.CountMinterm(nvars);
return tf;
}
/** @brief set the measurement error bound **/
void set_measurement_error_bound(const state_type& error_bound) {
for(int i=0; i<m_pre.get_dim(); i++) {
m_z[i]=error_bound[i];
}
}
/** @brief activate console output **/
void verbose_on() {
m_verbose=true;
}
/** @brief get measurement error bound **/
std::vector<double> get_measruement_error_bound() const {
std::vector<double> z;
for(int i=0; i<m_pre.get_dim(); i++) {
z.push_back(m_z[i]);
}
return z;
}
/** @brief deactivate console output **/
void verbose_off() {
m_verbose=false;
}
const SymbolicSet& get_sym_set_pre() const {
return m_pre;
}
const SymbolicSet& get_sym_set_post() const {
return m_post;
}
const SymbolicSet& get_sym_set_input() const {
return m_input;
}
};
} /* close namespace */
#endif /* SYMBOLICMODEL_HH_ */
|
37ec39274054fb7eab0c29a8bc599b63eaa7abc0
|
3054ded5d75ec90aac29ca5d601e726cf835f76c
|
/Training/UVa/CP3/Mathematics/Java BigInteger/10235 - Simply Emirp.cpp
|
a101007bf41c37606933de1afcc0ac0ef43125e0
|
[] |
no_license
|
Yefri97/Competitive-Programming
|
ef8c5806881bee797deeb2ef12416eee83c03add
|
2b267ded55d94c819e720281805fb75696bed311
|
refs/heads/master
| 2022-11-09T20:19:00.983516
| 2022-04-29T21:29:45
| 2022-04-29T21:29:45
| 60,136,956
| 10
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 899
|
cpp
|
10235 - Simply Emirp.cpp
|
#include <bits/stdc++.h>
#define endl '\n'
#define debug(X) cout << #X << " = " << X << endl
#define fori(i,b,e) for (int i = (b); i < (e); ++i)
#define mod(x,m) ((((x) % (m)) + (m)) % (m))
using namespace std;
typedef long long ll;
typedef vector<int> vi;
typedef pair<int, int> ii;
typedef vector<ii> vii;
const int INF = 1e9;
bool isprime(int n) {
for (int i = 2; i * i <= n; i++)
if (n % i == 0)
return false;
return true;
}
int main() {
ios_base::sync_with_stdio(false); cin.tie(0);
string n;
while (cin >> n) {
int a = atoi(n.c_str());
reverse(n.begin(), n.end());
int b = atoi(n.c_str());
bool ipa = isprime(a), ipb = (a == b ? false : isprime(b));
if (ipa && ipb)
cout << a << " is emirp." << endl;
else if (ipa && !ipb)
cout << a << " is prime." << endl;
else
cout << a << " is not prime." << endl;
}
return 0;
}
|
e43f5af79c670419c930ff63192c3a9c70ef9b3a
|
8f0cf8a55ec608add3ba1b1d0cb35a12d26a2dfa
|
/app/src/sy_testmode.cpp
|
e14b7a95890adab2dc94c1cea3128d3c6edcbcdc
|
[] |
no_license
|
gxuliang/fox
|
f298596f3bdd3da2f51d949683e58123b9340e54
|
2ca2bbc88f4b0cf4576b5c5f8b083cef6b14452d
|
refs/heads/master
| 2021-01-18T16:27:59.254775
| 2014-11-10T15:01:19
| 2014-11-10T15:01:19
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,778
|
cpp
|
sy_testmode.cpp
|
/*
* sy_testmode.cpp
*
* Created on: 2014-10-30
* Author: xul
*/
#include "base/sy_types.h"
#include "NetService/sy_netServ.h"
#include "sy_testmode.h"
#include "base/sy_debug.h"
PATTERN_SINGLETON_IMPLEMENT(CTestMode)
CTestMode::CTestMode()
{
flag = 0;
}
CTestMode::~CTestMode()
{
}
void CTestMode::run(const char* path)
{
sleep(5);
errorf("============sned start================\n");
int fd = ::open(path, O_RDONLY, S_IWUSR);
if(fd <= 0)
return;
flag = 1;
char buf[2000]="";
int len,ret;
while((len = ::read(fd, buf, 2000)) > 0)
{
if(INetServ::instance()->getState()==true)
{
ret = INetServ::instance()->write(buf, len);
tracepoint();
if(ret < 0)//发送不成功
{
tracepoint();
if(ret == -2)
{//标示有备用服务器,等待5秒后再尝试发送
sleep(5);
ret = INetServ::instance()->write(buf, len);
}
//if(ret < 0)//还是小于0转为本地模式
//put(tmp, len);
}
}
else
{
//put(tmp, len);
}
//INetServ::instance()->write(buf, len);
fatalf("AAA============write len = %d================\n", len);
//usleep(200*1000);
}
errorf("============sned end================\n");
::close(fd);
tracepoint();
}
void CTestMode::save(char* buf, int len)
{
tracepoint();
if(flag == 0)
return;
tracepoint();
mfd = ::open("check.txt",O_WRONLY | O_CREAT | O_APPEND, S_IWUSR);
if(mfd <= 0)
return;
int ret = 0, cnt = 0;
warnf("BBB============write len = %d================\n", len);
char* p;
while(len > 0)
{
p = &buf[cnt];
ret = ::write(mfd, p, len);
errorf("CCC============write len = %d================\n", ret);
len = len - ret;
cnt = cnt + ret;
}
::close(mfd);
}
ITestMode *ITestMode::instance()
{
return CTestMode::instance();
}
|
0caef29eb2151730ca6294f80e4e5d2b648a5cec
|
835bd7f9fefc53816be3cf20d0d3e25aaf4c05b6
|
/workspace-latest/framework/src/ScreenAdapter.cpp
|
5ec12be3bb33738133c2952937356fe3f719ecf2
|
[] |
no_license
|
wangenheng/gitHub
|
fd24cee8bb9a3adf707cd095d88620dde91a2c87
|
3d5ccf1aee5650ad911affcfaf472f47db71e72b
|
refs/heads/master
| 2021-03-19T08:30:23.359813
| 2017-07-25T09:13:08
| 2017-07-25T09:13:08
| 98,287,966
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 153
|
cpp
|
ScreenAdapter.cpp
|
#include "ScreenAdapter.h"
Implement_DynCreate(ScreenAdapter, Adapter)
ScreenAdapter::ScreenAdapter(void)
{
}
ScreenAdapter::~ScreenAdapter(void)
{
}
|
e61b51bbbd9e7cee57bb50de97cc76b3cbf3e772
|
050af48721534d62f7a089254cc7abb096332299
|
/utility/relational-table-generator/table_data_gen.cpp
|
80bb6d38a918ef02ee13436b0d74b65f135c6906
|
[] |
no_license
|
dadaism/nested-parallelism
|
921451ec93dceebcd9baf0a19854b89c48b8e7c4
|
12e0fc301feb31cec00d1c1b431c398050a26926
|
refs/heads/master
| 2021-01-01T19:16:32.587668
| 2015-09-24T04:15:47
| 2015-09-24T04:15:47
| 32,062,904
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,927
|
cpp
|
table_data_gen.cpp
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <time.h>
#include <math.h>
#define KEY_RANGE 6666
typedef struct conf {
bool verbose;
int dist;
float k;
char *data_file;
} CONF;
typedef struct tb {
int size;
short *key;
short *value;
} TABLE;
CONF config;
bool VERBOSE = false;
FILE *fp = NULL;
TABLE table1;
TABLE table2;
double gettime() {
struct timeval t;
gettimeofday(&t, NULL);
return t.tv_sec+t.tv_usec*1e-6;
}
unsigned int gettime_usec() {
struct timeval t;
gettimeofday(&t, NULL);
return t.tv_sec*1e+6+t.tv_usec;
}
void usage() {
fprintf(stderr,"\n");
fprintf(stderr,"Usage: table-data-gen [option]\n");
fprintf(stderr, "\nOptions:\n");
fprintf(stderr, " --help,-h print this message\n");
fprintf(stderr, " --verbose,-v basic verbosity level\n");
fprintf(stderr, "\nOther:\n");
fprintf(stderr, " --export,-e <data file> export data file\n");
fprintf(stderr, " --size1 <number> specify the size of 1st table\n");
fprintf(stderr, " --size2 <number> specify the size of 2nd table\n");
fprintf(stderr, " --k,-k <float number> specify the distribution curve (default: 0)\n");
fprintf(stderr, " --dist,-d <number> specify the distribution (default: 0)\n");
fprintf(stderr, " 0 - unified distribution\n");
fprintf(stderr, " 1 - power law distribution\n");
}
void print_conf() {
fprintf(stderr, "\nCONFIGURATION:\n");
if (config.data_file) {
fprintf(stderr, "- Data file: %s\n", config.data_file);
}
if (config.verbose) fprintf(stderr, "- verbose mode\n");
}
void init_conf() {
config.dist = 0;
config.k = -0.5;
config.verbose = false;
config.data_file = NULL;
table1.size = 10;
table2.size = 10;
}
int parse_arguments(int argc, char** argv) {
int i = 1;
if ( argc<2 ) {
usage();
return 0;
}
while ( i<argc ) {
if ( strcmp(argv[i], "-h")==0 || strcmp(argv[i], "--help")==0 ) {
usage();
return 0;
}
else if ( strcmp(argv[i], "--size1")==0 ) {
++i;
table1.size = atoi(argv[i]);
}
else if ( strcmp(argv[i], "--size2")==0 ) {
++i;
table2.size = atoi(argv[i]);
}
else if ( strcmp(argv[i], "-v")==0 || strcmp(argv[i], "--verbose")==0 ) {
VERBOSE = config.verbose = 1;
}
else if ( strcmp(argv[i], "-e")==0 || strcmp(argv[i], "--export")==0 ) {
++i;
if (i==argc) {
fprintf(stderr, "Data file name missing.\n");
}
config.data_file = argv[i];
}
++i;
}
return 1;
}
inline int unified_dist(int l, int h) {
srand( gettime_usec() );
return rand() % (h-l) + l;
}
inline int power_law(int l, int h, float k) {
srand( gettime_usec() );
double value = ( pow(h, k+1) - pow(l, k+1) ) * ( (double)rand() / RAND_MAX) + pow(l, k+1);
return pow(value, 1.0/(k+1));
}
void gen_table_data() {
short start = 1;
short curr = 1;
short end = 1;
table1.key = new short [table1.size];
table1.value = new short [table1.size];
table2.key = new short [table2.size];
table2.value = new short [table2.size];
// generate relational table 1 (ordered key)
for (int i=0; i<table1.size; ++i) {
int increment = rand()%3 + 1;
curr = curr + increment;
table1.key[i] = curr;
table1.value[i] = rand() % KEY_RANGE + 1;
}
end = curr + 1;
// generate relational table 2
for (int i=0; i<table2.size; ++i) {
table2.key[i] = unified_dist(start, end); // can switch to pow-law distribution
table2.value[i] = rand() % KEY_RANGE + 1;
}
}
void dump_data() {
// dump relational table 1 (ordered key)
fprintf(fp, "%d\n", table1.size);
for (int i=0; i<table1.size; ++i) {
fprintf(fp, "%d %d\n", table1.key[i], table1.value[i]);
}
// dump relational table 2
fprintf(fp, "%d\n", table2.size);
for (int i=0; i<table2.size; ++i) {
fprintf(fp, "%d %d\n", table2.key[i], table2.value[i]);
}
}
void destroy_table_data() {
delete [] table1.key;
delete [] table1.value;
delete [] table2.key;
delete [] table2.value;
}
int main(int argc, char *argv[])
{
init_conf();
if ( !parse_arguments(argc, argv) ) return 0;
if (VERBOSE)
print_conf();
if ( config.data_file!=NULL ) {
fp = fopen(config.data_file, "w");
if ( fp==NULL ) {
fprintf(stderr, "Error: NULL file pointer.\n");
return 1;
}
}
else
fp = stdout;
double start_time, end_time;
start_time = gettime();
gen_table_data();
dump_data();
end_time = gettime();
if (VERBOSE)
fprintf(stderr, "Import graph:\t\t%lf\n",end_time-start_time);
return 0;
}
|
e2dcac08bf4118b07ab344314d5f53497b25ab4c
|
6738808ec10e41049d2bae752949469b5651f38f
|
/src/App/CommandFactory.cpp
|
46d088b6afebe06ea6f2ab2f809f733cea320611
|
[] |
no_license
|
22116/oslabskhpi
|
a746c6aeb0a06211d5403e63caa1cbfc3c766d71
|
ff005282e4c0989f9441defe7149bd2eb84c86df
|
refs/heads/master
| 2020-04-20T00:58:49.104718
| 2019-01-25T12:42:45
| 2019-01-25T12:42:45
| 168,533,393
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,372
|
cpp
|
CommandFactory.cpp
|
//
// Created by victor on 1/9/19.
//
#include <string.h>
#include "CommandFactory.h"
#include "Commands/EncodingSwitcher.h"
#include "Commands/SubstringSearcher.h"
#include "Exception/InvalidCommandIdentifierException.h"
#include "Commands/SubstringReplacer.h"
#ifdef __unix__
#include "../Core/Directory/Strategy/UnixStrategy.h"
#endif
#ifdef OS_Windows
#include "../Core/Directory/Strategy/WinStrategy.h"
#endif
ICommand* CommandFactory::create(std::string id) {
std::string list;
for (auto &command : this->getCommands()) {
list += " " + command->getId();
if (command->getId() == id) {
return command;
}
}
throw InvalidEncodingException(
"Invalid command identifier.\nAvailable commands:" + list
);
}
std::vector<ICommand*> CommandFactory::getCommands() {
std::vector<ICommand*> list;
IStrategy* strategy;
#ifdef __unix__
strategy = new UnixStrategy;
#endif
#ifdef OS_Windows
strategy = new WinStrategy;
#endif
list.push_back(new EncodingSwitcher(new FileReader, new FileWriter, new EncodingFacade));
list.push_back(new SubstringSearcher(new FileReader, new Explorer(strategy), new Searcher));
list.push_back(new SubstringReplacer(
new FileReader, new FileWriter, new Explorer(strategy), new Searcher)
);
return list;
}
|
8456039247a3863f5794f73d982b01ae88cb0eb3
|
6e00115571a7615cea6bed9b9821db6e4f4caf3b
|
/Source/MagicBattleSoccer/Private/Traps/MagicBattleSoccerTrap.cpp
|
0baf4a1966e892ed4fe01f4dd765ea061c488127
|
[] |
no_license
|
NoCodeBugsFree/UBattleSoccerPrototype
|
92d115edb2b95cb4b3aaa6d23a11d482db0acab5
|
9e7aba8cf17ce5b3c74d0869b70d1e7884d55bf5
|
refs/heads/master
| 2023-01-08T13:42:04.419213
| 2020-10-27T21:56:15
| 2020-10-27T21:56:15
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 294
|
cpp
|
MagicBattleSoccerTrap.cpp
|
#include "MagicBattleSoccerTrap.h"
#include "MagicBattleSoccer.h"
AMagicBattleSoccerTrap::AMagicBattleSoccerTrap(const class FObjectInitializer& OI)
: Super(OI)
{
bReplicates = true;
bNetUseOwnerRelevancy = true;
this->SetActorTickEnabled(true);
PrimaryActorTick.bCanEverTick = true;
}
|
03941350b99b670ce3ceef2ab1ae60249b8e098a
|
48c4ae1f8eae90082432273028302c0a977af6c0
|
/include/q0349_intersection.hpp
|
31eaa1610ec25d6a71905197ffc556673f3398ac
|
[] |
no_license
|
hahahaMing/cmake_demo
|
b4c7f36ba270f9dfcbf9b4b7c47e5ffa885c4574
|
e435e31b73ceda818a0378dc767ca3b3c00fc6e2
|
refs/heads/master
| 2021-09-29T03:00:35.275055
| 2021-09-26T06:28:30
| 2021-09-26T06:28:30
| 205,612,148
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,217
|
hpp
|
q0349_intersection.hpp
|
//
// Created by ming on 2020/11/2.
//
#ifndef CMAKETEST_Q0349_INTERSECTION_HPP
#define CMAKETEST_Q0349_INTERSECTION_HPP
#endif //CMAKETEST_Q0349_INTERSECTION_HPP
#include"tools.hpp"
class Solution {
public:
std::vector<int> intersection(std::vector<int> &nums1, std::vector<int> &nums2) {
int l1 = nums1.size(), l2 = nums2.size();
// std::vector<int> sn, ln;
// if (l1 < l2) {
// sn = nums1;
// ln = nums2;
// } else {
// sn = nums2;
// ln = nums1;
// std::swap(l1, l2);
// }
if (l1 > l2) {
std::swap(nums1, nums2);
std::swap(l1, l2);
}
std::vector<int> rst;
std::unordered_set<int> rcd;
for (int i = 0; i < l1; ++i) {
if (rcd.find(nums1[i]) == rcd.end())rcd.emplace(nums1[i]);
}
for (int i = 0; i < l2; ++i) {
if (rcd.find(nums2[i]) != rcd.end()){
rst.push_back(nums2[i]);
rcd.erase(rcd.find(nums2[i]));
}
if (rst.size() == rcd.size())break;
}
return rst;
}
void test() {
std::cout << "test start" << std::endl;
}
};
|
5fae50bad18a09b83e7d51b8d0274974d0613234
|
28999c5603d9e9e3db378a37169dccc17ea51f43
|
/code/render/visibility/systems/boxsystemjob.cc
|
1bfb601364e7fd89c3b77a7645ece2fc966b700f
|
[
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
gscept/nebula
|
e973c2b950da93ca30e0432fc6bd6dd6f6a59bdd
|
4dca6f2a8f1deb2020f1b7d179dd29e1ed45a5fe
|
refs/heads/master
| 2023-08-25T06:39:53.517007
| 2023-08-24T15:30:57
| 2023-08-24T15:30:57
| 164,856,783
| 603
| 36
|
NOASSERTION
| 2023-09-12T22:22:41
| 2019-01-09T12:14:20
|
C++
|
UTF-8
|
C++
| false
| false
| 318
|
cc
|
boxsystemjob.cc
|
//------------------------------------------------------------------------------
// boxsystemjob.cc
// (C) 2018-2020 Individual contributors, see AUTHORS file
//------------------------------------------------------------------------------
#include "boxsystem.h"
namespace Visibility
{
} // namespace Visibility
|
c9d9b05f60654e55926705d5811ec51f35263523
|
798182bfc3f06f321f43c1954b35ee702ae361d7
|
/TCPMSNServer/src/Login.cpp
|
b8a77e3045ab820164cf6d6c20043e1ed9bb4209
|
[] |
no_license
|
tomersaporta/Final-Project-Network-Programming-Lab
|
edbf63e5fdfe40357ccf3f5469b0fdb71c9b9c85
|
b81c88ec238a890819123757806a4a1f00584fe6
|
refs/heads/master
| 2021-05-16T01:15:59.795581
| 2017-10-15T22:51:08
| 2017-10-15T22:51:08
| 107,049,884
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,758
|
cpp
|
Login.cpp
|
/*
* Login.cpp
*
* Created on: Aug 27, 2017
* Author: user
*/
#include "Login.h"
namespace networkingLab {
networkingLab::Login::Login(LoginHandler* handler) {
this->stop = false;
this->newPeer = NULL;
this->init_first = true;
this->init_second = false;
this->path = "password3.txt";
this->handler = handler;
this->tcpListener = new MultipleTCPSocketsListener();
this->data = NULL;
this->fakeSocket = NULL;
loadData(path);
}
void networkingLab::Login::handlePeer(TCPSocket* peer) {
char * buff;
int cmdNet, cmd, len;
int rec;
string user_name = "", password = "";
bool success = true;
rec = peer->read((char*) &cmdNet, 4);
if (rec <= 0)
success = false;
cmd = ntohl(cmdNet);
if (success) {
switch (cmd) {
case LOG_IN: {
peer->read((char *) &len, sizeof(len));
len = ntohl(len);
buff = new char[len];
peer->read(buff, len);
//get the user name and password from client command
int i;
bool readUser = false;
for (i = 0; i < len; i++) {
if (buff[i] == ':')
readUser = true;
else if (!readUser)
user_name += buff[i];
else
password += buff[i];
}
//search the password
cout << "get from user: " << user_name << " " << password << endl;
//check hash password
stringstream str;
hash<string> hs;
size_t hash = hs(password);
string hashedPass;
str << hash;
str >> hashedPass;
auto it = userMap.find(user_name);
if (it != userMap.end()) {
cout << "user name: " << user_name << " Succeed!" << endl;
if (it->second.compare(hashedPass) == 0) { // check password
this->handler->handleLoginPeer(peer, user_name);
this->tcpListener->removeSocket(peer);
cout << "user name password: " << password << " Succeed!"
<< endl;
int cmdNet = htonl(LOG_IN_SUCCEESED);
peer->write((char*) &cmdNet, 4);
break;
} else {
int cmdNet = htonl(LOG_IN_REFUSED_PASSWORD);
peer->write((char*) &cmdNet, 4);
}
}
int cmdNet = htonl(LOG_IN_REFUSED_USERNAME);
peer->write((char*) &cmdNet, 4);
break;
}
case INTERRUPT_SOCKET_LOGIN: {
//cout << " INTERRUPT_SOCKET- LOGIN" << endl;
this->tcpListener->addSocket(this->newPeer);
cout << "Login: " << peer->getRemotedSocketIP() << ""
<< newPeer->getRemotedSocketPort() << endl;
break;
}
case REGISTER: {
peer->read((char *) &len, sizeof(len));
len = ntohl(len);
buff = new char[len];
peer->read(buff, len);
//get the user name and password from client command
int i;
bool readUser = false;
for (i = 0; i < len; i++) {
if (buff[i] == ':')
readUser = true;
else if (!readUser)
user_name += buff[i];
else
password += buff[i];
}
cout << "get from user: " << user_name << " " << password << endl;
cout << "Register Succeeded!" << endl;
// hash password
stringstream str;
hash<string> hs;
size_t hash = hs(password);
string hashedPass;
str << hash;
str >> hashedPass;
this->userMap[user_name] = hashedPass;
int cmdNet = htonl(REGISTER_SUCCEESED);
peer->write((char*) &cmdNet, 4);
this->handler->handleLoginPeer(peer, user_name);
this->tcpListener->removeSocket(peer);
break;
}
case INTERRUPT_SOCKET: {
cout << "INTERRUPT_SOCKET" << endl;
break;
}
default: {
break;
}
}
}
}
void Login::addPeer(TCPSocket* peer) {
if (this->init_first) {
this->tcpListener->addSocket(peer);
this->init_first = false;
this->start();
this->init_second = true;
} else if (this->init_second) {
string empty;
this->handler->handleLoginPeer(peer, empty);
this->init_second = false;
} else {
this->newPeer = peer;
//Interrupt the fake socket
this->interruptFakeSocket();
}
}
void Login::close() {
saveData();
this->stop = true;
}
void Login::run() {
TCPSocket * aPeer;
while (!stop) {
//Blocking call
aPeer = this->tcpListener->listenToSocket();
this->handlePeer(aPeer);
}
}
void Login::loadData(string path) {
ssize_t ret_in;
this->data = new File(this->path, O_RDONLY);
//read from file to buffer
while ((ret_in = read(this->data->socket_fd, &buffer, sizeof(buffer))) > 0) {
cout << "reading data..." << endl;
}
int i = 0;
std::vector<char*> v;
char* chars_array = strtok(this->buffer, "\n");
while (chars_array) {
v.push_back(chars_array);
chars_array = strtok(NULL, "\n");
}
char*data[v.size() * 2];
for (size_t n = 0; n < v.size(); ++n) {
char* subchar_array = strtok(v[n], " ");
while (subchar_array) {
data[i] = subchar_array;
i++;
subchar_array = strtok(NULL, " ");
}
}
//cout << v.size() << endl;
for (size_t n = 0; n < v.size() * 2; n += 2) {
this->userMap[data[n]] = data[n + 1];
}
// for (auto it = userMap.begin(); it != userMap.end(); ++it) {
// std::cout << it->first << "," << it->second << "\n";
// }
}
void Login::interruptFakeSocket() {
int cmd = htonl(INTERRUPT_SOCKET_LOGIN);
int rec = this->fakeSocket->write((char*) &cmd, 4);
if (rec < 4) {
perror("ERROR INTERRUPT_SOCKET Failed");
}
}
void Login::initFakeSocket() {
this->fakeSocket = new TCPSocket("127.0.0.1", MSNGR_PORT);
}
void Login::startLogin() {
cout << "Login started" << endl;
//init the demo peer
this->initFakeSocket();
}
void Login::saveData() {
File * saveFile = new File(this->path, O_RDWR | O_CREAT | O_TRUNC);
for (map<string, string>::const_iterator loop = this->userMap.begin();
loop != this->userMap.end(); ++loop) {
string s = loop->first + " " + loop->second + "\n";
if (saveFile->write(s.data(), s.length()) < 0) {
cout << "cant write to file " << this->path << endl;
}
}
cout << "file saved: " << this->path << endl;
saveFile->close();
}
networkingLab::Login::~Login() {
this->stop = true;
}
}
|
27f4b9815d4f4dfd18a79b271d133563efb19d77
|
b05ee0ef4aa4df4ec04d276b525450a8632df588
|
/boj/13232.cc
|
01d7b922a90e18cf8cfaf0ab6f0fdb84808ff980
|
[] |
no_license
|
dongwoo338/algo
|
d300101a71d212bbb50effb0213af0facee6a2d7
|
fac72b49b08292374b8e96f2d41d8bb1f2404dac
|
refs/heads/master
| 2023-02-21T13:55:51.815259
| 2021-01-16T12:58:42
| 2021-01-16T12:58:42
| 306,344,271
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 847
|
cc
|
13232.cc
|
#include<bits/stdc++.h>
using namespace std;
int n, m;
const int N = 5005;
bool vis[N];
vector<vector<int>>g;
vector<vector<int>>ng;
stack<int>st;
void dfs(int u) {
vis[u] = 1;
for (int v : g[u]) {
if (!vis[v])dfs(v);
}
st.push(u);
}
int dfs2(int u) {
int ret = 1;
vis[u] = 0;
for (int v : ng[u]) {
if(vis[v])ret += dfs2(v);
}
return ret;
}
int main() {
ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
cin >> n >> m;
g.resize(n + 1);
ng.resize(n + 1);
for (int u, v; m--;) {
cin >> u >> v;
g[u].push_back(v);
ng[v].push_back(u);
}
for (int i = 1; i <= n; i++) {
if (!vis[i])dfs(i);
}
int ans = 0;
while (st.size()) {
int u = st.top(); st.pop();
if (vis[u])ans = max(ans, dfs2(u));
}
cout << ans;
}
|
3d020dfaad1c1ed9158677e2a966011d9c599e6b
|
c07797934115e827efe18190efb765825ddbeec8
|
/playerbot/strategy/deathknight/DKTriggers.h
|
816f0e3d8f07c513b7744bfbb6cc3bef0aeb2bfb
|
[] |
no_license
|
conan513/mangosbot-bots
|
5382d9939a0a5caedb91fa0f11cd773dd554f3c4
|
676ca668eae7c0814547b4a09f961a8a9eb214f8
|
refs/heads/master
| 2023-06-27T06:28:31.431732
| 2023-06-20T16:27:16
| 2023-06-20T16:27:16
| 153,980,213
| 7
| 3
| null | 2018-10-21T06:32:52
| 2018-10-21T06:32:52
| null |
UTF-8
|
C++
| false
| false
| 3,049
|
h
|
DKTriggers.h
|
#pragma once
#include "../triggers/GenericTriggers.h"
namespace ai
{
BUFF_TRIGGER(HornOfWinterTrigger, "horn of winter");
BUFF_TRIGGER(BoneShieldTrigger, "bone shield");
BUFF_TRIGGER(ImprovedIcyTalonsTrigger, "improved icy talons");
DEBUFF_TRIGGER(PlagueStrikeDebuffTrigger, "plague strike");
DEBUFF_TRIGGER(IcyTouchDebuffTrigger, "icy touch");
class PlagueStrikeDebuffOnAttackerTrigger : public DebuffOnAttackerTrigger
{
public:
PlagueStrikeDebuffOnAttackerTrigger(PlayerbotAI* ai) : DebuffOnAttackerTrigger(ai, "plague strike") {}
};
class IcyTouchDebuffOnAttackerTrigger : public DebuffOnAttackerTrigger
{
public:
IcyTouchDebuffOnAttackerTrigger(PlayerbotAI* ai) : DebuffOnAttackerTrigger(ai, "icy touch") {}
};
class DKPresenceTrigger : public BuffTrigger {
public:
DKPresenceTrigger(PlayerbotAI* ai) : BuffTrigger(ai, "blood presence") {}
virtual bool IsActive();
};
class BloodTapTrigger : public BuffTrigger {
public:
BloodTapTrigger(PlayerbotAI* ai) : BuffTrigger(ai, "blood tap") {}
};
class RaiseDeadTrigger : public BuffTrigger {
public:
RaiseDeadTrigger(PlayerbotAI* ai) : BuffTrigger(ai, "raise dead") {}
};
class RuneStrikeTrigger : public SpellCanBeCastTrigger {
public:
RuneStrikeTrigger(PlayerbotAI* ai) : SpellCanBeCastTrigger(ai, "rune strike") {}
};
class DeathCoilTrigger : public SpellCanBeCastTrigger {
public:
DeathCoilTrigger(PlayerbotAI* ai) : SpellCanBeCastTrigger(ai, "death coil") {}
};
class PestilenceTrigger : public DebuffTrigger {
public:
PestilenceTrigger(PlayerbotAI* ai) : DebuffTrigger(ai, "pestilence") {}
};
class BloodStrikeTrigger : public DebuffTrigger {
public:
BloodStrikeTrigger(PlayerbotAI* ai) : DebuffTrigger(ai, "blood strike") {}
};
class HowlingBlastTrigger : public DebuffTrigger {
public:
HowlingBlastTrigger(PlayerbotAI* ai) : DebuffTrigger(ai, "howling blast") {}
};
class MindFreezeInterruptSpellTrigger : public InterruptSpellTrigger
{
public:
MindFreezeInterruptSpellTrigger(PlayerbotAI* ai) : InterruptSpellTrigger(ai, "mind freeze") {}
};
class StrangulateInterruptSpellTrigger : public InterruptSpellTrigger
{
public:
StrangulateInterruptSpellTrigger(PlayerbotAI* ai) : InterruptSpellTrigger(ai, "strangulate") {}
};
class KillingMachineTrigger : public BoostTrigger
{
public:
KillingMachineTrigger(PlayerbotAI* ai) : BoostTrigger(ai, "killing machine") {}
};
class MindFreezeOnEnemyHealerTrigger : public InterruptEnemyHealerTrigger
{
public:
MindFreezeOnEnemyHealerTrigger(PlayerbotAI* ai) : InterruptEnemyHealerTrigger(ai, "mind freeze") {}
};
class ChainsOfIceSnareTrigger : public SnareTargetTrigger
{
public:
ChainsOfIceSnareTrigger(PlayerbotAI* ai) : SnareTargetTrigger(ai, "chains of ice") {}
};
class StrangulateOnEnemyHealerTrigger : public InterruptEnemyHealerTrigger
{
public:
StrangulateOnEnemyHealerTrigger(PlayerbotAI* ai) : InterruptEnemyHealerTrigger(ai, "strangulate") {}
};
}
|
61690d190001d915e6cc3669872cf8c8ff076770
|
6b40e9dccf2edc767c44df3acd9b626fcd586b4d
|
/NT/multimedia/directx/dinput/dicfgddk/cbitmap_stub.cpp
|
0999ec7281c9ad35f95ebf1b6a2a68f7db7e8f9a
|
[] |
no_license
|
jjzhang166/WinNT5_src_20201004
|
712894fcf94fb82c49e5cd09d719da00740e0436
|
b2db264153b80fbb91ef5fc9f57b387e223dbfc2
|
refs/heads/Win2K3
| 2023-08-12T01:31:59.670176
| 2021-10-14T15:14:37
| 2021-10-14T15:14:37
| 586,134,273
| 1
| 0
| null | 2023-01-07T03:47:45
| 2023-01-07T03:47:44
| null |
UTF-8
|
C++
| false
| false
| 70
|
cpp
|
cbitmap_stub.cpp
|
#include "common_stub.hpp"
#include "..\\..\\diconfig\\cbitmap.cpp"
|
3e8be1b526884ac1e9ee9bf35075ad0ac84edcc0
|
e966f01ccba42e397b6e99eda02334fbd8a08ea2
|
/nist/nist/stl/vector1.cpp
|
a216d7812fe101c1bdbfb9e92e662df753c7bbde
|
[] |
no_license
|
bhawneshdipu/college-code
|
382f849ee8e19b5e37e2ef55d9213dc27807a46c
|
5d9f21ccd6510d6928165f45d2d0e6eadb2ec268
|
refs/heads/master
| 2023-08-04T00:27:27.711718
| 2021-09-08T21:35:27
| 2021-09-08T21:35:27
| 43,536,991
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,490
|
cpp
|
vector1.cpp
|
#include<iostream>
#include<vector>
#include<cstdio>
using namespace std;
class Object{
public:
string s;
int n;
bool b;
};
int main(){
int n;
printf("Enter Length of Vector\n");
scanf("%d",&n);
vector <int> vi; // vector of integers
vector <string> vs;// vector of strings
vector < vector < int > > vvi;//vector of (vector of integers)
vector < Object > vo; // vector of object
for(int i=0;i<n;i++){
int a;
printf("enter integer \n");
scanf("%d",&a);
vi.push_back(a);
}
for(int i=0;i<n;i++){
string a;
printf("enter string \n");
cin>>a;
vs.push_back(a);
}
for(int i=0;i<n;i++){
vector <int> a;int m;
printf("enter length of vector\n");
scanf("%d",&m);
for(int j=0;j<m;j++){
int tt;
printf("enter integer \n");
scanf("%d",&tt);
a.push_back(tt);
}
vvi.push_back(a);
}
for(int i=0;i<n;i++){
Object a;
printf("enter string number boolean \n");
cin>>a.s>>a.n>>a.b;
vo.push_back(a);
}
vector <int> :: iterator it;
vector <string> :: iterator is;
vector < vector <int> > :: iterator iit;
vector <Object> :: iterator ot;
for(it=vi.begin();it!=vi.end();++it){
cout<<*it<<endl;
}
for(is=vs.begin();is!=vs.end();++is){
cout<<*is<<endl;
}
for(iit=vvi.begin();iit!=vvi.end();++iit){
vector <int> v=*iit;
for(it=v.begin();it!=v.end();it++)
cout<<*it<<" ";
cout<<endl;
}
for(ot=vo.begin();ot!=vo.end();ot++){
Object o=*ot;
cout<<o.s<<" "<<o.n<<" "<<o.b<<endl;
}
}
|
b6fae4b40324cfe7e069f0470062779d5cb286a9
|
49f6e2a1fff5a4e41081133965b3933d4efc82e0
|
/puzzle.cpp
|
7feb9ea337029bf77503544cacedda51dd771f81
|
[] |
no_license
|
ArjunBhushan-zz/Sudoku-Solving-XY-Robot
|
21520119e5ae8088fd17c91b9a2c665b53224cb3
|
7189f3bc98fdc950ec2629c184a850eccf096655
|
refs/heads/master
| 2021-09-08T00:18:28.359947
| 2018-03-04T02:54:13
| 2018-03-04T02:54:13
| 116,354,629
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 17,824
|
cpp
|
puzzle.cpp
|
#include<opencv2/opencv.hpp>
#include <opencv2/imgcodecs.hpp>
#include<iostream>
#include <opencv/ml.h>
#include <opencv/highgui.h>
#include "digitrecognizer.h"
#include <sstream>
using namespace std;
using namespace cv;
using namespace cv::ml;
Mat thresh(Mat img)
{
cvtColor(img,img,CV_BGR2GRAY);
Mat img_t=Mat::zeros(img.size(),CV_8UC3);
adaptiveThreshold(img,img_t,255,ADAPTIVE_THRESH_MEAN_C,THRESH_BINARY_INV,5,10);
return img_t;
}
Mat grid_extract(Mat img)
{
int index;
double max;
Mat grid;
grid=Mat::zeros(img.size(),CV_8UC1);
vector<vector<Point> > contour;
vector<Vec4i> h;
vector<Point> req;
findContours(img,contour,h,CV_RETR_TREE,CV_CHAIN_APPROX_SIMPLE,Point(0,0));
max=contourArea(contour[0]);
for(int i=0;i<contour.size();i++)
{
double temp;
temp=contourArea(contour[i]);
if(max<temp)
{
max=temp;
index=i;
req=contour[i];
}
}
drawContours(grid,contour,index,Scalar(255,255,255),CV_FILLED,8,h);
//namedWindow("Grid",0);
//imshow("Grid",grid);
//waitKey(0);
return grid(boundingRect(req));
}
//Function to remove the lines from the grid(To seperate out digits from the grid)
Mat hough(Mat img)
{
vector<Vec4i> lines;
HoughLinesP(img,lines,1,CV_PI/180,100,30,10);
for(int i=0; i<lines.size();i++)
{
Vec4i l=lines[i];
line(img,Point(l[0],l[1]),Point(l[2],l[3]),Scalar(0,0,0),10,CV_AA);
}
//imshow("Digits",img);
//waitKey(0);
return img;
}
void digit_extract(Mat img)
{
char key = 0;
Mat digit;
vector<vector<Point> > contour;
vector<Vec4i> h;
findContours(img,contour,h,CV_RETR_TREE,CV_CHAIN_APPROX_SIMPLE,Point(0,0));
for(int i=0;i<81;i++)
{
vector<Point> temp;
temp=contour[i];
img(boundingRect(temp)).copyTo(digit);
namedWindow("Digit",0);
std::ostringstream name;
name << "photo" << i << ".png";
cv::imwrite(name.str(), digit);
/*
imshow("Digit",digit);
waitKey(500);
*/
}
}
Mat DigitRecognizer::preprocessImage(Mat img)
{
int rowTop=-1, rowBottom=-1, colLeft=-1, colRight=-1;
Mat temp;
int thresholdBottom = 50;
int thresholdTop = 50;
int thresholdLeft = 50;
int thresholdRight = 50;
int center = img.rows/2;
for(int i=center;i<img.rows;i++)
{
if(rowBottom==-1)
{
temp = img.row(i);
IplImage stub = temp;
if(cvSum(&stub).val[0] < thresholdBottom || i==img.rows-1)
rowBottom = i;
}
if(rowTop==-1)
{
temp = img.row(img.rows-i);
IplImage stub = temp;
if(cvSum(&stub).val[0] < thresholdTop || i==img.rows-1)
rowTop = img.rows-i;
}
if(colRight==-1)
{
temp = img.col(i);
IplImage stub = temp;
if(cvSum(&stub).val[0] < thresholdRight|| i==img.cols-1)
colRight = i;
}
if(colLeft==-1)
{
temp = img.col(img.cols-i);
IplImage stub = temp;
if(cvSum(&stub).val[0] < thresholdLeft|| i==img.cols-1)
colLeft = img.cols-i;
}
}
Mat newImg;
newImg = newImg.zeros(img.rows, img.cols, CV_8UC1);
int startAtX = (newImg.cols/2)-(colRight-colLeft)/2;
int startAtY = (newImg.rows/2)-(rowBottom-rowTop)/2;
for(int y=startAtY;y<(newImg.rows/2)+(rowBottom-rowTop)/2;y++)
{
uchar *ptr = newImg.ptr<uchar>(y);
for(int x=startAtX;x<(newImg.cols/2)+(colRight-colLeft)/2;x++)
{
ptr[x] = img.at<uchar>(rowTop+(y-startAtY),colLeft+(x-startAtX));
}
}
Mat cloneImg = Mat(numRows, numCols, CV_8UC1);
resize(newImg, cloneImg, Size(numCols, numRows));
// Now fill along the borders
for(int i=0;i<cloneImg.rows;i++)
{
floodFill(cloneImg, cvPoint(0, i), cvScalar(0,0,0));
floodFill(cloneImg, cvPoint(cloneImg.cols-1, i), cvScalar(0,0,0));
floodFill(cloneImg, cvPoint(i, 0), cvScalar(0));
floodFill(cloneImg, cvPoint(i, cloneImg.rows-1), cvScalar(0));
}
cloneImg = cloneImg.reshape(1, 1);
return cloneImg;
}
void drawLine(Vec2f line, Mat &img, Scalar rgb = CV_RGB(0,0,255)) //BASED ON HOUGH TRANSFORM DRAWS LINE FOR EVERY POINT
{
if(line[1]!=0)
{
float m = -1/tan(line[1]);
float c = line[0]/sin(line[1]);
cv::line(img, Point(0, c), Point(img.size().width, m*img.size().width+c), rgb);
}
else
{
cv::line(img, Point(line[0], 0), Point(line[0], img.size().height), rgb);
}
}
void mergeRelatedLines(vector<Vec2f> *lines, Mat &img)// averages nearby lines, lines within a certain distance will merge together
{
vector<Vec2f>::iterator current; // helps traverse the array list, every element in array has 2 things: rho & theta (normal form of line)
for(current=lines->begin();current!=lines->end();current++){ //
if ((*current)[0]==0 && (*current)[1]==-100) continue; // mark lines that have been fused (set rho = 0 and theta = -100) so will skip merged lines
float p1 = (*current)[0]; // store rho
float theta1 = (*current)[1]; // store theta
Point pt1current, pt2current; // finds 2 points on the line FOR LINE CURRENT
if (theta1>CV_PI*45/180 && theta1<CV_PI*135/180){ // if the line is horizontal, finds a point at extreme left and extreme right
pt1current.x=0;
pt1current.y = p1/sin(theta1);
pt2current.x=img.size().width;
pt2current.y=-pt2current.x/tan(theta1) + p1/sin(theta1);
} else { // if line is vertical, finds a point at top and bottom
pt1current.y=0;
pt1current.x=p1/cos(theta1);
pt2current.y=img.size().height;
pt2current.x=-pt2current.y/tan(theta1) + p1/cos(theta1);
}
vector<Vec2f>::iterator pos;
for (pos=lines->begin();pos!=lines->end();pos++){ // loops to compare every line with every other line;
if (*current==*pos) continue; // if current = pos, the line is the same and there is no point fusing the same line
if (fabs((*pos)[0]-(*current)[0])<20 && fabs((*pos)[1]-(*current)[1])<CV_PI*10/180) { // check if lines are w/in certain distance
float p = (*pos)[0]; // store rho for line pos
float theta = (*pos)[1]; // store theta for line pos
Point pt1, pt2;
if ((*pos)[1]>CV_PI*45/180 && (*pos)[1]<CV_PI*135/180) { // find 2 points on the line pos
pt1.x=0; // pos is a horizontal line
pt1.y = p/sin(theta);
pt2.x=img.size().width;
pt2.y=-pt2.x/tan(theta) + p/sin(theta);
} else { // pos is a vertical line
pt1.y=0;
pt1.x=p/cos(theta);
pt2.y=img.size().height;
pt2.x=-pt2.y/tan(theta) + p/cos(theta);
}
if(((double)(pt1.x-pt1current.x)*(pt1.x-pt1current.x) + (pt1.y-pt1current.y)*(pt1.y-pt1current.y)<64*64) &&
((double)(pt2.x-pt2current.x)*(pt2.x-pt2current.x) + (pt2.y-pt2current.y)*(pt2.y-pt2current.y)<64*64)) {
// if the endpoints of pos and current are close, FUSION HA
(*current)[0] = ((*current)[0]+(*pos)[0])/2; // MERGE THE 2 LINES (X COORD)
(*current)[1] = ((*current)[1]+(*pos)[1])/2; // MERGE THE 2 LINES (Y COORD)
(*pos)[0]=0;
(*pos)[1]=-100;
}
}
}
}
}
int main(int, char**) {
// JASMINE's CODE TO TAKE A PHOTO
VideoCapture cap(0);
if(!cap.isOpened()) // check if we succeeded
return -1;
Mat sudokuB;
cap >> sudokuB; //
char key = 0;
while (key != 27 && cap.isOpened()) {
bool Frame = cap.read(sudokuB);
if (!Frame || sudokuB.empty()) {
cout << "error: frame not read from webcam\n";
break;
}
namedWindow("sudokuB", CV_WINDOW_NORMAL);
imshow("imgOriginal", sudokuB);
key = waitKey(1);
}
imwrite("sudoku.jpg", sudokuB);// saves the photo as a jpeg.
// END OF JASMINE's CODE
int size = 16 * 16;
Mat sudoku = imread("sudoku.jpg", 0); // loads a static image for detecting a photo
Mat original = sudoku.clone(); // clones the sudoku (original photo)
Mat outerBox = Mat(sudoku.size(), CV_8UC1); // blank image of same size, will hold the actual outer box of the photo
GaussianBlur(sudoku, sudoku, Size(11,11), 0); // blurs the image to smooth out the noise and makes extracting grid lines easier
adaptiveThreshold(sudoku, outerBox, 255, ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY, 5, 2); // thresholds image; adaptive is good b/c image can have varying levels of light
// calculates mean over 5 x 5 box, then -2 from mean the level for every pixel
bitwise_not(outerBox, outerBox); // inverts the image (borders are white + other noise)
Mat kernel = (Mat_<uchar>(3,3) << 0,1,0,1,1,1,0,1,0);
dilate(outerBox, outerBox, kernel);
// dilate the image again to fill in "cracks" between lines (here a + shaped kernel matrix is used)
// imwrite("sudokuA.jpg", outerBox);
int count = 0;
int max=-1;
Point maxPt;
for(int y=0;y<outerBox.size().height;y++)
{
uchar *row = outerBox.ptr(y);
for(int x=0;x<outerBox.size().width;x++){
if(row[x]>=128){ // ensures only white parts are filtered{
int area = floodFill(outerBox, Point(x,y), CV_RGB(0,0,64)); // returns a bounding rectangle of pixels it filled
if(area>max)
{
maxPt = Point(x,y); //since biggest blob is puzzle, will have biggest bounding box (saves location where fill done)
max = area;
}
}
}
}
floodFill(outerBox, maxPt, CV_RGB(255,255,255));//fill the blob with the max area with white
for(int y=0;y<outerBox.size().height;y++) // turn the other blobs BLACK
{
uchar *row = outerBox.ptr(y);
for(int x=0;x<outerBox.size().width;x++)
{
if(row[x]==64 && x!=maxPt.x && y!=maxPt.y)
{
int area = floodFill(outerBox, Point(x,y), CV_RGB(0,0,0)); // if a dark gray point is encountered, makes it BLACK
}
}
}
//imwrite("thresholded.jpg", outerBox);
erode(outerBox, outerBox, kernel); // b/c image was dilated a bit it is restored a bit by eroding it
//imwrite("eroded.jpg", outerBox);
vector<Vec2f> lines;
HoughLines(outerBox, lines, 1, CV_PI/180, 200); // hough transform
mergeRelatedLines(&lines, sudoku); // MERGE RELATED LINES
for(int i=0;i<lines.size();i++)
{
drawLine(lines[i], outerBox, CV_RGB(0,0,128)); // draws line based on the hough transform to see if the lines are good enough
}
// mergeRelatedLines(&lines, sudoku); // Add this line
imwrite("sudokuA.jpg", outerBox);
// FIND EXTREME LINES
// set lines as ridiculous values to ensure the edges of the grid can be found
Vec2f topEdge = Vec2f(1000,1000);
double topYIntercept=100000, topXIntercept=0;
Vec2f bottomEdge = Vec2f(-1000,-1000);
double bottomYIntercept=0, bottomXIntercept=0;
Vec2f leftEdge = Vec2f(1000,1000);
double leftXIntercept=100000, leftYIntercept=0;
Vec2f rightEdge = Vec2f(-1000,-1000);
double rightXIntercept=0, rightYIntercept=0;
for(int i=0;i<lines.size();i++){
Vec2f current = lines[i];
float p=current[0]; // store rho
float theta=current[1]; // store theta
if(p==0 && theta== -100) continue; // if current = a merged line, skip
double xIntercept, yIntercept; // calculate x and y intercepts (where lines intersect x and y axis)
xIntercept = p/cos(theta);
yIntercept = p/(cos(theta)*sin(theta));
if (theta>CV_PI*80/180 && theta<CV_PI*100/180){ // if line is vertical
if(p<topEdge[0]) topEdge = current;
if(p>bottomEdge[0]) bottomEdge = current;
} else if (theta<CV_PI*10/180 || theta>CV_PI*170/180) {
if (xIntercept>rightXIntercept) {
rightEdge = current;
rightXIntercept = xIntercept;
} else if (xIntercept<=leftXIntercept) {
leftEdge = current;
leftXIntercept = xIntercept;
}
}
}// all lines other than vertical and horizontal are IGNORED
// just to visualize the extreme lines
drawLine(topEdge, sudoku, CV_RGB(0,0,0));
drawLine(bottomEdge, sudoku, CV_RGB(0,0,0));
drawLine(leftEdge, sudoku, CV_RGB(0,0,0));
drawLine(rightEdge, sudoku, CV_RGB(0,0,0));
// calculate intersection of these 4 lines
Point left1, left2, right1, right2, bottom1, bottom2, top1, top2;
// finds 2 points on each line, then calculates where any 2 lines intersect
// right and left edges need 'if' statements to distinguish (vertical lines) can have infinite slope (computer rip)
// if slope is incalculable, aka vertical line, calculates 'safely'
//
int height=outerBox.size().height;
int width=outerBox.size().width;
if(leftEdge[1]!=0) {
left1.x=0;
left1.y=leftEdge[0]/sin(leftEdge[1]);
left2.x=width;
left2.y=-left2.x/tan(leftEdge[1]) + left1.y;
} else {
left1.y=0;
left1.x=leftEdge[0]/cos(leftEdge[1]);
left2.y=height;
left2.x=left1.x - height*tan(leftEdge[1]);
}
if (rightEdge[1]!=0) {
right1.x=0;
right1.y=rightEdge[0]/sin(rightEdge[1]);
right2.x=width;
right2.y=-right2.x/tan(rightEdge[1]) + right1.y;
} else {
right1.y=0;
right1.x=rightEdge[0]/cos(rightEdge[1]);
right2.y=height;
right2.x=right1.x - height*tan(rightEdge[1]);
}
bottom1.x=0;
bottom1.y=bottomEdge[0]/sin(bottomEdge[1]);
bottom2.x=width;
bottom2.y=-bottom2.x/tan(bottomEdge[1]) + bottom1.y;
top1.x=0;
top1.y=topEdge[0]/sin(topEdge[1]);
top2.x=width;
top2.y=-top2.x/tan(topEdge[1]) + top1.y;
// Next, we find the intersection of these four lines
double leftA = left2.y-left1.y;
double leftB = left1.x-left2.x;
double leftC = leftA*left1.x + leftB*left1.y;
double rightA = right2.y-right1.y;
double rightB = right1.x-right2.x;
double rightC = rightA*right1.x + rightB*right1.y;
double topA = top2.y-top1.y;
double topB = top1.x-top2.x;
double topC = topA*top1.x + topB*top1.y;
double bottomA = bottom2.y-bottom1.y;
double bottomB = bottom1.x-bottom2.x;
double bottomC = bottomA*bottom1.x + bottomB*bottom1.y;
// Intersection of left and top
double detTopLeft = leftA*topB - leftB*topA;
CvPoint ptTopLeft = cvPoint((topB*leftC - leftB*topC)/detTopLeft, (leftA*topC - topA*leftC)/detTopLeft);
// Intersection of top and right
double detTopRight = rightA*topB - rightB*topA;
CvPoint ptTopRight = cvPoint((topB*rightC-rightB*topC)/detTopRight, (rightA*topC-topA*rightC)/detTopRight);
// Intersection of right and bottom
double detBottomRight = rightA*bottomB - rightB*bottomA;
CvPoint ptBottomRight = cvPoint((bottomB*rightC-rightB*bottomC)/detBottomRight, (rightA*bottomC-bottomA*rightC)/detBottomRight);// Intersection of bottom and left
double detBottomLeft = leftA*bottomB-leftB*bottomA;
CvPoint ptBottomLeft = cvPoint((bottomB*leftC-leftB*bottomC)/detBottomLeft, (leftA*bottomC-bottomA*leftC)/detBottomLeft);
// corrects the skewed photo, orients it STRAIGHT; finds the longest edge, then creates a square w/ this side length
// calculate length of each side, whenever find a longer edge store its length squared. Once you have longest edge sqrt to find exact length
int maxLength = (ptBottomLeft.x-ptBottomRight.x)*(ptBottomLeft.x-ptBottomRight.x) + (ptBottomLeft.y-ptBottomRight.y)*(ptBottomLeft.y-ptBottomRight.y);
int temp = (ptTopRight.x-ptBottomRight.x)*(ptTopRight.x-ptBottomRight.x) + (ptTopRight.y-ptBottomRight.y)*(ptTopRight.y-ptBottomRight.y);
if(temp>maxLength) maxLength = temp;
temp = (ptTopRight.x-ptTopLeft.x)*(ptTopRight.x-ptTopLeft.x) + (ptTopRight.y-ptTopLeft.y)*(ptTopRight.y-ptTopLeft.y);
if(temp>maxLength) maxLength = temp;
temp = (ptBottomLeft.x-ptTopLeft.x)*(ptBottomLeft.x-ptTopLeft.x) + (ptBottomLeft.y-ptTopLeft.y)*(ptBottomLeft.y-ptTopLeft.y);
if(temp>maxLength) maxLength = temp;
maxLength = sqrt((double)maxLength);
// create source and destination points
Point2f src[4], dst[4];
src[0] = ptTopLeft;
src[1] = ptTopRight;
src[2] = ptBottomRight;
src[3] = ptBottomLeft;
dst[0] = Point2f(0,0);
dst[1] = Point2f(maxLength-1, 0);
dst[2] = Point2f(maxLength-1, maxLength-1);
dst[3] = Point2f(0, maxLength-1);
// create a new image and do the undistortion; now the image undistored has the corrected image
Mat undistorted = Mat(Size(maxLength, maxLength), CV_8UC1);
cv::warpPerspective(original, undistorted, cv::getPerspectiveTransform(src, dst), Size(maxLength, maxLength));
//adaptiveThreshold(undistorted, undistortedThreshed, 255, CV_ADAPTIVE_THRESH_GAUSSIAN_C, CV_THRESH_BINARY_INV, 101, 1);
imwrite("original.jpg", original);
imwrite("sudoku2.jpg", undistorted);// saves the photo as a jpeg.
erode(undistorted, undistorted, 0); // b/c image was dilated a bit it is restored a bit by eroding it
Mat undistortedThreshed = undistorted.clone();
adaptiveThreshold(undistorted, undistortedThreshed, 255, CV_ADAPTIVE_THRESH_GAUSSIAN_C, CV_THRESH_BINARY_INV, 101, 1);
//DigitRecognizer(undistorted);
//Mat DigitRecognizer::preprocessImage(Mat undistorted);
imwrite("sudoku3.jpg", undistortedThreshed);
Mat sudokuC = undistortedThreshed.clone();
//sudokuC = thresh(sudokuC);
//GaussianBlur(sudokuB, sudokuB, Size(11,11), 0); // blurs the image to smooth out the noise and makes extracting grid lines easier
//imwrite("B.png", sudokuC);
//sudokuC = grid_extract(sudokuC);
//imwrite("C.png", sudokuC);
//erode(sudokuB, sudokuB, 0); // b/c image was dilated a bit it is restored a bit by eroding it
//dilate(sudokuB, sudokuB, kernel);
//imwrite("D.png", sudokuB);
sudokuC = hough(sudokuC);
imwrite("E.png", sudokuC);
erode(sudokuC, sudokuC, 5); // b/c image was dilated a bit it is restored a bit by eroding it
imwrite("F.png", sudokuC);
fopen("tesseractAPI.exe", "r+");
fopen("sudokuSolverComplete.exe", "r+");
//sudokuB = grid_extract(sudokuB);
//imwrite("G.png", sudokuB);
//digit_extract(sudokuC);
//system("tesseract /Users/austinjiang/programming/eclipse-workspace/puzzle/F.png /Users/austinjiang/programming/eclipse-workspace/puzzle/output -psm 6");
//system("tesseract F.png output.txt");
return 0;
}
|
3068cbf23ee406e6f0535053807c1109cd82fe89
|
765d3d92befb0937030b04798f5536f71313d4ed
|
/moKa/adsrplot.h
|
7d3c579c840451b135f890a2cc24ee50bbea38db
|
[] |
no_license
|
vsr83/moKa
|
57bde0331c9311f8d641b2eedaf5ba99a153841d
|
4993cbc08a8567ccad3d89d40168a373e15a014b
|
refs/heads/master
| 2020-12-30T13:39:10.220624
| 2017-06-17T13:00:03
| 2017-06-17T13:00:03
| 91,235,717
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 497
|
h
|
adsrplot.h
|
#ifndef ADSRPLOT_H
#define ADSRPLOT_H
#include <QWidget>
#include <QPixmap>
#include "envelope.h"
class ADSRPlot : public QWidget {
Q_OBJECT
public:
ADSRPlot(QWidget *parent = 0);
~ADSRPlot();
protected:
void paintEvent(QPaintEvent *event);
void resizeEvent(QResizeEvent *event);
public slots:
void setValues(Envelope &_envelope);
private:
void refreshPixmap();
Envelope envelope;
QColor bgColor;
QPixmap pixmap;
int border;
};
#endif // ADSRPLOT_H
|
89f0080c3483f5fbab6dbd41a3bdf72d89cf09d0
|
2d7974502098a1c6c3b064befee0b68cd966fea1
|
/Piscine_CPP/cpp_rush3_2018/src/ncurses/User.cpp
|
93951a3d8695f4721f34ef5ba99d18a914ae5ca6
|
[] |
no_license
|
Tifloz/Tek2
|
85d280aac303a81cecbba7f0254b23a434583efd
|
e4cf798878c991ca7bc41e3dc075d47da8b854aa
|
refs/heads/master
| 2020-12-10T15:15:16.569214
| 2020-01-13T15:43:33
| 2020-01-13T15:43:33
| 233,628,967
| 0
| 0
| null | 2020-10-13T18:49:49
| 2020-01-13T15:33:25
|
C++
|
UTF-8
|
C++
| false
| false
| 807
|
cpp
|
User.cpp
|
/*
** EPITECH PROJECT, 2019
** cpp_rush03_2018
** File description:
**
*/
#include <ncurses.h>
#include "User.hpp"
User::User() = default;
User::~User() = default;;
void User::DisplayUserHost()
{
init_pair(1, COLOR_RED, COLOR_BLACK);
init_pair(2, COLOR_BLUE, COLOR_BLACK);
init_pair(3, COLOR_MAGENTA, COLOR_BLACK);
attron(COLOR_PAIR(3));
attron(A_UNDERLINE);
mvwprintw(stdscr, 2, 1, "Hostname & Username Module");
attroff(COLOR_PAIR(3));
attroff(A_UNDERLINE);
attron(COLOR_PAIR(2));
mvwprintw(stdscr, 3, 3, "Username:");
mvwprintw(stdscr, 4, 3, "Hostname:");
attroff(COLOR_PAIR(2));
attron(COLOR_PAIR(1));
mvwprintw(stdscr, 3, 4 + 9, "%s", _username.c_str());
mvwprintw(stdscr, 4, 4 + 9, "%s", _hostname.c_str());
attroff(COLOR_PAIR(1));
}
|
5cc47c216574383a6a8f8898abc40e5cdae8ccc5
|
83373f40f70c78bbbd0379d64e5c6e882d11d436
|
/Block.h
|
b37de5b0e1b547c870374801d4d9c39e160e4f05
|
[] |
no_license
|
AnargyrosArg/Project_OOP
|
4c61b22ad121543b73f303a528fae0367ed9f2bb
|
207b80fcbb427efc2d8d136ca5e448c2296c8dfa
|
refs/heads/master
| 2023-02-12T10:00:56.270268
| 2021-01-06T11:03:05
| 2021-01-06T11:03:05
| 325,373,700
| 0
| 0
| null | 2021-01-06T11:03:06
| 2020-12-29T19:47:32
|
Makefile
|
UTF-8
|
C++
| false
| false
| 294
|
h
|
Block.h
|
//
// Created by anarg on 1/3/2021.
//
#ifndef UNTITLED1_BLOCK_H
#define UNTITLED1_BLOCK_H
#include "Party.h"
class Block {
private:
public:
virtual bool isAccessible(){return true;}
virtual void event(Party* party)=0;
virtual void printBlock()=0;
};
#endif //UNTITLED1_BLOCK_H
|
87ca077f4d4a662713e72aba80c9108c451c9ace
|
e7fe3995745df145a1d12fca4c9847b605110bf3
|
/libs/Timer.h
|
941a52d909ec2227fe52736ef5460b0bcda6444e
|
[
"MIT"
] |
permissive
|
WowSoLaggy/Doh3d
|
42c8d78eae79a08d8bc9cfc5bc3b0815dfc4e3d3
|
0aca8f00fdc52975ff872c99b0f48fbac3d779d6
|
refs/heads/master
| 2021-09-11T13:25:59.586561
| 2018-04-07T19:28:35
| 2018-04-07T19:28:35
| 63,375,582
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,166
|
h
|
Timer.h
|
#pragma once
#ifndef TIMER_H
#define TIMER_H
#include <Windows.h>
// Simple class that counts the elapsed time in seconds. It's accuracy depends on the system performance counter frequency
class Timer
{
public:
// Default ctor with the system performance counter frequency check
Timer()
{
QueryPerformanceFrequency((LARGE_INTEGER *)&m_freq);
}
// Default dtor
virtual ~Timer() { }
// Starts the new timer
void Start()
{
QueryPerformanceCounter((LARGE_INTEGER *)&m_timeStart);
}
// Returns the time elapsed since the timer start, the timer doesn't stop
double Check()
{
QueryPerformanceCounter((LARGE_INTEGER *)&m_time);
return (double)(m_time - m_timeStart) / (double)m_freq;
}
// Returns the time elapsed since the timer start and restarts the timer
double Restart()
{
QueryPerformanceCounter((LARGE_INTEGER *)&m_time);
double dt = (double)(m_time - m_timeStart) / (double)m_freq;
m_timeStart = m_time;
return dt;
}
private:
__int64 m_timeStart; // Stores start time
__int64 m_time; // Used for calculations
__int64 m_freq; // Stores performance counter frequency, used in calculations
};
#endif // TIMER_H
|
1957d3e132cb188721c4e74d135ffb675494d5e9
|
8ea027a5325ef71ef5a5b1d11491a3f6498b3c0b
|
/Sheet_06_Code/DuplicateParenthesis.cpp
|
ba9bd2b758e4cc39603737b32a8112d6a7618dd2
|
[] |
no_license
|
Prateekkumar24/CipherSchools_CP
|
d3f886480862804a193e2adc750be20e1fb59e6d
|
79c8826409d3d66cc7644624e58a99ba9a7aacb0
|
refs/heads/main
| 2023-06-11T21:10:38.448340
| 2021-07-10T04:24:13
| 2021-07-10T04:24:13
| 384,535,729
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,170
|
cpp
|
DuplicateParenthesis.cpp
|
// Code to find duplicate parenthesis in a balanced expression
#include <bits/stdc++.h>
using namespace std;
bool Duplicateparenthesis(string str)
{
stack<char> Stack;
for (char ch : str)
{
// if current character is close parenthesis
if (ch == '}')
{
char top = Stack.top();
Stack.pop();
// stores the number of characters between a closing and opening parenthesis
// if this count is less than or equal to 1 then the brackets are redundant else not
int count = 0;
while (top != '{')
{
count++;
top = Stack.top();
Stack.pop();
}
if(count < 1) {
return true;}
}
// push open parenthesis, operators and operands to stack
else
Stack.push(ch);
}
return 0;
}
int main()
{
string str;
cin>>str;
if(Duplicateparenthesis(str))
cout<<"There is duplicate";
else
cout<<"No duplicate ";
return 0;
}
|
d4a3b9c47424c9090b96734836e3093bf6ab596a
|
a7caaf953a0849f6081e44382da74a600a86b3da
|
/opencv-2.4.9/modules/legacy/src/epilines.cpp
|
b63f8e1c770ad54c338adac0aa8cdaeffadf2df7
|
[
"BSD-3-Clause",
"Apache-2.0"
] |
permissive
|
watinha/collector
|
22d22116fc1dbdfeec3bddb05aa42d05efe5b5b4
|
fc4758f87aad99084ce4235de3e929d80c56a072
|
refs/heads/master
| 2021-12-28T11:12:50.548082
| 2021-08-19T20:05:20
| 2021-08-19T20:05:20
| 136,666,875
| 2
| 1
|
Apache-2.0
| 2021-04-26T16:55:02
| 2018-06-08T21:17:16
|
C++
|
UTF-8
|
C++
| false
| false
| 108,169
|
cpp
|
epilines.cpp
|
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// Intel License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of Intel Corporation may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/
#include "precomp.hpp"
#include <float.h>
#include <limits.h>
/* Valery Mosyagin */
#undef quad
#define EPS64D 1e-9
int cvComputeEssentialMatrix( CvMatr32f rotMatr,
CvMatr32f transVect,
CvMatr32f essMatr);
int cvConvertEssential2Fundamental( CvMatr32f essMatr,
CvMatr32f fundMatr,
CvMatr32f cameraMatr1,
CvMatr32f cameraMatr2);
int cvComputeEpipolesFromFundMatrix(CvMatr32f fundMatr,
CvPoint3D32f* epipole1,
CvPoint3D32f* epipole2);
void icvTestPoint( CvPoint2D64d testPoint,
CvVect64d line1,CvVect64d line2,
CvPoint2D64d basePoint,
int* result);
int icvGetSymPoint3D( CvPoint3D64d pointCorner,
CvPoint3D64d point1,
CvPoint3D64d point2,
CvPoint3D64d *pointSym2)
{
double len1,len2;
double alpha;
icvGetPieceLength3D(pointCorner,point1,&len1);
if( len1 < EPS64D )
{
return CV_BADARG_ERR;
}
icvGetPieceLength3D(pointCorner,point2,&len2);
alpha = len2 / len1;
pointSym2->x = pointCorner.x + alpha*(point1.x - pointCorner.x);
pointSym2->y = pointCorner.y + alpha*(point1.y - pointCorner.y);
pointSym2->z = pointCorner.z + alpha*(point1.z - pointCorner.z);
return CV_NO_ERR;
}
/* author Valery Mosyagin */
/* Compute 3D point for scanline and alpha betta */
int icvCompute3DPoint( double alpha,double betta,
CvStereoLineCoeff* coeffs,
CvPoint3D64d* point)
{
double partX;
double partY;
double partZ;
double partAll;
double invPartAll;
double alphabetta = alpha*betta;
partAll = alpha - betta;
if( fabs(partAll) > 0.00001 ) /* alpha must be > betta */
{
partX = coeffs->Xcoef + coeffs->XcoefA *alpha +
coeffs->XcoefB*betta + coeffs->XcoefAB*alphabetta;
partY = coeffs->Ycoef + coeffs->YcoefA *alpha +
coeffs->YcoefB*betta + coeffs->YcoefAB*alphabetta;
partZ = coeffs->Zcoef + coeffs->ZcoefA *alpha +
coeffs->ZcoefB*betta + coeffs->ZcoefAB*alphabetta;
invPartAll = 1.0 / partAll;
point->x = partX * invPartAll;
point->y = partY * invPartAll;
point->z = partZ * invPartAll;
return CV_NO_ERR;
}
else
{
return CV_BADFACTOR_ERR;
}
}
/*--------------------------------------------------------------------------------------*/
/* Compute rotate matrix and trans vector for change system */
int icvCreateConvertMatrVect( CvMatr64d rotMatr1,
CvMatr64d transVect1,
CvMatr64d rotMatr2,
CvMatr64d transVect2,
CvMatr64d convRotMatr,
CvMatr64d convTransVect)
{
double invRotMatr2[9];
double tmpVect[3];
icvInvertMatrix_64d(rotMatr2,3,invRotMatr2);
/* Test for error */
icvMulMatrix_64d( rotMatr1,
3,3,
invRotMatr2,
3,3,
convRotMatr);
icvMulMatrix_64d( convRotMatr,
3,3,
transVect2,
1,3,
tmpVect);
icvSubVector_64d(transVect1,tmpVect,convTransVect,3);
return CV_NO_ERR;
}
/*--------------------------------------------------------------------------------------*/
/* Compute point coordinates in other system */
int icvConvertPointSystem(CvPoint3D64d M2,
CvPoint3D64d* M1,
CvMatr64d rotMatr,
CvMatr64d transVect
)
{
double tmpVect[3];
icvMulMatrix_64d( rotMatr,
3,3,
(double*)&M2,
1,3,
tmpVect);
icvAddVector_64d(tmpVect,transVect,(double*)M1,3);
return CV_NO_ERR;
}
/*--------------------------------------------------------------------------------------*/
static int icvComputeCoeffForStereoV3( double quad1[4][2],
double quad2[4][2],
int numScanlines,
CvMatr64d camMatr1,
CvMatr64d rotMatr1,
CvMatr64d transVect1,
CvMatr64d camMatr2,
CvMatr64d rotMatr2,
CvMatr64d transVect2,
CvStereoLineCoeff* startCoeffs,
int* needSwapCamera)
{
/* For each pair */
/* In this function we must define position of cameras */
CvPoint2D64d point1;
CvPoint2D64d point2;
CvPoint2D64d point3;
CvPoint2D64d point4;
int currLine;
*needSwapCamera = 0;
for( currLine = 0; currLine < numScanlines; currLine++ )
{
/* Compute points */
double alpha = ((double)currLine)/((double)(numScanlines)); /* maybe - 1 */
point1.x = (1.0 - alpha) * quad1[0][0] + alpha * quad1[3][0];
point1.y = (1.0 - alpha) * quad1[0][1] + alpha * quad1[3][1];
point2.x = (1.0 - alpha) * quad1[1][0] + alpha * quad1[2][0];
point2.y = (1.0 - alpha) * quad1[1][1] + alpha * quad1[2][1];
point3.x = (1.0 - alpha) * quad2[0][0] + alpha * quad2[3][0];
point3.y = (1.0 - alpha) * quad2[0][1] + alpha * quad2[3][1];
point4.x = (1.0 - alpha) * quad2[1][0] + alpha * quad2[2][0];
point4.y = (1.0 - alpha) * quad2[1][1] + alpha * quad2[2][1];
/* We can compute coeffs for this line */
icvComCoeffForLine( point1,
point2,
point3,
point4,
camMatr1,
rotMatr1,
transVect1,
camMatr2,
rotMatr2,
transVect2,
&startCoeffs[currLine],
needSwapCamera);
}
return CV_NO_ERR;
}
/*--------------------------------------------------------------------------------------*/
static int icvComputeCoeffForStereoNew( double quad1[4][2],
double quad2[4][2],
int numScanlines,
CvMatr32f camMatr1,
CvMatr32f rotMatr1,
CvMatr32f transVect1,
CvMatr32f camMatr2,
CvStereoLineCoeff* startCoeffs,
int* needSwapCamera)
{
/* Convert data */
double camMatr1_64d[9];
double camMatr2_64d[9];
double rotMatr1_64d[9];
double transVect1_64d[3];
double rotMatr2_64d[9];
double transVect2_64d[3];
icvCvt_32f_64d(camMatr1,camMatr1_64d,9);
icvCvt_32f_64d(camMatr2,camMatr2_64d,9);
icvCvt_32f_64d(rotMatr1,rotMatr1_64d,9);
icvCvt_32f_64d(transVect1,transVect1_64d,3);
rotMatr2_64d[0] = 1;
rotMatr2_64d[1] = 0;
rotMatr2_64d[2] = 0;
rotMatr2_64d[3] = 0;
rotMatr2_64d[4] = 1;
rotMatr2_64d[5] = 0;
rotMatr2_64d[6] = 0;
rotMatr2_64d[7] = 0;
rotMatr2_64d[8] = 1;
transVect2_64d[0] = 0;
transVect2_64d[1] = 0;
transVect2_64d[2] = 0;
int status = icvComputeCoeffForStereoV3( quad1,
quad2,
numScanlines,
camMatr1_64d,
rotMatr1_64d,
transVect1_64d,
camMatr2_64d,
rotMatr2_64d,
transVect2_64d,
startCoeffs,
needSwapCamera);
return status;
}
/*--------------------------------------------------------------------------------------*/
int icvComputeCoeffForStereo( CvStereoCamera* stereoCamera)
{
double quad1[4][2];
double quad2[4][2];
int i;
for( i = 0; i < 4; i++ )
{
quad1[i][0] = stereoCamera->quad[0][i].x;
quad1[i][1] = stereoCamera->quad[0][i].y;
quad2[i][0] = stereoCamera->quad[1][i].x;
quad2[i][1] = stereoCamera->quad[1][i].y;
}
icvComputeCoeffForStereoNew( quad1,
quad2,
stereoCamera->warpSize.height,
stereoCamera->camera[0]->matrix,
stereoCamera->rotMatrix,
stereoCamera->transVector,
stereoCamera->camera[1]->matrix,
stereoCamera->lineCoeffs,
&(stereoCamera->needSwapCameras));
return CV_OK;
}
/*--------------------------------------------------------------------------------------*/
int icvComCoeffForLine( CvPoint2D64d point1,
CvPoint2D64d point2,
CvPoint2D64d point3,
CvPoint2D64d point4,
CvMatr64d camMatr1,
CvMatr64d rotMatr1,
CvMatr64d transVect1,
CvMatr64d camMatr2,
CvMatr64d rotMatr2,
CvMatr64d transVect2,
CvStereoLineCoeff* coeffs,
int* needSwapCamera)
{
/* Get direction for all points */
/* Direction for camera 1 */
CvPoint3D64f direct1;
CvPoint3D64f direct2;
CvPoint3D64f camPoint1;
CvPoint3D64f directS3;
CvPoint3D64f directS4;
CvPoint3D64f direct3;
CvPoint3D64f direct4;
CvPoint3D64f camPoint2;
icvGetDirectionForPoint( point1,
camMatr1,
&direct1);
icvGetDirectionForPoint( point2,
camMatr1,
&direct2);
/* Direction for camera 2 */
icvGetDirectionForPoint( point3,
camMatr2,
&directS3);
icvGetDirectionForPoint( point4,
camMatr2,
&directS4);
/* Create convertion for camera 2: two direction and camera point */
double convRotMatr[9];
double convTransVect[3];
icvCreateConvertMatrVect( rotMatr1,
transVect1,
rotMatr2,
transVect2,
convRotMatr,
convTransVect);
CvPoint3D64f zeroVect;
zeroVect.x = zeroVect.y = zeroVect.z = 0.0;
camPoint1.x = camPoint1.y = camPoint1.z = 0.0;
icvConvertPointSystem(directS3,&direct3,convRotMatr,convTransVect);
icvConvertPointSystem(directS4,&direct4,convRotMatr,convTransVect);
icvConvertPointSystem(zeroVect,&camPoint2,convRotMatr,convTransVect);
CvPoint3D64f pointB;
int postype = 0;
/* Changed order */
/* Compute point B: xB,yB,zB */
icvGetCrossLines(camPoint1,direct2,
camPoint2,direct3,
&pointB);
if( pointB.z < 0 )/* If negative use other lines for cross */
{
postype = 1;
icvGetCrossLines(camPoint1,direct1,
camPoint2,direct4,
&pointB);
}
CvPoint3D64d pointNewA;
CvPoint3D64d pointNewC;
pointNewA.x = pointNewA.y = pointNewA.z = 0;
pointNewC.x = pointNewC.y = pointNewC.z = 0;
if( postype == 0 )
{
icvGetSymPoint3D( camPoint1,
direct1,
pointB,
&pointNewA);
icvGetSymPoint3D( camPoint2,
direct4,
pointB,
&pointNewC);
}
else
{/* In this case we must change cameras */
*needSwapCamera = 1;
icvGetSymPoint3D( camPoint2,
direct3,
pointB,
&pointNewA);
icvGetSymPoint3D( camPoint1,
direct2,
pointB,
&pointNewC);
}
double gamma;
double xA,yA,zA;
double xB,yB,zB;
double xC,yC,zC;
xA = pointNewA.x;
yA = pointNewA.y;
zA = pointNewA.z;
xB = pointB.x;
yB = pointB.y;
zB = pointB.z;
xC = pointNewC.x;
yC = pointNewC.y;
zC = pointNewC.z;
double len1,len2;
len1 = sqrt( (xA-xB)*(xA-xB) + (yA-yB)*(yA-yB) + (zA-zB)*(zA-zB) );
len2 = sqrt( (xB-xC)*(xB-xC) + (yB-yC)*(yB-yC) + (zB-zC)*(zB-zC) );
gamma = len2 / len1;
icvComputeStereoLineCoeffs( pointNewA,
pointB,
camPoint1,
gamma,
coeffs);
return CV_NO_ERR;
}
/*--------------------------------------------------------------------------------------*/
int icvGetDirectionForPoint( CvPoint2D64d point,
CvMatr64d camMatr,
CvPoint3D64d* direct)
{
/* */
double invMatr[9];
/* Invert matrix */
icvInvertMatrix_64d(camMatr,3,invMatr);
/* TEST FOR ERRORS */
double vect[3];
vect[0] = point.x;
vect[1] = point.y;
vect[2] = 1;
/* Mul matr */
icvMulMatrix_64d( invMatr,
3,3,
vect,
1,3,
(double*)direct);
return CV_NO_ERR;
}
/*--------------------------------------------------------------------------------------*/
int icvGetCrossLines(CvPoint3D64d point11,CvPoint3D64d point12,
CvPoint3D64d point21,CvPoint3D64d point22,
CvPoint3D64d* midPoint)
{
double xM,yM,zM;
double xN,yN,zN;
double xA,yA,zA;
double xB,yB,zB;
double xC,yC,zC;
double xD,yD,zD;
xA = point11.x;
yA = point11.y;
zA = point11.z;
xB = point12.x;
yB = point12.y;
zB = point12.z;
xC = point21.x;
yC = point21.y;
zC = point21.z;
xD = point22.x;
yD = point22.y;
zD = point22.z;
double a11,a12,a21,a22;
double b1,b2;
a11 = (xB-xA)*(xB-xA)+(yB-yA)*(yB-yA)+(zB-zA)*(zB-zA);
a12 = -(xD-xC)*(xB-xA)-(yD-yC)*(yB-yA)-(zD-zC)*(zB-zA);
a21 = (xB-xA)*(xD-xC)+(yB-yA)*(yD-yC)+(zB-zA)*(zD-zC);
a22 = -(xD-xC)*(xD-xC)-(yD-yC)*(yD-yC)-(zD-zC)*(zD-zC);
b1 = -( (xA-xC)*(xB-xA)+(yA-yC)*(yB-yA)+(zA-zC)*(zB-zA) );
b2 = -( (xA-xC)*(xD-xC)+(yA-yC)*(yD-yC)+(zA-zC)*(zD-zC) );
double delta;
double deltaA,deltaB;
double alpha,betta;
delta = a11*a22-a12*a21;
if( fabs(delta) < EPS64D )
{
/*return ERROR;*/
}
deltaA = b1*a22-b2*a12;
deltaB = a11*b2-b1*a21;
alpha = deltaA / delta;
betta = deltaB / delta;
xM = xA+alpha*(xB-xA);
yM = yA+alpha*(yB-yA);
zM = zA+alpha*(zB-zA);
xN = xC+betta*(xD-xC);
yN = yC+betta*(yD-yC);
zN = zC+betta*(zD-zC);
/* Compute middle point */
midPoint->x = (xM + xN) * 0.5;
midPoint->y = (yM + yN) * 0.5;
midPoint->z = (zM + zN) * 0.5;
return CV_NO_ERR;
}
/*--------------------------------------------------------------------------------------*/
int icvComputeStereoLineCoeffs( CvPoint3D64d pointA,
CvPoint3D64d pointB,
CvPoint3D64d pointCam1,
double gamma,
CvStereoLineCoeff* coeffs)
{
double x1,y1,z1;
x1 = pointCam1.x;
y1 = pointCam1.y;
z1 = pointCam1.z;
double xA,yA,zA;
double xB,yB,zB;
xA = pointA.x;
yA = pointA.y;
zA = pointA.z;
xB = pointB.x;
yB = pointB.y;
zB = pointB.z;
if( gamma > 0 )
{
coeffs->Xcoef = -x1 + xA;
coeffs->XcoefA = xB + x1 - xA;
coeffs->XcoefB = -xA - gamma * x1 + gamma * xA;
coeffs->XcoefAB = -xB + xA + gamma * xB - gamma * xA;
coeffs->Ycoef = -y1 + yA;
coeffs->YcoefA = yB + y1 - yA;
coeffs->YcoefB = -yA - gamma * y1 + gamma * yA;
coeffs->YcoefAB = -yB + yA + gamma * yB - gamma * yA;
coeffs->Zcoef = -z1 + zA;
coeffs->ZcoefA = zB + z1 - zA;
coeffs->ZcoefB = -zA - gamma * z1 + gamma * zA;
coeffs->ZcoefAB = -zB + zA + gamma * zB - gamma * zA;
}
else
{
gamma = - gamma;
coeffs->Xcoef = -( -x1 + xA);
coeffs->XcoefB = -( xB + x1 - xA);
coeffs->XcoefA = -( -xA - gamma * x1 + gamma * xA);
coeffs->XcoefAB = -( -xB + xA + gamma * xB - gamma * xA);
coeffs->Ycoef = -( -y1 + yA);
coeffs->YcoefB = -( yB + y1 - yA);
coeffs->YcoefA = -( -yA - gamma * y1 + gamma * yA);
coeffs->YcoefAB = -( -yB + yA + gamma * yB - gamma * yA);
coeffs->Zcoef = -( -z1 + zA);
coeffs->ZcoefB = -( zB + z1 - zA);
coeffs->ZcoefA = -( -zA - gamma * z1 + gamma * zA);
coeffs->ZcoefAB = -( -zB + zA + gamma * zB - gamma * zA);
}
return CV_NO_ERR;
}
/*--------------------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------------------*/
/* This function get minimum angle started at point which contains rect */
int icvGetAngleLine( CvPoint2D64d startPoint, CvSize imageSize,CvPoint2D64d *point1,CvPoint2D64d *point2)
{
/* Get crosslines with image corners */
/* Find four lines */
CvPoint2D64d pa,pb,pc,pd;
pa.x = 0;
pa.y = 0;
pb.x = imageSize.width-1;
pb.y = 0;
pd.x = imageSize.width-1;
pd.y = imageSize.height-1;
pc.x = 0;
pc.y = imageSize.height-1;
/* We can compute points for angle */
/* Test for place section */
if( startPoint.x < 0 )
{/* 1,4,7 */
if( startPoint.y < 0)
{/* 1 */
*point1 = pb;
*point2 = pc;
}
else if( startPoint.y > imageSize.height-1 )
{/* 7 */
*point1 = pa;
*point2 = pd;
}
else
{/* 4 */
*point1 = pa;
*point2 = pc;
}
}
else if ( startPoint.x > imageSize.width-1 )
{/* 3,6,9 */
if( startPoint.y < 0 )
{/* 3 */
*point1 = pa;
*point2 = pd;
}
else if ( startPoint.y > imageSize.height-1 )
{/* 9 */
*point1 = pb;
*point2 = pc;
}
else
{/* 6 */
*point1 = pb;
*point2 = pd;
}
}
else
{/* 2,5,8 */
if( startPoint.y < 0 )
{/* 2 */
if( startPoint.x < imageSize.width/2 )
{
*point1 = pb;
*point2 = pa;
}
else
{
*point1 = pa;
*point2 = pb;
}
}
else if( startPoint.y > imageSize.height-1 )
{/* 8 */
if( startPoint.x < imageSize.width/2 )
{
*point1 = pc;
*point2 = pd;
}
else
{
*point1 = pd;
*point2 = pc;
}
}
else
{/* 5 - point in the image */
return 2;
}
}
return 0;
}/* GetAngleLine */
/*---------------------------------------------------------------------------------------*/
void icvGetCoefForPiece( CvPoint2D64d p_start,CvPoint2D64d p_end,
double *a,double *b,double *c,
int* result)
{
double det;
double detA,detB,detC;
det = p_start.x*p_end.y+p_end.x+p_start.y-p_end.y-p_start.y*p_end.x-p_start.x;
if( fabs(det) < EPS64D)/* Error */
{
*result = 0;
return;
}
detA = p_start.y - p_end.y;
detB = p_end.x - p_start.x;
detC = p_start.x*p_end.y - p_end.x*p_start.y;
double invDet = 1.0 / det;
*a = detA * invDet;
*b = detB * invDet;
*c = detC * invDet;
*result = 1;
return;
}
/*---------------------------------------------------------------------------------------*/
/* Get common area of rectifying */
static void icvGetCommonArea( CvSize imageSize,
CvPoint3D64d epipole1,CvPoint3D64d epipole2,
CvMatr64d fundMatr,
CvVect64d coeff11,CvVect64d coeff12,
CvVect64d coeff21,CvVect64d coeff22,
int* result)
{
int res = 0;
CvPoint2D64d point11;
CvPoint2D64d point12;
CvPoint2D64d point21;
CvPoint2D64d point22;
double corr11[3];
double corr12[3];
double corr21[3];
double corr22[3];
double pointW11[3];
double pointW12[3];
double pointW21[3];
double pointW22[3];
double transFundMatr[3*3];
/* Compute transpose of fundamental matrix */
icvTransposeMatrix_64d( fundMatr, 3, 3, transFundMatr );
CvPoint2D64d epipole1_2d;
CvPoint2D64d epipole2_2d;
if( fabs(epipole1.z) < 1e-8 )
{/* epipole1 in infinity */
*result = 0;
return;
}
epipole1_2d.x = epipole1.x / epipole1.z;
epipole1_2d.y = epipole1.y / epipole1.z;
if( fabs(epipole2.z) < 1e-8 )
{/* epipole2 in infinity */
*result = 0;
return;
}
epipole2_2d.x = epipole2.x / epipole2.z;
epipole2_2d.y = epipole2.y / epipole2.z;
int stat = icvGetAngleLine( epipole1_2d, imageSize,&point11,&point12);
if( stat == 2 )
{
/* No angle */
*result = 0;
return;
}
stat = icvGetAngleLine( epipole2_2d, imageSize,&point21,&point22);
if( stat == 2 )
{
/* No angle */
*result = 0;
return;
}
/* ============= Computation for line 1 ================ */
/* Find correspondence line for angle points11 */
/* corr21 = Fund'*p1 */
pointW11[0] = point11.x;
pointW11[1] = point11.y;
pointW11[2] = 1.0;
icvTransformVector_64d( transFundMatr, /* !!! Modified from not transposed */
pointW11,
corr21,
3,3);
/* Find crossing of line with image 2 */
CvPoint2D64d start;
CvPoint2D64d end;
icvGetCrossRectDirect( imageSize,
corr21[0],corr21[1],corr21[2],
&start,&end,
&res);
if( res == 0 )
{/* We have not cross */
/* We must define new angle */
pointW21[0] = point21.x;
pointW21[1] = point21.y;
pointW21[2] = 1.0;
/* Find correspondence line for this angle points */
/* We know point and try to get corr line */
/* For point21 */
/* corr11 = Fund * p21 */
icvTransformVector_64d( fundMatr, /* !!! Modified */
pointW21,
corr11,
3,3);
/* We have cross. And it's result cross for up line. Set result coefs */
/* Set coefs for line 1 image 1 */
coeff11[0] = corr11[0];
coeff11[1] = corr11[1];
coeff11[2] = corr11[2];
/* Set coefs for line 1 image 2 */
icvGetCoefForPiece( epipole2_2d,point21,
&coeff21[0],&coeff21[1],&coeff21[2],
&res);
if( res == 0 )
{
*result = 0;
return;/* Error */
}
}
else
{/* Line 1 cross image 2 */
/* Set coefs for line 1 image 1 */
icvGetCoefForPiece( epipole1_2d,point11,
&coeff11[0],&coeff11[1],&coeff11[2],
&res);
if( res == 0 )
{
*result = 0;
return;/* Error */
}
/* Set coefs for line 1 image 2 */
coeff21[0] = corr21[0];
coeff21[1] = corr21[1];
coeff21[2] = corr21[2];
}
/* ============= Computation for line 2 ================ */
/* Find correspondence line for angle points11 */
/* corr22 = Fund*p2 */
pointW12[0] = point12.x;
pointW12[1] = point12.y;
pointW12[2] = 1.0;
icvTransformVector_64d( transFundMatr,
pointW12,
corr22,
3,3);
/* Find crossing of line with image 2 */
icvGetCrossRectDirect( imageSize,
corr22[0],corr22[1],corr22[2],
&start,&end,
&res);
if( res == 0 )
{/* We have not cross */
/* We must define new angle */
pointW22[0] = point22.x;
pointW22[1] = point22.y;
pointW22[2] = 1.0;
/* Find correspondence line for this angle points */
/* We know point and try to get corr line */
/* For point21 */
/* corr2 = Fund' * p1 */
icvTransformVector_64d( fundMatr,
pointW22,
corr12,
3,3);
/* We have cross. And it's result cross for down line. Set result coefs */
/* Set coefs for line 2 image 1 */
coeff12[0] = corr12[0];
coeff12[1] = corr12[1];
coeff12[2] = corr12[2];
/* Set coefs for line 1 image 2 */
icvGetCoefForPiece( epipole2_2d,point22,
&coeff22[0],&coeff22[1],&coeff22[2],
&res);
if( res == 0 )
{
*result = 0;
return;/* Error */
}
}
else
{/* Line 2 cross image 2 */
/* Set coefs for line 2 image 1 */
icvGetCoefForPiece( epipole1_2d,point12,
&coeff12[0],&coeff12[1],&coeff12[2],
&res);
if( res == 0 )
{
*result = 0;
return;/* Error */
}
/* Set coefs for line 1 image 2 */
coeff22[0] = corr22[0];
coeff22[1] = corr22[1];
coeff22[2] = corr22[2];
}
/* Now we know common area */
return;
}/* GetCommonArea */
/*---------------------------------------------------------------------------------------*/
/* Get cross for direction1 and direction2 */
/* Result = 1 - cross */
/* Result = 2 - parallel and not equal */
/* Result = 3 - parallel and equal */
void icvGetCrossDirectDirect( CvVect64d direct1,CvVect64d direct2,
CvPoint2D64d *cross,int* result)
{
double det = direct1[0]*direct2[1] - direct2[0]*direct1[1];
double detx = -direct1[2]*direct2[1] + direct1[1]*direct2[2];
if( fabs(det) > EPS64D )
{/* Have cross */
cross->x = detx/det;
cross->y = (-direct1[0]*direct2[2] + direct2[0]*direct1[2])/det;
*result = 1;
}
else
{/* may be parallel */
if( fabs(detx) > EPS64D )
{/* parallel and not equal */
*result = 2;
}
else
{/* equals */
*result = 3;
}
}
return;
}
/*---------------------------------------------------------------------------------------*/
/* Get cross for piece p1,p2 and direction a,b,c */
/* Result = 0 - no cross */
/* Result = 1 - cross */
/* Result = 2 - parallel and not equal */
/* Result = 3 - parallel and equal */
void icvGetCrossPieceDirect( CvPoint2D64d p_start,CvPoint2D64d p_end,
double a,double b,double c,
CvPoint2D64d *cross,int* result)
{
if( (a*p_start.x + b*p_start.y + c) * (a*p_end.x + b*p_end.y + c) <= 0 )
{/* Have cross */
double det;
double detxc,detyc;
det = a * (p_end.x - p_start.x) + b * (p_end.y - p_start.y);
if( fabs(det) < EPS64D )
{/* lines are parallel and may be equal or line is point */
if( fabs(a*p_start.x + b*p_start.y + c) < EPS64D )
{/* line is point or not diff */
*result = 3;
return;
}
else
{
*result = 2;
}
return;
}
detxc = b*(p_end.y*p_start.x - p_start.y*p_end.x) + c*(p_start.x - p_end.x);
detyc = a*(p_end.x*p_start.y - p_start.x*p_end.y) + c*(p_start.y - p_end.y);
cross->x = detxc / det;
cross->y = detyc / det;
*result = 1;
}
else
{
*result = 0;
}
return;
}
/*--------------------------------------------------------------------------------------*/
void icvGetCrossPiecePiece( CvPoint2D64d p1_start,CvPoint2D64d p1_end,
CvPoint2D64d p2_start,CvPoint2D64d p2_end,
CvPoint2D64d* cross,
int* result)
{
double ex1,ey1,ex2,ey2;
double px1,py1,px2,py2;
double del;
double delA,delB,delX,delY;
double alpha,betta;
ex1 = p1_start.x;
ey1 = p1_start.y;
ex2 = p1_end.x;
ey2 = p1_end.y;
px1 = p2_start.x;
py1 = p2_start.y;
px2 = p2_end.x;
py2 = p2_end.y;
del = (py1-py2)*(ex1-ex2)-(px1-px2)*(ey1-ey2);
if( fabs(del) <= EPS64D )
{/* May be they are parallel !!! */
*result = 0;
return;
}
delA = (ey1-ey2)*(ex1-px1) + (ex1-ex2)*(py1-ey1);
delB = (py1-py2)*(ex1-px1) + (px1-px2)*(py1-ey1);
alpha = delA / del;
betta = delB / del;
if( alpha < 0 || alpha > 1.0 || betta < 0 || betta > 1.0)
{
*result = 0;
return;
}
delX = (px1-px2)*(ey1*(ex1-ex2)-ex1*(ey1-ey2))+
(ex1-ex2)*(px1*(py1-py2)-py1*(px1-px2));
delY = (py1-py2)*(ey1*(ex1-ex2)-ex1*(ey1-ey2))+
(ey1-ey2)*(px1*(py1-py2)-py1*(px1-px2));
cross->x = delX / del;
cross->y = delY / del;
*result = 1;
return;
}
/*---------------------------------------------------------------------------------------*/
void icvGetPieceLength(CvPoint2D64d point1,CvPoint2D64d point2,double* dist)
{
double dx = point2.x - point1.x;
double dy = point2.y - point1.y;
*dist = sqrt( dx*dx + dy*dy );
return;
}
/*---------------------------------------------------------------------------------------*/
void icvGetPieceLength3D(CvPoint3D64d point1,CvPoint3D64d point2,double* dist)
{
double dx = point2.x - point1.x;
double dy = point2.y - point1.y;
double dz = point2.z - point1.z;
*dist = sqrt( dx*dx + dy*dy + dz*dz );
return;
}
/*---------------------------------------------------------------------------------------*/
/* Find line from epipole which cross image rect */
/* Find points of cross 0 or 1 or 2. Return number of points in cross */
void icvGetCrossRectDirect( CvSize imageSize,
double a,double b,double c,
CvPoint2D64d *start,CvPoint2D64d *end,
int* result)
{
CvPoint2D64d frameBeg;
CvPoint2D64d frameEnd;
CvPoint2D64d cross[4];
int haveCross[4];
haveCross[0] = 0;
haveCross[1] = 0;
haveCross[2] = 0;
haveCross[3] = 0;
frameBeg.x = 0;
frameBeg.y = 0;
frameEnd.x = imageSize.width;
frameEnd.y = 0;
icvGetCrossPieceDirect(frameBeg,frameEnd,a,b,c,&cross[0],&haveCross[0]);
frameBeg.x = imageSize.width;
frameBeg.y = 0;
frameEnd.x = imageSize.width;
frameEnd.y = imageSize.height;
icvGetCrossPieceDirect(frameBeg,frameEnd,a,b,c,&cross[1],&haveCross[1]);
frameBeg.x = imageSize.width;
frameBeg.y = imageSize.height;
frameEnd.x = 0;
frameEnd.y = imageSize.height;
icvGetCrossPieceDirect(frameBeg,frameEnd,a,b,c,&cross[2],&haveCross[2]);
frameBeg.x = 0;
frameBeg.y = imageSize.height;
frameEnd.x = 0;
frameEnd.y = 0;
icvGetCrossPieceDirect(frameBeg,frameEnd,a,b,c,&cross[3],&haveCross[3]);
double maxDist;
int maxI=0,maxJ=0;
int i,j;
maxDist = -1.0;
double distance;
for( i = 0; i < 3; i++ )
{
if( haveCross[i] == 1 )
{
for( j = i + 1; j < 4; j++ )
{
if( haveCross[j] == 1)
{/* Compute dist */
icvGetPieceLength(cross[i],cross[j],&distance);
if( distance > maxDist )
{
maxI = i;
maxJ = j;
maxDist = distance;
}
}
}
}
}
if( maxDist >= 0 )
{/* We have cross */
*start = cross[maxI];
*result = 1;
if( maxDist > 0 )
{
*end = cross[maxJ];
*result = 2;
}
}
else
{
*result = 0;
}
return;
}/* GetCrossRectDirect */
/*---------------------------------------------------------------------------------------*/
void icvProjectPointToImage( CvPoint3D64d point,
CvMatr64d camMatr,CvMatr64d rotMatr,CvVect64d transVect,
CvPoint2D64d* projPoint)
{
double tmpVect1[3];
double tmpVect2[3];
icvMulMatrix_64d ( rotMatr,
3,3,
(double*)&point,
1,3,
tmpVect1);
icvAddVector_64d ( tmpVect1, transVect,tmpVect2, 3);
icvMulMatrix_64d ( camMatr,
3,3,
tmpVect2,
1,3,
tmpVect1);
projPoint->x = tmpVect1[0] / tmpVect1[2];
projPoint->y = tmpVect1[1] / tmpVect1[2];
return;
}
/*---------------------------------------------------------------------------------------*/
/* Get quads for transform images */
void icvGetQuadsTransform(
CvSize imageSize,
CvMatr64d camMatr1,
CvMatr64d rotMatr1,
CvVect64d transVect1,
CvMatr64d camMatr2,
CvMatr64d rotMatr2,
CvVect64d transVect2,
CvSize* warpSize,
double quad1[4][2],
double quad2[4][2],
CvMatr64d fundMatr,
CvPoint3D64d* epipole1,
CvPoint3D64d* epipole2
)
{
/* First compute fundamental matrix and epipoles */
int res;
/* Compute epipoles and fundamental matrix using new functions */
{
double convRotMatr[9];
double convTransVect[3];
icvCreateConvertMatrVect( rotMatr1,
transVect1,
rotMatr2,
transVect2,
convRotMatr,
convTransVect);
float convRotMatr_32f[9];
float convTransVect_32f[3];
icvCvt_64d_32f(convRotMatr,convRotMatr_32f,9);
icvCvt_64d_32f(convTransVect,convTransVect_32f,3);
/* We know R and t */
/* Compute essential matrix */
float essMatr[9];
float fundMatr_32f[9];
float camMatr1_32f[9];
float camMatr2_32f[9];
icvCvt_64d_32f(camMatr1,camMatr1_32f,9);
icvCvt_64d_32f(camMatr2,camMatr2_32f,9);
cvComputeEssentialMatrix( convRotMatr_32f,
convTransVect_32f,
essMatr);
cvConvertEssential2Fundamental( essMatr,
fundMatr_32f,
camMatr1_32f,
camMatr2_32f);
CvPoint3D32f epipole1_32f;
CvPoint3D32f epipole2_32f;
cvComputeEpipolesFromFundMatrix( fundMatr_32f,
&epipole1_32f,
&epipole2_32f);
/* copy to 64d epipoles */
epipole1->x = epipole1_32f.x;
epipole1->y = epipole1_32f.y;
epipole1->z = epipole1_32f.z;
epipole2->x = epipole2_32f.x;
epipole2->y = epipole2_32f.y;
epipole2->z = epipole2_32f.z;
/* Convert fundamental matrix */
icvCvt_32f_64d(fundMatr_32f,fundMatr,9);
}
double coeff11[3];
double coeff12[3];
double coeff21[3];
double coeff22[3];
icvGetCommonArea( imageSize,
*epipole1,*epipole2,
fundMatr,
coeff11,coeff12,
coeff21,coeff22,
&res);
CvPoint2D64d point11, point12,point21, point22;
double width1,width2;
double height1,height2;
double tmpHeight1,tmpHeight2;
CvPoint2D64d epipole1_2d;
CvPoint2D64d epipole2_2d;
/* ----- Image 1 ----- */
if( fabs(epipole1->z) < 1e-8 )
{
return;
}
epipole1_2d.x = epipole1->x / epipole1->z;
epipole1_2d.y = epipole1->y / epipole1->z;
icvGetCutPiece( coeff11,coeff12,
epipole1_2d,
imageSize,
&point11,&point12,
&point21,&point22,
&res);
/* Compute distance */
icvGetPieceLength(point11,point21,&width1);
icvGetPieceLength(point11,point12,&tmpHeight1);
icvGetPieceLength(point21,point22,&tmpHeight2);
height1 = MAX(tmpHeight1,tmpHeight2);
quad1[0][0] = point11.x;
quad1[0][1] = point11.y;
quad1[1][0] = point21.x;
quad1[1][1] = point21.y;
quad1[2][0] = point22.x;
quad1[2][1] = point22.y;
quad1[3][0] = point12.x;
quad1[3][1] = point12.y;
/* ----- Image 2 ----- */
if( fabs(epipole2->z) < 1e-8 )
{
return;
}
epipole2_2d.x = epipole2->x / epipole2->z;
epipole2_2d.y = epipole2->y / epipole2->z;
icvGetCutPiece( coeff21,coeff22,
epipole2_2d,
imageSize,
&point11,&point12,
&point21,&point22,
&res);
/* Compute distance */
icvGetPieceLength(point11,point21,&width2);
icvGetPieceLength(point11,point12,&tmpHeight1);
icvGetPieceLength(point21,point22,&tmpHeight2);
height2 = MAX(tmpHeight1,tmpHeight2);
quad2[0][0] = point11.x;
quad2[0][1] = point11.y;
quad2[1][0] = point21.x;
quad2[1][1] = point21.y;
quad2[2][0] = point22.x;
quad2[2][1] = point22.y;
quad2[3][0] = point12.x;
quad2[3][1] = point12.y;
/*=======================================================*/
/* This is a new additional way to compute quads. */
/* We must correct quads */
{
double convRotMatr[9];
double convTransVect[3];
double newQuad1[4][2];
double newQuad2[4][2];
icvCreateConvertMatrVect( rotMatr1,
transVect1,
rotMatr2,
transVect2,
convRotMatr,
convTransVect);
/* -------------Compute for first image-------------- */
CvPoint2D32f pointb1;
CvPoint2D32f pointe1;
CvPoint2D32f pointb2;
CvPoint2D32f pointe2;
pointb1.x = (float)quad1[0][0];
pointb1.y = (float)quad1[0][1];
pointe1.x = (float)quad1[3][0];
pointe1.y = (float)quad1[3][1];
icvComputeeInfiniteProject1(convRotMatr,
camMatr1,
camMatr2,
pointb1,
&pointb2);
icvComputeeInfiniteProject1(convRotMatr,
camMatr1,
camMatr2,
pointe1,
&pointe2);
/* JUST TEST FOR POINT */
/* Compute distances */
double dxOld,dyOld;
double dxNew,dyNew;
double distOld,distNew;
dxOld = quad2[1][0] - quad2[0][0];
dyOld = quad2[1][1] - quad2[0][1];
distOld = dxOld*dxOld + dyOld*dyOld;
dxNew = quad2[1][0] - pointb2.x;
dyNew = quad2[1][1] - pointb2.y;
distNew = dxNew*dxNew + dyNew*dyNew;
if( distNew > distOld )
{/* Get new points for second quad */
newQuad2[0][0] = pointb2.x;
newQuad2[0][1] = pointb2.y;
newQuad2[3][0] = pointe2.x;
newQuad2[3][1] = pointe2.y;
newQuad1[0][0] = quad1[0][0];
newQuad1[0][1] = quad1[0][1];
newQuad1[3][0] = quad1[3][0];
newQuad1[3][1] = quad1[3][1];
}
else
{/* Get new points for first quad */
pointb2.x = (float)quad2[0][0];
pointb2.y = (float)quad2[0][1];
pointe2.x = (float)quad2[3][0];
pointe2.y = (float)quad2[3][1];
icvComputeeInfiniteProject2(convRotMatr,
camMatr1,
camMatr2,
&pointb1,
pointb2);
icvComputeeInfiniteProject2(convRotMatr,
camMatr1,
camMatr2,
&pointe1,
pointe2);
/* JUST TEST FOR POINT */
newQuad2[0][0] = quad2[0][0];
newQuad2[0][1] = quad2[0][1];
newQuad2[3][0] = quad2[3][0];
newQuad2[3][1] = quad2[3][1];
newQuad1[0][0] = pointb1.x;
newQuad1[0][1] = pointb1.y;
newQuad1[3][0] = pointe1.x;
newQuad1[3][1] = pointe1.y;
}
/* -------------Compute for second image-------------- */
pointb1.x = (float)quad1[1][0];
pointb1.y = (float)quad1[1][1];
pointe1.x = (float)quad1[2][0];
pointe1.y = (float)quad1[2][1];
icvComputeeInfiniteProject1(convRotMatr,
camMatr1,
camMatr2,
pointb1,
&pointb2);
icvComputeeInfiniteProject1(convRotMatr,
camMatr1,
camMatr2,
pointe1,
&pointe2);
/* Compute distances */
dxOld = quad2[0][0] - quad2[1][0];
dyOld = quad2[0][1] - quad2[1][1];
distOld = dxOld*dxOld + dyOld*dyOld;
dxNew = quad2[0][0] - pointb2.x;
dyNew = quad2[0][1] - pointb2.y;
distNew = dxNew*dxNew + dyNew*dyNew;
if( distNew > distOld )
{/* Get new points for second quad */
newQuad2[1][0] = pointb2.x;
newQuad2[1][1] = pointb2.y;
newQuad2[2][0] = pointe2.x;
newQuad2[2][1] = pointe2.y;
newQuad1[1][0] = quad1[1][0];
newQuad1[1][1] = quad1[1][1];
newQuad1[2][0] = quad1[2][0];
newQuad1[2][1] = quad1[2][1];
}
else
{/* Get new points for first quad */
pointb2.x = (float)quad2[1][0];
pointb2.y = (float)quad2[1][1];
pointe2.x = (float)quad2[2][0];
pointe2.y = (float)quad2[2][1];
icvComputeeInfiniteProject2(convRotMatr,
camMatr1,
camMatr2,
&pointb1,
pointb2);
icvComputeeInfiniteProject2(convRotMatr,
camMatr1,
camMatr2,
&pointe1,
pointe2);
newQuad2[1][0] = quad2[1][0];
newQuad2[1][1] = quad2[1][1];
newQuad2[2][0] = quad2[2][0];
newQuad2[2][1] = quad2[2][1];
newQuad1[1][0] = pointb1.x;
newQuad1[1][1] = pointb1.y;
newQuad1[2][0] = pointe1.x;
newQuad1[2][1] = pointe1.y;
}
/*-------------------------------------------------------------------------------*/
/* Copy new quads to old quad */
int i;
for( i = 0; i < 4; i++ )
{
{
quad1[i][0] = newQuad1[i][0];
quad1[i][1] = newQuad1[i][1];
quad2[i][0] = newQuad2[i][0];
quad2[i][1] = newQuad2[i][1];
}
}
}
/*=======================================================*/
double warpWidth,warpHeight;
warpWidth = MAX(width1,width2);
warpHeight = MAX(height1,height2);
warpSize->width = (int)warpWidth;
warpSize->height = (int)warpHeight;
warpSize->width = cvRound(warpWidth-1);
warpSize->height = cvRound(warpHeight-1);
/* !!! by Valery Mosyagin. this lines added just for test no warp */
warpSize->width = imageSize.width;
warpSize->height = imageSize.height;
return;
}
/*---------------------------------------------------------------------------------------*/
static void icvGetQuadsTransformNew( CvSize imageSize,
CvMatr32f camMatr1,
CvMatr32f camMatr2,
CvMatr32f rotMatr1,
CvVect32f transVect1,
CvSize* warpSize,
double quad1[4][2],
double quad2[4][2],
CvMatr32f fundMatr,
CvPoint3D32f* epipole1,
CvPoint3D32f* epipole2
)
{
/* Convert data */
/* Convert camera matrix */
double camMatr1_64d[9];
double camMatr2_64d[9];
double rotMatr1_64d[9];
double transVect1_64d[3];
double rotMatr2_64d[9];
double transVect2_64d[3];
double fundMatr_64d[9];
CvPoint3D64d epipole1_64d;
CvPoint3D64d epipole2_64d;
icvCvt_32f_64d(camMatr1,camMatr1_64d,9);
icvCvt_32f_64d(camMatr2,camMatr2_64d,9);
icvCvt_32f_64d(rotMatr1,rotMatr1_64d,9);
icvCvt_32f_64d(transVect1,transVect1_64d,3);
/* Create vector and matrix */
rotMatr2_64d[0] = 1;
rotMatr2_64d[1] = 0;
rotMatr2_64d[2] = 0;
rotMatr2_64d[3] = 0;
rotMatr2_64d[4] = 1;
rotMatr2_64d[5] = 0;
rotMatr2_64d[6] = 0;
rotMatr2_64d[7] = 0;
rotMatr2_64d[8] = 1;
transVect2_64d[0] = 0;
transVect2_64d[1] = 0;
transVect2_64d[2] = 0;
icvGetQuadsTransform( imageSize,
camMatr1_64d,
rotMatr1_64d,
transVect1_64d,
camMatr2_64d,
rotMatr2_64d,
transVect2_64d,
warpSize,
quad1,
quad2,
fundMatr_64d,
&epipole1_64d,
&epipole2_64d
);
/* Convert epipoles */
epipole1->x = (float)(epipole1_64d.x);
epipole1->y = (float)(epipole1_64d.y);
epipole1->z = (float)(epipole1_64d.z);
epipole2->x = (float)(epipole2_64d.x);
epipole2->y = (float)(epipole2_64d.y);
epipole2->z = (float)(epipole2_64d.z);
/* Convert fundamental matrix */
icvCvt_64d_32f(fundMatr_64d,fundMatr,9);
return;
}
/*---------------------------------------------------------------------------------------*/
void icvGetQuadsTransformStruct( CvStereoCamera* stereoCamera)
{
/* Wrapper for icvGetQuadsTransformNew */
double quad1[4][2];
double quad2[4][2];
icvGetQuadsTransformNew( cvSize(cvRound(stereoCamera->camera[0]->imgSize[0]),cvRound(stereoCamera->camera[0]->imgSize[1])),
stereoCamera->camera[0]->matrix,
stereoCamera->camera[1]->matrix,
stereoCamera->rotMatrix,
stereoCamera->transVector,
&(stereoCamera->warpSize),
quad1,
quad2,
stereoCamera->fundMatr,
&(stereoCamera->epipole[0]),
&(stereoCamera->epipole[1])
);
int i;
for( i = 0; i < 4; i++ )
{
stereoCamera->quad[0][i] = cvPoint2D32f(quad1[i][0],quad1[i][1]);
stereoCamera->quad[1][i] = cvPoint2D32f(quad2[i][0],quad2[i][1]);
}
return;
}
/*---------------------------------------------------------------------------------------*/
void icvComputeStereoParamsForCameras(CvStereoCamera* stereoCamera)
{
/* For given intrinsic and extrinsic parameters computes rest parameters
** such as fundamental matrix. warping coeffs, epipoles, ...
*/
/* compute rotate matrix and translate vector */
double rotMatr1[9];
double rotMatr2[9];
double transVect1[3];
double transVect2[3];
double convRotMatr[9];
double convTransVect[3];
/* fill matrices */
icvCvt_32f_64d(stereoCamera->camera[0]->rotMatr,rotMatr1,9);
icvCvt_32f_64d(stereoCamera->camera[1]->rotMatr,rotMatr2,9);
icvCvt_32f_64d(stereoCamera->camera[0]->transVect,transVect1,3);
icvCvt_32f_64d(stereoCamera->camera[1]->transVect,transVect2,3);
icvCreateConvertMatrVect( rotMatr1,
transVect1,
rotMatr2,
transVect2,
convRotMatr,
convTransVect);
/* copy to stereo camera params */
icvCvt_64d_32f(convRotMatr,stereoCamera->rotMatrix,9);
icvCvt_64d_32f(convTransVect,stereoCamera->transVector,3);
icvGetQuadsTransformStruct(stereoCamera);
icvComputeRestStereoParams(stereoCamera);
}
/*---------------------------------------------------------------------------------------*/
/* Get cut line for one image */
void icvGetCutPiece( CvVect64d areaLineCoef1,CvVect64d areaLineCoef2,
CvPoint2D64d epipole,
CvSize imageSize,
CvPoint2D64d* point11,CvPoint2D64d* point12,
CvPoint2D64d* point21,CvPoint2D64d* point22,
int* result)
{
/* Compute nearest cut line to epipole */
/* Get corners inside sector */
/* Collect all candidate point */
CvPoint2D64d candPoints[8];
CvPoint2D64d midPoint = {0, 0};
int numPoints = 0;
int res;
int i;
double cutLine1[3];
double cutLine2[3];
/* Find middle line of sector */
double midLine[3]={0,0,0};
/* Different way */
CvPoint2D64d pointOnLine1; pointOnLine1.x = pointOnLine1.y = 0;
CvPoint2D64d pointOnLine2; pointOnLine2.x = pointOnLine2.y = 0;
CvPoint2D64d start1,end1;
icvGetCrossRectDirect( imageSize,
areaLineCoef1[0],areaLineCoef1[1],areaLineCoef1[2],
&start1,&end1,&res);
if( res > 0 )
{
pointOnLine1 = start1;
}
icvGetCrossRectDirect( imageSize,
areaLineCoef2[0],areaLineCoef2[1],areaLineCoef2[2],
&start1,&end1,&res);
if( res > 0 )
{
pointOnLine2 = start1;
}
icvGetMiddleAnglePoint(epipole,pointOnLine1,pointOnLine2,&midPoint);
icvGetCoefForPiece(epipole,midPoint,&midLine[0],&midLine[1],&midLine[2],&res);
/* Test corner points */
CvPoint2D64d cornerPoint;
CvPoint2D64d tmpPoints[2];
cornerPoint.x = 0;
cornerPoint.y = 0;
icvTestPoint( cornerPoint, areaLineCoef1, areaLineCoef2, epipole, &res);
if( res == 1 )
{/* Add point */
candPoints[numPoints] = cornerPoint;
numPoints++;
}
cornerPoint.x = imageSize.width;
cornerPoint.y = 0;
icvTestPoint( cornerPoint, areaLineCoef1, areaLineCoef2, epipole, &res);
if( res == 1 )
{/* Add point */
candPoints[numPoints] = cornerPoint;
numPoints++;
}
cornerPoint.x = imageSize.width;
cornerPoint.y = imageSize.height;
icvTestPoint( cornerPoint, areaLineCoef1, areaLineCoef2, epipole, &res);
if( res == 1 )
{/* Add point */
candPoints[numPoints] = cornerPoint;
numPoints++;
}
cornerPoint.x = 0;
cornerPoint.y = imageSize.height;
icvTestPoint( cornerPoint, areaLineCoef1, areaLineCoef2, epipole, &res);
if( res == 1 )
{/* Add point */
candPoints[numPoints] = cornerPoint;
numPoints++;
}
/* Find cross line 1 with image border */
icvGetCrossRectDirect( imageSize,
areaLineCoef1[0],areaLineCoef1[1],areaLineCoef1[2],
&tmpPoints[0], &tmpPoints[1],
&res);
for( i = 0; i < res; i++ )
{
candPoints[numPoints++] = tmpPoints[i];
}
/* Find cross line 2 with image border */
icvGetCrossRectDirect( imageSize,
areaLineCoef2[0],areaLineCoef2[1],areaLineCoef2[2],
&tmpPoints[0], &tmpPoints[1],
&res);
for( i = 0; i < res; i++ )
{
candPoints[numPoints++] = tmpPoints[i];
}
if( numPoints < 2 )
{
*result = 0;
return;/* Error. Not enought points */
}
/* Project all points to middle line and get max and min */
CvPoint2D64d projPoint;
CvPoint2D64d minPoint; minPoint.x = minPoint.y = FLT_MAX;
CvPoint2D64d maxPoint; maxPoint.x = maxPoint.y = -FLT_MAX;
double dist;
double maxDist = 0;
double minDist = 10000000;
for( i = 0; i < numPoints; i++ )
{
icvProjectPointToDirect(candPoints[i], midLine, &projPoint);
icvGetPieceLength(epipole,projPoint,&dist);
if( dist < minDist)
{
minDist = dist;
minPoint = projPoint;
}
if( dist > maxDist)
{
maxDist = dist;
maxPoint = projPoint;
}
}
/* We know maximum and minimum points. Now we can compute cut lines */
icvGetNormalDirect(midLine,minPoint,cutLine1);
icvGetNormalDirect(midLine,maxPoint,cutLine2);
/* Test for begin of line. */
CvPoint2D64d tmpPoint2;
/* Get cross with */
icvGetCrossDirectDirect(areaLineCoef1,cutLine1,point11,&res);
icvGetCrossDirectDirect(areaLineCoef2,cutLine1,point12,&res);
icvGetCrossDirectDirect(areaLineCoef1,cutLine2,point21,&res);
icvGetCrossDirectDirect(areaLineCoef2,cutLine2,point22,&res);
if( epipole.x > imageSize.width * 0.5 )
{/* Need to change points */
tmpPoint2 = *point11;
*point11 = *point21;
*point21 = tmpPoint2;
tmpPoint2 = *point12;
*point12 = *point22;
*point22 = tmpPoint2;
}
return;
}
/*---------------------------------------------------------------------------------------*/
/* Get middle angle */
void icvGetMiddleAnglePoint( CvPoint2D64d basePoint,
CvPoint2D64d point1,CvPoint2D64d point2,
CvPoint2D64d* midPoint)
{/* !!! May be need to return error */
double dist1;
double dist2;
icvGetPieceLength(basePoint,point1,&dist1);
icvGetPieceLength(basePoint,point2,&dist2);
CvPoint2D64d pointNew1;
CvPoint2D64d pointNew2;
double alpha = dist2/dist1;
pointNew1.x = basePoint.x + (1.0/alpha) * ( point2.x - basePoint.x );
pointNew1.y = basePoint.y + (1.0/alpha) * ( point2.y - basePoint.y );
pointNew2.x = basePoint.x + alpha * ( point1.x - basePoint.x );
pointNew2.y = basePoint.y + alpha * ( point1.y - basePoint.y );
int res;
icvGetCrossPiecePiece(point1,point2,pointNew1,pointNew2,midPoint,&res);
return;
}
/*---------------------------------------------------------------------------------------*/
/* Get normal direct to direct in line */
void icvGetNormalDirect(CvVect64d direct,CvPoint2D64d point,CvVect64d normDirect)
{
normDirect[0] = direct[1];
normDirect[1] = - direct[0];
normDirect[2] = -(normDirect[0]*point.x + normDirect[1]*point.y);
return;
}
/*---------------------------------------------------------------------------------------*/
CV_IMPL double icvGetVect(CvPoint2D64d basePoint,CvPoint2D64d point1,CvPoint2D64d point2)
{
return (point1.x - basePoint.x)*(point2.y - basePoint.y) -
(point2.x - basePoint.x)*(point1.y - basePoint.y);
}
/*---------------------------------------------------------------------------------------*/
/* Test for point in sector */
/* Return 0 - point not inside sector */
/* Return 1 - point inside sector */
void icvTestPoint( CvPoint2D64d testPoint,
CvVect64d line1,CvVect64d line2,
CvPoint2D64d basePoint,
int* result)
{
CvPoint2D64d point1,point2;
icvProjectPointToDirect(testPoint,line1,&point1);
icvProjectPointToDirect(testPoint,line2,&point2);
double sign1 = icvGetVect(basePoint,point1,point2);
double sign2 = icvGetVect(basePoint,point1,testPoint);
if( sign1 * sign2 > 0 )
{/* Correct for first line */
sign1 = - sign1;
sign2 = icvGetVect(basePoint,point2,testPoint);
if( sign1 * sign2 > 0 )
{/* Correct for both lines */
*result = 1;
}
else
{
*result = 0;
}
}
else
{
*result = 0;
}
return;
}
/*---------------------------------------------------------------------------------------*/
/* Project point to line */
void icvProjectPointToDirect( CvPoint2D64d point,CvVect64d lineCoeff,
CvPoint2D64d* projectPoint)
{
double a = lineCoeff[0];
double b = lineCoeff[1];
double det = 1.0 / ( a*a + b*b );
double delta = a*point.y - b*point.x;
projectPoint->x = ( -a*lineCoeff[2] - b * delta ) * det;
projectPoint->y = ( -b*lineCoeff[2] + a * delta ) * det ;
return;
}
/*---------------------------------------------------------------------------------------*/
/* Get distance from point to direction */
void icvGetDistanceFromPointToDirect( CvPoint2D64d point,CvVect64d lineCoef,double*dist)
{
CvPoint2D64d tmpPoint;
icvProjectPointToDirect(point,lineCoef,&tmpPoint);
double dx = point.x - tmpPoint.x;
double dy = point.y - tmpPoint.y;
*dist = sqrt(dx*dx+dy*dy);
return;
}
/*---------------------------------------------------------------------------------------*/
CV_IMPL IplImage* icvCreateIsometricImage( IplImage* src, IplImage* dst,
int desired_depth, int desired_num_channels )
{
CvSize src_size ;
src_size.width = src->width;
src_size.height = src->height;
CvSize dst_size = src_size;
if( dst )
{
dst_size.width = dst->width;
dst_size.height = dst->height;
}
if( !dst || dst->depth != desired_depth ||
dst->nChannels != desired_num_channels ||
dst_size.width != src_size.width ||
dst_size.height != src_size.height )
{
cvReleaseImage( &dst );
dst = cvCreateImage( src_size, desired_depth, desired_num_channels );
CvRect rect = cvRect(0,0,src_size.width,src_size.height);
cvSetImageROI( dst, rect );
}
return dst;
}
static int
icvCvt_32f_64d( float *src, double *dst, int size )
{
int t;
if( !src || !dst )
return CV_NULLPTR_ERR;
if( size <= 0 )
return CV_BADRANGE_ERR;
for( t = 0; t < size; t++ )
{
dst[t] = (double) (src[t]);
}
return CV_OK;
}
/*======================================================================================*/
/* Type conversion double -> float */
static int
icvCvt_64d_32f( double *src, float *dst, int size )
{
int t;
if( !src || !dst )
return CV_NULLPTR_ERR;
if( size <= 0 )
return CV_BADRANGE_ERR;
for( t = 0; t < size; t++ )
{
dst[t] = (float) (src[t]);
}
return CV_OK;
}
/*----------------------------------------------------------------------------------*/
#if 0
/* Find line which cross frame by line(a,b,c) */
static void FindLineForEpiline( CvSize imageSize,
float a,float b,float c,
CvPoint2D32f *start,CvPoint2D32f *end,
int*)
{
CvPoint2D32f frameBeg;
CvPoint2D32f frameEnd;
CvPoint2D32f cross[4];
int haveCross[4];
float dist;
haveCross[0] = 0;
haveCross[1] = 0;
haveCross[2] = 0;
haveCross[3] = 0;
frameBeg.x = 0;
frameBeg.y = 0;
frameEnd.x = (float)(imageSize.width);
frameEnd.y = 0;
haveCross[0] = icvGetCrossLineDirect(frameBeg,frameEnd,a,b,c,&cross[0]);
frameBeg.x = (float)(imageSize.width);
frameBeg.y = 0;
frameEnd.x = (float)(imageSize.width);
frameEnd.y = (float)(imageSize.height);
haveCross[1] = icvGetCrossLineDirect(frameBeg,frameEnd,a,b,c,&cross[1]);
frameBeg.x = (float)(imageSize.width);
frameBeg.y = (float)(imageSize.height);
frameEnd.x = 0;
frameEnd.y = (float)(imageSize.height);
haveCross[2] = icvGetCrossLineDirect(frameBeg,frameEnd,a,b,c,&cross[2]);
frameBeg.x = 0;
frameBeg.y = (float)(imageSize.height);
frameEnd.x = 0;
frameEnd.y = 0;
haveCross[3] = icvGetCrossLineDirect(frameBeg,frameEnd,a,b,c,&cross[3]);
int n;
float minDist = (float)(INT_MAX);
float maxDist = (float)(INT_MIN);
int maxN = -1;
int minN = -1;
double midPointX = imageSize.width / 2.0;
double midPointY = imageSize.height / 2.0;
for( n = 0; n < 4; n++ )
{
if( haveCross[n] > 0 )
{
dist = (float)((midPointX - cross[n].x)*(midPointX - cross[n].x) +
(midPointY - cross[n].y)*(midPointY - cross[n].y));
if( dist < minDist )
{
minDist = dist;
minN = n;
}
if( dist > maxDist )
{
maxDist = dist;
maxN = n;
}
}
}
if( minN >= 0 && maxN >= 0 && (minN != maxN) )
{
*start = cross[minN];
*end = cross[maxN];
}
else
{
start->x = 0;
start->y = 0;
end->x = 0;
end->y = 0;
}
return;
}
/*----------------------------------------------------------------------------------*/
static int GetAngleLinee( CvPoint2D32f epipole, CvSize imageSize,CvPoint2D32f point1,CvPoint2D32f point2)
{
float width = (float)(imageSize.width);
float height = (float)(imageSize.height);
/* Get crosslines with image corners */
/* Find four lines */
CvPoint2D32f pa,pb,pc,pd;
pa.x = 0;
pa.y = 0;
pb.x = width;
pb.y = 0;
pd.x = width;
pd.y = height;
pc.x = 0;
pc.y = height;
/* We can compute points for angle */
/* Test for place section */
float x,y;
x = epipole.x;
y = epipole.y;
if( x < 0 )
{/* 1,4,7 */
if( y < 0)
{/* 1 */
point1 = pb;
point2 = pc;
}
else if( y > height )
{/* 7 */
point1 = pa;
point2 = pd;
}
else
{/* 4 */
point1 = pa;
point2 = pc;
}
}
else if ( x > width )
{/* 3,6,9 */
if( y < 0 )
{/* 3 */
point1 = pa;
point2 = pd;
}
else if ( y > height )
{/* 9 */
point1 = pc;
point2 = pb;
}
else
{/* 6 */
point1 = pb;
point2 = pd;
}
}
else
{/* 2,5,8 */
if( y < 0 )
{/* 2 */
point1 = pa;
point2 = pb;
}
else if( y > height )
{/* 8 */
point1 = pc;
point2 = pd;
}
else
{/* 5 - point in the image */
return 2;
}
}
return 0;
}
/*--------------------------------------------------------------------------------------*/
static void icvComputePerspectiveCoeffs(const CvPoint2D32f srcQuad[4],const CvPoint2D32f dstQuad[4],double coeffs[3][3])
{/* Computes perspective coeffs for transformation from src to dst quad */
CV_FUNCNAME( "icvComputePerspectiveCoeffs" );
__BEGIN__;
double A[64];
double b[8];
double c[8];
CvPoint2D32f pt[4];
int i;
pt[0] = srcQuad[0];
pt[1] = srcQuad[1];
pt[2] = srcQuad[2];
pt[3] = srcQuad[3];
for( i = 0; i < 4; i++ )
{
#if 0
double x = dstQuad[i].x;
double y = dstQuad[i].y;
double X = pt[i].x;
double Y = pt[i].y;
#else
double x = pt[i].x;
double y = pt[i].y;
double X = dstQuad[i].x;
double Y = dstQuad[i].y;
#endif
double* a = A + i*16;
a[0] = x;
a[1] = y;
a[2] = 1;
a[3] = 0;
a[4] = 0;
a[5] = 0;
a[6] = -X*x;
a[7] = -X*y;
a += 8;
a[0] = 0;
a[1] = 0;
a[2] = 0;
a[3] = x;
a[4] = y;
a[5] = 1;
a[6] = -Y*x;
a[7] = -Y*y;
b[i*2] = X;
b[i*2 + 1] = Y;
}
{
double invA[64];
CvMat matA = cvMat( 8, 8, CV_64F, A );
CvMat matInvA = cvMat( 8, 8, CV_64F, invA );
CvMat matB = cvMat( 8, 1, CV_64F, b );
CvMat matX = cvMat( 8, 1, CV_64F, c );
CV_CALL( cvPseudoInverse( &matA, &matInvA ));
CV_CALL( cvMatMulAdd( &matInvA, &matB, 0, &matX ));
}
coeffs[0][0] = c[0];
coeffs[0][1] = c[1];
coeffs[0][2] = c[2];
coeffs[1][0] = c[3];
coeffs[1][1] = c[4];
coeffs[1][2] = c[5];
coeffs[2][0] = c[6];
coeffs[2][1] = c[7];
coeffs[2][2] = 1.0;
__END__;
return;
}
#endif
/*--------------------------------------------------------------------------------------*/
CV_IMPL void cvComputePerspectiveMap(const double c[3][3], CvArr* rectMapX, CvArr* rectMapY )
{
CV_FUNCNAME( "cvComputePerspectiveMap" );
__BEGIN__;
CvSize size;
CvMat stubx, *mapx = (CvMat*)rectMapX;
CvMat stuby, *mapy = (CvMat*)rectMapY;
int i, j;
CV_CALL( mapx = cvGetMat( mapx, &stubx ));
CV_CALL( mapy = cvGetMat( mapy, &stuby ));
if( CV_MAT_TYPE( mapx->type ) != CV_32FC1 || CV_MAT_TYPE( mapy->type ) != CV_32FC1 )
CV_ERROR( CV_StsUnsupportedFormat, "" );
size = cvGetMatSize(mapx);
assert( fabs(c[2][2] - 1.) < FLT_EPSILON );
for( i = 0; i < size.height; i++ )
{
float* mx = (float*)(mapx->data.ptr + mapx->step*i);
float* my = (float*)(mapy->data.ptr + mapy->step*i);
for( j = 0; j < size.width; j++ )
{
double w = 1./(c[2][0]*j + c[2][1]*i + 1.);
double x = (c[0][0]*j + c[0][1]*i + c[0][2])*w;
double y = (c[1][0]*j + c[1][1]*i + c[1][2])*w;
mx[j] = (float)x;
my[j] = (float)y;
}
}
__END__;
}
/*--------------------------------------------------------------------------------------*/
CV_IMPL void cvInitPerspectiveTransform( CvSize size, const CvPoint2D32f quad[4], double matrix[3][3],
CvArr* rectMap )
{
/* Computes Perspective Transform coeffs and map if need
for given image size and given result quad */
CV_FUNCNAME( "cvInitPerspectiveTransform" );
__BEGIN__;
double A[64];
double b[8];
double c[8];
CvPoint2D32f pt[4];
CvMat mapstub, *map = (CvMat*)rectMap;
int i, j;
if( map )
{
CV_CALL( map = cvGetMat( map, &mapstub ));
if( CV_MAT_TYPE( map->type ) != CV_32FC2 )
CV_ERROR( CV_StsUnsupportedFormat, "" );
if( map->width != size.width || map->height != size.height )
CV_ERROR( CV_StsUnmatchedSizes, "" );
}
pt[0] = cvPoint2D32f( 0, 0 );
pt[1] = cvPoint2D32f( size.width, 0 );
pt[2] = cvPoint2D32f( size.width, size.height );
pt[3] = cvPoint2D32f( 0, size.height );
for( i = 0; i < 4; i++ )
{
#if 0
double x = quad[i].x;
double y = quad[i].y;
double X = pt[i].x;
double Y = pt[i].y;
#else
double x = pt[i].x;
double y = pt[i].y;
double X = quad[i].x;
double Y = quad[i].y;
#endif
double* a = A + i*16;
a[0] = x;
a[1] = y;
a[2] = 1;
a[3] = 0;
a[4] = 0;
a[5] = 0;
a[6] = -X*x;
a[7] = -X*y;
a += 8;
a[0] = 0;
a[1] = 0;
a[2] = 0;
a[3] = x;
a[4] = y;
a[5] = 1;
a[6] = -Y*x;
a[7] = -Y*y;
b[i*2] = X;
b[i*2 + 1] = Y;
}
{
double invA[64];
CvMat matA = cvMat( 8, 8, CV_64F, A );
CvMat matInvA = cvMat( 8, 8, CV_64F, invA );
CvMat matB = cvMat( 8, 1, CV_64F, b );
CvMat matX = cvMat( 8, 1, CV_64F, c );
CV_CALL( cvPseudoInverse( &matA, &matInvA ));
CV_CALL( cvMatMulAdd( &matInvA, &matB, 0, &matX ));
}
matrix[0][0] = c[0];
matrix[0][1] = c[1];
matrix[0][2] = c[2];
matrix[1][0] = c[3];
matrix[1][1] = c[4];
matrix[1][2] = c[5];
matrix[2][0] = c[6];
matrix[2][1] = c[7];
matrix[2][2] = 1.0;
if( map )
{
for( i = 0; i < size.height; i++ )
{
CvPoint2D32f* maprow = (CvPoint2D32f*)(map->data.ptr + map->step*i);
for( j = 0; j < size.width; j++ )
{
double w = 1./(c[6]*j + c[7]*i + 1.);
double x = (c[0]*j + c[1]*i + c[2])*w;
double y = (c[3]*j + c[4]*i + c[5])*w;
maprow[j].x = (float)x;
maprow[j].y = (float)y;
}
}
}
__END__;
return;
}
/*-----------------------------------------------------------------------*/
/* Compute projected infinite point for second image if first image point is known */
void icvComputeeInfiniteProject1( CvMatr64d rotMatr,
CvMatr64d camMatr1,
CvMatr64d camMatr2,
CvPoint2D32f point1,
CvPoint2D32f* point2)
{
double invMatr1[9];
icvInvertMatrix_64d(camMatr1,3,invMatr1);
double P1[3];
double p1[3];
p1[0] = (double)(point1.x);
p1[1] = (double)(point1.y);
p1[2] = 1;
icvMulMatrix_64d( invMatr1,
3,3,
p1,
1,3,
P1);
double invR[9];
icvTransposeMatrix_64d( rotMatr, 3, 3, invR );
/* Change system 1 to system 2 */
double P2[3];
icvMulMatrix_64d( invR,
3,3,
P1,
1,3,
P2);
/* Now we can project this point to image 2 */
double projP[3];
icvMulMatrix_64d( camMatr2,
3,3,
P2,
1,3,
projP);
point2->x = (float)(projP[0] / projP[2]);
point2->y = (float)(projP[1] / projP[2]);
return;
}
/*-----------------------------------------------------------------------*/
/* Compute projected infinite point for second image if first image point is known */
void icvComputeeInfiniteProject2( CvMatr64d rotMatr,
CvMatr64d camMatr1,
CvMatr64d camMatr2,
CvPoint2D32f* point1,
CvPoint2D32f point2)
{
double invMatr2[9];
icvInvertMatrix_64d(camMatr2,3,invMatr2);
double P2[3];
double p2[3];
p2[0] = (double)(point2.x);
p2[1] = (double)(point2.y);
p2[2] = 1;
icvMulMatrix_64d( invMatr2,
3,3,
p2,
1,3,
P2);
/* Change system 1 to system 2 */
double P1[3];
icvMulMatrix_64d( rotMatr,
3,3,
P2,
1,3,
P1);
/* Now we can project this point to image 2 */
double projP[3];
icvMulMatrix_64d( camMatr1,
3,3,
P1,
1,3,
projP);
point1->x = (float)(projP[0] / projP[2]);
point1->y = (float)(projP[1] / projP[2]);
return;
}
/* Select best R and t for given cameras, points, ... */
/* For both cameras */
static int icvSelectBestRt( int numImages,
int* numPoints,
CvPoint2D32f* imagePoints1,
CvPoint2D32f* imagePoints2,
CvPoint3D32f* objectPoints,
CvMatr32f cameraMatrix1,
CvVect32f distortion1,
CvMatr32f rotMatrs1,
CvVect32f transVects1,
CvMatr32f cameraMatrix2,
CvVect32f distortion2,
CvMatr32f rotMatrs2,
CvVect32f transVects2,
CvMatr32f bestRotMatr,
CvVect32f bestTransVect
)
{
/* Need to convert input data 32 -> 64 */
CvPoint3D64d* objectPoints_64d;
double* rotMatrs1_64d;
double* rotMatrs2_64d;
double* transVects1_64d;
double* transVects2_64d;
double cameraMatrix1_64d[9];
double cameraMatrix2_64d[9];
double distortion1_64d[4];
double distortion2_64d[4];
/* allocate memory for 64d data */
int totalNum = 0;
for(int i = 0; i < numImages; i++ )
{
totalNum += numPoints[i];
}
objectPoints_64d = (CvPoint3D64d*)calloc(totalNum,sizeof(CvPoint3D64d));
rotMatrs1_64d = (double*)calloc(numImages,sizeof(double)*9);
rotMatrs2_64d = (double*)calloc(numImages,sizeof(double)*9);
transVects1_64d = (double*)calloc(numImages,sizeof(double)*3);
transVects2_64d = (double*)calloc(numImages,sizeof(double)*3);
/* Convert input data to 64d */
icvCvt_32f_64d((float*)objectPoints, (double*)objectPoints_64d, totalNum*3);
icvCvt_32f_64d(rotMatrs1, rotMatrs1_64d, numImages*9);
icvCvt_32f_64d(rotMatrs2, rotMatrs2_64d, numImages*9);
icvCvt_32f_64d(transVects1, transVects1_64d, numImages*3);
icvCvt_32f_64d(transVects2, transVects2_64d, numImages*3);
/* Convert to arrays */
icvCvt_32f_64d(cameraMatrix1, cameraMatrix1_64d, 9);
icvCvt_32f_64d(cameraMatrix2, cameraMatrix2_64d, 9);
icvCvt_32f_64d(distortion1, distortion1_64d, 4);
icvCvt_32f_64d(distortion2, distortion2_64d, 4);
/* for each R and t compute error for image pair */
float* errors;
errors = (float*)calloc(numImages*numImages,sizeof(float));
if( errors == 0 )
{
return CV_OUTOFMEM_ERR;
}
int currImagePair;
int currRt;
for( currRt = 0; currRt < numImages; currRt++ )
{
int begPoint = 0;
for(currImagePair = 0; currImagePair < numImages; currImagePair++ )
{
/* For current R,t R,t compute relative position of cameras */
double convRotMatr[9];
double convTransVect[3];
icvCreateConvertMatrVect( rotMatrs1_64d + currRt*9,
transVects1_64d + currRt*3,
rotMatrs2_64d + currRt*9,
transVects2_64d + currRt*3,
convRotMatr,
convTransVect);
/* Project points using relative position of cameras */
double convRotMatr2[9];
double convTransVect2[3];
convRotMatr2[0] = 1;
convRotMatr2[1] = 0;
convRotMatr2[2] = 0;
convRotMatr2[3] = 0;
convRotMatr2[4] = 1;
convRotMatr2[5] = 0;
convRotMatr2[6] = 0;
convRotMatr2[7] = 0;
convRotMatr2[8] = 1;
convTransVect2[0] = 0;
convTransVect2[1] = 0;
convTransVect2[2] = 0;
/* Compute error for given pair and Rt */
/* We must project points to image and compute error */
CvPoint2D64d* projImagePoints1;
CvPoint2D64d* projImagePoints2;
CvPoint3D64d* points1;
CvPoint3D64d* points2;
int numberPnt;
numberPnt = numPoints[currImagePair];
projImagePoints1 = (CvPoint2D64d*)calloc(numberPnt,sizeof(CvPoint2D64d));
projImagePoints2 = (CvPoint2D64d*)calloc(numberPnt,sizeof(CvPoint2D64d));
points1 = (CvPoint3D64d*)calloc(numberPnt,sizeof(CvPoint3D64d));
points2 = (CvPoint3D64d*)calloc(numberPnt,sizeof(CvPoint3D64d));
/* Transform object points to first camera position */
for(int i = 0; i < numberPnt; i++ )
{
/* Create second camera point */
CvPoint3D64d tmpPoint;
tmpPoint.x = (double)(objectPoints[i].x);
tmpPoint.y = (double)(objectPoints[i].y);
tmpPoint.z = (double)(objectPoints[i].z);
icvConvertPointSystem( tmpPoint,
points2+i,
rotMatrs2_64d + currImagePair*9,
transVects2_64d + currImagePair*3);
/* Create first camera point using R, t */
icvConvertPointSystem( points2[i],
points1+i,
convRotMatr,
convTransVect);
CvPoint3D64d tmpPoint2 = { 0, 0, 0 };
icvConvertPointSystem( tmpPoint,
&tmpPoint2,
rotMatrs1_64d + currImagePair*9,
transVects1_64d + currImagePair*3);
/*double err;
double dx,dy,dz;
dx = tmpPoint2.x - points1[i].x;
dy = tmpPoint2.y - points1[i].y;
dz = tmpPoint2.z - points1[i].z;
err = sqrt(dx*dx + dy*dy + dz*dz);*/
}
#if 0
cvProjectPointsSimple( numPoints[currImagePair],
objectPoints_64d + begPoint,
rotMatrs1_64d + currRt*9,
transVects1_64d + currRt*3,
cameraMatrix1_64d,
distortion1_64d,
projImagePoints1);
cvProjectPointsSimple( numPoints[currImagePair],
objectPoints_64d + begPoint,
rotMatrs2_64d + currRt*9,
transVects2_64d + currRt*3,
cameraMatrix2_64d,
distortion2_64d,
projImagePoints2);
#endif
/* Project with no translate and no rotation */
#if 0
{
double nodist[4] = {0,0,0,0};
cvProjectPointsSimple( numPoints[currImagePair],
points1,
convRotMatr2,
convTransVect2,
cameraMatrix1_64d,
nodist,
projImagePoints1);
cvProjectPointsSimple( numPoints[currImagePair],
points2,
convRotMatr2,
convTransVect2,
cameraMatrix2_64d,
nodist,
projImagePoints2);
}
#endif
cvProjectPointsSimple( numPoints[currImagePair],
points1,
convRotMatr2,
convTransVect2,
cameraMatrix1_64d,
distortion1_64d,
projImagePoints1);
cvProjectPointsSimple( numPoints[currImagePair],
points2,
convRotMatr2,
convTransVect2,
cameraMatrix2_64d,
distortion2_64d,
projImagePoints2);
/* points are projected. Compute error */
int currPoint;
double err1 = 0;
double err2 = 0;
double err;
for( currPoint = 0; currPoint < numberPnt; currPoint++ )
{
double len1,len2;
double dx1,dy1;
dx1 = imagePoints1[begPoint+currPoint].x - projImagePoints1[currPoint].x;
dy1 = imagePoints1[begPoint+currPoint].y - projImagePoints1[currPoint].y;
len1 = sqrt(dx1*dx1 + dy1*dy1);
err1 += len1;
double dx2,dy2;
dx2 = imagePoints2[begPoint+currPoint].x - projImagePoints2[currPoint].x;
dy2 = imagePoints2[begPoint+currPoint].y - projImagePoints2[currPoint].y;
len2 = sqrt(dx2*dx2 + dy2*dy2);
err2 += len2;
}
err1 /= (float)(numberPnt);
err2 /= (float)(numberPnt);
err = (err1+err2) * 0.5;
begPoint += numberPnt;
/* Set this error to */
errors[numImages*currImagePair+currRt] = (float)err;
free(points1);
free(points2);
free(projImagePoints1);
free(projImagePoints2);
}
}
/* Just select R and t with minimal average error */
int bestnumRt = 0;
float minError = 0;/* Just for no warnings. Uses 'first' flag. */
int first = 1;
for( currRt = 0; currRt < numImages; currRt++ )
{
float avErr = 0;
for(currImagePair = 0; currImagePair < numImages; currImagePair++ )
{
avErr += errors[numImages*currImagePair+currRt];
}
avErr /= (float)(numImages);
if( first )
{
bestnumRt = 0;
minError = avErr;
first = 0;
}
else
{
if( avErr < minError )
{
bestnumRt = currRt;
minError = avErr;
}
}
}
double bestRotMatr_64d[9];
double bestTransVect_64d[3];
icvCreateConvertMatrVect( rotMatrs1_64d + bestnumRt * 9,
transVects1_64d + bestnumRt * 3,
rotMatrs2_64d + bestnumRt * 9,
transVects2_64d + bestnumRt * 3,
bestRotMatr_64d,
bestTransVect_64d);
icvCvt_64d_32f(bestRotMatr_64d,bestRotMatr,9);
icvCvt_64d_32f(bestTransVect_64d,bestTransVect,3);
free(errors);
return CV_OK;
}
/* ----------------- Stereo calibration functions --------------------- */
float icvDefinePointPosition(CvPoint2D32f point1,CvPoint2D32f point2,CvPoint2D32f point)
{
float ax = point2.x - point1.x;
float ay = point2.y - point1.y;
float bx = point.x - point1.x;
float by = point.y - point1.y;
return (ax*by - ay*bx);
}
/* Convert function for stereo warping */
int icvConvertWarpCoordinates(double coeffs[3][3],
CvPoint2D32f* cameraPoint,
CvPoint2D32f* warpPoint,
int direction)
{
double x,y;
double det;
if( direction == CV_WARP_TO_CAMERA )
{/* convert from camera image to warped image coordinates */
x = warpPoint->x;
y = warpPoint->y;
det = (coeffs[2][0] * x + coeffs[2][1] * y + coeffs[2][2]);
if( fabs(det) > 1e-8 )
{
cameraPoint->x = (float)((coeffs[0][0] * x + coeffs[0][1] * y + coeffs[0][2]) / det);
cameraPoint->y = (float)((coeffs[1][0] * x + coeffs[1][1] * y + coeffs[1][2]) / det);
return CV_OK;
}
}
else if( direction == CV_CAMERA_TO_WARP )
{/* convert from warped image to camera image coordinates */
x = cameraPoint->x;
y = cameraPoint->y;
det = (coeffs[2][0]*x-coeffs[0][0])*(coeffs[2][1]*y-coeffs[1][1])-(coeffs[2][1]*x-coeffs[0][1])*(coeffs[2][0]*y-coeffs[1][0]);
if( fabs(det) > 1e-8 )
{
warpPoint->x = (float)(((coeffs[0][2]-coeffs[2][2]*x)*(coeffs[2][1]*y-coeffs[1][1])-(coeffs[2][1]*x-coeffs[0][1])*(coeffs[1][2]-coeffs[2][2]*y))/det);
warpPoint->y = (float)(((coeffs[2][0]*x-coeffs[0][0])*(coeffs[1][2]-coeffs[2][2]*y)-(coeffs[0][2]-coeffs[2][2]*x)*(coeffs[2][0]*y-coeffs[1][0]))/det);
return CV_OK;
}
}
return CV_BADFACTOR_ERR;
}
/* Compute stereo params using some camera params */
/* by Valery Mosyagin. int ComputeRestStereoParams(StereoParams *stereoparams) */
int icvComputeRestStereoParams(CvStereoCamera *stereoparams)
{
icvGetQuadsTransformStruct(stereoparams);
cvInitPerspectiveTransform( stereoparams->warpSize,
stereoparams->quad[0],
stereoparams->coeffs[0],
0);
cvInitPerspectiveTransform( stereoparams->warpSize,
stereoparams->quad[1],
stereoparams->coeffs[1],
0);
/* Create border for warped images */
CvPoint2D32f corns[4];
corns[0].x = 0;
corns[0].y = 0;
corns[1].x = (float)(stereoparams->camera[0]->imgSize[0]-1);
corns[1].y = 0;
corns[2].x = (float)(stereoparams->camera[0]->imgSize[0]-1);
corns[2].y = (float)(stereoparams->camera[0]->imgSize[1]-1);
corns[3].x = 0;
corns[3].y = (float)(stereoparams->camera[0]->imgSize[1]-1);
for(int i = 0; i < 4; i++ )
{
/* For first camera */
icvConvertWarpCoordinates( stereoparams->coeffs[0],
corns+i,
stereoparams->border[0]+i,
CV_CAMERA_TO_WARP);
/* For second camera */
icvConvertWarpCoordinates( stereoparams->coeffs[1],
corns+i,
stereoparams->border[1]+i,
CV_CAMERA_TO_WARP);
}
/* Test compute */
{
CvPoint2D32f warpPoints[4];
warpPoints[0] = cvPoint2D32f(0,0);
warpPoints[1] = cvPoint2D32f(stereoparams->warpSize.width-1,0);
warpPoints[2] = cvPoint2D32f(stereoparams->warpSize.width-1,stereoparams->warpSize.height-1);
warpPoints[3] = cvPoint2D32f(0,stereoparams->warpSize.height-1);
CvPoint2D32f camPoints1[4];
CvPoint2D32f camPoints2[4];
for( int i = 0; i < 4; i++ )
{
icvConvertWarpCoordinates(stereoparams->coeffs[0],
camPoints1+i,
warpPoints+i,
CV_WARP_TO_CAMERA);
icvConvertWarpCoordinates(stereoparams->coeffs[1],
camPoints2+i,
warpPoints+i,
CV_WARP_TO_CAMERA);
}
}
/* Allocate memory for scanlines coeffs */
stereoparams->lineCoeffs = (CvStereoLineCoeff*)calloc(stereoparams->warpSize.height,sizeof(CvStereoLineCoeff));
/* Compute coeffs for epilines */
icvComputeCoeffForStereo( stereoparams);
/* all coeffs are known */
return CV_OK;
}
/*-------------------------------------------------------------------------------------------*/
int icvStereoCalibration( int numImages,
int* nums,
CvSize imageSize,
CvPoint2D32f* imagePoints1,
CvPoint2D32f* imagePoints2,
CvPoint3D32f* objectPoints,
CvStereoCamera* stereoparams
)
{
/* Firstly we must calibrate both cameras */
/* Alocate memory for data */
/* Allocate for translate vectors */
float* transVects1;
float* transVects2;
float* rotMatrs1;
float* rotMatrs2;
transVects1 = (float*)calloc(numImages,sizeof(float)*3);
transVects2 = (float*)calloc(numImages,sizeof(float)*3);
rotMatrs1 = (float*)calloc(numImages,sizeof(float)*9);
rotMatrs2 = (float*)calloc(numImages,sizeof(float)*9);
/* Calibrate first camera */
cvCalibrateCamera( numImages,
nums,
imageSize,
imagePoints1,
objectPoints,
stereoparams->camera[0]->distortion,
stereoparams->camera[0]->matrix,
transVects1,
rotMatrs1,
1);
/* Calibrate second camera */
cvCalibrateCamera( numImages,
nums,
imageSize,
imagePoints2,
objectPoints,
stereoparams->camera[1]->distortion,
stereoparams->camera[1]->matrix,
transVects2,
rotMatrs2,
1);
/* Cameras are calibrated */
stereoparams->camera[0]->imgSize[0] = (float)imageSize.width;
stereoparams->camera[0]->imgSize[1] = (float)imageSize.height;
stereoparams->camera[1]->imgSize[0] = (float)imageSize.width;
stereoparams->camera[1]->imgSize[1] = (float)imageSize.height;
icvSelectBestRt( numImages,
nums,
imagePoints1,
imagePoints2,
objectPoints,
stereoparams->camera[0]->matrix,
stereoparams->camera[0]->distortion,
rotMatrs1,
transVects1,
stereoparams->camera[1]->matrix,
stereoparams->camera[1]->distortion,
rotMatrs2,
transVects2,
stereoparams->rotMatrix,
stereoparams->transVector
);
/* Free memory */
free(transVects1);
free(transVects2);
free(rotMatrs1);
free(rotMatrs2);
icvComputeRestStereoParams(stereoparams);
return CV_NO_ERR;
}
#if 0
/* Find line from epipole */
static void FindLine(CvPoint2D32f epipole,CvSize imageSize,CvPoint2D32f point,CvPoint2D32f *start,CvPoint2D32f *end)
{
CvPoint2D32f frameBeg;
CvPoint2D32f frameEnd;
CvPoint2D32f cross[4];
int haveCross[4];
float dist;
haveCross[0] = 0;
haveCross[1] = 0;
haveCross[2] = 0;
haveCross[3] = 0;
frameBeg.x = 0;
frameBeg.y = 0;
frameEnd.x = (float)(imageSize.width);
frameEnd.y = 0;
haveCross[0] = icvGetCrossPieceVector(frameBeg,frameEnd,epipole,point,&cross[0]);
frameBeg.x = (float)(imageSize.width);
frameBeg.y = 0;
frameEnd.x = (float)(imageSize.width);
frameEnd.y = (float)(imageSize.height);
haveCross[1] = icvGetCrossPieceVector(frameBeg,frameEnd,epipole,point,&cross[1]);
frameBeg.x = (float)(imageSize.width);
frameBeg.y = (float)(imageSize.height);
frameEnd.x = 0;
frameEnd.y = (float)(imageSize.height);
haveCross[2] = icvGetCrossPieceVector(frameBeg,frameEnd,epipole,point,&cross[2]);
frameBeg.x = 0;
frameBeg.y = (float)(imageSize.height);
frameEnd.x = 0;
frameEnd.y = 0;
haveCross[3] = icvGetCrossPieceVector(frameBeg,frameEnd,epipole,point,&cross[3]);
int n;
float minDist = (float)(INT_MAX);
float maxDist = (float)(INT_MIN);
int maxN = -1;
int minN = -1;
for( n = 0; n < 4; n++ )
{
if( haveCross[n] > 0 )
{
dist = (epipole.x - cross[n].x)*(epipole.x - cross[n].x) +
(epipole.y - cross[n].y)*(epipole.y - cross[n].y);
if( dist < minDist )
{
minDist = dist;
minN = n;
}
if( dist > maxDist )
{
maxDist = dist;
maxN = n;
}
}
}
if( minN >= 0 && maxN >= 0 && (minN != maxN) )
{
*start = cross[minN];
*end = cross[maxN];
}
else
{
start->x = 0;
start->y = 0;
end->x = 0;
end->y = 0;
}
return;
}
/* Find line which cross frame by line(a,b,c) */
static void FindLineForEpiline(CvSize imageSize,float a,float b,float c,CvPoint2D32f *start,CvPoint2D32f *end)
{
CvPoint2D32f frameBeg;
CvPoint2D32f frameEnd;
CvPoint2D32f cross[4];
int haveCross[4];
float dist;
haveCross[0] = 0;
haveCross[1] = 0;
haveCross[2] = 0;
haveCross[3] = 0;
frameBeg.x = 0;
frameBeg.y = 0;
frameEnd.x = (float)(imageSize.width);
frameEnd.y = 0;
haveCross[0] = icvGetCrossLineDirect(frameBeg,frameEnd,a,b,c,&cross[0]);
frameBeg.x = (float)(imageSize.width);
frameBeg.y = 0;
frameEnd.x = (float)(imageSize.width);
frameEnd.y = (float)(imageSize.height);
haveCross[1] = icvGetCrossLineDirect(frameBeg,frameEnd,a,b,c,&cross[1]);
frameBeg.x = (float)(imageSize.width);
frameBeg.y = (float)(imageSize.height);
frameEnd.x = 0;
frameEnd.y = (float)(imageSize.height);
haveCross[2] = icvGetCrossLineDirect(frameBeg,frameEnd,a,b,c,&cross[2]);
frameBeg.x = 0;
frameBeg.y = (float)(imageSize.height);
frameEnd.x = 0;
frameEnd.y = 0;
haveCross[3] = icvGetCrossLineDirect(frameBeg,frameEnd,a,b,c,&cross[3]);
int n;
float minDist = (float)(INT_MAX);
float maxDist = (float)(INT_MIN);
int maxN = -1;
int minN = -1;
double midPointX = imageSize.width / 2.0;
double midPointY = imageSize.height / 2.0;
for( n = 0; n < 4; n++ )
{
if( haveCross[n] > 0 )
{
dist = (float)((midPointX - cross[n].x)*(midPointX - cross[n].x) +
(midPointY - cross[n].y)*(midPointY - cross[n].y));
if( dist < minDist )
{
minDist = dist;
minN = n;
}
if( dist > maxDist )
{
maxDist = dist;
maxN = n;
}
}
}
if( minN >= 0 && maxN >= 0 && (minN != maxN) )
{
*start = cross[minN];
*end = cross[maxN];
}
else
{
start->x = 0;
start->y = 0;
end->x = 0;
end->y = 0;
}
return;
}
/* Cross lines */
static int GetCrossLines(CvPoint2D32f p1_start,CvPoint2D32f p1_end,CvPoint2D32f p2_start,CvPoint2D32f p2_end,CvPoint2D32f *cross)
{
double ex1,ey1,ex2,ey2;
double px1,py1,px2,py2;
double del;
double delA,delB,delX,delY;
double alpha,betta;
ex1 = p1_start.x;
ey1 = p1_start.y;
ex2 = p1_end.x;
ey2 = p1_end.y;
px1 = p2_start.x;
py1 = p2_start.y;
px2 = p2_end.x;
py2 = p2_end.y;
del = (ex1-ex2)*(py2-py1)+(ey2-ey1)*(px2-px1);
if( del == 0)
{
return -1;
}
delA = (px1-ex1)*(py1-py2) + (ey1-py1)*(px1-px2);
delB = (ex1-px1)*(ey1-ey2) + (py1-ey1)*(ex1-ex2);
alpha = delA / del;
betta = -delB / del;
if( alpha < 0 || alpha > 1.0 || betta < 0 || betta > 1.0)
{
return -1;
}
delX = (ex1-ex2)*(py1*(px1-px2)-px1*(py1-py2))+
(px1-px2)*(ex1*(ey1-ey2)-ey1*(ex1-ex2));
delY = (ey1-ey2)*(px1*(py1-py2)-py1*(px1-px2))+
(py1-py2)*(ey1*(ex1-ex2)-ex1*(ey1-ey2));
cross->x = (float)( delX / del);
cross->y = (float)(-delY / del);
return 1;
}
#endif
int icvGetCrossPieceVector(CvPoint2D32f p1_start,CvPoint2D32f p1_end,CvPoint2D32f v2_start,CvPoint2D32f v2_end,CvPoint2D32f *cross)
{
double ex1 = p1_start.x;
double ey1 = p1_start.y;
double ex2 = p1_end.x;
double ey2 = p1_end.y;
double px1 = v2_start.x;
double py1 = v2_start.y;
double px2 = v2_end.x;
double py2 = v2_end.y;
double del = (ex1-ex2)*(py2-py1)+(ey2-ey1)*(px2-px1);
if( del == 0)
{
return -1;
}
double delA = (px1-ex1)*(py1-py2) + (ey1-py1)*(px1-px2);
//double delB = (ex1-px1)*(ey1-ey2) + (py1-ey1)*(ex1-ex2);
double alpha = delA / del;
//double betta = -delB / del;
if( alpha < 0 || alpha > 1.0 )
{
return -1;
}
double delX = (ex1-ex2)*(py1*(px1-px2)-px1*(py1-py2))+
(px1-px2)*(ex1*(ey1-ey2)-ey1*(ex1-ex2));
double delY = (ey1-ey2)*(px1*(py1-py2)-py1*(px1-px2))+
(py1-py2)*(ey1*(ex1-ex2)-ex1*(ey1-ey2));
cross->x = (float)( delX / del);
cross->y = (float)(-delY / del);
return 1;
}
int icvGetCrossLineDirect(CvPoint2D32f p1,CvPoint2D32f p2,float a,float b,float c,CvPoint2D32f* cross)
{
double del;
double delX,delY,delA;
double px1,px2,py1,py2;
double X,Y,alpha;
px1 = p1.x;
py1 = p1.y;
px2 = p2.x;
py2 = p2.y;
del = a * (px2 - px1) + b * (py2-py1);
if( del == 0 )
{
return -1;
}
delA = - c - a*px1 - b*py1;
alpha = delA / del;
if( alpha < 0 || alpha > 1.0 )
{
return -1;/* no cross */
}
delX = b * (py1*(px1-px2) - px1*(py1-py2)) + c * (px1-px2);
delY = a * (px1*(py1-py2) - py1*(px1-px2)) + c * (py1-py2);
X = delX / del;
Y = delY / del;
cross->x = (float)X;
cross->y = (float)Y;
return 1;
}
#if 0
static int cvComputeEpipoles( CvMatr32f camMatr1, CvMatr32f camMatr2,
CvMatr32f rotMatr1, CvMatr32f rotMatr2,
CvVect32f transVect1,CvVect32f transVect2,
CvVect32f epipole1,
CvVect32f epipole2)
{
/* Copy matrix */
CvMat ccamMatr1 = cvMat(3,3,CV_MAT32F,camMatr1);
CvMat ccamMatr2 = cvMat(3,3,CV_MAT32F,camMatr2);
CvMat crotMatr1 = cvMat(3,3,CV_MAT32F,rotMatr1);
CvMat crotMatr2 = cvMat(3,3,CV_MAT32F,rotMatr2);
CvMat ctransVect1 = cvMat(3,1,CV_MAT32F,transVect1);
CvMat ctransVect2 = cvMat(3,1,CV_MAT32F,transVect2);
CvMat cepipole1 = cvMat(3,1,CV_MAT32F,epipole1);
CvMat cepipole2 = cvMat(3,1,CV_MAT32F,epipole2);
CvMat cmatrP1 = cvMat(3,3,CV_MAT32F,0); cvmAlloc(&cmatrP1);
CvMat cmatrP2 = cvMat(3,3,CV_MAT32F,0); cvmAlloc(&cmatrP2);
CvMat cvectp1 = cvMat(3,1,CV_MAT32F,0); cvmAlloc(&cvectp1);
CvMat cvectp2 = cvMat(3,1,CV_MAT32F,0); cvmAlloc(&cvectp2);
CvMat ctmpF1 = cvMat(3,1,CV_MAT32F,0); cvmAlloc(&ctmpF1);
CvMat ctmpM1 = cvMat(3,3,CV_MAT32F,0); cvmAlloc(&ctmpM1);
CvMat ctmpM2 = cvMat(3,3,CV_MAT32F,0); cvmAlloc(&ctmpM2);
CvMat cinvP1 = cvMat(3,3,CV_MAT32F,0); cvmAlloc(&cinvP1);
CvMat cinvP2 = cvMat(3,3,CV_MAT32F,0); cvmAlloc(&cinvP2);
CvMat ctmpMatr = cvMat(3,3,CV_MAT32F,0); cvmAlloc(&ctmpMatr);
CvMat ctmpVect1 = cvMat(3,1,CV_MAT32F,0); cvmAlloc(&ctmpVect1);
CvMat ctmpVect2 = cvMat(3,1,CV_MAT32F,0); cvmAlloc(&ctmpVect2);
CvMat cmatrF1 = cvMat(3,3,CV_MAT32F,0); cvmAlloc(&cmatrF1);
CvMat ctmpF = cvMat(3,3,CV_MAT32F,0); cvmAlloc(&ctmpF);
CvMat ctmpE1 = cvMat(3,1,CV_MAT32F,0); cvmAlloc(&ctmpE1);
CvMat ctmpE2 = cvMat(3,1,CV_MAT32F,0); cvmAlloc(&ctmpE2);
/* Compute first */
cvmMul( &ccamMatr1, &crotMatr1, &cmatrP1);
cvmInvert( &cmatrP1,&cinvP1 );
cvmMul( &ccamMatr1, &ctransVect1, &cvectp1 );
/* Compute second */
cvmMul( &ccamMatr2, &crotMatr2, &cmatrP2 );
cvmInvert( &cmatrP2,&cinvP2 );
cvmMul( &ccamMatr2, &ctransVect2, &cvectp2 );
cvmMul( &cmatrP1, &cinvP2, &ctmpM1);
cvmMul( &ctmpM1, &cvectp2, &ctmpVect1);
cvmSub( &cvectp1,&ctmpVect1,&ctmpE1);
cvmMul( &cmatrP2, &cinvP1, &ctmpM2);
cvmMul( &ctmpM2, &cvectp1, &ctmpVect2);
cvmSub( &cvectp2, &ctmpVect2, &ctmpE2);
/* Need scale */
cvmScale(&ctmpE1,&cepipole1,1.0);
cvmScale(&ctmpE2,&cepipole2,1.0);
cvmFree(&cmatrP1);
cvmFree(&cmatrP1);
cvmFree(&cvectp1);
cvmFree(&cvectp2);
cvmFree(&ctmpF1);
cvmFree(&ctmpM1);
cvmFree(&ctmpM2);
cvmFree(&cinvP1);
cvmFree(&cinvP2);
cvmFree(&ctmpMatr);
cvmFree(&ctmpVect1);
cvmFree(&ctmpVect2);
cvmFree(&cmatrF1);
cvmFree(&ctmpF);
cvmFree(&ctmpE1);
cvmFree(&ctmpE2);
return CV_NO_ERR;
}/* cvComputeEpipoles */
#endif
/* Compute epipoles for fundamental matrix */
int cvComputeEpipolesFromFundMatrix(CvMatr32f fundMatr,
CvPoint3D32f* epipole1,
CvPoint3D32f* epipole2)
{
/* Decompose fundamental matrix using SVD ( A = U W V') */
CvMat fundMatrC = cvMat(3,3,CV_MAT32F,fundMatr);
CvMat* matrW = cvCreateMat(3,3,CV_MAT32F);
CvMat* matrU = cvCreateMat(3,3,CV_MAT32F);
CvMat* matrV = cvCreateMat(3,3,CV_MAT32F);
/* From svd we need just last vector of U and V or last row from U' and V' */
/* We get transposed matrices U and V */
cvSVD(&fundMatrC,matrW,matrU,matrV,CV_SVD_V_T|CV_SVD_U_T);
/* Get last row from U' and compute epipole1 */
epipole1->x = matrU->data.fl[6];
epipole1->y = matrU->data.fl[7];
epipole1->z = matrU->data.fl[8];
/* Get last row from V' and compute epipole2 */
epipole2->x = matrV->data.fl[6];
epipole2->y = matrV->data.fl[7];
epipole2->z = matrV->data.fl[8];
cvReleaseMat(&matrW);
cvReleaseMat(&matrU);
cvReleaseMat(&matrV);
return CV_OK;
}
int cvConvertEssential2Fundamental( CvMatr32f essMatr,
CvMatr32f fundMatr,
CvMatr32f cameraMatr1,
CvMatr32f cameraMatr2)
{/* Fund = inv(CM1') * Ess * inv(CM2) */
CvMat essMatrC = cvMat(3,3,CV_MAT32F,essMatr);
CvMat fundMatrC = cvMat(3,3,CV_MAT32F,fundMatr);
CvMat cameraMatr1C = cvMat(3,3,CV_MAT32F,cameraMatr1);
CvMat cameraMatr2C = cvMat(3,3,CV_MAT32F,cameraMatr2);
CvMat* invCM2 = cvCreateMat(3,3,CV_MAT32F);
CvMat* tmpMatr = cvCreateMat(3,3,CV_MAT32F);
CvMat* invCM1T = cvCreateMat(3,3,CV_MAT32F);
cvTranspose(&cameraMatr1C,tmpMatr);
cvInvert(tmpMatr,invCM1T);
cvmMul(invCM1T,&essMatrC,tmpMatr);
cvInvert(&cameraMatr2C,invCM2);
cvmMul(tmpMatr,invCM2,&fundMatrC);
/* Scale fundamental matrix */
double scale;
scale = 1.0/fundMatrC.data.fl[8];
cvConvertScale(&fundMatrC,&fundMatrC,scale);
cvReleaseMat(&invCM2);
cvReleaseMat(&tmpMatr);
cvReleaseMat(&invCM1T);
return CV_OK;
}
/* Compute essential matrix */
int cvComputeEssentialMatrix( CvMatr32f rotMatr,
CvMatr32f transVect,
CvMatr32f essMatr)
{
float transMatr[9];
/* Make antisymmetric matrix from transpose vector */
transMatr[0] = 0;
transMatr[1] = - transVect[2];
transMatr[2] = transVect[1];
transMatr[3] = transVect[2];
transMatr[4] = 0;
transMatr[5] = - transVect[0];
transMatr[6] = - transVect[1];
transMatr[7] = transVect[0];
transMatr[8] = 0;
icvMulMatrix_32f(transMatr,3,3,rotMatr,3,3,essMatr);
return CV_OK;
}
|
44c02fbf230b4997504447f98a69c22633cb00f6
|
4f4d5fb91b80c1f69966bd29c0fbd83890417371
|
/Projects/FinalProject/UseItemRoom.hpp
|
9d8c6ccb7dfc7886e45a61dca5ae7bf174a19fe0
|
[] |
no_license
|
Huffmajo/CS162
|
62b3bda16c7fa054a7658f72dbe043c85caa3fb7
|
60d7063d8826cf939ac42bb53b2163f2e45f3635
|
refs/heads/master
| 2021-09-16T05:13:46.134720
| 2018-06-16T22:38:13
| 2018-06-16T22:38:13
| 137,614,621
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 619
|
hpp
|
UseItemRoom.hpp
|
/*********************************************************************
** Program name: Race to the Throne
** Author: Joel Huffman
** Date: 03/7/18
** Description: A text-based adventure game
*********************************************************************/
#ifndef UseItemRoom_hpp
#define UseItemRoom_hpp
#include "Space.hpp"
class UseItemRoom: public Space
{
private:
public:
UseItemRoom();
~UseItemRoom();
void useItem(item activeItem, Player* p);
void talk(Player* p);
void pickUp(Player* p);
//void examineRoom();
};
#endif /* UseItemRoom_hpp */
|
7e91822ae7e47445d2c07fc77f8184fbaebab65e
|
2a8d5db78a76a109b2b38e86654f02795c66f5f0
|
/code/Prey/game_talon.cpp
|
d7094cbec42946e725f66f93601696aca0f06c52
|
[] |
no_license
|
dirtydanisreal/PreyDoom
|
a7302082561c856b067be94daf2024853a4a5124
|
543e9ebf40d1cf0d82f7f74f542d07aacafeca6c
|
refs/heads/master
| 2023-09-01T06:31:59.604401
| 2023-08-18T18:49:41
| 2023-08-18T18:49:41
| 311,948,860
| 0
| 0
| null | 2020-11-11T11:21:32
| 2020-11-11T11:21:31
| null |
UTF-8
|
C++
| false
| false
| 51,489
|
cpp
|
game_talon.cpp
|
//*****************************************************************************
//**
//** GAME_TALON.CPP
//**
//** Game code for Tommy's sidekick, Talon the Hawk
//**
//*****************************************************************************
// HEADER FILES ---------------------------------------------------------------
#include "precompiled.h"
#pragma hdrstop
#include "prey_local.h"
// MACROS ---------------------------------------------------------------------
#define PERCH_ROTATION 3.5
#define ROTATION_SPEED 3.5
#define ROTATION_SPEED_FAST 5
#define TALON_BLEND 100
// TYPES ----------------------------------------------------------------------
// CLASS DECLARATIONS ---------------------------------------------------------
const idEventDef EV_PerchTicker("<perchTicker>", NULL);
const idEventDef EV_PerchChatter("perchChatter", NULL);
const idEventDef EV_PerchSquawk("<perchSquawk>", NULL);
const idEventDef EV_CheckForTarget( "<checkForTarget>", NULL );
const idEventDef EV_CheckForEnemy( "<checkForEnemy>", NULL );
const idEventDef EV_TalonAction("talonaction", "ed");
// Anim Events
const idEventDef EV_LandAnim("<landAnim>", NULL);
const idEventDef EV_PreLandAnim("<prelandAnim>", NULL);
const idEventDef EV_IdleAnim("<idleAnim>", NULL);
const idEventDef EV_TommyIdleAnim("<tommyIdleAnim>", NULL);
const idEventDef EV_FlyAnim("<flyAnim>", NULL);
const idEventDef EV_GlideAnim("<glideAnim>", NULL);
const idEventDef EV_TakeOffAnim("<takeOffAnim>", NULL);
const idEventDef EV_TakeOffAnimB("<takeOffAnimB>", NULL);
CLASS_DECLARATION( hhMonsterAI, hhTalon )
EVENT(EV_PerchChatter, hhTalon::Event_PerchChatter)
EVENT(EV_PerchSquawk, hhTalon::Event_PerchSquawk)
EVENT(EV_CheckForTarget, hhTalon::Event_CheckForTarget)
EVENT(EV_CheckForEnemy, hhTalon::Event_CheckForEnemy)
// Anims
EVENT(EV_LandAnim, hhTalon::Event_LandAnim)
EVENT(EV_PreLandAnim, hhTalon::Event_PreLandAnim)
EVENT(EV_IdleAnim, hhTalon::Event_IdleAnim)
EVENT(EV_TommyIdleAnim, hhTalon::Event_TommyIdleAnim)
EVENT(EV_FlyAnim, hhTalon::Event_FlyAnim)
EVENT(EV_GlideAnim, hhTalon::Event_GlideAnim)
EVENT(EV_TakeOffAnim, hhTalon::Event_TakeOffAnim)
EVENT(EV_TakeOffAnimB, hhTalon::Event_TakeOffAnimB)
END_CLASS
const idEventDef EV_CallTalon("callTalon", "fff" );
const idEventDef EV_ReleaseTalon("releaseTalon", NULL );
const idEventDef EV_SetPerchState("setPerchState", "f" );
CLASS_DECLARATION( idEntity, hhTalonTarget )
EVENT( EV_CallTalon, hhTalonTarget::Event_CallTalon )
EVENT( EV_ReleaseTalon, hhTalonTarget::Event_ReleaseTalon )
EVENT( EV_SetPerchState, hhTalonTarget::Event_SetPerchState )
END_CLASS
// STATE DECLARATIONS ---------------------------------------------------------
// EXTERNAL FUNCTION PROTOTYPES -----------------------------------------------
// PRIVATE FUNCTION PROTOTYPES ------------------------------------------------
// EXTERNAL DATA DECLARATIONS -------------------------------------------------
// PUBLIC DATA DEFINITIONS ----------------------------------------------------
// PRIVATE DATA DEFINITIONS ---------------------------------------------------
// CODE -----------------------------------------------------------------------
//=============================================================================
//
// hhTalon::Spawn
//
//=============================================================================
void hhTalon::Spawn(void) {
flyAnim = GetAnimator()->GetAnim("fly");
glideAnim = GetAnimator()->GetAnim("glide");
prelandAnim = GetAnimator()->GetAnim("preland");
landAnim = GetAnimator()->GetAnim("land");
idleAnim = GetAnimator()->GetAnim("idle");
tommyIdleAnim = GetAnimator()->GetAnim("tommy_idle");
squawkAnim = GetAnimator()->GetAnim("squawk");
stepAnim = GetAnimator()->GetAnim("step");
takeOffAnim = GetAnimator()->GetAnim("takeoffA");
takeOffAnimB = GetAnimator()->GetAnim("takeoffB");
attackAnim = GetAnimator()->GetAnim("attack1");
preAttackAnim = GetAnimator()->GetAnim("preattack");
fl.neverDormant = true;
fl.takedamage = false;
fl.notarget = true;
allowHiddenMovement = true; // Allow Talon to move while hidden
health = 1; // Talon need some health for enemies to consider it alive
//AOB
GetAnimator()->RemoveOriginOffset( true );
// Register the wings skins
openWingsSkin = declManager->FindSkin( spawnArgs.GetString("skin_openWings") );
closedWingsSkin = declManager->FindSkin( spawnArgs.GetString("skin_closeWings") );
Event_SetMoveType(MOVETYPE_FLY);
GetPhysics()->SetContents( 0 ); // No collisions
GetPhysics()->SetClipMask( 0 ); // No collisions
Hide();
BecomeInactive(TH_THINK);
}
void hhTalon::Save(idSaveGame *savefile) const {
owner.Save(savefile);
savefile->WriteVec3(velocity);
savefile->WriteVec3(acceleration);
savefile->WriteObject(talonTarget);
savefile->WriteVec3(talonTargetLoc);
savefile->WriteMat3(talonTargetAxis);
savefile->WriteVec3(lastCheckOrigin);
savefile->WriteFloat(checkTraceTime);
savefile->WriteFloat(checkFlyTime);
savefile->WriteFloat(flyStraightTime);
savefile->WriteBool(bLanding);
savefile->WriteBool(bReturnToTommy);
savefile->WriteBool( bForcedTarget );
savefile->WriteBool( bClawingAtEnemy );
savefile->WriteFloat( velocityFactor );
savefile->WriteFloat( rotationFactor );
savefile->WriteFloat( perchRotationFactor );
savefile->WriteInt(flyAnim);
savefile->WriteInt(glideAnim);
savefile->WriteInt(prelandAnim);
savefile->WriteInt(landAnim);
savefile->WriteInt(idleAnim);
savefile->WriteInt(tommyIdleAnim);
savefile->WriteInt(squawkAnim);
savefile->WriteInt(stepAnim);
savefile->WriteInt(takeOffAnim);
savefile->WriteInt(takeOffAnimB);
savefile->WriteInt(attackAnim);
savefile->WriteInt(preAttackAnim);
savefile->WriteSkin(openWingsSkin);
savefile->WriteSkin(closedWingsSkin);
enemy.Save( savefile );
trailFx.Save( savefile );
savefile->WriteInt( state );
}
void hhTalon::Restore( idRestoreGame *savefile ) {
owner.Restore(savefile);
savefile->ReadVec3(velocity);
savefile->ReadVec3(acceleration);
savefile->ReadObject( reinterpret_cast<idClass *&>(talonTarget) );
savefile->ReadVec3(talonTargetLoc);
savefile->ReadMat3(talonTargetAxis);
savefile->ReadVec3(lastCheckOrigin);
savefile->ReadFloat(checkTraceTime);
savefile->ReadFloat(checkFlyTime);
savefile->ReadFloat(flyStraightTime);
savefile->ReadBool(bLanding);
savefile->ReadBool(bReturnToTommy);
savefile->ReadBool( bForcedTarget );
savefile->ReadBool( bClawingAtEnemy );
savefile->ReadFloat( velocityFactor );
savefile->ReadFloat( rotationFactor );
savefile->ReadFloat( perchRotationFactor );
savefile->ReadInt(flyAnim);
savefile->ReadInt(glideAnim);
savefile->ReadInt(prelandAnim);
savefile->ReadInt(landAnim);
savefile->ReadInt(idleAnim);
savefile->ReadInt(tommyIdleAnim);
savefile->ReadInt(squawkAnim);
savefile->ReadInt(stepAnim);
savefile->ReadInt(takeOffAnim);
savefile->ReadInt(takeOffAnimB);
savefile->ReadInt(attackAnim);
savefile->ReadInt(preAttackAnim);
savefile->ReadSkin(openWingsSkin);
savefile->ReadSkin(closedWingsSkin);
enemy.Restore( savefile );
trailFx.Restore( savefile );
savefile->ReadInt( reinterpret_cast<int &> (state) );
}
//=============================================================================
//
// hhTalon::hhTalon
//
//=============================================================================
hhTalon::hhTalon() {
owner = NULL;
talonTarget = NULL;
enemy.Clear();
trailFx.Clear();
}
//=============================================================================
//
// hhTalon::~hhTalon
//
//=============================================================================
hhTalon::~hhTalon() {
if( owner.IsValid() ) {
owner->talon = NULL;
}
if ( trailFx.IsValid() ) {
trailFx->Nozzle( false );
SAFE_REMOVE( trailFx );
}
}
//=============================================================================
//
// hhTalon::SummonTalon
//
//=============================================================================
void hhTalon::SummonTalon(void) {
hhFxInfo fxInfo;
state = StateNone;
BecomeActive(TH_THINK);
Show();
checkTraceTime = spawnArgs.GetFloat( "traceCheckPulse", "0.1" );
lastCheckOrigin = GetOrigin();
FindTalonTarget(NULL, NULL, true);
CalculateTalonTargetLocation(); // Must recalculate the target location, as the target may have moved
SetOrigin(talonTargetLoc);
viewAxis = talonTargetAxis;
bLanding = false;
SetSkin( closedWingsSkin ); // The only time this is set in code, otherwise it's set by the land anim
fl.neverDormant = true;
SetForcedTarget( false );
velocityFactor = 1.0f;
rotationFactor = 1.0f;
perchRotationFactor = 1.0f;
SetShaderParm( SHADERPARM_DIVERSITY, 0 );
EnterTommyState();
TommyTicker(); // Force Talon to tick once to adjust his orientation
}
//=============================================================================
//
// hhTalon::SetOwner
//
//=============================================================================
void hhTalon::SetOwner( hhPlayer *newOwner ) {
owner = newOwner;
Event_SetOwner( newOwner );
}
void hhTalon::OwnerEnteredVehicle( void ) {
if ( talonTarget ) {
talonTarget->Left( this );
}
SummonTalon();
EnterVehicleState();
}
void hhTalon::OwnerExitedVehicle( void ) {
ExitVehicleState();
SummonTalon();
}
//=============================================================================
//
// hhTalon::FindTalonTarget
//
//=============================================================================
void hhTalon::FindTalonTarget( idEntity *skipEntity, hhTalonTarget *forceTarget, bool bForcePlayer ) {
int i;
int count;
float dist;
float bestDist;
hhTalonTarget *ent;
idVec3 dir;
talonTarget = NULL;
bestDist = spawnArgs.GetFloat( "perchDistance", "250" );
if ( owner->InVehicle() ) {
bestDist *= 10;
}
if( bReturnToTommy) {
bForcePlayer = true;
}
if ( forceTarget ) {
talonTarget = forceTarget;
}
// Iterate through valid perch spots and find the best choice
if( !bForcePlayer && !forceTarget ) {
count = gameLocal.talonTargets.Num();
for(i = 0; i < count; i++) {
ent = (hhTalonTarget *)gameLocal.talonTargets[i];
if ( !ent->bValidForTalon ) { // Not a valid target
continue;
}
// ignore if there is no way we can see this perch spot
if( ent == skipEntity || !gameLocal.InPlayerPVS( ent ) || ent->priority == -1) {
continue;
}
if ( owner.IsValid() && owner->IsSpiritOrDeathwalking() && ent->bNotInSpiritWalk ) { // If the owner is spiritwalking, then don't try to fly to this target (useful for lifeforce pickups)
continue;
}
// Calculate the distance from the player to the perch spot
dist = ( owner->GetEyePosition() - ent->GetPhysics()->GetOrigin() ).Length();
// Adjust the distance based upon the priority (ranges from 0 - 2, -1 to completely skip).
dist *= ent->priority;
if(dist > bestDist) { // Farther than the nearest perch spot
continue;
}
talonTarget = ent;
bestDist = dist;
}
}
if( !talonTarget && owner.IsValid() ) { // No perch spot, so use a spot close to the player
owner->GetJointWorldTransform( "FX_bird", talonTargetLoc, talonTargetAxis );
talonTargetAxis = owner->viewAxis;
} else {
CalculateTalonTargetLocation();
}
}
//=============================================================================
//
// hhTalon::CalculateTalonTargetLocation
//
//=============================================================================
void hhTalon::CalculateTalonTargetLocation() {
trace_t tr;
if ( !talonTarget ) {
return;
}
// Trace down a bit to get the exact perch location
if( gameLocal.clip.TracePoint( tr, talonTarget->GetPhysics()->GetOrigin() + idVec3(0, 0, 4), talonTarget->GetPhysics()->GetOrigin() - idVec3(0, 0, 16), MASK_SOLID, this )) {
talonTargetLoc = tr.endpos - idVec3( 0, 0, 1 ); // End position, minus a tiny bit so Talon perches on railings
} else { // No collision, just use the current floating spot
talonTargetLoc = talonTarget->GetPhysics()->GetOrigin();
}
talonTargetAxis = talonTarget->GetPhysics()->GetAxis();
}
//=============================================================================
//
// CheckReachedTarget
//
//=============================================================================
bool hhTalon::CheckReachedTarget( float distance ) {
idVec3 vec;
if(distance < spawnArgs.GetFloat( "distanceSlow", "80" ) ) {
if(talonTarget) {
velocity = (talonTargetLoc - GetOrigin()) * 0.05f; // Move more slowly when about to perch
if( !GetAnimator()->IsAnimPlaying( GetAnimator()->GetAnim( prelandAnim ) ) ) {
Event_PreLandAnim();
StartSound( "snd_preland", SND_CHANNEL_BODY );
}
bLanding = true;
}
if(talonTarget) {
if(distance < spawnArgs.GetFloat( "distancePerchEpsilon", "3" ) ) { // Perch on this spot
Event_LandAnim();
StartSound( "snd_land", SND_CHANNEL_BODY );
talonTarget->Reached(this);
EnterPerchState();
return true; // No need to continue the fly ticker
}
} else if(distance < spawnArgs.GetFloat( "distanceTommyEpsilon", "15.0" ) ) { // No perch spot, so perch on Tommy around this location
Event_LandAnim();
EnterTommyState();
return true; // No need to continue the fly ticker
}
} else if(distance >= spawnArgs.GetFloat( "distanceTurbo", "2500" ) ) { // Distance is so far, we should kick Talon into turbo mode
velocity *= 10;
}
return false;
}
//=============================================================================
//
// hhTalon::CheckCollisions
//
//=============================================================================
void hhTalon::CheckCollisions(float deltaTime) {
idVec3 oldOrigin;
trace_t tr;
checkTraceTime -= deltaTime;
if(checkTraceTime > 0) {
return;
}
checkTraceTime = spawnArgs.GetFloat( "traceCheckPulse", "0.1" );
idVec3 nextLocation = GetOrigin() + this->velocity * 0.5f;
// Trace to determine if the hawk is just about to fly into a wall
if ( gameLocal.clip.TracePoint( tr, GetOrigin(), nextLocation, MASK_SOLID, owner.GetEntity() ) ) { // Struck something solid
// Glow
SetShaderParm( SHADERPARM_TIMEOFFSET, MS2SEC( gameLocal.time ) );
} else if ( gameLocal.clip.TracePoint( tr, GetOrigin(), lastCheckOrigin, MASK_SOLID, owner.GetEntity() ) ) { // Exited something solid
// Glow
SetShaderParm( SHADERPARM_TIMEOFFSET, MS2SEC( gameLocal.time ) );
}
lastCheckOrigin = GetOrigin();
}
//=============================================================================
//
// hhTalon::Think
//
//=============================================================================
void hhTalon::Think(void) {
if ( owner->InGravityZone() ) { // don't perch in gravity zones, unless gravity is "normal"
idVec3 gravity = owner->GetGravity();
gravity.Normalize();
float dot = gravity * idVec3( 0.0f, 0.0f, -1.0f );
if ( dot < 1.0f ) {
if ( talonTarget ) {
talonTarget->Left( this );
}
ReturnToTommy();
}
}
// Shadow suppression based upon the player
if ( g_showPlayerShadow.GetBool() ) {
renderEntity.suppressShadowInViewID = 0;
}
else {
renderEntity.suppressShadowInViewID = owner->entityNumber + 1;
}
hhMonsterAI::Think();
}
//=============================================================================
//
// hhTalon::FlyMove
//
//=============================================================================
void hhTalon::FlyMove( void ) {
// Run the specific task Ticker
switch( state ) {
case StateTommy:
TommyTicker();
break;
case StateFly:
FlyTicker();
break;
case StateVehicle:
VehicleTicker();
break;
case StatePerch:
PerchTicker();
break;
case StateAttack:
AttackTicker();
break;
}
// run the physics for this frame
physicsObj.UseFlyMove( true );
physicsObj.UseVelocityMove( false );
physicsObj.SetDelta( vec3_zero );
physicsObj.ForceDeltaMove( disableGravity );
RunPhysics();
}
//=============================================================================
//
// hhTalon::AdjustFlyingAngles
//
// No need to adjust flying angles on Talon
//=============================================================================
void hhTalon::AdjustFlyingAngles() {
return;
}
//=============================================================================
//
// hhTalon::GetPhysicsToVisualTransform
//
//=============================================================================
bool hhTalon::GetPhysicsToVisualTransform( idVec3 &origin, idMat3 &axis ) {
origin = modelOffset;
if ( GetBindMaster() && bindJoint != INVALID_JOINT ) {
idMat3 masterAxis;
idVec3 masterOrigin;
GetMasterPosition( masterOrigin, masterAxis );
origin = masterOrigin + physicsObj.GetLocalOrigin() * masterAxis;
axis = GetBindMaster()->GetAxis();
} else {
axis = viewAxis;
}
return true;
}
//=============================================================================
//
// hhTalon::CrashLand
//
// No need to check crash landing on Talon
//=============================================================================
void hhTalon::CrashLand( const idVec3 &oldOrigin, const idVec3 &oldVelocity ) {
return;
}
//=============================================================================
//
// hhTalon::Damage
//
// Talon cannot be damaged
//=============================================================================
void hhTalon::Damage( idEntity *inflictor, idEntity *attack, const idVec3 &dir, const char *damageDefName, const float damageScale, const int location ) {
return;
}
//=============================================================================
//
// hhTalon::Killed
//
// Talon cannot be killed
//=============================================================================
void hhTalon::Killed( idEntity *inflictor, idEntity *attacker, int damage, const idVec3 &dir, int location ) {
return;
}
//=============================================================================
//
// hhTalon::Portalled
//
//=============================================================================
void hhTalon::Portalled( idEntity *portal ) {
if ( state == StateTommy ) { // No need to portal if Talon is already on Tommy's shoulder
return;
}
CancelEvents( &EV_GlideAnim ); // Could possibly have a glide anim queue
CancelEvents( &EV_TakeOffAnimB );
// If Talon is currently on a gui, inform the gui he is leaving
if ( talonTarget && ( state == StatePerch || state == StateVehicle ) ) { // CJR PCF 050306: Only call Left() if Talon is perching on a console
talonTarget->Left( this );
}
StopAttackFX();
// Force Talon to Tommy's shoulder after he portals
talonTarget = NULL;
bLanding = false;
SetSkin( openWingsSkin ); // The only time this is set in code, otherwise it's set by the land anim
Event_LandAnim();
SetForcedTarget( false );
EnterTommyState();
}
//=============================================================================
//
// hhTalon::EnterFlyState
//
//=============================================================================
void hhTalon::EnterFlyState(void) {
EndState();
state = StateFly;
checkFlyTime = spawnArgs.GetFloat( "checkFlyTime", "4.0" );
flyStraightTime = spawnArgs.GetFloat( "flyStraightTime", "0.5" );
bLanding = false;
SetShaderParm( SHADERPARM_DIVERSITY, 0 ); // Talon's model should phase out if the player is too close
}
//=============================================================================
//
// hhTalon::FlyTicker
//
//=============================================================================
void hhTalon::FlyTicker(void) {
idAngles ang;
float distance;
float deltaTime = MS2SEC(gameLocal.msec);
idVec3 oldVel;
float distanceXY;
float deltaZ;
float rotSpeed;
// If the bird is currently in fly mode, but hasn't finished the takeoff anim, then don't let the bird fly around
if( GetAnimator()->IsAnimPlaying( GetAnimator()->GetAnim( takeOffAnim ) ) ) {
return;
}
acceleration = talonTargetLoc - GetOrigin();
idVec2 vecXY = acceleration.ToVec2();
distance = acceleration.Normalize();
distanceXY = vecXY.Length();
deltaZ = talonTargetLoc.z - GetOrigin().z;
float dp = acceleration * GetAxis()[0];
float side = acceleration * GetAxis()[1];
ang = GetAxis().ToAngles();
// Talon can either rotate towards the target, or fly straight.
if( flyStraightTime > 0 ) { // Continue to fly straight
flyStraightTime -= deltaTime;
if ( flyStraightTime <= 0 && !bLanding ) { // No longer flying straight
Event_FlyAnim();
}
rotSpeed = 0;
} else if( bLanding ) { // About to land, so turn slightly faster than normal
rotSpeed = ROTATION_SPEED_FAST * rotationFactor;
} else {
rotSpeed = ROTATION_SPEED * rotationFactor;
}
rotSpeed *= (60.0f * USERCMD_ONE_OVER_HZ);
// Determine whether Talon should rotate left or right to reach the target
if(dp > 0) {
if(dp >= 0.98f || ( side <= 0.1f && side >= 0.1f )) { // CJR PCF 04/28/06: don't turn if directly facing the target
rotSpeed = 0;
} else if (side < -0.1f) {
rotSpeed *= -1.0f;
}
} else {
if(side < 0) {
rotSpeed *= -1.0f;
}
}
// Apply rotation
deltaViewAngles.yaw = rotSpeed;
oldVel = velocity;
float defaultVelocityXY = spawnArgs.GetFloat( "velocityXY", "7.0" );
float defaultVelocityZ = spawnArgs.GetFloat( "velocityZ", "4" );
velocity = viewAxis[0] * defaultVelocityXY * velocityFactor; // xy-velocity
// Z-change based upon distance
if(abs(deltaZ) > 0 && distanceXY > 0) {
velocity.z = (deltaZ * defaultVelocityXY) / distanceXY;
// Clamp z velocity
if(velocity.z > defaultVelocityZ) {
velocity.z = defaultVelocityZ;
}
}
if ( CheckReachedTarget( distance ) ) {
return;
}
// Apply velocity
SetOrigin( GetOrigin() + velocity * (60.0f * USERCMD_ONE_OVER_HZ) );
// Check for colliding with world surfaces (only if not currently trying to land)
if( !bLanding ) {
CheckCollisions(deltaTime);
}
// Timeout for flying to perch spot... if too much time has passed, then fly straight for a bit
checkFlyTime -= deltaTime;
if( checkFlyTime <= 0 && !bLanding ) {
flyStraightTime = spawnArgs.GetFloat( "flyStraightTime", "0.5" );
checkFlyTime = spawnArgs.GetFloat( "checkFlyTime", "4.0" );
PostEventMS( &EV_GlideAnim, 0 );
}
// If no talonTarget (probably flying towards Tommy), then constantly look for a new target
if( !bForcedTarget && !GetAnimator()->IsAnimPlaying( GetAnimator()->GetAnim( prelandAnim ) ) ) {
FindTalonTarget( NULL, NULL, false );
}
}
//=============================================================================
//
// hhTalon::EnterTommyState
//
//=============================================================================
void hhTalon::EnterTommyState(void) {
idVec3 bindOrigin;
idMat3 bindAxis;
bReturnToTommy = false;
EndState();
state = StateTommy;
Hide();
UpdateVisuals();
// Bind the bird to Tommy's shoulder
owner->GetJointWorldTransform( "fx_bird", bindOrigin, bindAxis );
SetOrigin( bindOrigin );
SetAxis( owner->viewAxis );
BindToJoint( owner.GetEntity(), "fx_bird", true );
// Start checking for enemies
PostEventSec( &EV_CheckForEnemy, spawnArgs.GetFloat("checkEnemyTime", "4.0" ) );
// Start checking for nearby targets
PostEventSec( &EV_CheckForTarget, spawnArgs.GetFloat( "checkTargetTime", "1.0" ) );
}
//=============================================================================
//
// hhTalon::EndState
//
//=============================================================================
void hhTalon::EndState(void) {
Unbind();
int oldState = state;
state = StateNone;
if ( fl.hidden ) { // If the bird is hidden, show it when ending the state
Show();
}
// Zero out Talon's velocity when initially taking off, so it doesn't inherit any from the bind master
velocity = vec3_zero;
GetPhysics()->SetLinearVelocity( vec3_zero );
// Cancel any checks for enemies
CancelEvents( &EV_CheckForEnemy );
CancelEvents( &EV_CheckForTarget );
StopAttackFX();
if( oldState == StateTommy ) {
GetPhysics()->SetAxis( mat3_identity );
// Show the hawk in the player's view after it takes off
Show();
} else if( oldState == StatePerch ) {
CancelEvents( &EV_PerchSquawk );
} else if ( oldState == StateAttack ) {
// Clear the enemy
if ( enemy.IsValid() ) {
(static_cast<hhMonsterAI*>(enemy.GetEntity()))->Distracted( GetOwner() ); // Set the enemy's enemy back to Tommy
enemy.Clear();
}
}
}
//=============================================================================
//
// hhTalon::TommyTicker
//
//=============================================================================
void hhTalon::TommyTicker(void) {
idVec3 viewOrigin;
idMat3 viewAxis;
idMat3 ownerAxis;
float deltaTime = MS2SEC(gameLocal.msec);
bLanding = false;
// Turn towards direction of Tommy
idVec3 toFace = owner->GetAxis()[0];
toFace.z = 0;
toFace.Normalize();
float dp = toFace * GetAxis()[0];
float side = toFace * GetAxis()[1];
if(side > 0.05 || dp < 0 ) {
deltaViewAngles.yaw = PERCH_ROTATION * perchRotationFactor;
UpdateVisuals();
} else if (side < -0.05) {
deltaViewAngles.yaw = -PERCH_ROTATION * perchRotationFactor;
UpdateVisuals();
}
}
//=============================================================================
//
// hhTalon::FindEnemy
//
//=============================================================================
bool hhTalon::FindEnemy( void ) {
idEntity *ent;
hhMonsterAI *actor;
hhMonsterAI *bestEnemy;
float bestDist;
float maxEnemyDist;
float dist;
idVec3 delta;
int enemyCount;
// Check if Talon already has a valid enemy
if ( enemy.IsValid() && enemy->health > 0 ) {
return true;
}
bestDist = 0;
maxEnemyDist = 1024.0f * 1024.0f; // sqr
bestEnemy = NULL;
enemyCount = 0;
for ( ent = gameLocal.activeEntities.Next(); ent != NULL; ent = ent->activeNode.Next() ) {
if ( ent->fl.hidden || ent->fl.isDormant || !ent->IsType( hhMonsterAI::Type ) ) {
continue;
}
actor = static_cast<hhMonsterAI *>( ent );
// Only attack living enemies, and only attack enemies that are targetting Tommy or Talon
if ( (actor->health <= 0) || ( actor->GetEnemy() != GetOwner() && actor->GetEnemy() != this ) ) {
continue;
}
if ( !gameLocal.InPlayerPVS( actor ) ) {
continue;
}
// Check if Talon should avoid this enemy -- these enemies are also not included in the enemy count
if ( !ent->spawnArgs.GetBool( "bTalonAttack", "0" ) ) {
continue;
}
delta = GetOwner()->GetOrigin() - actor->GetPhysics()->GetOrigin(); // Find the farthest enemy (in the PVS) to Tommy
dist = delta.LengthSqr();
if ( dist > bestDist && dist < maxEnemyDist && GetOwner()->CanSee( actor, false ) ) {
bestDist = dist;
bestEnemy = actor;
}
enemyCount++;
}
if ( bestEnemy && enemyCount >= 2 ) { // Only attack if more than one enemy is attacking the player
enemy = bestEnemy;
return true;
}
enemy.Clear();
return false;
}
//=============================================================================
//
// hhTalon::EnterPerchState
//
//=============================================================================
void hhTalon::EnterPerchState(void) {
EndState();
state = StatePerch;
velocity = vec3_zero;
if ( talonTarget ) {
CalculateTalonTargetLocation(); // Must recalculate the target location, as the target may have moved
SetOrigin( talonTargetLoc );
if ( talonTarget->IsBound() ) { // Only bind talon to this target, if it's bound to something
Bind( talonTarget, true );
}
GetPhysics()->SetLinearVelocity( vec3_zero );
}
if ( talonTarget && talonTarget->bShouldSquawk ) {
float frequency = talonTarget->spawnArgs.GetFloat( "squawkFrequency", "5.0" );
PostEventSec( &EV_PerchSquawk, frequency );
}
SetShaderParm( SHADERPARM_DIVERSITY, 1 ); // Talon's model shouldn't phase out if the player is too close
// Start checking for nearby enemies
PostEventSec( &EV_CheckForEnemy, spawnArgs.GetFloat("checkEnemyTime", "4.0" ) );
// Start checking for nearby targets
PostEventSec( &EV_CheckForTarget, spawnArgs.GetFloat( "checkTargetTime", "1.0" ) );
}
//=============================================================================
//
// hhTalon::PerchTicker
//
//=============================================================================
void hhTalon::PerchTicker(void) {
float deltaTime = MS2SEC(gameLocal.msec);
bLanding = false;
// Turn towards direction of perch spot
idVec3 toFace = talonTarget->GetPhysics()->GetAxis()[0];
toFace.z = 0;
toFace.Normalize();
float dp = toFace * GetAxis()[0];
float side = toFace * GetAxis()[1];
if ( dp < 0 ) {
if ( side >= 0 ) {
deltaViewAngles.yaw = PERCH_ROTATION * perchRotationFactor;
} else {
deltaViewAngles.yaw = -PERCH_ROTATION * perchRotationFactor;
}
} else if (side > 0.05 ) {
deltaViewAngles.yaw = PERCH_ROTATION * perchRotationFactor;
} else if (side < -0.05) {
deltaViewAngles.yaw = -PERCH_ROTATION * perchRotationFactor;
}
UpdateVisuals();
}
//=============================================================================
//
// hhTalon::Event_PerchChatter
//
// Small chirping noise which is part of Talon's idle animation
//=============================================================================
void hhTalon::Event_PerchChatter(void) {
if ( state != StateTommy ) { // Don't chatter when on Tommy's shoulder
StartSound( "snd_chatter", SND_CHANNEL_VOICE );
}
}
//=============================================================================
//
// hhTalon::Event_PerchSquawk
//
// Louder, squawking noise, alerting the player to this location
//=============================================================================
void hhTalon::Event_PerchSquawk(void) {
if ( !talonTarget ) {
return;
}
if ( talonTarget->bShouldSquawk ) { // Always check, because it could have been turned off after Talon perched
// Check if the player is outside of the squawk distance
float squawkDistSqr = talonTarget->spawnArgs.GetFloat( "squawkDistance", "0" );
squawkDistSqr *= squawkDistSqr;
if ( (GetOrigin() - owner->GetOrigin() ).LengthSqr() > squawkDistSqr ) { // Far enough away, so squawk
GetAnimator()->ClearAllAnims( gameLocal.time, TALON_BLEND );
GetAnimator()->PlayAnim( ANIMCHANNEL_ALL, squawkAnim, gameLocal.time, TALON_BLEND);
PostEventMS( &EV_IdleAnim, GetAnimator()->GetAnim( squawkAnim )->Length() + TALON_BLEND );
StartSound( "snd_squawk", SND_CHANNEL_VOICE );
// Glow
SetShaderParm( SHADERPARM_TIMEOFFSET, MS2SEC( gameLocal.time ) );
}
// Post the next squawk attempt
float frequency = talonTarget->spawnArgs.GetFloat( "squawkFrequency", "5.0" );
PostEventSec( &EV_PerchSquawk, frequency + frequency * gameLocal.random.RandomFloat() );
}
}
//=============================================================================
//
// hhTalon::Event_CheckForTarget
//
//=============================================================================
void hhTalon::Event_CheckForTarget() {
hhTalonTarget *oldTarget = talonTarget;
// Determine if Talon should take off from his perch
if ( !bForcedTarget ) { // do not check if Talon is forced this this point
FindTalonTarget(NULL, NULL, false);
if( oldTarget != talonTarget ) {
Event_TakeOffAnim();
if( oldTarget ) { // Inform the perch spot that talon is leaving
oldTarget->Left(this);
}
EnterFlyState();
return;
}
}
PostEventSec( &EV_CheckForTarget, spawnArgs.GetFloat( "checkTargetTime", "1.0" ) );
}
//=============================================================================
//
// hhTalon::Event_CheckForEnemy
//
//=============================================================================
void hhTalon::Event_CheckForEnemy() {
if ( !ai_talonAttack.GetBool() ) {
return;
}
if ( !bForcedTarget ) {
if ( FindEnemy() ) {
Event_TakeOffAnim();
if( talonTarget ) { // Inform the perch spot that talon is leaving
talonTarget->Left( this );
}
EnterAttackState();
return;
}
}
PostEventSec( &EV_CheckForEnemy, spawnArgs.GetFloat("checkEnemyTime", "4.0" ) );
}
//=============================================================================
//
// hhTalon::EnterAttackState
//
//=============================================================================
void hhTalon::EnterAttackState(void) {
EndState();
state = StateAttack;
checkFlyTime = spawnArgs.GetFloat( "attackTime", "8.0f" );
StartSound( "snd_attack", SND_CHANNEL_BODY );
bClawingAtEnemy = false;
StartAttackFX();
}
//=============================================================================
//
// hhTalon::AttackTicker
//
//=============================================================================
void hhTalon::AttackTicker(void) {
float deltaTime = MS2SEC(gameLocal.msec);
if ( !FindEnemy() ) {
ReturnToTommy();
StopAttackFX();
return;
}
idAngles ang;
float distance;
idVec3 oldVel;
bool landing = false;
float distanceXY;
float deltaZ;
float rotSpeed;
float distToEnemy;
idMat3 junkAxis;
enemy->GetViewPos(talonTargetLoc, junkAxis);
talonTargetLoc -= junkAxis[2] * 10.0f;
distToEnemy = (talonTargetLoc - GetOrigin()).Length();
acceleration = talonTargetLoc - GetOrigin();
idVec2 vecXY = acceleration.ToVec2();
distance = acceleration.Normalize();
distanceXY = vecXY.Length();
deltaZ = talonTargetLoc.z - GetOrigin().z;
float dp = acceleration * GetAxis()[0];
float side = acceleration * GetAxis()[1];
ang = GetAxis().ToAngles();
// Talon can either rotate towards the target, or fly straight.
if( flyStraightTime > 0 ) { // Continue to fly straight
flyStraightTime -= deltaTime;
if ( flyStraightTime <= 0 ) { // Done gliding, play a flap animation
Event_FlyAnim();
if ( bClawingAtEnemy ) { // Done attacking
bClawingAtEnemy = false;
flyStraightTime = 1.0f;
}
}
rotSpeed = 0;
} else {
rotSpeed = ROTATION_SPEED * rotationFactor;
}
rotSpeed *= (60.0f * USERCMD_ONE_OVER_HZ); // CJR PCF 04/28/06: Adjust for 30Hz
// Determine whether Talon should rotate left or right to reach the target
if(dp > 0) {
if(dp >= 0.98f || ( side <= 0.1f && side >= 0.1f )) { // CJR PCF 04/28/06: don't turn if directly facing the target
rotSpeed = 0;
} else if (side < -0.1f) {
rotSpeed *= -1;
}
} else {
if(side < 0) {
rotSpeed *= -1;
}
}
// Apply rotation
deltaViewAngles.yaw = rotSpeed;
float desiredRoll = -side * 20 * rotSpeed;
oldVel = velocity;
float defaultVelocityXY = spawnArgs.GetFloat( "velocityXY_attack", "8.5" );
float defaultVelocityZ = spawnArgs.GetFloat( "velocityZ", "4" );
// Adjust velocity based upon the attack
if ( bClawingAtEnemy ) {
defaultVelocityXY = 0.0f;
idVec3 tempVec( vecXY.x, vecXY.y, 0.0f );
viewAxis = tempVec.ToMat3();
} else if ( flyStraightTime > 0 ) { // Flying away from the enemy
float adjust = hhMath::ClampFloat( 0.0f, 1.0f, 2.0f - flyStraightTime * 2.0f );
defaultVelocityXY *= adjust; // Move more slowly when about to attack
} else { // Flying around, check if the bird should slow down when nearing the enemy
if ( distToEnemy < 150.0f && dp > 0 ) { // Close to the enemy and facing it
if( !GetAnimator()->IsAnimPlaying( GetAnimator()->GetAnim( preAttackAnim ) ) ) {
GetAnimator()->ClearAllAnims( gameLocal.time, TALON_BLEND );
GetAnimator()->CycleAnim(ANIMCHANNEL_ALL, preAttackAnim, gameLocal.time, TALON_BLEND);
CancelEvents( &EV_GlideAnim ); // Could possibly have a glide anim queue
CancelEvents( &EV_TakeOffAnimB );
}
float adjust = 1.0f - hhMath::ClampFloat( 0.0f, 0.9f, (100 - (distToEnemy-50) ) / 100.0f); // Decelerate Talon
defaultVelocityXY *= adjust;
}
}
velocity = viewAxis[0] * defaultVelocityXY * velocityFactor; // xy-velocity
// Z-change based upon distance
if(abs(deltaZ) > 0 && distanceXY > 0) {
velocity.z = (deltaZ * defaultVelocityXY) / distanceXY;
// Clamp z velocity
if(velocity.z > defaultVelocityZ) {
velocity.z = defaultVelocityZ;
}
}
// Apply velocity
SetOrigin( GetOrigin() + velocity );
UpdateVisuals();
// Timeout for flying to perch spot... if too much time has passed, then fly straight for a bit
checkFlyTime -= deltaTime;
if( checkFlyTime <= 0 && !bClawingAtEnemy && flyStraightTime <= 0 ) {
ReturnToTommy();
StopAttackFX();
}
// Check if Talon reached the target and attack!
if ( flyStraightTime <= 0 && ( distToEnemy < spawnArgs.GetFloat( "distanceAttackEpsilon", "60" ) ) ) {
// Damage the enemy
StartSound( "snd_attack", SND_CHANNEL_BODY );
// Distract the enemy by setting Talon as its enemy -- random chance that this will succeed
if ( enemy.IsValid() && gameLocal.random.RandomFloat() < spawnArgs.GetFloat( "attackChance", "0.5" ) ) {
(static_cast<hhMonsterAI*>(enemy.GetEntity()))->Distracted( this );
owner->TalonAttackComment();
}
// Play an attack anim here
GetAnimator()->ClearAllAnims( gameLocal.time, 0 );
GetAnimator()->CycleAnim(ANIMCHANNEL_ALL, attackAnim, gameLocal.time, 0 );
flyStraightTime = MS2SEC( GetAnimator()->GetAnim( attackAnim )->Length() );
PostEventSec( &EV_FlyAnim, flyStraightTime ); // Play a fly anim once this attack animation is done
bClawingAtEnemy = true;
}
}
//=============================================================================
//
// hhTalon::StartAttackFX
//
//=============================================================================
void hhTalon::StartAttackFX() {
SetShaderParm( SHADERPARM_MODE, 1 ); // Fire glow attack
if ( trailFx.IsValid() ) { // An effect already exists, turn it on
trailFx->Nozzle( true );
} else { // Spawn a new effect
const char *defName = spawnArgs.GetString( "fx_attackTrail" );
if (defName && defName[0]) {
hhFxInfo fxInfo;
fxInfo.SetNormal( -GetAxis()[0] );
fxInfo.SetEntity( this );
fxInfo.RemoveWhenDone( false );
trailFx = SpawnFxLocal( defName, GetOrigin(), GetAxis(), &fxInfo, gameLocal.isClient );
if (trailFx.IsValid()) {
trailFx->fl.neverDormant = true;
trailFx->fl.networkSync = false;
trailFx->fl.clientEvents = true;
}
}
}
}
//=============================================================================
//
// hhTalon::StopAttackFX
//
//=============================================================================
void hhTalon::StopAttackFX() {
SetShaderParm( SHADERPARM_MODE, 0 ); // Fire glow attack done
if ( trailFx.IsValid() ) {
trailFx->Nozzle( false );
}
}
//=============================================================================
//
// hhTalon::EnterVehicleState
//
//=============================================================================
void hhTalon::EnterVehicleState(void) {
EndState();
state = StateVehicle;
Hide();
CancelEvents( &EV_GlideAnim ); // Could possibly have a glide anim queue
CancelEvents( &EV_TakeOffAnimB );
}
//=============================================================================
//
// hhTalon::ExitVehicleState
//
//=============================================================================
void hhTalon::ExitVehicleState(void) {
if ( talonTarget ) {
talonTarget->Left( this );
}
}
//=============================================================================
//
// hhTalon::VehicleTicker
//
// How Talon acts when the player is in a vehicle:
// - In the interest of speed, Talon warps from target to Target
// - This allows for the giant translation GUIs to instantly translate as the player gets near
//=============================================================================
void hhTalon::VehicleTicker(void) {
float deltaTime = MS2SEC(gameLocal.msec);
hhTalonTarget *oldEnt = talonTarget;
if( GetAnimator()->IsAnimPlaying( GetAnimator()->GetAnim( prelandAnim ) ) ) {
return;
}
FindTalonTarget( NULL, NULL, bReturnToTommy );
if ( talonTarget == oldEnt ) { // No change to the target, so do nothing
return;
}
if ( !talonTarget ) { // No Talon Target, so hide Talon
Hide();
} else { // have a target, to show the bird
Show();
}
// Have a target, so spawn the bird at the target, if it isn't already there
CalculateTalonTargetLocation(); // Must recalculate the target location, as the target may have moved
SetOrigin( talonTargetLoc );
SetAxis( talonTargetAxis );
UpdateVisuals();
SetSkin( openWingsSkin );
Event_LandAnim();
// Trigger the target
if ( talonTarget ) {
talonTarget->Reached( this ); // Reached the spot, but fly through it
}
// Inform the last talonTarget that Talon has left
if ( oldEnt ) {
oldEnt->Left( this );
}
}
//=============================================================================
//
// hhTalon::UpdateAnimationControllers
// Talon doesn't use any anim controllers
//=============================================================================
bool hhTalon::UpdateAnimationControllers() {
idVec3 vel;
float speed;
float roll;
speed = velocity.Length();
if ( speed < 3.0f || flyStraightTime > 0 ) {
roll = 0.0f;
} else {
roll = acceleration * viewAxis[1] * -fly_roll_scale / fly_speed;
if ( roll > fly_roll_max ) {
roll = fly_roll_max;
} else if ( roll < -fly_roll_max ) {
roll = -fly_roll_max;
}
}
fly_roll = fly_roll * 0.95f + roll * 0.05f;
viewAxis = idAngles( 0, current_yaw, fly_roll ).ToMat3();
return false;
}
//=============================================================================
//
// hhTalon::ReturnToTommy
//
//=============================================================================
void hhTalon::ReturnToTommy( void ) {
if ( bReturnToTommy ) { // already returning
return;
}
bReturnToTommy = true;
bLanding = false;
FindTalonTarget(NULL, NULL, true);
SetSkin( openWingsSkin );
GetAnimator()->ClearAllAnims( gameLocal.time, TALON_BLEND );
GetAnimator()->CycleAnim(ANIMCHANNEL_ALL, flyAnim, gameLocal.time, TALON_BLEND);
EnterFlyState();
}
// ANIM EVENTS ================================================================
//=============================================================================
//
// hhTalon::Event_LandAnim
//
//=============================================================================
void hhTalon::Event_LandAnim(void) {
GetAnimator()->ClearAllAnims( gameLocal.time, TALON_BLEND );
GetAnimator()->PlayAnim( ANIMCHANNEL_ALL, landAnim, gameLocal.time, TALON_BLEND);
if ( talonTarget ) { // Different animation if landing on Tommy or not
PostEventMS( &EV_IdleAnim, GetAnimator()->GetAnim( landAnim )->Length() + TALON_BLEND );
} else { // No target, so the bird must be landing on Tommy
PostEventMS( &EV_TommyIdleAnim, GetAnimator()->GetAnim( landAnim )->Length() + TALON_BLEND );
}
CancelEvents( &EV_GlideAnim ); // Could possibly have a glide anim queue
CancelEvents( &EV_TakeOffAnimB );
}
//=============================================================================
//
// hhTalon::Event_PreLandAnim
//
//=============================================================================
void hhTalon::Event_PreLandAnim(void) {
GetAnimator()->ClearAllAnims( gameLocal.time, TALON_BLEND );
GetAnimator()->CycleAnim( ANIMCHANNEL_ALL, prelandAnim, gameLocal.time, TALON_BLEND );
CancelEvents( &EV_GlideAnim ); // Could possibly have a glide anim queue
CancelEvents( &EV_TakeOffAnimB );
}
//=============================================================================
//
// hhTalon::Event_IdleAnim
//
//=============================================================================
void hhTalon::Event_IdleAnim(void) {
GetAnimator()->CycleAnim( ANIMCHANNEL_ALL, idleAnim, gameLocal.time, TALON_BLEND);
StartSound("snd_idle", SND_CHANNEL_BODY);
}
//=============================================================================
//
// hhTalon::Event_TommyIdleAnim
//
//=============================================================================
void hhTalon::Event_TommyIdleAnim(void) {
GetAnimator()->CycleAnim( ANIMCHANNEL_ALL, tommyIdleAnim, gameLocal.time, TALON_BLEND);
}
//=============================================================================
//
// hhTalon::Event_FlyAnim
//
//=============================================================================
void hhTalon::Event_FlyAnim(void) {
GetAnimator()->ClearAllAnims( gameLocal.time, TALON_BLEND );
GetAnimator()->CycleAnim( ANIMCHANNEL_ALL, flyAnim, gameLocal.time, TALON_BLEND);
StartSound("snd_fly", SND_CHANNEL_BODY);
}
//=============================================================================
//
// hhTalon::Event_GlideAnim
//
//=============================================================================
void hhTalon::Event_GlideAnim(void) {
GetAnimator()->ClearAllAnims( gameLocal.time, TALON_BLEND );
GetAnimator()->CycleAnim( ANIMCHANNEL_ALL, glideAnim, gameLocal.time, TALON_BLEND);
StartSound("snd_glide", SND_CHANNEL_BODY);
}
//=============================================================================
//
// hhTalon::Event_TakeOffAnim
//
//=============================================================================
void hhTalon::Event_TakeOffAnim(void) {
GetAnimator()->ClearAllAnims( gameLocal.time, 0 ); // No blend when clearing old anims while taking off
GetAnimator()->PlayAnim( ANIMCHANNEL_ALL, takeOffAnim, gameLocal.time, TALON_BLEND);
PostEventMS( &EV_TakeOffAnimB, GetAnimator()->GetAnim( takeOffAnim )->Length() + TALON_BLEND );
StartSound("snd_takeoff", SND_CHANNEL_ANY);
}
//=============================================================================
//
// hhTalon::Event_TakeOffAnimB
//
//=============================================================================
void hhTalon::Event_TakeOffAnimB(void) {
GetAnimator()->ClearAllAnims( gameLocal.time, 0 );
GetAnimator()->PlayAnim( ANIMCHANNEL_ALL, takeOffAnimB, gameLocal.time, 0);
PostEventMS( &EV_GlideAnim, GetAnimator()->GetAnim( takeOffAnimB )->Length() + TALON_BLEND );
}
//=============================================================================
//
// hhTalon::Show
//
// Special show needed to remove any collision information on Talon
//=============================================================================
void hhTalon::Show() {
if ( state == StateTommy ) {
return;
}
hhMonsterAI::Show();
// Needed after the show
GetPhysics()->SetContents( 0 ); // No collisions
GetPhysics()->SetClipMask( 0 ); // No collisions
}
// TALON PERCH SPOT ===========================================================
//=============================================================================
//
// hhTalonTarget::Spawn
//
//=============================================================================
void hhTalonTarget::Spawn(void) {
priority = 2.0f - spawnArgs.GetInt("priority");
if ( priority < 0 ) {
priority = 0;
} else if ( priority > 2) {
priority = 2;
}
bNotInSpiritWalk = spawnArgs.GetBool( "notInSpiritWalk" );
bShouldSquawk = spawnArgs.GetBool( "shouldSquawk" );
bValidForTalon = spawnArgs.GetBool( "valid", "1" );
gameLocal.RegisterTalonTarget(this);
GetPhysics()->SetContents( 0 );
Hide();
}
void hhTalonTarget::Save(idSaveGame *savefile) const {
savefile->WriteInt( priority );
savefile->WriteBool( bNotInSpiritWalk );
savefile->WriteBool( bShouldSquawk );
savefile->WriteBool( bValidForTalon );
}
void hhTalonTarget::Restore( idRestoreGame *savefile ) {
savefile->ReadInt( priority );
savefile->ReadBool( bNotInSpiritWalk );
savefile->ReadBool( bShouldSquawk );
savefile->ReadBool( bValidForTalon );
}
//=============================================================================
//
// hhTalonTarget::ShowTargets
//
//=============================================================================
void hhTalonTarget::ShowTargets( void ) {
int i;
int count;
idEntity *ent;
count = gameLocal.talonTargets.Num();
for(i = 0; i < count; i++) {
ent = (hhTalonTarget *)gameLocal.talonTargets[i];
ent->Show();
}
}
//=============================================================================
//
// hhTalonTarget::HideTargets
//
//=============================================================================
void hhTalonTarget::HideTargets( void ) {
int i;
int count;
idEntity *ent;
count = gameLocal.talonTargets.Num();
for(i = 0; i < count; i++) {
ent = (hhTalonTarget *)gameLocal.talonTargets[i];
ent->Hide();
}
}
//=============================================================================
//
// hhTalonTarget::~hhTalonTarget
//
//=============================================================================
hhTalonTarget::~hhTalonTarget() {
gameLocal.talonTargets.Remove( this );
}
//=============================================================================
//
// hhTalonTarget::Reached
//
// Called when Talon reaches the target point
//=============================================================================
void hhTalonTarget::Reached( hhTalon *talon ) {
if( !talon ) {
return;
}
// Landing on a perch spot sends an action message to the spot's targets
int num = targets.Num();
for (int ix=0; ix<num; ix++) {
if (targets[ix].IsValid()) {
targets[ix].GetEntity()->PostEventMS(&EV_TalonAction, 0, talon, true);
}
}
}
//=============================================================================
//
// hhTalonTarget::Left
//
// Called when Talon leaves the target point
//=============================================================================
void hhTalonTarget::Left( hhTalon *talon ) {
if( !talon ) {
return;
}
// Leaving on a perch spot sends an action message to the spot's targets
int num = targets.Num();
for (int ix=0; ix<num; ix++) {
if (targets[ix].IsValid()) {
targets[ix].GetEntity()->PostEventMS(&EV_TalonAction, 0, talon, false);
}
}
}
//=============================================================================
//
// hhTalonTarget::Event_CallTalon
//
// Calls Talon to this point and forces him to stay on this point unless released
// or called to another point
//=============================================================================
void hhTalonTarget::Event_CallTalon( float vel, float rot, float perch ) {
hhPlayer *player;
hhTalon *talon;
// Find Talon
player = static_cast<hhPlayer *>( gameLocal.GetLocalPlayer() );
if ( !player->talon.IsValid() ) {
return;
}
talon = player->talon.GetEntity();
talon->SetForcedTarget( true );
talon->SetForcedPhysicsFactors( vel, rot, perch );
talon->FindTalonTarget( NULL, this, false ); // Force this entity as the target
talon->Event_TakeOffAnim();
talon->EnterFlyState();
}
//=============================================================================
//
// hhTalonTarget::Event_ReleaseTalon
//
// Releases Talon from this perch spot and allows him to continue his normal scripting
//=============================================================================
void hhTalonTarget::Event_ReleaseTalon() {
hhPlayer *player;
hhTalon *talon;
// Find Talon
player = static_cast<hhPlayer *>( gameLocal.GetLocalPlayer() );
if ( !player->talon.IsValid() ) {
return;
}
talon = player->talon.GetEntity();
talon->SetForcedTarget( false );
talon->SetForcedPhysicsFactors( 1.0f, 1.0f, 1.0f );
}
//=============================================================================
//
// hhTalonTarget::Event_SetPerchState
//
// Set the state if Talon can or cannot fly towards this target
//=============================================================================
void hhTalonTarget::Event_SetPerchState( float newState ) {
bValidForTalon = ( newState > 0 ) ? true : false;
}
|
54354282e9e7bd6e2ece32fc43ec0fb197f546ba
|
7f2cf760d5434c61775ff8a28efa8dd68df88e65
|
/FirstEngine/PixelShader.h
|
531ac6633aa13ff5a0e7190e0a6d1466b6153fb1
|
[] |
no_license
|
RKGekk/BabaYaga
|
7fb9435c77a4a7cd433bc5856eca578653856259
|
459c81659291d58af86392d9e5196e18162f1c71
|
refs/heads/main
| 2023-02-07T22:35:30.657047
| 2020-12-22T16:28:08
| 2020-12-22T16:28:08
| 306,056,207
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 472
|
h
|
PixelShader.h
|
#pragma once
#include <d3d11.h>
#include <d3dcompiler.h>
#include <wrl.h>
#include <string>
#include <fstream>
#include "Bindable.h"
#include "memoryUtility.h"
class PixelShader : public Bindable {
public:
PixelShader(ID3D11Device* device, ID3DBlob* pBytecodeBlob, ID3D11PixelShader* pPixelShader);
void Bind(ID3D11DeviceContext* deviceContext) override;
ID3DBlob* GetBytecode() const;
protected:
ID3DBlob* m_pBytecodeBlob;
ID3D11PixelShader* m_pPixelShader;
};
|
1b28f5b91971750ccd4c006edf29b1940567c39d
|
9aa0ec9065485acab4fba5263b86366402a1a9b1
|
/入门经典/part3/chapter9/9.3-0-1背包问题/9-5-0-1背包问题_滚动数组_边读边算.cpp
|
68e66a53bafb7145e60ad05b323c570886cf5067
|
[] |
no_license
|
defuyun/ACM
|
1883ad46f057b79f7fab2a7b659ab8320a1a9ca7
|
b2879d10b1a292b593250d5b85fb791b17a676c4
|
refs/heads/master
| 2021-01-18T21:18:40.290945
| 2016-05-06T01:17:00
| 2016-05-06T01:17:00
| 33,590,907
| 1
| 2
| null | null | null | null |
WINDOWS-1252
|
C++
| false
| false
| 430
|
cpp
|
9-5-0-1背包问题_滚动数组_边读边算.cpp
|
//online judge: TYVJ P1005 ²ÉÒ©
#include<cstdio>
#include<cstring>
const int maxt = 1010;
int T, M, v, t, f[maxt];
int main(){
scanf("%d%d", &T, &M);
memset(f, 0, sizeof(f));
for(int i = 1; i <= M; ++i) {
scanf("%d%d", &t, &v);
for(int j = T; j >= 0; --j){
if(j>=t && f[j-t] + v > f[j]) f[j] = f[j-t] + v;
}
}
printf("%d\n", f[T]);
return 0;
}
|
b8bf3734ce45709df42bc59dfdfca05efdbe70e2
|
c7838c5bfc1a4583ed5646eb957d00406bd165d4
|
/observer.pattern/octonary_observer.cpp
|
15ad44f3ffd96d45dd536b8a0e3ab46a87786a34
|
[] |
no_license
|
giszmr/design-pattern
|
ee4dd8257b78e9d6212e279f997fb4f9ceab0980
|
50b0a2d881a369d7fac4ec967fb87e41ff52339b
|
refs/heads/main
| 2023-04-14T02:56:39.997792
| 2021-04-25T07:31:48
| 2021-04-25T07:31:48
| 361,359,112
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 137
|
cpp
|
octonary_observer.cpp
|
#include <stdio.h>
#include "octonary_observer.h"
void COctonaryObserver::Update(int msg)
{
printf("Octonary string: %o\n", msg);
}
|
d87116e29b6c6904317d579764c584c567f5ed23
|
4b187bd1e89f6bcce100b7bd05b4ff202522bc4d
|
/OnlineJudgeSolutions/Codeforces/codeforces 1023C.cpp
|
9d6a1891cb7fb02b071bdedd4f0e4c38bc59cf77
|
[] |
no_license
|
codefresher32/CompetitiveProgramming
|
e53133a906081e7931966216b55d4537730d8ba3
|
923009b9893bdb0162ef02e88ea4223dc8d85449
|
refs/heads/master
| 2021-04-13T06:51:04.428078
| 2020-03-24T13:40:16
| 2020-03-24T13:40:16
| 249,144,621
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 586
|
cpp
|
codeforces 1023C.cpp
|
#include<bits/stdc++.h>
using namespace std;
bool f[200005];
int main()
{
string s;
int l,n,k,j,r;
cin>>n>>k;
cin>>s;
stack<int>st;
r=(n-k)/2;
for(int i=0;i<n;i++)
{
if(s[i]=='(')
{
st.push(i);
}
else
{
if(r>0)
{
f[st.top()]=1;
f[i]=1;
r--;
}
st.pop();
}
}
for(int i=0;i<n;i++)
if(!f[i])
cout<<s[i];
cout<<endl;
return 0;
}
|
e4d9c63f7736f210b8c3324a078f18d9d9f470b8
|
7583f6e9cc1a73ad8aa90c53767435edc87b7219
|
/sheet_1/Salary-with-Bonus.cpp
|
60b37c2c7df4fc35bc0a17d9a8c939662b53f98b
|
[] |
no_license
|
MohamedElmdary/acm-0
|
23fc5d6480ac1e1ca5d9b5cead3fe9b34301945e
|
67ab046140bfc5368b7557b4aca204236d6e3b8e
|
refs/heads/master
| 2020-07-18T06:25:01.293359
| 2019-09-19T10:05:54
| 2019-09-19T10:05:54
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 194
|
cpp
|
Salary-with-Bonus.cpp
|
#include <iostream>
int main()
{
std::string name;
float salary, sales;
std::cin >> name >> salary >> sales;
printf("TOTAL = R$ %0.2f\n", salary + 0.15 * sales);
return 0;
}
|
e78f4e0d932c30f4a173a305e9ad6fbe290f4f2e
|
b21d5ef96a4b11edd401bb438c05d25f3af6381f
|
/src/main.cpp
|
dedc0dbf46556d380b7c97329cec6b8a056ce3d6
|
[
"MIT"
] |
permissive
|
rufus-stone/hufflepuffle
|
501ffc7c0914439e57d5c73540fa5758e67d3f29
|
ff2745dfb910c15ca81f27166748880673a79698
|
refs/heads/main
| 2023-06-16T17:07:20.266888
| 2021-07-12T08:59:55
| 2021-07-12T08:59:55
| 343,747,156
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 868
|
cpp
|
main.cpp
|
#include <string>
#include <string_view>
#include <spdlog/spdlog.h>
#include "huffle.hpp"
using namespace std::string_view_literals;
static constexpr auto text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."sv;
int main()
{
auto coder = hfl::tree_t{text};
//coder.freqs(); // Print the char frequencies
//coder.codes(); // Print the Huffman codes for each char
std::string encoded = coder.encode();
spdlog::info(encoded);
return EXIT_SUCCESS;
}
|
0fde17941a03a5bcedf7537774919e1a0eaa4de3
|
ca6b7bd6516e5098310cd803168007249f3b469d
|
/src/libraries/disp/viewers/helpers/bidsviewmodel.cpp
|
a0172a65e858d6f9c6b0f50da5f1f89bfb2b811d
|
[
"BSD-3-Clause"
] |
permissive
|
mne-tools/mne-cpp
|
125e90d2373cb30ae8207fb3e2317511356a4705
|
3b3c722936981e4ecc3310c3b38f60b1737c69ec
|
refs/heads/main
| 2023-08-16T16:41:05.569008
| 2023-08-09T15:28:39
| 2023-08-09T17:52:56
| 5,600,932
| 145
| 150
|
BSD-3-Clause
| 2023-08-09T17:52:57
| 2012-08-29T13:33:22
|
C++
|
UTF-8
|
C++
| false
| false
| 15,182
|
cpp
|
bidsviewmodel.cpp
|
//=============================================================================================================
/**
* @file bidsviewmodel.cpp
* @author Lorenz Esch <lesch@mgh.harvard.edu>
* Gabriel Motta <gbmotta@mgh.harvard.edu>
* @since 0.1.6
* @date October, 2020
*
* @section LICENSE
*
* Copyright (C) 2020, Lorenz Esch, Gabriel Motta. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that
* the following conditions are met:
* * Redistributions of source code must retain the above copyright notice, this list of conditions and the
* following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
* the following disclaimer in the documentation and/or other materials provided with the distribution.
* * Neither the name of MNE-CPP authors nor the names of its contributors may be used
* to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
* @brief Definition of the BidsViewModel Class.
*
*/
//=============================================================================================================
// INCLUDES
//=============================================================================================================
#include "bidsviewmodel.h"
#include <iostream>
//=============================================================================================================
// QT INCLUDES
//=============================================================================================================
#include <QtDebug>
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================
using namespace DISPLIB;
//=============================================================================================================
// DEFINE MEMBER METHODS
//=============================================================================================================
BidsViewModel::BidsViewModel(QObject *pParent)
: QStandardItemModel(pParent)
{
}
//=============================================================================================================
BidsViewModel::~BidsViewModel()
{
}
//=============================================================================================================
void BidsViewModel::addData(QModelIndex selectedItem,
QStandardItem* pNewItem,
int iDataType)
{
switch(iDataType){
case BIDS_FUNCTIONALDATA:
case BIDS_ANATOMICALDATA:
case BIDS_BEHAVIORALDATA: {
if(!selectedItem.isValid()) {
addDataToSession(addSessionToSubject(addSubject("sub-01"), "ses-01"), pNewItem, iDataType);
} else {
if (itemFromIndex(selectedItem)->data(BIDS_ITEM_TYPE).value<int>() != BIDS_SUBJECT){
addDataToSession(itemFromIndex(selectedItem)->data(BIDS_ITEM_SESSION).value<QModelIndex>(),
pNewItem,
iDataType);
} else {
qDebug() << "[BidsViewModel::addData] Prompt user to select a session";
}
}
break;
}
case BIDS_EVENT:
case BIDS_AVERAGE: {
if(!selectedItem.isValid()) {
QStandardItem* pItem = new QStandardItem("Unknown");
pItem->setEditable(false);
pItem->setDragEnabled(true);
addDataToSession(addSessionToSubject(addSubject("sub-01"), "ses-01"), pItem, BIDS_UNKNOWN);
addToData(pNewItem,
indexFromItem(pItem),
iDataType);
} else {
addToData(pNewItem,
selectedItem,
iDataType);
}
break;
}
}
}
//=============================================================================================================
void BidsViewModel::addToData(QStandardItem *pNewAvgItem,
const QModelIndex &parentIndex,
int iDataType)
{
QStandardItem* selectedData = itemFromIndex(parentIndex);
selectedData->setChild(selectedData->rowCount(),
pNewAvgItem);
pNewAvgItem->setData(itemFromIndex(parentIndex)->data(BIDS_ITEM_SUBJECT), BIDS_ITEM_SUBJECT);
pNewAvgItem->setData(itemFromIndex(parentIndex)->data(BIDS_ITEM_SESSION), BIDS_ITEM_SESSION);
pNewAvgItem->setData(QVariant::fromValue(iDataType), BIDS_ITEM_TYPE);
emit newItemIndex(pNewAvgItem->index());
}
//=============================================================================================================
QModelIndex BidsViewModel::addSubject(const QString &sSubjectName)
{
//Ensure subject name follow BIDS format
QString sNewSubjectName;
if(!sSubjectName.startsWith("sub-")){
sNewSubjectName = "sub-" + sSubjectName;
} else {
sNewSubjectName = sSubjectName;
}
sNewSubjectName.remove(" ");
//Add subject to model
QStandardItem* pSubjectItem = new QStandardItem(sNewSubjectName);
appendRow(pSubjectItem);
pSubjectItem->setData(QVariant::fromValue(BIDS_SUBJECT), BIDS_ITEM_TYPE);
pSubjectItem->setData(QVariant::fromValue(pSubjectItem->index()), BIDS_ITEM_SUBJECT);
emit newItemIndex(pSubjectItem->index());
return pSubjectItem->index();
}
//=============================================================================================================
QModelIndex BidsViewModel::addSessionToSubject(const QString &sSubjectName,
const QString &sSessionName)
{
//Ensure session name follow BIDS format
QString sNewSessionName;
if(!sSessionName.startsWith("ses-")){
sNewSessionName = "ses-" + sSessionName;
} else {
sNewSessionName = sSessionName;
}
sNewSessionName.remove(" ");
QList<QStandardItem*> listItems = findItems(sSubjectName);
bool bRepeat = false;
//Check for repeated names, no names
if (listItems.size() > 1) {
qWarning() << "[BidsViewModel::addSessionToSubject] Multiple subjects with same name";
bRepeat = true;
} else if (listItems.size() == 0) {
qWarning() << "[BidsViewModel::addSessionToSubject] No Subject found with name:" << sSubjectName;
return QModelIndex();
}
QStandardItem* pNewSessionItem;
//Add session to subjects with mathcing names. Renames them if multiple.
for (int i = 0; i < listItems.size(); i++){
QStandardItem* pSubjectItem = listItems.at(i);
if(bRepeat){
pSubjectItem->setText(pSubjectItem->text() + QString::number(i + 1));
}
pNewSessionItem = new QStandardItem(sNewSessionName);
pSubjectItem->setChild(pSubjectItem->rowCount(),
pNewSessionItem);
pNewSessionItem->setData(QVariant::fromValue(BIDS_SESSION), BIDS_ITEM_TYPE);
pNewSessionItem->setData(QVariant::fromValue(pSubjectItem->index()), BIDS_ITEM_SUBJECT);
pNewSessionItem->setData(QVariant::fromValue(pNewSessionItem->index()), BIDS_ITEM_SESSION);
emit newItemIndex(pNewSessionItem->index());
}
return pNewSessionItem->index();
}
//=============================================================================================================
QModelIndex BidsViewModel::addSessionToSubject(QModelIndex subjectIndex,
const QString &sSessionName)
{
//Ensure session name follow BIDS format
QString sNewSessionName;
if(!sSessionName.startsWith("ses-")){
sNewSessionName = "ses-" + sSessionName;
} else {
sNewSessionName = sSessionName;
}
sNewSessionName.remove(" ");
QStandardItem* pSubjectItem = itemFromIndex(subjectIndex);
QStandardItem* pNewSessionItem = new QStandardItem(sNewSessionName);
pSubjectItem->setChild(pSubjectItem->rowCount(),
pNewSessionItem);
pNewSessionItem->setData(QVariant::fromValue(BIDS_SESSION), BIDS_ITEM_TYPE);
pNewSessionItem->setData(QVariant::fromValue(subjectIndex), BIDS_ITEM_SUBJECT);
pNewSessionItem->setData(QVariant::fromValue(pNewSessionItem->index()), BIDS_ITEM_SESSION);
emit newItemIndex(pNewSessionItem->index());
return pNewSessionItem->index();
}
//=============================================================================================================
QModelIndex BidsViewModel::addDataToSession(QModelIndex sessionIndex,
QStandardItem *pNewItem,
int iDataType)
{
QStandardItem* pSessionItem = itemFromIndex(sessionIndex);
bool bFolder = false;
int iFolder;
QString sFolderName;
switch (iDataType){
case BIDS_FUNCTIONALDATA:
sFolderName = "func";
break;
case BIDS_ANATOMICALDATA:
sFolderName = "anat";
break;
case BIDS_BEHAVIORALDATA:
sFolderName = "beh";
default:
sFolderName = "unknown";
}
for(iFolder = 0; iFolder < pSessionItem->rowCount(); iFolder++){
if (pSessionItem->child(iFolder)->text() == sFolderName){
bFolder = true;
break;
}
}
if(!bFolder) {
QStandardItem* pFunctionalItem = new QStandardItem(sFolderName);
pFunctionalItem->setData(QVariant::fromValue(BIDS_FOLDER), BIDS_ITEM_TYPE);
pFunctionalItem->setData(QVariant::fromValue(sessionIndex), BIDS_ITEM_SESSION);
pFunctionalItem->setData(itemFromIndex(sessionIndex)->data(BIDS_ITEM_SUBJECT), BIDS_ITEM_SUBJECT);
pSessionItem->setChild(pSessionItem->rowCount(),
pFunctionalItem);
pFunctionalItem->setChild(pFunctionalItem->rowCount(),
pNewItem);
} else {
pSessionItem->child(iFolder)->setChild(pSessionItem->child(iFolder)->rowCount(),
pNewItem);
}
pNewItem->setData(QVariant::fromValue(iDataType), BIDS_ITEM_TYPE);
pNewItem->setData(QVariant::fromValue(sessionIndex), BIDS_ITEM_SESSION);
pNewItem->setData(itemFromIndex(sessionIndex)->data(BIDS_ITEM_SUBJECT), BIDS_ITEM_SUBJECT);
emit newItemIndex(pNewItem->index());
return pNewItem->index();
}
//=============================================================================================================
QModelIndex BidsViewModel::moveSessionToSubject(QModelIndex subjectIndex,
QModelIndex sessionIndex)
{
beginResetModel();
QStandardItem* subjectItem = itemFromIndex(subjectIndex);
QStandardItem* sessionItem = itemFromIndex(sessionIndex);
sessionItem->parent()->takeRow(sessionItem->row());
subjectItem->setChild(subjectItem->rowCount(), sessionItem);
subjectItem->setData(subjectIndex, BIDS_ITEM_SUBJECT);
for (int i = 0; i < sessionItem->rowCount(); i++){
sessionItem->child(i)->setData(subjectIndex, BIDS_ITEM_SUBJECT);
for (int j = 0; j < sessionItem->child(i)->rowCount(); j++) {
sessionItem->child(i)->child(j)->setData(subjectIndex, BIDS_ITEM_SUBJECT);
}
}
endResetModel();
emit newItemIndex(sessionItem->index());
return sessionItem->index();
}
//=============================================================================================================
QModelIndex BidsViewModel::moveDataToSession(QModelIndex sessionIndex,
QModelIndex dataIndex)
{
beginResetModel();
QStandardItem* dataItem = itemFromIndex(dataIndex);
if(dataItem->parent()->rowCount() < 2){
QStandardItem* parent = dataItem->parent();
dataItem->parent()->takeRow(dataItem->row()).first();
parent->parent()->takeRow(parent->row()).first();
} else {
dataItem->parent()->takeRow(dataItem->row()).first();
}
QModelIndex newIndex;
// switch(dataItem->data(ITEM_TYPE).value<int>()){
// case FUNCTIONALDATA:{
// newIndex = addDataToSession(sessionIndex,
// dataItem,
// FUNCTIONALDATA);
// break;
// }
// default:{
// qWarning() << "[BidsViewModel::moveDataToSession] Move not supported for this type of data";
// }
// }
newIndex = addDataToSession(sessionIndex,
dataItem,
dataItem->data(BIDS_ITEM_TYPE).value<int>());
endResetModel();
emit newItemIndex(sessionIndex);
emit newItemIndex(newIndex);
return newIndex;
}
//=============================================================================================================
bool BidsViewModel::removeItem(QModelIndex itemIndex)
{
if(!itemIndex.isValid()){
return false;
}
beginResetModel();
QStandardItem* pItem = itemFromIndex(itemIndex);
qInfo() << "Deleting" << pItem->text();
switch(pItem->data(BIDS_ITEM_TYPE).value<int>()){
case BIDS_SUBJECT:
if(removeRows(itemIndex.row(), 1, itemIndex.parent())){
endResetModel();
}
return true;
case BIDS_SESSION:
if(removeRows(itemIndex.row(), 1, itemIndex.parent())){
endResetModel();
}
return true;
case BIDS_BEHAVIORALDATA:
case BIDS_ANATOMICALDATA:
case BIDS_FUNCTIONALDATA:
if(removeRows(itemIndex.row(), 1, itemIndex.parent())){
endResetModel();
}
return true;
case BIDS_AVERAGE:
case BIDS_EVENT:
case BIDS_DIPOLE:
if(removeRows(itemIndex.row(), 1, itemIndex.parent())){
endResetModel();
}
return true;
default:
if(removeRows(itemIndex.row(), 1, itemIndex.parent())){
endResetModel();
}
return true;
}
}
|
5df2e92f06116597ad38747868c23ac9b623b306
|
f250678b454d1ce7c9f0d471e3a40ee057710669
|
/common/shape.cpp
|
6e4dee5b10e89cec0d7052baf56c04e03e771062
|
[] |
no_license
|
gejimayu/OpenGLK
|
6e25733b8f82a8a5c09ce594efc2a41411505e5e
|
c1dbb8bd4597f6673e07fa16cd6fa515e7434573
|
refs/heads/master
| 2020-03-19T17:15:33.291089
| 2018-05-14T17:06:12
| 2018-05-14T17:06:12
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,248
|
cpp
|
shape.cpp
|
#include<iostream>
#include<math.h>
#include "shape.h"
void addPolygon(GLfloat* &arr_a, int &num_of_point_a, GLuint* &ele_a, int &num_of_element_a, GLfloat* arr_b, int num_of_point_b, GLuint* ele_b, int num_of_element_b, std::vector<std::pair<int, int>> &segments) {
segments.push_back(std::make_pair(num_of_element_a, num_of_element_b));
auto arr_result = new GLfloat[5*(num_of_point_a + num_of_point_b)];
auto ele_result = new GLuint[num_of_element_a + num_of_element_b];
for(int i = 0; i < 5*num_of_point_a; i++) {
arr_result[i] = arr_a[i];
}
for(int i = 0; i < 5*num_of_point_b; i++) {
arr_result[5*num_of_point_a + i] = arr_b[i];
}
for (int i = 0; i < num_of_element_a; i++) {
ele_result[i] = ele_a[i];
}
for (int i = 0; i < num_of_element_b; i++) {
ele_result[num_of_element_a + i] = ele_b[i] + num_of_point_a;
}
delete[] arr_a;
delete[] ele_a;
arr_a = arr_result;
ele_a = ele_result;
num_of_point_a = num_of_point_a + num_of_point_b;
num_of_element_a = num_of_element_a + num_of_element_b;
}
GLfloat* createPolygon(GLfloat* arr, int num_of_point, GLfloat r, GLfloat g, GLfloat b) {
GLfloat* result_arr = new GLfloat[num_of_point * 5];
for (int i = 0; i < num_of_point; i++) {
result_arr[5*i] = arr[2*i];
result_arr[5*i + 1] = arr[2*i + 1];
result_arr[5*i + 2] = r;
result_arr[5*i + 3] = g;
result_arr[5*i + 4] = b;
}
return result_arr;
}
GLfloat* createCircle(GLfloat x, GLfloat y, GLfloat r, GLfloat color_r, GLfloat color_g, GLfloat color_b, int n) {
auto result = new GLfloat[(n + 1) * 5];
result[0] = x;
result[1] = y;
result[2] = color_r;
result[3] = color_g;
result[4] = color_b;
for (int i = 1; i < n+1; i++) {
result[5*i] = x + (r * cos(i*2*M_PI / n));
result[5*i + 1] = y + (r * sin(i*2*M_PI / n));
result[5*i + 2] = color_r;
result[5*i + 3] = color_g;
result[5*i + 4] = color_b;
}
return result;
}
GLuint* createCircleElements(int n) {
auto result = new GLuint[(n + 2)];
for (int i = 0; i < n+1; i++) {
result[i] = i;
}
result[n+1] = 1;
return result;
}
|
784e797079ab52e2b0b7f35764a3b87fb0cfd2ca
|
cd6b5688f1f91e9a6de26993ab4ecedcb0af8e7c
|
/GlobalGameJam2018Game/PolyJamGame/Src/ActorSystem.hpp
|
35f31c565a3cf083326b4a7c8c7107e5ce44d76d
|
[
"MIT"
] |
permissive
|
KNTGPolygon/PolyEngineExamples
|
8009639ece30f790b6b6a7f01a6a10ddae84c164
|
f91c87fff0ea1ffa0b743b584d5f621cb86a0edb
|
refs/heads/dev
| 2021-05-05T22:33:34.870120
| 2019-01-04T13:06:17
| 2019-01-04T13:06:17
| 116,171,508
| 0
| 9
|
MIT
| 2019-01-08T20:49:37
| 2018-01-03T19:00:12
|
C++
|
UTF-8
|
C++
| false
| false
| 461
|
hpp
|
ActorSystem.hpp
|
#pragma once
#include <ECS/Scene.hpp>
using namespace Poly;
namespace GGJGame
{
enum class eProjectileType;
namespace ActorSystem
{
void GAME_DLLEXPORT Update(Scene* world);
void Jump(Poly::Entity* actor);
void Shoot(Poly::Scene* world, Poly::Entity* actor, const Vector& localOffset, const Vector& direction);
void Move(Poly::Entity* actor, Vector direction, float speedMult = 1.0f);
void GiveDamage(Poly::Entity* actor, float damage);
}
}
|
ba5b0775bc1b9900181820df1fa674e897bd46d7
|
4a1ef66e84febdd996ccccb1d7cdf0002ba9e411
|
/framework/Renderer/Headers/Light.h
|
c195485329ffe5e6de37d050c714ad6ae20339c5
|
[
"MIT"
] |
permissive
|
grtwall/kigs
|
dc782b517626ab792048a3f74e670ba39ae17aaa
|
2ada0068c8618935ed029db442ecf58f6bf96126
|
refs/heads/master
| 2023-06-06T12:11:44.054106
| 2021-06-28T11:31:43
| 2021-06-28T11:35:05
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,744
|
h
|
Light.h
|
#ifndef _LIGHT_H_
#define _LIGHT_H_
#include "Node3D.h"
#include "maReference.h"
#include "TecLibs/Tec3D.h"
#ifdef _3DSMAX
namespace KigsFramework
{
#endif
// ****************************************
// * Light class
// * --------------------------------------
/**
* \file Light.h
* \class Light
* \ingroup Renderer
* \brief Base class, generic light object.
*
*/
// ****************************************
class Light : public Node3D
{
public:
DECLARE_ABSTRACT_CLASS_INFO(Light, Node3D,Renderer)
/**
* \brief constructor
* \fn Light(const kstl::string& name,DECLARE_CLASS_NAME_TREE_ARG);
* \param name : instance name
* \param DECLARE_CLASS_NAME_TREE_ARG : list of arguments
*/
Light(const kstl::string& name,DECLARE_CLASS_NAME_TREE_ARG);
/**
* \brief set the diffuse color
* \fn void SetDiffuseColor(kfloat r,kfloat g,kfloat b,kfloat a)
* \param r : red color
* \param g : green color
* \param b : blue color
* \param a : alpha value
*/
void SetDiffuseColor(kfloat r,kfloat g,kfloat b)
{
mDiffuseColor[0]=r;
mDiffuseColor[1]=g;
mDiffuseColor[2]=b;
NotifyUpdate(mDiffuseColor.getLabelID()._id);
}
/**
* \brief set the specular color
* \fn void SetSpecularColor(kfloat r,kfloat g,kfloat b,kfloat a)
* \param r : red color
* \param g : green color
* \param b : blue color
* \param a : alpha value
*/
void SetSpecularColor(kfloat r,kfloat g,kfloat b)
{
mSpecularColor[0]=r;
mSpecularColor[1]=g;
mSpecularColor[2]=b;
NotifyUpdate(mSpecularColor.getLabelID()._id);
}
/**
* \brief set the ambient color
* \fn void SetAmbientColor(kfloat r,kfloat g,kfloat b,kfloat a)
* \param r : red color
* \param g : green color
* \param b : blue color
* \param a : alpha value
*/
void SetAmbientColor(kfloat r,kfloat g,kfloat b)
{
mAmbientColor[0]=r;
mAmbientColor[1]=g;
mAmbientColor[2]=b;
NotifyUpdate(mAmbientColor.getLabelID()._id);
}
inline void setIsOn(bool a_value) { mIsOn = a_value; }
inline bool getIsOn() const { return mIsOn; }
protected:
void InitModifiable() override;
/**
* \brief destructor
* \fn ~Light();
*/
virtual ~Light();
//! specular color
maVect3DF mSpecularColor;
//! ambient color
maVect3DF mAmbientColor;
//! diffuse color
maVect3DF mDiffuseColor;
//! spot attenuation
maFloat mSpotAttenuation;
//! spot cut off
maFloat mSpotCutOff;
//! attenuation constante
maFloat mConstAttenuation;
//! attenuation linear
maFloat mLinAttenuation;
//! attenuation quad
maFloat mQuadAttenuation;
//! TRUE if the light is on
maBool mIsOn;
//0 for point, 1 for directional, 2 for spot
maEnum<3> mLightType;
};
#ifdef _3DSMAX
} // namespace KigsFramework
#endif
#endif //_LIGHT_H_
|
7e7524f6d64df2082faddb0bae74289d1b9e5b9a
|
d8c12ea48213b4cbe7448bf0e0b82c3e190e32a9
|
/URI_c/1564 - Brazil World Cup.cpp
|
9c0370b5ae8df08f3e7ee9cc8794a80ca6d588d8
|
[] |
no_license
|
MinhazulKabir/CodingStore
|
f49ba17ef3a98eb97f5232ea989ebd842cbb3cd8
|
393a6363d4ce10d7a4f21f1deed9c6799818e1c5
|
refs/heads/master
| 2023-05-05T01:39:52.517682
| 2021-04-10T05:20:54
| 2021-05-26T08:16:49
| 356,479,134
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 280
|
cpp
|
1564 - Brazil World Cup.cpp
|
#include<bits/stdc++.h>
using namespace std;
int main()
{
int i,j,n;
while(scanf("%d",&n)!=EOF)
{
if(n==0)
{
printf("vai ter copa!\n");
}
else
{
printf("vai ter duas!\n");
}
}
return 0;
}
|
10b1fe5017cbdb44d70fab12670b1b1876c2070e
|
6e9511e57ced8bb869447c40de4dfcf6ae4bd8e5
|
/Src/Prj/UnitTest/Gen/Dcc/Ut_Packet/test.cpp
|
332b57c132668119fbb98341b105ce654df0775d
|
[
"MIT"
] |
permissive
|
RalfSondershaus/Arduino
|
f49b2802656796ee25462fbaf98b04ec14dfd0c1
|
7db614a29dbd4a9301073944d17584cf79f34a6f
|
refs/heads/master
| 2023-03-08T15:44:39.582369
| 2023-02-26T09:51:12
| 2023-02-26T09:51:12
| 151,407,265
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,948
|
cpp
|
test.cpp
|
/**
* @file test.cpp
*
* @author Ralf Sondershaus
*
* Google Test for Gen/Dcc/Packet.h
*/
#include <Dcc/Packet.h>
#include <gtest/gtest.h>
#include <array>
TEST(Ut_Packet, packet_empty)
{
Dcc::Packet<6> packet;
int i;
for (i = 0; i < 6; i++)
{
EXPECT_EQ(packet.refByte(i), 0);
}
EXPECT_EQ(packet.getNrBytes(), 0u);
}
TEST(Ut_Packet, packet_add_2_bits)
{
Dcc::Packet<6> packet;
packet.addBit(1);
EXPECT_EQ(packet.refByte(0), 1);
packet.addBit(1);
EXPECT_EQ(packet.refByte(0), 3);
EXPECT_EQ(packet.getNrBytes(), 1u);
}
TEST(Ut_Packet, packet_add_16_bits)
{
Dcc::Packet<6> packet;
std::array<uint8_t, 8> byte0 = { 1, 0, 1, 1, 0, 1, 1, 0 };
std::array<uint8_t, 8> byte1 = { 0, 1, 1, 0, 0, 0, 0, 1 };
uint8_t byte;
byte = 0;
for (auto it = byte0.begin(); it != byte0.end(); it++)
{
packet.addBit(*it);
byte = static_cast<uint8_t>((byte << 1u) | *it);
EXPECT_EQ(packet.refByte(0), byte);
EXPECT_EQ(packet.getNrBytes(), 1u);
}
byte = 0;
for (auto it = byte1.begin(); it != byte1.end(); it++)
{
packet.addBit(*it);
byte = static_cast<uint8_t>((byte << 1u) | *it);
EXPECT_EQ(packet.refByte(1), byte);
EXPECT_EQ(packet.getNrBytes(), 2u);
}
}
TEST(Ut_Packet, packet_copy_constructor)
{
Dcc::Packet<6> packet;
std::array<uint8_t, 8> byte0 = { 1, 0, 1, 1, 0, 1, 1, 0 };
std::array<uint8_t, 8> byte1 = { 0, 1, 1, 0, 0, 0, 0, 1 };
for (auto it = byte0.begin(); it != byte0.end(); it++)
{
packet.addBit(*it);
}
for (auto it = byte1.begin(); it != byte1.end(); it++)
{
packet.addBit(*it);
}
auto packet_copy = packet; // copy initialization
EXPECT_EQ(packet_copy.refByte(0), 0b10110110u);
EXPECT_EQ(packet_copy.refByte(1), 0b01100001u);
EXPECT_EQ(packet_copy.getNrBytes(), 2u);
}
TEST(Ut_Packet, packet_copy_assignment)
{
Dcc::Packet<6> packet;
Dcc::Packet<6> packet_copy;
std::array<uint8_t, 8> byte0 = { 1, 0, 1, 1, 0, 1, 1, 0 };
std::array<uint8_t, 8> byte1 = { 0, 1, 1, 0, 0, 0, 0, 1 };
for (auto it = byte0.begin(); it != byte0.end(); it++)
{
packet.addBit(*it);
}
for (auto it = byte1.begin(); it != byte1.end(); it++)
{
packet.addBit(*it);
}
packet_copy = packet; // copy assignment
EXPECT_EQ(packet_copy.refByte(0), 0b10110110u);
EXPECT_EQ(packet_copy.refByte(1), 0b01100001u);
EXPECT_EQ(packet_copy.getNrBytes(), 2u);
}
TEST(Ut_Packet, packet_operator_equal)
{
Dcc::Packet<6> packet;
Dcc::Packet<6> packet_copy;
std::array<uint8_t, 8> byte0 = { 1, 0, 1, 1, 0, 1, 1, 0 };
std::array<uint8_t, 8> byte1 = { 0, 1, 1, 0, 0, 0, 0, 1 };
for (auto it = byte0.begin(); it != byte0.end(); it++)
{
packet.addBit(*it);
}
for (auto it = byte1.begin(); it != byte1.end(); it++)
{
packet.addBit(*it);
}
packet_copy = packet; // copy assignment
EXPECT_EQ(packet_copy == packet, true);
packet.addBit(1);
EXPECT_EQ(packet_copy == packet, false);
}
|
10f42c722f7633855298f315c889ccd68ffad99f
|
7271999719f130d2e56d058c445b5871f2e0a517
|
/include/db.hpp
|
353e8d591a30c59cfb7b94db15b16e53e826d6a8
|
[] |
no_license
|
alexmustdie/PolyLib
|
2beefb62d7bab142fcf3d13f44623c6289bf6555
|
0f1aa02e38bcab8e38d833c997dce443762a96ba
|
refs/heads/master
| 2020-03-21T20:44:18.385161
| 2018-08-13T16:16:50
| 2018-08-13T16:16:50
| 139,024,821
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 504
|
hpp
|
db.hpp
|
#ifndef DB_HPP_INCLUDED
#define DB_HPP_INCLUDED
#include <pqxx/pqxx>
namespace polylib
{
class DB
{
private:
DB() = default;
~DB() = default;
DB(const DB &) = delete;
DB& operator=(const DB &) = delete;
DB(DB &&) = delete;
DB& operator=(DB &&) = delete;
public:
static pqxx::nontransaction * get()
{
static pqxx::connection db_connection("dbname=polylib");
static pqxx::nontransaction db(db_connection);
return &db;
}
};
}
#endif
|
f03ea4cf02cb79fb9cb38a5ff687935a75323cd8
|
f327ee49aa144bf5d3397e509bdadb36cf835f7c
|
/merge-k-sorted-lists-1.cpp
|
6f1f6a7bd71f1e59c5000d1afe54274825154f69
|
[] |
no_license
|
sidthekidder/dsa-practice
|
5c677f7654c83f332c23561851e5f890ba5b2b93
|
14d019d79416f8b32c97dbf6105cf0835157d25b
|
refs/heads/master
| 2020-03-24T18:43:01.613110
| 2019-10-16T19:15:39
| 2019-10-16T19:15:39
| 142,897,894
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,362
|
cpp
|
merge-k-sorted-lists-1.cpp
|
// https://leetcode.com/problems/merge-k-sorted-lists/
// time complexity - O(k + nlogk), space complexity - O(k)
class Comparator
{
public:
bool operator() (ListNode* a, ListNode* b)
{
return a->val > b->val;
}
};
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists)
{
// push all list heads into min priority_queue and insert min node into result each time
// keep doing so until all lists are empty
ListNode* head = NULL;
ListNode* result = NULL;
priority_queue<ListNode*, vector<ListNode*>, Comparator> pq;
for(int i = 0 ; i < lists.size() ; i++)
if (lists[i] != NULL)
pq.push(lists[i]);
while (!pq.empty())
{
// get min value node and pop from queue
ListNode* min_node = pq.top();
pq.pop();
// insert into result
if (!result)
{
result = min_node;
head = min_node;
}
else
{
result->next = min_node;
result = result->next;
}
// insert next node after min_node
if (min_node->next != NULL)
pq.push(min_node->next);
}
return head;
}
};
|
caa8805587e7570e5ce53e6918ac9415e706782d
|
82a986a306b0a9f9947a8c9f55aad4817f4f4137
|
/Zadanka z Algosów/graph.hpp
|
2ff1e34f6a565474afd42b682e8ef255bea705e0
|
[] |
no_license
|
SoliareofAstora/Algosy
|
e89ff45f10c8604dc6cae66d3eec5703ff94ad86
|
f442ffb1c8f94e30a24ab8ee6c68ad3735b2e4a7
|
refs/heads/master
| 2018-10-13T18:15:33.540815
| 2018-08-15T01:36:15
| 2018-08-15T01:36:15
| 106,525,474
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 12,265
|
hpp
|
graph.hpp
|
#pragma once
#include <vector>
#include <future>
#include "avl.h"
#include <stack>
#include <queue>
template <typename T,typename edge>
class graph
{
struct edge_info
{
edge label;
bool connection;
edge_info():connection(false){}
edge_info(edge& label) :label(label), connection(true) {}
};
public:
std::vector<std::vector<edge_info>> adjacency_matrix;
std::vector<T> vertices;
graph();
#pragma region Iterators
typedef typename std::vector<T>::iterator VerticesIterator;
VerticesIterator beginVertices();
VerticesIterator endVertices();
VerticesIterator begin();
VerticesIterator end();
class EdgesIterator
{
graph<T,edge> * source_;
std::pair<int, int> current_;
public:
EdgesIterator(graph<T, edge>* source,int first, int second);
EdgesIterator(graph<T, edge>* source, std::pair<int, int> current);
bool operator==(const EdgesIterator &i) const;
bool operator!=(const EdgesIterator &i) const;
EdgesIterator& operator++();
EdgesIterator operator++(int);
edge operator*();
void findNextEdge();
};
EdgesIterator beginEdges();
EdgesIterator endEdges();
class DFSIterator
{
graph* source_;
int current_;
avl<int> visited_;
std::stack<int> stack_;
public:
DFSIterator(graph* source, int start_at);
bool operator==(const DFSIterator &i) const;
bool operator!=(const DFSIterator &i) const;
DFSIterator& operator++();
DFSIterator operator++(int);
T operator*();
void findNextVertex();
};
DFSIterator beginDFS(int n);
DFSIterator endDFS();
class BFSIterator
{
graph* source_;
int current_;
int currentNeighbor_;
avl<int> visited_;
std::queue<int> queue_;
public:
BFSIterator(graph* source, int start_at);
bool operator==(const BFSIterator &i) const;
bool operator!=(const BFSIterator &i) const;
BFSIterator& operator++();
BFSIterator operator++(int);
T operator*();
void findNextVertex();
};
BFSIterator beginBFS(int start_at);
BFSIterator endBFS();
#pragma endregion
EdgesIterator insertEdge(int from_index, int destination_index, edge name);
EdgesIterator insertEdge(int from_index, int destination_index, edge name, bool overwrite);
VerticesIterator insertVertex(T value);
VerticesIterator removeVertex(int index);
EdgesIterator removeEdge(int from_index, int destination_index);
T* vertexData(int index);
edge* edgeLabel(int from_index, int destination_index);
bool edgeExist(int from_index, int destination_index)const;
size_t nrOfVertices() const;
size_t nrOfEdges() const;
void printNeighborhoodMatrix();
};
#pragma region Graph functions
template<typename T, typename edge>
graph<T, edge>::graph() = default;
template <typename T, typename edge>
typename graph<T,edge>::EdgesIterator graph<T, edge>::insertEdge(int from_index, int destination_index, edge name)
{
return insertEdge(from_index, destination_index, name, false);
}
template <typename T, typename edge>
typename graph<T,edge>::EdgesIterator graph<T, edge>::insertEdge(int from_index, int destination_index, edge name, bool overwrite)
{
if (from_index >= vertices.size() ||destination_index >= vertices.size() ||from_index<0||destination_index<0)
{
return endEdges();
}
if (!(adjacency_matrix[from_index][destination_index].connection)||overwrite)
{
adjacency_matrix[from_index][destination_index] = edge_info(name);
}
return EdgesIterator(this,from_index,destination_index);
}
template <typename T, typename edge>
typename graph<T, edge>::VerticesIterator graph<T, edge>::insertVertex(T value)
{
vertices.push_back(value);
adjacency_matrix.push_back(std::vector<edge_info>());
for(auto &v : adjacency_matrix)
{
v.push_back(edge_info());
}
adjacency_matrix[vertices.size()-1].resize(vertices.size());
return endVertices() - 1;
}
template <typename T, typename edge>
typename graph<T, edge>::VerticesIterator graph<T, edge>::removeVertex(int index)
{
vertices.erase(vertices.begin()+index);
for(auto &v : adjacency_matrix)
{
v.erase(v.begin() + index);
}
adjacency_matrix.erase(adjacency_matrix.begin() + index);
return beginVertices() + index;
}
template <typename T, typename edge>
typename graph<T, edge>::EdgesIterator graph<T, edge>::removeEdge(int from_index, int destination_index)
{
adjacency_matrix[from_index][destination_index] = edge_info();
return EdgesIterator(this, from_index, destination_index);
}
template <typename T, typename edge>
T* graph<T, edge>::vertexData(int index)
{
if (index<0 || index >= this->nrOfVertices())
{
return nullptr;
}
return &vertices[index];
}
template <typename T, typename edge>
edge* graph<T, edge>::edgeLabel(int from_index, int destination_index)
{
if (from_index<0 || from_index >= this->nrOfVertices()|| destination_index<0 || destination_index >= this->nrOfVertices())
{
return nullptr;
}
return &adjacency_matrix[from_index][destination_index].label;
}
template <typename T, typename edge>
bool graph<T, edge>::edgeExist(int from_index, int destination_index) const
{
return adjacency_matrix[from_index][destination_index].connection;
}
template <typename T, typename edge>
size_t graph<T, edge>::nrOfVertices() const
{
return vertices.size();
}
template <typename T, typename edge>
size_t graph<T, edge>::nrOfEdges() const
{
size_t sum = 0;
for (auto &vector : adjacency_matrix)
{
for (auto &element : vector)
{
if (element.connection)
{
sum++;
}
}
}
return sum;
}
template <typename T, typename edge>
void graph<T, edge>::printNeighborhoodMatrix()
{
for (auto &v : adjacency_matrix)
{
for (auto &a : v)
{
std::string temp = a.connection == true ? "1" : "0";
std::cout << temp<<" ";
}
std::cout << "\n";
}
std::cout << "\n";
}
#pragma endregion
#pragma region VerticesIterator
template <typename T, typename edge>
typename graph<T, edge>::VerticesIterator graph<T, edge>::beginVertices()
{
return vertices.begin();
}
template <typename T, typename edge>
typename graph<T, edge>::VerticesIterator graph<T, edge>::endVertices()
{
return vertices.end();
}
template <typename T, typename edge>
typename graph<T, edge>::VerticesIterator graph<T, edge>::begin()
{
return beginVertices();
}
template <typename T, typename edge>
typename graph<T, edge>::VerticesIterator graph<T, edge>::end()
{
return endVertices();
}
#pragma endregion
#pragma region EdgeIterator
template <typename T, typename edge>
graph<T, edge>::EdgesIterator::EdgesIterator(graph<T,edge>* source, int first, int second):source_(source),current_(first,second)
{
if (first>=0)
{
findNextEdge();
}
}
template <typename T, typename edge>
graph<T, edge>::EdgesIterator::EdgesIterator(graph<T, edge>* source, std::pair<int, int> current):source_(source),current_(current)
{
}
template <typename T, typename edge>
bool graph<T, edge>::EdgesIterator::operator==(const EdgesIterator& i) const
{
return current_ == i.current_ && source_==i.source_;
}
template <typename T, typename edge>
bool graph<T, edge>::EdgesIterator::operator!=(const EdgesIterator& i) const
{
return current_ != i.current_ || source_ != i.source_;
}
template <typename T, typename edge>
typename graph<T, edge>::EdgesIterator& graph<T, edge>::EdgesIterator::operator++()
{
findNextEdge();
return *this;
}
template <typename T, typename edge>
typename graph<T, edge>::EdgesIterator graph<T, edge>::EdgesIterator::operator++(int)
{
EdgesIterator temp = EdgesIterator(source_, current_);
findNextEdge();
return temp;
}
template <typename T, typename edge>
edge graph<T, edge>::EdgesIterator::operator*()
{
return source_->adjacency_matrix[current_.first][current_.second].label;
}
template <typename T, typename edge>
void graph<T, edge>::EdgesIterator::findNextEdge()
{
do
{
do
{
if (++current_.second >= source_->vertices.size())
{
break;
}
if (source_->adjacency_matrix[current_.first][current_.second].connection)
{
return;
}
}
while (current_.second+1<source_->vertices.size());
current_.first++;
current_.second = -1;
}
while (current_.first<source_->vertices.size());
current_.first = -1;
}
template <typename T, typename edge>
typename graph<T, edge>::EdgesIterator graph<T, edge>::beginEdges()
{
return EdgesIterator(this,0,-1);
}
template <typename T, typename edge>
typename graph<T, edge>::EdgesIterator graph<T, edge>::endEdges()
{
return EdgesIterator(this, -1, -1);
}
#pragma endregion
#pragma region DFSIterator
template <typename T, typename edge>
graph<T, edge>::DFSIterator::DFSIterator(graph* source, int start_at):source_(source),current_(start_at)
{
visited_.insert(current_);
stack_.push(current_);
}
template <typename T, typename edge>
bool graph<T, edge>::DFSIterator::operator==(const DFSIterator& i) const
{
return current_ == i.current_ && source_ == i.source_;
}
template <typename T, typename edge>
bool graph<T, edge>::DFSIterator::operator!=(const DFSIterator& i) const
{
return current_ != i.current_ || source_ != i.source_;
}
template <typename T, typename edge>
typename graph<T, edge>::DFSIterator& graph<T, edge>::DFSIterator::operator++()
{
findNextVertex();
return *this;
}
template <typename T, typename edge>
typename graph<T, edge>::DFSIterator graph<T, edge>::DFSIterator::operator++(int)
{
DFSIterator temp = DFSIterator(source_,current_);
findNextVertex();
return temp;
}
template <typename T, typename edge>
T graph<T, edge>::DFSIterator::operator*()
{
return source_->vertices[current_];
}
template <typename T, typename edge>
void graph<T, edge>::DFSIterator::findNextVertex()
{
for (int i = 0; i < source_->nrOfVertices(); i++)
{
if (source_->adjacency_matrix[current_][i].connection)
{
if (visited_.find(i)==nullptr)
{
current_ = i;
visited_.insert(current_);
stack_.push(current_);
return;
}
}
}
if (stack_.empty())
{
current_ = -1;
return;
}
current_ = stack_.top();
stack_.pop();
findNextVertex();
}
template <typename T, typename edge>
typename graph<T, edge>::DFSIterator graph<T, edge>::beginDFS(int start_at)
{
if (start_at<0||start_at>=this->nrOfVertices())
{
return DFSIterator(this, -1);
}
return DFSIterator(this,start_at);
}
template <typename T, typename edge>
typename graph<T, edge>::DFSIterator graph<T, edge>::endDFS()
{
return DFSIterator(this, -1);
}
#pragma endregion
#pragma region BFSIterator
template <typename T, typename edge>
graph<T, edge>::BFSIterator::BFSIterator(graph* source, int start_at) :source_(source), current_(start_at), currentNeighbor_(-1)
{
visited_.insert(start_at);
}
template <typename T, typename edge>
bool graph<T, edge>::BFSIterator::operator==(const BFSIterator& i) const
{
return current_ == i.current_ && source_ == i.source_;
}
template <typename T, typename edge>
bool graph<T, edge>::BFSIterator::operator!=(const BFSIterator& i) const
{
return current_ != i.current_ || source_ != i.source_;
}
template <typename T, typename edge>
typename graph<T, edge>::BFSIterator& graph<T, edge>::BFSIterator::operator++()
{
findNextVertex();
return *this;
}
template <typename T, typename edge>
typename graph<T, edge>::BFSIterator graph<T, edge>::BFSIterator::operator++(int)
{
BFSIterator temp = BFSIterator(source_, current_);
findNextVertex();
return temp;
}
template <typename T, typename edge>
T graph<T, edge>::BFSIterator::operator*()
{
return source_->vertices[currentNeighbor_==-1?current_:currentNeighbor_];
}
template <typename T, typename edge>
void graph<T, edge>::BFSIterator::findNextVertex()
{
for (int i = currentNeighbor_+1; i < source_->nrOfVertices(); i++)
{
if (source_->adjacency_matrix[current_][i].connection)
{
if (visited_.find(i) == nullptr)
{
currentNeighbor_ = i;
queue_.push(i);
visited_.insert(i);
return;
}
}
}
currentNeighbor_ = -1;
if (queue_.empty())
{
current_ = -1;
return;
}
current_ = queue_.front();
queue_.pop();
findNextVertex();
}
template <typename T, typename edge>
typename graph<T, edge>::BFSIterator graph<T, edge>::beginBFS(int start_at)
{
if (start_at<0 || start_at >= this->nrOfVertices())
{
return BFSIterator(this, -1);
}
return BFSIterator(this, start_at);
}
template <typename T, typename edge>
typename graph<T, edge>::BFSIterator graph<T, edge>::endBFS()
{
return BFSIterator(this, -1);
}
#pragma endregion
|
2bf813b6e9533e67b3fb7cdf7572d192ab6b4106
|
745c975ae7afb47dc682a8130b8ea648b4227f7d
|
/aes_rsa_demo/rsa_example.cpp
|
341e3817aacd20a8ba5b628102ced25639df0067
|
[] |
no_license
|
acoolbest/practice
|
5a65878e2fdad570ac851bb7f2a50e0be39250cb
|
95790d9a5cc061619937cb18f6672be9655876cc
|
refs/heads/master
| 2021-04-06T00:09:51.733864
| 2018-12-24T01:31:25
| 2018-12-24T01:31:25
| 125,301,828
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,659
|
cpp
|
rsa_example.cpp
|
//example.cpp
//g++ rsa_example.cpp -o rsa.out -lcrypto
#include <openssl/pem.h>
#include <openssl/ssl.h>
#include <openssl/rsa.h>
#include <openssl/evp.h>
#include <openssl/bio.h>
#include <openssl/err.h>
#include <stdio.h>
int padding = RSA_PKCS1_PADDING;
RSA* createRSAWithFilename(const char*, int);
int public_encrypt(unsigned char * data,int data_len, const char* pub_fp, unsigned char *encrypted)
{
RSA * rsa = createRSAWithFilename(pub_fp,1);
int result = RSA_public_encrypt(data_len,data,encrypted,rsa,padding);
return result;
}
int private_decrypt(unsigned char * enc_data,int data_len, const char* pri_fp, unsigned char *decrypted)
{
RSA * rsa = createRSAWithFilename(pri_fp,0);
int result = RSA_private_decrypt(data_len,enc_data,decrypted,rsa,padding);
return result;
}
int private_encrypt(unsigned char * data,int data_len, const char* pri_fp, unsigned char *encrypted)
{
RSA * rsa = createRSAWithFilename(pri_fp,0);
int result = RSA_private_encrypt(data_len,data,encrypted,rsa,padding);
return result;
}
int public_decrypt(unsigned char * enc_data,int data_len, const char *pub_fp, unsigned char *decrypted)
{
RSA * rsa = createRSAWithFilename(pub_fp,1);
int result = RSA_public_decrypt(data_len,enc_data,decrypted,rsa,padding);
return result;
}
void printLastError(char *msg)
{
char * err = (char*)malloc(130);
ERR_load_crypto_strings();
ERR_error_string(ERR_get_error(), err);
printf("%s ERROR: %s\n",msg, err);
free(err);
}
RSA * createRSAWithFilename(const char * filename,int nPublic)
{
FILE * fp = fopen(filename,"rb");
if(fp == NULL)
{
printf("Unable to open file %s \n",filename);
return NULL;
}
RSA *rsa= RSA_new() ;
if(nPublic)
{
rsa = PEM_read_RSA_PUBKEY(fp, &rsa,NULL, NULL);
}
else
{
rsa = PEM_read_RSAPrivateKey(fp, &rsa,NULL, NULL);
}
return rsa;
}
int main(){
unsigned char plainText[2048/8] = "Hello this is tab_space";
unsigned char encrypted[4098]={};
unsigned char decrypted[4098]={};
const char* pub_fp = "/home/charge/share/practice/aes_rsa_demo/public.pem";
const char* pri_fp = "/home/charge/share/practice/aes_rsa_demo/private.pem";
int encrypted_length= public_encrypt(plainText,strlen((const char*)plainText),pub_fp,encrypted);
if(encrypted_length == -1)
{
printLastError((char*)"Public Encrypt failed ");
exit(0);
}
printf("Encrypted Text =%s\n",encrypted);
printf("Encrypted length =%d\n",encrypted_length);
int decrypted_length = private_decrypt(encrypted,encrypted_length, pri_fp, decrypted);
if(decrypted_length == -1)
{
printLastError((char*)"Private Decrypt failed ");
exit(0);
}
printf("Decrypted Text =%s\n",decrypted);
printf("Decrypted Length =%d\n",decrypted_length);
encrypted_length= private_encrypt(plainText,strlen((const char*) plainText),pri_fp,encrypted);
if(encrypted_length == -1)
{
printLastError((char*)"Private Encrypt failed");
exit(0);
}
printf("Encrypted Text =%s\n",encrypted);
printf("Encrypted length =%d\n",encrypted_length);
decrypted_length = public_decrypt(encrypted,encrypted_length,pub_fp, decrypted);
if(decrypted_length == -1)
{
printLastError((char*)"Public Decrypt failed");
exit(0);
}
printf("Decrypted Text =%s\n",decrypted);
printf("Decrypted Length =%d\n",decrypted_length);
}
|
c982d1dd13c4d2adca2ccd695a55f096ad9d6662
|
da86d9f9cf875db42fd912e3366cfe9e0aa392c6
|
/2018/solutions/C/MPA-Varna/palindromes.cpp
|
e364d6bf115da9b8ec1667bf397e2b6bc35c7526
|
[] |
no_license
|
Alaxe/noi2-ranking
|
0c98ea9af9fc3bd22798cab523f38fd75ed97634
|
bb671bacd369b0924a1bfa313acb259f97947d05
|
refs/heads/master
| 2021-01-22T23:33:43.481107
| 2020-02-15T17:33:25
| 2020-02-15T17:33:25
| 85,631,202
| 2
| 4
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,496
|
cpp
|
palindromes.cpp
|
#include<iostream>
#include<string>
using namespace std;
string input;
int ar[1301];
int main()
{
cin>>input;
int size = input.size();
bool oddSize = false;
for(int i = 0; i<size/2; ++i)
{
ar[i] = input[i]-'0';
ar[size-i-1] = input[i]-'0';
}
if(input.size()%2!=0)
{
ar[input.size()/2] = input [input.size()/2]-'0';
oddSize = true;
}
if(!oddSize)
{
for(int i = 0; i<size/2; ++i)
{
if(ar[i]<input[size-i-1]-'0')
{
if(ar[size/2]<=input[size/2]-'0'&&ar[size-size/2]<=input[size-size/2]-'0')
{
ar[size/2-1]++;
ar[size-size/2]++;
}
else break;
}
if(ar[i]>input[size-i-1]-'0') break;
}
}
else
{
for(int i = 0; i<size/2; ++i)
{
if(ar[i]<input[size-i-1]-'0')
{
if(ar[size/2]<=input[size/2]-'0')ar[size/2]++;
else break;
}
if(ar[i]>input[size-i-1]-'0') break;
}
}
for(int i = 0; i< size ; ++i)
{
if(ar[i]==10)
{
ar[i-1]++;
ar[i]=0;
ar[size-i-1] = 0;
ar[size-i] = ar[i-1];
}
}
for(int i = 0; i<size; ++i) cout<<ar[i];
return 0;
}
|
8c59b403b94f38fe529bd7bddaa37075c1f73e45
|
28aeabd696ad96b52ffc8b275aa948f4c3eeef80
|
/test/vendorTest.cpp
|
8edfe5bf001df28cdc6c663102fd81a2cf758b7c
|
[] |
no_license
|
naokirin/tddbc_cpp_disappointing_sample
|
40eedad36d62487fb46f94e7210ecacfa42ae975
|
4c3a1a2d420fe6350cc3fa5160d03949d6b72774
|
refs/heads/master
| 2021-01-10T20:49:19.132771
| 2013-01-06T04:47:49
| 2013-01-06T04:47:49
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,677
|
cpp
|
vendorTest.cpp
|
#include <gtest/gtest.h>
#include "../src/vendor.h"
#include <memory>
#include <iostream>
#include <stdexcept>
using namespace AutoVendor;
class VendorTest : public ::testing::Test {
protected:
std::unique_ptr<Vendor> vendor;
VendorTest() {vendor = std::unique_ptr<Vendor>(new Vendor());}
virtual void SetUp() {}
virtual void TearDown() {}
};
// Test Vendor.input()
TEST_F(VendorTest, Input1000) {
vendor->input(Money::Thousand);
EXPECT_EQ(1000u, vendor->getTotalAmount());
}
TEST_F(VendorTest, Input500) {
vendor->input(Money::FiveHundored);
EXPECT_EQ(500u, vendor->getTotalAmount());
}
TEST_F(VendorTest, Input100) {
vendor->input(Money::Hundored);
EXPECT_EQ(100u, vendor->getTotalAmount());
}
TEST_F(VendorTest, Input50) {
vendor->input(Money::Fifty);
EXPECT_EQ(50u, vendor->getTotalAmount());
}
TEST_F(VendorTest, Input10) {
vendor->input(Money::Ten);
EXPECT_EQ(10u, vendor->getTotalAmount());
}
TEST_F(VendorTest, Input) {
vendor->input(Money::Hundored);
vendor->input(Money::Ten);
EXPECT_EQ(110u, vendor->getTotalAmount());
vendor->input(Money::Thousand);
EXPECT_EQ(1110u, vendor->getTotalAmount());
}
// Test Vendor.inventory
TEST_F(VendorTest, coke) {
auto inventory = vendor->getInventory();
ASSERT_EQ(3u, inventory.size());
EXPECT_EQ(1u, inventory[1u].id);
EXPECT_EQ("コーラ", inventory[1u].name);
EXPECT_EQ(5u, inventory[1u].num);
EXPECT_EQ(120u, inventory[1u].value);
}
TEST_F(VendorTest, addStock) {
vendor->addStock({10u, "", 0u, 0u});
auto inventory = vendor->getInventory();
ASSERT_EQ(4u, inventory.size());
EXPECT_EQ(10u, inventory[10u].id);
EXPECT_EQ("", inventory[10u].name);
EXPECT_EQ(0u, inventory[10u].num);
EXPECT_EQ(0u, inventory[10u].value);
}
// vendor.purchase
TEST_F(VendorTest, purchasable) {
vendor->input(Money::Hundored);
vendor->input(Money::Fifty);
ASSERT_EQ(2u, vendor->getPurchasableList().size());
EXPECT_EQ(1u, vendor->getPurchasableList().front());
EXPECT_EQ(3u, vendor->getPurchasableList().back());
}
TEST_F(VendorTest, notPurchasable) {
vendor->input(Money::Ten);
EXPECT_TRUE(vendor->getPurchasableList().empty());
}
TEST_F(VendorTest, purchase) {
vendor->input(Money::Thousand);
auto actual = vendor->purchase(1u);
auto inventory = vendor->getInventory();
ASSERT_TRUE(actual);
EXPECT_EQ(4u, inventory[1u].num);
EXPECT_EQ(880u, actual.get());
EXPECT_EQ(880u, vendor->getTotalAmount());
}
TEST_F(VendorTest, purchaseAndGetZeroChange) {
vendor->input(Money::Hundored);
auto actual = vendor->purchase(3u);
ASSERT_TRUE(actual);
EXPECT_EQ(0u, actual.get());
}
TEST_F(VendorTest, notPurchase) {
vendor->input(Money::Hundored);
auto actual = vendor->purchase(1u);
auto inventory = vendor->getInventory();
ASSERT_FALSE(actual);
EXPECT_EQ(5u, inventory[1u].num);
EXPECT_EQ(100u, vendor->getTotalAmount());
EXPECT_EQ(0u, vendor->getSaleAmount());
}
TEST_F(VendorTest, saleAmount) {
vendor->input(Money::Thousand);
EXPECT_EQ(0u, vendor->getSaleAmount());
vendor->purchase(1u);
EXPECT_EQ(120u, vendor->getSaleAmount());
vendor->purchase(1u);
EXPECT_EQ(240u, vendor->getSaleAmount());
}
TEST_F(VendorTest, nothingInventory) {
vendor->input(Money::Thousand);
vendor->purchase(1u); vendor->purchase(1u); vendor->purchase(1u); vendor->purchase(1u); vendor->purchase(1u);
EXPECT_EQ(400u, vendor->getTotalAmount());
EXPECT_EQ(600u, vendor->getSaleAmount());
ASSERT_FALSE(vendor->purchase(1u));
EXPECT_EQ(400u, vendor->getTotalAmount());
EXPECT_EQ(600u, vendor->getSaleAmount());
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
7231f5d16f3a5967d957455887f7fda92de3c3ee
|
66d0c08a15947e6df23adcc17ab2fd461d6edc37
|
/linux/window_manager_plugin.cc
|
624357f23c285744de7aa52ba89828f6b6922dc9
|
[
"MIT"
] |
permissive
|
sergey925/window_manager
|
6bf746916737a0f44d62040b2f8555d303d06ad7
|
3120f7ebd3768f949354f001d486d8b29657312b
|
refs/heads/main
| 2023-07-12T21:10:22.523012
| 2021-08-30T03:07:10
| 2021-08-30T03:07:10
| 401,209,563
| 1
| 0
|
MIT
| 2021-08-30T04:05:40
| 2021-08-30T03:54:49
| null |
UTF-8
|
C++
| false
| false
| 11,621
|
cc
|
window_manager_plugin.cc
|
#include "include/window_manager/window_manager_plugin.h"
#include <flutter_linux/flutter_linux.h>
#include <gtk/gtk.h>
#include <sys/utsname.h>
#include <cstring>
#define WINDOW_MANAGER_PLUGIN(obj) \
(G_TYPE_CHECK_INSTANCE_CAST((obj), window_manager_plugin_get_type(), \
WindowManagerPlugin))
struct _WindowManagerPlugin
{
GObject parent_instance;
FlPluginRegistrar *registrar;
GdkGeometry window_geometry;
bool _is_minimized = false;
bool _is_always_on_top = false;
};
G_DEFINE_TYPE(WindowManagerPlugin, window_manager_plugin, g_object_get_type())
// Gets the window being controlled.
GtkWindow *get_window(WindowManagerPlugin *self)
{
FlView *view = fl_plugin_registrar_get_view(self->registrar);
if (view == nullptr)
return nullptr;
return GTK_WINDOW(gtk_widget_get_toplevel(GTK_WIDGET(view)));
}
GdkWindow *get_gdk_window(WindowManagerPlugin *self)
{
return gtk_widget_get_window(GTK_WIDGET(get_window(self)));
}
static FlMethodResponse *focus(WindowManagerPlugin *self)
{
gtk_window_present(get_window(self));
return FL_METHOD_RESPONSE(fl_method_success_response_new(fl_value_new_bool(true)));
}
static FlMethodResponse *blur(WindowManagerPlugin *self)
{
return FL_METHOD_RESPONSE(fl_method_success_response_new(fl_value_new_bool(true)));
}
static FlMethodResponse *show(WindowManagerPlugin *self)
{
gtk_widget_show(GTK_WIDGET(get_window(self)));
return FL_METHOD_RESPONSE(fl_method_success_response_new(fl_value_new_bool(true)));
}
static FlMethodResponse *hide(WindowManagerPlugin *self)
{
gtk_widget_hide(GTK_WIDGET(get_window(self)));
return FL_METHOD_RESPONSE(fl_method_success_response_new(fl_value_new_bool(true)));
}
static FlMethodResponse *is_visible(WindowManagerPlugin *self)
{
bool is_visible = gtk_widget_is_visible(GTK_WIDGET(get_window(self)));
return FL_METHOD_RESPONSE(fl_method_success_response_new(fl_value_new_bool(is_visible)));
}
static FlMethodResponse *is_maximized(WindowManagerPlugin *self)
{
bool is_maximized = gtk_window_is_maximized(get_window(self));
return FL_METHOD_RESPONSE(fl_method_success_response_new(fl_value_new_bool(is_maximized)));
}
static FlMethodResponse *maximize(WindowManagerPlugin *self)
{
gtk_window_maximize(get_window(self));
return FL_METHOD_RESPONSE(fl_method_success_response_new(fl_value_new_bool(true)));
}
static FlMethodResponse *unmaximize(WindowManagerPlugin *self)
{
gtk_window_unmaximize(get_window(self));
return FL_METHOD_RESPONSE(fl_method_success_response_new(fl_value_new_bool(true)));
}
static FlMethodResponse *is_minimized(WindowManagerPlugin *self)
{
return FL_METHOD_RESPONSE(fl_method_success_response_new(fl_value_new_bool(self->_is_minimized)));
}
static FlMethodResponse *minimize(WindowManagerPlugin *self)
{
gtk_window_iconify(get_window(self));
self->_is_minimized = true;
return FL_METHOD_RESPONSE(fl_method_success_response_new(fl_value_new_bool(true)));
}
static FlMethodResponse *restore(WindowManagerPlugin *self)
{
gtk_window_deiconify(get_window(self));
gtk_window_present(get_window(self));
self->_is_minimized = false;
return FL_METHOD_RESPONSE(fl_method_success_response_new(fl_value_new_bool(true)));
}
static FlMethodResponse *is_full_screen(WindowManagerPlugin *self)
{
bool is_full_screen = (bool)(gdk_window_get_state(get_gdk_window(self)) & GDK_WINDOW_STATE_FULLSCREEN);
g_autoptr(FlValue) result_data = fl_value_new_map();
fl_value_set_string_take(result_data, "isFullScreen", fl_value_new_bool(is_full_screen));
return FL_METHOD_RESPONSE(fl_method_success_response_new(result_data));
}
static FlMethodResponse *set_full_screen(WindowManagerPlugin *self,
FlValue *args)
{
bool is_full_screen = fl_value_get_bool(fl_value_lookup_string(args, "isFullScreen"));
if (is_full_screen)
gtk_window_fullscreen(get_window(self));
else
gtk_window_unfullscreen(get_window(self));
return FL_METHOD_RESPONSE(fl_method_success_response_new(fl_value_new_bool(true)));
}
static FlMethodResponse *get_bounds(WindowManagerPlugin *self)
{
gint width, height;
gtk_window_get_size(get_window(self), &width, &height);
gint x, y;
gtk_window_get_position(get_window(self), &x, &y);
g_autoptr(FlValue) result_data = fl_value_new_map();
fl_value_set_string_take(result_data, "x", fl_value_new_float(x));
fl_value_set_string_take(result_data, "y", fl_value_new_float(y));
fl_value_set_string_take(result_data, "width", fl_value_new_float(width));
fl_value_set_string_take(result_data, "height", fl_value_new_float(height));
return FL_METHOD_RESPONSE(fl_method_success_response_new(result_data));
}
static FlMethodResponse *set_bounds(WindowManagerPlugin *self,
FlValue *args)
{
const float x = fl_value_get_float(fl_value_lookup_string(args, "x"));
const float y = fl_value_get_float(fl_value_lookup_string(args, "y"));
const float width = fl_value_get_float(fl_value_lookup_string(args, "width"));
const float height = fl_value_get_float(fl_value_lookup_string(args, "height"));
gtk_window_resize(get_window(self), static_cast<gint>(width), static_cast<gint>(height));
gtk_window_move(get_window(self), static_cast<gint>(x), static_cast<gint>(y));
return FL_METHOD_RESPONSE(fl_method_success_response_new(fl_value_new_bool(true)));
}
static FlMethodResponse *set_minimum_size(WindowManagerPlugin *self,
FlValue *args)
{
const float width = fl_value_get_float(fl_value_lookup_string(args, "width"));
const float height = fl_value_get_float(fl_value_lookup_string(args, "height"));
if (width >= 0 && height >= 0)
{
self->window_geometry.min_width = static_cast<gint>(width);
self->window_geometry.min_height = static_cast<gint>(height);
}
gdk_window_set_geometry_hints(
get_gdk_window(self),
&self->window_geometry,
static_cast<GdkWindowHints>(GDK_HINT_MIN_SIZE | GDK_HINT_MAX_SIZE));
return FL_METHOD_RESPONSE(fl_method_success_response_new(fl_value_new_bool(true)));
}
static FlMethodResponse *set_maximum_size(WindowManagerPlugin *self,
FlValue *args)
{
const float width = fl_value_get_float(fl_value_lookup_string(args, "width"));
const float height = fl_value_get_float(fl_value_lookup_string(args, "height"));
self->window_geometry.max_width = static_cast<gint>(width);
self->window_geometry.max_height = static_cast<gint>(height);
if (self->window_geometry.max_width < 0)
self->window_geometry.max_width = G_MAXINT;
if (self->window_geometry.max_height < 0)
self->window_geometry.max_height = G_MAXINT;
gdk_window_set_geometry_hints(
get_gdk_window(self),
&self->window_geometry,
static_cast<GdkWindowHints>(GDK_HINT_MIN_SIZE | GDK_HINT_MAX_SIZE));
return FL_METHOD_RESPONSE(fl_method_success_response_new(fl_value_new_bool(true)));
}
static FlMethodResponse *is_always_on_top(WindowManagerPlugin *self)
{
return FL_METHOD_RESPONSE(fl_method_success_response_new(fl_value_new_bool(self->_is_always_on_top)));
}
static FlMethodResponse *set_always_on_top(WindowManagerPlugin *self,
FlValue *args)
{
bool isAlwaysOnTop = fl_value_get_bool(fl_value_lookup_string(args, "isAlwaysOnTop"));
gtk_window_set_keep_above(get_window(self), isAlwaysOnTop);
self->_is_always_on_top = isAlwaysOnTop;
return FL_METHOD_RESPONSE(fl_method_success_response_new(fl_value_new_bool(true)));
}
static FlMethodResponse *terminate(WindowManagerPlugin *self)
{
gtk_window_close(get_window(self));
return FL_METHOD_RESPONSE(fl_method_success_response_new(fl_value_new_bool(true)));
}
// Called when a method call is received from Flutter.
static void window_manager_plugin_handle_method_call(
WindowManagerPlugin *self,
FlMethodCall *method_call)
{
g_autoptr(FlMethodResponse) response = nullptr;
const gchar *method = fl_method_call_get_name(method_call);
FlValue *args = fl_method_call_get_args(method_call);
if (strcmp(method, "focus") == 0)
{
response = focus(self);
}
else if (strcmp(method, "blur") == 0)
{
response = blur(self);
}
else if (strcmp(method, "show") == 0)
{
response = show(self);
}
else if (strcmp(method, "hide") == 0)
{
response = hide(self);
}
else if (strcmp(method, "isVisible") == 0)
{
response = is_visible(self);
}
else if (strcmp(method, "isMaximized") == 0)
{
response = is_maximized(self);
}
else if (strcmp(method, "maximize") == 0)
{
response = maximize(self);
}
else if (strcmp(method, "unmaximize") == 0)
{
response = unmaximize(self);
}
else if (strcmp(method, "isMinimized") == 0)
{
response = is_minimized(self);
}
else if (strcmp(method, "minimize") == 0)
{
response = minimize(self);
}
else if (strcmp(method, "restore") == 0)
{
response = restore(self);
}
else if (strcmp(method, "isFullScreen") == 0)
{
response = is_full_screen(self);
}
else if (strcmp(method, "setFullScreen") == 0)
{
response = set_full_screen(self, args);
}
else if (strcmp(method, "getBounds") == 0)
{
response = get_bounds(self);
}
else if (strcmp(method, "setBounds") == 0)
{
response = set_bounds(self, args);
}
else if (strcmp(method, "setMinimumSize") == 0)
{
response = set_minimum_size(self, args);
}
else if (strcmp(method, "setMaximumSize") == 0)
{
response = set_maximum_size(self, args);
}
else if (strcmp(method, "isAlwaysOnTop") == 0)
{
response = is_always_on_top(self);
}
else if (strcmp(method, "setAlwaysOnTop") == 0)
{
response = set_always_on_top(self, args);
}
else if (strcmp(method, "terminate") == 0)
{
response = terminate(self);
}
else
{
response = FL_METHOD_RESPONSE(fl_method_not_implemented_response_new());
}
fl_method_call_respond(method_call, response, nullptr);
}
static void window_manager_plugin_dispose(GObject *object)
{
G_OBJECT_CLASS(window_manager_plugin_parent_class)->dispose(object);
}
static void window_manager_plugin_class_init(WindowManagerPluginClass *klass)
{
G_OBJECT_CLASS(klass)->dispose = window_manager_plugin_dispose;
}
static void window_manager_plugin_init(WindowManagerPlugin *self) {}
static void method_call_cb(FlMethodChannel *channel, FlMethodCall *method_call,
gpointer user_data)
{
WindowManagerPlugin *plugin = WINDOW_MANAGER_PLUGIN(user_data);
window_manager_plugin_handle_method_call(plugin, method_call);
}
void window_manager_plugin_register_with_registrar(FlPluginRegistrar *registrar)
{
WindowManagerPlugin *plugin = WINDOW_MANAGER_PLUGIN(
g_object_new(window_manager_plugin_get_type(), nullptr));
plugin->registrar = FL_PLUGIN_REGISTRAR(g_object_ref(registrar));
plugin->window_geometry.min_width = -1;
plugin->window_geometry.min_height = -1;
plugin->window_geometry.max_width = G_MAXINT;
plugin->window_geometry.max_height = G_MAXINT;
g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new();
g_autoptr(FlMethodChannel) channel =
fl_method_channel_new(fl_plugin_registrar_get_messenger(registrar),
"window_manager",
FL_METHOD_CODEC(codec));
fl_method_channel_set_method_call_handler(channel, method_call_cb,
g_object_ref(plugin),
g_object_unref);
g_object_unref(plugin);
}
|
5ca6cd0f1e3ba7106252b92ee6c55be826ef7e79
|
120798d0e20c15be0edc5d76264c13149b80d22d
|
/Importer/ScoutPerson.cpp
|
7049df4fdb0d4ea4bab4f0bc444439f97eaa16ca
|
[] |
no_license
|
martinariel/cc_2011
|
b7dbddb5ef303f02d1f8e601117f5f64ffb3ef53
|
05c43cb15ccdebd0a8dec998590e7d886e616ce0
|
refs/heads/master
| 2022-11-13T08:57:26.051643
| 2013-09-13T22:07:04
| 2013-09-13T22:07:04
| 276,488,562
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 493
|
cpp
|
ScoutPerson.cpp
|
//---------------------------------------------------------------------------
#pragma hdrstop
#include "ScoutPerson.h"
//---------------------------------------------------------------------------
ScoutPerson::ScoutPerson ( void )
{
age = code = weight = height = -1;
date = name = place = observations = borndate = telephone = celphone = email = activities = "";
nacionality = languages = "";
hair = size = skin = eyes = agency = "";
}
#pragma package(smart_init)
|
b41da69984cfc0aca6eeafd8007e087af9f6229a
|
17ed4ae8ba3734198ae38665ef702a4b511ec8ab
|
/OALWrapper/sources/OAL_Helper.cpp
|
65c2ad49f29c271a218efda6c42d6dd76ed291ed
|
[
"Zlib"
] |
permissive
|
newyork167/penumbra_vr
|
9b5bbf8d876b2244f0de04fd56b68dde0d69eb60
|
0f97d24b94b75828da8c72cce7fe8581df6b2bb1
|
refs/heads/master
| 2020-03-21T09:42:58.123068
| 2018-06-23T17:19:44
| 2018-06-23T17:19:44
| 138,414,121
| 7
| 3
| null | 2018-06-23T15:51:47
| 2018-06-23T15:51:47
| null |
UTF-8
|
C++
| false
| false
| 4,788
|
cpp
|
OAL_Helper.cpp
|
/*
* Copyright 2007-2010 (C) - Frictional Games
*
* This file is part of OALWrapper
*
* For conditions of distribution and use, see copyright notice in LICENSE
*/
/**
@file OAL_Helper.cpp
@author Luis Rodero
@date 2006-10-02
@version 0.1
Set of Helper functions
*/
#include "OALWrapper/OAL_Helper.h"
#include "OALWrapper/OAL_Device.h"
ALenum geALErrorState = AL_NO_ERROR;
ALCenum geALCErrorState = ALC_NO_ERROR;
///////////////////////////////////////////////////////////
// string GetExtension ( const string& asFilename )
// - Returns the file extension in lowercase
///////////////////////////////////////////////////////////
string GetExtension(const string& asFilename)
{
wstring strTemp = GetExtensionW(String2WString(asFilename));
return WString2String(strTemp);
}
wstring GetExtensionW(const wstring& asFilename)
{
int lNameOffset = (int) asFilename.find_last_of ('.')+1;
wstring strExt = asFilename.substr( lNameOffset, asFilename.size() - lNameOffset );
for ( int i = 0; i < (int) strExt.size(); ++i )
strExt[i] = tolower( strExt[i] );
return strExt;
}
///////////////////////////////////////////////////////////
//
// Wide char to byte char and back again convertion utils
///////////////////////////////////////////////////////////
string WString2String(const wstring& asWString)
{
string sTemp;
size_t needed = wcstombs(NULL,&asWString[0],asWString.length());
sTemp.resize(needed);
wcstombs(&sTemp[0],&asWString[0],asWString.length());
return sTemp;
}
wstring String2WString(const string& asString)
{
wstring wsTemp;
size_t needed = mbstowcs(NULL,&asString[0],asString.length());
wsTemp.resize(needed);
mbstowcs(&wsTemp[0],&asString[0],asString.length());
return wsTemp;
}
///////////////////////////////////////////////////////////
//
//
///////////////////////////////////////////////////////////
bool OAL_GetALError()
{
geALErrorState = alGetError();
return (geALErrorState != AL_NO_ERROR);
}
bool OAL_GetALCError()
{
ALCcontext *ctx = alcGetCurrentContext();
if (ctx==NULL) return false;
geALCErrorState = alcGetError(alcGetContextsDevice(ctx));
return (geALCErrorState != ALC_NO_ERROR);
}
///////////////////////////////////////////////////////////
//
//
///////////////////////////////////////////////////////////
string OAL_GetALErrorString( )
{
switch (geALErrorState)
{
case AL_INVALID_VALUE:
return string("AL_INVALID_VALUE");
case AL_INVALID_ENUM:
return string("AL_INVALID_ENUM");
case AL_INVALID_NAME:
return string("AL_INVALID_NAME");
case AL_INVALID_OPERATION:
return string("AL_INVALID_OPERATION");
case AL_NO_ERROR:
return string("AL_NO_ERROR");
default:
break;
}
return string("AL_NO_ERROR");
}
string OAL_GetALCErrorString( )
{
switch (geALCErrorState)
{
case ALC_NO_ERROR:
return string("ALC_NO_ERROR");
case ALC_INVALID_DEVICE:
return string("ALC_INVALID_DEVICE");
case ALC_INVALID_CONTEXT:
return string("ALC_INVALID_CONTEXT");
case ALC_INVALID_ENUM:
return string("ALC_INVALID_ENUM");
case ALC_INVALID_VALUE:
return string("ALC_INVALID_VALUE");
case ALC_OUT_OF_MEMORY:
return string("ALC_OUT_OF_MEMORY");
default:
break;
}
return string("ALC_NO_ERROR");
}
///////////////////////////////////////////////////////////
//
//
///////////////////////////////////////////////////////////
void ClearALErrors(const string& asFunction)
{
ALenum eStatus = alGetError();
//if ( eStatus != AL_NO_ERROR )
// OAL_Log(2, "%s ClearALErrors raised %d\n", asFunction.c_str(), eStatus );
}
///////////////////////////////////////////////////////////
//
//
///////////////////////////////////////////////////////////
bool CheckALErrors(const string& asFunc1, const string& asFunc2)
{
bool bErrorOccurred = OAL_GetALError();
//if ( (bErrorOccured) && (cOAL_Device::IsLogEnabled()))
//OAL_Log(2,"%s: %s raised %s\n", asFunc1.c_str(), asFunc2.c_str(), OAL_GetALErrorString().c_str() );
return bErrorOccurred;
}
///////////////////////////////////////////////////////////
//
//
///////////////////////////////////////////////////////////
void ClearALCErrors(const string& asFunction)
{
ALCcontext *ctx = alcGetCurrentContext();
if (ctx == NULL) return;
ALCenum eStatus = alcGetError(alcGetContextsDevice(ctx));
//if ( eStatus != ALC_NO_ERROR )
//s OAL_Log(2, "%s ClearALCErrors raised %d\n", asFunction.c_str(), eStatus );
}
///////////////////////////////////////////////////////////
//
//
///////////////////////////////////////////////////////////
bool CheckALCErrors(const string& asFunction)
{
bool bErrorOccurred = OAL_GetALCError();
//if ( (bErrorOccured) && (gbLogSounds) )
// OAL_Log(2,"%s CheckALCErrors raised %s\n", asFunction.c_str(), OAL_GetALCErrorString().c_str() );
return bErrorOccurred;
}
|
22b7dda09ebf4cdda0cb21d4b206abbe40a220c6
|
91303af9283852434f1e1a99abe33559b9ccce61
|
/Task_3.h
|
f80498a6775fcc30d7931807c209b4110de71b50
|
[] |
no_license
|
ee3579-lab-3-group-x/LAB-3
|
6a18374744f20f167e50f946ff4165c2e4311492
|
b10a95336cd982743810c853c3b74c60c643fd68
|
refs/heads/master
| 2020-04-28T22:38:32.722672
| 2019-03-25T20:48:45
| 2019-03-25T20:48:45
| 175,625,201
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 16,366
|
h
|
Task_3.h
|
//Included Libraries
#ifndef Task_3_h
#define Task_3_h
#include "IntervalCheckTimer.h"
#include "InterruptBasedSpeedMeasure.h"
#include "DCmotor.h"
#include "SystemControl_Unit.h"
class task_3{
public:
//Classes and Objects
IntervalCheckTimer timer; //Object "timer" declared from class "IntervalCheckTimer"
InterruptSpeedMeasure rotation_counter_L, rotation_counter_R; //Objects "rotation_counter L&R" declared from class "InterruptSpeedMeasure"
SystemControler MotorLeft, MotorRight; //Objects "Motor L&R" declared from class "SystemControler"
HBridgeDCmotor hbdcmotor_R, hbdcmotor_L; //Objects "hbdcmotor L&R" declared from class "HBridgeDCmotor"
basic_speed_PID motor_L, motor_R;
//System Constants
const int Wc = 100; //Width of car (mm)
const int wheel_diameter = 57; //Diameter of wheel (mm)
//Global Variables
double RPM_R;
double RPM_L;
double PWM_R;
double PWM_L;
//Setup Functions
void setup_Hardware(int motorpin_L,int directionpin_L,int motorpin_R,int directionpin_R)
{
MotorLeft.PID_SetupHardware(motorpin_L, directionpin_L, int_0); //Initialise Direction and PWM Pins for Left Motor
MotorRight.PID_SetupHardware(motorpin_R, directionpin_R, int_1); //Initialise Direction and PWM Pins for Left Motor
hbdcmotor_R.setup_HBridgeDCmotor(motorpin_R,directionpin_R); //Initialise Direction and PWM Pins for Left Motor
hbdcmotor_L.setup_HBridgeDCmotor(motorpin_L,directionpin_L); //Initialise Direction and PWM Pins for Right Motor
}
void setup_speed_measurement(const int inp_interr_on_circle) //Initialise Hall Effect Iteupt Readings
{
rotation_counter_L.setupSpeedMeasure(int_0,inp_interr_on_circle); //Initialise Left Speed Counter
rotation_counter_R.setupSpeedMeasure(int_1,inp_interr_on_circle); //Initialise Right Speed counter
}
void setup_PID(double Kp_R,double Kp_L,double Ki,double Kd,double lowerbound,double upperbound,const int control_interval_ms) //Function to intialise PID Controller
{
MotorLeft.setTunings(Kp_L,Ki,Kd); //Initialise Gain Parameters L
MotorRight.setTunings(Kp_R,Ki,Kd); //Initialise Gain Parameters R
MotorLeft.PID_SetupControl(lowerbound, upperbound, control_interval_ms); //Set PWM Limits and Control Interval
MotorRight.PID_SetupControl(lowerbound, upperbound, control_interval_ms); //Set PWM Limits and Control Interval
}
void Setup_Hardware_PID(const int motorpin_L,const int directionpin_L,const int motorpin_R,const int directionpin_R,const int inp_interr_on_circle,double Kp_L,double Kp_R,double Ki,double Kd,double lowerbound,double upperbound,const int control_interval_ms) //Used Becuase I'm too dumb for constructors :/
{
setup_Hardware(motorpin_L,directionpin_L, motorpin_R,directionpin_R); //Call Function to setup Hardware
setup_speed_measurement(inp_interr_on_circle); //Call Function to initilase spped measurement
setup_PID(Kp_R,Kp_L,Ki,Kd,lowerbound,upperbound,control_interval_ms); //Call Function to setup PID Controller
}
//Calculation Functions
double distance_traveled_L() //Function to calculate distance travelled by left wheel
{
double interupt_count = rotation_counter_L.GetkDistanceCount(); //Count and Store Number of Interupts
double distance = (interupt_count/49)*((3.1415926539)*wheel_diameter); //Calculate and Store Distance (mm)
return distance; //Return to allow for external acess
}
double distance_traveled_R() //Function to calculate distance travelled by left wheel
{
double interupt_count = rotation_counter_R.GetkDistanceCount(); //Count and Store Number of Rotations
double distance = (interupt_count/49)*((3.1415926539)*wheel_diameter); //Calculate and Store Distance (mm)
return distance; //Return to allow for external acess
}
//Opperational Functions
void delta_speed_fun(int inp_speed, float delta_percent, int time_durr, bool add, int itterative_counter, int RPM_LIMIT)
{
float new_output_speed; //Blank Local Variable
timer.setInterCheck(time_durr); //Initialised Check Timer
if(timer.isMinChekTimeElapsed()) //Boolean Timer Check
{
if (delta_percent >= 100) //conditional dissalows invalid selection i.e 110%
{
new_output_speed = inp_speed; //Return Input speed as safety measure
}
if(add == true){ //If add flag is set to true...
new_output_speed = inp_speed + (inp_speed*(delta_percent/100)); //Add Percentage
return new_output_speed; //Return Calculated Value
}else if(add==false){ //If add flag is set to false
new_output_speed = inp_speed - (inp_speed*(delta_percent/100)); //Subtract Percentage
}
if(timer.isMinChekTimeElapsedAndUpdate()) //If check Timer has elapsed...
{
RPM_R=rotation_counter_R.getRPMandUpdate(); //Get Speed of Right Motor in RPM
RPM_L=rotation_counter_L.getRPMandUpdate(); //Get Speed of Left Motor in RPM
}
for (int i = 0; i < itterative_counter; i++)
if(RPM_LIMIT>=RPM_L||RPM_LIMIT>=RPM_R)
{
hbdcmotor_R.stop(); //Stop Right Motor
hbdcmotor_L.stop(); //Stop Left Motor
}else{
double PWM_L=motor_L.ComputePID_output(new_output_speed,RPM_L); //Compute Required PWM output Right
hbdcmotor_L. set_jumpstart(true); //Jumpstart Left Motor
hbdcmotor_L.start(); //Start Left Motor
hbdcmotor_L.setSpeedPWM(PWM_L); //Set Speed in PWM
double PWM_R=motor_R.ComputePID_output(new_output_speed,RPM_R); //Compute Required PWM output Left
hbdcmotor_R. set_jumpstart(true); //Jumpstart Right Motor
hbdcmotor_R.start(); //Start Right Motor
hbdcmotor_R.setSpeedPWM(PWM_R); //Set Speed in PWM
i++;
}
}
}
void drive_straight(int inp_RPM, int distance)
{
hbdcmotor_R.stop(); //Stop Right Motor
hbdcmotor_L.stop(); //Stop Left Motor
if(timer.isMinChekTimeElapsedAndUpdate())
{
RPM_L=rotation_counter_L.getRPMandUpdate(); //Get Speed of Left Motor in RPM
RPM_R=rotation_counter_R.getRPMandUpdate(); //Get Speed of Right Motor in RPM
}
double distance_R = distance_traveled_R(); //Calculate and Store Distance traveled
double distance_L = distance_traveled_L(); //Calculate and Store Distance traveled
if ((distance_R <= (double)distance)||(distance_L <= (double)distance))
{
PWM_R=motor_R.ComputePID_output(inp_RPM,RPM_R); //Compute Required PWM output
PWM_L=motor_L.ComputePID_output(inp_RPM,RPM_L); //Compute Required PWM output
hbdcmotor_R. set_jumpstart(true); //Jumpstart Right Motor
hbdcmotor_L. set_jumpstart(true); //Jumpstart Left Motor
hbdcmotor_R.start(); //Start Right Motor
hbdcmotor_L.start(); //Start Left Motor
hbdcmotor_R.setSpeedPWM(PWM_R); //Set Speed in PWM
hbdcmotor_L.setSpeedPWM(PWM_L); //Set Speed in PWM
}else{
hbdcmotor_R.stop(); //Stop Right Motor
hbdcmotor_L.stop(); //Stop Left Motor
}
}
void rotate_clockwise(int radius, int inp_RPM_R, int itterations)
{
hbdcmotor_R.stop(); //Stop Right Motor
hbdcmotor_L.stop(); //Stop Left Motor
double circumfrance = 2*(3.1415926539)*(double)radius; //Calculate Circumfrance
if(timer.isMinChekTimeElapsedAndUpdate())
{
RPM_L=rotation_counter_L.getRPMandUpdate(); //Get Speed of Left Motor in RPM
RPM_R=rotation_counter_R.getRPMandUpdate(); //Get Speed of Right Motor in RPM
}
double distance = distance_traveled_L(); //Calculate and Store Distance traveled
if (distance <= circumfrance*(double)itterations){ //If distance travelled is >= desired path
double Target_RPM_L = (((double)Wc+(double)radius)/(double)radius)*(double)inp_RPM_R; //Calculate Left Wheel Velocity
PWM_R=motor_R.ComputePID_output(inp_RPM_R,RPM_R); //Compute Required PWM output
PWM_L=motor_L.ComputePID_output(Target_RPM_L,RPM_L); //Compute Required PWM output
hbdcmotor_R. set_jumpstart(true); //Jumpstart Right Motor
hbdcmotor_L. set_jumpstart(true); //Jumpstart Left Motor
hbdcmotor_R.start(); //Start Right Motor
hbdcmotor_L.start(); //Start Left Motor
hbdcmotor_R.setSpeedPWM(PWM_R); //Set Speed in PWM
hbdcmotor_L.setSpeedPWM(PWM_L); //Set Speed in PWM
}else{
hbdcmotor_R.stop(); //Stop Right Motor
hbdcmotor_L.stop(); //Stop Left Motor
}
}
void rotate_counter_clockwise(int radius, int inp_RPM_L, int itterations)
{
hbdcmotor_R.stop(); //Stop Right Motor
hbdcmotor_L.stop(); //Stop Left Motor
double circumfrance = 2*(3.1415926539)*(double)radius; //Calculate Circumfrance
if(timer.isMinChekTimeElapsedAndUpdate())
{
RPM_L=rotation_counter_L.getRPMandUpdate(); //Get Speed of Left Motor in RPM
RPM_R=rotation_counter_R.getRPMandUpdate(); //Get Speed of Right Motor in RPM
}
double distance = distance_traveled_R(); //Calculate and Store Distance traveled
if (distance <= circumfrance*itterations){ //If distance travelled is >= desired path
double Target_RPM_R = (((double)Wc+(double)radius)/(double)radius)*(double)inp_RPM_L; //Calculate Left Wheel Velocity
PWM_L=motor_L.ComputePID_output(inp_RPM_L,RPM_L); //Compute Required PWM output
PWM_R=motor_R.ComputePID_output(Target_RPM_R,RPM_R); //Compute Required PWM output
hbdcmotor_R. set_jumpstart(true); //Jumpstart Right Motor
hbdcmotor_L. set_jumpstart(true); //Jumpstart Left Motor
hbdcmotor_R.start(); //Start Right Motor
hbdcmotor_L.start(); //Start Left Motor
hbdcmotor_R.setSpeedPWM(PWM_R); //Set Speed in PWM
hbdcmotor_L.setSpeedPWM(PWM_L); //Set Speed in PWM
}else{
hbdcmotor_R.stop(); //Stop Right Motor
hbdcmotor_L.stop(); //Stop Left Motor
}
}
void turn_L(int inp_RPM_L,int angle) //Function to turn 90 degrees to the left
{
hbdcmotor_R.stop(); //Stop Right Motor
hbdcmotor_L.stop(); //Stop Left Motor
double turn_distance = (2*(3.1415926539)*((double)Wc))*((double)angle/360); //Calculate Distance
double distance = distance_traveled_L(); //Calculate and Store Distance traveled
if(timer.isMinChekTimeElapsedAndUpdate()) //If check timer has expired...
{
RPM_L=rotation_counter_L.getRPMandUpdate(); //Get Speed of Left Motor in RPM
}
if (distance <= turn_distance) //If distance travelled is >= desired path
{
double PWM_L=motor_L.ComputePID_output(inp_RPM_L,RPM_L); //Compute Required PWM output
hbdcmotor_L. set_jumpstart(true); //Jumpstart Left Motor
hbdcmotor_L.start(); //Start Left Motor
hbdcmotor_L.setSpeedPWM(PWM_R); //Set Speed in PWM
}else if (distance > turn_distance){
hbdcmotor_R.stop(); //Stop Right Motor
hbdcmotor_L.stop(); //Stop Left Motor
}
}
void turn_R(int inp_RPM_R,int angle) //Function to turn 90 degrees to the right
{
hbdcmotor_R.stop(); //Stop Right Motor
hbdcmotor_L.stop(); //Stop Left Motor
double turn_distance = (2*(3.1415926539)*((double)Wc))*((double)angle/360); //Calculate Distance
double distance = distance_traveled_R(); //Calculate and Store Distance traveled
if(timer.isMinChekTimeElapsedAndUpdate()) //If check timer has expired...
{
RPM_R=rotation_counter_R.getRPMandUpdate(); //Get Speed of Left Motor in RPM
}
if (distance <= turn_distance) //If distance travelled is >= desired path
{
double PWM_R=motor_R.ComputePID_output(inp_RPM_R,RPM_R); //Compute Required PWM output
hbdcmotor_R. set_jumpstart(true); //Jumpstart Left Motor
hbdcmotor_R.start(); //Start Left Motor
hbdcmotor_R.setSpeedPWM(PWM_R); //Set Speed in PWM
}else if (distance > turn_distance){
hbdcmotor_R.stop(); //Stop Right Motor
hbdcmotor_L.stop(); //Stop Left Motor
}
}
void task_4_fun(int radius, int inp_RPM, int itterations, int distance,int inp_turning_RPM)
{
int total_length = (((2*(distance))+(2*(3.1415926539)*radius))*itterations);
double distance_R = distance_traveled_R(); //Calculate and Store Distance traveled
double distance_L = distance_traveled_L(); //Calculate and Store Distance traveled
Serial.print(distance_L);
if ((distance_R <= total_length)||(distance_L <= total_length))
{
drive_straight(inp_RPM,distance);
rotate_clockwise(radius, inp_turning_RPM, 1);
drive_straight(inp_RPM,distance);
rotate_clockwise(radius, inp_turning_RPM, 1);
}else{
hbdcmotor_R.stop(); //Stop Right Motor
hbdcmotor_L.stop(); //Stop Left Motor
}
}
};
#endif //End Class Decleration //End Class Decleration
|
56f0e240de8bee871df787921fcb7f4bdeb38a61
|
8211a82bae03e70068e24922788b6d747325f2e5
|
/02/1.cpp
|
50626578d32c06472391bb444163b249c126fa73
|
[] |
no_license
|
hallmluke/AdventOfCode2k19
|
a5a1a9718e8494a9ebfba7237e55216a7cd4af8b
|
f80355180cf2ac0752fa6df7b301bee92a8e09d5
|
refs/heads/master
| 2020-09-22T14:43:49.539143
| 2020-05-31T21:09:52
| 2020-05-31T21:09:52
| 225,244,801
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,761
|
cpp
|
1.cpp
|
#include <cmath>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
int getIntCodeOutput(std::vector<int> input) {
int i = 0;
std::vector<int> parsedCsv = input;
while(i < parsedCsv.size()){
if(parsedCsv[i] == 1){
parsedCsv[parsedCsv[i+3]] = parsedCsv[parsedCsv[i+1]] + parsedCsv[parsedCsv[i+2]];
i += 4;
} else if (parsedCsv[i] == 2){
parsedCsv[parsedCsv[i+3]] = parsedCsv[parsedCsv[i+1]] * parsedCsv[parsedCsv[i+2]];
i += 4;
} else if (parsedCsv[i] == 99){
break;
} else {
std::cout << "Something went wrong!" << std::endl;
break;
}
}
return parsedCsv[0];
}
int main() {
std::ifstream file("input.txt");
std::string str;
std::vector<int> parsedCsv;
while(std::getline(file,str)) {
std::stringstream lineStream(str);
std::string cell;
while(std::getline(lineStream,cell,',')) {
std::cout << cell << std::endl;
std::cout << std::stoi(cell) << std::endl;
int cellVal = std::stoi(cell);
parsedCsv.push_back(cellVal);
}
}
for(int i=0; i<100; i++) {
int result = 0;
for(int j=0; j<100; j++) {
std::vector<int> inputTry = parsedCsv;
inputTry[1] = i;
inputTry[2] = j;
result = getIntCodeOutput(inputTry);
if(result == 19690720) {
std::cout << "Success! " << i << " " << j << std::endl;
break;
}
}
if(result == 19690720) {
break;
}
}
std::cout << parsedCsv[0] << std::endl;
}
|
d5e07366428f457811394e1870e67f0aa13b0913
|
048c562d2a124a10fc41ce4b38f9f0c42248f886
|
/StandingWave_Particle/src/StandingWave.cpp
|
dd1cd6fb03c763f5dead99932d924c311d33597b
|
[] |
no_license
|
ConnorFk/FlyOnTheWall-2
|
f1be03dce93ea1f93d871cff03fc440b07b96401
|
d35805c84fb6e7b824ac0ae9039e425db0079057
|
refs/heads/master
| 2021-01-10T18:44:14.127756
| 2013-12-16T11:16:07
| 2013-12-16T11:16:07
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,754
|
cpp
|
StandingWave.cpp
|
#include "testApp.h"
//--------------------------------------------------------------
void testApp::Parameter_Set(ofVec2f a, ofVec2f b){
//two points
NumPoints = 40; //Number of Points on the string
//set points
for (int i = 0; i < NumPoints; i++){
ofVec2f pos = ofVec2f((b-a).x/NumPoints*(i),(b-a).y/NumPoints*(i));
pointsOnString.push_back(pos);
}
//parameter settings
//A = 70;
}
//--------------------------------------------------------------
void testApp::Vibration_Calc(ofVec2f a, ofVec2f b, ofVec2f c){
ofPushMatrix();
ofTranslate(a); //transrate x,y-coordinate to point a
decay *= 0.97; //decay magnitude
if(decay < 0.01){
decay = 0;
}
ofVec2f q=ofVec2f(1,0); //normal vector
float angle=q.angle(b-a); //get angle of q and (b-a)
ofRotateZ(angle); //rotate x,y-coordinate(around z-axis)
float L = abs((b-a).x/cos(angle/180*PI)); // avoid square root
float Lsq = L*L;
for (int i = 1; i < 41; i++){
pointsOnString[i].x = L/NumPoints*i;
pointsOnString[i].y = A*sin(n*PI/L*i*L/NumPoints + sigma)*cos(TWO_PI*20/2/L*ofGetElapsedTimef()*250) * decay;
}
if (minimum_distance_Squared(a, b, c) < 15*15){ //squared of minimum distance
if ((c-a).dot(c-a) < Lsq/(3*3)) { //when collision point is near to a
n=3;
A = 40;
decay = 1;
sigma = 0;
// sigma = PI/2;
}
if ((c-a).dot(c-a) > Lsq/(3*3) && (c-a).dot(c-a) < Lsq*4/9) { //when collision point is in the middle of a and b
n=1;
A = 70;
decay = 1;
sigma = 0;
}
if( ((c-a).dot(c-a) > Lsq*4/9)){ //when collision point is near to b
n=2;
A= 40;
decay=1;
// sigma = PI/2;
sigma = 0;
}
collision[int(a.y)] = true;
}else{
collision[int(a.y)] = false;
}
ofPopMatrix();
}
//--------------------------------------------------------------
void testApp::Vibration_Draw(ofVec2f a, ofVec2f b, ofVec2f c){
ofSetColor(10, 20, 80);
ofCircle(a, 15+10*sin(ofGetElapsedTimef())*sin(ofGetElapsedTimef()*0.9));
ofCircle(b, 15+10*sin(ofGetElapsedTimef())*sin(ofGetElapsedTimef()*0.9));
ofCircle(c, 20);
ofPushMatrix();
ofTranslate(a);
ofVec2f q=ofVec2f(1,0);
float angle=q.angle(b-a);
ofRotateZ(angle);
for (int i = 1; i < 41; i++){
//pointsOnString[NumPoints] = ofVec2f(L, 0);
ofCircle(pointsOnString[i], 2);
ofCircle(pointsOnString[0], 5);
ofCircle(pointsOnString[40], 5);
}
ofPopMatrix();
}
//--------------------------------------------------------------
float testApp::minimum_distance_Squared(ofVec2f v, ofVec2f w, ofVec2f p){
// Return minimum distance between line segment vw and point p
const float l2 = ofDistSquared(v.x, v.y, w.x, w.y); // i.e. |w-v|^2 - avoid a sqrt
if (l2 == 0.0) return ofDistSquared(p.x, p.y, v.x, v.y); // v == w case
// Consider the line extending the segment, parameterized as v + t (w - v).
// We find projection of point p onto the line.
// It falls where t = [(p-v) . (w-v)] / |w-v|^2
const float t =(p - v).dot(w - v) / l2;
if (t < 0.0) return ofDistSquared(p.x, p.y, v.x, v.y); // Beyond the 'v' end of the segment
else if (t > 1.0) return ofDistSquared(p.x, p.y, w.x, w.y); // Beyond the 'w' end of the segment
const ofVec2f projection = v + t * (w - v); // Projection falls on the segment
return ofDistSquared(p.x, p.y, projection.x, projection.y);
}
|
cad8c5dd79ae2761fd38d3c37f30d141e49ec8d7
|
fead2d2ea15e43f058ce5b76ccd7a42786a66ea9
|
/7/_Button.cpp
|
3613d5163ceac94c19e0403698039ea1ce845be0
|
[] |
no_license
|
jsg2021/Simply-Transparent
|
adba084caba5a6f4a0f7f95a7a3d29c93de54810
|
bb875a8010d5c01e76a64e57dd3fe807d8f0fec0
|
refs/heads/master
| 2021-01-02T08:56:53.867936
| 2012-01-16T20:07:06
| 2012-01-16T20:07:06
| 2,200,338
| 3
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,287
|
cpp
|
_Button.cpp
|
///////////////////////////////////////////////////////////////////////////////
//// _Button.cpp
//
#include "stdafx.h"
#include "simplytransparent.h"
#include "_Button.h"
///////////////////////////////////////////////////////////////////////////////
///// Button Box Proc
//
LRESULT CALLBACK ButtonWndProc( HWND hWnd, UINT message,
WPARAM wParam, LPARAM lParam)
{
PAINTSTRUCT ps;
HDC hdc,hdc2;
HBITMAP bm;
HGDIOBJ obj;
RECT rt;
switch ( message )
{
case WM_INITDIALOG:
InvalidateRect( hWnd, 0, true );
return true;
case WM_LBUTTONUP:
ShowWindow( GetDeskListCtlWnd( ), SW_SHOW );
__AnimateWindow( hWnd, 200, AW_HIDE|AW_BLEND );
ShowWindow( hWnd, SW_HIDE );
return true;
case WM_PAINT:
hdc = BeginPaint(hWnd, &ps);
GetClientRect(hWnd, &rt);
bm = LoadBitmap( GetMyInstanceHandle( ),
MAKEINTRESOURCE( IDB_BUTTON ) );
hdc2 = CreateCompatibleDC(hdc);
obj = SelectObject( hdc2, bm );
BitBlt( hdc, 0, 0, 20, 18, hdc2, 0, 0, SRCCOPY);
//FillRect( hdc, &rt, CreateSolidBrush( 0x00ff00ff ) );
SelectObject( hdc2, obj );
DeleteDC( hdc2 );
DeleteObject( bm );
EndPaint(hWnd, &ps);
}
return DefWindowProc( hWnd, message, wParam, lParam );
}
|
00c8680212f135888183ff42800f99ba9ae86078
|
fa1ca6e79951c622c8c6194af4c2aa982c332d04
|
/ArduinoTransceiver/ArduinoTransceiver.ino
|
1818b8180f09a99ab69b7252082dfbf0214b82ec
|
[] |
no_license
|
eyeboah369/ArduinoController
|
312c0b96f507f2af213f5c28020604dc9dafe063
|
b37b0d027405e65a4d4006db32f24e363def14e3
|
refs/heads/master
| 2020-03-29T16:20:45.522828
| 2018-09-24T14:26:02
| 2018-09-24T14:26:02
| 150,109,892
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 817
|
ino
|
ArduinoTransceiver.ino
|
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
const int SW_pin = 2; // digital pin connected to switch output
const int VRx_pin = 0; // analog pin connected to X output
const int VRy_pin = 1; // analog pin connected to Y output
const byte news[0] = "00001";
RF24 radio(9,10);
void setup() {
radio.begin();
radio.openWritingPipe(news);
radio.setPALevel(RF24_PA_MIN);
radio.stopListening();
pinMode(SW_pin, INPUT);
digitalWrite(SW_pin, HIGH);
}
void loop() {
String hey = "Hello World!";
Serial.print("Switch: ");
Serial.print(digitalRead(SW_pin));
Serial.print("\n");
Serial.print("X-axis: ");
Serial.print(analogRead(VRx_pin));
Serial.print("\n");
Serial.print("Y-axis: ");
Serial.println(analogRead(VRy_pin));
Serial.print("\n\n");
delay(500);
}
|
a917865cc7e6e31b0130cdb8ec2e8be6a30ce9ee
|
84a6f59595e3ec05797c9e73909fbba29a88d20f
|
/Adminpan.h
|
cf5ef43c8b10d09ad20a4c07ade0d3390ec09b61
|
[] |
no_license
|
tahmid108/Electronics-Company-C-project
|
3fc97f636715ee93966e4151429e4c6d7b1ba247
|
0b5795e06afe0526643f471b0a3dd80674dda27c
|
refs/heads/master
| 2023-03-15T16:47:41.948273
| 2021-03-19T17:27:03
| 2021-03-19T17:27:03
| 349,502,368
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 524
|
h
|
Adminpan.h
|
#ifndef ADMINPAN_H
#define ADMINPAN_H
#include<iostream>
using namespace std;
//#include "Profit.cpp"
#include"Mobile.h"
#include"Television.h"
#include"Customer.h"
class Adminpan : public Mobile,public Television,public Customer
{
public:
Adminpan(string pass);
~Adminpan();
Adminpan(Mobile &m);
Adminpan(Television &t);
Adminpan(Customer &c);
friend istream& operator>>(istream& input,Adminpan &a);
friend ostream& operator<<(ostream& output,Adminpan &a);
protected:
string aname;
int id;
};
#endif
|
7a1095941f88e6dfceca3db962d2cb9c80848514
|
6b40e9dccf2edc767c44df3acd9b626fcd586b4d
|
/NT/admin/snapin/dnsmgr/zoneui.cpp
|
500cca6032b88203470b1aa3bd70bd23a48e44e4
|
[] |
no_license
|
jjzhang166/WinNT5_src_20201004
|
712894fcf94fb82c49e5cd09d719da00740e0436
|
b2db264153b80fbb91ef5fc9f57b387e223dbfc2
|
refs/heads/Win2K3
| 2023-08-12T01:31:59.670176
| 2021-10-14T15:14:37
| 2021-10-14T15:14:37
| 586,134,273
| 1
| 0
| null | 2023-01-07T03:47:45
| 2023-01-07T03:47:44
| null |
UTF-8
|
C++
| false
| false
| 99,634
|
cpp
|
zoneui.cpp
|
//+-------------------------------------------------------------------------
//
// Microsoft Windows
//
// Copyright (C) Microsoft Corporation, 1998 - 1999
//
// File: zoneui.cpp
//
//--------------------------------------------------------------------------
#include "preDNSsn.h"
#include <SnapBase.h>
#include "resource.h"
#include "dnsutil.h"
#include "DNSSnap.h"
#include "snapdata.h"
#include "server.h"
#include "domain.h"
#include "record.h"
#include "zone.h"
#include "ZoneUI.h"
#include "browser.h"
#ifdef DEBUG_ALLOCATOR
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
#endif
#ifdef USE_NDNC
///////////////////////////////////////////////////////////////////////////////
// CDNSZoneChangeReplicationScopeDialog
class CDNSZoneChangeReplicationScopeDialog : public CHelpDialog
{
public:
CDNSZoneChangeReplicationScopeDialog(CPropertyPageHolderBase* pHolder,
ReplicationType replType,
PCWSTR pszCustomScope,
DWORD dwServerVersion);
ReplicationType m_newReplType; // IN/OUT
CString m_szCustomScope; // IN/OUT
protected:
virtual BOOL OnInitDialog();
virtual void OnOK();
virtual void OnCancel();
afx_msg void OnRadioChange();
afx_msg void OnCustomComboSelChange();
DECLARE_MESSAGE_MAP()
private:
void SyncRadioButtons();
ReplicationType m_replType;
BOOL m_dwServerVersion;
CPropertyPageHolderBase* m_pHolder;
};
CDNSZoneChangeReplicationScopeDialog::CDNSZoneChangeReplicationScopeDialog(CPropertyPageHolderBase* pHolder,
ReplicationType replType,
PCWSTR pszCustomScope,
DWORD dwServerVersion)
: m_pHolder(pHolder),
m_replType(replType),
m_newReplType(replType),
m_szCustomScope(pszCustomScope),
m_dwServerVersion(dwServerVersion),
CHelpDialog(IDD_ZONE_GENERAL_CHANGE_REPLICATION, pHolder->GetComponentData())
{
ASSERT(pHolder != NULL);
}
BEGIN_MESSAGE_MAP(CDNSZoneChangeReplicationScopeDialog, CHelpDialog)
ON_BN_CLICKED(IDC_FOREST_RADIO, OnRadioChange)
ON_BN_CLICKED(IDC_DOMAIN_RADIO, OnRadioChange)
ON_BN_CLICKED(IDC_DOMAIN_DC_RADIO, OnRadioChange)
ON_BN_CLICKED(IDC_CUSTOM_RADIO, OnRadioChange)
ON_CBN_EDITCHANGE(IDC_CUSTOM_COMBO, OnRadioChange)
ON_CBN_SELCHANGE(IDC_CUSTOM_COMBO, OnCustomComboSelChange)
END_MESSAGE_MAP()
void CDNSZoneChangeReplicationScopeDialog::OnRadioChange()
{
if (SendDlgItemMessage(IDC_FOREST_RADIO, BM_GETCHECK, 0, 0) == BST_CHECKED)
{
m_newReplType = forest;
}
else if (SendDlgItemMessage(IDC_DOMAIN_RADIO, BM_GETCHECK, 0, 0) == BST_CHECKED)
{
m_newReplType = domain;
}
else if (SendDlgItemMessage(IDC_DOMAIN_DC_RADIO, BM_GETCHECK, 0, 0) == BST_CHECKED)
{
m_newReplType = w2k;
}
else if (SendDlgItemMessage(IDC_CUSTOM_RADIO, BM_GETCHECK, 0, 0) == BST_CHECKED)
{
m_newReplType = custom;
LRESULT iSel = SendDlgItemMessage(IDC_CUSTOM_COMBO, CB_GETCURSEL, 0, 0);
if (CB_ERR != iSel)
{
CString szTemp;
CComboBox* pComboBox = reinterpret_cast<CComboBox*>(GetDlgItem(IDC_CUSTOM_COMBO));
ASSERT(pComboBox);
pComboBox->GetLBText(static_cast<int>(iSel), m_szCustomScope);
}
}
else
{
// one of the radio buttons must be selected
ASSERT(FALSE);
}
SyncRadioButtons();
}
void CDNSZoneChangeReplicationScopeDialog::SyncRadioButtons()
{
switch (m_newReplType)
{
case forest:
SendDlgItemMessage(IDC_FOREST_RADIO, BM_SETCHECK, (WPARAM)BST_CHECKED, 0);
SendDlgItemMessage(IDC_DOMAIN_RADIO, BM_SETCHECK, (WPARAM)BST_UNCHECKED, 0);
SendDlgItemMessage(IDC_DOMAIN_DC_RADIO, BM_SETCHECK, (WPARAM)BST_UNCHECKED, 0);
SendDlgItemMessage(IDC_CUSTOM_RADIO, BM_SETCHECK, (WPARAM)BST_UNCHECKED, 0);
GetDlgItem(IDC_CUSTOM_COMBO)->EnableWindow(FALSE);
GetDlgItem(IDC_CUSTOM_STATIC)->EnableWindow(FALSE);
break;
case domain:
SendDlgItemMessage(IDC_DOMAIN_RADIO, BM_SETCHECK, (WPARAM)BST_CHECKED, 0);
SendDlgItemMessage(IDC_FOREST_RADIO, BM_SETCHECK, (WPARAM)BST_UNCHECKED, 0);
SendDlgItemMessage(IDC_DOMAIN_DC_RADIO, BM_SETCHECK, (WPARAM)BST_UNCHECKED, 0);
SendDlgItemMessage(IDC_CUSTOM_RADIO, BM_SETCHECK, (WPARAM)BST_UNCHECKED, 0);
GetDlgItem(IDC_CUSTOM_COMBO)->EnableWindow(FALSE);
GetDlgItem(IDC_CUSTOM_STATIC)->EnableWindow(FALSE);
break;
case w2k:
SendDlgItemMessage(IDC_DOMAIN_DC_RADIO, BM_SETCHECK, (WPARAM)BST_CHECKED, 0);
SendDlgItemMessage(IDC_FOREST_RADIO, BM_SETCHECK, (WPARAM)BST_UNCHECKED, 0);
SendDlgItemMessage(IDC_DOMAIN_RADIO, BM_SETCHECK, (WPARAM)BST_UNCHECKED, 0);
SendDlgItemMessage(IDC_CUSTOM_RADIO, BM_SETCHECK, (WPARAM)BST_UNCHECKED, 0);
GetDlgItem(IDC_CUSTOM_COMBO)->EnableWindow(FALSE);
GetDlgItem(IDC_CUSTOM_STATIC)->EnableWindow(FALSE);
break;
case custom:
SendDlgItemMessage(IDC_CUSTOM_RADIO, BM_SETCHECK, (WPARAM)BST_CHECKED, 0);
SendDlgItemMessage(IDC_FOREST_RADIO, BM_SETCHECK, (WPARAM)BST_UNCHECKED, 0);
SendDlgItemMessage(IDC_DOMAIN_RADIO, BM_SETCHECK, (WPARAM)BST_UNCHECKED, 0);
SendDlgItemMessage(IDC_DOMAIN_DC_RADIO, BM_SETCHECK, (WPARAM)BST_UNCHECKED, 0);
GetDlgItem(IDC_CUSTOM_COMBO)->EnableWindow(TRUE);
GetDlgItem(IDC_CUSTOM_STATIC)->EnableWindow(TRUE);
break;
default:
SendDlgItemMessage(IDC_DOMAIN_RADIO, BM_SETCHECK, (WPARAM)BST_CHECKED, 0);
SendDlgItemMessage(IDC_FOREST_RADIO, BM_SETCHECK, (WPARAM)BST_UNCHECKED, 0);
SendDlgItemMessage(IDC_DOMAIN_DC_RADIO, BM_SETCHECK, (WPARAM)BST_UNCHECKED, 0);
SendDlgItemMessage(IDC_CUSTOM_RADIO, BM_SETCHECK, (WPARAM)BST_UNCHECKED, 0);
GetDlgItem(IDC_CUSTOM_COMBO)->EnableWindow(FALSE);
GetDlgItem(IDC_CUSTOM_STATIC)->EnableWindow(FALSE);
break;
}
if (BST_CHECKED == SendDlgItemMessage(IDC_CUSTOM_RADIO, BM_GETCHECK, 0, 0))
{
CString szTemp;
GetDlgItemText(IDC_CUSTOM_COMBO, szTemp);
GetDlgItem(IDOK)->EnableWindow(!szTemp.IsEmpty());
}
else
{
GetDlgItem(IDOK)->EnableWindow(TRUE);
}
}
void CDNSZoneChangeReplicationScopeDialog::OnCustomComboSelChange()
{
LRESULT iSel = SendDlgItemMessage(IDC_CUSTOM_COMBO, CB_GETCURSEL, 0, 0);
if (CB_ERR != iSel)
{
CComboBox* pComboBox = reinterpret_cast<CComboBox*>(GetDlgItem(IDC_CUSTOM_COMBO));
ASSERT(pComboBox);
pComboBox->GetLBText(static_cast<int>(iSel), m_szCustomScope);
GetDlgItem(IDOK)->EnableWindow(!m_szCustomScope.IsEmpty());
}
else
{
GetDlgItem(IDOK)->EnableWindow(FALSE);
}
}
BOOL CDNSZoneChangeReplicationScopeDialog::OnInitDialog()
{
CHelpDialog::OnInitDialog();
m_pHolder->PushDialogHWnd(GetSafeHwnd());
CDNSZonePropertyPageHolder* pHolder = (CDNSZonePropertyPageHolder*)m_pHolder;
CDNSServerNode* pServerNode = pHolder->GetZoneNode()->GetServerNode();
//
// We should only reach this dialog if we are on a Whistler or greater server
//
ASSERT(DNS_SRV_BUILD_NUMBER(m_dwServerVersion) >= DNS_SRV_BUILD_NUMBER_WHISTLER &&
(DNS_SRV_MAJOR_VERSION(m_dwServerVersion) > DNS_SRV_MAJOR_VERSION_NT_5 ||
DNS_SRV_MINOR_VERSION(m_dwServerVersion) >= DNS_SRV_MINOR_VERSION_WHISTLER));
USES_CONVERSION;
//
// Get the forest and domain names and format them into the UI
//
PCWSTR pszDomainName = UTF8_TO_W(pServerNode->GetDomainName());
PCWSTR pszForestName = UTF8_TO_W(pServerNode->GetForestName());
ASSERT(pszDomainName);
ASSERT(pszForestName);
CString szWin2KReplText;
szWin2KReplText.Format(IDS_ZWIZ_AD_REPL_FORMAT, pszDomainName);
SetDlgItemText(IDC_DOMAIN_DC_RADIO, szWin2KReplText);
CString szDNSDomainText;
szDNSDomainText.Format(IDS_ZWIZ_AD_DOMAIN_FORMAT, pszDomainName);
SetDlgItemText(IDC_DOMAIN_RADIO, szDNSDomainText);
CString szDNSForestText;
szDNSForestText.Format(IDS_ZWIZ_AD_FOREST_FORMAT, pszForestName);
SetDlgItemText(IDC_FOREST_RADIO, szDNSForestText);
//
// Enumerate the available directory partitions
//
PDNS_RPC_DP_LIST pDirectoryPartitions = NULL;
DWORD dwErr = ::DnssrvEnumDirectoryPartitions(pServerNode->GetRPCName(),
DNS_DP_ENLISTED,
&pDirectoryPartitions);
//
// Don't show an error if we are not able to get the available directory partitions
// We can still continue on and the user can type in the directory partition they need
//
bool bCustomPartitionAdded = false;
if (dwErr == 0 && pDirectoryPartitions)
{
for (DWORD dwIdx = 0; dwIdx < pDirectoryPartitions->dwDpCount; dwIdx++)
{
PDNS_RPC_DP_INFO pDirectoryPartition = 0;
dwErr = ::DnssrvDirectoryPartitionInfo(pServerNode->GetRPCName(),
pDirectoryPartitions->DpArray[dwIdx]->pszDpFqdn,
&pDirectoryPartition);
if (dwErr == 0 &&
pDirectoryPartition)
{
//
// Only add the partition if it is not one of the autocreated ones
// and the DNS server is enlisted in the partition
//
if (!(pDirectoryPartition->dwFlags & DNS_DP_AUTOCREATED) &&
(pDirectoryPartition->dwFlags & DNS_DP_ENLISTED))
{
SendDlgItemMessage(IDC_CUSTOM_COMBO,
CB_ADDSTRING,
0,
(LPARAM)UTF8_TO_W(pDirectoryPartition->pszDpFqdn));
bCustomPartitionAdded = true;
}
::DnssrvFreeDirectoryPartitionInfo(pDirectoryPartition);
}
}
::DnssrvFreeDirectoryPartitionList(pDirectoryPartitions);
}
if (!bCustomPartitionAdded)
{
GetDlgItem(IDC_CUSTOM_RADIO)->EnableWindow(FALSE);
}
//
// Select the correct partition if we are using a custom partition
//
if (m_replType == custom)
{
LRESULT lIdx = SendDlgItemMessage(IDC_CUSTOM_COMBO,
CB_FINDSTRINGEXACT,
(WPARAM)-1,
(LPARAM)(PCWSTR)m_szCustomScope);
if (lIdx != CB_ERR)
{
SendDlgItemMessage(IDC_CUSTOM_COMBO,
CB_SETCURSEL,
(WPARAM)lIdx,
0);
}
else
{
//
// Add the partition
//
SendDlgItemMessage(IDC_CUSTOM_COMBO,
CB_ADDSTRING,
0,
(LPARAM)(PCWSTR)m_szCustomScope);
}
}
SyncRadioButtons();
return TRUE;
}
void CDNSZoneChangeReplicationScopeDialog::OnCancel()
{
if (m_pHolder != NULL)
{
m_pHolder->PopDialogHWnd();
}
CHelpDialog::OnCancel();
}
void CDNSZoneChangeReplicationScopeDialog::OnOK()
{
if (m_pHolder != NULL)
{
m_pHolder->PopDialogHWnd();
}
CHelpDialog::OnOK();
}
#endif // USE_NDNC
///////////////////////////////////////////////////////////////////////////////
// CDNSZoneChangeTypeDialog
class CDNSZoneChangeTypeDialog : public CHelpDialog
{
public:
CDNSZoneChangeTypeDialog(CPropertyPageHolderBase* pHolder,
BOOL bServerADSEnabled,
DWORD dwServerVersion);
BOOL m_bIsPrimary; // IN/OUT
BOOL m_bDSIntegrated; // IN/OUT
BOOL m_bIsStub; // IN/OUT
protected:
virtual BOOL OnInitDialog();
virtual void OnOK();
virtual void OnCancel();
afx_msg void OnRadioChange();
DECLARE_MESSAGE_MAP()
private:
BOOL m_bServerADSEnabled;
BOOL m_dwServerVersion;
CPropertyPageHolderBase* m_pHolder;
};
CDNSZoneChangeTypeDialog::CDNSZoneChangeTypeDialog(CPropertyPageHolderBase* pHolder,
BOOL bServerADSEnabled,
DWORD dwServerVersion)
: CHelpDialog(IDD_ZONE_GENERAL_CHANGE_TYPE, pHolder->GetComponentData())
{
ASSERT(pHolder != NULL);
m_pHolder = pHolder;
m_bServerADSEnabled = bServerADSEnabled;
m_dwServerVersion = dwServerVersion;
}
BEGIN_MESSAGE_MAP(CDNSZoneChangeTypeDialog, CHelpDialog)
ON_BN_CLICKED(IDC_RADIO_ZONE_PRIMARY, OnRadioChange)
ON_BN_CLICKED(IDC_RADIO_ZONE_SECONDARY, OnRadioChange)
ON_BN_CLICKED(IDC_RADIO_ZONE_STUB, OnRadioChange)
END_MESSAGE_MAP()
void CDNSZoneChangeTypeDialog::OnRadioChange()
{
if (SendDlgItemMessage(IDC_RADIO_ZONE_SECONDARY, BM_GETCHECK, 0, 0) == BST_CHECKED)
{
SendDlgItemMessage(IDC_ADINT_CHECK, BM_SETCHECK, BST_UNCHECKED, 0);
GetDlgItem(IDC_ADINT_CHECK)->EnableWindow(FALSE);
}
else
{
if (m_bServerADSEnabled)
{
GetDlgItem(IDC_ADINT_CHECK)->EnableWindow(TRUE);
}
else
{
GetDlgItem(IDC_ADINT_CHECK)->EnableWindow(FALSE);
}
}
}
BOOL CDNSZoneChangeTypeDialog::OnInitDialog()
{
CHelpDialog::OnInitDialog();
m_pHolder->PushDialogHWnd(GetSafeHwnd());
GetDlgItem(IDC_ADINT_CHECK)->EnableWindow(m_bServerADSEnabled);
int nIDCheckButton;
if (m_bIsPrimary)
{
nIDCheckButton = IDC_RADIO_ZONE_PRIMARY;
}
else
{
if (m_bIsStub)
{
nIDCheckButton = IDC_RADIO_ZONE_STUB;
}
else
{
nIDCheckButton = IDC_RADIO_ZONE_SECONDARY;
GetDlgItem(IDC_ADINT_CHECK)->EnableWindow(FALSE);
}
}
CheckRadioButton(IDC_RADIO_ZONE_PRIMARY, IDC_RADIO_ZONE_STUB, nIDCheckButton);
SendDlgItemMessage(IDC_ADINT_CHECK, BM_SETCHECK, m_bDSIntegrated, 0);
if (DNS_SRV_BUILD_NUMBER(m_dwServerVersion) < DNS_SRV_BUILD_NUMBER_WHISTLER ||
(DNS_SRV_MAJOR_VERSION(m_dwServerVersion) <= DNS_SRV_MAJOR_VERSION_NT_5 &&
DNS_SRV_MINOR_VERSION(m_dwServerVersion) < DNS_SRV_MINOR_VERSION_WHISTLER))
{
//
// Stub zones not available on pre-Whistler servers
//
GetDlgItem(IDC_RADIO_ZONE_STUB)->EnableWindow(FALSE);
GetDlgItem(IDC_STUB_STATIC)->EnableWindow(FALSE);
}
return TRUE;
}
void CDNSZoneChangeTypeDialog::OnCancel()
{
if (m_pHolder != NULL)
{
m_pHolder->PopDialogHWnd();
}
CHelpDialog::OnCancel();
}
void CDNSZoneChangeTypeDialog::OnOK()
{
BOOL bIsPrimary = TRUE;
BOOL bDSIntegrated = TRUE;
BOOL bIsStub = FALSE;
int nIDCheckButton = GetCheckedRadioButton(IDC_RADIO_ZONE_PRIMARY, IDC_RADIO_ZONE_STUB);
switch (nIDCheckButton)
{
case IDC_RADIO_ZONE_PRIMARY:
bIsPrimary = TRUE;
bIsStub = FALSE;
break;
case IDC_RADIO_ZONE_SECONDARY:
bIsPrimary = FALSE;
bIsStub = FALSE;
break;
case IDC_RADIO_ZONE_STUB:
bIsPrimary = FALSE;
bIsStub = TRUE;
break;
default:
ASSERT(FALSE);
break;
}
bDSIntegrated = static_cast<BOOL>(SendDlgItemMessage(IDC_ADINT_CHECK, BM_GETCHECK, 0, 0));
//
// warnings on special transitions
//
if (m_bDSIntegrated && !bDSIntegrated)
{
//
// warning changing from DS integrated to something else
//
if (IDYES != DNSMessageBox(IDS_MSG_ZONE_WARNING_CHANGE_TYPE_FROM_DS,MB_YESNO))
{
return;
}
}
else if (!m_bDSIntegrated && bDSIntegrated)
{
//
// warning changing from primary to DS integrated primary
//
if (IDYES != DNSMessageBox(IDS_MSG_ZONE_WARNING_CHANGE_TYPE_TO_DS,MB_YESNO))
{
return;
}
}
m_bIsPrimary = bIsPrimary;
m_bDSIntegrated = bDSIntegrated;
m_bIsStub = bIsStub;
if (m_pHolder != NULL)
{
m_pHolder->PopDialogHWnd();
}
CHelpDialog::OnOK();
}
///////////////////////////////////////////////////////////////////////////////
// CDNSZoneChangeTypeDataConflict
class CDNSZoneChangeTypeDataConflict : public CHelpDialog
{
public:
CDNSZoneChangeTypeDataConflict(CPropertyPageHolderBase* pHolder);
BOOL m_bUseDsData; // IN/OUT
protected:
virtual BOOL OnInitDialog();
virtual void OnOK();
virtual void OnCancel();
private:
CPropertyPageHolderBase* m_pHolder;
};
CDNSZoneChangeTypeDataConflict::CDNSZoneChangeTypeDataConflict(
CPropertyPageHolderBase* pHolder)
: CHelpDialog(IDD_ZONE_GENERAL_CHANGE_TYPE_DATA_CONFLICT, pHolder->GetComponentData())
{
m_pHolder = pHolder;
m_bUseDsData = FALSE;
}
BOOL CDNSZoneChangeTypeDataConflict::OnInitDialog()
{
CHelpDialog::OnInitDialog();
m_pHolder->PushDialogHWnd(GetSafeHwnd());
CheckRadioButton(IDC_RADIO_USE_DS_DATA, IDC_RADIO_USE_MEM_DATA,
m_bUseDsData ? IDC_RADIO_USE_DS_DATA : IDC_RADIO_USE_MEM_DATA);
return TRUE;
}
void CDNSZoneChangeTypeDataConflict::OnCancel()
{
if (m_pHolder != NULL)
m_pHolder->PopDialogHWnd();
CHelpDialog::OnCancel();
}
void CDNSZoneChangeTypeDataConflict::OnOK()
{
int nIDCheckButton = GetCheckedRadioButton(
IDC_RADIO_USE_DS_DATA, IDC_RADIO_USE_MEM_DATA);
m_bUseDsData = (nIDCheckButton == IDC_RADIO_USE_DS_DATA);
if (m_pHolder != NULL)
m_pHolder->PopDialogHWnd();
CHelpDialog::OnOK();
}
///////////////////////////////////////////////////////////////////////////////
// CDNSZoneNotifyDialog
class CDNSZoneNotifyDialog : public CHelpDialog
{
public:
CDNSZoneNotifyDialog(CDNSZone_ZoneTransferPropertyPage* pPage, BOOL bSecondaryZone,
CComponentDataObject* pComponentData);
protected:
virtual BOOL OnInitDialog();
virtual void OnOK();
virtual void OnCancel();
afx_msg void OnRadioNotifyOff() { SyncUIRadioHelper(IDC_CHECK_AUTO_NOTIFY);}
afx_msg void OnRadioNotifyAll() { SyncUIRadioHelper(IDC_RADIO_NOTIFY_ALL);}
afx_msg void OnRadioNotifyList() { SyncUIRadioHelper(IDC_RADIO_NOTIFY_LIST);}
DECLARE_MESSAGE_MAP()
private:
void SyncUIRadioHelper(UINT nRadio);
int SetRadioState(DWORD fNotifyFlag);
DWORD GetRadioState();
CDNSZone_ZoneTransferPropertyPage* m_pPage;
BOOL m_bSecondaryZone;
class CDNSNotifyIPEditor : public CIPEditor
{
public:
CDNSNotifyIPEditor() : CIPEditor(TRUE) {} // no up/down buttons
virtual void OnChangeData();
};
CDNSNotifyIPEditor m_notifyListEditor;
friend class CDNSNotifyIPEditor;
CComponentDataObject* m_pComponentData;
};
BEGIN_MESSAGE_MAP(CDNSZoneNotifyDialog, CHelpDialog)
ON_BN_CLICKED(IDC_CHECK_AUTO_NOTIFY, OnRadioNotifyOff)
ON_BN_CLICKED(IDC_RADIO_NOTIFY_ALL, OnRadioNotifyAll)
ON_BN_CLICKED(IDC_RADIO_NOTIFY_LIST, OnRadioNotifyList)
END_MESSAGE_MAP()
void CDNSZoneNotifyDialog::CDNSNotifyIPEditor::OnChangeData()
{
CWnd* pWnd = GetParentWnd();
pWnd->GetDlgItem(IDOK)->EnableWindow(TRUE); // it is dirty now
}
CDNSZoneNotifyDialog::CDNSZoneNotifyDialog(CDNSZone_ZoneTransferPropertyPage* pPage,
BOOL bSecondaryZone,
CComponentDataObject* pComponentData)
: CHelpDialog(IDD_ZONE_NOTIFY_SUBDIALOG, pComponentData)
{
m_pPage = pPage;
m_bSecondaryZone = bSecondaryZone;
m_pComponentData = pComponentData;
}
BOOL CDNSZoneNotifyDialog::OnInitDialog()
{
CHelpDialog::OnInitDialog();
m_pPage->GetHolder()->PushDialogHWnd(GetSafeHwnd());
VERIFY(m_notifyListEditor.Initialize(this,
this,
IDC_BUTTON_UP,
IDC_BUTTON_DOWN,
IDC_BUTTON_ADD,
IDC_BUTTON_REMOVE,
IDC_IPEDIT,
IDC_LIST));
if (m_bSecondaryZone)
{
ASSERT(m_pPage->m_fNotifyLevel != ZONE_NOTIFY_ALL);
GetDlgItem(IDC_RADIO_NOTIFY_ALL)->EnableWindow(FALSE);
}
// read the state and set the UI
if ( (ZONE_NOTIFY_LIST == m_pPage->m_fNotifyLevel) && (m_pPage->m_cNotify > 0) )
{
m_notifyListEditor.AddAddresses(m_pPage->m_aipNotify, m_pPage->m_cNotify);
}
SyncUIRadioHelper(SetRadioState(m_pPage->m_fNotifyLevel));
GetDlgItem(IDOK)->EnableWindow(FALSE); // not dirty
BOOL bListState = ((CButton*)GetDlgItem(IDC_RADIO_NOTIFY_LIST))->GetCheck();
BOOL bAllState = ((CButton*)GetDlgItem(IDC_RADIO_NOTIFY_ALL))->GetCheck();
if (!bAllState && !bListState)
{
((CButton*)GetDlgItem(IDC_RADIO_NOTIFY_LIST))->SetCheck(TRUE);
}
return TRUE;
}
void CDNSZoneNotifyDialog::OnCancel()
{
if (m_pPage->GetHolder() != NULL)
m_pPage->GetHolder()->PopDialogHWnd();
CHelpDialog::OnCancel();
}
void CDNSZoneNotifyDialog::OnOK()
{
// read the data back to the main page storage
m_pPage->m_fNotifyLevel = GetRadioState();
m_pPage->m_cNotify = 0;
if (m_pPage->m_aipNotify != NULL)
{
free(m_pPage->m_aipNotify);
m_pPage->m_aipNotify = NULL;
}
if (m_pPage->m_fNotifyLevel == ZONE_NOTIFY_LIST)
{
m_pPage->m_cNotify = m_notifyListEditor.GetCount();
if (m_pPage->m_cNotify > 0)
{
m_pPage->m_aipNotify = (DWORD*) malloc(sizeof(DWORD)*m_pPage->m_cNotify);
int nFilled = 0;
if (m_pPage->m_aipNotify != NULL)
{
m_notifyListEditor.GetAddresses(m_pPage->m_aipNotify, m_pPage->m_cNotify, &nFilled);
}
ASSERT(nFilled == (int)m_pPage->m_cNotify);
}
}
// dismiss dialog, all cool
if (m_pPage->GetHolder())
m_pPage->GetHolder()->PopDialogHWnd();
CHelpDialog::OnOK();
}
void CDNSZoneNotifyDialog::SyncUIRadioHelper(UINT nRadio)
{
m_notifyListEditor.EnableUI(IDC_RADIO_NOTIFY_LIST == nRadio, TRUE);
// if (IDC_RADIO_NOTIFY_LIST != nRadio)
// m_notifyListEditor.Clear();
GetDlgItem(IDOK)->EnableWindow(TRUE); // dirty
if (IDC_CHECK_AUTO_NOTIFY == nRadio)
{
BOOL bState = ((CButton*)GetDlgItem(IDC_CHECK_AUTO_NOTIFY))->GetCheck();
((CButton*)GetDlgItem(IDC_RADIO_NOTIFY_LIST))->EnableWindow(bState);
((CButton*)GetDlgItem(IDC_RADIO_NOTIFY_ALL))->EnableWindow(bState);
BOOL bRadioState = ((CButton*)GetDlgItem(IDC_RADIO_NOTIFY_LIST))->GetCheck();
m_notifyListEditor.EnableUI(bRadioState && bState, TRUE);
}
}
int CDNSZoneNotifyDialog::SetRadioState(DWORD fNotifyLevel)
{
int nRadio = 0;
switch (fNotifyLevel)
{
case ZONE_NOTIFY_OFF:
nRadio = IDC_CHECK_AUTO_NOTIFY;
((CButton*)GetDlgItem(IDC_CHECK_AUTO_NOTIFY))->SetCheck(FALSE);
break;
case ZONE_NOTIFY_LIST:
nRadio = IDC_RADIO_NOTIFY_LIST;
((CButton*)GetDlgItem(nRadio))->SetCheck(TRUE);
((CButton*)GetDlgItem(IDC_CHECK_AUTO_NOTIFY))->SetCheck(TRUE);
break;
case ZONE_NOTIFY_ALL:
nRadio = IDC_RADIO_NOTIFY_ALL;
((CButton*)GetDlgItem(nRadio))->SetCheck(TRUE);
((CButton*)GetDlgItem(IDC_CHECK_AUTO_NOTIFY))->SetCheck(TRUE);
break;
}
ASSERT(nRadio != 0);
return nRadio;
}
DWORD CDNSZoneNotifyDialog::GetRadioState()
{
static int nRadioArr[] =
{
IDC_RADIO_NOTIFY_OFF,
IDC_RADIO_NOTIFY_LIST,
IDC_RADIO_NOTIFY_ALL
};
int nRadio = 0;
if (!((CButton*)GetDlgItem(IDC_CHECK_AUTO_NOTIFY))->GetCheck())
{
nRadio = IDC_CHECK_AUTO_NOTIFY;
}
else
{
if (((CButton*)GetDlgItem(IDC_RADIO_NOTIFY_LIST))->GetCheck())
{
nRadio = IDC_RADIO_NOTIFY_LIST;
}
else if (((CButton*)GetDlgItem(IDC_RADIO_NOTIFY_ALL))->GetCheck())
{
nRadio = IDC_RADIO_NOTIFY_ALL;
}
}
// int nRadio = ::GetCheckedRadioButtonHelper(m_hWnd, 3, nRadioArr, IDC_RADIO_NOTIFY_OFF);
ASSERT(nRadio != 0);
DWORD fNotifyLevel = (DWORD)-1;
switch (nRadio)
{
case IDC_CHECK_AUTO_NOTIFY:
fNotifyLevel = ZONE_NOTIFY_OFF;
break;
case IDC_RADIO_NOTIFY_LIST:
fNotifyLevel = ZONE_NOTIFY_LIST;
break;
case IDC_RADIO_NOTIFY_ALL:
fNotifyLevel = ZONE_NOTIFY_ALL;
break;
}
ASSERT(fNotifyLevel != (DWORD)-1);
return fNotifyLevel;
}
///////////////////////////////////////////////////////////////////////////////
// CDNSZone_GeneralPropertyPage
//
// defines for the status text string positions (matching the RC file)
//
#define N_ZONE_STATES 3
#define N_ZONE_STATUS_RUNNING 0
#define N_ZONE_STATUS_PAUSED 1
#define N_ZONE_STATUS_EXPIRED 2
#define N_ZONE_TYPES 4
#define N_ZONE_TYPES_PRIMARY 0
#define N_ZONE_TYPES_DS_PRIMARY 1
#define N_ZONE_TYPES_SECONDARY 2
#define N_ZONE_TYPES_STUB 3
void CDNSZone_GeneralIPEditor::OnChangeData()
{
if (m_bNoUpdateNow)
{
return;
}
((CDNSZone_GeneralPropertyPage*)GetParentWnd())->OnChangeIPEditorData();
}
void CDNSZone_GeneralIPEditor::FindMastersNames()
{
m_bNoUpdateNow = TRUE;
FindNames();
m_bNoUpdateNow = FALSE;
}
BEGIN_MESSAGE_MAP(CDNSZone_GeneralPropertyPage, CPropertyPageBase)
ON_BN_CLICKED(IDC_CHANGE_TYPE_BUTTON, OnChangeTypeButton)
#ifdef USE_NDNC
ON_BN_CLICKED(IDC_CHANGE_REPL_BUTTON, OnChangeReplButton)
#endif // USE_NDNC
ON_BN_CLICKED(IDC_PAUSE_START_BUTTON, OnPauseStartButton)
ON_EN_CHANGE(IDC_FILE_NAME_EDIT, OnChangePrimaryFileNameEdit)
ON_CBN_SELCHANGE(IDC_PRIMARY_DYN_UPD_COMBO, OnChangePrimaryDynamicUpdateCombo)
ON_BN_CLICKED(IDC_BROWSE_MASTERS_BUTTON, OnBrowseMasters)
ON_BN_CLICKED(IDC_FIND_MASTERS_NAMES_BUTTON, OnFindMastersNames)
ON_BN_CLICKED(IDC_AGING_BUTTON, OnAging)
ON_BN_CLICKED(IDC_LOCAL_LIST_CHECK, OnLocalCheck)
END_MESSAGE_MAP()
CDNSZone_GeneralPropertyPage::CDNSZone_GeneralPropertyPage()
: CPropertyPageBase(CDNSZone_GeneralPropertyPage::IDD),
m_statusHelper(N_ZONE_STATES), m_typeStaticHelper(N_ZONE_TYPES)
{
// actual values will be set when loading UI data
m_bIsPrimary = TRUE;
m_bIsPaused = FALSE;
m_bIsExpired = FALSE;
m_bDSIntegrated = FALSE;
m_bIsStub = FALSE;
m_bServerADSEnabled = FALSE;
m_bScavengingEnabled = FALSE;
m_dwRefreshInterval = 0;
m_dwNoRefreshInterval = 0;
m_nAllowsDynamicUpdate = ZONE_UPDATE_OFF;
m_bDiscardUIState = FALSE;
m_bDiscardUIStateShowMessage = FALSE;
#ifdef USE_NDNC
m_replType = none;
#endif // USE_NDNC
}
void CDNSZone_GeneralPropertyPage::OnChangeIPEditorData()
{
ASSERT(!m_bIsPrimary);
SetDirty(TRUE);
GetFindMastersNamesButton()->EnableWindow(m_mastersEditor.GetCount()>0);
}
BOOL CDNSZone_GeneralPropertyPage::OnPropertyChange(BOOL, long*)
{
CDNSZonePropertyPageHolder* pHolder = (CDNSZonePropertyPageHolder*)GetHolder();
CDNSZoneNode* pZoneNode = pHolder->GetZoneNode();
// need to apply the pause/start zone command ?
BOOL bWasPaused = pZoneNode->IsPaused();
if (bWasPaused != m_bIsPaused)
{
DNS_STATUS err = pZoneNode->TogglePauseHelper(pHolder->GetComponentData());
if (err != 0)
pHolder->SetError(err);
}
if (pZoneNode->GetZoneType() == DNS_ZONE_TYPE_SECONDARY ||
pZoneNode->GetZoneType() == DNS_ZONE_TYPE_STUB)
{
// NTRAID#NTBUG9-762897-2003/01/16-JeffJon
// Need to update the result pane view because changing stub
// and secondary zones can easily put the zone in an expired
// state which requires us to show the message view instead
// of the normal result pane.
pZoneNode->ToggleView(pHolder->GetComponentData());
}
return TRUE;
}
void CDNSZone_GeneralPropertyPage::SetUIData()
{
CDNSZonePropertyPageHolder* pHolder = (CDNSZonePropertyPageHolder*)GetHolder();
CDNSZoneNode* pZoneNode = pHolder->GetZoneNode();
CDNSServerNode* pServerNode = pZoneNode->GetServerNode();
//
// get zone type
//
DWORD dwZoneType = pZoneNode->GetZoneType();
ASSERT((dwZoneType == DNS_ZONE_TYPE_PRIMARY) ||
(dwZoneType == DNS_ZONE_TYPE_SECONDARY)||
(dwZoneType == DNS_ZONE_TYPE_STUB));
m_bIsPrimary = (dwZoneType == DNS_ZONE_TYPE_PRIMARY);
m_bIsStub = (dwZoneType == DNS_ZONE_TYPE_STUB);
m_bDSIntegrated = pZoneNode->IsDSIntegrated();
m_bIsPaused = pZoneNode->IsPaused();
m_bIsExpired = pZoneNode->IsExpired();
m_bScavengingEnabled = pZoneNode->IsScavengingEnabled();
m_dwRefreshInterval = pZoneNode->GetAgingRefreshInterval();
m_dwNoRefreshInterval = pZoneNode->GetAgingNoRefreshInterval();
m_dwScavengingStart = pZoneNode->GetScavengingStart();
#ifdef USE_NDNC
m_replType = pZoneNode->GetDirectoryPartitionFlagsAsReplType();
m_szCustomScope = pZoneNode->GetCustomPartitionName();
//
// Enable the replication scope button only for AD integrated zones
//
if (m_bDSIntegrated &&
(DNS_SRV_BUILD_NUMBER(pServerNode->GetVersion()) >= DNS_SRV_BUILD_NUMBER_WHISTLER &&
(DNS_SRV_MAJOR_VERSION(pServerNode->GetVersion()) > DNS_SRV_MAJOR_VERSION_NT_5 ||
DNS_SRV_MINOR_VERSION(pServerNode->GetVersion()) >= DNS_SRV_MINOR_VERSION_WHISTLER)))
{
GetDlgItem(IDC_CHANGE_REPL_BUTTON)->EnableWindow(TRUE);
GetDlgItem(IDC_REPL_LABEL_STATIC)->EnableWindow(TRUE);
GetDlgItem(IDC_REPLICATION_STATIC)->EnableWindow(TRUE);
}
else
{
GetDlgItem(IDC_CHANGE_REPL_BUTTON)->EnableWindow(FALSE);
GetDlgItem(IDC_REPL_LABEL_STATIC)->EnableWindow(FALSE);
GetDlgItem(IDC_REPLICATION_STATIC)->EnableWindow(FALSE);
}
#endif // USE_NDNC
//
// change the controls to the zone type
//
ChangeUIControls();
USES_CONVERSION;
//
// set the file name control
//
CString szZoneStorage;
szZoneStorage = UTF8_TO_W(pZoneNode->GetDataFile());
if (m_bIsPrimary)
{
m_nAllowsDynamicUpdate = pZoneNode->GetDynamicUpdate();
}
else // secondary
{
DWORD cAddrCount;
PIP_ADDRESS pipMasters;
if (m_bIsStub)
{
pZoneNode->GetLocalListOfMasters(&cAddrCount, &pipMasters);
if (cAddrCount > 0 && pipMasters != NULL)
{
m_mastersEditor.AddAddresses(pipMasters, cAddrCount);
SendDlgItemMessage(IDC_LOCAL_LIST_CHECK, BM_SETCHECK, (WPARAM)BST_CHECKED, 0);
}
else
{
pZoneNode->GetMastersInfo(&cAddrCount, &pipMasters);
if (cAddrCount > 0)
{
m_mastersEditor.AddAddresses(pipMasters, cAddrCount);
}
SendDlgItemMessage(IDC_LOCAL_LIST_CHECK, BM_SETCHECK, (WPARAM)BST_UNCHECKED, 0);
}
}
else
{
pZoneNode->GetMastersInfo(&cAddrCount, &pipMasters);
if (cAddrCount > 0)
{
m_mastersEditor.AddAddresses(pipMasters, cAddrCount);
}
}
}
if (m_bDSIntegrated && !m_bIsStub)
{
GetDlgItem(IDC_AGING_STATIC)->EnableWindow(TRUE);
GetDlgItem(IDC_AGING_STATIC)->ShowWindow(TRUE);
GetDlgItem(IDC_AGING_BUTTON)->EnableWindow(TRUE);
GetDlgItem(IDC_AGING_BUTTON)->ShowWindow(TRUE);
}
//
// we set also the database name of the "other" zone type, just
// in case the user promotes or demotes
//
GetFileNameEdit()->SetWindowText(szZoneStorage);
SetPrimaryDynamicUpdateComboVal(m_nAllowsDynamicUpdate);
if (m_bIsExpired)
{
//
// hide the start/stop button
//
CButton* pBtn = GetPauseStartButton();
pBtn->ShowWindow(FALSE);
pBtn->EnableWindow(FALSE);
//
// change the text to "expired"
//
m_statusHelper.SetStateX(N_ZONE_STATUS_EXPIRED);
}
else
{
m_statusHelper.SetStateX(m_bIsPaused ? N_ZONE_STATUS_PAUSED : N_ZONE_STATUS_RUNNING);
m_pauseStartHelper.SetToggleState(!m_bIsPaused);
}
}
#define PRIMARY_DYN_UPD_COMBO_ITEM_COUNT 3
void _MoveChildWindowY(CWnd* pChild, CWnd* pParent, int nY)
{
CRect r;
pChild->GetWindowRect(r);
pParent->ScreenToClient(r);
int nDy = r.bottom - r.top;
r.top = nY;
r.bottom = nY + nDy;
pChild->MoveWindow(r, TRUE);
}
BOOL CDNSZone_GeneralPropertyPage::OnInitDialog()
{
CPropertyPageBase::OnInitDialog();
CDNSZonePropertyPageHolder* pHolder = (CDNSZonePropertyPageHolder*)GetHolder();
m_bServerADSEnabled = pHolder->GetZoneNode()->GetServerNode()->CanUseADS();
VERIFY(m_mastersEditor.Initialize(this,
GetParent(),
IDC_MASTERS_BUTTON_UP,
IDC_MASTERS_BUTTON_DOWN,
IDC_MASTERS_BUTTON_ADD,
IDC_MASTERS_BUTTON_REMOVE,
IDC_MASTERS_IPEDIT,
IDC_MASTERS_IP_LIST));
UINT pnButtonStringIDs[2] = { IDS_BUTTON_TEXT_PAUSE_BUTTON, IDS_BUTTON_TEXT_START_BUTTON };
VERIFY(m_pauseStartHelper.Init(this, IDC_PAUSE_START_BUTTON, pnButtonStringIDs));
VERIFY(m_typeStaticHelper.Init(this, IDC_TYPE_STATIC));
VERIFY(m_statusHelper.Init(this, IDC_STATUS_STATIC));
VERIFY(m_zoneStorageStaticHelper.Init(this, IDC_STORAGE_STATIC));
SendDlgItemMessage(IDC_FILE_NAME_EDIT, EM_SETLIMITTEXT, (WPARAM)_MAX_FNAME, 0);
// initial positioning (in the resource these controls are at the bottom of the screen)
// move relative the file name exit box
CRect fileNameEditRect;
GetDlgItem(IDC_FILE_NAME_EDIT)->GetWindowRect(fileNameEditRect);
ScreenToClient(fileNameEditRect);
// move below the edit box, with with separation equal of 6 (DBU)
// height of the edit box.
int nYPos = fileNameEditRect.bottom + 6;
CComboBox* pDynamicUpdateCombo = GetPrimaryDynamicUpdateCombo();
// The static control needs to be 2 lower
_MoveChildWindowY(GetPrimaryDynamicUpdateStatic(), this, nYPos + 2);
_MoveChildWindowY(pDynamicUpdateCombo, this, nYPos);
// initialize the state of the page
SetUIData();
#ifdef USE_NDNC
SetTextForReplicationScope();
#endif
SetDirty(FALSE);
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
BOOL CDNSZone_GeneralPropertyPage::OnApply()
{
if (m_bDiscardUIState)
{
// if we get called from other pages, we have to make them fail
if (m_bDiscardUIStateShowMessage)
{
DNSMessageBox(IDS_ZONE_LOADED_FROM_DS_WARNING);
m_bDiscardUIStateShowMessage = FALSE;
}
return FALSE;
}
if (!IsDirty())
return TRUE;
CDNSZonePropertyPageHolder* pHolder = (CDNSZonePropertyPageHolder*)GetHolder();
CDNSZoneNode* pZoneNode = pHolder->GetZoneNode();
CDNSServerNode* pServerNode = pZoneNode->GetServerNode();
//
// changed from primary to secondary or vice versa?
//
DWORD dwZoneType = pZoneNode->GetZoneType();
ASSERT((dwZoneType == DNS_ZONE_TYPE_PRIMARY) ||
(dwZoneType == DNS_ZONE_TYPE_SECONDARY)||
(dwZoneType == DNS_ZONE_TYPE_STUB));
BOOL bWasPrimary = (dwZoneType == DNS_ZONE_TYPE_PRIMARY);
DNS_STATUS dwErr = 0;
USES_CONVERSION;
CString szDataStorageName;
GetStorageName(szDataStorageName);
DWORD dwLoadOptions;
if (m_bIsPrimary)
{
dwLoadOptions = 0x0;
PWSTR pszZoneFile = UTF8_TO_W(pZoneNode->GetDataFile());
//
// Check to see if this was primary before if so only submit changes if the storage changed
//
if (!bWasPrimary ||
(bWasPrimary &&
((pZoneNode->IsDSIntegrated() && !m_bDSIntegrated) ||
(!pZoneNode->IsDSIntegrated() && m_bDSIntegrated))) ||
(pszZoneFile && szDataStorageName.CompareNoCase(pszZoneFile)))
{
dwErr = pZoneNode->SetPrimary(dwLoadOptions, m_bDSIntegrated, szDataStorageName);
if (m_bDSIntegrated && (dwErr == DNS_ERROR_DS_ZONE_ALREADY_EXISTS))
{
FIX_THREAD_STATE_MFC_BUG();
CThemeContextActivator activator;
CDNSZoneChangeTypeDataConflict dlg(pHolder);
//
// if the zone was a primary, use in memory data
// otherwise, use DS data
//
dlg.m_bUseDsData = bWasPrimary ? FALSE : TRUE;
if (IDOK == dlg.DoModal())
{
//
// try again, getting options from dialog
//
dwLoadOptions = dlg.m_bUseDsData ? DNS_ZONE_LOAD_OVERWRITE_MEMORY : DNS_ZONE_LOAD_OVERWRITE_DS;
dwErr = pZoneNode->SetPrimary(dwLoadOptions, m_bDSIntegrated, szDataStorageName);
if ((dwErr == 0) && dlg.m_bUseDsData)
{
//
// we loaded from the DS, we will have to discard all the other
// changes the user has made.
//
m_bDiscardUIState = TRUE;
//
// tell the user to bail out
//
m_bDiscardUIStateShowMessage = FALSE;
DNSMessageBox(IDS_ZONE_LOADED_FROM_DS_WARNING);
SetDirty(FALSE);
return TRUE;
}
}
else
{
//
// user canceled the operation, just stop here
//
return FALSE;
}
}
}
if (dwErr == 0)
{
// update dynamic update flag, if changed
m_nAllowsDynamicUpdate = GetPrimaryDynamicUpdateComboVal();
UINT nWasDynamicUpdate = pZoneNode->GetDynamicUpdate();
if ( (dwErr == 0) && (m_nAllowsDynamicUpdate != nWasDynamicUpdate) )
{
dwErr = pZoneNode->SetDynamicUpdate(m_nAllowsDynamicUpdate);
if (dwErr != 0)
DNSErrorDialog(dwErr, IDS_ERROR_ZONE_DYN_UPD);
}
}
else
{
DNSErrorDialog(dwErr, IDS_ERROR_ZONE_PRIMARY);
}
if (dwErr == 0 && m_bIsPrimary)
{
dwErr = pZoneNode->SetAgingNoRefreshInterval(m_dwNoRefreshInterval);
if (dwErr != 0)
{
DNSErrorDialog(dwErr, IDS_MSG_ERROR_NO_REFRESH_INTERVAL);
return FALSE;
}
dwErr = pZoneNode->SetAgingRefreshInterval(m_dwRefreshInterval);
if (dwErr != 0)
{
DNSErrorDialog(dwErr, IDS_MSG_ERROR_REFRESH_INTERVAL);
return FALSE;
}
dwErr = pZoneNode->SetScavengingEnabled(m_bScavengingEnabled);
if (dwErr != 0)
{
DNSErrorDialog(dwErr, IDS_MSG_ERROR_SCAVENGING_ENABLED);
return FALSE;
}
}
}
else // it is a secondary or stub
{
//
// get data from the IP editor
//
DWORD cAddrCount = m_mastersEditor.GetCount();
// NTRAID#NTBUG9-655784-2002/07/05-artm
// Initialize the array.
DWORD* pArr = (cAddrCount > 0) ? (DWORD*) calloc(cAddrCount, sizeof(DWORD)) : NULL;
if (cAddrCount > 0)
{
int nFilled = 0;
// NTRAID#NTBUG9-653630-2002/07/05-artm
if (pArr)
{
m_mastersEditor.GetAddresses(pArr, cAddrCount, &nFilled);
ASSERT(nFilled == (int)cAddrCount);
}
else
{
// Out of memory! Try to tell the user, and abort the operation.
dwErr = ERROR_OUTOFMEMORY;
DNSDisplaySystemError(dwErr);
return FALSE;
}
}
dwLoadOptions = 0x0;
if (m_bIsStub)
{
LRESULT lLocalListOfMasters = SendDlgItemMessage(IDC_LOCAL_LIST_CHECK, BM_GETCHECK, 0, 0);
BOOL bLocalListOfMasters = (lLocalListOfMasters == BST_CHECKED);
dwErr = pZoneNode->SetStub(cAddrCount,
pArr,
dwLoadOptions,
m_bDSIntegrated,
szDataStorageName,
bLocalListOfMasters);
if (dwErr != 0)
{
DNSErrorDialog(dwErr, IDS_ERROR_ZONE_STUB);
}
}
else
{
dwErr = pZoneNode->SetSecondary(cAddrCount, pArr, dwLoadOptions, szDataStorageName);
if (dwErr != 0)
{
DNSErrorDialog(dwErr, IDS_ERROR_ZONE_SECONDARY);
}
}
if (pArr)
{
free(pArr);
pArr = 0;
}
}
#ifdef USE_NDNC
if ((DNS_SRV_BUILD_NUMBER(pServerNode->GetVersion()) >= DNS_SRV_BUILD_NUMBER_WHISTLER &&
(DNS_SRV_MAJOR_VERSION(pServerNode->GetVersion()) > DNS_SRV_MAJOR_VERSION_NT_5 ||
DNS_SRV_MINOR_VERSION(pServerNode->GetVersion()) >= DNS_SRV_MINOR_VERSION_WHISTLER)) &&
(m_replType != pZoneNode->GetDirectoryPartitionFlagsAsReplType() ||
_wcsicmp(m_szCustomScope, pZoneNode->GetCustomPartitionName()) != 0) &&
m_bDSIntegrated)
{
dwErr = pZoneNode->ChangeDirectoryPartitionType(m_replType, m_szCustomScope);
if (dwErr != 0)
{
DNSErrorDialog(dwErr, IDS_ERROR_ZONE_REPLTYPE);
}
}
#endif
// if promoted or demoted, have to change icon
// if paused/started, have to apply the command
BOOL bWasPaused = pZoneNode->IsPaused();
DNS_STATUS dwPauseStopErr = 0;
if ((bWasPrimary != m_bIsPrimary) || (bWasPaused != m_bIsPaused))
{
dwPauseStopErr = pHolder->NotifyConsole(this);
if (dwPauseStopErr != 0)
{
if (m_bIsPaused)
DNSErrorDialog(dwPauseStopErr, IDS_ERROR_ZONE_PAUSE);
else
DNSErrorDialog(dwPauseStopErr, IDS_ERROR_ZONE_START);
}
}
if ( (dwErr != 0) || (dwPauseStopErr != 0) )
return FALSE; // something went wrong, already got error messages
// NTRAID#NTBUG9-762897-2003/01/16-JeffJon
// Need to update the result pane view because changing stub
// and secondary zones can easily put the zone in an expired
// state which requires us to show the message view instead
// of the normal result pane.
pHolder->NotifyConsole(this);
SetDirty(FALSE);
return TRUE;
}
void CDNSZone_GeneralPropertyPage::OnAging()
{
CThemeContextActivator activator;
CDNSZonePropertyPageHolder* pHolder =
(CDNSZonePropertyPageHolder*)GetHolder();
CDNSZone_AgingDialog dlg(pHolder, IDD_ZONE_AGING_DIALOG, pHolder->GetComponentData());
dlg.m_dwRefreshInterval = m_dwRefreshInterval;
dlg.m_dwNoRefreshInterval = m_dwNoRefreshInterval;
dlg.m_dwScavengingStart = m_dwScavengingStart;
dlg.m_fScavengingEnabled = m_bScavengingEnabled;
dlg.m_bAdvancedView = pHolder->IsAdvancedView();
if (IDCANCEL == dlg.DoModal())
{
return;
}
m_dwRefreshInterval = dlg.m_dwRefreshInterval;
m_dwNoRefreshInterval = dlg.m_dwNoRefreshInterval;
m_bScavengingEnabled = dlg.m_fScavengingEnabled;
SetDirty(TRUE);
}
void CDNSZone_GeneralPropertyPage::OnLocalCheck()
{
SetDirty(TRUE);
}
#ifdef USE_NDNC
void CDNSZone_GeneralPropertyPage::OnChangeReplButton()
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
FIX_THREAD_STATE_MFC_BUG();
CThemeContextActivator activator;
CDNSZonePropertyPageHolder* pHolder = (CDNSZonePropertyPageHolder*)GetHolder();
CDNSZoneNode* pZoneNode = pHolder->GetZoneNode();
CDNSZoneChangeReplicationScopeDialog dlg(GetHolder(),
m_replType,
m_szCustomScope,
pZoneNode->GetServerNode()->GetVersion());
if (IDCANCEL == dlg.DoModal())
{
return;
}
BOOL bDirty = (m_replType != dlg.m_newReplType) ||
(m_szCustomScope != dlg.m_szCustomScope);
if (!bDirty)
{
return;
}
m_replType = dlg.m_newReplType;
m_szCustomScope = dlg.m_szCustomScope;
SetTextForReplicationScope();
SetDirty(TRUE);
}
void CDNSZone_GeneralPropertyPage::SetTextForReplicationScope()
{
CDNSZonePropertyPageHolder* pHolder = (CDNSZonePropertyPageHolder*)GetHolder();
CDNSZoneNode* pZoneNode = pHolder->GetZoneNode();
CDNSServerNode* pServerNode = pZoneNode->GetServerNode();
UINT nStringID = 0;
CString szReplText;
if (m_bDSIntegrated)
{
switch(m_replType)
{
case domain :
nStringID = IDS_ZONE_REPLICATION_DOMAIN_TEXT;
break;
case forest :
nStringID = IDS_ZONE_REPLICATION_FOREST_TEXT;
break;
case custom :
nStringID = IDS_ZONE_REPLICATION_CUSTOM_TEXT;
break;
default :
nStringID = IDS_ZONE_REPLICATION_W2K_TEXT;
break;
}
if (m_bDSIntegrated &&
(DNS_SRV_BUILD_NUMBER(pServerNode->GetVersion()) >= DNS_SRV_BUILD_NUMBER_WHISTLER &&
(DNS_SRV_MAJOR_VERSION(pServerNode->GetVersion()) > DNS_SRV_MAJOR_VERSION_NT_5 ||
DNS_SRV_MINOR_VERSION(pServerNode->GetVersion()) >= DNS_SRV_MINOR_VERSION_WHISTLER)))
{
GetDlgItem(IDC_CHANGE_REPL_BUTTON)->EnableWindow(TRUE);
GetDlgItem(IDC_REPL_LABEL_STATIC)->EnableWindow(TRUE);
GetDlgItem(IDC_REPLICATION_STATIC)->EnableWindow(TRUE);
}
}
else
{
nStringID = IDS_ZONE_REPLICATION_NONDS_TEXT;
GetDlgItem(IDC_CHANGE_REPL_BUTTON)->EnableWindow(FALSE);
GetDlgItem(IDC_REPL_LABEL_STATIC)->EnableWindow(FALSE);
GetDlgItem(IDC_REPLICATION_STATIC)->EnableWindow(FALSE);
}
szReplText.LoadString(nStringID);
SetDlgItemText(IDC_REPLICATION_STATIC, szReplText);
}
#endif // USE_NDNC
void CDNSZone_GeneralPropertyPage::OnChangeTypeButton()
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
FIX_THREAD_STATE_MFC_BUG();
CThemeContextActivator activator;
CDNSZonePropertyPageHolder* pHolder = (CDNSZonePropertyPageHolder*)GetHolder();
CDNSZoneNode* pZoneNode = pHolder->GetZoneNode();
CDNSZoneChangeTypeDialog dlg(GetHolder(),
m_bServerADSEnabled,
pZoneNode->GetServerNode()->GetVersion());
dlg.m_bIsPrimary = m_bIsPrimary;
dlg.m_bIsStub = m_bIsStub;
dlg.m_bDSIntegrated = m_bDSIntegrated;
if (IDCANCEL == dlg.DoModal())
{
return;
}
BOOL bDirty = (m_bIsPrimary != dlg.m_bIsPrimary) ||
(m_bDSIntegrated != dlg.m_bDSIntegrated) ||
(m_bIsStub != dlg.m_bIsStub);
if (!bDirty)
{
return;
}
CString szZoneStorage;
GetFileNameEdit()->GetWindowText(szZoneStorage);
if (dlg.m_bDSIntegrated == FALSE &&
m_bDSIntegrated == TRUE &&
szZoneStorage.IsEmpty())
{
//
// we have no file name, synthesize one
//
CString szZoneName = pZoneNode->GetDisplayName();
int nLen = szZoneName.GetLength();
if (nLen == 0)
{
szZoneStorage.Empty();
}
else if (nLen == 1 && szZoneName[0] == TEXT('.'))
{
szZoneStorage = _T("root.dns");
}
else
{
LPCTSTR lpszFmt = ( TEXT('.') == szZoneName.GetAt(nLen-1))
? _T("%sdns") : _T("%s.dns");
szZoneStorage.Format(lpszFmt, (LPCTSTR)szZoneName);
}
GetFileNameEdit()->SetWindowText(szZoneStorage);
}
else if (dlg.m_bDSIntegrated == TRUE &&
m_bDSIntegrated == FALSE)
{
//
// Set the default replication
// if the zone was previously file based
//
if (pZoneNode->GetServerNode()->GetDomainVersion() > DS_BEHAVIOR_WIN2000)
{
m_replType = domain;
}
else
{
m_replType = w2k;
}
}
m_bIsPrimary = dlg.m_bIsPrimary;
m_bDSIntegrated = dlg.m_bDSIntegrated;
m_bIsStub = dlg.m_bIsStub;
SetDirty(TRUE);
ChangeUIControls();
#ifdef USE_NDNC
SetTextForReplicationScope();
#endif
}
void CDNSZone_GeneralPropertyPage::OnPauseStartButton()
{
ASSERT(!m_bIsExpired); // the button should not be enabled
SetDirty(TRUE);
m_bIsPaused = !m_bIsPaused;
m_pauseStartHelper.SetToggleState(!m_bIsPaused);
m_statusHelper.SetStateX(m_bIsPaused ? N_ZONE_STATUS_PAUSED : N_ZONE_STATUS_RUNNING);
}
void CDNSZone_GeneralPropertyPage::OnBrowseMasters()
{
ASSERT(!m_bIsPrimary);
CDNSZonePropertyPageHolder* pZoneHolder = (CDNSZonePropertyPageHolder*)GetHolder();
if (!m_mastersEditor.BrowseFromDNSNamespace(pZoneHolder->GetComponentData(),
pZoneHolder,
TRUE,
pZoneHolder->GetZoneNode()->GetServerNode()->GetDisplayName()))
{
DNSMessageBox(IDS_MSG_ZONE_MASTERS_BROWSE_FAIL);
}
}
void CDNSZone_GeneralPropertyPage::OnFindMastersNames()
{
m_mastersEditor.FindMastersNames();
}
void CDNSZone_GeneralPropertyPage::SetPrimaryDynamicUpdateComboVal(UINT nAllowsDynamicUpdate)
{
int nIndex = 0;
switch (nAllowsDynamicUpdate)
{
case ZONE_UPDATE_OFF:
nIndex = 0;
break;
case ZONE_UPDATE_UNSECURE:
nIndex = 1;
break;
case ZONE_UPDATE_SECURE:
nIndex = 2;
break;
default:
ASSERT(FALSE);
}
VERIFY(CB_ERR != GetPrimaryDynamicUpdateCombo()->SetCurSel(nIndex));
}
UINT CDNSZone_GeneralPropertyPage::GetPrimaryDynamicUpdateComboVal()
{
int nIndex = GetPrimaryDynamicUpdateCombo()->GetCurSel();
ASSERT(nIndex != CB_ERR);
UINT nVal = 0;
switch (nIndex)
{
case 0:
nVal = ZONE_UPDATE_OFF;
break;
case 1:
nVal = ZONE_UPDATE_UNSECURE;
break;
case 2:
nVal = ZONE_UPDATE_SECURE;
break;
default:
ASSERT(FALSE);
}
return nVal;
}
void CDNSZone_GeneralPropertyPage::ChangeUIControlHelper(CWnd* pChild, BOOL bEnable)
{
pChild->EnableWindow(bEnable);
pChild->ShowWindow(bEnable);
}
void CDNSZone_GeneralPropertyPage::ChangeUIControls()
{
// change button label
int nType;
if (m_bIsPrimary)
{
nType = m_bDSIntegrated ? N_ZONE_TYPES_DS_PRIMARY : N_ZONE_TYPES_PRIMARY;
}
else
{
if (m_bIsStub)
{
nType = N_ZONE_TYPES_STUB;
}
else
{
nType = N_ZONE_TYPES_SECONDARY;
}
}
m_typeStaticHelper.SetStateX(nType);
//
// file name controls (show for secondary and for non DS integrated primary and stub)
//
BOOL bNotDSIntegrated = (!m_bIsPrimary && !m_bIsStub) ||
(m_bIsPrimary && !m_bDSIntegrated) ||
(m_bIsStub && !m_bDSIntegrated);
m_zoneStorageStaticHelper.SetToggleState(bNotDSIntegrated); // bNotDSIntegrated == bShowEdit
ChangeUIControlHelper(GetFileNameEdit(), bNotDSIntegrated); // bNotDSIntegrated == bShowEdit
//
// change primary zone controls
CComboBox* pPrimaryDynamicUpdateCombo = GetPrimaryDynamicUpdateCombo();
//
// see if the combo box had a selection in it and save it
//
UINT nAllowsDynamicUpdateSaved = ZONE_UPDATE_OFF;
if (pPrimaryDynamicUpdateCombo->GetCurSel() != CB_ERR)
{
nAllowsDynamicUpdateSaved = GetPrimaryDynamicUpdateComboVal();
}
//
// set strings in the combo box
//
UINT nMaxAddCount = PRIMARY_DYN_UPD_COMBO_ITEM_COUNT;
//
// the last item in the combo box would be the "secure dynamic udate"
// which is valid only for DS integrated primaries
//
if (bNotDSIntegrated)
{
nMaxAddCount--; // remove the last one
}
VERIFY(LoadStringsToComboBox(_Module.GetModuleInstance(),
pPrimaryDynamicUpdateCombo,
IDS_ZONE_PRIMARY_DYN_UPD_OPTIONS,
256, nMaxAddCount));
//
// reset selection
//
if (bNotDSIntegrated && (nAllowsDynamicUpdateSaved == ZONE_UPDATE_SECURE))
{
//
// the selected secure update otion is gone, so turn off secure update
//
nAllowsDynamicUpdateSaved = ZONE_UPDATE_OFF;
}
SetPrimaryDynamicUpdateComboVal(nAllowsDynamicUpdateSaved);
ChangeUIControlHelper(GetPrimaryDynamicUpdateStatic(), m_bIsPrimary);
ChangeUIControlHelper(GetPrimaryDynamicUpdateCombo(), m_bIsPrimary);
ChangeUIControlHelper(GetPrimaryDynamicWarningText(), m_bIsPrimary);
ChangeUIControlHelper(GetPrimaryDynamicWarningIcon(), m_bIsPrimary);
//
// change secondary zone controls
//
GetIPLabel()->ShowWindow(!m_bIsPrimary);
GetIPLabel()->EnableWindow(!m_bIsPrimary);
m_mastersEditor.ShowUI(!m_bIsPrimary);
CButton* pBrowseButton = GetMastersBrowseButton();
pBrowseButton->ShowWindow(!m_bIsPrimary);
pBrowseButton->EnableWindow(!m_bIsPrimary);
CButton* pFindMastersNamesButton = GetFindMastersNamesButton();
pFindMastersNamesButton->ShowWindow(!m_bIsPrimary);
pFindMastersNamesButton->EnableWindow(!m_bIsPrimary && m_mastersEditor.GetCount()>0);
GetDlgItem(IDC_LOCAL_LIST_CHECK)->EnableWindow(m_bIsStub && !bNotDSIntegrated);
GetDlgItem(IDC_LOCAL_LIST_CHECK)->ShowWindow(m_bIsStub && !bNotDSIntegrated);
GetDlgItem(IDC_AGING_STATIC)->EnableWindow(m_bIsPrimary);
GetDlgItem(IDC_AGING_STATIC)->ShowWindow(m_bIsPrimary);
GetDlgItem(IDC_AGING_BUTTON)->EnableWindow(m_bIsPrimary);
GetDlgItem(IDC_AGING_BUTTON)->ShowWindow(m_bIsPrimary);
}
void CDNSZone_GeneralPropertyPage::GetStorageName(CString& szDataStorageName)
{
//
// only for secondary ad for non DS integrated primary)
//
GetFileNameEdit()->GetWindowText(szDataStorageName);
szDataStorageName.TrimLeft();
szDataStorageName.TrimRight();
}
///////////////////////////////////////////////////////////////////////////////
// CDNSZone_ZoneTransferPropertyPage
void CDNSZone_ZoneTransferPropertyPage::CDNSSecondariesIPEditor::OnChangeData()
{
CDNSZone_ZoneTransferPropertyPage* pPage = (CDNSZone_ZoneTransferPropertyPage*)GetParentWnd();
pPage->SetDirty(TRUE);
}
BEGIN_MESSAGE_MAP(CDNSZone_ZoneTransferPropertyPage, CPropertyPageBase)
ON_BN_CLICKED(IDC_CHECK_ALLOW_TRANSFERS, OnRadioSecSecureNone)
ON_BN_CLICKED(IDC_RADIO_SECSECURE_OFF, OnRadioSecSecureOff)
ON_BN_CLICKED(IDC_RADIO_SECSECURE_NS, OnRadioSecSecureNS)
ON_BN_CLICKED(IDC_RADIO_SECSECURE_LIST, OnRadioSecSecureList)
ON_BN_CLICKED(IDC_BUTTON_NOTIFY, OnButtonNotify)
END_MESSAGE_MAP()
CDNSZone_ZoneTransferPropertyPage::CDNSZone_ZoneTransferPropertyPage()
: CPropertyPageBase(IDD_ZONE_ZONE_TRANSFER_PAGE)
{
m_fNotifyLevel = (DWORD)-1;
m_cNotify = 0;
m_aipNotify = NULL;
m_bStub = FALSE;
}
CDNSZone_ZoneTransferPropertyPage::~CDNSZone_ZoneTransferPropertyPage()
{
if (m_aipNotify != NULL)
free(m_aipNotify);
}
BOOL CDNSZone_ZoneTransferPropertyPage::OnSetActive()
{
CDNSZonePropertyPageHolder* pHolder =
(CDNSZonePropertyPageHolder*)GetHolder();
m_bStub = pHolder->IsStubZoneUI();
GetDlgItem(IDC_CHECK_ALLOW_TRANSFERS)->EnableWindow(!m_bStub);
return CPropertyPageBase::OnSetActive();
}
void CDNSZone_ZoneTransferPropertyPage::OnButtonNotify()
{
CDNSZonePropertyPageHolder* pHolder =
(CDNSZonePropertyPageHolder*)GetHolder();
CDNSZoneNode* pZoneNode = pHolder->GetZoneNode();
FIX_THREAD_STATE_MFC_BUG();
CThemeContextActivator activator;
CDNSZoneNotifyDialog dlg(this, pZoneNode->GetZoneType() == DNS_ZONE_TYPE_SECONDARY,
pHolder->GetComponentData());
if (IDOK == dlg.DoModal())
{
//
// the dialog already updated the notify data
//
SetDirty(TRUE);
}
}
void CDNSZone_ZoneTransferPropertyPage::SyncUIRadioHelper(UINT nRadio)
{
BOOL bState = ((CButton*)GetDlgItem(IDC_CHECK_ALLOW_TRANSFERS))->GetCheck();
GetNotifyButton()->EnableWindow(bState);
m_secondariesListEditor.EnableUI(IDC_RADIO_SECSECURE_LIST == nRadio, TRUE);
if (IDC_RADIO_SECSECURE_LIST != nRadio)
m_secondariesListEditor.Clear();
SetDirty(TRUE);
if (IDC_CHECK_ALLOW_TRANSFERS == nRadio)
{
((CButton*)GetDlgItem(IDC_RADIO_SECSECURE_LIST))->EnableWindow(bState);
((CButton*)GetDlgItem(IDC_RADIO_SECSECURE_OFF))->EnableWindow(bState);
((CButton*)GetDlgItem(IDC_RADIO_SECSECURE_NS))->EnableWindow(bState);
BOOL bRadioState = ((CButton*)GetDlgItem(IDC_RADIO_SECSECURE_LIST))->GetCheck();
m_secondariesListEditor.EnableUI(bRadioState && bState, TRUE);
}
}
int CDNSZone_ZoneTransferPropertyPage::SetRadioState(DWORD fSecureSecondaries)
{
int nRadio = 0;
switch (fSecureSecondaries)
{
case ZONE_SECSECURE_NONE:
nRadio = IDC_CHECK_ALLOW_TRANSFERS;
((CButton*)GetDlgItem(IDC_CHECK_ALLOW_TRANSFERS))->SetCheck(FALSE);
break;
case ZONE_SECSECURE_LIST:
nRadio = IDC_RADIO_SECSECURE_LIST;
((CButton*)GetDlgItem(IDC_RADIO_SECSECURE_LIST))->SetCheck(TRUE);
((CButton*)GetDlgItem(IDC_CHECK_ALLOW_TRANSFERS))->SetCheck(TRUE);
break;
case ZONE_SECSECURE_OFF:
nRadio = IDC_RADIO_SECSECURE_OFF;
((CButton*)GetDlgItem(IDC_RADIO_SECSECURE_OFF))->SetCheck(TRUE);
((CButton*)GetDlgItem(IDC_CHECK_ALLOW_TRANSFERS))->SetCheck(TRUE);
break;
case ZONE_SECSECURE_NS:
nRadio = IDC_RADIO_SECSECURE_NS;
((CButton*)GetDlgItem(IDC_RADIO_SECSECURE_NS))->SetCheck(TRUE);
((CButton*)GetDlgItem(IDC_CHECK_ALLOW_TRANSFERS))->SetCheck(TRUE);
break;
}
ASSERT(nRadio != 0);
return nRadio;
}
DWORD CDNSZone_ZoneTransferPropertyPage::GetRadioState()
{
int nRadio = 0;
if (!((CButton*)GetDlgItem(IDC_CHECK_ALLOW_TRANSFERS))->GetCheck())
{
nRadio = IDC_CHECK_ALLOW_TRANSFERS;
}
else
{
if (((CButton*)GetDlgItem(IDC_RADIO_SECSECURE_OFF))->GetCheck())
{
nRadio = IDC_RADIO_SECSECURE_OFF;
}
else if (((CButton*)GetDlgItem(IDC_RADIO_SECSECURE_LIST))->GetCheck())
{
nRadio = IDC_RADIO_SECSECURE_LIST;
}
else if (((CButton*)GetDlgItem(IDC_RADIO_SECSECURE_NS))->GetCheck())
{
nRadio = IDC_RADIO_SECSECURE_NS;
}
}
ASSERT(nRadio != 0);
DWORD fSecureSecondaries = (DWORD)-1;
switch (nRadio)
{
case IDC_CHECK_ALLOW_TRANSFERS:
fSecureSecondaries = ZONE_SECSECURE_NONE;
break;
case IDC_RADIO_SECSECURE_LIST:
fSecureSecondaries = ZONE_SECSECURE_LIST;
break;
case IDC_RADIO_SECSECURE_OFF:
fSecureSecondaries = ZONE_SECSECURE_OFF;
break;
case IDC_RADIO_SECSECURE_NS:
fSecureSecondaries = ZONE_SECSECURE_NS;
break;
}
ASSERT(fSecureSecondaries != (DWORD)-1);
return fSecureSecondaries;
}
BOOL CDNSZone_ZoneTransferPropertyPage::OnInitDialog()
{
//
// NOTE: this control has to be initialized before the
// base class OnInitDialog is called because the
// base class OnInitDialog calls SetUIData() in
// this derived class which uses this control
//
VERIFY(m_secondariesListEditor.Initialize(this,
GetParent(),
IDC_BUTTON_UP,
IDC_BUTTON_DOWN,
IDC_BUTTON_ADD,
IDC_BUTTON_REMOVE,
IDC_IPEDIT,
IDC_LIST));
CPropertyPageBase::OnInitDialog();
CDNSZonePropertyPageHolder* pHolder = (CDNSZonePropertyPageHolder*)GetHolder();
CDNSZoneNode* pZoneNode = pHolder->GetZoneNode();
DWORD fSecureSecondaries;
DWORD cSecondaries;
PIP_ADDRESS aipSecondaries;
ASSERT(m_fNotifyLevel == (DWORD)-1);
ASSERT(m_cNotify == 0);
ASSERT(m_aipNotify == NULL);
pZoneNode->GetSecondariesInfo(&fSecureSecondaries, &cSecondaries, &aipSecondaries,
&m_fNotifyLevel, &m_cNotify, &m_aipNotify);
BOOL bSecondaryZone = pZoneNode->GetZoneType() == DNS_ZONE_TYPE_SECONDARY ||
pZoneNode->GetZoneType() == DNS_ZONE_TYPE_STUB;
if (bSecondaryZone)
{
//
// just to make sure here...
//
ASSERT(m_fNotifyLevel != ZONE_NOTIFY_ALL);
if (m_fNotifyLevel == ZONE_NOTIFY_ALL)
{
m_fNotifyLevel = ZONE_NOTIFY_OFF;
}
}
if ( (m_cNotify > 0) && (m_aipNotify != NULL) )
{
//
// make a deep copy
//
PIP_ADDRESS aipNotifyTemp = (DWORD*) malloc(sizeof(DWORD)*m_cNotify);
if (aipNotifyTemp != NULL)
{
memcpy(aipNotifyTemp, m_aipNotify, sizeof(DWORD)*m_cNotify);
m_aipNotify = aipNotifyTemp;
}
}
if ( (ZONE_SECSECURE_LIST == fSecureSecondaries) && (cSecondaries > 0) )
{
m_secondariesListEditor.AddAddresses(aipSecondaries, cSecondaries);
}
SyncUIRadioHelper(SetRadioState(fSecureSecondaries));
BOOL bListState = ((CButton*)GetDlgItem(IDC_RADIO_SECSECURE_LIST))->GetCheck();
BOOL bAllState = ((CButton*)GetDlgItem(IDC_RADIO_SECSECURE_OFF))->GetCheck();
BOOL bNSState = ((CButton*)GetDlgItem(IDC_RADIO_SECSECURE_NS))->GetCheck();
if (!bAllState && !bListState && !bNSState)
{
((CButton*)GetDlgItem(IDC_RADIO_SECSECURE_OFF))->SetCheck(TRUE);
}
SetDirty(FALSE);
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
BOOL CDNSZone_ZoneTransferPropertyPage::OnApply()
{
CDNSZonePropertyPageHolder* pHolder =
(CDNSZonePropertyPageHolder*)GetHolder();
CDNSZoneNode* pZoneNode = pHolder->GetZoneNode();
// first commit possible zone type transition changes
if (!pHolder->ApplyGeneralPageChanges())
return FALSE;
if (!IsDirty())
return TRUE;
DWORD fSecureSecondaries = GetRadioState();
DWORD cSecondaries = 0;
DWORD* aipSecondaries = NULL;
if (fSecureSecondaries == ZONE_SECSECURE_LIST)
{
cSecondaries = m_secondariesListEditor.GetCount();
aipSecondaries = (cSecondaries > 0) ? (DWORD*) malloc(sizeof(DWORD)*cSecondaries) : NULL;
if (aipSecondaries != NULL && cSecondaries > 0)
{
int nFilled = 0;
m_secondariesListEditor.GetAddresses(aipSecondaries, cSecondaries, &nFilled);
ASSERT(nFilled == (int)cSecondaries);
}
}
BOOL bRet = TRUE;
// write to server
DNS_STATUS err = pZoneNode->ResetSecondaries(fSecureSecondaries, cSecondaries, aipSecondaries,
m_fNotifyLevel, m_cNotify, m_aipNotify);
if (err != 0)
{
DNSErrorDialog(err, IDS_MSG_ZONE_FAIL_UPDATE_ZONE_TRANSFERS);
bRet = FALSE;
}
if (aipSecondaries)
{
free (aipSecondaries);
aipSecondaries = 0;
}
// all went fine
if (bRet)
{
SetDirty(FALSE);
}
return bRet;
}
////////////////////////////////////////////////////////////////////////////
// CDNSZone_SOA_PropertyPage
void CDNS_SOA_SerialNumberEditGroup::OnEditChange()
{
m_pPage->SetDirty(TRUE);
}
void CDNS_SOA_TimeIntervalEditGroup::OnEditChange()
{
m_pPage->SetDirty(TRUE);
}
BEGIN_MESSAGE_MAP(CDNSZone_SOA_PropertyPage, CDNSRecordPropertyPage)
ON_EN_CHANGE(IDC_PRIMARY_SERV_EDIT, OnPrimaryServerChange)
ON_EN_CHANGE(IDC_RESP_PARTY_EDIT, OnResponsiblePartyChange)
ON_EN_CHANGE(IDC_MIN_TTLEDIT, OnMinTTLChange)
ON_BN_CLICKED(IDC_BROWSE_SERV_BUTTON, OnBrowseServer)
ON_BN_CLICKED(IDC_BROWSE_PARTY_BUTTON, OnBrowseResponsibleParty)
END_MESSAGE_MAP()
CDNSZone_SOA_PropertyPage::CDNSZone_SOA_PropertyPage(BOOL bZoneRoot)
: CDNSRecordPropertyPage(IDD_RR_SOA)
{
m_pTempSOARecord = NULL;
m_bZoneRoot = bZoneRoot;
}
CDNSZone_SOA_PropertyPage::~CDNSZone_SOA_PropertyPage()
{
if (m_bZoneRoot && (m_pTempSOARecord != NULL))
delete m_pTempSOARecord;
}
void _DisableDialogControls(HWND hWnd)
{
HWND hWndCurr = ::GetWindow(hWnd, GW_CHILD);
if (hWndCurr != NULL)
{
::ShowWindow(hWndCurr,FALSE);
::EnableWindow(hWndCurr,FALSE);
hWndCurr = ::GetNextWindow(hWndCurr, GW_HWNDNEXT);
while (hWndCurr)
{
::ShowWindow(hWndCurr,FALSE);
::EnableWindow(hWndCurr,FALSE);
hWndCurr = ::GetNextWindow(hWndCurr, GW_HWNDNEXT);
}
}
}
void CDNSZone_SOA_PropertyPage::ShowErrorUI()
{
_DisableDialogControls(m_hWnd);
CStatic* pErrorStatic = GetErrorStatic();
// need to move the error control to the center
CRect r;
pErrorStatic->GetWindowRect(&r);
ScreenToClient(r);
int dx = r.right - r.left;
int dy = r.bottom - r.top;
CRect rThis;
GetClientRect(rThis);
int x = ((rThis.right - rThis.left) - dx)/2;
int y = 4*dy;
r.top = y;
r.bottom = y + dy;
r.left = x;
r.right = x + dx;
pErrorStatic->MoveWindow(r, TRUE);
pErrorStatic->EnableWindow(TRUE);
pErrorStatic->ShowWindow(TRUE);
}
BOOL CDNSZone_SOA_PropertyPage::OnInitDialog()
{
CPropertyPageBase::OnInitDialog();
ASSERT(m_pTempSOARecord == NULL);
// create temporary record
if (m_bZoneRoot)
{
CDNSZonePropertyPageHolder* pHolder = (CDNSZonePropertyPageHolder*)GetHolder();
CDNSZoneNode* pZoneNode = pHolder->GetZoneNode();
if (pZoneNode->HasSOARecord())
{
m_pTempSOARecord = pZoneNode->GetSOARecordCopy();
}
else
{
// something is wrong, need to disable
ShowErrorUI();
}
}
else
{
// we are in the cache here...
CDNSRecordPropertyPageHolder* pHolder = (CDNSRecordPropertyPageHolder*)GetHolder();
m_pTempSOARecord = (CDNS_SOA_Record*)pHolder->GetTempDNSRecord();
}
// initialize controls
m_serialNumberEditGroup.m_pPage = this;
VERIFY(m_serialNumberEditGroup.Initialize(this,
IDC_SERIAL_NUMBER_EDIT,IDC_SERIAL_UP, IDC_SERIAL_DOWN));
m_serialNumberEditGroup.SetRange(0,(UINT)-1);
m_refreshIntervalEditGroup.m_pPage = this;
m_retryIntervalEditGroup.m_pPage = this;
m_expireIntervalEditGroup.m_pPage = this;
m_minTTLIntervalEditGroup.m_pPage = this;
VERIFY(m_refreshIntervalEditGroup.Initialize(this,
IDC_REFR_INT_EDIT, IDC_REFR_INT_COMBO,IDS_TIME_INTERVAL_UNITS));
VERIFY(m_retryIntervalEditGroup.Initialize(this,
IDC_RETRY_INT_EDIT, IDC_RETRY_INT_COMBO,IDS_TIME_INTERVAL_UNITS));
VERIFY(m_expireIntervalEditGroup.Initialize(this,
IDC_EXP_INT_EDIT, IDC_EXP_INT_COMBO,IDS_TIME_INTERVAL_UNITS));
VERIFY(m_minTTLIntervalEditGroup.Initialize(this,
IDC_MINTTL_INT_EDIT, IDC_MINTTL_INT_COMBO, IDS_TIME_INTERVAL_UNITS));
HWND dialogHwnd = GetSafeHwnd();
// Disable IME support on the controls
ImmAssociateContext(::GetDlgItem(dialogHwnd, IDC_REFR_INT_EDIT), NULL);
ImmAssociateContext(::GetDlgItem(dialogHwnd, IDC_RETRY_INT_EDIT), NULL);
ImmAssociateContext(::GetDlgItem(dialogHwnd, IDC_EXP_INT_EDIT), NULL);
ImmAssociateContext(::GetDlgItem(dialogHwnd, IDC_MINTTL_INT_EDIT), NULL);
ImmAssociateContext(::GetDlgItem(dialogHwnd, IDC_SERIAL_NUMBER_EDIT), NULL);
// load data
SetUIData();
if (!m_bZoneRoot)
{
// we are in the cache here...
EnableDialogControls(m_hWnd, FALSE);
}
SetDirty(FALSE);
return TRUE;
}
BOOL CDNSZone_SOA_PropertyPage::OnApply()
{
if (!IsDirty())
{
return TRUE;
}
DNS_STATUS err = 0;
if (m_bZoneRoot)
{
//
// we are in a real zone
//
CDNSZonePropertyPageHolder* pHolder = (CDNSZonePropertyPageHolder*)GetHolder();
ASSERT(!pHolder->IsWizardMode());
//
// first commit possible zone type transition changes
//
if (!pHolder->ApplyGeneralPageChanges())
{
return FALSE;
}
if ((m_pTempSOARecord == NULL) || !IsDirty() || !pHolder->IsPrimaryZoneUI())
{
return TRUE;
}
//
// No need to verify success here because we don't return anything that isn't valid
//
err = GetUIDataEx(FALSE);
if (err != 0)
{
return FALSE;
}
err = pHolder->NotifyConsole(this);
}
else
{
//
// we are in the cache, that is read only...
//
return TRUE;
}
if (err != 0)
{
DNSErrorDialog(err,IDS_MSG_ZONE_SOA_UPDATE_FAILED);
return FALSE;
}
else
{
SetUIData();
SetDirty(FALSE);
}
return TRUE; // all is cool
}
BOOL CDNSZone_SOA_PropertyPage::OnPropertyChange(BOOL, long*)
{
ASSERT(m_pTempSOARecord != NULL);
if (m_pTempSOARecord == NULL)
return FALSE;
DNS_STATUS err = 0;
if (m_bZoneRoot)
{
CDNSZonePropertyPageHolder* pHolder = (CDNSZonePropertyPageHolder*)GetHolder();
err = pHolder->GetZoneNode()->UpdateSOARecord(m_pTempSOARecord, NULL);
}
else
{
ASSERT(FALSE);
}
if (err != 0)
GetHolder()->SetError(err);
return (err == 0);
}
void CDNSZone_SOA_PropertyPage::SetUIData()
{
CDNS_SOA_Record* pRecord = m_pTempSOARecord;
if (pRecord == NULL)
return;
GetPrimaryServerEdit()->SetWindowText(pRecord->m_szNamePrimaryServer);
GetResponsiblePartyEdit()->SetWindowText(pRecord->m_szResponsibleParty);
m_serialNumberEditGroup.SetVal(pRecord->m_dwSerialNo);
m_refreshIntervalEditGroup.SetVal(pRecord->m_dwRefresh);
m_retryIntervalEditGroup.SetVal(pRecord->m_dwRetry);
m_expireIntervalEditGroup.SetVal(pRecord->m_dwExpire);
m_minTTLIntervalEditGroup.SetVal(pRecord->m_dwMinimumTtl);
GetTTLCtrl()->SetTTL(pRecord->m_dwTtlSeconds);
if (m_bZoneRoot)
{
CDNSZonePropertyPageHolder* pHolder = (CDNSZonePropertyPageHolder*)GetHolder();
EnableDialogControls(m_hWnd, pHolder->IsPrimaryZoneUI());
}
}
DNS_STATUS CDNSZone_SOA_PropertyPage::GetUIDataEx(BOOL)
{
DNS_STATUS err = 0;
CDNS_SOA_Record* pRecord = m_pTempSOARecord;
if (pRecord == NULL)
return err;
GetPrimaryServerEdit()->GetWindowText(pRecord->m_szNamePrimaryServer);
GetResponsiblePartyEdit()->GetWindowText(pRecord->m_szResponsibleParty);
//
// Check to see if the Responsible Party field contains an '@'
//
if (-1 != pRecord->m_szResponsibleParty.Find(L'@'))
{
UINT nResult = DNSMessageBox(IDS_MSG_RESPONSIBLE_PARTY_CONTAINS_AT, MB_YESNOCANCEL | MB_ICONWARNING);
if (IDYES == nResult)
{
//
// Replace '@' with '.'
//
pRecord->m_szResponsibleParty.Replace(L'@', L'.');
}
else if (IDCANCEL == nResult)
{
//
// Don't make any changes but don't let the apply continue
//
err = DNS_ERROR_INVALID_NAME_CHAR;
}
else
{
//
// We will allow IDNO to continue to set the responsible party with the '@'
//
err = 0;
}
}
pRecord->m_dwSerialNo = m_serialNumberEditGroup.GetVal();
pRecord->m_dwRefresh = m_refreshIntervalEditGroup.GetVal();
pRecord->m_dwRetry = m_retryIntervalEditGroup.GetVal();
pRecord->m_dwExpire = m_expireIntervalEditGroup.GetVal();
pRecord->m_dwMinimumTtl = m_minTTLIntervalEditGroup.GetVal();
GetTTLCtrl()->GetTTL(&(pRecord->m_dwTtlSeconds));
return err;
}
void CDNSZone_SOA_PropertyPage::OnPrimaryServerChange()
{
SetDirty(TRUE);
}
void CDNSZone_SOA_PropertyPage::OnResponsiblePartyChange()
{
SetDirty(TRUE);
}
void CDNSZone_SOA_PropertyPage::OnMinTTLChange()
{
SetDirty(TRUE);
}
void CDNSZone_SOA_PropertyPage::OnBrowseServer()
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
FIX_THREAD_STATE_MFC_BUG();
CThemeContextActivator activator;
CDNSBrowserDlg dlg(GetHolder()->GetComponentData(), GetHolder(), RECORD_A_AND_CNAME);
if (IDOK == dlg.DoModal())
{
CEdit* pEdit = GetPrimaryServerEdit();
pEdit->SetWindowText(dlg.GetSelectionString());
}
}
void CDNSZone_SOA_PropertyPage::OnBrowseResponsibleParty()
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
FIX_THREAD_STATE_MFC_BUG();
CThemeContextActivator activator;
CDNSBrowserDlg dlg(GetHolder()->GetComponentData(), GetHolder(), RECORD_RP);
if (IDOK == dlg.DoModal())
{
CEdit* pEdit = GetResponsiblePartyEdit();
pEdit->SetWindowText(dlg.GetSelectionString());
}
}
////////////////////////////////////////////////////////////////////////////
// CWinsAdvancedDialog
class CWinsAdvancedDialog : public CHelpDialog
{
public:
CWinsAdvancedDialog(CPropertyPageHolderBase* pHolder, BOOL bReverse);
// data
BOOL m_bNetBios;
DWORD m_dwLookupTimeout;
DWORD m_dwCacheTimeout;
protected:
virtual BOOL OnInitDialog();
virtual void OnOK();
virtual void OnCancel();
DECLARE_MESSAGE_MAP()
private:
CPropertyPageHolderBase* m_pHolder;
BOOL m_bReverse;
CButton* GetNetBiosCheck()
{ return (CButton*)GetDlgItem(IDC_NETBIOS_CHECK);}
CDNSTTLControl* GetCacheTimeoutTTLCtrl()
{ return (CDNSTTLControl*)GetDlgItem(IDC_CACHE_TIMEOUT_TTLEDIT);}
CDNSTTLControl* GetLookupTimeoutTTLCtrl()
{ return (CDNSTTLControl*)GetDlgItem(IDC_LOOKUP_TIMEOUT_TTLEDIT);}
};
BEGIN_MESSAGE_MAP(CWinsAdvancedDialog, CHelpDialog)
END_MESSAGE_MAP()
CWinsAdvancedDialog::CWinsAdvancedDialog(CPropertyPageHolderBase* pHolder,
BOOL bReverse)
: CHelpDialog(IDD_ZONE_WINS_ADVANCED, pHolder->GetComponentData())
{
ASSERT(pHolder != NULL);
m_pHolder = pHolder;
m_bReverse = bReverse;
m_bNetBios = FALSE;
m_dwLookupTimeout = 0x0;
m_dwCacheTimeout = 0x0;
}
BOOL CWinsAdvancedDialog::OnInitDialog()
{
CHelpDialog::OnInitDialog();
m_pHolder->PushDialogHWnd(GetSafeHwnd());
if (m_bReverse)
{
GetNetBiosCheck()->SetCheck(m_bNetBios);
}
else
{
GetNetBiosCheck()->EnableWindow(FALSE);
GetNetBiosCheck()->ShowWindow(FALSE);
}
GetCacheTimeoutTTLCtrl()->SetTTL(m_dwCacheTimeout);
GetLookupTimeoutTTLCtrl()->SetTTL(m_dwLookupTimeout);
return TRUE; // return TRUE unless you set the focus to a control
}
void CWinsAdvancedDialog::OnCancel()
{
ASSERT(m_pHolder != NULL);
m_pHolder->PopDialogHWnd();
CHelpDialog::OnCancel();
}
void CWinsAdvancedDialog::OnOK()
{
if (m_bReverse)
{
m_bNetBios = GetNetBiosCheck()->GetCheck();
}
GetCacheTimeoutTTLCtrl()->GetTTL(&m_dwCacheTimeout);
GetLookupTimeoutTTLCtrl()->GetTTL(&m_dwLookupTimeout);
ASSERT(m_pHolder != NULL);
m_pHolder->PopDialogHWnd();
CHelpDialog::OnOK();
}
////////////////////////////////////////////////////////////////////////////
// CDNSZone_WINSBase_PropertyPage
BEGIN_MESSAGE_MAP(CDNSZone_WINSBase_PropertyPage, CDNSRecordPropertyPage)
ON_BN_CLICKED(IDC_USE_WINS_RES_CHECK, OnUseWinsResolutionChange)
ON_BN_CLICKED(IDC_NOT_REPL_CHECK, OnDoNotReplicateChange)
END_MESSAGE_MAP()
CDNSZone_WINSBase_PropertyPage::CDNSZone_WINSBase_PropertyPage(UINT nIDTemplate)
: CDNSRecordPropertyPage(nIDTemplate)
{
m_pTempRecord = NULL;
m_action = none;
m_iWINSMsg = 0;
}
CDNSZone_WINSBase_PropertyPage::~CDNSZone_WINSBase_PropertyPage()
{
if (m_pTempRecord != NULL)
delete m_pTempRecord;
}
BOOL CDNSZone_WINSBase_PropertyPage::OnPropertyChange(BOOL, long*)
{
ASSERT(m_action != none);
ASSERT(m_pTempRecord != NULL);
if (m_pTempRecord == NULL)
return FALSE;
CComponentDataObject* pComponentData = GetZoneHolder()->GetComponentData();
DNS_STATUS err = 0;
if (IsValidTempRecord())
{
switch(m_action)
{
case remove:
err = GetZoneNode()->DeleteWINSRecord(pComponentData);
break;
case add:
err = GetZoneNode()->CreateWINSRecord(m_pTempRecord, pComponentData);
break;
case edit:
err = GetZoneNode()->UpdateWINSRecord(m_pTempRecord, pComponentData);
break;
}
}
else
{
if (m_action == remove)
{
err = GetZoneNode()->DeleteWINSRecord(pComponentData);
}
else
{
err = ERROR_INVALID_DATA;
}
}
if (err != 0)
GetZoneHolder()->SetError(err);
return (err == 0);
}
CDNSZoneNode* CDNSZone_WINSBase_PropertyPage::GetZoneNode()
{
return GetZoneHolder()->GetZoneNode();
}
BOOL CDNSZone_WINSBase_PropertyPage::OnInitDialog()
{
CPropertyPageBase::OnInitDialog();
CDNSRootData* pRootData = (CDNSRootData*)GetHolder()->GetComponentData()->GetRootData();
ASSERT(pRootData != NULL);
EnableTTLCtrl(pRootData->IsAdvancedView());
BOOL bUseWins = GetZoneNode()->HasWinsRecord();
// unabe disable the WINS checkbox
GetUseWinsCheck()->SetCheck(bUseWins);
// get new temporary record
if (bUseWins)
m_pTempRecord = GetZoneNode()->GetWINSRecordCopy();
else
m_pTempRecord = GetZoneNode()->IsReverse() ?
(CDNSRecord*)(new CDNS_NBSTAT_Record) : (CDNSRecord*)(new CDNS_WINS_Record);
ASSERT(m_pTempRecord != NULL);
SetUIData();
SetDirty(FALSE);
// EnableUI(bUseWins);
return TRUE;
}
BOOL CDNSZone_WINSBase_PropertyPage::OnSetActive()
{
BOOL bRet = CDNSRecordPropertyPage::OnSetActive();
if (bRet)
{
CDNSZonePropertyPageHolder* pHolder = (CDNSZonePropertyPageHolder*)GetHolder();
m_bPrimaryZone = pHolder->IsPrimaryZoneUI();
m_bStub = pHolder->IsStubZoneUI();
CDNS_WINS_Record* pRecord = (CDNS_WINS_Record*)m_pTempRecord;
if (pRecord)
{
m_bLocalRecord = (pRecord->m_dwMappingFlag & DNS_WINS_FLAG_LOCAL);
}
BOOL bUseWins = GetZoneNode()->HasWinsRecord();
if (bUseWins && m_bLocalRecord)
{
m_nState = wins_local_state;
}
else if (bUseWins && !m_bLocalRecord)
{
m_nState = wins_not_local_state;
}
else // (!bUseWins && !m_bLocalRecord) || (!bUseWins && m_bLocalRecord)
{
m_nState = no_wins_state;
}
EnableUI();
CString szCheckText;
if (m_bPrimaryZone)
{
m_nReplCheckTextID = IDS_CHECK_TEXT_NOT_REPLICATE;
}
szCheckText.LoadString(m_nReplCheckTextID);
GetDoNotReplicateCheck()->SetWindowText((LPWSTR)(LPCWSTR)szCheckText);
}
return bRet;
}
BOOL CDNSZone_WINSBase_PropertyPage::OnApply()
{
CDNSZonePropertyPageHolder* pHolder =
(CDNSZonePropertyPageHolder*)GetHolder();
// first commit possible zone type transition changes
if (!pHolder->ApplyGeneralPageChanges())
return FALSE;
BOOL bUseWins = GetZoneNode()->HasWinsRecord(); // current state in the zone
BOOL bNewUseWins = GetUseWinsCheck()->GetCheck(); // current state in the UI
if (bUseWins && !bNewUseWins)
{
m_action = remove;
}
else if (!bUseWins && bNewUseWins)
{
m_action = add;
}
else if (bUseWins && bNewUseWins && IsDirty())
{
m_action = edit;
}
if (m_action == none)
return TRUE;
// No need to verify the return value here because we don't return anything except success
DNS_STATUS err = GetUIDataEx(FALSE);
if (err != 0)
{
ASSERT(FALSE);
return (err == 0);
}
err = GetZoneHolder()->NotifyConsole(this);
if (err != 0)
{
DNSErrorDialog(err, m_iWINSMsg);
}
else
{
// reset dirty flag!!!
}
m_action = none;
return (err == 0);
}
void CDNSZone_WINSBase_PropertyPage::OnUseWinsResolutionChange()
{
SetDirty(TRUE);
if (m_bPrimaryZone)
{
EnableUI(GetUseWinsCheck()->GetCheck());
}
else
{
switch (m_nState)
{
case wins_local_state :
#ifdef DBG
ASSERT(!GetUseWinsCheck()->GetCheck());
ASSERT(GetUseWinsCheck()->IsWindowEnabled());
ASSERT(GetDoNotReplicateCheck()->GetCheck());
ASSERT(!GetDoNotReplicateCheck()->IsWindowEnabled());
#endif
m_nState = no_wins_state;
break;
case wins_not_local_state : // should never happen
#ifdef DBG
ASSERT(FALSE);
#endif
break;
case no_wins_state :
#ifdef DBG
ASSERT(GetUseWinsCheck()->GetCheck());
ASSERT(GetUseWinsCheck()->IsWindowEnabled());
ASSERT(GetDoNotReplicateCheck()->GetCheck());
ASSERT(!GetDoNotReplicateCheck()->IsWindowEnabled());
#endif
m_nState = wins_local_state;
break;
default : // illegal state
#ifdef DBG
ASSERT(FALSE);
#endif
break;
}
EnableUI();
}
}
void CDNSZone_WINSBase_PropertyPage::OnDoNotReplicateChange()
{
SetDirty(TRUE);
if (!m_bPrimaryZone)
{
switch (m_nState)
{
case wins_local_state : // should never happen
#ifdef DBG
ASSERT(FALSE);
#endif
break;
case wins_not_local_state :
#ifdef DBG
ASSERT(GetUseWinsCheck()->GetCheck());
ASSERT(!GetUseWinsCheck()->IsWindowEnabled());
ASSERT(GetDoNotReplicateCheck()->GetCheck());
ASSERT(GetDoNotReplicateCheck()->IsWindowEnabled());
#endif
m_nState = wins_local_state;
break;
case no_wins_state : // should never happen
#ifdef DBG
ASSERT(FALSE);
#endif
break;
default : // illegal state
#ifdef DBG
ASSERT(FALSE);
#endif
break;
}
EnableUI();
}
}
void CDNSZone_WINSBase_PropertyPage::EnableUI(BOOL bEnable)
{
GetDoNotReplicateCheck()->EnableWindow(bEnable);
GetAdvancedButton()->EnableWindow(bEnable);
GetTTLCtrl()->EnableWindow(bEnable);
}
void CDNSZone_WINSBase_PropertyPage::EnableUI()
{
if (m_bPrimaryZone)
{
GetDlgItem(IDC_USE_WINS_RES_CHECK)->EnableWindow(TRUE);
if (!IsDirty())
{
EnableUI(GetZoneNode()->HasWinsRecord());
}
}
else if (m_bStub)
{
GetDlgItem(IDC_USE_WINS_RES_CHECK)->EnableWindow(FALSE);
EnableUI(FALSE);
}
else //secondary
{
GetDlgItem(IDC_USE_WINS_RES_CHECK)->EnableWindow(TRUE);
switch (m_nState)
{
case wins_local_state :
GetDoNotReplicateCheck()->SetCheck(TRUE);
GetDoNotReplicateCheck()->EnableWindow(FALSE);
GetUseWinsCheck()->SetCheck(TRUE);
GetUseWinsCheck()->EnableWindow(TRUE);
GetTTLCtrl()->EnableWindow(TRUE);
GetAdvancedButton()->EnableWindow(TRUE);
break;
case wins_not_local_state :
GetDoNotReplicateCheck()->SetCheck(FALSE);
GetDoNotReplicateCheck()->EnableWindow(TRUE);
GetUseWinsCheck()->SetCheck(TRUE);
GetUseWinsCheck()->EnableWindow(FALSE);
GetTTLCtrl()->EnableWindow(FALSE);
GetAdvancedButton()->EnableWindow(FALSE);
break;
case no_wins_state :
GetDoNotReplicateCheck()->SetCheck(TRUE);
GetDoNotReplicateCheck()->EnableWindow(FALSE);
GetUseWinsCheck()->SetCheck(FALSE);
GetUseWinsCheck()->EnableWindow(TRUE);
GetTTLCtrl()->EnableWindow(FALSE);
GetAdvancedButton()->EnableWindow(FALSE);
break;
default : // Illegal state
break;
}
}
}
void CDNSZone_WINSBase_PropertyPage::SetUIData()
{
GetTTLCtrl()->SetTTL(m_pTempRecord->m_dwTtlSeconds);
}
DNS_STATUS CDNSZone_WINSBase_PropertyPage::GetUIDataEx(BOOL)
{
GetTTLCtrl()->GetTTL(&(m_pTempRecord->m_dwTtlSeconds));
return 0;
}
////////////////////////////////////////////////////////////////////////////
// CDNSZone_WINS_PropertyPage
void CDNSZone_WINS_WinsServersIPEditor::OnChangeData()
{
CDNSZone_WINS_PropertyPage* pPage =
(CDNSZone_WINS_PropertyPage*)GetParentWnd();
pPage->SetDirty(TRUE);
}
BEGIN_MESSAGE_MAP(CDNSZone_WINS_PropertyPage, CDNSZone_WINSBase_PropertyPage)
ON_BN_CLICKED(IDC_ADVANCED_BUTTON, OnAdvancedButton)
END_MESSAGE_MAP()
CDNSZone_WINS_PropertyPage::CDNSZone_WINS_PropertyPage()
: CDNSZone_WINSBase_PropertyPage(IDD_ZONE_WINS_PAGE)
{
m_iWINSMsg = IDS_MSG_ZONE_WINS_FAILED;
m_nReplCheckTextID = IDS_CHECK_TEXT_USE_LOCAL_WINS;
m_bStub = FALSE;
}
BOOL CDNSZone_WINS_PropertyPage::OnInitDialog()
{
//
// NOTE: this control has to be initialized before the
// base class OnInitDialog is called because the
// base class OnInitDialog calls SetUIData() in
// this derived class which uses this control
//
VERIFY(m_winsServersEditor.Initialize(this,
GetParent(),
IDC_BUTTON_UP,
IDC_BUTTON_DOWN,
IDC_BUTTON_ADD,
IDC_BUTTON_REMOVE,
IDC_IPEDIT,
IDC_LIST));
CDNSZone_WINSBase_PropertyPage::OnInitDialog();
return TRUE;
}
void CDNSZone_WINS_PropertyPage::EnableUI(BOOL bEnable)
{
CDNSZone_WINSBase_PropertyPage::EnableUI(bEnable);
m_winsServersEditor.EnableUI(bEnable);
GetDlgItem(IDC_IP_STATIC)->EnableWindow(bEnable);
}
void CDNSZone_WINS_PropertyPage::EnableUI()
{
CDNSZone_WINSBase_PropertyPage::EnableUI();
if (m_bPrimaryZone)
{
if (!IsDirty())
{
m_winsServersEditor.EnableUI(GetZoneNode()->HasWinsRecord());
GetDlgItem(IDC_IP_STATIC)->EnableWindow(GetZoneNode()->HasWinsRecord());
}
}
else // secondary zone
{
switch (m_nState)
{
case wins_local_state :
m_winsServersEditor.EnableUI(TRUE);
GetDlgItem(IDC_IP_STATIC)->EnableWindow(FALSE);
break;
case wins_not_local_state :
case no_wins_state :
m_winsServersEditor.EnableUI(FALSE);
GetDlgItem(IDC_IP_STATIC)->EnableWindow(FALSE);
break;
default : // Illegal state
break;
}
}
}
BOOL CDNSZone_WINS_PropertyPage::IsValidTempRecord()
{
CDNS_WINS_Record* pRecord = (CDNS_WINS_Record*)m_pTempRecord;
return (pRecord->m_nWinsServerCount > 0);
}
void CDNSZone_WINS_PropertyPage::SetUIData()
{
CDNSZone_WINSBase_PropertyPage::SetUIData();
CDNS_WINS_Record* pRecord = (CDNS_WINS_Record*)m_pTempRecord;
GetDoNotReplicateCheck()->SetCheck(pRecord->m_dwMappingFlag & DNS_WINS_FLAG_LOCAL);
m_winsServersEditor.Clear();
if (pRecord->m_nWinsServerCount > 0)
{
DWORD* pTemp = (DWORD*)malloc(sizeof(DWORD)*pRecord->m_nWinsServerCount);
if (pTemp)
{
for (int k=0; k< pRecord->m_nWinsServerCount; k++)
{
pTemp[k] = pRecord->m_ipWinsServersArray[k];
}
m_winsServersEditor.AddAddresses(pTemp, pRecord->m_nWinsServerCount);
free(pTemp);
pTemp = 0;
}
}
}
DNS_STATUS CDNSZone_WINS_PropertyPage::GetUIDataEx(BOOL bSilent)
{
DNS_STATUS err = CDNSZone_WINSBase_PropertyPage::GetUIDataEx(bSilent);
CDNS_WINS_Record* pRecord = (CDNS_WINS_Record*)m_pTempRecord;
pRecord->m_dwMappingFlag = GetDoNotReplicateCheck()->GetCheck() ?
pRecord->m_dwMappingFlag |= DNS_WINS_FLAG_LOCAL :
pRecord->m_dwMappingFlag &= ~DNS_WINS_FLAG_LOCAL;
pRecord->m_nWinsServerCount = m_winsServersEditor.GetCount();
if (pRecord->m_nWinsServerCount > 0)
{
DWORD* pTemp = (DWORD*)malloc(sizeof(DWORD)*pRecord->m_nWinsServerCount);
if (pTemp)
{
int nFilled;
m_winsServersEditor.GetAddresses(pTemp, pRecord->m_nWinsServerCount, &nFilled);
ASSERT(nFilled == pRecord->m_nWinsServerCount);
for (int k=0; k<nFilled; k++)
pRecord->m_ipWinsServersArray.SetAtGrow(k, pTemp[k]);
free(pTemp);
pTemp = 0;
}
else
{
err = ERROR_OUTOFMEMORY;
}
}
return err;
}
void CDNSZone_WINS_PropertyPage::OnAdvancedButton()
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
FIX_THREAD_STATE_MFC_BUG();
CThemeContextActivator activator;
CDNS_WINS_Record* pRecord = (CDNS_WINS_Record*)m_pTempRecord;
CWinsAdvancedDialog dlg(GetHolder(), FALSE);
dlg.m_dwLookupTimeout = pRecord->m_dwLookupTimeout;
dlg.m_dwCacheTimeout = pRecord->m_dwCacheTimeout;
if (IDOK == dlg.DoModal() )
{
pRecord->m_dwLookupTimeout = dlg.m_dwLookupTimeout;
pRecord->m_dwCacheTimeout = dlg.m_dwCacheTimeout;
SetDirty(TRUE);
}
}
////////////////////////////////////////////////////////////////////////////
// CDNSZone_NBSTAT_PropertyPage
BEGIN_MESSAGE_MAP(CDNSZone_NBSTAT_PropertyPage, CDNSZone_WINSBase_PropertyPage)
ON_EN_CHANGE(IDC_DOMAIN_NAME_EDIT, OnDomainNameEditChange)
ON_BN_CLICKED(IDC_ADVANCED_BUTTON, OnAdvancedButton)
END_MESSAGE_MAP()
CDNSZone_NBSTAT_PropertyPage::CDNSZone_NBSTAT_PropertyPage()
: CDNSZone_WINSBase_PropertyPage(IDD_ZONE_NBSTAT_PAGE)
{
m_iWINSMsg = IDS_MSG_ZONE_NBSTAT_FAILED;
m_nReplCheckTextID = IDS_CHECK_TEXT_USE_LOCAL_WINSR;
}
void CDNSZone_NBSTAT_PropertyPage::OnDomainNameEditChange()
{
SetDirty(TRUE);
}
void CDNSZone_NBSTAT_PropertyPage::EnableUI(BOOL bEnable)
{
CDNSZone_WINSBase_PropertyPage::EnableUI(bEnable);
GetDomainNameEdit()->EnableWindow(bEnable);
}
void CDNSZone_NBSTAT_PropertyPage::EnableUI()
{
CDNSZone_WINSBase_PropertyPage::EnableUI();
if (m_bPrimaryZone)
{
GetDlgItem(IDC_USE_WINS_RES_CHECK)->EnableWindow(TRUE);
GetDomainNameEdit()->EnableWindow(GetZoneNode()->HasWinsRecord());
}
else if (m_bStub)
{
GetDlgItem(IDC_USE_WINS_RES_CHECK)->EnableWindow(FALSE);
EnableUI(FALSE);
}
else // secondary zone
{
GetDlgItem(IDC_USE_WINS_RES_CHECK)->EnableWindow(TRUE);
switch (m_nState)
{
case wins_local_state :
GetDomainNameEdit()->EnableWindow(TRUE);
break;
case wins_not_local_state :
GetDomainNameEdit()->EnableWindow(FALSE);
break;
case no_wins_state :
GetDomainNameEdit()->EnableWindow(FALSE);
break;
default : // Illegal state
break;
}
}
}
BOOL CDNSZone_NBSTAT_PropertyPage::IsValidTempRecord()
{
CDNS_NBSTAT_Record* pRecord = (CDNS_NBSTAT_Record*)m_pTempRecord;
CString szTemp = pRecord->m_szNameResultDomain;
szTemp.TrimLeft();
szTemp.TrimRight();
return (!szTemp.IsEmpty());
}
void CDNSZone_NBSTAT_PropertyPage::SetUIData()
{
CDNSZone_WINSBase_PropertyPage::SetUIData();
CDNS_NBSTAT_Record* pRecord = (CDNS_NBSTAT_Record*)m_pTempRecord;
GetDoNotReplicateCheck()->SetCheck(pRecord->m_dwMappingFlag & DNS_WINS_FLAG_LOCAL);
// strip out the "in-addr.arpa" suffix
CString szTemp = pRecord->m_szNameResultDomain;
//VERIFY(RemoveInAddrArpaSuffix(szTemp.GetBuffer(1)));
//szTemp.ReleaseBuffer();
GetDomainNameEdit()->SetWindowText(szTemp);
}
DNS_STATUS CDNSZone_NBSTAT_PropertyPage::GetUIDataEx(BOOL bSilent)
{
DNS_STATUS err = CDNSZone_WINSBase_PropertyPage::GetUIDataEx(bSilent);
CDNS_NBSTAT_Record* pRecord = (CDNS_NBSTAT_Record*)m_pTempRecord;
pRecord->m_dwMappingFlag = GetDoNotReplicateCheck()->GetCheck() ?
pRecord->m_dwMappingFlag |= DNS_WINS_FLAG_LOCAL :
pRecord->m_dwMappingFlag &= ~DNS_WINS_FLAG_LOCAL;
GetDomainNameEdit()->GetWindowText(pRecord->m_szNameResultDomain);
return err;
}
void CDNSZone_NBSTAT_PropertyPage::OnAdvancedButton()
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
FIX_THREAD_STATE_MFC_BUG();
CThemeContextActivator activator;
CDNS_NBSTAT_Record* pRecord = (CDNS_NBSTAT_Record*)m_pTempRecord;
CWinsAdvancedDialog dlg(GetHolder(), TRUE);
dlg.m_dwLookupTimeout = pRecord->m_dwLookupTimeout;
dlg.m_dwCacheTimeout = pRecord->m_dwCacheTimeout;
dlg.m_bNetBios = pRecord->m_dwMappingFlag & DNS_WINS_FLAG_SCOPE;
if (IDOK == dlg.DoModal())
{
pRecord->m_dwLookupTimeout = dlg.m_dwLookupTimeout;
pRecord->m_dwCacheTimeout = dlg.m_dwCacheTimeout;
pRecord->m_dwMappingFlag = dlg.m_bNetBios ?
pRecord->m_dwMappingFlag |= DNS_WINS_FLAG_SCOPE :
pRecord->m_dwMappingFlag &= ~DNS_WINS_FLAG_SCOPE;
SetDirty(TRUE);
}
}
///////////////////////////////////////////////////////////////////////////////
// CDNSZoneNameServersPropertyPage
BOOL CDNSZoneNameServersPropertyPage::OnSetActive()
{
BOOL bRet = CDNSNameServersPropertyPage::OnSetActive();
if (bRet)
{
CDNSZonePropertyPageHolder* pHolder = (CDNSZonePropertyPageHolder*)GetHolder();
BOOL bReadOnly = !pHolder->IsPrimaryZoneUI();
if (m_bReadOnly != bReadOnly)
{
m_bReadOnly = bReadOnly;
EnableButtons(!m_bReadOnly);
}
}
return bRet;
}
void CDNSZoneNameServersPropertyPage::ReadRecordNodesList()
{
ASSERT(m_pCloneInfoList != NULL);
CDNSZonePropertyPageHolder* pHolder = (CDNSZonePropertyPageHolder*)GetHolder();
CDNSZoneNode* pDomainNode = pHolder->GetZoneNode();
SetDomainNode(pDomainNode);
pDomainNode->GetNSRecordNodesInfo(m_pCloneInfoList);
}
BOOL CDNSZoneNameServersPropertyPage::WriteNSRecordNodesList()
{
ASSERT(m_pCloneInfoList != NULL);
CDNSZonePropertyPageHolder* pHolder = (CDNSZonePropertyPageHolder*)GetHolder();
CDNSZoneNode* pDomainNode = pHolder->GetZoneNode();
return pDomainNode->UpdateNSRecordNodesInfo(m_pCloneInfoList, pHolder->GetComponentData());
}
///////////////////////////////////////////////////////////////////////////////
// CDNSZonePropertyPageHolder
CDNSZonePropertyPageHolder::CDNSZonePropertyPageHolder(CCathegoryFolderNode* pFolderNode,
CDNSZoneNode* pZoneNode, CComponentDataObject* pComponentData)
: CPropertyPageHolderBase(pFolderNode, pZoneNode, pComponentData)
{
ASSERT(pComponentData != NULL);
ASSERT(pFolderNode != NULL);
ASSERT(pFolderNode == GetContainerNode());
ASSERT(pZoneNode != NULL);
ASSERT(pZoneNode == GetZoneNode());
m_bAutoDeletePages = FALSE; // we have the pages as embedded members
int nCurrPage = 0;
m_nGenPage = -1;
m_nSOAPage = -1;
m_nWINSorWINSRPage = -1;
m_nNSPage = -1;
// add pages
m_nGenPage = nCurrPage;
AddPageToList((CPropertyPageBase*)&m_generalPage);
nCurrPage++;
m_nSOAPage = nCurrPage;
AddPageToList((CPropertyPageBase*)&m_SOARecordPage);
nCurrPage++;
m_nNSPage = nCurrPage;
AddPageToList((CPropertyPageBase*)&m_nameServersPage);
nCurrPage++;
if (pZoneNode->IsReverse())
{
m_nWINSorWINSRPage = nCurrPage;
AddPageToList((CPropertyPageBase*)&m_NBSTATRecordPage);
nCurrPage++;
}
else
{
m_nWINSorWINSRPage = nCurrPage;
AddPageToList((CPropertyPageBase*)&m_WINSRecordPage);
nCurrPage++;
}
AddPageToList((CPropertyPageBase*)&m_zoneTransferPage);
// security page added only if needed
m_pAclEditorPage = NULL;
if (pZoneNode->IsDSIntegrated())
{
CString szPath;
pZoneNode->GetServerNode()->CreateDsZoneLdapPath(pZoneNode, szPath);
if (!szPath.IsEmpty())
m_pAclEditorPage = CAclEditorPage::CreateInstance(szPath, this);
}
// determine if we need/can have advanced view
CDNSRootData* pRootData = (CDNSRootData*)pComponentData->GetRootData();
ASSERT(pRootData != NULL);
m_bAdvancedView = pRootData->IsAdvancedView();
}
CDNSZonePropertyPageHolder::~CDNSZonePropertyPageHolder()
{
if (m_pAclEditorPage != NULL)
delete m_pAclEditorPage;
}
int CDNSZonePropertyPageHolder::OnSelectPageMessage(long nPageCode)
{
TRACE(_T("CDNSZonePropertyPageHolder::OnSelectPageMessage()\n"));
switch (nPageCode)
{
case ZONE_HOLDER_GEN:
return m_nGenPage;
case ZONE_HOLDER_SOA:
return m_nSOAPage;
case ZONE_HOLDER_NS:
return m_nNSPage;
case ZONE_HOLDER_WINS:
return m_nWINSorWINSRPage;
}
return -1;
}
HRESULT CDNSZonePropertyPageHolder::OnAddPage(int nPage, CPropertyPageBase*)
{
// add the ACL editor page after the last, if present
if ( (nPage != -1) || (m_pAclEditorPage == NULL) )
return S_OK;
// add the ACLU page
HPROPSHEETPAGE hPage = m_pAclEditorPage->CreatePage();
if (hPage == NULL)
return E_FAIL;
// add the raw HPROPSHEETPAGE to sheet, not in the list
return AddPageToSheetRaw(hPage);
}
|
416a1a3e2cdda2c41ae9f2c4339737217bd83741
|
68e7aa9480fa140af30aa7135ccaf98daebae46d
|
/smtrat/src/lib/modules/CADModule/CADModule.h
|
dce062ecf84c035fc2bcb0410a460e8d04f79cf3
|
[
"MIT"
] |
permissive
|
kperun/SATPrakPDW
|
eb3edf6f3050f3c46541b6fafea382c4a661c16a
|
5d567c7bb5c84468da792388a408595a0849a346
|
refs/heads/master
| 2021-01-19T17:00:24.619155
| 2017-09-02T14:20:07
| 2017-09-02T14:20:07
| 86,146,758
| 4
| 0
| null | 2017-09-02T14:16:37
| 2017-03-25T09:34:07
|
C++
|
UTF-8
|
C++
| false
| false
| 4,629
|
h
|
CADModule.h
|
/**
* @file CADModule.h
*
* @author Ulrich Loup
* @since 2012-02-04
* @version 2013-05-27
*
*/
#pragma once
#include "config.h"
#include "../../solver/Module.h"
#include "../../solver/RuntimeSettings.h"
#include <unordered_map>
#include "carl/cad/CAD.h"
#include "../../datastructures/VariableBounds.h"
#ifdef SMTRAT_DEVOPTION_Statistics
#include "CADStatistics.h"
#endif
#include "CADSettings.h"
namespace smtrat
{
/// Hash function for use of Input::const_iterator in unordered data structures
struct FormulaIteratorHasher
{
size_t operator ()(ModuleInput::const_iterator i) const
{
return i->formula().constraint().id();
}
};
/**
* Module invoking a CAD solver of the GiNaCRA library. The solver is only used with univariate polynomials.
* If a polynomial with more than one variable is added, this module passes it on.
*
* @author Ulrich Loup
* @since 2012-02-04
* @version 2012-11-29
*
*/
template<typename Settings>
class CADModule: public Module
{
typedef std::unordered_map<FormulaT, unsigned> ConstraintIndexMap;
typedef smtrat::vb::VariableBounds< FormulaT > VariableBounds;
////////////////
// ATTRIBUTES //
////////////////
/// The actual CAD object.
carl::CAD<smtrat::Rational> mCAD;
/// The constraints extracted from the passed formulas.
std::vector<carl::cad::Constraint<smtrat::Rational>> mConstraints;
std::map<carl::cad::Constraint<smtrat::Rational>, FormulaT> mCFMap;
/// Indicates if false has been asserted.
bool hasFalse;
/**
* If false has been asserted, new formulas are stored in this list until false is removed.
* This prevents unnecessary add() and remove() operation on the CAD object.
*/
FormulasT mSubformulaQueue;
/// Maps the received formulas to indices within mConstraints.
ConstraintIndexMap mConstraintsMap;
/// A satisfying assignment of the received constraints if existent; otherwise it is empty.
carl::RealAlgebraicPoint<smtrat::Rational> mRealAlgebraicSolution;
/// the conflict graph storing for each last component of all sample points which constraints were satisfied by the point
carl::cad::ConflictGraph<smtrat::Rational> mConflictGraph;
VariableBounds mVariableBounds;
public:
typedef Settings SettingsType;
std::string moduleName() const {
return SettingsType::moduleName;
}
CADModule( const ModuleInput*, RuntimeSettings*, Conditionals&, Manager* const = NULL );
~CADModule();
bool addCore(ModuleInput::const_iterator _subformula);
void removeCore(ModuleInput::const_iterator _subformula);
Answer checkCore();
void updateModel() const;
const VariableBounds& variableBounds () const { return mVariableBounds; }
VariableBounds& rVariableBounds () { return mVariableBounds; }
const ConstraintIndexMap& constraints () const { return mConstraintsMap; }
carl::cad::ConflictGraph<smtrat::Rational> conflictGraph() const { return mConflictGraph; }
const FormulaT& formulaFor(const carl::cad::Constraint<smtrat::Rational>& constraint) const {
auto it = mCFMap.find(constraint);
assert(it != mCFMap.end());
return it->second;
}
private:
bool validateIntegrality(const std::vector<carl::Variable>& vars, std::size_t d) {
if (vars[d].getType() != carl::VariableType::VT_INT) return true;
return carl::isInteger(this->mRealAlgebraicSolution[d].branchingPoint());
}
bool checkIntegerAssignment(const std::vector<carl::Variable>& vars, std::size_t d, bool createBranch) {
if (vars[d].getType() != carl::VariableType::VT_INT) return false;
auto r = this->mRealAlgebraicSolution[d].branchingPoint();
if (createBranch) {
if (!carl::isInteger(r)) {
branchAt(vars[d], r);
return true;
}
return false;
} else {
return !carl::isInteger(r);
}
return false;
}
bool checkSatisfiabilityOfAssignment() const;
bool addConstraintFormula(const FormulaT& f);
const carl::cad::Constraint<smtrat::Rational> convertConstraint(const ConstraintT&);
ConstraintT convertConstraint(const carl::cad::Constraint<smtrat::Rational>&);
const FormulaT& getConstraintAt(unsigned index);
void updateConstraintMap(unsigned index, bool decrement = true);
#ifdef SMTRAT_DEVOPTION_Statistics
CADStatistics* mStats;
#endif
};
} // namespace smtrat
|
01f5e26820557c378e2c30aa8fea29786fb6cc39
|
3d4c7b9c179322e6bdb3c7a0c137919364806cb3
|
/include/flexflow/ops/batch_matmul.h
|
c5b743e1e00cb51b95f53161cad245fd445b073d
|
[
"Apache-2.0"
] |
permissive
|
flexflow/FlexFlow
|
291282d27009924a427966e899d7c2fda9c20cec
|
b2ec6cb5d2b898db1ad4df32adf5699bc48aaac7
|
refs/heads/inference
| 2023-09-04T05:25:02.250225
| 2023-09-03T14:15:07
| 2023-09-03T14:15:07
| 160,988,469
| 1,139
| 186
|
Apache-2.0
| 2023-09-14T17:56:24
| 2018-12-08T23:43:13
|
C++
|
UTF-8
|
C++
| false
| false
| 2,580
|
h
|
batch_matmul.h
|
#ifndef _FLEXFLOW_BATCH_MATMUL_H
#define _FLEXFLOW_BATCH_MATMUL_H
#include "flexflow/model.h"
namespace FlexFlow {
class BatchMatmul : public Op {
public:
using Params = BatchMatmulParams;
using Input = std::pair<ParallelTensor, ParallelTensor>;
BatchMatmul(FFModel &model,
BatchMatmulParams const ¶ms,
Input const &inputs,
char const *name = nullptr);
BatchMatmul(FFModel &model,
const ParallelTensor A,
const ParallelTensor B,
int a_seq_length_dim,
int b_seq_length_dim,
char const *name = nullptr);
static Op *
create_operator_from_layer(FFModel &model,
Layer const *layer,
std::vector<ParallelTensor> const &inputs);
void init(FFModel const &) override;
void forward(FFModel const &) override;
void backward(FFModel const &) override;
void print_layer(FFModel const &model) override;
void serialize(Legion::Serializer &) const override;
static PCG::Node deserialize(FFModel &ff,
Legion::Deserializer &d,
ParallelTensor inputs[],
int num_inputs);
Op *materialize(FFModel &ff,
ParallelTensor inputs[],
int num_inputs) const override;
Params get_params() const;
static OpMeta *init_task(Legion::Task const *task,
std::vector<Legion::PhysicalRegion> const ®ions,
Legion::Context ctx,
Legion::Runtime *runtime);
static void forward_task(Legion::Task const *task,
std::vector<Legion::PhysicalRegion> const ®ions,
Legion::Context ctx,
Legion::Runtime *runtime);
static void backward_task(Legion::Task const *task,
std::vector<Legion::PhysicalRegion> const ®ions,
Legion::Context ctx,
Legion::Runtime *runtime);
bool measure_operator_cost(Simulator *sim,
MachineView const &pc,
CostMetrics &cost_metrics) const override;
private:
template <int NDIM>
void init_with_dim(FFModel const &ff);
template <int NDIM>
void forward_with_dim(FFModel const &ff);
template <int NDIM>
void backward_with_dim(FFModel const &ff);
public:
int a_seq_length_dim, b_seq_length_dim;
};
}; // namespace FlexFlow
#endif
|
3a538ffe002120e454c81905db964fdb75cbaca4
|
b8dc7dee0d6204624c35b48d194dd408bfd26a6c
|
/src/decomposition.h
|
26050141d515c1848ff943ee764e88ea32fb014f
|
[
"MIT"
] |
permissive
|
Laakeri/sharpsat-td
|
bb757c5183b9b58823ddc74f48d2dc092fa8a879
|
b9bb015305ea5d4e1ac7141691d0fe55ca983d31
|
refs/heads/main
| 2023-07-18T18:57:02.769031
| 2021-09-05T16:09:53
| 2021-09-05T16:09:53
| 372,407,764
| 19
| 3
|
NOASSERTION
| 2021-09-05T16:09:54
| 2021-05-31T06:41:13
|
C++
|
UTF-8
|
C++
| false
| false
| 296
|
h
|
decomposition.h
|
#ifndef DECOMPOSITION_H_
#define DECOMPOSITION_H_
#include <vector>
// SharpSAT uses this anyway globally so...
using namespace std;
namespace decomp {
pair<int, vector<int>> ComputeTreewidth(const vector<vector<int>>& graph, double time);
} // namespace decomp
#endif /* DECOMPOSITION_H_ */
|
83a3430ea628138022950e925e0960f1f53f7d6b
|
f3dc6c7cd701bfa97f6aeb9552a4f120cc701aad
|
/de0_nano/software/emg_test/emg_test.cpp
|
3f566355ccb5c01d92f19109ff73f6d79beb2301
|
[] |
no_license
|
grantdhunter/ECE492
|
d847d3c45e8f9b8f946c9a12fd800e629038d906
|
d275f10c8095616302e16598c299a919ef1663dd
|
refs/heads/master
| 2021-01-25T06:06:02.939662
| 2014-04-09T21:37:24
| 2014-04-09T21:37:24
| 15,781,542
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,489
|
cpp
|
emg_test.cpp
|
/*************************************************************************
* Copyright (c) 2004 Altera Corporation, San Jose, California, USA. *
* All rights reserved. All use of this software and documentation is *
* subject to the License Agreement located at the end of this file below.*
**************************************************************************
* Description: *
* The following is a simple hello world program running MicroC/OS-II.The *
* purpose of the design is to be a very simple application that just *
* demonstrates MicroC/OS-II running on NIOS II.The design doesn't account*
* for issues such as checking system call return codes. etc. *
* *
* Requirements: *
* -Supported Example Hardware Platforms *
* Standard *
* Full Featured *
* Low Cost *
* -Supported Development Boards *
* Nios II Development Board, Stratix II Edition *
* Nios Development Board, Stratix Professional Edition *
* Nios Development Board, Stratix Edition *
* Nios Development Board, Cyclone Edition *
* -System Library Settings *
* RTOS Type - MicroC/OS-II *
* Periodic System Timer *
* -Know Issues *
* If this design is run on the ISS, terminal output will take several*
* minutes per iteration. *
**************************************************************************/
#include <stdio.h>
#include "includes.h"
#include "system.h"
#include "emgInterface.h"
/* Definition of Task Stacks */
#define TASK_STACKSIZE 2048
OS_STK task1_stk[TASK_STACKSIZE];
/* Definition of Task Priorities */
#define TASK1_PRIORITY 1
/* Prints "Hello World" and sleeps for three seconds */
void task1(void* pdata)
{
char* adc = DE0_NANO_ADC_0_NAME;
EmgInterface emg(adc, CHANNEL);
volatile uint16_t data = 0;
while (1)
{
data = emg.rawRead()/16;
printf("EMG READS: %u\n", data);
OSTimeDlyHMSM(0, 0, 0, 5);
}
}
/* The main function creates two task and starts multi-tasking */
int main(void)
{
OSTaskCreateExt(task1,
NULL,
&task1_stk[TASK_STACKSIZE-1],
TASK1_PRIORITY,
TASK1_PRIORITY,
task1_stk,
TASK_STACKSIZE,
NULL,
0);
OSStart();
return 0;
}
/******************************************************************************
* *
* License Agreement *
* *
* Copyright (c) 2004 Altera Corporation, San Jose, California, USA. *
* All rights reserved. *
* *
* Permission is hereby granted, free of charge, to any person obtaining a *
* copy of this software and associated documentation files (the "Software"), *
* to deal in the Software without restriction, including without limitation *
* the rights to use, copy, modify, merge, publish, distribute, sublicense, *
* and/or sell copies of the Software, and to permit persons to whom the *
* Software is furnished to do so, subject to the following conditions: *
* *
* The above copyright notice and this permission notice shall be included in *
* all copies or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE *
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *
* DEALINGS IN THE SOFTWARE. *
* *
* This agreement shall be governed in all respects by the laws of the State *
* of California and by the laws of the United States of America. *
* Altera does not recommend, suggest or require that this reference design *
* file be used in conjunction or combination with any other product. *
******************************************************************************/
|
7e54fa00bf51eaad022e9c5674cc7d96dc49bdab
|
42d92daa0d5e71a9ed62e9eb21a5cfbf7191477e
|
/提高班/考核/7.cpp
|
76332ece4d123d07cb15b79a00924cd24112a39e
|
[] |
no_license
|
luqian2017/haizei-2
|
7223529b697acb2e3a20031965c67905ef795347
|
51b1fe57127f48b1109af0198305f2deaefd549b
|
refs/heads/master
| 2021-10-22T07:09:37.157276
| 2019-03-09T02:07:15
| 2019-03-09T02:07:15
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 533
|
cpp
|
7.cpp
|
#include <iostream>
#include <stdio.h>
#include <math.h>
#define max_n 1000000
#define INF 0x3f3f3f3f
using namespace std;
int dp[max_n + 5] = {0};
int sum[max_n + 5] = {0};
int main()
{
int n, M;
cin >> n >> M;
for (int i = 1; i <= n; i++) cin >> sum[i], sum[i] += sum[i - 1];
for (int i = 1; i <= n; i++) {
dp[i] = INF;
for (int j = 0; j < i; j++) {
dp[i] = min(dp[i], dp[j] + (sum[i] - sum[j])*(sum[i] - sum[j]) + M);
}
}
cout << dp[n] << endl;;
return 0;
}
|
22c92c8742b0bf9ef8577e242d77223edd3104f2
|
0aef26863f142bef75a0e4aaf7da76fc95e3d8ae
|
/crypto_aead/seakeyakv2/refnew/Motorist.h
|
dcdf91f4b15366f157c1f1fb0441a0e92b7be06a
|
[] |
no_license
|
jedisct1/supercop
|
94e5afadc56ef650d7029774a6b05cfe2af54738
|
7c27338ee73a2bd642ba3359faaec395914175a2
|
refs/heads/master
| 2023-08-02T20:12:39.321029
| 2023-05-30T03:03:48
| 2023-05-30T03:03:48
| 179,046,113
| 23
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,349
|
h
|
Motorist.h
|
/*
Implementation by the Keccak, Keyak and Ketje Teams, namely, Guido Bertoni,
Joan Daemen, Michaël Peeters, Gilles Van Assche and Ronny Van Keer, hereby
denoted as "the implementer".
For more information, feedback or questions, please refer to our websites:
http://keccak.noekeon.org/
http://keyak.noekeon.org/
http://ketje.noekeon.org/
To the extent possible under law, the implementer has waived all copyright
and related or neighboring rights to the source code in this file.
http://creativecommons.org/publicdomain/zero/1.0/
*/
#ifndef _MOTORIST_H_
#define _MOTORIST_H_
#include <iostream>
#include <memory>
#include <sstream>
#include <vector>
#include "Keccak-f.h"
#include "types.h"
using namespace std;
class Piston {
protected:
const Permutation *f;
auto_ptr<UINT8> state;
unsigned int Rs, Ra;
unsigned int EOM, CryptEnd, InjectStart, InjectEnd;
unsigned int OmegaC, OmegaI;
public:
Piston(const Permutation *f, unsigned int Rs, unsigned int Ra);
Piston(const Piston& other);
void Crypt(istream& I, ostream& O, bool decryptFlag);
void Inject(istream& X);
void Spark(void);
void GetTag(ostream& T, unsigned int l);
friend ostream& operator<<(ostream& a, const Piston& piston);
};
class Engine {
protected:
vector<Piston>& Pistons;
public:
Engine(vector<Piston>& Pistons);
public:
void Wrap(istream& I, ostream& O, istream& A, bool decryptFlag);
void GetTags(ostream& T, const vector<unsigned int>& l);
void InjectCollective(istream& X, bool diversifyFlag);
friend ostream& operator<<(ostream& a, const Engine& engine);
};
class Motorist {
protected:
unsigned int Pi;
unsigned int W;
unsigned int c;
unsigned int cprime;
unsigned int tau;
vector<Piston> Pistons;
Engine engine;
enum { ready, riding, failed } phase;
public:
Motorist(const Permutation *f, unsigned int Pi, unsigned int W, unsigned int c, unsigned int tau);
bool StartEngine(istream& SUV, bool tagFlag, stringstream& T, bool decryptFlag, bool forgetFlag);
bool Wrap(istream& I, stringstream& O, istream& A, stringstream& T, bool decryptFlag, bool forgetFlag);
protected:
void MakeKnot(void);
bool HandleTag(bool tagFlag, stringstream& T, bool decryptFlag);
public:
friend ostream& operator<<(ostream& a, const Motorist& motorist);
};
#endif
|
ad7ced52623d833ffb5a01b97b4448f25354a7a3
|
b8765e762b1087505189506a35cffce43638fba7
|
/question/BZOJ/3504/x1.cpp
|
5686bcc42b7544225d340111a43ff2f60bcf1b39
|
[] |
no_license
|
yaoling1997/desktop
|
0d0782f44cca18ac97e806e919fc7c6446872a00
|
1053d1a30b1e45e82ceec90cfd3b31eec361c1e2
|
refs/heads/master
| 2022-02-17T12:50:54.349782
| 2019-05-18T06:13:03
| 2019-05-18T06:13:03
| 120,167,243
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,343
|
cpp
|
x1.cpp
|
#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<cstring>
#include<vector>
#include<queue>
using namespace std;
const int maxn= 55,oo= 1e8;
struct edge{
int from,to,cap,flow;
};
vector<edge> edges;
vector<int> g[maxn];
int cur[maxn],vis[maxn],d[maxn];
char ch;
int a1,a2,b1,b2,an,bn,n,flow,s,t,i,j;
void addedge(int from,int to,int cap){
edges.push_back((edge){from,to,cap,0});
edges.push_back((edge){to,from,cap,0});
int m= edges.size();
g[from].push_back(m-2);
g[to].push_back(m-1);
}
bool bfs(){
memset(vis,0,sizeof(vis));
queue<int> Q;vis[s]= 1;
Q.push(s);
while (!Q.empty()){
int u= Q.front(),len= g[u].size(),i;
Q.pop();
for (i= 0;i<len;i++){
edge e= edges[g[u][i]];
if (!vis[e.to]&&e.cap-e.flow){
vis[e.to]= 1;
d[e.to]= d[u]+1;
Q.push(e.to);
}
}
}
return vis[t];
}
int dfs(int o,int re){
if (o==t||!re) return re;
int flow= 0,f,len= g[o].size();
for (int &i= cur[o];i<len;i++){
edge &e= edges[g[o][i]];
if (d[e.to]==d[o]+1&&(f= dfs(e.to,min(re,e.cap-e.flow)))>0){
flow+= f;
re-= f;
e.flow+= f;
edges[g[o][i]^1].flow-= f;
if (!re) break;
}
}return flow;
}
char read(){
char c;
for (;;){
c= getchar();
if (c=='O'||c=='X'||c=='N') return c;
}
}
void init(int n){
int i;
edges.clear();
for (i= 1;i<=n;i++)
g[i].clear();
g[s].clear(),g[t].clear();
flow= 0;
}
void clear(){
int i;
for (i= 1;i<=8;i++){
int u= edges[edges.size()-1].from;
g[u].pop_back();
edges.pop_back();
}
for (i= 0;i<edges.size();i++) edges[i].flow= 0;
addedge(s,a1,an);
addedge(s,b2,bn);
addedge(a2,t,an);
addedge(b1,t,bn);
flow= 0;
}
int main()
{
freopen("1.in","r",stdin);
freopen("1.out","w",stdout);
s= 51;t= s+1;
while (scanf("%d %d %d %d %d %d %d\n",&n, &a1, &a2, &an, &b1, &b2, &bn)!=EOF){a1++;a2++;b1++;b2++;
init(n);
for (i= 1;i<=n;i++)
for (j= 1;j<=n;j++){
ch= read();
if (j>=i){
if (ch=='O') addedge(i,j,2);
else if (ch=='N') addedge(i,j,oo);
}
}
an*= 2;bn*= 2;
addedge(s,a1,an);
addedge(s,b1,bn);
addedge(a2,t,an);
addedge(b2,t,bn);
while (bfs()){
memset(cur,0,sizeof(cur));
flow+= dfs(s,oo);
}
if (flow==an+bn){
clear();
while (bfs()){
memset(cur,0,sizeof(cur));
flow+= dfs(s,oo);
}if (flow==an+bn){
printf("Yes\n");
continue;
}
} printf("No\n");
}return 0;
}
|
0a27dca4d0b36ddece9c9b43d358379b6337c7c3
|
cfaf0124f32156006d9c87f4264dca53596a3d78
|
/VikingGame/UnitsConversion.h
|
ea5b80e7c4894af19f568209ba232c929e230aac
|
[] |
no_license
|
MariusMyburg/GitHubGameOff2017
|
46ad7cff48b27469243bbd83d642e474b0a826ca
|
6c4c7a86e22336d494790b94958274fb01cd1cdb
|
refs/heads/master
| 2021-08-10T13:03:40.663885
| 2017-11-12T15:52:13
| 2017-11-12T15:52:13
| 110,013,211
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 567
|
h
|
UnitsConversion.h
|
#pragma once
#ifndef UNITS_CONVERSION_H
#define UNITS_CONVERSION_H
namespace unitsConversion
{
constexpr double PIXELS_PER_METERS = 32.0;
constexpr double PI = 3.14159265358979323846;
template<typename T>
constexpr T pixelsToMeters(const T& x){return x/PIXELS_PER_METERS;};
template<typename T>
constexpr T metersToPixels(const T& x){return x*PIXELS_PER_METERS;};
template<typename T>
constexpr T degToRad(const T& x){return PI*x/180.0;};
template<typename T>
constexpr T radToDeg(const T& x){return 180.0*x/PI;}
}
#endif
|
6cf84e9718836075e9f61eae44b3c63e63388271
|
ef761a03a2788832f729ee9783c23414a698c5c8
|
/Common/Utils/StaticArray.h
|
63d60beb2b377f112c42b8ef5b00463acfa95ef3
|
[
"MIT"
] |
permissive
|
kovalexius/SSAODemo
|
db98a3089ab607d21084dc471e7a887b518eea16
|
56bee973b5b8fb9483918042c11ee107a262babc
|
refs/heads/master
| 2020-12-02T05:05:26.422799
| 2016-12-07T16:09:50
| 2016-12-07T16:09:50
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 826
|
h
|
StaticArray.h
|
/*******************************************************************************
Author: Alexey Frolov (alexwin32@mail.ru)
This software is distributed freely under the terms of the MIT License.
See "LICENSE" or "http://copyfree.org/content/standard/licenses/mit/license.txt".
*******************************************************************************/
#pragma once
namespace Utils
{
template<class TVar, INT ArrSize>
class StaticArray
{
private:
TVar data[ArrSize];
public:
StaticArray(){}
StaticArray(TVar Data[ArrSize])
{
memcpy(data, Data, sizeof(data));
}
TVar &operator [] (INT Index) {return data[Index];}
const TVar &operator [] (INT Index) const {return data[Index];}
operator TVar * const () const {return data;}
operator TVar * () {return data;}
};
}
|
175fc8e1388faa405ffebebd85d934db48a22823
|
5702eb53222af6e3e41672853c98e87c76fda0e3
|
/util/cpp/ZipFileReader.h
|
76529aa12c276481f12ef88d4af8bfc1a550d31c
|
[] |
no_license
|
agilecomputing/nomads
|
fe46464f62440d29d6074370c1750f69c75ea309
|
0c381bfe728fb24d170721367336c383f209d839
|
refs/heads/master
| 2021-01-18T11:12:29.670874
| 2014-12-13T00:46:40
| 2014-12-13T00:46:40
| 50,006,520
| 1
| 0
| null | 2016-01-20T05:19:14
| 2016-01-20T05:19:13
| null |
UTF-8
|
C++
| false
| false
| 12,834
|
h
|
ZipFileReader.h
|
/*
* ZipFileReader.h
*
* This file is part of the IHMC Util Library
* Copyright (c) 1993-2014 IHMC.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 3 (GPLv3) as published by the Free Software Foundation.
*
* U.S. Government agencies and organizations may redistribute
* and/or modify this program under terms equivalent to
* "Government Purpose Rights" as defined by DFARS
* 252.227-7014(a)(12) (February 2014).
*
* Alternative licenses that allow for use within commercial products may be
* available. Contact Niranjan Suri at IHMC (nsuri@ihmc.us) for details.
*
* This class reads files of type .zip or .jar
*
* See comments for the getEntry() functions below regarding using this class is to extract
* compressed (deflated) entries
*
* NOTE: Objects of this class are not thread-safe. In particular, Due to some state variables
* and seek operations performed on the input file, multiple threads should not
* simultaneously call functions.
*/
#ifndef INCL_ZIP_FILE_READER_H
#define INCL_ZIP_FILE_READER_H
#include <stdio.h>
#include "FTypes.h"
namespace NOMADSUtil
{
typedef int i4;
typedef unsigned long u4;
typedef unsigned short u2;
class ZipFileReader
{
public:
ZipFileReader (void);
~ZipFileReader (void);
enum ReturnCodes {
RC_Ok,
RC_FileAccessError = 1,
RC_FileFormatError = 2
};
struct Entry {
Entry (void);
~Entry (void);
enum CompressionType {
CT_None = 0,
CT_Deflate = 8
};
uint32 ui32Offset;
uint16 ui16VersionMadeBy;
uint16 ui16VersionNeeded;
uint16 ui16Flags;
CompressionType compType;
uint16 ui16LastModTime;
uint16 ui16LastModDate;
uint32 ui32CRC32;
uint32 ui32CompSize;
uint32 ui32UncompSize;
uint16 ui16ExtraFieldLen;
char *pszName;
char *pExtraField;
char *pszComment;
char *pBuf;
};
int init (const char *pszFile, bool bCacheDir = false);
int getFileCount (void);
const char * getFirstFileName (void);
const char * getNextFileName (void);
bool checkForFile (const char *pszFileName);
// Returns an entry for the specified name or NULL if the name is not found
//
// NOTES: The entry object that is returned must be deleted by the caller
//
// The buffer allocated for the data (pBuf) will be one byte larger than
// the size of the entry (ui32CompSize). This is simply as a matter
// of convenience. If this is a deflated entry and the zlib library
// is used to decompress, then the "nowrap" option of the zlib library
// will need to be used (see inflate.c in zlib). However, the "nowrap"
// option requires an extra padded byte for the input buffer.
//
// NOTE to the above note: Although an extra byte is allocated for the
// buffer, the size reported is still the original size.
//
// Example: If the CompressedReader/BufferReader classes are being used,
// here is one way to handle decompressing entries:
//
// CompressedReader *pcr = new CompressedReader (new BufferReader (pEntry->pBuf,
// pEntry->ui32CompSize+1),
// true,
// true);
//
// and then read pEntry->ui32UncompSize number of bytes from the CompressedReader
Entry * getEntry (const char *pszName) const;
// Returns entry at the specified index
// Index may range from 0 to getFileCount()-1
//
// NOTE: If bCacheDir is true in init(), the ZipFileReader currently sorts the
// entries upon loading the directory of the zip file. Therefore, the
// order will be different from that in the original zip file.
//
// Also - see notes above for getEntry (const char *pszName)
Entry * getEntry (int iIndex) const;
static i4 swapBytes (i4 i4Input);
static u2 swapBytes (u2 u2Input);
static u4 swapBytes (u4 u4Input);
// Read and discard bytes from the specified input file until the specified
// signature is encountered
// The file pointer is positioned at the end of the signature
// Returns the number of bytes that were skipped or -1 in case of error
static int skipToEndOfSignature (u4 u4Signature, FILE *fileInput);
protected:
enum Type {
T_LocalFileHeader,
T_FileHeader,
T_EndOfCentralDir
};
#pragma pack (1)
struct LocalFileHeader {
LocalFileHeader (void);
~LocalFileHeader (void);
int read (FILE *fileInput);
int skip (FILE *fileInput);
u4 u4Sig;
u2 u2Version;
u2 u2Flags;
u2 u2CompMethod;
u2 u2LastModFileTime;
u2 u2LastModFileDate;
u4 u4CRC32;
u4 u4CompSize;
u4 u4UncompSize;
u2 u2FileNameLen;
u2 u2ExtraFieldLen;
char *pszFileName;
char *pExtraField;
u4 u4BytesToSkipToNextHeader; // The number of bytes to skip to reach the start of
// the next header
// This will include the bytes in u4CompSize plus the
// bytes needed for data descriptor that could optionally
// follow the data bytes
};
struct DataDescriptor {
DataDescriptor (void);
~DataDescriptor (void);
int read (FILE *fileInput);
u4 u4CRC32;
u4 u4CompSize;
u4 u4UncompSize;
};
struct FileHeader {
FileHeader (void);
~FileHeader (void);
int read (FILE *fileInput);
int skip (FILE *fileInput);
u4 u4Sig;
u2 u2VersionMadeBy;
u2 u2VersionNeeded;
u2 u2Flags;
u2 u2CompMethod;
u2 u2LastModFileTime;
u2 u2LastModFileDate;
u4 u4CRC32;
u4 u4CompSize;
u4 u4UncompSize;
u2 u2FileNameLen;
u2 u2ExtraFieldLen;
u2 u2FileCommentLen;
u2 u2DiskNumberStart;
u2 u2IntFileAttr;
u4 u4ExtFileAttr;
i4 i4LocalHdrRelOffset;
char *pszFileName;
char *pExtraField;
char *pszFileComment;
};
struct EndOfCentralDir {
EndOfCentralDir (void);
~EndOfCentralDir (void);
int read (FILE *fileInput);
u4 u4Sig;
u2 u2DiskNum;
u2 u2CentralDirDiskNum;
u2 u2LocalDiskCentralDirCount;
u2 u2CentralDirCount;
u4 u4CentralDirSize;
u4 u4CentralDirOffset;
u2 u2ZipFileCommentLen;
char *pszZipFileComment;
};
#pragma pack()
struct FileEntry { /*!!*/ // There is really no need for this struct anymore.
FileEntry (void); // Change the code to use FileHeader instead
~FileEntry (void); // However, need to watch out for getEntry() which steals
int init (FileHeader &fh); // memory pointers when using FileHeader
static int compare (const void *pElem1, const void *pElem2);
u4 u4Offset;
u2 u2VersionMadeBy;
u2 u2VersionNeeded;
u2 u2Flags;
u2 u2CompMethod;
u2 u2LastModFileTime;
u2 u2LastModFileDate;
u4 u4CRC32;
u4 u4CompSize;
u4 u4UncompSize;
u2 u2ExtraFieldLen;
char *pszName;
char *pExtraField;
char *pszComment;
};
protected:
int readSignature (FILE *fileInput);
// Search the central directory linearly to find a matching file header
// The file header is read into fh and the file pointer is left
// at the end of the file header
int findFileHeader (const char *pszFile, FILE *fileInput);
// Step through the central directory linearly until the entry specified
// by iIndex is found
// The file header is read into fh and the file pointer is left
// at the end of the file header
int gotoFileHeader (int iIndex, FILE *fileInput);
FileEntry * binarySearch (const char *pszFile, int iBegin, int iEnd);
// Search the FileEntry array to locate the corresponding entry
// Returns NULL if the directory information is not cached in pEntries
// or if no matching entry was found
FileEntry * findFileEntry (const char *pszFile);
// Returns the FileEntry at the specified index in the FileEntry array
// Returns NULL if the directory information is not cached in pEntries
// or if the specified index was not valid
FileEntry * getFileEntry (int iIndex);
// Returns an entry given a FileEntry object and the input file
Entry * getEntry (FileEntry *pfe, FILE *fileInput);
// Returns an entry given a FileHeader object and the input file
// NOTE: The pointers in FileHeader are "stolen" by getEntry and placed into
// Entry for efficiency reasons. After the call, pszFileName, pszFileComment,
// and pExtraBytes will be NULL in pfh
Entry * getEntry (FileHeader *pfh, FILE *fileInput);
protected:
FILE *fileInput;
long lLastFileHeaderSeekPos;
LocalFileHeader lfh;
FileHeader fh;
EndOfCentralDir ecd;
FileEntry *pEntries;
int iEntryArraySize;
};
inline i4 ZipFileReader::swapBytes (i4 i4Input)
{
#if defined (BIG_ENDIAN_SYSTEM)
i4 i4Output;
char *pInput = (char*) &i4Input;
char *pOutput = (char*) &i4Output;
pOutput[0] = pInput[3];
pOutput[1] = pInput[2];
pOutput[2] = pInput[1];
pOutput[3] = pInput[0];
return i4Output;
#elif defined (LITTLE_ENDIAN_SYSTEM)
return i4Input;
#endif
}
inline u2 ZipFileReader::swapBytes (u2 u2Input)
{
#if defined (BIG_ENDIAN_SYSTEM)
u2 u2Output;
char *pInput = (char*) &u2Input;
char *pOutput = (char*) &u2Output;
pOutput[0] = pInput[1];
pOutput[1] = pInput[0];
return u2Output;
#elif defined (LITTLE_ENDIAN_SYSTEM)
return u2Input;
#endif
}
inline u4 ZipFileReader::swapBytes (u4 u4Input)
{
#if defined (BIG_ENDIAN_SYSTEM)
u4 u4Output;
char *pInput = (char*) &u4Input;
char *pOutput = (char*) &u4Output;
pOutput[0] = pInput[3];
pOutput[1] = pInput[2];
pOutput[2] = pInput[1];
pOutput[3] = pInput[0];
return u4Output;
#elif defined (LITTLE_ENDIAN_SYSTEM)
return u4Input;
#endif
}
}
#endif // #ifndef INCL_ZIP_FILE_READER_H
|
80d5706249ee6f8f04714242c5fadf3f20090ad6
|
014e34bb2c2e7995515b0868dc76ecc2a0e41521
|
/test/Stacktest.cpp
|
97ed840a08d85730d5d568f52ccc474ad22b743e
|
[] |
no_license
|
flydzt/tiny-data-structure
|
08de3129f5015428679fe3e68948244ad4e331a3
|
4b8b4dd141f1f92e2c2da729f2326c4f3c8ced50
|
refs/heads/master
| 2021-05-17T21:45:06.966315
| 2020-03-29T06:21:24
| 2020-03-29T06:21:24
| 250,963,983
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 376
|
cpp
|
Stacktest.cpp
|
#include "../Stack.hpp"
#include <iostream>
using namespace std;
int main() {
Stack<int> s;
cout << "push_back" << endl;
for (int i = 0; i < 100; ++i)
s.push_back(i);
for (int i : s)
cout << i << ' ';
cout << endl;
cout << "pop_back" << endl;
for (int i = 0; i < 100; ++i)
cout << s.pop_back() << ' ';
cout << endl;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.