branch_name
stringclasses 149
values | text
stringlengths 23
89.3M
| directory_id
stringlengths 40
40
| languages
listlengths 1
19
| num_files
int64 1
11.8k
| repo_language
stringclasses 38
values | repo_name
stringlengths 6
114
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
|
---|---|---|---|---|---|---|---|---|
refs/heads/master
|
<repo_name>nhatmaiquang/react-youtube<file_sep>/src/components/App.js
import React from 'react';
import SearchBar from './SearchBar';
import youtube from '../apis/youtube';
import VideoList from './VideoList';
import VideoDetail from './VideoDetail';
import Clock from './Clock';
import ThemeDisplay from './ThemeDisplay';
//import customsearch from '../apis/customsearch';
import ImageList from './ImageList';
import unsplash from '../apis/unsplash';
class App extends React.Component {
state = {videos: [], selectedVideo: null, images: [] };
componentDidMount() {
this.onTermSubmit('amee');
}
onTermSubmit = async term => {
const responseYoutube = await youtube.get('/search', {
params: {
q: term
}
});
/*
const responseCSE = await customsearch.get('', {
params: {
q: term,
}
});
console.log(responseCSE);*/
const responseUnsplash = await unsplash.get('/search/photos', {
params: {
query: term
}
});
this.setState({
videos: responseYoutube.data.items,
selectedVideo: responseYoutube.data.items[0],
//images: responseCSE.data.items
images: responseUnsplash.data.results
});
};
onVideoSelect = video => {
this.setState({ selectedVideo: video })
};
render() {
return (
<div className="ui container">
<ThemeDisplay>
<div className="ui grid">
<div className="header row">
<div className="twelve wide column" >
<SearchBar onFormSubmit={this.onTermSubmit}/>
</div>
<div className="four wide column" >
<Clock />
</div>
</div>
<div className="videos row">
<div className="nine wide column">
<VideoDetail video={this.state.selectedVideo} />
<ImageList images={this.state.images} />
</div>
<div className="seven wide column">
<VideoList
onVideoSelect={this.onVideoSelect}
videos={this.state.videos}
/>
</div>
</div>
</div>
</ThemeDisplay>
</div>
);
}
}
export default App;
<file_sep>/src/components/Clock.js
import React from 'react';
class Clock extends React.Component {
state = { date: '', time : '' };
componentDidMount() {
/*
setInterval(() => {
this.setState( { time: new Date().toLocaleTimeString() } )
}, 1000);
}*/
setInterval(() => {
let current = new Date(Date.now());
let currentYear = current.getFullYear();
let currentMonth = (current.getMonth() + 1 < 10 ? "0" : "") + (current.getMonth() + 1);
let currentDay = (current.getDate() < 10 ? "0" : "") + current.getDate();
let currentHour = (current.getHours() < 10 ? "0" : "") + current.getHours();
let currentMin = (current.getMinutes() < 10 ? "0" : "") + current.getMinutes();
let currentSec = (current.getSeconds() < 10 ? "0" : "") + current.getSeconds();
let currentDate = currentDay + "/" + currentMonth + "/" + currentYear;
let currentTime = currentHour + ":" + currentMin + ":" + currentSec;
this.setState({ date: currentDate, time: currentTime });
}, 1000);
}
render() {
return (
<div className="ui huge blue labels" >
<div className="ui label">{this.state.time}</div>
<div className="ui label">{this.state.date}</div>
</div>
);
}
}
export default Clock;
|
8f0d6b4ef412d5b9caa1e1950548c9fb0b156d34
|
[
"JavaScript"
] | 2 |
JavaScript
|
nhatmaiquang/react-youtube
|
4998c1aefdc7c92fc468b254e4fc8a172470802f
|
11b3a8d2b8cad186790b40b66f47190464286462
|
refs/heads/main
|
<repo_name>devashish-gupta09/Sports-Analyzer<file_sep>/README.md
# Sports-Analyzer
Sports Analyzer provides a multi-dimensional way to analyze, view and process
the performance data as per the need of the user. This program works in multiple
sports categories including: Football, Basketball, Cricket. It uses real-time match
stats to analyze the data and using its sorting algorithms it processes it into
various sub categories where a user can view top stats as per need.
The current program uses latest stats from different leagues which are:
1. Euro 2020 (Football)
2. NBA 2020 (Basketball)
3. IPL 2020 (Cricket)
Using various principles of Object-Oriented programming the data has been
divided into various classes and sub classes which not only makes it easy to
maintain but also reduces chances of errors in arranging the data.
This project is aimed to provide a tool for free and easy statistical analysis and gathering data
related to different sports and sportspersons. The purpose of this project entitled as “SPORTS
ANALYZER” is to computerize all the analytical activities by developing various algorithms
using different data structures and classes.
<file_sep>/main.cpp
#include <bits/stdc++.h>
using namespace std;
//Base class of the program
class Sports
{
protected:
public:
//Components of Sports common for all 3 sports.
string First_name;
string Last_name;
int Age;
string Team;
string Country;
int Win;
int Lost;
int No_of_matches;
Sports() //Default Constructor
{
First_name = "";
Last_name = "";
Age = 0;
Team = "";
Country = "";
Win = 0;
Lost = 0;
No_of_matches = 0;
}
//Parameterized Constructor
Sports(string first_name, string last_name, int age, string team, string country, int win, int lost, int no_of_matches)
{
First_name = first_name;
Last_name = last_name;
Age = age;
Team = team;
Country = country;
Win = win;
Lost = lost;
No_of_matches = no_of_matches;
}
~Sports() {} //Destructor
void Main_Display()
{
cout << " **********************************" << endl;
cout << " WELCOME TO SPORTS ANALYZER PROGRAM" << endl;
cout << " **********************************" << endl
<< endl
<< endl;
cout << " ";
system("pause");
system("cls");
cout << " **********************************" << endl;
cout << " WELCOME TO SPORTS ANALYZER PROGRAM" << endl;
cout << " **********************************" << endl
<< endl
<< endl;
cout << " Please Choose the Sports by pressing the number next to it : " << endl
<< endl;
cout << " 1) Football" << endl;
cout << " 2) Basketball" << endl;
cout << " 3) Cricket" << endl;
cout << " 0) To exit the program " << endl
<< endl;
cout << " Enter your choice: ";
}
};
//Base class for football ---> Inherited from class "Sports"
class Football : public Sports
{
protected:
public:
string Position;
int Pass_Accuracy;
int Red_card;
int Draw;
Football() //Default Constructor for Football class
{
Position = "";
Pass_Accuracy = 0;
Red_card = 0;
Draw = 0;
}
//Parameterized Constructor for Football class
Football(string first_name, string last_name, int age, string team, string country, int win, int lost, int no_of_matches, string position, int pass_accuracy, int red_card, int draw) : Sports(first_name, last_name, age, team, country, win, lost, no_of_matches)
{
Position = position;
Pass_Accuracy = pass_accuracy;
Red_card = red_card;
Draw = draw;
}
~Football() {} //Deconstructor for Football class
void Display_content_f()
{
cout << " **********************************" << endl;
cout << " WELCOME TO SPORTS ANALYZER PROGRAM" << endl;
cout << " **********************************" << endl
<< endl
<< endl;
cout << " >>>>>> Welcome to Football <<<<<<" << endl
<< endl;
cout << " 1. View Teams " << endl;
cout << " 2. View Players " << endl;
cout << " 3. Stats " << endl;
cout << " 4. Standings " << endl;
cout << " 5. Return to Main Menu" << endl;
cout << " 0. EXIT" << endl
<< endl;
cout << " Enter your choice: ";
}
void Team_display_f() //For diplaying the teams of football
{
fstream team_f("team_f.txt");
string f;
if (!team_f)
cout << "Error" << endl;
else
{
while (!team_f.eof())
{
getline(team_f, f);
cout << f << endl;
}
}
}
void Standings_display_f() //For displaying the standings of football
{
fstream standings_f("standings_f.txt");
string f;
if (!standings_f)
cout << "Error" << endl;
else
{
while (!standings_f.eof())
{
getline(standings_f, f);
cout << f << endl;
}
}
}
};
//Attack class (Inherited from Football class --> Will contain all the components of Football as well as its parent class Sports)
class Attack : public Football
{
protected:
public:
int Goals;
float Shot_accuracy;
int Assist;
Attack() // Default Constructor for Attack class
{
Goals = 0;
Shot_accuracy = 0;
Assist = 0;
}
// Parameterized Constructor for Attack class
Attack(string first_name, string last_name, int age, string team, string country, int win, int lost, string position, int no_of_matches, int assist, int pass_accuracy, int red_card, int draw, int goals, float shot_accurracy) : Football(first_name, last_name, age, team, country, win, lost, no_of_matches, position, pass_accuracy, red_card, draw)
{
Assist = assist;
Goals = goals;
Shot_accuracy = shot_accurracy;
}
~Attack() {} // Destructor for Attack class
void Display_stats_f_a(Attack *A)
{
fstream stats_f_a("attack.txt");
int id[60];
int _id = 1;
for (int i = 0; i < 60; i++)
{
id[i] = _id;
_id++;
}
stats_f_a.seekg(0);
for (int i = 0; i < 58; i++)
{
stats_f_a >> A[i].First_name >> A[i].Last_name >> A[i].Position >> A[i].Age >> A[i].Team >> A[i].Country >> A[i].No_of_matches >> A[i].Goals >> A[i].Shot_accuracy >> A[i].Assist >> A[i].Pass_Accuracy >> A[i].Red_card;
}
cout << "SNO F.Name L.Name Pos AGE TEAM COUNTRY App Goals S.Accu Ass P.Accu RCd" << endl
<< endl
<< endl;
for (int i = 0; i < 58; i++)
{
cout << left << setw(4) << id[i] << setw(10) << A[i].First_name << setw(14) << A[i].Last_name << setw(5) << A[i].Position << setw(4) << A[i].Age << setw(19) << A[i].Team << setw(13) << A[i].Country << setw(5) << A[i].No_of_matches << setw(6) << A[i].Goals << setw(7) << A[i].Shot_accuracy << setw(4) << A[i].Assist << setw(7) << A[i].Pass_Accuracy << setw(3) << A[i].Red_card << endl;
cout << "-----------------------------------------------------------------------------------------------------" << endl;
}
}
void Search_player_f_a(Attack *A, string name)
{
fstream psearch_a("attack.txt");
int id[60];
int _id = 1;
for (int i = 0; i < 60; i++)
{
id[i] = _id;
_id++;
}
psearch_a.seekg(0);
for (int i = 0; i < 58; i++)
{
psearch_a >> A[i].First_name >> A[i].Last_name >> A[i].Position >> A[i].Age >> A[i].Team >> A[i].Country >> A[i].No_of_matches >> A[i].Goals >> A[i].Shot_accuracy >> A[i].Assist >> A[i].Pass_Accuracy >> A[i].Red_card;
}
int check = 0;
for (int i = 0; i < 58; i++)
{
if (name == A[i].First_name || name == A[i].Last_name)
{
check = 1;
}
}
if (check == 1)
{
cout << "SNO F.Name L.Name Pos AGE TEAM COUNTRY App Goals S.Accu Ass P.Accu RCd" << endl
<< endl
<< endl;
}
else
{
cout << "This player does not exist" << endl
<< endl;
}
for (int i = 0; i < 58; i++)
{
if (name == A[i].First_name || name == A[i].Last_name)
{
cout << left << setw(4) << id[i] << setw(10) << A[i].First_name << setw(14) << A[i].Last_name << setw(5) << A[i].Position << setw(4) << A[i].Age << setw(22) << A[i].Team << setw(13) << A[i].Country << setw(5) << A[i].No_of_matches << setw(6) << A[i].Goals << setw(7) << A[i].Shot_accuracy << setw(4) << A[i].Assist << setw(7) << A[i].Pass_Accuracy << setw(3) << A[i].Red_card << endl;
cout << "---------------------------------------------------------------------------------------------------------" << endl;
}
}
}
void Player_display_f_a(Attack *A)
{
fstream player_f_a("attack.txt");
int id[60];
int _id = 1;
for (int i = 0; i < 60; i++)
{
id[i] = _id;
_id++;
}
player_f_a.seekg(0);
for (int i = 0; i < 60; i++)
{
player_f_a >> A[i].First_name >> A[i].Last_name >> A[i].Position >> A[i].Age >> A[i].Team >> A[i].Country >> A[i].No_of_matches >> A[i].Goals >> A[i].Shot_accuracy >> A[i].Assist >> A[i].Pass_Accuracy >> A[i].Red_card;
}
cout << "FORWARD : " << endl
<< endl;
cout << "SNO F.Name L.Name Pos AGE TEAM COUNTRY" << endl
<< endl;
for (int i = 0; i < 45; i++)
{
cout << left << setw(4) << id[i] << setw(10) << A[i].First_name << setw(14) << A[i].Last_name << setw(5) << A[i].Position << setw(4) << A[i].Age << setw(19) << A[i].Team << setw(13) << A[i].Country << endl;
cout << "----------------------------------------------------------------------" << endl;
}
cout << endl;
}
};
//Midfield class (Inherited from Football class --> Will contain all the components of Football as well as its parent class Sports)
class MidField : public Football
{
protected:
public:
int Goals;
float Shot_accuracy;
int Assist;
MidField() //Default Constructor for Midfield class
{
Goals = 0;
Shot_accuracy = 0;
}
//Parameterized Constructor for Midfield class
MidField(string first_name, string last_name, int age, string team, string country, int win, int lost, string position, int no_of_matches, int assist, int pass_accuracy, int red_card, int draw, int goals, float shot_accurracy) : Football(first_name, last_name, age, team, country, win, lost, no_of_matches, position, pass_accuracy, red_card, draw)
{
Goals = goals;
Shot_accuracy = shot_accurracy;
Assist = assist;
}
~MidField() {} //Destructor for Midfield class
void Display_stats_f_m(MidField *Mf)
{
fstream stats_f_m("midfield.txt");
int id[120];
int _id = 1;
for (int i = 0; i < 120; i++)
{
id[i] = _id;
_id++;
}
stats_f_m.seekg(0);
for (int i = 0; i < 111; i++)
{
stats_f_m >> Mf[i].First_name >> Mf[i].Last_name >> Mf[i].Position >> Mf[i].Age >> Mf[i].Team >> Mf[i].Country >> Mf[i].No_of_matches >> Mf[i].Goals >> Mf[i].Shot_accuracy >> Mf[i].Assist >> Mf[i].Pass_Accuracy >> Mf[i].Red_card;
}
cout << "SNO F.Name L.Name Pos AGE TEAM COUNTRY App Goals S.Accu Ass P.Accu RCd" << endl
<< endl
<< endl;
for (int i = 0; i < 111; i++)
{
cout << left << setw(4) << id[i] << setw(10) << Mf[i].First_name << setw(14) << Mf[i].Last_name << setw(5) << Mf[i].Position << setw(4) << Mf[i].Age << setw(22) << Mf[i].Team << setw(13) << Mf[i].Country << setw(5) << Mf[i].No_of_matches << setw(6) << Mf[i].Goals << setw(7) << Mf[i].Shot_accuracy << setw(4) << Mf[i].Assist << setw(7) << Mf[i].Pass_Accuracy << setw(3) << Mf[i].Red_card << endl;
cout << "--------------------------------------------------------------------------------------------------------" << endl;
}
}
void Search_player_f_m(MidField *Mf, string name)
{
fstream psearch_m("midfield.txt");
int id[120];
int _id = 1;
for (int i = 0; i < 120; i++)
{
id[i] = _id;
_id++;
}
psearch_m.seekg(0);
for (int i = 0; i < 111; i++)
{
psearch_m >> Mf[i].First_name >> Mf[i].Last_name >> Mf[i].Position >> Mf[i].Age >> Mf[i].Team >> Mf[i].Country >> Mf[i].No_of_matches >> Mf[i].Goals >> Mf[i].Shot_accuracy >> Mf[i].Assist >> Mf[i].Pass_Accuracy >> Mf[i].Red_card;
}
int check = 0;
for (int i = 0; i < 111; i++)
{
if (name == Mf[i].First_name || name == Mf[i].Last_name)
{
check = 1;
}
}
if (check == 1)
{
cout << "SNO F.Name L.Name Pos AGE TEAM COUNTRY App Goals S.Accu Ass P.Accu RCd" << endl
<< endl
<< endl;
}
else
{
cout << "This player does not exist" << endl
<< endl;
}
for (int i = 0; i < 111; i++)
{
if (name == Mf[i].First_name || name == Mf[i].Last_name)
{
cout << left << setw(4) << id[i] << setw(10) << Mf[i].First_name << setw(14) << Mf[i].Last_name << setw(5) << Mf[i].Position << setw(4) << Mf[i].Age << setw(22) << Mf[i].Team << setw(13) << Mf[i].Country << setw(5) << Mf[i].No_of_matches << setw(6) << Mf[i].Goals << setw(7) << Mf[i].Shot_accuracy << setw(4) << Mf[i].Assist << setw(7) << Mf[i].Pass_Accuracy << setw(3) << Mf[i].Red_card << endl;
cout << "--------------------------------------------------------------------------------------------------------" << endl;
}
}
}
void Player_display_f_m(MidField *Mf)
{
fstream player_f_m("midfield.txt");
int id[120];
int _id = 1;
for (int i = 0; i < 120; i++)
{
id[i] = _id;
_id++;
}
player_f_m.seekg(0);
for (int i = 0; i < 111; i++)
{
player_f_m >> Mf[i].First_name >> Mf[i].Last_name >> Mf[i].Position >> Mf[i].Age >> Mf[i].Team >> Mf[i].Country >> Mf[i].No_of_matches >> Mf[i].Goals >> Mf[i].Shot_accuracy >> Mf[i].Assist >> Mf[i].Pass_Accuracy >> Mf[i].Red_card;
}
cout << "MID-FIELD : " << endl
<< endl;
cout << "SNO F.Name L.Name Pos AGE TEAM COUNTRY" << endl
<< endl;
for (int i = 0; i < 111; i++)
{
cout << left << setw(4) << id[i] << setw(10) << Mf[i].First_name << setw(14) << Mf[i].Last_name << setw(5) << Mf[i].Position << setw(4) << Mf[i].Age << setw(22) << Mf[i].Team << setw(13) << Mf[i].Country << endl;
cout << "-----------------------------------------------------------------------" << endl;
}
cout << endl;
}
};
//Defence class (Inherited from Football class --> Will contain all the components of Football as well as its parent class Sports)
class Defence : public Football
{
protected:
public:
int Goals;
int Tackles_won;
int Clearance;
int Blocked_shots;
int Assist;
Defence() //Default constructor for Defence class
{
Goals = 0;
Tackles_won = 0;
Clearance = 0;
Blocked_shots = 0;
Assist = 0;
}
//Parameterized Constructor for Defence class
Defence(string first_name, string last_name, int age, string team, string country, int win, int lost, string position, int no_of_matches, int assist, int pass_accuracy, int red_card, int draw, int goals, int tackles_won, int clearance, int blocked_shots) : Football(first_name, last_name, age, team, country, win, lost, no_of_matches, position, pass_accuracy, red_card, draw)
{
Goals = goals;
Tackles_won = tackles_won;
Clearance = clearance;
Blocked_shots = blocked_shots;
Assist = assist;
}
~Defence() {} //Destructor for Defence class
void Display_stats_f_d(Defence *D)
{
fstream stats_f_d("DEFENDERS.txt");
if (!stats_f_d)
cout << "Error opening this file!!" << endl;
int id[120];
int _id = 1;
for (int i = 0; i < 120; i++)
{
id[i] = _id;
_id++;
}
stats_f_d.seekg(0);
for (int i = 0; i < 107; i++)
{
stats_f_d >> D[i].First_name >> D[i].Last_name >> D[i].Position >> D[i].Age >> D[i].Team >> D[i].Country >> D[i].No_of_matches >> D[i].Tackles_won >> D[i].Clearance >> D[i].Blocked_shots >> D[i].Red_card >> D[i].Goals >> D[i].Pass_Accuracy;
}
cout << "SNO F.NAME L.NAME POS AGE TEAM COUNTRY APP TACKLE CLEARANCE BLK.SHOT RC Goals P.ACC" << endl
<< endl
<< endl;
for (int i = 0; i < 107; i++)
{
cout << left << setw(4) << id[i] << setw(10) << D[i].First_name << setw(14) << D[i].Last_name << setw(5) << D[i].Position << setw(4) << D[i].Age << setw(22) << D[i].Team << setw(13) << D[i].Country << setw(5) << D[i].No_of_matches << setw(7) << D[i].Tackles_won << setw(10) << D[i].Clearance << setw(9) << D[i].Blocked_shots << setw(3) << D[i].Red_card << setw(6) << D[i].Goals << setw(7) << D[i].Pass_Accuracy << endl;
cout << "---------------------------------------------------------------------------------------------------------------------" << endl;
}
}
void Search_player_f_d(Defence *D, string name)
{
fstream psearch_d("DEFENDERS.txt");
if (!psearch_d)
cout << "Error opening this file!!" << endl;
int id[120];
int _id = 1;
for (int i = 0; i < 120; i++)
{
id[i] = _id;
_id++;
}
psearch_d.seekg(0);
for (int i = 0; i < 107; i++)
{
psearch_d >> D[i].First_name >> D[i].Last_name >> D[i].Position >> D[i].Age >> D[i].Team >> D[i].Country >> D[i].No_of_matches >> D[i].Tackles_won >> D[i].Clearance >> D[i].Blocked_shots >> D[i].Red_card >> D[i].Goals >> D[i].Pass_Accuracy;
}
int check = 0;
for (int i = 0; i < 107; i++)
{
if (name == D[i].First_name || name == D[i].Last_name)
{
check = 1;
}
}
if (check == 1)
{
cout << "F.NAME L.NAME POS AGE TEAM COUNTRY APP TACKLE CLEARANCE BLK.SHOT RC Goals P.ACC" << endl
<< endl
<< endl;
}
else
{
cout << "This player does not exist" << endl
<< endl;
}
for (int i = 0; i < 107; i++)
{
if (name == D[i].First_name || name == D[i].Last_name)
{
cout << left << setw(10) << D[i].First_name << setw(14) << D[i].Last_name << setw(5) << D[i].Position << setw(4) << D[i].Age << setw(22) << D[i].Team << setw(13) << D[i].Country << setw(5) << D[i].No_of_matches << setw(7) << D[i].Tackles_won << setw(10) << D[i].Clearance << setw(9) << D[i].Blocked_shots << setw(3) << D[i].Red_card << setw(6) << D[i].Goals << setw(7) << D[i].Pass_Accuracy << endl;
cout << "------------------------------------------------------------------------------------------------------------------" << endl;
}
}
}
void Player_display_f_d(Defence *D)
{
fstream player_f_d("DEFENDERS.txt");
int id[120];
int _id = 1;
for (int i = 0; i < 120; i++)
{
id[i] = _id;
_id++;
}
player_f_d.seekg(0);
for (int i = 0; i < 107; i++)
{
player_f_d >> D[i].First_name >> D[i].Last_name >> D[i].Position >> D[i].Age >> D[i].Team >> D[i].Country >> D[i].No_of_matches >> D[i].Tackles_won >> D[i].Clearance >> D[i].Blocked_shots >> D[i].Red_card >> D[i].Goals >> D[i].Pass_Accuracy;
}
cout << "DEFENCE : " << endl
<< endl;
cout << "SNO F.Name L.Name Pos AGE TEAM COUNTRY" << endl
<< endl;
for (int i = 0; i < 107; i++)
{
cout << left << setw(4) << id[i] << setw(10) << D[i].First_name << setw(14) << D[i].Last_name << setw(5) << D[i].Position << setw(4) << D[i].Age << setw(22) << D[i].Team << setw(13) << D[i].Country << endl;
cout << "-----------------------------------------------------------------------" << endl;
}
cout << endl;
}
};
//GoalKeeper class (Inherited from Football class --> Will contain all the components of Football as well as its parent class Sports)
class GoalKeeper : public Football
{
protected:
public:
int Clean_sheets;
int Saves_made;
int Goals_conceeded;
GoalKeeper() //Default constructor for Goalkeeper class
{
Clean_sheets = 0;
Saves_made = 0;
Goals_conceeded = 0;
}
//Parameterized Constructor for Goalkeeper class
GoalKeeper(string first_name, string last_name, int age, string team, string country, int win, int lost, string position, int no_of_matches, int assist, int pass_accuracy, int red_card, int draw, int clean_sheets, int saves_made, int goals_conceeded) : Football(first_name, last_name, age, team, country, win, lost, no_of_matches, position, pass_accuracy, red_card, draw)
{
Clean_sheets = clean_sheets;
Saves_made = saves_made;
Goals_conceeded = goals_conceeded;
}
~GoalKeeper() {} //Destructor for Goalkeeper class
void Search_player_f_gk(GoalKeeper *Gk, string name)
{
fstream psearch_gk("gk.txt");
int id[30];
int _id = 1;
for (int i = 0; i < 30; i++)
{
id[i] = _id;
_id++;
}
psearch_gk.seekg(0);
for (int i = 0; i < 27; i++)
{
psearch_gk >> Gk[i].First_name >> Gk[i].Last_name >> Gk[i].Position >> Gk[i].Age >> Gk[i].Team >> Gk[i].Country >> Gk[i].No_of_matches >> Gk[i].Clean_sheets >> Gk[i].Saves_made >> Gk[i].Goals_conceeded >> Gk[i].Red_card;
}
int check = 0;
for (int i = 0; i < 27; i++)
{
if (name == Gk[i].First_name || name == Gk[i].Last_name)
{
check = 1;
}
}
if (check == 1)
{
cout << "SNO F.Name L.Name Pos AGE TEAM COUNTRY App Cln.S Saves G.Con RCd" << endl
<< endl
<< endl;
}
else
{
cout << "This player does not exist" << endl
<< endl;
}
for (int i = 0; i < 27; i++)
{
if (name == Gk[i].First_name || name == Gk[i].Last_name)
{
cout << left << setw(4) << id[i] << setw(10) << Gk[i].First_name << setw(14) << Gk[i].Last_name << setw(5) << Gk[i].Position << setw(4) << Gk[i].Age << setw(22) << Gk[i].Team << setw(13) << Gk[i].Country << setw(5) << Gk[i].No_of_matches << setw(6) << Gk[i].Clean_sheets << setw(6) << Gk[i].Saves_made << setw(6) << Gk[i].Goals_conceeded << setw(3) << Gk[i].Red_card << endl;
cout << "-----------------------------------------------------------------------------------------------------" << endl;
}
}
}
void Player_display_f_gk(GoalKeeper *Gk)
{
fstream player_f_gk("gk.txt");
int id[30];
int _id = 1;
for (int i = 0; i < 30; i++)
{
id[i] = _id;
_id++;
}
player_f_gk.seekg(0);
for (int i = 0; i < 27; i++)
{
player_f_gk >> Gk[i].First_name >> Gk[i].Last_name >> Gk[i].Position >> Gk[i].Age >> Gk[i].Team >> Gk[i].Country >> Gk[i].No_of_matches >> Gk[i].Clean_sheets >> Gk[i].Saves_made >> Gk[i].Goals_conceeded >> Gk[i].Red_card;
}
cout << "GOAL-KEEPERS : " << endl
<< endl;
cout << "SNO F.Name L.Name Pos AGE TEAM COUNTRY" << endl
<< endl;
for (int i = 0; i < 27; i++)
{
cout << left << setw(4) << id[i] << setw(10) << Gk[i].First_name << setw(14) << Gk[i].Last_name << setw(5) << Gk[i].Position << setw(4) << Gk[i].Age << setw(22) << Gk[i].Team << setw(13) << Gk[i].Country << endl;
cout << "-----------------------------------------------------------------------" << endl;
}
cout << endl;
}
void Display_stats_f_gk(GoalKeeper *Gk)
{
fstream stats_f_gk("gk.txt");
int id[30];
int _id = 1;
for (int i = 0; i < 30; i++)
{
id[i] = _id;
_id++;
}
stats_f_gk.seekg(0);
for (int i = 0; i < 27; i++)
{
stats_f_gk >> Gk[i].First_name >> Gk[i].Last_name >> Gk[i].Position >> Gk[i].Age >> Gk[i].Team >> Gk[i].Country >> Gk[i].No_of_matches >> Gk[i].Clean_sheets >> Gk[i].Saves_made >> Gk[i].Goals_conceeded >> Gk[i].Red_card;
}
cout << "SNO F.Name L.Name Pos AGE TEAM COUNTRY App Cln.S Saves G.Con RCd" << endl
<< endl
<< endl;
for (int i = 0; i < 27; i++)
{
cout << left << setw(4) << id[i] << setw(10) << Gk[i].First_name << setw(14) << Gk[i].Last_name << setw(5) << Gk[i].Position << setw(4) << Gk[i].Age << setw(22) << Gk[i].Team << setw(13) << Gk[i].Country << setw(5) << Gk[i].No_of_matches << setw(6) << Gk[i].Clean_sheets << setw(7) << Gk[i].Saves_made << setw(7) << Gk[i].Goals_conceeded << setw(3) << Gk[i].Red_card << endl;
cout << "-----------------------------------------------------------------------------------------------------" << endl;
}
}
};
//Base class for basketball ---> Inherited from class "Sports"
class Basketball : public Sports
{
protected:
string Position;
int Minutes_played;
int Points;
int Assists;
int Rebounds;
int Field_goal_made;
int Field_goal_attempt;
float Field_goal_percentage;
int Three_ptr_made;
int Three_ptr_attempt;
float Three_ptr_percentage;
int Free_throw_made;
int Free_throw_attempt;
float Free_throw_percentage;
int Steals;
int Blocks;
int Turnover;
public:
Basketball() //Default constructor for Basketball class
{
Position = "";
Minutes_played = 0;
Points = 0;
Assists = 0;
Rebounds = 0;
Field_goal_made = 0;
Field_goal_attempt = 0;
Field_goal_percentage = 0;
Three_ptr_made = 0;
Three_ptr_attempt = 0;
Three_ptr_percentage = 0;
Free_throw_made = 0;
Free_throw_attempt = 0;
Free_throw_percentage = 0;
Steals = 0;
Blocks = 0;
Turnover = 0;
}
//Parameterized Constructor for Basketball class
Basketball(string first_name, string last_name, int age, string team, string country, int win, int lost, int no_of_matches, string position, int minutes_played, int points, int assists, int rebounds, int field_goal_made, int field_goal_attempt, float field_goal_percentage, int three_ptr_made, int three_ptr_attempt, float three_ptr_percentage, int free_throw_made, int free_throw_attempt, float free_throw_percentage, int steals, int blocks, int turnover) : Sports(first_name, last_name, age, team, country, win, lost, no_of_matches)
{
Position = position;
Minutes_played = minutes_played;
Points = points;
Assists = assists;
Rebounds = rebounds;
Field_goal_made = field_goal_made;
Field_goal_attempt = field_goal_attempt;
Field_goal_percentage = field_goal_percentage;
Three_ptr_made = three_ptr_made;
Three_ptr_attempt = three_ptr_attempt;
Three_ptr_percentage = three_ptr_percentage;
Free_throw_made = free_throw_made;
Free_throw_attempt = free_throw_attempt;
Free_throw_percentage = free_throw_percentage;
Steals = steals;
Blocks = blocks;
Turnover = turnover;
}
~Basketball() {} //Destructor for Basketball class
void Display_content_b() //Main Display of basketball
{
cout << " **********************************" << endl;
cout << " WELCOME TO SPORTS ANALYZER PROGRAM" << endl;
cout << " **********************************" << endl
<< endl
<< endl;
cout << " >>>> Welcome to Basketball <<<<" << endl
<< endl;
cout << " 1. View Teams " << endl;
cout << " 2. View Players " << endl;
cout << " 3. Stats " << endl;
cout << " 4. Standings " << endl;
cout << " 5. Return to Main Menu" << endl;
cout << " 0. EXIT" << endl
<< endl;
cout << " Enter your Choice: ";
}
void Team_display_b()
{
fstream team_b("team_b.txt"); //Team txt file
string b;
if (!team_b) // if there's an error opening the team file
cout << "Error opening the file!!" << endl;
else
{
while (!team_b.eof()) //reads the file till eof
{
getline(team_b, b);
cout << b << endl;
}
}
}
void Search_player_b(Basketball *B)
{
fstream search_b("basketball_demo.txt");
if (!search_b) // if there's an error opening the team file
cout << "Error opening the file!!" << endl;
int id[400]; // ID allotted to every player
search_b.seekg(0); //makes the pointer start reading from the beginning
for (int i = 0; i < 300; i++) //inputs all the data into class's objects
{
search_b >> id[i] >> B[i].First_name >> B[i].Last_name >> B[i].Age >> B[i].Team >> B[i].Country >> B[i].Position >> B[i].No_of_matches >> B[i].Win >> B[i].Lost >> B[i].Minutes_played >> B[i].Points >> B[i].Assists >> B[i].Rebounds >> B[i].Field_goal_made >> B[i].Field_goal_attempt >> B[i].Field_goal_percentage >> B[i].Three_ptr_made >> B[i].Three_ptr_attempt >> B[i].Three_ptr_percentage >> B[i].Free_throw_made >> B[i].Free_throw_attempt >> B[i].Free_throw_percentage >> B[i].Steals >> B[i].Blocks >> B[i].Turnover;
}
cout << "Enter name of the player to search : ";
string name; // player to be searched
cin >> name;
int check = 0;
for (int i = 0; i < 300; i++)
{
if (name == B[i].First_name || name == B[i].Last_name)
{
check = 1;
}
}
if (check == 1)
{
cout << "F.Name L.Name AGE TEAM COUNTRY POS TM MP PTS ASS REB FGM FGA FG% 3PM 3PA 3P% FTM FTA FT% STL BLK TO " << endl
<< endl;
}
else
{
cout << "This player does not exist" << endl
<< endl;
}
for (int i = 0; i < 300; i++)
{
if (name == B[i].First_name || name == B[i].Last_name) // checks both first and last name of the player from the file list
{
cout << left << setw(9) << B[i].First_name << setw(17) << B[i].Last_name << setw(5) << B[i].Age << setw(13) << B[i].Team << setw(15) << B[i].Country << setw(15) << B[i].Position << setw(3) << B[i].No_of_matches << setw(5) << B[i].Minutes_played << setw(5) << B[i].Points << setw(4) << B[i].Assists << setw(4) << B[i].Rebounds << setw(4) << B[i].Field_goal_made << setw(5) << B[i].Field_goal_attempt << setw(5) << B[i].Field_goal_percentage << setw(4) << B[i].Three_ptr_made << setw(4) << B[i].Three_ptr_attempt << setw(5) << B[i].Three_ptr_percentage << setw(4) << B[i].Free_throw_made << setw(4) << B[i].Free_throw_attempt << setw(5) << B[i].Free_throw_percentage << setw(4) << B[i].Steals << setw(4) << B[i].Blocks << setw(4) << B[i].Turnover << endl;
cout << "--------------------------------------------------------------------------------------------------------------------------------------------------" << endl;
}
}
}
void Player_display_b(Basketball *B)
{
fstream player_b("basketball_demo.txt");
if (!player_b)
cout << "Error opening the file!!" << endl;
int id[400]; // ID allotted to every player
player_b.seekg(0); //makes the pointer start reading from the beginning
for (int i = 0; i < 300; i++) //inputs all the data into class's objects
{
player_b >> id[i] >> B[i].First_name >> B[i].Last_name >> B[i].Age >> B[i].Team >> B[i].Country >> B[i].Position >> B[i].No_of_matches >> B[i].Win >> B[i].Lost >> B[i].Minutes_played >> B[i].Points >> B[i].Assists >> B[i].Rebounds >> B[i].Field_goal_made >> B[i].Field_goal_attempt >> B[i].Field_goal_percentage >> B[i].Three_ptr_made >> B[i].Three_ptr_attempt >> B[i].Three_ptr_percentage >> B[i].Free_throw_made >> B[i].Free_throw_attempt >> B[i].Free_throw_percentage >> B[i].Steals >> B[i].Blocks >> B[i].Turnover;
}
cout << "SNO F.NAME L.NAME AGE TEAM COUNTRY " << endl
<< endl
<< endl;
for (int i = 0; i < 300; i++) //displays all the players in the league after reading from the file
{
cout << left << setw(4) << id[i] << left << setw(9) << B[i].First_name << left << setw(17) << B[i].Last_name << left << setw(6) << B[i].Age << left << setw(13) << B[i].Team << left << setw(15) << B[i].Country << endl;
cout << "---------------------------------------------------------------" << endl;
}
}
void Display_top10_b_p(Basketball *B)
{
fstream top10_b("basketball_demo.txt");
if (!top10_b)
cout << "Error opening the file!!" << endl;
int id[400]; // ID allotted to every player
top10_b.seekg(0); //makes the pointer start reading from the beginning
for (int i = 0; i < 300; i++) //inputs all the data into class's objects
{
top10_b >> id[i] >> B[i].First_name >> B[i].Last_name >> B[i].Age >> B[i].Team >> B[i].Country >> B[i].Position >> B[i].No_of_matches >> B[i].Win >> B[i].Lost >> B[i].Minutes_played >> B[i].Points >> B[i].Assists >> B[i].Rebounds >> B[i].Field_goal_made >> B[i].Field_goal_attempt >> B[i].Field_goal_percentage >> B[i].Three_ptr_made >> B[i].Three_ptr_attempt >> B[i].Three_ptr_percentage >> B[i].Free_throw_made >> B[i].Free_throw_attempt >> B[i].Free_throw_percentage >> B[i].Steals >> B[i].Blocks >> B[i].Turnover;
}
int points[300];
for (int i = 0; i < 300; i++)
{
points[i] = B[i].Points; //stores all Points from the file in a array
}
int n = sizeof(points) / sizeof(points[0]);
sort(points, points + n, greater<int>()); // sort function to arrange them into descending order
int n1 = 300;
for (int i = 0; i < n1; ++i)
{
for (int j = i + 1; j < n1;)
{
if (points[i] == points[j]) //checks for multiple instances of same points
{
for (int k = j; k < n1 - 1; ++k)
points[k] = points[k + 1];
--n1;
}
else
++j;
}
}
cout << "Rank F.Name L.Name Team MP Points" << endl
<< endl;
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 300; j++)
{
if (points[i] == B[j].Points) // checks where the given (point) occurs in the stat file
{
cout << left << setw(5) << id[i] << setw(9) << B[j].First_name << setw(17) << B[j].Last_name << setw(13) << B[j].Team << setw(5) << B[j].No_of_matches << setw(5) << B[j].Points << endl;
cout << "--------------------------------------------------------" << endl;
}
}
}
}
void Display_top10_b_a(Basketball *B)
{
fstream top10_b("basketball_demo.txt");
int id[400];
top10_b.seekg(0);
for (int i = 0; i < 300; i++)
{
top10_b >> id[i] >> B[i].First_name >> B[i].Last_name >> B[i].Age >> B[i].Team >> B[i].Country >> B[i].Position >> B[i].No_of_matches >> B[i].Win >> B[i].Lost >> B[i].Minutes_played >> B[i].Points >> B[i].Assists >> B[i].Rebounds >> B[i].Field_goal_made >> B[i].Field_goal_attempt >> B[i].Field_goal_percentage >> B[i].Three_ptr_made >> B[i].Three_ptr_attempt >> B[i].Three_ptr_percentage >> B[i].Free_throw_made >> B[i].Free_throw_attempt >> B[i].Free_throw_percentage >> B[i].Steals >> B[i].Blocks >> B[i].Turnover;
}
int assist[300];
for (int i = 0; i < 300; i++)
{
assist[i] = B[i].Assists;
}
int n = sizeof(assist) / sizeof(assist[0]);
sort(assist, assist + n, greater<int>());
int n1 = 300;
for (int i = 0; i < n1; ++i)
{
for (int j = i + 1; j < n1;)
{
if (assist[i] == assist[j])
{
for (int k = j; k < n1 - 1; ++k)
assist[k] = assist[k + 1];
--n1;
}
else
++j;
}
}
cout << "Rank F.Name L.Name Team MP Assists" << endl
<< endl;
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 300; j++)
{
if (assist[i] == B[j].Assists)
{
cout << left << setw(5) << id[i] << setw(9) << B[j].First_name << setw(17) << B[j].Last_name << setw(13) << B[j].Team << setw(5) << B[j].No_of_matches << setw(5) << B[j].Assists << endl;
cout << "--------------------------------------------------------" << endl;
}
}
}
}
void Display_top10_b_r(Basketball *B)
{
fstream top10_b("basketball_demo.txt");
int id[400];
top10_b.seekg(0);
for (int i = 0; i < 300; i++)
{
top10_b >> id[i] >> B[i].First_name >> B[i].Last_name >> B[i].Age >> B[i].Team >> B[i].Country >> B[i].Position >> B[i].No_of_matches >> B[i].Win >> B[i].Lost >> B[i].Minutes_played >> B[i].Points >> B[i].Assists >> B[i].Rebounds >> B[i].Field_goal_made >> B[i].Field_goal_attempt >> B[i].Field_goal_percentage >> B[i].Three_ptr_made >> B[i].Three_ptr_attempt >> B[i].Three_ptr_percentage >> B[i].Free_throw_made >> B[i].Free_throw_attempt >> B[i].Free_throw_percentage >> B[i].Steals >> B[i].Blocks >> B[i].Turnover;
}
int rebound[300];
for (int i = 0; i < 300; i++)
{
rebound[i] = B[i].Rebounds;
}
int n = sizeof(rebound) / sizeof(rebound[0]);
sort(rebound, rebound + n, greater<int>());
int n1 = 300;
for (int i = 0; i < n1; ++i)
{
for (int j = i + 1; j < n1;)
{
if (rebound[i] == rebound[j])
{
for (int k = j; k < n1 - 1; ++k)
rebound[k] = rebound[k + 1];
--n1;
}
else
++j;
}
}
cout << "Rank F.Name L.Name Team MP Rebounds" << endl
<< endl;
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 300; j++)
{
if (rebound[i] == B[j].Rebounds)
{
cout << left << setw(5) << id[i] << setw(9) << B[j].First_name << setw(17) << B[j].Last_name << setw(13) << B[j].Team << setw(5) << B[j].No_of_matches << setw(5) << B[j].Rebounds << endl;
cout << "---------------------------------------------------------" << endl;
}
}
}
}
void Display_top10_b_fg(Basketball *B)
{
fstream top10_b("basketball_demo.txt");
int id[400];
top10_b.seekg(0);
for (int i = 0; i < 300; i++)
{
top10_b >> id[i] >> B[i].First_name >> B[i].Last_name >> B[i].Age >> B[i].Team >> B[i].Country >> B[i].Position >> B[i].No_of_matches >> B[i].Win >> B[i].Lost >> B[i].Minutes_played >> B[i].Points >> B[i].Assists >> B[i].Rebounds >> B[i].Field_goal_made >> B[i].Field_goal_attempt >> B[i].Field_goal_percentage >> B[i].Three_ptr_made >> B[i].Three_ptr_attempt >> B[i].Three_ptr_percentage >> B[i].Free_throw_made >> B[i].Free_throw_attempt >> B[i].Free_throw_percentage >> B[i].Steals >> B[i].Blocks >> B[i].Turnover;
}
float field_goal[300];
for (int i = 0; i < 300; i++)
{
field_goal[i] = B[i].Field_goal_percentage;
}
int n = sizeof(field_goal) / sizeof(field_goal[0]);
sort(field_goal, field_goal + n, greater<int>());
int n1 = 300;
for (int i = 0; i < n1; ++i)
{
for (int j = i + 1; j < n1;)
{
if (field_goal[i] == field_goal[j])
{
for (int k = j; k < n1 - 1; ++k)
field_goal[k] = field_goal[k + 1];
--n1;
}
else
++j;
}
}
cout << "Rank F.Name L.Name Team MP FG%" << endl
<< endl;
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 300; j++)
{
if (field_goal[i] == B[j].Field_goal_percentage)
{
cout << left << setw(5) << id[i] << setw(9) << B[j].First_name << setw(17) << B[j].Last_name << setw(13) << B[j].Team << setw(5) << B[j].No_of_matches << setw(5) << B[j].Field_goal_percentage << endl;
cout << "------------------------------------------------------" << endl;
}
}
}
}
void Display_top10_b_3p(Basketball *B)
{
fstream top10_b("basketball_demo.txt");
int id[400];
top10_b.seekg(0);
for (int i = 0; i < 300; i++)
{
top10_b >> id[i] >> B[i].First_name >> B[i].Last_name >> B[i].Age >> B[i].Team >> B[i].Country >> B[i].Position >> B[i].No_of_matches >> B[i].Win >> B[i].Lost >> B[i].Minutes_played >> B[i].Points >> B[i].Assists >> B[i].Rebounds >> B[i].Field_goal_made >> B[i].Field_goal_attempt >> B[i].Field_goal_percentage >> B[i].Three_ptr_made >> B[i].Three_ptr_attempt >> B[i].Three_ptr_percentage >> B[i].Free_throw_made >> B[i].Free_throw_attempt >> B[i].Free_throw_percentage >> B[i].Steals >> B[i].Blocks >> B[i].Turnover;
}
float three_point[300];
for (int i = 0; i < 300; i++)
{
three_point[i] = B[i].Three_ptr_percentage;
}
int n = sizeof(three_point) / sizeof(three_point[0]);
sort(three_point, three_point + n, greater<int>());
int n1 = 300;
for (int i = 0; i < n1; ++i)
{
for (int j = i + 1; j < n1;)
{
if (three_point[i] == three_point[j])
{
for (int k = j; k < n1 - 1; ++k)
three_point[k] = three_point[k + 1];
--n1;
}
else
++j;
}
}
cout << "Rank F.Name L.Name Team MP 3P%" << endl
<< endl;
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 300; j++)
{
if (three_point[i] == B[j].Three_ptr_percentage)
{
cout << left << setw(5) << id[i] << setw(9) << B[j].First_name << setw(17) << B[j].Last_name << setw(13) << B[j].Team << setw(5) << B[j].No_of_matches << setw(5) << B[j].Three_ptr_percentage << endl;
cout << "------------------------------------------------------" << endl;
}
}
}
}
void Display_top10_b_ft(Basketball *B)
{
fstream top10_b("basketball_demo.txt");
int id[400];
top10_b.seekg(0);
for (int i = 0; i < 300; i++)
{
top10_b >> id[i] >> B[i].First_name >> B[i].Last_name >> B[i].Age >> B[i].Team >> B[i].Country >> B[i].Position >> B[i].No_of_matches >> B[i].Win >> B[i].Lost >> B[i].Minutes_played >> B[i].Points >> B[i].Assists >> B[i].Rebounds >> B[i].Field_goal_made >> B[i].Field_goal_attempt >> B[i].Field_goal_percentage >> B[i].Three_ptr_made >> B[i].Three_ptr_attempt >> B[i].Three_ptr_percentage >> B[i].Free_throw_made >> B[i].Free_throw_attempt >> B[i].Free_throw_percentage >> B[i].Steals >> B[i].Blocks >> B[i].Turnover;
}
float free_throw[300];
for (int i = 0; i < 300; i++)
{
free_throw[i] = B[i].Free_throw_percentage;
}
int n = sizeof(free_throw) / sizeof(free_throw[0]);
sort(free_throw, free_throw + n, greater<int>());
int n1 = 300;
for (int i = 0; i < n1; ++i)
{
for (int j = i + 1; j < n1;)
{
if (free_throw[i] == free_throw[j])
{
for (int k = j; k < n1 - 1; ++k)
free_throw[k] = free_throw[k + 1];
--n1;
}
else
++j;
}
}
cout << "Rank F.Name L.Name Team MP FT%" << endl
<< endl;
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 300; j++)
{
if (free_throw[i] == B[j].Free_throw_percentage)
{
cout << left << setw(5) << id[i] << setw(9) << B[j].First_name << setw(17) << B[j].Last_name << setw(13) << B[j].Team << setw(5) << B[j].No_of_matches << setw(5) << B[j].Free_throw_percentage << endl;
cout << "------------------------------------------------------" << endl;
}
}
}
}
void Stats_display_b(Basketball *B)
{
fstream stats_b("basketball_demo.txt");
if (!stats_b)
cout << "Error opening the file!!" << endl;
int id[400]; // ID allotted to every player
stats_b.seekg(0); //makes the pointer start reading from the beginning
for (int i = 0; i < 300; i++) //inputs all the data into class's objects
{
stats_b >> id[i] >> B[i].First_name >> B[i].Last_name >> B[i].Age >> B[i].Team >> B[i].Country >> B[i].Position >> B[i].No_of_matches >> B[i].Win >> B[i].Lost >> B[i].Minutes_played >> B[i].Points >> B[i].Assists >> B[i].Rebounds >> B[i].Field_goal_made >> B[i].Field_goal_attempt >> B[i].Field_goal_percentage >> B[i].Three_ptr_made >> B[i].Three_ptr_attempt >> B[i].Three_ptr_percentage >> B[i].Free_throw_made >> B[i].Free_throw_attempt >> B[i].Free_throw_percentage >> B[i].Steals >> B[i].Blocks >> B[i].Turnover;
}
cout << "SNO F.Name L.Name AGE TEAM COUNTRY POS TM MP PTS ASS REB FGM FGA FG% 3PM 3PA 3P% FTM FTA FT% STL BLK TO " << endl
<< endl
<< endl;
for (int i = 0; i < 300; i++)
{
cout << left << setw(4) << id[i] << setw(9) << B[i].First_name << setw(17) << B[i].Last_name << setw(5) << B[i].Age << setw(13) << B[i].Team << setw(15) << B[i].Country << setw(15) << B[i].Position << setw(3) << B[i].No_of_matches << setw(5) << B[i].Minutes_played << setw(5) << B[i].Points << setw(4) << B[i].Assists << setw(4) << B[i].Rebounds << setw(4) << B[i].Field_goal_made << setw(5) << B[i].Field_goal_attempt << setw(5) << B[i].Field_goal_percentage << setw(4) << B[i].Three_ptr_made << setw(4) << B[i].Three_ptr_attempt << setw(5) << B[i].Three_ptr_percentage << setw(4) << B[i].Free_throw_made << setw(4) << B[i].Free_throw_attempt << setw(5) << B[i].Free_throw_percentage << setw(4) << B[i].Steals << setw(4) << B[i].Blocks << setw(4) << B[i].Turnover << endl;
cout << "------------------------------------------------------------------------------------------------------------------------------------------------------" << endl;
}
cout << "Legends: F.Name = First Name, L.Name = Last Name, POS = Position, TM = Total Matches Played, MP = Minutes Played, PTS = Total Points, ASS = Total Assists, RPG = Total Rebounds, FGM = Field Goals Made, FGA = Field Goals Attempt, FG% = Field Goal Percentage, 3PM = 3-Pointers Made, 3PA = 3-Pointers Attempt, 3P% = 3-Point Percentage, FTM = Free Throws Made, FTA = Free Throw Attempts, FT% = Free Throw Percentage, STL = Steals, BLK = Bloacks, TO = Turnovers " << endl;
}
void Standings_display_b()
{
string b;
fstream standings_b("standings_b.txt");
if (!standings_b)
cout << "Error opening the file!!" << endl;
else
{
while (!standings_b.eof()) // copies whole file
{
getline(standings_b, b);
cout << b << endl;
}
}
}
};
//Base class for cricket ---> Inherited from class "Sports"
class Cricket : public Sports
{
protected:
public:
int Innings;
int Runs;
float Batting_strike_rate;
float Batting_average;
int Fours;
int Sixes;
string Best_Batting_figure;
Cricket() //Default Constructor for Cricket class
{
Innings = 0;
Runs = 0;
Batting_strike_rate = 0;
Batting_average = 0;
Fours = 0;
Sixes = 0;
Best_Batting_figure = "";
}
//Parameterized Constructor for Cricket class
Cricket(string first_name, string last_name, int age, string team, string country, int win, int lost, int no_of_matches, int innings, int runs, float batting_strike_rate, float batting_average, int fours, int sixes, string best_batting_figure) : Sports(first_name, last_name, age, team, country, win, lost, no_of_matches)
{
Innings = innings;
Runs = runs;
Batting_strike_rate = batting_strike_rate;
Batting_average = batting_average;
Fours = fours;
Sixes = sixes;
Best_Batting_figure = best_batting_figure;
}
~Cricket() {} //Destructor for Cricket class
void Display_content_c() //Main content display of cricket
{
cout << " **********************************" << endl;
cout << " WELCOME TO SPORTS ANALYZER PROGRAM" << endl;
cout << " **********************************" << endl
<< endl
<< endl;
cout << " >>>>>>> Welcome to Cricket <<<<<<" << endl
<< endl;
cout << " 1. View Teams " << endl;
cout << " 2. View Players " << endl;
cout << " 3. Stats " << endl;
cout << " 4. Standings " << endl;
cout << " 5. Return to Main Menu" << endl;
cout << " 0. EXIT" << endl
<< endl;
cout << " Enter your Choice: ";
}
void Team_display_c() //For diplaying the teams of cricket
{
fstream team_c("team_c.txt");
string c;
if (!team_c)
cout << "Error" << endl;
else
{
while (!team_c.eof())
{
getline(team_c, c);
cout << c << endl;
}
}
}
void Standings_display_c()
{
fstream standings_c("standings_c.txt");
string c;
if (!standings_c)
cout << "Error" << endl;
else
{
while (!standings_c.eof())
{
getline(standings_c, c);
cout << c << endl;
}
}
}
};
//Batsman class (Inherited from Cricket class --> Will contain all the components of Cricket as well as its parent class Sports)
class Batsman : public Cricket
{
protected:
public:
int Centuries;
int Fifties;
Batsman() //Default constructor for Batsman class
{
Centuries = 0;
Fifties = 0;
}
//Parameterized constructor for Batsman class
Batsman(string first_name, string last_name, int age, string team, string country, int win, int lost, int no_of_matches, int innings, int runs, float batting_strike_rate, float batting_average, int fours, int sixes, string best_batting_figure, int centuries, int fifties) : Cricket(first_name, last_name, age, team, country, win, lost, no_of_matches, innings, runs, batting_strike_rate, batting_average, fours, sixes, best_batting_figure)
{
Centuries = centuries;
Fifties = fifties;
}
~Batsman() {} //Destructor for Batsman class
void Player_display_c_bt(Batsman *Bt) //For displaying the Batsman
{
fstream player_c_bt("batsman.txt");
int id[100];
player_c_bt.seekg(0);
for (int i = 0; i < 45; i++)
{
player_c_bt >> id[i] >> Bt[i].First_name >> Bt[i].Last_name >> Bt[i].Age >> Bt[i].Team >> Bt[i].Country >> Bt[i].No_of_matches >> Bt[i].Innings >> Bt[i].Runs >> Bt[i].Batting_strike_rate >> Bt[i].Batting_average >> Bt[i].Fifties >> Bt[i].Centuries >> Bt[i].Best_Batting_figure >> Bt[i].Fours >> Bt[i].Sixes;
}
cout << "BATSMAN : " << endl
<< endl;
cout << "F.Name L.Name AGE TEAM COUNTRY" << endl
<< endl
<< endl;
for (int i = 0; i < 45; i++)
{
cout << left << setw(11) << Bt[i].First_name << setw(12) << Bt[i].Last_name << setw(4) << Bt[i].Age << setw(28) << Bt[i].Team << setw(13) << Bt[i].Country << endl;
cout << "-------------------------------------------------------------------" << endl;
}
cout << endl;
}
void Search_player_c_bt(Batsman *Bt, string name)
{
fstream psearch_bt("batsman.txt");
int id[50];
psearch_bt.seekg(0);
for (int i = 0; i < 45; i++)
{
psearch_bt >> id[i] >> Bt[i].First_name >> Bt[i].Last_name >> Bt[i].Age >> Bt[i].Team >> Bt[i].Country >> Bt[i].No_of_matches >> Bt[i].Innings >> Bt[i].Runs >> Bt[i].Batting_strike_rate >> Bt[i].Batting_average >> Bt[i].Fifties >> Bt[i].Centuries >> Bt[i].Best_Batting_figure >> Bt[i].Fours >> Bt[i].Sixes;
}
int check = 0;
for (int i = 0; i < 45; i++)
{
if (name == Bt[i].First_name || name == Bt[i].Last_name)
{
check = 1;
}
}
if (check == 1)
{
cout << "F.Name L.Name AGE TEAM COUNTRY TM INN RUNS S.R. Avg 50s 100s Best 4s 6s" << endl
<< endl
<< endl;
}
else
{
cout << "This player does not exist" << endl
<< endl;
}
for (int i = 0; i < 45; i++)
{
if (name == Bt[i].First_name || name == Bt[i].Last_name)
{
cout << left << setw(11) << Bt[i].First_name << setw(12) << Bt[i].Last_name << setw(4) << Bt[i].Age << setw(28) << Bt[i].Team << setw(13) << Bt[i].Country << setw(3) << Bt[i].No_of_matches << setw(4) << Bt[i].Innings << setw(5) << Bt[i].Runs << setw(7) << Bt[i].Batting_strike_rate << setw(6) << Bt[i].Batting_average << setw(5) << Bt[i].Fifties << setw(5) << Bt[i].Centuries << setw(5) << Bt[i].Best_Batting_figure << setw(3) << Bt[i].Fours << setw(3) << Bt[i].Sixes << endl;
cout << "------------------------------------------------------------------------------------------------------------------------" << endl;
}
}
}
void Display_stats_c_bt(Batsman *Bt)
{
fstream stats_c_bt("batsman.txt");
int id[50];
stats_c_bt.seekg(0);
for (int i = 0; i < 45; i++)
{
stats_c_bt >> id[i] >> Bt[i].First_name >> Bt[i].Last_name >> Bt[i].Age >> Bt[i].Team >> Bt[i].Country >> Bt[i].No_of_matches >> Bt[i].Innings >> Bt[i].Runs >> Bt[i].Batting_strike_rate >> Bt[i].Batting_average >> Bt[i].Fifties >> Bt[i].Centuries >> Bt[i].Best_Batting_figure >> Bt[i].Fours >> Bt[i].Sixes;
}
cout << "SNO F.Name L.Name AGE TEAM COUNTRY TM INN RUNS S.R. Avg 50s 100s Best 4s 6s" << endl
<< endl
<< endl;
for (int i = 0; i < 45; i++)
{
cout << left << setw(4) << id[i] << setw(11) << Bt[i].First_name << setw(12) << Bt[i].Last_name << setw(4) << Bt[i].Age << setw(28) << Bt[i].Team << setw(13) << Bt[i].Country << setw(3) << Bt[i].No_of_matches << setw(4) << Bt[i].Innings << setw(5) << Bt[i].Runs << setw(7) << Bt[i].Batting_strike_rate << setw(6) << Bt[i].Batting_average << setw(5) << Bt[i].Fifties << setw(5) << Bt[i].Centuries << setw(5) << Bt[i].Best_Batting_figure << setw(4) << Bt[i].Fours << setw(3) << Bt[i].Sixes << endl;
cout << "------------------------------------------------------------------------------------------------------------------------" << endl;
}
}
};
//Bowler class (Inherited from Cricket class --> Will contain all the components of Cricket as well as its parent class Sports)
class Bowler : public Cricket
{
protected:
public:
int Wickets;
float Bowling_average;
int Four_wkt_hauls;
float Economy;
string Best_Bowling_figure;
Bowler() //Default Constructor for Bowler class
{
Wickets = 0;
Bowling_average = 0;
Four_wkt_hauls = 0;
Economy = 0;
Best_Bowling_figure = "";
}
// Parameterized Constructor for Bowler class
Bowler(string first_name, string last_name, int age, string team, string country, int win, int lost, int no_of_matches, int innings, int runs, float batting_strike_rate, float batting_average, int fours, int sixes, string best_batting_figure, int wickets, float bowling_average, int four_wkt_haul, float economy, string best_bowling_figure) : Cricket(first_name, last_name, age, team, country, win, lost, no_of_matches, innings, runs, batting_strike_rate, batting_average, fours, sixes, best_batting_figure)
{
Wickets = wickets;
Bowling_average = bowling_average;
Four_wkt_hauls = four_wkt_haul;
Economy = economy;
Best_Bowling_figure = best_bowling_figure;
}
~Bowler() {} //Destructor for Bowler class
void Player_display_c_bo(Bowler *Bo) //For displaying the Bowlers
{
fstream player_c_bo("bowlers.txt");
int id[100];
player_c_bo.seekg(0);
for (int i = 0; i < 53; i++)
{
player_c_bo >> id[i] >> Bo[i].First_name >> Bo[i].Last_name >> Bo[i].Age >> Bo[i].Team >> Bo[i].Country >> Bo[i].No_of_matches >> Bo[i].Innings >> Bo[i].Wickets >> Bo[i].Economy >> Bo[i].Bowling_average >> Bo[i].Best_Bowling_figure >> Bo[i].Four_wkt_hauls >> Bo[i].Runs >> Bo[i].Batting_strike_rate >> Bo[i].Batting_average >> Bo[i].Best_Batting_figure >> Bo[i].Fours >> Bo[i].Sixes;
}
cout << "BOWLERS : " << endl
<< endl;
cout << "F.Name L.Name AGE TEAM COUNTRY" << endl
<< endl
<< endl;
for (int i = 0; i < 53; i++)
{
cout << left << setw(13) << Bo[i].First_name << setw(14) << Bo[i].Last_name << setw(4) << Bo[i].Age << setw(28) << Bo[i].Team << setw(13) << Bo[i].Country << endl;
cout << "-----------------------------------------------------------------------" << endl;
}
cout << endl;
}
void Search_player_c_bo(Bowler *Bo, string name)
{
fstream psearch_bo("bowlers.txt");
int id[60];
psearch_bo.seekg(0);
for (int i = 0; i < 53; i++)
{
psearch_bo >> id[i] >> Bo[i].First_name >> Bo[i].Last_name >> Bo[i].Age >> Bo[i].Team >> Bo[i].Country >> Bo[i].No_of_matches >> Bo[i].Innings >> Bo[i].Wickets >> Bo[i].Economy >> Bo[i].Bowling_average >> Bo[i].Best_Bowling_figure >> Bo[i].Four_wkt_hauls >> Bo[i].Runs >> Bo[i].Batting_strike_rate >> Bo[i].Batting_average >> Bo[i].Best_Batting_figure >> Bo[i].Fours >> Bo[i].Sixes;
}
int check = 0;
for (int i = 0; i < 53; i++)
{
if (name == Bo[i].First_name || name == Bo[i].Last_name)
{
check = 1;
}
}
if (check == 1)
{
cout << "F.Name L.Name AGE TEAM COUNTRY TM INN W ECO Avg Best 4WH RUNS S.R. Avg Best 4s 6s" << endl
<< endl
<< endl;
}
else
{
cout << "This player does not exist" << endl
<< endl;
}
for (int i = 0; i < 53; i++)
{
if (name == Bo[i].First_name || name == Bo[i].Last_name)
{
cout << left << setw(13) << Bo[i].First_name << setw(14) << Bo[i].Last_name << setw(4) << Bo[i].Age << setw(28) << Bo[i].Team << setw(13) << Bo[i].Country << setw(3) << Bo[i].No_of_matches << setw(4) << Bo[i].Innings << setw(4) << Bo[i].Wickets << setw(6) << Bo[i].Economy << setw(6) << Bo[i].Bowling_average << setw(5) << Bo[i].Best_Bowling_figure << setw(4) << Bo[i].Four_wkt_hauls << setw(5) << Bo[i].Runs << setw(7) << Bo[i].Batting_strike_rate << setw(6) << Bo[i].Batting_average << setw(5) << Bo[i].Best_Batting_figure << setw(4) << Bo[i].Fours << setw(3) << Bo[i].Sixes << endl;
cout << "-----------------------------------------------------------------------------------------------------------------------------------------" << endl;
}
}
}
void Display_stats_c_bo(Bowler *Bo)
{
fstream stats_c_bo("bowlers.txt");
int id[60];
stats_c_bo.seekg(0);
for (int i = 0; i < 53; i++)
{
stats_c_bo >> id[i] >> Bo[i].First_name >> Bo[i].Last_name >> Bo[i].Age >> Bo[i].Team >> Bo[i].Country >> Bo[i].No_of_matches >> Bo[i].Innings >> Bo[i].Wickets >> Bo[i].Economy >> Bo[i].Bowling_average >> Bo[i].Best_Bowling_figure >> Bo[i].Four_wkt_hauls >> Bo[i].Runs >> Bo[i].Batting_strike_rate >> Bo[i].Batting_average >> Bo[i].Best_Batting_figure >> Bo[i].Fours >> Bo[i].Sixes;
}
cout << "SNO F.Name L.Name AGE TEAM COUNTRY TM INN W ECO Avg Best 4WH RUNS S.R. Avg Best 4s 6s" << endl
<< endl
<< endl;
for (int i = 0; i < 53; i++)
{
cout << left << setw(4) << id[i] << setw(13) << Bo[i].First_name << setw(14) << Bo[i].Last_name << setw(4) << Bo[i].Age << setw(28) << Bo[i].Team << setw(13) << Bo[i].Country << setw(3) << Bo[i].No_of_matches << setw(4) << Bo[i].Innings << setw(4) << Bo[i].Wickets << setw(6) << Bo[i].Economy << setw(6) << Bo[i].Bowling_average << setw(5) << Bo[i].Best_Bowling_figure << setw(4) << Bo[i].Four_wkt_hauls << setw(5) << Bo[i].Runs << setw(7) << Bo[i].Batting_strike_rate << setw(6) << Bo[i].Batting_average << setw(5) << Bo[i].Best_Batting_figure << setw(4) << Bo[i].Fours << setw(3) << Bo[i].Sixes << endl;
cout << "-----------------------------------------------------------------------------------------------------------------------------------------" << endl;
}
}
};
//All-Rounder class (Inherited from Cricket class --> Will contain all the components of Cricket as well as its parent class Sports)
class All_rounder : public Cricket
{
protected:
public:
int Centuries;
int Fifties;
int Wickets;
float Bowling_average;
int Four_wkt_hauls;
float Economy;
string Best_Bowling_figure;
All_rounder() //Default constructor for All_rounder class
{
Centuries = 0;
Fifties = 0;
Wickets = 0;
Bowling_average = 0;
Four_wkt_hauls = 0;
Economy = 0;
Best_Bowling_figure = "";
}
//Parameterized constructor for All_rounder class
All_rounder(string first_name, string last_name, int age, string team, string country, int win, int lost, int no_of_matches, int innings, int runs, float batting_strike_rate, float batting_average, int fours, int sixes, string best_batting_figure, int centuries, int fifties, int wickets, float bowling_average, int four_wkt_hauls, float economy, string best_bowling_figure) : Cricket(first_name, last_name, age, team, country, win, lost, no_of_matches, innings, runs, batting_strike_rate, batting_average, fours, sixes, best_batting_figure)
{
Centuries = centuries;
Fifties = fifties;
Wickets = wickets;
Bowling_average = bowling_average;
Four_wkt_hauls = four_wkt_hauls;
Economy = economy;
Best_Bowling_figure = best_bowling_figure;
}
~All_rounder() {} //Destructor for All_rounder class
void Player_display_c_ar(All_rounder *Ar) //For displaying the All-rounders
{
fstream player_c_ar("all_rounders.txt");
int id[100];
player_c_ar.seekg(0);
for (int i = 0; i < 30; i++)
{
player_c_ar >> id[i] >> Ar[i].First_name >> Ar[i].Last_name >> Ar[i].Age >> Ar[i].Team >> Ar[i].Country >> Ar[i].No_of_matches >> Ar[i].Innings >> Ar[i].Runs >> Ar[i].Batting_strike_rate >> Ar[i].Batting_average >> Ar[i].Fifties >> Ar[i].Centuries >> Ar[i].Best_Batting_figure >> Ar[i].Fours >> Ar[i].Sixes >> Ar[i].Wickets >> Ar[i].Economy >> Ar[i].Bowling_average >> Ar[i].Best_Bowling_figure >> Ar[i].Four_wkt_hauls;
}
cout << "ALL-ROUNDERS : " << endl
<< endl;
cout << "F.Name L.Name AGE TEAM COUNTRY" << endl
<< endl
<< endl;
for (int i = 0; i < 30; i++)
{
cout << left << setw(13) << Ar[i].First_name << setw(14) << Ar[i].Last_name << setw(4) << Ar[i].Age << setw(28) << Ar[i].Team << setw(13) << Ar[i].Country << endl;
cout << "-----------------------------------------------------------------------" << endl;
}
cout << endl;
}
void Search_player_c_ar(All_rounder *Ar, string name)
{
fstream psearch_ar("all_rounders.txt");
int id[50];
psearch_ar.seekg(0);
for (int i = 0; i < 30; i++)
{
psearch_ar >> id[i] >> Ar[i].First_name >> Ar[i].Last_name >> Ar[i].Age >> Ar[i].Team >> Ar[i].Country >> Ar[i].No_of_matches >> Ar[i].Innings >> Ar[i].Runs >> Ar[i].Batting_strike_rate >> Ar[i].Batting_average >> Ar[i].Fifties >> Ar[i].Centuries >> Ar[i].Best_Batting_figure >> Ar[i].Fours >> Ar[i].Sixes >> Ar[i].Wickets >> Ar[i].Economy >> Ar[i].Bowling_average >> Ar[i].Best_Bowling_figure >> Ar[i].Four_wkt_hauls;
}
int check = 0;
for (int i = 0; i < 30; i++)
{
if (name == Ar[i].First_name || name == Ar[i].Last_name)
{
check = 1;
}
}
if (check == 1)
{
cout << "F.Name L.Name AGE TEAM COUNTRY TM INN RUNS S.R. Avg 50s 100s Best 4s 6s W ECO Avg Best 4WH" << endl
<< endl
<< endl;
}
else
{
cout << "This player does not exist" << endl
<< endl;
}
for (int i = 0; i < 30; i++)
{
if (name == Ar[i].First_name || name == Ar[i].Last_name)
{
cout << left << setw(13) << Ar[i].First_name << setw(14) << Ar[i].Last_name << setw(4) << Ar[i].Age << setw(28) << Ar[i].Team << setw(13) << Ar[i].Country << setw(3) << Ar[i].No_of_matches << setw(4) << Ar[i].Innings << setw(5) << Ar[i].Runs << setw(7) << Ar[i].Batting_strike_rate << setw(6) << Ar[i].Batting_average << setw(4) << Ar[i].Fifties << setw(5) << Ar[i].Centuries << setw(5) << Ar[i].Best_Batting_figure << setw(4) << Ar[i].Fours << setw(3) << Ar[i].Sixes << setw(4) << Ar[i].Wickets << setw(6) << Ar[i].Economy << setw(6) << Ar[i].Bowling_average << setw(5) << Ar[i].Best_Bowling_figure << setw(4) << Ar[i].Four_wkt_hauls << endl;
cout << "--------------------------------------------------------------------------------------------------------------------------------------------------" << endl;
}
}
}
void Display_stats_c_ar(All_rounder *Ar)
{
fstream stats_c_ar("all_rounders.txt");
int id[30];
stats_c_ar.seekg(0);
for (int i = 0; i < 30; i++)
{
stats_c_ar >> id[i] >> Ar[i].First_name >> Ar[i].Last_name >> Ar[i].Age >> Ar[i].Team >> Ar[i].Country >> Ar[i].No_of_matches >> Ar[i].Innings >> Ar[i].Runs >> Ar[i].Batting_strike_rate >> Ar[i].Batting_average >> Ar[i].Fifties >> Ar[i].Centuries >> Ar[i].Best_Batting_figure >> Ar[i].Fours >> Ar[i].Sixes >> Ar[i].Wickets >> Ar[i].Economy >> Ar[i].Bowling_average >> Ar[i].Best_Bowling_figure >> Ar[i].Four_wkt_hauls;
}
cout << "SNO F.Name L.Name AGE TEAM COUNTRY TM INN RUNS S.R. Avg 50s 100s Best 4s 6s W ECO Avg Best 4WH" << endl
<< endl
<< endl;
for (int i = 0; i < 30; i++)
{
cout << left << setw(4) << id[i] << setw(13) << Ar[i].First_name << setw(14) << Ar[i].Last_name << setw(4) << Ar[i].Age << setw(28) << Ar[i].Team << setw(13) << Ar[i].Country << setw(3) << Ar[i].No_of_matches << setw(4) << Ar[i].Innings << setw(5) << Ar[i].Runs << setw(7) << Ar[i].Batting_strike_rate << setw(6) << Ar[i].Batting_average << setw(4) << Ar[i].Fifties << setw(5) << Ar[i].Centuries << setw(5) << Ar[i].Best_Batting_figure << setw(4) << Ar[i].Fours << setw(3) << Ar[i].Sixes << setw(4) << Ar[i].Wickets << setw(6) << Ar[i].Economy << setw(6) << Ar[i].Bowling_average << setw(5) << Ar[i].Best_Bowling_figure << setw(4) << Ar[i].Four_wkt_hauls << endl;
cout << "--------------------------------------------------------------------------------------------------------------------------------------------------" << endl;
}
}
};
//Wicket-Keeper class (Inherited from Cricket class --> Will contain all the components of Cricket as well as its parent class Sports)
class Wicket_keeper : public Cricket
{
protected:
public:
int Centuries;
int Fifties;
int Stumps;
int Catches;
Wicket_keeper() //Default Constructor for Wicket_keeper class;
{
Centuries = 0;
Fifties = 0;
Stumps = 0;
Catches = 0;
}
//Parameterized constructor for Wicket_keeper class
Wicket_keeper(string first_name, string last_name, int age, string team, string country, int win, int lost, int no_of_matches, int innings, int runs, float batting_strike_rate, float batting_average, int fours, int sixes, string best_batting_figure, int centuries, int fifties, int stumps, int catches) : Cricket(first_name, last_name, age, team, country, win, lost, no_of_matches, innings, runs, batting_strike_rate, batting_average, fours, sixes, best_batting_figure)
{
Centuries = centuries;
Fifties = fifties;
Stumps = stumps;
Catches = catches;
}
void Player_display_c_wk(Wicket_keeper *Wk) //For displaying the wicket-keepers
{
fstream player_c_wk("WICKETKEEPERS.txt");
player_c_wk.seekg(0);
int id[100];
for (int i = 0; i < 8; i++) //Reading WICKETKEEPERS.txt file in the object
{
player_c_wk >> id[i] >> Wk[i].First_name >> Wk[i].Last_name >> Wk[i].Age >> Wk[i].Team >> Wk[i].Country >> Wk[i].No_of_matches >> Wk[i].Innings >> Wk[i].Stumps >> Wk[i].Catches >> Wk[i].Runs >> Wk[i].Batting_strike_rate >> Wk[i].Batting_average >> Wk[i].Fifties >> Wk[i].Centuries >> Wk[i].Best_Batting_figure >> Wk[i].Fours >> Wk[i].Sixes;
}
cout << "WICKET-KEEPERS : " << endl
<< endl;
cout << "F.Name L.Name AGE TEAM COUNTRY" << endl
<< endl
<< endl;
for (int i = 0; i < 8; i++) //Displaying all wicketkeepers from the file
{
cout << left << setw(13) << Wk[i].First_name << setw(14) << Wk[i].Last_name << setw(4) << Wk[i].Age << setw(28) << Wk[i].Team << setw(13) << Wk[i].Country << endl;
cout << "-----------------------------------------------------------------------" << endl;
}
cout << endl;
}
void Search_player_c_wk(Wicket_keeper *Wk, string name) //For searching a specific player from the file via First Name search
{
fstream psearch_wk("WICKETKEEPERS.txt");
int id[10];
psearch_wk.seekg(0);
for (int i = 0; i < 8; i++) //Reading WICKETKEEPERS.txt file in the object
{
psearch_wk >> id[i] >> Wk[i].First_name >> Wk[i].Last_name >> Wk[i].Age >> Wk[i].Team >> Wk[i].Country >> Wk[i].No_of_matches >> Wk[i].Innings >> Wk[i].Stumps >> Wk[i].Catches >> Wk[i].Runs >> Wk[i].Batting_strike_rate >> Wk[i].Batting_average >> Wk[i].Fifties >> Wk[i].Centuries >> Wk[i].Best_Batting_figure >> Wk[i].Fours >> Wk[i].Sixes;
}
int check = 0;
for (int i = 0; i < 8; i++)
{
if (name == Wk[i].First_name || name == Wk[i].Last_name)
{
check = 1;
}
}
if (check == 1)
{
cout << "F.Name L.Name AGE TEAM COUNTRY TM INN C St RUNS S.R. Avg 50s 100s Best 4s 6s" << endl
<< endl
<< endl;
}
else
{
cout << "This player does not exist" << endl
<< endl;
}
for (int i = 0; i < 8; i++)
{
if (name == Wk[i].First_name || name == Wk[i].Last_name) //Checking and printing the required Wicket-keeper's Data
{
cout << left << setw(13) << Wk[i].First_name << setw(14) << Wk[i].Last_name << setw(4) << Wk[i].Age << setw(28) << Wk[i].Team << setw(13) << Wk[i].Country << setw(3) << Wk[i].No_of_matches << setw(4) << Wk[i].Innings << setw(4) << Wk[i].Stumps << setw(4) << Wk[i].Catches << setw(5) << Wk[i].Runs << setw(7) << Wk[i].Batting_strike_rate << setw(6) << Wk[i].Batting_average << setw(4) << Wk[i].Fifties << setw(5) << Wk[i].Centuries << setw(5) << Wk[i].Best_Batting_figure << setw(4) << Wk[i].Fours << setw(3) << Wk[i].Sixes << endl;
cout << "-----------------------------------------------------------------------------------------------------------------------------------" << endl;
}
}
}
void Display_stats_c_wk(Wicket_keeper *Wk)
{
fstream stats_c_wk("WICKETKEEPERS.txt");
int id[10];
stats_c_wk.seekg(0);
for (int i = 0; i < 8; i++)
{
stats_c_wk >> id[i] >> Wk[i].First_name >> Wk[i].Last_name >> Wk[i].Age >> Wk[i].Team >> Wk[i].Country >> Wk[i].No_of_matches >> Wk[i].Innings >> Wk[i].Stumps >> Wk[i].Catches >> Wk[i].Runs >> Wk[i].Batting_strike_rate >> Wk[i].Batting_average >> Wk[i].Fifties >> Wk[i].Centuries >> Wk[i].Best_Batting_figure >> Wk[i].Fours >> Wk[i].Sixes;
}
cout << "SNO F.Name L.Name AGE TEAM COUNTRY TM INN C St RUNS S.R. Avg 50s 100s Best 4s 6s" << endl
<< endl
<< endl;
for (int i = 0; i < 8; i++)
{
cout << left << setw(4) << id[i] << setw(13) << Wk[i].First_name << setw(14) << Wk[i].Last_name << setw(4) << Wk[i].Age << setw(28) << Wk[i].Team << setw(13) << Wk[i].Country << setw(3) << Wk[i].No_of_matches << setw(4) << Wk[i].Innings << setw(4) << Wk[i].Stumps << setw(4) << Wk[i].Catches << setw(5) << Wk[i].Runs << setw(7) << Wk[i].Batting_strike_rate << setw(6) << Wk[i].Batting_average << setw(4) << Wk[i].Fifties << setw(5) << Wk[i].Centuries << setw(5) << Wk[i].Best_Batting_figure << setw(4) << Wk[i].Fours << setw(3) << Wk[i].Sixes << endl;
cout << "-----------------------------------------------------------------------------------------------------------------------------------" << endl;
}
}
};
void Display_top10_run(Batsman *Bt, Bowler *Bo, All_rounder *Ar, Wicket_keeper *Wk)
{
fstream bat("batsman.txt");
if (!bat)
cout << "Error opening the file!!" << endl;
fstream bowl("bowlers.txt");
if (!bowl)
cout << "Error opening the file!!" << endl;
fstream allrounder("all_rounders.txt");
if (!allrounder)
cout << "Error opening the file!!" << endl;
fstream wktkeeper("WICKETKEEPERS.txt");
if (!wktkeeper)
cout << "Error opening the file!!" << endl;
int id[136];
bat.seekg(0);
bowl.seekg(0);
allrounder.seekg(0);
wktkeeper.seekg(0);
for (int i = 0; i < 45; i++)
{
bat >> id[i] >> Bt[i].First_name >> Bt[i].Last_name >> Bt[i].Age >> Bt[i].Team >> Bt[i].Country >> Bt[i].No_of_matches >> Bt[i].Innings >> Bt[i].Runs >> Bt[i].Batting_strike_rate >> Bt[i].Batting_average >> Bt[i].Fifties >> Bt[i].Centuries >> Bt[i].Best_Batting_figure >> Bt[i].Fours >> Bt[i].Sixes;
}
for (int i = 45; i < 98; i++)
{
bowl >> id[i] >> Bo[i - 45].First_name >> Bo[i - 45].Last_name >> Bo[i - 45].Age >> Bo[i - 45].Team >> Bo[i - 45].Country >> Bo[i - 45].No_of_matches >> Bo[i - 45].Innings >> Bo[i - 45].Wickets >> Bo[i - 45].Economy >> Bo[i - 45].Bowling_average >> Bo[i - 45].Best_Bowling_figure >> Bo[i - 45].Four_wkt_hauls >> Bo[i - 45].Runs >> Bo[i - 45].Batting_strike_rate >> Bo[i - 45].Batting_average >> Bo[i - 45].Best_Batting_figure >> Bo[i - 45].Fours >> Bo[i - 45].Sixes;
}
for (int i = 98; i < 128; i++)
{
allrounder >> id[i] >> Ar[i - 98].First_name >> Ar[i - 98].Last_name >> Ar[i - 98].Age >> Ar[i - 98].Team >> Ar[i - 98].Country >> Ar[i - 98].No_of_matches >> Ar[i - 98].Innings >> Ar[i - 98].Runs >> Ar[i - 98].Batting_strike_rate >> Ar[i - 98].Batting_average >> Ar[i - 98].Fifties >> Ar[i - 98].Centuries >> Ar[i - 98].Best_Batting_figure >> Ar[i - 98].Fours >> Ar[i - 98].Sixes >> Ar[i - 98].Wickets >> Ar[i - 98].Economy >> Ar[i - 98].Bowling_average >> Ar[i - 98].Best_Bowling_figure >> Ar[i - 98].Four_wkt_hauls;
}
for (int i = 128; i < 136; i++)
{
wktkeeper >> id[i] >> Wk[i - 128].First_name >> Wk[i - 128].Last_name >> Wk[i - 128].Age >> Wk[i - 128].Team >> Wk[i - 128].Country >> Wk[i - 128].No_of_matches >> Wk[i - 128].Innings >> Wk[i - 128].Stumps >> Wk[i - 128].Catches >> Wk[i - 128].Runs >> Wk[i - 128].Batting_strike_rate >> Wk[i - 128].Batting_average >> Wk[i - 128].Fifties >> Wk[i - 128].Centuries >> Wk[i - 128].Best_Batting_figure >> Wk[i - 128].Fours >> Wk[i - 128].Sixes;
}
int runs[136];
for (int i = 0; i < 45; i++)
runs[i] = Bt[i].Runs;
for (int i = 45; i < 98; i++)
runs[i] = Bo[i - 45].Runs;
for (int i = 98; i < 128; i++)
runs[i] = Ar[i - 98].Runs;
for (int i = 128; i < 136; i++)
runs[i] = Wk[i - 128].Runs;
int n = sizeof(runs) / sizeof(runs[0]);
sort(runs, runs + n, greater<int>());
int n1 = 136;
for (int i = 0; i < n1; ++i)
{
for (int j = i + 1; j < n1;)
{
if (runs[i] == runs[j]) //checks for multiple instances of same runs
{
for (int k = j; k < n1 - 1; ++k)
runs[k] = runs[k + 1];
--n1;
}
else
++j;
}
}
cout << "SNo F.Name L.Name TEAM TM RUNS" << endl
<< endl
<< endl;
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 45; j++)
{
if (runs[i] == Bt[j].Runs) // checks where the given (runs) occurs in the stat file
{
cout << left << setw(5) << id[i] << setw(11) << Bt[j].First_name << setw(13) << Bt[j].Last_name << setw(28) << Bt[j].Team << setw(5) << Bt[j].No_of_matches << setw(5) << Bt[j].Runs << endl;
cout << "------------------------------------------------------------------" << endl;
}
}
for (int j = 0; j < 53; j++)
{
if (runs[i] == Bo[j].Runs) // checks where the given (runs) occurs in the stat file
{
cout << left << setw(5) << id[i] << setw(11) << Bo[j].First_name << setw(13) << Bo[j].Last_name << setw(28) << Bo[j].Team << setw(5) << Bo[j].No_of_matches << setw(5) << Bo[j].Runs << endl;
cout << "------------------------------------------------------------------" << endl;
}
}
for (int j = 0; j < 30; j++)
{
if (runs[i] == Ar[j].Runs) // checks where the given (runs) occurs in the stat file
{
cout << left << setw(5) << id[i] << setw(11) << Ar[j].First_name << setw(13) << Ar[j].Last_name << setw(28) << Ar[j].Team << setw(5) << Ar[j].No_of_matches << setw(5) << Ar[j].Runs << endl;
cout << "------------------------------------------------------------------" << endl;
}
}
for (int j = 0; j < 8; j++)
{
if (runs[i] == Wk[j].Runs) // checks where the given (runs) occurs in the stat file
{
cout << left << setw(5) << id[i] << setw(11) << Wk[j].First_name << setw(13) << Wk[j].Last_name << setw(28) << Wk[j].Team << setw(5) << Wk[j].No_of_matches << setw(5) << Wk[j].Runs << endl;
cout << "------------------------------------------------------------------" << endl;
}
}
}
}
void Display_top10_strikerate(Batsman *Bt, All_rounder *Ar, Wicket_keeper *Wk)
{
fstream bat("batsman.txt");
if (!bat)
cout << "Error opening the file!!" << endl;
fstream allrounder("all_rounders.txt");
if (!allrounder)
cout << "Error opening the file!!" << endl;
fstream wktkeeper("WICKETKEEPERS.txt");
if (!wktkeeper)
cout << "Error opening the file!!" << endl;
int id[83];
bat.seekg(0);
allrounder.seekg(0);
wktkeeper.seekg(0);
for (int i = 0; i < 45; i++)
{
bat >> id[i] >> Bt[i].First_name >> Bt[i].Last_name >> Bt[i].Age >> Bt[i].Team >> Bt[i].Country >> Bt[i].No_of_matches >> Bt[i].Innings >> Bt[i].Runs >> Bt[i].Batting_strike_rate >> Bt[i].Batting_average >> Bt[i].Fifties >> Bt[i].Centuries >> Bt[i].Best_Batting_figure >> Bt[i].Fours >> Bt[i].Sixes;
}
for (int i = 45; i < 75; i++)
{
allrounder >> id[i] >> Ar[i - 45].First_name >> Ar[i - 45].Last_name >> Ar[i - 45].Age >> Ar[i - 45].Team >> Ar[i - 45].Country >> Ar[i - 45].No_of_matches >> Ar[i - 45].Innings >> Ar[i - 45].Runs >> Ar[i - 45].Batting_strike_rate >> Ar[i - 45].Batting_average >> Ar[i - 45].Fifties >> Ar[i - 45].Centuries >> Ar[i - 45].Best_Batting_figure >> Ar[i - 45].Fours >> Ar[i - 45].Sixes >> Ar[i - 45].Wickets >> Ar[i - 45].Economy >> Ar[i - 45].Bowling_average >> Ar[i - 45].Best_Bowling_figure >> Ar[i - 45].Four_wkt_hauls;
}
for (int i = 75; i < 83; i++)
{
wktkeeper >> id[i] >> Wk[i - 75].First_name >> Wk[i - 75].Last_name >> Wk[i - 75].Age >> Wk[i - 75].Team >> Wk[i - 75].Country >> Wk[i - 75].No_of_matches >> Wk[i - 75].Innings >> Wk[i - 75].Stumps >> Wk[i - 75].Catches >> Wk[i - 75].Runs >> Wk[i - 75].Batting_strike_rate >> Wk[i - 75].Batting_average >> Wk[i - 75].Fifties >> Wk[i - 75].Centuries >> Wk[i - 75].Best_Batting_figure >> Wk[i - 75].Fours >> Wk[i - 75].Sixes;
}
float strike_rate[83];
for (int i = 0; i < 45; i++)
strike_rate[i] = Bt[i].Batting_strike_rate;
for (int i = 45; i < 75; i++)
strike_rate[i] = Ar[i - 45].Batting_strike_rate;
for (int i = 75; i < 83; i++)
strike_rate[i] = Wk[i - 75].Batting_strike_rate;
int n = sizeof(strike_rate) / sizeof(strike_rate[0]);
sort(strike_rate, strike_rate + n, greater<int>());
int n1 = 83;
for (int i = 0; i < n1; ++i)
{
for (int j = i + 1; j < n1;)
{
if (strike_rate[i] == strike_rate[j]) //checks for multiple instances of same runs
{
for (int k = j; k < n1 - 1; ++k)
strike_rate[k] = strike_rate[k + 1];
--n1;
}
else
++j;
}
}
cout << "SNo F.Name L.Name TEAM TM St Rate" << endl
<< endl
<< endl;
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 45; j++)
{
if (strike_rate[i] == Bt[j].Batting_strike_rate) // checks where the given (strike_rate) occurs in the stat file
{
cout << left << setw(5) << id[i] << setw(11) << Bt[j].First_name << setw(13) << Bt[j].Last_name << setw(28) << Bt[j].Team << setw(5) << Bt[j].No_of_matches << setw(5) << Bt[j].Batting_strike_rate << endl;
cout << "---------------------------------------------------------------------" << endl;
}
}
for (int j = 0; j < 30; j++)
{
if (strike_rate[i] == Ar[j].Batting_strike_rate) // checks where the given (strike_rate) occurs in the stat file
{
cout << left << setw(5) << id[i] << setw(11) << Ar[j].First_name << setw(13) << Ar[j].Last_name << setw(28) << Ar[j].Team << setw(5) << Ar[j].No_of_matches << setw(5) << Ar[j].Batting_strike_rate << endl;
cout << "---------------------------------------------------------------------" << endl;
}
}
for (int j = 0; j < 8; j++)
{
if (strike_rate[i] == Wk[j].Batting_strike_rate) // checks where the given (strike_rate) occurs in the stat file
{
cout << left << setw(5) << id[i] << setw(11) << Wk[j].First_name << setw(13) << Wk[j].Last_name << setw(28) << Wk[j].Team << setw(5) << Wk[j].No_of_matches << setw(5) << Wk[j].Batting_strike_rate << endl;
cout << "---------------------------------------------------------------------" << endl;
}
}
}
}
void Display_top10_batavg(Batsman *Bt, All_rounder *Ar, Wicket_keeper *Wk)
{
fstream bat("batsman.txt");
if (!bat)
cout << "Error opening the file!!" << endl;
fstream allrounder("all_rounders.txt");
if (!allrounder)
cout << "Error opening the file!!" << endl;
fstream wktkeeper("WICKETKEEPERS.txt");
if (!wktkeeper)
cout << "Error opening the file!!" << endl;
int id[83];
bat.seekg(0);
allrounder.seekg(0);
wktkeeper.seekg(0);
for (int i = 0; i < 45; i++)
{
bat >> id[i] >> Bt[i].First_name >> Bt[i].Last_name >> Bt[i].Age >> Bt[i].Team >> Bt[i].Country >> Bt[i].No_of_matches >> Bt[i].Innings >> Bt[i].Runs >> Bt[i].Batting_strike_rate >> Bt[i].Batting_average >> Bt[i].Fifties >> Bt[i].Centuries >> Bt[i].Best_Batting_figure >> Bt[i].Fours >> Bt[i].Sixes;
}
for (int i = 45; i < 75; i++)
{
allrounder >> id[i] >> Ar[i - 45].First_name >> Ar[i - 45].Last_name >> Ar[i - 45].Age >> Ar[i - 45].Team >> Ar[i - 45].Country >> Ar[i - 45].No_of_matches >> Ar[i - 45].Innings >> Ar[i - 45].Runs >> Ar[i - 45].Batting_strike_rate >> Ar[i - 45].Batting_average >> Ar[i - 45].Fifties >> Ar[i - 45].Centuries >> Ar[i - 45].Best_Batting_figure >> Ar[i - 45].Fours >> Ar[i - 45].Sixes >> Ar[i - 45].Wickets >> Ar[i - 45].Economy >> Ar[i - 45].Bowling_average >> Ar[i - 45].Best_Bowling_figure >> Ar[i - 45].Four_wkt_hauls;
}
for (int i = 75; i < 83; i++)
{
wktkeeper >> id[i] >> Wk[i - 75].First_name >> Wk[i - 75].Last_name >> Wk[i - 75].Age >> Wk[i - 75].Team >> Wk[i - 75].Country >> Wk[i - 75].No_of_matches >> Wk[i - 75].Innings >> Wk[i - 75].Stumps >> Wk[i - 75].Catches >> Wk[i - 75].Runs >> Wk[i - 75].Batting_strike_rate >> Wk[i - 75].Batting_average >> Wk[i - 75].Fifties >> Wk[i - 75].Centuries >> Wk[i - 75].Best_Batting_figure >> Wk[i - 75].Fours >> Wk[i - 75].Sixes;
}
float batavg[83];
for (int i = 0; i < 45; i++)
batavg[i] = Bt[i].Batting_average;
for (int i = 45; i < 75; i++)
batavg[i] = Ar[i - 45].Batting_average;
for (int i = 75; i < 83; i++)
batavg[i] = Wk[i - 75].Batting_average;
int n = sizeof(batavg) / sizeof(batavg[0]);
sort(batavg, batavg + n, greater<int>());
int n1 = 83;
for (int i = 0; i < n1; ++i)
{
for (int j = i + 1; j < n1;)
{
if (batavg[i] == batavg[j]) //checks for multiple instances of same runs
{
for (int k = j; k < n1 - 1; ++k)
batavg[k] = batavg[k + 1];
--n1;
}
else
++j;
}
}
cout << "SNo F.Name L.Name TEAM TM Bat Avg" << endl
<< endl
<< endl;
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 45; j++)
{
if (batavg[i] == Bt[j].Batting_average) // checks where the given (batavg) occurs in the stat file
{
cout << left << setw(5) << id[i] << setw(11) << Bt[j].First_name << setw(13) << Bt[j].Last_name << setw(28) << Bt[j].Team << setw(5) << Bt[j].No_of_matches << setw(5) << Bt[j].Batting_average << endl;
cout << "---------------------------------------------------------------------" << endl;
}
}
for (int j = 0; j < 30; j++)
{
if (batavg[i] == Ar[j].Batting_average) // checks where the given (batavg) occurs in the stat file
{
cout << left << setw(5) << id[i] << setw(11) << Ar[j].First_name << setw(13) << Ar[j].Last_name << setw(28) << Ar[j].Team << setw(5) << Ar[j].No_of_matches << setw(5) << Ar[j].Batting_average << endl;
cout << "---------------------------------------------------------------------" << endl;
}
}
for (int j = 0; j < 8; j++)
{
if (batavg[i] == Wk[j].Batting_average) // checks where the given (batavg) occurs in the stat file
{
cout << left << setw(5) << id[i] << setw(11) << Wk[j].First_name << setw(13) << Wk[j].Last_name << setw(28) << Wk[j].Team << setw(5) << Wk[j].No_of_matches << setw(5) << Wk[j].Batting_average << endl;
cout << "---------------------------------------------------------------------" << endl;
}
}
}
}
void Display_top10_wkt(Bowler *Bo, All_rounder *Ar)
{
fstream bowl("bowlers.txt");
if (!bowl)
cout << "Error opening the file!!" << endl;
fstream allrounder("all_rounders.txt");
if (!allrounder)
cout << "Error opening the file!!" << endl;
int id[83];
bowl.seekg(0);
allrounder.seekg(0);
for (int i = 0; i < 53; i++)
{
bowl >> id[i] >> Bo[i].First_name >> Bo[i].Last_name >> Bo[i].Age >> Bo[i].Team >> Bo[i].Country >> Bo[i].No_of_matches >> Bo[i].Innings >> Bo[i].Wickets >> Bo[i].Economy >> Bo[i].Bowling_average >> Bo[i].Best_Bowling_figure >> Bo[i].Four_wkt_hauls >> Bo[i].Runs >> Bo[i].Batting_strike_rate >> Bo[i].Batting_average >> Bo[i].Best_Batting_figure >> Bo[i].Fours >> Bo[i].Sixes;
}
for (int i = 53; i < 83; i++)
{
allrounder >> id[i] >> Ar[i - 53].First_name >> Ar[i - 53].Last_name >> Ar[i - 53].Age >> Ar[i - 53].Team >> Ar[i - 53].Country >> Ar[i - 53].No_of_matches >> Ar[i - 53].Innings >> Ar[i - 53].Runs >> Ar[i - 53].Batting_strike_rate >> Ar[i - 53].Batting_average >> Ar[i - 53].Fifties >> Ar[i - 53].Centuries >> Ar[i - 53].Best_Batting_figure >> Ar[i - 53].Fours >> Ar[i - 53].Sixes >> Ar[i - 53].Wickets >> Ar[i - 53].Economy >> Ar[i - 53].Bowling_average >> Ar[i - 53].Best_Bowling_figure >> Ar[i - 53].Four_wkt_hauls;
}
int wkts[83];
for (int i = 0; i < 53; i++)
wkts[i] = Bo[i].Wickets;
for (int i = 53; i < 83; i++)
wkts[i] = Ar[i - 53].Wickets;
int n = sizeof(wkts) / sizeof(wkts[0]);
sort(wkts, wkts + n, greater<int>());
int n1 = 83;
for (int i = 0; i < n1; ++i)
{
for (int j = i + 1; j < n1;)
{
if (wkts[i] == wkts[j]) //checks for multiple instances of same runs
{
for (int k = j; k < n1 - 1; ++k)
wkts[k] = wkts[k + 1];
--n1;
}
else
++j;
}
}
cout << "SNo F.Name L.Name TEAM TM Wkt" << endl
<< endl
<< endl;
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 53; j++)
{
if (wkts[i] == Bo[j].Wickets) // checks where the given (wkts) occurs in the stat file
{
cout << left << setw(5) << id[i] << setw(11) << Bo[j].First_name << setw(14) << Bo[j].Last_name << setw(28) << Bo[j].Team << setw(5) << Bo[j].No_of_matches << setw(5) << Bo[j].Wickets << endl;
cout << "------------------------------------------------------------------" << endl;
}
}
for (int j = 0; j < 30; j++)
{
if (wkts[i] == Ar[j].Wickets) // checks where the given (wkts) occurs in the stat file
{
cout << left << setw(5) << id[i] << setw(11) << Ar[j].First_name << setw(14) << Ar[j].Last_name << setw(28) << Ar[j].Team << setw(5) << Ar[j].No_of_matches << setw(5) << Ar[j].Wickets << endl;
cout << "------------------------------------------------------------------" << endl;
}
}
}
}
void Display_top10_bowlavg(Bowler *Bo, All_rounder *Ar)
{
fstream bowl("bowlers.txt");
if (!bowl)
cout << "Error opening the file!!" << endl;
fstream allrounder("all_rounders.txt");
if (!allrounder)
cout << "Error opening the file!!" << endl;
int id[83];
bowl.seekg(0);
allrounder.seekg(0);
for (int i = 0; i < 53; i++)
{
bowl >> id[i] >> Bo[i].First_name >> Bo[i].Last_name >> Bo[i].Age >> Bo[i].Team >> Bo[i].Country >> Bo[i].No_of_matches >> Bo[i].Innings >> Bo[i].Wickets >> Bo[i].Economy >> Bo[i].Bowling_average >> Bo[i].Best_Bowling_figure >> Bo[i].Four_wkt_hauls >> Bo[i].Runs >> Bo[i].Batting_strike_rate >> Bo[i].Batting_average >> Bo[i].Best_Batting_figure >> Bo[i].Fours >> Bo[i].Sixes;
}
for (int i = 53; i < 83; i++)
{
allrounder >> id[i] >> Ar[i - 53].First_name >> Ar[i - 53].Last_name >> Ar[i - 53].Age >> Ar[i - 53].Team >> Ar[i - 53].Country >> Ar[i - 53].No_of_matches >> Ar[i - 53].Innings >> Ar[i - 53].Runs >> Ar[i - 53].Batting_strike_rate >> Ar[i - 53].Batting_average >> Ar[i - 53].Fifties >> Ar[i - 53].Centuries >> Ar[i - 53].Best_Batting_figure >> Ar[i - 53].Fours >> Ar[i - 53].Sixes >> Ar[i - 53].Wickets >> Ar[i - 53].Economy >> Ar[i - 53].Bowling_average >> Ar[i - 53].Best_Bowling_figure >> Ar[i - 53].Four_wkt_hauls;
}
float bowlavg[83];
for (int i = 0; i < 53; i++)
bowlavg[i] = Bo[i].Bowling_average;
for (int i = 53; i < 83; i++)
bowlavg[i] = Ar[i - 53].Bowling_average;
int tot = 83;
for (int i = 0; i < tot; i++)
{
if (bowlavg[i] == 0)
{
for (int j = i; j < (tot - 1); j++)
bowlavg[j] = bowlavg[j + 1];
i--;
tot--;
}
}
int n = sizeof(bowlavg) / sizeof(bowlavg[0]);
sort(bowlavg, bowlavg + n);
int n1 = 83;
for (int i = 0; i < n1; ++i)
{
for (int j = i + 1; j < n1;)
{
if (bowlavg[i] == bowlavg[j]) //checks for multiple instances of same runs
{
for (int k = j; k < n1 - 1; ++k)
bowlavg[k] = bowlavg[k + 1];
--n1;
}
else
++j;
}
}
cout << "SNo F.Name L.Name TEAM TM Bowl Avg" << endl
<< endl
<< endl;
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 53; j++)
{
if (bowlavg[i] == Bo[j].Bowling_average) // checks where the given (bowlavg) occurs in the stat file
{
cout << left << setw(5) << id[i] << setw(11) << Bo[j].First_name << setw(14) << Bo[j].Last_name << setw(28) << Bo[j].Team << setw(5) << Bo[j].No_of_matches << setw(5) << Bo[j].Bowling_average << endl;
cout << "-----------------------------------------------------------------------" << endl;
}
}
for (int j = 0; j < 30; j++)
{
if (bowlavg[i] == Ar[j].Bowling_average) // checks where the given (bowlavg) occurs in the stat file
{
cout << left << setw(5) << id[i] << setw(11) << Ar[j].First_name << setw(14) << Ar[j].Last_name << setw(28) << Ar[j].Team << setw(5) << Ar[j].No_of_matches << setw(5) << Ar[j].Bowling_average << endl;
cout << "-----------------------------------------------------------------------" << endl;
}
}
}
}
void Display_top10_eco(Bowler *Bo, All_rounder *Ar)
{
fstream bowl("bowlers.txt");
if (!bowl)
cout << "Error opening the file!!" << endl;
fstream allrounder("all_rounders.txt");
if (!allrounder)
cout << "Error opening the file!!" << endl;
int id[83];
bowl.seekg(0);
allrounder.seekg(0);
for (int i = 0; i < 53; i++)
{
bowl >> id[i] >> Bo[i].First_name >> Bo[i].Last_name >> Bo[i].Age >> Bo[i].Team >> Bo[i].Country >> Bo[i].No_of_matches >> Bo[i].Innings >> Bo[i].Wickets >> Bo[i].Economy >> Bo[i].Bowling_average >> Bo[i].Best_Bowling_figure >> Bo[i].Four_wkt_hauls >> Bo[i].Runs >> Bo[i].Batting_strike_rate >> Bo[i].Batting_average >> Bo[i].Best_Batting_figure >> Bo[i].Fours >> Bo[i].Sixes;
}
for (int i = 53; i < 83; i++)
{
allrounder >> id[i] >> Ar[i - 53].First_name >> Ar[i - 53].Last_name >> Ar[i - 53].Age >> Ar[i - 53].Team >> Ar[i - 53].Country >> Ar[i - 53].No_of_matches >> Ar[i - 53].Innings >> Ar[i - 53].Runs >> Ar[i - 53].Batting_strike_rate >> Ar[i - 53].Batting_average >> Ar[i - 53].Fifties >> Ar[i - 53].Centuries >> Ar[i - 53].Best_Batting_figure >> Ar[i - 53].Fours >> Ar[i - 53].Sixes >> Ar[i - 53].Wickets >> Ar[i - 53].Economy >> Ar[i - 53].Bowling_average >> Ar[i - 53].Best_Bowling_figure >> Ar[i - 53].Four_wkt_hauls;
}
float eco[83];
for (int i = 0; i < 53; i++)
eco[i] = Bo[i].Economy;
for (int i = 53; i < 83; i++)
eco[i] = Ar[i - 53].Economy;
int tot = 83;
for (int i = 0; i < tot; i++)
{
if (eco[i] == 0)
{
for (int j = i; j < (tot - 1); j++)
eco[j] = eco[j + 1];
i--;
tot--;
}
}
int n = sizeof(eco) / sizeof(eco[0]);
sort(eco, eco + n);
int n1 = 83;
for (int i = 0; i < n1; ++i)
{
for (int j = i + 1; j < n1;)
{
if (eco[i] == eco[j]) //checks for multiple instances of same runs
{
for (int k = j; k < n1 - 1; ++k)
eco[k] = eco[k + 1];
--n1;
}
else
++j;
}
}
cout << "SNo F.Name L.Name TEAM TM Eco" << endl
<< endl
<< endl;
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 53; j++)
{
if (eco[i] == Bo[j].Economy) // checks where the given (eco) occurs in the stat file
{
cout << left << setw(5) << id[i] << setw(11) << Bo[j].First_name << setw(14) << Bo[j].Last_name << setw(28) << Bo[j].Team << setw(5) << Bo[j].No_of_matches << setw(5) << Bo[j].Economy << endl;
cout << "--------------------------------------------------------------------" << endl;
}
}
for (int j = 0; j < 30; j++)
{
if (eco[i] == Ar[j].Economy) // checks where the given (eco) occurs in the stat file
{
cout << left << setw(5) << id[i] << setw(11) << Ar[j].First_name << setw(14) << Ar[j].Last_name << setw(28) << Ar[j].Team << setw(5) << Ar[j].No_of_matches << setw(5) << Ar[j].Economy << endl;
cout << "--------------------------------------------------------------------" << endl;
}
}
}
}
void Display_top10_goal(Attack *A, MidField *Mf, Defence *D)
{
fstream forward("attack.txt");
if (!forward)
cout << "Error opening the file!!" << endl;
fstream midf("midfield.txt");
if (!midf)
cout << "Error opening the file!!" << endl;
fstream defence("DEFENDERS.txt");
if (!defence)
cout << "Error opening the file!!" << endl;
forward.seekg(0);
midf.seekg(0);
defence.seekg(0);
int id[276];
int _id = 1;
for (int i = 0; i < 276; i++)
{
id[i] = _id;
_id++;
}
for (int i = 0; i < 58; i++)
{
forward >> A[i].First_name >> A[i].Last_name >> A[i].Position >> A[i].Age >> A[i].Team >> A[i].Country >> A[i].No_of_matches >> A[i].Goals >> A[i].Shot_accuracy >> A[i].Assist >> A[i].Pass_Accuracy >> A[i].Red_card;
}
for (int i = 58; i < 169; i++)
{
midf >> Mf[i - 58].First_name >> Mf[i - 58].Last_name >> Mf[i - 58].Position >> Mf[i - 58].Age >> Mf[i - 58].Team >> Mf[i - 58].Country >> Mf[i - 58].No_of_matches >> Mf[i - 58].Goals >> Mf[i - 58].Shot_accuracy >> Mf[i - 58].Assist >> Mf[i - 58].Pass_Accuracy >> Mf[i - 58].Red_card;
}
for (int i = 169; i < 276; i++)
{
defence >> D[i - 169].First_name >> D[i - 169].Last_name >> D[i - 169].Position >> D[i - 169].Age >> D[i - 169].Team >> D[i - 169].Country >> D[i - 169].No_of_matches >> D[i - 169].Tackles_won >> D[i - 169].Clearance >> D[i - 169].Blocked_shots >> D[i - 169].Red_card >> D[i - 169].Goals >> D[i - 169].Pass_Accuracy;
}
int goalrt[276];
for (int i = 0; i < 58; i++)
goalrt[i] = A[i].Goals;
for (int i = 58; i < 169; i++)
goalrt[i] = Mf[i - 58].Goals;
for (int i = 169; i < 276; i++)
goalrt[i] = D[i - 169].Goals;
int n = sizeof(goalrt) / sizeof(goalrt[0]);
sort(goalrt, goalrt + n, greater<int>());
int n1 = 276;
for (int i = 0; i < n1; ++i)
{
for (int j = i + 1; j < n1;)
{
if (goalrt[i] == goalrt[j]) //checks for multiple instances of same goals
{
for (int k = j; k < n1 - 1; ++k)
goalrt[k] = goalrt[k + 1];
--n1;
}
else
++j;
}
}
cout << "SNo Name Pos Age Club Country GP Goals" << endl
<< endl;
int check = 1;
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 58; j++)
{
if (goalrt[i] == A[j].Goals && check <= 10) // checks where the given (goals) occurs in the stat file
{
check++;
cout << left << setw(4) << id[i] << setw(10) << A[j].First_name << setw(14) << A[j].Last_name << setw(5) << A[j].Position << setw(4) << A[j].Age << setw(22) << A[j].Team << setw(13) << A[j].Country << setw(5) << A[j].No_of_matches << setw(6) << A[j].Goals << endl;
cout << "----------------------------------------------------------------------------------" << endl;
}
}
for (int j = 0; j < 111; j++)
{
if (goalrt[i] == Mf[j].Goals && check <= 10) // checks where the given (goals) occurs in the stat file
{
check++;
cout << left << setw(4) << id[i] << setw(10) << Mf[j].First_name << setw(14) << Mf[j].Last_name << setw(5) << Mf[j].Position << setw(4) << Mf[j].Age << setw(22) << Mf[j].Team << setw(13) << Mf[j].Country << setw(5) << Mf[j].No_of_matches << setw(6) << Mf[j].Goals << endl;
cout << "----------------------------------------------------------------------------------" << endl;
}
}
for (int j = 0; j < 107; j++)
{
if (goalrt[i] == D[j].Goals && check <= 10) // checks where the given (goals) occurs in the stat file
{
check++;
cout << left << setw(4) << id[i] << setw(10) << D[j].First_name << setw(14) << D[j].Last_name << setw(5) << D[j].Position << setw(4) << D[j].Age << setw(22) << D[j].Team << setw(13) << D[j].Country << setw(5) << D[j].No_of_matches << setw(7) << D[j].Goals << endl;
cout << "-----------------------------------------------------------------------------------" << endl;
}
}
}
}
void Display_top10_cleansheet(GoalKeeper *Gk)
{
fstream gk("gk.txt");
if (!gk)
cout << "Error opening the file!!" << endl;
gk.seekg(0);
int id[27];
int _id = 1;
for (int i = 0; i < 27; i++)
{
id[i] = _id;
_id++;
}
for (int i = 0; i < 27; i++)
{
gk >> Gk[i].First_name >> Gk[i].Last_name >> Gk[i].Position >> Gk[i].Age >> Gk[i].Team >> Gk[i].Country >> Gk[i].No_of_matches >> Gk[i].Clean_sheets >> Gk[i].Saves_made >> Gk[i].Goals_conceeded >> Gk[i].Red_card;
}
int cs[27];
for (int i = 0; i < 27; i++)
cs[i] = Gk[i].Clean_sheets;
int n = sizeof(cs) / sizeof(cs[0]);
sort(cs, cs + n, greater<int>());
int n1 = 27;
for (int i = 0; i < n1; ++i)
{
for (int j = i + 1; j < n1;)
{
if (cs[i] == cs[j]) //checks for multiple instances of same goals
{
for (int k = j; k < n1 - 1; ++k)
cs[k] = cs[k + 1];
--n1;
}
else
++j;
}
}
cout << "SNo Name Pos Age Club Country GP C.Sheet" << endl
<< endl;
int check = 1;
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 58; j++)
{
if (cs[i] == Gk[j].Clean_sheets && check <= 10) // checks where the given (cleansheet) occurs in the stat file
{
check++;
cout << left << setw(4) << id[i] << setw(10) << Gk[j].First_name << setw(14) << Gk[j].Last_name << setw(5) << Gk[j].Position << setw(4) << Gk[j].Age << setw(22) << Gk[j].Team << setw(13) << Gk[j].Country << setw(5) << Gk[j].No_of_matches << setw(6) << Gk[j].Clean_sheets << endl;
cout << "------------------------------------------------------------------------------------" << endl;
}
}
}
}
void Display_top10_assist(Attack *A, MidField *Mf)
{
fstream forward("attack.txt");
if (!forward)
cout << "Error opening the file!!" << endl;
fstream midf("midfield.txt");
if (!midf)
cout << "Error opening the file!!" << endl;
forward.seekg(0);
midf.seekg(0);
int id[169];
int _id = 1;
for (int i = 0; i < 169; i++)
{
id[i] = _id;
_id++;
}
for (int i = 0; i < 58; i++)
{
forward >> A[i].First_name >> A[i].Last_name >> A[i].Position >> A[i].Age >> A[i].Team >> A[i].Country >> A[i].No_of_matches >> A[i].Goals >> A[i].Shot_accuracy >> A[i].Assist >> A[i].Pass_Accuracy >> A[i].Red_card;
}
for (int i = 58; i < 169; i++)
{
midf >> Mf[i - 58].First_name >> Mf[i - 58].Last_name >> Mf[i - 58].Position >> Mf[i - 58].Age >> Mf[i - 58].Team >> Mf[i - 58].Country >> Mf[i - 58].No_of_matches >> Mf[i - 58].Goals >> Mf[i - 58].Shot_accuracy >> Mf[i - 58].Assist >> Mf[i - 58].Pass_Accuracy >> Mf[i - 58].Red_card;
}
int assrt[169];
for (int i = 0; i < 58; i++)
assrt[i] = A[i].Assist;
for (int i = 58; i < 169; i++)
assrt[i] = Mf[i - 58].Assist;
int n = sizeof(assrt) / sizeof(assrt[0]);
sort(assrt, assrt + n, greater<int>());
int n1 = 169;
for (int i = 0; i < n1; ++i)
{
for (int j = i + 1; j < n1;)
{
if (assrt[i] == assrt[j]) //checks for multiple instances of same goals
{
for (int k = j; k < n1 - 1; ++k)
assrt[k] = assrt[k + 1];
--n1;
}
else
++j;
}
}
cout << "SNo Name Pos Age Club Country GP Assist" << endl
<< endl;
int check = 1;
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 58; j++)
{
if (assrt[i] == A[j].Assist && check <= 10) // checks where the given (assist) occurs in the stat file
{
check++;
cout << left << setw(4) << id[i] << setw(10) << A[j].First_name << setw(14) << A[j].Last_name << setw(5) << A[j].Position << setw(4) << A[j].Age << setw(22) << A[j].Team << setw(13) << A[j].Country << setw(5) << A[j].No_of_matches << setw(6) << A[j].Assist << endl;
cout << "-----------------------------------------------------------------------------------" << endl;
}
}
for (int j = 0; j < 111; j++)
{
if (assrt[i] == Mf[j].Assist && check <= 10) // checks where the given (assist) occurs in the stat file
{
check++;
cout << left << setw(4) << id[i] << setw(10) << Mf[j].First_name << setw(14) << Mf[j].Last_name << setw(5) << Mf[j].Position << setw(4) << Mf[j].Age << setw(22) << Mf[j].Team << setw(13) << Mf[j].Country << setw(5) << Mf[j].No_of_matches << setw(6) << Mf[j].Assist << endl;
cout << "-----------------------------------------------------------------------------------" << endl;
}
}
}
}
void Display_top10_defenders(Defence *D)
{
fstream defence("DEFENDERS.txt");
if (!defence)
cout << "Error opening the file!!" << endl;
defence.seekg(0);
int id[107];
int _id = 1;
for (int i = 0; i < 107; i++)
{
id[i] = _id;
_id++;
}
for (int i = 0; i < 107; i++)
{
defence >> D[i].First_name >> D[i].Last_name >> D[i].Position >> D[i].Age >> D[i].Team >> D[i].Country >> D[i].No_of_matches >> D[i].Tackles_won >> D[i].Clearance >> D[i].Blocked_shots >> D[i].Red_card >> D[i].Goals >> D[i].Pass_Accuracy;
}
int clrt[107];
for (int i = 0; i < 107; i++)
clrt[i] = D[i].Clearance;
int n = sizeof(clrt) / sizeof(clrt[0]);
sort(clrt, clrt + n, greater<int>());
int n1 = 107;
for (int i = 0; i < n1; ++i)
{
for (int j = i + 1; j < n1;)
{
if (clrt[i] == clrt[j]) //checks for multiple instances of same goals
{
for (int k = j; k < n1 - 1; ++k)
clrt[k] = clrt[k + 1];
--n1;
}
else
++j;
}
}
cout << "SNo Name Pos Age Club Country GP Clearance" << endl
<< endl;
int check = 1;
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 107; j++)
{
if (clrt[i] == D[j].Clearance && check <= 10) // checks where the given (clearance) occurs in the stat file
{
check++;
cout << left << setw(4) << id[i] << setw(10) << D[j].First_name << setw(14) << D[j].Last_name << setw(5) << D[j].Position << setw(4) << D[j].Age << setw(22) << D[j].Team << setw(13) << D[j].Country << setw(5) << D[j].No_of_matches << setw(7) << D[j].Clearance << endl;
cout << "--------------------------------------------------------------------------------------" << endl;
}
}
}
}
void Display_top10_leastgoal(GoalKeeper *Gk)
{
fstream gk("gk.txt");
if (!gk)
cout << "Error opening the file!!" << endl;
gk.seekg(0);
int id[27];
int _id = 1;
for (int i = 0; i < 27; i++)
{
id[i] = _id;
_id++;
}
for (int i = 0; i < 27; i++)
{
gk >> Gk[i].First_name >> Gk[i].Last_name >> Gk[i].Position >> Gk[i].Age >> Gk[i].Team >> Gk[i].Country >> Gk[i].No_of_matches >> Gk[i].Clean_sheets >> Gk[i].Saves_made >> Gk[i].Goals_conceeded >> Gk[i].Red_card;
}
int gc[27];
for (int i = 0; i < 27; i++)
gc[i] = Gk[i].Goals_conceeded;
int tot = 83;
for (int i = 0; i < tot; i++)
{
if (gc[i] == 0)
{
for (int j = i; j < (tot - 1); j++)
gc[j] = gc[j + 1];
i--;
tot--;
}
}
int n = sizeof(gc) / sizeof(gc[0]);
sort(gc, gc + n);
int n1 = 27;
for (int i = 0; i < n1; ++i)
{
for (int j = i + 1; j < n1;)
{
if (gc[i] == gc[j]) //checks for multiple instances of same goals
{
for (int k = j; k < n1 - 1; ++k)
gc[k] = gc[k + 1];
--n1;
}
else
++j;
}
}
cout << "SNo Name Pos Age Club Country GP Goal Conceeded" << endl
<< endl;
int check = 1;
int s_no = 1;
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 58; j++)
{
if (gc[i] == Gk[j].Goals_conceeded && check <= 10) // checks where the given (gc) occurs in the stat file
{
check++;
cout << left << setw(4) << s_no << setw(10) << Gk[j].First_name << setw(14) << Gk[j].Last_name << setw(5) << Gk[j].Position << setw(4) << Gk[j].Age << setw(22) << Gk[j].Team << setw(13) << Gk[j].Country << setw(5) << Gk[j].No_of_matches << setw(5) << Gk[j].Goals_conceeded << endl;
cout << "-------------------------------------------------------------------------------------------" << endl;
s_no++;
}
}
}
}
//Main function of the program
int main()
{
system("COLOR 06");
Sports S; //Object declaration for the Sports
Football F[500];
Attack A[100];
MidField Mf[120];
Defence D[120];
GoalKeeper Gk[100];
Basketball B[500];
Cricket C[200];
Batsman Bt[50];
Bowler Bo[60];
All_rounder Ar[50];
Wicket_keeper Wk[10];
start: //Goto point for the Main Menu
system("cls");
S.Main_Display();
int num;
cin >> num; //Main menu choice input
system("cls");
if (num == 1)
{
checkpoint_1: // Go-to point for Main menu of football
F->Display_content_f();
int switch_f; //For selecting options for football
cin >> switch_f;
system("cls");
switch (switch_f)
{
case 1:
F->Team_display_f();
system("pause");
system("cls");
goto checkpoint_1; // returns to main content selection menu of football
checkpoint_1_1:
case 2:
cout << " >>>>>> Welcome to Football <<<<<<" << endl
<< endl;
cout << " X--------- View Players --------X" << endl
<< endl;
cout << " 1. Search Player " << endl
<< " 2. View All Players " << endl
<< " 3. Return to Main Menu" << endl
<< " 0. Exit the program " << endl
<< endl;
cout << " Enter your choice: ";
int player;
cin >> player;
system("cls");
if (player == 1)
{
checkpoint_1_1_1:
cout << " 1. Forward" << endl
<< " 2. Mid-Fielder" << endl
<< " 3. Defender " << endl
<< " 4. Goal-Keeper" << endl
<< " 5. Return to Main Menu" << endl
<< endl;
cout << " Enter your choice: ";
int category;
cin >> category;
system("cls");
string name;
switch (category)
{
case 1:
cout << "Enter name of the player to search : ";
cin >> name;
A->Search_player_f_a(A, name);
system("pause");
system("cls");
goto checkpoint_1_1_1;
break;
case 2:
cout << "Enter name of the player to search : ";
cin >> name;
Mf->Search_player_f_m(Mf, name);
system("pause");
system("cls");
goto checkpoint_1_1_1;
break;
case 3:
cout << "Enter name of the player to search : ";
cin >> name;
D->Search_player_f_d(D, name);
system("pause");
system("cls");
goto checkpoint_1_1_1;
break;
case 4:
cout << "Enter name of the player to search : ";
cin >> name;
Gk->Search_player_f_gk(Gk, name);
system("pause");
system("cls");
goto checkpoint_1_1_1;
break;
case 5:
system("cls");
goto checkpoint_1_1;
break;
default:
cout << "No such option available! Please try again!" << endl;
system("pause");
system("cls");
goto checkpoint_1_1_1;
break;
}
system("pause");
system("cls");
goto checkpoint_1_1; // returns to player menu of football
}
else if (player == 2)
{
A->Player_display_f_a(A);
Mf->Player_display_f_m(Mf);
D->Player_display_f_d(D);
Gk->Player_display_f_gk(Gk);
system("pause");
system("cls");
goto checkpoint_1_1; // returns to player menu of football
}
else if (player == 3)
{
system("cls");
goto checkpoint_1; // returns to main content selection menu of football
}
else if (player == 0)
{
system("cls");
exit(0); //EXITS THE PROGRAM
}
else
{
cout << "No such option available! Please try again!" << endl;
system("pause");
system("cls");
goto checkpoint_1_1; // returns to stat menu of football
}
break;
checkpoint_1_2:
case 3:
cout << " >>>>>> Welcome to Football <<<<<<" << endl
<< endl;
cout << " X---------- View Stats ---------X" << endl
<< endl;
cout << " 1. View Top Players" << endl
<< " 2. View Stats by Positions " << endl
<< " 3. Return to Main Menu" << endl
<< " 0. Exit the program" << endl
<< endl;
cout << " Enter your choice: ";
int stat;
cin >> stat;
system("cls");
if (stat == 1)
{
checkpoint_1_2_1:
int top;
cout << " >>>>>> Welcome to Football <<<<<<" << endl
<< endl;
cout << " X----- View League Leaders -----X" << endl
<< endl;
cout << " 1. Top Goal Scorers" << endl
<< " 2. Top Assists" << endl
<< " 3. Cleansheets" << endl
<< " 4. Top Defenders " << endl
<< " 5. Least Goals Conceeded" << endl
<< " 6. Return to Main Menu" << endl
<< " 0. Exit the program" << endl
<< endl;
cout << " Enter your choice: ";
cin >> top;
system("cls");
switch (top)
{
case 1:
Display_top10_goal(A, Mf, D);
system("pause");
system("cls");
goto checkpoint_1_2_1;
break;
case 2:
Display_top10_assist(A, Mf);
system("pause");
system("cls");
goto checkpoint_1_2_1;
break;
case 3:
Display_top10_cleansheet(Gk);
system("pause");
system("cls");
goto checkpoint_1_2_1;
break;
case 4:
Display_top10_defenders(D);
system("pause");
system("cls");
goto checkpoint_1_2_1;
break;
case 5:
Display_top10_leastgoal(Gk);
system("pause");
system("cls");
goto checkpoint_1_2_1;
break;
case 6:
system("cls");
goto checkpoint_1_2;
break;
case 0:
system("cls");
exit(0);
default:
cout << "No such option available! Please try again!" << endl;
system("pause");
system("cls");
goto checkpoint_1_2_1;
break;
}
system("pause");
system("cls");
goto checkpoint_1_2; // returns to stat menu of football
}
else if (stat == 2)
{
checkpoint_1_2_2:
cout << " 1. Forward" << endl
<< " 2. Mid-Field" << endl
<< " 3. Defence " << endl
<< " 4. Goal-keeper" << endl
<< " 5. Return to Main Menu" << endl
<< endl;
cout << " Enter your choice: ";
int position;
cin >> position;
system("cls");
switch (position)
{
case 1:
A->Display_stats_f_a(A);
system("pause");
system("cls");
goto checkpoint_1_2_2;
break;
case 2:
Mf->Display_stats_f_m(Mf);
system("pause");
system("cls");
goto checkpoint_1_2_2;
break;
case 3:
D->Display_stats_f_d(D);
system("pause");
system("cls");
goto checkpoint_1_2_2;
break;
case 4:
Gk->Display_stats_f_gk(Gk);
system("pause");
system("cls");
goto checkpoint_1_2_2;
break;
case 5:
system("cls");
goto checkpoint_1_2;
break;
default:
cout << "No such option available! Please try again!" << endl;
system("pause");
system("cls");
goto checkpoint_1_2_2;
break;
}
}
else if (stat == 3)
{
system("cls");
goto checkpoint_1; // returns to main content selection menu of football
}
else if (stat == 0)
{
system("cls");
exit(0); //EXITS THE PROGRAM
}
else
{
cout << "No such option available! Please try again!" << endl;
system("pause");
system("cls");
goto checkpoint_1_2; // returns to stat menu of football
}
break;
case 4:
F->Standings_display_f();
system("pause");
system("cls");
goto checkpoint_1; // returns to main content selection menu of football
case 5:
system("cls");
goto start; // returns to main menu of the Program
case 0:
system("cls");
exit(0); //EXITS the program
default:
cout << "No such option available! Please Try Again" << endl;
system("pause");
system("cls");
goto checkpoint_1; // returns to main content selection menu of football in case of invalid option
}
}
else if (num == 2)
{
checkpoint_2: // Goto point for Main menu of basketball
B->Display_content_b();
int switch_b; //For selecting options for basketball
cin >> switch_b;
system("cls");
switch (switch_b)
{
case 1:
B->Team_display_b();
system("pause");
system("cls");
goto checkpoint_2; // returns to main content selection menu of basketball
checkpoint_2_1:
case 2:
cout << " >>>> Welcome to Basketball <<<<" << endl
<< endl;
cout << " X--------- View Players --------X" << endl
<< endl;
cout << " 1. Search Player " << endl
<< " 2. View All Players " << endl
<< " 3. Return to Main Menu" << endl
<< " 0. Exit the program " << endl
<< endl;
cout << " Enter your choice: ";
int player;
cin >> player;
system("cls");
if (player == 1)
{
B->Search_player_b(B);
system("pause");
system("cls");
goto checkpoint_2_1; // returns to player menu of basketball
}
else if (player == 2)
{
B->Player_display_b(B);
system("pause");
system("cls");
goto checkpoint_2_1; // returns to player menu of basketball
}
else if (player == 3)
{
system("cls");
goto checkpoint_2; // returns to main content selection menu of basketball
}
else if (player == 0)
{
system("cls");
exit(0); //EXITS THE PROGRAM
}
else
{
cout << "No such option available! Please try again!" << endl;
system("pause");
system("cls");
goto checkpoint_2_1; // returns to stat menu of basketball
}
break;
checkpoint_2_2:
case 3:
cout << " >>>> Welcome to Basketball <<<<" << endl
<< endl;
cout << " X---------- View Stats ---------X" << endl
<< endl;
cout << " 1. League Leaders" << endl
<< " 2. All Stats" << endl
<< " 3. Return to Main Menu" << endl
<< " 0. Exit the program" << endl
<< endl;
cout << " Enter your choice: ";
int stat;
cin >> stat;
system("cls");
if (stat == 1)
{
system("cls");
checkpoint_2_2_1:
int top;
cout << " >>>> Welcome to Basketball <<<<" << endl
<< endl;
cout << " X----- View League Leaders -----X" << endl
<< endl;
cout << " 1. Total Points" << endl
<< " 2. Total Assists" << endl
<< " 3. Total Rebounds" << endl
<< " 4. Field Goal Percentage " << endl
<< " 5. Three-point Percentage" << endl
<< " 6. Free Throw Percentage" << endl
<< " 7. Return to Main Menu" << endl
<< " 0. Exit the program" << endl
<< endl;
cout << " Enter your choice: ";
cin >> top;
system("cls");
switch (top)
{
case 1:
B->Display_top10_b_p(B);
system("pause");
system("cls");
goto checkpoint_2_2_1;
break;
case 2:
B->Display_top10_b_a(B);
system("pause");
system("cls");
goto checkpoint_2_2_1;
break;
case 3:
B->Display_top10_b_r(B);
system("pause");
system("cls");
goto checkpoint_2_2_1;
break;
case 4:
B->Display_top10_b_fg(B);
system("pause");
system("cls");
goto checkpoint_2_2_1;
break;
case 5:
B->Display_top10_b_3p(B);
system("pause");
system("cls");
goto checkpoint_2_2_1;
break;
case 6:
B->Display_top10_b_ft(B);
system("pause");
system("cls");
goto checkpoint_2_2_1;
break;
case 7:
system("cls");
goto checkpoint_2_2;
break;
case 0:
system("cls");
exit(0);
default:
cout << "No such option available! Please try again!" << endl;
system("pause");
system("cls");
goto checkpoint_2_2_1;
break;
}
goto checkpoint_2_2; // returns to stat menu of basketball
}
else if (stat == 2)
{
B->Stats_display_b(B);
system("pause");
system("cls");
goto checkpoint_2_2; // returns to stat menu of basketball
}
else if (stat == 3)
{
system("cls");
goto checkpoint_2; // returns to main content selection menu of basketball
}
else if (stat == 0)
{
system("cls");
exit(0); //EXITS THE PROGRAM
}
else
{
cout << "No such option available! Please try again!" << endl;
system("pause");
system("cls");
goto checkpoint_2_2; // returns to stat menu of basketball
}
break;
case 4:
B->Standings_display_b();
system("pause");
system("cls");
goto checkpoint_2; // returns to main content selection menu of basketball
case 5:
system("cls");
goto start; // returns to main menu of the Program
case 0:
system("cls");
exit(0); // EXITS Program
default:
cout << "No such option available! Please Try Again" << endl;
system("pause");
system("cls");
goto checkpoint_2; // returns to main content selection menu of basketball in case of invalid option
}
}
else if (num == 3)
{
checkpoint_3: // Goto point for Main menu of cricket
C->Display_content_c();
int switch_c; //For selecting options for cricket
cin >> switch_c;
system("cls");
switch (switch_c)
{
case 1:
C->Team_display_c();
system("pause");
system("cls");
goto checkpoint_3; // returns to main content selection menu of cricket
checkpoint_3_1:
case 2:
cout << " >>>>>> Welcome to Cricket <<<<<<" << endl
<< endl;
cout << " X--------- View Players --------X" << endl
<< endl;
cout << " 1. Search Player " << endl
<< " 2. View All Players " << endl
<< " 3. Return to Main Menu" << endl
<< " 0. Exit the program " << endl
<< endl;
cout << " Enter your choice: ";
int player;
cin >> player;
system("cls");
if (player == 1)
{
checkpoint_3_1_1:
cout << " 1. Batsman" << endl
<< " 2. Bowler" << endl
<< " 3. All-Rounder " << endl
<< " 4. Wicket-Keeper" << endl
<< " 5. Return to Main Menu" << endl
<< endl;
cout << " Enter your choice: ";
int category;
cin >> category;
system("cls");
cout << "Enter name of the player to search : ";
string name;
switch (category)
{
case 1:
cin >> name;
Bt->Search_player_c_bt(Bt, name);
system("pause");
system("cls");
goto checkpoint_3_1_1;
break;
case 2:
cin >> name;
Bo->Search_player_c_bo(Bo, name);
system("pause");
system("cls");
goto checkpoint_3_1_1;
break;
case 3:
cin >> name;
Ar->Search_player_c_ar(Ar, name);
system("pause");
system("cls");
goto checkpoint_3_1_1;
break;
case 4:
cin >> name;
Wk->Search_player_c_wk(Wk, name);
system("pause");
system("cls");
goto checkpoint_3_1_1;
break;
case 5:
system("cls");
goto checkpoint_3_1;
break;
default:
cout << "No such option available! Please try again!" << endl;
system("pause");
system("cls");
goto checkpoint_3_1_1;
break;
}
system("pause");
system("cls");
goto checkpoint_3_1; // returns to player menu of cricket
}
else if (player == 2)
{
Bt->Player_display_c_bt(Bt);
Bo->Player_display_c_bo(Bo);
Ar->Player_display_c_ar(Ar);
Wk->Player_display_c_wk(Wk);
system("pause");
system("cls");
goto checkpoint_3_1; // returns to player menu of cricket
}
else if (player == 3)
{
system("cls");
goto checkpoint_3; // returns to main content selection menu of cricket
}
else if (player == 0)
{
system("cls");
exit(0); //EXITS THE PROGRAM
}
else
{
cout << "No such option available! Please try again!" << endl;
system("pause");
system("cls");
goto checkpoint_3_1; // returns to stat menu of cricket
}
break;
checkpoint_3_2:
case 3:
cout << " >>>>>> Welcome to Cricket <<<<<<" << endl
<< endl;
cout << " X---------- View Stats ---------X" << endl
<< endl;
cout << " 1. View League Leaders" << endl
<< " 2. View Stats by Category " << endl
<< " 3. Return to Main Menu" << endl
<< " 0. Exit the program" << endl
<< endl;
cout << " Enter your choice: ";
int stat;
cin >> stat;
system("cls");
if (stat == 1)
{
checkpoint_3_2_1:
cout << " >>>>>> Welcome to Cricket <<<<<<" << endl
<< endl;
cout << " X----- View League Leaders -----X" << endl
<< endl;
cout << " 1. Top Run Scorers" << endl
<< " 2. Highest Batting Strike Rates" << endl
<< " 3. Highest Batting Average" << endl
<< " 4. Top Wicket Takers" << endl
<< " 5. Best Bowling Average" << endl
<< " 6. Best Economy Rate" << endl
<< " 7. Return to Previous Menu " << endl
<< " 0. Exit" << endl
<< endl;
cout << " Enter your choice: ";
int field;
cin >> field;
system("cls");
switch (field)
{
case 1:
Display_top10_run(Bt, Bo, Ar, Wk);
system("pause");
system("cls");
goto checkpoint_3_2_1;
break;
case 2:
Display_top10_strikerate(Bt, Ar, Wk);
system("pause");
system("cls");
goto checkpoint_3_2_1;
break;
case 3:
Display_top10_batavg(Bt, Ar, Wk);
system("pause");
system("cls");
goto checkpoint_3_2_1;
break;
case 4:
Display_top10_wkt(Bo, Ar);
system("pause");
system("cls");
goto checkpoint_3_2_1;
break;
case 5:
Display_top10_bowlavg(Bo, Ar);
system("pause");
system("cls");
goto checkpoint_3_2_1;
break;
case 6:
Display_top10_eco(Bo, Ar);
system("pause");
system("cls");
goto checkpoint_3_2_1;
break;
case 7:
system("cls");
goto checkpoint_3_2;
break;
case 0:
system("cls");
exit(0);
default:
cout << "No such option available! Please try again!" << endl;
system("pause");
system("cls");
goto checkpoint_3_2;
break;
}
system("pause");
system("cls");
goto checkpoint_3_2; // returns to stat menu of cricket
}
else if (stat == 2)
{
checkpoint_3_2_2:
cout << "1. Batsman" << endl
<< "2. Bowler" << endl
<< "3. All-Rounder " << endl
<< "4. Wicket-Keeper" << endl
<< "5. Return to Main Menu" << endl;
cout << "Enter your choice: ";
int category;
cin >> category;
system("cls");
switch (category)
{
case 1:
Bt->Display_stats_c_bt(Bt);
system("pause");
system("cls");
goto checkpoint_3_2_2;
break;
case 2:
Bo->Display_stats_c_bo(Bo);
system("pause");
system("cls");
goto checkpoint_3_2_2;
break;
case 3:
Ar->Display_stats_c_ar(Ar);
system("pause");
system("cls");
goto checkpoint_3_2_2;
break;
case 4:
Wk->Display_stats_c_wk(Wk);
system("pause");
system("cls");
goto checkpoint_3_2_2;
break;
case 5:
system("cls");
goto checkpoint_3_2;
break;
default:
cout << "No such option available! Please try again!" << endl;
system("pause");
system("cls");
goto checkpoint_3_2_2;
break;
}
}
else if (stat == 3)
{
system("cls");
goto checkpoint_3; // returns to main content selection menu of cricket
}
else if (stat == 0)
{
system("cls");
exit(0); //EXITS THE PROGRAM
}
else
{
cout << "No such option available! Please try again!" << endl;
system("pause");
system("cls");
goto checkpoint_3_2; // returns to stat menu of cricket
}
break;
case 4:
C->Standings_display_c();
system("pause");
system("cls");
goto checkpoint_3; // returns to main content selection menu of cricket
case 5:
system("cls");
goto start; // returns to main menu of the Program
case 0:
system("cls");
exit(0); // EXITS the program
default:
cout << "No such option available! Please Try Again" << endl;
system("pause");
system("cls");
goto checkpoint_3; // returns to main content selection menu of cricket in case of invalid option
}
}
else if (num == 0)
{
system("cls");
exit(0); //EXITS the program
}
else
{
cout << "No such option available! Please Try Again" << endl;
system("pause");
system("cls");
goto start; // returns to main content selection menu of cricket in case of invalid option
}
return 0;
}
|
0333abb05d804f7491c8817a98bd128347f5ad4c
|
[
"Markdown",
"C++"
] | 2 |
Markdown
|
devashish-gupta09/Sports-Analyzer
|
76aa7c4f8b387dc2d1b880ed4caedef52b4b8999
|
8fce7d0495b51ac2c1afbf098ac9f2e96b66184f
|
refs/heads/main
|
<repo_name>Vevark/ZOO_Attack_PyTorch<file_sep>/README.md
# ZOO: Zeroth Order Optimization Based Adversarial Black Box Attack (PyTorch)
This repository contains the PyTorch implementation of Zeroth Order Optimization Based Adversarial Black Box Attack(https://arxiv.org/abs/1708.03999) using MNIST and CIFAR10 dataset. This is the exact replica as far possible of the ZOO Attack (https://github.com/IBM/ZOO-Attack) which was originally implemented in Tensorflow. The results match almost as same as the paper evaluation results for MNIST and CIFAR10 for both targeted and untargeted attack all with 100% success rate on the 7 layer CNNs model trained on MNIST with 99.5% val accuracy and on CIFAR10 with 80% val accuracy as done in the original paper work. Both ZOO_Adam and ZOO_Newton methods of Coordinate Descent Solvers are implemented.
**Note: This doesn't contain implementation of importance sampling, hierarchical attack, and dimentional reduction right now (as its mainly needed for large image sized dataset like ImageNet).**
## Setup and train models
The code is tested with Python 3.7.6 and PyTorch 1.6.0. The following packages are required:
```
python pip install --upgrade pip
pip install torch==1.6.0 torchsummary==1.5.1 torchvision==0.7.0
pip install numpy matplotlib
```
To prepare model and datasets of MNIST and CIFAR10
```
python setup_mnist_model.py
python setup_cifar10_model.py
```
## Run attacks
To run the attacks run the
```
python zoo_l2_attack_black.py
```
Both untargeted and targeted attack are accessible via above code all the changes (comment/uncomment) for transition from ZOO_Adam/ZOO_Newton or CIFAR10/MNIST are from line 259-262, 270/271, 274-277 and for visualization of example generated, line 307/329. For more details go through the code zoo_l2_attack_black.py and the paper https://arxiv.org/abs/1708.03999
## Sample Results
#### ZOO_Adam
##### Untargeted on CIFAR10

##### Untargeted on CIFAR10

#### ZOO_Newton
##### Targeted on MNIST

<file_sep>/zoo_l2_attack_black.py
import numpy as np
import matplotlib.pyplot as plt
import torch
import torch.nn.functional as F
from torchvision import transforms,datasets
from numba import jit
import math
import time
import scipy.misc
import os
import sys
from PIL import Image
from setup_mnist_model import MNIST
from setup_cifar10_model import CIFAR10
"""##L2 Black Box Attack"""
@jit(nopython=True)
def coordinate_ADAM(losses, indice, grad, hess, batch_size, mt_arr, vt_arr, real_modifier, adam_epoch, up, down, step_size,beta1, beta2, proj):
for i in range(batch_size):
grad[i] = (losses[i*2+1] - losses[i*2+2]) / 0.0002
# ADAM update
mt = mt_arr[indice]
mt = beta1 * mt + (1 - beta1) * grad
mt_arr[indice] = mt
vt = vt_arr[indice]
vt = beta2 * vt + (1 - beta2) * (grad * grad)
vt_arr[indice] = vt
epoch = adam_epoch[indice]
corr = (np.sqrt(1 - np.power(beta2,epoch))) / (1 - np.power(beta1, epoch))
m = real_modifier.reshape(-1)
old_val = m[indice]
old_val -= step_size * corr * mt / (np.sqrt(vt) + 1e-8)
# set it back to [-0.5, +0.5] region
if proj:
old_val = np.maximum(np.minimum(old_val, up[indice]), down[indice])
m[indice] = old_val
adam_epoch[indice] = epoch + 1
@jit(nopython=True)
def coordinate_Newton(losses, indice, grad, hess, batch_size, mt_arr, vt_arr, real_modifier, adam_epoch, up, down, step_size, beta1, beta2, proj):
cur_loss = losses[0]
for i in range(batch_size):
grad[i] = (losses[i*2+1] - losses[i*2+2]) / 0.0002
hess[i] = (losses[i*2+1] - 2 * cur_loss + losses[i*2+2]) / (0.0001 * 0.0001)
hess[hess < 0] = 1.0
hess[hess < 0.1] = 0.1
m = real_modifier.reshape(-1)
old_val = m[indice]
old_val -= step_size * grad / hess
# set it back to [-0.5, +0.5] region
if proj:
old_val = np.maximum(np.minimum(old_val, up[indice]), down[indice])
m[indice] = old_val
def loss_run(input,target,model,modifier,use_tanh,use_log,targeted,confidence,const):
if use_tanh:
pert_out = torch.tanh(input +modifier)/2
else:
pert_out = input + modifier
output = model(pert_out)
if use_log:
output = F.softmax(output,-1)
if use_tanh:
loss1 = torch.sum(torch.square(pert_out-torch.tanh(input)/2),dim=(1,2,3))
else:
loss1 = torch.sum(torch.square(pert_out-input),dim=(1,2,3))
real = torch.sum(target*output,-1)
other = torch.max((1-target)*output-(target*10000),-1)[0]
if use_log:
real=torch.log(real+1e-30)
other=torch.log(other+1e-30)
confidence = torch.tensor(confidence).type(torch.float64).cuda()
if targeted:
loss2 = torch.max(other-real,confidence)
else:
loss2 = torch.max(real-other,confidence)
loss2 = const*loss2
l2 = loss1
loss = loss1 + loss2
return loss.detach().cpu().numpy(), l2.detach().cpu().numpy(), loss2.detach().cpu().numpy(), output.detach().cpu().numpy(), pert_out.detach().cpu().numpy()
def l2_attack(input, target, model, targeted, use_log, use_tanh, solver, reset_adam_after_found=True,abort_early=True,
batch_size=128,max_iter=1000,const=0.01,confidence=0.0,early_stop_iters=100, binary_search_steps=9,
step_size=0.01,adam_beta1=0.9,adam_beta2=0.999):
early_stop_iters = early_stop_iters if early_stop_iters != 0 else max_iter // 10
input = torch.from_numpy(input).cuda()
target = torch.from_numpy(target).cuda()
var_len = input.view(-1).size()[0]
modifier_up = np.zeros(var_len, dtype=np.float32)
modifier_down = np.zeros(var_len, dtype=np.float32)
real_modifier = torch.zeros(input.size(),dtype=torch.float32).cuda()
mt = np.zeros(var_len, dtype=np.float32)
vt = np.zeros(var_len, dtype=np.float32)
adam_epoch = np.ones(var_len, dtype=np.int32)
grad=np.zeros(batch_size,dtype=np.float32)
hess=np.zeros(batch_size,dtype=np.float32)
upper_bound=1e10
lower_bound=0.0
out_best_attack=input.clone().detach().cpu().numpy()
out_best_const=const
out_bestl2=1e10
out_bestscore=-1
if use_tanh:
input = torch.atanh(input*1.99999)
if not use_tanh:
modifier_up = 0.5-input.clone().detach().view(-1).cpu().numpy()
modifier_down = -0.5-input.clone().detach().view(-1).cpu().numpy()
def compare(x,y):
if not isinstance(x, (float, int, np.int64)):
if targeted:
x[y] -= confidence
else:
x[y] += confidence
x = np.argmax(x)
if targeted:
return x == y
else:
return x != y
for step in range(binary_search_steps):
bestl2 = 1e10
prev=1e6
bestscore=-1
last_loss2=1.0
# reset ADAM status
mt.fill(0)
vt.fill(0)
adam_epoch.fill(1)
stage=0
for iter in range(max_iter):
if (iter+1)%100 == 0:
loss, l2, loss2, _ , __ = loss_run(input,target,model,real_modifier,use_tanh,use_log,targeted,confidence,const)
print("[STATS][L2] iter = {}, loss = {:.5f}, loss1 = {:.5f}, loss2 = {:.5f}".format(iter+1, loss[0], l2[0], loss2[0]))
sys.stdout.flush()
var_list = np.array(range(0, var_len), dtype = np.int32)
indice = var_list[np.random.choice(var_list.size, batch_size, replace=False)]
var = np.repeat(real_modifier.detach().cpu().numpy(), batch_size * 2 + 1, axis=0)
for i in range(batch_size):
var[i*2+1].reshape(-1)[indice[i]]+=0.0001
var[i*2+2].reshape(-1)[indice[i]]-=0.0001
var = torch.from_numpy(var)
var = var.view((-1,)+input.size()[1:]).cuda()
losses, l2s, losses2, scores, pert_images = loss_run(input,target,model,var,use_tanh,use_log,targeted,confidence,const)
real_modifier_numpy = real_modifier.clone().detach().cpu().numpy()
if solver=="adam":
coordinate_ADAM(losses,indice,grad,hess,batch_size,mt,vt,real_modifier_numpy,adam_epoch,modifier_up,modifier_down,step_size,adam_beta1,adam_beta2,proj=not use_tanh)
if solver=="newton":
coordinate_Newton(losses,indice,grad,hess,batch_size,mt,vt,real_modifier_numpy,adam_epoch,modifier_up,modifier_down,step_size,adam_beta1,adam_beta2,proj=not use_tanh)
real_modifier=torch.from_numpy(real_modifier_numpy).cuda()
if losses2[0]==0.0 and last_loss2!=0.0 and stage==0:
if reset_adam_after_found:
mt.fill(0)
vt.fill(0)
adam_epoch.fill(1)
stage=1
last_loss2=losses2[0]
if abort_early and (iter+1) % early_stop_iters == 0:
if losses[0] > prev*.9999:
print("Early stopping because there is no improvement")
break
prev = losses[0]
if l2s[0] < bestl2 and compare(scores[0], np.argmax(target.cpu().numpy(),-1)):
bestl2 = l2s[0]
bestscore = np.argmax(scores[0])
if l2s[0] < out_bestl2 and compare(scores[0],np.argmax(target.cpu().numpy(),-1)):
if out_bestl2 == 1e10:
print("[STATS][L3](First valid attack found!) iter = {}, loss = {:.5f}, loss1 = {:.5f}, loss2 = {:.5f}".format(iter+1, losses[0], l2s[0], losses2[0]))
sys.stdout.flush()
out_bestl2 = l2s[0]
out_bestscore = np.argmax(scores[0])
out_best_attack = pert_images[0]
out_best_const = const
if compare(bestscore, np.argmax(target.cpu().numpy(),-1)) and bestscore != -1:
print('old constant: ', const)
upper_bound = min(upper_bound,const)
if upper_bound < 1e9:
const = (lower_bound + upper_bound)/2
print('new constant: ', const)
else:
print('old constant: ', const)
lower_bound = max(lower_bound,const)
if upper_bound < 1e9:
const = (lower_bound + upper_bound)/2
else:
const *= 10
print('new constant: ', const)
return out_best_attack, out_bestscore
def generate_data(test_loader,targeted,samples,start):
inputs=[]
targets=[]
num_label=10
cnt=0
for i, data in enumerate(test_loader):
if cnt<samples:
if i>start:
data, label = data[0],data[1]
if targeted:
seq = range(num_label)
for j in seq:
if j==label.item():
continue
inputs.append(data[0].numpy())
targets.append(np.eye(num_label)[j])
else:
inputs.append(data[0].numpy())
targets.append(np.eye(num_label)[label.item()])
cnt+=1
else:
continue
else:
break
inputs=np.array(inputs)
targets=np.array(targets)
return inputs,targets
def attack(inputs, targets, model, targeted, use_log, use_tanh, solver, device):
r = []
print('go up to',len(inputs))
# run 1 image at a time, minibatches used for gradient evaluation
for i in range(len(inputs)):
print('tick',i+1)
attack,score=l2_attack(np.expand_dims(inputs[i],0), np.expand_dims(targets[i],0), model, targeted, use_log, use_tanh, solver, device)
r.append(attack)
return np.array(r)
if __name__=='__main__':
np.random.seed(42)
torch.manual_seed(42)
transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5,), (1.0,))])
# test_set = datasets.MNIST(root = './data', train=False, transform = transform, download=True)
test_set = datasets.CIFAR10(root = './data', train=False, transform = transform, download=True)
test_loader = torch.utils.data.DataLoader(test_set,batch_size=1,shuffle=True)
use_cuda=True
device = torch.device("cuda" if (use_cuda and torch.cuda.is_available()) else "cpu")
# model = MNIST().to(device)
model = CIFAR10().to(device)
# model.load_state_dict(torch.load('./models/mnist_model.pt'))
model.load_state_dict(torch.load('./models/cifar10_model.pt'))
model.eval()
use_log=True
use_tanh=True
targeted=True
solver="newton"
#start is a offset to start taking sample from test set
#samples is the how many samples to take in total : for targeted, 1 means all 9 class target -> 9 total samples whereas for untargeted the original data
#sample is taken i.e. 1 sample only
inputs, targets = generate_data(test_loader,targeted,samples=10,start=6)
timestart = time.time()
adv = attack(inputs, targets, model, targeted, use_log, use_tanh, solver, device)
timeend = time.time()
print("Took",(timeend-timestart)/60.0,"mins to run",len(inputs),"samples.")
if use_log:
valid_class = np.argmax(F.softmax(model(torch.from_numpy(inputs).cuda()),-1).detach().cpu().numpy(),-1)
adv_class = np.argmax(F.softmax(model(torch.from_numpy(adv).cuda()),-1).detach().cpu().numpy(),-1)
else:
valid_class = np.argmax(model(torch.from_numpy(inputs).cuda()).detach().cpu().numpy(),-1)
adv_class = np.argmax(model(torch.from_numpy(adv).cuda()).detach().cpu().numpy(),-1)
acc = ((valid_class==adv_class).sum())/len(inputs)
print("Valid Classification: ", valid_class)
print("Adversarial Classification: ", adv_class)
print("Success Rate: ", (1.0-acc)*100.0)
print("Total distortion: ", np.sum((adv-inputs)**2)**.5)
# for saving the mnist samples
# for i in range(len(inputs)):
# save(inputs[i], "original_"+str(i)+".png")
# save(adv[i], "adversarial_"+str(i)+".png")
# save(adv[i] - inputs[i], "diff_"+str(i)+".png")
#visualization of created mnist adv examples
# cnt=0
# plt.figure(figsize=(10,10))
# for i in range(len(adv)):
# cnt+=1
# plt.subplot(10,10,cnt)
# plt.xticks([], [])
# plt.yticks([], [])
# plt.title("{} -> {}".format(valid_class[i],adv_class[i]))
# plt.imshow(adv[i].reshape(28,28), cmap="gray")
# plt.tight_layout()
# if targeted:
# if solver=="newton":
# plt.savefig('newton_targeted_mnist.png')
# else:
# plt.savefig('adam_targeted_mnist.png')
# else:
# if solver=="newton":
# plt.savefig('newton_untargeted_mnist.png')
# else:
# plt.savefig('adam_untargeted_mnist.png')
#visualization of created cifar10 adv examples
classes = ('plane', 'car', 'bird', 'cat', 'deer','dog', 'frog', 'horse', 'ship', 'truck')
cnt=0
plt.figure(figsize=(10,10))
for i in range(len(adv)):
cnt+=1
plt.subplot(10,10,cnt)
plt.xticks([], [])
plt.yticks([], [])
plt.title("{}->{}".format(classes[valid_class[i]],classes[adv_class[i]]))
plt.imshow(((adv[i]+0.5)).transpose(1,2,0))
plt.tight_layout()
if targeted:
if solver=="newton":
plt.savefig('newton_targeted_cifar10.png')
else:
plt.savefig('adam_targeted_cifar10.png')
else:
if solver=="newton":
plt.savefig('newton_untargeted_cifar10.png')
else:
plt.savefig('adam_untargeted_cifar10.png')
<file_sep>/setup_mnist_model.py
import numpy as np
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchsummary import summary
from torchvision import transforms,datasets
class MNIST(nn.Module):
def __init__(self):
super(MNIST, self).__init__()
self.conv1 = nn.Conv2d(1, 32, 3, 1)
self.conv2 = nn.Conv2d(32, 32, 3, 1)
self.conv3= nn.Conv2d(32, 64, 3, 1)
self.conv4= nn.Conv2d(64, 64, 3, 1)
self.dropout1 = nn.Dropout2d(0.5)
self.fc1 = nn.Linear(1024, 200)
self.fc2 = nn.Linear(200, 200)
self.fc3 = nn.Linear(200, 10)
def forward(self, x):
x = self.conv1(x)
x = F.relu(x)
x = self.conv2(x)
x = F.relu(x)
x = F.max_pool2d(x, 2)
x = self.conv3(x)
x = F.relu(x)
x = self.conv4(x)
x = F.relu(x)
x = F.max_pool2d(x, 2)
x = torch.flatten(x,1)
x = self.fc1(x)
x = F.relu(x)
x = self.dropout1(x)
x = self.fc2(x)
x = F.relu(x)
x = self.fc3(x)
return x
def fit(model,device,train_loader,val_loader,optimizer,criterion,epochs):
data_loader = {'train':train_loader,'val':val_loader}
print("Fitting the model...")
train_loss,val_loss=[],[]
train_acc,val_acc=[],[]
for epoch in range(epochs):
loss_per_epoch,val_loss_per_epoch=0,0
acc_per_epoch,val_acc_per_epoch,total,val_total=0,0,0,0
for phase in ('train','val'):
for i,data in enumerate(data_loader[phase]):
inputs,labels = data[0].to(device),data[1].to(device)
outputs = model(inputs)
#preding classes of one batch
preds = torch.max(outputs,1)[1]
#calculating loss on the output of one batch
loss = criterion(outputs,labels)
if phase == 'train':
acc_per_epoch+=(labels==preds).sum().item()
total+= labels.size(0)
optimizer.zero_grad()
#grad calc w.r.t Loss func
loss.backward()
#update weights
optimizer.step()
loss_per_epoch+=loss.item()
else:
val_acc_per_epoch+=(labels==preds).sum().item()
val_total+=labels.size(0)
val_loss_per_epoch+=loss.item()
print("Epoch: {} Loss: {:0.6f} Acc: {:0.6f} Val_Loss: {:0.6f} Val_Acc: {:0.6f}".format(epoch+1,loss_per_epoch/len(train_loader),acc_per_epoch/total,val_loss_per_epoch/len(val_loader),val_acc_per_epoch/val_total))
train_loss.append(loss_per_epoch/len(train_loader))
val_loss.append(val_loss_per_epoch/len(val_loader))
train_acc.append(acc_per_epoch/total)
val_acc.append(val_acc_per_epoch/val_total)
return train_loss,val_loss,train_acc,val_acc
if __name__=='__main__':
np.random.seed(42)
torch.manual_seed(42)
transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5,), (1.0,))])
dataset = datasets.MNIST(root = './data', train=True, transform = transform, download=True)
train_set, val_set = torch.utils.data.random_split(dataset, [55000, 5000])
train_loader = torch.utils.data.DataLoader(train_set,batch_size=128,shuffle=True)
val_loader = torch.utils.data.DataLoader(val_set,batch_size=128,shuffle=True)
use_cuda=True
device = torch.device("cuda" if (use_cuda and torch.cuda.is_available()) else "cpu")
model = MNIST().to(device)
summary(model,(1,28,28))
optimizer = optim.SGD(model.parameters(),lr=0.01, momentum=0.9, nesterov=True, weight_decay=1e-6)
criterion = nn.CrossEntropyLoss()
train_loss,val_loss,train_acc,val_acc=fit(model,device,train_loader,val_loader,optimizer,criterion,50)
fig = plt.figure(figsize=(5,5))
plt.plot(np.arange(1,51), train_loss, "*-",label="Training Loss")
plt.plot(np.arange(1,51), val_loss,"o-",label="Val Loss")
plt.xlabel("Num of epochs")
plt.legend()
plt.savefig('mnist_model_loss_event.png')
fig = plt.figure(figsize=(5,5))
plt.plot(np.arange(1,51), train_acc, "*-",label="Training Acc")
plt.plot(np.arange(1,51), val_acc,"o-",label="Val Acc")
plt.xlabel("Num of epochs")
plt.legend()
plt.savefig('mnist_model_accuracy_event.png')
torch.save(model.state_dict(),'./models/mnist_model.pt')
|
36588c82fdf56c69b482fac1c58daeed151d3ab5
|
[
"Markdown",
"Python"
] | 3 |
Markdown
|
Vevark/ZOO_Attack_PyTorch
|
ab003a1c16944a82b6ab9bfb392cebd8c0dc7814
|
b6fb34ed32b15aefd3839837203886db1fdf1528
|
refs/heads/master
|
<file_sep>
// ALL INCOME/EXPENSE CARDS GO HERE
let cardSelector = document.querySelector(".examples");
// SHOW/HIDE ALL CARDS
let viewSelector = document.querySelector(".allItems");
// FORM
let backEnd = document.querySelector(".send");
// let iDoNotWantIt = document.querySelector(".delete");
// MODAL
let editModal = document.querySelector("#popup1");
// Calculate Modal
let calcModal = document.getElementById("calculateModal");
// TOGGLE class to show and hide all examples
viewSelector.addEventListener("click", () => {
cardSelector.classList.toggle("hide");
})
// display all users who used their income and expenses as examples
fetch("https://sleepy-meadow-20552.herokuapp.com/incomes")
.then(r => r.json())
.then(res => {
// console.log(res)
let responses = res
for (const response of responses) {
// console.log(response.expenses);
cardMaker(response);
}
updateCard();
calculateButton()
})
// SUBMIT FORM
backEnd.addEventListener("submit", (evt) => {
evt.preventDefault();
console.log(evt.target.parentElement)
let selectedForm = evt.target.parentElement;
// debugger
// INCOME
let name = document.querySelector("#name");
let yrSalary = document.querySelector(".yrSalary");
let incomeObject = calculate(yrSalary.value, name.value);
// console.log(name.value, yrSalary.value);
// EXPENSE
let foodExpense = document.querySelector(".foodExpense");
let travelExpense = document.querySelector(".travelExpense");
let otherExpense = document.querySelector(".otherExpense");
// console.log(foodExpense.value, travelExpense.value, otherExpense.value);
let allExpenses = [
{
category: "food",
amount: foodExpense.value
},
{
category: "travel",
amount: travelExpense.value
},
{
category: "other",
amount: otherExpense.value
}
]
// POST fetch INCOME && EXPENSES
fetch("https://sleepy-meadow-20552.herokuapp.com/incomes", {
method: "POST",
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
income: incomeObject,
expense: allExpenses
})
})
.then(r => r.json())
.then(res => {
console.log(res)
// make another card
cardMaker(res);
// make another edit event listener for newly made card
updateCard();
let refreshForm = selectedForm.firstElementChild.firstElementChild
emptyForm(refreshForm)
console.log(backEnd)
calculateButton()
})
})
// Make EDIT eventListener for each card made
let updateCard = () => {
let cardClicks = document.querySelectorAll(".card-1");
for (const cardClick of cardClicks) {
cardClick.addEventListener("click", (evt) => {
// console.log(evt.target.parentElement.parentElement.parentElement.dataset.id)
let id = evt.target.parentElement.parentElement.parentElement.dataset.id;
let selectedBox = evt.target.parentElement.parentElement.parentElement
// console.log(selectedBox)
editModal.classList.add("overlay")
fetch(`https://sleepy-meadow-20552.herokuapp.com/incomes/${id}`)
.then(r => r.json())
.then(res => {
// console.log(res)
// make Modal form
createEditForm(res);
// select Edit Submit button
let newSubmitForEdit = document.querySelector(".sendEdit");
// EDIT SUBMIT is Clicked
newSubmitForEdit.addEventListener("submit", (evt) => {
evt.preventDefault();
// select INCOME Edit
let name = document.querySelector("#nameEdit");
let yrSalary = document.querySelector(".yrSalaryEdit");
console.log(yrSalary.value, name.value)
let incomeObject = calculate(yrSalary.value, name.value);
// select EXPENSE Edit
let foodExpense = document.querySelector(".foodExpenseEdit");
let travelExpense = document.querySelector(".travelExpenseEdit");
let otherExpense = document.querySelector(".otherExpenseEdit");
let allExpenses = [
{
category: "food",
amount: foodExpense.value
},
{
category: "travel",
amount: travelExpense.value
},
{
category: "other",
amount: otherExpense.value
}
]
fetch(`https://sleepy-meadow-20552.herokuapp.com/incomes/${id}`, {
method: "PATCH",
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify({
income: incomeObject,
expense: allExpenses
})
})
.then(updateRes => {
editModal.innerHTML = ``;
editModal.classList.remove("overlay");
selectedBox.innerHTML = ``;
selectedBox.innerHTML = `
<div class="row">
<div class="col incomeSection">
<br>
<h5>INCOME</h5>
<br>
<h6> Name: ${incomeObject.name}</h6>
<h6>Yearly: $ ${incomeObject.yearly}</h6>
<h6>Monthly: $ ${incomeObject.monthly}</h6>
<h6>Weekly: $ ${incomeObject.weekly}</h6>
<h6>Daily: $ ${incomeObject.daily}</h6>
</div>
<div class="col expenseSection">
<br>
<h5>EXPENSE </h5>
<br>
<h6 class="food">Category: ${allExpenses[0].category}</h6>
<h6 class="fAmount">Amount: ${allExpenses[0].amount}</h6>
<br>
<h6 class="travel">Category: ${allExpenses[1].category}</h6>
<h6 class="tAmount">Amount: ${allExpenses[1].amount}</h6>
<br>
<h6 class="other">Category: ${allExpenses[2].category}</h6>
<h6 class="othAmount">Amount: ${allExpenses[2].amount}</h6>
</div>
</div>
<div class="row">
<div class="col">
<a class="button" href="#popup1">Edit</a>
<button type="button" class="btn btn-outline-success updated" data-toggle="modal" data-target="#calculateModal">
Calculate
</button>
</div>
</div>
`;
// calculateButton()
// cardSelector.addEventListener("click", (evt) => {
// console.log(evt.target.parentElement.parentElement.parentElement)
// })
let updatedCalculations = document.querySelectorAll('.updated')
for (const updateCalc of updatedCalculations) {
// console.log(calcButton)
updateCalc.addEventListener("click", (evt) => {
let calcBox = evt.target.parentElement.parentElement.parentElement;
// console.log(calcBox);
let dailyFoodAmount = calcBox.querySelector(".fAmount");
let monthlyTravelAmount = calcBox.querySelector(".tAmount");
let monthlyOtherAmount = calcBox.querySelector(".othAmount");
// console.log(dailyFoodAmount)
let foodNumberInside = parseInt(dailyFoodAmount.innerText.slice(8));
let travelNumberInside = parseInt(monthlyTravelAmount.innerText.slice(8));
let otherNumberInside = parseInt(monthlyOtherAmount.innerText.slice(8));
// console.log(numberInside)
let convertedFoodExpenses = dailyFood(foodNumberInside);
let convertedTravelExpenses = monthlyTravel(travelNumberInside);
let convertedOtherExpenses = monthlyOther(otherNumberInside);
// console.log(convertedFoodExpenses)
// console.log(convertedTravelExpenses)
// console.log(convertedOtherExpenses)
createCalcModal(convertedFoodExpenses, convertedTravelExpenses, convertedOtherExpenses)
})
}
})
})
})
})
}
}
let calculateButton = () => {
let calcButtons = document.querySelectorAll(".calculate");
for (const calcButton of calcButtons) {
// console.log(calcButton)
calcButton.addEventListener("click", (evt) => {
let calcBox = evt.target.parentElement.parentElement.parentElement;
// console.log(calcBox);
let dailyFoodAmount = calcBox.querySelector(".fAmount");
let monthlyTravelAmount = calcBox.querySelector(".tAmount");
let monthlyOtherAmount = calcBox.querySelector(".othAmount");
// console.log(dailyFoodAmount)
let foodNumberInside = parseInt(dailyFoodAmount.innerText.slice(9));
let travelNumberInside = parseInt(monthlyTravelAmount.innerText.slice(9));
let otherNumberInside = parseInt(monthlyOtherAmount.innerText.slice(9));
// console.log(numberInside)
let convertedFoodExpenses = dailyFood(foodNumberInside);
let convertedTravelExpenses = monthlyTravel(travelNumberInside);
let convertedOtherExpenses = monthlyOther(otherNumberInside);
// console.log(convertedFoodExpenses)
// console.log(convertedTravelExpenses)
// console.log(convertedOtherExpenses)
createCalcModal(convertedFoodExpenses, convertedTravelExpenses, convertedOtherExpenses)
})
}
}
//************************** */ INNER HTML'S *****************************************
// EMPTY FORM
let emptyForm = (form) => {
form.innerHTML = `
<div class="row">
<div class="col">
<h3>Yearly Income</h3>
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" placeholder="Enter Name">
</div>
<div class="form-group">
<label for="yearlySalary">How Much do you make a Year?</label>
<input type="number" class="form-control yrSalary" id="yearlySalary" placeholder="Yearly Salary" value="">
<small id="emailHelp" class="form-text text-muted">We will Transform this into Monthly, Weekly, and Daily Cash you have Available</small>
</div>
</div>
<div class="col">
<h3>Expenses</h3>
<div class="form-group">
<label for="foodExpense">How much do you spend on <strong>FOOD</strong> in a <strong>DAILY</strong> Basis</label>
<input type="number" class="form-control foodExpense" id="foodExpense" placeholder="Enter Amount">
</div>
<div class="form-group">
<label for="travelExpense">How much do you spend on <strong>TRAVEL</strong> in a <strong>MONTHLY</strong> Basis</label>
<input type="number" class="form-control travelExpense" id="travelExpense" placeholder="Enter Amount">
</div>
<div class="form-group">
<label for="other">What are your <strong>OTHER EXPENSES</strong> in a <strong>MONTHLY</strong> Basis</label>
<input type="number" class="form-control otherExpense" id="other" placeholder="Enter Amount">
<small id="emailHelp" class="form-text text-muted">Other Expenses include total amount for credit card payments, Insurance, Rent, etc.</small>
</div>
</div>
</div>
`;
}
// Make INCOME/EXPENSE card HTML/JSON Response
let cardMaker = (jsonRes) => {
cardSelector.innerHTML +=
`
<div class="card card-1 animated flipInX" data-id="${jsonRes.id}">
<div class="row">
<div class="col incomeSection">
<br>
<h5>INCOME</h5>
<br>
<h6> Name: ${jsonRes.name}</h6>
<h6>Yearly: $ ${jsonRes.yearly}</h6>
<h6>Monthly: $ ${jsonRes.monthly}</h6>
<h6>Weekly: $ ${jsonRes.weekly}</h6>
<h6>Daily: $ ${jsonRes.daily}</h6>
</div>
<div class="col expenseSection">
<br>
<h5>EXPENSE </h5>
<br>
<h6 class="food">Category: ${jsonRes.expenses[0].category}</h6>
<h6 class="fAmount">Amount: $${jsonRes.expenses[0].amount}</h6>
<br>
<h6 class="travel">Category: ${jsonRes.expenses[1].category}</h6>
<h6 class="tAmount">Amount: $${jsonRes.expenses[1].amount}</h6>
<br>
<h6 class="other">Category: ${jsonRes.expenses[2].category}</h6>
<h6 class="othAmount">Amount: $${jsonRes.expenses[2].amount}</h6>
</div>
</div>
<div class="btn-group">
<div class="col">
<a class="button" href="#popup1">Edit</a>
<button type="button" class="btn btn-outline-success calculate" data-toggle="modal" data-target="#calculateModal">
Calculate
</button>
</div>
</div>
</div>
`;
}
// Edit modal HTML
let createEditForm = (jsonRes) => {
editModal.innerHTML = `
<div class="popup animated rubberBand">
<h2>EDIT</h2>
<a class="close" href="#">×</a>
<div class="content">
<div class="container">
<form class="sendEdit">
<div class="row">
<div class="col">
<h3>Yearly Income</h3>
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="nameEdit" placeholder="${jsonRes.name}" value="${jsonRes.name}">
</div>
<div class="form-group">
<label for="yearlySalary">How Much do you make a Year?</label>
<input type="number" class="form-control yrSalaryEdit" id="yearlySalary" placeholder="${jsonRes.yearly}" value="${jsonRes.yearly}">
<small id="emailHelp" class="form-text text-muted">We will Transform this into Monthly, Weekly, and Daily Cash you have Available</small>
</div>
</div>
<div class="col">
<h3>Expenses</h3>
<div class="form-group">
<label for="foodExpense">How much do you spend on <strong>FOOD</strong> in a <strong>DAILY</strong> Basis</label>
<input type="number" class="form-control foodExpenseEdit" id="foodExpense" placeholder="${jsonRes.expenses[0].amount}" value="${jsonRes.expenses[0].amount}">
</div>
<div class="form-group">
<label for="travelExpense">How much do you spend on <strong>TRAVEL</strong> in a <strong>MONTHLY</strong> Basis</label>
<input type="number" class="form-control travelExpenseEdit" id="travelExpense" placeholder="${jsonRes.expenses[1].amount}" value="${jsonRes.expenses[1].amount}">
</div>
<div class="form-group">
<label for="other">What are your <strong>OTHER EXPENSES</strong> in a <strong>MONTHLY</strong> Basis</label>
<input type="number" class="form-control otherExpenseEdit" id="other" placeholder="${jsonRes.expenses[2].amount}" value="${jsonRes.expenses[2].amount}">
<small id="emailHelp" class="form-text text-muted">Other Expenses include total amount for credit card payments, Insurance, Rent, etc.</small>
</div>
</div>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>`;
}
// Calculation Modal
let createCalcModal = (convertedFoodExpenses, convertedTravelExpenses, convertedOtherExpenses) => {
calcModal.innerHTML = `
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Deeper Insight into Expenses</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div>
<h2>Food Expense BreakDown</h2>
<ul>
<li>Daily Food: $${convertedFoodExpenses.daily}</li>
<li>Weekly Food: $${convertedFoodExpenses.weeklyAmount}</li>
<li>Monthly Food: $${convertedFoodExpenses.monthlyAmount}</li>
<li>Yearly Food: $${convertedFoodExpenses.yearlyAmount}</li>
</ul>
</div>
<div>
<h2>Travel Expense BreakDown</h2>
<ul>
<li>Daily Travel: $${convertedTravelExpenses.dailyAmount}</li>
<li>Weekly Travel: $${convertedTravelExpenses.weeklyAmount}</li>
<li>Monthly Travel: $${convertedTravelExpenses.monthly}</li>
<li>Yearly Travel: $${convertedTravelExpenses.yearlyAmount}</li>
</ul>
</div>
<div>
<h2>Other Expense BreakDown</h2>
<ul>
<li>Daily Other: $${convertedOtherExpenses.dailyAmount}</li>
<li>Weekly Other: $${convertedOtherExpenses.weeklyAmount}</li>
<li>Monthly Other: $${convertedOtherExpenses.monthly}</li>
<li>Yearly Other: $${convertedOtherExpenses.yearlyAmount}</li>
</ul>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
`
}
// ********************** CALCULATIONS *************************************
// convert YEARLY SALARY
let calculate = (yearly, name) => {
let yearSal = yearly
let monthly = Math.round(yearSal / 12);
let weekly = Math.round(yearSal / 52);
let daily = Math.round(yearSal / 365);
console.log(monthly, weekly, daily);
makeIntoObj = {
name: name,
yearly: yearSal,
weekly: weekly,
daily: daily,
monthly: monthly
}
return makeIntoObj;
}
// convert DAILY FOOD EXPENSE
let dailyFood = (dailyAmount) => {
let dAmount = dailyAmount
let yearly = Math.floor(dAmount * 365);
let monthly = Math.floor(yearly / 12);
let weekly = Math.floor(yearly / 52);
// console.log(yearly, monthly, weekly, dAmount)
dailyAmountObj = {
daily: dAmount,
yearlyAmount: yearly,
monthlyAmount: monthly,
weeklyAmount: weekly
}
return dailyAmountObj;
}
// convert MONTHLY TRAVEL EXPENSE
let monthlyTravel = (monthlyAmount) => {
let mAmount = monthlyAmount;
let yearly = Math.round(mAmount * 12);
let weekly = Math.round(yearly / 52);
let daily = Math.round(yearly / 365);
// console.log(yearly, weekly, daily, mAmount)
monthlyAmountObj = {
monthly: mAmount,
yearlyAmount: yearly,
weeklyAmount: weekly,
dailyAmount: daily
}
return monthlyAmountObj;
}
// convert MONTHLY OTHER EXPENSE
let monthlyOther = (monthlyOther) => {
let mOtherAmount = monthlyOther;
let yearly = Math.round(mOtherAmount * 12);
let weekly = Math.round(yearly / 52);
let daily = Math.round(yearly / 365);
// console.log(yearly, weekly, daily, mAmount)
monthlyOtherAmountObj = {
monthly: mOtherAmount,
yearlyAmount: yearly,
weeklyAmount: weekly,
dailyAmount: daily
}
return monthlyOtherAmountObj;
}
|
b19945792fcb5821cb0e3cc56f5b6a1e6d3da9fd
|
[
"JavaScript"
] | 1 |
JavaScript
|
tawhidali123/monthly_planner
|
2d3febe1d075ac3d0567d3a0abd126869bb0d9a5
|
21b00c340c1f19a9f6f6f98034ad83070e1dddd7
|
refs/heads/master
|
<file_sep>file = File.read "input.txt"
code_characters = 0
memory_characters = 0
file.each_line do |line|
code_characters += line.chomp.length
line.gsub!(/(\\x\d{2})|(\\)|(\\")/,'a')
line.gsub!(/\W/, '')
memory_characters += line.scan(/\D/).count
end
puts code_characters - memory_characters
|
3c5b116c43ef602aef919e76a46ff9ceb3bcc13e
|
[
"Ruby"
] | 1 |
Ruby
|
charuths/Day8
|
574028060329f7e2790a063e5fdfba0348183f99
|
c4e1859bace144dde014af9b8bb40088991a8e73
|
refs/heads/master
|
<repo_name>priyanka-herur/SVG-MetaRefresh2014<file_sep>/README.md
SVG-MetaRefresh2014
===================
Modern Graphics for the Web- MetaRefresh 2014
You can view the presentation at:
http://priyanka-herur.github.io/SVG-MetaRefresh2014/#/
<file_sep>/js/animations.js
$( document ).ready(function() {
$( "p" ).text( "The DOM is now loaded and can be manipulated." );
// Flapping animation
$('#startFlap').click(function() {
$('#rightwing').attr('class','right_wing');
});
$('#stopFlap').click(function() {
$('#rightwing').attr('class','');
});
$('#map .india #center_portion').mouseover(function() {
$('#map .india #center_portion path').attr('fill','#ffffff');
$('#map .india #chakra path').attr('fill','#000088');
});
$('#map .india #center_portion').mouseout(function() {
$('#map .india #chakra path').attr('fill','#ffffff');
$('#map .india #center_portion path').attr('fill','#d3d3d3');
});
var start = false;
var pathPoints = "";
var offsetValues ;
var drawPath = function () {
$( "#svgCanvasForPath" ).bind({
mousemove: function(e) {
rect = document.getElementById('svgCanvasForPath').getBoundingClientRect(),
offsetX = e.clientX - rect.left,
offsetY = e.clientY - rect.top;
var x = e.offsetX==undefined?offsetX:e.offsetX;
var y = e.offsetY==undefined?offsetY:e.offsetY;
pathPoints += " L " + (parseFloat(x) + 10) + " " + (parseFloat(y) - 30);
$( "#pathForDrawing" ).attr('d', pathPoints);
}
});
};
var stopDrawingPath = function () {
start = false;
$( "#svgCanvasForPath" ).unbind( "mousemove" );
};
$( "#svgCanvasForPath" ).bind({
click: function(e) {
if(!start) {
start = true;
rect = document.getElementById('svgCanvasForPath').getBoundingClientRect(),
offsetX = e.clientX - rect.left,
offsetY = e.clientY - rect.top;
var x = e.offsetX==undefined?offsetX:e.offsetX;
var y = e.offsetY==undefined?offsetY:e.offsetY;
pathPoints = "M " + (parseFloat(x) + 10) + " " + (parseFloat(y) - 30);
drawPath();
} else {
stopDrawingPath();
}
}
});
});
|
8b4fad3b49864f9e1cd0a76db7374c0635746662
|
[
"Markdown",
"JavaScript"
] | 2 |
Markdown
|
priyanka-herur/SVG-MetaRefresh2014
|
83e39f88ba4497efbc6246774c9e5b8527e9141a
|
954af7e761d9b04bc16795405450208431d26133
|
refs/heads/master
|
<file_sep>package zombieproject;
import java.util.Scanner;
public class battle
{
public static void battle()
{
Scanner input = new Scanner(System.in);
String[] zombieName = {"The Winter Zombie", "Dr. Zombie", "Obamazombie", "FrankinZombie",
"Count-Zombula", "<NAME>", "Soda-Poppizombie"};
System.out.println("Please pick your zombie leader....");
zombieMenu();
//assigning the integer to use for the array
int z = input.nextInt() - 1;
while(z > 6)
{
System.out.println("Please select a valid zombie leader ! !");
zombieMenu();
z = input.nextInt() - 1;
}
//Assigning name of user's zombie based on their selection through Array
String userZombie = zombieName[z];
System.out.println("Please choose a Zombie that will test your zombie's strength !");
zombieMenu();
int f = input.nextInt() - 1;
//Gets the user to enter a valid zombie
while(f > 6)
{
System.out.println("Please choose a valid Zombie ! !");
zombieMenu();
f = input.nextInt() - 1;
}
//Assigning the user's zombie to the selection of the user
String computerZombie = zombieName[f];
System.out.printf("This battle between %s and %s should be epic!!\n\n", userZombie, computerZombie);
switch(z)
{
case 0:
if(f == 0)
{
System.out.print("The zombies fought with such ferocity, they died at the same time\n");
}
else if(f < 4)
{
System.out.println("Your Zombie tore apart the enemy zombie!\n");
}
else
{
System.out.println("Your Zombie got torn apart :(\n");
}
break;
case 1:
if(f == 1)
{
System.out.print("The zombies hurt eachother so much, they both died to their wounds\n");
}
else if(f > 2)
{
System.out.println("Your Zombie Won...barely!\n");
}
else
{
System.out.println("Your Zombie almost won...but still lost :(\n");
}
break;
case 2:
if(f == 2)
{
System.out.print("The Zombies mutually eliminated eachother!\n");
}
else if(f > 4)
{
System.out.println("Your zombie annihilated the other zombie!\n");
}
else
{
System.out.println("Your Zombie got annihilated:(\n");
}
break;
case 3:
if(f == 3)
{
System.out.print("The zombies fought so well, they died at the same time\n");
}
else if(f < 2 || f > 4)
{
System.out.println("Your Zombie Won!\n");
}
else
{
System.out.println("Your Zombie did not win :(\n");
}
break;
case 4:
if(f == 4)
{
System.out.print("While the zombies were fighting, a piano fell on them and they both died.\n");
}
else if(f > 2 && f < 5)
{
System.out.println("Your Zombie won because a piano fell on the opponent!\n");
}
else
{
System.out.println("A piano fell on your zombie, and lost :(\n");
}
break;
case 5:
if(f == 5)
{
System.out.print("The zombies decided to be zombie-bros, and left the fight\n");
}
else if(f > 5)
{
System.out.println("Your Zombie crushed all opposition!\n");
}
else
{
System.out.println("Your Zombie got slapped, punched, bitten, scratched, and otherwise horribly murdered. :(\n");
}
break;
case 6:
if(f == 6)
{
System.out.print("The Zombies where so ruthless in their assaults, that they killed eachother at the same time\n");
}
else if(f > 4 || f < 1)
{
System.out.println("Your Zombie brutally won!\n");
}
else
{
System.out.println("Your Zombie got brutally murdered :( \n");
}
break;
default:
System.out.println("Your battle just ended...oddly.... ! !\n");
}
}
public static void zombieMenu()
{
System.out.print("1. The Winter Zombie\n2. Dr. Zombie\n3. Obamazombie\n"
+ "4. FrankinZombie\n5. Count-Zombula\n6. <NAME> Zombody\n7. Soda-Poppizombie\n\n");
}
}
<file_sep>package zombieproject;
import java.util.Scanner;
public class takeover{
public static void takeover(){
Scanner input = new Scanner(System.in);
takeover myTakeOver = new takeover();
//variables
int factor = 1;
int curZom = 0;
int day = 0;
int remPop = 1;
//Alert User of the Zombie Takeover
System.out.println("Please get ready to have your dream city taken over by zombies!!!!\n");
System.out.println("Please enter the population of your dream city:");
int citPop = input.nextInt();
System.out.println("Please enter the zombies already in your dream city:");
int zomLiv = input.nextInt();
//Zombie Takeover Simulation
while(remPop > 0){
remPop = citPop - factor * zomLiv;
zomLiv = factor * zomLiv;
curZom = citPop - remPop;
day++;
factor++;
//If-Else to determine if there are still humans in the city
if(remPop > 0){
System.out.printf("The Remaining Human Population on Day %d is : %d\n"
+ "There are now %d Zombies in your dream city\n\n", day, remPop, curZom);
}
else{
System.out.println("Your Dream City has been taken over by the Zombies ! !\n\n");
break;
}
//Giving the user the option to continue and abandon the city or remain and fight
System.out.println("Select 0 to abandon the city or any other number to continue..\n");
int exit;
exit = input.nextInt();
if(exit == 0){
System.out.println("You are a coward, go to a safer place!!!\n\n");
break;
}
}
}
}
<file_sep># zombieProject
A project dedicated to the greatest thing ever...zombies.
This is just a school project...don't take it seriously.
<file_sep>package zombieProject;
import java.util.Scanner;
class Selfdestruct {
public static final String ANSI_RESET = "\u001B[0m";
public static final String ANSI_BLACK = "\u001B[30m";
public static final String ANSI_RED = "\u001B[31m";
public static final String ANSI_GREEN = "\u001B[32m";
public static final String ANSI_YELLOW = "\u001B[33m";
public static final String ANSI_BLUE = "\u001B[34m";
public static final String ANSI_PURPLE = "\u001B[35m";
public static final String ANSI_CYAN = "\u001B[36m";
public static final String ANSI_WHITE = "\u001B[37m";
public static void selfdestruct() {
Scanner input = new Scanner(System.in);
System.out.println
("\n" +ANSI_GREEN + "The military has installed explosives throught the city to \n" +ANSI_GREEN + "save the rest of the world from the zombies.\n" +ANSI_RESET);
System.out.println
(ANSI_GREEN + "Do you want to destroy the city and everyone in it or continue "
+ "trying to survive.\n"+ANSI_RESET);
System.out.println
(ANSI_BLUE + "Press 1 to self-destruct or enter any other number to decline."+ANSI_RESET);
int i = input.nextInt();
switch(i){
case 0:
System.out.print(ANSI_GREEN + "Your city will continue to try and survive the zombies."+ANSI_RESET);
break;
case 1:
System.out.print
(ANSI_GREEN + "You've killed so many people, but saved many more. Your city is destroyed and you are dead, but so are the zombies.\n"+ANSI_RESET);
break;
}
if (i == 1){
System.exit(0);
}
}
}
<file_sep> package zombieproject;
public class ZombieProject
{
public static void main(String[] args)
{
battle.battle();
takeover.takeover();
zombiePotential.zombiePotential();
}
}
|
3f72ed91b74ba9e574c005ea4a9eb80f48cad7b9
|
[
"Markdown",
"Java"
] | 5 |
Java
|
dreadnought101/zombieProject
|
f099281fbbc45931b0e7a72d6da63fcb63f4df82
|
0586ad8d9ec9dea6f54904ad6abcffc2fa7a5d95
|
refs/heads/master
|
<file_sep>package cs3331;
/**
* @author <NAME>
*/
public class Player {
private int playerName;//will be useful for the future
private char symbol;// should be 1 or 2 will be useful for the future
private boolean isReal;// will be used later on once AI is implemented
public Player(int currPlayer, char symbol) {
this.playerName = currPlayer;
this.symbol = symbol;
isReal = true;
}
public char getSymbol() {
return symbol;
}
public int getPlayerName() {
return playerName;
}
//Eventually we will implement the AI stuff here or related to here that is why we have the irReal
}
<file_sep>package cs3331;
/**
* @author <NAME>
*/
public class PlayerWonException extends Exception {
public PlayerWonException(String message) {
super(message);
}
public PlayerWonException() {
}
}
<file_sep>package cs3331;
/**
* Contains the model for the Connect Five board. (No GUI elements should placed here.)
*
* @author <NAME>
*/
public class Board {
private Square[][] tiles;
private boolean[][] isFilled;
private int counter = 0;
/**
* Defines the size of the board
*/
private final int size;
/**
* Constructor including size of board
*
* @param size Board Size
*/
public Board(int size) {
this.size = size;
tiles= new Square[size][size];
isFilled=new boolean[size][size];
// Your Code Goes Here!
}
/**
* Adds a disc to the game board.
*
* @param x x coordinate of where the disc needs to be placed.
* @param y y coordinate of where the disc needs to be placed.
*/
public void addDisc(int x, int y, int player) throws InValidDiskPositionException, PlayerWonException {
if (isValidPosition(x, y)) {
tiles[y][x] = new Square(x, y, player);
isFilled[y][x] = true;
counter++;
if (checkForWin(tiles[y][x])) {
throw new PlayerWonException();
}
} else {
throw new InValidDiskPositionException();
}
}
/**
* Checks if input positions is valid. Checks if valid x-y range. Also checks if position is empty.
*
* @param x x input.
* @param y y input.
* @return Validity of placement of the disc.
*/
private boolean isValidPosition(int x, int y) {
// Your Code Goes Here!
return !isFilled[y][x];
}
public Square[][] getAllTiles() {
return tiles;
}
public Square getTiles(int x,int y){
try {
return tiles[y][x];
}catch(NullPointerException e){
return new Square(x,y,null);
}
}
/**
* Returns the size of this board.
*
* @return Returns size of board
*/
public int size() {
return size;
}
/**
* This method is used to check for a tie
*
* @return true if tie, false otherwise
*/
public boolean isBoardFull() {
return counter >= Math.pow(size, 2);
}
private boolean checkForWin(Square square) {
if (((checkWinHelper(square.getX(), square.getY(), square.getPlayer(),0,-1) + checkWinHelper(square.getX(), square.getY(),square.getPlayer(),0,1))) >= 6) {
// System.out.println("Current Points:" + currpoints);
return true;
}
if (checkWinHelper(square.getX(), square.getY(), square.getPlayer(),-1,0) + checkWinHelper(square.getX(), square.getY(), square.getPlayer(),1,0) >= 6)
return true;
if (checkWinHelper(square.getX(), square.getY(), square.getPlayer(),-1,-1) + checkWinHelper(square.getX(), square.getY(), square.getPlayer(),1,1) >= 6)
return true;
return checkWinHelper(square.getX(), square.getY(), square.getPlayer(),-1,1) + checkWinHelper(square.getX(), square.getY(), square.getPlayer(),1,-1) >= 6;
}
private int checkWinHelper(int x, int y,int player,int dx,int dy){
try {
if (tiles[y][x].getPlayer() == player) {
return 1 + checkWinHelper(x+dx, y+dy, player,dx,dy);
}
} catch (NullPointerException | ArrayIndexOutOfBoundsException e) {
return 0;
}
return 0;
}
/* //dx:0 dy:-1 upCheck
private int upCheck(int x, int y, char player) {
try {
if (tiles[y][x].getPlayer().getSymbol() == player) {
return 1 + upCheck(x, y - 1, player);
}
} catch (NullPointerException | ArrayIndexOutOfBoundsException e) {
return 0;
}
return 0;
}
//dx:0 dy:1 downCheck
private int downCheck(int x, int y, char player) {
try {
if (tiles[y][x].getPlayer().getSymbol() == player)
return 1 + downCheck(x, y + 1, player);
} catch (NullPointerException | ArrayIndexOutOfBoundsException e) {
return 0;
}
return 0;
}
//dx:-1 dy:0 leftCheck
private int leftCheck(int x, int y, char player) {
try {
if (tiles[y][x].getPlayer().getSymbol() == player)
return 1 + leftCheck(x - 1, y, player);
} catch (NullPointerException | ArrayIndexOutOfBoundsException e) {
return 0;
}
return 0;
}
//dx:1 dy:0 rightCheck
private int rightCheck(int x, int y, char player) {
try {
if (tiles[y][x].getPlayer().getSymbol() == player) {
return 1 + rightCheck(x + 1, y, player);
}
} catch (NullPointerException | ArrayIndexOutOfBoundsException e) {
return 0;
}
return 0;
}
//dx:-1 dy:-1 leftUpCheck
private int leftUpCheck(int x, int y, char player) {
try {
if (tiles[y][x].getPlayer().getSymbol() == player) {
return 1 + leftUpCheck(x - 1, y - 1, player);
}
} catch (NullPointerException e) {
return 0;
} catch (ArrayIndexOutOfBoundsException e) {
return 0;
}
return 0;
}
//dx:1 dy:1 rightDownCheck
private int rightDownCheck(int x, int y, char player) {
try {
if (tiles[y][x].getPlayer().getSymbol() == player)
return 1 + rightDownCheck(x + 1, y + 1, player);
} catch (NullPointerException e) {
return 0;
} catch (ArrayIndexOutOfBoundsException e) {
return 0;
}
return 0;
}
//dx:-1 dy:1 leftDownCheck
private int leftDownCHeck(int x, int y, char player) {
try {
if (tiles[y][x].getPlayer().getSymbol() == player) {
return 1 + leftDownCHeck(x - 1, y + 1, player);
}
} catch (NullPointerException e) {
return 0;
} catch (ArrayIndexOutOfBoundsException e) {
return 0;
}
return 0;
}
//dx:1 dy:-1 rightUpCheck
private int rightUpCheck(int x, int y, char player) {
try {
if (tiles[y][x].getPlayer().getSymbol() == player)
return 1 + rightUpCheck(x + 1, y - 1, player);
} catch (NullPointerException e) {
return 0;
} catch (ArrayIndexOutOfBoundsException e) {
return 0;
}
return 0;
}*/
}
|
89251482a358d9b7ce92213a6514bbfdae09a028
|
[
"Java"
] | 3 |
Java
|
AFTorres15/HW3Connect5
|
52011ad22416cb44c458d83c8b0bb24f71234ff1
|
d43109d1f22159de55f412bd376402213dfa6365
|
refs/heads/master
|
<file_sep>from collections import OrderedDict
import os.path as osp
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.distributed as dist
from torch.nn.parallel import DistributedDataParallel
from utils.data_utils import create_kernel
from utils.dist_utils import master_only
class BaseModel():
def __init__(self, opt):
self.opt = opt
self.verbose = opt['verbose']
self.scale = opt['scale']
self.device = torch.device(opt['device'])
self.blur_kernel = None
self.dist = opt['dist']
self.is_train = opt['is_train']
if self.is_train:
self.lr_data, self.gt_data = None, None
self.ckpt_dir = opt['train']['ckpt_dir']
self.log_decay = opt['logger'].get('decay', 0.99)
self.log_dict = OrderedDict()
self.running_log_dict = OrderedDict()
def set_networks(self):
pass
def config_training(self):
pass
def set_criterions(self):
pass
def set_optimizers(self):
pass
def set_lr_schedules(self):
pass
def prepare_data(self, data):
""" prepare gt, lr data for training
for BD degradation, generate lr data and remove border of gt data
for BI degradation, use the input data directly
"""
degradation_type = self.opt['dataset']['degradation']['type']
if degradation_type == 'BI':
self.lr_data = data['lr'].to(self.device)
self.gt_data = data['gt'].to(self.device)
elif degradation_type == 'BD':
# generate lr data on the fly
# set params
scale = self.opt['scale']
sigma = self.opt['dataset']['degradation'].get('sigma', 1.5)
border_size = int(sigma*3.0)
gt_with_border = data['gt'].to(self.device)
n, t, c, gt_h, gt_w = gt_with_border.size()
lr_h = (gt_h - 2*border_size)//scale
lr_w = (gt_w - 2*border_size)//scale
# create blurring kernel
if self.blur_kernel is None:
self.blur_kernel = create_kernel(sigma).to(self.device)
# generate lr data
gt_with_border = gt_with_border.view(n*t, c, gt_h, gt_w)
lr_data = F.conv2d(
gt_with_border, self.blur_kernel, stride=scale, bias=None,
padding=0)
self.lr_data = lr_data.view(n, t, c, lr_h, lr_w)
# remove gt border
gt_data = gt_with_border[
...,
border_size: border_size + scale*lr_h,
border_size: border_size + scale*lr_w
]
self.gt_data = gt_data.view(n, t, c, scale*lr_h, scale*lr_w)
def train(self):
pass
def infer(self, data):
pass
def model_to_device(self, net):
net = net.to(self.device)
if self.dist:
net = nn.SyncBatchNorm.convert_sync_batchnorm(net)
net = DistributedDataParallel(
net, device_ids=[torch.cuda.current_device()])
return net
def update_learning_rate(self):
if hasattr(self, 'sched_G') and self.sched_G is not None:
self.sched_G.step()
if hasattr(self, 'sched_D') and self.sched_D is not None:
self.sched_D.step()
def get_current_learning_rate(self):
lr_dict = OrderedDict()
if hasattr(self, 'optim_G'):
lr_dict['lr_G'] = self.optim_G.param_groups[0]['lr']
if hasattr(self, 'optim_D'):
lr_dict['lr_D'] = self.optim_D.param_groups[0]['lr']
return lr_dict
def update_running_log(self):
d = self.log_decay
for k in self.log_dict.keys():
current_val = self.log_dict[k]
running_val = self.running_log_dict.get(k)
if running_val is None:
running_val = current_val
else:
running_val = d * running_val + (1.0 - d) * current_val
self.running_log_dict[k] = running_val
def reduce_log(self):
if self.dist:
rank, world_size = self.opt['rank'], self.opt['world_size']
with torch.no_grad():
keys, vals = [], []
for key, val in self.log_dict.items():
keys.append(key)
vals.append(val)
vals = torch.FloatTensor(vals).to(self.device)
dist.reduce(vals, dst=0)
if rank == 0: # average
vals /= world_size
self.log_dict = {key: val.item() for key, val in zip(keys, vals)}
def get_current_log(self):
return self.log_dict
def get_running_log(self):
return self.running_log_dict
def get_format_msg(self, epoch, iter):
# generic info
msg = f'[epoch: {epoch} | iter: {iter}'
for lr_type, lr in self.get_current_learning_rate().items():
msg += f' | {lr_type}: {lr:.2e}'
msg += '] '
# loss info
log_dict = self.get_running_log()
msg += ', '.join([f'{k}: {v:.3e}' for k, v in log_dict.items()])
return msg
def save(self, current_iter):
pass
@staticmethod
def get_bare_model(net):
if isinstance(net, DistributedDataParallel):
net = net.module
return net
@master_only
def save_network(self, net, net_label, current_iter):
filename = f'{net_label}_iter{current_iter}.pth'
save_path = osp.join(self.ckpt_dir, filename)
net = self.get_bare_model(net)
torch.save(net.state_dict(), save_path)
def save_training_state(self, current_epoch, current_iter):
# TODO
pass
def load_network(self, net, load_path):
state_dict = torch.load(
load_path, map_location=lambda storage, loc: storage)
net = self.get_bare_model(net)
net.load_state_dict(state_dict)
def pad_sequence(self, lr_data):
"""
Parameters:
:param lr_data: tensor in shape tchw
"""
padding_mode = self.opt['test'].get('padding_mode', 'reflect')
n_pad_front = self.opt['test'].get('num_pad_front', 0)
assert n_pad_front < lr_data.size(0)
# pad
if padding_mode == 'reflect':
lr_data = torch.cat(
[lr_data[1: 1 + n_pad_front, ...].flip(0), lr_data], dim=0)
elif padding_mode == 'replicate':
lr_data = torch.cat(
[lr_data[:1, ...].expand(n_pad_front, -1, -1, -1), lr_data], dim=0)
else:
raise ValueError(f'Unrecognized padding mode: {padding_mode}')
return lr_data, n_pad_front
<file_sep># TecoGAN-PyTorch
### Introduction
This is a PyTorch reimplementation of **TecoGAN**: **Te**mporally **Co**herent **GAN** for Video Super-Resolution (VSR). Please refer to the official TensorFlow implementation [TecoGAN-TensorFlow](https://github.com/thunil/TecoGAN) for more information.
<p align = "center">
<img src="resources/fire.gif" width="320" />
<img src="resources/pond.gif" width="320" />
</p>
<p align = "center">
<img src="resources/foliage.gif" width="320" />
<img src="resources/bridge.gif" width="320" />
</p>
### Updates
- Upgraded codebase, now support Multi-GPUs training & testing.
### Features
- **Better Performance**: This repo provides model with smaller size yet better performance than the official repo. See our [Benchmark](https://github.com/skycrapers/TecoGAN-PyTorch#benchmark).
- **Multiple Degradations**: This repo supports two types of degradation, i.e., BI & BD. Please refer to [this wiki]() for more details about degradation types.
- **Unified Framework**: This repo provides a unified framework for distortion-based and perception-based VSR methods.
### Contents
1. [Dependencies](#dependencies)
1. [Testing](#testing)
1. [Training](#training)
1. [Benchmark](#benchmark)
1. [License & Citation](#license--citation)
1. [Acknowledgements](#acknowledgements)
## Dependencies
- Ubuntu >= 16.04
- NVIDIA GPU + CUDA
- Python >= 3.7
- PyTorch >= 1.4.0
- Python packages: numpy, matplotlib, opencv-python, pyyaml, lmdb
- (Optional) Matlab >= R2016b
## Testing
**Note:** We apply different models according to the degradation type. The following steps are for 4x upsampling for BD degradation. You can switch to BI degradation by replacing all `BD` to `BI` below.
1. Download the official Vid4 and ToS3 datasets.
```bash
bash ./scripts/download/download_datasets.sh BD
```
> You can manually download these datasets from Google Drive, and unzip them under `./data`.
> * Vid4 Dataset [[Ground-Truth Data](https://drive.google.com/file/d/1T8TuyyOxEUfXzCanH5kvNH2iA8nI06Wj/view?usp=sharing)] [[Low Resolution Data (BD)](https://drive.google.com/file/d/1-5NFW6fEPUczmRqKHtBVyhn2Wge6j3ma/view?usp=sharing)] [[Low Resolution Data (BI)](https://drive.google.com/file/d/1Kg0VBgk1r9I1c4f5ZVZ4sbfqtVRYub91/view?usp=sharing)]
> * ToS3 Dataset [[Ground-Truth Data](https://drive.google.com/file/d/1XoR_NVBR-LbZOA8fXh7d4oPV0M8fRi8a/view?usp=sharing)] [[Low Resolution Data (BD)](https://drive.google.com/file/d/1rDCe61kR-OykLyCo2Ornd2YgPnul2ffM/view?usp=sharing)] [[Low Resolution Data (BI)](https://drive.google.com/file/d/1FNuC0jajEjH9ycqDkH4cZQ3_eUqjxzzf/view?usp=sharing)]
The dataset structure is shown as below.
```tex
data
├─ Vid4
├─ GT # Ground-Truth (GT) video sequences
└─ calendar
├─ 0001.png
└─ ...
├─ Gaussian4xLR # Low Resolution (LR) video sequences in BD degradation
└─ calendar
├─ 0001.png
└─ ...
└─ Bicubic4xLR # Low Resolution (LR) video sequences in BI degradation
└─ calendar
├─ 0001.png
└─ ...
└─ ToS3
├─ GT
├─ Gaussian4xLR
└─ Bicubic4xLR
```
2. Download our pre-trained TecoGAN model.
```bash
bash ./scripts/download/download_models.sh BD TecoGAN
```
> You can download the model from [[BD degradation](https://drive.google.com/file/d/13FPxKE6q7tuRrfhTE7GB040jBeURBj58/view?usp=sharing)] or [[BI degradation](https://drive.google.com/file/d/1ie1F7wJcO4mhNWK8nPX7F0LgOoPzCwEu/view?usp=sharing)], and put it under `./pretrained_models`.
3. Upsample the LR videos by TecoGAN. The results will be saved at `./results`. You can specify which model and how many gpus to use in `test.sh`.
```bash
bash ./test.sh BD TecoGAN
```
4. Evaluate the upsampled results using the official metrics. These codes are borrowed from [TecoGAN-TensorFlow](https://github.com/thunil/TecoGAN), with minor modifications to adapt to the BI degradation.
```bash
python ./codes/official_metrics/evaluate.py -m TecoGAN_BD_iter500000
```
5. Profile model (FLOPs, parameters and speed). You can modify the last argument to specify the size of the LR video.
```bash
bash ./profile.sh BD TecoGAN 3x134x320
```
## Training
1. Download the official training dataset according to the instructions in [TecoGAN-TensorFlow](https://github.com/thunil/TecoGAN), rename to `VimeoTecoGAN`, and place under `./data`.
2. Generate LMDB for GT data to accelerate IO. The LR counterpart will then be generated on the fly during training.
```bash
python ./scripts/create_lmdb.py --dataset VimeoTecoGAN --data_type GT
```
The following shows the dataset structure after finishing the above two steps.
```tex
data
├─ VimeoTecoGAN # Original (raw) dataset
├─ scene_2000
├─ col_high_0000.png
├─ col_high_0001.png
└─ ...
├─ scene_2001
├─ col_high_0000.png
├─ col_high_0001.png
└─ ...
└─ ...
└─ VimeoTecoGAN.lmdb # LMDB dataset
├─ data.mdb
├─ lock.mdb
└─ meta_info.pkl # each key has format: [vid]_[total_frame]x[h]x[w]_[i-th_frame]
```
3. **(Optional, this step is only required for BI degradation)** Manually generate the LR sequences with Matlab's imresize function, and then create LMDB for them.
```bash
# Generate the raw LR video sequences. Results will be saved at ./data/Bicubic4xLR
matlab -nodesktop -nosplash -r "cd ./scripts; generate_lr_BI"
# Create LMDB for the raw LR video sequences
python ./scripts/create_lmdb.py --dataset VimeoTecoGAN --data_type Bicubic4xLR
```
4. Train a FRVSR model first. FRVSR has the same generator as TecoGAN, but without perceptual training (i.e., GAN and perceptual losses). When the training is complete, copy and rename the last checkpoint weight from `./experiments_BD/FRVSR/001/train/ckpt/G_iter400000.pth` to `./pretrained_models/FRVSR_BD_iter400000.pth`. A pre-trained FRVSR model offers a better initialization for the following TecoGAN training.
```bash
bash ./train.sh BD FRVSR
```
> You can download and use our pre-trained FRVSR model [[BD degradation](https://drive.google.com/file/d/11kPVS04a3B3k0SD-mKEpY_Q8WL7KrTIA/view?usp=sharing)] [[BI degradation](https://drive.google.com/file/d/1wejMAFwIBde_7sz-H7zwlOCbCvjt3G9L/view?usp=sharing)] without training from scratch.
>```bash
>bash ./scripts/download/download_models.sh BD FRVSR
>```
5. Train a TecoGAN model. You can specify which gpus to use in `train.sh`. By default, the training is conducted in the background and the output info will be logged in `./experiments_BD/TecoGAN/001/train/train.log`.
```bash
bash ./train.sh BD TecoGAN
```
6. To monitor the training process and visualize the validation performance, run the following script.
```bash
python ./scripts/monitor_training.py --m TecoGAN -d Vid4
```
> Note that the validation results are NOT exactly the same as the testing results mentioned above due to different implementation of the metrics. The differences are caused by croping policy, LPIPS version and some other issues.
## Benchmark
<p align = "center">
<img src="resources/benchmark.png" width="640" />
</p>
> <sup>[1]</sup> FLOPs & speed are computed on RGB sequence with resolution 134\*320 on a single NVIDIA 1080Ti GPU. \
> <sup>[2]</sup> Both FRVSR & TecoGAN use 10 residual blocks, while TecoGAN+ has 16 residual blocks.
## License & Citation
If you use this code for your research, please cite the following paper and our project.
```tex
@article{tecogan2020,
title={Learning temporal coherence via self-supervision for GAN-based video generation},
author={<NAME> and <NAME> and <NAME> and Leal-Taix{\'e}, Laura and <NAME>},
journal={ACM Transactions on Graphics (TOG)},
volume={39},
number={4},
pages={75--1},
year={2020},
publisher={ACM New York, NY, USA}
}
```
```tex
@misc{tecogan_pytorch,
author={<NAME> and <NAME>},
title={PyTorch Implementation of Temporally Coherent GAN (TecoGAN) for Video Super-Resolution},
howpublished="\url{https://github.com/skycrapers/TecoGAN-PyTorch}",
year={2020},
}
```
## Acknowledgements
This code is built on [TecoGAN-TensorFlow](https://github.com/thunil/TecoGAN), [BasicSR](https://github.com/xinntao/BasicSR) and [LPIPS](https://github.com/richzhang/PerceptualSimilarity). We thank the authors for sharing their codes.
If you have any questions, feel free to email me `<EMAIL>`
|
afd87fedbbccea7c8b29e1ca49e6848d19e5354f
|
[
"Markdown",
"Python"
] | 2 |
Python
|
zzg-tju/TecoGAN-PyTorch
|
15d87000ed35d2037317144f54fa0e3d64f34e2f
|
2ecd148417cb741f95e29c3d75158f259edbf9a2
|
refs/heads/master
|
<repo_name>Retardvoldy/project_euler<file_sep>/euler002.py
##Even Fibonacci numbers
##Problem 2
##Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
##
##1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
##
##By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
##f(n) = f(n-1) - f(n-2) where n > 2
##f(n) = 1
##f(n) = 2
##def fibo(n):
## if n == 1: # terminating case 1
## return 1
## if n == 2: # terminating case 2
## return 2
## else:
## return fibo(n-1) + fibo(n-1)
def fibo(term1, term2):
while term1 + term2 < 4000000:
fibo = term1 + term2
term1 = term2
term2 = fibo
return fibo
# main
print(fibo(1, 2))
|
19b5752bf4684984fe32f7f2a18f501584563a19
|
[
"Python"
] | 1 |
Python
|
Retardvoldy/project_euler
|
5e38b3fc12e0b57a13fd1ac47573feb48df1b89f
|
2d2e4e84f5746020c517b479c1fa7a0e3526c303
|
refs/heads/master
|
<repo_name>Chrhernk/package-finder-64<file_sep>/HKTRY3/HKTRY3/Source.cpp
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
srand(static_cast<unsigned int>(time(0)));
//seed random number generator
//int secretNumber = rand() % 100 + 1;
//random number between 1-100
int trueLocation = rand() % 64 + 1;
int tries = 0;
int searchGridHighNumber = 64;
int searchGridLowNumber = 1;
int predicted = ((searchGridHighNumber - searchGridLowNumber) / 2) + searchGridLowNumber;
bool solved = false;
cout << "\tWelcome to Package finder 64!!!\n\n";
do
{
int predicted = ((searchGridHighNumber - searchGridLowNumber) / 2) + searchGridLowNumber;
cout << "\n\nThe AI has guessed the package is at :" << predicted;
cout << "\n\nthe package is at : " << trueLocation;
++tries;
if (predicted > trueLocation)
{
cout << "\n\nOVERSHOT!!!\n\n";
searchGridHighNumber = predicted;
}
else if (predicted < trueLocation)
{
cout << "\n\nUNDERSHOT\n\n";
searchGridLowNumber = predicted;
}
else
{
cout << "\nThats it!! The AI got it in " << tries << " Guesses!!\n";
solved = true;
}
} while (solved == false);
return 0;
}
|
f207796fb9a13a80def235f4875a9933e07cc9a2
|
[
"C++"
] | 1 |
C++
|
Chrhernk/package-finder-64
|
d29d8008d3c01ac3d3eb1b6b458248e2b90d63ee
|
2370af7ee9ecbb08a42054116040351c95bfe985
|
refs/heads/master
|
<file_sep>const { json } = require('express');
let Lead = require('../models/lead/lead.model');
exports.getAllLeads = async (req, res) => {
console.log(req.body);
await Lead.find()
.then(leads => res.json(leads))
.catch(err => res.status(400).send('Error: ' + err));
};
//GEt lead by ID
exports.getLeadbyId = async (req, res) => {
await Lead.findById(req.params.id)
.then(lead => res.json(lead))
.catch(err => res.status(400).json('Error: '+err));
};
exports.getByPhoneNumber = async (req, res) => {
const Phone = req.body.Phone;
console.log('Displaying all Data...')
await Lead.find({ Phone: `${Phone}` })
.then(leads => res.json(leads))
.catch(err => res.status(400).send('Error :' + err));
};
exports.getByFirstName = async (req, res) => {
const first = req.body.firstName;
console.log('Displaying specific first name');
await Lead.find({ firstName: `${first}` })
.then(leads => res.json(leads))
.catch(err => res.status(400).send('Error :' + err));
};
exports.getByLastName = async (req, res) => {
const LastName = req.body.lastName;
console.log('Displaying specific last name');
await Lead.find({ lastName: `${LastName}` })
.then(leads => res.json(leads))
.catch(err => res.status(400).send('Error :' + err));
};
exports.getByCampaignType = async (req, res) => {
const campaign = req.body.Type;
console.log('Displaying specific campaign');
await Lead.find({ Type: `${campaign}` })
.then(leads => res.json(leads))
.catch(err => res.status(400).send('Error :' + err));
};
exports.getByDispositionType = async (req, res) => {
const disposition = req.body.Xencall;
console.log('Displaying specific disposition');
await Lead.find({ Xencall: `${disposition}` })
.then(leads => res.json(leads))
.catch(err => res.status(400).send('Error :' + err));
};
exports.addNewLead = async (req, res) => {
const { firstName, lastName, Address, City, Zip, Xencall, Type, Phone } = req.body;
const newLead = new Lead({ firstName, lastName, Address, City, Zip, Xencall, Type, Phone });
console.log('Adding new lead...');
await newLead.save()
.then(() => res.json('Lead added!'))
.catch(err => res.status(400).json('Error: ' + err));
};
//update leads
exports.updateLead = async(req, res)=>{
await Lead.findByIdAndUpdate(req.params.id,
req.body, { new: true, runValidators: true })
.then(()=> res.json('Lead Updated!'))
.catch(err => res.status(400).json('Error: '+err));
};
//Delete lead
exports.deleteLeadById = async (req, res) => {
await Lead.findByIdAndDelete(req.params.id)
.then(()=>res.json('Successfully deleted!'))
.catch(err => json.status(400).json("Error: "+err));
};<file_sep>import React, { useState, useEffect } from 'react';
import { useHistory } from 'react-router-dom';
import axios from 'axios';
import Table from 'react-bootstrap/Table';
import { faEdit, faTrash } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import Sidebar from '../Sidebar/Sidebar';
export default () => {
const history = useHistory();
const [dispositons, setDispositions] = useState({});
//const [id, setId] = useState({});
//fetch disposition
const fetchDisposition = async () => {
const res = await axios.get('http://localhost:4001/dispositions/all');
setDispositions(res.data);
};
useEffect(() => { fetchDisposition() }, []);
const IconEdit = (x) => {
history.push('/UpdateDisposition', { id: x });
};
//function to map disposition
const fetchedDispotions = Object.values(dispositons).map(x => {
return <tr key={x._id}>
<td>{x.dispositionName}</td>
<td>{x.dispositionDescription}</td>
<td><a className="action-btn" onClick={() => { IconEdit(x._id) }}><FontAwesomeIcon icon={faEdit} /></a></td>
<td><FontAwesomeIcon icon={faTrash} /></td>
</tr>
});
//function to navigate to create dispo
const addDisposition = () => {
history.push('/AddDisposition');
};
//render the page
return <div className="container">
<div className="row">
<div className="col-lg-2"><Sidebar /></div>
<div className="col-lg-10">
<Table striped bordered hover>
<thead>
<tr>
<th>Disposition Name</th>
<th>Disposition Description</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
{fetchedDispotions}
</tbody>
</Table>
<div>
<button className="btn btn-primary" onClick={addDisposition}>Create Disposition</button>
</div>
</div>
</div>
</div>
};<file_sep>const { json } = require('express');
let Dispositions = require('../models/lead/disposition.model');
exports.getAllDisposition = async (req, res) =>{
console.log('getting all dispositions...');
Dispositions.find()
.then(dispo => res.json(dispo))
.catch(err => res.status(400).send('Error: '+err));
};
//get disposition by ID
exports.getDispoByID = async(req, res) => {
console.log('gettinf one dispo....');
Dispositions.findById(req.params.id)
.then(dispo => res.json(dispo))
.catch(err => res.status(400).send('Error: '+err));
};
//post disposition
exports.postDisposition = async(req, res) => {
const{dispositionName, dispositionDescription} = req.body;
const newDispo = new Dispositions({dispositionName, dispositionDescription});
console.log('Adding new dispo into the DB');
newDispo.save()
.then(()=> res.json('New disposition successfully added!!'))
.catch(err => res.status(400).send('Error: '+err));
};<file_sep>const router = require('express').Router();
const dispoController = require('../LeadController/dispositionController');
//get all dispo
router.get('/all', dispoController.getAllDisposition);
//get dispo by id
router.get('/:id', dispoController.getDispoByID);
//post new disposition
router.post('/addDispo', dispoController.postDisposition);
module.exports = router;<file_sep>import React, { useState, useEffect } from 'react';
import {Link, useHistory} from 'react-router-dom';
import axios from 'axios';
import Table from 'react-bootstrap/Table';
// get our fontawesome imports
import { faEdit, faTrash } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
export default () => {
const history = useHistory();
const [leads, setLeads] = useState({});
const fetchLeads = async () => {
const res = await axios.get('http://localhost:4001/');
setLeads(res.data);
};
useEffect(() => {
fetchLeads();
}, []);
const addLead = async () => {
history.push("/AddLead");
};
//Edit Lead
const IconEdit = async(x)=>{
history.push('/UpdateLead', {id: x});
};
//Delete lead
const IconDelete = async(_id)=>{
history.push('/DeleteLead', {leadId: _id});
};
const renderedLeads = Object.values(leads).map(lead => {
return <tr key={lead._id}>
<td>{lead.firstName}</td>
<td>{lead.lastName}</td>
<td>{lead.Address}</td>
<td>{lead.City}</td>
<td>{lead.Type}</td>
<td>{lead.Xencall}</td>
<td>{lead.Phone}</td>
<td><a className="action-btn" onClick={()=> {IconEdit(lead._id)}}><FontAwesomeIcon icon={faEdit}/></a></td>
<td><a className="action-btn" onClick={()=> {IconDelete(lead._id)}}><FontAwesomeIcon icon={faTrash}/></a></td>
</tr>
});
return <div>
<Table striped bordered hover>
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Address</th>
<th>City</th>
<th>Campaign</th>
<th>Disposition</th>
<th>Phone</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
{renderedLeads}
</tbody>
</Table>
<div>
<button className="btn btn-primary" onClick={addLead}>Add Lead</button>
</div>
</div>
};<file_sep># LeadManagerApp
LeadManagerApp used to manage real estate leads
<file_sep>import React, { useState } from 'react';
import Sidebar from '../Sidebar/Sidebar';
import axios from 'axios';
export default () => {
const [campaignName, setCampaignName] = useState('');
const [campaignState, setCampaignState] = useState('');
const [campaignDescription, setCampaignDescription] = useState('');
const onSubmit = async (event) => {
event.preventDefault();
await axios.post('http://localhost:4001/campaigns/addCampaign', { campaignName, campaignState, campaignDescription });
setCampaignName('');
setCampaignState('');
setCampaignDescription('');
};
return <div className="container">
<div className="row">
<div className="col-lg-2"><Sidebar /></div>
<div className="col-lg-10">
<form onSubmit={onSubmit}>
<div className="form-group">
<label>Campaign Name</label>
<input value={campaignName} onChange={e => setCampaignName(e.target.value)} className="form-control" />
<label>Campaign State</label>
<input value={campaignState} onChange={e => setCampaignState(e.target.value)} className="form-control" />
<label>Campaign Description</label>
<textarea rows="3" value={campaignDescription} onChange={e => setCampaignDescription(e.target.value)} className="form-control" />
</div>
<button className="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
};<file_sep>const { json } = require('express');
let Campaigns = require('../models/lead/campaign.model');
exports.getAllCampaign = async (req, res) => {
await Campaigns.find()
.then(x => res.json(x))
.catch(err => res.status(400).send('Error: ' + err));
};
//Get campaign by ID
exports.getCampainById = async (req, res) => {
await Campaigns.findById(req.params.id)
.then(lead => res.json(lead))
.catch(err => res.status(400).json('Error: '+err));
};
//post a campaign
exports.postACampaign = async(req, res) => {
console.log(req.body);
const {campaignName, campaignState, campaignDescription} = req.body;
const newCampaign = new Campaigns({campaignName, campaignState, campaignDescription});
console.log('Adding new campaigns....');
newCampaign.save()
.then(() => res.json('New Campaign added to the database'))
.catch(err => res.status(400).send('Error: '+err));
};<file_sep>import React, { useState, useEffect } from 'react';
import {useHistory, useLocation} from 'react-router-dom';
import axios from 'axios';
export default()=>{
const location = useLocation();
const leadId = location.state.id;
//const[lead, setLead]=useState({});
const [firstName, setFirstName] = useState('');
const [lastName, setLastName] = useState('');
const [Address, setAddress] = useState('');
const [City, setCity] = useState('');
const [Zip, setZip] = useState('');
const [Type, setCampaign] = useState('');
const [Phone, setphone] = useState('');
const [Xencall, setDisposition]=useState('');
const [leadNote, setLeadNote]=useState('');
const fetchLead = async()=>{
const res = await axios.get(`http://localhost:4001/${leadId}`);
//setLead(res.data);
setFirstName(res.data.firstName);
setLastName(res.data.lastName);
setAddress(res.data.Address);
setCity(res.data.City);
setZip(res.data.Zip);
if(typeof res.data.Type === 'undefined'){setCampaign('');}
//setCampaign(res.data.Type);
setphone(res.data.Phone );
//setDisposition(res.data.Xencall);
if(typeof res.data.Xencall === 'undefined'){setDisposition('');}
};
useEffect(()=>{fetchLead()},[]);
const onSubmit = ()=>{
console('leadName'+firstName);
};
return<div>
<form onSubmit={onSubmit}>
<div className="form-group">
<label>First Name</label>
<input value={firstName} onChange={e => setFirstName(e.target.value)} className="form-control" />
<label>Last Name</label>
<input value={lastName} onChange={e => setLastName(e.target.value)} className="form-control" />
<label>Address</label>
<input value={Address} onChange={e => setAddress(e.target.value)} className="form-control" />
<label>City</label>
<input value={City} onChange={e => setCity(e.target.value)} className="form-control" />
<label>Zip</label>
<input value={Zip} onChange={e => setZip(e.target.value)} className="form-control" />
<label>Telephone</label>
<input value={Phone} onChange={e => setphone(e.target.value)} className="form-control" />
<label>Campaign</label>
<input value={Type} onChange={e => setCampaign(e.target.value)} className="form-control" />
<label>Dispositon</label>
<input value={Xencall} onChange={e => setDisposition(e.target.value)} className="form-control" />
<label>Notes</label>
<textarea rows="6" value={leadNote} onChange={e => setLeadNote(e.target.value)} className="form-control"/>
</div>
<button className="btn btn-primary">Update</button>
</form>
</div>
};<file_sep>const router = require('express').Router();
const campaignCOntroller = require('../LeadController/campaignController');
//get all campaign
router.get('/all', campaignCOntroller.getAllCampaign);
//get campaign by id
router.get('/:id', campaignCOntroller.getCampainById);
//post a campaign
router.post('/addCampaign', campaignCOntroller.postACampaign);
module.exports = router;<file_sep>const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const leadSchema = new Schema({
firstName:{type:String, required:false},
lastName:{type: String, required: false},
Address:{type: String, required: false},
City: {type: String, required: false},
Zip: {type: String, required: false},
Xencall: {type: String, required: false},
Type: {type: String, requred: false},
Phone:{ type: String, required:false}
});
const Leads = mongoose.model('Leads', leadSchema);
module.exports = Leads;<file_sep>import React from 'react';
import Sidebar from '../Sidebar/Sidebar';
import ViewCampaign from '../Campaigns/CampaignView';
export default () => {
return<div className="container">
<div className="row">
<div className="col-lg-2"><Sidebar/></div>
<div className="col-lg-10"><ViewCampaign/></div>
</div>
</div>
};
<file_sep>import React, { useState } from 'react';
import axios from 'axios';
import Sidebar from '../Sidebar/Sidebar';
export default () => {
const [dispositionName, setDispositionName] = useState('');
const [dispositionDescription, setDispositionDescription] = useState('');
const onSubmit = async (event) => {
event.preventDefault();
await axios.post('http://localhost:4001/dispositions/addDispo', { dispositionName, dispositionDescription });
setDispositionName('');
setDispositionDescription(''); //dispositionDescription
};
return <div className="container">
<div className="row">
<div className="col-lg-2"><Sidebar /></div>
<div className="col-lg-10">
<form onSubmit={onSubmit}>
<div className="form-group">
<label>Disposition Name</label>
<input value={dispositionName} onChange={e => setDispositionName(e.target.value)} className="form-control" />
<label>Disposition Description</label>
<textarea rows="3" value={dispositionDescription} onChange={e => setDispositionDescription(e.target.value)} className="form-control" />
</div>
<button className="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
};
|
97c3fb4642ab65c68a8ee97a7ada4c7f08d68689
|
[
"JavaScript",
"Markdown"
] | 13 |
JavaScript
|
diddyp20/LeadManagerApp
|
c44506c883c17b07281583ba505b98682e87e773
|
ffcf761c81490993594f4a7b383f48c62587700d
|
refs/heads/master
|
<repo_name>studflexmax/pyviz<file_sep>/content/charts/histogram.md
title: Histogram
author: studflexmax
date: 2016-04
[TOC]
### Quick Dirty
:::python
sample_dataframe.hist() # Option 1, PREFERED

:::python
sample_dataframe.plot(kind='hist') # Option 2

### Clean Shaven
:::python
# Customize binning resolution
bin_boundaries = range(0, 11, 1)
ax_hist = sample_dataframe.hist(
column=[
'int_field_1',
'int_field_2'],
bins=bin_boundaries,
layout=(2,1),
sharex=True,
sharey=True)

### Random Thoughts
<file_sep>/content/charts/violin.md
title: Violin Plot
author: studflexmax
date: 2016-04
[TOC]
### Quick Dirty
:::python
seaborn.violinplot(sample_dataframe) # Option 1

### Random Thoughts
<file_sep>/requirements.txt
# This requirements file lists all third-party dependencies for this project.
#
# Run 'pip install -r requirements.txt -t lib/' to install these dependencies
# in `lib/` subdirectory.
#
# Note: The `lib` directory is added to `sys.path` by `appengine_config.py`.
# Flask==0.10.1
# Flask-FlatPages==0.5
# Frozen-Flask==0.11
# Jinja2==2.7.1
# Markdown==2.3.1
# MarkupSafe==0.18
# PyYAML==3.10
# Pygments==1.6
# Werkzeug==0.9.3
# itsdangerous==0.22
# wsgiref==0.1.2
Flask
Flask-FlatPages
Frozen-Flask
Jinja2
Markdown
MarkupSafe
PyYAML
Pygments
Werkzeug
itsdangerous
wsgiref
<file_sep>/content/charts/box.md
title: Box Plot
author: studflexmax
date: 2016-04
[TOC]
### Quick Dirty
:::python
sample_dataframe.boxplot() # Option 1, PREFERED

:::python
seaborn.boxplot(sample_dataframe) # Option 2

### Clean Shaven
:::python
# Option 1
ax_box = sample_dataframe.boxplot(
column=['int_field_1'],
by=['string_field_1']) # grouping by a categorical var

:::python
# Option 2
ax_box = seaborn.boxplot(
data=sample_dataframe,
x='int_field_2',
y='string_field_1', # grouping by a categorical var
orient='h')

### Random Thoughts
<file_sep>/content/charts/line.md
title: Line Plot
author: studflexmax
date: 2016-04
[TOC]
### Quick Dirty
:::python
sample_dataframe.plot.line() # Option 1

### Clean Shaven
:::python
# Extract the row index values, range(0, n, 1), into a field.
# This is required to use the index as the x-axis.
sample_dataframe['index_value'] = sample_dataframe.index
seaborn.pointplot(
data=sample_dataframe,
estimator=numpy.mean,
x='index_value',
y='int_field_1',
join=True)
seaborn.pointplot(
data=sample_dataframe,
estimator=numpy.mean,
x='index_value',
y='int_field_1',
hue='string_field_1',
join=False)

### Random Thoughts
<file_sep>/content/misc/index.md
date: 2016-04-25
author: studflexmax
<h1 align='center'>Python Data Visualization Primer</h1>
<br>
<p align='center'>One-liners to visualize data.</p>
<p align='center'>Embrace it & spread it on.</p>
<br>
<p align='center'>
<img src='/static/img/poster.jpg' alt='poster' style='width:300px; height:382px;' align='center'>
</p>
<file_sep>/content/charts/heatmap.md
title: Heatmap
author: studflexmax
date: 2016-04
[TOC]
### Quick Dirty
:::python
two_dimentional_dataframe = sample_dataframe.pivot_table(
index="string_field_1", columns="string_field_2", values="float_field_1")
seabor.heatmap(two_dimentional_dataframe)

### Random Thoughts
<file_sep>/content/misc/sample_data.md
title: Sample Data
author: studflexmax
date: 2016-04
[TOC]
### Generate Sample Data
:::python
# Generate some sample data to vizualize.
numpy.random.seed(49)
sample_size = 100
strings = ['foo', 'bar', 'baz', 'qux']
sample_dataframe = pandas.DataFrame({
'int_field_1': numpy.random.randint(1, 11, sample_size),
'int_field_2': numpy.random.randint(1, 11, sample_size),
'float_field_1': numpy.random.normal(0, 10, sample_size),
'float_field_2': numpy.random.normal(0, 10, sample_size),
'string_field_1': numpy.random.choice(strings, sample_size),
'string_field_2': numpy.random.choice(strings, sample_size)})
print(sample_dataframe.shape)
sample_dataframe.head(10)

### Random Thoughts
<file_sep>/content/charts/bar.md
title: Bar
author: studflexmax
date: 2016-04
[TOC]
### Quick Dirty
:::python
# Option 1, PREFERED
seaborn.barplot(sample_dataframe.string_field_1, sample_dataframe.int_field_1)

:::python
# Option 2
sample_dataframe.groupby("string_field_1").sum()['int_field_1'].plot.bar()

### Clean Shaven
:::python
seaborn.barplot(
data=sample_dataframe,
orient='h',
estimator=numpy.median,
x='float_field_1',
y='string_field_1',
order=['baz', 'bar', 'qux', 'foo'],
hue_order=['b', 'g', 'r', 'p'])

### Random Thoughts
<file_sep>/content/charts/scatter_matrix.md
title: Scatter Matrix
author: studflexmax
date: 2016-04
[TOC]
### Quick Dirty
:::python
seaborn.pairplot(sample_dataframe) # Option 1, PREFERED

:::python
pandas.tools.plotting.scatter_matrix(sample_dataframe) # Option 2

### Clean Shaven
:::python
ax_scatter_matrix = seaborn.pairplot(
data=sample_dataframe,
x_vars=[
'int_field_1',
'int_field_2',
'float_field_1'],
y_vars=[
'int_field_1',
'int_field_2',
'float_field_1'],
diag_kind = 'kde', # kde vs hist
hue='string_field_1', # color base on categories
palette = 'Spectral')

### Random Thoughts
<file_sep>/content/misc/preface.md
title: Preface
author: studflexmax
date: 2016-04
[TOC]
### Mission
Seek out the most practical & efficient data visualization possible.
### About Me
Grew up in Vancouver, studied in Ithaca, currently working with Big Data in Mountain View.
### Python Data Visualization Options
There are many data visualization options available, from mild (Excel) to
wild (writing customized javascript/python/R libraries). Even within Python,
there are many options. Here, let's examine some of the most popular ones:
#### [Matplotlib](http://matplotlib.org/)
* a highly-customizable plotting lib for Python, forming the basis for
many other modules/packages on this list.
* **CON**: Complexity, requires too much effort to produce charts
required during an (exploratory) analysis.
* **SUITABLE**: Fine-tune plots produced by other packages
that build off matplotlib (e.g. seaborn, pandas).
#### [Pandas](http://pandas.pydata.org/) [chosen for this primer]
* An absolute godsend, THE data structure/analysis tool for anyone who is
interested in working with data in Python.
* Created by the great [<NAME>](https://twitter.com/wesmckinn).
* Integrated plotting functions into data structures (e.g. Series, DataFrames).
* e.g. Allows you to conveniently `sample_dataframe.hist()` to produce a
histogram.
* In most cases these plotting functions call matplotlib.
* **CON**: Currently lacks the ability produce some less-common plots (e.g.
heatmap, violin plots).
* **PRO**: Fast, second only to using matplotlib natively.
* This is critically important when the data points gets large (say
>=50,000 data pt, working on a "high-performance" laptop).
* e.g. Its implementation of histogram is likely the fastest
amongst all the available options, often only require a fifth or a
tenth of the time it would require other packages to produce a
comparable histogram.
* **PRO**: Convenient, in most cases only require 1 line of code (instead of
the 10-20 lines typically required when using matplotlib, even assuming a
simple plot).
* **SUITABLE**: Produce charts/plots required during an analysis to verify
insights and/or explore shapes/distributions/correlations.
* In most cases it's fairly easy to convert these often rough-on-the-edges
plots into something nice and presentable.
#### [Seaborn](https://stanford.edu/~mwaskom/software/seaborn/) [chosen for this primer]
#### [Bokah](http://bokeh.pydata.org/)
* A Python interactivite visualization library that targets modern web
browswers for presentation.
* **CON**: Performance, when working with large number of data points, it may
take impractically long to produce required plots.
* Thus omitted from this primer.
* **PRO**: Interactivity, all plots are rendered as javascript widgets;
therefore, you can manipulate the plots after they have been generated
(pinch, zoom, change resolution, etc.).
* **SUITABLE**: Context in which the number of data points is managable (in
my experience ~5,000 on a laptop) and interactivity is required/prefered
(e.g. dashboards, webpages).
#### [PyGal](http://www.pygal.org/)
#### [VisPy](http://vispy.org/)
#### [Folium](https://folium.readthedocs.io/)
#### [NetworkX](http://networkx.github.io/)
### Inspirations & Learning Resources
<file_sep>/main.py
"""Top level module for your Flask application."""
import datetime
from pytz.gae import pytz
# Import the Flask Framework
from flask import Flask, render_template
app = Flask(__name__)
from flask_flatpages import FlatPages, pygments_style_defs
from flask_frozen import Freezer
# Don't need to call run() since the app is embedded within the App Engine WSGI
# application server.
# Configuration for FlatPages
DEBUG = True
FLATPAGES_AUTO_RELOAD = DEBUG
FLATPAGES_EXTENSION = '.md'
FLATPAGES_ROOT = 'content'
FLATPAGES_MARKDOWN_EXTENSIONS = [
'codehilite', 'headerid',
'toc']
flatpages = FlatPages(app)
app.config.from_object(__name__)
@app.errorhandler(404)
def page_not_found(e):
"""Return a custom 404 error."""
return 'Sorry, Nothing at this URL.', 404
@app.errorhandler(500)
def application_error(e):
"""Return a custom 500 error."""
return 'Sorry, unexpected error: {}'.format(e), 500
# For '/', render from markdown /content/misc/index.md.
@app.route('/')
def index(misc_dir='misc'):
"""Return a friendly HTTP greeting."""
path = '{}/{}'.format(misc_dir, 'index')
content = flatpages.get_or_404(path)
return render_template("index.html", content=content)
# For '/misc/*', render from markdown /content/misc/<name>.md.
@app.route('/misc/<name>/')
def misc(name, misc_dir='misc'):
path = '{}/{}'.format(misc_dir, name)
content = flatpages.get_or_404(path)
return render_template('index.html', content=content)
# For '/charts/*', render from markdown /content/charts/<name>.md.
@app.route('/charts/<name>/')
def chart(name, charts_dir='charts'):
path = '{}/{}'.format(charts_dir, name)
content = flatpages.get_or_404(path)
return render_template('index.html', content=content)
# For the pygments module.
@app.route('/pygments.css')
def pygments_css():
return pygments_style_defs('tango'), 200, {'Content-Type': 'text/css'}
<file_sep>/content/charts/pie.md
title: Pie Plot
author: studflexmax
date: 2016-04
[TOC]
### Quick Dirty
:::python
# Sum ofint_field_1, by categories string_field_1
sample_dataframe.groupby("string_field_1").sum()['int_field_1'].plot.pie()

### Random Thoughts
|
f3881b6e313fe85cb174f864cf3b239e42e922b2
|
[
"Markdown",
"Python",
"Text"
] | 13 |
Markdown
|
studflexmax/pyviz
|
99ed96e56c90ce2002d09b2d04e2307a981cf5a8
|
4d2dd5955c5479ad062393036c31da77693694f5
|
refs/heads/main
|
<file_sep>import { HttpClient, HttpErrorResponse, HttpParams, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable, throwError } from 'rxjs';
import { catchError, tap } from 'rxjs/operators';
import { NotificationService } from 'src/app/notification.service';
import { environment } from 'src/environments/environment';
@Injectable({
providedIn: 'root'
})
export class ImageService {
constructor(private http: HttpClient, private notiService: NotificationService) { }
upload(formData: FormData): Observable<any> {
return this.http.post(`${environment.backend_host}/api/images`, formData).pipe(
tap(() => this.notiService.success("Images have been uploaded")),
catchError((err: HttpErrorResponse) => {
this.notiService.error(err.message);
return throwError(err);
}));
}
get(search? : string): Observable<string[]> {
let params = new HttpParams();
if(search != null || search != "") params = params.set("search", search);
return this.http.get<string[]>(`${environment.backend_host}/api/images`, { params: params }).pipe(
catchError((err: HttpErrorResponse) => {
this.notiService.error(err.message);
return throwError(err);
})
)
}
}
<file_sep>export const environment = {
production: true,
backend_host: "https://backend.yuss.cc"
};
<file_sep># Shopify Challenge: [yuss.cc](https://yuss.cc) 📷
[yuss.cc](https://yuss.cc) is a public image repository where everyone can upload their images. This project is made as part of the application submission to Shopify Summer Internship 2021.
This repository hosts the frontend code for [yuss.cc](https://yuss.cc)
## Installation ⚙️
### Requirements
- Node.js version 12.14.0 installed
- UNIX environment
### Steps
1. Install npm dependencies
``` bash
npm install
```
2. Serve Angular application
```
node_modules/@angular/cli/bin/ng serve
```
3. Open [localhost:4200](http://localhost:4200/) and you should be able to see our application running
## Contributing
Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.
## License
[MIT](https://choosealicense.com/licenses/mit/)<file_sep>import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';
import { Alert, AlertType } from 'src/models/alert.model';
@Injectable({
providedIn: 'root'
})
export class NotificationService {
private subject = new Subject<Alert>();
constructor() { }
success(msg: string) {
this.subject.next(new Alert(msg, AlertType.Success));
this.close();
}
error(msg: string) {
this.subject.next(new Alert(msg, AlertType.Error));
this.close();
}
info(msg: string) {
this.subject.next(new Alert(msg, AlertType.Info));
this.close();
}
onAlert(): Observable<Alert> {
return this.subject.asObservable();
}
close(timeout = 10000) {
setTimeout(() => {
this.subject.next(new Alert(null, AlertType.Close))
}, timeout);
}
}
<file_sep>export class Alert {
msg: string;
type: AlertType
constructor(msg: string, type: AlertType) {
this.msg = msg;
this.type = type;
}
}
export enum AlertType {
Success,
Error,
Info,
Close
}<file_sep>import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core';
import { Observable, Subject } from 'rxjs';
import { switchMap, tap } from 'rxjs/operators';
import { ImageService } from 'src/app/image.service';
import { NotificationService } from 'src/app/notification.service';
import { Alert, AlertType } from 'src/models/alert.model';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements AfterViewInit {
@ViewChild('file_input', { static: false }) file_input_el;
@ViewChild('modal', { static: false }) modal;
@ViewChild('modal_caption', { static : false }) modal_caption;
@ViewChild('modal_img', { static: false }) modal_img;
title = 'shopify-challenge-frontend';
AlertType = AlertType;
alertObservable$: Observable<Alert> = this.notiService.onAlert();
searchSubject$: Subject<string> = new Subject();
imagesObservable$: Observable<string[]> = this.searchSubject$.pipe(
switchMap((search: string) => this.imageService.get(search))
)
ngOnInit() {
}
ngAfterViewInit() {
this.searchSubject$.next("");
}
showImageUploadInput() {
this.file_input_el.nativeElement.click();
}
search(value: string) {
this.searchSubject$.next(value);
}
upload(files: FileList) {
if(files == null || files.length == 0) return;
var formData: FormData = new FormData();
for(var i = 0; i < files.length; i++) {
var file = files.item(i);
if(file.size >= 5e6) {
this.notiService.error("Only image that is less than 5 MB in file size can be uploaded");
return;
}
formData.append('photos', file);
}
this.imageService.upload(formData).pipe(
tap(() => this.searchSubject$.next(""))
).subscribe();
}
showModal(image: string) {
let el = this.modal.nativeElement;
el.style.display = "block";
el.src = image;
this.modal_img.nativeElement.src = image
this.modal_caption.nativeElement.innerHTML = image.substring(image.indexOf('_') + 1);
}
closeModal() {
this.modal.nativeElement.style.display = "none";
}
constructor(public notiService: NotificationService,
private imageService: ImageService) { }
}
|
f3d8bb4c88c659e1d2f0276137d3bd6c6559d943
|
[
"Markdown",
"TypeScript"
] | 6 |
TypeScript
|
hongthang152/shopify-challenge-frontend
|
5f7a86b9b178320d93407275491aac59db7e7ab0
|
b18913f1e0106893c479fd320a4e3f88422ceee7
|
refs/heads/master
|
<file_sep>AppharborLogTesting
===================
AppharborLogTesting
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using log4net;
namespace AppharborLogTesting
{
public partial class _Default : System.Web.UI.Page
{
private static readonly ILog logger = LogManager.GetLogger(typeof(_Default));
protected void Page_Load(object sender, EventArgs e)
{
logger.Debug("Debugging message");
logger.Info("Info message");
logger.Warn("Warning message");
logger.Error("Error message");
logger.Fatal("Fatal message");
}
}
}
|
d44dec65be35c7b1565f5e14b73bc7d0f6d7fbd5
|
[
"Markdown",
"C#"
] | 2 |
Markdown
|
mohanvkumar/AppharborLogTesting
|
bfee4d9dee90948f9aa4044b8a852cdbf7767b66
|
9c3edcfb2e6daa67855a43918536735e7efb3712
|
refs/heads/master
|
<repo_name>LauraDiosan-CS/lab04-craciungabi<file_sep>/LAB4-prob3/apartament.h
#ifndef APARTAMENT_H
#define APARTAMENT_H
#include <bits/stdc++.h>
class APARTAMENT
{
private:
int nrAp;
int suma;
char* tipAp;
public:
APARTAMENT();
APARTAMENT(int nr, int su, char* tip);
APARTAMENT(const APARTAMENT &s);
~APARTAMENT();
int getNrAp();
int getSuma();
char* getTip();
void setNrAp(int nr);
void setSuma(int su);
void setTip(char* tip);
APARTAMENT& operator=(const APARTAMENT &s);
bool operator==(const APARTAMENT &s);
};
#endif // APARTAMENT_H
<file_sep>/LAB4-prob3/main.cpp
#include <bits/stdc++.h>
#include "tests.h"
using namespace std;
int main()
{
cout << " start... " << endl;
testRepo();
testApart();
cout << " good job!! " << endl;
return 0;
}
<file_sep>/LAB4-prob3/tests.cpp
#include "tests.h"
#include "apartament.h"
#include "repo.h"
#include <bits/stdc++.h>
using namespace std;
void testApart()
{
APARTAMENT a1(12,100,"gaaz");
APARTAMENT a2(15,200,"apa");
APARTAMENT a3(5,400,"gaz");
APARTAMENT a4(6,50,"electricitate");
APARTAMENT flats[4] = {a1, a2, a3, a4};
APARTAMENT results[4];
/// A1
assert( a1.getNrAp() == 12);
assert( a1.getSuma() == 100);
assert( strcmp(a1.getTip(),"gaaz")== 0);
a1.setNrAp(60);
assert(a1.getNrAp() == 60);
/// A2
assert( a2.getNrAp() == 15);
assert( a2.getSuma() == 200);
assert( strcmp(a2.getTip(),"apa") == 0);
a2.setNrAp(70);
assert(a2.getNrAp() == 70);
/// A3
assert( a3.getNrAp() == 5);
assert( a3.getSuma() == 400);
assert(strcmp(a3.getTip(),"gaz") == 0);
a3.setNrAp(26);
assert(a3.getNrAp() == 26);
/// A4
assert( a4.getNrAp() == 6);
assert( a4.getSuma() == 50);
assert( strcmp(a4.getTip(), "electricitate") == 0);
a4.setNrAp(288);
assert(a4.getNrAp() == 288);
}
void testRepo()
{
APARTAMENT a1(12,100,"gaaz");
APARTAMENT a2(15,200,"apa");
APARTAMENT a3(5,400,"gaz");
APARTAMENT a4(6,50,"electricitate");
Repo rep;
rep.addItem(a1);
rep.addItem(a2);
rep.addItem(a3);
rep.addItem(a4);
APARTAMENT flats = rep.getItemFromPos(2);
int flat = flats.getNrAp();
int sum = flats.getSuma();
char* tip = flats.getTip();
assert(flat == 5);
assert(sum == 400);
assert(strcmp(tip,"gaz") == 0);
}
<file_sep>/LAB4-prob3/repo.h
#ifndef REPO_H
#define REPO_H
#include "apartament.h"
using namespace std;
class Repo
{
private:
APARTAMENT flats[10];
int noFlats;
public:
Repo();
~Repo();
void addItem(APARTAMENT &s);
APARTAMENT getItemFromPos(int pos);
void getAllItems(Repo &rep);
int getSize();
};
#endif // REPO_H
<file_sep>/LAB4-prob3/tests.h
void testRepo();
void testApart();
<file_sep>/LAB4-prob3/repo.cpp
#include "repo.h"
Repo::Repo()
{
this-> noFlats = 0;
}
Repo::~Repo(){}
void Repo::addItem(APARTAMENT &s)
{
this->flats[this->noFlats++] = s;
}
APARTAMENT Repo::getItemFromPos(int pos)
{
return this->flats[pos];
}
int Repo::getSize()
{
return this->noFlats;
}
<file_sep>/LAB4-prob3/apartament.cpp
#include "apartament.h"
#include <bits/stdc++.h>
/// CONSTRUCTOR
/// In: -
/// Out: an empty object of type APARTAMENT
APARTAMENT::APARTAMENT()
{
this->nrAp = 0;
this->suma = 0;
this->tipAp = NULL;
}
/// Constructor with parameters
/// In: a name (string) and an age (integer)
/// Out: an object of type Student that contains the given info
APARTAMENT::APARTAMENT(int nr, int su, char* tip)
{
this->nrAp = nr;
this->suma = su;
this->tipAp = new char[strlen(tip)+1];
strcpy(this->tipAp, tip);
}
/// Copy constructor
/// In: an object s of type Student
/// Out: another object of type Student that contains the same info as s
APARTAMENT::APARTAMENT(const APARTAMENT &s)
{
this->nrAp = s.nrAp;
this->suma = s.suma;
this->tipAp = new char[strlen(s.tipAp) + 1];
strcpy(this->tipAp, s.tipAp);
}
/// Desonstructor
/// In: an object of type APARTAMENT
/// Out: -
APARTAMENT:: ~APARTAMENT()
{
if(this->nrAp)
{
///delete[] (int*)this->nrAp;
this->nrAp = 0;
}
}
/// GETERS
int APARTAMENT::getNrAp()
{
return this->nrAp;
}
int APARTAMENT::getSuma()
{
return this->suma;
}
char* APARTAMENT::getTip()
{
return this->tipAp;
}
/// Setter
/// In: an object of type APARTAMENT and a nrAp (int)
/// Out: the same object with a new nrAp
void APARTAMENT::setNrAp(int nr)
{
this->nrAp = nr;
}
/// Setter
/// In: an object of type APARTAMENT and a sum (int)
/// Out: the same object with a new sum
void APARTAMENT::setSuma(int sum)
{
this->suma = sum;
}
/// Setter
/// In: an object of type APARTAMENT and a tipAp (char)
/// Out: the same object with a new tipAp
void APARTAMENT::setTip(char* tip)
{
if(this-> tipAp)
delete[] this->tipAp;
this->tipAp = new char[strlen(tip) + 1];
strcpy(this->tipAp, tip);
}
/// assignment operator
/// In: two objects of type APARTAMENT (the current one, this, and s)
/// Out: the new state of the current object (this)
APARTAMENT& APARTAMENT::operator=(const APARTAMENT &s)
{
this->setNrAp(s.nrAp);
this->setSuma(s.suma);
this->setTip(s.tipAp);
return *this;
}
/// comparator
/// In: two objects of type APARTAMENT (this and s)
/// Out: true or false
bool APARTAMENT::operator==(const APARTAMENT &s)
{
return ((this->nrAp == s.nrAp) && (this->suma == s.suma) && (strcmp(this->tipAp, s.tipAp) == 0));
}
|
3f101c11721f62cfa5a3ab24d092ba19f1024b49
|
[
"C",
"C++"
] | 7 |
C++
|
LauraDiosan-CS/lab04-craciungabi
|
00298133e17853e96bfaa1c91ec5799e77277807
|
0135c544121ead99efe263710d56f003ee00d02d
|
refs/heads/master
|
<repo_name>felipestgoiabeira/projeto-ceuma<file_sep>/server/src/routes/alunos.js
const express = require("express");
const router = express.Router();
const auth = require ('../config/passport/auth')
const alunoController = require('../Controllers/AlunosController');
const cursosController = require('../Controllers/CursosController');
router.get('/alunos',auth.required, alunoController.show);
router.get('/alunos/:id', auth.required, alunoController.index)
router.post('/alunos', auth.required, alunoController.store);
router.delete('/alunos/:id', auth.required, alunoController.destroy);
router.put('/alunos/:id', auth.required, alunoController.update);
//rota para paginação
router.get('/getAlunos/:page', auth.optional, alunoController.getAlunos),
router.get('/listarAlunos/:id', auth.required,cursosController.showAlunos)
module.exports = router
<file_sep>/server/src/server.js
const app = require("./config/express");
const models = require('./app/models')
const routes = require("./routes")
//# Routes
app.use("/", routes)
// PORT from .env file
const PORT = process.env.APP_SERVER_PORT || 8000 ;
// sync sequelize mysql and start the server
models.sequelize.sync().then(function () {
app.listen(PORT, function () {
console.log("Listening on localhost:" + PORT);
})
})<file_sep>/server/src/aplication.js
const app = require("./config/express");
const routes = require("./routes")
//# Route
module.exports = app.use("/", routes);<file_sep>/client/react/src/components/loginHeader.js
import React from 'react';
import logo from '../assets/marca2.png';
import { withRouter } from 'react-router';
import { Menus } from './header';
//quando o usuário não está logado
const Login = () => (
<div className="right menu">
<a href="/login" className="ui item">
Login
</a>
<a href="/register" className="ui item">
Sign up
</a>
</div>
);
const Mount = props => {
return (
<div className="ui stackable menu">
<div className="item">
<img className="logo" src={logo} alt="logoCeuma" />
</div>
<a className="item" href="/">
{' '}
Home{' '}
</a>
<>
<Menus />
<Login />
</>
</div>
);
};
function Menu({ location }) {
return <Mount />;
}
export default withRouter(Menu);
<file_sep>/server/__tests__/integration/login.test.js
const faker = require("faker");
const request = require("supertest");
const { users } = require("../../src/app/models/");
const truncate = require("../utils/truncate");
const routes = require("../../src/routes");
const app = require("../../src/config/express");
app.use("/", routes);
const user = {
nome: faker.name.findName(),
email: faker.internet.email(),
password: "<PASSWORD>",
password2: "<PASSWORD>",
}
describe("Login", () => {
beforeEach(async () => {
await truncate();
});
it("should create a user", async () => {
const response = await request(app).post("/register").send(user)
expect(response.status).toBe(200);
});
it("should receive a token after login", async () => {
await request(app).post("/register").send(user);
const response = await request(app).post("/login").send(user);
expect(response.body.success).toBeTruthy();
expect(response.body).toHaveProperty("token");
});
it("should be able to acess private routes", async () => {
await request(app).post("/register").send(user);
const { token } = ( await request(app).post("/login").send(user) ).body;
const response = await request(app).get("/alunos").set("Authorization", token);
expect(response.status).toBe(200);
})
})
<file_sep>/client/react/src/components/redirect.js
import { Component } from 'react';
export default class Redirect extends Component {
componentDidMount() {
try {
this.props.history.push('/');
} catch (error) {
throw error;
}
}
}
<file_sep>/README.md
# Gerenciamento de Cursos e Alunos
Sistema para gerenciamento de alunos e cursos, usuários logados no sistema podem ver, adicionar, alterar e deletar Cursos e Alunos.
## Getting Started
These instructions will get you a copy of the project up and running on your local machine for development and testing purposes.
## Setup project
```sh
docker-compose -f "docker-compose.yml" up -d --build
```
### Run sequelize migrations
```
docker exec -it backend-server /bin/sh -c "[ -e /bin/bash ] && /bin/bash || /bin/sh"
npx sequelize db:migrate
npx sequelize db:seed:all
```
## Built With
* [React](https://reactjs.org/) - A JavaScript library for building user interfaces.
* [Nodejs](https://expressjs.com/) - Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine.
* [Express](https://expressjs.com/) - Fast, unopinionated, minimalist web framework for Node.js.
* [Axios](https://github.com/axios/axios) - Promise based HTTP client for the browser and node.js
* [JSON Web Tokens](https://jwt.io/) - JSON Web Tokens are an open, industry standard RFC 7519 method for representing claims securely between two parties.
* [Passportjs](https://rometools.github.io/rome/) - Simple, unobtrusive authentication for Node.js.
* [Formik](https://jaredpalmer.com/formik/) -Build forms in React, without the tears.
* [Yup](https://github.com/jquense/yup) - Read, manipulate and write spreadsheet data and styles to XLSX and JSON.
* [Sequelize](https://sequelize.org/) - Sequelize is a promise-based Node.js ORM. It features solid transaction support, relations, eager and lazy loading, read replication and more.
* [bcrypts](https://www.npmjs.com/package/bcrypt) - A library to help you hash passwords.
* [validator](https://www.mysql.com/) - TA library of string validators and sanitizers.
* [exceljs](https://www.npmjs.com/package/exceljs) - Read, manipulate and write spreadsheet data and styles to XLSX and JSON.
<!-- ## Requesitos do Sistema -->
O sistema tem os seguintes requisitos
[x]Inserir 3 cursos (código do curso, nome do curso, data de cadastro, carga horária) *Administração, Direito,
Medicina;
[x]Remover cursos;
[x]Alterar cursos;
[x]Inserir 7 alunos (código do aluno, nome do aluno, CPF, Endereço, CEP, E-mail, número de Telefone) atrelando
aos respectivos cursos na seguinte configuração: 2 aluno para Direito, 2 para Administração, 3 para Medicina;
[x]Remover alunos;
[x]Alterar alunos;
[x]Listar os cursos e os alunos que fazem parte deste curso;
[x]O sistema deve exportar a lista de cursos e alunos para planilha excel;
[x]É desejável que o sistema também seja capaz de prevê erros de usuários no ato do cadastro das informações;
[x]É desejável que o sistema possa imprimir os dados dos cursos;
[x]É desejável que o sistema contenha um controle de segurança do acesso ao sistema;
[x]É desejável que o sistema guarde log de acesso em arquivo txt;
## Authors
* **<NAME>** - *Initial work* - [<NAME>](https://github.com/felipestgoiabeira)
<file_sep>/server/src/routes/excel.js
const excel = require('exceljs');
const express = require('express');
const router = express.Router();
const Aluno = require('../app/models').alunos
const Curso = require('../app/models').cursos
const auth = require ('../config/passport/auth')
// -> Express RestAPIs
router.get("/download/alunos", async function (req, res) {
try {
// -> Create a connection to the database
alunosResponse = await Aluno.findAll();
const alunos = JSON.parse(JSON.stringify(alunosResponse));
console.log(alunos);
let workbook = new excel.Workbook(); //creating workbook
let worksheet = workbook.addWorksheet('Alunos'); //creating worksheet
// WorkSheet Header
worksheet.columns = [
{ header: 'Id', key: 'id', width: 10 },
{ header: 'Nome', key: 'nome', width: 30 },
{ header: 'Email', key: 'email', width: 30},
{ header: 'CPF', key: 'cpf', width: 30},
{ header: 'Endereço', key: 'endereco', width: 30},
{ header: 'Cep', key: 'cep', width: 30},
{ header: 'Telefone', key: 'telefone', width: 30},
{ header: 'Curso', key: 'curso_id', width: 30},
];
// Add Array Rows
worksheet.addRows(alunos);
res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
res.setHeader('Content-Disposition', 'attachment; filename=' + 'alunos.xlsx');
return workbook.xlsx.write(res)
.then(function() {
res.status(200).end();
});
} catch (error) {
console.log(error)
}
}
);
router.get("/download/cursos", auth.required,async function (req, res) {
try {
// -> Create a connection to the database
cursosResponse = await Curso.findAll();
const cursos = JSON.parse(JSON.stringify(cursosResponse));
console.log(cursos);
let workbook = new excel.Workbook(); //creating workbook
let worksheet = workbook.addWorksheet('Alunos'); //creating worksheet
// WorkSheet Header
worksheet.columns = [
{ header: 'Id', key: 'id', width: 10 },
{ header: 'Nome', key: 'nome', width: 30 },
{ header: 'Carga Horária', key: 'cargaHoraria', width: 30},
];
// Add Array Rows
worksheet.addRows(cursos);
res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
res.setHeader('Content-Disposition', 'attachment; filename=' + 'cursos.xlsx');
return workbook.xlsx.write(res)
.then(function() {
res.status(200).end();
});
} catch (error) {
console.log(error)
}
}
);
module.exports = router;<file_sep>/server/src/app/models/alunos.js
'use strict';
module.exports = (sequelize, DataTypes) => {
const Alunos = sequelize.define('alunos', {
nome: DataTypes.STRING,
cpf: DataTypes.STRING,
email: DataTypes.STRING,
endereco: DataTypes.STRING,
cep: DataTypes.STRING,
telefone: DataTypes.STRING,
curso_id: DataTypes.INTEGER
}, {});
Alunos.associate = function(models) {
Alunos.belongsTo(models.cursos, {foreignKey: 'curso_id', as: 'curso'})
};
return Alunos;
};<file_sep>/banco-dados/BancoDadosSQL.sql
-- MySQL dump 10.13 Distrib 5.7.27, for Linux (x86_64)
--
-- Host: localhost Database: desafio-ceuma
-- ------------------------------------------------------
-- Server version 5.7.27-0ubuntu0.18.04.1
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Table structure for table `Alunos`
--
DROP TABLE IF EXISTS `Alunos`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Alunos` (
`idAluno` int(11) NOT NULL AUTO_INCREMENT,
`nome` varchar(255) DEFAULT NULL,
`cpf` varchar(11) DEFAULT NULL,
`endereco` varchar(255) DEFAULT NULL,
`cep` varchar(8) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
`telefone` varchar(15) DEFAULT NULL,
`idCursos` int(11) NOT NULL,
PRIMARY KEY (`idAluno`),
KEY `fk_Alunos_Cursos_idx` (`idCursos`),
CONSTRAINT `fk_Alunos_Cursos` FOREIGN KEY (`idCursos`) REFERENCES `Cursos` (`idCurso`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=26 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `Alunos`
--
LOCK TABLES `Alunos` WRITE;
/*!40000 ALTER TABLE `Alunos` DISABLE KEYS */;
INSERT INTO `Alunos` VALUES (19,'<NAME>','60512718900','São Luís','65059668','<EMAIL>','98 98933971',1),(20,'<NAME>','65023457800','São Paulo','60598999','<EMAIL>','89 989124578',1),(21,'<NAME>','65023789800','Rio de Janeiro','60598999','<EMAIL>','89 989128911',2),(22,'<NAME>','67202378900','Rio de Janeiro','6058229','<EMAIL>','89 892212333',1),(23,'<NAME>','67302378900','Rio de Janeiro','6058229','<EMAIL>','89 895512333',2),(24,'<NAME>','895677790','Baixada Maranhense','6258225','<EMAIL>','89 895512333',3),(25,'<NAME>','895677790','Cohatrac','65012225','<EMAIL>','99 895512333',3);
/*!40000 ALTER TABLE `Alunos` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `Cursos`
--
DROP TABLE IF EXISTS `Cursos`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Cursos` (
`idCurso` int(11) NOT NULL AUTO_INCREMENT,
`nome` varchar(255) DEFAULT NULL,
`dataRegistro` date DEFAULT NULL,
`cargaHoraria` int(11) DEFAULT NULL,
PRIMARY KEY (`idCurso`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `Cursos`
--
LOCK TABLES `Cursos` WRITE;
/*!40000 ALTER TABLE `Cursos` DISABLE KEYS */;
INSERT INTO `Cursos` VALUES (1,'Medicina','2019-10-10',80),(2,'Direito','2019-10-10',120),(3,'Administração','2019-10-10',90);
/*!40000 ALTER TABLE `Cursos` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2019-10-11 11:48:55
<file_sep>/client/react/src/pages/alunos/index.js
import React, { useState, useEffect } from 'react';
import './style.css';
import api from '../../services/api';
import { Link } from 'react-router-dom';
import { EXCEL_ALUNOS } from '../../services/constants';
import { FormField, Form, GridColumn } from 'semantic-ui-react';
//select
const Cursos = props => {
return <option value={`${props.curso.nome}`}> {props.curso.nome}</option>;
};
//table
const Alunos = props => (
<>
<tr>
<td>{props.aluno.nome}</td>
<td>{props.aluno.email}</td>
<td>{props.aluno.cpf}</td>
<td>{props.aluno.endereco}</td>
<td>{props.aluno.cep}</td>
<td>{props.aluno.telefone}</td>
<td>{props.aluno.curso.nome}</td>
<td>
<Link to={'/editarAluno/' + props.aluno.id}>Alterar</Link>
</td>
<td>
<a className="action" href={'/deletarAluno/' + props.aluno.id}>
Deletar
</a>
</td>
</tr>
</>
);
export default function AlunosListar() {
//store the alunos to show on table
const [alunos, setAlunos] = useState([]);
//list of cursos to select input
const [cursosList, setCursosList] = useState([]);
//store the value of select
const [curso, setCurso] = useState('');
//store the value of input text
const [nome, setNome] = useState('');
useEffect(() => {
//alunos from api
api
.get('/alunos')
.then(response => {
console.log(response);
setAlunos(response.data);
})
.catch(function(error) {
console.log(error);
});
// get cursos from api
api
.get('/cursos')
.then(response => {
console.log(response);
setCursosList(response.data);
})
.catch(function(error) {
console.log(error);
});
}, []);
//make the list of select
function cursoLista() {
if (cursosList) {
return cursosList.map(function(cursoAtual, i) {
return <Cursos curso={cursoAtual} key={i} />;
});
}
}
//filter on alunos
function alunoList() {
const alunosCurso = [...alunos].filter(aluno => {
// case where user search a name and course
if (curso && nome) {
return (
aluno.curso.nome === curso &&
aluno.nome.toLowerCase() === nome.toLowerCase()
);
}
//case where use only search for name
if (nome) {
return aluno.nome.toLowerCase().includes(nome.toLowerCase());
}
//case where user search only for course
if (curso) {
return aluno.curso.nome === curso;
}
return aluno;
});
// make the list of alunos to table
return alunosCurso.map(function(alunoAtual, i) {
return <Alunos aluno={alunoAtual} key={i} />;
});
}
function onChangeCurso(event) {
setCurso(event.target.value);
}
function onChangeNome(event) {
setNome(event.target.value);
}
return (
<div className="tb">
<div className="ui three column grid">
<GridColumn>
<h3 style={{ marginTop: 20 }}>Tabela de Alunos</h3>
</GridColumn>
<Form>
<GridColumn>
<FormField>
<input
style={{ marginLeft: 50, marginTop: 20 }}
type="text"
placeholder="Pesquisar por nome de aluno"
onChange={onChangeNome}
/>
</FormField>
</GridColumn>
</Form>
<Form>
<GridColumn>
<FormField>
<select
style={{ marginLeft: 120, marginBottom: 40, marginTop: 20 }}
name="curso"
onChange={onChangeCurso}
id=""
>
<option value="">Selecione um Curso</option>
<option value="">Todos os Cursos</option>
{cursoLista()}
</select>
</FormField>
</GridColumn>
</Form>
</div>
<table className="table table-bordered" style={{ paddingTop: 20 }}>
<thead className="thead-light">
<tr>
<th scope="col">Nome</th>
<th scope="col">Email</th>
<th scope="col">CPF</th>
<th scope="col">Endereço</th>
<th scope="col">CEP</th>
<th scope="col">Telefone</th>
<th scope="col">Curso</th>
<th scope="col">Editar</th>
<th scope="col">Deletar</th>
</tr>
</thead>
<tbody>{alunoList()}</tbody>
</table>
<form action={EXCEL_ALUNOS}>
<button className="ui green button" type="submit">
Download Tabela Excel
</button>
</form>
<br />
</div>
);
}
<file_sep>/server/src/config/passport/validation/resgister.js
const Validator = require("validator");
const isEmpty = require("is-empty");
module.exports = function validateRegisterInput(data) {
let errors = {};
// Convert empty fields to an empty string so we can use validator functions
data.nome = !isEmpty(data.nome) ? data.nome : "";
data.email = !isEmpty(data.email) ? data.email : "";
data.password = !isEmpty(data.password) ? data.password : "";
data.password2 = !isEmpty(data.password2) ? data.password2 : "";
// nome checks
if (Validator.isEmpty(data.nome)) {
errors.nome = "O nome é obrigatório";
}
// Email checks
if (Validator.isEmpty(data.email)) {
errors.email = "Email é um campo obrigatório";
} else if (!Validator.isEmail(data.email)) {
errors.email = "Email é inválido";
}
// Password checks
if (Validator.isEmpty(data.password)) {
errors.password = "Password é um campo obrigatório";
}
if (Validator.isEmpty(data.password2)) {
errors.password2 = "Confirmar senha é um campo obrigatório";
}
if (!Validator.isLength(data.password, { min: 6, max: 30 })) {
errors.password = "A senha deve ter no mínimo 6 caracters";
}
if (!Validator.equals(data.password, data.password2)) {
errors.password2 = "As senhas devem ser iguais";
}
return {
errors,
isValid: isEmpty(errors)
};
};<file_sep>/server/src/database/seeders/20191021215859-alunos.js
'use strict';
module.exports = {
up: (queryInterface, Sequelize) => {
/*
Add altering commands here.
Return a promise to correctly handle asynchronicity.
*/
return queryInterface.bulkInsert('alunos', [
{
nome: '<NAME>',
email: '<EMAIL>',
telefone:'9823445789',
endereco: 'São Luís, Rua dos Patos',
cep: '605987445',
cpf: '605138184',
curso_id: '1',
},
{
nome: '<NAME>',
email: '<EMAIL>',
telefone:'9825395789',
endereco: 'São Luís, Rua dos Gansos',
cep: '605985545',
cpf: '605138183',
curso_id: '1',
},
{
nome: 'Diego',
email: '<EMAIL>',
telefone:'9823445789',
endereco: 'São Luís, Rua dos Rãs',
cep: '605987445',
cpf: '604138182',
curso_id: '1',
},
{
nome: '<NAME>',
email: '<EMAIL>',
telefone:'9853446789',
endereco: 'São Luís, Rua dos Jacarés',
cep: '605987446',
cpf: '606138187',
curso_id: '2',
},
{
nome: '<NAME>',
email: '<EMAIL>',
telefone:'9853446789',
endereco: 'São Luís, Rua das Tartarugas',
cep: '605987446',
cpf: '606138187',
curso_id: '2',
},
{
nome: '<NAME>',
email: '<EMAIL>',
telefone:'9853446789',
endereco: 'São Luís, Rua dos Peixes',
cep: '601285446',
cpf: '607838187',
curso_id: '3',
},
{
nome: '<NAME>',
email: '<EMAIL>',
telefone:'9853446789',
endereco: 'São Luís, Rua das Baleias',
cep: '67895446',
cpf: '607838187',
curso_id: '3',
},
], {});
},
down: (queryInterface, Sequelize) => {
/*
Add reverting commands here.
Return a promise to correctly handle asynchronicity.
Example:
return queryInterface.bulkDelete('People', null, {});
*/
}
};
<file_sep>/client/react/src/pages/Login/form.js
import React from 'react';
import { withFormik } from 'formik';
import * as Yup from 'yup';
// import './index.css'
import { Form, Grid, FormField } from 'semantic-ui-react';
import api from '../../services/api';
import { login, isAuthenticated } from '../../services/auth';
var emailnotfound = false;
const App = ({
values,
handleChange,
onChange,
handleBlur,
errors,
touched,
isSubmitting,
handleSubmit,
}) => {
return (
<div className="column">
<h3>{'Login'}</h3>
<p style={{ marginBottom: 5 }}>
Para acessar o sistema é necessário estar logado.
</p>{' '}
<br />
<Grid columns={2}>
<Grid.Column>
{emailnotfound && <p className="error">Email ou senha incorretos!</p>}
<Form onSubmit={handleSubmit}>
<FormField>
<label>Email</label>
<input
type="email"
name="email"
onChange={handleChange}
onBlur={handleBlur}
value={values.email}
placeholder="Email do Usuário"
/>
{touched.email && errors.email && (
<p className="error">{errors.email}</p>
)}
</FormField>
<FormField>
<label>Senha</label>
<input
type="password"
name="senha"
onChange={handleChange}
value={values.senha}
onBlur={handleBlur}
placeholder="Insira a senha"
/>
{touched.senha && errors.senha && (
<p className="error">{errors.senha}</p>
)}
</FormField>
<button type="submit" className="ui primary basic button">
Login
</button>
</Form>
</Grid.Column>
</Grid>
<p style={{ marginTop: 10 }}>
Ainda não tem usuário? <a href="/register">Sign up</a>
</p>
</div>
);
};
const FormikApp = withFormik({
enableReinitialize: true,
mapPropsToValues({ email, senha, success }) {
return {
email: email || '',
senha: senha || '',
};
},
validationSchema: Yup.object().shape({
senha: Yup.string().required('Insira a senha'),
email: Yup.string()
.email('Insira um email válido')
.required('Insira o email'),
}),
handleSubmit(values, { props, resetForm }) {
try {
api
.post('/login', {
email: values.email,
password: values.<PASSWORD>,
})
.then(response => {
console.log(response);
if (response.data.emailnotfound) {
console.log('não encontrado');
emailnotfound = true;
resetForm();
}
if (response.data.success) {
const token = response.data.token.split(' ')[1];
//console.log(token)
login(token);
if (isAuthenticated()) {
return props.history.push('/');
}
} else {
}
});
} catch (error) {
/* console.log(error)
console.log("Senha ou Email incorretos") */
}
},
})(App);
export default FormikApp;
<file_sep>/client/react/Dockerfile
FROM node:10.16-alpine
RUN mkdir -p /srv/app/project-client
WORKDIR /srv/app/project-client
COPY package.json ./
COPY yarn.lock ./
RUN yarn install
COPY . .
EXPOSE 4000
CMD ["yarn", "start"]<file_sep>/server/__tests__/factory.js
const faker = require("faker");
const { factory } = require("factory-girl");
const { users, alunos } = require("../src/app/models");
factory.define("User", users, {
name: faker.name.findName(),
email: faker.internet.email(),
password: faker.<PASSWORD>.<PASSWORD>()
});
factory.define("Aluno", alunos, {
nome: faker.name.findName(),
email: faker.internet.email(),
cpf: "60518219300",
cep: faker.address.zipCode(),
endereco: faker.address.streetAddress(),
telefone: faker.phone.phoneNumber(),
curso_id: "1",
});
module.exports = factory;<file_sep>/server/src/Controllers/CursosController.js
const models = require('../app/models')
const Curso = require('../app/models').cursos
module.exports = {
async index(req, res) {
try {
const curso = await Curso.findByPk(req.params.id);
return res.send (curso);
} catch (error) {
return res.sendStatus(401).json(error);
}
},
async show(req, res) {
try {
const curso = await Curso.findAll();
return res.send(curso);
} catch (error) {
return res.sendStatus(401).json(error);
}
},
async update(req,res) {
try {
const curso = await Curso.update(req.body, { where: { id: req.params.id } });
return res.send (curso);
} catch (error) {
return res.sendStatus(401).json(error);
}
},
async store(req, res) {
try {
const curso = await Curso.create(req.body);
if (curso) {
return res.json (curso);
}
throw new Error("Curso não adicionado")
} catch (error) {
return res.sendStatus(401).send(error);
}
},
async destroy(req, res) {
try {
await Curso.destroy({
where: { id: req.params.id }
});
return res.send(curso);
} catch (error) {
return res.sendStatus(401).send(error.message);
}
},
async showAlunos(req,res){
try {
const curso = await Curso.findByPk(req.params.id,{include:'alunos'});
return res.send (curso);
} catch (error) {
return res.sendStatus(401).json(error);
}
}
};<file_sep>/client/react/src/pages/adicionarCursos/index.js
import React from 'react';
import FormMake from './form';
export default function AdicionarAluno() {
return <FormMake />;
}
<file_sep>/server/src/config/express.js
require("dotenv").config({
path: process.env.NODE_ENV === "test" ? ".env.test" : ".env"
});
var fs = require('fs')
const logger = require('morgan');
const express = require('express');
const bodyParser = require("body-parser");
const cookieParser = require('cookie-parser')
const passport = require("passport");
const cors = require('cors')
const app = express();
app.use(logger('common', {
stream: fs.createWriteStream('./access.log', {flags: 'a'})
}));
app.use(logger('dev'));
app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(cookieParser())
// Passport middleware
app.use(passport.initialize());
// Passport config
require("./passport/passport")(passport);
module.exports = app;<file_sep>/client/react/src/pages/editarCursos/index.js
import React, { useState, useEffect } from 'react';
import api from '../../services/api';
import { useParams } from 'react-router';
import FormMake from './form';
export default function EditarCursos() {
const [curso, setCurso] = useState([]);
const { id } = useParams();
useEffect(() => {
//Effect dont let be async
async function getCurso() {
const response = await api.get('/cursos/' + id);
setCurso(response.data);
}
getCurso();
}, [id]);
return (
<FormMake
nome={curso.nome}
cargaHoraria={`${curso.carga_horaria}`}
id={`${id}`}
/>
);
}
<file_sep>/server/src/app/models/cursos.js
'use strict';
module.exports = (sequelize, DataTypes) => {
const cursos = sequelize.define('cursos', {
nome: DataTypes.STRING,
carga_horaria: DataTypes.STRING
}, {});
cursos.associate = function(models) {
cursos.hasMany(models.alunos, {as: 'alunos'})
// associations can be defined here
};
return cursos;
};<file_sep>/server/Dockerfile
FROM node:10.16-alpine
RUN mkdir -p /srv/app
WORKDIR /srv/app
COPY package.json ./
COPY package-lock.json ./
RUN apk --no-cache add --virtual native-deps \
g++ gcc libgcc libstdc++ linux-headers make python && \
npm install --quiet node-gyp -g &&\
npm install --quiet && \
apk del native-deps
RUN npm install
COPY . .
EXPOSE 8000
CMD ["npm", "run", "dev"]<file_sep>/server/src/Controllers/AlunosController.js
const Aluno = require('../app/models').alunos
module.exports = {
async index(req, res) {
try {
const aluno = await Aluno.findByPk(req.params.id);
return res.send(aluno);
} catch (error) {
return res.sendStatus(401).json(error);
}
},
async show(req, res) {
try {
const aluno = await Aluno.findAll({ include: 'curso' });
return res.send(aluno);
} catch (error) {
return res.sendStatus(401).json(error);
}
},
async update(req, res) {
try {
const response = Aluno.findByPk(req.params.id);
if (response) {
const aluno = await Aluno.update(req.body, { where: { id: req.params.id } });
return res.send(aluno);
}
return res.sendStatus(401).json({ message: "Aluno não encontrado" })
} catch (error) {
return res.sendStatus(401).json(error);
}
},
async store(req, res) {
//console.log(req.body);
try {
const aluno = await Aluno.create(req.body);
if (aluno) {
return res.send(aluno);
}
throw new Error("Aluno não adicionado")
} catch (error) {
console.log(error)
return res.sendStatus(401);
}
},
// usar para paginação
async getAlunos(req, res) {
const PAGE = req.params.page;
const LIMIT_ROWS = 3;
const response = await Aluno.findAndCountAll({
offset: (PAGE - 1)*LIMIT_ROWS,
limit: LIMIT_ROWS,
});
console.log(req.params);
return res.send(response);
},
async destroy(req, res) {
try {
const deleted = await Aluno.destroy({
where: { id: req.params.id }
});
if (deleted) {
return res.send(200);
}
throw new Error('Aluno não encontrado')
} catch (error) {
console.log(error)
return res.sendStatus(401)
}
}
};<file_sep>/client/react/src/services/constants/index.js
export const PORT = 8000;
export const EXCEL_ALUNOS = 'http://localhost:8000/download/alunos';
export const EXCEL_CURSOS = 'http://localhost:8000/download/cursos';
<file_sep>/client/react/src/pages/home/index.js
import React, { Component } from 'react';
export default class Home extends Component {
render() {
return (
<div className="exec">
<h3>
Seja bem vindo ao sistema de Gereciamento de <strong>Alunos</strong> e{' '}
<strong>Cursos</strong>
</h3>
<p>
<i className="angle right icon" />
Em <strong>Curso</strong> você pode <strong>Adicionar</strong> e{' '}
<strong>Ver</strong> os Cursos cadastrados.
</p>
<p>
<i className="angle right icon" />
Em <strong>Alunos</strong> você pode <strong>Adicionar</strong> e{' '}
<strong>Ver</strong> os Alunos cadastrados no sistema e seus Cursos.
</p>
</div>
);
}
}
<file_sep>/client/react/src/pages/Register/form.js
import React from 'react';
import { withFormik } from 'formik';
import * as Yup from 'yup';
// import './index.css'
import { Form, Grid, FormField } from 'semantic-ui-react';
import api from '../../services/api';
const App = ({
values,
handleChange,
onChange,
handleBlur,
errors,
touched,
isSubmitting,
handleSubmit,
}) => {
return (
<div className="column">
<h3>{'Registrar Usuário'}</h3>
<Grid columns={2}>
<Grid.Column>
<Form onSubmit={handleSubmit}>
<FormField>
<label>Nome</label>
<input
type="text"
name="nome"
onChange={handleChange}
onBlur={handleBlur}
value={values.nome}
placeholder="Nome do Usuário"
/>
{touched.nome && errors.nome && (
<p className="error">{errors.nome}</p>
)}
</FormField>
<FormField>
<label>Email</label>
<input
type="email"
name="email"
onChange={handleChange}
onBlur={handleBlur}
value={values.email}
placeholder="Email do Usuário"
/>
{touched.email && errors.email && (
<p className="error">{errors.email}</p>
)}
</FormField>
<FormField>
<label>Senha</label>
<input
type="password"
name="senha"
onChange={handleChange}
value={values.senha}
onBlur={handleBlur}
placeholder="Insira a senha"
/>
{touched.senha && errors.senha && (
<p className="error">{errors.senha}</p>
)}
</FormField>
<FormField>
<label>Confirme a senha</label>
<input
type="password"
name="senha2"
onChange={handleChange}
value={values.senha2}
onBlur={handleBlur}
placeholder="Insira a senha"
/>
{touched.senha2 && errors.senha2 && (
<p className="error">{errors.senha2}</p>
)}
</FormField>
<button type="submit" className="ui primary basic button">
Login
</button>
</Form>
</Grid.Column>
</Grid>
</div>
);
};
const FormikApp = withFormik({
enableReinitialize: true,
mapPropsToValues({ nome, email, senha, senha2 }) {
return {
nome: nome || '',
email: email || '',
senha: senha || '',
senha2: senha2 || '',
};
},
validationSchema: Yup.object().shape({
nome: Yup.string().required('Insira o nome'),
senha: Yup.string().required('Insira a senha'),
senha2: Yup.string().required('Confirme a senha'),
email: Yup.string()
.email('Insira um email válido')
.required('Insira o email'),
}),
handleSubmit(values, { props }) {
try {
console.log({
email: values.email,
password: values.<PASSWORD>,
});
api
.post('/register', {
nome: values.nome,
email: values.email,
password: <PASSWORD>,
password2: <PASSWORD>,
})
.then(response => {
console.log(response);
if (response.status === 200) {
props.history.push('/');
}
});
} catch (error) {
console.log(error);
}
},
})(App);
export default FormikApp;
<file_sep>/client/react/src/routes.js
import React from 'react';
import { Switch, Route } from 'react-router-dom';
import Home from './pages/home/';
import AdicionarAlunos from './pages/adicionarAlunos/';
import AdicionarCursos from './pages/adicionarCursos/';
import Alunos from './pages/alunos/';
import Cursos from './pages/cursos/';
import EditarAluno from './pages/editarAlunos/';
import DeletarAluno from './pages/deletarAluno/';
import DeletarCurso from './pages/deletarCurso/';
import EscolherCurso from './pages/listarAlunos/';
import EditarCurso from './pages/editarCursos';
import ListarAlunos from './pages/listarAlunos/listar';
import Login from './pages/Login';
import Logout from './pages/Logout';
import Register from './pages/Register';
import PrivateRoute from './components/PrivateRoute';
export default function Router() {
return (
<>
<Switch>
<PrivateRoute path="/" exact component={Home}></PrivateRoute>
<PrivateRoute
path="/adicionarAlunos"
exact
component={AdicionarAlunos}
></PrivateRoute>
<PrivateRoute path="/alunos" exact component={Alunos}></PrivateRoute>
<PrivateRoute
path="/deletarAluno/:id"
exact
component={DeletarAluno}
></PrivateRoute>
<PrivateRoute
path="/editarAluno/:id"
exact
component={EditarAluno}
></PrivateRoute>
<PrivateRoute
path="/adicionarCursos"
exact
component={AdicionarCursos}
></PrivateRoute>
<PrivateRoute path="/cursos" exact component={Cursos}></PrivateRoute>
<PrivateRoute
path="/deletarCurso/:id"
exact
component={DeletarCurso}
></PrivateRoute>
<PrivateRoute
path="/editarCurso/:id"
exact
component={EditarCurso}
></PrivateRoute>
<PrivateRoute
path="/escolherCurso"
exact
component={EscolherCurso}
></PrivateRoute>
<PrivateRoute
path="/listarAlunos/:id"
exact
component={ListarAlunos}
></PrivateRoute>
<Route path="/login" exact component={Login}></Route>
<Route path="/logout" exact component={Logout}></Route>
<Route path="/register" exact component={Register}></Route>
</Switch>
</>
);
}
<file_sep>/client/react/src/pages/editarCursos/form.js
import React from 'react';
import { withFormik } from 'formik';
import * as Yup from 'yup';
import './index.css';
import { Form, Grid, FormField } from 'semantic-ui-react';
import api from '../../services/api';
var submited = false;
const App = ({
values,
handleChange,
onChange,
handleBlur,
errors,
touched,
isSubmitting,
handleSubmit,
}) => {
return (
<Grid columns={2}>
<Grid.Column>
<h3 style={{ marginLeft: '0.8em' }}>{'Alterar curso'}</h3>
<Form onSubmit={handleSubmit}>
<Form.Group widths="equal">
<FormField disabled={submited}>
<label>Nome *</label>
<input
type="text"
name="nome"
onChange={handleChange}
value={values.nome}
onBlur={handleBlur}
placeholder="<NAME>"
/>
{touched.nome && errors.nome && (
<p className="error">{errors.nome}</p>
)}
</FormField>
<FormField disabled={submited}>
<label>Carga Horária</label>
<input
type="text"
name="cargaHoraria"
onChange={handleChange}
onBlur={handleBlur}
value={values.cargaHoraria}
placeholder="Carga Horária do Curso"
/>
{touched.email && errors.email && (
<p className="error">{errors.email}</p>
)}
</FormField>
</Form.Group>
<button type="submit" className="ui primary button">
Alterar Curso
</button>
</Form>
{submited ? (
<div className="ui success message">
<div className="header">Curso Alterado com Sucesso</div>
<a href="/cursos"> Ver cursos </a> |
<a href="/adicionarCursos"> Adicionar Novo Curso </a>
</div>
) : (
''
)}
</Grid.Column>
</Grid>
);
};
const FormikApp = withFormik({
enableReinitialize: true,
validationSchema: Yup.object().shape({
nome: Yup.string().required('Insira o nome do Curso'),
cargaHoraria: Yup.number()
.typeError('Insira somente números')
.required('Insira a carga horária'),
}),
mapPropsToValues({ nome, cargaHoraria, id }) {
return {
nome: nome || '',
cargaHoraria: cargaHoraria || '',
id: id,
};
},
async handleSubmit(values, { props, resetForm, setErrors, setSubmitting }) {
try {
console.log({ nome: values.nome, cargaHoraria: values.cargaHoraria });
console.log(
await api.put('/cursos/' + values.id, {
nome: values.nome,
carga_horaria: values.cargaHoraria,
})
);
submited = true;
resetForm();
} catch (error) {
console.log(error);
throw error;
}
},
})(App);
export default FormikApp;
<file_sep>/client/react/src/pages/editarAlunos/index.js
import React, { useState, useEffect } from 'react';
import api from '../../services/api';
import { useParams } from 'react-router';
import FormMake from './form';
export default function EditarCursos() {
const [aluno, setAluno] = useState([]);
const [cursos, setCursos] = useState([]);
const { id } = useParams();
useEffect(() => {
async function getCursos() {
const response = await api.get('/cursos');
setCursos(response.data);
}
async function getAluno() {
const response = await api.get('/alunos/' + id);
setAluno(response.data);
}
getAluno();
getCursos();
}, [id]);
return (
<>
<FormMake
nome={aluno.nome}
email={aluno.email}
cpf={aluno.cpf}
endereco={aluno.endereco}
cep={aluno.cep}
telefone={aluno.telefone}
curso={aluno.curso_id}
listCursos={cursos}
id={id}
/>
</>
);
}
<file_sep>/client/react/src/pages/adicionarCursos/form.js
import React from 'react';
import { withFormik } from 'formik';
import * as Yup from 'yup';
import './index.css';
import { Form, Grid, FormField } from 'semantic-ui-react';
import api from '../../services/api';
var submited = false;
const App = ({
values,
handleChange,
onChange,
handleBlur,
errors,
touched,
isSubmitting,
handleSubmit,
}) => {
return (
<Grid columns={2}>
<Grid.Column>
<h3 style={{ marginLeft: '0.8em' }}>{'Adicionar novo curso'}</h3>
<Form onSubmit={handleSubmit}>
<Form.Group widths="equal">
<FormField disabled={submited}>
<label>Nome *</label>
<input
type="text"
name="nome"
onChange={handleChange}
value={values.nome}
onBlur={handleBlur}
placeholder="Nome do Curso"
disabled={submited}
/>
{touched.nome && errors.nome && (
<p className="error">{errors.nome}</p>
)}
</FormField>
<FormField disabled={submited}>
<label>Carga Horária</label>
<input
type="text"
name="cargaHoraria"
onChange={handleChange}
onBlur={handleBlur}
value={values.email}
placeholder="Carga Horária do Curso"
/>
{touched.cargaHoraria && errors.cargaHoraria && (
<p className="error">{errors.cargaHorariacd}</p>
)}
</FormField>
</Form.Group>
<button
disabled={submited}
type="submit"
className="ui primary button"
>
Adicionar Curso
</button>
</Form>
{submited ? (
<div className="ui success message">
<div className="header">Curso Adicionado com Sucesso</div>
<a href="/cursos"> Ver cursos </a> |
<a href="/adicionarCursos"> Adicionar Novo Curso </a>
</div>
) : (
''
)}
</Grid.Column>
</Grid>
);
};
const FormikApp = withFormik({
enableReinitialize: true,
validationSchema: Yup.object().shape({
nome: Yup.string().required('Insira o nome do Curso'),
cargaHoraria: Yup.number()
.typeError('Insira somente números')
.required('Insira a carga horária'),
}),
mapPropsToValues({ nome, cargaHoraria }) {
return {
nome: nome || '',
cargaHoraria: cargaHoraria || '',
/* [{ nome: 'Direito', idCurso: 1 }, { nome: "Medicina", idCurso: 2 } */
};
},
handleSubmit(values, { resetForm, setErrors, setSubmitting }) {
api.post('/cursos', {
nome: values.nome,
carga_horaria: values.cargaHoraria,
});
submited = true;
resetForm();
},
})(App);
export default FormikApp;
<file_sep>/client/react/src/components/MenuParent.js
import React, { Component } from 'react';
import Menu from './header';
import { withRouter } from 'react-router';
// --> Criado para obter location.pathname em header, passandos os props da MenuParent
// hooks não tem acesso a history, location...
class MenuParent extends Component {
render() {
return <Menu {...this.props} />;
}
}
export default withRouter(MenuParent);
|
3a426622cd03dc1f56b770a1d465eaf56583d84d
|
[
"JavaScript",
"SQL",
"Dockerfile",
"Markdown"
] | 31 |
JavaScript
|
felipestgoiabeira/projeto-ceuma
|
9868e0bcdfba71fd7c72044a83d4eb8c09dad454
|
5ac7b6d9262224efe80581e16db410f745c4bbe4
|
refs/heads/master
|
<repo_name>faizinahsan/JagaSehatAdmin<file_sep>/app/src/main/java/com/example/pbo/jagasehatadmin/DataPengguna.java
package com.example.pbo.jagasehatadmin;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.Map;
public class DataPengguna extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_data_pengguna);
final ArrayList<User> dataPengguna = new ArrayList<>();
DatabaseReference hello = FirebaseDatabase.getInstance().getReference().child("user");
hello.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot: dataSnapshot.getChildren()){
User user = snapshot.getValue(User.class);
dataPengguna.add(user);
}
UserAdapter adapter = new UserAdapter(DataPengguna.this,dataPengguna);
ListView listView = (ListView) findViewById(R.id.listPengguna);
listView.setAdapter(adapter);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
|
b23a34f57589a121238102735317e8937bc7cee3
|
[
"Java"
] | 1 |
Java
|
faizinahsan/JagaSehatAdmin
|
ec548a7b206597c4fc44e68185a343d8af0361d8
|
bf38828f58bd2a9bb6414277c7b5dd1ef6b44344
|
refs/heads/master
|
<file_sep>
var express = require("express"),
mysql = require('mysql'),
bodyParser = require('body-parser'),
PORT = process.env.PORT || 8081,
app = express();
app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static(__dirname + "/public"));
var connection = mysql.createConnection({
host : process.env.DBHOST,
user : process.env.DBUSER,
password : <PASSWORD>,
database : process.env.DBNAME
});
app.get("/", function(req, res){
// Find count of users in Db
var q = "SELECT COUNT(*) AS count FROM users";
connection.query(q, function(err, results){
if (err) throw err;
var count = results[0].count;
// res.send("We have " + count + " users in our db");
res.render("home", {count: count});
});
});
//post route
app.post("/register", function(req, res){
var person = {
email: req.body.email
};
connection.query('INSERT INTO users SET ?', person, function(err, result) {
if (err) throw err;
res.redirect("/success");
});
});
//success route
app.get("/success", function(req, res){
var q = "SELECT COUNT(*) AS count FROM users";
connection.query(q, function(err, results){
if (err) throw err;
var count = results[0].count;
// res.send("We have " + count + " users in our db");
res.render("success", {count: count});
});
});
app.listen(PORT, function() {
console.log('App listening on port ' + PORT);
});
|
184dae8df82592b2219b312b2d3385fdc790b7cf
|
[
"JavaScript"
] | 1 |
JavaScript
|
KaloyJS/JoinUs
|
849628bc5a916443d5f94c8043fb80d04c0d213f
|
b92f47bc56bcc5a75639db8d2e8ec5ba394da88f
|
refs/heads/main
|
<file_sep>document.getElementById('submit_btn').onclick = function System() {
var name = document.getElementById('name').value;
var surname = document.getElementById('surname').value;
var birthday = document.getElementById('birthday').value;
var email = document.getElementById('email').value;
//var
name_var = true
surname_var = true
birthday_var = true
email_var = true
//Überprüfung
if (name === '') {
alert("Name is empty!!!")
console.clear()
console.warn("Name is empty!!!")
name_var = false
}
else {
name_var = true
}
if (surname === '') {
alert("Surname is empty!!!")
console.clear()
console.warn("Surname is empty!!!")
surname_var = false
}
else {
surname_var = true
}
if (birthday === '') {
alert("Birtday is empty!!!")
console.clear()
console.warn("Birtday is empty!!!")
birthday_var = false
}
else {
birthday_var = true
}
if (email === '') {
alert("Email is empty!!!")
console.clear()
console.warn("Email is empty!!!")
email_var = false
}
else {
email_var = true
}
if(name_var === true && surname_var === true && birthday_var === true && email_var === true) {
console.clear()
console.log("Name: ", name)
console.log("Surname: ", surname)
console.log("Birthday: ", birthday)
console.log("Email: ", email)
document.getElementById('save_name').innerText = "Name: " + name
document.getElementById('save_surname').innerText = "Surname: " + surname
document.getElementById('save_birthday').innerText = "Birthday: " + birthday
document.getElementById('sava_email').innerText = "Email: " + email
}
}
//
document.getElementById('clear_btn').onclick = function () {
console.clear()
document.getElementById('save_name').innerText = "Name: "
document.getElementById('save_surname').innerText = "Surname: "
document.getElementById('save_birthday').innerText = "Birthday: "
document.getElementById('sava_email').innerText = "Email: "
}
//darkmode
document.getElementById('dark_mode_btn').onclick = function () {
document.getElementById('style').href = 'css/dark.css'
console.log("Dark mode is aktive.")
}
document.getElementById('white_mode_btn').onclick = function () {
document.getElementById('style').href = 'style.css'
console.log("White mode is aktive.")
}
|
82afbe59e1b22fa17ac558da096fbab79736afe8
|
[
"JavaScript"
] | 1 |
JavaScript
|
Nikita88888/My-data
|
ecb5a9d39b3be50b69812eeca3fa14c3d0e83709
|
1def1616368f2379beb1064a82e2e0220f26cd94
|
refs/heads/master
|
<repo_name>Kavan-Patel/IoTGameController<file_sep>/main.cpp
/* Includes */
#include "mbed.h"
#include "XNucleoIKS01A2.h"
/* Instantiate the expansion board */
static XNucleoIKS01A2 *mems_expansion_board = XNucleoIKS01A2::instance(D14, D15, D4, D5);
Serial serialCom(SERIAL_TX, SERIAL_RX);
/* Retrieve the composing elements of the expansion board *///
static LSM303AGRAccSensor *accelerometer = mems_expansion_board->accelerometer;
DigitalIn mybutton(USER_BUTTON);
/* Simple main function */
int main()
{
uint8_t id;
int32_t axes[3];
float x,y;
accelerometer->enable();
accelerometer->read_id(&id);
while(1) {
accelerometer->get_x_axes(axes);
x=axes[0];
y=axes[1];
// if(x>300&&y>350)
// {
// //up-right=5
// serialCom.printf("5");
// }
// else if(x>300&&y<-350)
// {
// //up-left=6
// serialCom.printf("6");
// }
// else if(x<-300&&y>350)
// {
// //down-right=7
// serialCom.printf("7");
// }
// else if(x<-300&&y<-350)
// {
// //down-left=8
// serialCom.printf("8");
// }
if(x>500)
{
//up=1
serialCom.printf("1");
wait(0.4);
}
else if(x<-500)
{
//down=2
serialCom.printf("2");
wait(0.4);
}
else if(y<-550)
{
//right=3
serialCom.printf("3");
wait(0.4);
}
else if(y>550)
{
//left=4
serialCom.printf("4");
wait(0.4);
}
else
{
//idle=0
serialCom.printf("0");
}
if (mybutton == 0) { // Button is pressed
serialCom.printf("9");
}
wait(0.05);
fflush(stdout);
}
}
<file_sep>/README.md
# IoTGameController
Make a GameController with using NUCLEOF401RE with MEMS Expansion board.
You just need to Import X_NUCLEO_IKS01A2 library to your project on mbed the link for import that library is : https://os.mbed.com/teams/ST/code/X_NUCLEO_IKS01A2/
Then downlaod main.cpp file from this repo and place it in your project.
Now finally download subway.py python file from this repo and run it on PC.
if you get any library error then use
1) pip install pyserial
2) pip install pyautogui
|
c17223ab5446a36165081b1aba85208516387249
|
[
"Markdown",
"C++"
] | 2 |
C++
|
Kavan-Patel/IoTGameController
|
209f24c7479e5469e8436948fbb8db80824804c9
|
2569da820e90dea0a2c514d6b0b00e23ebd9a330
|
refs/heads/master
|
<repo_name>phny/my_simple_stack<file_sep>/CMakeLists.txt
cmake_minimum_required(VERSION 3.5)
project(myloger)
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -fPIC -mavx")
set(src
./stack.hpp
./main.cpp
)
add_executable(my_stack ${src})
<file_sep>/main.cpp
/*************************************************************************
> File Name: main.cpp
> Author:
> Mail:
> Created Time: 2020年04月28日 星期二 23时49分23秒
************************************************************************/
#include <iostream>
#include "stack.hpp"
using namespace std;
int main() {
my_stack<int> stack;
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
while (!stack.empty()) {
int ret = stack.top();
std::cout << ret << std::endl;
stack.pop();
}
my_stack<std::string> stack_2;
stack_2.push("hello");
stack_2.push("work");
stack_2.push("test");
while (!stack_2.empty()) {
std::string ret = stack_2.top();
std::cout << ret << std::endl;
stack_2.pop();
}
return 0;
}
<file_sep>/stack.hpp
#include <iostream>
#include <stdexcept>
// my_stack的前置声明
template<typename T> class my_stack;
// 链表节点模板类
template<typename T>
class list_node {
T value;
list_node* next;
// 私有构造函数,只能由友元函数来构造
list_node(T const& v, list_node* n): value(v), next(n) {}
// 友元函数必须是类模板my_stack的实例
friend class my_stack<T>;
};
template<typename T=int>
class my_stack {
typedef list_node<T> node_type;
node_type* head;
// my_stack不可复制也不可构造
my_stack operator=(my_stack const& ) {}
my_stack(my_stack const& s) {}
public:
// 构造与析构
my_stack() : head(0) {}
~my_stack() {
while(!empty()) {
pop();
}
}
// 在类模板中实现成员函数
bool empty() const {
return head == 0;
}
T const& top() const throw (std::runtime_error) {
if (empty()) {
throw std::runtime_error("stack is empty");
}
return head->value;
}
void push(T const& v) {
head = new node_type(v, head);
}
void pop();
};
// 在模板类外面实现类的成员函数
template<typename T>
void my_stack<T>::pop() {
if (head) {
node_type* tmp = head;
head = head->next;
delete tmp;
}
}
<file_sep>/build/CMakeFiles/my_stack.dir/cmake_clean.cmake
file(REMOVE_RECURSE
"CMakeFiles/my_stack.dir/main.cpp.o"
"my_stack"
"my_stack.pdb"
)
# Per-language clean rules from dependency scanning.
foreach(lang CXX)
include(CMakeFiles/my_stack.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
|
61927dcee314f7447bcd7971bb2e00c7cd2ca6b0
|
[
"CMake",
"C++"
] | 4 |
CMake
|
phny/my_simple_stack
|
5d2abec67e115a8273c87e44522806269094c931
|
8bd6e59a6f7a299182c70d23c4d78c56eac7ad21
|
refs/heads/main
|
<file_sep>package io;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import gui.PanelTrendDetectionStreamflowBrazil;
import types.ResultadosEstacionaridadeAgrupados;
import types.SimulationDataExtremos;
/*import org.snirh.extremos_unb.deteccao.gui.PanelTestesEstatisticos;
import org.snirh.extremos_unb.deteccao.util.ResultadosEstacionaridadeAgrupados;
import org.snirh.extremos_unb.tipos.SimulationDataExtremos;
import org.snirh.util.ExtensionFileFilter;*/
public class ExportarResultadoTabelaResumoIndicesPorRegiaoVazao {
private JFileChooser chooser_xls;
private ExtensionFileFilter filter_xls;
private SimulationDataExtremos simulationData;
private PanelTrendDetectionStreamflowBrazil pnt;
public ExportarResultadoTabelaResumoIndicesPorRegiaoVazao(SimulationDataExtremos simulationData,PanelTrendDetectionStreamflowBrazil pnt){
this.simulationData=simulationData;
this.pnt=pnt;
this.createFileChooser();
}
public void executar(String dirTemplate,String nomearq,String dirOutput,String nomeShapeGrupo,
Map<String, Map<String, ResultadosEstacionaridadeAgrupados>> resultGrupoIndices){
//this.selecionarArquivoTemplateXls();
//String dirTemplate=simulationData.getDirTemplateXls();
// String nomearq=simulationData.getFilenameTemplateXls();
String nomearqOriginal=simulationData.getFilenameBD();
if(nomearq.contains(".xls") == false){
nomearq=nomearq+".xls";
}
try {
HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream(dirTemplate+nomearq));
FileOutputStream stream = new FileOutputStream(dirOutput+nomeShapeGrupo+".xls");
Set<String> chavesIndice = resultGrupoIndices.keySet();
HSSFSheet sh = wb.getSheet("RESUMO");
for (String nomeIndice : chavesIndice){
//HSSFSheet sh = wb.getSheet(nomeIndice);
//int nlinhasIniserie=76;
String [] nometeste=this.pegarSiglaTeste();
//int ilinha=0
for(int i=0;i<nometeste.length;i++){
String nmteste=nometeste[i];
int nlinhasIniserie=pegarLinhaArquivoExcelTemplateTp3(nmteste,nomeIndice);
ResultadosEstacionaridadeAgrupados resTesteIndice=resultGrupoIndices.get(nomeIndice).get(nmteste);
Row rowLinha = sh.getRow(nlinhasIniserie);
ArrayList<Double> resLinha=resTesteIndice.pegarResultadosLinhasTabela();
for(int j=0;j<resLinha.size();j++){
//Cell cell = rowLinha.createCell(j+1);
Cell cell = rowLinha.getCell(j+1);
cell.setCellValue((Double) resLinha.get(j));
}
}
}
wb.write(stream);
stream.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Messages.informMsg("Executado com sucesso");
System.out.println("Executado com sucesso");
}
private int pegarLinhaArquivoExcelTemplateTp3(String nmteste,String nomeIndice){
int linhaIndiceTeste=0;
Map<String, Integer>ordemIndice=new HashMap<String, Integer>();
ArrayList<String> nomesIndice=this.pegarIndice();
for(int i=0;i<nomesIndice.size();i++){
ordemIndice.put(nomesIndice.get(i), i);
}
Map<String, Integer>ordemTesteLinhaIni=new HashMap<String, Integer>();
ArrayList<String> nomesTeste=this.pegarTeste();
int linhaIniTeste=4;
int incremento=17;
int linhaInicialTeste=linhaIniTeste;
for(int i=0;i<nomesTeste.size();i++){
ordemTesteLinhaIni.put(nomesTeste.get(i), linhaInicialTeste);
linhaInicialTeste=linhaInicialTeste+incremento;
}
linhaIndiceTeste=ordemIndice.get(nomeIndice)+ordemTesteLinhaIni.get(nmteste);
return linhaIndiceTeste;
}
private void createFileChooser(){
this.chooser_xls = new JFileChooser(new File("."));
this.filter_xls = new ExtensionFileFilter("xls", "Arquivos EXCEL97 (*.xls)");
this.chooser_xls.setFileFilter(this.filter_xls);
}
public void selecionarArquivoTemplateXls(){
int returnVal = this.chooser_xls.showOpenDialog(this.pnt);
String dir="";
String filename ="";
if (returnVal == JFileChooser.APPROVE_OPTION) {
dir = this.chooser_xls.getCurrentDirectory().getAbsolutePath() + "\\";
filename = this.chooser_xls.getSelectedFile().getName();
}
this.simulationData.setDirTemplateXls(dir);
this.simulationData.setFilenameTemplateXls(filename);
}
public void selecionarDiretorioTemplateXlx(){
JFileChooser fc = new JFileChooser();
// restringe a amostra a diretorios apenas
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int res = fc.showOpenDialog(null);
if(res == JFileChooser.APPROVE_OPTION){
File diretorio = fc.getSelectedFile();
//JOptionPane.showMessageDialog(null, "Voce escolheu o diretório: " + diretorio.getName());
//txtDiretorioArquivoTodosTemplate.setText(diretorio.getAbsolutePath()+ "\\");
simulationData.setDirTodosTemplateXls(diretorio.getAbsolutePath()+ "\\");
}
else
JOptionPane.showMessageDialog(null, "Voce nao selecionou nenhum diretorio.");
}
public String [] pegarNomeTeste(){
int ntestes=14;
String [] nometesteExtenso=new String [ntestes];
nometesteExtenso[0]="Mann-Kendall";
nometesteExtenso[1]="Spearman’s Rho";
nometesteExtenso[2]="Linear Regression";
nometesteExtenso[3]="Teste T";
nometesteExtenso[4]="Distribution CUSUM";
nometesteExtenso[5]="Cumulative Deviation";
nometesteExtenso[6]="Worsley Lik. Ratio";
nometesteExtenso[7]="Rank-Sum (Mann-Whitney)";
nometesteExtenso[8]="Teste F";
nometesteExtenso[9]="Median Crossing";
nometesteExtenso[10]="Turning Points";
nometesteExtenso[11]="Rank Difference";
nometesteExtenso[12]="Autocorrelation";
nometesteExtenso[13]="Wald-Wolfowitz";
return nometesteExtenso;
}
public String [] pegarSiglaTeste(){
int ntestes=14;
String [] nometeste=new String [ntestes];
nometeste[0]="MK";
nometeste[1]="SR";
nometeste[2]="LR";
nometeste[3]="TT";
nometeste[4]="DC";
nometeste[5]="CD";
nometeste[6]="WR";
nometeste[7]="MW";
nometeste[8]="TF";
nometeste[9]="MC";
nometeste[10]="TP";
nometeste[11]="RD";
nometeste[12]="AC";
nometeste[13]="WW";
return nometeste;
}
public ArrayList<String> pegarTeste(){
int ntestes=14;
ArrayList<String> nomeTeste=new ArrayList<String>();
nomeTeste.add("MK");
nomeTeste.add("MW");
nomeTeste.add("SR");
nomeTeste.add("LR");
nomeTeste.add("TT");
nomeTeste.add("DC");
nomeTeste.add("CD");
nomeTeste.add("WR");
nomeTeste.add("TF");
nomeTeste.add("MC");
nomeTeste.add("TP");
nomeTeste.add("RD");
nomeTeste.add("AC");
nomeTeste.add("WW");
return nomeTeste;
}
public ArrayList<String> pegarIndice(){
int ntestes=14;
ArrayList<String> nomeIndice=new ArrayList<String>();
nomeIndice.add("QX1day");
nomeIndice.add("QMed");
nomeIndice.add("Qmin7day");
nomeIndice.add("Qmin30day");
nomeIndice.add("QX5day");
nomeIndice.add("QX30day");
nomeIndice.add("Qmin7dayUmidoSemestre");
nomeIndice.add("Qmin7dayUmidoTrimestre");
return nomeIndice;
}
}
<file_sep>package io.graph;
import java.awt.BorderLayout;
import java.awt.Color;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.SwingWorker;
import javax.swing.border.EtchedBorder;
import org.jfree.ui.RefineryUtilities;
/*import org.snirh.extremos_unb.deteccao.gui.FrameGraficosAnual;
import org.snirh.extremos_unb.deteccao.gui.GuiGraficoAnual;
import org.snirh.extremos_unb.deteccao.gui.PanelGraficoAnual;
import org.snirh.extremos_unb.deteccao.gui.PanelImportarDados;
import org.snirh.extremos_unb.deteccao.gui.GuiGraficoAnual.executarGraficoLinhaAnual;
import org.snirh.extremos_unb.tipos.DadoTemporal;
import org.snirh.extremos_unb.tipos.SimulationDataExtremos;*/
import gui.PanelTrendDetectionStreamflowBrazil;
import types.DadoTemporal;
import types.SimulationDataExtremos;
import util.PegarSerieEstatisticaPadrao;
public class GuiGraficoAnual extends JPanel {
private static final long serialVersionUID = 1L;
private JTabbedPane tabResults;
private PanelGraficoAnual panelResultGraficoDistrib;
private SimulationDataExtremos simulationData;
private PanelTrendDetectionStreamflowBrazil pid;
private FrameGraficosAnual frm;
public GuiGraficoAnual(SimulationDataExtremos simulationData){
this.simulationData = simulationData;
this.createAndShowGUI();
}
private void createAndShowGUI() {
this.setBackground(Color.LIGHT_GRAY);
this.setLayout(new BorderLayout());
this.formatPanels();
}
private void formatPanels(){
this.tabResults = new JTabbedPane();
this.tabResults.setBackground(this.getBackground());
this.tabResults.setBorder(new EtchedBorder());
this.tabResults.setBounds(0, 0, 550, 300);
int nseries=0;
for(int i=0;i<this.simulationData.getVariaveisHidr().size();i++){
if(this.simulationData.getVariaveisHidr().get(i).isSelecionada()) {
String codigo=String.valueOf(this.simulationData.getVariaveisHidr().get(i).getInvhidro().getEstacao_codigo());
int tipoSerie=this.simulationData.getTipoSerieFalhaEstacionaridade();
// PanelTrendDetectionStreamflowBrazil pid=new PanelTrendDetectionStreamflowBrazil();
PegarSerieEstatisticaPadrao pid=new PegarSerieEstatisticaPadrao();
Map<String,DadoTemporal> serieMapa=new HashMap<String,DadoTemporal>();
int anodiv=this.simulationData.getVariaveisHidr().get(i).getSerietemporal().pegarAnoMetadeSerie();
//boolean normalizar=false;
//int iflagAnodiv=0;
//serieMapa=pid.pegarSerieEstatistica(this.simulationData.getVariaveisHidr().get(i), this.simulationData, anodiv, iflagAnodiv, normalizar);
int anoIni=this.simulationData.getAnoIniSerie1Estacionaridade();
int anoFim=this.simulationData.getAnoIniSerie1Estacionaridade();
serieMapa=pid.pegarSerieEstatistica(this.simulationData.getVariaveisHidr().get(i), this.simulationData, anoIni,anoFim);
ArrayList<Double> serieNew=new ArrayList<Double>();
Set<String> chaves = serieMapa.keySet();
for (String data : chaves){
DadoTemporal dado = serieMapa.get(data);
serieNew.add(dado.getValor());
}
int tamanhoMinimoSerie=this.simulationData.getTamMinSerietotEstacionaridade();
//int anodiv=this.simulationData.getVariaveisHidr().get(i).getSerietemporal().pegarAnoMetadeSerie();
//int nseries=0;
if(serieNew.size() >= tamanhoMinimoSerie){
//this.panelResultGraficoDistrib = new PanelGraficoAnual(this.simulationData.getVariaveisHidr().get(i),codigo,serieMapa,anodiv);
this.panelResultGraficoDistrib = new PanelGraficoAnual(this.simulationData,this.simulationData.getVariaveisHidr().get(i),codigo,serieMapa,anodiv);
this.tabResults.addTab(codigo, this.panelResultGraficoDistrib.getComponent(0));
nseries++;
}
}
}
this.simulationData.setnSeriesSelecionadas(nseries);
this.add(this.tabResults, BorderLayout.CENTER);
}
public GuiGraficoAnual(SimulationDataExtremos simulationData,PanelTrendDetectionStreamflowBrazil pid, FrameGraficosAnual frm){
this.pid=pid;
this.frm=frm;
this.simulationData = simulationData;
this.createAndShowGUI(this.pid,this.frm);
}
private void createAndShowGUI(PanelTrendDetectionStreamflowBrazil pid, FrameGraficosAnual frm) {
this.setBackground(Color.LIGHT_GRAY);
this.setLayout(new BorderLayout());
this.formatPanels(pid,frm);
}
private void formatPanels(PanelTrendDetectionStreamflowBrazil pid, FrameGraficosAnual frm){
this.tabResults = new JTabbedPane();
this.tabResults.setBackground(this.getBackground());
this.tabResults.setBorder(new EtchedBorder());
this.tabResults.setBounds(0, 0, 550, 300);
executarGraficoLinhaAnual exegraf= new executarGraficoLinhaAnual(this.simulationData,pid,this,this.tabResults,this.panelResultGraficoDistrib, frm);
exegraf.addPropertyChangeListener(this.pid);
exegraf.execute();
}
class executarGraficoLinhaAnual extends SwingWorker<Void, String> {
private SimulationDataExtremos simulationData;
private PanelTrendDetectionStreamflowBrazil pid;
private GuiGraficoAnual guiresgraf;
private JTabbedPane tabResults;
private PanelGraficoAnual panelResultGrafico;
private FrameGraficosAnual frm;
private int iestfim;
public executarGraficoLinhaAnual(SimulationDataExtremos simulationData,PanelTrendDetectionStreamflowBrazil pid,GuiGraficoAnual guiresgraf,JTabbedPane tabResults,PanelGraficoAnual panelResultGrafico,FrameGraficosAnual frm){
this.simulationData=simulationData;
this.pid=pid;
this.guiresgraf=guiresgraf;
this.tabResults=tabResults;
this.panelResultGrafico=panelResultGrafico;
this.frm=frm;
}
protected Void doInBackground() throws Exception {
setProgress(0);
String textointerface= "Iniciando desenho dos gráficos ";
publish(textointerface);
int progress = 0;
setProgress(0);
int nestac=this.simulationData.getVariaveisHidr().size();
int iestfim=0;
for(int i=0;i<this.simulationData.getVariaveisHidr().size();i++){
if(this.simulationData.getVariaveisHidr().get(i).isSelecionada()) {
String codigo=String.valueOf(this.simulationData.getVariaveisHidr().get(i).getInvhidro().getEstacao_codigo());
int tipoSerie=this.simulationData.getTipoSerieFalhaEstacionaridade();
// PanelTrendDetectionStreamflowBrazil pid=new PanelTrendDetectionStreamflowBrazil();
PegarSerieEstatisticaPadrao pid=new PegarSerieEstatisticaPadrao();
Map<String,DadoTemporal> serieMapa=new HashMap<String,DadoTemporal>();
int anodiv=this.simulationData.getVariaveisHidr().get(i).getSerietemporal().pegarAnoMetadeSerie();
//boolean normalizar=false;
//int iflagAnodiv=0;
//serieMapa=pid.pegarSerieEstatistica(this.simulationData.getVariaveisHidr().get(i), this.simulationData, anodiv, iflagAnodiv, normalizar);
int anoIni=this.simulationData.getAnoIniSubConjunto();
int anoFim=this.simulationData.getAnoFimSubConjunto();
serieMapa=pid.pegarSerieEstatistica(this.simulationData.getVariaveisHidr().get(i), this.simulationData, anoIni,anoFim);
ArrayList<Double> serieNew=new ArrayList<Double>();
Set<String> chaves = serieMapa.keySet();
for (String data : chaves){
DadoTemporal dado = serieMapa.get(data);
serieNew.add(dado.getValor());
}
int tamanhoMinimoSerie=this.simulationData.getTamMinSerietotEstacionaridade();
//int anodiv=this.simulationData.getVariaveisHidr().get(i).getSerietemporal().pegarAnoMetadeSerie();
if(serieNew.size() >= tamanhoMinimoSerie){
//this.panelResultGraficoDistrib = new PanelGraficoAnual(this.simulationData,this.simulationData.getVariaveisHidr().get(i),codigo,serieMapa,anodiv);
this.panelResultGrafico = new PanelGraficoAnual(this.simulationData,this.simulationData.getVariaveisHidr().get(i),codigo,serieMapa,anodiv);
this.tabResults.addTab(codigo, this.panelResultGrafico.getComponent(0));
iestfim++;
}
}
double progress2 = ((i+1)*1.0/(this.simulationData.getVariaveisHidr().size()*1.0))*100;
progress=(int) progress2;
setProgress(Math.min(progress, 100));
textointerface= "Aguarde..desenhando o(s) gráfico(s) da estação "+(i+1)+"/"+nestac+"";
publish(textointerface);
System.out.println(textointerface);
}
this.guiresgraf.add(this.tabResults, BorderLayout.CENTER);
this.iestfim=iestfim;
return null;
}
protected void process(List<String> text) {
//this.pid.lblAguardeThread.setText(text.get(0));
}
protected void done() {
String textointerface="Gráficos da Séries Selecionadas - "+this.iestfim+" Séries Selecionadas";
this.frm.setTitle(this.iestfim+" Gauge Annual Time Series");
//this.pid.lblAguardeThread.setText(textointerface);
this.frm.setContentPane(this.guiresgraf);
this.frm.setVisible(true);
this.frm.pack();
RefineryUtilities.centerFrameOnScreen(this.frm);
//Messages.informMsg("Definição dos Gráficos com os Resultados do Ajuste das Distribuições de Probabilidade efetuado com sucesso");
}
}
}
<file_sep>package types;
public class ResultadoEstacMagnitudeTamanho {
/**
* Feito para o artigo 1 de analise de tendencia no Brasil - 27/12/2018
*/
private int CS_S_tam1_mag1;
private int CS_S_tam1_mag2;
private int CS_S_tam1_mag3;
private int CS_S_tam2_mag1;
private int CS_S_tam2_mag2;
private int CS_S_tam2_mag3;
private int CS_S_tam3_mag1;
private int CS_S_tam3_mag2;
private int CS_S_tam3_mag3;
private int DS_S_tam1_mag1;
private int DS_S_tam1_mag2;
private int DS_S_tam1_mag3;
private int DS_S_tam2_mag1;
private int DS_S_tam2_mag2;
private int DS_S_tam2_mag3;
private int DS_S_tam3_mag1;
private int DS_S_tam3_mag2;
private int DS_S_tam3_mag3;
public int getCS_S_tam1_mag1() {
return CS_S_tam1_mag1;
}
public void setCS_S_tam1_mag1(int cS_S_tam1_mag1) {
CS_S_tam1_mag1 = cS_S_tam1_mag1;
}
public int getCS_S_tam1_mag2() {
return CS_S_tam1_mag2;
}
public void setCS_S_tam1_mag2(int cS_S_tam1_mag2) {
CS_S_tam1_mag2 = cS_S_tam1_mag2;
}
public int getCS_S_tam1_mag3() {
return CS_S_tam1_mag3;
}
public void setCS_S_tam1_mag3(int cS_S_tam1_mag3) {
CS_S_tam1_mag3 = cS_S_tam1_mag3;
}
public int getCS_S_tam2_mag1() {
return CS_S_tam2_mag1;
}
public void setCS_S_tam2_mag1(int cS_S_tam2_mag1) {
CS_S_tam2_mag1 = cS_S_tam2_mag1;
}
public int getCS_S_tam2_mag2() {
return CS_S_tam2_mag2;
}
public void setCS_S_tam2_mag2(int cS_S_tam2_mag2) {
CS_S_tam2_mag2 = cS_S_tam2_mag2;
}
public int getCS_S_tam2_mag3() {
return CS_S_tam2_mag3;
}
public void setCS_S_tam2_mag3(int cS_S_tam2_mag3) {
CS_S_tam2_mag3 = cS_S_tam2_mag3;
}
public int getCS_S_tam3_mag1() {
return CS_S_tam3_mag1;
}
public void setCS_S_tam3_mag1(int cS_S_tam3_mag1) {
CS_S_tam3_mag1 = cS_S_tam3_mag1;
}
public int getCS_S_tam3_mag2() {
return CS_S_tam3_mag2;
}
public void setCS_S_tam3_mag2(int cS_S_tam3_mag2) {
CS_S_tam3_mag2 = cS_S_tam3_mag2;
}
public int getCS_S_tam3_mag3() {
return CS_S_tam3_mag3;
}
public void setCS_S_tam3_mag3(int cS_S_tam3_mag3) {
CS_S_tam3_mag3 = cS_S_tam3_mag3;
}
public int getDS_S_tam1_mag1() {
return DS_S_tam1_mag1;
}
public void setDS_S_tam1_mag1(int dS_S_tam1_mag1) {
DS_S_tam1_mag1 = dS_S_tam1_mag1;
}
public int getDS_S_tam1_mag2() {
return DS_S_tam1_mag2;
}
public void setDS_S_tam1_mag2(int dS_S_tam1_mag2) {
DS_S_tam1_mag2 = dS_S_tam1_mag2;
}
public int getDS_S_tam1_mag3() {
return DS_S_tam1_mag3;
}
public void setDS_S_tam1_mag3(int dS_S_tam1_mag3) {
DS_S_tam1_mag3 = dS_S_tam1_mag3;
}
public int getDS_S_tam2_mag1() {
return DS_S_tam2_mag1;
}
public void setDS_S_tam2_mag1(int dS_S_tam2_mag1) {
DS_S_tam2_mag1 = dS_S_tam2_mag1;
}
public int getDS_S_tam2_mag2() {
return DS_S_tam2_mag2;
}
public void setDS_S_tam2_mag2(int dS_S_tam2_mag2) {
DS_S_tam2_mag2 = dS_S_tam2_mag2;
}
public int getDS_S_tam2_mag3() {
return DS_S_tam2_mag3;
}
public void setDS_S_tam2_mag3(int dS_S_tam2_mag3) {
DS_S_tam2_mag3 = dS_S_tam2_mag3;
}
public int getDS_S_tam3_mag1() {
return DS_S_tam3_mag1;
}
public void setDS_S_tam3_mag1(int dS_S_tam3_mag1) {
DS_S_tam3_mag1 = dS_S_tam3_mag1;
}
public int getDS_S_tam3_mag2() {
return DS_S_tam3_mag2;
}
public void setDS_S_tam3_mag2(int dS_S_tam3_mag2) {
DS_S_tam3_mag2 = dS_S_tam3_mag2;
}
public int getDS_S_tam3_mag3() {
return DS_S_tam3_mag3;
}
public void setDS_S_tam3_mag3(int dS_S_tam3_mag3) {
DS_S_tam3_mag3 = dS_S_tam3_mag3;
}
}
<file_sep>package io;
import java.util.Map;
import java.util.Set;
import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics;
//import org.apache.commons.math.stat.descriptive.DescriptiveStatistics;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import types.InventarioHidrologico;
import types.ResultEstacionaridade;
//import org.snirh.extremos_unb.deteccao.testes.ResultEstacionaridade;
//import org.snirh.extremos_unb.tipos.InventarioHidrologico;
public class ExportarResultadoTabelaResumoBsenTamanho {
public static void preencherPlanilhaTemplate(HSSFWorkbook wb,String nmteste,String nomeIndice,
Map<String,InventarioHidrologico> inventario, Map<String,Map<String,ResultEstacionaridade>> resultEstacTesteEstacao,
boolean utilizouFDR){
String nomePlan="VALORES_TAMANHO_MAGNITUDE";
HSSFSheet sh = wb.getSheet(nomePlan);
Set<String> chaves = resultEstacTesteEstacao.get(nmteste).keySet();
int nlinhasIniserie=3;
int i1=0;
DescriptiveStatistics dscBsen = new DescriptiveStatistics();
DescriptiveStatistics dscBsenRel = new DescriptiveStatistics();
DescriptiveStatistics dscAlt = new DescriptiveStatistics();
//double ns=5.0;
int itam1=0;
double valTam1=45;
int coliniTam1=26;
int itam2=0;
double valTam2=60;
int coliniTam2=coliniTam1+5;
int itam3=0;
int coliniTam3=coliniTam2+5;
int itamFDR=0;
int coliniFDR=coliniTam3+5;
for (String codigo : chaves){
if(i1 == 0){
Row row = sh.getRow(0);
Cell cellNome = row.createCell(1);
cellNome.setCellValue(String.valueOf(nomeIndice));
//ns=resultEstacTesteEstacao.get(nmteste).get(codigo).g
}
Row rowLinhaEst = sh.createRow(nlinhasIniserie+i1);
Cell cell = rowLinhaEst.createCell(0);
cell.setCellValue(String.valueOf(codigo));
cell = rowLinhaEst.createCell(1);
cell.setCellValue((Double) inventario.get(codigo).getLatitude());
cell = rowLinhaEst.createCell(2);
cell.setCellValue((Double) inventario.get(codigo).getLongitude());
cell = rowLinhaEst.createCell(3);
// if (estacAlt.containsKey(codigo)){
//double altitude=estacAlt.get(codigo);
//if(!(altitude < 0)){
// cell.setCellValue((Double) estacAlt.get(codigo));
// dscAlt.addValue((Double) estacAlt.get(codigo));
//}
//}else{
cell.setCellValue(0.0);
dscAlt.addValue(0.0);
// }
cell = rowLinhaEst.createCell(4);
cell.setCellValue((Double) inventario.get(codigo).getAreaDrenagem());
cell = rowLinhaEst.createCell(5);
cell.setCellValue((Double) resultEstacTesteEstacao.get(nmteste).get(codigo).getEstatteste());
cell = rowLinhaEst.createCell(6);
cell.setCellValue((Double) resultEstacTesteEstacao.get(nmteste).get(codigo).getPvalue());
cell = rowLinhaEst.createCell(7);
cell.setCellValue((Double) resultEstacTesteEstacao.get(nmteste).get(codigo).getBsen());
cell = rowLinhaEst.createCell(8);
dscBsen.addValue(resultEstacTesteEstacao.get(nmteste).get(codigo).getBsen());
cell.setCellValue((Double) resultEstacTesteEstacao.get(nmteste).get(codigo).getBsenRel());
cell = rowLinhaEst.createCell(9);
dscBsenRel.addValue(resultEstacTesteEstacao.get(nmteste).get(codigo).getBsenRel());
cell.setCellValue((Double) resultEstacTesteEstacao.get(nmteste).get(codigo).getNanos());
cell = rowLinhaEst.createCell(10);
cell.setCellValue((Double) resultEstacTesteEstacao.get(nmteste).get(codigo).getNanosPeriodo());
cell = rowLinhaEst.createCell(11);
cell.setCellValue(String.valueOf(resultEstacTesteEstacao.get(nmteste).get(codigo).getSentidoTendencia()));
double nanos=(Double) resultEstacTesteEstacao.get(nmteste).get(codigo).getNanos();
double bsenrel=(Double) resultEstacTesteEstacao.get(nmteste).get(codigo).getBsenRel();
double pvalue=resultEstacTesteEstacao.get(nmteste).get(codigo).getPvalue();
boolean eFalsoPositivoFDP=false;
//boolean utilizouFDR=this.simulationData.isFazerFDR();
if(utilizouFDR){
eFalsoPositivoFDP=resultEstacTesteEstacao.get(nmteste).get(codigo).getResultadoFDR().isFalsoPositivo();
}
if(nanos <= valTam1 && !eFalsoPositivoFDP){
Row rowtam1 = sh.getRow(nlinhasIniserie+itam1);
Cell celltam1 = rowtam1.createCell(coliniTam1+0);
celltam1.setCellValue(String.valueOf(codigo));
celltam1 = rowtam1.createCell(coliniTam1+1);
celltam1.setCellValue((Double)pvalue);
celltam1 = rowtam1.createCell(coliniTam1+2);
celltam1.setCellValue((Double)bsenrel);
celltam1 = rowtam1.createCell(coliniTam1+3);
celltam1.setCellValue((Double)nanos);
itam1++;
}else if(nanos > valTam1 && nanos <= valTam2 && !eFalsoPositivoFDP){
Row rowtam1 = sh.getRow(nlinhasIniserie+itam2);
Cell celltam1 = rowtam1.createCell(coliniTam2+0);
celltam1.setCellValue(String.valueOf(codigo));
celltam1 = rowtam1.createCell(coliniTam2+1);
celltam1.setCellValue((Double)pvalue);
celltam1 = rowtam1.createCell(coliniTam2+2);
celltam1.setCellValue((Double)bsenrel);
celltam1 = rowtam1.createCell(coliniTam2+3);
celltam1.setCellValue((Double)nanos);
itam2++;
}else if(nanos > valTam2 && !eFalsoPositivoFDP){
Row rowtam1 = sh.getRow(nlinhasIniserie+itam3);
Cell celltam1 = rowtam1.createCell(coliniTam3+0);
celltam1.setCellValue(String.valueOf(codigo));
celltam1 = rowtam1.createCell(coliniTam3+1);
celltam1.setCellValue((Double)pvalue);
celltam1 = rowtam1.createCell(coliniTam3+2);
celltam1.setCellValue((Double)bsenrel);
celltam1 = rowtam1.createCell(coliniTam3+3);
celltam1.setCellValue((Double)nanos);
itam3++;
}else if(eFalsoPositivoFDP){
Row rowtam1 = sh.getRow(nlinhasIniserie+itamFDR);
Cell celltam1 = rowtam1.createCell(coliniFDR+0);
celltam1.setCellValue(String.valueOf(codigo));
celltam1 = rowtam1.createCell(coliniFDR+1);
celltam1.setCellValue((Double)pvalue);
celltam1 = rowtam1.createCell(coliniFDR+2);
celltam1.setCellValue((Double)bsenrel);
celltam1 = rowtam1.createCell(coliniFDR+3);
celltam1.setCellValue((Double)nanos);
itamFDR++;
}
i1++;
}
double ns=5.0;
int nlinha=nlinhasIniserie;
for(int k=0;k<2;k++){
Row row = sh.getRow(nlinha);
Cell cellNome = row.createCell(15);
cellNome.setCellValue((Double) ns*-1.0);
cellNome = row.createCell(16);
cellNome.setCellValue((Double) dscBsen.getMin());
cellNome = row.createCell(17);
cellNome.setCellValue((Double) dscBsenRel.getMin());
cellNome = row.createCell(18);
cellNome.setCellValue((Double) dscAlt.getMin());
row = sh.getRow(nlinha+1);
cellNome = row.createCell(15);
cellNome.setCellValue((Double) ns*-1.0);
cellNome = row.createCell(16);
cellNome.setCellValue((Double) dscBsen.getMax());
cellNome = row.createCell(17);
cellNome.setCellValue((Double) dscBsenRel.getMax());
cellNome = row.createCell(18);
cellNome.setCellValue((Double) dscAlt.getMax());
row = sh.getRow(nlinha);
cellNome = row.createCell(20);
cellNome.setCellValue((Double) ns*1.0);
cellNome = row.createCell(21);
cellNome.setCellValue((Double) dscBsen.getMin());
cellNome = row.createCell(22);
cellNome.setCellValue((Double) dscBsenRel.getMin());
cellNome = row.createCell(23);
cellNome.setCellValue((Double) dscAlt.getMin());
row = sh.getRow(nlinha+1);
cellNome = row.createCell(20);
cellNome.setCellValue((Double) ns*1.0);
cellNome = row.createCell(21);
cellNome.setCellValue((Double) dscBsen.getMax());
cellNome = row.createCell(22);
cellNome.setCellValue((Double) dscBsenRel.getMax());
cellNome = row.createCell(23);
cellNome.setCellValue((Double) dscAlt.getMax());
ns=ns+5.0;
nlinha=nlinha+2;
}
}
}
<file_sep>package util;
import java.util.HashMap;
import java.util.Map;
import types.DadoTemporal;
public class ST_pegarDadosCriterioFalha {
public static Map<String,DadoTemporal> mapa(Map<String,DadoTemporal> dados,int tipoSerie,double toleranciaMaxFalha, double percentualDeFalhas){
Map<String,DadoTemporal> dadosComFalha=new HashMap<String,DadoTemporal>();
Map<String,DadoTemporal> dadosSemFalha=new HashMap<String,DadoTemporal>();
Map<String,DadoTemporal> dadosComFalhaPercMaxTolerado=new HashMap<String,DadoTemporal>();
if(percentualDeFalhas == 0){
dadosSemFalha.putAll(dados);
dadosComFalha.putAll(dados);
dadosComFalhaPercMaxTolerado.putAll(dados);
}else if(percentualDeFalhas < toleranciaMaxFalha){
dadosComFalhaPercMaxTolerado.putAll(dados);
dadosComFalha.putAll(dados);
}else{
dadosComFalha.putAll(dados);
}
if(tipoSerie == 0){
return dadosComFalha;
}else if(tipoSerie == 1){
return dadosSemFalha;
}else if(tipoSerie == 2){
return dadosComFalhaPercMaxTolerado;
}
return dadosComFalha;
}
}
<file_sep>package util;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Map;
import types.DadoTemporal;
import types.SerieTemporal;
public class ST_pegarDataInicioFiltroMes {
public static Date data(SerieTemporal st,int mesIni,int mesFim,int anoIni, int anoFIm){
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Date diniSerie =st.getDataInicialSerie().getTime();
Date dfimSerie =st.getDataFinalSerie().getTime();
Date utilDateIni = null;
String datastrini =formatter.format(diniSerie);
String[] strini = datastrini.split("/");
String datastrInicial = null;
if(mesIni == mesFim){
mesFim=mesIni;
datastrInicial="01/"+mesIni+"/"+anoIni;
}else{
if(mesIni > mesFim) {
int anoInicial=anoIni;
anoInicial=anoInicial-1;
datastrInicial="01/"+mesIni+"/"+anoInicial;
}else{
datastrInicial="01/"+mesIni+"/"+anoIni;
}
}
try {
utilDateIni = formatter.parse(datastrInicial);
} catch (ParseException e) {
e.printStackTrace();
}
return utilDateIni;
}
public static Date data(SerieTemporal st,int mesIni,int mesFim){
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Date diniSerie =st.getDataInicialSerie().getTime();
Date dfimSerie =st.getDataFinalSerie().getTime();
Date utilDateIni = null;
String datastrini =formatter.format(diniSerie);
String[] strini = datastrini.split("/");
String datastrInicial = null;
if(mesIni == mesFim){
mesFim=mesIni;
datastrInicial="01/"+mesIni+"/"+strini[2];
}else{
if(mesIni > mesFim) {
int anoInicial=Integer.parseInt(strini[2]);
anoInicial=anoInicial-1;
datastrInicial="01/"+mesIni+"/"+anoInicial;
}else{
datastrInicial="01/"+mesIni+"/"+strini[2];
}
}
try {
utilDateIni = formatter.parse(datastrInicial);
} catch (ParseException e) {
e.printStackTrace();
}
return utilDateIni;
}
public static Date data(Map<String,DadoTemporal> mapaStrDadosGer,int mesIni,int mesFim,int anoIni, int anoFIm){
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
ArrayList<String> datasstr= ST_seriesOutrosFormatos.pegarArrayListDataOrdenada(mapaStrDadosGer);
Date diniSerie =null;
Date dfimSerie=null;
try {
diniSerie =formatter.parse(datasstr.get(0));
dfimSerie = formatter.parse(datasstr.get(datasstr.size()-1));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Date diniSerie =st.getDataInicialSerie().getTime();
//Date dfimSerie =st.getDataFinalSerie().getTime();
Date utilDateIni = null;
String datastrini =formatter.format(diniSerie);
String[] strini = datastrini.split("/");
String datastrInicial = null;
if(mesIni == mesFim){
mesFim=mesIni;
datastrInicial="01/"+mesIni+"/"+anoIni;
}else{
if(mesIni > mesFim) {
int anoInicial=anoIni;
anoInicial=anoInicial-1;
datastrInicial="01/"+mesIni+"/"+anoInicial;
}else{
datastrInicial="01/"+mesIni+"/"+anoIni;
}
}
try {
utilDateIni = formatter.parse(datastrInicial);
} catch (ParseException e) {
e.printStackTrace();
}
return utilDateIni;
}
}
<file_sep>package io;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextArea;
import javax.swing.ProgressMonitor;
import javax.swing.SwingWorker;
import javax.swing.border.EtchedBorder;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import gui.PanelTrendDetectionStreamflowBrazil;
import types.ResultEstacionaridade;
import types.SimulationDataExtremos;
import types.VariavelHidrologica;
import util.Messages;
/*import org.snirh.extremos_unb.deteccao.gui.PanelTestesEstatisticos;
import org.snirh.extremos_unb.deteccao.gui.PanelEscolherArquivoExcelExportarResultado.executarSalvarExcel;
import org.snirh.extremos_unb.deteccao.io.ExportarResultadoTabelaResumoBsen;
import org.snirh.extremos_unb.deteccao.testes.ResultEstacionaridade;
import org.snirh.extremos_unb.tipos.SimulationDataExtremos;
import org.snirh.extremos_unb.tipos.VariavelHidrologica;
import org.snirh.extremos_unb.util.ExtensionFileFilter;
import org.snirh.extremos_unb.util.Messages;*/
public class PanelEscolherArquivoExcelExportarResultado extends JFrame{
private static final long serialVersionUID = 1L;
private JFileChooser chooser;
private JPanel panelData;
private JPanel panelButtons;
private JButton btnExecute;
private JButton btnCancel;
private ButtonGroup cboxButtonGroup;
private JRadioButton button1;
private JRadioButton button2;
private JRadioButton button3;
private JRadioButton button4;
private JRadioButton button5;
private JRadioButton button6;
private SimulationDataExtremos simulationData;
private PanelTrendDetectionStreamflowBrazil pnt;
private ExtensionFileFilter filter;
private JFileChooser chooser_xlsx;
private ExtensionFileFilter filter_xlsx;
public PanelEscolherArquivoExcelExportarResultado(SimulationDataExtremos simulationData,PanelTrendDetectionStreamflowBrazil pnt){
super("Indique o tipo de Arquivo a ser exportado");
this.simulationData = simulationData;
this.pnt=pnt;
this.createAndShowGUI();
this.createPane();
this.pack();
}
private void createPane() {
this.chooser = new JFileChooser(new File("."));
this.filter = new ExtensionFileFilter("dat", "Arquivos de dados hidrológicos (*.dat)");
this.chooser.setFileFilter(this.filter);
this.chooser_xlsx = new JFileChooser(new File("."));
this.filter_xlsx = new ExtensionFileFilter("xlsx", "Arquivos de dados hidrológicos (*.xlsx)");
this.chooser_xlsx.setFileFilter(this.filter_xlsx);
}
private void createAndShowGUI() {
this.setBounds(20, 20, 440, 320);
this.setPreferredSize(new Dimension(440, 320));
this.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
this.setResizable(false);
this.setAlwaysOnTop(true);
this.setLayout(null);
this.formatPanelData();
this.formatPanelButtons();
}
private void formatPanelData(){
this.panelData = new JPanel();
this.panelData.setBorder(new EtchedBorder());
this.panelData.setBounds(10, 10, 290, 280);
this.panelData.setLayout(null);
this.add(this.panelData);
this.formatButtonGroup();
//this.formatLabels();
}
private void formatButtonGroup() {
JPanel panel = new JPanel();
panel.setBounds(10, 10, 265, 260);
JLabel label = new JLabel("Choose one of the options:");
panel.add(label);
panel.setLayout(new GridLayout(0, 1));
this.cboxButtonGroup = new ButtonGroup();
//button1 = new JRadioButton("DAT - Máximos");
String nomeEstat=this.simulationData.getTipoEstatisticaSelecionadaEstacionaridade();
button1 = new JRadioButton("Trend Result");
button1.setSelected(true);
//button2 = new JRadioButton("Excel - Máximos");
button2 = new JRadioButton("bsen and pvalue Table");
//button3 = new JRadioButton("DAT - Original");
//button4 = new JRadioButton("Excel - Original");
//button5 = new JRadioButton("DAT - Original - Filtro");
//button6 = new JRadioButton("DAT - Original- Total - Filtro");
this.cboxButtonGroup.add(button1);
this.cboxButtonGroup.add(button2);
//this.cboxButtonGroup.add(button3);
//this.cboxButtonGroup.add(button4);
//this.cboxButtonGroup.add(button5);
//this.cboxButtonGroup.add(button6);
panel.add(button1);
panel.add(button2);
//panel.add(button3);
//panel.add(button4);
//panel.add(button5);
//panel.add(button6);
this.panelData.add(panel);
}
private void formatPanelButtons() {
this.panelButtons = new JPanel();
this.panelButtons.setBorder(new EtchedBorder());
this.panelButtons.setBounds(310, 10, 110, 280);
this.panelButtons.setLayout(null);
this.add(this.panelButtons);
this.btnExecute = new JButton("Export");
String nomeEstat=this.simulationData.getTipoEstatisticaSelecionadaEstacionaridade();
this.btnExecute.setToolTipText("Open a selected file that will be used to obtain series of "+ nomeEstat);
this.btnExecute.setBounds(10, 10, 90, 25);
this.btnExecute.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
buttonAction(btnExecute);
}
});
this.panelButtons.add(this.btnExecute, JLayeredPane.DEFAULT_LAYER);
/*this.btnCancel = new JButton("Adicionar");
this.btnCancel.setToolTipText("Adicionar ao estudo as séries do arquivo selecionado");
this.btnCancel.setBounds(10, 40, 90, 25);
this.btnCancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
buttonAction(btnCancel);
}
});
this.panelButtons.add(this.btnCancel, JLayeredPane.DEFAULT_LAYER);*/
}
private void buttonAction(JButton jb){
if (jb.equals(this.btnExecute)){
this.exportarDados();
}else if (jb.equals(this.btnCancel)){
//this.AdicionarDados();
//this.setVisible(false);
}
this.setVisible(false);
}
public void exportarDados() {
String dir = null;
String filename = null;
if(this.button1.isSelected()){
executeSaveXLSX_MK boot= new executeSaveXLSX_MK(this.simulationData,this.pnt);
boot.addPropertyChangeListener(this.pnt);
boot.execute();
}else if(this.button2.isSelected()){
ExportarResultadoTabelaResumoBsen exportar=new ExportarResultadoTabelaResumoBsen(this.simulationData,this.pnt);
exportar.executar();
}
}
private void SolicitarArquivosAoUsuário(JFileChooser chooser) {
String filename=null;
String dir =null;
int returnVal = chooser.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
dir = chooser.getCurrentDirectory().getAbsolutePath() + "\\";
filename = chooser.getSelectedFile().getName();
}
this.simulationData.setDataDirBD(dir);
this.simulationData.setFilenameBD(filename);
}
class executeSaveXLSX_MK extends SwingWorker<Void, String> {
private SimulationDataExtremos simulationData;
private PanelTrendDetectionStreamflowBrazil pnt;
private ProgressMonitor progressMonitor;
private JTextArea taskOutput;
private JFileChooser chooser;
private ExtensionFileFilter filter;
public executeSaveXLSX_MK (SimulationDataExtremos simulationData,PanelTrendDetectionStreamflowBrazil pnt){
this.simulationData=simulationData;
this.pnt=pnt;
}
@Override
protected Void doInBackground() throws Exception {
String dir = null;
String filename = null;
//if(dir == null){
Messages.informMsg("Indique o nome do arquivo de resultados .xlsx");
int returnVal = this.pnt.getChooser().showOpenDialog(this.pnt);
if (returnVal == JFileChooser.APPROVE_OPTION) {
dir = this.pnt.getChooser().getCurrentDirectory().getAbsolutePath() + "\\";
filename = this.pnt.getChooser().getSelectedFile().getName();
}
//this.simulationData.setFilenameBD(filename);
this.simulationData.setDataDirBD(dir);
String[] columnNames = new String[11];
columnNames[0] = "Gauge Code";
columnNames[1] = "Trend Test";
columnNames[2] = "Test Statistics";
columnNames[3] = "Pvalue (%)";
columnNames[4] = "Critical Value Method";
columnNames[5] = "Critical Value";
columnNames[6] = "Result";
columnNames[7] = "Description Result";
columnNames[8] = "Trend";
columnNames[9] = "Year Shift";
columnNames[10] = "Mean";
int ntestes=1;
String [] nometesteExtenso=new String [ntestes];
nometesteExtenso[0]="Mann-Kendall";
/*nometesteExtenso[1]="Spearman’s Rho";
nometesteExtenso[2]="Linear Regression";
nometesteExtenso[3]="Teste T";
nometesteExtenso[4]="Distribution CUSUM";
nometesteExtenso[5]="Cumulative Deviation";
nometesteExtenso[6]="Worsley Lik. Ratio";
nometesteExtenso[7]="Rank-Sum (Mann-Whitney)";
nometesteExtenso[8]="Teste F";
nometesteExtenso[9]="Median Crossing";
nometesteExtenso[10]="Turning Points";
nometesteExtenso[11]="Rank Difference";
nometesteExtenso[12]="Autocorrelation";
nometesteExtenso[13]="Wald-Wolfowitz";*/
String [] nometeste=new String [ntestes];
nometeste[0]="MK";
/*nometeste[1]="SR";
nometeste[2]="LR";
nometeste[3]="TT";
nometeste[4]="DC";
nometeste[5]="CD";
nometeste[6]="WR";
nometeste[7]="MW";
nometeste[8]="TF";
nometeste[9]="MC";
nometeste[10]="TP";
nometeste[11]="RD";
nometeste[12]="AC";
nometeste[13]="WW";*/
String nomearq=dir+filename+".xlsx";
Workbook wb = new SXSSFWorkbook(100);
setProgress(0);
String textointerface= "Iniciando o Calculo do Resumo dos Resultados das Estações ";
publish(textointerface);
int progress = 0;
setProgress(0);
int iestfim=0;
Sheet sh = wb.createSheet("MK Trend Result");
Row rowHEAD = sh.createRow(0);
for(int i1=0;i1<columnNames.length;i1++) {
Cell cell = rowHEAD.createCell(i1);
cell.setCellValue(columnNames[i1]);
}
int igauge=1;
for(int i=0;i<this.simulationData.getVariaveisHidr().size();i++){
if(this.simulationData.getVariaveisHidr().get(i).isSelecionada() && this.simulationData.getVariaveisHidr().get(i).isAtendeRestricaoTamMin()) {
String codigo=String.valueOf(this.simulationData.getVariaveisHidr().get(i).getInvhidro().getEstacao_codigo());
ArrayList<ResultEstacionaridade> resultestacionaridade =new ArrayList<ResultEstacionaridade>();
resultestacionaridade = this.simulationData.getVariaveisHidr().get(i).getResultestacionaridade();
VariavelHidrologica vhid =this.simulationData.getVariaveisHidr().get(i);
int nlinhastr=ntestes+1;
int ncolstr=columnNames.length;
Object[][] result =this.pnt.setDadosResEstac_MK(resultestacionaridade);
result[0][0]=codigo;
//for(int rownum = 0; rownum <nlinhastr; rownum++){
Row row = sh.createRow(igauge);
for(int cellnum = 0; cellnum < ncolstr; cellnum++){
Cell cell = row.createCell(cellnum);
String address = new CellReference(cell).formatAsString();
if(igauge !=0){
if(cellnum == 2 || cellnum == 3 || cellnum == 5 || cellnum == 9){
String teste=String.valueOf(result[0][cellnum]);
if(teste != ""){
double val=Double.parseDouble(teste);
cell.setCellValue(val);
}else{
}
}else{
cell.setCellValue(String.valueOf(result[0][cellnum]));
}
}else{
cell.setCellValue(columnNames[cellnum]);
}
}
// }
igauge++;
iestfim++;
}
double progress2 = ((i+1)*1.0/(this.simulationData.getVariaveisHidr().size()*1.0))*100;
int ngauges= this.simulationData.getVariaveisHidr().size();
progress=(int) progress2;
setProgress(Math.min(progress, 100));
textointerface= "Aguarde..executando o calculo da estação "+(i+1)+"/"+ngauges+"";
publish(textointerface);
System.out.println(textointerface);
}
FileOutputStream out = null;
try {
out = new FileOutputStream(nomearq);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
wb.write(out);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
textointerface= "arquivo excel dos resultados da(s) "+iestfim+" estação(ões) efetuado com sucesso";
publish(textointerface);
// keep 100 rows in memory, exceeding rows will be flushed to disk
//Messages.informMsg("Arquivo excel criado com sucesso");
return null;
}
protected void process(List<String> text) {
//this.pnt.lblAguardeThread.setText(text.get(0));
}
protected void done() {
Messages.informMsg("XLSX file exported successfully");
}
}
class executarSalvarExcel extends SwingWorker<Void, String> {
private SimulationDataExtremos simulationData;
private PanelTrendDetectionStreamflowBrazil pnt;
private ProgressMonitor progressMonitor;
private JTextArea taskOutput;
private JFileChooser chooser;
private ExtensionFileFilter filter;
public executarSalvarExcel (SimulationDataExtremos simulationData,PanelTrendDetectionStreamflowBrazil pnt){
this.simulationData=simulationData;
this.pnt=pnt;
}
@Override
protected Void doInBackground() throws Exception {
String dir = null;
String filename = null;
//if(dir == null){
Messages.informMsg("Indique o nome do arquivo de resultados .xlsx");
int returnVal = this.pnt.getChooser().showOpenDialog(this.pnt);
if (returnVal == JFileChooser.APPROVE_OPTION) {
dir = this.pnt.getChooser().getCurrentDirectory().getAbsolutePath() + "\\";
filename = this.pnt.getChooser().getSelectedFile().getName();
}
this.simulationData.setFilenameBD(filename);
this.simulationData.setDataDirBD(dir);
String[] columnNames = new String[11];
columnNames[0] = "Tipo de Teste";
columnNames[1] = "Teste Estatístico";
columnNames[2] = "Estatística do Teste";
columnNames[3] = "Pvalue (%)";
columnNames[4] = "Método Valor Critico";
columnNames[5] = "Valor Critico";
columnNames[6] = "Resultado";
columnNames[7] = "Descrição Resultado";
columnNames[8] = "Tendencia";
columnNames[9] = "Ano Divisão";
columnNames[10] = "Média Pós-AnoDivisão";
int ntestes=14;
String [] nometesteExtenso=new String [ntestes];
nometesteExtenso[0]="Mann-Kendall";
nometesteExtenso[1]="Spearman’s Rho";
nometesteExtenso[2]="Linear Regression";
nometesteExtenso[3]="Teste T";
nometesteExtenso[4]="Distribution CUSUM";
nometesteExtenso[5]="Cumulative Deviation";
nometesteExtenso[6]="Worsley Lik. Ratio";
nometesteExtenso[7]="Rank-Sum (Mann-Whitney)";
nometesteExtenso[8]="Teste F";
nometesteExtenso[9]="Median Crossing";
nometesteExtenso[10]="Turning Points";
nometesteExtenso[11]="Rank Difference";
nometesteExtenso[12]="Autocorrelation";
nometesteExtenso[13]="Wald-Wolfowitz";
String [] nometeste=new String [ntestes];
nometeste[0]="MK";
nometeste[1]="SR";
nometeste[2]="LR";
nometeste[3]="TT";
nometeste[4]="DC";
nometeste[5]="CD";
nometeste[6]="WR";
nometeste[7]="MW";
nometeste[8]="TF";
nometeste[9]="MC";
nometeste[10]="TP";
nometeste[11]="RD";
nometeste[12]="AC";
nometeste[13]="WW";
String nomearq=dir+filename+".xlsx";
Workbook wb = new SXSSFWorkbook(100);
setProgress(0);
String textointerface= "Iniciando o Calculo do Resumo dos Resultados das Estações ";
publish(textointerface);
int progress = 0;
setProgress(0);
int iestfim=0;
for(int i=0;i<this.simulationData.getVariaveisHidr().size();i++){
if(this.simulationData.getVariaveisHidr().get(i).isSelecionada() && this.simulationData.getVariaveisHidr().get(i).isAtendeRestricaoTamMin()) {
String codigo=String.valueOf(this.simulationData.getVariaveisHidr().get(i).getInvhidro().getEstacao_codigo());
ArrayList<ResultEstacionaridade> resultestacionaridade =new ArrayList<ResultEstacionaridade>();
resultestacionaridade = this.simulationData.getVariaveisHidr().get(i).getResultestacionaridade();
VariavelHidrologica vhid =this.simulationData.getVariaveisHidr().get(i);
int nlinhastr=ntestes+1;
int ncolstr=columnNames.length;
Sheet sh = wb.createSheet(codigo);
Object[][] result =this.pnt.setDadosResEstac(resultestacionaridade);
for(int rownum = 0; rownum <nlinhastr; rownum++){
Row row = sh.createRow(rownum);
for(int cellnum = 0; cellnum < ncolstr; cellnum++){
Cell cell = row.createCell(cellnum);
String address = new CellReference(cell).formatAsString();
if(rownum !=0){
if(cellnum == 2 || cellnum == 3 || cellnum == 5 || cellnum == 9){
String teste=String.valueOf(result[rownum-1][cellnum]);
if(teste != ""){
double val=Double.parseDouble(teste);
cell.setCellValue(val);
}else{
}
}else{
cell.setCellValue(String.valueOf(result[rownum-1][cellnum]));
}
/* if(cellnum == 0){
cell.setCellValue(String.valueOf(result[rownum-1][0]));
}else if (cellnum == 1){
cell.setCellValue(String.valueOf(result[rownum-1][0]));
}else if (cellnum == 2){
cell.setCellValue(result[rownum-1][2]);
}else if (cellnum == 3){
cell.setCellValue(result[rownum-1][3]);
}else if (cellnum == 4){
cell.setCellValue(result[rownum-1][3]);
}*/
}else{
cell.setCellValue(columnNames[cellnum]);
}
}
}
iestfim++;
}
double progress2 = ((i+1)*1.0/(this.simulationData.getVariaveisHidr().size()*1.0))*100;
int ngauges= this.simulationData.getVariaveisHidr().size();
progress=(int) progress2;
setProgress(Math.min(progress, 100));
textointerface= "Aguarde..executando o calculo da estação "+(i+1)+"/"+ngauges+"";
publish(textointerface);
System.out.println(textointerface);
}
FileOutputStream out = null;
try {
out = new FileOutputStream(nomearq);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
wb.write(out);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
textointerface= "arquivo excel dos resultados da(s) "+iestfim+" estação(ões) efetuado com sucesso";
publish(textointerface);
// keep 100 rows in memory, exceeding rows will be flushed to disk
//Messages.informMsg("Arquivo excel criado com sucesso");
return null;
}
protected void process(List<String> text) {
//this.pnt.lblAguardeThread.setText(text.get(0));
}
protected void done() {
Messages.informMsg("Arquivo excel construido com sucesso");
}
}
}
<file_sep>package gui;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.border.EtchedBorder;
import org.geotools.feature.SchemaException;
import org.jfree.ui.RefineryUtilities;
import com.vividsolutions.jump.workbench.model.Category;
import com.vividsolutions.jump.workbench.plugin.PlugInContext;
import gui.tableResultTrendTeste.FrameResultadoEstacionaridade;
import gui.tableResultTrendTeste.FrameResultadoEstacionaridadeAllGauges;
import io.DesenharShapesResultadoDetalhado;
import io.DesenharShapesResultadoDetalhadoGeotools;
import io.ExportarResultadoTabelaResumoBsen;
import io.ExtensionFileFilter;
import io.MAR_ImportDataDAO;
import io.PanelEscolherArquivoExcelExportarResultado;
import io.StationaritySummary;
import io.graph.PanelEscolherGrafico;
import tests.ExecutarTestesEstacionaridadeMapaResultsAllCorrelTemporal;
import types.InventarioHidrologico;
import types.ResultEstacionaridade;
import types.SimulationDataExtremos;
import types.VariavelHidrologica;
import util.Messages;
public class PanelTrendDetectionStreamflowBrazil extends JFrame implements
PropertyChangeListener{
private static final long serialVersionUID = 1L;
private JFileChooser chooser;
private JFileChooser chooser_xlsx;
private ExtensionFileFilter filter_xlsx;
public JTextField getTxtDiretorioArquivo() {
return txtDiretorioArquivo;
}
public JTextField getTxtDiretorioArquivoOutput() {
return txtDiretorioArquivoOutput;
}
private JPanel panelData;
private JPanel panelButtons;
private JButton btnExecute;
private JButton btnExecuteSIM2;
private JButton btnCancel;
private ButtonGroup cboxButtonGroup;
private JRadioButton button1;
private JRadioButton button2;
private JRadioButton button3;
private JCheckBox ckbox01;
private JCheckBox ckbox02;
private SimulationDataExtremos simulationData;
//private PanelTestesEstatisticos pnd;
private ExtensionFileFilter filter;
//private PanelImportarDados panelImportarDados;
private JPanel panelSetarDiretorios;
public JTextField txtDiretorioArquivo;
private JButton btnDiretorioArquivo;
private JPanel panelSetarDiretoriosOutput;
public JTextField txtDiretorioArquivoOutput;
private JButton btnDiretorioArquivoOutput;
protected PlugInContext context = null;
protected Category category = null;
private JButton btnExecuteSIM3;
private JButton btnExecuteSIM5;
private JButton btnExecuteSIM6;
private JButton btnExecuteSIM7;
private JButton btnExecuteSIM8;
//public PanelShapeComAtributoSimplificado panelShapeComAtributoSimplificado;
private JPanel panelAgregarShapes;
private JButton btnAgregarShapesTipo1;
private JButton btnAgregarShapesTipo2;
private JButton btnBaciasONS;
private JButton btnExportarVhidPorShape;
private JButton btnDefinirCaracteristicaSeriesHidro;
private JButton btnDefinirDesenharPermanenciaIntervaloConfiancaBoostrap;
private JButton btnDefinirCorrelEspacial;
private JButton btnExecuteSIM9;
private JButton btnExecuteSIM10;
private JButton btnSimulaTipo1TemperaturaNexgddp;
private JButton btnResultadoBudykoSMAPGabriela;
private JButton btnResultadosFelipeSBRH;
private JButton btnResultadosDecisaoTp1;
private JButton btnResultadosDecisaoTp2;
private JPanel panelImportData;
private PanelTabelaIDadosImportados panelDadosTable;
private JCheckBox checkSelecionarTodas;
private JPanel formatPanelData;
private JButton btnexecutarTestes;
private JButton btnImportData;
private JPanel panelEstacionaridadeTendencia;
private JCheckBox[] checkEstacionaridadeTendencia = new JCheckBox[50];
static private String [] nomeTesteIndep =new String[12];
static private String [] nomeTesteTenden =new String[12];
static private String [] nomeTesteMedia =new String[12];
static private String [] nomeTesteVariancia =new String[12];
static private String [] nomeTesteOutlier=new String[12];
static private String [] nomeTesteHomogeneidade=new String[12];
static private String [] nomeTesteAnaReg=new String[12];
static private String [] nomeTesteTendenAutoCorrelacao =new String[12];
private JPanel panelFDR;
private ButtonGroup cboxButtonGroupFDR;
private JRadioButton button1FDR;
private JRadioButton button2FDR;
private JCheckBox checkSelFDR;
private JPanel panelTipoHipotese;
/*private ButtonGroup cboxButtonGroup;
private JRadioButton button1;
private JRadioButton button2;
private JRadioButton button3;*/
private JPanel panelNivelSignificanciaTeorico;
private JLabel lblNivelSignificanciaTeorico;
private JComboBox cboNivelSignificanciaTeorico;
private JCheckBox[] checkEstacionaridadeTendenciaAutoCorrelacao = new JCheckBox[50];
private JPanel panelEstacionaridadeTendenciaAutoCorrelacao;
private ButtonGroup cboxButtonGroupAutoCorrel;
private JRadioButton button1AutoCorrel;
private JRadioButton button2AutoCorrel;
private JRadioButton button3AutoCorrel;
private JRadioButton button4AutoCorrel;
private JRadioButton button5AutoCorrel;
private JCheckBox checkSelAutoCorrel;
private JButton btnResultTable;
public JTextArea textAreaResumo;
public final static String newline = "\n";
public JFrame frameResumo;
public JPanel panelResumo;
private JButton btnSummaryResult;
private JButton btnSaveXLSXProgress;
private JButton btnSaveSHP;
private JPanel panelRecordLength;
private JTextField txtRecordLength;
private JLabel lblRecordLength;
private JButton btnGraphTS;
public PanelTabelaIDadosImportados getPanelDadosTable() {
return panelDadosTable;
}
public void setPanelDadosTable(PanelTabelaIDadosImportados panelDadosTable) {
this.panelDadosTable = panelDadosTable;
}
public PanelTrendDetectionStreamflowBrazil(SimulationDataExtremos simulationData) {
super("Trend Detection Streamflow Brazil");
this.simulationData = simulationData;
this.createAndShowGUI();
this.createPane();
this.pack();
}
private void createPane() {
this.chooser = new JFileChooser(new File("."));
this.filter = new ExtensionFileFilter("dat", "Lista de Arquivos (*.dat)");
this.chooser.setFileFilter(this.filter);
}
private void formatPanelData() {
this.formatPanelData = new JPanel();
this.formatPanelData.setBorder(new EtchedBorder());
this.formatPanelData.setBounds(0, 0, 850, 500);
this.formatPanelData.setLayout(null);
this.formatPanelData.setBackground(Color.LIGHT_GRAY);
this.add(this.formatPanelData);
}
private void createAndShowGUI() {
this.setBounds(20, 20, 800, 500);
this.setPreferredSize(new Dimension(850, 500));
this.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
this.setBackground(Color.LIGHT_GRAY);
this.setResizable(false);
this.setAlwaysOnTop(true);
this.setLayout(null);
this.formatPanelData();
this.setarnomescheckbox();
//this.formatPanelData();
this.formatPanelButton();
//this.formatPanelSetarDirTemplate();
this.formatPanelSetarDirOutput();
this.formatPanelTableDadosFluviometricas();
this.formatPanelEstacionaridadeTendencia();
this.formatpanelTipoHipotese();
this.formatpanelNivelSignificancia();
this.formatPanelEstacionaridadeTendenciaAutoCorrelacao();
this.formatPanelFDR();
this.formatPanelRecordLength();
}
public void setarFrameResumoResultados(){
this.frameResumo = new JFrame("Resultados");
this.frameResumo.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
this.frameResumo.setBounds(100, 60, 500, 200);
//this.frameResumo.set
//Add contents to the window.
this.frameResumo.add(this.setarPanelResumo());
//Display the window.
this.frameResumo.pack();
this.frameResumo.setVisible(true);
}
private JPanel setarPanelResumo(){
this.panelResumo=new JPanel();
this.panelResumo.setLayout(new GridBagLayout());
this.textAreaResumo = new JTextArea(40, 110);
this.textAreaResumo.setEditable(false);
JScrollPane scrollPane = new JScrollPane(this.textAreaResumo);
//Add Components to this panel.
GridBagConstraints c = new GridBagConstraints();
c.gridwidth = GridBagConstraints.REMAINDER;
c.fill = GridBagConstraints.HORIZONTAL;
//add(textField, c);
c.fill = GridBagConstraints.BOTH;
c.weightx = 1.0;
c.weighty = 1.0;
this.panelResumo.add(scrollPane, c);
return this.panelResumo;
}
private void formatPanelSetarDirOutput() {
this.panelSetarDiretoriosOutput = new JPanel();
this.panelSetarDiretoriosOutput.setBackground(Color.LIGHT_GRAY);
this.panelSetarDiretoriosOutput.setBorder(new EtchedBorder());
this.panelSetarDiretoriosOutput.setBorder(BorderFactory.createTitledBorder("Directory Output"));
this.panelSetarDiretoriosOutput.setBounds(5, 410, 835,50);
this.panelSetarDiretoriosOutput.setLayout(null);
this.formatPanelData.add(this.panelSetarDiretoriosOutput);
this.txtDiretorioArquivoOutput = new JTextField();
this.txtDiretorioArquivoOutput.setBounds(10, 20, 700, 25);
this.txtDiretorioArquivoOutput.setEnabled(true);
this.panelSetarDiretoriosOutput.add(this.txtDiretorioArquivoOutput);
this.btnDiretorioArquivoOutput = new JButton("Directory");
this.btnDiretorioArquivoOutput.setToolTipText("Selecionar diretorio onde os arquivos criados serão salvos");
this.btnDiretorioArquivoOutput.setBounds(720, 20, 90, 25);
//String dirOutput="E:\\PROJETO E IMPLEMENTACOES\\EXTREMOS_UNB\\resultados\\RESULTADOS_SET_2017\\";
//String dirOutput="C:\\Users\\saulo.souza\\Desktop\\Resultados - CAPES-ANA - SET_17\\RESULTADOS\\30 ANOS_COHID_01\\ANUAL\\FLU\\FDR-PW\\";
//String dirOutput="C:\\AnaliseTendenciaExtremosBrasil\\resultados\\";
//String dirOutput="C:\\Artigos 2018\\Artigo2 - Analise de Sensibilidade\\Resultados2018\\";
//String dirOutput="C:\\Artigos 2018\\Artigo1 - Analise de Tendencia\\resultados\\testes\\";
//String dirOutput="C:\\Users\\saulo.souza\\Desktop\\Capitulos_Livro_Dirceu\\CorrelacaoEspacialDirceu\\resultados\\";
String dirOutput="C:\\Users\\saulo.souza\\eclipse-workspace\\TrendDetectionStreamflowBrazil\\test\\";
this.txtDiretorioArquivoOutput.setText(dirOutput);
this.simulationData.setDirOutputExtremosUNB(dirOutput);
this.btnDiretorioArquivoOutput.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JFileChooser fc = new JFileChooser();
/*JFileChooser fc = new JFileChooser();
// restringe a amostra a diretorios apenas
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
// int res = fc.showOpenDialog(null);
JFrame frm=new JFrame();
int res = fc.showOpenDialog(frm); */
int res=selecionarDiretorio(fc);
if(res == JFileChooser.APPROVE_OPTION){
File diretorio = fc.getSelectedFile();
//JOptionPane.showMessageDialog(null, "Voce escolheu o diretório: " + diretorio.getName());
txtDiretorioArquivoOutput.setText(diretorio.getAbsolutePath()+ "\\");
//simulationData.setDirSalvarArquivos(diretorio.getAbsolutePath()+ "\\");
simulationData.setDirOutputExtremosUNB(diretorio.getAbsolutePath()+ "\\");
}
else
JOptionPane.showMessageDialog(null, "Voce nao selecionou nenhum diretorio.");
}
});
this.panelSetarDiretoriosOutput.add(this.btnDiretorioArquivoOutput, JLayeredPane.DEFAULT_LAYER);
}
private int selecionarDiretorio(JFileChooser fc) {
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int res = fc.showOpenDialog(this);
return res;
}
private void formatPanelSetarDirTemplate() {
this.panelSetarDiretorios = new JPanel();
this.panelSetarDiretorios.setBackground(Color.LIGHT_GRAY);
this.panelSetarDiretorios.setBorder(new EtchedBorder());
this.panelSetarDiretorios.setBorder(BorderFactory.createTitledBorder("Directory Templates"));
this.panelSetarDiretorios.setBounds(5, 360, 835,50);
this.panelSetarDiretorios.setLayout(null);
this.formatPanelData.add(this.panelSetarDiretorios);
this.txtDiretorioArquivo = new JTextField();
this.txtDiretorioArquivo.setBounds(10, 20, 700, 25);
this.txtDiretorioArquivo.setEnabled(true);
this.panelSetarDiretorios.add(this.txtDiretorioArquivo);
this.btnDiretorioArquivo = new JButton("Directory");
this.btnDiretorioArquivo.setToolTipText("Selecionar diretorio onde os arquivos criados serão salvos");
this.btnDiretorioArquivo.setBounds(720, 20, 90, 25);
//String dirTemplate="E:\\PROJETO E IMPLEMENTACOES\\EXTREMOS_UNB\\resultados\\templates\\";
//String dirTemplate="C:\\AnaliseTendenciaExtremosBrasil\\templates\\";
//String dirTemplate="C:\\Users\\saulo.souza\\eclipse-workspace\\OpenJump1141\\TemplatesXLSOficial\\";
String dirTemplate="C:\\Users\\saulo.souza\\eclipse-workspace\\TrendDetectionStreamflowBrazil\\TemplatesXLSOficial\\";
this.txtDiretorioArquivo.setText(dirTemplate);
this.simulationData.setDirTemplateExtremosUNB(dirTemplate);
this.btnDiretorioArquivo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JFileChooser fc = new JFileChooser();
// restringe a amostra a diretorios apenas
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int res = fc.showOpenDialog(null);
if(res == JFileChooser.APPROVE_OPTION){
File diretorio = fc.getSelectedFile();
//JOptionPane.showMessageDialog(null, "Voce escolheu o diretório: " + diretorio.getName());
txtDiretorioArquivo.setText(diretorio.getAbsolutePath()+ "\\");
//simulationData.setDirSalvarArquivos(diretorio.getAbsolutePath()+ "\\");
simulationData.setDirTemplateExtremosUNB(diretorio.getAbsolutePath()+ "\\");
}
else
JOptionPane.showMessageDialog(null, "Voce nao selecionou nenhum diretorio.");
}
});
this.panelSetarDiretorios.add(this.btnDiretorioArquivo, JLayeredPane.DEFAULT_LAYER);
}
public void formatPanelTableDadosFluviometricas(){
this.panelImportData= new JPanel();
this.panelImportData.setBounds(10, 10, 250, 340);
this.panelImportData.setLayout(null);
this.formatPanelData.add(this.panelImportData);
this.panelImportData.setBorder(BorderFactory.createTitledBorder("Import Data"));
this.panelImportData.setBackground(Color.LIGHT_GRAY);
//this.panelButtons
int posx=10;
int posy=20;
int tamx=230;
int tamy=290;
ArrayList<VariavelHidrologica> variaveishidrologicas=new ArrayList<VariavelHidrologica>();
this.simulationData.setVariaveisHidr(variaveishidrologicas);
this.panelDadosTable=new PanelTabelaIDadosImportados(this.simulationData.getVariaveisHidr(),tamx,tamy);
this.panelDadosTable.setBounds(posx, posy, tamx,tamy);
this.panelDadosTable .setBackground(Color.LIGHT_GRAY);
this.panelDadosTable .setBorder(new EtchedBorder());
this.panelDadosTable.setBorder(BorderFactory.createTitledBorder("Gauges"));
this.panelDadosTable.setLayout(null);
//this.add(this.panelDadosTable);
this.panelImportData.add(this.panelDadosTable);
this.formateCheckSelTodas();
}
private void formateCheckSelTodas(){
this.checkSelecionarTodas =new JCheckBox("Select All Gauges");
this.checkSelecionarTodas.setHorizontalTextPosition(SwingConstants.RIGHT);
this.checkSelecionarTodas.setVerticalTextPosition(SwingConstants.CENTER);
this.checkSelecionarTodas.setSelected(true);
this.checkSelecionarTodas.setBackground(Color.LIGHT_GRAY);
this.panelImportData.add(this.checkSelecionarTodas);
//this.panelDadosTable.add(this.checkSelecionarTodas);
this.checkSelecionarTodas.setBounds(10, 310, 200, 25);
this.checkSelecionarTodas.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent evt){
int nrows =5000;
if(simulationData.getVariaveisHidr() != null){
nrows = simulationData.getVariaveisHidr().size();
}
if(checkSelecionarTodas.isSelected() == true){
for (int r = 0; r < nrows; r++){
panelDadosTable.getTabela().setValueAt(true, r, 0);
}
}else{
for (int r = 0; r < nrows; r++){
panelDadosTable.getTabela().setValueAt(false, r, 0);
}
}
panelDadosTable.getTabela().repaint();
}
});
}
private void formatPanelEstacionaridadeTendencia() {
this.panelEstacionaridadeTendencia = new JPanel();
this.panelEstacionaridadeTendencia.setBackground(Color.LIGHT_GRAY);
this.panelEstacionaridadeTendencia.setBorder(BorderFactory.createTitledBorder("Trend Tests"));
//this.panelEstacionaridadeTendencia.setBounds(230, 210, 215, 190);
this.panelEstacionaridadeTendencia.setBounds(260, 10, 160, 120);
this.panelEstacionaridadeTendencia.setLayout(null);
this.formatPanelData.add(this.panelEstacionaridadeTendencia);
this.formatCheckEstacionaridadeTendencia();
//this.panelEstacionaridadeTendencia.setEnabled(false);
}
private void formatCheckEstacionaridadeTendencia() {
int ntestindep=3;
for (int i=0;i<ntestindep;i++){
this.checkEstacionaridadeTendencia[i] = new JCheckBox(PanelTrendDetectionStreamflowBrazil.nomeTesteTenden[i]);
this.checkEstacionaridadeTendencia[i].setHorizontalTextPosition(SwingConstants.LEFT);
this.checkEstacionaridadeTendencia[i].setVerticalTextPosition(SwingConstants.CENTER);
this.checkEstacionaridadeTendencia[i].setSelected(false);
this.checkEstacionaridadeTendencia[i].setBackground(Color.LIGHT_GRAY);
this.panelEstacionaridadeTendencia.add(this.checkEstacionaridadeTendencia[i]);
this.checkEstacionaridadeTendencia[i].setEnabled(true);
}
this.checkEstacionaridadeTendencia[0].setBounds(10, 20, 140, 25);
this.checkEstacionaridadeTendencia[1].setBounds(10, 50, 140, 25);
this.checkEstacionaridadeTendencia[2].setBounds(10, 80, 140, 25);
//this.checkEstacionaridadeTendencia[3].setBounds(10, 110, 140, 25);
this.checkEstacionaridadeTendencia[1].setEnabled(false);
this.checkEstacionaridadeTendencia[2].setEnabled(false);
this.checkEstacionaridadeTendencia[0].setSelected(true);
}
private void setarnomescheckbox() {
PanelTrendDetectionStreamflowBrazil.nomeTesteIndep[0]="Median Crossing";
PanelTrendDetectionStreamflowBrazil.nomeTesteIndep[1]="Turning Points";
PanelTrendDetectionStreamflowBrazil.nomeTesteIndep[2]="Rank Difference";
PanelTrendDetectionStreamflowBrazil.nomeTesteIndep[3]="Autocorrelation";
PanelTrendDetectionStreamflowBrazil.nomeTesteIndep[4]="Wald-Wolfowitz";
PanelTrendDetectionStreamflowBrazil.nomeTesteTenden[0]="Mann-Kendall ";
PanelTrendDetectionStreamflowBrazil.nomeTesteTenden[1]="Spearman’s Rho ";
PanelTrendDetectionStreamflowBrazil.nomeTesteTenden[2]="Linear Regression";
PanelTrendDetectionStreamflowBrazil.nomeTesteTenden[3]="Autocorrelation";
PanelTrendDetectionStreamflowBrazil.nomeTesteHomogeneidade[0]="Mann-Whitney";
PanelTrendDetectionStreamflowBrazil.nomeTesteMedia[0]="Teste T";
PanelTrendDetectionStreamflowBrazil.nomeTesteMedia[1]="Distribution CUSUM";
PanelTrendDetectionStreamflowBrazil.nomeTesteMedia[2]="Cumul. Deviation";
PanelTrendDetectionStreamflowBrazil.nomeTesteMedia[3]="Worsley Lik. Ratio";
PanelTrendDetectionStreamflowBrazil.nomeTesteMedia[4]="Rank-Sum";
PanelTrendDetectionStreamflowBrazil.nomeTesteMedia[5]="Mann-Whitney";
PanelTrendDetectionStreamflowBrazil.nomeTesteVariancia[0]="Teste F";
PanelTrendDetectionStreamflowBrazil.nomeTesteAnaReg[0]="Medida de discordância";
PanelTrendDetectionStreamflowBrazil.nomeTesteAnaReg[1]="Heterogeneidade - Identificação de Regiões Homogêneas";
PanelTrendDetectionStreamflowBrazil.nomeTesteOutlier[0]="Chauvenet’s method";
PanelTrendDetectionStreamflowBrazil.nomeTesteOutlier[1]="Dixon–Thompson";
PanelTrendDetectionStreamflowBrazil.nomeTesteOutlier[2]="Rosner";
PanelTrendDetectionStreamflowBrazil.nomeTesteOutlier[3]="Grubbs and Beck";
//PanelTrendDetectionStreamflowBrazil.nomeTesteAderencia[0]="Teste Qui-Quadrado";
//PanelTrendDetectionStreamflowBrazil.nomeTesteAderencia[1]="Kolmogorov-Smirnov";
//PanelTrendDetectionStreamflowBrazil.nomeTesteAderencia[2]="Zdist(Hosking,1991)";
PanelTrendDetectionStreamflowBrazil.nomeTesteTendenAutoCorrelacao[0]="Mann-Kendall - PW";
PanelTrendDetectionStreamflowBrazil.nomeTesteTendenAutoCorrelacao[1]="Mann-Kendall - TFPW";
}
public void formatpanelTipoHipotese (){
this.panelTipoHipotese=new JPanel();
this.panelTipoHipotese.setBackground(Color.LIGHT_GRAY);
this.panelTipoHipotese.setBorder(BorderFactory.createTitledBorder("Hypothesis"));
this.panelTipoHipotese.setBounds(420, 10, 120, 120);
this.panelTipoHipotese.setLayout(new GridLayout(0, 1));
this.cboxButtonGroup = new ButtonGroup();
button1 = new JRadioButton("Two-Tailed");
button1.setSelected(true);
button2 = new JRadioButton("Left-Tailed");
button3 = new JRadioButton("Right-Tailed");
button1.setBackground(Color.LIGHT_GRAY);
button2.setBackground(Color.LIGHT_GRAY);
button3.setBackground(Color.LIGHT_GRAY);
this.cboxButtonGroup.add(button1);
this.cboxButtonGroup.add(button2);
this.cboxButtonGroup.add(button3);
this.panelTipoHipotese.add(button1);
this.panelTipoHipotese.add(button2);
this.panelTipoHipotese.add(button3);
this.formatPanelData.add(this.panelTipoHipotese);
this.simulationData.setTipoHipoteseEstacionaridade(0);
this.simulationData.setBootstrap(false);
button1.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent evt){
if(button1.isSelected() == true){
simulationData.setTipoHipoteseEstacionaridade(0);
}
}
});
button2.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent evt){
if(button2.isSelected() == true){
simulationData.setTipoHipoteseEstacionaridade(2);
}
}
});
button3.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent evt){
if(button3.isSelected() == true){
simulationData.setTipoHipoteseEstacionaridade(1);
}
}
});
}
public void formatpanelNivelSignificancia (){
this.panelNivelSignificanciaTeorico=new JPanel();
this.panelNivelSignificanciaTeorico.setBackground(Color.LIGHT_GRAY);
this.panelNivelSignificanciaTeorico.setBorder(BorderFactory.createTitledBorder("Significance Level"));
this.panelNivelSignificanciaTeorico.setBounds(540, 10, 120, 60);
//this.panelNivelSignificanciaTeorico.setLayout(new GridLayout(0, 1));
this.panelNivelSignificanciaTeorico.setLayout(null);
this.formatPanelData.add(this.panelNivelSignificanciaTeorico);
String[] items = {"5 %", "10 %", "1 %"};
this.cboNivelSignificanciaTeorico = new JComboBox(items);
this.cboNivelSignificanciaTeorico.setBounds(50, 25, 60, 20);
this.panelNivelSignificanciaTeorico.add(this.cboNivelSignificanciaTeorico);
this.lblNivelSignificanciaTeorico = new JLabel("Alpha:");
this.lblNivelSignificanciaTeorico.setBounds(10, 30, 40, 15);
this.panelNivelSignificanciaTeorico.add(this.lblNivelSignificanciaTeorico);
this.simulationData.setNivelSignificancia(5);
this.simulationData.setBootstrap(false);
this.cboNivelSignificanciaTeorico.addFocusListener(new FocusListener(){ //need these to handle tab key; will also handle click in/out
public void focusGained(FocusEvent e){}
public void focusLost(FocusEvent e){
int ns = cboNivelSignificanciaTeorico.getSelectedIndex();
if(ns == 1){
simulationData.setNivelSignificancia(10);
}else if(ns == 2){
simulationData.setNivelSignificancia(1);
}else{
simulationData.setNivelSignificancia(5);
}
//int mesIni=indice+1;
//simulationData.setMesIniEstacionaridade(mesIni);
}
});
}
public void formatPanelRecordLength (){
this.panelRecordLength=new JPanel();
this.panelRecordLength.setBackground(Color.LIGHT_GRAY);
this.panelRecordLength.setBorder(BorderFactory.createTitledBorder("Record Length"));
this.panelRecordLength.setBounds(540, 70, 120, 60);
this.panelRecordLength.setLayout(null);
this.formatPanelData.add(this.panelRecordLength);
this.txtRecordLength = new JTextField();
this.txtRecordLength.setBounds(60, 25, 50, 25);
this.txtRecordLength.setEnabled(true);
this.panelRecordLength.add(this.txtRecordLength);
this.txtRecordLength.setText("30");
this.lblRecordLength = new JLabel("N = ");
this.lblRecordLength.setBounds(10, 30, 30, 15);
this.panelRecordLength.add(this.lblRecordLength);
}
private void formatPanelFDR() {
this.panelFDR = new JPanel();
this.panelFDR.setBackground(Color.LIGHT_GRAY);
this.panelFDR.setBorder(BorderFactory.createTitledBorder("Multiplicity Test"));
this.panelFDR.setBounds(420, 130, 120, 100);
this.panelFDR.setLayout(null);
//this.panelEstacionaridadeTendenciaAutoCorrelacao.setLayout(new GridLayout(0, 1));
this.formatPanelData.add(this.panelFDR);
JPanel panel = new JPanel();
panel.setBounds(10, 40, 100, 50);
panel.setLayout(new GridLayout(0, 1));
this.cboxButtonGroupFDR = new ButtonGroup();
int ntestindep=2;
this.button1FDR = new JRadioButton("FDR");
this.button1FDR.setSelected(true);
this.button2FDR = new JRadioButton("FWER");
this.cboxButtonGroupFDR.add(this.button1FDR);
this.cboxButtonGroupAutoCorrel.add(this.button2FDR);
panel.add(this.button1FDR);
panel.add(this.button2FDR);
this.panelFDR.add(panel);
//this.panelEstacionaridadeTendenciaAutoCorrelacao.add(panel);
this.button1FDR.setBackground(Color.LIGHT_GRAY);
this.button2FDR.setBackground(Color.LIGHT_GRAY);
this.button1FDR.setEnabled(false);
this.button2FDR.setEnabled(false);
this.simulationData.setFazerFDR(false);
this.simulationData.setFazerFDRClassico(true);
this.button1FDR.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent evt){
if(button1FDR.isSelected() == true){
simulationData.setFazerFDRClassico(button1FDR.isSelected());
//simulationData.setFazerTFPW(button2AutoCorrel.isSelected());
// simulationData.setTipoHipoteseEstacionaridade(0);
}
}
});
this.button2FDR.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent evt){
if(button2FDR.isSelected() == true){
//simulationData.setFazerPW(button1AutoCorrel.isSelected());
//simulationData.setFazerTFPW(button2FDR.isSelected());
}
}
});
this.checkSelFDR =new JCheckBox("Select");
this.checkSelFDR.setHorizontalTextPosition(SwingConstants.LEFT);
this.checkSelFDR.setVerticalTextPosition(SwingConstants.CENTER);
this.checkSelFDR.setSelected(false);
this.checkSelFDR.setBackground(Color.LIGHT_GRAY);
this.checkSelFDR.setBounds(45, 15, 80, 25);
this.panelFDR.add(this.checkSelFDR);
this.checkSelFDR.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent evt){
if(checkSelFDR.isSelected() == true){
button1FDR.setEnabled(true);
button2FDR.setEnabled(false);
simulationData.setFazerFDR(true);
}else{
button1FDR.setEnabled(false);
button2FDR.setEnabled(false);
simulationData.setFazerFDR(false);
}
}
});
}
private void formatPanelEstacionaridadeTendenciaAutoCorrelacao() {
this.panelEstacionaridadeTendenciaAutoCorrelacao = new JPanel();
this.panelEstacionaridadeTendenciaAutoCorrelacao.setBackground(Color.LIGHT_GRAY);
this.panelEstacionaridadeTendenciaAutoCorrelacao.setBorder(BorderFactory.createTitledBorder("Serial Correlation"));
//this.panelEstacionaridadeTendencia.setBounds(230, 210, 215, 190);
this.panelEstacionaridadeTendenciaAutoCorrelacao.setBounds(260, 130, 160, 220);
this.panelEstacionaridadeTendenciaAutoCorrelacao.setLayout(null);
//this.panelEstacionaridadeTendenciaAutoCorrelacao.setLayout(new GridLayout(0, 1));
this.formatPanelData.add(this.panelEstacionaridadeTendenciaAutoCorrelacao);
//260, 10, 160, 120
this.formatCheckEstacionaridadeTendenciaAutoCorrelacao();
//this.panelEstacionaridadeTendencia.setEnabled(false);
}
private void formatCheckEstacionaridadeTendenciaAutoCorrelacao() {
JPanel panel = new JPanel();
panel.setBounds(10, 40, 100, 130);
panel.setLayout(new GridLayout(0, 1));
this.cboxButtonGroupAutoCorrel = new ButtonGroup();
int ntestindep=2;
this.button1AutoCorrel = new JRadioButton("PW");
this.button1AutoCorrel.setSelected(true);
this.button2AutoCorrel = new JRadioButton("TFPW");
this.button3AutoCorrel = new JRadioButton("MTFPW");
this.button4AutoCorrel = new JRadioButton("VCPW");
this.button5AutoCorrel = new JRadioButton("VC");
this.cboxButtonGroupAutoCorrel.add(this.button1AutoCorrel);
this.cboxButtonGroupAutoCorrel.add(this.button2AutoCorrel);
this.cboxButtonGroupAutoCorrel.add(this.button3AutoCorrel);
this.cboxButtonGroupAutoCorrel.add(this.button4AutoCorrel);
this.cboxButtonGroupAutoCorrel.add(this.button5AutoCorrel);
panel.add(this.button1AutoCorrel);
panel.add(this.button2AutoCorrel);
panel.add(this.button3AutoCorrel);
panel.add(this.button4AutoCorrel);
panel.add(this.button5AutoCorrel);
this.panelEstacionaridadeTendenciaAutoCorrelacao.add(panel);
this.panelEstacionaridadeTendenciaAutoCorrelacao.add(panel);
this.button1AutoCorrel.setBackground(Color.LIGHT_GRAY);
this.button2AutoCorrel.setBackground(Color.LIGHT_GRAY);
this.button3AutoCorrel.setBackground(Color.LIGHT_GRAY);
this.button4AutoCorrel.setBackground(Color.LIGHT_GRAY);
this.button5AutoCorrel.setBackground(Color.LIGHT_GRAY);
this.button1AutoCorrel.setEnabled(false);
this.button2AutoCorrel.setEnabled(false);
this.button3AutoCorrel.setEnabled(false);
this.button4AutoCorrel.setEnabled(false);
this.button5AutoCorrel.setEnabled(false);
this.simulationData.setConsiderarAutoCorrelacao(false);
this.simulationData.setFazerPW(true);
this.button1AutoCorrel.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent evt){
if(button1AutoCorrel.isSelected() == true){
simulationData.setFazerPW(button1AutoCorrel.isSelected());
simulationData.setFazerTFPW(button2AutoCorrel.isSelected());
simulationData.setFazerMTFPW(button3AutoCorrel.isSelected());
simulationData.setFazerVCPW(button4AutoCorrel.isSelected());
simulationData.setFazerVC(button5AutoCorrel.isSelected());
// simulationData.setTipoHipoteseEstacionaridade(0);
}
}
});
this.button2AutoCorrel.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent evt){
if(button2AutoCorrel.isSelected() == true){
simulationData.setFazerPW(button1AutoCorrel.isSelected());
simulationData.setFazerTFPW(button2AutoCorrel.isSelected());
simulationData.setFazerMTFPW(button3AutoCorrel.isSelected());
simulationData.setFazerVCPW(button4AutoCorrel.isSelected());
simulationData.setFazerVC(button5AutoCorrel.isSelected());
}
}
});
this.button3AutoCorrel.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent evt){
if(button3AutoCorrel.isSelected() == true){
simulationData.setFazerPW(button1AutoCorrel.isSelected());
simulationData.setFazerTFPW(button2AutoCorrel.isSelected());
simulationData.setFazerMTFPW(button3AutoCorrel.isSelected());
simulationData.setFazerVCPW(button4AutoCorrel.isSelected());
simulationData.setFazerVC(button5AutoCorrel.isSelected());
}
}
});
this.button4AutoCorrel.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent evt){
if(button4AutoCorrel.isSelected() == true){
simulationData.setFazerPW(button1AutoCorrel.isSelected());
simulationData.setFazerTFPW(button2AutoCorrel.isSelected());
simulationData.setFazerMTFPW(button3AutoCorrel.isSelected());
simulationData.setFazerVCPW(button4AutoCorrel.isSelected());
simulationData.setFazerVC(button5AutoCorrel.isSelected());
}
}
});
this.button5AutoCorrel.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent evt){
if(button5AutoCorrel.isSelected() == true){
simulationData.setFazerPW(button1AutoCorrel.isSelected());
simulationData.setFazerTFPW(button2AutoCorrel.isSelected());
simulationData.setFazerMTFPW(button3AutoCorrel.isSelected());
simulationData.setFazerVCPW(button4AutoCorrel.isSelected());
simulationData.setFazerVC(button5AutoCorrel.isSelected());
}
}
});
this.checkSelAutoCorrel =new JCheckBox("Select");
this.checkSelAutoCorrel.setHorizontalTextPosition(SwingConstants.LEFT);
this.checkSelAutoCorrel.setVerticalTextPosition(SwingConstants.CENTER);
this.checkSelAutoCorrel.setSelected(false);
this.checkSelAutoCorrel.setBackground(Color.LIGHT_GRAY);
this.checkSelAutoCorrel.setBounds(90, 15, 70, 25);
this.panelEstacionaridadeTendenciaAutoCorrelacao.add(this.checkSelAutoCorrel);
this.checkSelAutoCorrel.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent evt){
if(checkSelAutoCorrel.isSelected() == true){
button1AutoCorrel.setEnabled(true);
button2AutoCorrel.setEnabled(true);
button3AutoCorrel.setEnabled(true);
button4AutoCorrel.setEnabled(true);
button5AutoCorrel.setEnabled(true);
simulationData.setConsiderarAutoCorrelacao(true);
}else{
button1AutoCorrel.setEnabled(false);
button2AutoCorrel.setEnabled(false);
button3AutoCorrel.setEnabled(false);
button4AutoCorrel.setEnabled(false);
button5AutoCorrel.setEnabled(false);
simulationData.setConsiderarAutoCorrelacao(false);
}
}
});
}
private void formatPanelButton() {
this.panelButtons = new JPanel();
this.panelButtons.setBackground(Color.LIGHT_GRAY);
this.panelButtons.setBorder(new EtchedBorder());
this.panelButtons.setBounds(720, 10, 110, 350);
this.panelButtons.setLayout(null);
this.formatPanelData.add(this.panelButtons);
this.btnImportData = new JButton("Import");
this.btnImportData.setToolTipText("Import streamflow time series");
this.btnImportData.setBounds(10, 10, 90, 25);
this.btnImportData.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
buttonAction(btnImportData);
}
});
this.panelButtons.add(this.btnImportData, JLayeredPane.DEFAULT_LAYER);
this.btnGraphTS = new JButton("Graph");
this.btnGraphTS.setToolTipText("Create a graph with the annual series for each gauge");
this.btnGraphTS.setBounds(10, 40, 90, 25);
this.btnGraphTS.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
buttonAction(btnGraphTS);
}
});
this.panelButtons.add(this.btnGraphTS, JLayeredPane.DEFAULT_LAYER);
this.btnExecute = new JButton("Execute");
this.btnExecute.setToolTipText("Execute trend tests");
this.btnExecute.setBounds(10, 70, 90, 25);
this.btnExecute.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
buttonAction(btnExecute);
}
});
this.panelButtons.add(this.btnExecute, JLayeredPane.DEFAULT_LAYER);
this.btnResultTable = new JButton("Restbl");
this.btnResultTable.setToolTipText("Result in table format for each gauge");
this.btnResultTable.setBounds(10, 100, 90, 25);
this.btnResultTable.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
buttonAction(btnResultTable);
}
});
this.panelButtons.add(this.btnResultTable, JLayeredPane.DEFAULT_LAYER);
this.btnSummaryResult = new JButton("Summary");
this.btnSummaryResult.setToolTipText("Summary result of trend tests");
this.btnSummaryResult.setBounds(10, 130, 90, 25);
this.btnSummaryResult.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
buttonAction(btnSummaryResult);
}
});
this.panelButtons.add(this.btnSummaryResult, JLayeredPane.DEFAULT_LAYER);
this.btnSaveXLSXProgress = new JButton("XLSX");
this.btnSaveXLSXProgress.setToolTipText("Result in XLSX format for each gauge");
this.btnSaveXLSXProgress.setBounds(10, 160, 90, 25);
this.btnSaveXLSXProgress.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
buttonAction(btnSaveXLSXProgress);
}
});
this.panelButtons.add(this.btnSaveXLSXProgress, JLayeredPane.DEFAULT_LAYER);
this.btnSaveSHP = new JButton("SHP");
this.btnSaveSHP.setToolTipText("Export Result in shapefile format");
this.btnSaveSHP.setBounds(10, 190, 90, 25);
this.btnSaveSHP.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
buttonAction(btnSaveSHP);
}
});
this.panelButtons.add(this.btnSaveSHP, JLayeredPane.DEFAULT_LAYER);
}
private void buttonAction(JButton jb){
//this.context= this.simulationData.getContext();
//this.category = this.context.getLayerManager().getCategory(SNIRHPlugInSettings.resultLayerCategory());
if (jb.equals(this.btnImportData)){
this.importDataGauges();
}else if(jb.equals(this.btnGraphTS)){
this.executeGraphTimeSeries();
}else if(jb.equals(this.btnExecute)){
this.executeTrendTest();
}else if(jb.equals(this.btnResultTable)){
this.executeResultTable();
}else if(jb.equals(this.btnSummaryResult)){
this.summaryResult();
}else if(jb.equals(this.btnSaveXLSXProgress)){
this.saveXLSXProgress();
}else if(jb.equals(this.btnSaveSHP)){
this.saveSHP();
}
}
private void executeGraphTimeSeries() {
// TODO Auto-generated method stub
final PanelEscolherGrafico panelGraf = new PanelEscolherGrafico(this.simulationData,this);
panelGraf.setVisible(true);
panelGraf.pack();
RefineryUtilities.centerFrameOnScreen(panelGraf);
}
private void saveSHP() {
// TODO Auto-generated method stub
DesenharShapesResultadoDetalhadoGeotools desenharShapesResultadoDetalhado=new DesenharShapesResultadoDetalhadoGeotools(this.simulationData,this);
String dirShape=this.txtDiretorioArquivoOutput.getText();
try {
desenharShapesResultadoDetalhado.execute("MK", dirShape);
} catch (SchemaException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Messages.informMsg("Shapefile exported successfully");
}
private void saveXLSXProgress(){
/*executarSalvarExcel boot= new executarSalvarExcel(this.simulationData,this);
boot.addPropertyChangeListener(this);
boot.execute();*/
//ExportarResultadoTabelaResumoBsen exportar=new ExportarResultadoTabelaResumoBsen(this.simulationData,this);
//exportar.executar();
final PanelEscolherArquivoExcelExportarResultado panelEscolherArq = new PanelEscolherArquivoExcelExportarResultado(this.simulationData,this);
panelEscolherArq.setVisible(true);
panelEscolherArq.pack();
RefineryUtilities.centerFrameOnScreen(panelEscolherArq);
}
private void summaryResult() {
// TODO Auto-generated method stub
StationaritySummary stationaritySummary=new StationaritySummary(this.simulationData,this);
stationaritySummary.resumoResultadosProgress();
}
private void importDataGauges() {
//ArrayList<ConfigAnaliseFrequenciaMinimos> config=this.panelDadosTableAnaliseFrequenciaMinimos.pegarConfiguracoesColocadasNaTabela();
final PanelEscolherArquivo panelEscolherArq = new PanelEscolherArquivo(this.simulationData,this);
panelEscolherArq.setVisible(true);
panelEscolherArq.pack();
RefineryUtilities.centerFrameOnScreen(panelEscolherArq);
}
public void executeTrendTest() {
//this.simulationData.setDirTemplateExtremosUNB(this.txtDiretorioArquivo.getText());
this.simulationData.setDirOutputExtremosUNB(this.txtDiretorioArquivoOutput.getText());
//String dirTemplate=this.simulationData.getDirTemplateExtremosUNB();
this.simulationData.setTamMinSerietotEstacionaridade(Integer.parseInt(this.txtRecordLength.getText()));
//this.simulationData.setCodEstatisticaSelecionadaEstacionaridade(1);
//this.simulationData.setAnoIniSubConjunto(-99999);
//this.simulationData.setAnoFimSubConjunto(-99999);
//this.simulationData.setConsiderarAutoCorrelacao(true);
//this.simulationData.setFazerFDR(true);
//this.simulationData.setFazerFDRClassico(true);
ExecutarTestesEstacionaridadeMapaResultsAllCorrelTemporal executarTestes = new ExecutarTestesEstacionaridadeMapaResultsAllCorrelTemporal(this.simulationData);
Map<String, Map<String,ResultEstacionaridade>> resultEstacionaridadeTipo2=executarTestes.executarTestes();
Messages.informMsg("Trend test run successfully");
System.out.println("finished");
}
private void executeResultTable() {
// TODO Auto-generated method stub
//final FrameResultadoEstacionaridade frameresultest = new FrameResultadoEstacionaridade(this.simulationData,this);
final FrameResultadoEstacionaridadeAllGauges frameresultest = new FrameResultadoEstacionaridadeAllGauges(this.simulationData,this);
frameresultest.setVisible(true);
frameresultest.pack();
RefineryUtilities.centerFrameOnScreen(frameresultest);
}
public void simularTipo1() {
//String dirTemplate="C:\\OpenJump150\\PROJETO E IMPLEMENTACOES\\EXTREMOS_UNB\\resultados\\templates\\";
this.simulationData.setDirTemplateExtremosUNB(this.txtDiretorioArquivo.getText());
this.simulationData.setDirOutputExtremosUNB(this.txtDiretorioArquivoOutput.getText());
String dirTemplate=this.simulationData.getDirTemplateExtremosUNB();
String nomearqTemplate="template_xls_TabelaResultadosIndices_tp3.xls";
//String dirOutput="C:\\OpenJump150\\PROJETO E IMPLEMENTACOES\\EXTREMOS_UNB\\resultados\\";
String dirOutput=this.simulationData.getDirOutputExtremosUNB();
//boolean pegarDadosShape=this.panelShapeComAtributoSimplificado.getCheckboxSelecionado().isSelected();
boolean fazerFiltro=false;
//String tipoFiltro="areaDrenagem";
String tipoFiltro="impactoReservacao";
String filtroCod="0";
//String filtroCod="1";
/**
* Leitura dos varios arquivos de diferentes indices
*/
String dir = null;
String filename = null;
File [] files = null;
String [] filenames = null;
ArrayList<String> nomeArquivo=new ArrayList<String>();
//Messages.informMsg("Indique o(s) arquivo(s) .dat");
this.chooser.setMultiSelectionEnabled(true);
int returnVal = this.chooser.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
dir = this.chooser.getCurrentDirectory().getAbsolutePath() + "\\";
filename = this.chooser.getSelectedFile().getName();
files=this.chooser.getSelectedFiles();
filenames = new String [files.length];
for(int i=0;i<files.length;i++){
filenames[i]=files[i].getName();
nomeArquivo.add(files[i].getName());
}
}
MAR_ImportDataDAO leiturarArquivos = new MAR_ImportDataDAO();
Map<String,ArrayList<VariavelHidrologica>> vhidPorIndice=new HashMap<String,ArrayList<VariavelHidrologica>>();
ArrayList<String>nomeIndicePorOrdemUsuario=new ArrayList<String>();
Map<String,InventarioHidrologico> inventario=new HashMap<String,InventarioHidrologico>();
Map<String,Map<String,Double>> valoresCamposGeoMapaPorIndice=new HashMap<String,Map<String,Double>>();
Map<String, Map<String, Map<String, Map<String,ResultEstacionaridade>>>> resultEstacionaridadeShape=
new HashMap<String, Map<String, Map<String, Map<String,ResultEstacionaridade>>>> ();
for(int i=0;i<nomeArquivo.size();i++){
ArrayList<VariavelHidrologica> vhidOriginal=leiturarArquivos.leituraDATVarHidSemBarraProgresso(dir, nomeArquivo.get(i));
ArrayList<VariavelHidrologica> variaveishidrologicasSheet=new ArrayList<VariavelHidrologica>();
variaveishidrologicasSheet=vhidOriginal;
for(int k=0;k<variaveishidrologicasSheet.size();k++){
String cod=variaveishidrologicasSheet.get(k).getInvhidro().getEstacao_codigo();
if(!inventario.containsKey(cod)){
inventario.put(cod, variaveishidrologicasSheet.get(k).getInvhidro());
}
}
//formatos antigos dos arquivos o nome do indice ficavam em descricaoOrigem serie
String nomeIndice=variaveishidrologicasSheet.get(0).getInvhidro().getDescricaoOrigemSerie();
//String nomeIndice=variaveishidrologicasSheet.get(0).getInvhidro().getTipodeDado();
vhidPorIndice.put(nomeIndice, variaveishidrologicasSheet);
nomeIndicePorOrdemUsuario.add(nomeIndice);
this.simulationData.setVariaveisHidr(null);
//String nomeIndice=nomeIndicePorOrdemUsuario.get(j);
this.simulationData.setVariaveisHidr(vhidPorIndice.get(nomeIndice));
ExecutarTestesEstacionaridadeMapaResultsAllCorrelTemporal executarTestes = new ExecutarTestesEstacionaridadeMapaResultsAllCorrelTemporal(this.simulationData);
Map<String, Map<String,ResultEstacionaridade>> resultEstacionaridadeTipo2=executarTestes.executarTestes();
boolean escrecerPlanilhaTp1=false;
if(escrecerPlanilhaTp1){
//String nomearqTemplateTP1="template_xls_bsenPvalue_comS_tp3.xls";
String nomearqTemplateTP1="template_xls_bsenPvalue_comS_tp3_tamanho_magnitude";
ExportarResultadoTabelaResumoBsen.
executarPlanilhaSimulacao(dirTemplate,nomearqTemplateTP1,dirOutput,resultEstacionaridadeTipo2,nomeIndice+"_"+nomeIndice,inventario, this.simulationData);
}
System.out.println("arquivo - "+nomeArquivo.get(i));
}
}
public Object[][] setDadosResEstac(ArrayList<ResultEstacionaridade> resultestacionaridade) {
int ntestes=14;
String [] nometeste=new String [ntestes];
nometeste[0]="MK";
nometeste[1]="SR";
nometeste[2]="LR";
nometeste[3]="TT";
nometeste[4]="DC";
nometeste[5]="CD";
nometeste[6]="WR";
nometeste[7]="MW";
nometeste[8]="TF";
nometeste[9]="MC";
nometeste[10]="TP";
nometeste[11]="RD";
nometeste[12]="AC";
nometeste[13]="WW";
String [] nometesteExtenso=new String [ntestes];
nometesteExtenso[0]="Mann-Kendall";
nometesteExtenso[1]="Spearman’s Rho";
nometesteExtenso[2]="Linear Regression";
nometesteExtenso[3]="Teste T";
nometesteExtenso[4]="Distribution CUSUM";
nometesteExtenso[5]="Cumulative Deviation";
nometesteExtenso[6]="Worsley Lik. Ratio";
nometesteExtenso[7]="Rank-Sum (Mann-Whitney)";
nometesteExtenso[8]="Teste F";
nometesteExtenso[9]="Median Crossing";
nometesteExtenso[10]="Turning Points";
nometesteExtenso[11]="Rank Difference";
nometesteExtenso[12]="Autocorrelation";
nometesteExtenso[13]="Wald-Wolfowitz";
Object[][] result = new Object[ntestes][11];
for (int i = 0; i < ntestes; i++){
if(i<3){
result[i][0]="Mudança gradual (Tendência)";
}else if(i>=3 && i<7){
result[i][0]="Mudança brusca (Média)";
}else if(i==7){
result[i][0]="Mudança brusca (Mediana)";
}else if(i==8){
result[i][0]="Mudança brusca (Variância)";
}else{
result[i][0]="Teste de Independência";
}
DecimalFormatSymbols dc = new DecimalFormatSymbols();
dc.setDecimalSeparator('.');
String strange = "0.00";
DecimalFormat myFormatter = new DecimalFormat(strange, dc);
for(int j=0;j<resultestacionaridade.size();j++){
result[i][1]=nometesteExtenso[i];
if(resultestacionaridade.get(j).getNometeste().equals(nometeste[i])){
System.out.println(resultestacionaridade.get(j).getEstatteste());
Double valteste=resultestacionaridade.get(j).getEstatteste();
result[i][2]=myFormatter.format(resultestacionaridade.get(j).getEstatteste());
result[i][3]=myFormatter.format(resultestacionaridade.get(j).getPvalue());
result[i][5]=myFormatter.format(resultestacionaridade.get(j).getValorcriticoteste());
result[i][4]=resultestacionaridade.get(j).getMetodoObterValCritico();
result[i][6]=resultestacionaridade.get(j).getResultadoteste();
result[i][7]=resultestacionaridade.get(j).getResultadoDescritivoTeste();
String campo2="";
if(valteste.isNaN()){
campo2="-99999.0";
}else{
campo2=myFormatter.format(resultestacionaridade.get(j).getEstatteste());
}
String campo3=myFormatter.format(resultestacionaridade.get(j).getPvalue());
String campo5=myFormatter.format(resultestacionaridade.get(j).getValorcriticoteste());
result[i][2]=Double.parseDouble(campo2);
result[i][3]=Double.parseDouble(campo3);
result[i][5]=Double.parseDouble(campo5);
if(i<3){
result[i][8]=resultestacionaridade.get(j).getSentidoTendencia();
result[i][9]=-99999.0;
result[i][10]="-99999.0";
}else if(i>=3 && i<9){
result[i][8]="-99999.0";
String campo9=String.valueOf(resultestacionaridade.get(j).getAnoMudanca());
result[i][9]=Double.parseDouble(campo9);
result[i][10]=resultestacionaridade.get(j).getSentidoMediaRecente();
}else {
result[i][8]="-99999.0";
result[i][9]=-99999.0;
result[i][10]="-99999.0";
}
break;
}else{
result[i][2]=-99999.0;
result[i][3]=-99999.0;
result[i][5]=-99999.0;
result[i][4]="-99999.0";
result[i][6]="-99999.0";
result[i][7]="-99999.0";
if(i<3){
result[i][8]="-99999.0";
result[i][9]=-99999.0;
result[i][10]="-99999.0";
}else if(i>=3 && i<9){
result[i][8]="-99999.0";
result[i][9]=-99999.0;
result[i][10]="-99999.0";
}else {
result[i][8]="-99999.0";
result[i][9]=-99999.0;
result[i][10]="-99999.0";
}
}
}
//2,3,5,9
}
return result;
}
public Object[][] setDadosResEstac_MK(ArrayList<ResultEstacionaridade> resultestacionaridade) {
int ntestes=1;
String [] nometeste=new String [ntestes];
nometeste[0]="MK";
/*nometeste[1]="SR";
nometeste[2]="LR";
nometeste[3]="TT";
nometeste[4]="DC";
nometeste[5]="CD";
nometeste[6]="WR";
nometeste[7]="MW";
nometeste[8]="TF";
nometeste[9]="MC";
nometeste[10]="TP";
nometeste[11]="RD";
nometeste[12]="AC";
nometeste[13]="WW";*/
String [] nometesteExtenso=new String [ntestes];
nometesteExtenso[0]="Mann-Kendall";
/*nometesteExtenso[1]="Spearman’s Rho";
nometesteExtenso[2]="Linear Regression";
nometesteExtenso[3]="Teste T";
nometesteExtenso[4]="Distribution CUSUM";
nometesteExtenso[5]="Cumulative Deviation";
nometesteExtenso[6]="Worsley Lik. Ratio";
nometesteExtenso[7]="Rank-Sum (Mann-Whitney)";
nometesteExtenso[8]="Teste F";
nometesteExtenso[9]="Median Crossing";
nometesteExtenso[10]="Turning Points";
nometesteExtenso[11]="Rank Difference";
nometesteExtenso[12]="Autocorrelation";
nometesteExtenso[13]="Wald-Wolfowitz";*/
Object[][] result = new Object[ntestes][11];
for (int i = 0; i < ntestes; i++){
if(i<3){
result[i][0]="Mudança gradual (Tendência)";
}else if(i>=3 && i<7){
result[i][0]="Mudança brusca (Média)";
}else if(i==7){
result[i][0]="Mudança brusca (Mediana)";
}else if(i==8){
result[i][0]="Mudança brusca (Variância)";
}else{
result[i][0]="Teste de Independência";
}
DecimalFormatSymbols dc = new DecimalFormatSymbols();
dc.setDecimalSeparator('.');
String strange = "0.00";
DecimalFormat myFormatter = new DecimalFormat(strange, dc);
for(int j=0;j<resultestacionaridade.size();j++){
result[i][1]=nometesteExtenso[i];
if(resultestacionaridade.get(j).getNometeste().equals(nometeste[i])){
System.out.println(resultestacionaridade.get(j).getEstatteste());
Double valteste=resultestacionaridade.get(j).getEstatteste();
result[i][2]=myFormatter.format(resultestacionaridade.get(j).getEstatteste());
result[i][3]=myFormatter.format(resultestacionaridade.get(j).getPvalue());
result[i][5]=myFormatter.format(resultestacionaridade.get(j).getValorcriticoteste());
result[i][4]=resultestacionaridade.get(j).getMetodoObterValCritico();
result[i][6]=resultestacionaridade.get(j).getResultadoteste();
result[i][7]=resultestacionaridade.get(j).getResultadoDescritivoTeste();
String campo2="";
if(valteste.isNaN()){
campo2="-99999.0";
}else{
campo2=myFormatter.format(resultestacionaridade.get(j).getEstatteste());
}
String campo3=myFormatter.format(resultestacionaridade.get(j).getPvalue());
String campo5=myFormatter.format(resultestacionaridade.get(j).getValorcriticoteste());
result[i][2]=Double.parseDouble(campo2);
result[i][3]=Double.parseDouble(campo3);
result[i][5]=Double.parseDouble(campo5);
if(i<3){
result[i][8]=resultestacionaridade.get(j).getSentidoTendencia();
result[i][9]=-99999.0;
result[i][10]="-99999.0";
}else if(i>=3 && i<9){
result[i][8]="-99999.0";
String campo9=String.valueOf(resultestacionaridade.get(j).getAnoMudanca());
result[i][9]=Double.parseDouble(campo9);
result[i][10]=resultestacionaridade.get(j).getSentidoMediaRecente();
}else {
result[i][8]="-99999.0";
result[i][9]=-99999.0;
result[i][10]="-99999.0";
}
break;
}else{
result[i][2]=-99999.0;
result[i][3]=-99999.0;
result[i][5]=-99999.0;
result[i][4]="-99999.0";
result[i][6]="-99999.0";
result[i][7]="-99999.0";
if(i<3){
result[i][8]="-99999.0";
result[i][9]=-99999.0;
result[i][10]="-99999.0";
}else if(i>=3 && i<9){
result[i][8]="-99999.0";
result[i][9]=-99999.0;
result[i][10]="-99999.0";
}else {
result[i][8]="-99999.0";
result[i][9]=-99999.0;
result[i][10]="-99999.0";
}
}
}
//2,3,5,9
}
return result;
}
@Override
public void propertyChange(PropertyChangeEvent evt) {
// TODO Auto-generated method stub
}
public JFileChooser getChooser() {
return chooser;
}
public void setChooser(JFileChooser chooser) {
this.chooser = chooser;
}
public JFileChooser getChooser_xlsx() {
return chooser_xlsx;
}
public void setChooser_xlsx(JFileChooser chooser_xlsx) {
this.chooser_xlsx = chooser_xlsx;
}
public ExtensionFileFilter getFilter_xlsx() {
return filter_xlsx;
}
public void setFilter_xlsx(ExtensionFileFilter filter_xlsx) {
this.filter_xlsx = filter_xlsx;
}
}
<file_sep># TrendDetectionStreamflowBrazil-API-Java
[](https://zenodo.org/badge/latestdoi/491789566)
Java sample code for Brazilian Streamflow Trend Analysis
#Build and run instructions
Follow these steps
1. Download and extract the Trend-detection-in-annual-streamflow-extremes-in-Brazil source code zip file from GIT hub
2. Eclipse IDE is required to run the Trend-detection-in-annual-streamflow-extremes-in-Brazil project, please download the same from https://www.eclipse.org/downloads/
3. If JDK is not installed, download & install latest jdk from http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html
4. Open the eclipse IDE and click on File->Import

5. Select “File System” option and click next

6. Select the root directory option and browse for the extracted code, an example illustration is shown below. Click Finish

7. The code along with the project should appear as below in the eclipse IDE

8. Eclipse should now build the project with no errors.
9. To run the sample right click on the file MainTrendDetectionStreamflowBrazil_Workbench.java, select Debug-As, and select Java Application. The graphical user interface like the image below should appear.

<file_sep>package gui.tableResultTrendTeste;
import java.awt.Color;
import java.awt.Dimension;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.ArrayList;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JDesktopPane;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.Border;
import javax.swing.table.TableColumn;
import types.ResultEstacionaridade;
import types.SimulationDataExtremos;
import util.ExcelAdapter;
public class PanelResultEstacTableAllGauges extends JPanel{
private SimulationDataExtremos simulationData;
private static final long serialVersionUID = 1L;
private JDesktopPane panelButtons;
private JTable tblDailyData;
private JButton btnChart;
private JButton btnClose;
private JFileChooser chooser;
//ArrayList<ResultEstacionaridade> resultestacionaridade;
public PanelResultEstacTableAllGauges(SimulationDataExtremos simulationData){
this.simulationData = simulationData;
// this.resultestacionaridade=resultestacionaridade;
this.createAndShowGUI();
}
private void createAndShowGUI() {
this.setBounds(100, 200, 900, 270);
this.setBackground(Color.LIGHT_GRAY);
this.setLayout(null);
this.insertDataIntoTable();
//this.pack();
}
private void insertDataIntoTable() {
String[] columnNames = new String[11];
columnNames[0] = "Gauge Code";
columnNames[1] = "Trend Test";
columnNames[2] = "Test Statistics";
columnNames[3] = "Pvalue (%)";
columnNames[4] = "Critical Value Method";
columnNames[5] = "Critical Value";
columnNames[6] = "Result";
columnNames[7] = "Description Result";
columnNames[8] = "Trend";
columnNames[9] = "Year Shift";
columnNames[10] = "Mean";
Object[][] data = this.setDailyData();
this.tblDailyData = new JTable(data, columnNames);
ExcelAdapter exetbl=new ExcelAdapter(this.tblDailyData);
for(int i = 0; i < data.length; i++){
for(int j = 0; j < data[i].length; j++ ){
if(data[i][j] != null){
String valor = data[i][j].toString();
//int colunaCerta = j - 1;
int colunaCerta = j;
//String coluna = Integer.toString(colunaCerta);
if(j == 4){
if(valor != null ){
String coluna ="Result";
RenderizaCelulaTableResultEstac celula = new RenderizaCelulaTableResultEstac(coluna);
this.tblDailyData.getColumn(this.tblDailyData.getColumnName(j)).setCellRenderer(celula);
}
}else {
String coluna =columnNames[j];
RenderizaCelulaTableResultEstac celula = new RenderizaCelulaTableResultEstac(coluna);
this.tblDailyData.getColumn(this.tblDailyData.getColumnName(j)).setCellRenderer(celula);
}
}
}
}
this.tblDailyData.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
TableColumn colYear = this.tblDailyData.getColumnModel().getColumn(0);
colYear.setPreferredWidth(180);
for (int i =1; i < 11 ; i++){
TableColumn col = this.tblDailyData.getColumnModel().getColumn(i);
if(i == 2 ||i==3 || i==5){
col.setPreferredWidth(60);
}else{
col.setPreferredWidth(100);
}
}
this.tblDailyData.setPreferredScrollableViewportSize(new Dimension(900, 270));
JScrollPane scrollPane = new JScrollPane(this.tblDailyData);
scrollPane.setBounds(20, 20, 900, 270);
scrollPane.setPreferredSize(new Dimension(900, 270));
Border border = BorderFactory.createBevelBorder(2);
scrollPane.setBorder(border);
this.add(scrollPane);
}
private Object[][] setDailyData() {
//int ntestes=14;
int ntestes=1;
String [] nometeste=new String [ntestes];
nometeste[0]="MK";
/*nometeste[1]="SR";
nometeste[2]="LR";
nometeste[3]="TT";
nometeste[4]="DC";
nometeste[5]="CD";
nometeste[6]="WR";
nometeste[7]="MW";
nometeste[8]="TF";
nometeste[9]="MC";
nometeste[10]="TP";
nometeste[11]="RD";
nometeste[12]="AC";
nometeste[13]="WW";*/
String [] nometesteExtenso=new String [ntestes];
nometesteExtenso[0]="Mann-Kendall";
/*nometesteExtenso[1]="Spearman’s Rho";
nometesteExtenso[2]="Linear Regression";
nometesteExtenso[3]="Teste T";
nometesteExtenso[4]="Distribution CUSUM";
nometesteExtenso[5]="Cumulative Deviation";
nometesteExtenso[6]="Worsley Lik. Ratio";
nometesteExtenso[7]="Rank-Sum (Mann-Whitney)";
nometesteExtenso[8]="Teste F";
nometesteExtenso[9]="Median Crossing";
nometesteExtenso[10]="Turning Points";
nometesteExtenso[11]="Rank Difference";
nometesteExtenso[12]="Autocorrelation";
nometesteExtenso[13]="Wald-Wolfowitz";*/
ArrayList<ResultEstacionaridade> resultestacionaridade =new ArrayList<ResultEstacionaridade>();
ArrayList<String> codigos =new ArrayList<String>();
for(int i=0;i<this.simulationData.getVariaveisHidr().size();i++){
if(this.simulationData.getVariaveisHidr().get(i).isSelecionada() && this.simulationData.getVariaveisHidr().get(i).isAtendeRestricaoTamMin()) {
String codigo=this.simulationData.getVariaveisHidr().get(i).getInvhidro().getEstacao_codigo();
codigos.add(codigo);
resultestacionaridade.add(this.simulationData.getVariaveisHidr().get(i).getResultestacionaridade().get(0));
}
}
Object[][] result = new Object[resultestacionaridade.size()][11];
for (int i = 0; i < resultestacionaridade.size(); i++){
//result[i][0]="gradual change(trend)";
result[i][0]=codigos.get(i);
/*if(i<3){
result[i][0]="Mudança gradual (Tendência)";
}else if(i>=3 && i<7){
result[i][0]="Mudança brusca (Média)";
}else if(i==7){
result[i][0]="Mudança brusca (Mediana)";
}else if(i==8){
result[i][0]="Mudança brusca (Variância)";
}else{
result[i][0]="Teste de Independência";
}*/
DecimalFormatSymbols dc = new DecimalFormatSymbols();
dc.setDecimalSeparator('.');
String strange = "0.00";
DecimalFormat myFormatter = new DecimalFormat(strange, dc);
// for(int j=0;j<this.resultestacionaridade.size();j++){
result[i][1]=nometesteExtenso[0];
//if(this.resultestacionaridade.get(j).getNometeste().equals(nometeste[i])){
result[i][2]=myFormatter.format(resultestacionaridade.get(i).getEstatteste());
result[i][3]=myFormatter.format(resultestacionaridade.get(i).getPvalue());
result[i][4]=resultestacionaridade.get(i).getMetodoObterValCritico();
result[i][5]=myFormatter.format(resultestacionaridade.get(i).getValorcriticoteste());
result[i][6]=resultestacionaridade.get(i).getResultadoteste();
result[i][7]=resultestacionaridade.get(i).getResultadoDescritivoTeste();
//if(i<3){
result[i][8]=resultestacionaridade.get(i).getSentidoTendencia();
result[i][9]="";
result[i][10]="";
//}else if(i>=3 && i<9){
//result[i][8]="";
//result[i][9]=String.valueOf(this.resultestacionaridade.get(j).getAnoMudanca());
// result[i][10]=this.resultestacionaridade.get(j).getSentidoMediaRecente();
// }else {
// result[i][8]="";
// result[i][9]="";
// result[i][10]="";
// }
//}
//}
}
return result;
}
}
<file_sep>package util;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics;
import types.DadoTemporal;
import types.SerieTemporal;
public class ST_pegarEstatisticasDescritivasDaSerieAnualConfigurada {
/**
* Serie anual entre um ano inicial e um ano final
* @param anoIni
* @param anoFim
* @param st
* @return
*/
public static DescriptiveStatistics dsc(int anoIni,int anoFim,SerieTemporal st) {
//Map<String,DadoTemporal> dados = new HashMap<String,DadoTemporal>();
DescriptiveStatistics dsc = new DescriptiveStatistics();
Map<String,DadoTemporal> mapaStrDadosger=st.getMapaStrDados();
int [] ano =ST_verificarAno.anos(st, anoIni, anoFim);
if(ano[0]>ano[1])return dsc;
Set<String> chaves = mapaStrDadosger.keySet();
for (String data : chaves){
String [] datastr=data.split("/");
int anoatual=Integer.parseInt(datastr[2]);
Double valor = mapaStrDadosger.get(data).getValor();
if((valor != -99999 || valor > 0) && (anoatual >= ano[0]) && (anoatual <= ano[1])){
//dados.put(data,mapaStrDadosger.get(data));
dsc.addValue(valor);
}
}
return dsc;
}
public static DescriptiveStatistics dscPosterior(int anosepara,SerieTemporal st) {
Map<String,DadoTemporal> dados = new HashMap<String,DadoTemporal>();
DescriptiveStatistics dsc = new DescriptiveStatistics();
Set<String> chaves = st.getMapaStrDados().keySet();
for (String data : chaves){
String [] datastr=data.split("/");
int anoatual=Integer.parseInt(datastr[2]);
Double valor = st.getMapaStrDados().get(data).getValor();
if((valor != -99999 || valor > 0) && (anoatual >= anosepara)){
//dados.put(data,st.getMapaStrDados().get(data));
dsc.addValue(valor);
}
}
return dsc;
}
public static DescriptiveStatistics dscAnterior(int anosepara,SerieTemporal st) {
Map<String,DadoTemporal> dados = new HashMap<String,DadoTemporal>();
DescriptiveStatistics dsc = new DescriptiveStatistics();
Set<String> chaves = st.getMapaStrDados().keySet();
for (String data : chaves){
String [] datastr=data.split("/");
int anoatual=Integer.parseInt(datastr[2]);
Double valor = st.getMapaStrDados().get(data).getValor();
if((valor != -99999 || valor > 0) && (anoatual < anosepara)){
//dados.put(data,st.getMapaStrDados().get(data));
dsc.addValue(valor);
}
}
return dsc;
}
public static DescriptiveStatistics dsc(SerieTemporal st) {
Map<String,DadoTemporal> dados = new HashMap<String,DadoTemporal>();
DescriptiveStatistics dsc = new DescriptiveStatistics();
Set<String> chaves = st.getMapaStrDados().keySet();
for (String data : chaves){
Double valor = st.getMapaStrDados().get(data).getValor();
if(valor != -99999. || valor > 0){
//dados.put(data,st.getMapaStrDados().get(data));
dsc.addValue(valor);
}else{
System.out.println();
}
}
return dsc;
}
public static DescriptiveStatistics dsc(Map<String,DadoTemporal> serieMapa) {
DescriptiveStatistics dsc = new DescriptiveStatistics();
Set<String> chaves = serieMapa.keySet();
for (String data : chaves){
Double valor = serieMapa.get(data).getValor();
if(valor != -99999. || valor > 0){
dsc.addValue(valor);
}
}
return dsc;
}
public static DescriptiveStatistics dsc(ArrayList<DadoTemporal> dados) {
//Map<String,DadoTemporal> dados = new HashMap<String,DadoTemporal>();
DescriptiveStatistics dsc = new DescriptiveStatistics();
// Set<String> chaves = st.getMapaStrDados().keySet();
//for (String data : chaves){
for (int i=0;i<dados.size();i++){
Double valor = dados.get(i).getValor();
if(valor != -99999 || valor > 0){
//dados.put(data,st.getMapaStrDados().get(data));
dsc.addValue(valor);
}
}
return dsc;
}
public static DescriptiveStatistics dscGeral (ArrayList<Double> dados) {
DescriptiveStatistics dsc = new DescriptiveStatistics();
for (int i=0;i<dados.size();i++){
Double valor = dados.get(i);
if(valor != -99999 || valor > 0){
dsc.addValue(valor);
}
}
return dsc;
}
public static DescriptiveStatistics dsc(int anoIni,int anoFim,Map<String,DadoTemporal> serieMapa) {
DescriptiveStatistics dsc = new DescriptiveStatistics();
int [] ano =ST_verificarAno.anos(serieMapa, anoIni, anoFim);
Set<String> chaves = serieMapa.keySet();
for (String data : chaves){
String [] datastr=data.split("/");
int anoatual=Integer.parseInt(datastr[2]);
Double valor = serieMapa.get(data).getValor();
if((valor != -99999 || valor > 0) && (anoatual >= ano[0]) && (anoatual <= ano[1])){
dsc.addValue(valor);
}
}
return dsc;
}
}
<file_sep>package gui;
import org.jfree.ui.RefineryUtilities;
import types.SimulationDataExtremos;
public class MainTrendDetectionStreamflowBrazil_Workbench {
private void panelExecuteGuiMain() {
SimulationDataExtremos simulationData=new SimulationDataExtremos();
simulationData.setTipoSerieHidroMaximos("SF");
simulationData.setTipoSerieFalhaEstacionaridade(1);
simulationData.setTolFalhaMax(0.0);
simulationData.setMesIniEstacionaridade(1);
simulationData.setMesFimEstacionaridade(12);
simulationData.setTamMinSerietotEstacionaridade(30);
simulationData.setCodEstatisticaSelecionadaEstacionaridade(1);
simulationData.setAnoIniSubConjunto(-99999);
simulationData.setAnoFimSubConjunto(-99999);
simulationData.setConsiderarAutoCorrelacao(true);
simulationData.setFazerFDR(true);
simulationData.setFazerFDRClassico(true);
simulationData.setTipoEstatisticaSelecionadaEstacionaridade("Annual Streamflow (m³/s)");
final PanelTrendDetectionStreamflowBrazil panelSimulaExtremosUNB = new PanelTrendDetectionStreamflowBrazil(simulationData);
panelSimulaExtremosUNB.setVisible(true);
panelSimulaExtremosUNB.pack();
RefineryUtilities.centerFrameOnScreen(panelSimulaExtremosUNB);
/*final PanelTestesEstatisticos panelTestesEstatisticos = new PanelTestesEstatisticos(simulationData);
panelTestesEstatisticos.setVisible(true);
panelTestesEstatisticos.pack();
RefineryUtilities.centerFrameOnScreen(panelTestesEstatisticos);*/
}
public static void main(String[] args) {
MainTrendDetectionStreamflowBrazil_Workbench mainTrend=new MainTrendDetectionStreamflowBrazil_Workbench();
mainTrend.panelExecuteGuiMain();
}
}
<file_sep>package types;
public class ResultOutliers {
private DadoTemporal outlier;
private String codigo;
private String metodo;
private double linf;
private double lsup;
private String tipo;
private String datastr;
private boolean excluirSerie;
public DadoTemporal getOutlier() {
return outlier;
}
public void setOutlier(DadoTemporal outlier) {
this.outlier = outlier;
}
public String getCodigo() {
return codigo;
}
public void setCodigo(String codigo) {
this.codigo = codigo;
}
public String getMetodo() {
return metodo;
}
public void setMetodo(String metodo) {
this.metodo = metodo;
}
public double getLinf() {
return linf;
}
public void setLinf(double linf) {
this.linf = linf;
}
public double getLsup() {
return lsup;
}
public void setLsup(double lsup) {
this.lsup = lsup;
}
public String getTipo() {
return tipo;
}
public void setTipo(String tipo) {
this.tipo = tipo;
}
public String getDatastr() {
return datastr;
}
public void setDatastr(String datastr) {
this.datastr = datastr;
}
public boolean isExcluirSerie() {
return excluirSerie;
}
public void setExcluirSerie(boolean excluirSerie) {
this.excluirSerie = excluirSerie;
}
}
<file_sep>package util;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import types.DadoTemporal;
import types.SerieTemporal;
/*import org.snirh.extremos_unb.tipos.DadoTemporal;
import org.snirh.extremos_unb.tipos.SerieTemporal;
import org.snirh.extremos_unb.util.Dif;
import org.snirh.extremos_unb.util.MediaMovel;
import org.snirh.extremos_unb.util.ST_PegarSerieTemporalDeDadosTemporais;
import org.snirh.extremos_unb.util.ST_estatisticaDaSerie;
import org.snirh.extremos_unb.util.ST_pegarDadosCriterioFalha;
import org.snirh.extremos_unb.util.ST_pegarDataFinalFiltroMes;
import org.snirh.extremos_unb.util.ST_pegarDataInicioFiltroMes;
import org.snirh.extremos_unb.util.ST_pegarDataMesFinalFiltroMes;
import org.snirh.extremos_unb.util.ST_valoresDiariosIntervaloDataSemFalhaMapa;
import org.snirh.extremos_unb.util.ST_verificarAno;
import org.snirh.extremos_unb.util.ST_verificarNdiasFevereiro;*/
public class ST_PegarSerieDiariaMediaMovel {
private int tamMM;
private int tipoSerie;
private double tolFalha;
private int mesIni;
private int mesFim;
private int anoIni;
private int anoFim;
private SerieTemporal st;
public ST_PegarSerieDiariaMediaMovel(int tamMM,int tipoSerie,double tolFalha,int mesIni, int mesFim,int anoIni,int anoFim,SerieTemporal st){
this.tamMM=tamMM;
this.tipoSerie=tipoSerie;
this.tolFalha=tolFalha;
this.mesIni=mesIni;
this.mesFim=mesFim;
this.anoIni=anoIni;
this.anoFim=anoFim;
this.st=st;
}
public ST_PegarSerieDiariaMediaMovel(int tamMM,int tipoSerie,double tolFalha,int mesIni, int mesFim,SerieTemporal st){
this.tamMM=tamMM;
this.tipoSerie=tipoSerie;
this.tolFalha=tolFalha;
this.mesIni=mesIni;
this.mesFim=mesFim;
this.anoIni=-99999;
this.anoFim=-99999;
this.st=st;
}
public ST_PegarSerieDiariaMediaMovel(int tamMM,int tipoSerie,double tolFalha,SerieTemporal st){
this.tamMM=tamMM;
this.tipoSerie=tipoSerie;
this.tolFalha=tolFalha;
this.mesIni=1;
this.mesFim=12;
this.anoIni=-99999;
this.anoFim=-99999;
this.st=st;
}
public ST_PegarSerieDiariaMediaMovel(int tamMM,SerieTemporal st){
this.tamMM=tamMM;
this.tipoSerie=1;//sem falha SF
this.tolFalha=0.0;
this.mesIni=1;
this.mesFim=12;
this.anoIni=-99999;
this.anoFim=-99999;
this.st=st;
}
public ST_PegarSerieDiariaMediaMovel(int tamMM,int tipoSerie,double tolFalha,Map<String,DadoTemporal> dadosMapa){
this.tamMM=tamMM;
this.tipoSerie=tipoSerie;
this.tolFalha=tolFalha;
this.mesIni=1;
this.mesFim=12;
this.anoIni=-99999;
this.anoFim=-99999;
this.st=ST_PegarSerieTemporalDeDadosTemporais.st(dadosMapa);
}
public ST_PegarSerieDiariaMediaMovel(int tamMM,Map<String,DadoTemporal> dadosMapa){
this.tamMM=tamMM;
this.tipoSerie=1;//sem falha SF
this.tolFalha=0.0;
this.mesIni=1;
this.mesFim=12;
this.anoIni=-99999;
this.anoFim=-99999;
this.st=ST_PegarSerieTemporalDeDadosTemporais.st(dadosMapa);
}
public Map<String,DadoTemporal> executar(){
int codEstatistica=6;//minimas
Map<String,DadoTemporal> mapaStrDadosger=this.st.getMapaStrDados();
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Map<String,DadoTemporal> dadosEstatistica = new HashMap<String,DadoTemporal>();
int [] ano =ST_verificarAno.anos(this.st, this.anoIni, this.anoFim);
if(ano[0]>ano[1])return dadosEstatistica;
Date utilDateIni =ST_pegarDataInicioFiltroMes.data(this.st, this.mesIni, this.mesFim,ano[0],ano[1]);
Date utilDateIniMesFim =ST_pegarDataMesFinalFiltroMes.data(this.st, this.mesIni, this.mesFim, ano[0],ano[1]);
Date utilDateFim = ST_pegarDataFinalFiltroMes.data(this.st,this.mesIni, this.mesFim,ano[0],ano[1]);
Calendar clStart =Calendar.getInstance();
Calendar clEnd =Calendar.getInstance();
Calendar clStartfim =Calendar.getInstance();
clEnd.setTime(utilDateFim);
clStart.setTime(utilDateIni);
clStartfim.setTime(utilDateIniMesFim);
int ndiasSemFalha=Dif.dias(utilDateIni, utilDateIniMesFim)+1;
double toleranciaMaxFalha=this.tolFalha;
Map<String,DadoTemporal> dados_anual;
Map<String,DadoTemporal> dados_filtro;
Map<String,DadoTemporal> dados_anual_comFalha;
ArrayList<String> serieData = new ArrayList<String>();
while (clStartfim.get(Calendar.YEAR) != clEnd.get(Calendar.YEAR)) {
dados_anual=new HashMap<String,DadoTemporal>();
dados_anual=ST_valoresDiariosIntervaloDataSemFalhaMapa.serieDiaria(utilDateIni, utilDateIniMesFim,mapaStrDadosger);
double percentualDeFalhas=100.0-((dados_anual.size()*1.0/ndiasSemFalha*1.0)*100.0);
//dados_anual_comFalha=valoresIntervaloDataComFalhaMapa(utilDateIni, utilDateIniMesFim,mapaStrDadosger);
dados_filtro =ST_pegarDadosCriterioFalha.mapa(dados_anual, this.tipoSerie, toleranciaMaxFalha, percentualDeFalhas);
Double valorEstatistica=-99999.0;
DadoTemporal valorEstDT = null;
if(dados_filtro.size() > 0){
ArrayList<Double> serie=new ArrayList<Double>();
Set<String> chaves = dados_filtro.keySet();
double [] valor=new double[chaves.size()];
String [] datas=new String[chaves.size()];
int i1=0;
ArrayList<DadoTemporal> dadostemp=new ArrayList<DadoTemporal>();
for (String data : chaves){
DadoTemporal dado = dados_filtro.get(data);
dadostemp.add(dado);
}
Collections.sort(dadostemp);
for (int j=0;j<dadostemp.size();j++){
valor[j]=dadostemp.get(j).getValor();
datas[j]=formatter.format(dadostemp.get(j).getData());
}
MediaMovel mm = new MediaMovel(valor,this.tamMM,datas);
double [] serieMM = mm.calcmedia();
ArrayList<String> datasMM = mm.getDatamovel();
Map<String,DadoTemporal> dadosMMmapa = new HashMap<String,DadoTemporal>();
for (int j=0;j<datasMM.size();j++){
DadoTemporal dado = new DadoTemporal();
dado.setValor(serieMM [j]);
Date dini;
try {
dini = formatter.parse(datasMM.get(j));
dado.setData(dini);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
dadosMMmapa.put(datasMM.get(j), dado);
}
System.out.println("Media Movel = "+this.tamMM);
valorEstDT=ST_estatisticaDaSerie.estatCod(codEstatistica,dadosMMmapa);
valorEstatistica=valorEstDT.getValor();
}
String datastr =formatter.format(utilDateIni);
if(valorEstatistica != -99999.0){
DadoTemporal dt = new DadoTemporal();
if(valorEstDT.getData()==null){
dt.setData(utilDateIni);
}else{
datastr =formatter.format(valorEstDT.getData());
dt.setData(valorEstDT.getData());
}
dt.setValor(valorEstatistica);
dadosEstatistica.put(datastr,dt);
serieData.add(datastr);
}
clStart.add(Calendar.YEAR, 1);
clStartfim.add(Calendar.YEAR, 1);
utilDateIni=clStart.getTime();
utilDateIniMesFim=clStartfim.getTime();
if(this.mesFim == 2){
utilDateIniMesFim=ST_verificarNdiasFevereiro.verificarNdiasFevereiro(utilDateIniMesFim, this.mesFim);
}
ndiasSemFalha=Dif.dias(utilDateIni, utilDateIniMesFim)+1;
}
dados_anual=new HashMap<String,DadoTemporal>();
dados_anual=ST_valoresDiariosIntervaloDataSemFalhaMapa.serieDiaria(utilDateIni, utilDateIniMesFim,mapaStrDadosger);
double percentualDeFalhas=100.0-((dados_anual.size()*1.0/ndiasSemFalha*1.0)*100.0);
//dados_anual_comFalha=valoresIntervaloDataComFalhaMapa(utilDateIni, utilDateIniMesFim,mapaStrDadosger);
dados_filtro =ST_pegarDadosCriterioFalha.mapa(dados_anual, this.tipoSerie, toleranciaMaxFalha, percentualDeFalhas);
Double valorEstatistica=-99999.0;
DadoTemporal valorEstDT = null;
if(dados_filtro.size() > 0){
ArrayList<Double> serie=new ArrayList<Double>();
Set<String> chaves = dados_filtro.keySet();
double [] valor=new double[chaves.size()];
String [] datas=new String[chaves.size()];
int i1=0;
ArrayList<DadoTemporal> dadostemp=new ArrayList<DadoTemporal>();
for (String data : chaves){
DadoTemporal dado = dados_filtro.get(data);
dadostemp.add(dado);
}
Collections.sort(dadostemp);
for (int j=0;j<dadostemp.size();j++){
valor[j]=dadostemp.get(j).getValor();
datas[j]=formatter.format(dadostemp.get(j).getData());
}
MediaMovel mm = new MediaMovel(valor,this.tamMM,datas);
double [] serieMM = mm.calcmedia();
ArrayList<String> datasMM = mm.getDatamovel();
Map<String,DadoTemporal> dadosMMmapa = new HashMap<String,DadoTemporal>();
for (int j=0;j<datasMM.size();j++){
DadoTemporal dado = new DadoTemporal();
dado.setValor(serieMM [j]);
Date dini;
try {
dini = formatter.parse(datasMM.get(j));
dado.setData(dini);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
dadosMMmapa.put(datasMM.get(j), dado);
}
valorEstDT=ST_estatisticaDaSerie.estatCod(codEstatistica,dadosMMmapa);
valorEstatistica=valorEstDT.getValor();
}
String datastr =formatter.format(utilDateIni);
if(valorEstatistica != -99999.0){
DadoTemporal dt = new DadoTemporal();
if(valorEstDT.getData()==null){
dt.setData(utilDateIni);
}else{
datastr =formatter.format(valorEstDT.getData());
dt.setData(valorEstDT.getData());
}
dt.setValor(valorEstatistica);
dadosEstatistica.put(datastr,dt);
serieData.add(datastr);
}
//this.setSerieDatas(serieData);
return dadosEstatistica;
}
public static Map<String,DadoTemporal> executar(int tamMM,int tipoSerie,double tolFalha,int mesIni, int mesFim,int anoIni,int anoFim,SerieTemporal st) {
int codEstatistica=6;//minimas
Map<String,DadoTemporal> mapaStrDadosger=st.getMapaStrDados();
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Map<String,DadoTemporal> dadosEstatistica = new HashMap<String,DadoTemporal>();
int [] ano =ST_verificarAno.anos(st, anoIni, anoFim);
if(ano[0]>ano[1])return dadosEstatistica;
Date utilDateIni =ST_pegarDataInicioFiltroMes.data(st, mesIni, mesFim,ano[0],ano[1]);
Date utilDateIniMesFim =ST_pegarDataMesFinalFiltroMes.data(st, mesIni, mesFim, ano[0],ano[1]);
Date utilDateFim = ST_pegarDataFinalFiltroMes.data(st,mesIni, mesFim,ano[0],ano[1]);
Calendar clStart =Calendar.getInstance();
Calendar clEnd =Calendar.getInstance();
Calendar clStartfim =Calendar.getInstance();
clEnd.setTime(utilDateFim);
clStart.setTime(utilDateIni);
clStartfim.setTime(utilDateIniMesFim);
int ndiasSemFalha=Dif.dias(utilDateIni, utilDateIniMesFim)+1;
double toleranciaMaxFalha=tolFalha;
Map<String,DadoTemporal> dados_anual;
Map<String,DadoTemporal> dados_filtro;
Map<String,DadoTemporal> dados_anual_comFalha;
ArrayList<String> serieData = new ArrayList<String>();
while (clStartfim.get(Calendar.YEAR) != clEnd.get(Calendar.YEAR)) {
dados_anual=new HashMap<String,DadoTemporal>();
dados_anual=ST_valoresDiariosIntervaloDataSemFalhaMapa.serieDiaria(utilDateIni, utilDateIniMesFim,mapaStrDadosger);
double percentualDeFalhas=100.0-((dados_anual.size()*1.0/ndiasSemFalha*1.0)*100.0);
//dados_anual_comFalha=valoresIntervaloDataComFalhaMapa(utilDateIni, utilDateIniMesFim,mapaStrDadosger);
dados_filtro =ST_pegarDadosCriterioFalha.mapa(dados_anual, tipoSerie, toleranciaMaxFalha, percentualDeFalhas);
Double valorEstatistica=-99999.0;
DadoTemporal valorEstDT = null;
if(dados_filtro.size() > 0){
ArrayList<Double> serie=new ArrayList<Double>();
Set<String> chaves = dados_filtro.keySet();
double [] valor=new double[chaves.size()];
String [] datas=new String[chaves.size()];
int i1=0;
ArrayList<DadoTemporal> dadostemp=new ArrayList<DadoTemporal>();
for (String data : chaves){
DadoTemporal dado = dados_filtro.get(data);
dadostemp.add(dado);
}
Collections.sort(dadostemp);
for (int j=0;j<dadostemp.size();j++){
valor[j]=dadostemp.get(j).getValor();
datas[j]=formatter.format(dadostemp.get(j).getData());
}
MediaMovel mm = new MediaMovel(valor,tamMM,datas);
double [] serieMM = mm.calcmedia();
ArrayList<String> datasMM = mm.getDatamovel();
Map<String,DadoTemporal> dadosMMmapa = new HashMap<String,DadoTemporal>();
for (int j=0;j<datasMM.size();j++){
DadoTemporal dado = new DadoTemporal();
dado.setValor(serieMM [j]);
Date dini;
try {
dini = formatter.parse(datasMM.get(j));
dado.setData(dini);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
dadosMMmapa.put(datasMM.get(j), dado);
}
System.out.println("Media Movel = "+tamMM);
valorEstDT=ST_estatisticaDaSerie.estatCod(codEstatistica,dadosMMmapa);
valorEstatistica=valorEstDT.getValor();
}
String datastr =formatter.format(utilDateIni);
if(valorEstatistica != -99999.0){
DadoTemporal dt = new DadoTemporal();
if(valorEstDT.getData()==null){
dt.setData(utilDateIni);
}else{
datastr =formatter.format(valorEstDT.getData());
dt.setData(valorEstDT.getData());
}
dt.setValor(valorEstatistica);
dadosEstatistica.put(datastr,dt);
serieData.add(datastr);
}
clStart.add(Calendar.YEAR, 1);
clStartfim.add(Calendar.YEAR, 1);
utilDateIni=clStart.getTime();
utilDateIniMesFim=clStartfim.getTime();
if(mesFim == 2){
utilDateIniMesFim=ST_verificarNdiasFevereiro.verificarNdiasFevereiro(utilDateIniMesFim, mesFim);
}
ndiasSemFalha=Dif.dias(utilDateIni, utilDateIniMesFim)+1;
}
dados_anual=new HashMap<String,DadoTemporal>();
dados_anual=ST_valoresDiariosIntervaloDataSemFalhaMapa.serieDiaria(utilDateIni, utilDateIniMesFim,mapaStrDadosger);
double percentualDeFalhas=100.0-((dados_anual.size()*1.0/ndiasSemFalha*1.0)*100.0);
//dados_anual_comFalha=valoresIntervaloDataComFalhaMapa(utilDateIni, utilDateIniMesFim,mapaStrDadosger);
dados_filtro =ST_pegarDadosCriterioFalha.mapa(dados_anual, tipoSerie, toleranciaMaxFalha, percentualDeFalhas);
Double valorEstatistica=-99999.0;
DadoTemporal valorEstDT = null;
if(dados_filtro.size() > 0){
ArrayList<Double> serie=new ArrayList<Double>();
Set<String> chaves = dados_filtro.keySet();
double [] valor=new double[chaves.size()];
String [] datas=new String[chaves.size()];
int i1=0;
ArrayList<DadoTemporal> dadostemp=new ArrayList<DadoTemporal>();
for (String data : chaves){
DadoTemporal dado = dados_filtro.get(data);
dadostemp.add(dado);
}
Collections.sort(dadostemp);
for (int j=0;j<dadostemp.size();j++){
valor[j]=dadostemp.get(j).getValor();
datas[j]=formatter.format(dadostemp.get(j).getData());
}
MediaMovel mm = new MediaMovel(valor,tamMM,datas);
double [] serieMM = mm.calcmedia();
ArrayList<String> datasMM = mm.getDatamovel();
Map<String,DadoTemporal> dadosMMmapa = new HashMap<String,DadoTemporal>();
for (int j=0;j<datasMM.size();j++){
DadoTemporal dado = new DadoTemporal();
dado.setValor(serieMM [j]);
Date dini;
try {
dini = formatter.parse(datasMM.get(j));
dado.setData(dini);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
dadosMMmapa.put(datasMM.get(j), dado);
}
valorEstDT=ST_estatisticaDaSerie.estatCod(codEstatistica,dadosMMmapa);
valorEstatistica=valorEstDT.getValor();
}
String datastr =formatter.format(utilDateIni);
if(valorEstatistica != -99999.0){
DadoTemporal dt = new DadoTemporal();
if(valorEstDT.getData()==null){
dt.setData(utilDateIni);
}else{
datastr =formatter.format(valorEstDT.getData());
dt.setData(valorEstDT.getData());
}
dt.setValor(valorEstatistica);
dadosEstatistica.put(datastr,dt);
serieData.add(datastr);
}
//this.setSerieDatas(serieData);
return dadosEstatistica;
}
}
<file_sep>package io.graph;
import javax.swing.JFrame;
import gui.PanelTrendDetectionStreamflowBrazil;
import types.SimulationDataExtremos;
/*import org.snirh.extremos_unb.deteccao.gui.GuiGraficoAnual;
import org.snirh.extremos_unb.deteccao.gui.PanelImportarDados;
import org.snirh.extremos_unb.tipos.SimulationDataExtremos;*/
public class FrameGraficosAnual extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private SimulationDataExtremos simulationData;
private GuiGraficoAnual guiResultgraficodistrib;
private PanelTrendDetectionStreamflowBrazil pid;
public FrameGraficosAnual(SimulationDataExtremos simulationData){
super("Graphs of Selected Series");
this.simulationData = simulationData;
this.createMainFrame();
this.createTabbedPane();
this.setTitle("Graphs of Selected Series - "+this.simulationData.getnSeriesSelecionadas()+" Selected Series");
}
private void createMainFrame() {
this.setBounds(100, 100, 1000, 700);
}
private void createTabbedPane() {
this.guiResultgraficodistrib = new GuiGraficoAnual (this.simulationData);
this.setContentPane(this.guiResultgraficodistrib);
}
public FrameGraficosAnual(SimulationDataExtremos simulationData,PanelTrendDetectionStreamflowBrazil pid){
super("Graphs of Gauge Series");
this.pid=pid;
this.simulationData = simulationData;
this.createMainFrame();
this.createTabbedPane(this.pid);
}
private void createTabbedPane(PanelTrendDetectionStreamflowBrazil pid) {
this.guiResultgraficodistrib = new GuiGraficoAnual (this.simulationData,this.pid,this);
//this.setContentPane(this.guiResultgraficodistrib);
}
}
<file_sep>package io;
import java.io.File;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.ArrayList;
/*import org.snirh.extremos_unb.deteccao.testes.ResultEstacionaridade;
import org.snirh.extremos_unb.tipos.VariavelHidrologica;
import org.snirh.extremos_unb.util.Messages;
import org.snirh.extremos_unb.util.SNIRHPlugInSettings;
import org.snirh.extremos_unb.util.SalvarLayerDiretorio;*/
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.Point;
import com.vividsolutions.jump.feature.AttributeType;
import com.vividsolutions.jump.feature.BasicFeature;
import com.vividsolutions.jump.feature.Feature;
import com.vividsolutions.jump.feature.FeatureCollection;
import com.vividsolutions.jump.feature.FeatureDataset;
import com.vividsolutions.jump.feature.FeatureSchema;
import com.vividsolutions.jump.workbench.model.Category;
import com.vividsolutions.jump.workbench.model.Layer;
import com.vividsolutions.jump.workbench.plugin.PlugInContext;
import gui.PanelTrendDetectionStreamflowBrazil;
import gui.tableResultTrendTeste.GuiResultAllGauges;
import types.ResultEstacionaridade;
import types.SNIRHPlugInSettings;
import types.SimulationDataExtremos;
import types.VariavelHidrologica;
import util.Messages;
public class DesenharShapesResultadoDetalhado {
private SimulationDataExtremos simulationData;
private PanelTrendDetectionStreamflowBrazil pnt;
//protected PlugInContext context = null;
//protected Category category = null;
public DesenharShapesResultadoDetalhado(SimulationDataExtremos simulationData,PanelTrendDetectionStreamflowBrazil pnt) {
this.simulationData = simulationData;
this.pnt=pnt;
}
public void execute(String testeEscolhido,String dir){
int ncolum=8;
String[] columnNames = new String[ncolum];
columnNames[0] = "TTE";
columnNames[1] = "TES";
columnNames[2] = "ETE";
columnNames[3] = "VCT";
columnNames[4] = "RES";
columnNames[5] = "VCB";
columnNames[6] = "REB";
columnNames[7] = "DIR"; //DIRECAO DA MUDANCA
int ntestes=14;
String [] nometeste=new String [ntestes];
nometeste[0]="MK";
nometeste[1]="SR";
nometeste[2]="LR";
nometeste[3]="TT";
nometeste[4]="DC";
nometeste[5]="CD";
nometeste[6]="WR";
nometeste[7]="MW";
nometeste[8]="TF";
nometeste[9]="MC";
nometeste[10]="TP";
nometeste[11]="RD";
nometeste[12]="AC";
nometeste[13]="WW";
int ntipotestes=4;
String [] nometipoteste=new String [ntipotestes];
nometipoteste[0]="Mudança gradual (Tendência)";
nometipoteste[1]="Mudança brusca (Média e Mediana)";
nometipoteste[2]="Mudança brusca (Variância)";
nometipoteste[3]="Teste de Independência";
//this.context= new
/*this.category = context.getLayerManager().getCategory(SNIRHPlugInSettings.resultLayerCategory());
if (this.category == null) {
this.context.getLayerManager().addCategory(
SNIRHPlugInSettings.resultLayerCategory(), 0);
this.category = this.context.getLayerManager().getCategory(
SNIRHPlugInSettings.resultLayerCategory());
}*/
FeatureSchema fs = new FeatureSchema();
fs.addAttribute("Geometry", AttributeType.GEOMETRY);
fs.addAttribute("ID", AttributeType.STRING);
fs.addAttribute("CODIGO", AttributeType.STRING);
fs.addAttribute("LONG", AttributeType.DOUBLE);
fs.addAttribute("LAT", AttributeType.DOUBLE);
fs.addAttribute("AREA", AttributeType.DOUBLE);
for (int i = 0; i < ntestes; i++) {
for (int k = 0; k < ncolum; k++) {
if(k <=1 || k==4 || k==6 || k==7){
fs.addAttribute(nometeste[i]+"_"+columnNames[k], AttributeType.STRING);
}else{
fs.addAttribute(nometeste[i]+"_"+columnNames[k], AttributeType.DOUBLE);
}
}
}
//FeatureDataset featureDataset = new FeatureDataset(fs);
//Layer layer = context.addLayer(category.getName(), "Res_Estac_Total", featureDataset);
//FeatureCollection fd = layer.getFeatureCollectionWrapper();
//FeatureSchema fs2 = fd.getFeatureSchema();
//ArrayList<Feature> features = new ArrayList<Feature>();
String nomearq=this.simulationData.getFilenameBD();
if(nomearq.contains(".dat")){
nomearq=nomearq.replace(".dat","");
}
//String dir=this.simulationData.getDataDirBD();
//String dir="C:\\OpenJump150\\PROJETO E IMPLEMENTACOES\\EXTREMOS_UNB\\resultados\\RH_SFR\\CLASSICO\\shapes\\";
//String dir="C:\\OpenJump150\\PROJETO E IMPLEMENTACOES\\EXTREMOS_UNB\\resultados\\RH_SFR\\PW\\shapes\\";
//String dir="C:\\OpenJump150\\PROJETO E IMPLEMENTACOES\\EXTREMOS_UNB\\resultados\\RH_SFR\\TFPW\\shapes\\";
//this.simulationData.setFilenameBD(filename);
//this.simulationData.setDataDirBD(dir);
FeatureDataset featureDataset_MK_NS = new FeatureDataset(fs);
//Layer layer_MK_NS = context.addLayer(category.getName(),nomearq+"_"+testeEscolhido+"_NS", featureDataset_MK_NS);
Layer layer_MK_NS =new Layer();
layer_MK_NS.setFeatureCollection(featureDataset_MK_NS);
//FeatureCollection fd_MK_NS = new FeatureCollection();
//layer_MK_NS.set
FeatureCollection fd_MK_NS = layer_MK_NS.getFeatureCollectionWrapper();
FeatureSchema fs2_MK_NS = fd_MK_NS.getFeatureSchema();
ArrayList<Feature> featuresMK_NS = new ArrayList<Feature>();
FeatureDataset featureDataset_MK_S = new FeatureDataset(fs);
//Layer layer_MK_S = context.addLayer(category.getName(), nomearq+"_"+testeEscolhido+"_S", featureDataset_MK_S);
Layer layer_MK_S=new Layer();
layer_MK_S.setFeatureCollection(featureDataset_MK_S);
FeatureCollection fd_MK_S = layer_MK_S.getFeatureCollectionWrapper();
FeatureSchema fs2_MK_S = fd_MK_S.getFeatureSchema();
ArrayList<Feature> featuresMK_S = new ArrayList<Feature>();
ArrayList<Feature> featuresMK_CS = new ArrayList<Feature>();
ArrayList<Feature> featuresMK_DS = new ArrayList<Feature>();
ArrayList<Feature> featuresMK_CS_S = new ArrayList<Feature>();
ArrayList<Feature> featuresMK_DS_S = new ArrayList<Feature>();
for(int igauges=0;igauges<this.simulationData.getVariaveisHidr().size();igauges++){
if(this.simulationData.getVariaveisHidr().get(igauges).isSelecionada() && this.simulationData.getVariaveisHidr().get(igauges).getResultestacionaridade().size() > 0) {
String codigo=String.valueOf(this.simulationData.getVariaveisHidr().get(igauges).getInvhidro().getEstacao_codigo());
ArrayList<ResultEstacionaridade> resultestacionaridade =new ArrayList<ResultEstacionaridade>();
resultestacionaridade = this.simulationData.getVariaveisHidr().get(igauges).getResultestacionaridade();
VariavelHidrologica vhid =this.simulationData.getVariaveisHidr().get(igauges);
// if (layer==null || vhid ==null) return;
GeometryFactory geomFact = new GeometryFactory();
//Coordinate coord = new Coordinate(vhid.getInvhidro().getPosition().getX(), vhid.getInvhidro().getPosition().getY());
Coordinate coord = new Coordinate(vhid.getInvhidro().getLongitude(), vhid.getInvhidro().getLatitude());
Point p = geomFact.createPoint(coord);
BasicFeature featMK = new BasicFeature(fs2_MK_NS);
featMK.setGeometry(p);
featMK.setAttribute("ID", igauges);
featMK.setAttribute("LONG", vhid.getInvhidro().getLongitude());
featMK.setAttribute("LAT", vhid.getInvhidro().getLatitude());
featMK.setAttribute("CODIGO", vhid.getInvhidro().getEstacao_codigo());
featMK.setAttribute("AREA", vhid.getInvhidro().getAreaDrenagem());
//featMK.
DecimalFormatSymbols dc = new DecimalFormatSymbols();
dc.setDecimalSeparator('.');
String strange = "0.00";
DecimalFormat myFormatter = new DecimalFormat(strange, dc);
for (int i = 0; i < ntestes; i++) {
if(nometeste[i] == testeEscolhido){
featMK.setAttribute(nometeste[i]+"_"+columnNames[0], nometipoteste[0]);
}
for(int j=0;j<resultestacionaridade.size();j++){
if(resultestacionaridade.get(j).getNometeste().equals(nometeste[i])){
if(nometeste[i] == testeEscolhido){
featMK.setAttribute(nometeste[i]+"_"+columnNames[2], resultestacionaridade.get(j).getEstatteste());
featMK.setAttribute(nometeste[i]+"_"+columnNames[3], resultestacionaridade.get(j).getValorcriticoteste());
featMK.setAttribute(nometeste[i]+"_"+columnNames[4], resultestacionaridade.get(j).getResultadoteste());
if(resultestacionaridade.get(j).getSentidoTendencia() == null){
featMK.setAttribute(nometeste[i]+"_"+columnNames[7],resultestacionaridade.get(j).getSentidoMediaRecente());
}else{
featMK.setAttribute(nometeste[i]+"_"+columnNames[7],resultestacionaridade.get(j).getSentidoTendencia());
}
}
}
}
}
String resMK=(String) featMK.getAttribute(testeEscolhido+"_"+columnNames[4]);
String resMKDIR=(String) featMK.getAttribute(testeEscolhido+"_"+columnNames[7]);
//String resMK=(String) featMK.getAttribute("MK"+"_"+columnNames[4]);
//String resMKDIR=(String) featMK.getAttribute("MK"+"_"+columnNames[7]);
if(resMK == null){
System.out.println(igauges);
}
if(!resMK.equals("NS")){
System.out.println(igauges);
}
if(resMK.equals("S(1.0)") || resMK.equals("S(5.0)")){
featuresMK_S.add(featMK);
}else{
featuresMK_NS.add(featMK);
}
//Saulo 11/08/2016
if(resMKDIR == null){
System.out.println();
}else{
if(resMKDIR.equals("Crescente") || resMKDIR.equals("Maior")){
featuresMK_CS.add(featMK);
}else{
featuresMK_DS.add(featMK);
}
}
if(resMKDIR == null){
System.out.println();
}else{
if(resMK.equals("S(1.0)") || resMK.equals("S(5.0)") && (resMKDIR.equals("Crescente") || resMKDIR.equals("Maior"))){
featuresMK_CS_S.add(featMK);
}else if(resMK.equals("S(1.0)") || resMK.equals("S(5.0)") && (resMKDIR.equals("Decrescente") || resMKDIR.equals("Menor"))){
featuresMK_DS_S.add(featMK);
}
}
}
}
if(featuresMK_NS.size() != 0){
layer_MK_NS.setEditable(true);
fd_MK_NS.clear();
fd_MK_NS.addAll(featuresMK_NS);
layer_MK_NS.setEditable(false);
}
if(featuresMK_S.size() != 0){
layer_MK_S.setEditable(true);
fd_MK_S.clear();
fd_MK_S.addAll(featuresMK_S);
layer_MK_S.setEditable(false);
}
Layer layer_MK_CS = new Layer();
if(featuresMK_CS.size() != 0){
FeatureDataset featureDataset_MK_CS = new FeatureDataset(fs);
//layer_MK_CS = context.addLayer(category.getName(), nomearq+"_"+testeEscolhido+"_CS", featureDataset_MK_CS);
layer_MK_CS.setFeatureCollection(featureDataset_MK_CS);
FeatureCollection fd_MK_CS = layer_MK_CS.getFeatureCollectionWrapper();
FeatureSchema fs2_MK_CS = fd_MK_CS.getFeatureSchema();
layer_MK_CS.setEditable(true);
fd_MK_CS.clear();
fd_MK_CS.addAll(featuresMK_CS);
layer_MK_CS.setEditable(false);
}
Layer layer_MK_DS=new Layer();
if(featuresMK_DS.size() != 0){
FeatureDataset featureDataset_MK_DS = new FeatureDataset(fs);
//layer_MK_DS = context.addLayer(category.getName(), nomearq+"_"+testeEscolhido+"_DS", featureDataset_MK_DS);
layer_MK_DS.setFeatureCollection(featureDataset_MK_DS);
FeatureCollection fd_MK_DS = layer_MK_DS.getFeatureCollectionWrapper();
FeatureSchema fs2_MK_DS = fd_MK_DS.getFeatureSchema();
layer_MK_DS.setEditable(true);
fd_MK_DS.clear();
fd_MK_DS.addAll(featuresMK_DS);
layer_MK_DS.setEditable(false);
}
Layer layer_MK_CS_S =new Layer();
if(featuresMK_CS_S.size() != 0){
FeatureDataset featureDataset_MK_CS_S = new FeatureDataset(fs);
//layer_MK_CS_S = context.addLayer(category.getName(), nomearq+"_"+testeEscolhido+"_CS_S", featureDataset_MK_CS_S);
layer_MK_CS_S.setFeatureCollection(featureDataset_MK_CS_S);
FeatureCollection fd_MK_CS_S = layer_MK_CS_S.getFeatureCollectionWrapper();
FeatureSchema fs2_MK_CS_S = fd_MK_CS_S.getFeatureSchema();
layer_MK_CS_S.setEditable(true);
fd_MK_CS_S.clear();
fd_MK_CS_S.addAll(featuresMK_CS_S);
layer_MK_CS_S.setEditable(false);
}
Layer layer_MK_DS_S =new Layer();
if(featuresMK_DS_S.size() != 0){
FeatureDataset featureDataset_MK_DS_S = new FeatureDataset(fs);
//layer_MK_DS_S = context.addLayer(category.getName(), nomearq+"_"+testeEscolhido+"_DS_S", featureDataset_MK_DS_S);
layer_MK_DS_S.setFeatureCollection(featureDataset_MK_DS_S);
FeatureCollection fd_MK_DS_S = layer_MK_DS_S.getFeatureCollectionWrapper();
FeatureSchema fs2_MK_DS_S = fd_MK_DS_S.getFeatureSchema();
layer_MK_DS_S.setEditable(true);
fd_MK_DS_S.clear();
fd_MK_DS_S.addAll(featuresMK_DS_S);
layer_MK_DS_S.setEditable(false);
}
boolean salvarArquivo=true;
if(salvarArquivo){
File fdir= new File(dir);
String nomeShape="layer_MK_NS";
try {
if(layer_MK_NS != null){
SalvarLayerDiretorio.save(layer_MK_NS, fdir,nomeShape);
}
nomeShape="layer_MK_S";
if(layer_MK_S != null){
SalvarLayerDiretorio.save(layer_MK_S, fdir,nomeShape);
}
nomeShape="layer_MK_CS";
if(layer_MK_CS != null){
SalvarLayerDiretorio.save(layer_MK_CS, fdir,nomeShape);
}
nomeShape="layer_MK_DS";
if(layer_MK_DS != null){
SalvarLayerDiretorio.save(layer_MK_DS, fdir,nomeShape);
}
nomeShape="layer_MK_CS_S";
if(layer_MK_CS_S != null){
SalvarLayerDiretorio.save(layer_MK_CS_S, fdir,nomeShape);
}
nomeShape="layer_MK_DS_S";
if(layer_MK_DS_S != null){
SalvarLayerDiretorio.save(layer_MK_DS_S, fdir,nomeShape);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Messages.informMsg("Layer (arquivo .shp) criado com sucesso");
}
}
<file_sep>package io;
import java.io.File;
import javax.swing.filechooser.FileFilter;
public class ExtensionFileFilter extends FileFilter {
private String extension;
private String description;
public ExtensionFileFilter(String extension, String description){
if (!extension.startsWith(".")) extension = "." + extension;
this.extension = extension;
this.description = description;
}
public boolean accept (File f){
return f.getName().toLowerCase().endsWith(this.extension)
|| f.isDirectory();
}
public String getDescription(){
return this.description;
}
public String getExtension(){
return this.extension;
}
}
<file_sep>package util;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import types.DadoTemporal;
public class ST_valoresMensaisIntervaloDataSemFalhaMapa {
public static Map<String,DadoTemporal> serieMensal(Date dini, Date dfim,Map<String,DadoTemporal> mapaStrDadosger) {
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Map<String,DadoTemporal> dados=new HashMap<String,DadoTemporal>();
Calendar clStart =Calendar.getInstance();
clStart.setTime(dini);
Calendar clEnd =Calendar.getInstance();
clEnd.setTime(dfim);
int count = 0;
while (clStart.get(Calendar.MONTH) != clEnd.get(Calendar.MONTH) || clStart.get(Calendar.YEAR) != clEnd.get(Calendar.YEAR)) {
Date datual=clStart.getTime();
String datastratual =formatter.format(datual);
if(mapaStrDadosger.containsKey(datastratual)){
if(mapaStrDadosger.get(datastratual).getValor() != -99999 || mapaStrDadosger.get(datastratual).getValor() > 0){
//System.out.println(datastratual + " - "+ mapaStrDadosger.get(datastratual).getValor());
// dados.add(mapaStrDadosger.get(datastratual).getValor());
String datastr =formatter.format(mapaStrDadosger.get(datastratual).getData());
dados.put(datastr, mapaStrDadosger.get(datastratual));
count++;
}
}
clStart.add(Calendar.MONTH, 1);
}
/**
* incluir o valor da data final do intervalo
*/
Date datual=clStart.getTime();
String datastratual =formatter.format(datual);
if(mapaStrDadosger.containsKey(datastratual)){
if(mapaStrDadosger.get(datastratual).getValor() != -99999 || mapaStrDadosger.get(datastratual).getValor() > 0){
//dados.add(mapaStrDadosger.get(datastratual).getValor());
String datastr =formatter.format(mapaStrDadosger.get(datastratual).getData());
dados.put(datastr, mapaStrDadosger.get(datastratual));
}
}
return dados;
}
}
<file_sep>package util;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import types.DadoTemporal;
public class ST_valoresDiariosIntervaloDataSemFalhaMapa {
public static Map<String,DadoTemporal> serieDiaria(Date dini, Date dfim,Map<String,DadoTemporal> mapaStrDadosger) {
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Map<String,DadoTemporal> dados=new HashMap<String,DadoTemporal>();
Calendar clStart =Calendar.getInstance();
clStart.setTime(dini);
Calendar clEnd =Calendar.getInstance();
clEnd.setTime(dfim);
int count = 0;
while (clStart.get(Calendar.DAY_OF_MONTH) != clEnd.get(Calendar.DAY_OF_MONTH) || clStart.get(Calendar.MONTH) != clEnd.get(Calendar.MONTH) || clStart.get(Calendar.YEAR) != clEnd.get(Calendar.YEAR)) {
Date datual=clStart.getTime();
String datastratual =formatter.format(datual);
if(mapaStrDadosger.containsKey(datastratual)){
//saulo 11/10/2017
//if(mapaStrDadosger.get(datastratual).getValor() != -99999 || mapaStrDadosger.get(datastratual).getValor() > 0){
if(mapaStrDadosger.get(datastratual).getValor() >= 0.0){
if(mapaStrDadosger.get(datastratual).getValor() == 0){
System.out.println();
}
// System.out.println(datastratual + " - "+ mapaStrDadosger.get(datastratual).getValor());
// dados.add(mapaStrDadosger.get(datastratual).getValor());
String datastr =formatter.format(mapaStrDadosger.get(datastratual).getData());
dados.put(datastr, mapaStrDadosger.get(datastratual));
count++;
}/*else{
String datastr =datastratual;
DadoTemporal dt=new DadoTemporal();
dt.setData(datual);
dt.setValor(-99999.0);
dados.put(datastr,dt);
}*/
}/*else{
String datastr =datastratual;
DadoTemporal dt=new DadoTemporal();
dt.setData(datual);
dt.setValor(-99999.0);
dados.put(datastr,dt);
}*/
clStart.add(Calendar.DAY_OF_YEAR, 1);
}
/**
* incluir o valor da data final do intervalo
*/
Date datual=clStart.getTime();
String datastratual =formatter.format(datual);
if(mapaStrDadosger.containsKey(datastratual)){
//saulo 11/10/2017
//if(mapaStrDadosger.get(datastratual).getValor() != -99999 || mapaStrDadosger.get(datastratual).getValor() > 0){
if(mapaStrDadosger.get(datastratual).getValor() >= 0.0){
String datastr =formatter.format(mapaStrDadosger.get(datastratual).getData());
dados.put(datastr, mapaStrDadosger.get(datastratual));
}/*else{
String datastr =datastratual;
DadoTemporal dt=new DadoTemporal();
dt.setData(datual);
dt.setValor(-99999.0);
dados.put(datastr,dt);
}*/
}/*else{
String datastr =datastratual;
DadoTemporal dt=new DadoTemporal();
dt.setData(datual);
dt.setValor(-99999.0);
dados.put(datastr,dt);
}*/
return dados;
}
public static ArrayList<DadoTemporal> serieDiariaArray(Date dini, Date dfim,Map<String,DadoTemporal> mapaStrDadosger) {
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
ArrayList<DadoTemporal> dados=new ArrayList<DadoTemporal>();
Calendar clStart =Calendar.getInstance();
clStart.setTime(dini);
Calendar clEnd =Calendar.getInstance();
clEnd.setTime(dfim);
int count = 0;
while (clStart.get(Calendar.DAY_OF_MONTH) != clEnd.get(Calendar.DAY_OF_MONTH) || clStart.get(Calendar.MONTH) != clEnd.get(Calendar.MONTH) || clStart.get(Calendar.YEAR) != clEnd.get(Calendar.YEAR)) {
Date datual=clStart.getTime();
String datastratual =formatter.format(datual);
if(mapaStrDadosger.containsKey(datastratual)){
//saulo 11/10/2017
//if(mapaStrDadosger.get(datastratual).getValor() != -99999 || mapaStrDadosger.get(datastratual).getValor() > 0){
if(mapaStrDadosger.get(datastratual).getValor() >= 0.0){
System.out.println(datastratual + " - "+ mapaStrDadosger.get(datastratual).getValor());
// dados.add(mapaStrDadosger.get(datastratual).getValor());
String datastr =formatter.format(mapaStrDadosger.get(datastratual).getData());
dados.add(mapaStrDadosger.get(datastratual));
count++;
}
}
clStart.add(Calendar.DAY_OF_YEAR, 1);
}
/**
* incluir o valor da data final do intervalo
*/
Date datual=clStart.getTime();
String datastratual =formatter.format(datual);
if(mapaStrDadosger.containsKey(datastratual)){
//saulo 11/10/2017
//if(mapaStrDadosger.get(datastratual).getValor() != -99999 || mapaStrDadosger.get(datastratual).getValor() > 0){
if(mapaStrDadosger.get(datastratual).getValor() >= 0.0){
String datastr =formatter.format(mapaStrDadosger.get(datastratual).getData());
dados.add(mapaStrDadosger.get(datastratual));
}
}
return dados;
}
public static Map<String,DadoTemporal> serieDiariaValoresNaoNulos(Date dini, Date dfim,Map<String,DadoTemporal> mapaStrDadosger) {
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Map<String,DadoTemporal> dados=new HashMap<String,DadoTemporal>();
Calendar clStart =Calendar.getInstance();
clStart.setTime(dini);
Calendar clEnd =Calendar.getInstance();
clEnd.setTime(dfim);
int count = 0;
while (clStart.get(Calendar.DAY_OF_MONTH) != clEnd.get(Calendar.DAY_OF_MONTH) || clStart.get(Calendar.MONTH) != clEnd.get(Calendar.MONTH) || clStart.get(Calendar.YEAR) != clEnd.get(Calendar.YEAR)) {
Date datual=clStart.getTime();
String datastratual =formatter.format(datual);
if(mapaStrDadosger.containsKey(datastratual)){
//saulo 11/10/2017
//if(mapaStrDadosger.get(datastratual).getValor() != -99999 || mapaStrDadosger.get(datastratual).getValor() > 0){
if(mapaStrDadosger.get(datastratual).getValor() >= 0.0){
if(mapaStrDadosger.get(datastratual).getValor() == 0){
System.out.println();
}
System.out.println(datastratual + " - "+ mapaStrDadosger.get(datastratual).getValor());
// dados.add(mapaStrDadosger.get(datastratual).getValor());
String datastr =formatter.format(mapaStrDadosger.get(datastratual).getData());
dados.put(datastr, mapaStrDadosger.get(datastratual));
count++;
}
}
clStart.add(Calendar.DAY_OF_YEAR, 1);
}
/**
* incluir o valor da data final do intervalo
*/
Date datual=clStart.getTime();
String datastratual =formatter.format(datual);
if(mapaStrDadosger.containsKey(datastratual)){
//saulo 11/10/2017
//if(mapaStrDadosger.get(datastratual).getValor() != -99999 || mapaStrDadosger.get(datastratual).getValor() > 0){
if(mapaStrDadosger.get(datastratual).getValor() >= 0.0){
//dados.add(mapaStrDadosger.get(datastratual).getValor());
String datastr =formatter.format(mapaStrDadosger.get(datastratual).getData());
dados.put(datastr, mapaStrDadosger.get(datastratual));
}/*else{
String datastr =datastratual;
DadoTemporal dt=new DadoTemporal();
dt.setData(datual);
dt.setValor(-99999.0);
dados.put(datastr,dt);
}*/
}/*else{
String datastr =datastratual;
DadoTemporal dt=new DadoTemporal();
dt.setData(datual);
dt.setValor(-99999.0);
dados.put(datastr,dt);
}*/
return dados;
}
}
<file_sep>package tests.autocorrelationApproaches;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import tests.MannKendallTest;
import types.DadoTemporal;
public class VC {
/**
* Variance correct
*/
/**
* <NAME> (1998)
* @param amostra
* @return
*/
public double executar_CF1 (Map<String,DadoTemporal> serieMapa) {
double CF=1;
ArrayList<DadoTemporal> dadostot = new ArrayList<DadoTemporal>();
Set<String> chavesMax = serieMapa.keySet();
for (String data : chavesMax){
DadoTemporal dado = serieMapa.get(data);
dadostot.add(dado);
}
//
Collections.sort(dadostot);
FuncaoAutoCorrelacaoAnual facOriginal =new FuncaoAutoCorrelacaoAnual(dadostot);
double r1Original=facOriginal.correlLagMapa(1);
//int n=facOriginal.getSeries1().length+1;
int n=dadostot.size();
double r1AmostralCorrigido=(n*r1Original+2)/(n-4);
String resultado=TesteCorrelacaoLag1Tradicional.executar(r1AmostralCorrigido, n);
if(resultado.equals("NS")) {
return CF;
}
double r1Rank=PegarRoRankDadoRoSerie.executar(r1AmostralCorrigido);
double termo1=2.0/((n)*(n-1)*(n-2));
double termo2=(n-1)*(n-2)*(n-3)*r1Rank;
CF=1.0+termo1*termo2;
return CF;
}
public double executar_CF2 (Map<String,DadoTemporal> serieMapa) {
double CF=1;
ArrayList<DadoTemporal> dadostot = new ArrayList<DadoTemporal>();
Set<String> chavesMax = serieMapa.keySet();
for (String data : chavesMax){
DadoTemporal dado = serieMapa.get(data);
dadostot.add(dado);
}
//
Collections.sort(dadostot);
FuncaoAutoCorrelacaoAnual facOriginal =new FuncaoAutoCorrelacaoAnual(dadostot);
double r1Original=facOriginal.correlLagMapa(1);
int n=facOriginal.getSeries1().length+1;
//int n=dadostot.size();
double r1AmostralCorrigido=(n*r1Original+2)/(n-4);
String resultado=TesteCorrelacaoLag1Tradicional.executar(r1AmostralCorrigido, n);
if(resultado.equals("NS")) {
return CF;
}
//double r1Rank=PegarRoRankDadoRoSerie.executar(r1AmostralCorrigido);
CF=1.0+2.0*r1AmostralCorrigido-((2.0/n)*r1AmostralCorrigido);
return CF;
}
public double executar_CF3 (Map<String,DadoTemporal> serieMapa) {
double CF=1;
ArrayList<DadoTemporal> dadostot = new ArrayList<DadoTemporal>();
Set<String> chavesMax = serieMapa.keySet();
for (String data : chavesMax){
DadoTemporal dado = serieMapa.get(data);
dadostot.add(dado);
}
//
Collections.sort(dadostot);
FuncaoAutoCorrelacaoAnual facOriginal =new FuncaoAutoCorrelacaoAnual(dadostot);
double r1Original=facOriginal.correlLagMapa(1);
int n=facOriginal.getSeries1().length+1;
//int n=dadostot.size();
double r1AmostralCorrigido=(n*r1Original+2)/(n-4);
String resultado=TesteCorrelacaoLag1Tradicional.executar(r1AmostralCorrigido, n);
if(resultado.equals("NS")) {
return CF;
}
//double r1Rank=PegarRoRankDadoRoSerie.executar(r1AmostralCorrigido);
double termo1=Math.pow(r1AmostralCorrigido, (n+1));
double termo2=n*Math.pow(r1AmostralCorrigido, 2.0);
double termo3=(n-1)*r1AmostralCorrigido;
double termo4=Math.pow((r1AmostralCorrigido-1), 2.0)*n;
CF=1+2.0*((termo1*termo2*termo3)/termo4);
return CF;
}
public double executar_CF1(ArrayList<Double> amostra) {
double CF=1;
PegarRoLag1 estimarRo1=new PegarRoLag1();
estimarRo1.executar(amostra);
//double r1=estimarRo1.getR1amostral();
double r1corrigido=estimarRo1.getR1AmostralCorrigido();
int n=amostra.size();
String resultado=TesteCorrelacaoLag1Tradicional.executar(r1corrigido, n);
if(resultado.equals("NS")) {
return CF;
}
double r1Rank=PegarRoRankDadoRoSerie.executar(r1corrigido);
double termo1=2.0/((n)*(n-1)*(n-2));
double termo2=(n-1)*(n-2)*(n-3)*r1Rank;
CF=1.0+termo1*termo2;
return CF;
}
/**
* Yue e Wang (2004)
* @param amostra
* @return
*/
public double executar_CF2(ArrayList<Double> amostra) {
double CF=1;
PegarRoLag1 estimarRo1=new PegarRoLag1();
estimarRo1.executar(amostra);
//double r1=estimarRo1.getR1amostral();
double r1corrigido=estimarRo1.getR1AmostralCorrigido();
int n=amostra.size();
String resultado=TesteCorrelacaoLag1Tradicional.executar(r1corrigido, n);
if(resultado.equals("NS")) {
return CF;
}
//double r1Rank=PegarRoRankDadoRoSerie.executar(r1corrigido);
CF=1.0+2.0*r1corrigido-((2.0/n)*r1corrigido);
return CF;
}
/**
* <NAME> (1962), Lettemaier (1976) e <NAME> (2004)
* @param amostra
* @return
*/
public double executar_CF3(ArrayList<Double> amostra) {
double CF=1;
PegarRoLag1 estimarRo1=new PegarRoLag1();
estimarRo1.executar(amostra);
//double r1=estimarRo1.getR1amostral();
double r1corrigido=estimarRo1.getR1AmostralCorrigido();
int n=amostra.size();
String resultado=TesteCorrelacaoLag1Tradicional.executar(r1corrigido, n);
if(resultado.equals("NS")) {
return CF;
}
//double r1Rank=PegarRoRankDadoRoSerie.executar(r1corrigido);
double termo1=Math.pow(r1corrigido, (n+1));
double termo2=n*Math.pow(r1corrigido, 2.0);
double termo3=(n-1)*r1corrigido;
double termo4=Math.pow((r1corrigido-1), 2.0)*n;
CF=1+2.0*((termo1*termo2*termo3)/termo4);
return CF;
}
public double executar_CF4(ArrayList<Double> amostra) {
ArrayList<Double> amostraFinal=new ArrayList<Double> ();
boolean foiSignificativo=false;
MannKendallTest mkteste=new MannKendallTest(amostra);
mkteste.teste1();
double pvalueferahmk=mkteste.getPvalue();
double alfa=0.05;
if(pvalueferahmk < alfa){
foiSignificativo=true;
}
if(foiSignificativo) {
amostraFinal=this.fazerDetrend(amostra);
}else {
amostraFinal=amostra;
}
double CF=1;
PegarRoLag1 estimarRo1=new PegarRoLag1();
estimarRo1.executar(amostraFinal);
//double r1=estimarRo1.getR1amostral();
double r1corrigido=estimarRo1.getR1AmostralCorrigido();
int n=amostra.size();
String resultado=TesteCorrelacaoLag1Tradicional.executar(r1corrigido, n);
if(resultado.equals("NS")) {
return CF;
}
double r1Rank=PegarRoRankDadoRoSerie.executar(r1corrigido);
double termo1=2.0/((n)*(n-1)*(n-2));
double termo2=(n-1)*(n-2)*(n-3)*r1Rank;
CF=1.0+termo1*termo2;
return CF;
}
public double executar_CF5(ArrayList<Double> amostra) {
ArrayList<Double> amostraFinal=new ArrayList<Double> ();
boolean foiSignificativo=false;
MannKendallTest mkteste=new MannKendallTest(amostra);
mkteste.teste1();
double pvalueferahmk=mkteste.getPvalue();
double alfa=0.05;
if(pvalueferahmk < alfa){
foiSignificativo=true;
}
if(foiSignificativo) {
amostraFinal=this.fazerDetrend(amostra);
}else {
amostraFinal=amostra;
}
double CF=1;
PegarRoLag1 estimarRo1=new PegarRoLag1();
estimarRo1.executar(amostraFinal);
//double r1=estimarRo1.getR1amostral();
double r1corrigido=estimarRo1.getR1AmostralCorrigido();
int n=amostra.size();
String resultado=TesteCorrelacaoLag1Tradicional.executar(r1corrigido, n);
if(resultado.equals("NS")) {
return CF;
}
//double r1Rank=PegarRoRankDadoRoSerie.executar(r1corrigido);
CF=1.0+2.0*r1corrigido-((2.0/n)*r1corrigido);
return CF;
}
public double executar_CF6(ArrayList<Double> amostra) {
double CF=1;
PegarRoLag1 estimarRo1=new PegarRoLag1();
estimarRo1.executar(amostra);
double r1=estimarRo1.getR1amostral();
//double r1corrigido=estimarRo1.getR1AmostralCorrigido();
int n=amostra.size();
String resultado=TesteCorrelacaoLag1Tradicional.executar(r1, n);
if(resultado.equals("NS")) {
return CF;
}
double r1Rank=PegarRoRankDadoRoSerie.executar(r1);
double termo1=2.0/((n)*(n-1)*(n-2));
double termo2=(n-1)*(n-2)*(n-3)*r1Rank;
CF=1.0+termo1*termo2;
return CF;
}
public ArrayList<Double> fazerDetrend(ArrayList<Double> amostra){
ArrayList<Double> amostraDetrend=new ArrayList<Double>();
double bsen=MagnitudeTendencia.bSenDouble(amostra);
for(int i=0;i<amostra.size();i++) {
int t=i+1;
double xt=amostra.get(i);
double yt=xt-bsen*t;
amostraDetrend.add(yt);
}
return amostraDetrend;
}
}
<file_sep>package io;
import gui.PanelTrendDetectionStreamflowBrazil;
import types.ResultEstacionaridade;
import types.SimulationDataExtremos;
import types.VariavelHidrologica;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.geotools.data.DataUtilities;
import org.geotools.data.DefaultTransaction;
import org.geotools.data.Transaction;
import org.geotools.data.collection.ListFeatureCollection;
import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.data.shapefile.ShapefileDataStoreFactory;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.data.simple.SimpleFeatureStore;
import org.geotools.feature.SchemaException;
import org.geotools.feature.simple.SimpleFeatureBuilder;
import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
import org.geotools.geometry.jts.JTSFactoryFinder;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import org.geotools.swing.data.JFileDataStoreChooser;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.Point;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
public class DesenharShapesResultadoDetalhadoGeotools {
private SimulationDataExtremos simulationData;
private PanelTrendDetectionStreamflowBrazil pnt;
//protected PlugInContext context = null;
//protected Category category = null;
public DesenharShapesResultadoDetalhadoGeotools(SimulationDataExtremos simulationData,PanelTrendDetectionStreamflowBrazil pnt) {
this.simulationData = simulationData;
this.pnt=pnt;
}
public void execute(String testeEscolhido,String dir) throws SchemaException, IOException{
SimpleFeatureType TYPE=this.createFeatureTypeResultTrend();
List<SimpleFeature> featuresMK_NS = new ArrayList<>();
List<SimpleFeature> featuresMK_S = new ArrayList<>();
List<SimpleFeature> featuresMK_CS = new ArrayList<>();
List<SimpleFeature> featuresMK_DS = new ArrayList<>();
List<SimpleFeature> featuresMK_CS_S = new ArrayList<>();
List<SimpleFeature> featuresMK_DS_S = new ArrayList<>();
String filename=this.simulationData.getFilenameBD();
String filenameFinal="";
if(filename.contains(".dat")) {
filenameFinal=filename.split(".dat")[0];
}else {
filenameFinal=filename;
}
GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();
int idgauges=1;
for(int igauges=0;igauges<this.simulationData.getVariaveisHidr().size();igauges++){
boolean selGauges=this.simulationData.getVariaveisHidr().get(igauges).isSelecionada();
boolean isRecordLenght=this.simulationData.getVariaveisHidr().get(igauges).isAtendeRestricaoTamMin();
if(selGauges && isRecordLenght){
SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(TYPE);
String codigo=String.valueOf(this.simulationData.getVariaveisHidr().get(igauges).getInvhidro().getEstacao_codigo());
ArrayList<ResultEstacionaridade> resultestacionaridade =new ArrayList<ResultEstacionaridade>();
resultestacionaridade = this.simulationData.getVariaveisHidr().get(igauges).getResultestacionaridade();
VariavelHidrologica vhid =this.simulationData.getVariaveisHidr().get(igauges);
double latitude = vhid.getInvhidro().getLatitude();
double longitude = vhid.getInvhidro().getLongitude();
String gauge_code = vhid.getInvhidro().getEstacao_codigo();
int number = idgauges;
/* Longitude (= x coord) first ! */
Point point = geometryFactory.createPoint(new Coordinate(longitude, latitude));
featureBuilder.add(point);
featureBuilder.add(idgauges);
featureBuilder.add(gauge_code);
featureBuilder.add(latitude);
featureBuilder.add(longitude);
featureBuilder.add(vhid.getInvhidro().getAreaDrenagem());
featureBuilder.add("MannKendall");
featureBuilder.add(resultestacionaridade.get(0).getPvalue());
String resMK=resultestacionaridade.get(0).getResultadoteste();
String direction=resultestacionaridade.get(0).getSentidoTendencia();
featureBuilder.add(resMK);
featureBuilder.add(direction);
SimpleFeature feature = featureBuilder.buildFeature(null);
if(resMK.equals("S(1.0)") || resMK.equals("S(5.0)")|| resMK.equals("S(10.0)")){
featuresMK_S.add(feature);
}else{
featuresMK_NS.add(feature);
}
if(direction == null){
System.out.println();
}else{
if(direction.equals("Increase") || direction.equals("Maior")){
featuresMK_CS.add(feature);
}else{
featuresMK_DS.add(feature);
}
}
if(direction == null){
System.out.println();
}else{
if(resMK.equals("S(1.0)") || resMK.equals("S(5.0)") && (direction.equals("Increase") || direction.equals("Maior"))){
featuresMK_CS_S.add(feature);
}else if(resMK.equals("S(1.0)") || resMK.equals("S(5.0)") && (direction.equals("Decrease") || direction.equals("Menor"))){
featuresMK_DS_S.add(feature);
}
}
// features.add(feature);
idgauges++;
}
}
int nTypeShp=6;
String nameSHP=filenameFinal+"_MK_NS.shp";
File newFile_1= new File(dir+nameSHP); //Aqui tem que vim ja com o nome do arquivo shape
if(featuresMK_NS.size() > 0) {
this.createExportShapefile(TYPE, newFile_1, featuresMK_NS);
}
nameSHP=filenameFinal+"_MK_S.shp";
if(featuresMK_S.size() > 0) {
File newFile_2= new File(dir+nameSHP);
this.createExportShapefile(TYPE, newFile_2, featuresMK_S);
}
nameSHP=filenameFinal+"_MK_IC.shp";//increase
if(featuresMK_CS.size() > 0) {
File newFile_3= new File(dir+nameSHP);
this.createExportShapefile(TYPE, newFile_3, featuresMK_CS);
}
nameSHP=filenameFinal+"_MK_DC.shp";//decrease
if(featuresMK_DS.size() > 0) {
File newFile_4= new File(dir+nameSHP);
this.createExportShapefile(TYPE, newFile_4, featuresMK_DS);
}
nameSHP=filenameFinal+"_MK_IC_S.shp";//increase
if(featuresMK_CS_S.size() > 0) {
File newFile_5= new File(dir+nameSHP);
this.createExportShapefile(TYPE, newFile_5, featuresMK_CS_S);
}
nameSHP=filenameFinal+"_MK_DC_S.shp";//decrease
if(featuresMK_DS_S.size() > 0) {
File newFile_6= new File(dir+nameSHP);
this.createExportShapefile(TYPE, newFile_6, featuresMK_DS_S);
}
System.out.println("Final shape create");
}
public void createExportShapefile(SimpleFeatureType TYPE,File newFile,List<SimpleFeature> features) {
ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory();
Map<String, Serializable> params = new HashMap<>();
try {
params.put("url", newFile.toURI().toURL());
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
params.put("create spatial index", Boolean.TRUE);
ShapefileDataStore newDataStore = null;
try {
newDataStore = (ShapefileDataStore) dataStoreFactory.createNewDataStore(params);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*
* TYPE is used as a template to describe the file contents
*/
try {
newDataStore.createSchema(TYPE);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// docs break transaction
/*
* Write the features to the shapefile
*/
Transaction transaction = new DefaultTransaction("create");
String typeName = null;
try {
typeName = newDataStore.getTypeNames()[0];
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
SimpleFeatureSource featureSource = null;
try {
featureSource = newDataStore.getFeatureSource(typeName);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
SimpleFeatureType SHAPE_TYPE = featureSource.getSchema();
/*
* The Shapefile format has a couple limitations:
* - "the_geom" is always first, and used for the geometry attribute name
* - "the_geom" must be of type Point, MultiPoint, MuiltiLineString, MultiPolygon
* - Attribute names are limited in length
* - Not all data types are supported (example Timestamp represented as Date)
*
* Each data store has different limitations so check the resulting SimpleFeatureType.
*/
System.out.println("SHAPE:" + SHAPE_TYPE);
if (featureSource instanceof SimpleFeatureStore) {
SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource;
/*
* SimpleFeatureStore has a method to add features from a
* SimpleFeatureCollection object, so we use the ListFeatureCollection
* class to wrap our list of features.
*/
SimpleFeatureCollection collection = new ListFeatureCollection(TYPE, features);
featureStore.setTransaction(transaction);
try {
featureStore.addFeatures(collection);
transaction.commit();
} catch (Exception problem) {
problem.printStackTrace();
try {
transaction.rollback();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} finally {
try {
transaction.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//System.exit(0); // success!
} else {
System.out.println(typeName + " does not support read/write access");
// System.exit(1);
}
}
public SimpleFeatureType pegarTYPEGeotoolsSimpleFeature() throws SchemaException {
final SimpleFeatureType TYPE =
DataUtilities.createType(
"Location",
"the_geom:Point:srid=4326,"
+ // <- the geometry attribute: Point type
"name:String,"
+ // <- a String attribute
"number:Integer" // a number attribute
);
System.out.println("TYPE:" + TYPE);
return TYPE;
}
private static SimpleFeatureType createFeatureTypeResultTrend() {
SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder();
builder.setName("Location");
builder.setCRS(DefaultGeographicCRS.WGS84); // <- Coordinate reference system
// add attributes in order
builder.add("the_geom", Point.class);
builder.add("id", Integer.class);
builder.length(15).add("gauge_code", String.class); // <- 15 chars width for name field
builder.add("lat", Double.class);
builder.add("lon", Double.class);
builder.add("basin_area", Double.class);
builder.length(15).add("test", String.class);
builder.add("pvalue", Double.class);
builder.length(15).add("result", String.class);
builder.length(15).add("direction", String.class);
//builder.add("number", Integer.class);
// build the type
final SimpleFeatureType LOCATION = builder.buildFeatureType();
return LOCATION;
}
/**
* Here is how you can use a SimpleFeatureType builder to create the schema for your shapefile
* dynamically.
*
* <p>This method is an improvement on the code used in the main method above (where we used
* DataUtilities.createFeatureType) because we can set a Coordinate Reference System for the
* FeatureType and a a maximum field length for the 'name' field dddd
*/
private static SimpleFeatureType createFeatureType() {
SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder();
builder.setName("Location");
builder.setCRS(DefaultGeographicCRS.WGS84); // <- Coordinate reference system
// add attributes in order
builder.add("the_geom", Point.class);
builder.length(15).add("Name", String.class); // <- 15 chars width for name field
builder.add("number", Integer.class);
// build the type
final SimpleFeatureType LOCATION = builder.buildFeatureType();
return LOCATION;
}
private static File getNewShapeFile(File csvFile) {
String path = csvFile.getAbsolutePath();
String newPath = path.substring(0, path.length() - 4) + ".shp";
JFileDataStoreChooser chooser = new JFileDataStoreChooser("shp");
chooser.setDialogTitle("Save shapefile");
chooser.setSelectedFile(new File(newPath));
int returnVal = chooser.showSaveDialog(null);
if (returnVal != JFileDataStoreChooser.APPROVE_OPTION) {
// the user cancelled the dialog
System.exit(0);
}
File newFile = chooser.getSelectedFile();
if (newFile.equals(csvFile)) {
System.out.println("Error: cannot replace " + csvFile);
System.exit(0);
}
return newFile;
}
}
<file_sep>package tests;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import types.ResultEstacionaridade;
import types.ResultadoFDR;
import types.SimulationDataExtremos;
import util.Esco7;
import util.PegarResultadosEstacionaridadeMapa;
/*import org.snirh.extremos_unb.deteccao.testes.ResultEstacionaridade;
import org.snirh.extremos_unb.deteccao.testes.ResultadoFDR;
import org.snirh.extremos_unb.deteccao.util.PegarResultadosEstacionaridadeMapa;
import org.snirh.extremos_unb.tipos.SimulationDataExtremos;
import org.snirh.util.sort.Esco7;*/
public class DefinirFDR {
private SimulationDataExtremos simulationData;
private double nsCorrigido;
public DefinirFDR(SimulationDataExtremos simulationData){
this.simulationData= simulationData;
}
public ArrayList<ResultadoFDR> definirResultadosFDREstacaoPorTeste(String nomeTeste, double nsig){
//HashMap<String, ResultadoFDR> resultadoFDR=new HashMap<String, ResultadoFDR>();
HashMap<String,ResultEstacionaridade> resultEstacTesteEstacao =PegarResultadosEstacionaridadeMapa.executar(this.simulationData, nomeTeste);
ArrayList<ResultadoFDR>resultadoFDR=new ArrayList<ResultadoFDR>();
ArrayList<String> codigos=new ArrayList<String>();
ArrayList<Double> pvalues=new ArrayList<Double>();
Set<String> chaves = resultEstacTesteEstacao.keySet();
for (String codigo : chaves){
codigos.add(codigo);
pvalues.add(resultEstacTesteEstacao.get(codigo).getPvalue());
}
ArrayList<Integer> indArrayNovo=Esco7.ordenar(pvalues);
int iordem=1;
int n=indArrayNovo.size();
double nsCorrigido=nsig;
for(int i=0;i<indArrayNovo.size();i++){
ResultadoFDR resfdr=new ResultadoFDR();
String codigo=codigos.get(indArrayNovo.get(i));
double pvalue=pvalues.get(indArrayNovo.get(i));
double q=nsig*iordem/n;
String resTeste="NS";
if(pvalue < q){
nsCorrigido=q;
resTeste="S";
}
boolean falsoPositivo=false;
if(pvalue < nsig && resTeste.equals("NS")){
falsoPositivo=true;
}
resfdr.setCodigo(codigo);
resfdr.setOrdemi(iordem);
resfdr.setPvalue(pvalue);
resfdr.setQ(q);
resfdr.setResultFDR(resTeste);
resfdr.setFalsoPositivo(falsoPositivo);
resfdr.setResbsen(resultEstacTesteEstacao.get(codigo).getResbsen());
resultadoFDR.add(resfdr);
iordem++;
}
this.setNsCorrigido(nsCorrigido);
return resultadoFDR;
}
public HashMap<String, ResultadoFDR> definirResultadosFDREstacaoPorTesteMapa(String nomeTeste, double nsig){
HashMap<String, ResultadoFDR> resultadoFDR=new HashMap<String, ResultadoFDR>();
HashMap<String,ResultEstacionaridade> resultEstacTesteEstacao =PegarResultadosEstacionaridadeMapa.executar(this.simulationData, nomeTeste);
//ArrayList<ResultadoFDR>resultadoFDR=new ArrayList<ResultadoFDR>();
ArrayList<String> codigos=new ArrayList<String>();
ArrayList<Double> pvalues=new ArrayList<Double>();
Set<String> chaves = resultEstacTesteEstacao.keySet();
for (String codigo : chaves){
codigos.add(codigo);
pvalues.add(resultEstacTesteEstacao.get(codigo).getPvalue());
}
ArrayList<Integer> indArrayNovo=new ArrayList<Integer>();
if(pvalues.size() > 1){
indArrayNovo=Esco7.ordenar(pvalues);
}else{
indArrayNovo.add(0);
}
int iordem=1;
int n=indArrayNovo.size();
double nsCorrigido=nsig;
for(int i=0;i<indArrayNovo.size();i++){
ResultadoFDR resfdr=new ResultadoFDR();
String codigo=codigos.get(indArrayNovo.get(i));
double pvalue=pvalues.get(indArrayNovo.get(i));
double q=nsig*iordem/n;
String resTeste="NS";
if(pvalue < q){
nsCorrigido=q;
resTeste="S";
}
boolean falsoPositivo=false;
if(pvalue < nsig && resTeste.equals("NS")){
falsoPositivo=true;
}
resfdr.setCodigo(codigo);
resfdr.setOrdemi(iordem);
resfdr.setPvalue(pvalue);
resfdr.setQ(q);
resfdr.setResultFDR(resTeste);
resfdr.setFalsoPositivo(falsoPositivo);
resfdr.setResbsen(resultEstacTesteEstacao.get(codigo).getResbsen());
resultadoFDR.put(codigo, resfdr);
iordem++;
}
this.setNsCorrigido(nsCorrigido);
return resultadoFDR;
}
public HashMap<String, ResultadoFDR> definirResultadosFDREstacaoPorTesteMapa(Map<String, Map<String,ResultEstacionaridade>> resultEstacionaridadeTipo2,String nomeTeste,double nsig){
HashMap<String, ResultadoFDR> resultadoFDR=new HashMap<String, ResultadoFDR>();
HashMap<String,ResultEstacionaridade> resultEstacTesteEstacao =PegarResultadosEstacionaridadeMapa.executar(resultEstacionaridadeTipo2, nomeTeste);
//ArrayList<ResultadoFDR>resultadoFDR=new ArrayList<ResultadoFDR>();
ArrayList<String> codigos=new ArrayList<String>();
ArrayList<Double> pvalues=new ArrayList<Double>();
Set<String> chaves = resultEstacTesteEstacao.keySet();
for (String codigo : chaves){
codigos.add(codigo);
pvalues.add(resultEstacTesteEstacao.get(codigo).getPvalue());
}
ArrayList<Integer> indArrayNovo=new ArrayList<Integer>();
if(pvalues.size() > 1){
indArrayNovo=Esco7.ordenar(pvalues);
}else{
indArrayNovo.add(0);
}
int iordem=1;
int n=indArrayNovo.size();
double nsCorrigido=nsig;
for(int i=0;i<indArrayNovo.size();i++){
ResultadoFDR resfdr=new ResultadoFDR();
String codigo=codigos.get(indArrayNovo.get(i));
double pvalue=pvalues.get(indArrayNovo.get(i));
double q=nsig*iordem/n;
String resTeste="NS";
if(pvalue < q){
nsCorrigido=q;
resTeste="S";
}
boolean falsoPositivo=false;
if(pvalue < nsig && resTeste.equals("NS")){
falsoPositivo=true;
}
resfdr.setCodigo(codigo);
resfdr.setOrdemi(iordem);
resfdr.setPvalue(pvalue);
resfdr.setQ(q);
resfdr.setResultFDR(resTeste);
resfdr.setFalsoPositivo(falsoPositivo);
resfdr.setResbsen(resultEstacTesteEstacao.get(codigo).getResbsen());
resultadoFDR.put(codigo, resfdr);
iordem++;
}
this.setNsCorrigido(nsCorrigido);
return resultadoFDR;
}
public double getNsCorrigido() {
return nsCorrigido;
}
public void setNsCorrigido(double nsCorrigido) {
this.nsCorrigido = nsCorrigido;
}
}
<file_sep>package tests.autocorrelationApproaches;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.apache.commons.math3.stat.correlation.PearsonsCorrelation;
import types.DadoTemporal;
public class FuncaoAutoCorrelacaoAnual {
private double [][] seriesEmparelhadas;
private double [] series1;
private double [] series2;
private Map<String,DadoTemporal> mapaStrDados;
private Map<Integer,DadoTemporal> mapaAnoDados;
public Map<Integer, DadoTemporal> getMapaAnoDados() {
return mapaAnoDados;
}
private ArrayList<Integer>ano;
public ArrayList<Integer> getAno() {
return ano;
}
private int klag;
private int[]klags;
public FuncaoAutoCorrelacaoAnual(double [][] seriesEmparelhadas){
this.seriesEmparelhadas=seriesEmparelhadas;
int ncols=this.seriesEmparelhadas[0].length;
this.series1=new double [this.seriesEmparelhadas.length];
this.series2=new double [this.seriesEmparelhadas.length];
for (int i=0;i<this.seriesEmparelhadas.length;i++){
this.series1[i]=this.seriesEmparelhadas[i][0];
this.series2[i]=this.seriesEmparelhadas[i][1];
}
//RealMatrix matrix = MatrixUtils.createRealMatrix(this.seriesEmparelhadas);
}
public FuncaoAutoCorrelacaoAnual(double [] series1,double [] series2){
this.series1=series1;
this.series2=series2;
}
public double [] correlLags(int [] klags){
this.klags=klags;
double [] correl=new double[this.klags.length];
for (int i=0;i<this.klags.length;i++){
correl[i]=this.correlLag(this.klags[i]);
}
return correl;
}
public double correlLag(int klag){
double correl=-99999.0;
PearsonsCorrelation pcor=new PearsonsCorrelation();
correl=pcor.correlation(this.series1, this.series2);
return correl;
}
public FuncaoAutoCorrelacaoAnual(ArrayList<DadoTemporal>dados){
Map<Integer,DadoTemporal> mapaAnoDados=new HashMap<Integer,DadoTemporal>();
/**
* Saulo - 25/08/2016 - Correção para nao repetir ano (quando for usado ano hidrologico por exemplo)
*/
Collections.sort(dados);
ArrayList<Integer>ano=new ArrayList<Integer>();
int i1verificaAno=0;
for(int i=0;i<dados.size();i++){
String data =dados.get(i).getDataStr();
String [] datastr=data.split("/");
Integer anoatual=Integer.parseInt(datastr[2]);
/**
* Saulo - 06/05/2020 - corrigir pra quando tiver falha ele nao verifica o ano repetido
*/
if(dados.get(i).getValor() != -99999 || dados.get(i).getValor() > 0){
ano.add(anoatual);
if(i1verificaAno > 0){
if(ano.get(i1verificaAno).equals(ano.get(i1verificaAno-1))){
Integer anoNovo=ano.get(i1verificaAno)+1;
ano.remove(i1verificaAno);
ano.add(anoNovo);
mapaAnoDados.put(anoNovo, dados.get(i));
}else{
//ano.add(anoatual);
mapaAnoDados.put(anoatual, dados.get(i));
}
}else{
mapaAnoDados.put(anoatual, dados.get(i));
}
i1verificaAno++;
}
}
this.ano=ano;
this.mapaAnoDados=mapaAnoDados;
}
public FuncaoAutoCorrelacaoAnual(ArrayList<Double>dados,int anoIni){
Map<Integer,DadoTemporal> mapaAnoDados=new HashMap<Integer,DadoTemporal>();
/**
* Saulo - 25/08/2016 - Correção para nao repetir ano (quando for usado ano hidrologico por exemplo)
*/
//Collections.sort(dados);
ArrayList<Integer>ano=new ArrayList<Integer>();
int anovar=anoIni;
for(int i=0;i<dados.size();i++){
String data ="01/01/"+anovar;
String [] datastr=data.split("/");
Integer anoatual=Integer.parseInt(datastr[2]);
DadoTemporal dt=new DadoTemporal();
dt.setData(data);
dt.setValor(dados.get(i));
//if(dados.get(i).getValor() != -99999 || dados.get(i).getValor() > 0){ //restricao para chuva e vazao
ano.add(anoatual);
if(i > 0){
if(ano.get(i).equals(ano.get(i-1))){
Integer anoNovo=ano.get(i)+1;
ano.remove(i);
ano.add(anoNovo);
mapaAnoDados.put(anoNovo, dt);
}else{
//ano.add(anoatual);
mapaAnoDados.put(anoatual, dt);
}
}else{
mapaAnoDados.put(anoatual, dt);
}
//}
anovar++;
}
this.ano=ano;
this.mapaAnoDados=mapaAnoDados;
}
public FuncaoAutoCorrelacaoAnual(Map<String,DadoTemporal> mapaStrDados){
this.mapaStrDados= mapaStrDados;
Map<Integer,DadoTemporal> mapaAnoDados=new HashMap<Integer,DadoTemporal>();
ArrayList<DadoTemporal>dados=new ArrayList<DadoTemporal>();
Set<String> chaves = mapaStrDados.keySet();
for (String data : chaves){
//String [] datastr=data.split("/");
//Integer anoatual=Integer.parseInt(datastr[2]);
DadoTemporal dado = new DadoTemporal();
dado=mapaStrDados.get(data);
dados.add(dado);
/**
* Considerar Apenas dados sem Falha
*/
if(dado.getValor() != -99999 || dado.getValor() > 0){
//ano.add(anoatual);
//mapaAnoDados.put(anoatual, dado);
}
}
/**
* Saulo - 25/08/2016 - Correção para nao repetir ano (quando for usado ano hidrologico por exemplo)
*/
//Collections.sort(ano);
Collections.sort(dados);
ArrayList<Integer>ano=new ArrayList<Integer>();
//ArrayList <Integer> anoSerie=new ArrayList <Integer>();
int i1verificaAno=0;
for(int i=0;i<dados.size();i++){
String data =dados.get(i).getDataStr();
String [] datastr=data.split("/");
Integer anoatual=Integer.parseInt(datastr[2]);
/**
* Saulo - 06/05/2020 - corrigir pra quando tiver falha ele nao verifica o ano repetido
*/
if(dados.get(i).getValor() != -99999 || dados.get(i).getValor() > 0){
ano.add(anoatual);
if(i1verificaAno > 0){
if(ano.get(i1verificaAno).equals(ano.get(i1verificaAno-1))){
Integer anoNovo=ano.get(i1verificaAno)+1;
ano.remove(i1verificaAno);
ano.add(anoNovo);
mapaAnoDados.put(anoNovo, dados.get(i));
}else{
//ano.add(anoatual);
mapaAnoDados.put(anoatual, dados.get(i));
}
}else{
mapaAnoDados.put(anoatual, dados.get(i));
}
i1verificaAno++;
}
}
this.ano=ano;
this.mapaAnoDados=mapaAnoDados;
}
public double correlLagMapa(int klag){
double correl=-99999.0;
/**
* Generalizar para poder pegar amostrar emparelhadas com lag
*/
ArrayList<Double>dados=new ArrayList<Double>();
ArrayList<Double>dadosLag=new ArrayList<Double>();
for (int i=0;i<this.ano.size();i++){
Integer anolag=this.ano.get(i)-klag;
if(this.mapaAnoDados.containsKey(anolag)){
if(this.mapaAnoDados.get(anolag).getValor() != -99999 || this.mapaAnoDados.get(anolag).getValor() > 0){
dados.add(this.mapaAnoDados.get(this.ano.get(i)).getValor());
dadosLag.add(this.mapaAnoDados.get(anolag).getValor());
}
}
}
this.seriesEmparelhadas=new double [dados.size()][2];
this.series1=new double [dados.size()];
this.series2=new double [dados.size()];
for (int i=0;i<dados.size();i++){
this.seriesEmparelhadas[i][0]=dados.get(i);
this.seriesEmparelhadas[i][1]=dadosLag.get(i);
this.series1[i]=dados.get(i);
this.series2[i]=dadosLag.get(i);
}
PearsonsCorrelation pcor=new PearsonsCorrelation();
correl=pcor.correlation(this.series1, this.series2);
return correl;
}
public double [] correlLagsMapa(int [] klags){
this.klags=klags;
double [] correl=new double[this.klags.length];
for (int i=0;i<this.klags.length;i++){
correl[i]=this.correlLagMapa(this.klags[i]);
}
return correl;
}
public double correlLagMapaSemRestricao(int klag){
double correl=-99999.0;
/**
* Generalizar para poder pegar amostrar emparelhadas com lag
*/
ArrayList<Double>dados=new ArrayList<Double>();
ArrayList<Double>dadosLag=new ArrayList<Double>();
for (int i=0;i<this.ano.size();i++){
Integer anolag=this.ano.get(i)-klag;
if(this.mapaAnoDados.containsKey(anolag)){
//if(this.mapaAnoDados.get(anolag).getValor() != -99999 || this.mapaAnoDados.get(anolag).getValor() > 0){
dados.add(this.mapaAnoDados.get(this.ano.get(i)).getValor());
dadosLag.add(this.mapaAnoDados.get(anolag).getValor());
//}
}
}
this.seriesEmparelhadas=new double [dados.size()][2];
this.series1=new double [dados.size()];
this.series2=new double [dados.size()];
for (int i=0;i<dados.size();i++){
this.seriesEmparelhadas[i][0]=dados.get(i);
this.seriesEmparelhadas[i][1]=dadosLag.get(i);
this.series1[i]=dados.get(i);
this.series2[i]=dadosLag.get(i);
}
PearsonsCorrelation pcor=new PearsonsCorrelation();
correl=pcor.correlation(this.series1, this.series2);
return correl;
}
public double[] getSeries1() {
return series1;
}
public void setSeries1(double[] series1) {
this.series1 = series1;
}
public double[] getSeries2() {
return series2;
}
public void setSeries2(double[] series2) {
this.series2 = series2;
}
}
<file_sep>package tests;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
//import org.snirh.extremos_unb.deteccao.testes.MannKendallTest;
//import org.snirh.extremos_unb.deteccao.testes.VarianciaTieValuesMannKendall;
//import org.snirh.extremos_unb.tipos.DadoTemporal;
//import org.snirh.util.sort.Esco7;
import flanagan.analysis.Stat;
import types.DadoTemporal;
import util.Esco7;
public class MannKendallTest {
double [] valuetot;
double [] valuex;
double [] valuey;
double pvalue;
double estatteste;
double valorcriticoteste;
String resultadoteste;
int divisao;
private String sentidoTendencia;
private String resultesteTexto;
private String [] dataStr;
private int [] dataAno;
ArrayList<DadoTemporal> dadostot;
ArrayList<DadoTemporal> dadosx;
ArrayList<DadoTemporal> dadosy;
/**
* 0 - Bicauldal
* 1 - Unicauldal a direita
* 2 - Unicauldal a esquerda
*/
private int tipoHipotese;
private String tipoHipoteseStr;
/**
* 1 - 100%
*/
private double nivelSignificancia;
private final String HIPOTESE_NULA="There is no trend in the data";
private final String HIPOTESE_ALTERNATIVA_BICAULDAL="There is a trend in the data";
private final String HIPOTESE_ALTERNATIVA_UNICAULDAL_DIREITA="There is a increase trend in the data";
private final String HIPOTESE_ALTERNATIVA_UNICAULDAL_ESQUERDA="There is a decrease trend in the data";
private double estattesteBootstrap;
private double S; //estatistica S do teste MK
public double getEstattesteBootstrap() {
return estattesteBootstrap;
}
public void setEstattesteBootstrap(double estattesteBootstrap) {
this.estattesteBootstrap = estattesteBootstrap;
}
public String getTipoHipoteseStr() {
return tipoHipoteseStr;
}
public void setTipoHipoteseStr(String tipoHipoteseStr) {
this.tipoHipoteseStr = tipoHipoteseStr;
}
public String getSentidoTendencia() {
return sentidoTendencia;
}
public void setSentidoTendencia(String sentidoTendencia) {
this.sentidoTendencia = sentidoTendencia;
}
public ArrayList<DadoTemporal> getDadostot() {
return dadostot;
}
public void setDadostot(ArrayList<DadoTemporal> dadostot) {
this.dadostot = dadostot;
}
public ArrayList<DadoTemporal> getDadosx() {
return dadosx;
}
public void setDadosx(ArrayList<DadoTemporal> dadosx) {
this.dadosx = dadosx;
}
public ArrayList<DadoTemporal> getDadosy() {
return dadosy;
}
public void setDadosy(ArrayList<DadoTemporal> dadosy) {
this.dadosy = dadosy;
}
public String [] getDataStr() {
return dataStr;
}
public void setDataStr(String [] dataStr) {
this.dataStr = dataStr;
}
public String getResultesteTexto() {
return resultesteTexto;
}
public void setResultesteTexto(String resultesteTexto) {
this.resultesteTexto = resultesteTexto;
}
public MannKendallTest(ArrayList<Double> serieArray, int tipoHipotese, double nivelSignificancia){
this.tipoHipotese=tipoHipotese;
this.nivelSignificancia=nivelSignificancia;
this.valuetot=new double[serieArray.size()];
this.dataAno=new int[serieArray.size()];
this.dataStr=new String [serieArray.size()];
for (int i=0;i<serieArray.size();i++){
this.valuetot[i] =serieArray.get(i);
}
if(this.tipoHipotese ==1){
this.setTipoHipoteseStr("Unicauldal a direita");
}else if(this.tipoHipotese ==2){
this.setTipoHipoteseStr("Unicauldal a esquerda");
}else{
this.setTipoHipoteseStr("Bicauldal");
}
this.dividirSerie();
}
public MannKendallTest(Map<String,DadoTemporal> serieMapa, int tipoHipotese, double nivelSignificancia){
this.tipoHipotese=tipoHipotese;
this.nivelSignificancia=nivelSignificancia;
ArrayList<DadoTemporal> dados = new ArrayList<DadoTemporal>();
Set<String> chavesMax = serieMapa.keySet();
for (String data : chavesMax){
DadoTemporal dado = serieMapa.get(data);
dados.add(dado);
}
Collections.sort(dados);
this.setDadostot(dados);
this.valuetot=new double[this.dadostot.size()];
this.dataAno=new int[this.dadostot.size()];
this.dataStr=new String [this.dadostot.size()];
for (int i=0;i<this.dadostot.size();i++){
//int valorInt=(int)Math.round(this.dadostot.get(i).getValor());
//this.valuetot[i]=valorInt;
this.valuetot[i]=this.dadostot.get(i).getValor();
this.dataStr[i]=this.dadostot.get(i).getDataStr();
this.dataAno[i]=this.dadostot.get(i).pegarAno();
}
if(this.tipoHipotese ==1){
this.setTipoHipoteseStr("Unicauldal a direita");
}else if(this.tipoHipotese ==2){
this.setTipoHipoteseStr("Unicauldal a esquerda");
}else{
this.setTipoHipoteseStr("Bicauldal");
}
this.dividirSerie();
}
public void dividirSerie(){
int metade = this.valuetot.length/2;
this.valuex=new double[metade];
this.valuey=new double[this.valuetot.length-metade];
for (int i=0;i<metade;i++){
this.valuex[i]=this.valuetot[i];
}
int i1=0;
for (int i=metade;i<this.valuetot.length;i++){
this.valuey[i1]=this.valuetot[i];
i1++;
}
}
public boolean anoDivExiste(){
return false;
}
public MannKendallTest(double [] valuetot){
this.valuetot=new double[valuetot.length];
this.valuetot= valuetot;
this.dividirSerie();
this.tipoHipotese=0;
this.nivelSignificancia=5.0;
}
public MannKendallTest(ArrayList<Double> valuetotlist, int tipoHipotese){
this.valuetot=new double[valuetotlist.size()];
for(int i=0;i<valuetotlist.size();i++){
this.valuetot[i] =valuetotlist.get(i);
}
// this.valuetot= valuetot;
this.dividirSerie();
this.tipoHipotese=tipoHipotese;
this.nivelSignificancia=5.0;
}
public MannKendallTest(ArrayList<Double> valuetotlist){
this.valuetot=new double[valuetotlist.size()];
for(int i=0;i<valuetotlist.size();i++){
this.valuetot[i] =valuetotlist.get(i);
}
// this.valuetot= valuetot;
this.dividirSerie();
this.tipoHipotese=0;
this.nivelSignificancia=5.0;
}
public double getPvalue() {
return pvalue;
}
public void setPvalue(double pvalue) {
this.pvalue = pvalue;
}
public double getEstatteste() {
return estatteste;
}
public void setEstatteste(double estatteste) {
this.estatteste = estatteste;
}
public double getValorcriticoteste() {
return valorcriticoteste;
}
public void setValorcriticoteste(double valorcriticoteste) {
this.valorcriticoteste = valorcriticoteste;
}
public String getResultadoteste() {
return resultadoteste;
}
public void setResultadoteste(String resultadoteste) {
this.resultadoteste = resultadoteste;
}
public MannKendallTest(double [] valuex,double [] valuey){
this.valuex=new double[valuex.length];
this.valuex= valuex;
this.valuey=new double[valuey.length];
this.valuey= valuey;
this.valuetot=new double[valuex.length+valuey.length];
int k=0;
for (int i=0;i<valuex.length;i++){
this.valuetot[k]=this.valuex[i];
k++;
}
for (int i=0;i<valuey.length;i++){
this.valuetot[k]=this.valuey[i];
k++;
}
this.tipoHipotese=0;
this.nivelSignificancia=5.0;
}
public MannKendallTest(double [] valuetot, int divisao){
this.valuetot=new double[valuetot.length];
this.valuetot= valuetot;
this.divisao=divisao;
int metade = this.divisao; //divisão é a posição no vetor onde que se dividir a série
this.valuex=new double[metade];
for (int i=0;i<metade;i++){
this.valuex[i]=this.valuetot[i];
}
for (int i=metade;i<valuetot.length;i++){
this.valuey[i]=this.valuetot[i];
}
this.tipoHipotese=0;
this.nivelSignificancia=5.0;
}
public void teste1 (double [] vcritico) {
Stat sttotal = new Stat(this.valuetot);
//sttotal.setDenominatorToNminusOne();
sttotal.setDenominatorToN();
double totmedia =sttotal.mean_as_double();
double totdesvpad =sttotal.standardDeviation_as_double();
int N = this.valuetot.length;
int[] Ri=new int [N];
double x=0.0;
int[] indices=new int [this.valuetot.length];
indices = Esco7.ordenar(this.valuetot.length, this.valuetot) ;
for (int i=0;i<this.valuetot.length;i++){
if(indices[i] <= this.valuex.length-1){
Ri[indices[i]]=i+1;
}else{
Ri[indices[i]]=i+1;
}
}
for (int i=0;i<this.valuetot.length-1;i++){
if(this.valuetot[indices[i]] == this.valuetot[indices[i+1]]){
Ri[indices[i+1]]=Ri[indices[i]];
}
}
double S=0.0;
double soma =0;
for (int i=0;i<this.valuetot.length-1;i++){
for (int j=i+1;j<this.valuetot.length;j++){
x=0.0;
x=Ri[j]-Ri[i];
if(x > 0){
soma=soma+1;
}else if(x<0){
soma=soma-1;
}else{
soma=soma+0;
}
}
// System.out.println("Soma acumulada "+soma);
}
S=soma;
double desvpadtest=Math.sqrt((N*(N-1)*(2*N+5))/18);
double zcrit = Math.abs(S)/desvpadtest;
double zcritBoot = S/desvpadtest;
this.setEstatteste(zcrit);
this.setEstattesteBootstrap(zcritBoot);
if(S <0){
this.setSentidoTendencia("Decrease");
}else{
this.setSentidoTendencia("Increase");
}
//Quando o teste for bicaudal deve multiplicar por 2
if(this.tipoHipotese >0){
double pvalue = (1-Stat.gaussianCDF(0.0, 1.0, zcrit));
this.setPvalue(pvalue);
double ns=(100-this.nivelSignificancia)/100.0;
double nsgui=(this.nivelSignificancia)/100.0;
double vcritteste=vcritico[0];
//double vcritteste=Stat.gaussianInverseCDF(ns);
if(this.tipoHipotese == 1){
if(S <0){
this.setValorcriticoteste(vcritteste);
this.setResultadoteste("NS");
this.setResultesteTexto("The null hypothesis that the data do not show an INCREASING trend cannot be rejected.");
}else if(zcritBoot > vcritteste){
this.setValorcriticoteste(vcritteste);
this.setResultadoteste("S("+this.nivelSignificancia+")");
this.setResultesteTexto("reject the null hypothesis that the data show an INCREASING trend at the level of "+this.nivelSignificancia+"%");
}else{
this.setValorcriticoteste(vcritteste);
this.setResultadoteste("NS");
this.setResultesteTexto("The null hypothesis that the data do not show an INCREASING trend cannot be rejected.");
}
}else{
if(S > 0){
this.setValorcriticoteste(vcritteste);
this.setResultadoteste("NS");
this.setResultesteTexto("The null hypothesis that the data do not show a DECREASING trend cannot be rejected");
}else if(zcritBoot < vcritteste){
this.setValorcriticoteste(vcritteste);
this.setResultadoteste("S("+this.nivelSignificancia+")");
this.setResultesteTexto("reject the null hypothesis that the data show an DECREASING trend at the level of "+this.nivelSignificancia+"%");
}else{
this.setValorcriticoteste(vcritteste);
this.setResultadoteste("NS");
this.setResultesteTexto("The null hypothesis that the data do not show an DECREASING trend cannot be rejected.");
}
}
}else{
double pvalue = (1-Stat.gaussianCDF(0.0, 1.0, zcrit))*2.0;
this.setPvalue(pvalue);
double nsBicaudal=this.nivelSignificancia/2.0;
double ns=(100-nsBicaudal)/100.0;
double nsgui=(this.nivelSignificancia)/100.0;
double vcritinf=vcritico[0];
double vcritsup=vcritico[1];
if(zcritBoot < vcritinf){
this.setValorcriticoteste(vcritinf);
this.setResultadoteste("S("+this.nivelSignificancia+")");
this.setResultesteTexto("reject the null hypothesis that the data show a trend at the level of "+this.nivelSignificancia+"%");
}else if(zcritBoot > vcritsup){
this.setValorcriticoteste(vcritsup);
this.setResultadoteste("S("+this.nivelSignificancia+")");
this.setResultesteTexto("reject the null hypothesis that the data show a trend at the level of "+this.nivelSignificancia+"%");
}else{
this.setValorcriticoteste(vcritsup);
this.setResultadoteste("NS");
this.setResultesteTexto("One cannot reject the null hypothesis that the data do not show a trend.");
}
}
}
public void teste1 () {
Stat sttotal = new Stat(this.valuetot);
//sttotal.setDenominatorToNminusOne();
sttotal.setDenominatorToN();
double totmedia =sttotal.mean_as_double();
double totdesvpad =sttotal.standardDeviation_as_double();
int N = this.valuetot.length;
int[] Ri=new int [N];
double x=0.0;
int[] indices=new int [this.valuetot.length];
indices = Esco7.ordenar(this.valuetot.length, this.valuetot) ;
for (int i=0;i<this.valuetot.length;i++){
if(indices[i] <= this.valuex.length-1){
Ri[indices[i]]=i+1;
}else{
Ri[indices[i]]=i+1;
}
}
for (int i=0;i<this.valuetot.length-1;i++){
if(this.valuetot[indices[i]] == this.valuetot[indices[i+1]]){
Ri[indices[i+1]]=Ri[indices[i]];
}
}
double S=0.0;
double soma =0;
for (int i=0;i<this.valuetot.length-1;i++){
for (int j=i+1;j<this.valuetot.length;j++){
x=0.0;
x=Ri[j]-Ri[i];
if(x > 0){
soma=soma+1;
}else if(x<0){
soma=soma-1;
}else{
soma=soma+0;
}
}
// System.out.println("Soma acumulada "+soma);
}
S=soma;
this.S=S;
double parteSemTiedValue=(N*(N-1)*(2*N+5));
double parteComTiedValue=0.0;
boolean pegarParteTiedValue=true;
if(pegarParteTiedValue){
parteComTiedValue=VarianciaTieValuesMannKendall.executar(valuetot);
}
//double desvpadtest=Math.sqrt((N*(N-1)*(2*N+5))/18);
double desvpadtest=Math.sqrt((parteSemTiedValue-parteComTiedValue)/18.0);
/**
* Saulo 31/01/218 - DesvPadSnovo considerando
*/
// double zcrit = Math.abs(S)/desvpadtest;
double zcrit = -99999.;
double zcritBoot = S/desvpadtest;
this.setEstattesteBootstrap(zcritBoot);
if(S <0){
zcrit = (S+1)/desvpadtest;
this.setSentidoTendencia("Decrease");
}else if(S >0){
zcrit = (S-1)/desvpadtest;
this.setSentidoTendencia("Increase");
}else{
this.setSentidoTendencia("Decrease");
zcrit =0;
}
this.setEstatteste(zcrit);
//Quando o teste for bicaudal deve multiplicar por 2
if(this.tipoHipotese >0){
double pvalue = (1-Stat.gaussianCDF(0.0, 1.0, zcrit));
this.setPvalue(pvalue);
double ns=(100-this.nivelSignificancia)/100.0;
double nsgui=(this.nivelSignificancia)/100.0;
double vcritteste=Stat.gaussianInverseCDF(ns);
if(this.tipoHipotese == 1){
if(S <0){
this.setValorcriticoteste(vcritteste);
this.setResultadoteste("NS");
this.setResultesteTexto("The null hypothesis that the data do not show an INCREASING trend cannot be rejected");
}else if(zcrit > vcritteste){
this.setValorcriticoteste(vcritteste);
this.setResultadoteste("S("+this.nivelSignificancia+")");
this.setResultesteTexto("reject the null hypothesis that the data show an INCREASING trend at the level of "+this.nivelSignificancia+"%");
}else{
this.setValorcriticoteste(vcritteste);
this.setResultadoteste("NS");
this.setResultesteTexto("The null hypothesis that the data do not show an INCREASING trend cannot be rejected");
}
}else{
if(S > 0){
this.setValorcriticoteste(vcritteste);
this.setResultadoteste("NS");
this.setResultesteTexto("The null hypothesis that the data do not show a DECREASING trend cannot be rejected");
}else if(zcrit > vcritteste){
this.setValorcriticoteste(vcritteste);
this.setResultadoteste("S("+this.nivelSignificancia+")");
this.setResultesteTexto("reject the null hypothesis that the data show an DECREASING trend at the level of "+this.nivelSignificancia+"% ");
}else{
this.setValorcriticoteste(vcritteste);
this.setResultadoteste("NS");
this.setResultesteTexto("The null hypothesis that the data do not show an DECREASING trend cannot be rejected");
}
}
}else{
double pvalVerdadeiro=Stat.gaussianCDF(0.0, 1.0, zcritBoot);
if(pvalVerdadeiro > 0.5){
// System.out.println("Cauda superior");
}else{
//System.out.println("Cauda inferior");
}
zcrit=Math.abs(zcrit);
// double pvalueteste = (1-Stat.gaussianCDF(0.0, 1.0, 1.96))*2.0;
double pvalue = (1-Stat.gaussianCDF(0.0, 1.0, zcrit))*2.0;
this.setPvalue(pvalue);
double nsBicaudal=this.nivelSignificancia/2.0;
double ns=(100-nsBicaudal)/100.0;
double nsgui=(this.nivelSignificancia)/100.0;
double vcritteste=Stat.gaussianInverseCDF(ns);
if(zcrit > vcritteste){
this.setValorcriticoteste(vcritteste);
this.setResultadoteste("S("+this.nivelSignificancia+")");
this.setResultesteTexto("reject the null hypothesis that the data show a trend at the level of "+this.nivelSignificancia+"%");
}else{
this.setValorcriticoteste(vcritteste);
this.setResultadoteste("NS");
this.setResultesteTexto("One cannot reject the null hypothesis that the data do not show a trend");
}
}
}
public void teste1 (double CF) {
Stat sttotal = new Stat(this.valuetot);
//sttotal.setDenominatorToNminusOne();
sttotal.setDenominatorToN();
double totmedia =sttotal.mean_as_double();
double totdesvpad =sttotal.standardDeviation_as_double();
int N = this.valuetot.length;
int[] Ri=new int [N];
double x=0.0;
int[] indices=new int [this.valuetot.length];
indices = Esco7.ordenar(this.valuetot.length, this.valuetot) ;
for (int i=0;i<this.valuetot.length;i++){
if(indices[i] <= this.valuex.length-1){
Ri[indices[i]]=i+1;
}else{
Ri[indices[i]]=i+1;
}
}
for (int i=0;i<this.valuetot.length-1;i++){
if(this.valuetot[indices[i]] == this.valuetot[indices[i+1]]){
Ri[indices[i+1]]=Ri[indices[i]];
}
}
double S=0.0;
double soma =0;
for (int i=0;i<this.valuetot.length-1;i++){
for (int j=i+1;j<this.valuetot.length;j++){
x=0.0;
x=Ri[j]-Ri[i];
if(x > 0){
soma=soma+1;
}else if(x<0){
soma=soma-1;
}else{
soma=soma+0;
}
}
// System.out.println("Soma acumulada "+soma);
}
S=soma;
this.S=S;
double parteSemTiedValue=(N*(N-1)*(2*N+5));
double parteComTiedValue=0.0;
boolean pegarParteTiedValue=true;
if(pegarParteTiedValue){
parteComTiedValue=VarianciaTieValuesMannKendall.executar(valuetot);
}
//double desvpadtest=Math.sqrt((N*(N-1)*(2*N+5))/18);
/**
* Saulo - 21/04/2020 - Considerar a correção da variancia
*/
double varianciaS=((parteSemTiedValue-parteComTiedValue)/18.0)*CF;
double desvpadtest=Math.sqrt(varianciaS);
/**
* Saulo 31/01/218 - DesvPadSnovo considerando
*/
// double zcrit = Math.abs(S)/desvpadtest;
double zcrit = -99999.;
double zcritBoot = S/desvpadtest;
this.setEstattesteBootstrap(zcritBoot);
if(S <0){
zcrit = (S+1)/desvpadtest;
this.setSentidoTendencia("Decrease");
}else if(S >0){
zcrit = (S-1)/desvpadtest;
this.setSentidoTendencia("Increase");
}else{
this.setSentidoTendencia("Decrease");
zcrit =0;
}
this.setEstatteste(zcrit);
//Quando o teste for bicaudal deve multiplicar por 2
if(this.tipoHipotese >0){
double pvalue = (1-Stat.gaussianCDF(0.0, 1.0, zcrit));
this.setPvalue(pvalue);
double ns=(100-this.nivelSignificancia)/100.0;
double nsgui=(this.nivelSignificancia)/100.0;
double vcritteste=Stat.gaussianInverseCDF(ns);
if(this.tipoHipotese == 1){
if(S <0){
this.setValorcriticoteste(vcritteste);
this.setResultadoteste("NS");
this.setResultesteTexto("The null hypothesis that the data do not show an INCREASING trend cannot be rejected");
}else if(zcrit > vcritteste){
this.setValorcriticoteste(vcritteste);
this.setResultadoteste("S("+this.nivelSignificancia+")");
this.setResultesteTexto("reject the null hypothesis that the data show an INCREASING trend at the level of "+this.nivelSignificancia+"%");
}else{
this.setValorcriticoteste(vcritteste);
this.setResultadoteste("NS");
this.setResultesteTexto("The null hypothesis that the data do not show an INCREASING trend cannot be rejected");
}
}else{
if(S > 0){
this.setValorcriticoteste(vcritteste);
this.setResultadoteste("NS");
this.setResultesteTexto("The null hypothesis that the data do not show a DECREASING trend cannot be rejected");
}else if(zcrit > vcritteste){
this.setValorcriticoteste(vcritteste);
this.setResultadoteste("S("+this.nivelSignificancia+")");
this.setResultesteTexto("reject the null hypothesis that the data show an DECREASING trend at the level of "+this.nivelSignificancia+"%");
}else{
this.setValorcriticoteste(vcritteste);
this.setResultadoteste("NS");
this.setResultesteTexto("The null hypothesis that the data do not show an DECREASING trend cannot be rejected");
}
}
}else{
double pvalVerdadeiro=Stat.gaussianCDF(0.0, 1.0, zcritBoot);
if(pvalVerdadeiro > 0.5){
// System.out.println("Cauda superior");
}else{
//System.out.println("Cauda inferior");
}
zcrit=Math.abs(zcrit);
// double pvalueteste = (1-Stat.gaussianCDF(0.0, 1.0, 1.96))*2.0;
double pvalue = (1-Stat.gaussianCDF(0.0, 1.0, zcrit))*2.0;
this.setPvalue(pvalue);
double nsBicaudal=this.nivelSignificancia/2.0;
double ns=(100-nsBicaudal)/100.0;
double nsgui=(this.nivelSignificancia)/100.0;
double vcritteste=Stat.gaussianInverseCDF(ns);
if(zcrit > vcritteste){
this.setValorcriticoteste(vcritteste);
this.setResultadoteste("S("+this.nivelSignificancia+")");
this.setResultesteTexto("reject the null hypothesis that the data show a trend at the level of"+this.nivelSignificancia+"%");
}else{
this.setValorcriticoteste(vcritteste);
this.setResultadoteste("NS");
this.setResultesteTexto("One cannot reject the null hypothesis that the data do not show a trend.");
}
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String dir="C:\\OpenJump150\\Exemplos\\ArqTestes\\";
//String filename="QmensaisPonteNovaParaopeba.dat";
String filename="QmensaisPonteNovaParaopebasemdecimais.dat";
StringTokenizer tok;
double [][] value=new double[1000][1000];
BufferedReader file;
try {
file = new BufferedReader(new FileReader(dir + filename));
String str = file.readLine();
str = file.readLine();
tok = new StringTokenizer(str);
int ngauges = Integer.valueOf(tok.nextToken(" ").trim());
int [] nvalues=new int [1000];
for (int i = 0; i < ngauges; i++){
str = file.readLine();
tok = new StringTokenizer(str);
int cod = Integer.valueOf(tok.nextToken(" ").trim());
str = file.readLine();
tok = new StringTokenizer(str);
nvalues [i] = Integer.valueOf(tok.nextToken(" ").trim());
str = file.readLine();
tok = new StringTokenizer(str);
for (int j = 0; j < nvalues[i]; j++){
value[i][j]=Double.valueOf(tok.nextToken(" ").trim());
}
}
//cod=35 - sugar creek -exemplo RAO
double [] param=new double[10];
int cod=0;
//int cod=13;
double [] x = new double [nvalues [cod]];
for (int j = 0; j < nvalues[cod]; j++){
x[j]=value[cod][j];
System.out.println(x[j]);
}
int n=nvalues[cod];
MannKendallTest WW = new MannKendallTest(x);
double nivelsig=0.5;
WW.teste1();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public double getS() {
return S;
}
public void setS(double s) {
S = s;
}
}
<file_sep>package types;
import java.awt.geom.Point2D;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Map;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.LinearRing;
import com.vividsolutions.jts.geom.Point;
import com.vividsolutions.jump.feature.AttributeType;
import com.vividsolutions.jump.feature.BasicFeature;
import com.vividsolutions.jump.feature.Feature;
import com.vividsolutions.jump.feature.FeatureSchema;
public class InventarioHidrologico {
private int id;
private int BaciaCodigo;
private int SubBaciaCodigo;
//private int Estacao_codigo;
private String Estacao_codigo;
private int MesAnoHidro;
private double Latitude;
private double Longitude;
private double Altitude;
private double AreaDrenagem;
private int OrigemSerie;
private String DescricaoOrigemSerie;
private String DiscretizaçãoTemporária;
private String TipodeDado;
private String dataInicialstr;
private String dataFinalstr;
private String NomedaEstacao;
protected Point2D position;
private double ThiessenArea;
private double ThiessenCoef;
private String dataInicial;
private String dataFinal;
private Date dataIni;
private Date dataFim;
private int nAnosSF;
private int [] nAnosSFSazonal;
private String nomedoRio;
private String municipio;
private String codmunicipio;
private String codrio;
private Double resolLatyKm;
private Double resolLaty;
private Double resolLonxKm;
private Double resolLonx;
private Double areaKm2;
private String nomeRegiaoHidrografica;
private ArrayList<String> nomesRHsCompartilhadas;
//private ArrayList<Geometry> gradePoligonoCompartilhadas;
private Map<String,Geometry> gradePoligonoCompartilhadas;
private Geometry gradePoligono;
private Point gradeCentroide;
private double gradeEW;
private double gradeNS;
private double gradeKmEW;
private double gradeKmNS;
private double areaDaGradeKm2;
private boolean selecionadaApoio;
private boolean selecionadaPrincipal;
//informacao hidro
private String codHidroNivelConsistencia;
private String nomeTabelaBDHidro;
private String nomeCampoTipoVarHidro;
private String nivelconsistenciaNome;
private boolean existeInventarioBD;
private String nomeTabelaBD;
private String cobacia;
private String codigoResponsavel;
private String codigoOperadora;
private String codigoAdicional;
private String siglaResponsavel;
private String siglaOperadora;
private String emoperacao;
private String ultimaAtualizacao;
/*public Coordenadas pegarCoordenadas(){
Coordenadas c=new Coordenadas();
c.setLat(Latitude);
c.setLon(Longitude);
return c;
}
public Point pegarPontoFeature(){
Point ponto = CriarPontoGeografico.coordenadas(Latitude, Longitude);
return ponto;
}*/
public Geometry pegarGrade(double gradeEW,double gradeNS){
double latV1=Latitude+(gradeNS/2.0);
double lonV1=Longitude+(gradeEW/2.0);
double latV2=Latitude+(gradeNS/2.0);
double lonV2=Longitude-(gradeEW/2.0);
double latV3=Latitude-(gradeNS/2.0);
double lonV3=Longitude-(gradeEW/2.0);
double latV4=Latitude-(gradeNS/2.0);
double lonV4=Longitude+(gradeEW/2.0);
GeometryFactory geomFact = new GeometryFactory();
Coordinate[] coords =
new Coordinate[] {new Coordinate(lonV1, latV1), new Coordinate(lonV2, latV2),
new Coordinate(lonV3, latV3), new Coordinate(lonV4, latV4), new Coordinate(lonV1, latV1) };
LinearRing ring = geomFact.createLinearRing(coords);
LinearRing holes[] = null; // use LinearRing[] to represent holes
Geometry gradePoligono=geomFact.createPolygon(ring, holes);
return gradePoligono;
}
public Feature getFeatureWebservice(Geometry geom) {
//Point ponto = CriarPontoGeografico.coordenadas(lat, lon);
FeatureSchema fsnew = new FeatureSchema();
fsnew.addAttribute("Geometry", AttributeType.GEOMETRY);
fsnew.addAttribute("lat", AttributeType.DOUBLE);
fsnew.addAttribute("lon", AttributeType.DOUBLE);
fsnew.addAttribute("alt", AttributeType.DOUBLE);
fsnew.addAttribute("codigo", AttributeType.STRING);
fsnew.addAttribute("nome", AttributeType.STRING);
fsnew.addAttribute("baciacod", AttributeType.INTEGER);
fsnew.addAttribute("subbaccod", AttributeType.INTEGER);
fsnew.addAttribute("rio", AttributeType.STRING);
fsnew.addAttribute("municipio", AttributeType.STRING);
fsnew.addAttribute("resp", AttributeType.STRING);
fsnew.addAttribute("operador", AttributeType.STRING);
fsnew.addAttribute("adkm2", AttributeType.DOUBLE);
fsnew.addAttribute("emoperacao", AttributeType.STRING);
fsnew.addAttribute("ultimatualiza", AttributeType.STRING);
Feature feature = new BasicFeature(fsnew);
//feature.setGeometry(this.pegarPontoFeature());
feature.setGeometry(geom);
feature.setAttribute("lat", this.Latitude);
feature.setAttribute("lon", this.Longitude);
feature.setAttribute("alt", this.Altitude);
feature.setAttribute("codigo", this.Estacao_codigo);
feature.setAttribute("nome", this.NomedaEstacao);
feature.setAttribute("baciacod", this.BaciaCodigo);
feature.setAttribute("subbaccod", this.SubBaciaCodigo);
feature.setAttribute("rio",this.nomedoRio);
feature.setAttribute("municipio", this.municipio);
feature.setAttribute("resp", this.siglaResponsavel);
feature.setAttribute("operador", this.siglaOperadora);
feature.setAttribute("adkm2", this.AreaDrenagem);
feature.setAttribute("emoperacao",this.emoperacao);
feature.setAttribute("ultimatualiza",this.ultimaAtualizacao);
return feature;
}
/* public Feature getFeatureWebservice(Geometry geom) {
//Point ponto = CriarPontoGeografico.coordenadas(lat, lon);
FeatureSchema fsnew = new FeatureSchema();
fsnew.addAttribute("Geometry", AttributeType.GEOMETRY);
fsnew.addAttribute("lat", AttributeType.DOUBLE);
fsnew.addAttribute("lon", AttributeType.DOUBLE);
fsnew.addAttribute("alt", AttributeType.DOUBLE);
fsnew.addAttribute("codigo", AttributeType.STRING);
fsnew.addAttribute("nome", AttributeType.STRING);
fsnew.addAttribute("baciacod", AttributeType.INTEGER);
fsnew.addAttribute("subbaccod", AttributeType.INTEGER);
fsnew.addAttribute("rio", AttributeType.STRING);
fsnew.addAttribute("municipio", AttributeType.STRING);
fsnew.addAttribute("resp", AttributeType.STRING);
fsnew.addAttribute("operador", AttributeType.STRING);
fsnew.addAttribute("adkm2", AttributeType.DOUBLE);
fsnew.addAttribute("emoperacao", AttributeType.STRING);
fsnew.addAttribute("ultimatualiza", AttributeType.STRING);
Feature feature = new BasicFeature(fsnew);
//feature.setGeometry(this.pegarPontoFeature());
feature.setGeometry(geom);
feature.setAttribute("lat", this.Latitude);
feature.setAttribute("lon", this.Longitude);
feature.setAttribute("alt", this.Altitude);
feature.setAttribute("codigo", this.Estacao_codigo);
feature.setAttribute("nome", this.NomedaEstacao);
feature.setAttribute("baciacod", this.BaciaCodigo);
feature.setAttribute("subbaccod", this.SubBaciaCodigo);
feature.setAttribute("rio",this.nomedoRio);
feature.setAttribute("municipio", this.municipio);
feature.setAttribute("resp", this.siglaResponsavel);
feature.setAttribute("operador", this.siglaOperadora);
feature.setAttribute("adkm2", this.AreaDrenagem);
feature.setAttribute("emoperacao",this.emoperacao);
feature.setAttribute("ultimatualiza",this.ultimaAtualizacao);
return feature;
}
public Feature getFeatureWebservice() {
//Point ponto = CriarPontoGeografico.coordenadas(lat, lon);
FeatureSchema fsnew = new FeatureSchema();
fsnew.addAttribute("Geometry", AttributeType.GEOMETRY);
fsnew.addAttribute("lat", AttributeType.DOUBLE);
fsnew.addAttribute("lon", AttributeType.DOUBLE);
fsnew.addAttribute("alt", AttributeType.DOUBLE);
fsnew.addAttribute("codigo", AttributeType.STRING);
fsnew.addAttribute("nome", AttributeType.STRING);
fsnew.addAttribute("baciacod", AttributeType.INTEGER);
fsnew.addAttribute("subbaccod", AttributeType.INTEGER);
fsnew.addAttribute("rio", AttributeType.STRING);
fsnew.addAttribute("municipio", AttributeType.STRING);
fsnew.addAttribute("resp", AttributeType.STRING);
fsnew.addAttribute("operador", AttributeType.STRING);
fsnew.addAttribute("adkm2", AttributeType.DOUBLE);
fsnew.addAttribute("emoperacao", AttributeType.STRING);
fsnew.addAttribute("ultimatualiza", AttributeType.STRING);
Feature feature = new BasicFeature(fsnew);
feature.setGeometry(this.pegarPontoFeature());
feature.setAttribute("lat", this.Latitude);
feature.setAttribute("lon", this.Longitude);
feature.setAttribute("alt", this.Altitude);
feature.setAttribute("codigo", this.Estacao_codigo);
feature.setAttribute("nome", this.NomedaEstacao);
feature.setAttribute("baciacod", this.BaciaCodigo);
feature.setAttribute("subbaccod", this.SubBaciaCodigo);
feature.setAttribute("rio",this.nomedoRio);
feature.setAttribute("municipio", this.municipio);
feature.setAttribute("resp", this.siglaResponsavel);
feature.setAttribute("operador", this.siglaOperadora);
feature.setAttribute("adkm2", this.AreaDrenagem);
feature.setAttribute("emoperacao",this.emoperacao);
feature.setAttribute("ultimatualiza",this.ultimaAtualizacao);
return feature;
}
public Feature getFeature() {
//Point ponto = CriarPontoGeografico.coordenadas(lat, lon);
FeatureSchema fsnew = new FeatureSchema();
fsnew.addAttribute("Geometry", AttributeType.GEOMETRY);
fsnew.addAttribute("Codigo", AttributeType.STRING);
//fsnew.addAttribute("j", AttributeType.INTEGER);
Feature feature = new BasicFeature(fsnew);
feature.setGeometry(this.pegarPontoFeature());
feature.setAttribute("Codigo", this.Estacao_codigo);
//feature.setAttribute("j",this.j);
return feature;
}
public Feature getFeatureWebserviceCaracResMon(CaracteristicaReservacaoMontante caracResMon) {
//Point ponto = CriarPontoGeografico.coordenadas(lat, lon);
FeatureSchema fsnew = new FeatureSchema();
fsnew.addAttribute("Geometry", AttributeType.GEOMETRY);
fsnew.addAttribute("lat", AttributeType.DOUBLE);
fsnew.addAttribute("lon", AttributeType.DOUBLE);
fsnew.addAttribute("alt", AttributeType.DOUBLE);
fsnew.addAttribute("codigo", AttributeType.STRING);
fsnew.addAttribute("nome", AttributeType.STRING);
fsnew.addAttribute("baciacod", AttributeType.INTEGER);
fsnew.addAttribute("subbaccod", AttributeType.INTEGER);
fsnew.addAttribute("rio", AttributeType.STRING);
fsnew.addAttribute("municipio", AttributeType.STRING);
fsnew.addAttribute("resp", AttributeType.STRING);
fsnew.addAttribute("operador", AttributeType.STRING);
fsnew.addAttribute("adkm2", AttributeType.DOUBLE);
fsnew.addAttribute("emoperacao", AttributeType.STRING);
fsnew.addAttribute("ultimatualiza", AttributeType.STRING);
fsnew.addAttribute("cobacia", AttributeType.STRING);
fsnew.addAttribute("cocursodag", AttributeType.STRING);
fsnew.addAttribute("ne", AttributeType.DOUBLE);
fsnew.addAttribute("sumae", AttributeType.DOUBLE);
fsnew.addAttribute("volhm3", AttributeType.DOUBLE);
fsnew.addAttribute("perae", AttributeType.DOUBLE);
fsnew.addAttribute("rvolqmlt", AttributeType.DOUBLE);
Feature feature = new BasicFeature(fsnew);
feature.setGeometry(this.pegarPontoFeature());
feature.setAttribute("lat", this.Latitude);
feature.setAttribute("lon", this.Longitude);
feature.setAttribute("alt", this.Altitude);
feature.setAttribute("codigo", this.Estacao_codigo);
feature.setAttribute("nome", this.NomedaEstacao);
feature.setAttribute("baciacod", this.BaciaCodigo);
feature.setAttribute("subbaccod", this.SubBaciaCodigo);
feature.setAttribute("rio",this.nomedoRio);
feature.setAttribute("municipio", this.municipio);
feature.setAttribute("resp", this.siglaResponsavel);
feature.setAttribute("operador", this.siglaOperadora);
feature.setAttribute("adkm2", this.AreaDrenagem);
feature.setAttribute("emoperacao",this.emoperacao);
feature.setAttribute("ultimatualiza",this.ultimaAtualizacao);
feature.setAttribute("cobacia", caracResMon.getCobacia());
feature.setAttribute("cocursodag", caracResMon.getCocursodag());
feature.setAttribute("ne", caracResMon.getNumeroEspelhoDagua());
feature.setAttribute("sumae", caracResMon.getSomaAreaEspelhos());
feature.setAttribute("volhm3", caracResMon.getVolumeTotalEstimado());
feature.setAttribute("perae", caracResMon.getPercentualAreaEspelhos());
feature.setAttribute("rvolqmlt", caracResMon.getRelVolQmedAnual());
return feature;
}*/
public double getGradeEW() {
return gradeEW;
}
public void setGradeEW(double gradeEW) {
this.gradeEW = gradeEW;
}
public double getGradeNS() {
return gradeNS;
}
public void setGradeNS(double gradeNS) {
this.gradeNS = gradeNS;
}
public double getGradeKmEW() {
return gradeKmEW;
}
public void setGradeKmEW(double gradeKmEW) {
this.gradeKmEW = gradeKmEW;
}
public double getGradeKmNS() {
return gradeKmNS;
}
public void setGradeKmNS(double gradeKmNS) {
this.gradeKmNS = gradeKmNS;
}
private String unidadeDaVariavel;
public Point2D getPosition() {
return position;
}
public void setPosition(Point2D position) {
this.position = position;
}
public int getBaciaCodigo() {
return BaciaCodigo;
}
public void setBaciaCodigo(int baciaCodigo) {
BaciaCodigo = baciaCodigo;
}
public int getSubBaciaCodigo() {
return SubBaciaCodigo;
}
public void setSubBaciaCodigo(int subBaciaCodigo) {
SubBaciaCodigo = subBaciaCodigo;
}
public String getEstacao_codigo() {
return Estacao_codigo;
}
public void setEstacao_codigo(String estacao_codigo) {
Estacao_codigo = estacao_codigo;
}
public double getLatitude() {
return Latitude;
}
public void setLatitude(double latitude) {
Latitude = latitude;
}
public double getLongitude() {
return Longitude;
}
public void setLongitude(double longitude) {
Longitude = longitude;
}
public double getAltitude() {
return Altitude;
}
public void setAltitude(double altitude) {
Altitude = altitude;
}
public double getAreaDrenagem() {
return AreaDrenagem;
}
public void setAreaDrenagem(double areaDrenagem) {
AreaDrenagem = areaDrenagem;
}
public int getOrigemSerie() {
return OrigemSerie;
}
public void setOrigemSerie(int origemSerie) {
OrigemSerie = origemSerie;
}
public String getDescricaoOrigemSerie() {
return DescricaoOrigemSerie;
}
public void setDescricaoOrigemSerie(String descricaoOrigemSerie) {
DescricaoOrigemSerie = descricaoOrigemSerie;
}
public String getDiscretizaçãoTemporária() {
return DiscretizaçãoTemporária;
}
public void setDiscretizaçãoTemporária(String discretizaçãoTemporária) {
DiscretizaçãoTemporária = discretizaçãoTemporária;
}
public String getTipodeDado() {
return TipodeDado;
}
public void setTipodeDado(String tipodeDado) {
TipodeDado = tipodeDado;
}
public int getMesAnoHidro() {
return MesAnoHidro;
}
public void setMesAnoHidro(int mesAnoHidro) {
MesAnoHidro = mesAnoHidro;
}
public String getDataInicialstr() {
return dataInicialstr;
}
public void setDataInicialstr(String dataInicialstr) {
this.dataInicialstr = dataInicialstr;
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
try {
this.setDataIni(formatter.parse(dataInicialstr));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String getDataFinalstr() {
return dataFinalstr;
}
public void setDataFinalstr(String dataFinalstr) {
this.dataFinalstr = dataFinalstr;
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
try {
this.setDataFim(formatter.parse(dataFinalstr));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String getNomedaEstacao() {
return NomedaEstacao;
}
public void setNomedaEstacao(String nomedaEstacao) {
NomedaEstacao = nomedaEstacao;
}
public double getThiessenArea() {
return ThiessenArea;
}
public void setThiessenArea(double thiessenArea) {
ThiessenArea = thiessenArea;
}
public double getThiessenCoef() {
return ThiessenCoef;
}
public void setThiessenCoef(double thiessenCoef) {
ThiessenCoef = thiessenCoef;
}
public String getDataInicial() {
return dataInicial;
}
public void setDataInicial(String dataInicial) {
this.dataInicial = dataInicial;
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
try {
this.setDataIni(formatter.parse(dataInicial));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String getDataFinal() {
return dataFinal;
}
public void setDataFinal(String dataFinal) {
this.dataFinal = dataFinal;
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
try {
this.setDataFim(formatter.parse(dataFinal));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public int getnAnosSF() {
return nAnosSF;
}
public void setnAnosSF(int nAnosSF) {
this.nAnosSF = nAnosSF;
}
public String getNomedoRio() {
return nomedoRio;
}
public void setNomedoRio(String nomedoRio) {
this.nomedoRio = nomedoRio;
}
public String getMunicipio() {
return municipio;
}
public void setMunicipio(String municipio) {
this.municipio = municipio;
}
public String getCodmunicipio() {
return codmunicipio;
}
public void setCodmunicipio(String codmunicipio) {
this.codmunicipio = codmunicipio;
}
public String getCodrio() {
return codrio;
}
public void setCodrio(String codrio) {
this.codrio = codrio;
}
public String getUnidadeDaVariavel() {
return unidadeDaVariavel;
}
public void setUnidadeDaVariavel(String unidadeDaVariavel) {
this.unidadeDaVariavel = unidadeDaVariavel;
}
public Double getResolLatyKm() {
return resolLatyKm;
}
public void setResolLatyKm(Double resolLatyKm) {
this.resolLatyKm = resolLatyKm;
}
public Double getResolLaty() {
return resolLaty;
}
public void setResolLaty(Double resolLaty) {
this.resolLaty = resolLaty;
}
public Double getResolLonxKm() {
return resolLonxKm;
}
public void setResolLonxKm(Double resolLonxKm) {
this.resolLonxKm = resolLonxKm;
}
public Double getResolLonx() {
return resolLonx;
}
public void setResolLonx(Double resolLonx) {
this.resolLonx = resolLonx;
}
public String getNomeRegiaoHidrografica() {
return nomeRegiaoHidrografica;
}
public void setNomeRegiaoHidrografica(String nomeRegiaoHidrografica) {
this.nomeRegiaoHidrografica = nomeRegiaoHidrografica;
}
public Geometry getGradePoligono() {
return gradePoligono;
}
public void setGradePoligono(Geometry gradePoligono) {
this.gradePoligono = gradePoligono;
}
public Point getGradeCentroide() {
return gradeCentroide;
}
public void setGradeCentroide(Point gradeCentroide) {
this.gradeCentroide = gradeCentroide;
}
public Double getAreaKm2() {
return areaKm2;
}
public void setAreaKm2(Double areaKm2) {
this.areaKm2 = areaKm2;
}
public ArrayList<String> getNomesRHsCompartilhadas() {
return nomesRHsCompartilhadas;
}
public void setNomesRHsCompartilhadas(ArrayList<String> nomesRHsCompartilhadas) {
this.nomesRHsCompartilhadas = nomesRHsCompartilhadas;
}
public Map<String,Geometry> getGradePoligonoCompartilhadas() {
return gradePoligonoCompartilhadas;
}
public void setGradePoligonoCompartilhadas(
Map<String,Geometry> gradePoligonoCompartilhadas) {
this.gradePoligonoCompartilhadas = gradePoligonoCompartilhadas;
}
public double getAreaDaGradeKm2() {
return areaDaGradeKm2;
}
public void setAreaDaGradeKm2(double areaDaGradeKm2) {
this.areaDaGradeKm2 = areaDaGradeKm2;
}
public boolean isSelecionadaApoio() {
return selecionadaApoio;
}
public void setSelecionadaApoio(boolean selecionadaApoio) {
this.selecionadaApoio = selecionadaApoio;
}
public boolean isSelecionadaPrincipal() {
return selecionadaPrincipal;
}
public void setSelecionadaPrincipal(boolean selecionadaPrincipal) {
this.selecionadaPrincipal = selecionadaPrincipal;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Date getDataIni() {
return dataIni;
}
public void setDataIni(Date dataIni) {
this.dataIni = dataIni;
}
public Date getDataFim() {
return dataFim;
}
public void setDataFim(Date dataFim) {
this.dataFim = dataFim;
}
public String getCodHidroNivelConsistencia() {
return codHidroNivelConsistencia;
}
public void setCodHidroNivelConsistencia(String codHidroNivelConsistencia) {
this.codHidroNivelConsistencia = codHidroNivelConsistencia;
}
public String getNomeTabelaBDHidro() {
return nomeTabelaBDHidro;
}
public void setNomeTabelaBDHidro(String nomeTabelaBDHidro) {
this.nomeTabelaBDHidro = nomeTabelaBDHidro;
}
public String getNomeCampoTipoVarHidro() {
return nomeCampoTipoVarHidro;
}
public void setNomeCampoTipoVarHidro(String nomeCampoTipoVarHidro) {
this.nomeCampoTipoVarHidro = nomeCampoTipoVarHidro;
}
public String getNivelconsistenciaNome() {
return nivelconsistenciaNome;
}
public void setNivelconsistenciaNome(String nivelconsistenciaNome) {
this.nivelconsistenciaNome = nivelconsistenciaNome;
}
public boolean isExisteInventarioBD() {
return existeInventarioBD;
}
public void setExisteInventarioBD(boolean existeInventarioBD) {
this.existeInventarioBD = existeInventarioBD;
}
public String getNomeTabelaBD() {
return nomeTabelaBD;
}
public void setNomeTabelaBD(String nomeTabelaBD) {
this.nomeTabelaBD = nomeTabelaBD;
}
public String getCobacia() {
return cobacia;
}
public void setCobacia(String cobacia) {
this.cobacia = cobacia;
}
public int [] getnAnosSFSazonal() {
return nAnosSFSazonal;
}
public void setnAnosSFSazonal(int [] nAnosSFSazonal) {
this.nAnosSFSazonal = nAnosSFSazonal;
}
public String getCodigoResponsavel() {
return codigoResponsavel;
}
public void setCodigoResponsavel(String codigoResponsavel) {
this.codigoResponsavel = codigoResponsavel;
}
public String getCodigoOperadora() {
return codigoOperadora;
}
public void setCodigoOperadora(String codigoOperadora) {
this.codigoOperadora = codigoOperadora;
}
public String getCodigoAdicional() {
return codigoAdicional;
}
public void setCodigoAdicional(String codigoAdicional) {
this.codigoAdicional = codigoAdicional;
}
public String getSiglaResponsavel() {
return siglaResponsavel;
}
public void setSiglaResponsavel(String siglaResponsavel) {
this.siglaResponsavel = siglaResponsavel;
}
public String getSiglaOperadora() {
return siglaOperadora;
}
public void setSiglaOperadora(String siglaOperadora) {
this.siglaOperadora = siglaOperadora;
}
public String getEmoperacao() {
return emoperacao;
}
public void setEmoperacao(String emoperacao) {
this.emoperacao = emoperacao;
}
public String getUltimaAtualizacao() {
return ultimaAtualizacao;
}
public void setUltimaAtualizacao(String ultimaAtualizacao) {
this.ultimaAtualizacao = ultimaAtualizacao;
}
}
<file_sep>package tests.autocorrelationApproaches;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics;
import tests.MannKendallTest;
import types.DadoTemporal;
public class TFPWcunbPW {
/**
* Aqui só tira a tendencia pra estimar o Ro depois faz o PW na amostra original
* @param amostra
* @return
*/
public Map<String,DadoTemporal> executar (Map<String,DadoTemporal> serieMapa) {
ArrayList<DadoTemporal> dadostot = new ArrayList<DadoTemporal>();
Set<String> chavesMax = serieMapa.keySet();
for (String data : chavesMax){
DadoTemporal dado = serieMapa.get(data);
dadostot.add(dado);
}
//
Collections.sort(dadostot);
FuncaoAutoCorrelacaoAnual facOriginal =new FuncaoAutoCorrelacaoAnual(dadostot);
Map<Integer,DadoTemporal> mapaAnoDadosOriginal=facOriginal.getMapaAnoDados();
Map<Integer,Integer>mapaAnoOrdem=PegarOrdemCronologicaAnoSerieTemporal.pegarMapaAnoOrdem(dadostot);
Map<String,DadoTemporal> Yt=new HashMap<String,DadoTemporal>(); //Serie com tendencia (original) removida
Map<Integer,Double> Ylt=new HashMap<Integer,Double>(); // Serie com autocorrelação removida
Map<Integer,Double> Y=new HashMap<Integer,Double>(); //Serie com adicao da tendencia mas sem correlacao
Map<String,DadoTemporal> serieMapaY=new HashMap<String,DadoTemporal>(); //Serie MAPA com adicao da tendencia mas sem correlacao
/**
* Calcula o b de sen (slope ou declividade)
*/
double bsemCronologia=MagnitudeTendencia.bSen(dadostot);
double b=MagnitudeTendencia.bSenRespeitandoCronologia(dadostot);
Set<Integer> chaves = mapaAnoDadosOriginal.keySet();
int ival=0;
for (Integer ano : chaves){
DadoTemporal dado=new DadoTemporal();
//double t=ano; //Importante para considerar a distancia entre dois anos que entre eles exista falha
double t=mapaAnoOrdem.get(ano);
double xt=mapaAnoDadosOriginal.get(ano).getValor();
double yt=xt-b*t;
dado.setData(mapaAnoDadosOriginal.get(ano).getData());
dado.setValor(yt);
Yt.put(mapaAnoDadosOriginal.get(ano).getDataStr(), dado);
ival++;
}
int klag=1;
FuncaoAutoCorrelacaoAnual fac =new FuncaoAutoCorrelacaoAnual(Yt);
double r1Original=fac.correlLagMapa(1);
//int n=facOriginal.getSeries1().length+1;
int n=ival;
//int n=dadostot.size();
double r1AmostralCorrigido=(n*r1Original+2)/(n-4);
String resultado=TesteCorrelacaoLag1Tradicional.executar(r1AmostralCorrigido, n);
if(resultado.equals("NS")) {
return serieMapa;
}
ArrayList<Integer>ano=facOriginal.getAno();
Map<Integer,DadoTemporal> mapaAnoDados=facOriginal.getMapaAnoDados();
for (int i=0;i<ano.size();i++){
Integer anolag=ano.get(i)-klag;
if(mapaAnoDadosOriginal.containsKey(anolag)){
if(mapaAnoDadosOriginal.get(anolag).getValor() != -99999. || mapaAnoDadosOriginal.get(anolag).getValor() > 0){
double yt=mapaAnoDadosOriginal.get(ano.get(i)).getValor();
double yt1=mapaAnoDadosOriginal.get(anolag).getValor();
double ylt=yt-r1AmostralCorrigido*yt1;
Ylt.put(ano.get(i), ylt);
}
}
}
Set<Integer> chavesAno = Ylt.keySet();
for (Integer anoFinal : chavesAno){
double t=mapaAnoOrdem.get(anoFinal);
double ylt=Ylt.get(anoFinal);
//double y=ylt+b*t;
Y.put(anoFinal, ylt);
DadoTemporal dado=new DadoTemporal();
String datastr="01/01/"+anoFinal;
dado.setData(datastr);
dado.setValor(ylt);
serieMapaY.put(datastr, dado);
}
return serieMapaY;
}
public ArrayList<Double> executar(ArrayList<Double> amostra){
ArrayList<Double> amostraDetrend=new ArrayList<Double>();
double bsen=MagnitudeTendencia.bSenDouble(amostra);
for(int i=0;i<amostra.size();i++) {
int t=i+1;
double xt=amostra.get(i);
double xtmod=xt-bsen*t;
amostraDetrend.add(xtmod);
}
PegarRoLag1 estimarRo1=new PegarRoLag1();
estimarRo1.executar(amostraDetrend);
//double r1=estimarRo1.getR1amostral();
double r1corrigido=estimarRo1.getR1AmostralCorrigido();
int n=amostra.size();
String resultado=TesteCorrelacaoLag1Tradicional.executar(r1corrigido, n);
if(resultado.equals("NS")) {
return amostra;
}
ArrayList<Double> amostraPW=new ArrayList<Double>();
for(int i=1;i<amostra.size();i++) {
//int t=i+1;
double xtmodmenos1=amostra.get(i-1);
double xtmod=amostra.get(i);
double ytmod=xtmod-r1corrigido*xtmodmenos1;
amostraPW.add(ytmod);
}
return amostraPW;
}
public ArrayList<Double> executar_V2(ArrayList<Double> amostra){
/*ArrayList<Double> amostraDetrend=new ArrayList<Double>();
double bsen=MagnitudeTendencia.bSenDouble(amostra);
for(int i=0;i<amostra.size();i++) {
int t=i+1;
double xt=amostra.get(i);
double xtmod=xt-bsen*t;
amostraDetrend.add(xtmod);
}*/
boolean foiSignificativo=false;
MannKendallTest mkteste=new MannKendallTest(amostra);
mkteste.teste1();
double pvalueferahmk=mkteste.getPvalue();
double alfa=0.05;
if(pvalueferahmk < alfa){
foiSignificativo=true;
}
ArrayList<Double> amostraDetrend=new ArrayList<Double>();
DescriptiveStatistics amostraXtmod=new DescriptiveStatistics();
//DescriptiveStatistics amostraYtmod=new DescriptiveStatistics();
double bsen=MagnitudeTendencia.bSenDouble(amostra);
if(foiSignificativo) {
for(int i=0;i<amostra.size();i++) {
int t=i+1;
double xt=amostra.get(i);
double xtmod=xt-bsen*t;
amostraXtmod.addValue(xtmod);
amostraDetrend.add(xtmod);
}
}else{
double bsennulo=0.0;
for(int i=0;i<amostra.size();i++) {
int t=i+1;
double xt=amostra.get(i);
double xtmod=xt-bsennulo*t;
amostraXtmod.addValue(xtmod);
amostraDetrend.add(xtmod);
}
}
PegarRoLag1 estimarRo1=new PegarRoLag1();
estimarRo1.executar(amostraDetrend);
//double r1=estimarRo1.getR1amostral();
double r1corrigido=estimarRo1.getR1AmostralCorrigido();
int n=amostra.size();
String resultado=TesteCorrelacaoLag1Tradicional.executar(r1corrigido, n);
if(resultado.equals("NS")) {
return amostra;
}
ArrayList<Double> amostraPW=new ArrayList<Double>();
for(int i=1;i<amostra.size();i++) {
//int t=i+1;
double xtmodmenos1=amostra.get(i-1);
double xtmod=amostra.get(i);
double ytmod=xtmod-r1corrigido*xtmodmenos1;
amostraPW.add(ytmod);
}
return amostraPW;
}
public ArrayList<Double> executar_V3(ArrayList<Double> amostra){
ArrayList<Double> amostraDetrend=new ArrayList<Double>();
double bsen=MagnitudeTendencia.bSenDouble(amostra);
for(int i=0;i<amostra.size();i++) {
int t=i+1;
double xt=amostra.get(i);
double xtmod=xt-bsen*t;
amostraDetrend.add(xtmod);
}
PegarRoLag1 estimarRo1=new PegarRoLag1();
estimarRo1.executar(amostraDetrend);
double r1=estimarRo1.getR1amostral();
//double r1corrigido=estimarRo1.getR1AmostralCorrigido();
int n=amostra.size();
String resultado=TesteCorrelacaoLag1Tradicional.executar(r1, n);
if(resultado.equals("NS")) {
return amostra;
}
ArrayList<Double> amostraPW=new ArrayList<Double>();
for(int i=1;i<amostra.size();i++) {
//int t=i+1;
double xtmodmenos1=amostra.get(i-1);
double xtmod=amostra.get(i);
double ytmod=xtmod-r1*xtmodmenos1;
amostraPW.add(ytmod);
}
return amostraPW;
}
}
<file_sep>package types;
public class ConfiguraSeries {
private int mesIni;
private int mesFim;
/**
* tipoSerie == 0 - CF
* tipoSerie == 1 - SF
* tipoSerie == 2 - CFT
*/
private int TipoSerieFalha;
/**
* VALIDO PARA TipoSerieFalha = CFT
*/
private Double tolFalhaMax;
private int anoIniSubConjunto;
private int anoFimSubConjunto;
private int tamanhoMinimo;
private String TipoSerieFalhaHidro;
/**
* A ideia do codigo é no futuro saber em qual modulo essa configuração se refere
*/
private String codConfiguracao;
/**
* codEstatistica = 0 - SOMA
* codEstatistica = 1 - MEDIA
* codEstatistica = 2 - DESVPAD
* codEstatistica = 3 - ASSIMETRIA
* codEstatistica = 4 - CURTOSE
* codEstatistica = 5 - MAXIMOS
* codEstatistica = 6 - MINIMOS
*/
private int codEstatistica;
public ConfiguraSeries(){
}
public ConfiguraSeries(String codConfiguracao){
this.codConfiguracao=codConfiguracao;
}
public int getMesIni() {
return mesIni;
}
public void setMesIni(int mesIni) {
this.mesIni = mesIni;
}
public int getMesFim() {
return mesFim;
}
public void setMesFim(int mesFim) {
this.mesFim = mesFim;
}
public Double getTolFalhaMax() {
return tolFalhaMax;
}
public void setTolFalhaMax(Double tolFalhaMax) {
this.tolFalhaMax = tolFalhaMax;
}
public int getTipoSerieFalha() {
return TipoSerieFalha;
}
public void setTipoSerieFalha(int tipoSerieFalha) {
TipoSerieFalha = tipoSerieFalha;
}
public int getAnoIniSubConjunto() {
return anoIniSubConjunto;
}
public void setAnoIniSubConjunto(int anoIniSubConjunto) {
this.anoIniSubConjunto = anoIniSubConjunto;
}
public int getAnoFimSubConjunto() {
return anoFimSubConjunto;
}
public void setAnoFimSubConjunto(int anoFimSubConjunto) {
this.anoFimSubConjunto = anoFimSubConjunto;
}
public int getTamanhoMinimo() {
return tamanhoMinimo;
}
public void setTamanhoMinimo(int tamanhoMinimo) {
this.tamanhoMinimo = tamanhoMinimo;
}
public String getCodConfiguracao() {
return codConfiguracao;
}
public void setCodConfiguracao(String codConfiguracao) {
this.codConfiguracao = codConfiguracao;
}
public String getTipoSerieFalhaHidro() {
return TipoSerieFalhaHidro;
}
public void setTipoSerieFalhaHidro(String tipoSerieFalhaHidro) {
TipoSerieFalhaHidro = tipoSerieFalhaHidro;
}
public int getCodEstatistica() {
return codEstatistica;
}
public void setCodEstatistica(int codEstatistica) {
this.codEstatistica = codEstatistica;
}
}
<file_sep>package io;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.StringTokenizer;
import javax.swing.JButton;
import javax.swing.JTextArea;
import javax.swing.ProgressMonitor;
import javax.swing.SwingWorker;
import types.DadoTemporal;
import types.InventarioHidrologico;
import types.SerieTemporal;
import types.SimulationDataExtremos;
import types.VariavelHidrologica;
/*import org.snirh.extremos_unb.deteccao.gui.PanelImportarDados;
import org.snirh.extremos_unb.deteccao.io.LeituraDATEstacionaridade;
import org.snirh.extremos_unb.tipos.DadoTemporal;
import org.snirh.extremos_unb.tipos.InventarioHidrologico;
import org.snirh.extremos_unb.tipos.SerieTemporal;
import org.snirh.extremos_unb.tipos.SimulationDataExtremos;
import org.snirh.extremos_unb.tipos.VariavelHidrologica;
import org.snirh.extremos_unb.util.Messages;*/
public class MAR_ImportDataDAO {
private ProgressMonitor progressMonitor;
private JButton startButton;
private JTextArea taskOutput;
private ArrayList<VariavelHidrologica> vhidExistente;
private boolean adicionar_estac;
private int nseries;
private String tabulacao;
private int nestac;
//public ArrayList<VariavelHidrologica> leituraDATVarHidSemBarraProgresso(final SimulationDataExtremos simulationData,PanelImportarDados pnd) {
public ArrayList<VariavelHidrologica> leituraDATVarHidSemBarraProgresso(String dir,String nomearq) {
ArrayList<VariavelHidrologica> variaveishidrologicasSheet=new ArrayList<VariavelHidrologica>();
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
//String dir=simulationData.getDataDirBD();
//String nomearq=simulationData.getFilenameBD();
if(nomearq.contains(".dat") == false){
nomearq=nomearq+".dat";
}
String modelDir=dir+nomearq;
BufferedReader file = null;
int nLinhasArquivo = 0;
try{
file = new BufferedReader(new FileReader(modelDir));
File arquivo = new File(modelDir);
LineNumberReader lineRead = new LineNumberReader(new FileReader(arquivo));
lineRead.skip(arquivo.length());
nLinhasArquivo = lineRead.getLineNumber();
StringTokenizer tok2 = null;
int nseries=0;
ArrayList<String> strInvHidDAT=new ArrayList<String>();
int nLinhasArquivoInventario=15;
for(int i=0;i<nLinhasArquivoInventario;i++){
strInvHidDAT.add(file.readLine());
}
ArrayList<InventarioHidrologico> invhidTot=this.SetarInventarioVariavelHidrologica(strInvHidDAT);
for(int i=0;i<this.nseries;i++){
SerieTemporal serietemp = new SerieTemporal ();
ArrayList<DadoTemporal> dados = new ArrayList<DadoTemporal>();
VariavelHidrologica vhid=new VariavelHidrologica();
vhid.setInvhidro(invhidTot.get(i));
vhid.setSerietemporal(serietemp);
vhid.getSerietemporal().setDados(dados);
variaveishidrologicasSheet.add(vhid);
}
//simulationData.setVariaveisHidr(variaveishidrologicasSheet);
int nlinhasVazio=6;
for(int i=0;i<nlinhasVazio;i++){
file.readLine();
}
//setProgress(0);
String textointerface= "Iniciando leitura a estação ";
// publish(textointerface);
int nLinhasSeries=nLinhasArquivo-(nLinhasArquivoInventario+nlinhasVazio);
int tot=this.nseries;
int progress = 0;
//setProgress(0);
int totlinhas=nLinhasSeries;
for(int i=0;i<nLinhasSeries;i++){
if(i==nLinhasSeries-1){
System.out.println();
}
if(i==920){
System.out.println();
}
String linhaStr=file.readLine();
String[] str = linhaStr.split(this.tabulacao);
int i1=0;
for(int j=0;j<this.nseries;j++){
double progress2 = ((i+1)*1.0/(totlinhas*1.0))*100;
progress=(int) progress2;
// setProgress(Math.min(progress, 100));
textointerface= "Aguarde..lendo o registro "+(i+1)+"/"+totlinhas+" da estação "+(j+1)+"/"+tot+"";
// publish(textointerface);
System.out.println(textointerface);
if(i == 1735 && j == 29){
System.out.println();
}
String vdata=str[i1];
String vval=str[i1+1];
//varData.add(str[i1]);
//varValor.add(str[i1+1]);
DadoTemporal dado=new DadoTemporal();
if(vdata.equals("-99999")){
System.out.println(vdata);
}
if(vdata.equals("")){
System.out.println(vdata);
}
if(!vdata.equals("null") && !vdata.equals("") && !vdata.equals("-99999")){
Date utilDate = new Date();
String dataStrdia= vdata;
try {
utilDate = formatter.parse(dataStrdia);
} catch (ParseException e) {
e.printStackTrace();
}
//dado.setData(utilDate);
/**
* Saulo - 19/11/2015
*/
dado.setData(vdata);
if(!(vval.equals("null") || vval.equals(""))){
dado.setValor(Double.parseDouble((vval)));
}else{
dado.setValor(-99999.0);
}
variaveishidrologicasSheet.get(j).getSerietemporal().getDados().add(dado);
}
//dados.add(dado);
i1=i1+2;
}
}
//textointerface= "Aguarde..lendo o registro "+totlinhas+"/"+totlinhas+" da estação "+tot+"/"+tot+"";
//publish(textointerface);
this.nestac=tot;
for(int i=0;i<variaveishidrologicasSheet.size();i++){
int ndados=variaveishidrologicasSheet.get(i).getSerietemporal().getDados().size();
Collections.sort(variaveishidrologicasSheet.get(i).getSerietemporal().getDados());
Calendar dataInicialSerie= Calendar.getInstance();
Calendar dataFinalSerie= Calendar.getInstance();
dataInicialSerie.setTime(variaveishidrologicasSheet.get(i).getSerietemporal().getDados().get(0).getData());
dataFinalSerie.setTime(variaveishidrologicasSheet.get(i).getSerietemporal().getDados().get(ndados-1).getData());
Date dini=dataInicialSerie.getTime();
String dataInistr=formatter.format(dini);
variaveishidrologicasSheet.get(i).getInvhidro().setDataInicialstr(dataInistr);
Date dfim=dataFinalSerie.getTime();
String dataFimstr=formatter.format(dfim);
variaveishidrologicasSheet.get(i).getInvhidro().setDataFinalstr(dataFimstr);
variaveishidrologicasSheet.get(i).getSerietemporal().setDataInicialSerie(dataInicialSerie);
variaveishidrologicasSheet.get(i).getSerietemporal().setDataFinalSerie(dataFinalSerie);
variaveishidrologicasSheet.get(i).getSerietemporal().setaMapaStrDadoTemporal();
}
// this.simulationData.setVariaveisHidr(variaveishidrologicasSheet);
}catch(IOException e){
e.printStackTrace();
}
try {
file.close();
} catch (IOException e) {
e.printStackTrace();
}
return variaveishidrologicasSheet;
}
private ArrayList<InventarioHidrologico> SetarInventarioVariavelHidrologica(ArrayList<String> strInvHidDAT){
ArrayList<InventarioHidrologico> inventarioDAT=new ArrayList<InventarioHidrologico>();
this.tabulacao=" ";
if(strInvHidDAT.get(0).contains(";")){
this.tabulacao=";";
}
String[] str2 =strInvHidDAT.get(0).split(tabulacao);
int nVariaveis=strInvHidDAT.size();
this.nseries=str2.length/2;
Object [][] varInventario=new Object[this.nseries][nVariaveis];
for (int k = 0; k < nVariaveis; k++){
String[] str =strInvHidDAT.get(k).split(tabulacao);
int i1=0;
for(int i=0;i<this.nseries;i++){
varInventario[i][k]=str[i1+1];
i1=i1+2;
}
}
int tot=this.nseries;
int progress = 0;
// setProgress(0);
for(int j=0;j<this.nseries;j++){
InventarioHidrologico invhid = new InventarioHidrologico();
for (int k = 0; k < nVariaveis; k++){
double progress2 = ((j+1)*1.0/(tot*1.0))*100;
progress=(int) progress2;
// setProgress(Math.min(progress, 100));
String textointerface= "Aguarde.. verificando a estação "+(j+1)+"/"+tot+"";
// publish(textointerface);
if(k == 0){
invhid.setBaciaCodigo(Integer.parseInt((String) varInventario[j][k]));
} else if(k == 1){
invhid.setSubBaciaCodigo(Integer.parseInt((String)varInventario[j][k]));
}else if(k == 2){
invhid.setEstacao_codigo((String)varInventario[j][k]);
} else if(k == 3){
invhid.setLatitude(Double.parseDouble((String)varInventario[j][k]));
}else if(k == 4){
invhid.setLongitude(Double.parseDouble((String)varInventario[j][k]));
} else if(k == 5){
invhid.setAltitude(Double.parseDouble((String)varInventario[j][k]));
}else if(k == 6){
invhid.setAreaDrenagem(Double.parseDouble((String)varInventario[j][k]));
} else if(k == 7){
invhid.setOrigemSerie(Integer.parseInt((String)varInventario[j][k]));
}else if(k == 8){
invhid.setDescricaoOrigemSerie((String) varInventario[j][k]);
} else if(k == 9){
invhid.setDiscretizaçãoTemporária((String) varInventario[j][k]);
}else if(k == 10){
invhid.setTipodeDado((String) varInventario[j][k]);
} else if(k ==11){
invhid.setMesAnoHidro(Integer.parseInt((String)varInventario[j][k]));
} else if(k ==12){
invhid.setNomedaEstacao(((String)varInventario[j][k]));
} else if(k ==13){
invhid.setNomedoRio(((String)varInventario[j][k]));
}else if(k ==14){
invhid.setMunicipio(((String)varInventario[j][k]));
}
}
inventarioDAT.add(invhid);
}
return inventarioDAT;
}
/*public static void leituraDATVarHid(final SimulationDataExtremos simulationData,PanelImportarDados pnd) {
LeituraDATEstacionaridade mbt= new LeituraDATEstacionaridade(simulationData,pnd);
mbt.addPropertyChangeListener(pnd);
mbt.execute();
// Messages.informMsg("Leitura efetuada com sucesso");
}
public static void leituraDATVarHid(final SimulationDataExtremos simulationData,PanelImportarDados pnd,ArrayList<VariavelHidrologica> vhid) {
LeituraDATEstacionaridade mbt= new LeituraDATEstacionaridade(simulationData,pnd,vhid);
mbt.addPropertyChangeListener(pnd);
mbt.execute();
// Messages.informMsg("Leitura efetuada com sucesso");
}*/
}
<file_sep>package gui;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.util.ArrayList;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.border.EtchedBorder;
import io.ExtensionFileFilter;
import io.MAR_ImportDataDAO;
import io.MAR_ImportDataDAO_TrendBrazil;
import types.SimulationDataExtremos;
import types.VariavelHidrologica;
public class PanelEscolherArquivo extends JFrame implements
PropertyChangeListener{
private static final long serialVersionUID = 1L;
private JFileChooser chooser;
private JPanel panelData;
private JPanel panelButtons;
private JButton btnExecute;
private JButton btnCancel;
private ButtonGroup cboxButtonGroup;
private JRadioButton button1;
private JRadioButton button2;
private JRadioButton button3;
private SimulationDataExtremos simulationData;
private PanelTrendDetectionStreamflowBrazil pnd;
private ExtensionFileFilter filter;
private JFileChooser chooser_xlsx;
private ExtensionFileFilter filter_xlsx;
//BIFURCAÇÃO pnd/pne para criar a regionalização diária (pne)
// Bloco pnd
public PanelEscolherArquivo(SimulationDataExtremos simulationData,PanelTrendDetectionStreamflowBrazil pnd){
super("Choosing the File to Import");
this.simulationData = simulationData;
this.pnd=pnd;
this.createAndShowGUI();
this.createPane();
this.pack();
}
// Bloco pne
private void createPane() {
this.chooser = new JFileChooser(new File("."));
this.filter = new ExtensionFileFilter("dat", "StreamFlow data files (*.dat)");
this.chooser.setFileFilter(this.filter);
this.chooser_xlsx = new JFileChooser(new File("."));
this.filter_xlsx = new ExtensionFileFilter("xlsx", "StreamFlow data files (*.xlsx)");
this.chooser_xlsx.setFileFilter(this.filter_xlsx);
}
private void createAndShowGUI() {
this.setBounds(20, 20, 440, 300);
this.setPreferredSize(new Dimension(440, 300));
this.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
this.setResizable(false);
this.setAlwaysOnTop(true);
this.setLayout(null);
this.formatPanelData();
this.formatPanelButtons();
}
private void formatPanelData(){
this.panelData = new JPanel();
this.panelData.setBorder(new EtchedBorder());
this.panelData.setBounds(10, 10, 290, 255);
this.panelData.setLayout(null);
this.add(this.panelData);
this.formatButtonGroup();
//this.formatLabels();
}
private void formatButtonGroup() {
JPanel panel = new JPanel();
panel.setBounds(10, 10, 265, 235);
JLabel label = new JLabel("Escolha uma da opções:");
panel.add(label);
panel.setLayout(new GridLayout(0, 1));
this.cboxButtonGroup = new ButtonGroup();
button1 = new JRadioButton("DAT");
button1.setSelected(true);
button2 = new JRadioButton("XLSX");
//button3 = new JRadioButton("Importar dados de média ja calculados.");
this.cboxButtonGroup.add(button1);
this.cboxButtonGroup.add(button2);
//this.cboxButtonGroup.add(button3);
panel.add(button1);
panel.add(button2);
//panel.add(button3);
this.panelData.add(panel);
}
private void formatPanelButtons() {
this.panelButtons = new JPanel();
this.panelButtons.setBorder(new EtchedBorder());
this.panelButtons.setBounds(310, 10, 110, 255);
this.panelButtons.setLayout(null);
this.add(this.panelButtons);
this.btnExecute = new JButton("Open");
this.btnExecute.setToolTipText("Open a selected file that will be used to trend analysis");
this.btnExecute.setBounds(10, 10, 90, 25);
this.btnExecute.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
buttonAction(btnExecute);
}
});
this.panelButtons.add(this.btnExecute, JLayeredPane.DEFAULT_LAYER);
this.btnCancel = new JButton("Add");
this.btnCancel.setToolTipText("Add the series from the selected file to the study");
this.btnCancel.setBounds(10, 40, 90, 25);
this.btnCancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
buttonAction(btnCancel);
}
});
this.panelButtons.add(this.btnCancel, JLayeredPane.DEFAULT_LAYER);
}
private void buttonAction(JButton jb){
if (jb.equals(this.btnExecute)){
this.AbrirNovosDados();
}else if (jb.equals(this.btnCancel)){
this.AdicionarDados();
//this.setVisible(false);
}
this.setVisible(false);
}
public void AdicionarDados() {
if(this.button1.isSelected()){
String dir = null;
String filename = null;
//Messages.informMsg("Indique o arquivo .dat");
int returnVal = this.chooser.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
dir = this.chooser.getCurrentDirectory().getAbsolutePath() + "\\";
filename = this.chooser.getSelectedFile().getName();
}
this.simulationData.setFilenameBD(filename);
this.simulationData.setDataDirBD(dir);
ArrayList<VariavelHidrologica> variaveishidrologicasExistentes=new ArrayList<VariavelHidrologica>();
if(!(this.simulationData.getVariaveisHidr() == null)){
for (int k = 0; k < this.simulationData.getVariaveisHidr().size(); k++){
if(this.simulationData.getVariaveisHidr().get(k).isSelecionada()) {
variaveishidrologicasExistentes.add(this.simulationData.getVariaveisHidr().get(k));
}
}
}
if(!(this.pnd == null)){
//MARDaily_FACADE mardaily = MARDaily_FACADE.getInstance();
//mardaily.leituraDATVarHid(this.simulationData, this.pnd,variaveishidrologicasExistentes);
MAR_ImportDataDAO_TrendBrazil.leituraDATVarHid(simulationData, pnd,variaveishidrologicasExistentes);
}
}else if(this.button2.isSelected()){
String dir = null;
String filename = null;
//Messages.informMsg("Indique o arquivo .dat");
int returnVal = this.chooser_xlsx.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
dir = this.chooser_xlsx.getCurrentDirectory().getAbsolutePath() + "\\";
filename = this.chooser_xlsx.getSelectedFile().getName();
}
this.simulationData.setFilenameBD(filename);
this.simulationData.setDataDirBD(dir);
ArrayList<VariavelHidrologica> variaveishidrologicasExistentes=new ArrayList<VariavelHidrologica>();
if(!(this.simulationData.getVariaveisHidr() == null)){
for (int k = 0; k < this.simulationData.getVariaveisHidr().size(); k++){
if(this.simulationData.getVariaveisHidr().get(k).isSelecionada()) {
variaveishidrologicasExistentes.add(this.simulationData.getVariaveisHidr().get(k));
}
}
}
// MARDaily_FACADE mardaily = MARDaily_FACADE.getInstance();
if(!(this.pnd == null)){
//mardaily.leituraXLSVarHid(this.simulationData, this.pnd,variaveishidrologicasExistentes);
}
}
}
public void AbrirNovosDados() {
String dir = null;
String filename = null;
//Messages.informMsg("Indique o arquivo .dat");
if(this.button1.isSelected()){
int returnVal = this.chooser.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
dir = this.chooser.getCurrentDirectory().getAbsolutePath() + "\\";
filename = this.chooser.getSelectedFile().getName();
}
this.simulationData.setFilenameBD(filename);
this.simulationData.setDataDirBD(dir);
if(!(this.simulationData.getVariaveisHidr() == null)){
this.simulationData.setVariaveisHidr(null);
}
// MARDaily_FACADE mardaily = MARDaily_FACADE.getInstance();
if(!(this.pnd == null)){
//mardaily.leituraDATVarHid(simulationData, this.pnd);
MAR_ImportDataDAO_TrendBrazil.leituraDATVarHid(simulationData, this.pnd);
}
}else if(this.button2.isSelected()){
int returnVal = this.chooser_xlsx.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
dir = this.chooser_xlsx.getCurrentDirectory().getAbsolutePath() + "\\";
filename = this.chooser_xlsx.getSelectedFile().getName();
}
this.simulationData.setFilenameBD(filename);
this.simulationData.setDataDirBD(dir);
if(!(this.simulationData.getVariaveisHidr() == null)){
this.simulationData.setVariaveisHidr(null);
}
//MARDaily_FACADE mardaily = MARDaily_FACADE.getInstance();
//mardaily.leituraXLSVarHid(simulationData, this.pnd);
}
}
@Override
public void propertyChange(PropertyChangeEvent arg0) {
// TODO Auto-generated method stub
}
}
<file_sep>package util;
public class PegarNomesTestes {
public static String [] nomeCompleto(){
int ntestes=14;
String [] nometesteExtenso=new String [ntestes];
nometesteExtenso[0]="Mann-Kendall";
nometesteExtenso[1]="<NAME>";
nometesteExtenso[2]="Linear Regression";
nometesteExtenso[3]="Teste T";
nometesteExtenso[4]="Distribution CUSUM";
nometesteExtenso[5]="Cumulative Deviation";
nometesteExtenso[6]="Worsley Lik. Ratio";
nometesteExtenso[7]="Rank-Sum (Mann-Whitney)";
nometesteExtenso[8]="Teste F";
nometesteExtenso[9]="Median Crossing";
nometesteExtenso[10]="Turning Points";
nometesteExtenso[11]="Rank Difference";
nometesteExtenso[12]="Autocorrelation";
nometesteExtenso[13]="Wald-Wolfowitz";
return nometesteExtenso;
}
public static String [] siglaTeste(){
int ntestes=14;
String [] nometeste=new String [ntestes];
nometeste[0]="MK";
nometeste[1]="SR";
nometeste[2]="LR";
nometeste[3]="TT";
nometeste[4]="DC";
nometeste[5]="CD";
nometeste[6]="WR";
nometeste[7]="MW";
nometeste[8]="TF";
nometeste[9]="MC";
nometeste[10]="TP";
nometeste[11]="RD";
nometeste[12]="AC";
nometeste[13]="WW";
return nometeste;
}
}
<file_sep>package io;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFileChooser;
import javax.swing.JTextArea;
import javax.swing.ProgressMonitor;
import javax.swing.SwingWorker;
import gui.PanelTrendDetectionStreamflowBrazil;
import types.ResultEstacionaridade;
import types.SimulationDataExtremos;
import types.VariavelHidrologica;
/*import org.snirh.extremos_unb.deteccao.gui.PanelTestesEstatisticos;
import org.snirh.extremos_unb.deteccao.testes.ResultEstacionaridade;
import org.snirh.extremos_unb.tipos.SimulationDataExtremos;
import org.snirh.extremos_unb.tipos.VariavelHidrologica;
import org.snirh.extremos_unb.util.ExtensionFileFilter;*/
public class StationaritySummary {
private SimulationDataExtremos simulationData;
//private GuiResulEstac guiResultestac;
private PanelTrendDetectionStreamflowBrazil pnt;
public StationaritySummary(SimulationDataExtremos simulationData,PanelTrendDetectionStreamflowBrazil pnt) {
this.simulationData = simulationData;
this.pnt=pnt;
//this.resumoResultadosProgress();
}
public void resumoResultadosProgress(){
executarResumoEstacionaridade boot= new executarResumoEstacionaridade(this.simulationData,this.pnt);
boot.addPropertyChangeListener(this.pnt);
boot.execute();
}
class executarResumoEstacionaridade extends SwingWorker<Void, String> {
private SimulationDataExtremos simulationData;
private PanelTrendDetectionStreamflowBrazil pnt;
private ProgressMonitor progressMonitor;
private JTextArea taskOutput;
private JFileChooser chooser;
private ExtensionFileFilter filter;
public final static String newline = "\n";
public executarResumoEstacionaridade (SimulationDataExtremos simulationData,PanelTrendDetectionStreamflowBrazil pnt){
this.simulationData=simulationData;
this.pnt=pnt;
}
@Override
protected Void doInBackground() throws Exception {
int ntestes=14;
String [] nometeste2=new String [ntestes];
nometeste2[0]="MK";
nometeste2[1]="SR";
nometeste2[2]="LR";
nometeste2[3]="TT";
nometeste2[4]="DC";
nometeste2[5]="CD";
nometeste2[6]="WR";
nometeste2[7]="MW";
nometeste2[8]="TF";
nometeste2[9]="MC";
nometeste2[10]="TP";
nometeste2[11]="RD";
nometeste2[12]="AC";
nometeste2[13]="WW";
String [] nometesteExtenso=new String [ntestes];
nometesteExtenso[0]="Mann-Kendall: ";
nometesteExtenso[1]="Spearman’s Rho: ";
nometesteExtenso[2]="Linear Regression: ";
nometesteExtenso[3]="Teste T: ";
nometesteExtenso[4]="Distribution CUSUM: ";
nometesteExtenso[5]="Cumulative Deviation: ";
nometesteExtenso[6]="Worsley Lik. Ratio: ";
nometesteExtenso[7]="Rank-Sum (Mann-Whitney): ";
nometesteExtenso[8]="Teste F: ";
nometesteExtenso[9]="Median Crossing: ";
nometesteExtenso[10]="Turning Points: ";
nometesteExtenso[11]="Rank Difference: ";
nometesteExtenso[12]="Autocorrelation: ";
nometesteExtenso[13]="Wald-Wolfowitz: ";
String [] nomeTipoEstacio=new String [4];
nomeTipoEstacio[0]="TENDENCIA";
nomeTipoEstacio[1]="SALTO";
nomeTipoEstacio[2]="VARIANCIA";
nomeTipoEstacio[3]="INDEPENDENCIA";
String [] nomeSentidoTend=new String [2];
nomeSentidoTend[0]="Increase";
nomeSentidoTend[1]="Decrease";
String [] nomeSentidoMedia=new String [2];
nomeSentidoMedia[0]="Maior";
nomeSentidoMedia[1]="Menor";
int ndecadas=9;
int [] decada=new int [ndecadas];
String [] nometesteAnoMud=new String [3];
nometesteAnoMud[0]="DC";
nometesteAnoMud[1]="CD";
nometesteAnoMud[2]="WR";
//int decadaIni=1930;
decada[0]=1929;
int passo=10;
for(int i=1;i<ndecadas;i++){
decada[i]=decada[i-1]+passo;
}
double [] resDecadaMudanca= new double [ndecadas];
double [] resDecadaMudanca_S= new double [ndecadas];
double [] resDecadaMudanca_NS= new double [ndecadas];
double [][] resDecadaMudancaTeste= new double [3] [ndecadas];
double [][] resDecadaMudancaTeste_S= new double [3] [ndecadas];
double [][] resDecadaMudancaTeste_NS= new double [3] [ndecadas];
double [] resTipoEstacio_NS= new double [4];
double [] resTipoTeste_NS= new double [14];
double [] resTipoEstacio_S= new double [4];
double [] resTipoTeste_S= new double [14];
double [] resSentidoTend= new double [2];
double [] resSentidoTend_NS= new double [2];
double [] resSentidoTend_S= new double [2];
double [][] resSentidoTendTeste_S= new double [3][2];
double [][] resSentidoTendTeste_NS= new double [3][2];
double [] resSentidoMedia= new double [2];
double [] resSentidoMedia_NS= new double [2];
double [] resSentidoMedia_S= new double [2];
double [][] resSentidoMediaTeste_S= new double [5][2];
double [][] resSentidoMediaTeste_NS= new double [5][2];
/**
* percentuais
*/
double [] percResTipoEstacio_NS= new double [4];
double [] percResTipoEstacio_S= new double [4];
double [] percResTipoTeste_S= new double [14];
double [] percResTipoTeste_NS= new double [14];
double [] percResSentidoTend_S=new double [2];
double [][] percResSentidoTendTeste_S= new double [3][2];
double [] percResSentidoTend_NS=new double [2];
double [][] percResSentidoTendTeste_NS= new double [3][2];
double [] percResSentidoTend= new double [2];
double [] percResSentidoMedia= new double [2];
double [] percResSentidoMedia_NS= new double [2];
double [] percResSentidoMedia_S= new double [2];
double [][] percResSentidoMediaTeste_S= new double [5][2];
double [][] percResSentidoMediaTeste_NS= new double [5][2];
double [] percResDecadaMudanca= new double [ndecadas];
double [] percResDecadaMudanca_S= new double [ndecadas];
double [] percResDecadaMudanca_NS= new double [ndecadas];
double [][] percResDecadaMudancaTeste= new double [3] [ndecadas];
double [][] percResDecadaMudancaTeste_S= new double [3] [ndecadas];
double [][] percResDecadaMudancaTeste_NS= new double [3] [ndecadas];
setProgress(0);
String textointerface= "Iniciando o Calculo do Resumo dos Resultados das Estações ";
publish(textointerface);
int progress = 0;
setProgress(0);
int ngauges=this.simulationData.getVariaveisHidr().size();
int iestac=0;
int iestfim=0;
for(int igauges=0;igauges<this.simulationData.getVariaveisHidr().size();igauges++){
if(this.simulationData.getVariaveisHidr().get(igauges).isSelecionada() && this.simulationData.getVariaveisHidr().get(igauges).isAtendeRestricaoTamMin()) {
String codigo=String.valueOf(this.simulationData.getVariaveisHidr().get(igauges).getInvhidro().getEstacao_codigo());
ArrayList<ResultEstacionaridade> resultestacionaridade =new ArrayList<ResultEstacionaridade>();
resultestacionaridade = this.simulationData.getVariaveisHidr().get(igauges).getResultestacionaridade();
VariavelHidrologica vhid =this.simulationData.getVariaveisHidr().get(igauges);
boolean optTipoEstacionaridade=true;
if(optTipoEstacionaridade){
for(int i=0;i<resultestacionaridade.size();i++){
int ktipo=0;
while(resultestacionaridade.get(i).getTipoTeste() != nomeTipoEstacio[ktipo]){
ktipo++;
}
if(resultestacionaridade.get(i).getResultadoteste() == "NS"){
resTipoEstacio_NS[ktipo]++;
}else{
resTipoEstacio_S[ktipo]++;
}
}
for(int i=0;i<resTipoEstacio_NS.length;i++){
double soma=resTipoEstacio_NS[i]+resTipoEstacio_S[i];
percResTipoEstacio_S[i]=(resTipoEstacio_S[i]/soma)*100.0;
percResTipoEstacio_NS[i]=(resTipoEstacio_NS[i]/soma)*100.0;
}
}
boolean optTipoTesteEstac=true;
if(optTipoTesteEstac){
for(int i=0;i<resultestacionaridade.size();i++){
int kteste=0;
while(resultestacionaridade.get(i).getNometeste() != nometeste2[kteste]){
kteste++;
}
if(resultestacionaridade.get(i).getResultadoteste() == "NS"){
resTipoTeste_NS[kteste]++;
}else{
resTipoTeste_S[kteste]++;
}
}
for(int i=0;i<resTipoTeste_NS.length;i++){
double soma=resTipoTeste_NS[i]+resTipoTeste_S[i];
percResTipoTeste_S[i]=(resTipoTeste_S[i]/soma)*100.0;
percResTipoTeste_NS[i]=(resTipoTeste_NS[i]/soma)*100.0;
}
}
boolean optSentidoTend=true;
if(optSentidoTend){
for(int i=0;i<resultestacionaridade.size();i++){
if(resultestacionaridade.get(i).getTipoTeste() == nomeTipoEstacio[0]) {
int kteste=0;
while(resultestacionaridade.get(i).getSentidoTendencia() != nomeSentidoTend[kteste]){
kteste++;
}
resSentidoTend[kteste]++;
if(resultestacionaridade.get(i).getResultadoteste() == "NS"){
resSentidoTend_NS[kteste]++;
}else{
resSentidoTend_S[kteste]++;
}
if(resultestacionaridade.get(i).getNometeste() == nometeste2[0]){
if(resultestacionaridade.get(i).getResultadoteste() != "NS"){
resSentidoTendTeste_S[0][kteste]++;
}else{
resSentidoTendTeste_NS[0][kteste]++;
}
}
if(resultestacionaridade.get(i).getNometeste() == nometeste2[1]){
if(resultestacionaridade.get(i).getResultadoteste() != "NS"){
resSentidoTendTeste_S[1][kteste]++;
}else{
resSentidoTendTeste_NS[1][kteste]++;
}
}
if(resultestacionaridade.get(i).getNometeste() == nometeste2[2]){
if(resultestacionaridade.get(i).getResultadoteste() != "NS"){
resSentidoTendTeste_S[2][kteste]++;
}else{
resSentidoTendTeste_NS[2][kteste]++;
}
}
}
}
//for(int i=0;i<resSentidoTend.length;i++){
double somaTot=resSentidoTend[0]+resSentidoTend[1];
percResSentidoTend[0]=(resSentidoTend[0]/somaTot)*100.0;
percResSentidoTend[1]=(resSentidoTend[1]/somaTot)*100.0;
//}
for(int i=0;i<resSentidoTend.length;i++){
double soma=resSentidoTend_NS[i]+resSentidoTend_S[i];
percResSentidoTend_NS[i]=(resSentidoTend_NS[i]/soma)*100.0;
percResSentidoTend_S[i]=(resSentidoTend_S[i]/soma)*100.0;
}
for(int i=0;i<resSentidoTend.length;i++){
for(int j=0;j<3;j++){
double soma=resSentidoTendTeste_S[j][i]+resSentidoTendTeste_NS[j][i];
percResSentidoTendTeste_S[j][i]=(resSentidoTendTeste_S[j][i]/soma)*100.0;
percResSentidoTendTeste_NS[j][i]=(resSentidoTendTeste_NS[j][i]/soma)*100.0;
}
}
}
boolean optSentidoMedia=true;
if(optSentidoMedia){
for(int i=0;i<resultestacionaridade.size();i++){
if(resultestacionaridade.get(i).getTipoTeste() == nomeTipoEstacio[1]) {
int kteste=0;
while(resultestacionaridade.get(i).getSentidoMediaRecente() != nomeSentidoMedia[kteste]){
kteste++;
}
resSentidoMedia[kteste]++;
if(resultestacionaridade.get(i).getResultadoteste() == "NS"){
resSentidoMedia_NS[kteste]++;
}else{
resSentidoMedia_S[kteste]++;
}
if(resultestacionaridade.get(i).getNometeste() == nometeste2[3]){
if(resultestacionaridade.get(i).getResultadoteste() != "NS"){
resSentidoMediaTeste_S[0][kteste]++;
}else{
resSentidoMediaTeste_NS[0][kteste]++;
}
}
if(resultestacionaridade.get(i).getNometeste() == nometeste2[4]){
if(resultestacionaridade.get(i).getResultadoteste() != "NS"){
resSentidoMediaTeste_S[1][kteste]++;
}else{
resSentidoMediaTeste_NS[1][kteste]++;
}
}
if(resultestacionaridade.get(i).getNometeste() == nometeste2[5]){
if(resultestacionaridade.get(i).getResultadoteste() != "NS"){
resSentidoMediaTeste_S[2][kteste]++;
}else{
resSentidoMediaTeste_NS[2][kteste]++;
}
}
if(resultestacionaridade.get(i).getNometeste() == nometeste2[6]){
if(resultestacionaridade.get(i).getResultadoteste() != "NS"){
resSentidoMediaTeste_S[3][kteste]++;
}else{
resSentidoMediaTeste_NS[3][kteste]++;
}
}
if(resultestacionaridade.get(i).getNometeste() == nometeste2[7]){
if(resultestacionaridade.get(i).getResultadoteste() != "NS"){
resSentidoMediaTeste_S[4][kteste]++;
}else{
resSentidoMediaTeste_NS[4][kteste]++;
}
}
}
}
double somaTot=resSentidoMedia[0]+resSentidoMedia[1];
percResSentidoMedia[0]=(resSentidoMedia[0]/somaTot)*100.0;
percResSentidoMedia[1]=(resSentidoMedia[1]/somaTot)*100.0;
//}
for(int i=0;i<resSentidoMedia.length;i++){
double soma=resSentidoMedia_NS[i]+resSentidoMedia_S[i];
percResSentidoMedia_NS[i]=(resSentidoMedia_NS[i]/soma)*100.0;
percResSentidoMedia_S[i]=(resSentidoMedia_S[i]/soma)*100.0;
}
for(int i=0;i<resSentidoMedia.length;i++){
for(int j=0;j<5;j++){
double soma=resSentidoMediaTeste_S[j][i]+resSentidoMediaTeste_NS[j][i];
percResSentidoMediaTeste_S[j][i]=(resSentidoMediaTeste_S[j][i]/soma)*100.0;
percResSentidoMediaTeste_NS[j][i]=(resSentidoMediaTeste_NS[j][i]/soma)*100.0;
}
}
}
boolean optDecadaMudanca=true;
if(optDecadaMudanca){
for(int i=0;i<resultestacionaridade.size();i++){
if(resultestacionaridade.get(i).getNometeste() == nometesteAnoMud[0]){
int kano=0;
int ano=resultestacionaridade.get(i).getAnoMudanca();
while((kano < decada.length-1) && resultestacionaridade.get(i).getAnoMudanca() > decada[kano]){
kano++;
}
resDecadaMudanca[kano]++;
String tp=resultestacionaridade.get(i).getResultadoteste();
if(resultestacionaridade.get(i).getResultadoteste() != "NS"){
resDecadaMudanca_S[kano]++;
resDecadaMudancaTeste_S[0][kano]++;
}
}else if(resultestacionaridade.get(i).getNometeste() == nometesteAnoMud[1]){
int kano=0;
int ano=resultestacionaridade.get(i).getAnoMudanca();
while((kano < decada.length-1) && resultestacionaridade.get(i).getAnoMudanca() > decada[kano]){
kano++;
}
resDecadaMudanca[kano]++;
String tp=resultestacionaridade.get(i).getResultadoteste();
if(resultestacionaridade.get(i).getResultadoteste() != "NS"){
resDecadaMudanca_S[kano]++;
resDecadaMudancaTeste_S[1][kano]++;
}
}else if(resultestacionaridade.get(i).getNometeste() == nometesteAnoMud[2]){
int kano=0;
int ano=resultestacionaridade.get(i).getAnoMudanca();
while((kano < decada.length-1) && resultestacionaridade.get(i).getAnoMudanca() > decada[kano]){
kano++;
}
resDecadaMudanca[kano]++;
String tp=resultestacionaridade.get(i).getResultadoteste();
if(resultestacionaridade.get(i).getResultadoteste() != "NS"){
resDecadaMudanca_S[kano]++;
resDecadaMudancaTeste_S[2][kano]++;
}
}
}
}
iestfim++;
iestac++;
}
System.out.println("estacao = "+igauges+"/"+ngauges+" estacao = "+iestac);
double progress2 = ((igauges+1)*1.0/(this.simulationData.getVariaveisHidr().size()*1.0))*100;
progress=(int) progress2;
setProgress(Math.min(progress, 100));
textointerface= "Aguarde..executando o calculo do resumo da estação "+(igauges+1)+"/"+ngauges+"";
publish(textointerface);
System.out.println(textointerface);
}
this.pnt.setarFrameResumoResultados();
DecimalFormatSymbols dc = new DecimalFormatSymbols();
dc.setDecimalSeparator(',');
String strange = "0.00";
DecimalFormat myFormatter = new DecimalFormat(strange, dc);
String strange2 = "0.0";
DecimalFormat myf = new DecimalFormat(strange2, dc);
this.pnt.textAreaResumo.append("SUMMARY OF RESULTS: "+ pnt.newline);
this.pnt.textAreaResumo.append("Percentage of non-significant (NS) and significant (S) results according to the type of change analyzed:"+ pnt.newline);
this.pnt.textAreaResumo.append(" NS S"+ pnt.newline);
this.pnt.textAreaResumo.append("Trend: "+myFormatter.format(percResTipoEstacio_NS[0])+"("+myf.format(resTipoEstacio_NS[0])+") "+myFormatter.format(percResTipoEstacio_S[0])+"("+myf.format(resTipoEstacio_S[0])+")"+ pnt.newline);
this.pnt.textAreaResumo.append("Jump : "+myFormatter.format(percResTipoEstacio_NS[1])+"("+myf.format(resTipoEstacio_NS[1])+") "+myFormatter.format(percResTipoEstacio_S[1])+"("+myf.format(resTipoEstacio_S[1])+")"+ pnt.newline);
this.pnt.textAreaResumo.append("Variance: "+myFormatter.format(percResTipoEstacio_NS[2])+"("+myf.format(resTipoEstacio_NS[2])+") "+myFormatter.format(percResTipoEstacio_S[2])+"("+myf.format(resTipoEstacio_S[2])+")"+ pnt.newline);
this.pnt.textAreaResumo.append("Independence: "+myFormatter.format(percResTipoEstacio_NS[3])+"("+myf.format(resTipoEstacio_NS[3])+") "+myFormatter.format(percResTipoEstacio_S[3])+"("+myf.format(resTipoEstacio_S[3])+")"+ pnt.newline);
for(int i=0;i<3;i++){
this.pnt.textAreaResumo.append(" "+ pnt.newline);
}
this.pnt.textAreaResumo.append("Percentage of non-significant (NS) and significant (S) results according to the type of test analyzed:"+ pnt.newline);
this.pnt.textAreaResumo.append(" NS S"+ pnt.newline);
for(int i=0;i<ntestes;i++){
this.pnt.textAreaResumo.append(nometesteExtenso[i]+myFormatter.format(percResTipoTeste_NS[i])+"("+myf.format(resTipoTeste_NS[i])+") "+myFormatter.format(percResTipoTeste_S[i])+"("+myf.format(resTipoTeste_S[i])+")"+ pnt.newline);
}
for(int i=0;i<3;i++){
this.pnt.textAreaResumo.append(" "+ newline);
}
this.pnt.textAreaResumo.append("Percentage of results in which the trend is Increase (C) and Decrease (D) considering statistical significance:"+ newline);
this.pnt.textAreaResumo.append(" Increase | Decrease"+ newline);
this.pnt.textAreaResumo.append("Non-significant: "+myFormatter.format(percResSentidoTend_NS[0])+"("+myf.format(resSentidoTend_NS[0])+") "+myFormatter.format(percResSentidoTend_NS[1])+"("+myf.format(resSentidoTend_NS[1])+")"+ newline);
this.pnt.textAreaResumo.append("Significant: "+myFormatter.format(percResSentidoTend_S[0])+"("+myf.format(resSentidoTend_S[0])+") "+myFormatter.format(percResSentidoTend_S[1])+"("+myf.format(resSentidoTend_S[1])+")"+ newline);
this.pnt.textAreaResumo.append("Total: "+myFormatter.format(percResSentidoTend[0])+"("+myf.format(resSentidoTend[0])+") "+myFormatter.format(percResSentidoTend[1])+"("+myf.format(resSentidoTend[1])+")"+ newline);
for(int i=0;i<2;i++){
this.pnt.textAreaResumo.append(" "+ newline);
}
this.pnt.textAreaResumo.append("Percentage of results in which the trend is Increase (C) and Decrease (D) by Test and Significance:"+ newline);
this.pnt.textAreaResumo.append(" Increase | Decrease"+ newline);
for(int i=0;i<3;i++){
this.pnt.textAreaResumo.append(nometesteExtenso[i]+"| (NS) | "+myFormatter.format(percResSentidoTendTeste_NS[i][0])+"("+myf.format(resSentidoTendTeste_NS[i][0])+") | "+myFormatter.format(percResSentidoTendTeste_NS[i][1])+"("+myf.format(resSentidoTendTeste_NS[i][1])+")"+ newline);
this.pnt.textAreaResumo.append(nometesteExtenso[i]+"| (S) | "+myFormatter.format(percResSentidoTendTeste_S[i][0])+"("+myf.format(resSentidoTendTeste_S[i][0])+") | "+myFormatter.format(percResSentidoTendTeste_S[i][1])+"("+myf.format(resSentidoTendTeste_S[i][1])+")"+ newline);
this.pnt.textAreaResumo.append("--------------------------------------------------------------------------------------------- "+ newline);
}
for(int i=0;i<3;i++){
this.pnt.textAreaResumo.append(" "+ newline);
}
this.pnt.textAreaResumo.append("Percentage of results in which the most recent Mean was Higher or Lower considering statistical significance:"+ newline);
this.pnt.textAreaResumo.append(" Higher | Lower"+ newline);
this.pnt.textAreaResumo.append("Non-significant: "+myFormatter.format(percResSentidoMedia_NS[0])+"("+myf.format(resSentidoMedia_NS[0])+") "+myFormatter.format(percResSentidoMedia_NS[1])+"("+myf.format(resSentidoMedia_NS[1])+")"+ newline);
this.pnt.textAreaResumo.append("Significant: "+myFormatter.format(percResSentidoMedia_S[0])+"("+myf.format(resSentidoMedia_S[0])+") "+myFormatter.format(percResSentidoMedia_S[1])+"("+myf.format(resSentidoMedia_S[1])+")"+ newline);
this.pnt.textAreaResumo.append("Total: "+myFormatter.format(percResSentidoMedia[0])+"("+myf.format(resSentidoMedia[0])+") "+myFormatter.format(percResSentidoMedia[1])+"("+myf.format(resSentidoMedia[1])+")"+ newline);
for(int i=0;i<2;i++){
this.pnt.textAreaResumo.append(" "+ newline);
}
this.pnt.textAreaResumo.append("Percentage of results in which the most recent Mean was Major or Minor by Test and Significance:"+ newline);
this.pnt.textAreaResumo.append(" Higher | Lower"+ newline);
for(int i=0;i<5;i++){
this.pnt.textAreaResumo.append(nometesteExtenso[i+3]+"| (NS) | "+myFormatter.format(percResSentidoMediaTeste_NS[i][0])+"("+myf.format(resSentidoMediaTeste_NS[i][0])+") | "+myFormatter.format(percResSentidoMediaTeste_NS[i][1])+"("+myf.format(resSentidoMediaTeste_NS[i][1])+")"+ newline);
this.pnt.textAreaResumo.append(nometesteExtenso[i+3]+"| (S) | "+myFormatter.format(percResSentidoMediaTeste_S[i][0])+"("+myf.format(resSentidoMediaTeste_S[i][0])+") | "+myFormatter.format(percResSentidoMediaTeste_S[i][1])+"("+myf.format(resSentidoMediaTeste_S[i][1])+")"+ newline);
this.pnt.textAreaResumo.append("--------------------------------------------------------------------------------------------- "+ newline);
}
this.pnt.frameResumo.pack();
this.pnt.frameResumo.setVisible(true);
System.out.println("finalizou");
textointerface= "resumo dos resultados da(s) "+iestfim+" estação(s) efetuado com sucesso";
publish(textointerface);
textointerface= "resumo dos resultados da(s) "+iestfim+" estação(s) efetuado com sucesso";
publish(textointerface);
textointerface= "resumo dos resultados da(s) "+iestfim+" estação(s) efetuado com sucesso";
publish(textointerface);
return null;
}
protected void process(List<String> text) {
// this.pnt.lblAguardeThread.setText(text.get(0));
}
protected void done() {
// Messages.informMsg("Arquivo excel construido com sucesso");
}
}
}
<file_sep>package tests;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics;
import tests.autocorrelationApproaches.MagnitudeTendencia;
import types.DadoTemporal;
import types.ResultEstacionaridade;
import types.ResultadoBsen;
import types.SimulationDataExtremos;
import util.PegarSerieEstatistica;
import util.ST_pegarEstatisticasDescritivasDaSerieAnualConfigurada;
import util.ST_verificarAno;
public class ExecutarTestesEstacionaridadeMapaResultsAllCorrelTemporal {
private SimulationDataExtremos simulationData;
//private PanelTestesEstatisticos pnt;
public ExecutarTestesEstacionaridadeMapaResultsAllCorrelTemporal(SimulationDataExtremos simulationData){
this.simulationData=simulationData;
// this.pnt=pnt;
}
public Map<String, Map<String,ResultEstacionaridade>> executarTestes(){
String tiposerie=null;
String nometeste=null;
double nivelsignificancia=simulationData.getNivelSignificancia();
String [] nometeste2=pegarNomeTesteSigla();
String textointerface= "Iniciando cálculo ....";
int progress = 0;
int nestac=this.simulationData.getVariaveisHidr().size();
//zerar resultados anteriores
for (int i = 0; i < this.simulationData.getVariaveisHidr().size(); i++) {
this.simulationData.getVariaveisHidr().get(i).setResultestacionaridade(null);
}
ArrayList<double []> valoresCriticos = new ArrayList<double []>();
ArrayList<ArrayList<Double>> distribTotTestes = new ArrayList<ArrayList<Double>>();
Map<String, ArrayList<ResultEstacionaridade>>resultEstacionaridadeTipo1=new HashMap<String, ArrayList<ResultEstacionaridade>>();
Map<String, Map<String,ResultEstacionaridade>> resultEstacionaridadeTipo2=new HashMap<String, Map<String,ResultEstacionaridade>>();
for (int i = 0; i < this.simulationData.getVariaveisHidr().size(); i++) {
Map<String,DadoTemporal> serieMapaOriginal=this.pegarSeriesMapasOriginais(i).get(0);
String codigo= this.simulationData.getVariaveisHidr().get(i).getInvhidro().getEstacao_codigo();
if(this.simulationData.getVariaveisHidr().get(i).isSelecionada()){
Map<String,ResultEstacionaridade> resultestacionaridadeTipo2=new HashMap<String,ResultEstacionaridade>();
ArrayList<ResultEstacionaridade> resultestacionaridade =new ArrayList<ResultEstacionaridade>();
int tamanhoMinimoSerie=this.simulationData.getTamMinSerietotEstacionaridade();
int tipoHipotese=this.simulationData.getTipoHipoteseEstacionaridade();
int tamanhoMinimoSerie1=5;
int tamanhoMinimoSerie2=5;
Map<String,DadoTemporal> serieMapaTFPW=new HashMap<String,DadoTemporal>();
double CF=1;
boolean autoCorrelacao=this.simulationData.isConsiderarAutoCorrelacao();
//String nomeAbordagemAC="TFPWcunbPW";
//String nomeAbordagemAC="TFPWcunbPW";//MK para nao considerar nenhuma abordagem
if(autoCorrelacao){
String nomeAbordagemAC=this.getApproachName();
SelecionarAbordagemCorrelacaoSerial selAbordagem=new SelecionarAbordagemCorrelacaoSerial();
selAbordagem.executarSerieMapa(nomeAbordagemAC, serieMapaOriginal);
serieMapaTFPW=selAbordagem.getSerieMapaFinal();
CF=selAbordagem.getCF();
}
Map<String,DadoTemporal> serieMapa=new HashMap<String,DadoTemporal>();
serieMapa=serieMapaOriginal;
if(serieMapa.size() >= tamanhoMinimoSerie){
this.simulationData.getVariaveisHidr().get(i).setAtendeRestricaoTamMin(true);
double bsen=MagnitudeTendencia.bSenRespeitandoCronologia(serieMapa);
DescriptiveStatistics dsc = ST_pegarEstatisticasDescritivasDaSerieAnualConfigurada.dsc(serieMapa);
double media=dsc.getMean();
double nanos=dsc.getN();
//double bsenRel=((bsen/media)*100.0);
double bsenRel=((bsen/media)*100.0)*10.0;//Decada
int [] anoIniFim = ST_verificarAno.anos(serieMapa);
double nanosPeriodo=anoIniFim[1]-anoIniFim[0]+1;
ResultadoBsen resbsen =new ResultadoBsen();
resbsen.setBsen(bsen);
resbsen.setMedia(media);
resbsen.setBsenRel(bsenRel);
resbsen.setNanos(nanos);
resbsen.setNanosPeriodo(nanosPeriodo);
double bsenRelAnual=((bsen/media)*1.0)*1.0;//Decada
resbsen.setBsenRelAnual(bsenRelAnual);
double cv=dsc.getStandardDeviation()/dsc.getMean();
resbsen.setCv(cv);
Integer tamanhon =(int) dsc.getN();
resbsen.setTamanhon(tamanhon);
boolean fazerMK=true;
//if(this.pnt.getCheckEstacionaridadeTendencia()[0].isSelected()){
if(fazerMK){
int opcaoTeste=0;
nometeste=nometeste2[opcaoTeste];
String tipoTeste="TENDENCIA";
ResultEstacionaridade resultest=null;
MannKendallTest mk = new MannKendallTest(serieMapa,tipoHipotese,nivelsignificancia);
ResultEstacionaridade resultestOriginal = this.executarMK(mk, tiposerie, nometeste, tipoTeste,resbsen);
resultest = resultestOriginal;
double pvalori=resultest.getPvalue();
if(!resultestOriginal.getResultadoteste().equals("NS") && serieMapaTFPW.size() > 0){
MannKendallTest mk3 = new MannKendallTest(serieMapaTFPW,tipoHipotese,nivelsignificancia);
resultest = this.executarMK(mk3, tiposerie, nometeste, tipoTeste,resbsen,CF);
System.out.println();
}
resultestacionaridadeTipo2.put(nometeste, resultest);
resultestacionaridade.add(resultest);
}
resultEstacionaridadeTipo2.put(codigo, resultestacionaridadeTipo2);
}else{
this.simulationData.getVariaveisHidr().get(i).setAtendeRestricaoTamMin(false);
}
resultEstacionaridadeTipo1.put(codigo, resultestacionaridade);
this.simulationData.getVariaveisHidr().get(i).setResultestacionaridade(resultestacionaridade);
double progress2 = ((i+1)*1.0/(this.simulationData.getVariaveisHidr().size()*1.0))*100;
progress=(int) progress2;
//setProgress(Math.min(progress, 100));
textointerface= "Aguarde..executando o cálculo da estação "+(i+1)+"/"+nestac+"";
//publish(textointerface);
System.out.println(textointerface);
}else {
System.out.println("not select gauge");
}
//System.out.println("Estac i"+i+" codigo = "+codigo);
}
boolean fazerFDR=this.simulationData.isFazerFDR();
//System.out.println(resultEstacionaridadeTipo2.get("245003").get("MK").getResultadoteste());
if(fazerFDR){
if(this.simulationData.isFazerFDRClassico()){
AnaliseResultadoFDR analiseResultadoFDR=new AnaliseResultadoFDR(this.simulationData);
boolean executouFDR=analiseResultadoFDR.executar(resultEstacionaridadeTipo2,nivelsignificancia);
if(!executouFDR){
System.out.println("nao teve estação");
}
}
}
//System.out.println(resultEstacionaridadeTipo2.get("245003").get("MK").getResultadoteste());
return resultEstacionaridadeTipo2;
}
public ResultEstacionaridade executarMK(MannKendallTest teste,String tiposerie,String nometeste,String tipoTeste,ResultadoBsen resbsen){
ResultEstacionaridade resultest = new ResultEstacionaridade(nometeste,tiposerie);
teste.teste1();
resultest.setEstatteste(teste.getEstatteste());
resultest.setPvalue(teste.getPvalue()*100.0);
//resultest.setPvalue(teste.getPvalue());
resultest.setValorcriticoteste(teste.getValorcriticoteste());
resultest.setResultadoteste(teste.getResultadoteste());
//resultest.setTipoTeste("TENDENCIA");
resultest.setTipoTeste(tipoTeste);
resultest.setMetodoObterValCritico("Teórico");
resultest.setSentidoTendencia(teste.getSentidoTendencia());
resultest.setResultadoDescritivoTeste(teste.getResultesteTexto());
//resultest.setSentidoMediaAntiga(teste.getSentidoMediaAnterior());
//resultest.setSentidoMediaRecente(teste.getSentidoMediaPosterior());
//resultest.setAnoMudanca(teste.getAnoIniSerie2());
resultest.setResbsen(resbsen);
return resultest;
}
public ResultEstacionaridade executarMK(MannKendallTest teste,String tiposerie,
String nometeste,String tipoTeste,ResultadoBsen resbsen, double CF){
ResultEstacionaridade resultest = new ResultEstacionaridade(nometeste,tiposerie);
teste.teste1(CF);
resultest.setEstatteste(teste.getEstatteste());
resultest.setPvalue(teste.getPvalue()*100.0);
//resultest.setPvalue(teste.getPvalue());
resultest.setValorcriticoteste(teste.getValorcriticoteste());
resultest.setResultadoteste(teste.getResultadoteste());
//resultest.setTipoTeste("TENDENCIA");
resultest.setTipoTeste(tipoTeste);
resultest.setMetodoObterValCritico("Teórico");
resultest.setSentidoTendencia(teste.getSentidoTendencia());
resultest.setResultadoDescritivoTeste(teste.getResultesteTexto());
//resultest.setSentidoMediaAntiga(teste.getSentidoMediaAnterior());
//resultest.setSentidoMediaRecente(teste.getSentidoMediaPosterior());
//resultest.setAnoMudanca(teste.getAnoIniSerie2());
resultest.setResbsen(resbsen);
return resultest;
}
public String getApproachName() {
String nomeAbordagemAC="";
if(simulationData.isFazerPW()) {
nomeAbordagemAC="PW";
}else if(simulationData.isFazerTFPW()) {
nomeAbordagemAC="TFPW";
}else if(simulationData.isFazerMTFPW()) {
nomeAbordagemAC="TFPWcunbPW";
}else if(simulationData.isFazerVCPW()) {
nomeAbordagemAC="VCPW";
}else if(simulationData.isFazerVC()) {
nomeAbordagemAC="VC_CF1";
}
return nomeAbordagemAC;
}
private String [] pegarNomeTesteSigla(){
int ntestes=14;
String [] nometeste2=new String [ntestes];
nometeste2[0]="MK";
nometeste2[1]="SR";
nometeste2[2]="LR";
nometeste2[3]="TT";
nometeste2[4]="DC";
nometeste2[5]="CD";
nometeste2[6]="WR";
nometeste2[7]="MW";
nometeste2[8]="TF";
nometeste2[9]="MC";
nometeste2[10]="TP";
nometeste2[11]="RD";
nometeste2[12]="AC";
nometeste2[13]="WW";
return nometeste2;
}
private ArrayList<Map<String,DadoTemporal>> pegarSeriesMapasOriginais(int i){
//PanelImportarDados pid=new PanelImportarDados();
int anoIniserieTot=this.simulationData.getAnoIniSubConjunto();
int anoFimserieTot=this.simulationData.getAnoFimSubConjunto();
ArrayList<Map<String,DadoTemporal>> series=new ArrayList<Map<String,DadoTemporal>>();
PegarSerieEstatistica pid=new PegarSerieEstatistica();
Map<String,DadoTemporal> serieMapa=new HashMap<String,DadoTemporal>();
serieMapa=pid.pegarSerieEstatistica(this.simulationData.getVariaveisHidr().get(i),this.simulationData, anoIniserieTot, anoFimserieTot);
series.add(serieMapa);
//series.add(serie1Mapa);
//series.add(serie2Mapa);
return series;
}
}
<file_sep>/**
*
*/
package util.fileloader;
import java.io.File;
import java.io.IOException;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import org.geotools.coverage.grid.GridCoverage2D;
import org.geotools.coverage.grid.io.AbstractGridFormat;
import org.geotools.coverage.grid.io.GridCoverage2DReader;
import org.geotools.coverage.grid.io.GridFormatFinder;
import org.geotools.coverage.processing.CoverageProcessor;
import org.geotools.coverage.processing.Operations;
import org.geotools.gce.geotiff.GeoTiffFormat;
import org.geotools.geometry.Envelope2D;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.geotools.util.Arguments;
import org.geotools.util.factory.Hints;
import org.opengis.geometry.Envelope;
import org.opengis.parameter.ParameterValueGroup;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
/**
* @author A.Riaydh
*
*/
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author A.Riaydh
*/
public class ImageTileGUI extends javax.swing.JDialog {
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
private javax.swing.JTextField jTextField3;
private javax.swing.JTextField jTextField4;
private javax.swing.JTextField jTextField5;
JFileChooser fc;
private final int NUM_HORIZONTAL_TILES = 16;
private final int NUM_VERTICAL_TILES = 8;
private Integer numberOfHorizontalTiles = NUM_HORIZONTAL_TILES;
private Integer numberOfVerticalTiles = NUM_VERTICAL_TILES;
private Double tileScale;
private File inputFile;
private File outputDirectory;
// End of variables declaration
/**
* Creates new form ImageTileGUI
*/
public ImageTileGUI() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
private void initComponents() {
fc = new JFileChooser();
jLabel1 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
jLabel2 = new javax.swing.JLabel();
jTextField2 = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
jTextField3 = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
jTextField4 = new javax.swing.JTextField();
jLabel5 = new javax.swing.JLabel();
jTextField5 = new javax.swing.JTextField();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
setTitle("Image Tile Convertor");
jLabel1.setText("Input Directory File");
jLabel1.setName("inputDirectioryFile"); // NOI18N
jTextField1.setName("inputDirectoryFileTextField"); // NOI18N
jTextField1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField1ActionPerformed(evt);
}
});
jButton1.setText("Run");
jButton1.setName("runImageTile"); // NOI18N
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jLabel2.setText("Output Directory File");
jLabel2.setName("inputDirectioryFile"); // NOI18N
jTextField2.setName("inputDirectoryFileTextField"); // NOI18N
jTextField2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField2ActionPerformed(evt);
}
});
jLabel3.setText("Number of Horizontal Tiles");
jLabel3.setName("numberOfHorizontalTile"); // NOI18N
jTextField3.setText("16");
jTextField3.setName("inputDirectoryFileTextField"); // NOI18N
jLabel4.setText("Number of Vertical Tiles");
jLabel4.setName("numberOfVerticalTile"); // NOI18N
jTextField4.setText("8");
jTextField4.setName("inputDirectoryFileTextField"); // NOI18N
jLabel5.setText("Tile Scale");
jLabel5.setName("tileScale"); // NOI18N
jTextField5.setText("2.0");
jTextField5.setName("inputDirectoryFileTextField"); // NOI18N
jButton2.setText("Browse");
jButton2.setHideActionText(true);
jButton2.setName("inputFileBrowseButton"); // NOI18N
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jButton3.setText("Browse");
jButton3.setHideActionText(true);
jButton3.setName("outputFileBrowseButton"); // NOI18N
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 187, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 328, Short.MAX_VALUE)
.addComponent(jTextField2))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 195, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jTextField3, javax.swing.GroupLayout.DEFAULT_SIZE, 108, Short.MAX_VALUE)
.addComponent(jTextField4))))
.addGap(226, 226, 226)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton2, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jButton3, javax.swing.GroupLayout.Alignment.TRAILING))))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(19, 19, 19)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton2))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton3))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5)
.addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(jButton1)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}
private String getFileExtension(File file) {
String name = file.getName();
try {
return name.substring(name.lastIndexOf(".") + 1);
} catch (Exception e) {
return "";
}
}
public Integer getNumberOfHorizontalTiles() {
return numberOfHorizontalTiles;
}
public void setNumberOfHorizontalTiles(Integer numberOfHorizontalTiles) {
this.numberOfHorizontalTiles = numberOfHorizontalTiles;
}
public Integer getNumberOfVerticalTiles() {
return numberOfVerticalTiles;
}
public void setNumberOfVerticalTiles(Integer numberOfVerticalTiles) {
this.numberOfVerticalTiles = numberOfVerticalTiles;
}
public File getInputFile() {
return inputFile;
}
public void setInputFile(File inputFile) {
this.inputFile = inputFile;
}
public File getOutputDirectory() {
return outputDirectory;
}
public void setOutputDirectory(File outputDirectory) {
this.outputDirectory = outputDirectory;
}
public Double getTileScale() {
return tileScale;
}
public void setTileScale(Double tileScale) {
this.tileScale = tileScale;
}
public static void mainImageTiler(String[] args) throws Exception {
//GeoTools provides utility classes to parse command line arguments
Arguments processedArgs = new Arguments(args);
ImageTileGUI tiler = new ImageTileGUI();
try {
tiler.setInputFile(new File(processedArgs.getRequiredString("-f")));
tiler.setOutputDirectory(new File(processedArgs.getRequiredString("-o")));
tiler.setNumberOfHorizontalTiles(processedArgs.getOptionalInteger("-htc"));
tiler.setNumberOfVerticalTiles(processedArgs.getOptionalInteger("-vtc"));
tiler.setTileScale(processedArgs.getOptionalDouble("-scale"));
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
printUsage();
System.exit(1);
}
tiler.tile();
}
private static void printUsage() {
System.out.println("Usage: -f inputFile -o outputDirectory [-tw tileWidth<default:256> "
+ "-th tileHeight<default:256> ");
System.out.println("-htc horizontalTileCount<default:16> -vtc verticalTileCount<default:8>");
}
private void tile() throws IOException {
AbstractGridFormat format = GridFormatFinder.findFormat(this.getInputFile());
String fileExtension = this.getFileExtension(this.getInputFile());
//working around a bug/quirk in geotiff loading via format.getReader which doesn't set this
//correctly
Hints hints = null;
if (format instanceof GeoTiffFormat) {
hints = new Hints(Hints.FORCE_LONGITUDE_FIRST_AXIS_ORDER,Boolean.TRUE);
}
GridCoverage2DReader gridReader = (GridCoverage2DReader) format.getReader(this.getInputFile(),hints);
GridCoverage2D gridCoverage = gridReader.read(null);
Envelope2D coverageEnvelope = gridCoverage.getEnvelope2D();
double coverageMinX = coverageEnvelope.getBounds().getMinX();
double coverageMaxX = coverageEnvelope.getBounds().getMaxX();
double coverageMinY = coverageEnvelope.getBounds().getMinY();
double coverageMaxY = coverageEnvelope.getBounds().getMaxY();
int htc = this.getNumberOfHorizontalTiles() != null ? this.getNumberOfHorizontalTiles() : NUM_HORIZONTAL_TILES;
int vtc = this.getNumberOfVerticalTiles() != null ? this.getNumberOfVerticalTiles() : NUM_VERTICAL_TILES;
double geographicTileWidth = (coverageMaxX - coverageMinX) / (double)htc;
double geographicTileHeight = (coverageMaxY - coverageMinY) / (double)vtc;
CoordinateReferenceSystem targetCRS = gridCoverage.getCoordinateReferenceSystem();
//make sure to create our output directory if it doesn't already exist
File tileDirectory = this.getOutputDirectory();
if (!tileDirectory.exists()) {
tileDirectory.mkdirs();
}
//iterate over our tile counts
for (int i = 0; i < htc; i++) {
for (int j = 0; j < vtc; j++) {
System.out.println("Processing tile at indices i: " + i + " and j: " + j);
//create the envelope of the tile
Envelope envelope = getTileEnvelope(coverageMinX, coverageMinY, geographicTileWidth,
geographicTileHeight, targetCRS, i, j);
GridCoverage2D finalCoverage = cropCoverage(gridCoverage, envelope);
if (this.getTileScale() != null) {
finalCoverage = scaleCoverage(finalCoverage);
}
//use the AbstractGridFormat's writer to write out the tile
File tileFile = new File(tileDirectory, i + "_" + j + "." + fileExtension);
format.getWriter(tileFile).write(finalCoverage, null);
}
}
}
private Envelope getTileEnvelope(double coverageMinX, double coverageMinY,
double geographicTileWidth, double geographicTileHeight,
CoordinateReferenceSystem targetCRS, int horizontalIndex, int verticalIndex) {
double envelopeStartX = (horizontalIndex * geographicTileWidth) + coverageMinX;
double envelopeEndX = envelopeStartX + geographicTileWidth;
double envelopeStartY = (verticalIndex * geographicTileHeight) + coverageMinY;
double envelopeEndY = envelopeStartY + geographicTileHeight;
return new ReferencedEnvelope(
envelopeStartX, envelopeEndX, envelopeStartY, envelopeEndY, targetCRS);
}
private GridCoverage2D cropCoverage(GridCoverage2D gridCoverage, Envelope envelope) {
CoverageProcessor processor = CoverageProcessor.getInstance();
//An example of manually creating the operation and parameters we want
final ParameterValueGroup param = processor.getOperation("CoverageCrop").getParameters();
param.parameter("Source").setValue(gridCoverage);
param.parameter("Envelope").setValue(envelope);
return (GridCoverage2D) processor.doOperation(param);
}
/**
* Scale the coverage based on the set tileScale
*
* As an alternative to using parameters to do the operations, we can use the
* Operations class to do them in a slightly more type safe way.
*
* @param coverage the coverage to scale
* @return the scaled coverage
*/
private GridCoverage2D scaleCoverage(GridCoverage2D coverage) {
Operations ops = new Operations(null);
coverage = (GridCoverage2D) ops.scale(coverage, this.getTileScale(), this.getTileScale(), 0, 0);
return coverage;
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent e) {
String textField1=jTextField1.getText();
System.out.println("Input File Path:"+textField1);
String textField2=jTextField2.getText();
System.out.println("Output File Path:"+textField2);
String textField3=jTextField3.getText();
System.out.println("Number of Horizontal Tiles:"+textField3);
String textField4=jTextField4.getText();
System.out.println("Number of Vertical Tiles:"+textField4);
String textField5=jTextField5.getText();
System.out.println("Tile Scale:"+textField5);
String [] params={"-f ",textField1,"-htc ",textField3,"-vtc ",textField4,"-o ",textField2,"-scale ",textField5};
try {
mainImageTiler(params);
JOptionPane.showMessageDialog(null,
String.format("Image Tiles Generation Successful!\n" +
"Generated File Path:%S\n",textField2));
} catch (Exception e1) {
JOptionPane.showMessageDialog(null,
String.format("Image Tiles Fail!\n" +
"Please Checks Input and Out File Pathe and It's format:\n" +
"%S\n" +
"%S\n", textField1, textField2));
e1.printStackTrace();
}
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent e) {
int returnVal = fc.showOpenDialog(ImageTileGUI.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
//This is where a real application would open the file.
String absolutePath =file.getAbsolutePath();
String value=absolutePath.replaceAll("\\\\", "/");
String value2=value.replace(":/", "://");
System.out.println("Input File Directory path: " +value2);
jTextField1.setText(value2);
} else {
jTextField1.setText("File not");
}
jTextField1.setCaretPosition(jTextField1.getDocument().getLength());
}
private void jButton3ActionPerformed(java.awt.event.ActionEvent e) {
int returnVal = fc.showSaveDialog(ImageTileGUI.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
//This is where a real application would open the file.
String absolutePath =file.getAbsolutePath();
String value=absolutePath.replaceAll("\\\\", "/");
String value2=value.replace(":/", "://");
System.out.println("Output File Directory path:" + value2);
String value3=value2.substring(0, value2.lastIndexOf('.'));
System.out.println("Output File Directory path:" + value3);
jTextField2.setText(value3);
} else {
jTextField2.setText("File not");
}
jTextField2.setCaretPosition(jTextField2.getDocument().getLength());
}
private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jTextField2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(ImageTileGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ImageTileGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ImageTileGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ImageTileGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
ImageTileGUI dialog = new ImageTileGUI();
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
}
|
f0dac03171d113413828dd220755b8efbb216a83
|
[
"Markdown",
"Java"
] | 33 |
Java
|
sauloaires/software_codes-Trend-detection-in-annual-streamflow-extremes-in-Brazil
|
6c67de23bb0f4b060c70527ccc37801f8f34b94d
|
f7738bd7bc247ed35390410c826dd68e6df27f7c
|
refs/heads/master
|
<repo_name>junuylia/datasciencecoursera<file_sep>/help/server.r
#This is the server code for the data product project help
library(shiny)
# It is a help documentation
shinyServer( function(input, output) {
})
<file_sep>/help/ui.r
#This is the ui code for the data product project help
library(shiny)
shinyUI(fluidPage(
headerPanel("Dynamic Histogram and Confidence Interval"),
mainPanel(
h3('What is the confidence interval for the population mean?'),
h4("It looks like a simple question. But if you have only a sample from the population, how would you estimate the population mean?"),
h4("This WebApp gives you a general idea:"),
withMathJax(),
br(),
h5("First, choose from the left panel the desired sample size. As this is a simple demo, we limit the sample size to between 50 and 1000."),
br(),
h5("Then, choose from the distribution list. Which distribution you want to sample from?"),
h5("Different distribution has different parameters, choose the ones for your specified distribution"),
p("Normal:"), withMathJax("$$y\\sim N(\\mu,\\sigma)$$"),
helpText("where \\(\\mu\\) is the population mean and \\(\\sigma\\) is the standard deviation."),
p("Poisson:"), withMathJax("$$y\\sim Pois(\\lambda)$$"),
helpText("where \\(\\lambda\\) is the population mean and \\(\\sqrt\\lambda\\) is the standard deviation."),
p("Binomial:"), withMathJax("$$y\\sim Bin(N,p)$$"),
helpText("where \\(N\\) is the number of trials and \\(p\\) is the possibility of success. The population mean is calculated as \\(\\mu\\)=np."),
p("Uniform:"), withMathJax("$$y\\sim Unif(A,B)$$"),
helpText("where A and B are lower and upper bound, and \\(\\mu\\) is the average of A and B."),
br(),
h5("The last input from you is the significance level. This is the area on the tail of the distribution density. "),
helpText("Usually, this number is indicated as \\(\\alpha\\). It can be used to find the confidence level"),
helpText("\\(C = (1-\\alpha)\\times 100 \\%\\)"),
helpText("where C is the confidence level."),
h5("The main panel displays corresponding plot with both population mean and confidence interval indicated as you change these values.")
)
))
<file_sep>/dataProducts/server.R
#This is the server code for the data product project
library(car)
library(shiny)
confInv <- function (xbar, s, n, alpha){
t = abs(qt(alpha/2,n-1))
bounds = c(xbar-t*s/sqrt(n), xbar + t*s/sqrt(n))
# cat(bounds)
bounds
}
shinyServer( function(input, output) {
vr <- reactive({ switch(input$dist,
Poisson= rpois(input$samplesize,input$lambda),
Uniform = runif(input$samplesize,input$lb,input$rng+input$lb),
Binomial = rbinom(input$samplesize,input$N,input$p),
Normal= rnorm(input$samplesize,input$mu,input$sigma))
})
param <- reactive({
switch(input$dist,
Poisson= paste('Mean',input$lambda),
Uniform = paste('Lower Bound',input$lb,'and Upper Bound',input$lb+input$rng),
Binomial = paste('Trial',input$N,'and Probability',input$p),
Normal= paste('Mean',input$mu,'and Standard Deviation',input$sigma))
})
distName = reactive({recode(input$dist, "
'Poisson' = 'Poisson';
'Binomial' = 'Binomial';
'Uniform' = 'Uniform';
else = 'Normal'")})
mn =reactive({ switch(input$dist,
Poisson=input$lambda, Normal= input$mu,
Uniform = input$rng/2+input$lb,
Binomial = input$N*input$p)})
CI = reactive({
format(confInv(mean(vr()),sd(vr()),input$samplesize,input$alpha),nsmall=2,digits=3)
})
al = reactive({input$alpha})
output$sampleHist = renderPlot({
vr = vr()
distn=distName()
prm = param()
mn=mn()
par(cex=1.2,lwd=2)
ret=hist(vr ,main=paste('Histogram of a Random Sample of',input$samplesize,'from',distn,'Distribution with',prm),
xlab='data',freq=F)
ht = max(ret$density)
nht = min(ret$density)
abline(v=mn,col=2,lwd=2)
conf = CI()
abline(v=conf[1],col=3,lwd=3,lty=20)
abline(v=conf[2],col=3,lwd=3,lty=20)
legend("topright", legend=c(paste("Population Mean=",mn),paste(format((1-al()*2)*100,digit=2),"% Confidence Interval")),col=2:3,lty=19:20)
})
output$ci = renderText({
conf = CI()
citext=paste("The confidence interval of the population mean at significant level",
{input$alpha},"is [",conf[1],",",conf[2],"]")
citext
})
})
<file_sep>/dataProducts/ui.R
#This is the ui code for the data product project
library(shiny)
shinyUI(pageWithSidebar(
headerPanel("Dynamic Histogram and Confidence Interval"),
sidebarPanel(
sliderInput('samplesize','Sample size:',500,min=50, max = 1000, step=5),
br(),
selectInput('dist',"Distribution:",choices=c('Binomial','Normal','Poisson','Uniform')),
conditionalPanel(
condition='input.dist=="Poisson"',
sliderInput('lambda','Population Mean:',50,min=0, max = 100, step=1)
),
conditionalPanel(
condition='input.dist=="Uniform"',
sliderInput('lb','Lower Bound:',0,min=-10, max = 10, step=0.5),
sliderInput('rng','Range:', 1,min=0.1, max = 20 , step=0.1)
),
conditionalPanel(
condition='input.dist=="Binomial"',
sliderInput('N','Number of Trials:',10,min=3, max = 100, step=1),
sliderInput('p','Probability of Success:',0.5,min=0.01, max = 1, step=0.01)
),
conditionalPanel(
condition='input.dist=="Normal"',
sliderInput('mu','Population Mean:',50,min=0, max = 100, step=1) ,
sliderInput('sigma','Standard Deviation:',1,min=0.1, max = 20, step=0.1)
),
br(),
sliderInput('alpha','Significance Level (alpha) [0.001-0.2]',0.05,min=0.001, max = 0.2,step=0.001),
br(), p("Please keep in mind that"),
code(" alpha = (1- confidence level (C))"),
br(),br(),
helpText("For help using this webapp, please visit"),
a(href="http://junuylia.shinyapps.io/help",
"help",target="_blank")
) ,
mainPanel(
h3('What is the confidence interval for the population mean?'),
plotOutput("sampleHist"),
verbatimTextOutput("ci")
)
))
|
9ed60bf084736b57d30a1f566369bedd1daf94de
|
[
"R"
] | 4 |
R
|
junuylia/datasciencecoursera
|
bbff9fd54f644a551fb7521a5d3c57b9ead03768
|
98a9fe1072e12f7cb5f5b357ce5d7ad8881ae241
|
refs/heads/master
|
<repo_name>HenryBenaye/Boo-7df659ba<file_sep>/boo.php
<?php
$a = true;
var_dump($a);
$b = false;
var_dump($b);
|
ca798a4d9411e4e47876422c106c38f9a70c2997
|
[
"PHP"
] | 1 |
PHP
|
HenryBenaye/Boo-7df659ba
|
4c157fde21e673dfccd5bb2032b6ec603d2a348f
|
a8fad06589d61eff07543dab2b8fb267abbe5fba
|
refs/heads/master
|
<file_sep>package com.example.usuario.pruebagoogleservices;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.widget.Button;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
public class MapActivity extends Activity implements OnMapReadyCallback {
GoogleMap googleMap;
Button button;
LatLng vigo = new LatLng(42.2208932,-8.7328468);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
googleMap = mapFragment.getMap();
}
@Override
public void onMapReady(GoogleMap googleMap) {
googleMap.setMyLocationEnabled(true);
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(vigo,15));//TODO: Mover esto a onStart?
googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
}
}
|
81cf80b85fadac77eca98f8d0715cf414ff6600a
|
[
"Java"
] | 1 |
Java
|
ildsiempre/PruebaGoogleServices
|
d370b32ac207b06db91454831183368e2ea4bded
|
4c1df0d0ff7ab4cf36d53ae1b30eb65442bae08a
|
refs/heads/master
|
<repo_name>rixtox/xplayer<file_sep>/js/main.js
$(document).ready(function() {
myPlayer = new xPlayer({
options: {
target: '#xPlayer',
json: 'songs.json',
thumbnailbg: 'img/empty_thumbnail.jpg',
autoplay: true
}
});
$(window).on('keypress', function(e) {
switch(e.keyCode) {
case 32: // space
e.preventDefault();
myPlayer.audio.paused
? myPlayer.play()
: myPlayer.pause();
break;
case 110: // 'n'
e.preventDefault();
myPlayer.next();
break;
case 112: // 'p'
e.preventDefault();
myPlayer.previous();
break;
case 109: // 'm'
e.preventDefault();
myPlayer.nextPlayMode();
break;
case 113: // 'q'
e.preventDefault();
myPlayer.stop();
}
});
});<file_sep>/README.md
xPlayer
========
This is an HTML5 audio player project based on JavaScript.
|
5f6ae4365d444c6b1d1d6c94e501ade516202164
|
[
"JavaScript",
"Markdown"
] | 2 |
JavaScript
|
rixtox/xplayer
|
f31ea78f6206af9fc4326efaff77ba5f4772f80a
|
5f52848dad6418c12eedce51f87eaaf28e8d3632
|
refs/heads/master
|
<file_sep>package com.darkfire;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import com.google.zxing.client.android.R;
import java.util.List;
public class DisplaySavedBillActivity extends Activity {
Payment payment;
TextView payerName, idNumber, amount;
EditText password;
ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_saved_bill);
if(getIntent().getSerializableExtra(Payment.BILL)==null){
return;
}
payment = (Payment) getIntent().getSerializableExtra(Payment.BILL);
initializeView();
}
private void initializeView(){
listView = (ListView) findViewById(R.id.billView);
listView.setAdapter(new BillAdapter(payment.getBill()));
payerName = (TextView) findViewById(R.id.payer_name);
payerName.setText(payment.getPayerVirtualAdd());
idNumber = (TextView) findViewById(R.id.id_number);
idNumber.setText(payment.getTransactionId());
amount = (TextView) findViewById(R.id.amount);
amount.setText(""+payment.getAmount());
password = (EditText)findViewById(R.id.password);
}
private class BillAdapter extends BaseAdapter {
List<BillElement> elements;
BillAdapter(List<BillElement> elements){
this.elements = elements;
}
@Override
public int getCount() {
return elements.size();
}
@Override
public Object getItem(int i) {
return elements.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
if(view != null){
return view;
}
view = getLayoutInflater().inflate(R.layout.bill_element, null);
((TextView)view.findViewById(R.id.element_serial)).setText("" + (i+1));
((TextView)view.findViewById(R.id.element_name)).setText(elements.get(i).name);
((TextView)view.findViewById(R.id.noOfUnits)).setText("" + elements.get(i).noOfUnits);
((TextView)view.findViewById(R.id.costPerUnit)).setText(""+elements.get(i).costPerUnit);
((TextView)view.findViewById(R.id.amount)).setText(""+elements.get(i).calculateAmount());
return view;
}
}
}
<file_sep>package com.darkfire;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.TextView;
import com.google.zxing.client.android.R;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.StreamCorruptedException;
import java.util.ArrayList;
import java.util.List;
/**
* A simple {@link Fragment} subclass.
*/
public class PaidBillFragment extends Fragment {
GridView gridView;
ArrayList<Payment> payments;
String type;
public PaidBillFragment(){
payments = new ArrayList<>();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_paid_bill, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
this.type = getArguments().getString("type");
gridView = (GridView) view.findViewById(R.id.paidBillGrid);
new LoadDataTask().execute();
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Payment p = (Payment) gridView.getAdapter().getItem(i);
Intent intent = new Intent(getActivity(), DisplaySavedBillActivity.class);
intent.putExtra(Payment.BILL, p);
startActivity(intent);
}
});
((TextView)view.findViewById(R.id.savedBillsFragHead)).setText(type + " Bills");
}
private class PaidBillAdapter extends BaseAdapter {
@Override
public int getCount() {
return payments.size();
}
@Override
public Object getItem(int i) {
return payments.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
view = getActivity().getLayoutInflater().inflate(R.layout.paidbill_grid_element, null);
if(type.equalsIgnoreCase("paid"))
((TextView)view.findViewById(R.id.gridElePayeeVPA)).setText(payments.get(i).getPayeeVirtualAdd());
else
((TextView)view.findViewById(R.id.gridElePayeeVPA)).setText(payments.get(i).getPayerVirtualAdd());
((TextView)view.findViewById(R.id.gridEleAmountPaid)).setText(payments.get(i).getAmount()+"/-");
return view;
}
}
public class LoadDataTask extends AsyncTask<Void, Void, Boolean> {
@Override
protected Boolean doInBackground(Void... voids) {
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(getActivity().openFileInput(CurrentUser.getInstance().getMobile()));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if(ois == null){
return false;
}
Object obj = null;
try {
while((obj = ois.readObject())!=null){
Payment p = (Payment)obj;
Log.i("PayObj",p.toString());
Log.i("tag",""+p.getAmount());
if(type.equalsIgnoreCase("paid") && p.getPayerVirtualAdd().equalsIgnoreCase(CurrentUser.getInstance().getVpa())){
Log.i("tag","Added to list"+p.getAmount());
payments.add(p);
}
if (type.equalsIgnoreCase("collected") && !p.getPayerVirtualAdd().equalsIgnoreCase(CurrentUser.getInstance().getVpa())){
Log.i("tag","Added to list"+p.getAmount());
payments.add(p);
}
}
ois.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
@Override
protected void onPostExecute(Boolean aBoolean) {
gridView.setAdapter(new PaidBillAdapter());
}
}
}<file_sep>Please read the Instructions.pdf to set up testing environment.
Go through Nimble.pdf, to understand everything about Nimble's concept.
Watch Nimble.mp4 to see Nimble in action.
For any quries contact DarkFire through Hackerearth/Unified Payments Interface Hackathon.
Youtube link: https://www.youtube.com/watch?v=sseBA-OJ-EI
<file_sep>package com.darkfire;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.google.zxing.client.android.R;
public class MainActivity extends Activity {
Button regis, login;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
regis = (Button) findViewById(R.id.registerbtn);
regis.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent registration = new Intent(MainActivity.this, Registration.class);
startActivity(registration);
}
});
login = (Button)findViewById(R.id.loginbtn);
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
CurrentUser user = CurrentUser.getInstance();
user.setMobile(((EditText)findViewById(R.id.mobileno)).getText().toString());
user.setPassword(((EditText)findViewById(R.id.password)).getText().toString());
new LoginUserTask(MainActivity.this).execute(CurrentUser.getInstance());
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
return true;
}
}
<file_sep>package com.darkfire;
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.zxing.client.android.R;
public class PaymentFragment extends Fragment {
public static PaymentFragment newInstance() {
PaymentFragment fragment = new PaymentFragment();
return fragment;
}
public PaymentFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_payment, container, false);
}
}
<file_sep>package com.darkfire;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import com.google.zxing.client.android.CaptureActivity;
import com.google.zxing.client.android.R;
import java.util.HashMap;
public class Dashboard extends Activity {
private final int GET_PAID_CODE = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
setUpListeners();
}
private void setUpListeners(){
//collect call to psp mobile app
Button getPaidBtn = (Button) findViewById(R.id.getpaidbtn);
getPaidBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//write implementation for getting paid
Intent intent = new Intent(getApplicationContext(), CaptureActivity.class);
intent.setAction("com.google.zxing.client.android.SCAN");
intent.putExtra("SAVE_HISTORY", false);
startActivityForResult(intent, GET_PAID_CODE);
}
});
//get call to psp mobile app
Button makePaymentBtn = (Button) findViewById(R.id.makepaybtn);
makePaymentBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(getBaseContext(), MakePayment.class);
startActivity(intent);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == GET_PAID_CODE && resultCode ==RESULT_OK){
String result = data.getStringExtra("SCAN_RESULT");
Payment payment;
if(result != null) {
payment = buildPayment(result);
new VerifyPaymentTask(this).execute(payment);
}
//build payment object
//confirm if payment is of valid credentials through upi server
//if yes direct to make payment activity
//else cancel the transaction
}
}
private Payment buildPayment(String valsList){
String vals[] = valsList.split(Utility.lineSeparator());
HashMap<String, String> map = new HashMap<>();
map.put(Payment.PAYER_VIRTUAL_ADD, vals[0]);
map.put(Payment.PAYER_ID_NUMBER, vals[1]);
map.put(Payment.TRANSACTION_ID, vals[2]);
map.put(Payment.TRANSACTION_DESC, vals[3]);
map.put(Payment.AMOUNT, vals[4]);
if(CurrentUser.getInstance().isActive()){
map.put(Payment.PAYEE_NAME, CurrentUser.getInstance().getMobile());
map.put(Payment.PAYEE_VIRTUAL_ADD, CurrentUser.getInstance().getVpa());
}
//TODO: put current user credentials from user singleton
Payment p = new Payment();
p.makePaymentObj(map);
return p;
}
}
<file_sep>package com.darkfire;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import com.google.zxing.client.android.R;
public class BiilsFragment extends Fragment {
ImageButton allBillButton;
public static BiilsFragment newInstance() {
BiilsFragment fragment = new BiilsFragment();
return fragment;
}
public BiilsFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_biils, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
allBillButton = (ImageButton) view.findViewById(R.id.allBills);
allBillButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(getActivity().getBaseContext(), YourBill.class);
startActivity(intent);
}
});
}
}
<file_sep>package com.darkfire;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.zxing.client.android.R;
import java.util.List;
public class GetPayment extends Activity {
Payment paymentObj;
TextView payerName, idNumber, amount;
EditText password;
ListView listView;
protected static final String DEEP_LINK_URL_BASE = "upi://pay";
public static final int PSP_APP = 1;
boolean testing = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_payment);
paymentObj=(Payment)getIntent().getSerializableExtra(VerifyPaymentTask.PAYMENT_OBJ);
if(paymentObj==null)
return;
if(!paymentObj.isVerified())
return;
intializeView();
setUpListeners();
}
private void intializeView(){
listView = (ListView) findViewById(R.id.billView);
payerName = (TextView) findViewById(R.id.payer_name);
payerName.setText(paymentObj.getPayerVirtualAdd());
idNumber = (TextView) findViewById(R.id.id_number);
idNumber.setText(paymentObj.getTransactionId());
amount = (TextView) findViewById(R.id.amount);
amount.setText(""+paymentObj.getAmount());
password = (EditText)findViewById(R.id.password);
}
private void setUpListeners(){
Button verifyPayBtn = (Button) findViewById(R.id.getPayBtn);
verifyPayBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(testing == true){
Log.i("tag","Reached inside testing...");
if(password.getText().toString().equals(CurrentUser.getInstance().getPassword())) {
onActivityResult(PSP_APP, RESULT_OK, new Intent());
return;
}
}
if(password.getText().toString().equals(CurrentUser.getInstance().getPassword())) {
//new GetPaymentTask(GetPayment.this).execute(paymentObj);
StringBuilder urlBuilder = new StringBuilder();
urlBuilder.append(DEEP_LINK_URL_BASE).append("?")
.append("pa").append("=").append(paymentObj.getPayeeVirtualAdd())
.append("&") .append("pn").append("=").append(paymentObj.getPayeeName())
.append("&") .append("mc").append("=").append(paymentObj.getPayeeIdNumber())
.append("&") .append("ti").append("=").append(paymentObj.getPayeeIdNumber())
.append("&") .append("tr").append("=").append(paymentObj.getTransactionId())
.append("&") .append("tn").append("=").append(paymentObj.getTransactionDesc())
.append("&") .append("am").append("=").append(paymentObj.getAmount())
.append("&") .append("cu").append("=").append("INR");
//.append("&")
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(urlBuilder.toString()));
startActivityForResult(intent, PSP_APP);
}
else{
Toast.makeText(getBaseContext(),"Wrong Password!",Toast.LENGTH_LONG).show();
}
}
});
listView.setAdapter(new BillAdapter(paymentObj.getBill()));
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == RESULT_OK && requestCode == PSP_APP){
if(data.getStringExtra("status").equalsIgnoreCase("success")) {
Toast.makeText(getBaseContext(), "Success!", Toast.LENGTH_SHORT).show();
new SavePaymentTask(getApplicationContext()).execute(paymentObj);
finish();
}else{
Toast.makeText(getBaseContext(), "Transaction Failed!", Toast.LENGTH_SHORT).show();
}
}
else{
Toast.makeText(getBaseContext(), "Transaction Failed!", Toast.LENGTH_SHORT).show();
finish();
}
}
private class BillAdapter extends BaseAdapter{
List<BillElement> elements;
BillAdapter(List<BillElement> elements){
this.elements = elements;
}
@Override
public int getCount() {
return elements.size();
}
@Override
public Object getItem(int i) {
return elements.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
if(view != null){
return view;
}
view = getLayoutInflater().inflate(R.layout.bill_element, null);
((TextView)view.findViewById(R.id.element_serial)).setText("" + (i+1));
((TextView)view.findViewById(R.id.element_name)).setText(elements.get(i).name);
((TextView)view.findViewById(R.id.noOfUnits)).setText("" + elements.get(i).noOfUnits);
((TextView)view.findViewById(R.id.costPerUnit)).setText(""+elements.get(i).costPerUnit);
((TextView)view.findViewById(R.id.amount)).setText(""+elements.get(i).calculateAmount());
return view;
}
}
}
<file_sep>package com.darkfire;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import com.google.zxing.client.android.R;
public class TestActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
new DelayTask().execute();
}
private class DelayTask extends AsyncTask<Void, Void, Integer>{
@Override
protected Integer doInBackground(Void... voids) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Integer integer) {
startActivity(new Intent(getBaseContext(), MainActivity.class));
finish();
}
}
}
<file_sep>package com.darkfire.database;
import android.provider.BaseColumns;
/**
* Created by Siddharth on 3/15/2016.
*/
public class PaymentContract {
public PaymentContract(){
}
public static abstract class PaymentEntry implements BaseColumns{
public static final String TABLE_NAME = "payments";
public static final String COLUMN_NAME_ENTRY_ID = "tid";
public static final String COLUMN_NAME_PAYER_NAME = "PAYER_NAME";
public static final String COLUMN_NAME_PAYEE_NAME = "PAYEE_NAME";
public static final String COLUMN_NAME_PAYER_VIRTUAL_ADD = "PAYER_VIRTUAL_ADD";
public static final String COLUMN_NAME_PAYEE_VIRTUAL_ADD = "PAYEE_VIRTUAL_ADD";
public static final String COLUMN_NAME_PAYER_ID_NUMBER = "PAYER_ID_NUMBER";
public static final String COLUMN_NAME_PAYEE_ID_NUMBER = "PAYEE_ID_NUMBER";
public static final String COLUMN_NAME_TRANSACTION_DESC = "TRANSACTION_DESC";
public static final String COLUMN_NAME_AMOUNT = "AMOUNT";
}
}
<file_sep>#Sat Feb 20 18:35:48 IST 2016
<file_sep>package com.darkfire;
import java.io.Serializable;
/**
* Created by Siddharth on 3/9/2016.
*/
public class BillElement implements Serializable {
String name;
int noOfUnits;
double costPerUnit;
double amount;
double calculateAmount(){
amount = noOfUnits*costPerUnit;
return amount;
}
}
<file_sep>package com.darkfire.database;
import java.sql.SQLDataException;
import java.util.ArrayList;
import java.util.List;
import org.w3c.dom.ls.LSInput;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.darkfire.Payment;
public class DatabaseHandler extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "MyPayment.db";
//SQLiteDatabase db;
public DatabaseHandler(Context context){
super(context, DATABASE_NAME , null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("create table if not exists payments (payerVirAdd string,payeeVirAdd string,payerName string,payeeName string,tranId string primary key,amount double,paidStatus string)");
}
public boolean add(Payment payment){
try{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("payerVirAdd", payment.getPayerVirtualAdd());
contentValues.put("payeeVirAdd", payment.getPayeeVirtualAdd() );
contentValues.put("payerName", payment.getPayerName());
contentValues.put("payeeName",payment.getPayeeName());
contentValues.put("tranId", payment.getTransactionId());
contentValues.put("amount", payment.getAmount());
contentValues.put("paidStatus", payment.isPaid());
//contentValues.put("condition", cond);
db.insert("payments", null, contentValues);
return true;
}catch(SQLException e){
Log.i("Erprfsdfljsldfdsljfl", e.getMessage());
return false;
}
}
public List<String> getPayDeatil(){
SQLiteDatabase db = this.getReadableDatabase();
List<String> paymentDetail = new ArrayList<String>();
Cursor c = db.rawQuery("SELECT payerName, payeeName, tranId, amount, paidStatus FROM payments",null);
if(c.moveToFirst()){
do{
String pyName = c.getString(0);
String peName = c.getString(1);
String TId = c.getString(2);
double amount = c.getDouble(3);
String pStatus = c.getString(4);
String next = pyName + "##" + peName + "##" + TId + "##" + amount + "##" + pStatus;
paymentDetail.add(next);
}while(c.moveToNext());
}
return paymentDetail;
}
@Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
}
}
<file_sep>package com.darkfire;
/**
* Created by Siddharth on 2/25/2016.
*/
public class CurrentServer {
private String protocol="http";
private String server = "10.42.0.1";
private String port = "3000";
private String servlet = "";
private static CurrentServer INSTANCE;
private CurrentServer(){
}
public static CurrentServer getInstance(){
if(INSTANCE==null)
INSTANCE = new CurrentServer();
return INSTANCE;
}
public String getBaseAddress(){
return protocol + "://" + server + ":" + port + "/" + servlet;
}
}
|
86b759926f5a5f3e5362d1efcfb776459a182a5b
|
[
"Java",
"Text",
"INI"
] | 14 |
Java
|
sidd-pandey/Nimble
|
8695f8adff1f73f1bade1e2dcd6954519fb85eb1
|
d24a20e9f874cd36b298bbdb3457dd3963c6b34a
|
refs/heads/main
|
<file_sep>
AI = {}
function AI:load()
self.img = love.graphics.newImage("assets/ai.png")
self.width = self.img:getWidth()
self.height = self.img:getHeight()
self.x = love.graphics.getWidth() - self.width - 50
self.y = love.graphics.getHeight() / 2 - 50
self.yVel = 0
self.speed = 500
self.timer = 0
self.rate = 0.5
end
function AI:update(dt)
self:move(dt)
self.timer = self.timer + dt
if self.timer > self.rate then
self.timer = 0
self:acquireTarget(dt)
end
self:checkBoundaries()
end
function AI:move(dt)
self.y = self.y + self.yVel * dt
end
function AI:acquireTarget()
if Ball.y + Ball.height < self.y then
self.yVel = -self.speed
elseif Ball.y > self.y + self.height then
self.yVel = self.speed
else
self.yVel = 0
end
end
function AI:checkBoundaries()
if self.y < 0 then
self.y = 0
elseif self.y + self.height > love.graphics.getHeight() then
self.y = love.graphics.getHeight() - self.height
end
end
function AI:draw()
love.graphics.draw(self.img, self.x, self.y)
end<file_sep>require("player")
require("ball")
require("AI")
require("background")
function love.load()
Player:load()
Ball:load()
AI:load()
Background:load()
Score =
{
player = 0,
ai = 0
}
font = love.graphics.newFont(30)
fps = love.graphics.newFont(17)
end
function love.update(dt)
Player:update(dt)
Ball:update(dt)
AI:update(dt)
Background:update(dt)
end
function drawScore()
love.graphics.setFont(font)
love.graphics.print("Player: "..Score.player, 50, 50)
love.graphics.print("Bot: "..Score.ai, 1000, 50)
end
function drawFPS()
love.graphics.setFont(fps)
love.graphics.print("FPS: "..love.timer.getFPS(), 10 , 10)
end
function love.draw()
Background:draw()
Player:draw()
Ball:draw()
AI:draw()
drawScore()
drawFPS()
end
function checkCollision(a, b)
if a.x + a.width > b.x and a.x < b.x + b.width and a.y + a.height > b.y and a.y < b.y + b.height then
return true
else
return false
end
end<file_sep>Ball = {}
function Ball:load()
self.img= love.graphics.newImage("assets/ball.png")
self.x = love.graphics.getWidth() / 2
self.y = love.graphics.getHeight() / 2
self.width = self.img:getWidth()
self.height = self.img:getHeight()
self.speed = 350
self.xVel = -self.speed
self.yVel = 0
end
function Ball:update(dt)
Ball:move(dt)
Ball:collide()
end
function Ball:collide()
self:collidePlayer()
self:collideWall()
self:collideAI()
self:score()
end
function Ball:collidePlayer()
if checkCollision(self, Player) then
self.xVel = self.speed
local middleBall = self.y + self.height / 2
local middlePlayer = Player.y + Player.height / 2
local collisionPosition = middleBall - middlePlayer
self.yVel = collisionPosition * 5
end
end
function Ball:collideWall()
if self.y < 0 then
self.y = 0
self.yVel = -self.yVel
elseif self.y + self.height > love.graphics.getHeight() then
self.y = love.graphics.getHeight() - self.height
self.yVel = - self.yVel
end
end
function Ball:collideAI()
if checkCollision(self, AI) then
self.xVel = -self.speed
local middleBall = self.y + self.height / 2
local middleAI = AI.y + AI.height / 2
local collisionPosition = middleBall - middleAI
self.yVel = collisionPosition * 5
end
end
function Ball:score()
if self.x < 0 then
self:resetPosition(1)
Score.ai = Score.ai + 1
end
if self.x + self.width > love.graphics.getWidth() then
self:resetPosition(-1)
Score.player = Score.player + 1
end
end
function Ball:resetPosition(modifier)
self.x = love.graphics.getWidth() / 2 -self.width / 2
self.y = love.graphics.getHeight() / 2 - self.height / 2
self.yVel = 0;
self.xVel = self.speed * modifier
end
function Ball:move(dt)
self.x = self.x + self.xVel * dt
self.y = self.y + self.yVel * dt
end
function Ball:draw()
love.graphics.draw(self.img, self.x, self.y)
end<file_sep>Player = {}
function Player:load()
self.x = 50
self.y = love.graphics.getHeight() / 2 - 50;
self.img = love.graphics.newImage("assets/player.png")
self.width = self.img:getWidth()
self.height = self.img:getHeight()
self.speed = 500
end
function Player:update(dt)
self:move(dt)
self:checkBoundaries()
end
function Player:move(dt)
if love.keyboard.isDown("w") then
self.y = self.y - self.speed * dt
elseif love.keyboard.isDown("s") then
self.y = self.y + self.speed * dt
end
end
function Player:checkBoundaries()
if self.y < 0 then
self.y = 0
elseif self.y + self.height > love.graphics.getHeight() then
self.y = love.graphics.getHeight() - self.height
end
end
function Player:draw()
love.graphics.draw(self.img, self.x, self.y)
end<file_sep>function love.conf(t)
t.title = "Pong"
t.version = "11.3"
t.console = true
t.window.height = 720
t.window.width = 1280
t.window.icon = "assets/ball.png"
end
|
244c9d582e28e2d2c9f17da43cc31c507aaf40b4
|
[
"Lua"
] | 5 |
Lua
|
SuperHydroman/Pong-The-Game
|
2883b7264745f3388e28bbae50096def35ec3db9
|
6e47bed43ec4ef2a1ea25332f7391141e69f264b
|
refs/heads/master
|
<file_sep>package nl.codecentric.game;
import java.util.Iterator;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.TimeUtils;
public class CodecentricGame extends ApplicationAdapter {
OrthographicCamera camera;
SpriteBatch batch;
Texture shipTexture;
Texture enemyTexture;
Texture bombTexture;
Rectangle shipRectangle;
Rectangle bombRectangle;
Array<Rectangle> enemyArray;
long lastEnemy;
BitmapFont font;
BitmapFont.TextBounds textBounds;
String livesText = "Ships: ";
int lives = 3;
@Override
public void create() {
camera = new OrthographicCamera();
camera.setToOrtho(false, 800, 480);
batch = new SpriteBatch();
font = new BitmapFont(false);
font.setColor(Color.GREEN);
textBounds = font.getBounds(livesText + lives);
shipTexture = new Texture("ship.png");
enemyTexture = new Texture("enemy.png");
bombTexture = new Texture("bomb.png");
shipRectangle = new Rectangle();
shipRectangle.x = 800 / 2 - 23 / 2;
shipRectangle.y = 20;
shipRectangle.width = 23;
shipRectangle.height = 23;
enemyArray = new Array<Rectangle>();
spawnEnemies();
}
@Override
public void render() {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
camera.update();
redrawScreen();
// Block moving ship after all lives lost
if (lives > 0) {
updateShipPositionAfterInput();
fireBombAfterInput();
}
updateBombPosition();
// Generate new enemies
if (TimeUtils.nanoTime() - lastEnemy > 2500000000L)
spawnEnemies();
updateEnemyPositions();
}
private void updateEnemyPositions() {
Iterator<Rectangle> iter = enemyArray.iterator();
while (iter.hasNext()) {
Rectangle enemy = iter.next();
enemy.y -= 100 * Gdx.graphics.getDeltaTime();
if (enemy.y + 20 < 0) {
updateLivesWhenEnemyHitsBottom();
iter.remove();
} else if (bombRectangle != null && bombRectangle.overlaps(enemy)) {
// Handle bomb hitting enemy
bombRectangle = null;
iter.remove();
}
}
}
private void updateLivesWhenEnemyHitsBottom() {
if (lives > 0) {
lives--;
}
}
private void updateBombPosition() {
if (bombRectangle != null) {
bombRectangle.y += 200 * Gdx.graphics.getDeltaTime();
if (bombRectangle.y + 10 > 480)
bombRectangle = null;
}
}
private void fireBombAfterInput() {
if (Gdx.input.isKeyPressed(Input.Keys.SPACE)) {
spawnBomb();
}
}
private void updateShipPositionAfterInput() {
if (Gdx.input.isTouched()) {
Vector3 touchPos = new Vector3();
touchPos.set(Gdx.input.getX(), Gdx.input.getY(), 0);
camera.unproject(touchPos);
shipRectangle.x = touchPos.x - 23 / 2;
}
if (Gdx.input.isKeyPressed(Input.Keys.LEFT))
shipRectangle.x -= 200 * Gdx.graphics.getDeltaTime();
if (Gdx.input.isKeyPressed(Input.Keys.RIGHT))
shipRectangle.x += 200 * Gdx.graphics.getDeltaTime();
if (shipRectangle.x < 0)
shipRectangle.x = 0;
if (shipRectangle.x > 800 - 23)
shipRectangle.x = 800 - 23;
}
private void redrawScreen() {
batch.setProjectionMatrix(camera.combined);
batch.begin();
drawMovingTextures();
font.draw(batch, livesText + lives, 780 - textBounds.width, 460 - textBounds.height);
if (lives == 0) {
drawGameOver(batch);
}
batch.end();
}
private void drawMovingTextures() {
batch.draw(shipTexture, shipRectangle.x, shipRectangle.y);
for (Rectangle enemyRectangle : enemyArray) {
batch.draw(enemyTexture, enemyRectangle.x, enemyRectangle.y);
}
if (bombRectangle != null) {
batch.draw(bombTexture, bombRectangle.x, bombRectangle.y);
}
}
private void drawGameOver(final SpriteBatch batch) {
final String gameOver = "GAME OVER";
BitmapFont gameOverFont = new BitmapFont(false);
gameOverFont.setColor(Color.RED);
gameOverFont.scale(5.0f);
BitmapFont.TextBounds gameOverTextBounds = gameOverFont.getBounds(gameOver);
gameOverFont.draw(batch, gameOver, 800 / 2 - gameOverTextBounds.width / 2, 300 - gameOverTextBounds.height / 2);
}
private void spawnBomb() {
if (bombRectangle == null) {
bombRectangle = new Rectangle();
bombRectangle.x = shipRectangle.x + 6;
bombRectangle.y = shipRectangle.height + shipRectangle.y;
bombRectangle.width = 10;
bombRectangle.height = 10;
}
}
private void spawnEnemies() {
Rectangle enemy = new Rectangle();
enemy.x = MathUtils.random(0, 800 - 18);
enemy.y = 480;
enemy.width = 18;
enemy.height = 18;
enemyArray.add(enemy);
lastEnemy = TimeUtils.nanoTime();
}
@Override
public void dispose() {
shipTexture.dispose();
enemyTexture.dispose();
bombTexture.dispose();
batch.dispose();
}
}
<file_sep>app.version=1.0
app.id=nl.codecentric.game.IOSLauncher
app.mainclass=nl.codecentric.game.IOSLauncher
app.executable=IOSLauncher
app.build=1
app.name=codecentric-game
<file_sep>codecentricGaming
=================
|
a863464d97cd74f6baa2e17d1e580017526b5b9a
|
[
"Markdown",
"Java",
"INI"
] | 3 |
Java
|
coding-with-craftsmen/codecentricGaming
|
2d9a064f825a8e7b5bd481c2b242009b01e4d3c3
|
e966299e39b69c11c58bfc1974787a79ddc29fd4
|
refs/heads/master
|
<repo_name>hoivikaj/pubscripts<file_sep>/xrdp1804.sh
sudo apt-get update -y
sudo apt-get upgrade -y
sudo apt-get install xrdp -y
sudo apt-get install gnome-tweak-tool -y
sudo sed -i 's/allowed_users=console/allowed_users=anybody/' /etc/X11/Xwrapper.config
sudo bash -c "cat >/etc/polkit-1/localauthority/50-local.d/45-allow.colord.pkla" <<EOF
[Allow Colord all Users]
Identity=unix-user:*
Action=org.freedesktop.color-manager.create-device;org.freedesktop.color-manager.create-profile;org.freedesktop.color-manager.delete-device;org.freedesktop.color-manager.delete-profile;org.freedesktop.color-manager.modify-device;org.freedesktop.color-manager.modify-profile
ResultAny=no
ResultInactive=no
ResultActive=yes
EOF
gnome-shell-extension-tool -e <EMAIL>
gnome-shell-extension-tool -e <EMAIL>
sudo apt install xserver-xorg-core -y
sudo apt install xorgxrdp -y
reboot
<file_sep>/ctx1804t.sh
echo **Disabling IPV6**
sudo sysctl -w net.ipv6.conf.all.disable_ipv6=1
sudo sysctl -w net.ipv6.conf.default.disable_ipv6=1
echo **Updates!**
#sudo apt-get update -y
#sudo apt-get upgrade -y
#sudo apt-get install openssh-server -y
echo **Getting VDA Package**
wget https://hoivikaj.s3.amazonaws.com/xendesktopvda_19.9.0.3-1.ubuntu18.04_amd64.deb
export CTX_EASYINSTALL_HOSTNAME=$HOSTNAME
export CTX_EASYINSTALL_DNS="172.28.67.34 172.28.67.35"
export CTX_EASYINSTALL_NTPS=ntp.unch.unc.edu
export CTX_EASYINSTALL_DOMAIN=UNCH
export CTX_EASYINSTALL_REALM=UNCH.UNC.EDU
export CTX_EASYINSTALL_FQDN=unch.unc.edu
export CTX_EASYINSTALL_ADINTEGRATIONWAY=winbind
export CTX_XDL_SUPPORT_DDC_AS_CNAME=N
export CTX_XDL_DDC_LIST="ctxvddc-un1-p01.unch.unc.edu ctxvddc-un1-p02.unch.unc.edu ctxvddc-un1-p03.unch.unc.edu ctxvddc-un2-p01.unch.unc.edu ctxvddc-un2-p02.unch.unc.edu ctxvddc-un2-p03.unch.unc.edu"
export CTX_XDL_VDA_PORT=80
export CTX_XDL_REGISTER_SERVICE=Y
export CTX_XDL_ADD_FIREWALL_RULES=Y
export CTX_XDL_HDX_3D_PRO=N
export CTX_XDL_VDI_MODE=Y
export CTX_XDL_SITE_NAME='<none>'
export CTX_XDL_LDAP_LIST='<none>'
export CTX_XDL_SEARCH_BASE='<none>'
export CTX_XDL_FAS_LIST='<none>'
export CTX_XDL_DOTNET_RUNTIME_PATH=/opt/dotnet
export CTX_XDL_START_SERVICE=Y
sudo dpkg -i xendesktopvda_19.9.0.3-1.ubuntu18.04_amd64.deb
sudo apt-get install -y -f
sudo -E /opt/Citrix/VDA/sbin/ctxinstall.sh
sudo apt-get install xserver-xorg ubuntu-desktop xserver-xorg-core -y
read -p "ENTER DOMAIN USER TO BE SUDO/ADMIN (u123456): " duser
sudo usermod -aG sudo $duser
echo V3
|
f5deebc79a4d2203c74e74598458537a03c53efc
|
[
"Shell"
] | 2 |
Shell
|
hoivikaj/pubscripts
|
8b31ba15fb698097df2639f68db23319c6849a9e
|
d5b6bcc49fec80de65c39d31ba0346e1351ba221
|
refs/heads/master
|
<file_sep>//
// ShellSortTest.cpp
// algo
//
// Created by raof01 on 8/2/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#include "gtest/gtest.h"
#include "ArraysMatch.hpp"
#include "ShellSort.h"
static int result[] = {7, 17, 18, 25, 28, 47, 53, 62, 69, 83, 86, 95};
// ShellSort
TEST(TestShellSort, Positive)
{
int a[] = {62, 83, 18, 53, 07, 17, 95, 86, 47, 69, 25, 28};
ShellSorter<int>::Sort(a);
ASSERT_TRUE(ArraysMatch(result, a));
}
TEST(TestShellSort, OneElem)
{
int a[] = {8};
ShellSorter<int>::Sort(a);
ASSERT_TRUE(ArraysMatch(a, a));
}
TEST(TestShellSort, TwoElems)
{
int a[] = {8, 0};
int result[] = {0, 8};
ShellSorter<int>::Sort(a);
ASSERT_TRUE(ArraysMatch(result, a));
}
<file_sep> //
// ConnectionTreeImpl.cpp
// algo
//
// Created by raof01 on 7/25/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#include <stdlib.h>
#include "ConnectionTreeImpl.h"
ConnectionTreeImpl::ConnectionTreeImpl(int sz)
: mRoot(sz)
{
for (int i = 0; i < mRoot.capacity(); ++i)
mRoot[i] = i;
}
ConnectionTreeImpl::~ConnectionTreeImpl()
{
}
int ConnectionTreeImpl::Root(int i)
{
if (OutOfRange(i)) return -1;
while (mRoot[i] != i) i = mRoot[i];
return i;
}
bool ConnectionTreeImpl::OutOfRange(int i)
{
return i < 0 || i >= mRoot.capacity();
}
void ConnectionTreeImpl::ConnectTo(int src, int target)
{
if (OutOfRange(src) || OutOfRange(target)) return;
if (Connected(src, target)) return;
mRoot[Root(src)] = mRoot[Root(target)];
}
bool ConnectionTreeImpl::Connected(int i1, int i2)
{
if (OutOfRange(i1) || OutOfRange(i2)) return false;
return Root(i1) == Root(i2);
}
<file_sep>//
// Stack.hpp
// algo
//
// Created by raof01 on 5/9/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#ifndef algo_Stack_hpp
#define algo_Stack_hpp
template <typename T, int MAX_SIZE = 1024>
class Stack
{
public:
Stack() : mTop(0) {}
bool Push(const T& v) {if (Full()) return false; mData[mTop++] = v; return true;}
T Pop() { if (Count() < 1) return T(); else return mData[--mTop]; }
const T Peek() const { if (Count() < 1) return T(); else return mData[mTop - 1]; }
bool Empty() const { return mTop == 0; }
bool Full() const { return mTop == MAX_SIZE; }
int MaxSize() const { return MAX_SIZE; }
int Count() const { return mTop; }
private:
T mData[MAX_SIZE];
int mTop;
};
#endif
<file_sep>//
// Created by raof01 on 8/29/15.
//
#include "gtest/gtest.h"
#include "MaxMin.h"
TEST(TestMax, OneElem)
{
int a[] = {1};
ASSERT_EQ(1, Max(a, 1));
}
TEST(TestMax, TwoDifferentElems)
{
int a[] = {1, 2};
ASSERT_EQ(2, Max(a, 2));
}
TEST(TestMax, TwoEqualElems)
{
int a[] = {2, 2};
ASSERT_EQ(2, Max(a, 2));
}
TEST(TestMax, ThreeDifferentElems)
{
int a[] = {2, 3, 3};
ASSERT_EQ(3, Max(a, 3));
}
TEST(TestMax, FourDifferentElems)
{
int a[] = {25, 3, 3, 5};
ASSERT_EQ(25, Max(a, 4));
}
TEST(TestMin, OneElem)
{
int a[] = {1};
ASSERT_EQ(1, Min(a, 1));
}
TEST(TestMin, TwoDifferentElems)
{
int a[] = {1, 2};
ASSERT_EQ(1, Min(a, 2));
}
TEST(TestMin, TwoEqualElems)
{
int a[] = {2, 2};
ASSERT_EQ(2, Min(a, 2));
}
TEST(TestMin, ThreeDifferentElems)
{
int a[] = {2, 3, 3};
ASSERT_EQ(2, Min(a, 3));
}
TEST(TestMin, FourDifferentElems)
{
int a[] = {25, 3, 3, 5};
ASSERT_EQ(3, Min(a, 4));
}
TEST(TestMaxMin, OneElem)
{
int a[] = {1};
int max = -1;
int min = -1;
MaxMin(a, 1, max, min);
ASSERT_EQ(1, max);
ASSERT_EQ(1, min);
}
TEST(TestMaxMin, TwoDifferentElems)
{
int a[] = {1, 2};
int max = -1;
int min = -1;
MaxMin(a, 2, max, min);
ASSERT_EQ(2, max);
ASSERT_EQ(1, min);
}
TEST(TestMaxMin, TenDifferentElems)
{
int a[] = {1, 2, 9, 8, 11, 8, 7, 167, -19, 0};
int max = -1;
int min = -1;
MaxMin(a, 10, max, min);
ASSERT_EQ(167, max);
ASSERT_EQ(-19, min);
}
<file_sep>//
// MinSubArrayLen.cpp
// algo
//
// Created by raof01 on 5/24/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#include "MinSubArrayLen.h"
#include <algorithm>
int MinSubArrayLen(int s, const std::vector<int>& nums)
{
#if 1
// O(n^2)
int size = static_cast<int>(nums.size());
if (size == 0) return 0;
int min = size + 1;
int i = 0, j = 0;
for (; i < size; ++i)
{
int sum = s - nums[i];
if (sum <= 0) min = 1;
for (j = i + 1; j < size && sum > 0; ++j)
{
sum -= nums[j];
if (sum <= 0)
{
if (j - i < min) min = j - i + 1;
break;
}
}
}
return min == size + 1 ? 0 : min;
#else
// O(n)
// The window technique here:
// 1. Grow window only by increasing right border
// 2. Reduce window only by increasing left border
// 3. Grow window by one elem at a time
// ****4. The invariant:
// sum([leftBorder .. rightBorder]) >= s
// && sum([leftBorder + 1 .. rightBorder]) <s
// 5. Update minimum window size every time a smaller window is found
int minLen = static_cast<int>(nums.size());
int wLeftBorder = 0, localSum = 0;
for(int wRightBorder = 0; wRightBorder < nums.size(); wRightBorder++)
{
// Grow the window by increasing right border...
localSum += nums[wRightBorder];
// until local sum in window larger than s.
// Then reduce the window by increasing left border...
// until local sum of [wLeftBorder + 1 .. wRightBorder] less than s
while(localSum - nums[wLeftBorder] >= s) localSum -= nums[wLeftBorder++];
// If local sum of [wLeftBorder .. wRightBorder] >= s, then we found one
// possible minimum window size
if(localSum >= s) minLen = std::min(minLen, wRightBorder - wLeftBorder + 1);
// If it's not the minimum window size, reduce window size by increasing
// left border and start to grow the window.
if(wRightBorder - wLeftBorder + 1 > minLen) localSum -= nums[wLeftBorder++];
}
if(minLen == nums.size()) return 0;
return minLen;
#endif
}
int MinSubArrayLen(int s, const int* nums, int numsSize)
{
#if 0
int minLen = numsSize;
if (nums == nullptr || numsSize <= 0) return minLen;
for (int i = 0; i < numsSize; ++i)
{
int sum = s - nums[i];
int j = i + 1;
while (sum > 0 && j < numsSize) sum -= nums[j++];
if (sum <= 0)
{
if (j - i < minLen) minLen = j - i;
}
else
if (j - i >= numsSize) return 0;
}
return minLen;
#else
int minLen = numsSize;
int localSum = 0;
int lBorder = 0;
for (int rBorder = 0; rBorder < numsSize && lBorder < numsSize; ++rBorder)
{
localSum += nums[rBorder];
while (localSum - nums[lBorder] >= s) localSum -= nums[lBorder++];
if (localSum >= s) minLen = minLen > rBorder - lBorder + 1 ? rBorder - lBorder + 1 : minLen;
if (rBorder - lBorder + 1 > minLen) localSum -= nums[lBorder++];
}
return minLen == numsSize ? 0 : minLen;
#endif
}
<file_sep># IntroAlgo
Simple implementations of IntroAlgo
<file_sep>//
// Misc.cpp
// algo
//
// Created by raof01 on 7/22/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#include <cstdio>
#include "Misc.h"
using namespace std;
int CountBinaryOneRecursive(int n)
{
if (n == 0) return 0;
if (n == 1) return 1;
int cnt = n & 0x00000001;
return cnt + CountBinaryOneRecursive(static_cast<unsigned int>(n) >> 1);
}
std::vector<int> GetLots(const std::vector<int>& lst1, const std::vector<int>& lst2)
{
std::vector<int> result;
std::vector<int>::const_iterator lst1Iter = lst1.begin();
std::vector<int>::const_iterator lst2Iter = lst2.begin();
int pos = 0;
for (; lst2Iter != lst2.end(); ++lst2Iter)
{
while (pos < *lst2Iter && lst1Iter != lst1.end())
{
++pos;
++lst1Iter;
}
if (lst1Iter == lst1.end()) break;
result.push_back(*lst1Iter);
}
return result;
}
std::vector<int> InterSect(const std::vector<int>& lst1, const std::vector<int>& lst2)
{
std::vector<int> result;
std::vector<int>::const_iterator lst1Iter = lst1.begin();
std::vector<int>::const_iterator lst2Iter = lst2.begin();
while (lst1Iter != lst1.end() && lst2Iter != lst2.end())
{
if (*lst1Iter < *lst2Iter)
++lst1Iter;
else if (*lst1Iter > *lst2Iter)
++lst2Iter;
else
{
result.push_back(*lst1Iter);
++lst1Iter;
++lst2Iter;
}
}
return result;
}
std::vector<int> Union(const std::vector<int>& lst1, const std::vector<int>& lst2)
{
std::vector<int> result;
std::vector<int>::const_iterator lst1Iter = lst1.begin();
std::vector<int>::const_iterator lst2Iter = lst2.begin();
while (lst1Iter != lst1.end() && lst2Iter != lst2.end())
{
if (*lst1Iter == *lst2Iter)
{
result.push_back(*lst1Iter++);
++lst2Iter;
}
else if (*lst1Iter < *lst2Iter)
result.push_back(*lst1Iter++);
else
result.push_back(*lst2Iter++);
}
while (lst1Iter != lst1.end()) result.push_back(*lst1Iter++);
while (lst2Iter != lst2.end()) result.push_back(*lst2Iter++);
return result;
}
// const int M = 3;
// The array has 3 rows
int Cover(int n)
{
if (n < 2 || (n % 2) == 1) return 1;
// if (m * n == 2) return 1;
return 4 * Cover(n - 2) - Cover(n - 4);
}
// No doubtedly, this recursive version will do
// N * M recomputation
int NumOfSum(int* a, int aPos, int* b, int bPos, int sum)
{
#if 0
if (aPos < 0 || bPos < 0) return 0;
// Ignore the numbers larger than sum
while (a[aPos] > sum) --aPos;
while (b[bPos] > sum) --bPos;
int n = (a[aPos] + b[bPos] == sum) ? 1 : 0;
int n1 = NumOfSum(a, aPos - 1, b, bPos, sum);
int n2 = NumOfSum(a, aPos, b, bPos - 1, sum);
// The repeated computed results
// Finally I realized this is the problem
int n3 = NumOfSum(a, aPos - 1, b, bPos - 1, sum);
return n + n1 + n2 - n3;
#endif
int ** r = new int*[100];
for (int i = 0; i < 100; ++i)
r[i] = new int[100];
for (int i = 0; i < 100; ++i)
for (int j = 0; j < 100; ++j)
r[i][j] = 0;
int ret = 0;
NumOfSum(a, aPos, b, bPos, sum, r, ret);
return ret;
}
void NumOfSum(int* a, int aPos, int* b, int bPos, int sum, int**r, int &ret)
{
if (aPos < 0 || bPos < 0) return;
// Ignore the numbers larger than sum
while (a[aPos] > sum) --aPos;
while (b[bPos] > sum) --bPos;
if (aPos < 0 || bPos < 0) return;
int n = (a[aPos] + b[bPos] == sum) ? 1 : 0;
if (r[aPos][bPos+1] == 0)
NumOfSum(a, aPos - 1, b, bPos, sum, r, r[aPos][bPos+1]);
if (r[aPos+1][bPos] == 0)
NumOfSum(a, aPos, b, bPos - 1, sum, r, r[aPos+1][bPos]);
if (r[aPos][bPos] == 0)
NumOfSum(a, aPos - 1, b, bPos - 1, sum, r, r[aPos][bPos]);
ret = n + r[aPos][bPos+1] + r[aPos+1][bPos] - r[aPos][bPos];
}
bool IsPermutationOf(const std::string& b, const std::string& a)
{
if (b.length() != a.length())
return false;
const int MAX_NUM_ASCII_CHARACTERS = 128;
int countA[MAX_NUM_ASCII_CHARACTERS] = {0};
int countB[MAX_NUM_ASCII_CHARACTERS] = {0};
for (size_t i = 0; i < a.length(); ++i)
{
++countA[static_cast<int>(a[i])];
++countB[static_cast<int>(b[i])];
}
for (int i = 0; i < MAX_NUM_ASCII_CHARACTERS; ++i)
if (countA[i] != countB[i])
return false;
return true;
}
const std::string& CompressString(const std::string& src, std::string& dest)
{
const int MAX_INT_LEN = 16;
dest.clear();
if (src.length() == 0) return src;
size_t cur = 0;
while (cur < src.length()) {
int cnt = 1;
size_t next = cur + 1;
while (src[cur] == src[next]) {
++cnt;
++next;
}
if (src.length() <= dest.length()) {
dest.clear();
return src;
}
dest.push_back(src[cur]);
char strCnt[MAX_INT_LEN] = {0};
#if WIN == 1
_snprintf(strCnt, MAX_INT_LEN - 1, "%d", cnt);
#else
snprintf(strCnt, MAX_INT_LEN - 1, "%d", cnt);
#endif
dest.append(strCnt);
cur = next;
}
return dest;
}
bool IsUnique(const std::string& s) {
const int MAX_NUM_ASCII_CHAR = 128;
if (s.length() > MAX_NUM_ASCII_CHAR) return false;
bool exists[MAX_NUM_ASCII_CHAR] = {false};
for (size_t i = 0; i < s.length(); ++i)
if (exists[static_cast<int>(s[i])])
return false;
else
exists[static_cast<int>(s[i])] = true;
return true;
}
bool IsRotate(const std::string& s1, const std::string& s2) {
if (s1.length() != s2.length()) return false;
if (s1.length() == 0) return false;
std::string s = s1 + s1;
return s.find(s2) != std::string::npos;
}
void SortStackUsingStack(std::vector<int>& s) {
if (s.empty()) return;
std::vector<int> aux;
int savedMin = INT_MAX;
int max = INT_MIN;
while (s.back() != max) {
int cnt = 1;
int min = INT_MAX;
while (!s.empty() && s.back() != savedMin) {
int v = s.back();
if (v == min) ++cnt;
if (v < min) { min = v; cnt = 1;}
if (v > max) max = v;
aux.push_back(v);
s.pop_back();
}
savedMin = min;
for (; cnt > 0; --cnt)
s.push_back(savedMin);
while (!aux.empty()) {
int v = aux.back();
if (v != savedMin) s.push_back(v);
aux.pop_back();
}
}
}
void SortStackUsingStack(std::vector<int>& s, std::vector<int>& d) {
if (s.empty()) { d.clear(); return; }
while (!s.empty()) {
int v = s.back();
s.pop_back();
while (!d.empty() && v < d.back()) {
s.push_back(d.back());
d.pop_back();
}
d.push_back(v);
}
}
void MergeTwoSortedArrays(std::vector<int>& dest, const std::vector<int>& src) {
if (src.size() == 0) return;
if (dest.size() == 0) dest = src;
dest.resize(dest.size() + src.size());
int cur = static_cast<int>(dest.size() - 1);
int srcPos = static_cast<int>(src.size() - 1);
int destPos = static_cast<int>(cur - srcPos - 1);
while (cur >= 0 && srcPos >= 0) {
if (dest[destPos] > src[srcPos])
dest[cur] = dest[destPos--];
else
dest[cur] = src[srcPos--];
--cur;
}
while (srcPos >= 0) {
dest[cur--] = src[srcPos--];
}
}
<file_sep>//
// Created by raof01 on 9/23/15.
//
#include "RouteCalculator.h"
#include "gtest/gtest.h"
TEST(TestRoutes, EmptyGrid) {
RouteCalculator rc = RouteCalculator(0, 0, 0, 0);
ASSERT_EQ(0, rc.Routes(Point(0, 0), Point(0, 0)));
}
TEST(TestRoutes, StartPointOutOfGrid) {
RouteCalculator rc = RouteCalculator(0, 0, 10, 10);
ASSERT_EQ(0, rc.Routes(Point(-1, -1), Point(0, 0)));
}
TEST(TestRoutes, EndPointOutOfGrid) {
RouteCalculator rc = RouteCalculator(0, 0, 10, 10);
ASSERT_EQ(0, rc.Routes(Point(0, 0), Point(20, 20)));
}
TEST(TestRoutes, EndPointOnTheLeftToStartPoint) {
RouteCalculator rc = RouteCalculator(0, 0, 10, 10);
ASSERT_EQ(0, rc.Routes(Point(5, 0), Point(0, 0)));
}
TEST(TestRoutes, EndPointOnTheAboveToStartPoint) {
RouteCalculator rc = RouteCalculator(0, 0, 10, 10);
ASSERT_EQ(0, rc.Routes(Point(5, 5), Point(5, 0)));
}
TEST(TestRoutes, EndPointBelowStartPoint) {
RouteCalculator rc = RouteCalculator(0, 0, 10, 10);
ASSERT_EQ(1, rc.Routes(Point(0, 5), Point(0, 10)));
}
TEST(TestRoutes, EndPointRightToStartPoint) {
RouteCalculator rc = RouteCalculator(0, 0, 10, 10);
ASSERT_EQ(1, rc.Routes(Point(0, 5), Point(5, 5)));
}
TEST(TestRoutes, EndPointOntRightBelowToStartPoint) {
RouteCalculator rc = RouteCalculator(0, 0, 10, 10);
ASSERT_EQ(252, rc.Routes(Point(0, 0), Point(5, 5)));
}
TEST(TestRoutes, EndPointOntRightBelowToStartPoint1) {
RouteCalculator rc = RouteCalculator(0, 0, 10, 10);
ASSERT_EQ(6, rc.Routes(Point(0, 0), Point(5, 1)));
}
TEST(TestRoutes, EndPointOntRightBelowToStartPoint2) {
RouteCalculator rc = RouteCalculator(0, 0, 10, 10);
ASSERT_EQ(6, rc.Routes(Point(0, 0), Point(1, 5)));
}
<file_sep>//
// KthSelectionTest.cpp
// algo
//
// Created by raof01 on 8/6/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#include "gtest/gtest.h"
#include "KthSelection.h"
TEST(TestKthSelection, Positive0)
{
int a[] = {2, 8, 7, 1, 3, 5, 6, 4};
ASSERT_EQ(1, KthSelection<int>::Select(a, 0));
}
TEST(TestKthSelection, Positive1)
{
int a[] = {2, 8, 7, 1, 3, 5, 6, 4};
ASSERT_EQ(2, KthSelection<int>::Select(a, 1));
}
TEST(TestKthSelection, Positive2)
{
int a[] = {2, 8, 7, 1, 3, 5, 6, 4};
ASSERT_EQ(3, KthSelection<int>::Select(a, 2));
}
TEST(TestKthSelection, Positive3)
{
int a[] = {2, 8, 7, 1, 3, 5, 6, 4};
ASSERT_EQ(4, KthSelection<int>::Select(a, 3));
}
TEST(TestKthSelection, Positive4)
{
int a[] = {2, 8, 7, 1, 3, 5, 6, 4};
ASSERT_EQ(5, KthSelection<int>::Select(a, 4));
}
TEST(TestKthSelection, Positive5)
{
int a[] = {2, 8, 7, 1, 3, 5, 6, 4};
ASSERT_EQ(6, KthSelection<int>::Select(a, 5));
}
TEST(TestKthSelection, Positive6)
{
int a[] = {2, 8, 7, 1, 3, 5, 6, 4};
ASSERT_EQ(7, KthSelection<int>::Select(a, 6));
}
TEST(TestKthSelection, Positive7)
{
int a[] = {2, 8, 7, 1, 3, 5, 6, 4};
ASSERT_EQ(8, KthSelection<int>::Select(a, 7));
}
<file_sep>//
// DoubleLinkedListTest.cpp
// algo
//
// Created by raof01 on 5/9/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#include "gtest/gtest.h"
#include "DoubleLinkedList.h"
TEST(TestDoubleLinkedList, EmptyReturnTrue)
{
DoubleLinkedList lst;
ASSERT_TRUE(lst.Empty());
ASSERT_EQ(0, lst.Count());
}
TEST(TestDoubleLinkedList, EmptyReturnTrueAfterInsertAndDelete)
{
DoubleLinkedList lst;
for (int i = 0; i < 10; ++i)
lst.Insert(i);
for (int i = 0; i < 10; ++i)
lst.Delete(i);
ASSERT_TRUE(lst.Empty());
ASSERT_EQ(0, lst.Count());
}
TEST(TestDoubleLinkedList, EmptyReturnFalseOnNonEmptyList)
{
DoubleLinkedList lst;
lst.Insert(10);
ASSERT_FALSE(lst.Empty());
ASSERT_EQ(1, lst.Count());
}
TEST(TestDoubleLinkedList, EmptyReturnFalseOnNonEmptyListAfterInsertAndDelete)
{
DoubleLinkedList lst;
for (int i = 0; i < 10; ++i)
lst.Insert(i);
for (int i = 0; i < 5; ++i)
lst.Delete(i);
ASSERT_FALSE(lst.Empty());
ASSERT_EQ(5, lst.Count());
}
TEST(TestDoubleLinkedList, Insert)
{
DoubleLinkedList lst;
int a[] = {0, 8, 7, 9, 3, 1, 5, 4, 2, 6};
for (int i = sizeof(a) / sizeof(int) - 1; i >= 0; --i)
lst.Insert(a[i]);
ASSERT_FALSE(lst.Empty());
ASSERT_EQ(10, lst.Count());
int i = 0;
for (DoubleLinkedList::Iterator iter = lst.Begin(); iter != lst.End(); ++iter)
ASSERT_EQ(a[i++], *iter);
}
TEST(TestDoubleLinkedList, InsertTenElemsDeleteFiveElems)
{
DoubleLinkedList lst;
int a[] = {0, 8, 7, 9, 3, 1, 5, 4, 2, 6};
for (int i = sizeof(a) / sizeof(int) - 1; i >= 0; --i)
lst.Insert(a[i]);
ASSERT_FALSE(lst.Empty());
ASSERT_EQ(10, lst.Count());
for (int i = 0; i < sizeof(a)/sizeof(int) / 2; ++i)
lst.Delete(a[i]);
ASSERT_FALSE(lst.Empty());
ASSERT_EQ(5, lst.Count());
int i = 5;
int loopCnt = 0;
for (DoubleLinkedList::Iterator iter = lst.Begin(); iter != lst.End(); ++iter)
{
++loopCnt;
ASSERT_EQ(a[i++], *iter);
}
ASSERT_EQ(5, loopCnt);
}
TEST(TestDoubleLinkedList, DeleteAll)
{
DoubleLinkedList lst;
for (int i = 0; i < 10; ++i)
lst.Insert(1);
ASSERT_FALSE(lst.Empty());
ASSERT_EQ(10, lst.Count());
lst.DeleteAll(1);
ASSERT_TRUE(lst.Empty());
}
TEST(TestDoubleLinkedList, DeleteHalf)
{
DoubleLinkedList lst;
for (int i = 0; i < 10; ++i)
lst.Insert(1);
for (int i = 0; i < 10; ++i)
lst.Insert(2);
ASSERT_FALSE(lst.Empty());
ASSERT_EQ(20, lst.Count());
lst.DeleteAll(1);
ASSERT_FALSE(lst.Empty());
ASSERT_EQ(10, lst.Count());
int loopCnt = 0;
for (DoubleLinkedList::Iterator iter = lst.Begin(); iter != lst.End(); ++iter)
{
++loopCnt;
ASSERT_EQ(2, *iter);
}
ASSERT_EQ(10, loopCnt);
}
TEST(TestDoubleLinkedList, OperatorPrefixIncOnOneElemList)
{
DoubleLinkedList lst;
lst.Insert(1);
int loopCnt = 0;
for (DoubleLinkedList::Iterator iter = lst.Begin(); iter != lst.End(); ++iter)
++loopCnt;
ASSERT_EQ(1, loopCnt);
}
TEST(TestDoubleLinkedList, OperatorPostfixIncOnOneElemList)
{
DoubleLinkedList lst;
lst.Insert(1);
int loopCnt = 0;
for (DoubleLinkedList::Iterator iter = lst.Begin(); iter != lst.End(); iter++)
++loopCnt;
ASSERT_EQ(1, loopCnt);
}
TEST(TestDoubleLinkedList, FindAndTraverseFromFoundItem)
{
DoubleLinkedList lst;
int a[] = {0, 8, 7, 9, 3, 1, 5, 4, 2, 6};
for (int i = sizeof(a) / sizeof(int) - 1; i >= 0; --i)
lst.Insert(a[i]);
int loopCnt = 0;
for (DoubleLinkedList::Iterator iter = lst.Find(9); iter != lst.End(); iter++)
++loopCnt;
ASSERT_EQ(10, loopCnt);
}
TEST(TestDoubleLinkedList, FindAndTraverseWhenNoItemFound)
{
DoubleLinkedList lst;
int a[] = {0, 8, 7, 9, 3, 1, 5, 4, 2, 6};
for (int i = sizeof(a) / sizeof(int) - 1; i >= 0; --i)
lst.Insert(a[i]);
int loopCnt = 0;
for (DoubleLinkedList::Iterator iter = lst.Find(11); iter != lst.End(); iter++)
++loopCnt;
ASSERT_EQ(0, loopCnt);
}
<file_sep>//
// WordPattern.cpp
// algo
//
// Created by <NAME> on 10/9/15.
// Copyright © 2015 raof01. All rights reserved.
#include <map>
#include <unordered_map>
#include <algorithm>
#include "LeetCodeProblems.h"
using namespace std;
/*
Given a pattern and a string str, find if str follows the same pattern.
Examples:
1 pattern = "abba", str = "dog cat cat dog" should return true.
2 pattern = "abba", str = "dog cat cat fish" should return false.
3 pattern = "aaaa", str = "dog cat cat dog" should return false.
4 pattern = "abba", str = "dog dog dog dog" should return false.
Notes:
1 patterncontains only lowercase alphabetical letters, and str contains words separated by a single space. Each word in str contains only lowercase alphabetical letters.
2 Both pattern and str do not have leading or trailing spaces.
3 Each letter in pattern must map to a word with length that is at least 1.
*/
bool WordPattern::wordPattern(const string& pattern, const string& str) {
vector<const string> v;
SplitString(str, v);
if (v.size() != pattern.length()) return false;
map<char, int> mp;
map<const string, int> ms;
for (int i = 0; i < pattern.length(); ++i) {
map<char, int>::iterator iterP = mp.find(pattern[i]);
map<const string, int>::iterator iterS = ms.find(v[i]);
if (iterP != mp.end() && iterS != ms.end()) {
if (iterP->second != iterS->second)
return false;
else {
iterP->second = i;
iterS->second = i;
}
} else if (iterP == mp.end() && iterS == ms.end()) {
mp.insert(make_pair(pattern[i], i));
ms.insert(make_pair(v[i], i));
} else
return false;
}
return true;
}
void WordPattern::SplitString(const string& str, vector<const string>& v) {
int s = 0; int end = 0;
while (s < str.length()) {
while (end < str.length() && str[end] != ' ') ++end;
v.push_back(str.substr(s, end - s));
s = ++end;
}
}
/*
You are a product manager and currently leading a team to develop a new
product. Unfortunately, the latest version of your product fails the
quality check. Since each version is developed based on the previous
version, all the versions after a bad version are also bad.
Suppose you have n versions [1, 2, ..., n] and you want to find out the
first bad one, which causes all the following ones to be bad.
You are given an API bool isBadVersion(version) which will return whether
version is bad. Implement a function to find the first bad version. You
should minimize the number of calls to the API.
*/
// Forward declaration of isBadVersion API.
bool isBadVersion(int version) {
return false;
}
int FirstBadVersion::firstBadVersion(int n) {
return firstBadVersion(1, n);
}
int FirstBadVersion::firstBadVersion(int lo, int hi) {
if (lo > hi) return INT_MAX;
if (lo == hi) {
if (isBadVersion(lo)) return lo;
else return INT_MAX;
}
int mid = (hi - lo) / 2 + lo;
if (isBadVersion(mid)) {
if (!isBadVersion(mid - 1))
return mid;
return firstBadVersion(lo, mid - 1);
} else {
if (isBadVersion(mid + 1))
return mid + 1;
return firstBadVersion(mid + 1, hi);
}
}
/*
Given an array of integers and an integer k, find out whether there are
two distinct indices i and j in the array such that nums[i] = nums[j] and
the difference between i and j is at most k.
*/
bool ContainsNearByDuplicate::containsNearbyDuplicate(vector<int>& nums, int k) {
unordered_map<int, int> m;
for (int i = 0; i < nums.size(); ++i) {
unordered_map<int, int>::const_iterator iter = m.find(nums[i]);
if (iter != m.end()) {
if (i - iter->second <= k)
return true;
else
m.erase(iter);
}
m.insert(make_pair(nums[i], i));
}
return false;
}
int AddDigits::addDigits(int num) {
#if 0
while (num >= 10) {
num = num % 10 + addDigits(num / 10);
}
return num;
#endif
return (num - 1) % 9 + 1;
}
bool NimGame::canWinNim(int n) {
return n % 4 != 0;
}
/*
* O(n) time with O(1) space
* cnt = n / 2 + x, and left = n - cnt = n / 2 -x
* so:
* cnt - left = 2x
*/
int MajorityElement::majorityElement(vector<int>& nums) {
int cur = nums[0];
int cnt = 1;
for (int i = 1; i < nums.size(); ++i) {
if (cur == nums[i]) ++cnt;
else --cnt;
if (cnt == 0) {
cur = nums[i];
cnt = 1;
}
}
return cur;
}
int MajorityElement::MajorityElementWithExtraSapce(vector<int>& nums) {
unordered_map<int, int> m;
for (int i = 0; i < nums.size(); ++i) {
unordered_map<int, int>::iterator iter = m.find(nums[i]);
if (iter != m.end()) {
++iter->second;
if (iter->second > nums.size() / 2)
return iter->first;
} else {
m.insert(make_pair(nums[i], 1));
}
}
return m.find(nums[0])->first;
}
bool Anagram::isAnagram(string s, string t) {
if (s.length() != t.length()) return false;
int cntS[MAXCHAR] = {0};
int cntT[MAXCHAR] = {0};
for (int i = 0; i < s.length(); ++i) {
++cntT[t[i]];
++cntS[s[i]];
}
for (int i = 0; i < MAXCHAR; ++i) {
if (cntT[i] != cntS[i]) {
return false;
}
}
return true;
}
vector<int> PlusOne::plusOne(vector<int>& digits) {
for (int i = static_cast<int>(digits.size() - 1); i >= 0; --i) {
if (digits[i] < 9) {
++digits[i];
return digits;
}
digits[i] = 0;
}
vector<int> ret = vector<int>(digits.size() + 1, 0);
ret[0] = 1;
return ret;
}
ListNode* ListNodeList::deleteDuplicates(ListNode* head) {
ListNode* cur = head;
while (cur != nullptr) {
ListNode* next = cur->next;
while (next != nullptr && next->val == cur->val) {
ListNode* d = next;
next = next->next;
delete d;
}
cur->next = next;
cur = cur->next;
}
return head;
}
ListNode *ListNodeList::reverseBetween(ListNode *head, int s, int e)
{
if (s == e) return head;
ListNode* prev = nullptr;
ListNode* cur = head;
for (int i = 1; i < s; ++i) {
prev = cur;
cur = cur->next;
}
ListNode* p = nullptr;
ListNode* c = cur;
ListNode* tail = c;
ListNode* n = nullptr;
for (int i = s; i <= e; ++i) {
n = c->next;
c->next = p;
p = c;
c = n;
}
if (prev != nullptr) {
prev->next = p;
cur->next = c;
return head;
} else {
if (tail != nullptr) tail->next = c;
return p;
}
}
ListNode* ListNodeList::reverseList(ListNode* head) {
ListNode* tail = nullptr;
return reverseRecursive(head, tail);
}
ListNode* ListNodeList::reverseRecursive(ListNode* head, ListNode*& tail) {
if (head == nullptr) {
tail = nullptr;
return head;
}
if (head->next == nullptr) {
tail = head;
return head;
}
ListNode* h = reverseRecursive(head->next, tail);
if (tail != nullptr) {
tail->next = head;
tail = tail->next;
head->next = nullptr;
}
return h;
}
int ClimeStairs::climbStairs(int n) {
if (n == 0) return 0;
if (n == 1) return 1;
if (n == 2) return 2;
int f_1 = 2;
int f_2 = 1;
int cnt = 0;
for (int i = 3; i <= n; ++i) {
cnt = f_1 + f_2;
f_2 = f_1;
f_1 = cnt;
}
return cnt;
}
long long SumOfFactorialsTo::sumOfFactorialsTo(int n)
{
if (n < 0) return n;
if (n == 0) return 1;
long long result = 0;
long long cur = 1;
for (int i = 1; i <= n; ++i)
{
cur *= i;
result += cur;
}
return result;
}
bool HappyNumber::isHappyNumber(int n)
{
int slow = n;
int fast = n;
while (true)
{
slow = sumOfSquareOfDigits(slow);
fast = sumOfSquareOfDigits(sumOfSquareOfDigits(fast));
if (fast == 1) return true;
if (slow == fast) return false;
}
}
int HappyNumber::sumOfSquareOfDigits(int n)
{
int ret = 0;
while (n != 0)
{
int d = n % 10;
ret += d * d;
n /= 10;
}
return ret;
}
bool SymmetricTree::isSymmetric(TreeNode* root) {
#if 0
if (root == nullptr) return true;
return isSymmetric(root->left, root->right);
#else
return isSymmetricIterative(root);
#endif
}
bool SymmetricTree::isSymmetric(TreeNode* n1, TreeNode* n2) {
if (n1 == nullptr && n2 == nullptr) return true;
if (n1 == nullptr || n2 == nullptr) return false;
if (n1->val != n2->val) return false;
return isSymmetric(n1->left, n2->right) && isSymmetric(n1->right, n2->left);
}
bool SymmetricTree::isSymmetricIterative(TreeNode* root) {
if (root == nullptr) return true;
if (root->left == nullptr && root->right == nullptr) return true;
if (root->left == nullptr || root->right == nullptr) return false;
vector<TreeNode*> v;
v.push_back(root->left);
v.push_back(root->right);
while (!v.empty()) {
TreeNode* tn1 = v.back();
v.pop_back();
TreeNode* tn2 = v.back();
v.pop_back();
if (tn1 == nullptr && tn2 == nullptr) continue;
if (tn1 == nullptr || tn2 == nullptr) return false;
if (tn1->val != tn2->val) return false;
v.push_back(tn1->left);
v.push_back(tn2->right);
v.push_back(tn1->right);
v.push_back(tn2->left);
}
return true;
}
vector<vector<int>> generatePascalNumber(int numRows) {
vector<vector<int>> v;
for (int i = 0; i < numRows; ++i) {
vector<int> v1 = vector<int>(i + 1);
for (int j = 0; j < v1.capacity(); ++j) {
if (j == 0 || j == v1.capacity() - 1)
v1[j] = 1;
else {
v1[j] = v[i - 1][j] + v[i - 1][j - 1];
}
}
v.push_back(v1);
}
return v;
}
ListNode *MergeToSorted(ListNode * l1, ListNode * l2)
{
if (l1 == nullptr && l2 == nullptr) return nullptr;
// O(N) space, O(NlogN) time
vector<int> v = vector<int>();
ListNode* h = l1, *t = nullptr;
while(l1 != nullptr)
{
v.push_back(l1->val);
if (l1->next == nullptr) t = l1;
l1 = l1->next;
}
t->next = l2;
while (l2 != nullptr)
{
v.push_back(l2->val);
l2 = l2->next;
}
std::sort(v.begin(), v.end());
l1 = h;
for (vector<int>::const_iterator iter = v.begin();
iter != v.end(); ++iter)
{
l1->val = *iter;
l1 = l1->next;
}
return h;
}
<file_sep>//
// Created by raof01 on 9/23/15.
//
#ifndef ALGO_ROUTECALCULATOR_H
#define ALGO_ROUTECALCULATOR_H
#include <vector>
/*
* The coordination system is:
* origin -------> x
* |
* |
* v
* y
*/
class Point {
public:
Point(int x = 0, int y = 0) : mX(x), mY(y) {}
int GetX() const { return mX; }
int GetY() const { return mY; }
Point Left() const { return Point(mX - 1, mY); }
Point Right() const { return Point(mX + 1, mY); }
Point Above() const { return Point(mX, mY - 1); }
Point Below() const { return Point(mX, mY + 1); }
bool operator == (const Point& rhs) const {
if (this == &rhs) return true;
return mX == rhs.mX && mY == rhs.mY;
}
bool operator != (const Point& rhs) const {
return !this->operator==(rhs);
}
private:
int mX;
int mY;
};
class Grid {
public:
Grid(const Point& topLeft, const Point& bottomRight)
: mTopLeft(topLeft)
, mBottomRight(bottomRight)
{}
bool Contains(const Point &point) const
{
return mTopLeft.GetX() <= point.GetX() &&
mTopLeft.GetY() <= point.GetY() &&
mBottomRight.GetX() >= point.GetX() &&
mBottomRight.GetY() >= point.GetY();
}
const Point& GetTopLeft() const {
return mTopLeft;
}
const Point& GetBottomRight() const {
return mBottomRight;
}
private:
Point mTopLeft;
Point mBottomRight;
};
class RouteCalculator {
public:
RouteCalculator(int topLeftX, int topRightY, int bottomRightX, int bottomRightY)
: mGrid(Point(topLeftX, topRightY), Point(bottomRightX, bottomRightY))
{}
int Routes(const Point& start, const Point& end) const;
private:
int RoutesRecursive(const Point&, const Point&) const;
int RoutesRecursive(const Point&, const Point&, std::vector<std::vector<int>>&) const;
private:
Grid mGrid;
};
#endif //ALGO_ROUTECALCULATOR_H
<file_sep>//
// MoveZerosTest.cpp
// algo
//
// Created by <NAME> on 10/11/15.
// Copyright © 2015 raof01. All rights reserved.
//
#include "gtest/gtest.h"
#include "MoveZeros.h"
#include "ArraysMatch.hpp"
using namespace std;
TEST(TestMoveZeros, SampleInput) {
vector<int> v = {0, 1, 0, 3, 12};
MoveZeroes(v);
vector<int> res = {1, 3, 12, 0, 0};
ASSERT_TRUE(VectorsMatch(res, v));
}
TEST(TestMoveZeros, SampleInput1) {
vector<int> v = {1, 0, 2, 0, 3, 0};
MoveZeroes(v);
vector<int> res = {1, 2, 3, 0, 0, 0};
ASSERT_TRUE(VectorsMatch(res, v));
}
<file_sep>//
// ElementarySortsTest.cpp
// algo
//
// Created by raof01 on 8/1/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#include "gtest/gtest.h"
#include "ArraysMatch.hpp"
#include "SelectionSort.h"
static int result[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
// SelectionSort
TEST(TestSelectionSort, Positive)
{
int a[] = {8, 7, 9, 0, 1, 3, 5, 4, 6, 2};
SelectionSorter<int>::Sort(a);
ASSERT_TRUE(ArraysMatch(result, a));
}
TEST(TestSelectionSort, OneElem)
{
int a[] = {8};
SelectionSorter<int>::Sort(a);
ASSERT_TRUE(ArraysMatch(a, a));
}
TEST(TestSelectionSort, TwoElems)
{
int a[] = {8, 0};
int result[] = {0, 8};
SelectionSorter<int>::Sort(a);
ASSERT_TRUE(ArraysMatch(result, a));
}<file_sep>//
// HelpersTest.cpp
// algo
//
// Created by raof01 on 8/13/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#include "gtest/gtest.h"
#include "Helpers.h"
#include "ArraysMatch.hpp"
TEST(TestLeft, LeftOfZero)
{
ASSERT_EQ(1, Left(0));
}
TEST(TestLeft, LeftOfTen)
{
ASSERT_EQ(21, Left(10));
}
TEST(TestRight, RightOfZero)
{
ASSERT_EQ(2, Right(0));
}
TEST(TestRight, RightOfTen)
{
ASSERT_EQ(22, Right(10));
}
TEST(TestParent, ParentOfZero)
{
ASSERT_EQ(0, Parent(0));
}
TEST(TestParent, ParentOfOne)
{
ASSERT_EQ(0, Parent(1));
}
TEST(TestParent, ParentOfTwo)
{
ASSERT_EQ(0, Parent(2));
}
TEST(TestParent, ParentOfThree)
{
ASSERT_EQ(1, Parent(3));
}
TEST(TestParent, ParentOfFour)
{
ASSERT_EQ(1, Parent(4));
}
TEST(TestParent, ParentOfFive)
{
ASSERT_EQ(2, Parent(5));
}
TEST(TestParent, ParentOfSix)
{
ASSERT_EQ(2, Parent(6));
}
TEST(TestParent, ParentOfFiveHundred)
{
ASSERT_EQ(249, Parent(500));
}
TEST(TestSink, SinkOneElemArray)
{
int a[] = {4};
int r[] = {4};
Sink(a, 0, 1);
ASSERT_TRUE(ArraysMatch(a, r));
}
TEST(TestSink, SinkTwoElemsArray)
{
int a[] = {4, 7};
int r[] = {7, 4};
Sink(a, 0, 2);
ASSERT_TRUE(ArraysMatch(a, r));
}
TEST(TestSink, SinkThreeElemsArray)
{
int a[] = {4, 7, 8};
int r[] = {8, 7, 4};
Sink(a, 0, 3);
ASSERT_TRUE(ArraysMatch(a, r));
}
TEST(TestSink, SinkThreeElemsArrayWithSameValue)
{
int a[] = {8, 8, 8};
int r[] = {8, 8, 8};
Sink(a, 0, 3);
ASSERT_TRUE(ArraysMatch(a, r));
}
TEST(TestSwim, AtPositionZero)
{
int a[] = {3, 7, 5, 0, 6, 8, 7, 9, 8, 2, 1, 6, 10};
int r[] = {3, 7, 5, 0, 6, 8, 7, 9, 8, 2, 1, 6, 10};
Swim(a, 0);
ASSERT_TRUE(ArraysMatch(a, r));
}
TEST(TestSwim, AtPositionOne)
{
int a[] = {3, 7, 5, 0, 6, 8, 7, 9, 8, 2, 1, 6, 10};
int r[] = {7, 3, 5, 0, 6, 8, 7, 9, 8, 2, 1, 6, 10};
Swim(a, 1);
ASSERT_TRUE(ArraysMatch(a, r));
}
TEST(TestSwim, AtPositionTwo)
{
int a[] = {3, 7, 5, 0, 6, 8, 7, 9, 8, 2, 1, 6, 10};
int r[] = {5, 7, 3, 0, 6, 8, 7, 9, 8, 2, 1, 6, 10};
Swim(a, 2);
ASSERT_TRUE(ArraysMatch(a, r));
}
TEST(TestSwim, AtPositionThree)
{
int a[] = {3, 7, 5, 0, 6, 8, 7, 9, 8, 2, 1, 6, 10};
int r[] = {3, 7, 5, 0, 6, 8, 7, 9, 8, 2, 1, 6, 10};
Swim(a, 3);
ASSERT_TRUE(ArraysMatch(a, r));
}
TEST(TestSwim, AtPositionFive)
{
int a[] = {3, 7, 5, 0, 6, 8, 7, 9, 8, 2, 1, 6, 10};
int r[] = {8, 7, 3, 0, 6, 5, 7, 9, 8, 2, 1, 6, 10};
Swim(a, 5);
ASSERT_TRUE(ArraysMatch(a, r));
}
TEST(TestSwim, AtPositionSix)
{
int a[] = {3, 7, 5, 0, 6, 8, 7, 9, 8, 2, 1, 6, 10};
int r[] = {7, 7, 3, 0, 6, 8, 5, 9, 8, 2, 1, 6, 10};
Swim(a, 6);
ASSERT_TRUE(ArraysMatch(a, r));
}
TEST(TestSwim, AtPositionSeven)
{
int a[] = {3, 7, 5, 0, 6, 8, 7, 9, 8, 2, 1, 6, 10};
int r[] = {9, 3, 5, 7, 6, 8, 7, 0, 8, 2, 1, 6, 10};
Swim(a, 7);
ASSERT_TRUE(ArraysMatch(a, r));
}
TEST(TestSwim, AtPositionTwevel)
{
int a[] = {3, 7, 5, 0, 6, 8, 7, 9, 8, 2, 1, 6, 10};
int r[] = {10, 7, 3, 0, 6, 5, 7, 9, 8, 2, 1, 6, 8};
Swim(a, 12);
ASSERT_TRUE(ArraysMatch(a, r));
}
<file_sep>//
// LinkedListWithExtra.h
// algo
//
// Created by <NAME> on 10/9/15.
// Copyright © 2015 raof01. All rights reserved.
//
#ifndef LinkedListWithExtra_h
#define LinkedListWithExtra_h
struct NodeWithExtra {
NodeWithExtra(int v) : data(v), next(NULL), extra(NULL) {}
int data;
NodeWithExtra* next;
NodeWithExtra* extra;
};
NodeWithExtra* Insert(NodeWithExtra* h, int v);
void Destroy(NodeWithExtra*& h);
NodeWithExtra* Copy(const NodeWithExtra* h);
#endif /* LinkedListWithExtra_h */
<file_sep>//
// FilterTest.cpp
// algo
//
// Created by raof01 on 5/17/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#include "gtest/gtest.h"
#include "ArraysMatch.hpp"
#include "Filter.hpp"
bool IsDigit(const char& c)
{
return isdigit(c) != 0;
}
TEST(TestFilter, Positive)
{
char s[] = "--+157al;skdj698-0k91nv";
char r[sizeof(s)/sizeof(char)] = {};
char expected[] = "157698091";
int end = -1;
Filter(s, r, std::ptr_fun(IsDigit), end);
ASSERT_EQ(strlen(expected), end);
ASSERT_TRUE(ArrayAndPointerMatch(expected, static_cast<char*>(r)));
}
//TEST(TestFilter, NoElemMakesPredicateTrue)
//{
// char s[] = "--+al;skdj-knv";
// char r[sizeof(s)/sizeof(char)] = {};
// int end = -1;
// Filter(s, r, std::ptr_fun(IsDigit), end);
// ASSERT_EQ(0, end);
//}
TEST(TestFilter, AllElemsMakePredicateTrue)
{
char s[] = "135897492873947129347194";
char r[sizeof(s)/sizeof(char)] = {};
int end = -1;
Filter(s, r, std::ptr_fun(IsDigit), end);
ASSERT_EQ(strlen(s), end);
ASSERT_TRUE(ArrayAndPointerMatch(s, static_cast<char*>(r)));
}
TEST(TestFilterInPlace, Positive)
{
char s[] = "--+157al;skdj698-0k91nv";
char r[sizeof(s)/sizeof(char)] = {};
char expected[] = "157698091";
int end = -1;
int start = -1;
FilterInPlace(s, std::ptr_fun(IsDigit), start, end);
for (int i = start, j = 0; i < end; ++i, ++j)
r[j] = s[i];
ASSERT_TRUE(ArrayAndPointerMatch(expected, static_cast<char*>(r)));
}
//TEST(TestFilterInPlace, NoElemMakesPredicateTrue)
//{
// char s[] = "--+al;skdj-knv";
// char r[] = "--+al;skdj-knv";
// int end = -1;
// int start = -1;
// FilterInPlace(s, std::ptr_fun(IsDigit), start, end);
// ASSERT_EQ(start, end);
// // minus 1 because of trailing non digit '\0' of string
// ASSERT_EQ(start - 1, strlen(s));
// ASSERT_TRUE(ArrayAndPointerMatch(r, s));
//}
TEST(TestFilterInPlace, AllElemsMakePredicateTrue)
{
char s[] = "135897492873947129347194";
char r[] = "135897492873947129347194";
int end = -1;
int start = -1;
FilterInPlace(s, std::ptr_fun(IsDigit), start, end);
ASSERT_EQ(0, start);
ASSERT_EQ(strlen(s), end);
ASSERT_TRUE(ArrayAndPointerMatch(s, static_cast<char*>(r)));
}
<file_sep>//
// ShortestPathLengthTest.cpp
// algo
//
// Created by raof01 on 8/13/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#include "gtest/gtest.h"
#include "ShortestPathInMatrix.h"
#include "ArraysMatch.hpp"
TEST(TestSearch, Positive)
{
char matrix[MaxHeight][MaxWidth] =
{
{ 'X', 'X', 'X', ' ', ' ' },
{ ' ', ' ', ' ', 'X', ' ' },
{ 'X', 'X', ' ', 'X', ' ' },
{ ' ', ' ', 'X', ' ', ' ' },
{ ' ', 'X', ' ', ' ', 'X' },
};
bool visited1[MaxHeight][MaxWidth] = {};
int minSteps1 = InvalidMinSteps;
Search(matrix, visited1, Point(0, 2), Point(2, 3), 0, minSteps1);
ASSERT_EQ(2, minSteps1);
std::vector<Point> p;
minSteps1 = InvalidMinSteps;
bool visitedn[MaxHeight][MaxWidth] = {};
ASSERT_TRUE(Search(matrix, visitedn, Point(0, 2), Point(2, 3), 0, minSteps1, p));
bool visited2[MaxHeight][MaxWidth] = {};
int minSteps2 = InvalidMinSteps;
Search(matrix, visited2, Point(0, 0), Point(4, 4), 0, minSteps2);
ASSERT_EQ(InvalidMinSteps, minSteps2);
bool visited3[MaxHeight][MaxWidth] = {};
int minSteps3 = InvalidMinSteps;
Search(matrix, visited3, Point(1, 2), Point(3, 2), 0, minSteps3);
ASSERT_EQ(1, minSteps3);
bool visited4[MaxHeight][MaxWidth] = {};
int minSteps4 = InvalidMinSteps;
Search(matrix, visited4, Point(1, 4), Point(2, 0), 0, minSteps4);
ASSERT_EQ(8, minSteps4);
bool visited5[MaxHeight][MaxWidth] = {};
int minSteps5 = InvalidMinSteps;
Search(matrix, visited5, Point(2, 0), Point(2, 3), 0, minSteps5);
ASSERT_EQ(2, minSteps5);
bool visited6[MaxHeight][MaxWidth] = {};
int minSteps6 = InvalidMinSteps;
Search(matrix, visited6, Point(2, 3), Point(2, 0), 0, minSteps6);
ASSERT_EQ(2, minSteps6);
bool visited7[MaxHeight][MaxWidth] = {};
int minSteps7 = InvalidMinSteps;
Search(matrix, visited7, Point(0, 2), Point(2, 3), 0, minSteps7);
ASSERT_EQ(2, minSteps7);
bool visited8[MaxHeight][MaxWidth] = {};
int minSteps8 = InvalidMinSteps;
Search(matrix, visited8, Point(0, 2), Point(4, 4), 0, minSteps8);
ASSERT_EQ(InvalidMinSteps, minSteps8);
bool visited9[MaxHeight][MaxWidth] = {};
int minSteps9 = InvalidMinSteps;
Search(matrix, visited9, Point(0, 0), Point(1, 0), 0, minSteps9);
ASSERT_EQ(0, minSteps9);
}
TEST(TestSearch, PositiveFullMatrix)
{
char matrix[MaxHeight][MaxWidth] =
{
{ 'X', 'X', 'X', 'X', 'X' },
{ 'X', 'X', 'X', 'X', 'X' },
{ 'X', 'X', 'X', 'X', 'X' },
{ 'X', 'X', 'X', 'X', 'X' },
{ 'X', 'X', 'X', 'X', 'X' },
};
bool visited[MaxHeight][MaxWidth] = {};
int minSteps = InvalidMinSteps;
Search(matrix, visited, Point(0, 0), Point(4, 4), 0, minSteps);
ASSERT_EQ(InvalidMinSteps, minSteps);
minSteps = InvalidMinSteps;
Search(matrix, visited, Point(0, 0), Point(1, 0), 0, minSteps);
ASSERT_EQ(0, minSteps);
}
<file_sep>//
// FactorialTest.cpp
// algo
//
// Created by raof01 on 5/17/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#include "gtest/gtest.h"
#include "Factorial.hpp"
// Factorial
TEST(TestFactorial, Positive)
{
int result = 720;
int a = Factorial<6>::result;
ASSERT_EQ(a, result);
}
TEST(TestFactorial, LowBound0)
{
int a = Factorial<0>::result;
ASSERT_EQ(a, 1);
}
TEST(TestFactorial, LowBound1)
{
int a = Factorial<1>::result;
ASSERT_EQ(a, 1);
}
TEST(TestFactorial, Negative)
{
int a = Factorial<-10>::result;
ASSERT_EQ(a, -1);
}
<file_sep>//
// ConnectionSlowImplTest.cpp
// algo
//
// Created by raof01 on 7/25/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#include "gtest/gtest.h"
#include "ConnectionSlowImpl.h"
TEST(ConnectionSlowImpleTest, Connected_TwoConnectedItemsReturnTrue)
{
Connection* sut = new ConnectionSlowImpl(10);
sut->ConnectTo(9, 8);
ASSERT_TRUE(sut->Connected(9, 8));
delete sut;
}
TEST(ConnectionSlowImpleTest, Connected)
{
Connection* sut = new ConnectionSlowImpl(10);
sut->ConnectTo(4, 3);
sut->ConnectTo(3, 8);
ASSERT_TRUE(sut->Connected(4, 3));
ASSERT_TRUE(sut->Connected(4, 8));
sut->ConnectTo(6, 5);
ASSERT_FALSE(sut->Connected(4, 5));
ASSERT_FALSE(sut->Connected(1, 2));
sut->ConnectTo(9, 4);
sut->ConnectTo(2, 1);
ASSERT_FALSE(sut->Connected(4, 5));
ASSERT_TRUE(sut->Connected(9, 8));
ASSERT_TRUE(sut->Connected(1, 2));
sut->ConnectTo(8, 9);
sut->ConnectTo(5, 0);
sut->ConnectTo(7, 2);
sut->ConnectTo(6, 1);
ASSERT_TRUE(sut->Connected(9, 8));
ASSERT_TRUE(sut->Connected(7, 0));
ASSERT_FALSE(sut->Connected(2, 8));
delete sut;
}
<file_sep>//
// StringFind.cpp
// algo
//
// Created by raof01 on 5/10/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#include <string.h>
#include <algorithm>
#include "StringOperations.hpp"
#include <stdlib.h>
#include <string>
#include <vector>
using namespace std;
size_t BFIndex(const char* str, const char* pattern, size_t start, size_t end)
{
if (strlen(str) < end) return -1;
size_t pStr = start;
size_t pPattern = 0;
size_t patternLen = strlen(pattern);
while (pPattern < patternLen && pStr < end)
{
if (str[pStr] == pattern[pPattern])
{
++pStr;
++pPattern;
}
else
{
pStr = pStr - pPattern + 1; // backtrack to next char in str
pPattern = 0;
}
}
return (pPattern == patternLen) ? pStr - patternLen : NOT_FOUND;
}
static void KMPNext(const char* pattern, vector<int>& nextVals)
{
int cur = 0, prev = -1, len = static_cast<int>(strlen(pattern));
while (cur < len)
{
if (prev == -1 || pattern[cur] == pattern[prev])
{
++cur; ++prev;
if (cur < len)
nextVals[cur] = prev;
}
else
prev = nextVals[prev];
}
}
size_t KMPIndex(const char* str, const char* pattern, size_t start, size_t end)
{
if (str == nullptr || pattern == nullptr || strlen(str) < strlen(pattern) || end < start)
return NOT_FOUND;
vector<int> btTable = vector<int>(strlen(pattern), - 1);
KMPNext(pattern, btTable);
int pStr = static_cast<int>(start), pPattern = 0;
int patternLen = static_cast<int>(strlen(pattern));
// cast needed because pPattern can be -1, which is 0xFFFFFFFFUL
while (pStr < end && pPattern < patternLen)
{
if (pPattern == -1 || str[pStr] == pattern[pPattern])
{
++pStr; ++pPattern;
}
else {
pPattern = btTable[pPattern];
}
}
if (pPattern == patternLen) return pStr - patternLen;
return NOT_FOUND;
}
void Reverse(char* str, size_t start, size_t end)
{
if (str == nullptr || start == end || end > start + strlen(str)) return;
for (--end; start < end; ++start, --end)
std::swap(str[start], str[end]);
}
void ReverseRecursive(char* start, char* end)
{
if (start == nullptr || start >= end) return;
std::swap(*start, *end);
ReverseRecursive(++start, --end);
}
bool IsPalindromeIgnoreCase(const char *s) {
if (s == nullptr || *s == 0) return true;
const char* e = s + strlen(s) - 1;
while (e > s) {
if (!isalnum(*s)) ++s;
else if (!isalnum(*e)) --e;
else if (*s != *e && (*s - ('a' - 'A') != *e) && (*e - ('a' - 'A') != *s)) return false;
else {++s; --e;}
}
return true;
}
const unsigned int INTEGER_MIN = 0x80000000;
const unsigned int INTEGER_MAX = 0x7FFFFFFF;
// Use macros to minimize number of function calls
#define ISDIGIT(n) ((n) >= '0' && (n) <= '9')
#define ISSIGN(n) ((n) == '+' || (n) == '-')
#define ISSPACE(n) ((n) == ' ')
int Atoi(const char *p, const char* pend) {
int r = 0;
if (p == nullptr) return r;
int sign = 1;
// Ignore leading spaces
while (p < pend && ISSPACE(*p)) ++p;
// Non-digit and non-sign result 0
if (!ISSIGN(*p) && !ISDIGIT(*p)) return 0;
if (*p == '-') sign = -1;
else r = ISDIGIT(*p) ? *p - '0' : 0;
++p;
// Handle the overflow and underflow
int v = sign > 0 ? INTEGER_MAX : INTEGER_MIN;
while (p < pend && ISDIGIT(*p))
{
int tmp = r;
r = r * 10 + ((*p) - '0'); // may overflow (no sign now)
if ((INTEGER_MAX / 10 <= tmp) // tmp >= 214748364(.7), caution! further check
&& ((tmp & 0x80000000) != (r & 0x80000000) // r has different sign with tmp, overflow, or
|| (tmp != 0 && r / tmp != 10))) // this means something wrong with r, overflow
return v;
++p;
}
return r * sign;
}
int Atoi(const char* p)
{
return Atoi(p, p + strlen(p));
}
inline int CompareChar(const char c1, const char c2)
{
if (c1 > c2) return 1;
else if (c1 == c2) return 0;
else return -1;
}
int CompareVersion(const char* version1, const char* version2)
{
const char sep = '.';
const char* p1 = version1;
const char* p2 = version2;
int ret = 0;
int i1 = 0;
int i2 = 0;
while (p1 != nullptr && p2 != nullptr)
{
const char* p1p = strchr(p1, sep);
const char* p1pp = p1p;
if (p1p == nullptr) p1p = p1 + strlen(p1);
const char* p2p = strchr(p2, sep);
const char* p2pp = p2p;
if (p2p == nullptr) p2p = p2 + strlen(p2);
i1 = Atoi(p1, p1p);
i2 = Atoi(p2, p2p);
if (i1 != i2) return abs(i1 - i2) / (i1 - i2);
p1 = p1pp == nullptr ? nullptr : ++p1pp;
p2 = p2pp == nullptr ? nullptr : ++p2pp;
}
if (p1 != nullptr && Atoi(p1) > 0) ret = 1;
if (p2 != nullptr && Atoi(p2) > 0) ret = -1;
return ret;
}
int CompareVersionNoAtoi(const char* version1, const char* version2)
{
const char sep = '.';
const char* p1 = version1;
const char* p2 = version2;
const char* p1end = version1 + strlen(version1);
const char* p2end = version2 + strlen(version2);
int ret = 0;
while (p1 != nullptr && p2 != nullptr)
{
const char* p1p = strchr(p1, sep);
const char* p1pp = p1p;
if (p1p == nullptr) p1p = p1 + strlen(p1);
const char* p2p = strchr(p2, sep);
const char* p2pp = p2p;
if (p2p == nullptr) p2p = p2 + strlen(p2);
while (*p1 == '0') ++p1;
while (*p2 == '0') ++p2;
if (p1p - p1 > p2p - p2 && *p1 > '0') return 1;
else if (p1p - p1 < p2p - p2 && *p2 > '0') return -1;
else
{
while (p1 < p1p && *p1 == *p2)
{
++p1; ++p2;
}
if (p1 < p1p) return abs(*p1 - *p2) / (*p1 - *p2);
}
p1 = p1pp == nullptr ? nullptr : ++p1pp;
p2 = p2pp == nullptr ? nullptr : ++p2pp;
}
while (p1 != nullptr && p1 < p1end && *p1 == '0') ++p1;
if (p1 != nullptr && p1 != p1end)
ret = 1;
while (p2 != nullptr && p2 < p2end && *p2 == '0') ++p2;
if (p2 != nullptr && p2 != p2end)
ret = -1;
return ret;
}
#define ToIndex(char) ((char) - 'A')
std::string minWindow(const std::string& s, std::string& t)
{
#if 0 // Can not pass the Negative case
if (s.length() == 0 || t.length() == 0 || t.length() > s.length()) return string();
std::sort(t.begin(), t.end());
string tmp = t.substr(0 , 1);
for (int i = 0; i < t.length(); ++i)
if (tmp[tmp.length() - 1] != t[i])
tmp += t[i];
string::size_type p = 0;
string::size_type len = s.length();
string::size_type end = 0;
string::size_type start = 0;
string::size_type min = string::npos;
while (start < len && p != string::npos)
{
for (string::size_type i = 0; i < tmp.length(); ++i)
{
p = s.find(tmp[i], start);
if (p == string::npos) break;
if (p < start) start = p;
if (p > end || end == len) end = p + 1;
}
if (p != string::npos)
{
if (min == string::npos || min > end - start) min = end - start + 1;
if (end < len) ++end;
++start;
}
}
--start;
return min == string::npos ? string() : s.substr(start, min);
#else
/* Copied version
string str = "";
int lenS = (int)s.size();
int lenT = (int)t.size();
if (lenT == 0) return str;
int minLen = lenS + 1;
int num[256], count[256];
memset(num, 0, sizeof(num));
memset(count, 0, sizeof(count));
for (int index = 0; index < (int)t.size(); index++)
num[(int)t[index]]++;
int first = 0, second = 0;
int chaCount = 0;
while (second < lenS) {
int secCha = (int)s[second];
if (++count[secCha] <= num[secCha]) {
chaCount++;
}
if (chaCount == lenT) {
while (first <= second) {
int firCha = (int)s[first];
if (count[firCha] > num[firCha])
count[firCha]--, first++;
else break;
}
if (minLen > second - first + 1) {
minLen = second - first + 1;
str = s.substr(first, minLen);
}
}
second++;
}
return str;
*/
// My own version.
// Invariant: the characters in the window will have the same or less occurrences
// then in T, as below:
// for each char from left to right
// NUMT[S[left]] <= NUM[S[left]]
int savedLeft = 0;
int left = 0;
int minLen = static_cast<int>(s.length()) + 1;
// Assumption: only 'a' - 'z' and 'A' - 'Z'
int cntT[64] = {0};
int cntS[64] = {0};
int matched = 0;
// Populate occurrences of each char in T
for (int i = 0; i < t.length(); ++i)
++cntT[ToIndex(t[i])];
for (int right = 0; right < s.length(); ++right)
{
int index = ToIndex(s[right]);
++cntS[index];
if (cntS[index] <= cntT[index])
++matched;
if (matched == t.length())
{
// Now the window containing at least all characters in T
// So the left should be determined to exclude extra characters
for (; left < right; ++left)
{
index = ToIndex(s[left]);
if (cntS[index] > cntT[index])
--cntS[index]; // Exclude the char, so the occurrence should be reduced
else
break;
}
if (minLen > right - left + 1)
{
minLen = right - left + 1;
savedLeft = left;
}
}
}
return minLen == static_cast<int>(s.length()) + 1 ? string() : s.substr(savedLeft, minLen);
#endif
}
bool IsIsomorphic(std::string& s, std::string& t)
{
char map_s[128];
memset(map_s, -1, 128);
char map_t[128];
memset(map_t, -1, 128);
int len = static_cast<int>(s.length());
for (int i = 0; i < len; ++i)
{
if (map_s[s[i]] != map_t[t[i]]) return false;
map_s[s[i]] = i;
map_t[t[i]] = i;
}
return true;
}
<file_sep>//
// LCSTest.cpp
// algo
//
// Created by raof01 on 5/18/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#include "gtest/gtest.h"
#include "ArraysMatch.hpp"
#include "LCS.h"
#include "Visitor.hpp"
class CharVisitor : public Visitor<char, false>
{
public:
CharVisitor(size_t n)
: data(nullptr)
, index(0)
, maxCnt(n)
{
if (static_cast<int>(maxCnt) <= 0)
maxCnt = 1024;
data = new char [maxCnt];
memset(data, 0x0, maxCnt);
}
void Visit(char c) override
{
if (index >= maxCnt)
return;
data[index++] = c;
}
~CharVisitor() override
{
if (data != nullptr)
{
delete [] data;
}
}
const char* GetData() const {return data;}
private:
char* data;
size_t index;
size_t maxCnt;
};
TEST(TestLCSLength, PositiveOfCharString)
{
const char x[] = "ABCBDAB";
const char y[] = "BDCABA";
const char r[] = "BCBA";
int len[9][8] = {0};
Direction d[9][8] = {UNKNOWN};
LCSLength(x, y, d, len);
CharVisitor v = CharVisitor(8);
LCSVisit<8, 7, char>(x, d, 7, 6, v);
ASSERT_EQ(4, len[7][6]);
ASSERT_TRUE(ArrayAndPointerMatch(r, v.GetData()));
}
TEST(TestLCSLength, PositiveOfIntArray)
{
const int x[] = {65, 66, 67, 66, 68, 65, 66};
const int y[] = {66, 68, 67, 65, 66, 65};
int len[8][7] = {0};
Direction d[8][7] = {UNKNOWN};
LCSLength(x, y, d, len);
ASSERT_EQ(4, len[7][6]);
}
TEST(TestLCSLen, PositiveOfCharString)
{
const char x[] = "ABCBDAB";
const char y[] = "BDCABA";
ASSERT_EQ(4, LCSLen(x, y, sizeof(x)/sizeof(char) - 2, sizeof(y)/sizeof(char) - 2));
}
TEST(TestLCSLen, PositiveOfIntArray)
{
const int x[] = {65, 66, 67, 66, 68, 65, 66};
const int y[] = {66, 68, 67, 65, 66, 65};
ASSERT_EQ(4, LCSLen(x, y, sizeof(x)/sizeof(int) - 1, sizeof(y)/sizeof(int) - 1));
}
TEST(TestLCSLenIter, PositiveOfIntArray)
{
const int x[] = {65, 66, 67, 66, 68, 65, 66};
const int y[] = {66, 68, 67, 65, 66, 65};
ASSERT_EQ(4, LCSLen(x, y));
}
TEST(TestLASLen, Positive)
{
const int x[] = {1, 7, 3, 5, 9, 4, 8};
ASSERT_EQ(4, LASLen(x));
}
<file_sep>//
// bubble_sort.h
// algo
//
// Created by raof01 on 5/5/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#ifndef algo_bubble_sort_h
#define algo_bubble_sort_h
template <typename Comparable>
class BubbleSorter
{
public:
template <size_t N>
static void Sort(Comparable (&a)[N])
{
SortImpl(a, N);
}
static void Sort(Comparable *a, size_t N)
{
SortImpl(a, N);
}
private:
static void SortImpl(Comparable* a, size_t N);
};
// Quardatic in average
template <typename Comparable>
void BubbleSorter<Comparable>::SortImpl(Comparable* a, size_t N)
{
for (int i = 0; i < N - 1; ++i)
for (int j = i + 1; j < N; ++j)
if (a[i] > a[j])
std::swap(a[i], a[j]);
}
#endif
<file_sep>//
// MaxPriorityQueueArrayImpl.h
// algo
//
// Created by raof01 on 8/11/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#ifndef algo_MaxPriorityQueueArrayImpl_h
#define algo_MaxPriorityQueueArrayImpl_h
#include "MaxPriorityQueue.h"
#include "Helpers.h"
template <typename Comparable, size_t N>
class MaxPriorityQueueArrayImpl : public MaxPriorityQueue<Comparable>
{
public:
MaxPriorityQueueArrayImpl();
virtual bool Insert(const Comparable& v);
virtual bool DeleteMax(Comparable& v);
virtual size_t Capacity();
virtual size_t Count();
virtual bool IsEmpty();
virtual bool IsFull();
virtual ~MaxPriorityQueueArrayImpl() {}
private:
Comparable mData[N];
size_t mItems;
};
template <typename Comparable, size_t N>
MaxPriorityQueueArrayImpl<Comparable, N>::MaxPriorityQueueArrayImpl()
: mItems(0)
{
}
template <typename Comparable, size_t N>
bool MaxPriorityQueueArrayImpl<Comparable, N>::Insert(const Comparable& v)
{
if (IsFull()) return false;
mData[mItems++] = v;
Swim(mData, mItems - 1);
return true;
}
template <typename Comparable, size_t N>
bool MaxPriorityQueueArrayImpl<Comparable, N>::DeleteMax(Comparable& v)
{
if (IsEmpty()) return false;
v = mData[0];
std::swap(mData[0], mData[mItems - 1]);
// Next Insert() will overwrite last item
--mItems;
if (!IsEmpty())
Sink(mData, 0, mItems);
return true;
}
template <typename Comparable, size_t N>
size_t MaxPriorityQueueArrayImpl<Comparable, N>::Capacity()
{
return N;
}
template <typename Comparable, size_t N>
size_t MaxPriorityQueueArrayImpl<Comparable, N>::Count()
{
return mItems;
}
template <typename Comparable, size_t N>
bool MaxPriorityQueueArrayImpl<Comparable, N>::IsEmpty()
{
return mItems == 0;
}
template <typename Comparable, size_t N>
bool MaxPriorityQueueArrayImpl<Comparable, N>::IsFull()
{
return mItems == N;
}
#endif
<file_sep>//
// AvlTree.h
// algo
//
// Created by raof01 on 7/30/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#ifndef algo_AvlTree_h
#define algo_AvlTree_h
#include "Visitor.hpp"
template <typename Comparable>
class AvlTree
{
public:
AvlTree() : mRoot(0) {}
~AvlTree();
bool Empty() const { return mRoot == 0; }
void Insert(const Comparable&);
int Height() const { return mRoot->mHeight; }
void InOrderTraversal(Visitor<Comparable, std::is_class<Comparable>::value>&) const;
void InOrderHeightTraversal(Visitor<Comparable, std::is_class<Comparable>::value>&) const;
private:
struct AvlNode
{
public:
AvlNode(Comparable elem, AvlNode* left = 0, AvlNode* right = 0, int height = 0)
: mElem(elem), mHeight(height), mLeft(left), mRight(right)
{
}
public:
Comparable mElem;
int mHeight;
AvlNode* mLeft;
AvlNode* mRight;
};
private:
int Height(const AvlNode*);
void Delete(AvlNode*&);
void RotateLeft(AvlNode*&);
void RotateRight(AvlNode*&);
void RotateLeftRight(AvlNode*&);
void RotateRightLeft(AvlNode*&);
void Insert(AvlNode*&, const Comparable&);
void InOrderTraversal(const AvlNode*, Visitor<Comparable, std::is_class<Comparable>::value>&) const;
void InOrderHeightTraversal(const AvlNode*, Visitor<Comparable, std::is_class<Comparable>::value>&) const;
private:
AvlNode* mRoot;
};
template <typename Comparable>
AvlTree<Comparable>::~AvlTree()
{
if (mRoot != 0)
{
Delete(mRoot->mLeft);
Delete(mRoot->mRight);
delete mRoot;
mRoot = 0;
}
}
template <typename Comparable>
void AvlTree<Comparable>::Delete(AvlNode*& n)
{
// Incorrect
if (n != 0)
{
delete n;
n = 0;
}
}
template <typename Comparable>
int AvlTree<Comparable>::Height(const AvlNode* r)
{
return r == 0 ? -1 : r->mHeight;
}
template <typename Comparable>
void AvlTree<Comparable>::Insert(const Comparable& elem)
{
Insert(mRoot, elem);
}
template <typename Comparable>
void AvlTree<Comparable>::Insert(AvlNode*& node, const Comparable& elem)
{
if (node == 0)
node = new AvlNode(elem);
else if (elem < node->mElem)
{
Insert(node->mLeft, elem);
if (Height(node->mLeft) - Height(node->mRight) == 2)
{
if (elem < node->mLeft->mElem)
RotateRight(node);
else
RotateLeftRight(node);
}
}
else if (elem > node->mElem)
{
Insert(node->mRight, elem);
if (Height(node->mRight) - Height(node->mLeft) == 2)
{
if (elem > node->mRight->mElem)
RotateLeft(node);
else
RotateRightLeft(node);
}
}
node->mHeight = std::max(Height(node->mLeft), Height(node->mRight)) + 1;
}
template <typename Comparable>
void AvlTree<Comparable>::RotateLeft(AvlNode*& r)
{
AvlNode* right = r->mRight;
r->mRight = right->mLeft;
right->mLeft = r;
r->mHeight = std::max(Height(r->mLeft), Height(r->mRight)) + 1;
right->mHeight = std::max(Height(right->mRight), r->mHeight) + 1;
r = right;
}
template <typename Comparable>
void AvlTree<Comparable>::RotateRight(AvlNode*& r)
{
AvlNode* left = r->mLeft;
r->mLeft = left->mRight;
left->mRight = r;
r->mHeight = std::max(Height(r->mLeft), Height(r->mRight)) + 1;
left->mHeight = std::max(Height(left->mLeft), r->mHeight) + 1;
r = left;
}
template <typename Comparable>
void AvlTree<Comparable>::RotateLeftRight(AvlNode*& r)
{
RotateLeft(r->mLeft);
RotateRight(r);
}
template <typename Comparable>
void AvlTree<Comparable>::RotateRightLeft(AvlNode*& r)
{
RotateRight(r->mRight);
RotateLeft(r);
}
template <typename Comparable>
void AvlTree<Comparable>::InOrderTraversal(Visitor<Comparable, std::is_class<Comparable>::value>& v) const
{
InOrderTraversal(mRoot, v);
}
template <typename Comparable>
void AvlTree<Comparable>::InOrderTraversal(const AvlNode* r, Visitor<Comparable, std::is_class<Comparable>::value>& v) const
{
if (r != 0)
{
InOrderTraversal(r->mLeft, v);
v.Visit(r->mElem);
InOrderTraversal(r->mRight, v);
}
}
template <typename Comparable>
void AvlTree<Comparable>::InOrderHeightTraversal(const AvlNode* r, Visitor<Comparable, std::is_class<Comparable>::value>& v) const
{
if (r != 0)
{
InOrderHeightTraversal(r->mLeft, v);
v.Visit(r->mHeight);
InOrderHeightTraversal(r->mRight, v);
}
}
template <typename Comparable>
void AvlTree<Comparable>::InOrderHeightTraversal(Visitor<Comparable, std::is_class<Comparable>::value>& v) const
{
InOrderHeightTraversal(mRoot, v);
}
#endif
<file_sep>//
// ConnectionTreeImpl.h
// algo
//
// Created by raof01 on 7/25/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#ifndef algo_ConnectionTreeImpl_h
#define algo_ConnectionTreeImpl_h
#include <vector>
#include "Connection.h"
class ConnectionTreeImpl : public Connection {
public:
ConnectionTreeImpl(int sz);
~ConnectionTreeImpl();
public:
virtual void ConnectTo(int, int);
virtual bool Connected(int, int);
private:
int Root(int);
bool OutOfRange(int);
private:
std::vector<int> mRoot;
};
#endif
<file_sep>//
// AccumVisitor.h
// algo
//
// Created by raof01 on 8/2/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#ifndef algo_AccumVisitor_h
#define algo_AccumVisitor_h
#include "Visitor.hpp"
template <typename T>
class AccumVisitor : public Visitor<T, std::is_class<T>::value>
{
public:
AccumVisitor(size_t n)
: data(NULL)
, index(0)
, maxCnt(n)
{
if (static_cast<int>(maxCnt) <= 0)
maxCnt = 1024;
data = new int [maxCnt];
}
~AccumVisitor() { if (data != NULL) delete [] data; }
virtual void Visit(T v)
{
if (index >= maxCnt)
return;
data[index++] = v;
}
const int* GetData() const { return data; }
private:
int* data;
size_t index;
size_t maxCnt;
};
#endif
<file_sep>//
// IsPalindrome.cpp
// algo
//
// Created by raof01 on 7/11/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#include <stdlib.h>
#include "IsPalindrome.h"
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(nullptr) {}
};
bool isPalindrome(ListNode* h)
{
// The O(n) time and space solution
// If the first / second half of list is reveresed to compare and then
// restore the original list, it will be O(n) time and O(1) space
if (h == nullptr || h->next == nullptr) return true;
ListNode* n = ReverseToNewList(h);
while (h != nullptr)
{
if (h->val != n->val)
return false;
h = h->next;
n = n->next;
}
return true;
}
ListNode* ReverseToNewList(ListNode* h)
{
ListNode* prev = nullptr;
ListNode* cur = nullptr;
while (h != nullptr)
{
cur = new ListNode(h->val);
cur->next = prev;
prev = cur;
h = h->next;
}
return cur;
}
size_t ListLength(ListNode* h)
{
size_t len = 0;
while (h != nullptr)
{
++len;
h = h->next;
}
return len;
}
ListNode* ListAppend(ListNode* h, int v)
{
ListNode* cur = new ListNode(v);
if (h == nullptr)
return cur;
ListNode* head = h;
while (head->next != nullptr) head = head->next;
head->next = cur;
return h;
}
int GetValue(ListNode* n)
{
return n->val;
}
void ListDestroy(ListNode* h)
{
while (h != nullptr)
{
ListNode* p = h;
h = h->next;
delete p;
}
}
ListNode* GetNext(ListNode* h)
{
return h->next;
}
<file_sep>//
// AvlTreeTest.cpp
// algo
//
// Created by raof01 on 7/30/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#include "gtest/gtest.h"
#include "ArraysMatch.hpp"
#include "AvlTree.h"
#include "AccumVisitor.h"
TEST(AvlTreeTest, PositiveSingleRotate)
{
AvlTree<int> t = AvlTree<int>();
int v[] = {4, 2, 5, 1, 3, 6, 7};
int result[] = {1, 2, 3, 4, 5, 6, 7};
int heightResult[] = {0, 1, 0, 2, 0, 1, 0};
for (int i = 0; i < sizeof(v) / sizeof(int); ++i)
t.Insert(v[i]);
AccumVisitor<int> visitor = AccumVisitor<int>(sizeof(v)/sizeof(int));
AccumVisitor<int> heightVisitor = AccumVisitor<int>(sizeof(v)/sizeof(int));
t.InOrderTraversal(visitor);
t.InOrderHeightTraversal(heightVisitor);
ASSERT_TRUE(ArrayAndPointerMatch(result, visitor.GetData()));
ASSERT_TRUE(ArrayAndPointerMatch(heightResult, heightVisitor.GetData()));
}
TEST(AvlTreeTest, PositiveDoubleRotate)
{
AvlTree<int> t = AvlTree<int>();
int v[] = {4, 2, 6, 1, 3, 5, 7, 16, 15};
int result[] = {1, 2, 3, 4, 5, 6, 7, 15, 16};
int heightResult[] = {0, 1, 0, 3, 0, 2, 0, 1, 0};
for (int i = 0; i < sizeof(v) / sizeof(int); ++i)
t.Insert(v[i]);
AccumVisitor<int> visitor = AccumVisitor<int>(sizeof(v)/sizeof(int));
AccumVisitor<int> heightVisitor = AccumVisitor<int>(sizeof(v)/sizeof(int));
t.InOrderTraversal(visitor);
t.InOrderHeightTraversal(heightVisitor);
ASSERT_TRUE(ArrayAndPointerMatch(result, visitor.GetData()));
ASSERT_TRUE(ArrayAndPointerMatch(heightResult, heightVisitor.GetData()));
}
TEST(AvlTreeTest, PositiveSingleRotateAtRoot)
{
AvlTree<int> t = AvlTree<int>();
int v[] = {4, 2, 6, 1, 3, 5, 15, 7, 16, 14, 13};
int result[] = {1, 2, 3, 4, 5, 6, 7, 13, 14, 15, 16};
int heightResult[] = {0, 1, 0, 2, 0, 1, 3, 0, 1, 2, 0};
for (int i = 0; i < sizeof(v) / sizeof(int); ++i)
t.Insert(v[i]);
AccumVisitor<int> visitor = AccumVisitor<int>(sizeof(v)/sizeof(int));
AccumVisitor<int> heightVisitor = AccumVisitor<int>(sizeof(v)/sizeof(int));
t.InOrderTraversal(visitor);
t.InOrderHeightTraversal(heightVisitor);
ASSERT_TRUE(ArrayAndPointerMatch(result, visitor.GetData()));
ASSERT_TRUE(ArrayAndPointerMatch(heightResult, heightVisitor.GetData()));
}
TEST(AvlTreeTest, PositiveSingleRotateWith12Elems)
{
AvlTree<int> t = AvlTree<int>();
int v[] = {4, 2, 6, 1, 3, 5, 15, 7, 16, 14, 13, 12};
int result[] = {1, 2, 3, 4, 5, 6, 7, 12, 13, 14, 15, 16};
int heightResult[] = {0, 1, 0, 2, 0, 1, 3, 0, 1, 0, 2, 0};
for (int i = 0; i < sizeof(v) / sizeof(int); ++i)
t.Insert(v[i]);
AccumVisitor<int> visitor = AccumVisitor<int>(sizeof(v)/sizeof(int));
AccumVisitor<int> heightVisitor = AccumVisitor<int>(sizeof(v)/sizeof(int));
t.InOrderTraversal(visitor);
t.InOrderHeightTraversal(heightVisitor);
ASSERT_TRUE(ArrayAndPointerMatch(result, visitor.GetData()));
ASSERT_TRUE(ArrayAndPointerMatch(heightResult, heightVisitor.GetData()));
}
TEST(AvlTreeTest, PositiveSingleRotateWith15Elems)
{
AvlTree<int> t = AvlTree<int>();
int v[] = {4, 2, 6, 1, 3, 5, 15, 7, 16, 14, 13, 12, 11, 10, 8};
int result[] = {1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15, 16};
int heightResult[] = {0, 1, 0, 2, 0, 1, 4, 0, 1, 2, 0, 3,0, 1, 0};
for (int i = 0; i < sizeof(v) / sizeof(int); ++i)
t.Insert(v[i]);
AccumVisitor<int> visitor = AccumVisitor<int>(sizeof(v)/sizeof(int));
AccumVisitor<int> heightVisitor = AccumVisitor<int>(sizeof(v)/sizeof(int));
t.InOrderTraversal(visitor);
t.InOrderHeightTraversal(heightVisitor);
ASSERT_TRUE(ArrayAndPointerMatch(result, visitor.GetData()));
ASSERT_TRUE(ArrayAndPointerMatch(heightResult, heightVisitor.GetData()));
}
TEST(AvlTreeTest, PositiveSingleRotateWith16Elems)
{
AvlTree<int> t = AvlTree<int>();
int v[] = {4, 2, 6, 1, 3, 5, 15, 7, 16, 14, 13, 12, 11, 10, 8, 9};
int result[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
int heightResult[] = {0, 1, 0, 2, 0, 1, 4, 0, 1, 0, 2, 0, 3,0, 1, 0};
for (int i = 0; i < sizeof(v) / sizeof(int); ++i)
t.Insert(v[i]);
AccumVisitor<int> visitor = AccumVisitor<int>(sizeof(v)/sizeof(int));
AccumVisitor<int> heightVisitor = AccumVisitor<int>(sizeof(v)/sizeof(int));
t.InOrderTraversal(visitor);
t.InOrderHeightTraversal(heightVisitor);
ASSERT_TRUE(ArrayAndPointerMatch(result, visitor.GetData()));
ASSERT_TRUE(ArrayAndPointerMatch(heightResult, heightVisitor.GetData()));
}
<file_sep>//
// MaxSumInTriangle.h
// algo
//
// Created by raof01 on 8/15/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#ifndef algo_MaxSumInTriangle_h
#define algo_MaxSumInTriangle_h
/**
* Dynamic Programming
*/
/*
* The MaxSum of array item (i, j):
* 1
* 2 3
* 4 5 6
* 7 8 9 10
* is item(i, j) + maximum of MaxSum(i+1, j) and MaxSum(i+1, j+1)
* in which, j <= i
*/
// Large amount of recomputation
template <int N>
int MaxSum(const int (&input)[N][N], int row, int col)
{
if (row >= N || col > row) return -1;
if (row == N - 1) return input[row][col];
else
return input[row][col] + std::max(MaxSum(input, row + 1, col), MaxSum(input, row + 1, col + 1));
}
template <int N>
int MaxSumIter(const int (&input)[N][N], int row, int col)
{
if (row >= N || col > row) return -1;
if (row == N - 1) return input[row][col];
// Use tmp to store the best solution of sub-problem
// to eliminate recomputation
int* tmp = new int[N];
for (int i = 0; i < N; ++i)
tmp[i] = input[N - 1][i];
for (int r = N - 2; r >= row; --r)
for (int c = col; c <= r; ++c)
tmp[c] = input[r][c] + std::max(tmp[c], tmp[c+1]);
return tmp[col];
}
#endif
<file_sep>//
// IsPalindrome.h
// algo
//
// Created by raof01 on 7/11/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#ifndef algo_IsPalindrome_h
#define algo_IsPalindrome_h
struct ListNode;
bool isPalindrome(ListNode*);
ListNode* ReverseToNewList(ListNode*);
size_t ListLength(ListNode*);
ListNode* ListAppend(ListNode*, int);
int GetValue(ListNode*);
void ListDestroy(ListNode*);
ListNode* GetNext(ListNode*);
#endif
<file_sep>//
// Misc.h
// algo
//
// Created by raof01 on 7/22/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#ifndef algo_Misc_h
#define algo_Misc_h
#include <vector>
#include <queue>
#include <string>
int CountBinaryOneRecursive(int);
/*
* lst1 and lst2 are sorted. The GetLots will pick up elements from lst1 according
* to the position specified by elements of lst2
*/
std::vector<int> GetLots(const std::vector<int>& lst1, const std::vector<int>& lst2);
/* lst1 and lst2 are sorted */
std::vector<int> InterSect(const std::vector<int>& lst1, const std::vector<int>& lst2);
/* lst1 and lst2 are sorted */
std::vector<int> Union(const std::vector<int>& lst1, const std::vector<int>& lst2);
// Use 2*1 squares to cover m*n of squares
int Cover(int n);
// Recursive version
int NumOfSum(int* a, int aLen, int* b, int bLen, int Sum);
void NumOfSum(int* a, int aLen, int* b, int bLen, int sum, int **r, int &ret);
/*
template <int N1, int N2>
int NumOfSum(int (&a)[N1], int (&b)[N2], int sum)
{
int r = NumOfSum(a, N1 - 1, b, N2 - 1, sum);
if (a[0] + b[0] == sum && !(N1 == 1 && N1 == N2)) return r - 1;
return r;
}
*/
template <int N1, int N2>
int NumOfSumIter(int (&a)[N1], int (&b)[N2], int sum)
{
int result = 0;
for (int i = 1; i < N1 + 1; ++i)
for (int j = 1; j < N2 + 1; ++j)
if (a[i - 1] + b[j - 1] == sum) ++result;
return result;
}
/*
* Assumption: ascii character string
*/
bool IsPermutationOf(const std::string& b, const std::string& a);
template <size_t StrLen>
void ReplaceCharWithString(char (&input)[StrLen], char c, const std::string& pattern) {
std::queue<char> q;
size_t cur = 0;
while (cur < StrLen && (input[cur] != 0 || !q.empty())) {
if (!q.empty()) {
q.push(input[cur]);
input[cur] = q.front();
q.pop();
}
if (input[cur] != c) ++cur;
else {
input[cur++] = pattern[0];
for (size_t i = 1; i < pattern.length(); ++i) {
q.push(input[cur]);
input[cur] = pattern[i];
++cur;
}
}
}
}
template <size_t StrLen>
void ReplaceCharWithPattern(char (&input)[StrLen], char c, const std::string& pattern) {
int len = 0;
int charCnt = 0;
while (input[len] != 0) {
if (input[len] == c) ++charCnt;
++len;
}
if (charCnt == 0) return;
size_t trueLen = len + charCnt * (pattern.length() - 1);
input[trueLen] = 0; // null terminated string
size_t newEnd = trueLen - 1;
int end = len -1;
while (end >= 0) {
if (input[end] != c) {
input[newEnd--] = input[end];
} else {
for (int i = static_cast<int>(pattern.length()) - 1; i >= 0; --i)
input[newEnd--] = pattern[i];
}
--end;
}
}
const std::string& CompressString(const std::string&, std::string&);
bool IsUnique(const std::string&);
bool IsRotate(const std::string&, const std::string&);
// Can only use push() (vector::push_back()), pop() (vector::pop_back())
// peek() (vector::back()), empty() (vector::empty())
// ASSUMPTION: No element larger than or equal to INT_MAX;
// No element less than or equal to INT_MIN;
void SortStackUsingStack(std::vector<int>&);
void SortStackUsingStack(std::vector<int>&, std::vector<int>&);
void MergeTwoSortedArrays(std::vector<int>& dest, const std::vector<int>& src);
#endif
<file_sep>//
// KthSelection.h
// algo
//
// Created by raof01 on 8/6/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#ifndef algo_KthSelection_h
#define algo_KthSelection_h
#include "QuickSort.hpp"
template <typename Comparable>
class KthSelection
{
public:
static Comparable Select(Comparable* input, size_t N, size_t k);
template <size_t N>
static Comparable Select(Comparable (&input)[N], size_t k);
};
template <typename T>
T KthSelection<T>::Select(T* input, size_t N, size_t k)
{
assert(k < N);
size_t lo = 0;
size_t hi = N;
while (hi > lo)
{
size_t p = QuickSorter<T>::PartitionWithLessSwap(input, lo, hi);
if (p == k) return input[k];
else if (p > k) hi = p;
else lo = p + 1;
}
return input[k];
}
template <typename T>
template <size_t N>
T KthSelection<T>::Select(T (&input)[N], size_t k)
{
return Select(input, N, k);
}
#endif
<file_sep>//
// SingleLinkedList.h
// algo
//
// Created by raof01 on 5/8/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#ifndef algo_SingleLinkedList_h
#define algo_SingleLinkedList_h
struct Node;
class SingleLinkedList
{
class _Iterator;
public:
typedef _Iterator Iterator;
SingleLinkedList() : mHead(0) {}
~SingleLinkedList();
void Insert(int);
void Append(int);
void Delete(int);
void DeleteAll(int);
void Reverse();
bool Empty();
size_t Count();
// Iterator creation / get should be separated with iterator operations
Iterator Begin();
Iterator End();
Iterator Find(int);
private:
Node* FindImpl(int);
bool DeleteImpl(int);
private:
class _Iterator
{
friend class SingleLinkedList;
friend bool operator == (const _Iterator& lhs, const _Iterator& rhs);
friend bool operator != (const _Iterator& lhs, const _Iterator& rhs);
public:
// Iterator operations should be separated with Iterator creation / get
int operator *();
_Iterator& operator++();
_Iterator operator++(int);
_Iterator operator+(int);
private:
_Iterator(Node* node) : mCur(node) { }
private:
Node* mCur;
};
private:
Node* mHead;
};
#endif
<file_sep>//
// BinaryTreeLinkImplTest.cpp
// algo
//
// Created by raof01 on 5/10/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#include "gtest/gtest.h"
#include "BinaryTreeLinkImpl.hpp"
#include "ArraysMatch.hpp"
#include "AccumVisitor.h"
class PrintVisitor : public Visitor<int, false>
{
public:
void Visit(int v) override
{
std::cout << v << " ";
}
};
TEST(TestBinaryTree, Destructor)
{
BinaryTree* sut = new BinaryTreeLinkImpl();
delete sut;
}
TEST(TestBinaryTree, InOrderTraversal)
{
BinaryTree* sut = new BinaryTreeLinkImpl();
int a[] = {5, 4, 7, 9, 10, 8, 6, 3, 1, 2};
int r[] = {1, 2, 3, 4, 5, 6, 7, 8, 9 ,10};
for (int i = 0; i < 10; ++i)
sut->Insert(a[i]);
AccumVisitor<int> v = AccumVisitor<int>(sizeof(a) / sizeof(int));
sut->InOrderTraversal(v);
ASSERT_TRUE(ArrayAndPointerMatch(r, v.GetData()));
delete sut;
}
TEST(TestBinaryTree, PreOrderTraversal)
{
BinaryTree* sut = new BinaryTreeLinkImpl();
int a[] = {5, 4, 7, 9, 10, 8, 6, 3, 1, 2};
int r[] = {5, 4, 3, 1, 2, 7, 6, 9, 8, 10};
for (int i = 0; i < 10; ++i)
sut->Insert(a[i]);
AccumVisitor<int> v = AccumVisitor<int>(sizeof(a) / sizeof(int));
sut->PreOrderTraversal(v);
ASSERT_TRUE(ArrayAndPointerMatch(r, v.GetData()));
delete sut;
}
TEST(TestBinaryTree, PostOrderTraversal)
{
BinaryTree* sut = new BinaryTreeLinkImpl();
int a[] = {5, 4, 7, 9, 10, 8, 6, 3, 1, 2};
int r[] = {2, 1, 3, 4, 6, 8, 10, 9, 7, 5};
for (int i = 0; i < 10; ++i)
sut->Insert(a[i]);
AccumVisitor<int> v = AccumVisitor<int>(sizeof(a) / sizeof(int));
sut->PostOrderTraversal(v);
ASSERT_TRUE(ArrayAndPointerMatch(r, v.GetData()));
delete sut;
}
TEST(TestBinaryTree, InOrderTraversalIter)
{
BinaryTree* sut = new BinaryTreeLinkImpl(false);
int a[] = {5, 4, 7, 9, 10, 8, 6, 3, 1, 2};
int r[] = {1, 2, 3, 4, 5, 6, 7, 8, 9 ,10};
for (int i = 0; i < 10; ++i)
sut->Insert(a[i]);
AccumVisitor<int> v = AccumVisitor<int>(sizeof(a) / sizeof(int));
sut->InOrderTraversal(v);
ASSERT_TRUE(ArrayAndPointerMatch(r, v.GetData()));
delete sut;
}
TEST(TestBinaryTree, PreOrderTraversalIter)
{
BinaryTree* sut = new BinaryTreeLinkImpl(false);
int a[] = {5, 4, 7, 9, 10, 8, 6, 3, 1, 2};
int r[] = {5, 4, 3, 1, 2, 7, 6, 9, 8, 10};
for (int i = 0; i < 10; ++i)
sut->Insert(a[i]);
AccumVisitor<int> v = AccumVisitor<int>(sizeof(a) / sizeof(int));
sut->PreOrderTraversal(v);
ASSERT_TRUE(ArrayAndPointerMatch(r, v.GetData()));
delete sut;
}
TEST(TestBinaryTree, PostOrderTraversalIter)
{
BinaryTree* sut = new BinaryTreeLinkImpl(false);
int a[] = {5, 4, 7, 9, 10, 8, 6, 3, 1, 2};
int r[] = {2, 1, 3, 4, 6, 8, 10, 9, 7, 5};
for (int i = 0; i < 10; ++i)
sut->Insert(a[i]);
AccumVisitor<int> v = AccumVisitor<int>(sizeof(a) / sizeof(int));
sut->PostOrderTraversal(v);
ASSERT_TRUE(ArrayAndPointerMatch(r, v.GetData()));
delete sut;
}
TEST(TestBinaryTree, GetMaxValue)
{
BinaryTree* sut = new BinaryTreeLinkImpl();
int a[] = {5, 4, 7, 9, 10, 8, 6, 3, 1, 2};
for (int i = 0; i < 10; ++i)
sut->Insert(a[i]);
ASSERT_EQ(10, sut->GetMaxValue());
delete sut;
}
TEST(TestBinaryTree, GetMinValue)
{
BinaryTree* sut = new BinaryTreeLinkImpl();
int a[] = {5, 4, 7, 9, 10, 8, 6, 3, 1, 2};
for (int i = 0; i < 10; ++i)
sut->Insert(a[i]);
ASSERT_EQ(1, sut->GetMinValue());
delete sut;
}
TEST(TestBinaryTree, GetParentValue)
{
BinaryTree* sut = new BinaryTreeLinkImpl();
int a[] = {5, 4, 7, 9, 10, 8, 6, 3, 1, 2};
for (int i = 0; i < 10; ++i)
sut->Insert(a[i]);
int v;
ASSERT_FALSE(sut->GetParentValue(5, v));
ASSERT_TRUE(sut->GetParentValue(2, v));
ASSERT_EQ(1, v);
ASSERT_TRUE(sut->GetParentValue(3, v));
ASSERT_EQ(4, v);
ASSERT_TRUE(sut->GetParentValue(4, v));
ASSERT_EQ(5, v);
ASSERT_TRUE(sut->GetParentValue(7, v));
ASSERT_EQ(5, v);
ASSERT_TRUE(sut->GetParentValue(6, v));
ASSERT_EQ(7, v);
ASSERT_TRUE(sut->GetParentValue(9, v));
ASSERT_EQ(7, v);
ASSERT_TRUE(sut->GetParentValue(8, v));
ASSERT_EQ(9, v);
ASSERT_TRUE(sut->GetParentValue(10, v));
ASSERT_EQ(9, v);
ASSERT_FALSE(sut->GetParentValue(12, v));
delete sut;
}
TEST(TestBinaryTree, GetSuccessorValue)
{
BinaryTree* sut = new BinaryTreeLinkImpl();
int a[] = {5, 4, 7, 9, 10, 8, 6, 3, 1, 2};
for (int i = 0; i < 10; ++i)
sut->Insert(a[i]);
int v;
ASSERT_TRUE(sut->GetSuccessorValue(5, v));
ASSERT_EQ(6, v);
ASSERT_TRUE(sut->GetSuccessorValue(2, v));
ASSERT_EQ(3, v);
ASSERT_TRUE(sut->GetSuccessorValue(1, v));
ASSERT_EQ(2, v);
ASSERT_TRUE(sut->GetSuccessorValue(3, v));
ASSERT_EQ(4, v);
ASSERT_TRUE(sut->GetSuccessorValue(4, v));
ASSERT_EQ(5, v);
ASSERT_TRUE(sut->GetSuccessorValue(7, v));
ASSERT_EQ(8, v);
ASSERT_TRUE(sut->GetSuccessorValue(6, v));
ASSERT_EQ(7, v);
ASSERT_TRUE(sut->GetSuccessorValue(9, v));
ASSERT_EQ(10, v);
ASSERT_TRUE(sut->GetSuccessorValue(8, v));
ASSERT_EQ(9, v);
ASSERT_FALSE(sut->GetSuccessorValue(10, v));
ASSERT_FALSE(sut->GetSuccessorValue(12, v));
delete sut;
}
TEST(TestBinaryTree, GetPredecessorValue)
{
BinaryTree* sut = new BinaryTreeLinkImpl();
int a[] = {5, 4, 7, 9, 10, 8, 6, 3, 1, 2};
for (int i = 0; i < 10; ++i)
sut->Insert(a[i]);
int v;
ASSERT_TRUE(sut->GetPredecessorValue(10, v));
ASSERT_EQ(9, v);
ASSERT_TRUE(sut->GetPredecessorValue(9, v));
ASSERT_EQ(8, v);
ASSERT_TRUE(sut->GetPredecessorValue(8, v));
ASSERT_EQ(7, v);
ASSERT_TRUE(sut->GetPredecessorValue(7, v));
ASSERT_EQ(6, v);
ASSERT_TRUE(sut->GetPredecessorValue(6, v));
ASSERT_EQ(5, v);
ASSERT_TRUE(sut->GetPredecessorValue(5, v));
ASSERT_EQ(4, v);
ASSERT_TRUE(sut->GetPredecessorValue(4, v));
ASSERT_EQ(3, v);
ASSERT_TRUE(sut->GetPredecessorValue(3, v));
ASSERT_EQ(2, v);
ASSERT_TRUE(sut->GetPredecessorValue(2, v));
ASSERT_EQ(1, v);
ASSERT_FALSE(sut->GetPredecessorValue(1, v));
ASSERT_FALSE(sut->GetPredecessorValue(12, v));
delete sut;
}
TEST(TestBinaryTree, DeleteLeaf)
{
BinaryTree* sut = new BinaryTreeLinkImpl();
int a[] = {15, 5, 16, 3, 12, 20, 10, 13, 18, 23, 6, 7};
int resultPreOrder[] = {15, 5, 3, 12, 10, 6, 7, 16, 20, 18, 23};
int resultInOrder[] = {3, 5, 6, 7, 10, 12, 15, 16, 18, 20, 23};
int resultPostOrder[] = {3, 7, 6, 10, 12, 5, 18, 23, 20, 16, 15};
for (int i = 0; i < sizeof(a) / sizeof(int); ++i)
sut->Insert(a[i]);
sut->Delete(13);
ASSERT_FALSE(sut->Find(13));
AccumVisitor<int> visitorPreOrder = AccumVisitor<int>(sizeof(resultInOrder)/sizeof(int));
sut->PreOrderTraversal(visitorPreOrder);
ASSERT_TRUE(ArrayAndPointerMatch(resultPreOrder, visitorPreOrder.GetData()));
AccumVisitor<int> visitorInOrder = AccumVisitor<int>(sizeof(resultInOrder)/sizeof(int));
sut->InOrderTraversal(visitorInOrder);
ASSERT_TRUE(ArrayAndPointerMatch(resultInOrder, visitorInOrder.GetData()));
AccumVisitor<int> visitorPostOrder = AccumVisitor<int>(sizeof(resultPostOrder)/sizeof(int));
sut->PostOrderTraversal(visitorPostOrder);
ASSERT_TRUE(ArrayAndPointerMatch(resultPostOrder, visitorPostOrder.GetData()));
delete sut;
}
TEST(TestBinaryTree, DeleteNodeWithOnlyRightSubTree)
{
BinaryTree* sut = new BinaryTreeLinkImpl();
int a[] = {15, 5, 16, 3, 12, 20, 10, 13, 18, 23, 6, 7};
int resultPreOrder[] = {15, 5, 3, 12, 10, 6, 7, 13, 20, 18, 23};
int resultInOrder[] = {3, 5, 6, 7, 10, 12, 13, 15, 18, 20, 23};
int resultPostOrder[] = {3, 7, 6, 10, 13, 12, 5, 18, 23, 20, 15};
for (int i = 0; i < sizeof(a) / sizeof(int); ++i)
sut->Insert(a[i]);
sut->Delete(16);
ASSERT_FALSE(sut->Find(16));
AccumVisitor<int> visitorPreOrder = AccumVisitor<int>(sizeof(resultInOrder)/sizeof(int));
sut->PreOrderTraversal(visitorPreOrder);
ASSERT_TRUE(ArrayAndPointerMatch(resultPreOrder, visitorPreOrder.GetData()));
AccumVisitor<int> visitorInOrder = AccumVisitor<int>(sizeof(resultInOrder)/sizeof(int));
sut->InOrderTraversal(visitorInOrder);
ASSERT_TRUE(ArrayAndPointerMatch(resultInOrder, visitorInOrder.GetData()));
AccumVisitor<int> visitorPostOrder = AccumVisitor<int>(sizeof(resultPostOrder)/sizeof(int));
sut->PostOrderTraversal(visitorPostOrder);
ASSERT_TRUE(ArrayAndPointerMatch(resultPostOrder, visitorPostOrder.GetData()));
delete sut;
}
TEST(TestBinaryTree, DeleteNodeWithOnlyLeftSubTree)
{
BinaryTree* sut = new BinaryTreeLinkImpl();
int a[] = {15, 5, 16, 3, 12, 20, 10, 13, 18, 23, 6, 7};
int resultPreOrder[] = {15, 5, 3, 12, 6, 7, 13, 16, 20, 18, 23};
int resultInOrder[] = {3, 5, 6, 7, 12, 13, 15, 16, 18, 20, 23};
int resultPostOrder[] = {3, 7, 6, 13, 12, 5, 18, 23, 20, 16, 15};
for (int i = 0; i < sizeof(a) / sizeof(int); ++i)
sut->Insert(a[i]);
sut->Delete(10);
ASSERT_FALSE(sut->Find(10));
AccumVisitor<int> visitorPreOrder = AccumVisitor<int>(sizeof(resultInOrder)/sizeof(int));
sut->PreOrderTraversal(visitorPreOrder);
ASSERT_TRUE(ArrayAndPointerMatch(resultPreOrder, visitorPreOrder.GetData()));
AccumVisitor<int> visitorInOrder = AccumVisitor<int>(sizeof(resultInOrder)/sizeof(int));
sut->InOrderTraversal(visitorInOrder);
ASSERT_TRUE(ArrayAndPointerMatch(resultInOrder, visitorInOrder.GetData()));
AccumVisitor<int> visitorPostOrder = AccumVisitor<int>(sizeof(resultPostOrder)/sizeof(int));
sut->PostOrderTraversal(visitorPostOrder);
ASSERT_TRUE(ArrayAndPointerMatch(resultPostOrder, visitorPostOrder.GetData()));
delete sut;
}
TEST(TestBinaryTree, DeleteNodeWithTwoSubTrees)
{
BinaryTree* sut = new BinaryTreeLinkImpl();
int a[] = {15, 5, 16, 3, 12, 20, 10, 13, 18, 23, 6, 7};
int resultPreOrder[] = {15, 5, 3, 13, 10, 6, 7, 16, 20, 18, 23};
int resultInOrder[] = {3, 5, 6, 7, 10, 13, 15, 16, 18, 20, 23};
int resultPostOrder[] = {3, 7, 6, 10, 13, 5, 18, 23, 20, 16, 15};
for (int i = 0; i < sizeof(a) / sizeof(int); ++i)
sut->Insert(a[i]);
sut->Delete(12);
ASSERT_FALSE(sut->Find(12));
AccumVisitor<int> visitorPreOrder = AccumVisitor<int>(sizeof(resultInOrder)/sizeof(int));
sut->PreOrderTraversal(visitorPreOrder);
ASSERT_TRUE(ArrayAndPointerMatch(resultPreOrder, visitorPreOrder.GetData()));
AccumVisitor<int> visitorInOrder = AccumVisitor<int>(sizeof(resultInOrder)/sizeof(int));
sut->InOrderTraversal(visitorInOrder);
ASSERT_TRUE(ArrayAndPointerMatch(resultInOrder, visitorInOrder.GetData()));
AccumVisitor<int> visitorPostOrder = AccumVisitor<int>(sizeof(resultPostOrder)/sizeof(int));
sut->PostOrderTraversal(visitorPostOrder);
ASSERT_TRUE(ArrayAndPointerMatch(resultPostOrder, visitorPostOrder.GetData()));
delete sut;
}
TEST(TestBinaryTree, DeleteNodeWithTwoSubTrees2)
{
BinaryTree* sut = new BinaryTreeLinkImpl();
int a[] = {15, 5, 16, 3, 12, 20, 10, 13, 18, 23, 6, 7};
int resultPreOrder[] = {15, 5, 3, 12, 10, 6, 7, 13, 16, 23, 18};
int resultInOrder[] = {3, 5, 6, 7, 10, 12, 13, 15, 16, 18, 23};
int resultPostOrder[] = {3, 7, 6, 10, 13, 12, 5, 18, 23, 16, 15};
for (int i = 0; i < sizeof(a) / sizeof(int); ++i)
sut->Insert(a[i]);
sut->Delete(20);
ASSERT_FALSE(sut->Find(20));
AccumVisitor<int> visitorPreOrder = AccumVisitor<int>(sizeof(resultInOrder)/sizeof(int));
sut->PreOrderTraversal(visitorPreOrder);
ASSERT_TRUE(ArrayAndPointerMatch(resultPreOrder, visitorPreOrder.GetData()));
AccumVisitor<int> visitorInOrder = AccumVisitor<int>(sizeof(resultInOrder)/sizeof(int));
sut->InOrderTraversal(visitorInOrder);
ASSERT_TRUE(ArrayAndPointerMatch(resultInOrder, visitorInOrder.GetData()));
AccumVisitor<int> visitorPostOrder = AccumVisitor<int>(sizeof(resultPostOrder)/sizeof(int));
sut->PostOrderTraversal(visitorPostOrder);
ASSERT_TRUE(ArrayAndPointerMatch(resultPostOrder, visitorPostOrder.GetData()));
delete sut;
}
TEST(TestBinaryTree, DeleteRoot)
{
BinaryTree* sut = new BinaryTreeLinkImpl();
int a[] = {15, 5, 16, 3, 12, 20, 10, 13, 18, 23, 6, 7};
int resultPreOrder[] = {16, 5, 3, 12, 10, 6, 7, 13, 20, 18, 23};
int resultInOrder[] = {3, 5, 6, 7, 10, 12, 13, 16, 18, 20, 23};
int resultPostOrder[] = {3, 7, 6, 10, 13, 12, 5, 18, 23, 20, 16};
for (int i = 0; i < sizeof(a) / sizeof(int); ++i)
sut->Insert(a[i]);
sut->Delete(15);
ASSERT_FALSE(sut->Find(15));
AccumVisitor<int> visitorPreOrder = AccumVisitor<int>(sizeof(resultInOrder)/sizeof(int));
sut->PreOrderTraversal(visitorPreOrder);
ASSERT_TRUE(ArrayAndPointerMatch(resultPreOrder, visitorPreOrder.GetData()));
AccumVisitor<int> visitorInOrder = AccumVisitor<int>(sizeof(resultInOrder)/sizeof(int));
sut->InOrderTraversal(visitorInOrder);
ASSERT_TRUE(ArrayAndPointerMatch(resultInOrder, visitorInOrder.GetData()));
AccumVisitor<int> visitorPostOrder = AccumVisitor<int>(sizeof(resultPostOrder)/sizeof(int));
sut->PostOrderTraversal(visitorPostOrder);
ASSERT_TRUE(ArrayAndPointerMatch(resultPostOrder, visitorPostOrder.GetData()));
delete sut;
}
TEST(TestBinaryTree, BreadthFirstTraversal)
{
BinaryTree* sut = new BinaryTreeLinkImpl(false);
int a[] = {5, 4, 7, 9, 10, 8, 6, 3, 1, 2};
int r[] = {5, 4, 7, 3, 6, 9, 1, 8, 10, 2};
for (int i = 0; i < 10; ++i)
sut->Insert(a[i]);
AccumVisitor<int> v = AccumVisitor<int>(sizeof(a) / sizeof(int));
sut->BreadthFirstTraversal(v);
ASSERT_TRUE(ArrayAndPointerMatch(r, v.GetData()));
delete sut;
}
TEST(TestBinaryTree, DepthFirstTraversal)
{
BinaryTree* sut = new BinaryTreeLinkImpl(false);
int a[] = {5, 4, 7, 9, 10, 8, 6, 3, 1, 2};
int r[] = {5, 4, 3, 1, 2, 7, 6, 9, 8, 10};
for (int i = 0; i < 10; ++i)
sut->Insert(a[i]);
AccumVisitor<int> v = AccumVisitor<int>(sizeof(a) / sizeof(int));
sut->DepthFirstTraversal(v);
ASSERT_TRUE(ArrayAndPointerMatch(r, v.GetData()));
delete sut;
}
TEST(TestBinaryTree, Invert)
{
BinaryTree* sut = new BinaryTreeLinkImpl();
int a[] = {5, 4, 7, 9, 10, 8, 6, 3, 1, 2};
int r[] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
for (int i = 0; i < 10; ++i)
sut->Insert(a[i]);
sut->Invert();
AccumVisitor<int> v = AccumVisitor<int>(sizeof(a) / sizeof(int));
sut->InOrderTraversal(v);
ASSERT_TRUE(ArrayAndPointerMatch(r, v.GetData()));
delete sut;
}
TEST(TestBinaryTree, InvertNonRecursive)
{
BinaryTree* sut = new BinaryTreeLinkImpl(false);
int a[] = {5, 4, 7, 9, 10, 8, 6, 3, 1, 2};
int r[] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
for (int i = 0; i < 10; ++i)
sut->Insert(a[i]);
sut->Invert();
AccumVisitor<int> v = AccumVisitor<int>(sizeof(a) / sizeof(int));
sut->InOrderTraversal(v);
ASSERT_TRUE(ArrayAndPointerMatch(r, v.GetData()));
delete sut;
}
TEST(TestBinaryTree, FloorPositive)
{
BinaryTree* sut = new BinaryTreeLinkImpl(false);
int a[] = {5, 4, 7, 9, 10, 8, 6, 3, 1, 2};
for (int i = 0; i < 10; ++i)
sut->Insert(a[i]);
ASSERT_EQ(9, sut->Floor(9));
delete sut;
}
TEST(TestBinaryTree, FloorOfValueLessThanMinValue)
{
BinaryTree* sut = new BinaryTreeLinkImpl(false);
int a[] = {5, 4, 7, 9, 10, 8, 6, 3, 1, 2};
for (int i = 0; i < 10; ++i)
sut->Insert(a[i]);
ASSERT_EQ(-1, sut->Floor(0));
delete sut;
}
TEST(TestBinaryTree, FloorOfValueGreaterThanMaxValue)
{
BinaryTree* sut = new BinaryTreeLinkImpl(false);
int a[] = {5, 4, 7, 9, 10, 8, 6, 3, 1, 2};
for (int i = 0; i < 10; ++i)
sut->Insert(a[i]);
ASSERT_EQ(10, sut->Floor(12));
delete sut;
}
TEST(TestBinaryTree, FloorOfValueInSideButNotEqualToAny)
{
BinaryTree* sut = new BinaryTreeLinkImpl(false);
int a[] = {5, 7, 9, 10, 6, 1, 2};
for (int i = 0; i < 7; ++i)
sut->Insert(a[i]);
ASSERT_EQ(7, sut->Floor(8));
ASSERT_EQ(2, sut->Floor(4));
delete sut;
}
TEST(TestBinaryTree, CeilingPositive)
{
BinaryTree* sut = new BinaryTreeLinkImpl(false);
int a[] = {5, 4, 7, 9, 10, 8, 6, 3, 1, 2};
for (int i = 0; i < 10; ++i)
sut->Insert(a[i]);
ASSERT_EQ(7, sut->Ceiling(7));
delete sut;
}
TEST(TestBinaryTree, CeilingOfValueLessThanMinValue)
{
BinaryTree* sut = new BinaryTreeLinkImpl(false);
int a[] = {5, 4, 7, 9, 10, 8, 6, 3, 1, 2};
for (int i = 0; i < 10; ++i)
sut->Insert(a[i]);
ASSERT_EQ(1, sut->Ceiling(0));
delete sut;
}
TEST(TestBinaryTree, CeilingOfValueGreaterThanMaxValue)
{
BinaryTree* sut = new BinaryTreeLinkImpl(false);
int a[] = {5, 4, 7, 9, 10, 8, 6, 3, 1, 2};
for (int i = 0; i < 10; ++i)
sut->Insert(a[i]);
ASSERT_EQ(-1, sut->Ceiling(12));
delete sut;
}
TEST(TestBinaryTree, CeilingOfValueInSideButNotEqualToAny)
{
BinaryTree* sut = new BinaryTreeLinkImpl(false);
int a[] = {5, 7, 9, 10, 6, 1, 2};
for (int i = 0; i < 7; ++i)
sut->Insert(a[i]);
ASSERT_EQ(9, sut->Ceiling(8));
ASSERT_EQ(5, sut->Ceiling(4));
delete sut;
}
TEST(TestBinaryTree, Size)
{
BinaryTree* sut = new BinaryTreeLinkImpl(false);
int a[] = {5, 4, 7, 9, 10, 8, 6, 3, 1, 2};
for (int i = 0; i < 10; ++i)
sut->Insert(a[i]);
ASSERT_EQ(10, sut->Size(5));
ASSERT_EQ(4, sut->Size(4));
ASSERT_EQ(5, sut->Size(7));
ASSERT_EQ(3, sut->Size(3));
ASSERT_EQ(1, sut->Size(6));
ASSERT_EQ(3, sut->Size(9));
ASSERT_EQ(2, sut->Size(1));
ASSERT_EQ(1, sut->Size(2));
ASSERT_EQ(1, sut->Size(8));
ASSERT_EQ(1, sut->Size(10));
ASSERT_EQ(0, sut->Size(20));
delete sut;
}
TEST(TestBinaryTree, Rank)
{
BinaryTree* sut = new BinaryTreeLinkImpl(false);
int a[] = {5, 4, 7, 9, 10, 8, 6, 3, 1, 2};
for (int i = 0; i < 10; ++i)
sut->Insert(a[i]);
ASSERT_EQ(4, sut->Rank(5));
ASSERT_EQ(3, sut->Rank(4));
ASSERT_EQ(6, sut->Rank(7));
ASSERT_EQ(2, sut->Rank(3));
ASSERT_EQ(5, sut->Rank(6));
ASSERT_EQ(8, sut->Rank(9));
ASSERT_EQ(0, sut->Rank(1));
ASSERT_EQ(1, sut->Rank(2));
ASSERT_EQ(7, sut->Rank(8));
ASSERT_EQ(9, sut->Rank(10));
delete sut;
}
TEST(TestBinaryTree, RankOfValueNotInTree)
{
BinaryTree* sut = new BinaryTreeLinkImpl(false);
int a[] = {5, 4, 9, 10, 8, 6, 1, 2};
for (int i = 0; i < 8; ++i)
sut->Insert(a[i]);
ASSERT_EQ(5, sut->Rank(7));
ASSERT_EQ(2, sut->Rank(3));
ASSERT_EQ(0, sut->Rank(0));
ASSERT_EQ(8, sut->Rank(110));
delete sut;
}
<file_sep>//
// Fibonacci.cpp
// algo
//
// Created by raof01 on 5/5/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#include "Fibonacci.hpp"
static void FiboRecursive(int n, size_t n_2, size_t n_1, size_t& result);
static void FiboIter(int n, size_t& result);
size_t Fibo(int n, const Iter&)
{
size_t r = 0;
FiboIter(n, r);
return r;
}
size_t Fibo(int n)
{
size_t r = 0;
FiboRecursive(n, 0, 1, r);
return r;
}
static void FiboRecursive(int n, size_t n_2, size_t n_1, size_t& result)
{
if (n == 0)
result = n_2;
else if (n == 1)
result = n_1;
else
{
result = n_2 + n_1;
FiboRecursive(n - 1, n_1, result, result);
}
}
static void FiboIter(int n, size_t& result)
{
size_t n_1 = 1;
size_t n_2 = 0;
if (n == 0)
result = n_2;
else if (n == 1)
result = n_1;
else
while (n > 1)
{
result = n_1 + n_2;
n_2 = n_1;
n_1 = result;
--n;
}
}
<file_sep>//
// DoubleLinkedList.cpp
// algo
//
// Created by raof01 on 5/9/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#include <stdlib.h>
#include "DoubleLinkedList.h"
struct DoubleLinkedList::Node
{
Node(int v = -1, Node* n = nullptr, Node* p = nullptr) : next(n), prev(p), value(v) {}
Node* next;
Node* prev;
int value;
};
bool operator==(const DoubleLinkedList::Iterator& lhs, const DoubleLinkedList::Iterator& rhs)
{
if (&lhs == &rhs || (lhs.mCnt == rhs.mCnt && lhs.mCur == rhs.mCur)) return true;
return false;
}
bool operator!=(const DoubleLinkedList::Iterator& lhs, const DoubleLinkedList::Iterator& rhs)
{
return !(lhs == rhs);
}
int DoubleLinkedList::_Iterator::operator*() const
{
return mCur->value;
}
void DoubleLinkedList::_Iterator::Next()
{
mCur = mCur->next;
--mCnt;
if (mCnt <= 0)
{
mCur = nullptr;
mCnt = 0;
}
}
DoubleLinkedList::Iterator DoubleLinkedList::_Iterator::operator++(int)
{
Iterator iter = *this;
Next();
return iter;
}
DoubleLinkedList::Iterator& DoubleLinkedList::_Iterator::operator++()
{
Next();
return *this;
}
DoubleLinkedList::~DoubleLinkedList()
{
Node* p = mHead;
if (p != nullptr)
{
// Break the loop
mHead->prev->next = nullptr;
while (p != nullptr)
{
p = p->next;
delete mHead;
mHead = p;
}
}
}
void DoubleLinkedList::Insert(int v)
{
if (Empty())
{
mHead = new Node(v);
// Form the loop
mHead->next = mHead;
mHead->prev = mHead;
}
else
{
Node* mCur = mHead;
Node* prev = mHead->prev;
mHead = new Node(v, mHead, prev);
prev->next = mHead;
mCur->prev = mHead;
}
}
DoubleLinkedList::Node* DoubleLinkedList::FindImpl(int v)
{
if (Empty()) return nullptr;
Node* end = mHead;
Node* mCur = mHead;
bool found = false;
do
{
if (mCur->value == v)
{
found = true;
break;
}
mCur = mCur->next;
} while (mCur != end);
return found ? mCur : nullptr;
}
bool DoubleLinkedList::DeleteImpl(int v)
{
if (Empty()) return false;
if (Count() == 1)
{
delete mHead;
mHead = nullptr;
return true;
}
Node* p = FindImpl(v);
if (p == nullptr)
return false;
if (p == mHead)
mHead = p->next;
p->prev->next = p->next;
p->next->prev = p->prev;
delete p;
return true;
}
void DoubleLinkedList::Delete(int v)
{
DeleteImpl(v);
}
void DoubleLinkedList::DeleteAll(int v)
{
while (DeleteImpl(v));
}
bool DoubleLinkedList::Empty()
{
return mHead == nullptr;
}
int DoubleLinkedList::Count()
{
if (Empty()) return 0;
int mCnt = 0;
Node* p = mHead;
do
{
++mCnt;
p = p->next;
}
while (p != mHead);
return mCnt;
}
// Iterator creation / get should be separated with iterator operations
DoubleLinkedList::Iterator DoubleLinkedList::Begin()
{
return _Iterator(mHead, Count());
}
DoubleLinkedList::Iterator DoubleLinkedList::End()
{
return _Iterator(nullptr, 0);
}
DoubleLinkedList::Iterator DoubleLinkedList::Find(int v)
{
Node* p = FindImpl(v);
return p == nullptr ? _Iterator(p, 0) : _Iterator(p, Count());
}
<file_sep>//
// LCS.h
// algo
//
// Created by raof01 on 5/18/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#ifndef algo_LCS_h
#define algo_LCS_h
////////////////////////////////////////////////////////////////////////////////
// This is the example for dynamic programming
////////////////////////////////////////////////////////////////////////////////
enum Direction
{
UNKNOWN = 0,
UP_LEFT = 1,
LEFT = 2,
UP = 3,
};
// No partial specialization for function template, so I have to write the code TWICE,
// with minor differences
template <int M, int N, typename T>
void LCSLength(const T (&a)[M], const T (&b)[N], Direction (&direction)[M + 1][N + 1], int (&len)[M + 1][N + 1])
{
for (int ai = 0, i = 1; ai < M; ++ai, ++i)
{
for (int bj = 0, j = 1; bj < N; ++bj, ++j)
{
if (a[ai] == b[bj])
{
len[i][j] = len[i - 1][j - 1] + 1;
direction[i][j] = UP_LEFT;
}
else
{
if (len[i - 1][j] >= len[i][j - 1])
{
len[i][j] = len[i - 1][j];
direction[i][j] = UP;
}
else
{
len[i][j] = len[i][j - 1];
direction[i][j] = LEFT;
}
}
}
}
}
template <int M, int N>
// input input output output
void LCSLength(const char (&a)[M], const char (&b)[N], Direction (&direction)[M + 1][N + 1], int (&len)[M + 1][N + 1])
{
// Ignore trailing '\0'
for (int ai = 0, i = 1; ai < M - 1; ++ai, ++i)
{
for (int bj = 0, j = 1; bj < N - 1; ++bj, ++j)
{
if (a[ai] == b[bj])
{
len[i][j] = len[i - 1][j - 1] + 1;
direction[i][j] = UP_LEFT;
}
else
{
if (len[i - 1][j] >= len[i][j - 1])
{
len[i][j] = len[i - 1][j];
direction[i][j] = UP;
}
else
{
len[i][j] = len[i][j - 1];
direction[i][j] = LEFT;
}
}
}
}
}
// dynamic programming
// Recursive version of LCS
template <typename Comparable, int N1, int N2>
int LCSLen(const Comparable (&a)[N1], const Comparable (&b)[N2], int posA, int posB)
{
if (posA == -1 || posB == -1) return 0;
if (a[posA] == b[posB])
return LCSLen(a, b, posA - 1, posB - 1) + 1;
return std::max(LCSLen(a, b, posA - 1, posB), LCSLen(a, b, posA, posB - 1));
}
// dynamic programming
// Non recursive version of LCS
template <typename Comparable, int N1, int N2>
int LCSLen(const Comparable (&a)[N1], const Comparable (&b)[N2])
{
int lenArray[N1 + 1][N2 + 1] = {0}; // Assume that the array size will not exceed stack size limit
for (int i = 1; i < N1 + 1; ++i)
{
for (int j = 1; j < N2 + 1; ++j)
{
if (a[i - 1] == b[j - 1])
lenArray[i][j] = lenArray[i - 1][j - 1] + 1;
else
lenArray[i][j] = std::max(lenArray[i-1][j], lenArray[i][j-1]);
}
}
return lenArray[N1][N2];
}
template <typename Comparable, int N>
int LASLen(const Comparable (&a)[N])
{
int maxLen[N];
for (int i = 0; i < N; ++i)
maxLen[i] = 1;
for (int cur = 1; cur < N; ++cur)
for (int max = 0; max < cur; ++max)
if (a[cur] > a[max])
maxLen[cur] = std::max(maxLen[max] + 1, maxLen[cur]);
int max = 1;
for (int i = 0; i < N; ++i)
if (maxLen[i] > max)
max = maxLen[i];
return max;
}
#include <type_traits>
template <typename T, bool IsClass>
class Visitor;
template <int M, int N, typename T>
void LCSVisit(const T (&a)[M], Direction (&direction)[M+1][N+1], int ai, int bj, Visitor<T, std::is_class<T>::value >& visitor)
{
if (ai == 0 || bj == 0)
return;
if (direction[ai][bj] == UP_LEFT)
{
LCSVisit<M, N, T>(a, direction, ai - 1, bj - 1, visitor);
visitor.Visit(a[ai-1]);
}
else if (direction[ai][bj] == UP)
LCSVisit<M, N, T>(a, direction, ai - 1, bj, visitor);
else
LCSVisit<M, N, T>(a, direction, ai, bj - 1, visitor);
}
#endif
<file_sep>//
// FindDupInt.h
// algo
//
// Created by <NAME> on 9/28/15.
// Copyright © 2015 raof01. All rights reserved.
//
#ifndef FindDupInt_h
#define FindDupInt_h
// ASSUMPTION: only 1 integer has 1 dup
// N + 1 integers, from 1 to N
template <size_t N>
void FindDupInt(const int (&a)[N], int& firstPos, int& secondPos) {
firstPos = -1;
secondPos = -1;
if (N < 2) return;
int sum = N * (N - 1) / 2;
int tmpSum = 0;
for (int i = 0; i < N; ++i)
tmpSum += a[i];
int dup = tmpSum - sum;
if (dup == 0) return;
for (int i = 0; i < N; ++i) {
if (a[i] == dup) {
if (firstPos == -1)
firstPos = i;
else
secondPos = i;
}
}
return;
}
#include <vector>
using namespace std;
int FindDuplicate(vector<int>& nums) {
if (nums.size() < 1) return -1;
int slow = 0;
int fast = 0;
do {
slow = nums[slow];
fast = nums[nums[fast]];
} while (slow != fast);
fast = 0;
while (slow != fast) {
slow = nums[slow];
fast = nums[fast];
}
return slow;
}
#endif /* FindDupInt_h */
<file_sep>//
// MiscTest.cpp
// algo
//
// Created by raof01 on 7/22/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#include "gtest/gtest.h"
#include "Misc.h"
#include "ArraysMatch.hpp"
#include <string>
TEST(TestCountBinaryOneRecursive, Zero)
{
ASSERT_EQ(0, CountBinaryOneRecursive(0));
}
TEST(TestCountBinaryOneRecursive, One)
{
ASSERT_EQ(1, CountBinaryOneRecursive(1));
}
TEST(TestCountBinaryOneRecursive, Two)
{
ASSERT_EQ(1, CountBinaryOneRecursive(2));
}
TEST(TestCountBinaryOneRecursive, Three)
{
ASSERT_EQ(2, CountBinaryOneRecursive(3));
}
TEST(TestCountBinaryOneRecursive, Four)
{
ASSERT_EQ(1, CountBinaryOneRecursive(4));
}
TEST(TestCountBinaryOneRecursive, Five)
{
ASSERT_EQ(2, CountBinaryOneRecursive(5));
}
TEST(TestCountBinaryOneRecursive, Six)
{
ASSERT_EQ(2, CountBinaryOneRecursive(6));
}
TEST(TestCountBinaryOneRecursive, 0x7FFFFFFF)
{
ASSERT_EQ(31, CountBinaryOneRecursive(0x7FFFFFFF));
}
TEST(TestCountBinaryOneRecursive, 0xFFFFFFFF)
{
ASSERT_EQ(32, CountBinaryOneRecursive(0xFFFFFFFF));
}
TEST(TestCountBinaryOneRecursive, NegativeFive)
{
ASSERT_EQ(31, CountBinaryOneRecursive(-5));
}
TEST(TestGetLots, TwoEmptyLists)
{
ASSERT_EQ(0, GetLots(std::vector<int>(), std::vector<int>()).size());
}
TEST(TestGetLots, EmptyList1)
{
std::vector<int> lst = {0};
ASSERT_EQ(0, GetLots(std::vector<int>(), lst).size());
}
TEST(TestGetLots, EmptyList2)
{
std::vector<int> lst = {0};
ASSERT_EQ(0, GetLots(lst, std::vector<int>()).size());
}
TEST(TestGetLots, List2ContainsOutOfBoundPosition)
{
std::vector<int> lst1 = {10};
std::vector<int> lst2 = {10};
ASSERT_EQ(0, GetLots(lst1, lst2).size());
}
TEST(TestGetLots, List2ContainsCorrectPosition)
{
std::vector<int> lst1;
for (int i = 0; i < 10; ++i)
lst1.push_back(i);
std::vector<int> lst2 = {1, 3, 5, 7};
std::vector<int> ret = GetLots(lst1, lst2);
ASSERT_EQ(4, ret.size());
ASSERT_TRUE(VectorsMatch(lst2, ret));
}
/*
TEST(TestGetLots, Performance)
{
std::vector<int> lst1;
for (int i = 0; i < 0x7fffffff; ++i)
lst1.push_back(i);
std::vector<int> lst2(lst1);
std::vector<int> ret = GetLots(lst1, lst2);
ASSERT_EQ(0x7fffffff, ret.size());
ASSERT_TRUE(VectorsMatch(lst2, ret));
}
*/
TEST(TestInterSect, TwoEmptyLists)
{
ASSERT_EQ(0, InterSect(std::vector<int>(), std::vector<int>()).size());
}
TEST(TestInterSect, EmptyList1)
{
std::vector<int> lst = {10};
ASSERT_EQ(0, InterSect(std::vector<int>(), lst).size());
}
TEST(TestInterSect, EmptyList2)
{
std::vector<int> lst = {10};
ASSERT_EQ(0, InterSect(lst, std::vector<int>()).size());
}
TEST(TestInterSect, Intersects)
{
std::vector<int> lst1 = {1, 2, 3, 5, 6};
std::vector<int> lst2 = {1, 5, 6, 7, 8};
std::vector<int> expected = {1, 5, 6};
std::vector<int> ret;
ret = InterSect(lst1, lst2);
ASSERT_EQ(3, ret.size());
ASSERT_TRUE(VectorsMatch(expected, ret));
}
TEST(TestUnion, TwoEmptyLists)
{
ASSERT_EQ(0, Union(std::vector<int>(), std::vector<int>()).size());
}
TEST(TestUnion, EmptyList1)
{
std::vector<int> lst = {10};
std::vector<int> ret = Union(std::vector<int>(), lst);
ASSERT_EQ(1, ret.size());
ASSERT_EQ(10, ret[0]);
}
TEST(TestUnion, EmptyList2)
{
std::vector<int> lst = {10};
std::vector<int> ret = Union(lst, std::vector<int>());
ASSERT_EQ(1, ret.size());
ASSERT_EQ(10, ret[0]);
}
TEST(TestUnion, Union)
{
std::vector<int> lst1 = {1, 2, 3, 5, 6};
std::vector<int> lst2 = {1, 5, 6, 7, 8};
std::vector<int> expected = {1, 2, 3, 5, 6, 7, 8};
std::vector<int> ret;
ret = Union(lst1, lst2);
ASSERT_EQ(7, ret.size());
ASSERT_TRUE(VectorsMatch(expected, ret));
}
TEST(TestCover, Positive)
{
ASSERT_EQ(3, Cover(2));
ASSERT_EQ(153, Cover(8));
ASSERT_EQ(2131, Cover(12));
}
TEST(TestNumOfSum, Positive)
{
int a[] = {49, 49};
int b[] = {50, 50};
ASSERT_EQ(1, NumOfSum(a, 0, b, 0, 99));
ASSERT_EQ(2, NumOfSum(a, 0, b, 1, 99));
ASSERT_EQ(2, NumOfSum(a, 1, b, 0, 99));
ASSERT_EQ(4, NumOfSum(a, 1, b, 1, 99));
}
TEST(TestNumOfSum, Positive3)
{
int a[] = {52, 49};
int b[] = {50, 50};
ASSERT_EQ(2, NumOfSum(a, 1, b, 1, 99));
}
TEST(TestNumOfSum, Positive2)
{
int a[] = {49};
int b[] = {50};
ASSERT_EQ(1, NumOfSum(a, 0, b, 0, 99));
}
TEST(TestNumOfSum, Positive1)
{
int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 13};
int b[] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 50};
ASSERT_EQ(1, NumOfSum(a, 0, b, 0, 11));
ASSERT_EQ(1, NumOfSum(a, 0, b, 1, 11));
ASSERT_EQ(1, NumOfSum(a, 1, b, 0, 11));
ASSERT_EQ(2, NumOfSum(a, 1, b, 1, 11));
ASSERT_EQ(3, NumOfSum(a, 2, b, 2, 11));
ASSERT_EQ(9, NumOfSum(a, 10, b, 10, 11));
}
TEST(TestNumOfSumIter, Positive)
{
int a[] = {49, 49};
int b[] = {50, 50};
ASSERT_EQ(4, NumOfSumIter(a, b, 99));
}
TEST(TestNumOfSumIter, Positive1)
{
int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 13};
int b[] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 50};
ASSERT_EQ(9, NumOfSumIter(a, b, 11));
}
TEST(TestIsPermutationOf, StringWithLessElems)
{
ASSERT_FALSE(IsPermutationOf("abc", "a"));
}
TEST(TestIsPermutationOf, StringWithEqualNumOfElems)
{
ASSERT_FALSE(IsPermutationOf("abc", "efg"));
}
TEST(TestIsPermutationOf, StringWithMoreElems)
{
ASSERT_FALSE(IsPermutationOf("abc", "abcd"));
}
TEST(TestReplaceCharWithString, EmptyString)
{
char a[8] = {0};
char r[8] = {0};
ReplaceCharWithString(a, ' ', "%20");
ASSERT_TRUE(ArraysMatch(a, r));
}
TEST(TestReplaceCharWithString, OneCharStringWithoutSpace)
{
char a[] = "a";
char r[] = "a";
ReplaceCharWithString(a, ' ', "%20");
ASSERT_TRUE(ArraysMatch(a, r));
}
TEST(TestReplaceCharWithString, OneCharStringWithSpace)
{
char a[] = " \0 ";
char r[] = "%20";
ReplaceCharWithString(a, ' ', "%20");
ASSERT_TRUE(ArraysMatch(a, r));
}
TEST(TestReplaceCharWithString, AllSpaces)
{
char a[] = " \0 ";
char r[] = "%20%20%20%20%20%20%20%20%20%20";
ReplaceCharWithString(a, ' ', "%20");
ASSERT_TRUE(ArraysMatch(a, r));
}
TEST(TestReplaceCharWithString, Sample)
{
char a[] = "Mr <NAME>\0 ";
char r[] = "Mr%20John%20Smith";
ReplaceCharWithString(a, ' ', "%20");
ASSERT_TRUE(ArraysMatch(a, r));
}
TEST(TestReplaceCharWithString, StringBeginWithSpaces)
{
char a[] = " Mr <NAME>\0 ";
char r[] = "%20%20Mr%20John%20Smith";
ReplaceCharWithString(a, ' ', "%20");
ASSERT_TRUE(ArraysMatch(a, r));
}
TEST(TestReplaceCharWithString, StringEndWithSpaces)
{
char a[] = "Mr <NAME> \0 ";
char r[] = "Mr%20John%20Smith%20%20";
ReplaceCharWithString(a, ' ', "%20");
ASSERT_TRUE(ArraysMatch(a, r));
}
TEST(TestReplaceCharWithString, StringWithConsectiveSpaces)
{
char a[] = "Mr John Smith\0 ";
char r[] = "Mr%20%20John%20%20Smith";
ReplaceCharWithString(a, ' ', "%20");
ASSERT_TRUE(ArraysMatch(a, r));
}
TEST(TestCompressString, EmptyString)
{
std::string src;
std::string dest;
const std::string& s = CompressString(src, dest);
ASSERT_EQ(&src, &s);
}
TEST(TestCompressString, EachCharAppearsOnlyOnce)
{
std::string src = "abcdefghijk";
std::string dest;
const std::string& s = CompressString(src, dest);
ASSERT_EQ(&src, &s);
ASSERT_TRUE(dest.empty());
}
TEST(TestCompressString, SampleInput)
{
std::string src = "aabcccccaaa";
std::string dest;
std::string result = "a2b1c5a3";
const std::string& s = CompressString(src, dest);
ASSERT_TRUE(&dest == &s);
ASSERT_TRUE(result == dest);
}
TEST(TestCompressString, SampleInputLong)
{
std::string src = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";
std::string dest;
std::string result = "a100b160";
const std::string& s = CompressString(src, dest);
ASSERT_TRUE(&dest == &s);
ASSERT_TRUE(result == dest);
}
TEST(TestReplaceCharWithPattern, EmptyString)
{
char a[8] = {0};
char r[8] = {0};
ReplaceCharWithPattern(a, ' ', "%20");
ASSERT_TRUE(ArraysMatch(a, r));
}
TEST(TestReplaceCharWithPattern, OneCharStringWithoutSpace)
{
char a[] = "a";
char r[] = "a";
ReplaceCharWithPattern(a, ' ', "%20");
ASSERT_TRUE(ArraysMatch(a, r));
}
TEST(TestReplaceCharWithPattern, OneCharStringWithSpace)
{
char a[] = " \0 ";
char r[] = "%20";
ReplaceCharWithPattern(a, ' ', "%20");
ASSERT_TRUE(ArraysMatch(a, r));
}
TEST(TestReplaceCharWithPattern, AllSpaces)
{
char a[] = " \0 ";
char r[] = "%20%20%20%20%20%20%20%20%20%20";
ReplaceCharWithPattern(a, ' ', "%20");
ASSERT_TRUE(ArraysMatch(a, r));
}
TEST(TestReplaceCharWithPattern, Sample)
{
char a[] = "Mr <NAME>\0 ";
char r[] = "Mr%20John%20Smith";
ReplaceCharWithPattern(a, ' ', "%20");
ASSERT_TRUE(ArraysMatch(a, r));
}
TEST(TestReplaceCharWithPattern, StringBeginWithSpaces)
{
char a[] = " <NAME>\0 ";
char r[] = "%20%20Mr%20John%20Smith";
ReplaceCharWithPattern(a, ' ', "%20");
ASSERT_TRUE(ArraysMatch(a, r));
}
TEST(TestReplaceCharWithPattern, StringEndWithSpaces)
{
char a[] = "<NAME> \0 ";
char r[] = "Mr%20John%20Smith%20%20";
ReplaceCharWithPattern(a, ' ', "%20");
ASSERT_TRUE(ArraysMatch(a, r));
}
TEST(TestReplaceCharWithPattern, StringWithConsectiveSpaces)
{
char a[] = "Mr John Smith\0 ";
char r[] = "Mr%20%20John%20%20Smith";
ReplaceCharWithPattern(a, ' ', "%20");
ASSERT_TRUE(ArraysMatch(a, r));
}
TEST(TestIsUnique, Sample)
{
std::string a = "MrJohnSmith";
ASSERT_FALSE(IsUnique(a));
}
TEST(TestIsUnique, EmptyString)
{
std::string a = "";
ASSERT_TRUE(IsUnique(a));
}
TEST(TestIsUnique, UniqueString)
{
std::string a = "abcdefghijklmnopqrstuvwxyz";
ASSERT_TRUE(IsUnique(a));
}
TEST(TestIsRotate, Self)
{
std::string a = "abcdefghijklmnopqrstuvwxyz";
ASSERT_TRUE(IsRotate(a, a));
}
TEST(TestIsRotate, Negative)
{
std::string a = "abcde";
std::string b = "defgh";
ASSERT_FALSE(IsRotate(a, b));
}
TEST(TestIsRotate, EmptyString)
{
std::string a = "";
std::string b = "";
ASSERT_FALSE(IsRotate(a, b));
}
TEST(TestIsRotate, StringsWithDifferentLength)
{
std::string a = "abcd";
std::string b = "abc";
ASSERT_FALSE(IsRotate(a, b));
}
TEST(TestIsRotate, Positive)
{
std::string a = "waterbottle";
std::string b = "erbottlewat";
ASSERT_TRUE(IsRotate(a, b));
}
TEST(TestSortStackUsingStack, SampleInput) {
std::vector<int> a;
int s[] = {0, 2, 0, 4, 8, 2, 5};
std::vector<int> r = {0, 0, 2, 2, 4, 5, 8};
for (size_t i = 0; i < sizeof (s) / sizeof (int); ++i)
a.push_back(s[i]);
SortStackUsingStack(a);
ASSERT_TRUE(VectorsMatch(r, a));
}
TEST(TestSortStackUsingStack, EmptyStack) {
std::vector<int> a;
SortStackUsingStack(a);
ASSERT_TRUE(a.empty());
}
TEST(TestSortStackUsingStack, StackWithOneElem) {
std::vector<int> a;
a.push_back(10);
SortStackUsingStack(a);
ASSERT_EQ(10, a.back());
}
TEST(TestSortStackUsingStack, StackWithAllSameValue) {
std::vector<int> a;
for (int i = 0; i < 100; ++i)
a.push_back(10);
SortStackUsingStack(a);
ASSERT_EQ(10, a.back());
ASSERT_EQ(100, a.size());
}
TEST(TestSortStackUsingStack, StackAlreadyOrdered) {
std::vector<int> a;
for (int i = 0; i < 100; ++i)
a.push_back(i);
SortStackUsingStack(a);
std::vector<int> r;
for (int i = 0; i < 100; ++i)
r.push_back(i);
ASSERT_TRUE(VectorsMatch(r, a));
}
TEST(TestSortStackUsingStack, StackReverseOrdered) {
std::vector<int> a;
for (int i = 99; i >= 0; --i)
a.push_back(i);
SortStackUsingStack(a);
std::vector<int> r;
for (int i = 0; i < 100; ++i)
r.push_back(i);
ASSERT_TRUE(VectorsMatch(r, a));
}
TEST(TestSortStackUsingStackTo, SampleInput) {
std::vector<int> a;
int s[] = {0, 2, 0, 4, 8, 2, 5};
std::vector<int> r = {0, 0, 2, 2, 4, 5, 8};
for (size_t i = 0; i < sizeof (s) / sizeof (int); ++i)
a.push_back(s[i]);
std::vector<int> res;
SortStackUsingStack(a, res);
ASSERT_TRUE(VectorsMatch(r, res));
}
TEST(TestSortStackUsingStackTo, EmptyStack) {
std::vector<int> a;
std::vector<int> res;
SortStackUsingStack(a, res);
ASSERT_TRUE(res.empty());
}
TEST(TestSortStackUsingStackTo, StackWithOneElem) {
std::vector<int> a;
a.push_back(10);
std::vector<int> res;
SortStackUsingStack(a, res);
ASSERT_EQ(10, res.back());
ASSERT_EQ(1, res.size());
}
TEST(TestSortStackUsingStackTo, StackWithAllSameValue) {
std::vector<int> a;
for (int i = 0; i < 100; ++i)
a.push_back(10);
std::vector<int> res;
SortStackUsingStack(a, res);
ASSERT_EQ(10, res.back());
ASSERT_EQ(100, res.size());
}
TEST(TestSortStackUsingStackTo, StackAlreadyOrdered) {
std::vector<int> a;
for (int i = 0; i < 100; ++i)
a.push_back(i);
std::vector<int> res;
SortStackUsingStack(a, res);
std::vector<int> r;
for (int i = 0; i < 100; ++i)
r.push_back(i);
ASSERT_TRUE(VectorsMatch(r, res));
}
TEST(TestSortStackUsingStackTo, StackReverseOrdered) {
std::vector<int> a;
for (int i = 99; i >= 0; --i)
a.push_back(i);
std::vector<int> res;
SortStackUsingStack(a, res);
std::vector<int> r;
for (int i = 0; i < 100; ++i)
r.push_back(i);
ASSERT_TRUE(VectorsMatch(r, res));
}
TEST(TestMergeTwoSortedArrays, SampleInput) {
std::vector<int> a = {1, 3, 5, 7, 9, 11, 13};
std::vector<int> b = {2, 4, 6, 8};
MergeTwoSortedArrays(a, b);
std::vector<int> ret = {1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 13};
ASSERT_TRUE(VectorsMatch(ret, a));
}
<file_sep>//
// Created by raof01 on 9/20/15.
//
#ifndef ALGO_BITMANIPULATION_H
#define ALGO_BITMANIPULATION_H
#include <vector>
bool IsBitSet(unsigned int val, int pos);
bool SetBit(unsigned int&, int);
bool ClearBit(unsigned int&, int);
bool ClearBitsMSBThroughInclusive(unsigned int &, int);
bool ClearBitsLSBThroughInclusive(unsigned int&, int);
// bool DoubleTo32BitBinary(double, std::vector<unsigned char>&);
int CountSetBits(int v);
int BitsNeededToConvert(int, int);
bool NextPositive(int, unsigned int&, unsigned int&);
auto SwapEvenAndOddBits(unsigned int v) -> decltype(v);
#endif //ALGO_BITMANIPULATION_H
<file_sep>//
// LeetCodeProblemsTest.cpp
// algo
//
// Created by <NAME> on 10/12/15.
// Copyright © 2015 raof01. All rights reserved.
//
#include "LeetCodeProblems.h"
#include "gtest/gtest.h"
TEST(TestAddDigits, SampleInput) {
ASSERT_EQ(2, AddDigits::addDigits(38));
ASSERT_EQ(6, AddDigits::addDigits(12345));
ASSERT_TRUE(NimGame::canWinNim(3));
ASSERT_FALSE(NimGame::canWinNim(8));
}
TEST(TestSumOfFactorialsTo, SampleInputs)
{
ASSERT_EQ(-10, SumOfFactorialsTo::sumOfFactorialsTo(-10));
ASSERT_EQ(1, SumOfFactorialsTo::sumOfFactorialsTo(0));
ASSERT_EQ(1, SumOfFactorialsTo::sumOfFactorialsTo(1));
ASSERT_EQ(3, SumOfFactorialsTo::sumOfFactorialsTo(2));
ASSERT_EQ(9, SumOfFactorialsTo::sumOfFactorialsTo(3));
ASSERT_EQ(33, SumOfFactorialsTo::sumOfFactorialsTo(4));
ASSERT_EQ(153, SumOfFactorialsTo::sumOfFactorialsTo(5));
}
TEST(TestHappyNumber, SampleInputs)
{
ASSERT_TRUE(HappyNumber::isHappyNumber(19));
ASSERT_TRUE(HappyNumber::isHappyNumber(1));
ASSERT_FALSE(HappyNumber::isHappyNumber(18));
ASSERT_FALSE(HappyNumber::isHappyNumber(2));
}
TEST(TestGeneratePascalNumber, SampleInputs)
{
generatePascalNumber(1);
}
vector<int> getRow(int rowIndex) {
vector<int> v;
if (rowIndex < 0) return v;
v.push_back(1);
if (rowIndex == 0) {
return v;
}
for (int c = 1; c <= rowIndex; ++c) {
vector<int> tmp = vector<int>(v);
v.resize(v.size() + 1);
int j = 1;
for (; j < c; ++j) {
v[j] = tmp[j] + tmp[j - 1];
}
v[j] = 1;
}
return v;
}
TEST(tt, sa)
{
getRow(0);
getRow(1);
getRow(2);
getRow(3);
getRow(4);
getRow(5);
getRow(6);
}
class Solution {
public:
static int strStr(string haystack, string needle) {
if (needle.length() == 0) return 0;
if (haystack.length() == 0) return -1;
vector<int> v = vector<int>(needle.length());
SetupBackTrackTable(needle, v);
int pStr = 0;
int pPattern = 0;
int patternLen = needle.length();
while (pStr < haystack.length() && pPattern < patternLen) {
if (pPattern == -1 || haystack[pStr] == needle[pPattern]) {
++pStr;
++pPattern;
} else {
pPattern = v[pPattern];
}
}
if (pPattern == patternLen) return pStr - pPattern;
return -1;
}
private:
static void SetupBackTrackTable(string pattern, vector<int>& btTable) {
int cur = 0;
int prev = -1;
int len = pattern.length();
btTable[0] = -1;
while (cur < len) {
if (prev == -1 || pattern[cur] == pattern[prev]) {
++prev;
++cur;
if (cur < len) btTable[cur] = prev;
} else {
prev = btTable[prev];
}
}
}
};
class Solution1 {
public:
static int countPrimes(int n) {
if (n < 3) return 0;
bool* sieve = new bool[n];
for (int i = 0; i < n; ++i) sieve[n] = true;
sieve[0] = false;
sieve[1] = false;
int cnt = 0;
// Count primes on-the-fly
for (int i = 2; i < n; ++i) {
if (!sieve[i]) continue;
++cnt;
for (int j = i + i; j < n; j += i) {
sieve[j] = false;
}
}
delete [] sieve;
return cnt;
}
};
class Solution3 {
public:
static vector<int> singleNumber(vector<int>& nums) {
int xorResult = 0;
for (int i = 0; i < nums.size(); ++i)
xorResult ^= nums[i];
if (xorResult == 0) return vector<int>();
int mask = 1;
/* find the position of set bit */
while ((mask & xorResult) == 0)
mask <<= 1;
int result1 = 0;
for (int i = 0; i < nums.size(); ++i) {
/* calculate the xor result of numbers with nth bit set*/
if (nums[i] & mask)
result1 ^= nums[i];
}
return vector<int>{result1, result1 ^ xorResult};
}
};
class NumArray {
public:
NumArray(vector<int> &nums) : v(nums) {
v = nums;
for (int i = 1; i < v.size(); ++i)
v[i] += v[i - 1];
}
int sumRange(int i, int j) {
if (i == 0) return v[j];
return v[j] - v[i - 1];
}
private:
vector<int>& v;
};
TEST(TT, ss)
{
vector<int> v = {-1, 0};
Solution3::singleNumber(v);
}
TEST(T1, s)
{
int n = 10;
int cnt = 0;
while (n--) ++cnt;
int n1 = 10;
int cnt1 = 0;
while (--n1) ++cnt1;
cout << cnt << endl;
cout << cnt1 << endl;
}
TEST(MergeToSorted, positive)
{
ListNode* l1 = new ListNode(10);
ListNode* l2 = new ListNode(1, l1);
ListNode* l3 = new ListNode(8);
ListNode* l4 = new ListNode(13, l3);
ListNode* l5 = new ListNode(7, l4);
ListNode* l = MergeToSorted(l2, l5);
while (l != nullptr)
{
ListNode* d = l;
cout << d->val << endl;
l = l->next;
delete d;
}
}
<file_sep>//
// SelectionSort.h
// algo
//
// Created by raof01 on 8/1/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#ifndef algo_SelectionSort_h
#define algo_SelectionSort_h
template <typename Comparable>
class SelectionSorter
{
public:
template <size_t N>
static void Sort(Comparable (&input)[N]);
static void Sort(Comparable* input, size_t N);
private:
static void SortImpl(Comparable* input, size_t N);
};
template <typename Comparable>
template <size_t N>
void SelectionSorter<Comparable>::Sort(Comparable (&input)[N])
{
SortImpl(input, N);
}
template <typename Comparable>
void SelectionSorter<Comparable>::Sort(Comparable* input, size_t N)
{
SortImpl(input, N);
}
template <typename Comparable>
void SelectionSorter<Comparable>::SortImpl(Comparable* input, size_t N)
{
for (size_t sorted = 0; sorted < N; ++sorted)
{
size_t min = sorted;
for (size_t unsorted = sorted + 1; unsorted < N; ++unsorted)
{
if (input[unsorted] < input[min])
min = unsorted;
}
std::swap(input[sorted], input[min]);
}
}
#endif
<file_sep>#include <unordered_map>
#include "LinkedListWithExtra.h"
using namespace std;
NodeWithExtra* Insert(NodeWithExtra* h, int v) {
NodeWithExtra* p = new NodeWithExtra(v);
p->next = h;
return p;
}
void Destroy(NodeWithExtra*& h) {
while (h != nullptr) {
NodeWithExtra* p = h;
h = h->next;
delete p;
}
}
NodeWithExtra* CopyNodeWithExtras(const NodeWithExtra* h, unordered_map<const NodeWithExtra*, NodeWithExtra*>& m) {
NodeWithExtra* l = nullptr;
NodeWithExtra* cur = nullptr;
while (h != nullptr) {
NodeWithExtra* p = new NodeWithExtra(*h);
if (h->extra != nullptr)
m.insert(make_pair(h->extra, p));
h = h->next;
if (l == nullptr) {
l = p;
cur = l;
}
else {
cur->next = p;
cur = cur->next;
}
}
return l;
}
void SetupExtra(const NodeWithExtra* hOld, NodeWithExtra* hNew, const unordered_map<const NodeWithExtra*, NodeWithExtra*>& m) {
while (hOld != nullptr && hNew != nullptr) {
unordered_map<const NodeWithExtra*, NodeWithExtra*>::const_iterator iter = m.find(hOld);
if (iter != m.end())
iter->second->extra = hNew;
hOld = hOld->next;
hNew = hNew->next;
}
}
NodeWithExtra* Copy(const NodeWithExtra* h) {
unordered_map<const NodeWithExtra*, NodeWithExtra*> m;
NodeWithExtra* l = CopyNodeWithExtras(h, m);
SetupExtra(h, l, m);
return l;
}
<file_sep>//
// HeapSort.hpp
// algo
//
// Created by raof01 on 5/6/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#ifndef algo_HeapSort_hpp
#define algo_HeapSort_hpp
#include <stdio.h>
#include "Helpers.h"
template <typename Comparable>
class HeapSorter
{
public:
static void Sort(Comparable *a, size_t N);
static void SortNonRecursive(Comparable *a, size_t N);
template <size_t N>
static void Sort(Comparable (&a)[N]);
template <size_t N>
static void SortNonRecursive(Comparable (&a)[N]);
static void SortUsingSink(Comparable *a, size_t N);
template <size_t N>
static void SortUsingSink(Comparable (&a)[N]);
// For testing
static void MaxHeapify(Comparable *a, size_t root, size_t heapSize);
static void MaxHeapifyIter(Comparable *a, size_t root, size_t heapSize);
template <size_t N>
static void MaxHeapify(Comparable (&a)[N], size_t root, size_t heapSize = N);
template <size_t N>
static void MaxHeapifyIter(Comparable (&a)[N], size_t root, size_t heapSize = N);
private:
static void BuildMaxHeap(Comparable *a, size_t N);
struct Iter {};
static void BuildMaxHeap(Comparable *a, size_t N, const Iter&);
};
// Less code and clear meaning using sink
template <typename T>
void HeapSorter<T>::SortUsingSink(T *a, size_t N)
{
for (int i = static_cast<int>(Parent(N - 1)); i >= 0; --i)
Sink(a, i, N);
size_t i = N;
while (i != 0)
{
std::swap(a[0], a[--i]);
Sink(a, 0, i);
}
}
template <typename T>
template <size_t N>
void HeapSorter<T>::SortUsingSink(T (&a)[N])
{
SortUsingSink(a, N);
}
// Recursive
template <typename T>
void HeapSorter<T>::MaxHeapify(T *a, size_t root, size_t heapSize)
{
// Recursively make every node to have the property:
// its value is the maximun of its 2 children and itself
size_t l = Left(root);
size_t r = Right(root);
size_t largest = root;
if (l < heapSize && a[l] >= a[largest])
largest = l;
if (r < heapSize && a[r] >= a[largest])
largest = r;
if (largest != root)
{
std::swap(a[largest], a[root]);
MaxHeapify(a, largest, heapSize);
}
}
// Iterative
template <typename T>
void HeapSorter<T>::MaxHeapifyIter(T *a, size_t root, size_t heapSize)
{
size_t largest = root;
while (largest < heapSize)
{
size_t l = Left(largest), r = Right(largest), savedLargest = largest;
if (l < heapSize && a[l] >= a[largest])
largest = l;
if (r < heapSize && a[r] >= a[largest])
largest = r;
if (largest != savedLargest)
std::swap(a[largest], a[savedLargest]);
else
break;
}
}
template <typename T>
void HeapSorter<T>::BuildMaxHeap(T *a, size_t N)
{
for (int i = static_cast<int>(Parent(N - 1)); i >= 0; --i)
MaxHeapify(a, i, N);
}
template <typename T>
void HeapSorter<T>::BuildMaxHeap(T *a, size_t N, const Iter&)
{
for (int i = static_cast<int>(Parent(N - 1)); i >= 0; --i)
MaxHeapifyIter(a, i, N);
}
template <typename T>
void HeapSorter<T>::Sort(T *a, size_t N)
{
BuildMaxHeap(a, N);
for (size_t i = N - 1; i != 0; --i)
{
std::swap(a[i], a[0]);
MaxHeapify(a, 0, i);
}
}
template <typename T>
void HeapSorter<T>::SortNonRecursive(T *a, size_t N)
{
BuildMaxHeap(a, N, Iter());
for (size_t i = N - 1; i != 0; --i)
{
std::swap(a[i], a[0]);
MaxHeapifyIter(a, 0, i);
}
}
template <typename T>
template <size_t N>
void HeapSorter<T>::Sort(T (&a)[N])
{
Sort(a, N);
}
template <typename T>
template <size_t N>
void HeapSorter<T>::SortNonRecursive(T (&a)[N])
{
SortNonRecursive(a, N);
}
template <typename T>
template <size_t N>
void HeapSorter<T>::MaxHeapify(T (&a)[N], size_t root, size_t heapSize)
{
MaxHeapifyIter(a, root, heapSize);
}
template <typename T>
template <size_t N>
void HeapSorter<T>::MaxHeapifyIter(T (&a)[N], size_t root, size_t heapSize)
{
MaxHeapify(a, root, heapSize);
}
#endif
<file_sep>//
// ArraysMatch.hpp
// algo
//
// Created by raof01 on 5/5/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#ifndef algo_ArraysMatch_hpp
#define algo_ArraysMatch_hpp
#include <vector>
template<typename T, size_t size>
::testing::AssertionResult ArraysMatch(const T (&expected)[size],
const T (&actual)[size]){
for (size_t i(0); i < size; ++i){
if (expected[i] != actual[i]){
return ::testing::AssertionFailure() << "array[" << i
<< "] (" << actual[i] << ") != expected[" << i
<< "] (" << expected[i] << ")";
}
}
return ::testing::AssertionSuccess();
}
template<typename T, size_t size>
::testing::AssertionResult ArrayAndPointerMatch(const T (&expected)[size],
const T *actual){
for (size_t i(0); i < size; ++i){
if (expected[i] != actual[i]){
return ::testing::AssertionFailure() << "array[" << i
<< "] (" << actual[i] << ") != expected[" << i
<< "] (" << expected[i] << ")";
}
}
return ::testing::AssertionSuccess();
}
template<typename T, size_t sz1, size_t sz2>
::testing::AssertionResult ArraysMatch(const T (&expected)[sz1][sz2],
const T (&actual)[sz1][sz2]){
for (size_t j = 0; j < sz1; ++j) {
for (size_t i(0); i < sz2; ++i){
if (expected[j][i] != actual[j][i]){
return ::testing::AssertionFailure() << "array[" << j << "][" << i
<< "] (" << actual[j][i] << ") != expected[" << j << "][" << i
<< "] (" << expected[j][i] << ")";
}
}
}
return ::testing::AssertionSuccess();
}
template<typename T>
::testing::AssertionResult VectorsMatch(const std::vector<T> &expected,
const std::vector<T> &actual){
if (expected.size() != actual.size())
return ::testing::AssertionFailure() << "actual size " << actual.size()
<< " != expected size " << expected.size();
for (size_t i(0); i < expected.size(); ++i){
if (expected[i] != actual[i]){
return ::testing::AssertionFailure() << "actual[" << i
<< "] (" << actual[i] << ") != expected[" << i
<< "] (" << expected[i] << ")";
}
}
return ::testing::AssertionSuccess();
}
#endif
<file_sep>//
// wob.h
// algo
//
// Created by raof01 on 8/17/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#ifndef algo_wob_h
#define algo_wob_h
#include <stdio.h>
#include <string>
#include <vector>
using std::string;
using std::vector;
/*******************************************************************************
* Notes: The block comments like this one are to documenting my thoughs
* and assumptions.
******************************************************************************/
/*******************************************************************************
* Some thoughts about class Employee:
* 1. It will be better to initialize Employee::reports in initialization list
* 2. Employee::getId() and Employee::getReports() could be a const function
* because the getter will not modify "this"
* 3. We may not want client code to modify Employee::reports, so the return
* type could be const vector<Employee*>&
******************************************************************************/
// IMPORTANT: DO NOT MODIFY THIS CLASS
class Employee {
private:
const int id;
const string name;
vector<Employee*> reports;
public:
Employee(int id, string name) : id(id), name(name) {
}
int getId() {
return id;
}
vector<Employee*>& getReports() {
return reports;
}
void addReport(Employee* employee) {
reports.push_back(employee);
}
};
/*******************************************************************************
* Helper function. It would be better to provide overloaded operator == by
* class Employee. Because the client code doesn't need to know how to compare
* two instances of Employee.
******************************************************************************/
/*
* Compare two instances of Employee.
* @param lhs
* @param rhs
* @return true if two employee is the same one, false otherwise
*/
bool equal(Employee* lhs, Employee* rhs)
{
if (lhs == NULL || rhs == NULL) return false;
return lhs->getId() == rhs->getId();
}
/*******************************************************************************
* Assumptions:
* - The org chart could be considered as a tree.
* - closestCommonManager() should always use a manager as first argument.
* - Employee ID is unique, but employee name is not
* - One employee reports no more than 1 manager
* - One manager doesn't report to the employee of his/her reports
* - One employee doesn't report to himself/herself
* - The common manager of same employee will be himself/herself if he/she
* is a manager
* - If employee e1 is a manager and the other, e2 is in his/her report
* tree, then the common manager is e1.
* - The std::vector is same on all implementations
******************************************************************************/
/*
* Find the path in the org chart, recursively.
* This is a Depth First Search
* @param root: the root of org chart tree
* @param employee: the employe to find in the org chart tree
* @param path: the report line of employee in reverse order.
* e.g. CEO->Mgr3->Mgr2->Mgr1->employee
* @return true if the employee is in the org chart, false otherwise
*/
// N employees in org chart
// Runtime complexity: O(N). Spatial complexity: O(N)
// - If employee is not in the org chart, the runtime and spatial
// complexity is N
// - If only one manager, the runtime and spatial complexity is N
// - If one manager has exact one report, the runtime and spatial
// complexity is N
// Notes:
// - The std::vector<T>::push_back(), std::vector<T>::push_back(), and
// std::vector<T>::rbegin() run in constant time, so it's O(1)
bool find(Employee* root, Employee* employee, vector<Employee*>& path)
{
if (root == NULL || employee == NULL) return false;
path.push_back(root);
if (equal(root, employee)) return true;
// The employee may be in reports of the root.
const vector<Employee*>& reports = root->getReports();
// Otherwise find in each report
for (vector<Employee*>::const_iterator iter = reports.begin();
iter != reports.end(); ++iter)
{
if (find(*iter, employee, path))
return true;
else
// Because each report is pushed to the stack,
// then when not found, the report is not in the path
path.pop_back();
}
// Not found in all reports
return false;
}
bool find(Employee* root, Employee* e, Employee*& parent) {
if (root == NULL || e == NULL) return false;
if (equal(root, e)) return true;
const vector<Employee*>& reports = root->getReports();
for (vector<Employee*>::const_iterator iter = reports.begin();
iter != reports.end(); ++iter) {
if (find (*iter, e, parent)) {
parent = *iter;
return true;
}
}
return false;
}
/*
* Find the path in the org chart, iteratively.
* This is a Breath First Search
* @param root: the root of org chart tree
* @param employee: the employe to find in the org chart tree
* @param path: the report line of employee in reverse order.
* e.g. CEO->Mgr3->Mgr2->Mgr1->employee
* @return true if the employee is in the org chart, false otherwise
*/
// N employees in org chart
// Runtime complexity: O(N). Spatial complexity: O(N)
// - If employee is not in the org chart, the runtime and spatial
// complexity is N
// - If only one manager, the runtime and spatial complexity is N
// - If one manager has exact one report, the runtime and spatial
// complexity is N
bool findNonRecursive(Employee* root, Employee* employee, vector<Employee*>& path)
{
if (root == NULL || employee == NULL) return false;
path.push_back(root);
vector<Employee*> triedReports = vector<Employee*>();
while(!path.empty())
{
Employee* currentParent = *path.rbegin();
if (equal(currentParent, employee)) return true;
// Find in reports
const vector<Employee*>& reports = currentParent->getReports();
for (vector<Employee*>::const_iterator iter = reports.begin();
iter != reports.end(); ++iter)
triedReports.push_back((*iter));
while (!triedReports.empty())
{
Employee* current = *triedReports.rbegin();
if (equal(current, employee))
{
path.push_back(current);
return true;
}
else
{
// Managers that may be on the path
if (current->getReports().size() != 0)
path.push_back(current);
}
triedReports.pop_back();
}
// Not found in reports.
if (equal(currentParent, *path.rbegin()))
{
path.clear();
return false;
}
}
return false;
}
bool isDirectReport(Employee* mgr, Employee* e) {
vector<Employee*> reports = mgr->getReports();
for (int i = 0; i < reports.size(); ++i) {
if (equal(reports[i], e))
return true;
}
return false;
}
bool InOrg(Employee* mgr, Employee* e) {
if (mgr == NULL || e == NULL) return false;
if (equal(mgr, e)) return true;
vector<Employee*> reports = mgr->getReports();
for (int i = 0; i < reports.size(); ++i) {
if (InOrg(reports[i], e))
return true;
}
return false;
}
Employee* CommonAncestor(Employee* root, Employee* e1, Employee* e2) {
if (root == NULL) return NULL;
if (equal(e1, root) && equal(e2, root)) return root; // the employees to search are root
vector<Employee*> reports = root->getReports();
int cnt = 0;
vector<Employee*> parents;
for (int i = 0; i < reports.size(); ++i) {
Employee* r = CommonAncestor(reports[i], e1, e2);
if (r != NULL) {
if (!equal(r, e1) && !equal(r, e2))
return r;
else {
++cnt;
parents.push_back(r);
}
}
}
Employee* p = NULL;
if (cnt == 2 || (cnt == 1 && equal(e1, e2))) return root;
else if (equal(root, e1) || equal(root, e2)) return root;
else {
while (!parents.empty()) {
p = parents.back();
if (p != NULL)
break;
parents.pop_back();
}
}
return p;
}
Employee* closestCommonManagerHelper(Employee* root, Employee* e1, Employee* e2) {
if (root == NULL) return NULL;
Employee* parent1 = NULL;
if (!find(root, e1, parent1)) return NULL;
Employee* parent2 = NULL;
if (!find(root, e2, parent2)) return NULL;
if (parent1 == NULL || parent2 == NULL || parent1 != parent2) return root;
if (equal(e1, e2) && isDirectReport(root, e1)) return root;
return closestCommonManagerHelper(parent1, e1, e2);
}
/*
* Read the attached PDF for more explanation about the problem
* Note: Don't modify the signature of this function
* @param ceo
* @param firstEmployee
*
* @param secondEmployee
*
* @return common manager for both the employee that is closest to them.
*/
// N employees in org chart
// Runtime complexity: O(N). Spatial complexity: O(2N)
// - Call to find() or findNonRecursive() twice, so the spatial
// complexity is O(2N)
static Employee* closestCommonManager(Employee* ceo, Employee* firstEmployee, Employee* secondEmployee) {
if (!InOrg(ceo, firstEmployee) || !InOrg(ceo, secondEmployee)) return NULL;
return CommonAncestor(ceo, firstEmployee, secondEmployee);
#if 0
if (equal(ceo, firstEmployee) && equal(ceo, secondEmployee)) return ceo;
return closestCommonManagerHelper(ceo, firstEmployee, secondEmployee);
//#else
vector<Employee*> pathToE1 = vector<Employee*>();
// The recursive version of find() can be used.
// if (!find(ceo, firstEmployee, pathToE1))
if (!findNonRecursive(ceo, firstEmployee, pathToE1))
return NULL;
vector<Employee*> pathToE2 = vector<Employee*>();
// The recursive verions of find() can be used.
// if (!find(ceo, secondEmployee, pathToE2))
if (!findNonRecursive(ceo, secondEmployee, pathToE2))
return NULL;
size_t shortestPath = std::min(pathToE1.size(), pathToE2.size());
size_t parentPos = 0;
for (; parentPos < shortestPath; ++parentPos)
{
if (!equal(pathToE1[parentPos], pathToE2[parentPos]))
break;
}
// Ignore the same employee
if (equal(firstEmployee, secondEmployee) && shortestPath > 1)
--parentPos;
Employee* ret = pathToE1[--parentPos];
// Assumption: Only manager will be returned. so:
// closestCommonManager(Bob, Bob, Bob) should return NULL
return ret->getReports().size() != 0 ? ret : NULL;
#endif
}
#endif
<file_sep>//
// Helpers.h
// algo
//
// Created by raof01 on 8/12/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#ifndef algo_Helpers_h
#define algo_Helpers_h
inline size_t Left(size_t pos)
{
return 2 * pos + 1; // 0-based
}
inline size_t Right(size_t pos)
{
return 2 * pos + 2; // 0-based
}
inline size_t Parent(size_t pos)
{
if (pos == 0) return 0; // in case of 0xFFFFFFFF
return (pos - 1) / 2; // 0-based
}
template <typename Comparable>
void Swim(Comparable *input, size_t pos)
{
while (pos != 0 && input[pos] > input[Parent(pos)])
{
std::swap(input[pos], input[Parent(pos)]);
pos = Parent(pos);
}
}
template <typename Comparable>
void Sink(Comparable* a, size_t root, size_t heapSize)
{
size_t largest = root;
while (Left(root) < heapSize)
{
if (a[Left(root)] > a[root]) largest = Left(root);
if (Right(root) < heapSize && a[largest] < a[Right(root)])
largest = Right(root);
if (root == largest) break;
std::swap(a[root], a[largest]);
root = largest;
}
}
#endif
<file_sep>//
// MaxSumInTriangleTest.cpp
// algo
//
// Created by raof01 on 8/15/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#include "gtest/gtest.h"
#include "MaxSumInTriangle.h"
const int a[][5] =
{
{3, 0, 0, 0, 0},
{7, 1, 0, 0, 0},
{2, 5, 8, 0, 0},
{0, 20, 11, 6, 0},
{4, 4, 3, 3, 2},
};
TEST(TestMaxSum, ColumnOutOfRange)
{
ASSERT_EQ(-1, MaxSum(a, 0, 1));
}
TEST(TestMaxSum, RowOutOfRange)
{
ASSERT_EQ(-1, MaxSum(a, 9, 0));
}
TEST(TestMaxSum, Positive)
{
ASSERT_EQ(4, MaxSum(a, 4, 0));
ASSERT_EQ(4, MaxSum(a, 4, 1));
ASSERT_EQ(3, MaxSum(a, 4, 2));
ASSERT_EQ(3, MaxSum(a, 4, 3));
ASSERT_EQ(2, MaxSum(a, 4, 4));
ASSERT_EQ(39, MaxSum(a, 0, 0));
}
TEST(TestMaxSumIter, ColumnOutOfRange)
{
ASSERT_EQ(-1, MaxSumIter(a, 0, 1));
}
TEST(TestMaxSumIter, RowOutOfRange)
{
ASSERT_EQ(-1, MaxSumIter(a, 9, 0));
}
TEST(TestMaxSumIter, Positive)
{
ASSERT_EQ(4, MaxSumIter(a, 4, 0));
ASSERT_EQ(4, MaxSumIter(a, 4, 1));
ASSERT_EQ(3, MaxSumIter(a, 4, 2));
ASSERT_EQ(3, MaxSumIter(a, 4, 3));
ASSERT_EQ(2, MaxSumIter(a, 4, 4));
ASSERT_EQ(39, MaxSumIter(a, 0, 0));
ASSERT_EQ(22, MaxSumIter(a, 2, 2));
ASSERT_EQ(29, MaxSumIter(a, 2, 1));
ASSERT_EQ(30, MaxSumIter(a, 1, 1));
}
<file_sep>//
// Created by raof01 on 9/13/15.
//
#include "CSingleLinkedList.h"
#include "gtest/gtest.h"
#include <memory>
#include "Visitor.hpp"
using std::make_shared;
class PrintVisitor : public Visitor<int, false>
{
public:
void Visit(int v) override
{
std::cerr << v << " ";
}
};
TEST(TestNode, Creation)
{
auto n = Node<int>(10);
ASSERT_TRUE(n.next == nullptr);
}
TEST(TestNode, Concatenation)
{
auto n1 = Node<int>(10);
ASSERT_TRUE(n1.next == nullptr);
{
auto n2 = Node<int>(9, n1);
ASSERT_TRUE(n2.next != nullptr);
}
ASSERT_TRUE(n1.next == nullptr);
}
TEST(TestSingleLinkedList, UseAppend)
{
auto l = SingleLinkedList<int>();
for (auto i = 0; i < 5; ++i)
l.Append(i);
std::cerr << std::endl;
auto visitor = PrintVisitor();
l.Traverse(visitor);
}
TEST(TestCSingleLinkedList, Append) {
CSingleLinkedList l;
ASSERT_EQ(nullptr, l.head);
int a[] = {3, 5, 7, 9};
for (int i = 0; i < sizeof (a) / sizeof (int); ++i)
l.Append(a[i]);
CNode* p = l.head;
for (int i = 0; i < sizeof (a) / sizeof (int); ++i) {
ASSERT_EQ(a[i], p->val);
p = p->next;
}
l.Destroy();
}
TEST(TestCSingleLinkedList, PartitionOnEmptyList) {
CSingleLinkedList l;
l.Partition(10);
ASSERT_EQ(nullptr, l.head);
l.Destroy();
}
TEST(TestCSingleLinkedList, PartitionOnListWithOneElem) {
CSingleLinkedList l;
l.Append(10);
l.Partition(1000);
ASSERT_EQ(10, l.head->val);
l.Destroy();
}
TEST(TestCSingleLinkedList, PartitionOnListWithTwoElemsAllLagerThanPartitionValue) {
CSingleLinkedList l;
l.Append(10).Append(20);
l.Partition(1);
ASSERT_EQ(20, l.head->val);
l.Destroy();
}
TEST(TestCSingleLinkedList, PartitionOnListWithTwoElemsAllLessThanPartitionValue) {
CSingleLinkedList l;
l.Append(10).Append(20);
l.Partition(30);
ASSERT_EQ(10, l.head->val);
l.Destroy();
}
TEST(TestCSingleLinkedList, PartitionOnListWithTwoElemsAscendingAndPartitionValueInBetween) {
CSingleLinkedList l;
l.Append(10).Append(20);
l.Partition(15);
ASSERT_EQ(10, l.head->val);
l.Destroy();
}
TEST(TestCSingleLinkedList, PartitionOnListWithTwoElemsDescendingAndPartitionValueInBetween) {
CSingleLinkedList l;
l.Append(20).Append(10);
l.Partition(15);
ASSERT_EQ(10, l.head->val);
l.Destroy();
}
TEST(TestCSingleLinkedList, Sample1) {
CSingleLinkedList l;
l.Append(3).Append(4).Append(5).Append(6).Append(7);
l.Partition(2);
int a[] = {7, 3, 4, 5, 6};
CNode* p = l.head;
for (int i = 0; i < sizeof (a) / sizeof (int); ++i) {
ASSERT_EQ(a[i], p->val);
p = p->next;
}
l.Destroy();
}
TEST(TestCSingleLinkedList, Sample2) {
CSingleLinkedList l;
l.Append(8).Append(5).Append(7).Append(2).Append(1);
l.Partition(6);
int a[] = {5, 2, 1, 8, 7};
CNode* p = l.head;
for (int i = 0; i < sizeof (a) / sizeof (int); ++i) {
ASSERT_EQ(a[i], p->val);
p = p->next;
}
l.Destroy();
}
TEST(TestCSingleLinkedList, DeleteFromEmptyList) {
CSingleLinkedList l;
l.Delete(10);
ASSERT_EQ(nullptr, l.head);
l.Destroy();
}
TEST(TestCSingleLinkedList, DeleteAtHeadWithOnlyOneElem) {
CSingleLinkedList l;
l.Append(8);
l.Delete(8);
ASSERT_EQ(nullptr, l.head);
l.Destroy();
}
TEST(TestCSingleLinkedList, DeleteAtTailWithTwoElems) {
CSingleLinkedList l;
l.Append(8).Append(5);
l.Delete(5);
ASSERT_EQ(8, l.head->val);
l.Destroy();
}
TEST(TestCSingleLinkedList, DeleteInMiddle) {
CSingleLinkedList l;
l.Append(8).Append(5).Append(7).Append(2).Append(1);
l.Delete(7);
int a[] = {8, 5, 2, 1};
CNode* p = l.head;
for (int i = 0; i < sizeof (a) / sizeof (int); ++i) {
ASSERT_EQ(a[i], p->val);
p = p->next;
}
l.Destroy();
}
TEST(TestCSingleLinkedList, RemoveDupOnEmptyList) {
CSingleLinkedList l;
l.RemoveDup();
ASSERT_EQ(nullptr, l.head);
l.Destroy();
}
TEST(TestCSingleLinkedList, RemoveDupOnOneElemList) {
CSingleLinkedList l;
l.Append(8);
l.RemoveDup();
ASSERT_EQ(8, l.head->val);
l.Destroy();
}
TEST(TestCSingleLinkedList, RemoveDupOnTwoElemsListWithoutDup) {
CSingleLinkedList l;
l.Append(8).Append(7);
l.RemoveDup();
ASSERT_EQ(8, l.head->val);
l.Destroy();
}
//TEST(TestCSingleLinkedList, RemoveDupOnTwoElemsListWithDup) {
// CSingleLinkedList l;
// l.Append(8).Append(8);
// l.RemoveDup();
// ASSERT_EQ(8, l.head->val);
// l.Destroy();
//}
//TEST(TestCSingleLinkedList, RemoveDupOn8ElemsList) {
// CSingleLinkedList l;
// l.Append(8).Append(8).Append(5).Append(5).Append(3).Append(2).Append(7).Append(8);
// l.RemoveDup();
// ASSERT_EQ(8, l.head->val);
// int a[] = {8, 5, 3, 2, 7};
// CNode* p = l.head;
// for (int i = 0; i < sizeof (a) / sizeof (int); ++i) {
// ASSERT_EQ(a[i], p->val);
// p = p->next;
// }
// l.Destroy();
//}
TEST(TestCSingleLinkedList, NthToLast) {
CSingleLinkedList l;
l.Append(8).Append(8).Append(5).Append(5).Append(3).Append(2).Append(7).Append(8);
int i = 0;
ASSERT_EQ(2, l.NthToLast(l.head, 3, i)->val);
l.Destroy();
}
TEST(TestCSingleLinkedList, NthToLastOnEmptyList) {
CSingleLinkedList l;
int i = 0;
ASSERT_EQ(nullptr, l.NthToLast(l.head, 3, i));
l.Destroy();
}
TEST(TestCSingleLinkedList, NthToLastWithNLargerThanListLength) {
CSingleLinkedList l;
l.Append(8).Append(8).Append(5).Append(5).Append(3).Append(2).Append(7).Append(8);
int i = 0;
ASSERT_EQ(nullptr, l.NthToLast(l.head, 100, i));
l.Destroy();
}
TEST(TestCSingleLinkedList, NthToLastWithNEqualToListLength) {
CSingleLinkedList l;
l.Append(8).Append(5).Append(3).Append(2).Append(7);
int i = 0;
ASSERT_EQ(8, l.NthToLast(l.head, 5, i)->val);
l.Destroy();
}
TEST(TestCSingleLinkedList, NthToLastNonRecursive) {
CSingleLinkedList l;
l.Append(8).Append(8).Append(5).Append(5).Append(3).Append(2).Append(7).Append(8);
ASSERT_EQ(2, l.NthToLast(3)->val);
l.Destroy();
}
TEST(TestCSingleLinkedList, NthToLastNonRecursiveOnEmptyList) {
CSingleLinkedList l;
ASSERT_EQ(nullptr, l.NthToLast(3));
l.Destroy();
}
TEST(TestCSingleLinkedList, NthToLastNonRecursiveWithNLargerThanListLength) {
CSingleLinkedList l;
l.Append(8).Append(8).Append(5).Append(5).Append(3).Append(2).Append(7).Append(8);
ASSERT_EQ(nullptr, l.NthToLast(100));
l.Destroy();
}
TEST(TestCSingleLinkedList, NthToLastNonRecursiveWithNEqualToListLength) {
CSingleLinkedList l;
l.Append(8).Append(5).Append(3).Append(2).Append(7);
ASSERT_EQ(8, l.NthToLast(5)->val);
l.Destroy();
}
TEST(TestCSingleLinkedList, AddListHeadAsLowestEmptyListToEmpytList) {
CSingleLinkedList l1;
CSingleLinkedList l2;
l1.AddListHeadAsLowest(l2);
ASSERT_EQ(nullptr, l1.head);
ASSERT_EQ(nullptr, l2.head);
l1.Destroy();
l2.Destroy();
}
TEST(TestCSingleLinkedList, AddListHeadAsLowestEmptyListToNonEmpytList) {
CSingleLinkedList l1;
CSingleLinkedList l2;
l1.Append(4);
l1.AddListHeadAsLowest(l2);
ASSERT_EQ(4, l1.head->val);
ASSERT_EQ(nullptr, l2.head);
l1.Destroy();
l2.Destroy();
}
TEST(TestCSingleLinkedList, AddListHeadAsLowestWithoutCarry) {
CSingleLinkedList l1;
CSingleLinkedList l2;
l1.Append(4).Append(3).Append(2).Append(1);
l2.Append(1).Append(2);
l1.AddListHeadAsLowest(l2);
ASSERT_EQ(5, l1.head->val);
ASSERT_EQ(5, l1.head->next->val);
ASSERT_EQ(2, l1.head->next->next->val);
l1.Destroy();
l2.Destroy();
}
TEST(TestCSingleLinkedList, AddListHeadAsLowestWithCarry) {
CSingleLinkedList l1;
CSingleLinkedList l2;
l1.Append(9).Append(8).Append(9).Append(9);
l2.Append(1).Append(1);
l1.AddListHeadAsLowest(l2);
ASSERT_EQ(0, l1.head->val);
ASSERT_EQ(0, l1.head->next->val);
ASSERT_EQ(0, l1.head->next->next->val);
ASSERT_EQ(0, l1.head->next->next->next->val);
ASSERT_EQ(1, l1.head->next->next->next->next->val);
l1.Destroy();
l2.Destroy();
}
TEST(TestCSingleLinkedList, AddListHeadAsLowestNonEmptyListToEmpytList) {
CSingleLinkedList l1;
CSingleLinkedList l2;
l2.Append(4);
l1.AddListHeadAsLowest(l2);
ASSERT_EQ(4, l1.head->val);
l1.Destroy();
l2.Destroy();
}
TEST(TestCSingleLinkedList, AddListHeadAsLowestLongListToShortWithoutCarry) {
CSingleLinkedList l1;
CSingleLinkedList l2;
l2.Append(4).Append(3).Append(2).Append(1);
l1.Append(1).Append(2);
l1.AddListHeadAsLowest(l2);
ASSERT_EQ(5, l1.head->val);
ASSERT_EQ(5, l1.head->next->val);
ASSERT_EQ(2, l1.head->next->next->val);
l1.Destroy();
l2.Destroy();
}
TEST(TestCSingleLinkedList, AddListHeadAsLowestLongListToShortWithCarry) {
CSingleLinkedList l1;
CSingleLinkedList l2;
l2.Append(9).Append(8).Append(9).Append(9);
l1.Append(1).Append(1);
l1.AddListHeadAsLowest(l2);
ASSERT_EQ(0, l1.head->val);
ASSERT_EQ(0, l1.head->next->val);
ASSERT_EQ(0, l1.head->next->next->val);
ASSERT_EQ(0, l1.head->next->next->next->val);
ASSERT_EQ(1, l1.head->next->next->next->next->val);
l1.Destroy();
l2.Destroy();
}
TEST(TestCSingleLinkedList, IsCircularOnEmptyList) {
CSingleLinkedList l1;
ASSERT_FALSE(l1.IsCircular());
l1.Destroy();
}
TEST(TestCSingleLinkedList, IsCircularOnNonCircularList) {
CSingleLinkedList l1;
l1.Append(9).Append(8).Append(9).Append(9);
ASSERT_FALSE(l1.IsCircular());
l1.Destroy();
}
TEST(TestCSingleLinkedList, IsCircularOnCircularList) {
CSingleLinkedList l1;
l1.Append(9).Append(8).Append(9).Append(9);
CNode* t = l1.Tail();
t->next = l1.Find(8);
ASSERT_TRUE(l1.IsCircular());
t->next = nullptr;
l1.Destroy();
}
TEST(TestCSingleLinkedList, FindCirCleBeginOnCircularList) {
CSingleLinkedList l1;
l1.Append(9).Append(8).Append(9).Append(9);
CNode* t = l1.Tail();
t->next = l1.Find(8);
ASSERT_EQ(8, l1.FindCirCleBegin()->val);
t->next = nullptr;
l1.Destroy();
}
TEST(TestCSingleLinkedList, FindCirCleBeginOnNonCircularList) {
CSingleLinkedList l1;
l1.Append(9).Append(8).Append(9).Append(9);
ASSERT_EQ(nullptr, l1.FindCirCleBegin());
l1.Destroy();
}
TEST(TestCSingleLinkedList, AddListHeadAsHighestEmptyListToEmpytList) {
CSingleLinkedList l1;
CSingleLinkedList l2;
l1.AddListHeadAsHighest(l2);
ASSERT_EQ(nullptr, l1.head);
ASSERT_EQ(nullptr, l2.head);
l1.Destroy();
l2.Destroy();
}
TEST(TestCSingleLinkedList, AddListHeadAsHighestEmptyListToNonEmpytList) {
CSingleLinkedList l1;
CSingleLinkedList l2;
l1.Append(4);
l1.AddListHeadAsHighest(l2);
ASSERT_EQ(4, l1.head->val);
l1.Destroy();
l2.Destroy();
}
TEST(TestCSingleLinkedList, AddListHeadAsHighestWithoutCarry) {
CSingleLinkedList l1;
CSingleLinkedList l2;
l1.Append(4).Append(3).Append(2).Append(1);
l2.Append(1).Append(2);
l1.AddListHeadAsHighest(l2);
ASSERT_EQ(4, l1.head->val);
ASSERT_EQ(3, l1.head->next->val);
ASSERT_EQ(3, l1.head->next->next->val);
l1.Destroy();
l2.Destroy();
}
TEST(TestCSingleLinkedList, AddListHeadAsHighestWithCarry) {
CSingleLinkedList l1;
CSingleLinkedList l2;
l1.Append(9).Append(9).Append(8).Append(9);
l2.Append(1).Append(1);
l1.AddListHeadAsHighest(l2);
ASSERT_EQ(1, l1.head->val);
ASSERT_EQ(0, l1.head->next->val);
ASSERT_EQ(0, l1.head->next->next->val);
ASSERT_EQ(0, l1.head->next->next->next->val);
ASSERT_EQ(0, l1.head->next->next->next->next->val);
l1.Destroy();
l2.Destroy();
}
TEST(TestCSingleLinkedList, AddListHeadAsHighestNonEmptyListToEmpytList) {
CSingleLinkedList l1;
CSingleLinkedList l2;
l2.Append(4);
l1.AddListHeadAsHighest(l2);
ASSERT_EQ(4, l1.head->val);
l1.Destroy();
l2.Destroy();
}
TEST(TestCSingleLinkedList, AddListHeadAsHighestLongListToShortWithoutCarry) {
CSingleLinkedList l1;
CSingleLinkedList l2;
l2.Append(4).Append(3).Append(2).Append(1);
l1.Append(1).Append(2);
l1.AddListHeadAsHighest(l2);
ASSERT_EQ(4, l1.head->val);
ASSERT_EQ(3, l1.head->next->val);
ASSERT_EQ(3, l1.head->next->next->val);
l1.Destroy();
l2.Destroy();
}
TEST(TestCSingleLinkedList, AddListHeadAsHighestLongListToShortWithCarry) {
CSingleLinkedList l1;
CSingleLinkedList l2;
l2.Append(9).Append(9).Append(8).Append(9);
l1.Append(1).Append(1);
l1.AddListHeadAsHighest(l2);
ASSERT_EQ(1, l1.head->val);
ASSERT_EQ(0, l1.head->next->val);
ASSERT_EQ(0, l1.head->next->next->val);
ASSERT_EQ(0, l1.head->next->next->next->val);
ASSERT_EQ(0, l1.head->next->next->next->next->val);
l1.Destroy();
l2.Destroy();
}
TEST(TestCSingleLinkedList, RevertEmptyList) {
CSingleLinkedList l1;
l1.Revert();
ASSERT_EQ(nullptr, l1.head);
l1.Destroy();
}
TEST(TestCSingleLinkedList, RevertOneElemList) {
CSingleLinkedList l1;
l1.Insert(1);
l1.Revert();
ASSERT_EQ(1, l1.head->val);
l1.Destroy();
}
TEST(TestCSingleLinkedList, RevertTwoElemsList) {
CSingleLinkedList l1;
l1.Append(1).Append(2);
l1.Revert();
ASSERT_EQ(2, l1.head->val);
ASSERT_EQ(1, l1.head->next->val);
l1.Destroy();
}
TEST(TestCSingleLinkedList, RevertFiveElemsList) {
CSingleLinkedList l1;
l1.Append(4).Append(3).Append(2).Append(1).Append(0);
l1.Revert();
ASSERT_EQ(0, l1.head->val);
ASSERT_EQ(1, l1.head->next->val);
ASSERT_EQ(2, l1.head->next->next->val);
ASSERT_EQ(3, l1.head->next->next->next->val);
ASSERT_EQ(4, l1.head->next->next->next->next->val);
l1.Destroy();
}
<file_sep>//
// ConnectionSlowImpl.cpp
// algo
//
// Created by raof01 on 7/25/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#include "ConnectionSlowImpl.h"
ConnectionSlowImpl::ConnectionSlowImpl(int sz) : m_Data(sz)
{
for (int i = 0; i < sz; ++i)
m_Data[i] = i;
}
ConnectionSlowImpl::~ConnectionSlowImpl()
{
}
bool ConnectionSlowImpl::OutOfRange(int i)
{
return i < 0 || i >= m_Data.capacity();
}
void ConnectionSlowImpl::ConnectTo(int src, int target)
{
if (OutOfRange(src) || OutOfRange(target)) return;
int srcId = m_Data[src];
int targetId = m_Data[target];
for (std::vector<int>::iterator iter = m_Data.begin();
iter != m_Data.end();
++iter)
{
if (*iter == srcId)
*iter = targetId;
}
}
bool ConnectionSlowImpl::Connected(int i1, int i2)
{
if (OutOfRange(i1) || OutOfRange(i2)) return false;
return m_Data[i1] == m_Data[i2];
}
<file_sep>//
// RBTree.h
// algo
//
// Created by raof01 on 6/17/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#ifndef algo_RBTree_h
#define algo_RBTree_h
#include "BinaryTree.hpp"
////////////////////////////////////////////////////////////////////////////////
// RBTree properties:
// 1. Each node must be either red or black
// 2. Root is black
// 3. Leaves are red (the nil is black) ???
// 4. A red node will have only black children
// 5. Any paths from a node to its descendents have the same number of black
// nodes
////////////////////////////////////////////////////////////////////////////////
enum Color
{
RED = 0,
BLACK = 1,
};
class RBTree : public BinaryTree
{
public:
RBTree();
virtual void Insert(int);
virtual void Delete(int);
virtual void InOrderTraversal(Visitor<int, false>&) const;
virtual void PreOrderTraversal(Visitor<int, false>&) const;
virtual void PostOrderTraversal(Visitor<int, false>&) const;
virtual void BreadthFirstTraversal(Visitor<int, false>&) const;
virtual void DepthFirstTraversal(Visitor<int, false>&) const;
virtual int GetMaxValue() const;
virtual int GetMinValue() const;
virtual bool Find(int) const;
virtual bool GetParentValue(int, int&) const;
virtual bool GetSuccessorValue(int, int&) const;
virtual bool GetPredecessorValue(int, int&) const;
virtual int GetCount() const;
virtual void Invert();
virtual ~RBTree();
private:
struct Node;
private:
void LeftRotate(Node*);
void RightRotate(Node*);
void DeleteTree(Node*&);
void Fixup(Node*);
//private:
// const static Node* nil;
private:
Node* mRoot;
int mCnt;
};
#endif
<file_sep>//
// Queue.hpp
// algo
//
// Created by raof01 on 5/9/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#ifndef algo_Queue_hpp
#define algo_Queue_hpp
// Circular Queue
template <typename T, int MAX_SIZE = 1024>
class Queue
{
public:
Queue() : mHead (0), mCnt(0) {}
bool Enqueue(const T& v);
bool Dequeue(T& v);
bool GetHead(T& v);
bool GetTail(T& v);
int MaxSize();
int Count();
bool Empty();
bool Full();
private:
int Wrap(int v) { if (v >= MAX_SIZE) return v % MAX_SIZE; else return v; }
private:
T mData[MAX_SIZE];
int mHead;
int mCnt;
};
template <typename T, int MAX_SIZE>
bool Queue<T, MAX_SIZE>::Enqueue(const T& v)
{
if (Full()) return false;
mData[Wrap(mHead + (mCnt++))] = v;
return true;
}
template <typename T, int MAX_SIZE>
bool Queue<T, MAX_SIZE>::Dequeue(T& v)
{
if (Empty()) return false;
--mCnt;
v = mData[mHead];
mHead = Wrap(++mHead);
return true;
}
template <typename T, int MAX_SIZE>
bool Queue<T, MAX_SIZE>::GetHead(T& v)
{
if (Empty()) return false;
v = mData[mHead];
return true;
}
template <typename T, int MAX_SIZE>
bool Queue<T, MAX_SIZE>::GetTail(T& v)
{
if (Empty()) return false;
v = mData[Wrap(mHead + mCnt - 1)];
return true;
}
template <typename T, int MAX_SIZE>
int Queue<T, MAX_SIZE>::MaxSize()
{
return MAX_SIZE;
}
template <typename T, int MAX_SIZE>
int Queue<T, MAX_SIZE>::Count()
{
return mCnt;
}
template <typename T, int MAX_SIZE>
bool Queue<T, MAX_SIZE>::Empty()
{
return mCnt == 0;
}
template <typename T, int MAX_SIZE>
bool Queue<T, MAX_SIZE>::Full()
{
return mCnt == MAX_SIZE;
}
#endif
<file_sep>//
// MaxPriorityQueueTest.cpp
// algo
//
// Created by raof01 on 8/11/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#include "gtest/gtest.h"
#include "MaxPriorityQueueArrayImpl.h"
TEST(TestMaxPriorityQueueArrayImpl, InsertToEmptyQueue)
{
MaxPriorityQueue<int>* pq = new MaxPriorityQueueArrayImpl<int, 5>();
ASSERT_TRUE(pq->Insert(0));
delete pq;
}
TEST(TestMaxPriorityQueueArrayImpl, EmptyQueue)
{
MaxPriorityQueue<int>* pq = new MaxPriorityQueueArrayImpl<int, 5>();
ASSERT_TRUE(pq->IsEmpty());
delete pq;
}
TEST(TestMaxPriorityQueueArrayImpl, SwimInOneElemArray)
{
MaxPriorityQueue<int>* pq = new MaxPriorityQueueArrayImpl<int, 5>();
ASSERT_TRUE(pq->IsEmpty());
delete pq;
}
TEST(TestMaxPriorityQueueArrayImpl, InsertToFullQueue)
{
MaxPriorityQueue<int>* pq = new MaxPriorityQueueArrayImpl<int, 1>();
ASSERT_TRUE(pq->Insert(0));
ASSERT_FALSE(pq->Insert(1));
delete pq;
}
TEST(TestMaxPriorityQueueArrayImpl, InsertToQueueInOrder)
{
MaxPriorityQueue<int>* pq = new MaxPriorityQueueArrayImpl<int, 5>();
int i = 0;
while (pq->Insert(i++));
int v = 0;
ASSERT_TRUE(pq->DeleteMax(v));
ASSERT_EQ(4, v);
ASSERT_TRUE(pq->DeleteMax(v));
ASSERT_EQ(3, v);
ASSERT_TRUE(pq->DeleteMax(v));
ASSERT_EQ(2, v);
ASSERT_TRUE(pq->DeleteMax(v));
ASSERT_EQ(1, v);
ASSERT_TRUE(pq->DeleteMax(v));
ASSERT_EQ(0, v);
ASSERT_FALSE(pq->DeleteMax(v));
delete pq;
}
TEST(TestMaxPriorityQueueArrayImpl, InsertToQueueInReverseOrder)
{
MaxPriorityQueue<int>* pq = new MaxPriorityQueueArrayImpl<int, 5>();
int i = 5;
while (pq->Insert(i--));
int v = 0;
ASSERT_TRUE(pq->DeleteMax(v));
ASSERT_EQ(5, v);
ASSERT_TRUE(pq->DeleteMax(v));
ASSERT_EQ(4, v);
ASSERT_TRUE(pq->DeleteMax(v));
ASSERT_EQ(3, v);
ASSERT_TRUE(pq->DeleteMax(v));
ASSERT_EQ(2, v);
ASSERT_TRUE(pq->DeleteMax(v));
ASSERT_EQ(1, v);
ASSERT_FALSE(pq->DeleteMax(v));
delete pq;
}
TEST(TestMaxPriorityQueueArrayImpl, InsertToQueueInRandomOrder)
{
int a[] = {62, 83, 18, 53, 07, 17, 95, 86, 47, 69, 25, 28};
int result[] = {7, 17, 18, 25, 28, 47, 53, 62, 69, 83, 86, 95};
MaxPriorityQueue<int>* pq = new MaxPriorityQueueArrayImpl<int, sizeof(a) / sizeof(int)>();
for (int i = 0; i < sizeof(a)/sizeof(int); ++i)
pq->Insert(a[i]);
int v = 0;
for (int i = sizeof(a)/sizeof(int) - 1; i >= 0; --i)
{
ASSERT_TRUE(pq->DeleteMax(v));
ASSERT_EQ(result[i], v);
}
ASSERT_FALSE(pq->DeleteMax(v));
delete pq;
}
<file_sep>//
// LeetCodeProblems.h
// algo
//
// Created by <NAME> on 10/12/15.
// Copyright © 2015 raof01. All rights reserved.
//
#ifndef LeetCodeProblems_h
#define LeetCodeProblems_h
#include <vector>
#include <string>
using namespace std;
class WordPattern {
public:
static bool wordPattern(const string& pattern, const string& str);
private:
static void SplitString(const string& str, vector<const string>& v);
};
/*
You are a product manager and currently leading a team to develop a new
product. Unfortunately, the latest version of your product fails the
quality check. Since each version is developed based on the previous
version, all the versions after a bad version are also bad.
Suppose you have n versions [1, 2, ..., n] and you want to find out the
first bad one, which causes all the following ones to be bad.
You are given an API bool isBadVersion(version) which will return whether
version is bad. Implement a function to find the first bad version. You
should minimize the number of calls to the API.
*/
// Forward declaration of isBadVersion API.
bool isBadVersion(int version);
class FirstBadVersion {
public:
static int firstBadVersion(int n);
private:
static int firstBadVersion(int lo, int hi);
};
/*
Given an array of integers and an integer k, find out whether there are
two distinct indices i and j in the array such that nums[i] = nums[j] and
the difference between i and j is at most k.
*/
class ContainsNearByDuplicate {
public:
static bool containsNearbyDuplicate(vector<int>& nums, int k);
};
class AddDigits {
public:
static int addDigits(int num) ;
};
/*
You are playing the following Nim Game with your friend: There is a heap of stones on the table, each time one of you take turns to remove 1 to 3 stones. The one who removes the last stone will be the winner. You will take the first turn to remove the stones.
Both of you are very clever and have optimal strategies for the game. Write a function to determine whether you can win the game given the number of stones in the heap.
For example, if there are 4 stones in the heap, then you will never win the game: no matter 1, 2, or 3 stones you remove, the last stone will always be removed by your friend.
Hint:
If there are 5 stones in the heap, could you figure out a way to remove the stones such that you will always be the winner?
*/
class NimGame {
public:
static bool canWinNim(int n);
};
/*
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty and the majority element always exist in the array.
*/
class MajorityElement {
public:
static int majorityElement(vector<int>& nums);
static int MajorityElementWithExtraSapce(vector<int>& nums);
};
/*
Given two strings s and t, write a function to determine if t is an anagram of s.
For example,
s = "anagram", t = "nagaram", return true.
s = "rat", t = "car", return false.
*/
class Anagram {
public:
const static int MAXCHAR = 128;
static bool isAnagram(string s, string t);
};
/*
Given a non-negative number represented as an array of digits, plus one to the number.
The digits are stored such that the most significant digit is at the head of the list.
*/
class PlusOne {
public:
static vector<int> plusOne(vector<int>& digits);
};
/**
* Definition for singly-linked list.
*/
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
ListNode(int x, ListNode* n) : val(x), next(n) {}
};
class ListNodeList {
public:
static ListNode* deleteDuplicates(ListNode* head);
/*
* Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:
Given 1->2->3->4->5->NULL, m = 2 and n = 4,
return 1->4->3->2->5->NULL.
*/
static ListNode* reverseBetween(ListNode* head, int s, int e);
static ListNode* reverseList(ListNode* head);
private:
static ListNode* reverseRecursive(ListNode* head, ListNode*& tail);
};
/*
You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
*/
class ClimeStairs {
public:
static int climbStairs(int n);
};
class SumOfFactorialsTo {
public:
static long long sumOfFactorialsTo(int n);
};
/*
* A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.
Example: 19 is a happy number
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
*/
/*
* Use fast and slow to determine if there's a loop so that the
* algorithm will be terminated
*/
class HappyNumber {
public:
static bool isHappyNumber(int);
private:
static int sumOfSquareOfDigits(int);
};
/**
* Definition for a binary tree node.
*/
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class SymmetricTree {
public:
static bool isSymmetric(TreeNode* root);
private:
static bool isSymmetric(TreeNode* n1, TreeNode* n2);
static bool isSymmetricIterative(TreeNode* root);
};
vector<vector<int>> generatePascalNumber(int numRows);
ListNode* MergeToSorted(ListNode*, ListNode*);
#endif /* LeetCodeProblems_h */
<file_sep>//
// Visitor.hpp
// algo
//
// Created by raof01 on 5/19/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#ifndef algo_Visitor_hpp
#define algo_Visitor_hpp
template <typename T, bool IsClass = true>
class Visitor
{
public:
virtual void Visit(const T&) = 0;
virtual ~Visitor() {};
};
template <typename T>
class Visitor<T, false>
{
public:
virtual void Visit(T) = 0;
virtual ~Visitor() {};
};
#endif
<file_sep>//
// StringFind.h
// algo
//
// Created by raof01 on 5/10/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#ifndef algo_StringFind_h
#define algo_StringFind_h
#include <stdio.h>
#include <string>
#define NOT_FOUND -1
size_t BFIndex(const char*, const char*, size_t, size_t);
size_t KMPIndex(const char*, const char*, size_t, size_t);
void Reverse(char*, size_t, size_t);
void ReverseRecursive(char*, char*);
bool IsPalindromeIgnoreCase(const char*);
int Atoi(const char*);
int CompareVersion(const char* version1, const char* version2);
int CompareVersionNoAtoi(const char* version1, const char* version2);
std::string minWindow(const std::string&, std::string&);
bool IsIsomorphic(std::string&, std::string&);
#endif
<file_sep>//
// Created by raof01 on 9/22/15.
//
#include "gtest/gtest.h"
#include "PrimeSieve.h"
#include "ArraysMatch.hpp"
TEST(TestPrimeSieve, MaxValueIsZero) {
PrimeSieve ps(0);
std::vector<int> v;
ASSERT_FALSE(ps.GetPrimes(v));
ASSERT_TRUE(v.empty());
}
TEST(TestPrimeSieve, MaxValueIsOne) {
PrimeSieve ps(1);
std::vector<int> v;
ASSERT_FALSE(ps.GetPrimes(v));
ASSERT_TRUE(v.empty());
}
TEST(TestPrimeSieve, MaxValueIsTwo) {
PrimeSieve ps(2);
std::vector<int> v;
ASSERT_TRUE(ps.GetPrimes(v));
ASSERT_EQ(2, v[0]);
}
TEST(TestPrimeSieve, MaxValueIs11) {
PrimeSieve ps(11);
std::vector<int> v;
ASSERT_TRUE(ps.GetPrimes(v));
std::vector<int> primes = {2, 3, 5, 7, 11};
ASSERT_TRUE(VectorsMatch(primes, v));
}
TEST(TestPrimeSieve, MaxValueIs30) {
PrimeSieve ps(30);
std::vector<int> v;
ASSERT_TRUE(ps.GetPrimes(v));
std::vector<int> primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29};
ASSERT_TRUE(VectorsMatch(primes, v));
}
<file_sep>//
// SingleLinkedListTest.cpp
// algo
//
// Created by raof01 on 5/8/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#include "gtest/gtest.h"
#include "SingleLinkedList.h"
#include "ArraysMatch.hpp"
TEST(TestSingleLinkedList, Insert)
{
int r[] = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
int a[10] = {};
int i = 0;
SingleLinkedList lst;
for (; i < 10; ++i) lst.Insert(i);
i = 0;
for (SingleLinkedList::Iterator iter = lst.Begin(); iter != lst.End(); ++iter, ++i)
a[i] = *iter;
ASSERT_TRUE(ArraysMatch(r, a));
}
TEST(TestSingleLinkedList, Append)
{
int r[] = {0, 1, 2, 3, 4, 5, 6, 7 ,8 ,9};
int a[10] = {};
int i = 0;
SingleLinkedList lst;
for (; i < 10; ++i) lst.Append(i);
i = 0;
for (SingleLinkedList::Iterator iter = lst.Begin(); iter != lst.End(); ++iter, ++i)
a[i] = *iter;
ASSERT_TRUE(ArraysMatch(r, a));
}
TEST(TestSingleLinkedList, PositiveFind)
{
SingleLinkedList lst;
for (int i = 0; i < 10; ++i) lst.Append(i);
ASSERT_EQ(8, *lst.Find(8));
}
TEST(TestSingleLinkedList, NegativeFind)
{
SingleLinkedList lst;
for (int i = 0; i < 10; ++i) lst.Append(i);
ASSERT_EQ(lst.End(), lst.Find(11));
}
TEST(TestSingleLinkedList, PositiveEmpty)
{
SingleLinkedList lst;
ASSERT_TRUE(lst.Empty());
}
TEST(TestSingleLinkedList, NegativeEmpty)
{
SingleLinkedList lst;
lst.Insert(10);
ASSERT_TRUE(!lst.Empty());
}
TEST(TestSingleLinkedList, DeleteFromEmptyList)
{
SingleLinkedList lst;
lst.Delete(1);
ASSERT_TRUE(lst.Empty());
}
TEST(TestSingleLinkedList, DeleteFirstFromOneElemList)
{
SingleLinkedList lst;
lst.Insert(1);
lst.Delete(1);
ASSERT_TRUE(lst.Empty());
}
TEST(TestSingleLinkedList, DeleteFirstFromTwoElemsList)
{
SingleLinkedList lst;
lst.Append(1);
lst.Append(2);
lst.Delete(1);
ASSERT_EQ(2, *lst.Begin());
}
TEST(TestSingleLinkedList, DeleteLastFromTwoElemsList)
{
SingleLinkedList lst;
lst.Append(1);
lst.Append(2);
lst.Delete(2);
ASSERT_EQ(1, *lst.Begin());
}
TEST(TestSingleLinkedList, DeleteLastFromThreeElemsList)
{
SingleLinkedList lst;
lst.Append(1);
lst.Append(2);
lst.Append(3);
lst.Delete(3);
int r[] = {1, 2};
int a[2] = {};
int i = 0;
for (SingleLinkedList::Iterator iter = lst.Begin(); iter != lst.End(); ++i, ++iter)
a[i] = *iter;
ASSERT_TRUE(ArraysMatch(r, a));
}
TEST(TestSingleLinkedList, DeleteAllResultingEmptyList)
{
SingleLinkedList lst;
lst.Append(1);
lst.Append(1);
lst.Append(1);
lst.DeleteAll(1);
ASSERT_TRUE(lst.Empty());
}
TEST(TestSingleLinkedList, DeleteAllResultingOneElemList)
{
SingleLinkedList lst;
lst.Append(3);
lst.Append(1);
lst.Append(1);
lst.Append(1);
lst.DeleteAll(1);
ASSERT_EQ(*lst.Begin(), 3);
}
TEST(TestSingleLinkedList, CountZeroOnEmptyList)
{
SingleLinkedList lst;
ASSERT_EQ(0, lst.Count());
}
TEST(TestSingleLinkedList, CountOneOnOneElemList)
{
SingleLinkedList lst;
lst.Insert(1);
ASSERT_EQ(1, lst.Count());
}
TEST(TestSingleLinkedList, CountFourOnFourElemsList)
{
SingleLinkedList lst;
lst.Append(1);
lst.Append(2);
lst.Append(3);
lst.Append(3);
ASSERT_EQ(4, lst.Count());
}
TEST(TestSingleLinkedList, ReverseEmptyList)
{
SingleLinkedList lst;
lst.Reverse();
ASSERT_EQ(0, lst.Count());
ASSERT_TRUE(lst.Empty());
}
TEST(TestSingleLinkedList, ReverseListWithOneElem)
{
SingleLinkedList lst;
lst.Insert(10);
lst.Reverse();
ASSERT_EQ(10, *lst.Begin());
}
TEST(TestSingleLinkedList, ReverseListWithTwoElems)
{
SingleLinkedList lst;
lst.Append(10);
lst.Append(9);
lst.Reverse();
SingleLinkedList::Iterator iter = lst.Begin();
ASSERT_EQ(9, *iter++);
ASSERT_EQ(10, *iter);
}
TEST(TestSingleLinkedList, ReverseListWithTenElems)
{
SingleLinkedList lst;
for (int i = 0; i < 10; ++i)
lst.Append(i);
lst.Reverse();
SingleLinkedList::Iterator iter = lst.Begin();
SingleLinkedList::Iterator end = lst.End();
for (int i = 9; i >= 0 && iter != end; --i, ++iter)
ASSERT_EQ(i, *iter);
}
TEST(TestSingleLinkedList, OperatorPlusInRange)
{
SingleLinkedList lst;
for (int i = 0; i < 10; ++i)
lst.Append(i);
SingleLinkedList::Iterator iter = lst.Begin();
SingleLinkedList::Iterator ret = iter + 2;
ASSERT_EQ(2, *ret);
}
TEST(TestSingleLinkedList, OperatorPlusOutOfRange)
{
SingleLinkedList lst;
for (int i = 0; i < 10; ++i)
lst.Append(i);
SingleLinkedList::Iterator iter = lst.Begin();
SingleLinkedList::Iterator ret = iter + 11;
ASSERT_EQ(lst.End(), ret);
}
<file_sep>//
// IsSorted.h
// algo
//
// Created by raof01 on 8/2/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#ifndef algo_IsSorted_h
#define algo_IsSorted_h
template <typename Comparable>
bool IsSorted(const Comparable* p, size_t start, size_t end)
{
for (size_t i = start + 1; i < end; ++i)
if (p[i] < p[i-1])
return false;
return true;
}
template <typename Comparable, size_t N>
bool IsSorted(const Comparable (&a)[N])
{
return IsSorted(static_cast<const Comparable*>(a), 0, N);
}
template <typename Comparable, size_t N>
bool IsSorted(const Comparable (&a)[N], size_t start, size_t end)
{
return IsSorted(static_cast<const Comparable*>(a), start, end);
}
#endif
<file_sep>//
// Created by raof01 on 9/13/15.
//
#include <stdlib.h>
#include "CSingleLinkedList.h"
CSingleLinkedList& CSingleLinkedList::Append(int v) {
CNode* p = new CNode(v);
if (head == nullptr) {
head = p;
} else {
CNode* c = head;
while (c->next != nullptr) {
c = c->next;
}
Tail()->next = p;
}
return *this;
}
CNode* CSingleLinkedList::Tail() {
CNode* c = head;
while (c != nullptr && c->next != nullptr)
c = c->next;
return c;
}
void CSingleLinkedList::Destroy() {
CNode* h = this->head;
while (h != nullptr) {
CNode* d = h;
h = h->next;
delete d;
}
this->head = nullptr;
}
void CSingleLinkedList::Partition(int v) {
CNode* cur = this->head;
CNode* pTail = Tail();
CNode* tail = pTail;
CNode* prev = nullptr;
CNode* pHead = this->head;
while (cur != tail) {
if (cur->val < v) {
prev = cur;
cur = cur->next;
} else {
if (prev == nullptr) pHead = pHead->next;
else prev->next = cur->next;
CNode* move = cur;
cur = cur->next;
move->next = nullptr;
pTail->next = move;
pTail = pTail->next;
}
}
this->head = pHead;
}
void CSingleLinkedList::Delete(CNode* n) {
CNode* prev = nullptr;
CNode* d = head;
while (d != nullptr && d != n) {
prev = d;
d = d->next;
}
if (d == nullptr) return;
if (prev == nullptr)
head = head->next;
else
prev->next = d->next;
delete d;
}
void CSingleLinkedList::Delete(int v) {
CNode* prev = nullptr;
CNode* d = head;
while (d != nullptr && d->val != v) {
prev = d;
d = d->next;
}
if (d == nullptr) return;
if (prev == nullptr)
head = head->next;
else
prev->next = d->next;
delete d;
}
void CSingleLinkedList::RemoveDup() {
// O(n^2) time with O(1) space
// A HashTable can be used to make O(n) time
CNode* p = head;
while (p != nullptr) {
int v = p->val;
CNode* r = p->next;
while (r != nullptr) {
if (r->val == v)
Delete(r);
r = r->next;
}
p = p->next;
}
}
const CNode* CSingleLinkedList::NthToLast(const CNode* h, int n, int& i) const {
if (h == nullptr) return nullptr;
const CNode* p = NthToLast(h->next, n, i);
i = i + 1;
if (i == n)
return h;
return p;
}
const CNode* CSingleLinkedList::NthToLast(int n) const {
CNode* p = head;
while (p != nullptr && n--) p = p->next;
if (n > 0) return nullptr;
CNode* c = head;
while (p != nullptr) {
c = c->next;
p = p->next;
}
return c;
}
int CSingleLinkedList::AddWithCarry(int v1, int v2, int& c) {
int sum = v1 + v2 + c;
c = sum / 10;
return sum % 10;
}
CSingleLinkedList& CSingleLinkedList::AddListHeadAsLowest(
const CSingleLinkedList &l) {
if (l.head == nullptr) return *this;
CNode* p1 = head;
CNode* p2 = l.head;
int carry = 0;
while (p1 != nullptr && p2 != nullptr) {
p1->val = AddWithCarry(p1->val, p2->val, carry);
p1 = p1->next;
p2 = p2->next;
}
while (p1 != nullptr) {
p1->val = AddWithCarry(p1->val, 0, carry);
p1 = p1->next;
}
while (p2 != nullptr) {
this->Append(AddWithCarry(0, p2->val, carry));
p2 = p2->next;
}
if (carry != 0)
this->Append(carry);
return *this;
}
CNode* CSingleLinkedList::Find(int v) {
CNode* n = head;
while (n != nullptr) {
if (n->val == v)
break;
n = n->next;
}
return n;
}
CNode* CSingleLinkedList::IsCircularImpl() const {
CNode* slow = head;
CNode* fast = head;
while (fast != nullptr && fast->next != nullptr) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast) return slow;
}
return nullptr;
}
bool CSingleLinkedList::IsCircular() const {
return IsCircularImpl() != nullptr;
}
CNode* CSingleLinkedList::FindCirCleBegin() {
CNode* p = IsCircularImpl();
if (p == nullptr) return nullptr;
CNode* c = head;
while (c != p) {
c = c->next;
p = p->next;
}
return c;
}
CSingleLinkedList& CSingleLinkedList::Insert(int v) {
CNode* p = new CNode(v, head);
head = p;
return *this;
}
int CSingleLinkedList::AddListRecursive(CNode* n1, CNode* n2) {
if (n1 == n2 && n1 == nullptr) return 0;
int carry = AddListRecursive(n1->next, n2->next);
n1->val = AddWithCarry(n1->val, n2->val, carry);
return carry;
}
CSingleLinkedList& CSingleLinkedList::AddListHeadAsHighest(CSingleLinkedList& l) {
int len1 = Length();
int len2 = l.Length();
int delta = abs(len1 - len2);
CSingleLinkedList* pl = len1 > len2 ? &l : this;
for (; delta > 0; --delta)
pl->Insert(0);
int carry = AddListRecursive(head, l.head);
if (carry != 0) this->Insert(carry);
return *this;
}
int CSingleLinkedList::Length() {
CNode* p = head;
int cnt = 0;
while (p != nullptr) {
++cnt;
p = p->next;
}
return cnt;
}
void CSingleLinkedList::RevertRecursive(CNode* n, CNode*& h, CNode*& t) {
if (n->next == nullptr) {
h = n;
t = n;
return;
}
RevertRecursive(n->next, h, t);
t->next = n;
t = n;
n->next = nullptr;
}
// Reverse tail, then append head to the tail of the reversed list
CNode *CSingleLinkedList::RevertRecursive(CNode *head, CNode *&tail) {
if (head == nullptr) {
tail = nullptr;
return head;
}
if (head->next == nullptr) {
tail = head;
return head;
}
CNode* h = RevertRecursive(head->next, tail);
if (tail != nullptr) {
tail->next = head;
tail = head;
head->next = nullptr;
}
return h;
}
// Reverse list before last node, then insert last node before head
CNode *CSingleLinkedList::ReverseRecursive(CNode *prev, CNode *head, CNode *next)
{
if (next == nullptr) return head;
CNode* n = next->next;
next->next = head;
head->next = prev;
return ReverseRecursive(head, next, n);
}
void CSingleLinkedList::Revert() {
#if 0
if (head == nullptr) return;
CNode* h = nullptr;
CNode* t = nullptr;
RevertRecursive(head, h, t);
head = h;
//#else
CNode* tail = nullptr;
head = RevertRecursive(head, tail);
#else
if (head == nullptr) return;
head = ReverseRecursive(nullptr, head, head->next);
#endif
}
<file_sep>//
// Created by raof01 on 9/6/15.
//
#ifndef ALGO_REVERSESTRING_H
#define ALGO_REVERSESTRING_H
#include <stddef.h>
#include <functional>
void ReverseString(char* start, char* end);
template <size_t N>
void ReverseString(char (&a)[N])
{
ReverseString(a, a + N - 2);
}
void ReverseString(char* start, char* end)
{
if (start == NULL || end == NULL) return;
if (start >= end) return;
ReverseString(start + 1, end - 1);
std::swap(*start, *end);
}
#endif //ALGO_REVERSESTRING_H
<file_sep>//
// LinkedListWithExtraPointerTest.cpp
// algo
//
// Created by <NAME> on 10/9/15.
// Copyright © 2015 raof01. All rights reserved.
//
#include <iostream>
#include "gtest/gtest.h"
#include "LinkedListWithExtra.h"
using namespace std;
void PrintByNext(const NodeWithExtra* h) {
while (h != nullptr) {
cout << h->data << "->";
h = h->next;
}
cout << endl;
}
void PrintByExtra(const NodeWithExtra* h) {
while (h != nullptr) {
cout << h->data << "->";
h = h->extra;
}
cout << endl;
}
NodeWithExtra* SetExtra() {
NodeWithExtra* h = nullptr;
for (int i = 0; i < 10; ++i)
h = Insert(h, i);
h->extra = h->next->next;
h->extra->extra = h->extra->next->next->next->next;
h->extra->extra->extra = h->extra->extra->next->next->next;
return h;
}
TEST(TestCopy, SampleInput) {
NodeWithExtra* l = SetExtra();
NodeWithExtra* lDup = Copy(l);
PrintByNext(l);
PrintByExtra(l);
PrintByNext(lDup);
PrintByExtra(lDup);
Destroy(l);
Destroy(lDup);
}
<file_sep>//
// BubbleSort.cpp
// algo
//
// Created by raof01 on 5/17/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#include "gtest/gtest.h"
#include "ArraysMatch.hpp"
#include "BubbleSort.hpp"
#include "IsSorted.h"
static int result[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
// BubbleSort
TEST(TestBubbleSort, Positive)
{
int a[] = {8, 7, 9, 0, 1, 3, 5, 4, 6, 2};
BubbleSorter<int>::Sort(a);
ASSERT_TRUE(ArraysMatch(result, a));
ASSERT_TRUE(IsSorted(a));
}
TEST(TestBubbleSort, OneElem)
{
int a[] = {8};
BubbleSorter<int>::Sort(a);
ASSERT_TRUE(ArraysMatch(a, a));
ASSERT_TRUE(IsSorted(a));
}
TEST(TestBubbleSort, TwoElems)
{
int a[] = {8, 0};
int result[] = {0, 8};
BubbleSorter<int>::Sort(a);
ASSERT_TRUE(ArraysMatch(result, a));
ASSERT_TRUE(IsSorted(a));
}
<file_sep>//
// StackTest.cpp
// algo
//
// Created by raof01 on 5/9/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#include "gtest/gtest.h"
#include "ArraysMatch.hpp"
#include "Stack.hpp"
TEST(TestStack, Push)
{
Stack<int, 10> sut;
ASSERT_TRUE(sut.Empty());
sut.Push(10);
ASSERT_EQ(10, sut.Peek());
ASSERT_FALSE(sut.Full());
}
TEST(TestStack, PushToFullStack)
{
Stack<int, 1> sut;
sut.Push(10);
ASSERT_FALSE(sut.Push(10));
}
TEST(TestStack, PopFromEmptyStack)
{
Stack<int, 10> sut;
ASSERT_EQ(int(), sut.Pop());
}
TEST(TestStack, PopFromOneElemStack)
{
Stack<int, 10> sut;
sut.Push(10);
ASSERT_EQ(10, sut.Pop());
ASSERT_TRUE(sut.Empty());
}
TEST(TestStack, MaxSize)
{
Stack<int, 10> sut;
ASSERT_EQ(10, sut.MaxSize());
}
TEST(TestStack, Count)
{
Stack<int, 10> sut;
ASSERT_EQ(0, sut.Count());
ASSERT_TRUE(sut.Empty());
ASSERT_FALSE(sut.Full());
}
TEST(TestStack, CountOne)
{
Stack<int, 10> sut;
sut.Push(1);
ASSERT_EQ(1, sut.Count());
ASSERT_FALSE(sut.Empty());
ASSERT_FALSE(sut.Full());
}
<file_sep>//
// wobTest.cpp
// algo
//
// Created by raof01 on 8/17/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#include "gtest/gtest.h"
#include "wob.h"
#include "ArraysMatch.hpp"
/*
class WobTestable : public ::testing::Test
{
public:
WobTestable() : ceo(nullptr) {}
private:
Employee* ceo;
};
*/
TEST(TestFind, Positive)
{
Employee bill = Employee(9, "Bill");
Employee dom = Employee(8, "Dom");
Employee samir = Employee(7, "Samir");
Employee michael = Employee(6, "Michael");
bill.addReport(&dom);
bill.addReport(&samir);
bill.addReport(&michael);
Employee bob = Employee(5, "Bob");
Employee peter = Employee(4, "Peter");
Employee porter = Employee(3, "Porter");
dom.addReport(&bob);
dom.addReport(&peter);
dom.addReport(&porter);
Employee milton = Employee(2, "Milton");
Employee nina = Employee(1, "Nina");
peter.addReport(&milton);
peter.addReport(&nina);
vector<Employee*> path;
ASSERT_TRUE(find(&bill, &nina, path));
vector<int> result;
for (int i = 0; i < path.size(); ++i)
result.push_back(path[i]->getId());
vector<int> res = {9, 8, 4, 1};
ASSERT_TRUE(VectorsMatch(res, result));
path.clear();
ASSERT_FALSE(find(&peter, &bill, path));
}
TEST(TestFindNonRecursive, Positive)
{
Employee bill = Employee(9, "Bill");
Employee dom = Employee(8, "Dom");
Employee samir = Employee(7, "Samir");
Employee michael = Employee(6, "Michael");
bill.addReport(&dom);
bill.addReport(&samir);
bill.addReport(&michael);
Employee bob = Employee(5, "Bob");
Employee peter = Employee(4, "Peter");
Employee porter = Employee(3, "Porter");
dom.addReport(&bob);
dom.addReport(&peter);
dom.addReport(&porter);
Employee milton = Employee(2, "Milton");
Employee nina = Employee(1, "Nina");
peter.addReport(&milton);
peter.addReport(&nina);
vector<Employee*> path;
ASSERT_TRUE(findNonRecursive(&bill, &nina, path));
vector<int> result;
for (int i = 0; i < path.size(); ++i)
result.push_back(path[i]->getId());
vector<int> res = {9, 8, 4, 1};
ASSERT_TRUE(VectorsMatch(res, result));
path.clear();
ASSERT_FALSE(findNonRecursive(&peter, &bill, path));
}
TEST(TestClosestCommonManager, Positive)
{
Employee bill = Employee(9, "Bill");
Employee dom = Employee(8, "Dom");
Employee samir = Employee(7, "Samir");
Employee michael = Employee(6, "Michael");
bill.addReport(&dom);
bill.addReport(&samir);
bill.addReport(&michael);
Employee bob = Employee(5, "Bob");
Employee peter = Employee(4, "Peter");
Employee porter = Employee(3, "Porter");
dom.addReport(&bob);
dom.addReport(&peter);
dom.addReport(&porter);
Employee milton = Employee(2, "Milton");
Employee nina = Employee(1, "Nina");
peter.addReport(&milton);
peter.addReport(&nina);
Employee* p = closestCommonManager(&bill, &milton, &nina);
ASSERT_EQ(4, p->getId());
ASSERT_TRUE(nullptr == closestCommonManager(&peter, &bill, &porter));
p = closestCommonManager(&bill, &bill, &bill);
ASSERT_EQ(9, p->getId());
p = closestCommonManager(&bill, &dom, &samir);
ASSERT_EQ(9, p->getId());
p = closestCommonManager(&bill, &dom, &dom);
ASSERT_EQ(9, p->getId());
p = closestCommonManager(&bill, &nina, &nina);
ASSERT_EQ(4, p->getId());
}
<file_sep>//
// InPlaceFilter.hpp
// algo
//
// Created by raof01 on 5/17/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#ifndef algo_InPlaceFilter_hpp
#define algo_InPlaceFilter_hpp
#include <functional>
template <typename T, int N>
void Filter(T(&a)[N], T (&t)[N], std::pointer_to_unary_function<const T&, bool> predicate, int& end)
{
int dest = 0;
for (int src = 0; src < N; ++src)
if (predicate(a[src])) t[dest++] = a[src];
end = dest;
}
template <typename T, int N>
void FilterInPlace(T(&a)[N], std::pointer_to_unary_function<const T&, bool> predicate, int& start, int& end)
{
if (start >= N) return;
if (start < 0) start = 0;
// Why while (!predicate(a[start++])); runs to 2nd of predicate() true?
while (!predicate(a[start]) && start < N)
++start;
int cur = start;
while (predicate(a[cur++]));
--cur;
for (int next = cur + 1; next < N;)
{
if (!predicate(a[next])) ++next;
else
a[cur++] = a[next++];
}
end = cur;
}
#endif
<file_sep>//
// IsPalindromeTest.cpp
// algo
//
// Created by raof01 on 7/11/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#include "gtest/gtest.h"
#include "IsPalindrome.h"
#include <stdlib.h>
TEST(TestReverseToNewList, EmptyList)
{
ASSERT_EQ(nullptr, ReverseToNewList(nullptr));
}
TEST(TestReverseToNewList, ListWithOneNode)
{
ListNode* p = ListAppend(nullptr, 0);
ListNode* n = ReverseToNewList(p);
ASSERT_EQ(ListLength(p), ListLength(n));
ASSERT_EQ(GetValue(p), GetValue(n));
ListDestroy(p);
ListDestroy(n);
}
TEST(TestReverseToNewList, ListWithTenNodes)
{
ListNode* p = nullptr;
for (int i = 0; i < 10; ++i)
p = ListAppend(p, i);
ListNode* q = ReverseToNewList(p);
ASSERT_EQ(ListLength(p), ListLength(q));
ListNode* n = q;
int i = 10;
while (n != nullptr)
{
ASSERT_EQ(--i, GetValue(n));
n = GetNext(n);
}
ListDestroy(p);
ListDestroy(q);
}
TEST(TestIsPalindrome, EmptyList)
{
ASSERT_TRUE(isPalindrome(nullptr));
}
TEST(TestIsPalindrome, ListWithOneNode)
{
ListNode* p = ListAppend(nullptr, 10);
ASSERT_TRUE(isPalindrome(p));
}
TEST(TestIsPalindrome, ListWithTwoDifferentValuedNodes)
{
ListNode* p = ListAppend(nullptr, 10);
p = ListAppend(p, 8);
ASSERT_FALSE(isPalindrome(p));
}
TEST(TestIsPalindrome, ListWithTwoSameValuedNodes)
{
ListNode* p = ListAppend(nullptr, 10);
p = ListAppend(p, 10);
ASSERT_TRUE(isPalindrome(p));
}
TEST(TestIsPalindrome, ListWithThreeSameValuedNodes)
{
ListNode* p = ListAppend(nullptr, 10);
p = ListAppend(p, 10);
p = ListAppend(p, 10);
ASSERT_TRUE(isPalindrome(p));
}
TEST(TestIsPalindrome, PalindromeListWithThreeNodes)
{
ListNode* p = ListAppend(nullptr, 10);
p = ListAppend(p, 8);
p = ListAppend(p, 10);
ASSERT_TRUE(isPalindrome(p));
}
<file_sep>//
// Created by raof01 on 9/20/15.
//
#include "BitManipulation.h"
#include "gtest/gtest.h"
TEST(TestIsBitSet, ReturnFalseWhenPositionInvalid) {
unsigned int v = 0xF8587612;
ASSERT_FALSE(IsBitSet(v, -1));
ASSERT_FALSE(IsBitSet(v, 32));
}
TEST(TestIsBitSet, WhenPositionValid) {
unsigned int v = 0xF8587612;
ASSERT_FALSE(IsBitSet(v, 0));
ASSERT_TRUE(IsBitSet(v, 31));
ASSERT_TRUE(IsBitSet(v, 12));
ASSERT_TRUE(IsBitSet(v, 13));
ASSERT_FALSE(IsBitSet(v, 11));
}
TEST(TestSetBit, ReturnFalseWhenPositionInvalid) {
unsigned int v = 0xF8587612;
ASSERT_FALSE(SetBit(v, -1));
ASSERT_FALSE(SetBit(v, 32));
}
TEST(TestSetBit, WhenPositionValid) {
unsigned int v = 0xF8587612;
ASSERT_TRUE(SetBit(v, 0));
ASSERT_EQ(0xF8587613, v);
ASSERT_TRUE(SetBit(v, 31));
ASSERT_EQ(0xF8587613, v);
ASSERT_TRUE(SetBit(v, 12));
ASSERT_EQ(0xF8587613, v);
ASSERT_TRUE(SetBit(v, 13));
ASSERT_EQ(0xF8587613, v);
ASSERT_TRUE(SetBit(v, 11));
ASSERT_EQ(0xF8587E13, v);
}
TEST(TestClearBit, WhenPositionValid) {
unsigned int v = 0xF8587612;
ASSERT_TRUE(ClearBit(v, 0));
ASSERT_EQ(0xF8587612, v);
ASSERT_TRUE(ClearBit(v, 31));
ASSERT_EQ(0x78587612, v);
ASSERT_TRUE(ClearBit(v, 12));
ASSERT_EQ(0x78586612, v);
ASSERT_TRUE(ClearBit(v, 13));
ASSERT_EQ(0x78584612, v);
ASSERT_TRUE(ClearBit(v, 11));
ASSERT_EQ(0x78584612, v);
}
TEST(TestClearBitsMSBThroughInclusive, WhenPositionValid) {
unsigned int v = 0xF8587612;
ASSERT_TRUE(ClearBitsMSBThroughInclusive(v, 31));
ASSERT_EQ(0x78587612, v);
ASSERT_TRUE(ClearBitsMSBThroughInclusive(v, 27));
ASSERT_EQ(0x00587612, v);
ASSERT_TRUE(ClearBitsMSBThroughInclusive(v, 21));
ASSERT_EQ(0x00187612, v);
v = 0xF8587612;
ASSERT_TRUE(ClearBitsMSBThroughInclusive(v, 13));
ASSERT_EQ(0x00001612, v);
ASSERT_TRUE(ClearBitsMSBThroughInclusive(v, 11));
ASSERT_EQ(0x00000612, v);
}
TEST(TestClearBitsLSBThroughInclusive, WhenPositionValid) {
unsigned int v = 0xF8587612;
ASSERT_TRUE(ClearBitsLSBThroughInclusive(v, 31));
ASSERT_EQ(0, v);
v = 0xF8587612;
ASSERT_TRUE(ClearBitsLSBThroughInclusive(v, 27));
ASSERT_EQ(0xF0000000, v);
v = 0xF8587612;
ASSERT_TRUE(ClearBitsLSBThroughInclusive(v, 21));
ASSERT_EQ(0xF8400000, v);
v = 0xF8587612;
ASSERT_TRUE(ClearBitsLSBThroughInclusive(v, 13));
ASSERT_EQ(0xF8584000, v);
v = 0xF8587612;
ASSERT_TRUE(ClearBitsLSBThroughInclusive(v, 11));
ASSERT_EQ(0xF8587000, v);
}
#if 0
TEST(TestDoubleTo32BitBinary, WhenCanNotFitIn) {
double d = 0.7912121313;
std::vector<unsigned char> v;
ASSERT_FALSE(DoubleTo32BitBinary(d, v));
}
TEST(TestDoubleTo32BitBinary, Positive) {
double d = 0.79;
std::vector<unsigned char> v;
ASSERT_FALSE(DoubleTo32BitBinary(d, v));
}
#endif
TEST(TestCountSetBits, SampleInputs) {
ASSERT_EQ(0, CountSetBits(0));
ASSERT_EQ(31, CountSetBits(-5));
ASSERT_EQ(1, CountSetBits(1));
ASSERT_EQ(1, CountSetBits(2));
ASSERT_EQ(2, CountSetBits(3));
ASSERT_EQ(15, CountSetBits(0xF8587612));
}
TEST(TestBitsNeededToConvert, SampleInputs) {
ASSERT_EQ(2, BitsNeededToConvert(31,14));
}
TEST(TestNextPositive, SampleInputs) {
unsigned int smallest = 0;
unsigned int largest = 0;
ASSERT_TRUE(NextPositive(13, smallest, largest));
ASSERT_EQ(0x7, smallest);
ASSERT_EQ(0x70000000, largest);
}
TEST(TestSwapEvenAndOddBits, SampleInputs) {
ASSERT_EQ(0x5E, SwapEvenAndOddBits(0xAD));
}
<file_sep>//
// SingleLinkedList.cpp
// algo
//
// Created by raof01 on 5/8/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#include <stdlib.h>
#include "SingleLinkedList.h"
struct Node
{
Node(): mNext(nullptr), mValue(-1) {}
Node(int v) : mNext(nullptr), mValue(v) {}
Node(Node* n, int v) : mNext(n), mValue(v) {}
Node* mNext;
int mValue;
};
bool operator == (const SingleLinkedList::Iterator& lhs, const SingleLinkedList::Iterator& rhs)
{
if (&lhs == &rhs || lhs.mCur == rhs.mCur) return true;
return false;
}
bool operator != (const SingleLinkedList::Iterator& lhs, const SingleLinkedList::Iterator& rhs)
{
return ! (lhs == rhs);
}
int SingleLinkedList::Iterator::operator *()
{
return mCur->mValue;
}
// !!!Attention: the return type of prefix ++
SingleLinkedList::Iterator& SingleLinkedList::_Iterator::operator++()
{
mCur = mCur->mNext;
return *this;
}
// !!!Attention: the return type of postfix ++
SingleLinkedList::Iterator SingleLinkedList::_Iterator::operator++(int)
{
SingleLinkedList::Iterator tmp = *this;
mCur = mCur->mNext;
return tmp;
}
SingleLinkedList::Iterator SingleLinkedList::_Iterator::operator+(int k)
{
SingleLinkedList::Iterator tmp = *this;
while (k-- && tmp != Iterator(nullptr))
++tmp;
return k >= 0 ? Iterator(nullptr) : tmp;
}
SingleLinkedList::~SingleLinkedList()
{
while (!Empty())
{
Node* p = mHead->mNext;
delete mHead;
mHead = p;
}
}
void SingleLinkedList::Insert(int v)
{
// Implicit but simple
mHead = new Node(mHead, v);
}
void SingleLinkedList::Append(int v)
{
// !!!Attention: special case - empty list
if (Empty())
{
mHead = new Node(v);
return;
}
Node* p = mHead;
while (p->mNext != nullptr) p = p->mNext;
p->mNext = new Node(v);
}
bool SingleLinkedList::Empty()
{
return mHead == nullptr;
}
Node* SingleLinkedList::FindImpl(int v)
{
Node* p = mHead;
while (p != nullptr && p->mValue != v) p = p->mNext;
return p;
}
SingleLinkedList::Iterator SingleLinkedList::Find(int v)
{
return Iterator(FindImpl(v));
}
void SingleLinkedList::Delete(int v)
{
DeleteImpl(v);
}
void SingleLinkedList::DeleteAll(int v)
{
while (DeleteImpl(v));
}
void SingleLinkedList::Reverse()
{
if (Empty()) return;
Node* prev = nullptr;
Node* mNext = mHead->mNext;
while (mNext != nullptr)
{
mHead->mNext = prev;
prev = mHead;
mHead = mNext;
mNext = mHead->mNext;
}
mHead->mNext = prev;
}
bool SingleLinkedList::DeleteImpl(int v)
{
// !!!Attention: prev is mandatory, otherwise, when deleting last element,
// the new last element has non-nullptr mNext
Node* prev = 0;
Node* p = mHead;
while (p != nullptr && p->mValue != v)
{
prev = p;
p = p->mNext;
}
if (p != nullptr)
{
// !!!Attention: special case - the mHead is to be deleted
if (mHead == p)
{
mHead = p->mNext;
delete p;
}
else
{
prev->mNext = p->mNext;
delete p;
}
return true;
}
else
{
return false;
}
}
size_t SingleLinkedList::Count()
{
size_t cnt = 0;
for (Node* p = mHead; p != nullptr; p = p->mNext)
++cnt;
return cnt;
}
SingleLinkedList::Iterator SingleLinkedList::Begin()
{
return Iterator(mHead);
}
SingleLinkedList::Iterator SingleLinkedList::End()
{
return Iterator(nullptr);
}
<file_sep>//
// Created by raof01 on 9/6/15.
//
#include "gtest/gtest.h"
#include "ArraysMatch.hpp"
#include "ReverseString.h"
TEST(TestReverseString, StringWithOneChar)
{
char a[] = "a";
char r[] = "a";
ReverseString(a);
ASSERT_TRUE(ArraysMatch(r, a));
}
TEST(TestReverseString, StringWithTwoChars)
{
char a[] = "ab";
char r[] = "ba";
ReverseString(a);
ASSERT_TRUE(ArraysMatch(r, a));
}
TEST(TestReverseString, StringWithThreeChars)
{
char a[] = "abc";
char r[] = "cba";
ReverseString(a);
ASSERT_TRUE(ArraysMatch(r, a));
}
TEST(TestReverseString, StringWithArbitaryNumOfChars)
{
char a[] = "abc!123";
char r[] = "321!cba";
ReverseString(a);
ASSERT_TRUE(ArraysMatch(r, a));
}
<file_sep>//
// Created by raof01 on 9/24/15.
//
#ifndef ALGO_MAGICINDEX_H
#define ALGO_MAGICINDEX_H
#include <stddef.h>
#include <algorithm>
#include <vector>
/*
* Magic index is that: the index equals to array[index]
* Precondition:
* Sorted array
* 1. Without duplicates 2. with duplicates
*/
template <size_t N>
class MagicIndexFinder {
public:
static int MagicIndexNoDup(const int (&)[N]);
static int MagicIndexWithDup(const int (&)[N]);
static size_t GetAllMagicIndicesWithDup(const int(&)[N], std::vector<int>&);
private:
static int MagicIndexWithoutDuplicates(const int (&)[N], int, int);
static int MagicIndexWithDuplicates(const int (&)[N], int, int);
};
template <size_t N>
int MagicIndexFinder<N>::MagicIndexWithoutDuplicates(const int (&arr)[N],
int start,
int end) {
if (start < 0 || end < start) return -1;
int mid = (start + end) / 2;
if (arr[mid] == mid) return mid;
if (arr[mid] > mid)
return MagicIndexWithoutDuplicates(arr, start, mid - 1);
return MagicIndexWithoutDuplicates(arr, mid + 1, end);
}
template <size_t N>
int MagicIndexFinder<N>::MagicIndexNoDup(const int (&arr)[N]) {
return MagicIndexWithoutDuplicates(arr, 0, N -1);
}
template <size_t N>
int MagicIndexFinder<N>::MagicIndexWithDup(const int (&arr)[N]) {
return MagicIndexWithDuplicates(arr, 0, N - 1);
}
template <size_t N>
size_t MagicIndexFinder<N>::GetAllMagicIndicesWithDup(const int(&arr)[N],
std::vector<int>& indices) {
indices.clear();
for (int start = 0; start != -1; ) {
start = MagicIndexWithDuplicates(arr, start, N - 1);
if (start != -1) {
indices.push_back(start);
++start;
}
}
return indices.size();
}
template <size_t N>
int MagicIndexFinder<N>::MagicIndexWithDuplicates(const int (&arr)[N],
int start,
int end) {
if (start < 0 || end < start) return -1;
int mid = (start + end) / 2;
if (arr[mid] == mid) return mid;
int leftIndex = std::min(mid - 1, arr[mid]);
int index = MagicIndexWithDuplicates(arr, start, leftIndex);
if (index > 0) return index;
int rightIndex = std::max(mid + 1, arr[mid]);
return MagicIndexWithDuplicates(arr, rightIndex, end);
}
#endif //ALGO_MAGICINDEX_H
<file_sep>//
// HeapSortTest.cpp
// algo
//
// Created by raof01 on 5/6/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#include "gtest/gtest.h"
#include "HeapSort.hpp"
#include "ArraysMatch.hpp"
TEST(TestMaxHeapify, HeapifyFromZero)
{
int a[] = {4, 5, 2, 6, 4, 7, 8};
int r[] = {5, 6, 2, 4, 4, 7, 8};
HeapSorter<int>::MaxHeapify(a, 0);
ASSERT_TRUE(ArraysMatch(a, r));
}
TEST(TestMaxHeapify, HeapifyFromZeroWithThirteenElems)
{
int a[] = {3, 7, 5, 0, 6, 8, 7, 9, 8, 2, 1, 6, 10};
int r[] = {7, 6, 5, 0, 3, 8, 7, 9, 8, 2, 1, 6, 10};
HeapSorter<int>::MaxHeapify(a, 0);
ASSERT_TRUE(ArraysMatch(a, r));
}
TEST(TestMaxHeapify, HeapifyFromOne)
{
int a[] = {0, 1, 2, 3, 4, 5, 6, 7, 8};
int r[] = {0, 4, 2, 3, 1, 5, 6, 7, 8};
HeapSorter<int>::MaxHeapify(a, 1);
ASSERT_TRUE(ArraysMatch(a, r));
}
TEST(TestMaxHeapify, HeapifyFromThree)
{
int a[] = {0, 1, 2, 3, 4, 5, 6, 7, 8};
int r[] = {0, 1, 2, 8, 4, 5, 6, 7, 3};
HeapSorter<int>::MaxHeapify(a, 3);
ASSERT_TRUE(ArraysMatch(a, r));
}
TEST(TestMaxHeapifyIter, HeapifyFromZero)
{
int a[] = {4, 5, 2, 6, 4, 7, 8};
int r[] = {5, 6, 2, 4, 4, 7, 8};
HeapSorter<int>::MaxHeapifyIter(a, 0);
ASSERT_TRUE(ArraysMatch(a, r));
}
TEST(TestMaxHeapifyIter, HeapifyFromOne)
{
int a[] = {0, 1, 2, 3, 4, 5, 6, 7, 8};
int r[] = {0, 4, 2, 3, 1, 5, 6, 7, 8};
HeapSorter<int>::MaxHeapifyIter(a, 1);
ASSERT_TRUE(ArraysMatch(a, r));
}
TEST(TestMaxHeapifyIter, HeapifyFromZeroWithThirteenElems)
{
int a[] = {3, 7, 5, 0, 6, 8, 7, 9, 8, 2, 1, 6, 10};
int r[] = {7, 6, 5, 0, 3, 8, 7, 9, 8, 2, 1, 6, 10};
HeapSorter<int>::MaxHeapifyIter(a, 0);
ASSERT_TRUE(ArraysMatch(a, r));
}
TEST(TestMaxHeapifyIter, HeapifyFromThree)
{
int a[] = {0, 1, 2, 3, 4, 5, 6, 7, 8};
int r[] = {0, 1, 2, 8, 4, 5, 6, 7, 3};
HeapSorter<int>::MaxHeapifyIter(a, 3);
ASSERT_TRUE(ArraysMatch(a, r));
}
TEST(TestHeapSort, Positive)
{
int a[] = {4, 1, 3, 2, 16, 9, 10, 14, 8, 7};
int r[] = {1, 2, 3, 4, 7, 8, 9, 10, 14, 16};
HeapSorter<int>::Sort(a);
ASSERT_TRUE(ArraysMatch(a, r));
}
TEST(TestHeapSortIter, Positive)
{
int a[] = {4, 1, 3, 2, 16, 9, 10, 14, 8, 7};
int r[] = {1, 2, 3, 4, 7, 8, 9, 10, 14, 16};
HeapSorter<int>::SortNonRecursive(a);
ASSERT_TRUE(ArraysMatch(a, r));
}
TEST(TestSortUsingSink, Positive)
{
int a[] = {4, 1, 3, 2, 16, 9, 10, 14, 8, 7};
int r[] = {1, 2, 3, 4, 7, 8, 9, 10, 14, 16};
HeapSorter<int>::SortUsingSink(a);
ASSERT_TRUE(ArraysMatch(a, r));
}
<file_sep>//
// WireTestFunc.h
// algo
//
// Created by raof01 on 8/4/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#ifndef algo_WireTestFunc_h
#define algo_WireTestFunc_h
#define WIRE_TEST_F(TestFixtureClass, TestMemberFunction) \
TEST_F(TestFixtureClass, TestMemberFunction) \
{ \
TestFixtureClass::TestMemberFunction(); \
}
#endif
<file_sep>//
// RBTree.cpp
// algo
//
// Created by raof01 on 6/17/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#include "RBTree.h"
struct RBTree::Node
{
int mValue;
Color mColor;
Node* mLeft;
Node* mRight;
Node* mParent;
Node(int v, Color c = RED, Node* l = 0, Node* r = 0, Node* p = 0)
: mValue(v), mColor(c), mLeft(l), mRight(r), mParent(p) {}
};
//const RBTree::Node* RBTree::0 = new RBTree::Node(0);
RBTree::RBTree()
: mRoot(0)
, mCnt(0)
{
}
RBTree::~RBTree()
{
if (mRoot != 0)
DeleteTree(mRoot);
mCnt = 0;
}
void RBTree::DeleteTree(Node*& n)
{
if (n != 0)
{
DeleteTree(n->mLeft);
DeleteTree(n->mRight);
delete n;
n = 0;
}
}
void RBTree::Insert(int v)
{
Node* n = new Node(v);
++mCnt;
Node* cur = mRoot;
Node* parent = 0;
while (cur != 0)
{
parent = cur;
if (v < cur->mValue)
cur = cur->mLeft;
else
cur = cur->mRight;
}
if (parent == 0) mRoot = n;
else
{
if (v < parent->mValue)
parent->mLeft = n;
else
parent->mRight = n;
// TODO
}
}
void RBTree::Delete(int)
{
}
void RBTree::InOrderTraversal(Visitor<int, false>&) const
{
}
void RBTree::PreOrderTraversal(Visitor<int, false>&) const
{
}
void RBTree::PostOrderTraversal(Visitor<int, false>&) const
{
}
void RBTree::BreadthFirstTraversal(Visitor<int, false>&) const
{
}
void RBTree::DepthFirstTraversal(Visitor<int, false>&) const
{
}
int RBTree::GetMaxValue() const
{
return -1;
}
int RBTree::GetMinValue() const
{
return -1;
}
bool RBTree::Find(int) const
{
return false;
}
bool RBTree::GetParentValue(int, int&) const
{
return false;
}
bool RBTree::GetSuccessorValue(int, int&) const
{
return false;
}
bool RBTree::GetPredecessorValue(int, int&) const
{
return false;
}
int RBTree::GetCount() const
{
return mCnt;
}
void RBTree::Invert()
{
}
void RBTree::LeftRotate(Node* x)
{
if (x->mRight == 0) return;
Node* p = x->mParent;
Node* r = x->mRight;
// Set left child of r to x's right child
x->mRight = r->mLeft;
if (x->mRight != 0)
x->mRight->mParent = x;
// Set y's parent
r->mParent = p;
if (p == 0) // Root
mRoot = r;
else
{
// Set r to x's parent's child
if (x == p->mLeft)
p->mLeft = r;
else
p->mRight = r;
}
// Set x to be y's child
r->mLeft = x;
x->mParent = r;
}
void RBTree::RightRotate(Node* x)
{
if (x->mLeft == 0) return;
Node* p = x->mParent;
Node* l = x->mLeft;
x->mLeft = l->mRight;
if (x->mLeft != 0)
x->mLeft->mParent = x;
l->mParent = p;
if (p == 0)
mRoot = l;
else
{
if (p->mLeft == x)
p->mLeft = l;
else
p->mRight = l;
}
l->mRight = x;
x->mParent = l;
}
void RBTree::Fixup(Node* z)
{
while (z->mParent->mColor == RED)
{
if (z->mParent->mParent->mLeft == z->mParent) // z'parent is on the left sub-tree
{
Node* y = z->mParent->mParent->mRight; // get the z's uncle
if (y->mColor == RED) // z's uncle is red, should be changed
{
y->mColor = BLACK;
z->mParent->mColor = BLACK;
z->mParent->mParent->mColor = RED;
z = z->mParent->mParent; // move z up to point its grand parent
}
else if (z == z->mParent->mRight) // z is on the righ sub-tree
{
z = z->mParent; // move z up to pint its parent
LeftRotate(z);
}
else
{
z->mParent->mColor = BLACK;
z->mParent->mParent->mColor = RED;
RightRotate(z->mParent->mParent);
}
}
else
{
Node* y = z->mParent->mParent->mLeft; // get the z's uncle
if (y->mColor == RED) // z's uncle is red, should be changed
{
y->mColor = BLACK;
z->mParent->mColor = BLACK;
z->mParent->mParent->mColor = RED;
z = z->mParent->mParent; // move z up to point its grand parent
}
else if (z == z->mParent->mLeft) // z is on the left sub-tree
{
z = z->mParent; // move z up to pint its parent
RightRotate(z);
}
else
{
z->mParent->mColor = BLACK;
z->mParent->mParent->mColor = RED;
LeftRotate(z->mParent->mParent);
}
}
}
mRoot->mColor = BLACK;
}
<file_sep>//
// ShellSort.h
// algo
//
// Created by raof01 on 8/2/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#ifndef algo_ShellSort_h
#define algo_ShellSort_h
#include "InsertionSort.hpp"
template <typename Comparable>
class ShellSorter
{
public:
template <size_t N>
static void Sort(Comparable (&input)[N])
{
Sort(input, N);
}
static void Sort(Comparable* input, size_t N)
{
SortImpl(input, N);
}
private:
static void SortImpl(Comparable* input, size_t N)
{
// f(x) = 3x + 1 = N
int x = 1;
size_t n = N;
while (n / 3) { n /= 3; ++x; }
for (int i = x; i > 0; --i)
{
InsertionSorter<int>::Sort(input, N, i);
}
}
};
#endif
<file_sep>//
// Created by raof01 on 8/29/15.
//
#ifndef ALGO_MAXMIN_H
#define ALGO_MAXMIN_H
int Max(int *a, size_t N);
int Min(int *a, size_t N);
void MaxMin(int *a, size_t N, int& max, int& min);
#endif //ALGO_MAXMIN_H
<file_sep>//
// Fibonacci.h
// algo
//
// Created by raof01 on 5/5/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#ifndef __algo__Fibonacci__
#define __algo__Fibonacci__
#include <stdio.h>
// Ignore overflow for now
template <int N, bool isNegative>
struct FibImpl
{
const static size_t Result = FibImpl<N - 1, isNegative>::Result
+ FibImpl<N - 2, isNegative>::Result;
};
template <>
struct FibImpl<0, false>
{
const static size_t Result = 0;
};
template <>
struct FibImpl<1, false>
{
const static size_t Result = 1;
};
template <int N>
struct FibImpl<N, true>
{
const static size_t Result = -1;
};
template <int N>
struct Fib
{
const static size_t Result = FibImpl<N, N < 0>::Result;
};
struct Iter {};
size_t Fibo(int n);
size_t Fibo(int n, const Iter&);
#endif /* defined(__algo__Fibonacci__) */
<file_sep>//
// MinSubArrayLen.h
// algo
//
// Created by raof01 on 5/24/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#ifndef algo_MinSubArrayLen_h
#define algo_MinSubArrayLen_h
#include <vector>
int MinSubArrayLen(int, const std::vector<int>&);
int MinSubArrayLen(int s, const int* nums, int numsSize);
#endif
<file_sep>cmake_minimum_required(VERSION 3.3)
project(algo)
if (${CMAKE_SYSTEM_NAME} MATCHES "Windows")
set(ENV{GTEST_ROOT} "C:/Program Files (x86)/googletest-distribution/")
if (${CMAKE_CXX_COMPILER} MATCHES "Visual Studio")
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} /MT")
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} /MTd")
endif (${CMAKE_CXX_COMPILER} MATCHES "Visual Studio")
add_definitions(-DWIN=1)
FIND_PACKAGE(GTest REQUIRED)
INCLUDE_DIRECTORIES(${GTEST_INCLUDE_DIRS})
endif (${CMAKE_SYSTEM_NAME} MATCHES "Windows")
if (${CMAKE_SYSTEM_NAME} MATCHES "Darwin")
INCLUDE_DIRECTORIES(/Users/raof01/workspace/gTest/gmock-1.7.0/gtest/include)
LINK_DIRECTORIES(/Users/raof01/workspace/gTest/gmock-1.7.0/gtest/lib)
SET(GTEST_LIBRARY gtest)
SET(GTEST_MAIN_LIBRARY gtest_main)
endif (${CMAKE_SYSTEM_NAME} MATCHES "Darwin")
if (${CMAKE_SYSTEM_NAME} MATCHES "Linux")
FIND_PACKAGE(GTest REQUIRED)
INCLUDE_DIRECTORIES(${GTEST_INCLUDE_DIRS})
endif (${CMAKE_SYSTEM_NAME} MATCHES "Linux")
aux_source_directory(. SRC_LIST)
aux_source_directory(algo SRC_LIST)
aux_source_directory(algo/src SRC_LIST)
aux_source_directory(algo/src/Algo SRC_LIST)
aux_source_directory(algo/src/DataStructure SRC_LIST)
aux_source_directory(algo/src/Sorts SRC_LIST)
aux_source_directory(algo/src/String SRC_LIST)
aux_source_directory(algo/src/Algo/DivideAndConquer SRC_LIST)
aux_source_directory(algo/tests SRC_LIST)
aux_source_directory(algo/tests/Algo SRC_LIST)
aux_source_directory(algo/tests/DataStructure SRC_LIST)
aux_source_directory(algo/tests/Sorts SRC_LIST)
aux_source_directory(algo/tests/algo/DivideAndConquer SRC_LIST)
aux_source_directory(algo/tests/String SRC_LIST)
INCLUDE_DIRECTORIES(algo/inc/Algo
algo/inc/Algo/DivideAndConquer
algo/inc/Algo/DP
algo/inc/DataStructure
algo/inc/Sorts
algo/inc/String
algo/inc
algo/tests/inc)
#LINK_DIRECTORIES(/Users/raof01/workspace/gTest/gmock-1.7.0/gtest/lib)
add_executable(${PROJECT_NAME} ${SRC_LIST})
set_property(TARGET ${PROJECT_NAME} PROPERTY CXX_STANDARD 14)
target_link_libraries(${PROJECT_NAME} ${GTEST_LIBRARY} ${GTEST_MAIN_LIBRARY} ${CMAKE_THREAD_LIBS_INIT})
<file_sep>//
// merge_sort.hpp
// algo
//
// Created by raof01 on 5/4/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#ifndef algo_merge_sort_hpp
#define algo_merge_sort_hpp
#include "IsSorted.h"
using namespace std;
template <typename Comparable>
class MergeSorter
{
public:
static void Sort(Comparable* input, size_t N);
template <size_t N>
static void Sort(Comparable (&input)[N]);
static void SortBottomUp(Comparable* input, size_t N);
template <size_t N>
static void SortBottomUp(Comparable (&input)[N]);
private:
static void Merge(Comparable *input, Comparable *aux, size_t start, size_t mid, size_t end);
static void Sort(Comparable* input, Comparable* aux, size_t start, size_t end);
static void SortBottomUpImpl(Comparable* input, size_t N);
};
template <typename Comparable>
void MergeSorter<Comparable>::Sort(Comparable *input, Comparable* aux, size_t start, size_t end)
{
// If end - start is very small, InsertionSort could be used.
if (start + 1 == end) return;
// Caution!!! start + end may wrap around
size_t mid = (start + end) / 2;
Sort(input, aux, start, mid);
Sort(input, aux, mid, end);
// Max of 1st half less than min of 2nd half: Done
if (input[mid - 1] < input[mid]) return;
Merge(input, aux, start, mid, end);
}
template <typename T>
void MergeSorter<T>::Sort(T* input, size_t N)
{
T* aux = new T[N];
Sort(input, aux, 0, N);
delete [] aux;
}
template <typename T>
template <size_t N>
void MergeSorter<T>::Sort(T (&a)[N])
{
Sort(a, N);
}
template <typename Comparable>
void MergeSorter<Comparable>::Merge(Comparable *a, Comparable *aux,
size_t start, size_t mid, size_t end)
{
for (size_t i = start; i < end; ++i)
aux[i] = a[i];
size_t j = start;
size_t k = mid;
for (size_t i = start; i < end; ++i)
{
if (j == mid) a[i] = aux[k++];
else if (k == end) a[i] = aux[j++];
else if (aux[j] > aux[k]) a[i] = aux[k++];
else a[i] = aux[j++];
}
}
template <typename T>
template <size_t N>
void MergeSorter<T>::SortBottomUp(T (&a)[N])
{
SortBottomUp(a, N);
}
template <typename T>
void MergeSorter<T>::SortBottomUp(T* a, size_t N)
{
SortBottomUpImpl(a, N);
}
template <typename T>
void MergeSorter<T>::SortBottomUpImpl(T* a, size_t N)
{
T* aux = new T[N];
for (size_t sz = 1; sz < N; sz += sz)
for (size_t start = 0; start < N - sz; start += sz + sz)
Merge(a, aux, start, start + sz, std::min(start + sz + sz, N));
delete [] aux;
}
#if 0
template <typename T, size_t N>
void Merge(T (&a)[N], size_t start, size_t mid, size_t end)
{
// Now off-by-one with the correct recursion base condition
size_t lSize = mid - start;
// mid is off-by-one of left array, the start (inclusive) of right array
size_t rSize = end - mid;
T* left = new T [lSize];
T* right = new T [rSize];
for (size_t i = 0; i < lSize; ++i)
left[i] = a[start + i];
for (size_t i = 0; i < rSize; ++i)
right[i] = a[mid + i];
size_t l = 0, r = 0, i = start;
for (; i <= end && l < lSize && r < rSize; ++i)
{
if (left[l] < right[r])
a[i] = left[l++];
else
a[i] = right[r++];
}
for (; i <= end; ++i)
{
if (l < lSize)
a[i] = left[l++];
if (r < rSize)
a[i] = right[r++];
}
delete [] left;
delete [] right;
return;
}
template <typename T, size_t N>
void MergeSort(T (&a)[N], size_t start, size_t end)
{
// !!! ATTENTION !!!
// start + 1 == end when only 1 element
// so this is the condition to stop recursion
// By doing so, conventional C array index can be used:
// starting from 0, and off-by-one to indicate last elem
if (start + 1 < end)
{
// !!! Attention: end + start, instead of end - start
size_t mid = (start + end) / 2;
MergeSort<T, N>(a, start, mid);
MergeSort<T, N>(a, mid, end);
Merge<T, N>(a, start, mid, end);
}
}
#endif
#endif
<file_sep>//
// Created by raof01 on 9/13/15.
//
#ifndef ALGO_CSINGLELINKEDLIST_H
#define ALGO_CSINGLELINKEDLIST_H
#include <stddef.h>
#include <memory>
#include <iostream>
#include "Visitor.hpp"
using std::cerr;
using std::endl;
using std::shared_ptr;
using std::weak_ptr;
using std::make_shared;
using std::move;
template <typename T>
struct Node
{
Node(const T& v): val(v), next() {}
Node(const T& v, Node<T>& n) :
val(v), next(make_shared<Node<T>>(n)) {}
~Node() { cerr << __FUNCTION__ << "val = " << val << endl; }
void Visit(Visitor<T, std::is_class<T>::value>& visitor)
{
visitor.Visit(val);
}
T val;
shared_ptr<Node<T>> next;
};
template <typename T>
struct SingleLinkedList
{
SingleLinkedList(): head() {}
~SingleLinkedList() { cerr << __FUNCTION__ << endl; }
SingleLinkedList& Append(const T&);
SingleLinkedList& Insert(const T&);
void Traverse(Visitor<T, std::is_class<T>::value>& visitor);
shared_ptr<Node<T>> head;
};
template <typename T>
SingleLinkedList<T>& SingleLinkedList<T>::Append(const T& v)
{
auto p = make_shared<Node<T>>(v);
if (head == nullptr)
head = p;
else
{
auto c = head;
while (c->next != nullptr) c = c->next;
c->next = p;
}
return *this;
}
template <typename T>
void SingleLinkedList<T>::Traverse(Visitor<T, std::is_class<T>::value>& visitor)
{
auto c = head;
while (c != nullptr)
{
c->Visit(visitor);
c = c->next;
}
}
struct CNode {
CNode(int v) : val(v), next(NULL) {}
CNode(int v, CNode* n) : val(v), next(n) {}
int val;
CNode* next;
};
struct CSingleLinkedList {
CSingleLinkedList() : head(NULL) {}
CSingleLinkedList& Append(int);
CSingleLinkedList& Insert(int);
void Partition(int);
void Destroy();
void Delete(CNode*);
void Delete(int);
void RemoveDup();
const CNode* NthToLast(const CNode*, int, int&) const; // Recursive version
const CNode* NthToLast(int) const; // Non-recursive version
CSingleLinkedList& AddListHeadAsLowest(const CSingleLinkedList &);
CSingleLinkedList& AddListHeadAsHighest(CSingleLinkedList &);
int AddWithCarry(int, int, int&);
int AddListRecursive(CNode*, CNode*);
int Length();
CNode* Find(int v);
bool IsCircular() const;
CNode* IsCircularImpl() const;
CNode* FindCirCleBegin();
void RevertRecursive(CNode*, CNode*&, CNode*&);
CNode* RevertRecursive(CNode*, CNode*&);
CNode* ReverseRecursive(CNode*, CNode*, CNode*);
void Revert();
CNode* Tail();
CNode* head;
};
#endif //ALGO_CSINGLELINKEDLIST_H
<file_sep>//
// QueueTest.cpp
// algo
//
// Created by raof01 on 5/9/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#include "gtest/gtest.h"
#include "Queue.hpp"
TEST(TestQueue, EnqueueWithoutWrap)
{
Queue<int, 5> sut;
ASSERT_TRUE(sut.Empty());
ASSERT_FALSE(sut.Full());
ASSERT_EQ(0, sut.Count());
sut.Enqueue(1);
ASSERT_EQ(1, sut.Count());
sut.Enqueue(2);
ASSERT_EQ(2, sut.Count());
sut.Enqueue(3);
ASSERT_EQ(3, sut.Count());
ASSERT_EQ(5, sut.MaxSize());
ASSERT_FALSE(sut.Full());
ASSERT_FALSE(sut.Empty());
int v1 = -1;
sut.GetHead(v1);
ASSERT_EQ(1, v1);
int v2 = -1;
sut.GetTail(v2);
ASSERT_EQ(3, v2);
}
TEST(TestQueue, EnqueueWithWrap)
{
Queue<int, 5> sut;
ASSERT_TRUE(sut.Empty());
ASSERT_FALSE(sut.Full());
ASSERT_EQ(0, sut.Count());
sut.Enqueue(1);
sut.Enqueue(2);
int v = -1;
sut.Dequeue(v);
sut.Dequeue(v);
sut.Enqueue(1);
ASSERT_EQ(1, sut.Count());
sut.Enqueue(2);
ASSERT_EQ(2, sut.Count());
sut.Enqueue(3);
ASSERT_EQ(3, sut.Count());
sut.Enqueue(4);
ASSERT_EQ(4, sut.Count());
sut.Enqueue(5);
ASSERT_EQ(5, sut.Count());
ASSERT_TRUE(sut.Full());
ASSERT_FALSE(sut.Empty());
int v1 = -1;
sut.GetHead(v1);
ASSERT_EQ(1, v1);
int v2 = -1;
sut.GetTail(v2);
ASSERT_EQ(5, v2);
}
TEST(TestQueue, DequeueWithoutWrap)
{
Queue<int, 3> sut;
ASSERT_TRUE(sut.Empty());
ASSERT_FALSE(sut.Full());
ASSERT_EQ(0, sut.Count());
sut.Enqueue(1);
ASSERT_EQ(1, sut.Count());
sut.Enqueue(2);
ASSERT_EQ(2, sut.Count());
sut.Enqueue(3);
ASSERT_EQ(3, sut.Count());
for (int i = 1; i < 4; ++i)
{
int v = -1;
sut.Dequeue(v);
ASSERT_EQ(i, v);
}
}
TEST(TestQueue, DequeueWithWrap)
{
Queue<int, 3> sut;
ASSERT_TRUE(sut.Empty());
ASSERT_FALSE(sut.Full());
ASSERT_EQ(0, sut.Count());
sut.Enqueue(1);
ASSERT_EQ(1, sut.Count());
sut.Enqueue(2);
ASSERT_EQ(2, sut.Count());
int v = -1;
sut.Dequeue(v);
sut.Dequeue(v);
sut.Enqueue(1);
sut.Enqueue(2);
sut.Enqueue(3);
ASSERT_EQ(3, sut.Count());
for (int i = 1; i < 4; ++i)
{
int v = -1;
sut.Dequeue(v);
ASSERT_EQ(i, v);
}
ASSERT_TRUE(sut.Empty());
}
TEST(TestQueue, Empty)
{
Queue<int, 5> sut;
ASSERT_TRUE(sut.Empty());
ASSERT_FALSE(sut.Full());
ASSERT_EQ(0, sut.Count());
sut.Enqueue(1);
sut.Enqueue(2);
sut.Enqueue(3);
sut.Enqueue(4);
sut.Enqueue(5);
int v;
for (int i = 1; i < 6; ++i)
{
sut.Dequeue(v);
ASSERT_EQ(i, v);
}
ASSERT_TRUE(sut.Empty());
}
TEST(TestQueue, EmptyWithWrap)
{
Queue<int, 3> sut;
ASSERT_TRUE(sut.Empty());
ASSERT_FALSE(sut.Full());
ASSERT_EQ(0, sut.Count());
sut.Enqueue(1);
sut.Enqueue(2);
sut.Enqueue(3);
int v;
sut.Dequeue(v);
sut.Dequeue(v);
sut.Enqueue(v);
sut.Dequeue(v);
sut.Dequeue(v);
ASSERT_TRUE(sut.Empty());
}
TEST(TestQueue, Full)
{
Queue<int, 5> sut;
ASSERT_TRUE(sut.Empty());
ASSERT_FALSE(sut.Full());
ASSERT_EQ(0, sut.Count());
sut.Enqueue(1);
sut.Enqueue(2);
sut.Enqueue(3);
sut.Enqueue(4);
sut.Enqueue(5);
ASSERT_TRUE(sut.Full());
}
TEST(TestQueue, FullWithWrap)
{
Queue<int, 5> sut;
ASSERT_TRUE(sut.Empty());
ASSERT_FALSE(sut.Full());
ASSERT_EQ(0, sut.Count());
sut.Enqueue(1);
sut.Enqueue(2);
int v;
sut.Dequeue(v);
sut.Dequeue(v);
sut.Enqueue(3);
sut.Enqueue(4);
sut.Enqueue(5);
sut.Enqueue(1);
sut.Enqueue(2);
ASSERT_TRUE(sut.Full());
}
TEST(TestQueue, MaxSize)
{
Queue<int, 5> sut;
ASSERT_EQ(5, sut.MaxSize());
Queue<int, 10> sut1;
ASSERT_EQ(10, sut1.MaxSize());
}
TEST(TestQueue, GetTail)
{
Queue<int, 5> sut;
for (int i = 0; i < 5; ++i)
{
sut.Enqueue(i);
int v = -1;
sut.GetTail(v);
ASSERT_EQ(i, v);
}
}
TEST(TestQueue, GetTailWrap)
{
Queue<int, 5> sut;
sut.Enqueue(1);
sut.Enqueue(2);
int v;
sut.Dequeue(v);
sut.Dequeue(v);
for (int i = 0; i < 5; ++i)
{
sut.Enqueue(i);
int v = -1;
sut.GetTail(v);
ASSERT_EQ(i, v);
}
}
TEST(TestQueue, GetHead)
{
Queue<int, 5> sut;
for (int i = 0; i < 5; ++i)
{
sut.Enqueue(i);
int v = -1;
sut.GetHead(v);
ASSERT_EQ(0, v);
}
}
TEST(TestQueue, GetHeadWrap)
{
Queue<int, 5> sut;
sut.Enqueue(1);
sut.Enqueue(2);
int v;
sut.Dequeue(v);
sut.Dequeue(v);
for (int i = 0; i < 5; ++i)
{
sut.Enqueue(i);
int v = -1;
sut.GetHead(v);
ASSERT_EQ(0, v);
}
}
<file_sep>//
// QuickSort.hpp
// algo
//
// Created by raof01 on 5/7/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#ifndef algo_QuickSort_hpp
#define algo_QuickSort_hpp
template <typename Comparable>
class QuickSorter
{
public:
static void Sort(Comparable* input, size_t N);
template <size_t N>
static void Sort(Comparable (&input)[N]);
static void SortWithLessSwap(Comparable* input, size_t N);
template <size_t N>
static void SortWithLessSwap(Comparable (&input)[N]);
static size_t Partition(Comparable* input, size_t start, size_t end);
static size_t PartitionFirstAsPivot(Comparable* input, size_t start, size_t end);
static size_t PartitionWithLessSwap(Comparable* input, size_t start, size_t end);
static void ThreeWayPatition(Comparable* input, size_t start, size_t end, size_t& low, size_t& hi);
static void SortWithThreeWayPartition(Comparable* input, size_t N);
template <size_t N>
static void SortWithThreeWayPartition(Comparable (&input)[N]);
private:
static void SortImpl(Comparable *a, size_t start, size_t end);
static void SortImplFirstAsPivot(Comparable *a, size_t start, size_t end);
static void SortImplWithLessSwap(Comparable *a, size_t start, size_t end);
static void SortImplWithThreeWayPartition(Comparable *a, size_t start, size_t end);
};
template <typename T>
void QuickSorter<T>::SortWithThreeWayPartition(T* input, size_t N)
{
SortImplWithThreeWayPartition(input, 0, N);
}
template <typename T>
template <size_t N>
void QuickSorter<T>::SortWithThreeWayPartition(T (&input)[N])
{
SortWithThreeWayPartition(input, N);
}
template <typename T>
void QuickSorter<T>::SortImplWithThreeWayPartition(T *a, size_t start, size_t end)
{
if (start >= end) return;
size_t lo = 0; size_t hi = 0;
ThreeWayPatition(a, start, end, lo, hi);
SortImplWithThreeWayPartition(a, start, lo);
SortImplWithThreeWayPartition(a, hi, end);
}
template <typename T>
void QuickSorter<T>::ThreeWayPatition(T* input, size_t start, size_t end, size_t& low, size_t& hi)
{
size_t eq = start;
low = start;
hi = end;
T v = input[start];
while (hi > eq)
{
if (input[eq] < v) std::swap(input[low++], input[eq++]);
else if (input[eq] > v) std::swap(input[--hi], input[eq]);
else if (input[eq] == v) ++eq;
}
}
template <typename T>
size_t QuickSorter<T>::Partition(T *a, size_t start, size_t end)
{
size_t p = start - 1;
for (size_t i = start; i < end - 1; ++i)
if (a[i] <= a[end - 1])
std::swap(a[i], a[++p]);
std::swap(a[++p], a[end - 1]);
return p;
}
template <typename T>
size_t QuickSorter<T>::PartitionFirstAsPivot(T *a, size_t start, size_t end)
{
size_t p = start;
for (size_t i = start + 1; i < end; ++i)
if (a[i] <= a[start])
std::swap(a[i], a[++p]);
std::swap(a[p], a[start]);
return p;
}
template <typename T>
void QuickSorter<T>::SortImpl(T *a, size_t start, size_t end)
{
if (start < end)
{
size_t p = Partition(a, start, end);
SortImpl(a, start, p);
SortImpl(a, p + 1, end);
}
}
template <typename T>
void QuickSorter<T>::SortImplFirstAsPivot(T *a, size_t start, size_t end)
{
if (start < end)
{
size_t p = PartitionFirstAsPivot(a, start, end);
SortImplFirstAsPivot(a, start, p);
SortImplFirstAsPivot(a, p + 1, end);
}
}
template <typename T>
template <size_t N>
void QuickSorter<T>::Sort(T (&input)[N])
{
Sort(input, N);
}
template <typename T>
void QuickSorter<T>::Sort(T* a, size_t N)
{
SortImplFirstAsPivot(a, 0, N);
}
template <typename T>
size_t QuickSorter<T>::PartitionWithLessSwap(T* input, size_t start, size_t end)
{
// Well, it's hard to get the code below run correctly
size_t lo = start;
size_t hi = end;
while (true)
{
// between lo and hi
while (input[++lo] < input[start]) // first value larger than pivot
if (lo == end) break;
while (input[--hi] > input[start]) // first value less than pivot
if (hi == start) break;
if (lo >= hi) break;
std::swap(input[lo], input[hi]);
}
std::swap(input[start], input[hi]);
return hi;
}
template <typename T>
void QuickSorter<T>::SortImplWithLessSwap(T *a, size_t start, size_t end)
{
if (start >= end) return;
size_t p = PartitionWithLessSwap(a, start, end);
SortImplWithLessSwap(a, start, p);
SortImplWithLessSwap(a, p + 1, end);
}
template <typename T>
void QuickSorter<T>::SortWithLessSwap(T* input, size_t N)
{
SortImplWithLessSwap(input, 0, N);
}
template <typename T>
template <size_t N>
void QuickSorter<T>::SortWithLessSwap(T (&input)[N])
{
SortWithLessSwap(input, N);
}
#endif
<file_sep>//
// FindDupIntTest.cpp
// algo
//
// Created by <NAME> on 9/28/15.
// Copyright © 2015 raof01. All rights reserved.
//
#include "gtest/gtest.h"
#include "FindDupInt.h"
TEST(TestFindDupInt, WhenNIsOne) {
int a[] = {1, 1};
int firstPos = -1;
int secondPos = -1;
FindDupInt(a, firstPos, secondPos);
ASSERT_EQ(0, firstPos);
ASSERT_EQ(1, secondPos);
}
TEST(TestFindDupInt, WhenNIsTwo) {
int a[] = {1, 1, 2};
int firstPos = -1;
int secondPos = -1;
FindDupInt(a, firstPos, secondPos);
ASSERT_EQ(0, firstPos);
ASSERT_EQ(1, secondPos);
int b[] = {2, 1, 1};
FindDupInt(b, firstPos, secondPos);
ASSERT_EQ(1, firstPos);
ASSERT_EQ(2, secondPos);
}
TEST(TestFindDuplicate, SampleInput) {
vector<int> a = {1, 3, 4, 2, 2};
ASSERT_EQ(2, FindDuplicate(a));
}
TEST(TestFindDuplicate, TwoIntegers) {
vector<int> a = {1, 1};
ASSERT_EQ(1, FindDuplicate(a));
}
TEST(TestFindDuplicate, ThreeIntegers) {
vector<int> a = {1, 1, 2};
ASSERT_EQ(1, FindDuplicate(a));
}
TEST(TestFindDuplicate, SampleInput2) {
vector<int> a = {2,5,9,6,9,3,8,9,7,1};
ASSERT_EQ(9, FindDuplicate(a));
}
<file_sep>//
// Created by raof01 on 9/16/15.
//
#ifndef ALGO_CBINARYTREE_H
#define ALGO_CBINARYTREE_H
#include <stddef.h>
#include <vector>
#include "CSingleLinkedList.h"
struct CBTNode {
int val;
CBTNode* left;
CBTNode* right;
CBTNode(int v, CBTNode* l = NULL, CBTNode* r = NULL)
: val(v), left(l), right(r)
{}
};
struct CBinaryTree {
CBinaryTree() : root(NULL) {}
CBTNode* root;
CBinaryTree& Insert(int);
~CBinaryTree() { Destroy(root); }
int Height() const { return Height(root); }
bool IsBalanced() const;
bool IsBinarySearchTree() const;
void BuildTreeFromList(const std::vector<int> &);
std::vector<CSingleLinkedList*>& BuildLevelLinkedLists(std::vector<CSingleLinkedList*>&);
const CBTNode * Find(int) const;
const CBTNode* CommonAncestor(int, int) const;
bool ContainsTree(const CBTNode*) const;
bool FindSum(int, std::vector<int>&) const;
bool FindPathsOfSum(int, std::vector<std::vector<int>>&) const;
private:
void Insert(CBTNode*&, int);
void Destroy(CBTNode*&);
bool IsBalanced(const CBTNode*) const;
int Height(const CBTNode *) const;
int CheckHeight(const CBTNode*) const;
void BuildTreeFromList(CBTNode *&, const std::vector<int> &, int, int);
void BuildLevelLinkedLists(std::vector<CSingleLinkedList*>&, const CBTNode*, int);
bool IsBST(const CBTNode *) const;
bool IsBSTUsingInOrderWithOneOutputArg(const CBTNode *, int &) const;
bool IsBSTUsingInOrderWithTwoArgs(const CBTNode*, int, int) const;
const CBTNode* CommonAncestor(const CBTNode *, const CBTNode*, const CBTNode*) const;
const CBTNode* Find(const CBTNode *, int) const;
bool MatchTree(const CBTNode*, const CBTNode*) const;
bool IsSubTree(const CBTNode*, const CBTNode*) const;
bool ContainsTree(const CBTNode*, const CBTNode*) const;
// Assumption: All positive values in tree.
// Start from root.
// Only one path will be found
bool FindSum(const CBTNode*, int, std::vector<int>&) const;
void FindPathOfSum(const CBTNode*, int, int, std::vector<int>&, std::vector<std::vector<int>>&) const;
// Helpers - can be static in utility class
void AddToPath(std::vector<std::vector<int>>&, const std::vector<int>&, int, int) const;
void InitializeVector(std::vector<int>&, int, int) const;
const CBTNode *LowestCommonAncestor(const CBTNode* root, const CBTNode* p, const CBTNode* q, bool& found) const;
};
#endif //ALGO_CBINARYTREE_H
<file_sep>//
// MaxPriorityQueue.h
// algo
//
// Created by raof01 on 8/11/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#ifndef algo_MaxPriorityQueue_h
#define algo_MaxPriorityQueue_h
template <typename Comparable>
class MaxPriorityQueue
{
public:
virtual bool Insert(const Comparable& v) = 0;
virtual bool DeleteMax(Comparable& v) = 0;
virtual size_t Capacity() = 0;
virtual size_t Count() = 0;
virtual bool IsEmpty() = 0;
virtual bool IsFull() = 0;
virtual ~MaxPriorityQueue() {}
};
#endif
<file_sep>//
// MergeSortTest.cpp
// algo
//
// Created by raof01 on 5/17/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#include "gtest/gtest.h"
#include "ArraysMatch.hpp"
#include "MergeSort.hpp"
static int result[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
static int result1[] = {7, 17, 18, 25, 28, 47, 53, 62, 69, 83, 86, 95};
// MergeSort
TEST(TestMergeSort, Positive)
{
int a[] = {8, 7, 9, 0, 1, 3, 5, 4, 6, 2};
MergeSorter<int>::Sort(a);
ASSERT_TRUE(ArraysMatch(result, a));
}
TEST(TestMergeSort, Positive_Odd)
{
int a[] = {8, 7, 9, 0, 1, 3, 5, 4, 6};
MergeSorter<int>::Sort(a);
int result[] = {0, 1, 3, 4, 5, 6, 7, 8, 9};
ASSERT_TRUE(ArraysMatch(result, a));
}
TEST(TestMergeSort, OneElem)
{
int a[] = {8};
MergeSorter<int>::Sort(a);
ASSERT_TRUE(ArraysMatch(a, a));
}
TEST(TestMergeSort, TwoElems)
{
int a[] = {8, 0};
int result[] = {0, 8};
MergeSorter<int>::Sort(a);
ASSERT_TRUE(ArraysMatch(result, a));
}
TEST(TestMergeSortWithAuxArray, Positive)
{
int a[] = {8, 7, 9, 0, 1, 3, 5, 4, 6, 2};
MergeSorter<int>::Sort(a);
ASSERT_TRUE(ArraysMatch(result, a));
}
TEST(TestMergeSortWithAuxArray, Positive_Odd)
{
int a[] = {8, 7, 9, 0, 1, 3, 5, 4, 6};
int result[] = {0, 1, 3, 4, 5, 6, 7, 8, 9};
MergeSorter<int>::Sort(a);
ASSERT_TRUE(ArraysMatch(result, a));
}
TEST(TestMergeSortWithAuxArray, OneElem)
{
int a[] = {8};
MergeSorter<int>::Sort(a);
ASSERT_TRUE(ArraysMatch(a, a));
}
TEST(TestMergeSortWithAuxArray, TwoElems)
{
int a[] = {8, 0};
int result[] = {0, 8};
MergeSorter<int>::Sort(a);
ASSERT_TRUE(ArraysMatch(result, a));
}
TEST(TestMergeSortWithAuxArray, Positive1)
{
int a[] = {62, 83, 18, 53, 07, 17, 95, 86, 47, 69, 25, 28};
MergeSorter<int>::Sort(a);
ASSERT_TRUE(ArraysMatch(result1, a));
}
TEST(TestMergeSortBottomUp, Positive)
{
int a[] = {8, 7, 9, 0, 1, 3, 5, 4, 6, 2};
MergeSorter<int>::SortBottomUp(a);
ASSERT_TRUE(ArraysMatch(result, a));
}
TEST(TestMergeSortBottomUp, Positive_Odd)
{
int a[] = {8, 7, 9, 0, 1, 3, 5, 4, 6};
int result[] = {0, 1, 3, 4, 5, 6, 7, 8, 9};
MergeSorter<int>::SortBottomUp(a);
ASSERT_TRUE(ArraysMatch(result, a));
}
TEST(TestMergeSortBottomUp, OneElem)
{
int a[] = {8};
MergeSorter<int>::SortBottomUp(a);
ASSERT_TRUE(ArraysMatch(a, a));
}
TEST(TestMergeSortBottomUp, TwoElems)
{
int a[] = {8, 0};
int result[] = {0, 8};
MergeSorter<int>::SortBottomUp(a);
ASSERT_TRUE(ArraysMatch(result, a));
}
TEST(TestMergeSortBottomUp, Positive1)
{
int a[] = {62, 83, 18, 53, 07, 17, 95, 86, 47, 69, 25, 28};
MergeSorter<int>::SortBottomUp(a);
ASSERT_TRUE(ArraysMatch(result1, a));
}
<file_sep>//
// QuickSortTest.cpp
// algo
//
// Created by raof01 on 5/8/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#include "gtest/gtest.h"
#include "QuickSort.hpp"
#include "ArraysMatch.hpp"
TEST(TestPartition, Positive)
{
int a[] = {2, 8, 7, 1, 3, 5, 6, 4};
int r[] = {2, 1, 3, 4, 7, 5, 6, 8};
size_t p = QuickSorter<int>::Partition(a, 0, sizeof(a) / sizeof(int));
ASSERT_TRUE(ArraysMatch(a, r));
ASSERT_EQ(3, p);
}
TEST(TestPartition, PositiveWithOneElem)
{
int a[] = {2};
int r[] = {2};
size_t p = QuickSorter<int>::Partition(a, 0, sizeof(a) / sizeof(int));
ASSERT_TRUE(ArraysMatch(a, r));
ASSERT_EQ(0, p);
}
TEST(TestPartition, PositiveWithTwoElems)
{
int a[] = {8, 2};
int r[] = {2, 8};
size_t p = QuickSorter<int>::Partition(a, 0, sizeof(a) / sizeof(int));
ASSERT_TRUE(ArraysMatch(a, r));
ASSERT_EQ(0, p);
}
TEST(TestPartitionFirstAsPivot, Positive)
{
int a[] = {2, 8, 7, 1, 3, 5, 6, 4};
int r[] = {1, 2, 7, 8, 3, 5, 6, 4};
size_t p = QuickSorter<int>::PartitionFirstAsPivot(a, 0, sizeof(a) / sizeof(int));
ASSERT_TRUE(ArraysMatch(a, r));
ASSERT_EQ(1, p);
}
TEST(TestPartitionFirstAsPivot, PositiveWithOneElem)
{
int a[] = {2};
int r[] = {2};
size_t p = QuickSorter<int>::PartitionFirstAsPivot(a, 0, sizeof(a) / sizeof(int));
ASSERT_TRUE(ArraysMatch(a, r));
ASSERT_EQ(0, p);
}
TEST(TestPartitionFirstAsPivot, PositiveWithTwoElems)
{
int a[] = {8, 2};
int r[] = {2, 8};
size_t p = QuickSorter<int>::PartitionFirstAsPivot(a, 0, sizeof(a) / sizeof(int));
ASSERT_TRUE(ArraysMatch(a, r));
ASSERT_EQ(1, p);
}
TEST(TestQuickSort, Positive)
{
int a[] = {2, 8, 7, 1, 3, 5, 4, 6};
int r[] = {1, 2, 3, 4, 5, 6, 7, 8};
QuickSorter<int>::Sort(a);
ASSERT_TRUE(ArraysMatch(a, r));
}
TEST(TestQuickSortA, Positive)
{
int a[] = {2, 8, 7, 1, 3, 5, 4, 6};
int r[] = {1, 2, 3, 4, 5, 6, 7, 8};
QuickSorter<int>::Sort(a);
ASSERT_TRUE(ArraysMatch(a, r));
}
TEST(TestQuickSort, PositiveWithTenElems)
{
int a[] = {4, 1, 3, 2, 16, 9, 10, 14, 8, 7};
int r[] = {1, 2, 3, 4, 7, 8, 9, 10, 14, 16};
QuickSorter<int>::Sort(a);
ASSERT_TRUE(ArraysMatch(a, r));
}
TEST(TestQuickSortA, PositiveWithTenElems)
{
int a[] = {4, 1, 3, 2, 16, 9, 10, 14, 8, 7};
int r[] = {1, 2, 3, 4, 7, 8, 9, 10, 14, 16};
QuickSorter<int>::Sort(a);
ASSERT_TRUE(ArraysMatch(a, r));
}
TEST(TestQuickSort, PositiveWithOrdered)
{
int a[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
int r[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
QuickSorter<int>::Sort(a);
ASSERT_TRUE(ArraysMatch(a, r));
}
TEST(TestQuickSort, PositiveWithReverseOrdered)
{
int a[] = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
int r[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
QuickSorter<int>::Sort(a);
ASSERT_TRUE(ArraysMatch(a, r));
}
TEST(TestPartitionWithLessSwap, Positive)
{
int a[] = {2, 8, 7, 1, 3, 5, 6, 4};
int r[] = {1, 2, 7, 8, 3, 5, 6, 4};
size_t p = QuickSorter<int>::PartitionWithLessSwap(a, 0, sizeof(a) / sizeof(int));
ASSERT_TRUE(ArraysMatch(a, r));
ASSERT_EQ(1, p);
}
TEST(TestPartitionWithLessSwap, PositiveWithOneElem)
{
int a[] = {2};
int r[] = {2};
size_t p = QuickSorter<int>::PartitionWithLessSwap(a, 0, sizeof(a) / sizeof(int));
ASSERT_TRUE(ArraysMatch(a, r));
ASSERT_EQ(0, p);
}
TEST(TestPartitionWithLessSwap, PositiveWithTwoElems)
{
int a[] = {8, 2};
int r[] = {2, 8};
size_t p = QuickSorter<int>::PartitionWithLessSwap(a, 0, sizeof(a) / sizeof(int));
ASSERT_TRUE(ArraysMatch(a, r));
ASSERT_EQ(1, p);
}
TEST(TestQuickSortWithLessSwap, Positive)
{
int a[] = {2, 8, 7, 1, 3, 5, 4, 6};
int r[] = {1, 2, 3, 4, 5, 6, 7, 8};
QuickSorter<int>::SortWithLessSwap(a);
ASSERT_TRUE(ArraysMatch(a, r));
}
TEST(TestQuickSortWithLessSwap, PositiveWithTenElems)
{
int a[] = {4, 1, 3, 2, 16, 9, 10, 14, 8, 7};
int r[] = {1, 2, 3, 4, 7, 8, 9, 10, 14, 16};
QuickSorter<int>::SortWithLessSwap(a);
ASSERT_TRUE(ArraysMatch(a, r));
}
TEST(TestQuickSortWithLessSwap, PositiveWithOrdered)
{
int a[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
int r[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
QuickSorter<int>::SortWithLessSwap(a);
ASSERT_TRUE(ArraysMatch(a, r));
}
TEST(TestQuickSortWithLessSwap, PositiveWithReverseOrdered)
{
int a[] = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
int r[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
QuickSorter<int>::SortWithLessSwap(a);
ASSERT_TRUE(ArraysMatch(a, r));
}
TEST(TestThreeWayPatition, Positive)
{
int a[] = {5, 7, 4, 6, 5, 9, 3, 6, 5, 0, 5, 0};
int r[] = {0, 4, 0, 3, 5, 5, 5, 5, 6, 9, 6, 7};
size_t low = 0, hi = 0;
QuickSorter<int>::ThreeWayPatition(a, 0, sizeof(a)/sizeof(int), low, hi);
ASSERT_TRUE(ArraysMatch(a, r));
ASSERT_EQ(4, low);
ASSERT_EQ(8, hi);
}
TEST(TestThreeWayPatition, OneElem)
{
int a[] = {5};
int r[] = {5};
size_t low = 0, hi = 0;
QuickSorter<int>::ThreeWayPatition(a, 0, sizeof(a)/sizeof(int), low, hi);
ASSERT_TRUE(ArraysMatch(a, r));
ASSERT_EQ(0, low);
ASSERT_EQ(1, hi);
}
TEST(TestThreeWayPatition, TwoElemsInOrder)
{
int a[] = {2, 5};
int r[] = {2, 5};
size_t low = 0, hi = 0;
QuickSorter<int>::ThreeWayPatition(a, 0, sizeof(a)/sizeof(int), low, hi);
ASSERT_TRUE(ArraysMatch(a, r));
ASSERT_EQ(0, low);
ASSERT_EQ(1, hi);
}
TEST(TestThreeWayPatition, TwoElemsInReverseOrder)
{
int a[] = {5, 2};
int r[] = {2, 5};
size_t low = 0, hi = 0;
QuickSorter<int>::ThreeWayPatition(a, 0, sizeof(a)/sizeof(int), low, hi);
ASSERT_TRUE(ArraysMatch(a, r));
ASSERT_EQ(1, low);
ASSERT_EQ(2, hi);
}
TEST(TestThreeWayPatition, ThreeElemsInOrder)
{
int a[] = {2, 5, 6};
int r[] = {2, 6, 5};
size_t low = 0, hi = 0;
QuickSorter<int>::ThreeWayPatition(a, 0, sizeof(a)/sizeof(int), low, hi);
ASSERT_TRUE(ArraysMatch(a, r));
ASSERT_EQ(0, low);
ASSERT_EQ(1, hi);
}
TEST(TestThreeWayPatition, ThreeElemsInReverseOrder)
{
int a[] = {5, 2, 1};
int r[] = {2, 1, 5};
size_t low = 0, hi = 0;
QuickSorter<int>::ThreeWayPatition(a, 0, sizeof(a)/sizeof(int), low, hi);
ASSERT_TRUE(ArraysMatch(a, r));
ASSERT_EQ(2, low);
ASSERT_EQ(3, hi);
}
TEST(TestSortWithThreeWayPatition, Positive)
{
int a[] = {5, 7, 4, 6, 5, 9, 3, 6, 5, 0, 5, 0};
int r[] = {0, 0, 3, 4, 5, 5, 5, 5, 6, 6, 7, 9};
QuickSorter<int>::SortWithThreeWayPartition(a);
ASSERT_TRUE(ArraysMatch(a, r));
}
TEST(TestSortWithThreeWayPatition, OneElem)
{
int a[] = {5};
int r[] = {5};
QuickSorter<int>::SortWithThreeWayPartition(a);
ASSERT_TRUE(ArraysMatch(a, r));
}
TEST(TestSortWithThreeWayPatition, TwoElemsInOrder)
{
int a[] = {2, 5};
int r[] = {2, 5};
QuickSorter<int>::SortWithThreeWayPartition(a);
ASSERT_TRUE(ArraysMatch(a, r));
}
TEST(TestSortWithThreeWayPatition, TwoElemsInReverseOrder)
{
int a[] = {5, 2};
int r[] = {2, 5};
QuickSorter<int>::SortWithThreeWayPartition(a);
ASSERT_TRUE(ArraysMatch(a, r));
}
TEST(TestSortWithThreeWayPatition, ThreeElemsInOrder)
{
int a[] = {2, 5, 6};
int r[] = {2, 5, 6};
QuickSorter<int>::SortWithThreeWayPartition(a);
ASSERT_TRUE(ArraysMatch(a, r));
}
TEST(TestSortWithThreeWayPatition, ThreeElemsInReverseOrder)
{
int a[] = {5, 2, 1};
int r[] = {1, 2, 5};
QuickSorter<int>::SortWithThreeWayPartition(a);
ASSERT_TRUE(ArraysMatch(a, r));
}
TEST(TestSortWithThreeWayPatition, AllEqualElems)
{
int a[] = {1, 1, 1, 1, 1, 1};
int r[] = {1, 1, 1, 1, 1, 1};
QuickSorter<int>::SortWithThreeWayPartition(a);
ASSERT_TRUE(ArraysMatch(a, r));
}
TEST(TestPartitionWithLessSwap, PositiveDupValues)
{
char a[] = {'B', 'B', 'A', 'B', 'A', 'B', 'B', 'B', 'A', 'B', 'B', 'B'};
char r[] = {'B', 'B', 'A', 'B', 'A', 'B', 'A', 'B', 'B', 'B', 'B', 'B'};
size_t p = QuickSorter<char>::PartitionWithLessSwap(a, 0, sizeof(a) / sizeof(char));
ASSERT_TRUE(ArraysMatch(a, r));
ASSERT_EQ(7, p);
}
TEST(TestSortWithThreeWayPartitionp, PositiveDupValues)
{
char a[] = {'B', 'B', 'A', 'B', 'A', 'B', 'B', 'B', 'A', 'B', 'B', 'B'};
char r[] = {'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B'};
QuickSorter<char>::SortWithThreeWayPartition(a);
ASSERT_TRUE(ArraysMatch(a, r));
}
<file_sep>//
// ConnectionWeightedTreeImpl.h
// algo
//
// Created by raof01 on 7/25/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#ifndef algo_ConnectionWeightedTreeImpl_h
#define algo_ConnectionWeightedTreeImpl_h
#include <vector>
#include "Connection.h"
class ConnectionWeightedTreeImpl : public Connection {
public:
ConnectionWeightedTreeImpl(int);
~ConnectionWeightedTreeImpl();
public:
virtual void ConnectTo(int, int);
virtual bool Connected(int, int);
private:
bool OutOfRange(int);
int Root(int);
private:
std::vector<int> mRoot;
std::vector<int> mWeight;
};
#endif
<file_sep>//
// ShortestPathInMatrix.h
// algo
//
// Created by raof01 on 8/13/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#ifndef algo_ShortestPathInMatrix_h
#define algo_ShortestPathInMatrix_h
/*
class ShortestPathInMatrix
{
public:
int MinLength() const;
};
*/
// Non-OO version
const int MaxWidth = 5;
const int MaxHeight = 5;
const int InvalidMinSteps = -1;
const char Blocked = 'X';
const char CanPass = ' ';
enum Direction
{
East = 0,
South = 1,
West = 2,
North = 3,
Invalid = 4,
};
// Attention: the x is column of array, and the y is row of array.
// The coordination system is:
// -----------------> x
// |
// |
// |
// |
// v
// y
struct Point
{
Point() : x(0), y(0) {}
Point(int vx, int vy) : x(vx), y(vy) {}
int x;
int y;
};
// East South West North
int next[4][2] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
// bool visited[MaxHeight][MaxWidth] = {}; // all false
bool OutOfBound(const Point& p)
{
return (p.x < 0 || p.x >= MaxHeight) || (p.y < 0 || p.y >= MaxWidth);
}
bool Arrived(const char matrix[MaxHeight][MaxWidth], const Point& start, const Point& end)
{
return start.x == end.x && start.y == end.y && matrix[end.y][end.x] == Blocked;
}
bool CanBeVisited(const char matrix[MaxHeight][MaxWidth], const bool visited[MaxHeight][MaxWidth], const Point& p)
{
return !OutOfBound(p) && matrix[p.y][p.x] == CanPass && !visited[p.y][p.x];
}
Point NextPoint(const Point& p, int d)
{
return Point(p.x + next[d][0], p.y + next[d][1]);
}
void Search(const char matrix[MaxHeight][MaxWidth],
bool visited[MaxHeight][MaxWidth],
const Point& start, const Point& dest,
int steps, int& minSteps)
{
// Don't need to try if we already shortes path
if (minSteps != InvalidMinSteps && steps > minSteps) return;
// Try all directions in order of East, South, West, North
for (int d = East; d < Invalid; ++d)
{
// Get next position
Point n = NextPoint(start, d);
// Arrived at destination
if (Arrived(matrix, n, dest))
{
visited[n.y][n.x] = false;
if (minSteps == InvalidMinSteps || steps < minSteps) minSteps = steps;
return;
}
// Valid position
if (CanBeVisited(matrix, visited, n))
{
visited[n.y][n.x] = true;
Search(matrix, visited, n, dest, steps + 1, minSteps);
// Now backtrack
// visited[n.y][n.x] = false;
}
}
}
bool Search(const char matrix[MaxHeight][MaxWidth],
bool visited[MaxHeight][MaxWidth],
const Point& start, const Point& dest,
int steps, int& minSteps, std::vector<Point>& path) {
if (minSteps != InvalidMinSteps && steps > minSteps) return false;
path.push_back(start);
// Try all directions in order of East, South, West, North
for (int d = East; d < Invalid; ++d)
{
// Get next position
Point n = NextPoint(start, d);
// Arrived at destination
if (Arrived(matrix, n, dest))
{
visited[n.y][n.x] = false;
if (minSteps == InvalidMinSteps || steps < minSteps) {
path.push_back(n);
minSteps = steps;
return true;
}
return false;
}
// Valid position
if (CanBeVisited(matrix, visited, n))
{
visited[n.y][n.x] = true;
if (Search(matrix, visited, n, dest, steps + 1, minSteps, path))
return true;
visited[n.y][n.x] = false;
}
}
path.pop_back();
return false;
}
#endif
<file_sep>//
// Created by raof01 on 9/23/15.
//
#include "RouteCalculator.h"
int RouteCalculator::Routes(const Point& start, const Point& end) const {
if (!mGrid.Contains(start) || !mGrid.Contains(end)) return 0;
if (!Grid(start, mGrid.GetBottomRight()).Contains(end)) return 0;
#if 0
return RoutesRecursive(start, end);
#else
std::vector<std::vector<int>> v = std::vector<std::vector<int>>(end.GetY() - start.GetY() + 1);
for (int i = 0; i < v.size(); ++i)
v[i] = std::vector<int>(end.GetX() - start.GetX() + 1, -1);
return RoutesRecursive(start, end, v);
#endif
}
int RouteCalculator::RoutesRecursive(const Point &start,
const Point &end) const {
if (start == end) return 0;
if (start.GetX() == end.GetX() || start.GetY() == end.GetY())
return 1;
return RoutesRecursive(start, end.Left()) +
RoutesRecursive(start, end.Above());
}
int RouteCalculator::RoutesRecursive(const Point &start, const Point &end,
std::vector<std::vector<int>> &vector) const {
if (end == start) return 0;
if (start.GetX() == end.GetX() || start.GetY() == end.GetY())
return 1;
if (vector[end.GetY()][end.GetX()] == -1)
vector[end.GetY()][end.GetX()] = RoutesRecursive(start, end.Left(), vector) +
RoutesRecursive(start, end.Above(), vector);
return vector[end.GetY()][end.GetX()];
}
<file_sep>//
// Created by raof01 on 9/16/15.
//
#include <stddef.h>
#include <algorithm>
#include <stdlib.h>
#include "CBinaryTree.h"
CBinaryTree& CBinaryTree::Insert(int i) {
Insert(root, i);
return *this;
}
void CBinaryTree::Insert(CBTNode*& n, int i) {
if (n == nullptr) {
n = new CBTNode(i);
} else {
if (i < n->val)
Insert(n->left, i);
else if (i > n->val)
Insert(n->right, i);
}
}
void CBinaryTree::Destroy(CBTNode*& n) {
if (n == nullptr) return;
Destroy(n->left);
Destroy(n->right);
delete n;
n = nullptr;
}
int CBinaryTree::Height(const CBTNode *node) const {
if (node == nullptr) return 0;
return std::max(Height(node->left), Height(node->right)) + 1;
}
bool CBinaryTree::IsBalanced() const {
#if 0
return IsBalanced(root);
#endif
return CheckHeight(root) == -1 ? false : true;
}
bool CBinaryTree::IsBalanced(const CBTNode *node) const {
if (node == nullptr) return true;
int delta = abs(Height(node->left) - Height(node->right));
return delta > 1 ? false :
IsBalanced(node->left) && IsBalanced(node->right);
}
int CBinaryTree::CheckHeight(const CBTNode* node) const {
if (node == nullptr) return 0;
int leftHeight = CheckHeight(node->left);
if (leftHeight < 0) return -1;
int rightHeight = CheckHeight(node->right);
if (rightHeight < 0) return -1;
int delta = abs(leftHeight - rightHeight);
if (delta > 1) return -1;
return std::max(leftHeight, rightHeight) + 1;
}
void CBinaryTree::BuildTreeFromList(const std::vector<int> &vector) {
if (root != nullptr) Destroy(root);
BuildTreeFromList(root, vector, 0, static_cast<int>(vector.size() - 1));
}
void CBinaryTree::BuildTreeFromList(CBTNode *&node,
const std::vector<int> &vector, int first,
int last) {
/*
* !!! ATTENTION !!!!
* middle = (last - first) / 2 + first
* This is a common mistake!
*/
if (last < first) return;
size_t mid = (last - first) / 2 + first;
CBTNode* n = new CBTNode(vector[mid]);
if (node == nullptr)
node = n;
BuildTreeFromList(node->left, vector, first, static_cast<int>(mid - 1));
BuildTreeFromList(node->right, vector, static_cast<int>(mid + 1), last);
}
std::vector<CSingleLinkedList*> &CBinaryTree::BuildLevelLinkedLists(std::vector<CSingleLinkedList*>& v) {
BuildLevelLinkedLists(v, root, 0);
return v;
}
void CBinaryTree::BuildLevelLinkedLists(std::vector<CSingleLinkedList*> &vector,
const CBTNode *node, int level) {
if (node == nullptr) return;
CSingleLinkedList* l = nullptr;
if (vector.size() <= level) {
l = new CSingleLinkedList();
vector.push_back(l);
} else {
l = vector[level];
}
l->Append(node->val);
BuildLevelLinkedLists(vector, node->left, level + 1);
BuildLevelLinkedLists(vector, node->right, level + 1);
}
bool CBinaryTree::IsBinarySearchTree() const {
#if 0
return IsBinarySearchTreeRecursive(root);
#endif
#if 0
int v = INT_MIN;
return IsBSTUsingInOrderWithOneOutputArg(root, v);
#endif
return IsBSTUsingInOrderWithTwoArgs(root, INT_MIN, INT_MAX);
}
bool CBinaryTree::IsBST(const CBTNode *node) const {
if (node == nullptr) return true;
if (!IsBST(node->left)) return false;
if (!IsBST(node->right)) return false;
bool ret1 = true;
bool ret2 = true;
if (node->left != nullptr) ret1 = node->left->val <= node->val;
if (node->right != nullptr) ret2 = node->right->val > node->val;
return ret1 && ret2;
}
bool CBinaryTree::IsBSTUsingInOrderWithOneOutputArg(
const CBTNode *node, int &last) const {
if (node == nullptr) return true;
if (!IsBSTUsingInOrderWithOneOutputArg(node->left, last)) return false;
if (last > node->val) return false;
last = node->val;
if (!IsBSTUsingInOrderWithOneOutputArg(node->right, last)) return false;
return true;
}
bool CBinaryTree::IsBSTUsingInOrderWithTwoArgs(const CBTNode *node, int min,
int max) const {
if (node == nullptr) return true;
if (node->val > max || node->val < min) return false;
if (!IsBSTUsingInOrderWithTwoArgs(node->left, min, node->val)) return false;
if (!IsBSTUsingInOrderWithTwoArgs(node->right, node->val, max)) return false;
return true;
}
const CBTNode * CBinaryTree::Find(int v) const {
return Find(root, v);
}
const CBTNode * CBinaryTree::Find(const CBTNode *node, int v) const {
if (node == nullptr) return nullptr;
if (node->val == v) return node;
const CBTNode* p = Find(node->left, v);
return p == nullptr ? Find(node->right, v) : p;
}
const CBTNode *CBinaryTree::LowestCommonAncestor(const CBTNode* root, const CBTNode* p, const CBTNode* q, bool& found) const {
if (root == nullptr) {
found = false;
return nullptr;
}
if (root == p && root == q) { // This makes r1 != r2 in the logic below.
found = true;
return root;
}
const CBTNode* r1 = LowestCommonAncestor(root->left, p, q, found);
if (found) return r1;
const CBTNode* r2 = LowestCommonAncestor(root->right, p, q, found);
if (found) return r2;
if (r1 != nullptr && r2 != nullptr && r1 != r2) { // r1 != r2 is unnecessary
found = true;
return root;
}
if (root == q || root == p) {
found = r1 != nullptr || r2 != nullptr;
return root;
} else {
found = false;
return r1 == nullptr ? r2 : r1;
}
return nullptr;
}
const CBTNode *CBinaryTree::CommonAncestor(const CBTNode *node,
const CBTNode *n1,
const CBTNode *n2) const {
#if 0
if (node == nullptr || n1 == nullptr || n2 == nullptr) return nullptr;
if (node == n1 && node == n2) return node;
const CBTNode* r1 = CommonAncestor(node->left, n1, n2);
if (r1 != nullptr && r1 != n1 && r1 != n2) return r1;
const CBTNode* r2 = CommonAncestor(node->right, n1, n2);
if (r2 != nullptr && r2 != n1 && r2 != n2) return r2;
if (r1 != nullptr && r2 != nullptr) return node;
else if (node == n1 || node == n2) return node;
else {
// The if below is key for the case when n1 == n2
if ((r1 != nullptr || r2 != nullptr) && n1 == n2) return node;
return r1 == nullptr ? r2 : r1;
}
#endif
bool found = false;
const CBTNode* p = LowestCommonAncestor(node, n1, n2, found);
return found ? p : nullptr;
}
const CBTNode *CBinaryTree::CommonAncestor(int v1, int v2) const {
return CommonAncestor(root, Find(v1), Find(v2));
}
bool CBinaryTree::MatchTree(const CBTNode *node1, const CBTNode *node2) const {
// Two nodes are all nullptr, than match
if (node1 == nullptr && node2 == nullptr) return true;
// Otherwise, one of nodes is nullptr, than not match
if (node1 == nullptr || node2 == nullptr) return false;
// Otherwise, none of nodes is nullptr
// The 2 nodes are not match
if (node1->val != node2->val) return false;
// Otherwise, check left and right of the 2 nodes to see if they match
return MatchTree(node1->left, node2->left) && MatchTree(node1->right, node2->right);
}
bool CBinaryTree::IsSubTree(const CBTNode *node1, const CBTNode *node2) const {
if (node1 == nullptr) return false;
// Redundant because the caller ContainsTree() will check this case
if (node2 == nullptr) return true;
if (node1->val == node2->val) return MatchTree(node1, node2);
return IsSubTree(node1->left, node2) || IsSubTree(node1->right, node2);
}
bool CBinaryTree::ContainsTree(const CBTNode *node1,
const CBTNode *node2) const {
if (node2 == nullptr) return true;
// Redundant because IsSubTree() will check this case
if (node1 == nullptr) return false;
return IsSubTree(node1, node2);
}
bool CBinaryTree::ContainsTree(const CBTNode *node) const {
return ContainsTree(root, node);
}
bool CBinaryTree::FindSum(const CBTNode *node, int sum,
std::vector<int> &vector) const {
if (sum < 0) return false;
if (node == nullptr) {
if (sum == 0) return true;
return false;
}
if (sum == 0) {
return true;
}
bool retLeft = FindSum(node->left, sum - node->val, vector);
bool retRight = FindSum(node->right, sum - node->val, vector);
if (retRight || retLeft) vector.push_back(node->val);
return retLeft || retRight;
}
bool CBinaryTree::FindSum(int sum, std::vector<int> &vector) const {
return FindSum(root, sum, vector);
}
void CBinaryTree::AddToPath(std::vector<std::vector<int>> &vector,
const std::vector<int> &vector1, int start,
int end) const {
if (start > end) return;
std::vector<int> v;
for (int i = start; i <= end; ++i) {
v.push_back(vector1[i]);
}
vector.push_back(v);
}
void CBinaryTree::FindPathOfSum(const CBTNode *node, int sum, int level,
std::vector<int> &path,
std::vector<std::vector<int>> &paths) const {
if (node == nullptr || path.size() < level) return;
path[level] = node->val;
int tmpSum = 0;
for (int j = level; j >=0; --j) {
tmpSum += path[j];
if (tmpSum == sum)
AddToPath(paths, path, j, level);
}
FindPathOfSum(node->left, sum, level + 1, path, paths);
FindPathOfSum(node->right, sum, level + 1, path, paths);
path[level] = INT_MIN;
}
void CBinaryTree::InitializeVector(std::vector<int> &vector, int n,
int initialVal) const {
vector.clear();
for (int i = 0; i < n; ++i)
vector.push_back(initialVal);
}
bool CBinaryTree::FindPathsOfSum(int sum,
std::vector<std::vector<int>> &vector) const {
std::vector<int> path;
InitializeVector(path, Height(), INT_MIN);
FindPathOfSum(root, sum, 0, path, vector);
return vector.size() > 0;
}
<file_sep>//
// RBTreeTest.cpp
// algo
//
// Created by raof01 on 6/17/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#include "RBTree.h"
<file_sep>//
// SortsPerformance.h
// algo
//
// Created by raof01 on 8/2/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#ifndef algo_SortsPerformance_h
#define algo_SortsPerformance_h
#include "gtest/gtest.h"
#include "WireTestFunc.h"
class SortsPerformanceTest : public ::testing::Test
{
public:
SortsPerformanceTest();
~SortsPerformanceTest();
void SetUp();
void TearDown();
protected:
void MergeSortBottomUpPerformance();
void MergeSortPerformance();
void InsertionSortPerformance();
void QuickSortPerformance();
void BubbleSortPerformance();
void HeapSortPerformance();
void HeapSortNonRecursivePerformance();
private:
int* mInput;
//int* mResult;
};
WIRE_TEST_F(SortsPerformanceTest, MergeSortBottomUpPerformance)
WIRE_TEST_F(SortsPerformanceTest, MergeSortPerformance)
WIRE_TEST_F(SortsPerformanceTest, InsertionSortPerformance)
WIRE_TEST_F(SortsPerformanceTest, QuickSortPerformance)
WIRE_TEST_F(SortsPerformanceTest, BubbleSortPerformance)
WIRE_TEST_F(SortsPerformanceTest, HeapSortPerformance)
WIRE_TEST_F(SortsPerformanceTest, HeapSortNonRecursivePerformance)
#endif
<file_sep>//
// Created by raof01 on 8/29/15.
//
#include <stddef.h>
#include <algorithm>
#include <functional>
#include "MaxMin.h"
static int Max(int* a, size_t N, size_t lo, size_t hi)
{
if (lo >= N || hi >= N) return -1;
if (lo == hi) return a[lo];
if (lo + 1 == hi)
return std::max(a[lo], a[hi]);
size_t mid = (lo + hi) / 2;
int max1 = Max(a, N, lo, mid);
int max2 = Max(a, N, mid + 1, hi);
return std::max(max1, max2);
}
int Max(int *a, size_t N)
{
return Max(a, N, 0, N - 1);
}
static int Min(int* a, size_t N, size_t lo, size_t hi)
{
if (lo >= N || hi >= N) return -1;
if (lo == hi) return a[lo];
if (lo + 1 == hi)
return std::min(a[lo], a[hi]);
size_t mid = (lo + hi) / 2;
int min1 = Min(a, N, lo, mid);
int min2 = Min(a, N, mid + 1, hi);
return std::min(min1, min2);
}
int Min(int *a, size_t N)
{
return Min(a, N, 0, N - 1);
}
static void MaxMin(int *a, size_t N, int lo, int hi, int& max, int& min)
{
if (lo >= N || hi >= N)
{
max = -1;
min = -1;
return;
}
if (lo == hi)
{
max = a[lo];
min = a[lo];
return;
}
if (lo + 1 == hi)
{
max = std::max(a[lo], a[hi]);
min = std::min(a[lo], a[hi]);
return;
}
size_t mid = (lo + hi) / 2;
int max1 = -1;
int min1 = -1;
int max2 = -1;
int min2 = -1;
MaxMin(a, N, lo, static_cast<int>(mid), max1, min1);
MaxMin(a, N, static_cast<int>(mid + 1), hi, max2, min2);
max = std::max(max1, max2);
min = std::min(min1, min2);
return;
}
void MaxMin(int *a, size_t N, int& max, int& min)
{
MaxMin(a, N, 0, static_cast<int>(N - 1), max, min);
}
<file_sep>//
// Created by raof01 on 9/21/15.
//
#ifndef ALGO_PRIMESIEVE_H
#define ALGO_PRIMESIEVE_H
#include <vector>
class PrimeSieve {
public:
PrimeSieve(int);
~PrimeSieve();
bool GetPrimes(std::vector<int> &) const;
private:
int GetNextPrime(int) const;
void SetupSieve(int);
void InitSieve(int);
private:
int mMaxValue;
std::vector<bool>* mSieve;
};
#endif //ALGO_PRIMESIEVE_H
<file_sep>//
// MoveZeros.cpp
// algo
//
// Created by <NAME> on 10/11/15.
// Copyright © 2015 raof01. All rights reserved.
//
#include "MoveZeros.h"
using namespace std;
void MoveZeroes(vector<int>& nums) {
vector<int>::size_type nonZero = 0;
vector<int>::size_type next = 0;
while (next < nums.size()) {
if (nums[next] != 0) {
swap(nums[next], nums[nonZero]);
++nonZero;
}
++next;
}
}<file_sep>//
// BinaryTreeLinkImpl.cpp
// algo
//
// Created by raof01 on 5/10/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#include <stdlib.h>
#include "BinaryTreeLinkImpl.hpp"
#include "Stack.hpp"
#include "Queue.hpp"
#include "Visitor.hpp"
struct BinaryTreeLinkImpl::Node
{
Node(int v = -1, Node* l = nullptr, Node* r = nullptr, Node* p = nullptr)
: mLeft(l)
, mRigth(r)
, mParent(p)
, mValue(v)
, mSize(1)
{}
Node*& GetLeft() { return mLeft; }
Node*& GetRight() { return mRigth; }
Node* mLeft;
Node* mRigth;
Node* mParent;
int mValue;
int mSize;
};
BinaryTreeLinkImpl::Node* GetLeft(BinaryTreeLinkImpl::Node* r)
{
return r->mLeft;
}
BinaryTreeLinkImpl::Node* GetRight(BinaryTreeLinkImpl::Node* r)
{
return r->mRigth;
}
void BinaryTreeLinkImpl::DestroyBinaryTree(Node*& r)
{
if (r != nullptr)
{
DestroyBinaryTree(r->mLeft);
DestroyBinaryTree(r->mRigth);
delete r;
r = nullptr;
--mCnt;
}
}
BinaryTreeLinkImpl::~BinaryTreeLinkImpl()
{
DestroyBinaryTree(mRoot);
}
void BinaryTreeLinkImpl::Insert(int v)
{
Node* n = new Node(v);
Node* parent = nullptr;
Node* cur = mRoot;
while (cur != nullptr)
{
++cur->mSize;
parent = cur;
if (v < cur->mValue)
cur = cur->mLeft;
else
cur = cur->mRigth;
}
if (parent == nullptr) mRoot = n;
else
{
if (v < parent->mValue)
parent->mLeft = n;
else
parent->mRigth = n;
n->mParent = parent;
}
++mCnt;
}
// 1. If the node is leaf, delete it.
// 2. If the node has only 1 sub-tree, same as case 1
// 3. If the node has 2 sub-trees, find the successor of v, the move the mValue of successor
// to the node to be deleted, then delete the successor
void BinaryTreeLinkImpl::Delete(int v)
{
const Node* d = FindImpl(mRoot, v);
if (d == nullptr) return;
// Find the node that will be affected (or deleted)
Node* c = nullptr;
if (d->mLeft == nullptr || d->mRigth == nullptr)
c = const_cast<Node*>(d); // At most 1 sub-tree
else
c = const_cast<Node*>(Successor(d)); // 2 sub-trees
Node* x = nullptr;
if (c->mLeft != nullptr)
x = c->mLeft;
else
x = c->mRigth;
Node* mParent = c->mParent;
if (x != nullptr)
x->mParent = mParent; // Re-link
if (mParent == nullptr)
mRoot = x; // Re-link
else
{
// Re-link
if (mParent->mLeft == c)
mParent->mLeft = x;
else
mParent->mRigth = x;
}
if (c != d)
{
const_cast<Node*>(d)->mValue = c->mValue;
d = c;
}
delete d;
--mCnt;
return;
}
bool BinaryTreeLinkImpl::Find(int v) const
{
return FindImpl(mRoot, v) != nullptr;
}
const BinaryTreeLinkImpl::Node*
BinaryTreeLinkImpl::Extreme(
std::pointer_to_unary_function<Node*, Node*> getChild, const Node* r) const
{
if (r == nullptr) return r;
Node* cur = const_cast<Node*>(r);
while (getChild(cur) != nullptr)
cur = getChild(cur);
return cur;
}
const BinaryTreeLinkImpl::Node* BinaryTreeLinkImpl::Maximum(const Node* r) const
{
return Extreme(std::ptr_fun(GetRight), r);
}
const BinaryTreeLinkImpl::Node* BinaryTreeLinkImpl::Minimum(const Node* r) const
{
return Extreme(std::ptr_fun(GetLeft), r);
}
int BinaryTreeLinkImpl::GetMaxValue() const
{
return Maximum(mRoot)->mValue;
}
int BinaryTreeLinkImpl::GetMinValue() const
{
return Minimum(mRoot)->mValue;
}
const BinaryTreeLinkImpl::Node* BinaryTreeLinkImpl::Parent(int v) const
{
const Node* p = FindImpl(mRoot, v);
if (p == nullptr) return nullptr;
return p->mParent;
}
bool BinaryTreeLinkImpl::GetParentValue(int v, int& o) const
{
const Node* p = Parent(v);
if (p == nullptr) return false;
o = p->mValue;
return true;
}
// Successor: The minimum of the mRigth sub-tree. If mRigth sub-tree is
// empty, then find a mParent which has r on its mLeft sub-tree
const BinaryTreeLinkImpl::Node* BinaryTreeLinkImpl::Successor(const Node* r) const
{
Node* cur = const_cast<Node*>(r);
if (cur == nullptr)
return nullptr;
if (cur->mRigth != nullptr)
return Minimum(cur->mRigth);
Node* p = cur->mParent;
while (p != nullptr && cur != p->mLeft)
{
cur = p;
p = p->mParent;
}
return p;
}
bool BinaryTreeLinkImpl::GetSuccessorValue(int v, int& o) const
{
const Node* p = Successor(FindImpl(mRoot, v));
if (p == nullptr) return false;
o = p->mValue;
return true;
}
// Predecessor: the maximum of mLeft sub-tree. If the mLeft sub-tree is empty,
// then find a mParent which has r on its mRigth sub-tree
const BinaryTreeLinkImpl::Node* BinaryTreeLinkImpl::Predecessor(const Node* r) const
{
Node* cur = const_cast<Node*>(r);
if (cur == nullptr)
return nullptr;
if (cur->mLeft != nullptr)
return Maximum(cur->mLeft);
Node* p = cur->mParent;
while (p != nullptr && cur != p->mRigth)
{
cur = p;
p = p->mParent;
}
return p;
}
bool BinaryTreeLinkImpl::GetPredecessorValue(int v, int& o) const
{
const Node* p = Predecessor(FindImpl(mRoot, v));
if (p == nullptr) return false;
o = p->mValue;
return true;
}
const BinaryTreeLinkImpl::Node* BinaryTreeLinkImpl::FindImpl(Node* r, int v) const
{
Node* cur = r;
while (cur != nullptr)
{
if (v != cur->mValue)
{
if (v < cur->mValue)
cur = cur->mLeft;
else
cur = cur->mRigth;
}
else
break;
}
return cur;
}
void BinaryTreeLinkImpl::InOrderTraversalRecursive(Visitor<int, false>& visitor, const Node* r) const
{
if (r != nullptr)
{
InOrderTraversalRecursive(visitor, r->mLeft);
visitor.Visit(r->mValue);
InOrderTraversalRecursive(visitor, r->mRigth);
}
}
void BinaryTreeLinkImpl::PreOrderTraversalRecursive(Visitor<int, false>& visitor, const Node* r) const
{
if (r != nullptr)
{
visitor.Visit(r->mValue);
PreOrderTraversalRecursive(visitor, r->mLeft);
PreOrderTraversalRecursive(visitor, r->mRigth);
}
}
void BinaryTreeLinkImpl::PostOrderTraversalRecursive(Visitor<int, false>& visitor, const Node* r) const
{
if (r != nullptr)
{
PostOrderTraversalRecursive(visitor, r->mLeft);
PostOrderTraversalRecursive(visitor, r->mRigth);
visitor.Visit(r->mValue);
}
}
void BinaryTreeLinkImpl::InOrderTraversalIter(Visitor<int, false>& visitor, const Node* r) const
{
// 1. push root and its left child to stack, until the left child is nullptr
// 2. visit the top of stack (leftmost leaf, or the root of tree with a righ child)
// 3. pop a node
// 4. if the node has right child, then make it right child as root, goto 1
// 5. otherwise (leftmost leaf):
// goto 2
const Node* p = r;
Stack<const Node*> stack;
while (p != nullptr || !stack.Empty())
{
while (p != nullptr)
{
stack.Push(p);
p = p->mLeft;
}
if (!stack.Empty())
{
// OK, comma expression seems to work with paranthesis
// I don't recommend this because it make people confused.
// visitor.Visit((p = stack.Peek()->mRigth, stack.Pop()->mValue));
visitor.Visit(stack.Peek()->mValue);
p = stack.Pop()->mRigth;
}
}
}
void BinaryTreeLinkImpl::PreOrderTraversalIter(Visitor<int, false>& visitor, const Node* r) const
{
// 1. visit root, push root to stack and make left child to be root until
// the current visit reaches leftmost leaf
// 2. if the stack is empty, the traverse is done.
// 3. pop a node (already visited), if it doesn't has right tree, pop again,
// then goto 1
Stack<const Node*> stack;
const Node* p = r;
while (p != nullptr || !stack.Empty())
{
while (p != nullptr)
{
visitor.Visit(p->mValue);
if (p->mLeft != nullptr || p->mRigth != nullptr)
{
stack.Push(p);
p = p->mLeft;
}
else
p = nullptr;
}
if (!stack.Empty())
p = stack.Pop()->mRigth;
}
}
void BinaryTreeLinkImpl::PostOrderTraversalIter(Visitor<int, false>& visitor, const Node* r) const
{
Stack<const Node*> stack;
const Node* cur;
const Node* pre = nullptr;
if (r != nullptr)
stack.Push(r);
while(!stack.Empty())
{
cur = stack.Peek();
if((cur->mLeft == nullptr && cur->mRigth == nullptr) ||
(pre != nullptr && (pre == cur->mLeft || pre == cur->mRigth)))
{
visitor.Visit(cur->mValue);
stack.Pop();
pre = cur;
}
else
{
if(cur->mRigth != nullptr)
stack.Push(cur->mRigth);
if(cur->mLeft != nullptr)
stack.Push(cur->mLeft);
}
}
}
void BinaryTreeLinkImpl::InOrderTraversal(Visitor<int, false>& visitor) const
{
if (mRecursive)
InOrderTraversalRecursive(visitor, mRoot);
else
InOrderTraversalIter(visitor, mRoot);
}
void BinaryTreeLinkImpl::PreOrderTraversal(Visitor<int, false>& visitor) const
{
if (mRecursive)
PreOrderTraversalRecursive(visitor, mRoot);
else
PreOrderTraversalIter(visitor, mRoot);
}
void BinaryTreeLinkImpl::PostOrderTraversal(Visitor<int, false>& visitor) const
{
if (mRecursive)
PostOrderTraversalRecursive(visitor, mRoot);
else
PostOrderTraversalIter(visitor, mRoot);
}
void BinaryTreeLinkImpl::BreadthFirstTraversal(Visitor<int, false>& visitor) const
{
BreadthFirstTraversalImpl(visitor, mRoot);
}
void BinaryTreeLinkImpl::DepthFirstTraversal(Visitor<int, false>& visitor) const
{
DepthFirstTraversalImpl(visitor, mRoot);
}
void BinaryTreeLinkImpl::BreadthFirstTraversalImpl(Visitor<int, false>& visitor, const Node* r) const
{
Queue<const Node*, 512> queue;
queue.Enqueue(r);
const Node* cur = nullptr;
while (!queue.Empty())
{
queue.Dequeue(cur);
if (cur->mLeft != nullptr)
queue.Enqueue(cur->mLeft);
if (cur->mRigth != nullptr)
queue.Enqueue(cur->mRigth);
visitor.Visit(cur->mValue);
}
}
void BinaryTreeLinkImpl::DepthFirstTraversalImpl( Visitor<int, false>& visitor, const Node* r) const
{
Stack<const Node*, 512> stack;
stack.Push(r);
const Node* cur = nullptr;
while (!stack.Empty())
{
cur = stack.Pop();
visitor.Visit(cur->mValue);
if (cur->mRigth != nullptr)
stack.Push(cur->mRigth);
if (cur->mLeft != nullptr)
stack.Push(cur->mLeft);
}
}
void BinaryTreeLinkImpl::Invert()
{
if (mRecursive)
InvertRecursive(mRoot);
else
InvertNoneRecursive();
}
void BinaryTreeLinkImpl::InvertRecursive(Node* r)
{
if (r == nullptr || (r->mLeft == nullptr && r->mRigth == nullptr)) return;
std::swap(r->mLeft, r->mRigth);
InvertRecursive(r->mLeft);
InvertRecursive(r->mRigth);
}
void BinaryTreeLinkImpl::InvertNoneRecursive()
{
if (mRoot == nullptr || (mRoot->mLeft == nullptr && mRoot->mRigth == nullptr)) return;
Queue<Node*, 512> q;
q.Enqueue(mRoot);
Node* p = nullptr;
while (!q.Empty())
{
q.Dequeue(p);
std::swap(p->mLeft, p->mRigth);
if (p->mLeft != nullptr) q.Enqueue(p->mLeft);
if (p->mRigth != nullptr) q.Enqueue(p->mRigth);
}
}
const BinaryTreeLinkImpl::Node* BinaryTreeLinkImpl::Floor(const Node* r, int v) const
{
if (r == nullptr) return nullptr;
if (r->mValue == v) return r;
if (r->mValue > v) return Floor(r->mLeft, v);
const Node* p = Floor(r->mRigth, v);
if (p != nullptr) return p;
return r;
}
int BinaryTreeLinkImpl::Floor(int v) const
{
const Node* p = Floor(mRoot, v);
return p == nullptr ? -1 : p->mValue;
}
const BinaryTreeLinkImpl::Node* BinaryTreeLinkImpl::Ceiling(const Node* r, int v) const
{
if (r == nullptr) return nullptr;
if (r->mValue == v) return r;
if (r->mValue < v) return Ceiling(r->mRigth, v);
const Node* p = Ceiling(r->mLeft, v);
if (p != nullptr) return p;
return r;
}
int BinaryTreeLinkImpl::Ceiling(int v) const
{
const Node* p = Ceiling(mRoot, v);
return p == nullptr ? -1 : p->mValue;
}
int BinaryTreeLinkImpl::Size(int v) const
{
/*
const Node* p = FindImpl(mRoot, v);
return p == nullptr ? 0 : p->mSize;
*/
return Size(FindImpl(mRoot, v));
}
int BinaryTreeLinkImpl::Size(const Node* r) const
{
if (r == nullptr) return 0;
return r->mSize;
}
int BinaryTreeLinkImpl::Rank(const Node* r, int v) const
{
if (r == nullptr) return 0;
if (v <= r->mValue) return Rank(r->mLeft, v);
return 1 + Size(r->mLeft) + Rank(r->mRigth, v);
}
int BinaryTreeLinkImpl::Rank(int v) const
{
return Rank(mRoot, v);
}
<file_sep>//
// Created by raof01 on 9/20/15.
//
#include <stdio.h>
#include <vector>
#include <stdlib.h>
const static int BYTE_SIZE = 8;
template <typename IntegralType>
struct TotalBits {
const static int value = sizeof(IntegralType) * BYTE_SIZE;
};
inline bool IsLittleEndian() {
unsigned short val = 0xFF00;
return static_cast<unsigned char>(val) == 0;
}
template <typename IntegralType>
bool ValidPos(IntegralType, int pos) {
return pos >= 0 && pos < TotalBits<IntegralType>::value;
}
bool IsBitSet(unsigned int v, int pos) {
if (!ValidPos(v, pos)) return false;
return (v & (1 << pos)) != 0;
}
bool SetBit(unsigned int &v, int pos) {
if (!ValidPos(v, pos)) return false;
v |= (1 << pos);
return true;
}
bool ClearBit(unsigned int &v, int pos) {
if (!ValidPos(v, pos)) return false;
v &= ~(1 << pos);
return true;
}
bool ClearBitsMSBThroughInclusive(unsigned int &v, int pos) {
if (!ValidPos(v, pos)) return false;
v &= ((1 << pos) - 1);
return true;
}
bool ClearBitsLSBThroughInclusive(unsigned int &v, int pos) {
if (!ValidPos(v, pos)) return false;
unsigned long long tmp = (~((1ull << (pos + 1)) - 1)) & v;
v = static_cast<unsigned int>(tmp); // endian-ness related?
return true;
}
#if 0
bool DoubleTo32BitBinary(double d, std::vector<unsigned char> &vector) {
return false;
}
#endif
static int CountSetBitsIterative(int v) {
int cnt = 0;
for (int i = 0; i < TotalBits<int>::value; ++i)
if (IsBitSet(v, i))
++cnt;
return cnt;
}
// Shift op needs a conversion to unsigned value
static int CountSetBitsByShift(int v) {
int cnt = 0;
unsigned int tmp = static_cast<unsigned int>(v);
while (tmp != 0) {
if ((tmp & 1) != 0)
++cnt;
tmp >>= 1;
}
return cnt;
}
static int CountSetBitsByBitwiseAnd(unsigned int v) {
int cnt = 0;
while (v != 0) {
++cnt;
v &= (v - 1);
}
return cnt;
}
/*
* x x x x x x x x x x x x x x x x 0
* - - - - - - - - - - - - - - - -
* | | | | | | | | | | | | | | | | 1
* - - - - - - - -
* | | | | | | | | 2
* --- --- --- ---
* | | | | 4
* ------- -------
* | | 8
* ---------------
*/
const unsigned int ODD_BIT_MASK = 0xAAAAAAAA;
const unsigned int EVEN_BIT_MASK = 0x55555555;
const unsigned int ODD_2BIT_MASK = 0xCCCCCCCC;
const unsigned int EVEN_2BIT_MASK = 0x33333333;
const unsigned int ODD_4BIT_MASK = 0xF0F0F0F0;
const unsigned int EVEN_4BIT_MASK = 0x0F0F0F0F;
const unsigned int ODD_8BIT_MASK = 0xFF00FF00;
const unsigned int EVEN_8BIT_MASK = 0x00FF00FF;
const unsigned int ODD_16BIT_MASK = 0xFFFF0000;
const unsigned int EVEN_16BIT_MASK = 0x0000FFFF;
static int CountSetBitsByBitOp(int v) {
v = (v & EVEN_BIT_MASK) + ((v & ODD_BIT_MASK) >> 1);
v = (v & EVEN_2BIT_MASK) + ((v & ODD_2BIT_MASK) >> 2);
v = (v & EVEN_4BIT_MASK) + ((v & ODD_4BIT_MASK) >> 4);
v = (v & EVEN_8BIT_MASK) + ((v & ODD_8BIT_MASK) >> 8);
return (v & EVEN_16BIT_MASK) + ((v & ODD_16BIT_MASK) >> 16);
}
int CountSetBits(int v) {
#if 0
return CountSetBitsIterative(v);
return CountSetBitsByShift(v);
#endif
return CountSetBitsByBitOp(v);
}
int BitsNeededToConvert(int v1, int v2) {
return abs(CountSetBits(v1) - CountSetBits(v2));
}
bool NextPositive(int v, unsigned int &smallest, unsigned int &largest) {
if (IsBitSet(v, TotalBits<int>::value - 1)) return false;
int cnt = CountSetBits(v);
for (int i = 0; i < cnt; ++i) {
SetBit(smallest, i);
SetBit(largest, TotalBits<int>::value - 2 - i);
}
return true;
}
auto SwapEvenAndOddBits(unsigned int v) -> decltype(v) {
return ((ODD_BIT_MASK & v) >> 1) | ((EVEN_BIT_MASK & v) << 1);
}
<file_sep>//
// insertion_sort.h
// algo
//
// Created by raof01 on 5/3/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#ifndef __algo__insertion_sort__
#define __algo__insertion_sort__
template <typename Comparable>
class InsertionSorter
{
public:
template <size_t N>
static void Sort(Comparable (&input)[N])
{
Sort(input, N);
}
static void Sort(Comparable *input, size_t N)
{
SortImpl(input, N);
}
template <size_t N>
static void Sort(Comparable (&input)[N], int stride)
{
Sort(input, N, stride);
}
static void Sort(Comparable *input, size_t N, int stride)
{
SortImpl(input, N, stride);
}
private:
static void SortImpl(Comparable *input, size_t N);
static void SortImpl(Comparable *input, size_t N, int stride);
};
// Quardratic
template <typename Comparable>
void InsertionSorter<Comparable>::SortImpl(Comparable *input, size_t N)
{
for (int unsorted = 1; unsorted < N; ++unsorted) // Unsorted: 1 to N
{
Comparable tmp = input[unsorted];
int sorted = unsorted - 1; // Sorted: 0 to i - 1
for (; sorted >= 0; --sorted)
{
if (input[sorted] > tmp)
input[sorted + 1] = input[sorted];
else
break;
}
input[sorted + 1] = tmp;
}
}
template <typename Comparable>
void InsertionSorter<Comparable>::SortImpl(Comparable *a, size_t N, int stride)
{
for (int unsorted = stride; unsorted < N; ++unsorted) // Unsorted: stride to N
{
for (int sorted = unsorted; sorted - stride >= 0; --sorted)
{
if (a[sorted - stride] > a[sorted])
std::swap(a[sorted - stride], a[sorted]);
}
}
}
#endif /* defined(__algo__insertion_sort__) */
<file_sep>//
// FlipSurroundedRegions.cpp
// algo
//
// Created by raof01 on 5/24/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#include <stdio.h>
<file_sep>//
// Created by raof01 on 9/17/15.
//
#include "CBinaryTree.h"
#include "gtest/gtest.h"
#include "ArraysMatch.hpp"
TEST(TestCBinaryTree, IsBalancedReturnFalseOnUnbalancedTree) {
CBinaryTree cbt;
cbt.Insert(1).Insert(2).Insert(3);
ASSERT_FALSE(cbt.IsBalanced());
ASSERT_EQ(3, cbt.Height());
}
TEST(TestCBinaryTree, IsBalancedReturnFalseOnBalancedTree) {
CBinaryTree cbt;
cbt.Insert(1).Insert(2);
ASSERT_TRUE(cbt.IsBalanced());
ASSERT_EQ(2, cbt.Height());
}
TEST(TestCBinaryTree, BuildTreeWithSortedValuesWithSampleInput) {
CBinaryTree cbt;
std::vector<int> v = {0, 1, 2, 3, 4};
cbt.BuildTreeFromList(v);
ASSERT_TRUE(cbt.IsBalanced());
ASSERT_EQ(3, cbt.Height());
}
TEST(TestCBinaryTree, BuildTreeWithSortedValuesWithEmptyList) {
CBinaryTree cbt;
std::vector<int> v;
cbt.BuildTreeFromList(v);
ASSERT_TRUE(cbt.IsBalanced());
ASSERT_EQ(0, cbt.Height());
}
TEST(TestCBinaryTree, BuildTreeWithSortedValuesWithOneElemList) {
CBinaryTree cbt;
std::vector<int> v = {1};
cbt.BuildTreeFromList(v);
ASSERT_TRUE(cbt.IsBalanced());
ASSERT_EQ(1, cbt.Height());
}
TEST(TestCBinaryTree, BuildTreeWithSortedValuesWithTwoElemsList) {
CBinaryTree cbt;
std::vector<int> v = {1, 2};
cbt.BuildTreeFromList(v);
ASSERT_TRUE(cbt.IsBalanced());
ASSERT_EQ(2, cbt.Height());
}
TEST(TestCBinaryTree, BuildTreeWithSortedValuesWithThreeElemsList) {
CBinaryTree cbt;
std::vector<int> v = {1, 2, 3};
cbt.BuildTreeFromList(v);
ASSERT_TRUE(cbt.IsBalanced());
ASSERT_EQ(2, cbt.Height());
}
TEST(TestCBinaryTree, BuildTreeWithSortedValuesWithTenElemsList) {
CBinaryTree cbt;
std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
cbt.BuildTreeFromList(v);
ASSERT_TRUE(cbt.IsBalanced());
ASSERT_EQ(4, cbt.Height());
}
TEST(TestCBinaryTree, BuildLevelLinkedListsWithSampleInput) {
CBinaryTree cbt;
std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
cbt.BuildTreeFromList(v);
std::vector<CSingleLinkedList*> vl;
cbt.BuildLevelLinkedLists(vl);
while (!vl.empty()) {
CSingleLinkedList* l = vl.back();
CNode* p = l->head;
while (p != nullptr) {
std::cout << p->val << "->";
p = p->next;
}
std::cout << std::endl;
vl.pop_back();
}
ASSERT_TRUE(cbt.IsBalanced());
ASSERT_EQ(4, cbt.Height());
}
TEST(TestCBinaryTree, IsBinarySearchTreeOnEmptyTree) {
CBinaryTree cbt;
ASSERT_TRUE(cbt.IsBinarySearchTree());
}
TEST(TestCBinaryTree, IsBinarySearchTreeOnOneElemTree) {
CBinaryTree cbt;
cbt.Insert(10);
ASSERT_TRUE(cbt.IsBinarySearchTree());
}
TEST(TestCBinaryTree, IsBinarySearchTreeOnTwoElemTree) {
CBinaryTree cbt;
std::vector<int> v = {2, 1};
cbt.BuildTreeFromList(v);
ASSERT_FALSE(cbt.IsBinarySearchTree());
}
TEST(TestCBinaryTree, IsBinarySearchTreeOnSampleInputNegative) {
CBinaryTree cbt;
std::vector<int> v = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
cbt.BuildTreeFromList(v);
ASSERT_FALSE(cbt.IsBinarySearchTree());
}
TEST(TestCBinaryTree, IsBinarySearchTreeOnSampleInputPositive) {
CBinaryTree cbt;
std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
cbt.BuildTreeFromList(v);
ASSERT_TRUE(cbt.IsBinarySearchTree());
}
TEST(TestCBinaryTree, FindReturnNonnullptrValueWhenElemInTree) {
CBinaryTree cbt;
std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
cbt.BuildTreeFromList(v);
const CBTNode* p = cbt.Find(5);
ASSERT_TRUE(p != nullptr);
ASSERT_EQ(5, p->val);
}
TEST(TestCBinaryTree, FindReturnnullptrValueWhenElemNotInTree) {
CBinaryTree cbt;
std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
cbt.BuildTreeFromList(v);
const CBTNode* p = cbt.Find(100);
ASSERT_TRUE(p == nullptr);
}
TEST(TestCBinaryTree, FindReturnnullptrValueWhenTreeIsEmpty) {
CBinaryTree cbt;
const CBTNode* p = cbt.Find(100);
ASSERT_TRUE(p == nullptr);
}
TEST(TestCBinaryTree, CommonAncestorReturnnullptrWhenTreeIsEmpty) {
CBinaryTree cbt;
const CBTNode* p = cbt.CommonAncestor(10, 20);
ASSERT_TRUE(p == nullptr);
}
TEST(TestCBinaryTree, CommonAncestorReturnnullptrWhenOneValueNotInTree) {
CBinaryTree cbt;
std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
cbt.BuildTreeFromList(v);
const CBTNode* p = cbt.CommonAncestor(10, 20);
ASSERT_TRUE(p == nullptr);
}
TEST(TestCBinaryTree, CommonAncestorReturnnullptrWhenTwoValuesNotInTree) {
CBinaryTree cbt;
std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
cbt.BuildTreeFromList(v);
const CBTNode* p = cbt.CommonAncestor(30, 20);
ASSERT_TRUE(p == nullptr);
}
TEST(TestCBinaryTree, CommonAncestorReturnRootWhenAllValueIsAtRoot) {
CBinaryTree cbt;
std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
cbt.BuildTreeFromList(v);
const CBTNode* p = cbt.CommonAncestor(5, 5);
ASSERT_TRUE(p != nullptr);
ASSERT_EQ(5, p->val);
}
TEST(TestCBinaryTree, CommonAncestorReturnParentWhenTwoValuesAreEqual) {
CBinaryTree cbt;
std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
cbt.BuildTreeFromList(v);
const CBTNode* p = cbt.CommonAncestor(6, 6);
ASSERT_TRUE(p != nullptr);
ASSERT_EQ(6, p->val);
}
TEST(TestCBinaryTree, CommonAncestorReturnParentPositive1) {
CBinaryTree cbt;
std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
cbt.BuildTreeFromList(v);
const CBTNode* p = cbt.CommonAncestor(1, 6);
ASSERT_TRUE(p != nullptr);
ASSERT_EQ(5, p->val);
}
TEST(TestCBinaryTree, CommonAncestorReturnParentPositive2) {
CBinaryTree cbt;
std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
cbt.BuildTreeFromList(v);
const CBTNode* p = cbt.CommonAncestor(7, 10);
ASSERT_TRUE(p != nullptr);
ASSERT_EQ(8, p->val);
}
TEST(TestCBinaryTree, CommonAncestorReturnParentPositive3) {
CBinaryTree cbt;
std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
cbt.BuildTreeFromList(v);
const CBTNode* p = cbt.CommonAncestor(4, 10);
ASSERT_TRUE(p != nullptr);
ASSERT_EQ(5, p->val);
}
TEST(TestCBinaryTree, ContainsTreeReturnFalseWhenTargetTreeIsEmpty) {
CBinaryTree cbt1;
CBinaryTree cbt2;
std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
cbt2.BuildTreeFromList(v);
ASSERT_FALSE(cbt1.ContainsTree(cbt2.root));
}
TEST(TestCBinaryTree, ContainsTreeReturnTrueWhenTreeToBeFoundIsEmpty) {
CBinaryTree cbt1;
CBinaryTree cbt2;
std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
cbt1.BuildTreeFromList(v);
ASSERT_TRUE(cbt1.ContainsTree(cbt2.root));
}
TEST(TestCBinaryTree, ContainsTreeReturnFalseWhenTreeToBeFoundIsNotSubTree) {
CBinaryTree cbt1;
CBinaryTree cbt2;
std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
std::vector<int> v2 = {11, 12, 13, 14, 15};
cbt1.BuildTreeFromList(v);
cbt2.BuildTreeFromList(v2);
ASSERT_FALSE(cbt1.ContainsTree(cbt2.root));
}
TEST(TestCBinaryTree, ContainsTreeReturnFalseWhenTreeToBeFoundIsFromTarget) {
CBinaryTree cbt1;
std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
cbt1.BuildTreeFromList(v);
ASSERT_TRUE(cbt1.ContainsTree(cbt1.Find(2)));
}
TEST(TestCBinaryTree, ContainsTreeReturnFalseWhenTreeToBeFoundIsSubTree) {
CBinaryTree cbt1;
std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
cbt1.BuildTreeFromList(v);
CBinaryTree cbt2;
std::vector<int> v2 = {6, 7, 8, 9, 10};
cbt2.BuildTreeFromList(v2);
ASSERT_TRUE(cbt1.ContainsTree(cbt2.root));
}
TEST(TestCBinaryTree, FindSumReturnFalseOnEmptyTree) {
CBinaryTree cbt1;
std::vector<int> l;
ASSERT_FALSE(cbt1.FindSum(10, l));
}
TEST(TestCBinaryTree, FindSumReturnFalseForNegativeValue) {
CBinaryTree cbt1;
std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
cbt1.BuildTreeFromList(v);
std::vector<int> l;
ASSERT_FALSE(cbt1.FindSum(-10, l));
}
TEST(TestCBinaryTree, FindSumReturnFalseForLargeValue) {
CBinaryTree cbt1;
std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
cbt1.BuildTreeFromList(v);
std::vector<int> l;
ASSERT_FALSE(cbt1.FindSum(100, l));
ASSERT_EQ(0, l.size());
}
TEST(TestCBinaryTree, FindSumReturnFalseNegative) {
CBinaryTree cbt1;
std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
cbt1.BuildTreeFromList(v);
std::vector<int> l;
ASSERT_FALSE(cbt1.FindSum(15, l));
ASSERT_EQ(0, l.size());
}
TEST(TestCBinaryTree, FindSumReturnTrueSampleInput1) {
CBinaryTree cbt1;
std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
cbt1.BuildTreeFromList(v);
std::vector<int> l;
std::vector<int> res = {4, 3, 2, 5};
ASSERT_TRUE(cbt1.FindSum(14, l));
ASSERT_TRUE(VectorsMatch(res, l));
}
TEST(TestCBinaryTree, FindSumReturnTrueSampleInput2) {
CBinaryTree cbt1;
std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
cbt1.BuildTreeFromList(v);
std::vector<int> l;
std::vector<int> res = {3, 2, 5};
ASSERT_TRUE(cbt1.FindSum(10, l));
ASSERT_TRUE(VectorsMatch(res, l));
}
TEST(TestCBinaryTree, FindPathsOfSumReturnFalseOnEmptyTree) {
CBinaryTree cbt1;
std::vector<std::vector<int>> l;
ASSERT_FALSE(cbt1.FindPathsOfSum(10, l));
}
TEST(TestCBinaryTree, FindPathsOfSumReturnFalseForNegativeValue) {
CBinaryTree cbt1;
std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
cbt1.BuildTreeFromList(v);
std::vector<std::vector<int>> l;
ASSERT_FALSE(cbt1.FindPathsOfSum(-10, l));
}
TEST(TestCBinaryTree, FindPathsOfSumReturnFalseForLargeValue) {
CBinaryTree cbt1;
std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
cbt1.BuildTreeFromList(v);
std::vector<std::vector<int>> l;
ASSERT_FALSE(cbt1.FindPathsOfSum(100, l));
ASSERT_EQ(0, l.size());
}
TEST(TestCBinaryTree, FindPathsOfSumReturnFalseNegative) {
CBinaryTree cbt1;
std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
cbt1.BuildTreeFromList(v);
std::vector<std::vector<int>> l;
ASSERT_FALSE(cbt1.FindPathsOfSum(15, l));
ASSERT_EQ(0, l.size());
}
TEST(TestCBinaryTree, FindPathsOfSumReturnTrueSampleInput1) {
CBinaryTree cbt1;
std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
cbt1.BuildTreeFromList(v);
std::vector<std::vector<int>> l;
ASSERT_TRUE(cbt1.FindPathsOfSum(14, l));
ASSERT_EQ(2, l.size());
std::vector<int> path1 = {5, 2, 3, 4};
std::vector<int> path2 = {8, 6};
ASSERT_TRUE(VectorsMatch(path1, l[0]));
ASSERT_TRUE(VectorsMatch(path2, l[1]));
}
TEST(TestCBinaryTree, FindPathsOfSumReturnTrueSampleInput2) {
CBinaryTree cbt1;
std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
cbt1.BuildTreeFromList(v);
std::vector<std::vector<int>> l;
std::vector<int> path1 = {5, 2};
std::vector<int> path2 = {3, 4};
std::vector<int> path3 = {7};
ASSERT_TRUE(cbt1.FindPathsOfSum(7, l));
ASSERT_TRUE(VectorsMatch(path1, l[0]));
ASSERT_TRUE(VectorsMatch(path2, l[1]));
ASSERT_TRUE(VectorsMatch(path3, l[2]));
}
<file_sep>//
// unit_test.cpp
// algo
//
// Created by raof01 on 5/4/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#include "gtest/gtest.h"
#include "Fibonacci.hpp"
// Fibonacci
TEST(TestFibo, Positive)
{
std::size_t r = Fib<20>::Result;
ASSERT_EQ(Fibo(20), r);
}
TEST(TestFibo, LowBound0)
{
ASSERT_EQ(Fibo(0), 0);
}
TEST(TestFibo, LowBound1)
{
ASSERT_EQ(Fibo(1), 1);
}
TEST(TestFiboIter, Positive)
{
std::size_t r = Fib<20>::Result;
ASSERT_EQ(Fibo(20, Iter()), r);
}
TEST(TestFiboIter, LowBound0)
{
ASSERT_EQ(Fibo(0, Iter()), 0);
}
TEST(TestFiboIter, LowBound1)
{
ASSERT_EQ(Fibo(1, Iter()), 1);
}
TEST(TestFibTemplate, Negative)
{
std::size_t r = Fib<-10>::Result;
ASSERT_EQ((size_t)-1, r);
}
TEST(TestFibTemplate, Positive)
{
std::size_t r = Fib<10>::Result;
ASSERT_EQ(Fibo(10, Iter()), r);
}
<file_sep>//
// MoveZeros.h
// algo
//
// Created by <NAME> on 10/11/15.
// Copyright © 2015 raof01. All rights reserved.
//
#ifndef MoveZeros_h
#define MoveZeros_h
#include <vector>
void MoveZeroes(std::vector<int>&);
#endif /* MoveZeros_h */
<file_sep>//
// BinaryTree.hpp
// algo
//
// Created by raof01 on 5/10/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#ifndef algo_BinaryTree_hpp
#define algo_BinaryTree_hpp
template <typename T, bool IsClass>
class Visitor;
class BinaryTree
{
public:
virtual void Insert(int) = 0;
virtual void Delete(int) = 0;
virtual void InOrderTraversal(Visitor<int, false>&) const = 0;
virtual void PreOrderTraversal(Visitor<int, false>&) const = 0;
virtual void PostOrderTraversal(Visitor<int, false>&) const = 0;
virtual void BreadthFirstTraversal(Visitor<int, false>&) const = 0;
virtual void DepthFirstTraversal(Visitor<int, false>&) const = 0;
virtual int GetMaxValue() const = 0;
virtual int GetMinValue() const = 0;
virtual bool Find(int) const = 0;
virtual bool GetParentValue(int, int&) const = 0;
virtual bool GetSuccessorValue(int, int&) const = 0;
virtual bool GetPredecessorValue(int, int&) const = 0;
virtual int GetCount() const = 0;
virtual void Invert() = 0;
virtual int Floor(int) const = 0;
virtual int Ceiling(int) const = 0;
virtual int Size(int) const = 0;
virtual int Rank(int) const = 0;
virtual ~BinaryTree() {}
};
#endif
<file_sep>//
// ConectionSlowImpl.h
// algo
//
// Created by raof01 on 7/25/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#ifndef algo_ConectionSlowImpl_h
#define algo_ConectionSlowImpl_h
#include <vector>
#include "Connection.h"
class ConnectionSlowImpl : public Connection {
public:
ConnectionSlowImpl(int);
virtual void ConnectTo(int, int);
virtual bool Connected(int, int);
virtual ~ConnectionSlowImpl();
private:
bool OutOfRange(int i);
private:
std::vector<int> m_Data;
};
#endif
<file_sep>//
// Created by raof01 on 9/24/15.
//
#include "MagicIndex.h"
#include "gtest/gtest.h"
TEST(TestMagicIndexNoDuplicates, OneElemArray) {
int a[] = {10};
ASSERT_EQ(-1, MagicIndexFinder<1>::MagicIndexNoDup(a));
}
TEST(TestMagicIndexNoDuplicates, OneElemArrayWithZero) {
int a[] = {0};
ASSERT_EQ(0, MagicIndexFinder<1>::MagicIndexNoDup(a));
}
TEST(TestMagicIndexNoDuplicates, NotFound1) {
int a[] = {1, 2, 3, 4, 5};
ASSERT_EQ(-1, MagicIndexFinder<5>::MagicIndexNoDup(a));
}
TEST(TestMagicIndexNoDuplicates, NotFound2) {
int a[] = {-1, 0, 1, 2, 3};
ASSERT_EQ(-1, MagicIndexFinder<5>::MagicIndexNoDup(a));
}
TEST(TestMagicIndexDuplicates, Found1) {
int a[] = {-2, -1, 0, 3, 4};
ASSERT_EQ(3, MagicIndexFinder<5>::MagicIndexNoDup(a));
}
TEST(TestMagicIndexWithDuplicates, NotFound1) {
int a[] = {2, 2, 3, 5, 5};
ASSERT_EQ(-1, MagicIndexFinder<5>::MagicIndexWithDup(a));
std::vector<int> v;
ASSERT_EQ(0, MagicIndexFinder<5>::GetAllMagicIndicesWithDup(a, v));
}
TEST(TestMagicIndexWithDuplicates, NotFound2) {
int a[] = {-1, -1, 0, 1, 3};
ASSERT_EQ(-1, MagicIndexFinder<5>::MagicIndexWithDup(a));
std::vector<int> v;
ASSERT_EQ(0, MagicIndexFinder<5>::GetAllMagicIndicesWithDup(a, v));
}
TEST(TestMagicIndexWithDuplicates, Found1) {
int a[] = {-10, -5, 2, 2, 2, 3, 4, 7, 9, 12, 13};
ASSERT_EQ(2, MagicIndexFinder<11>::MagicIndexWithDup(a));
std::vector<int> v;
ASSERT_EQ(2, MagicIndexFinder<11>::GetAllMagicIndicesWithDup(a, v));
ASSERT_EQ(2, v[0]);
ASSERT_EQ(7, v[1]);
}
<file_sep>//
// ConnectionWeightedTreeImpl.cpp
// algo
//
// Created by raof01 on 7/25/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#include "ConnectionWeightedTreeImpl.h"
ConnectionWeightedTreeImpl::ConnectionWeightedTreeImpl(int sz)
: mRoot(sz)
, mWeight(sz)
{
for (int i = 0; i < sz; ++i)
{
mRoot[i] = i;
mWeight[i] = 1;
}
}
ConnectionWeightedTreeImpl::~ConnectionWeightedTreeImpl()
{
}
void ConnectionWeightedTreeImpl::ConnectTo(int src, int target)
{
if (OutOfRange(src) || OutOfRange(target)) return;
if (Connected(src, target)) return;
int srcRoot = Root(src);
int targetRoot = Root(target);
if (mWeight[srcRoot] > mWeight[targetRoot])
std::swap(srcRoot, targetRoot);
mRoot[srcRoot] = mRoot[targetRoot];
mWeight[targetRoot] += mWeight[srcRoot];
}
bool ConnectionWeightedTreeImpl::Connected(int i1, int i2)
{
if (OutOfRange(i1) || OutOfRange(i2)) return false;
return Root(i1) == Root(i2);
}
bool ConnectionWeightedTreeImpl::OutOfRange(int i)
{
return i < 0 || i > mRoot.capacity();
}
int ConnectionWeightedTreeImpl::Root(int i)
{
if (OutOfRange(i)) return -1;
while (mRoot[i] != i)
{
mRoot[i] = mRoot[mRoot[i]]; // !!! path compression
i = mRoot[i];
}
return i;
}
<file_sep>//
// Created by raof01 on 9/21/15.
//
#include <cmath>
#include "PrimeSieve.h"
void PrimeSieve::InitSieve(int n) {
mSieve = new std::vector<bool>(n, true);
(*mSieve)[0] = false;
if (n > 1) (*mSieve)[1] = false;
}
PrimeSieve::PrimeSieve(int max) : mMaxValue(max + 1), mSieve(nullptr) {
if (mMaxValue <= 0) return;
InitSieve(mMaxValue);
int prime = 2;
while (prime < std::sqrt(mMaxValue)) {
SetupSieve(prime);
prime = GetNextPrime(prime);
}
}
int PrimeSieve::GetNextPrime(int prime) const {
int pos = ++prime;
while (pos < mSieve->size() && !(*mSieve)[pos])
++pos;
return pos;
}
void PrimeSieve::SetupSieve(int prime) {
for (int pos = prime * prime; pos < mSieve->size(); pos += prime) {
(*mSieve)[pos] = false;
}
}
bool PrimeSieve::GetPrimes(std::vector<int> &primes) const {
if (mSieve == nullptr) return false;
primes.clear();
for (int i = 2; i < mMaxValue; ++i) {
if ((*mSieve)[i])
primes.push_back(i);
}
return primes.size() > 0;
}
PrimeSieve::~PrimeSieve() {
if (mSieve != nullptr)
delete mSieve;
}
<file_sep>//
// Factorial.hpp
// algo
//
// Created by raof01 on 5/17/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#ifndef algo_Factorial_hpp
#define algo_Factorial_hpp
// Ignore overflow for now
template <int N, bool isPositive>
struct FactorialImpl
{
const static int result = N * FactorialImpl<N - 1, isPositive>::result;
};
template <>
struct FactorialImpl<0, true>
{
const static int result = 1;
};
template <>
struct FactorialImpl<1, true>
{
const static int result = 1;
};
template <int N>
struct FactorialImpl<N, false>
{
const static int result = -1;
};
template <int N>
struct Factorial
{
const static int result = FactorialImpl<N, N >= 0>::result;
};
#endif
<file_sep>//
// Connection.h
// algo
//
// Created by raof01 on 7/25/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#ifndef algo_Connection_h
#define algo_Connection_h
class Connection {
public:
virtual ~Connection() {};
public:
virtual void ConnectTo(int, int) = 0;
virtual bool Connected(int, int) = 0;
};
#endif
<file_sep>//
// DoubleLinkedList.h
// algo
//
// Created by raof01 on 5/9/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#ifndef algo_DoubleLinkedList_h
#define algo_DoubleLinkedList_h
class DoubleLinkedList
{
class _Iterator;
public:
typedef _Iterator Iterator;
DoubleLinkedList() : mHead(0) {}
~DoubleLinkedList();
void Insert(int);
void Delete(int);
void DeleteAll(int);
bool Empty();
int Count();
// Iterator creation / get should be separated with iterator operations
Iterator Begin();
Iterator End();
Iterator Find(int);
private:
struct Node;
private:
class _Iterator
{
public:
int operator*() const;
Iterator operator++(int);
Iterator& operator++();
private:
_Iterator(const Node* node, int n) : mCur(node), mCnt(n) {}
void Next();
private:
friend class DoubleLinkedList;
friend bool operator==(const Iterator& lhs, const Iterator& rhs);
friend bool operator!=(const Iterator& lhs, const Iterator& rhs);
private:
const Node* mCur;
int mCnt;
};
private:
Node* FindImpl(int);
bool DeleteImpl(int);
private:
struct Node* mHead;
};
#endif
<file_sep>//
// BinaryTreeLinkImpl.hpp
// algo
//
// Created by raof01 on 5/10/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#ifndef algo_BinaryTreeLinkImpl_hpp
#define algo_BinaryTreeLinkImpl_hpp
#include <functional>
#include "BinaryTree.hpp"
class BinaryTreeLinkImpl : public BinaryTree
{
public:
BinaryTreeLinkImpl(bool recur = true) : mRoot(0), mRecursive(recur), mCnt(0) {}
virtual ~BinaryTreeLinkImpl();
virtual void Insert(int);
virtual void Delete(int);
virtual void InOrderTraversal(Visitor<int, false>&) const;
virtual void PreOrderTraversal(Visitor<int, false>&) const;
virtual void PostOrderTraversal(Visitor<int, false>&) const;
virtual void BreadthFirstTraversal(Visitor<int, false>&) const;
virtual void DepthFirstTraversal(Visitor<int, false>&) const;
virtual int GetMaxValue() const;
virtual int GetMinValue() const;
virtual bool Find(int) const;
virtual bool GetParentValue(int, int&) const;
virtual bool GetSuccessorValue(int, int&) const;
virtual bool GetPredecessorValue(int, int&) const;
virtual int GetCount() const { return mCnt; }
virtual void Invert();
virtual int Floor(int) const;
virtual int Ceiling(int) const;
virtual int Size(int) const;
virtual int Rank(int) const;
private:
struct Node;
friend Node* GetLeft(Node*);
friend Node* GetRight(Node*);
private:
void DestroyBinaryTree(Node*&);
void InOrderTraversalRecursive(Visitor<int, false>&, const Node*) const;
void PreOrderTraversalRecursive(Visitor<int, false>&, const Node*) const;
void PostOrderTraversalRecursive(Visitor<int, false>&, const Node*) const;
void InOrderTraversalIter(Visitor<int, false>&, const Node*) const;
void PreOrderTraversalIter(Visitor<int, false>&, const Node*) const;
void PostOrderTraversalIter(Visitor<int, false>&, const Node*) const;
void BreadthFirstTraversalImpl(Visitor<int, false>&, const Node* r) const;
void DepthFirstTraversalImpl(Visitor<int, false>&, const Node* r) const;
const Node* FindImpl(Node*, int) const;
const Node* Extreme(std::pointer_to_unary_function<Node*, Node*>, const Node*) const;
const Node* Maximum(const Node*) const;
const Node* Minimum(const Node*) const;
const Node* Parent(int) const;
const Node* Successor(const Node*) const;
const Node* Predecessor(const Node*) const;
void InvertRecursive(Node*);
void InvertNoneRecursive();
const Node* Floor(const Node*, int) const;
const Node* Ceiling(const Node*, int) const;
int Rank(const Node*, int) const;
int Size(const Node*) const;
private:
Node* mRoot;
bool mRecursive;
int mCnt;
};
#endif
<file_sep>//
// SortsPerformanceTest.cpp
// algo
//
// Created by raof01 on 8/2/15.
// Copyright (c) 2015 raof01. All rights reserved.
//
#include <random>
#include "SortsPerformanceTest.h"
#include "MergeSort.hpp"
#include "InsertionSort.hpp"
#include "QuickSort.hpp"
#include "BubbleSort.hpp"
#include "HeapSort.hpp"
// command line argument to run only performance test:
// --gtest_filter=SortsPerformanceTest.*
const int MAX = 0xFFFFF;
SortsPerformanceTest::SortsPerformanceTest() : mInput(0)//, mResult(0)
{
mInput = new int [MAX];
//mResult = new int [MAX];
}
SortsPerformanceTest::~SortsPerformanceTest()
{
if (mInput != 0) delete [] mInput;
//if (mResult != 0) delete [] mResult;
};
void SortsPerformanceTest::SetUp()
{
std::default_random_engine generator;
std::uniform_int_distribution<int> distribution(1,0x7FFFFFFF);
for (int i = 0; i < MAX; ++i)
mInput[i] = distribution(generator);
// for (int i = 0; i < MAX; ++i)
// mInput[i] = MAX - i - 1;
//for (int i = 0; i < MAX; ++i)
// mResult[i] = i;
}
void SortsPerformanceTest::TearDown()
{
}
void SortsPerformanceTest::MergeSortBottomUpPerformance()
{
MergeSorter<int>::SortBottomUp(mInput, MAX);
}
void SortsPerformanceTest::MergeSortPerformance()
{
MergeSorter<int>::Sort(mInput, MAX);
}
void SortsPerformanceTest::InsertionSortPerformance()
{
//InsertionSorter<int>::Sort(mInput, MAX, 1);
}
void SortsPerformanceTest::QuickSortPerformance()
{
QuickSorter<int>::Sort(mInput, MAX);
}
void SortsPerformanceTest::BubbleSortPerformance()
{
//BubbleSorter<int>::Sort(mInput, MAX);
}
void SortsPerformanceTest::HeapSortPerformance()
{
HeapSorter<int>::Sort(mInput, MAX);
}
void SortsPerformanceTest::HeapSortNonRecursivePerformance()
{
HeapSorter<int>::SortNonRecursive(mInput, MAX);
}
|
6c8b51390819e22cec188678cd34881855e87efb
|
[
"Markdown",
"C",
"CMake",
"C++"
] | 115 |
C++
|
raof01/IntroAlgo
|
bc8871f25106aceac57305fc9be0e47efd053239
|
a89e9df82e337876b20ea3ac673e2de279ed8531
|
refs/heads/master
|
<repo_name>nj222dt/Front-page-New<file_sep>/php/handler/KLIhandler.php
<?php
class KLIHandler{
private $database;
private $session;
private $loginmodel;
public function __construct(Session $session, DataBase $database, LoginModel $loginmodel){
$this->database = $database;
$this->session = $session;
$this->loginmodel = $loginmodel;
$this->keeploggedin();
}
//checks against the cookies that are set if you check keep login
public function keeploggedin(){
if(isset($_COOKIE["KeepMeLoggedIn"]) && isset($_COOKIE["Security_one"]) && isset($_COOKIE["Security_two"])){
$data = substr($this->database->get($_COOKIE["Security_two"]),1,-1);
if($data == $_COOKIE["Security_one"]);{
$this->loginmodel->sessiontoken();
$this->session->setlogintoken();
return $this->session->checklogintoken();
}
}
return false;
}
}<file_sep>/php/model/logoutmodel.php
<?php
class LogoutModel{
private $session;
public function __construct(Session $session){
$this->session = $session;
}
public function logoutuser(){
$this->session->destroysession();
}
}<file_sep>/php/view/rssdivview.php
<?php
class RssDivView{
public function rssdivHTML(){
return '
'.$this->rssnotloggedin().'
';
}
private function rssnotloggedin(){
return'
<div id="rss_daily">
</div>
<div id="rss_york">
</div>
<div id="rss_wall">
</div>
<div id="rss_washington">
</div>
';
}
}<file_sep>/php/model/loginmodel.php
<?php
class LoginModel{
private $session;
private $database;
public function __construct(Session $session, DataBase $database){
$this->session = $session;
$this->database = $database;
}
public function authenticate($user,$checkbox){
$hash = $this->checkpassword($user);
if($checkbox){
$this->keeploggedin($user->getusername, $hash);
}
}
//checks the logintoken if it exist
public function loginstatus(){
return $this->session->checklogintoken();
}
//sets the sessiontoken in the session.
public function sessiontoken(){
$this->session->setsessiontoken($this->createtoken());
}
//sets the logintoken in the session
public function loginuser(){
$this->session->setlogintoken();
}
//creates a random 6 figure number
private function createtoken(){
return mt_rand(100000,999999);
}
//checks the password against the hash
private function checkpassword($user){
$data = substr($this->database->get($user->getusername()),1,-1);
if(!password_verify($user->getpassword(),$data)){
throw new \catchwrongcredentials();
}
$this->loginuser();
$this->sessiontoken();
return $data;
}
//if the user checked the box for allowing that they want to to bypass the login session.
//TODO: Change the Cookie names.
//TODO: Maybe find new solution. At the moment this is the best sulotion.
private function keeploggedin($user,$data){
setcookie("KeepMeLoggedIn",true,time() + (86400 * 30), "/");
setcookie("Security_one", $data,time() + (86400 * 30), "/");
setcookie("Security_two", $user->getusername,time() + (86400 * 30), "/");
}
}<file_sep>/php/firebase/database.php
<?php
class DataBase{
private $firebase;
public function __construct($database){
$this->firebase = $database;
}
//sets to database
//$data have to be array
public function set($path,$data){
$hash = password_hash($data->getpassword(), PASSWORD_DEFAULT, array("cost" => 10));
$storedata = array(
'Username' => $data->getusername(),
'Password' => $<PASSWORD>,
'FirstTime' => true
);
$this->firebase->set($path,$storedata);
}
//gets from database
public function get($path){
return $this->firebase->get($path);
}
public function gethash($path){
return $this->firebase->get($path.'/Password');
}
//deletes from database
public function delete($path){
$this->firebase->delete($path);
}
//updates database
//$data have to be array
public function update($path,$data){
$this->firebase->update($path,$data);
}
//push to database
//$data have to be array
public function push($path,$data){
$this->firebase->push($path,$data);
}
}<file_sep>/php/view/llrview.php
<?php
class LLRView{
//buttons
private static $gotologin ="LLRView::GoToLogin";
private static $logout = "LLRView::Logout";
private static $gotoregister = "LLRView::GoToRegister";
//login-form
private static $username = "LLRView::Username";
private static $password = "<PASSWORD>";
private static $checkbox = "LLRView::Checkbox";
private static $login = "LLRView::Login";
//register-form
private static $regusername = "LLRView::RegUsername";
private static $regpassword = "LLRView::RegPassword";
private static $regconfpass = "LLRView::RegConfPass";
private static $regregister = "LLRView::RegRegister";
//errorhandling
private $message = "";
//------------------------------------------------------------------------------
//renders buttons depending on session state
public function buttonHTML(){
return '
<form method="post">
<input type="submit" name="'. self::$gotologin .'" value="Go To Login" class="main_submit_login"/>
<input type="submit" name="'. self::$gotoregister .'" value="Go To Register" class="main_submit_register"/>
</form>
';
}
public function logutHTML(){
return '
<form method="post">
<input type="submit" name="'. self::$logout .'" value="Logout" class="main_submit_logout"/>
</form>
';
}
public function loginHTML(){
return '
<p class="main_error_message">'. $this->message .'</p>
<form method="post">
<input type="text" name="'. self::$username .'" placeholder="Username" class="main_submit_login_form" />
<input type="password" name="'. self::$password .'" placeholder="<PASSWORD>" class="main_submit_login_form" /><br>
<label for="'. self::$checkbox .'" class="main_submit_login_form_label" >Stay Logged In</label>
<input type="checkbox" name="'. self::$checkbox .'" id="'. $rssdn .'" class="main_submit_login_form" value="Checked"/><br>
<input type="submit" name="'. self::$login .'" value="Login" class="main_submit_login_form_button"/>
</form>
';
}
public function registerHTML(){
return '
<p class="main_error_message">'. $this->message .'</p>
<form method="post">
<input type="text" name="'. self::$regusername .'" placeholder="Username" class="" />
<input type="password" name="'. self::$regpassword .'" placeholder="<PASSWORD>" class="" />
<input type="password" name="'. self::$regconfpass .'" placeholder="<PASSWORD> Password" class="" />
<input type="submit" name="'. self::$regregister .'" value="Register" class="" />
</form>
';
}
//checks after button event
//might wanna look for a better solution.
public function diduserpressgologin(){
return isset($_POST[self::$gotologin]);
}
public function diduserpresslogin(){
return isset($_POST[self::$login]);
}
public function diduserpressgoregister(){
return isset($_POST[self::$gotoregister]);
}
public function diduserpressregister(){
return isset($_POST[self::$regregister]);
}
public function diduserpresslogout(){
return isset($_POST[self::$logout]);
}
//sets the error messages
private function setmessage($message){
$this->message = $message;
}
public function setcredentialmessage(){
$this->setmessage(ErrorMsg::$wrongcredentials);
}
public function setuserexistmessage(){
$this->setmessage(self::$userexist);
}
//checks the inputs for errors and escapes them aswell.
//TODO: Find better solution
private function errorcheck(){
if($_SERVER['QUERY_STRING'] == "login"){
$user = $this->getcredential(self::$username);
$pass = $this->getcredential(self::$password);
}
else{
$user = $this->getcredential(self::$regusername);
$pass = $this->getcredential(self::$regpassword);
}
if($user == "" || $pass == ""){
throw new \catchemptyinput();
}
if(preg_match('/\s/',$user) || preg_match('/\s/',$pass)){
throw new \catchwhitespace();
}
if($pass != strip_tags($pass) || $user != strip_tags($user)){
throw new \catchcodeinput();
}
if($_SERVER['QUERY_STRING'] == "register"){
$this->checkpassword();
}
}
//gets the values from username and password and checks if they are set
private function getcredential($id){
if(isset($_POST[$id])) {
return $_POST[$id];
}
return "";
}
//checks if the register password and confirm password match
private function checkpassword(){
if($this->getcredential(self::$regpassword) != $this->getcredential(self::$regconfpass)){
throw new \catchnomatch();
}
}
//returns the information of either login or register
public function getnewuser(){
try{
$this->errorcheck();
return new user($this->getcredential(self::$regusername), $this->getcredential(self::$regpassword));
}
catch(catchnomatch $e){
$this->setmessage(ErrorMsg::$passnomatch);
}
catch(catchemptyinput $e){
$this->setmessage(ErrorMsg::$emptyinput);
}
catch(catchcodeinput $e){
$this->setmessage(ErrorMsg::$codeinput);
}
catch(catchwhitespace $e){
$this->setmessage(ErrorMsg::$whitespace);
}
}
public function getloginuser(){
try{
$this->errorcheck();
return new user($this->getcredential(self::$username), $this->getcredential(self::$password));
}
catch(catchemptyinput $e){
$this->setmessage(ErrorMsg::$emptyinput);
}
catch(catchcodeinput $e){
$this->setmessage(ErrorMsg::$codeinput);
}
catch(catchwhitespace $e){
$this->setmessage(ErrorMsg::$whitespace);
}
}
}<file_sep>/JAVASCRIPT/rsspublicscript.js
"use strict";
const rssPublicFeed = {
render:function(){
let feed;
var div;
const rssarray = [
['rss_daily','http://www.dailymail.co.uk/articles.rss'],
['rss_york','http://rss.nytimes.com/services/xml/rss/nyt/InternationalHome.xml'],
['rss_wall','http://www.wsj.com/xml/rss/3_7085.xml'],
['rss_washington','http://feeds.washingtonpost.com/rss/world']
];
for(var i = 0; i <= rssarray.length -1; i++){
feed = new google.feeds.Feed(rssarray[i][1]);
div = document.getElementById(rssarray[i][0]);
console.log(div);
feed.load(function(result){
if(!result.error){
for(var x = 0; x <= result.feed.entries.length; x++){
var entry = result.feed.entries[x];
console.log(entry);
var a = document.createElement("a");
var atext = document.createTextNode(entry.title);
a.href = entry.link;
a.appendChild(atext);
div.appendChild(a);
}
}
});
}
}
};
window.onload = rssPublicFeed.render();<file_sep>/index.php
<?php
//handlers
require_once("php/handler/LLRhandler.php");
require_once("php/handler/KLIhandler.php");
//models
require_once("php/model/loginmodel.php");
require_once("php/model/registermodel.php");
require_once("php/model/logoutmodel.php");
//session
require_once("php/session/session.php");
//users
require_once("php/users/user.php");
//views
require_once("php/view/rssdivview.php");
require_once("php/view/llrview.php");
require_once("php/view/mainview.php");
//error
require_once("php/error/errormsg.php");
require_once("php/error/errorexception.php");
//database
require_once('php/firebase/firebaseInterface.php');
require_once('php/firebase/firebaseStub.php');
require_once('php/firebase/firebaseLib.php');
require_once('php/firebase/database.php');
//---------------------------------------------------------
//database
$firebase = new \firebase\FirebaseLib('https://frontpageworks.firebaseio.com/','<KEY>');
$database = new DataBase($firebase);
//error
$errormsg = new ErrorMsg();
//session
$session = new Session();
//models
$loginmodel = new LoginModel($session,$database);
$registermodel = new RegisterModel($session,$database);
$logoutmodel = new LogoutModel($session);
//views
$llrview = new LLRView();
$rssdivview = new RssDivView();
//handlers
//login/logout/register handler
$llrhandler = new LLRHandler($llrview,$loginmodel,$registermodel,$logoutmodel);
$klihandler = new KLIHandler($session,$database,$loginmodel);
//mainfile
$mainview = new MainView();
//---------------------------------------------------------
$llrhandler->logout();
if(!$loginmodel->loginstatus()){
if(!$klihandler->keeploggedin()){
$llrhandler->login();
$llrhandler->register();
$llrhandler->loginuser();
$llrhandler->register();
}
}
$mainview->Render($llrview,$rssdivview);<file_sep>/php/view/mainview.php
<?php
class Mainview{
//handels the main dom rendering
public function Render($llrview,$rssdiv){
echo '<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Custom Front Page</title>
</head>
<body>
<script type="text/javascript">google.load("feeds", "1");</script>
<header>
<div class="header_container">
'.$this->llrbuttonrender($llrview).'
</div>
</header>
<main>
<div class="main_container">
'.$this->lrrender($llrview).'
'.$this->rssdivrender($rssdiv).'
</div>
</main>
<script type="text/javascript" src="../../JAVASCRIPT/rsspublicscript.js"></script>
</body>
</html>
';
}
//renders what buttons to show
private function llrbuttonrender($llrview){
if($_SESSION["LoginToken"] == null){
return $llrview->buttonHTML();
}
return $llrview->logoutHTML();
}
//renders if register or login should render
private function lrrender($llrview){
if($_SERVER['QUERY_STRING'] == "login"){
return $llrview->loginHTML();
}
if($_SERVER['QUERY_STRING'] == "register"){
return $llrview->registerHTML();
}
}
//depends how it should render the RSS-feed divs based on if you are logged in or not.
private function rssdivrender($rssdiv){
if($_SESSION["LoginToken"] == null){
return $rssdiv->rssdivHTML();
}
}
}<file_sep>/php/handler/LLRhandler.php
<?php
class LLRHandler{
private $llrview;
private $loginmodel;
private $registermodel;
private $logoutmodel;
public function __construct(LLRView $llrview,LoginModel $loginmodel, RegisterModel $registermodel, LogoutModel $logoutmodel){
$this->llrview = $llrview;
$this->loginmodel = $loginmodel;
$this->registermodel = $registermodel;
$this->logoutmodel = $logoutmodel;
}
//checking for login event
public function login(){
if($this->llrview->diduserpressgologin()){
header("Location: /?login");
}
}
//checking for logout event
public function logout(){
if($this->llrview->diduserpresslogout()){
$this->logoutmodel->logoutuser();
header("Location: /?");
}
}
//checking for register event
public function register(){
if($this->llrview->diduserpressgoregister()){
header("Location: /?register");
}
}
//checking for login main event
public function loginuser(){
if($this->llrview->diduserpresslogin()){
$user = $this->llrview->getloginuser();
$checkbox = false;
if(isset($_POST[LLRView::$checkbox])){
$checkbox = true;
}
if($user != null){
try{
$this->loginmodel->authenticate($user,$checkbox);
}
catch(catchwrongcredentials $e){
$this->llrview->setcredentialmessage();
}
}
}
}
//checking register main event
public function registeruser(){
if($this->llrview->diduserpressregister()){
$user = $this->llrview->getnewuser();
if($user != null){
try{
$this->registermodel->register($user);
}
catch(catchuserexist $e){
$this->llrview->setuserexistmessage();
}
}
}
}
}<file_sep>/php/error/errormsg.php
<?php
class ErrorMsg{
public static $wrongcredentials = "Either the username or the password is wrong.";
public static $whitespace = "Whitespace in either password or username.";
public static $emptyinput = 'All fields must be filled in.';
public static $codeinput = "There is code in one of the input fields, this is not allowed.";
public static $passnotmatch = "The password does not match.";
public static $overlayingerror = "An error have happend in the registration process.";
public static $userexist = "The username already exist.";
}<file_sep>/php/model/registermodel.php
<?php
class RegisterModel{
private $session;
private $database;
public function __construct(Session $session, DataBase $database){
$this->session = $session;
$this->database = $database;
}
//Register the user if the username exist it will throw the exception
public function register($user){
if($this->database->get($user->getusername()) == null){
$this->database->set($user->getusername(),$user);
}
else{
throw new \catchuserexist();
}
}
}<file_sep>/php/error/errorexception.php
<?php
class catchemptyinput extends Exception{}
class catchwrongcredentials extends Exception{}
class catchwhitespace extends Exception{}
class catchcodeinput extends Exception{}
class catchnomatch extends Exception{}
class catchoverlaying extends Exception{}
class catchuserexist extends Exception{}<file_sep>/php/session/session.php
<?php
class Session{
public function __construct(){
session_start();
}
//Destroys the session
public function destroysession(){
setcookie("KeepMeLoggedIn",true,time() - 3600, "/");
setcookie("Security_one", "Gone",time() - 3600, "/");
setcookie("Security_two", "Gone",time() - 3600, "/");
session_destroy();
}
//sets and checks if the user have logged in this session
public function setlogintoken(){
$_SESSION["LoginToken"] = true;
}
public function checklogintoken(){
if(isset($_SESSION["LoginToken"])){
return $_SESSION["LoginToken"];
}
return false;
}
public function setsessiontoken($token){
$_SESSION["SessionToken"] = $token;
}
}
|
da7056ac545f6574028b8664d9634671e8bc4f5b
|
[
"JavaScript",
"PHP"
] | 14 |
PHP
|
nj222dt/Front-page-New
|
49f4ce223a859600943614086905364d28491738
|
b4454a0eb880d2268f48f55b94c7654afad427fd
|
refs/heads/master
|
<file_sep>var curRun = undefined;
function loadRunList() {
$.ajax({
url:"/runs",
}).done(function(data) {
if (!Array.isArray(data)) {
console.log("Didn't get an array for the run list.");
return;
}
data.forEach(function(runEntry) {
var newRunE = $(document.createElement("div"));
newRunE.attr('id', runEntry.run);
newRunE.addClass("run");
newRunE.addClass(runEntry.success ? "run-success" : "run-error");
newRunE.append($("<div>" + runEntry.project + "</div>"));
newRunE.append($("<div>" + runEntry.branch + "</div>"));
newRunE.append($("<div>" + runEntry.commit.substr(0, 8) + "...</div>"));
newRunE.click(function() {
loadRun(runEntry, runEntry.run);
$("#runs>div.active").removeClass("active");
$(this).addClass("active");
});
$("#runs").append(newRunE);
});
if (curRun === undefined) {
loadRun(data[0], data[0].run);
$("#"+data[0].run).addClass("active");
}
});
}
function loadLogFile(logUrl) {
$.ajax({
url:logUrl
}).done(function(data) {
$("#logOutput").text(data);
});
}
function loadRun(parent, runId) {
$.ajax({
url:("/runs/" + runId)
}).done(function(data) {
curRun = data;
$("#runData h3").html(""); // clear it
if (parent.success) {
$("#runData h3").append("<span class='checkmark'></span>");
} else {
$("#runData h3").append("<span class='ex'></span>");
}
$("#runData h3").append(data.project + " - " + data.branch + " - " + data.commit);
var hasPatchLog = false;
var patchLogIndex = 0;
$("#logFileList").empty();
data.files.forEach(function(filename, idx) {
var parts = filename.split("/");
var entry = $(document.createElement("div"));
entry.attr('id', 'log'+idx);
entry.append(parts[parts.length - 1]);
entry.addClass("log-file");
entry.click(function() {
loadLogFile(filename);
$("#logFileList>div.active").removeClass("active");
$(this).addClass("active");
});
$("#logFileList").append(entry);
if (parts[parts.length - 1] == "patch.log") {
hasPatchLog = true;
patchLogIndex = idx;
}
});
if (hasPatchLog) {
loadLogFile("/runs/" + runId + "/patch.log");
$("#log"+patchLogIndex).addClass("active");
} else {
loadLogFile(data.files[0]);
$("#log0").addClass("active");
}
});
}
$(document).ready(function() {
loadRunList();
});
<file_sep>#!/bin/bash
for x in `ls /dev/cu.usbmodem*`; do
devId=${x#\/dev\/cu.}
killPid=`ps -o command,args,pid | grep node | grep $devId | awk '{print $NF}'`
kill $killPid
done
<file_sep>#!/bin/bash
checkTime=`date "+%s"`
for x in `ls /dev/cu.usbmodem*`; do
devId=${x#\/dev\/cu.}
if [ ! -e $devId.0 ]; then
echo "No log for $devId"
else
lastLog=`ls -t $devId.* | head -1`
lastModified=`stat -f "%m" $lastLog`
modDiff=$((checkTime-lastModified))
if [ $modDiff > 10 ]; then
echo "Long gap on device $devId $modDiff"
fi
fi
done
<file_sep>#!/bin/bash
for x in `ls /dev/cu.usbmodem*`; do
devId=${x#\/dev\/cu.}
node reliability.js longtest -d $x --id run.id -l log-runs/cur/$devId &
done
<file_sep>var fs = require("fs");
var split = require("split");
var argv = require('minimist')(process.argv.slice(2));
var writeStream = fs.createWriteStream(argv["o"]);
writeStream.write("type,t,up,seen,links,mem,temp,humidity,lux,moveX,moveY,moveZ,db,beat,build,tap,error\n");
var readStream = fs.createReadStream(argv["i"]);
readStream.pipe(split(JSON.parse, null, {trailing: false})).on('data', function(objData) {
if (objData.type == "error") {
writeStream.write("error," + objData.t + ",,,,,,,,,,,,,,,\"" + objData.data + "\"\n");
} else if (objData.type == "report") {
var reportLine = "report," + objData.t + ",";
reportKeys = ["up", "seen", "links", "mem", "temp", "humidity", "lux", "move", "dB", "beat", "build", "tap"];
reportKeys.forEach(function(key) {
if (key == "move") {
if (objData.data["move"] == undefined) {
reportLine += ",,,";
} else {
var parts = objData.data.move.split(",");
reportLine += parts[0] + "," + parts[1] + "," + parts[2] + ",";
}
} else if (typeof(objData.data[key]) === 'undefined') {
reportLine += ",";
} else {
reportLine += objData.data[key] + ",";
}
});
reportLine += "\n";
writeStream.write(reportLine);
} else {
console.log("Unknown field type", objData.type);
}
}).on("error", function(err) {
console.log("we got an error", err);
console.log(err.stack);
}).on("end", function() {
console.log("All done, end");
});
writeStream.on("close", function() {
console.log("All done writing");
});
|
b2dae35ccddff3b9d47589de0bad9864bbb0438b
|
[
"JavaScript",
"Shell"
] | 5 |
JavaScript
|
getfilament/Phil
|
33f32dd5824063188dc5ddc510094cde110d301c
|
e46ca104a1ef19e9b06f6de7930f204a45cda16b
|
refs/heads/master
|
<repo_name>qbaty/veui<file_sep>/src/managers/overlay.js
import { uniqueId, remove } from 'lodash'
import Vue from 'vue'
const tree = []
const treeNodeIndex = {}
let baseZIndex = 100
class TreeNode {
children = [];
isTopMost = false;
constructor ({ id, parentId, isTopMost }) {
this.id = id
this.parentId = parentId
}
}
function iterateTree (tree, iteratee) {
for (let i = 0, il = tree.length; i < il; ++i) {
let treeNode = tree[i]
if (iteratee(treeNode)) {
return true
}
if (iterateTree(treeNode.children, iteratee)) {
return true
}
}
return false
}
function genUid () {
return uniqueId('overlay-')
}
function addToList (list, treeNode) {
if (treeNode.isTopMost) {
list.push(treeNode)
} else {
let firstTopMostIndex
for (let i = 0, il = list.length; i < il; ++i) {
if (list[i].isTopMost) {
firstTopMostIndex = i
}
}
if (firstTopMostIndex === undefined) {
list.push(treeNode)
} else {
list.splice(firstTopMostIndex, 0, TreeNode)
}
}
}
function removeTreeNode (id) {
if (treeNodeIndex[id] === null) {
return
}
iterateTree(tree, (treeNode) => {
if (treeNode.id === id) {
const parentTreeNode = treeNode.parentId && treeNodeIndex[treeNode.parentId].treeNode
const treeNodeList = parentTreeNode ? parentTreeNode.children : tree
remove(treeNodeList, item => item.id === id)
return true
}
})
treeNodeIndex[id] = null
}
function toTop (id) {
const treeNode = treeNodeIndex[id].treeNode
if (treeNode) {
const parentTreeNode = treeNode.parentId && treeNodeIndex[treeNode.parentId].treeNode
const treeNodeList = parentTreeNode ? parentTreeNode.children : tree
const treeNodeIndex = treeNodeList.indexOf(treeNode)
const treeNodeListLength = treeNodeList.length
for (let i = treeNodeIndex + 1; i < treeNodeListLength; ++i) {
const curTreeNode = treeNodeList[i]
if (curTreeNode.isTopMost) {
treeNodeList.splice(i - 1, 1, treeNode)
break
}
treeNodeList[i - 1] = curTreeNode
treeNodeList[i] = null
}
// 如果没有topMost的元素,就直接把目标元素放在数组最后面
if (treeNodeList[treeNodeListLength - 1] === null) {
treeNodeList[treeNodeListLength - 1] = treeNode
}
} else {
throw new Error(`The treeNode ${id} does not exist!`)
}
// 变了位置,自然要刷一遍zindex了
refreshZIndex()
}
function refreshZIndex () {
let counter = baseZIndex
iterateTree(tree, (treeNode) => {
counter++
treeNodeIndex[treeNode.id].overlayZIndexInstance.$emit('zindexchange', counter)
})
}
export function addOverlay (parentOverlayId, isTopMost = false) {
let uid = genUid()
let treeNode
if (parentOverlayId) {
// 找到父节点
const parentTreeNode = treeNodeIndex[parentOverlayId].treeNode
if (!parentTreeNode) {
throw new Error(`The overlay(${parentOverlayId})'s parent overlay does not exist!`)
} else {
treeNode = new TreeNode({ id: uid, parentId: parentTreeNode.id, isTopMost })
addToList(parentTreeNode.children, treeNode)
}
} else {
treeNode = new TreeNode({ id: uid, isTopMost })
addToList(tree, treeNode)
}
const overlayZIndexInstance = new Vue()
overlayZIndexInstance.id = uid
overlayZIndexInstance.toTop = () => toTop(uid)
overlayZIndexInstance.remove = () => removeTreeNode(uid)
overlayZIndexInstance.refresh = () => refreshZIndex()
treeNodeIndex[uid] = {
treeNode,
overlayZIndexInstance
}
return overlayZIndexInstance
}
export function setBaseZIndex (zIndex) {
baseZIndex = zIndex
}
<file_sep>/src/directives/clickoutside.js
import { isFunction, uniqueId, remove } from 'lodash'
let handlerBindings = []
const bindingKey = '__veui_click_outside__'
document.addEventListener('click', e => {
handlerBindings.forEach(item => {
item[bindingKey] && item[bindingKey].handler(e)
})
}, true)
function generate (el, value) {
return function (e) {
if (!el.contains(e.target) && isFunction(value)) {
// 目前只支持v-clickoutside="func"这种形式
value(e)
}
}
}
export default {
bind (el, {value}) {
el[bindingKey] = {
id: uniqueId(),
handler: generate(el, value)
}
handlerBindings.push(el)
},
update (el, {value}) {
if (isFunction(value)) {
el[bindingKey].handler = generate(el, value)
}
},
unbind (el) {
remove(handlerBindings, item => item[bindingKey].id === el[bindingKey].id)
}
}
<file_sep>/src/index.js
import { setBaseZIndex, addOverlay } from './managers/overlay'
import drag from './directives/drag'
import clickoutside from './directives/clickoutside'
export default {
install (Vue, { baseZIndex = 100 } = {}) {
setBaseZIndex(baseZIndex)
Vue.prototype.$veui = {
addOverlay
}
Vue.directive('drag', drag)
Vue.directive('clickoutside', clickoutside)
}
}
<file_sep>/src/components/Table/mixin.js
import { includes } from 'lodash'
export default {
computed: {
table () {
let current = this.$parent
while (current) {
let { uiTypes } = current.$options
if (uiTypes && includes(uiTypes, 'table')) {
return current
}
current = current.$parent
}
return null
}
}
}
<file_sep>/src/components/Table/Body.js
import Checkbox from '../Checkbox'
import mixin from './mixin'
export default {
components: {
'veui-checkbox': Checkbox
},
mixins: [mixin],
props: {
data: Array,
columns: Array,
selectable: Boolean,
selectedItems: Object,
keys: Array
},
render () {
return (
<tbody>
{this._l(this.data, (item, index) => (
<tr>
{
this.table.selectable
? <td><veui-checkbox checked={!!this.selectedItems[this.keys ? this.keys[index] : index]}
key={this.keys[index]} onChange={checked => { this.$emit('select', checked, index) }}/></td>
: ''
}
{
this._l(this.columns, col => (
<td>{col.renderBody.call(this._renderProxy, { item, col, index })}</td>
))
}
</tr>
))}
</tbody>
)
}
}
<file_sep>/src/utils/date.js
import { flatten } from 'lodash'
export function getDaysInMonth (year, month) {
let day
if (year instanceof Date) {
day = new Date(year)
} else {
day = new Date(year, month + 1)
}
day.setDate(0)
return day.getDate()
}
export function toDateData (date) {
if (typeof date === 'number') {
date = new Date(date)
}
if (date instanceof Date) {
return {
date: date.getDate(),
month: date.getMonth(),
year: date.getFullYear()
}
}
return date
}
export function toDate (date) {
if (typeof date === 'number') {
return new Date(date)
} else if ('date' in date && 'month' in date && 'year' in date) {
return fromDateData(date)
}
return date
}
export function fromDateData ({ year, month, date }) {
return new Date(year, month, date)
}
export function isSameDay (src, target) {
if (!src || !target) {
return false
}
let srcData = toDateData(src)
let targetData = toDateData(target)
return srcData.date === targetData.date &&
srcData.month === targetData.month &&
srcData.year === targetData.year
}
export function isInRange (day, range) {
if (!range || range.length < 2) {
return false
}
let date = toDate(day)
let dateRange = range.map(toDate)
for (let i = 0; i < dateRange.length / 2; i++) {
if (date - dateRange[i * 2] >= 0 && dateRange[i * 2 + 1] - date >= 0) {
return true
}
}
return false
}
export function mergeRange (r1, r2) {
let dates1 = flatten(r1)
let dates2 = flatten(r2)
let dates = [...dates1, ...dates2]
.sort((a, b) => a - b)
.map((date, i) => {
if (isInRange(date, dates1) && isInRange(date, dates2)) {
return addDays(date, i % 2 ? -1 : 1)
}
return date
})
for (let i = 0; i < dates.length / 2; i++) {
if (dates[i * 2 + 1] - dates[i * 2] < 0) {
dates[i * 2 + 1] = dates[i * 2] = null
}
if (dates[i * 2] - addDays(dates[i * 2 - 1], 1) === 0) {
dates[i * 2] = dates[i * 2 - 1] = null
}
}
dates = dates.filter(date => date !== null)
let result = []
while (dates.length) {
result.push(dates.splice(0, 2))
}
return result
}
const ONE_DAY = 24 * 60 * 60 * 1000
function addDays (date, days) {
return new Date(date - 0 + days * ONE_DAY)
}
<file_sep>/src/utils/dom.js
export function closest (element, selectors) {
if (element.closest) {
return element.closest(selectors)
}
// Polyfill from https://developer.mozilla.org/en-US/docs/Web/API/Element/closest
let matches = (element.document || element.ownerDocument).querySelectorAll(selectors)
let i
do {
i = matches.length
while (--i >= 0 && matches.item(i) !== element) {}
} while ((i < 0) && (element = element.parentElement))
return element
}
<file_sep>/test/unit/specs/utils/dom.spec.js
import {closest} from '@/utils/dom'
describe('utils/dom', () => {
it('closest', () => {
let root = document.createElement('div')
root.innerHTML = `<div class="tip">点此
<a class="btn" href="/login">
<span class="text">登录</span>
</a>
</div>`
document.body.appendChild(root)
let span = root.querySelector('span')
expect(closest(span, 'span').className).to.equal('text')
expect(closest(span, 'a').className).to.equal('btn')
expect(closest(span, 'div').className).to.equal('tip')
expect(closest(span, 'nav')).to.be.a('null')
})
})
<file_sep>/src/directives/drag.js
export default {
bind (el, { modifiers }, vnode) {
const contextComponent = vnode.context
const dragData = {
dragging: false,
initX: 0,
initY: 0,
mousedownHandler (event) {
const { clientX, clientY } = event
if (dragData.dragging) {
return
}
dragData.dragging = true
dragData.initX = clientX
dragData.initY = clientY
contextComponent.$emit('dragstart', { event })
function selectStartHandler (e) {
e.preventDefault()
}
function mouseMoveHandler (event) {
const { clientX, clientY } = event
if (!dragData.dragging) {
return
}
contextComponent.$emit('drag', {
distanceX: clientX - dragData.initX,
distanceY: clientY - dragData.initY,
event
})
}
function mouseupHandler (event) {
dragData.dragging = false
contextComponent.$emit('dragend', { event })
window.removeEventListener('mousemove', mouseMoveHandler)
window.removeEventListener('mouseup', mouseupHandler)
window.removeEventListener('selectstart', selectStartHandler)
}
// TODO: 非IE下面不用移除选区
document.getSelection().removeAllRanges()
window.addEventListener('selectstart', selectStartHandler)
window.addEventListener('mousemove', mouseMoveHandler)
window.addEventListener('mouseup', mouseupHandler)
}
}
el.addEventListener('mousedown', dragData.mousedownHandler)
el.dragData = dragData
},
unbind (el) {
const dragData = el.dragData
el.removeEventListener('mousedown', dragData.mousedownHandler)
el.dragData = null
}
}
<file_sep>/src/mixins/input.js
// import zipObject from 'lodash/zipObject'
// import isFunction from 'lodash/isFunction'
// import validator from '../utils/validators'
export default {
uiTypes: ['input'],
props: {
value: null,
name: String,
readonly: Boolean,
disabled: Boolean
},
computed: {
// _validateRules () {
// if (!this.rules) {
// return {}
// } else {
// let rules = this.rules.trim().split(/\s+/)
// switch (typeof this.rules) {
// case 'string':
// return zipObject(
// rules,
// rules.map(rule => {
// return {
// value: true,
// message: ''
// }
// })
// )
// case 'object':
// return this.rules
// }
// }
// }
},
methods: {
// validate () {
// let rules = this._validateRules
// let res = validator.validate(rules, this.$data._rawValue)
// if (res && typeof res === 'object') {
// isFunction(this.showErrorMessage) && this.showErrorMessage(res)
// }
// return res
// }
}
}
|
e8b39873403318a71a762d9cbc8ba1d07358f979
|
[
"JavaScript"
] | 10 |
JavaScript
|
qbaty/veui
|
ab96047af95931e9238ce301730f3f1a3aaf4174
|
a40ae134901e8f6befb982eb52dfcf18a32caa88
|
refs/heads/master
|
<file_sep>using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace Application_Processing
{
/// <summary>
/// Логика взаимодействия для Edit_Order.xaml
/// </summary>
public partial class Edit_Order : Window
{
public long ID_Client_Order = 0;
public long ID_Client = 0;
Request req = new Request();
public Edit_Order()
{
InitializeComponent();
}
private void btn_Cancel_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
private void btn_Add_Click(object sender, RoutedEventArgs e)
{
if (String.IsNullOrEmpty(combo_Vyd.Text.ToString()))
{
MessageBox.Show("Выберите вид заявки", "Информация", MessageBoxButton.OK, MessageBoxImage.Information);
return;
}
if (String.IsNullOrEmpty(txt_Description.Text.ToString()))
{
MessageBox.Show("Заполните поле Комментарий", "Информация", MessageBoxButton.OK, MessageBoxImage.Information);
return;
}
if (Rad_Vybrat.IsChecked == true)
{
if (String.IsNullOrEmpty(combo_Audience.Text.ToString()))
{
MessageBox.Show("Выберите номер аудитории со списка", "Информация", MessageBoxButton.OK, MessageBoxImage.Information);
return;
}
}
else
{
if (Rad_Vvesty.IsChecked == true)
{
if (String.IsNullOrEmpty(txt_Audience_New.Text.ToString()))
{
MessageBox.Show("Заполните поле Аудитория", "Информация", MessageBoxButton.OK, MessageBoxImage.Information);
return;
}
}
}
ComboBoxItem typeItem = (ComboBoxItem)combo_Vyd.SelectedItem;
string Vyd_Zayavka = typeItem.Content.ToString();
string Description = txt_Description.Text.ToString();
string Number_Audience = string.Empty;
string date_Now = DateTime.Now.ToString();
if (Rad_Vybrat.IsChecked == true)
{
Number_Audience = combo_Audience.SelectedItem.ToString();
}
else
{
if (Rad_Vvesty.IsChecked == true)
{
Number_Audience = txt_Audience_New.Text.ToString();
}
}
if (ID_Client_Order > 0)
{
string Sql_Command_Update = "UPDATE [dbo].[Client_Order] SET " +
"[Type_of_request] = '" + Vyd_Zayavka + "', " +
"[Description] = '" + Description + "', " +
"[Number_Audience] = '" + Number_Audience + "', " +
"[Date_Add] = '" + date_Now + "', " +
"WHERE ID=" + ID_Client_Order + "";
long rez_update_Document = req.insert_del_update(Sql_Command_Update);
if (rez_update_Document > 0)
{
MessageBox.Show("Заявка успешно обновлена", "Успех", MessageBoxButton.OK, MessageBoxImage.Information);
MainWindow.SelfRefMain_frm.Fill_DGV_Client_Orders(ID_Client);
this.Close();
}
}
else
{
string Sql_Command_Insert = "INSERT INTO [dbo].[Client_Order] (" +
"[Type_of_request], " +
"[Description], " +
"[Number_Audience], " +
"[Date_Add], " +
"[ID_Client], " +
"[Status]) " +
"VALUES (" +
"'" + Vyd_Zayavka + "', " +
"'" + Description + "', " +
"'" + Number_Audience + "', " +
"'" + date_Now + "', " +
"" + ID_Client + ", " +
"'В работе')";
long rez_insert_Document = req.insert_del_update(Sql_Command_Insert);
if (rez_insert_Document > 0)
{
MessageBox.Show("Заявка успешно добавлена в систему!", "Успех", MessageBoxButton.OK, MessageBoxImage.Information);
MainWindow.SelfRefMain_frm.Fill_DGV_Client_Orders(ID_Client);
this.Close();
}
}
}
public void Fill_Combo_Audience()
{
combo_Audience.Items.Clear();
string sql_command = "SELECT DISTINCT ORD.Number_Audience FROM Client_Order ORD";
int row_count = 0;
req.con.Open();
SqlCommand exeSql = new SqlCommand(sql_command, req.con);
SqlDataReader dr = exeSql.ExecuteReader();
while (dr.Read())
{
row_count++;
}
dr.Close();
if (row_count > 0)
{
dr = exeSql.ExecuteReader(CommandBehavior.CloseConnection);
int i = 0;
while (dr.Read())
{
for (int j = 0; j < dr.FieldCount; j++)
{
combo_Audience.Items.Add(dr[j].ToString());
}
i += 1;
}
dr.Close();
req.con.Close();
}
dr.Close();
req.con.Close();
if(combo_Audience.Items.Count>0)
{
combo_Audience.SelectedIndex = 0;
}
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
Fill_Combo_Audience();
}
private void Rad_Vybrat_Checked(object sender, RoutedEventArgs e)
{
combo_Audience.Visibility = Visibility.Visible;
txt_Audience_New.Visibility = Visibility.Hidden;
}
private void Rad_Vvesty_Checked(object sender, RoutedEventArgs e)
{
combo_Audience.Visibility = Visibility.Hidden;
txt_Audience_New.Visibility = Visibility.Visible;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace Application_Processing
{
/// <summary>
/// Логика взаимодействия для Edit_Client.xaml
/// </summary>
public partial class Edit_Client : Window
{
Request req = new Request();
public long ID_Client = 0;
public Edit_Client()
{
InitializeComponent();
}
private void btn_Cancel_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
private void btn_Add_Click(object sender, RoutedEventArgs e)
{
if (String.IsNullOrEmpty(txt_FIO.Text.ToString()))
{
MessageBox.Show("Введите ФИО клиента", "Информация", MessageBoxButton.OK, MessageBoxImage.Information);
return;
}
if (String.IsNullOrEmpty(txt_Login.Text.ToString()))
{
MessageBox.Show("Введите ЛОГИН клиента", "Информация", MessageBoxButton.OK, MessageBoxImage.Information);
return;
}
if (String.IsNullOrEmpty(txt_Password.Text.ToString()))
{
MessageBox.Show("Введите ПАРОЛЬ клиента", "Информация", MessageBoxButton.OK, MessageBoxImage.Information);
return;
}
string str_FIO = txt_FIO.Text.ToString();
string str_LOGIN = txt_Login.Text.ToString();
string str_PASSWORD = txt_Password.Text.ToString();
if (ID_Client > 0)
{
string Sql_Command_Update_Client = "UPDATE [dbo].[Users] SET " +
"[FIO] = '" + str_FIO + "', " +
"[Password] = '" + str_PASSWORD + "' " +
"WHERE ID=" + ID_Client + "";
long rez_Update_Client = req.insert_del_update(Sql_Command_Update_Client);
if (rez_Update_Client > 0)
{
MessageBox.Show("Учетная запись клиента успешно обновлена!", "Успех", MessageBoxButton.OK, MessageBoxImage.Information);
MainWindow.SelfRefMain_frm.Fill_DGV_All_Client();
this.Close();
}
}
else
{
string sql_command = "SELECT US.ID " +
"FROM Users US " +
"WHERE " +
"(US.Login='" + str_LOGIN + "')";
int row_count = 0;
req.con.Open();
SqlCommand exeSql = new SqlCommand(sql_command, req.con);
SqlDataReader dr = exeSql.ExecuteReader();
while (dr.Read())
{
row_count++;
}
dr.Close();
req.con.Close();
if (row_count > 0)
{
MessageBox.Show("Учетная запись с таким логином уже существует! Выберите другой логин!", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Exclamation);
}
else
{
string Sql_Command_Insert_Client = "INSERT INTO [dbo].[Users] (" +
"[FIO], " +
"[Login], " +
"[Password], " +
"[ID_Role]) " +
"VALUES (" +
"'" + str_FIO + "', " +
"'" + str_LOGIN + "', " +
"'" + str_PASSWORD + "', " +
"1)";
long rez_insert_Client = req.insert_del_update(Sql_Command_Insert_Client);
if (rez_insert_Client > 0)
{
MessageBox.Show("Учетная запись клиента успешно создана!", "Успех", MessageBoxButton.OK, MessageBoxImage.Information);
MainWindow.SelfRefMain_frm.Fill_DGV_All_Client();
this.Close();
}
}
}
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
if (ID_Client > 0)
{
string sql_command = "SELECT [FIO],[Login],[Password] FROM [dbo].[Users] where ID=" + ID_Client + "";
int row_count = 0;
req.con.Open();
SqlCommand exeSql = new SqlCommand(sql_command, req.con);
SqlDataReader dr = exeSql.ExecuteReader();
while (dr.Read())
{
row_count++;
}
dr.Close();
if (row_count > 0)
{
dr = exeSql.ExecuteReader(CommandBehavior.CloseConnection);
int i = 0;
while (dr.Read())
{
txt_FIO.Text = (dr[0].ToString());
txt_Login.Text = (dr[1].ToString());
txt_Password.Text = (dr[2].ToString());
}
dr.Close();
req.con.Close();
}
dr.Close();
req.con.Close();
txt_Login.IsEnabled = false;
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace Application_Processing
{
/// <summary>
/// Логика взаимодействия для Login.xaml
/// </summary>
public partial class Login : Window
{
Request req = new Request();
public Login()
{
InitializeComponent();
}
private void btn_Cancel_Click(object sender, RoutedEventArgs e)
{
Environment.Exit(0);
}
private void btn_Login_Click(object sender, RoutedEventArgs e)
{
if (txt_Login.Text != "" &&
txt_Password.Password.ToString() != "")
{
long ID_User = checkAccount(txt_Login.Text.ToString(), txt_Password.Password.ToString());
if (ID_User > 0)
{
MainWindow mainWindow = new MainWindow();
mainWindow.ID_User = ID_User;
mainWindow.Show();
this.Close();
}
else
{
MessageBox.Show("Имя пользователя или пароль неверные! ", " Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
}
else
{
MessageBox.Show("Заполните поля логин и пароль!", "Ошибка",MessageBoxButton.OK,MessageBoxImage.Warning);
}
}
private long checkAccount(string username, string password)
{
long ID_User = 0;
string sql_command_Select_Users = "SELECT US.ID " +
"FROM Users US " +
"WHERE (" +
"(US.Login='" + username + "') AND " +
"(US.Password='" + <PASSWORD> + "'))";
int row_count = 0;
req.con.Open();
SqlCommand exeSql = new SqlCommand(sql_command_Select_Users, req.con);
SqlDataReader dr = exeSql.ExecuteReader();
while (dr.Read())
{
row_count++;
}
dr.Close();
if (row_count > 0)
{
dr = exeSql.ExecuteReader(CommandBehavior.CloseConnection);
while (dr.Read())
{
ID_User = Convert.ToInt64(dr[0].ToString());
}
dr.Close();
req.con.Close();
}
dr.Close();
req.con.Close();
return ID_User;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Drawing;
using System.Collections;
using System.Diagnostics;
using System.IO;
using System.Globalization;
using System.Security.Cryptography;
namespace Application_Processing
{
public class Request
{
//основное соединение
public SqlConnection con = new SqlConnection(@"Data Source=TTYSTOTA-ПК;Initial Catalog=BD_Application_Processing;Integrated Security=False;User ID=admin;Password=123; MultipleActiveResultSets=True");
//основное соединение
public int insert_del_update(string command)
{
SqlCommand exeSql = new SqlCommand(command, con);
exeSql.CommandType = CommandType.Text;
con.Open();
int res = (int)exeSql.ExecuteNonQuery();
con.Close();
return res;
}
public long insert_del_update_Scalar(string command)
{
SqlCommand cmd = new SqlCommand(command, con);
cmd.CommandType = CommandType.Text;
con.Open();
cmd.ExecuteNonQuery();
cmd.CommandText = "SELECT SCOPE_IDENTITY();";
long lastId = Convert.ToInt64(cmd.ExecuteScalar());
con.Close();
return lastId;
}
public DataTable Get_Data_FromDB(string sql_command)
{
con.Open();
DataTable Data_Result = new DataTable();
string sql = sql_command;
using (SqlCommand cmd = new SqlCommand(sql, this.con))
{
SqlDataReader dr = cmd.ExecuteReader();
Data_Result.Load(dr);
dr.Close();
con.Close();
}
return Data_Result;
}
}
}<file_sep>using System;
using System.Globalization;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Collections;
using System.Diagnostics;
using System.Collections.ObjectModel;
namespace Application_Processing
{
/// <summary>
/// Логика взаимодействия для MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public long ID_User = 0;
public long Role_User = 0;
public long ID_Client____ = 0;
public string FIO_Client = string.Empty;
Request req = new Request();
public DataTable _dataTable_Client_Orders = null;
public DataTable _dataTable_All_Orders = null;
public DataTable _dataTable_All_Client = null;
public DataTable _dataTable_All_Specialist = null;
public static MainWindow SelfRefMain_frm
{
get;
set;
}
public MainWindow()
{
InitializeComponent();
SelfRefMain_frm = this;
_dataTable_Client_Orders = new DataTable();
_dataTable_All_Orders = new DataTable();
_dataTable_All_Client = new DataTable();
_dataTable_All_Specialist = new DataTable();
}
private void menu_Change_User_Click(object sender, RoutedEventArgs e)
{
Login login = new Login();
login.Show();
this.Close();
}
public void Fill_DGV_Client_Orders(long ID_Client)
{
_dataTable_Client_Orders.Clear();
string sql_command_ = "SELECT " +
"[ID] as 'ID', " +
"[Type_of_request] as 'Тип заявки', " +
"[Description] as 'Комментарий', " +
"[Number_Audience] as 'Номер аудитории', " +
"[Date_Add] as 'Дата добавления', " +
"[Status] as 'Статус' " +
"FROM [dbo].[Client_Order] CL_O " +
"where CL_O.ID_Client=" + ID_Client + "";
SqlDataAdapter dataAdapter = new SqlDataAdapter(sql_command_, req.con);
dataAdapter.Fill(_dataTable_Client_Orders);
DGV_Client_Orders.ItemsSource = _dataTable_Client_Orders.DefaultView;
DGV_Client_Orders.Columns[0].Visibility = Visibility.Hidden;
_dataTable_Client_Orders.Dispose();
req.con.Close();
}
public void Fill_DGV_All_Client()
{
_dataTable_All_Client.Clear();
string sql_command_ = "SELECT " +
"[ID] as 'Уникальный номер', " +
"[FIO] as 'ФИО', " +
"[Login] as 'Логин', " +
"[Password] as '<PASSWORD>' " +
"FROM [dbo].[Users] " +
"Where ID_Role=1";
SqlDataAdapter dataAdapter2 = new SqlDataAdapter(sql_command_, req.con);
dataAdapter2.Fill(_dataTable_All_Client);
DGV_All_Client.ItemsSource = _dataTable_All_Client.DefaultView;
// DGV_All_Client.Columns[0].Visibility = Visibility.Hidden;
_dataTable_All_Client.Dispose();
req.con.Close();
}
public void Fill_DGV_All_Specialist()
{
_dataTable_All_Specialist.Clear();
string sql_command_ = "SELECT " +
"[ID] as 'Уникальный номер', " +
"[FIO] as 'ФИО', [Audience] as 'Аудитория', " +
"[Email] as 'EMAIL', " +
"[Phone] as 'Телефон' " +
"FROM [dbo].[Specialist]";
SqlDataAdapter dataAdapter3 = new SqlDataAdapter(sql_command_, req.con);
dataAdapter3.Fill(_dataTable_All_Specialist);
DGV_All_Specialist.ItemsSource = _dataTable_All_Specialist.DefaultView;
_dataTable_All_Specialist.Dispose();
req.con.Close();
}
public void Fill_DGV_All_Orders()
{
//_dataTable_All_Orders.Clear();
//string sql_command_ = "";
//SqlDataAdapter dataAdapter3 = new SqlDataAdapter(sql_command_, req.con);
//dataAdapter3.Fill(_dataTable_All_Orders);
//DGV_All_Orders.ItemsSource = _dataTable_All_Orders.DefaultView;
//_dataTable_All_Orders.Dispose();
//req.con.Close();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
string sql_command = "SELECT US.ID_Role FROM [dbo].[Users] US where US.ID=" + ID_User + "";
int row_count = 0;
req.con.Open();
SqlCommand exeSql = new SqlCommand(sql_command, req.con);
SqlDataReader dr = exeSql.ExecuteReader();
while (dr.Read())
{
row_count++;
}
dr.Close();
if (row_count > 0)
{
dr = exeSql.ExecuteReader(CommandBehavior.CloseConnection);
while (dr.Read())
{
Role_User = Convert.ToInt64(dr[0].ToString());
}
dr.Close();
req.con.Close();
}
dr.Close();
req.con.Close();
switch (Role_User.ToString())
{
case "1":
TAB1.Items.Remove(TAB1_Orders);
TAB1.Items.Remove(TAB1_Clients);
TAB1.Items.Remove(TAB1_Specialists);
string sql_command2 = "SELECT " +
"[ID], " +
"[FIO] " +
"FROM [dbo].[Users] " +
"where (ID=" + ID_User + ")";
int row_count2 = 0;
req.con.Open();
SqlCommand exeSql2 = new SqlCommand(sql_command2, req.con);
SqlDataReader dr2 = exeSql2.ExecuteReader();
while (dr2.Read())
{
row_count2++;
}
dr2.Close();
if (row_count2 > 0)
{
dr2 = exeSql2.ExecuteReader(CommandBehavior.CloseConnection);
while (dr2.Read())
{
ID_Client____ = Convert.ToInt64(dr2[0].ToString());
FIO_Client = dr2[1].ToString();
}
dr2.Close();
req.con.Close();
}
dr2.Close();
req.con.Close();
label_Hello.Content = "Здравствуйте, " + FIO_Client + "";
Fill_DGV_Client_Orders(ID_Client____);
break;
case "2":
TAB1.Items.Remove(TAB1_Client_Orders);
label_Hello.Content = "Здравствуйте, Admin";
Fill_DGV_All_Client();
Fill_DGV_All_Specialist();
Fill_DGV_All_Orders();
break;
}
}
private void menu_Exit_Click(object sender, RoutedEventArgs e)
{
Environment.Exit(0);
}
private void btn_Edit_Order_Click(object sender, RoutedEventArgs e)
{
btn_Edit_Order.IsEnabled = false;
btn_Delete_Order.IsEnabled = false;
DGV_Client_Orders.UnselectAllCells();
}
private void btn_Delete_Order_Click(object sender, RoutedEventArgs e)
{
btn_Edit_Order.IsEnabled = false;
btn_Delete_Order.IsEnabled = false;
DGV_Client_Orders.UnselectAllCells();
// const string message =
//"Вы действительно хотите удалить выбранную заявку? После удаления ее невозможно будет восстановить. Подтвердить удаление?";
// const string caption = "Удаление";
// var result = MessageBox.Show(message, caption,
// MessageBoxButton.YesNo,
// MessageBoxImage.Question);
// if (result == MessageBoxResult.Yes)
// {
// string sql_delete = "DELETE FROM [dbo].[Users] WHERE Users.ID=" + ID_Worker + "";
// int res = req.insert_del_update(sql_delete);
// if (res > 0)
// {
// MessageBox.Show("Обліковий запис успішно видалений!", "Успіх!", MessageBoxButtons.OK, MessageBoxIcon.Information);
// }
// }
// this.Add_new_Client_Load(sender, e);
}
private void btn_Add_Order_Click(object sender, RoutedEventArgs e)
{
Edit_Order edit_Order = new Edit_Order();
edit_Order.ID_Client = this.ID_Client____;
edit_Order.Show();
}
private void btn_Add_Client_Click(object sender, RoutedEventArgs e)
{
Edit_Client edit_Client = new Edit_Client();
edit_Client.Show();
}
private void btn_Edit_Client_Click(object sender, RoutedEventArgs e)
{
DataRowView rowView = DGV_All_Client.SelectedValue as DataRowView;
if (DGV_All_Client.SelectedItem != null)
{
Edit_Client edit_Client = new Edit_Client();
edit_Client.ID_Client = Convert.ToInt64(rowView[0].ToString());
edit_Client.Show();
}
}
private void btn_Delete_Client_Click(object sender, RoutedEventArgs e)
{
DataRowView rowView = DGV_All_Client.SelectedValue as DataRowView;
long ID_CLient_Del= Convert.ToInt64(rowView[0].ToString());
if (DGV_All_Client.SelectedItem != null)
{
const string message =
"Вы действительно хотите удалить выбранного клиента? После удаления его невозможно будет восстановить. Прежде чем удалить клиента - удалите все его заявки. Подтвердить удаление?";
const string caption = "Удаление";
var result = MessageBox.Show(message, caption,
MessageBoxButton.YesNo,
MessageBoxImage.Question);
if (result == MessageBoxResult.Yes)
{
string sql_command = "SELECT [ID] FROM [dbo].[Client_Order] where (Client_Order.ID_Client=" + ID_CLient_Del + ")";
int row_count = 0;
req.con.Open();
SqlCommand exeSql = new SqlCommand(sql_command, req.con);
SqlDataReader dr = exeSql.ExecuteReader();
while (dr.Read())
{
row_count++;
}
dr.Close();
req.con.Close();
if (row_count > 0)
{
MessageBox.Show("Невозможно удалить клиента. У клиента есть заявки. Для того, чтобы удалить клиента удалите заявки клиента и повторите попытку!", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Exclamation);
}
else
{
string sql_delete = "DELETE FROM [dbo].[Users] WHERE Users.ID=" + ID_CLient_Del + "";
int res = req.insert_del_update(sql_delete);
if (res > 0)
{
MessageBox.Show("Клиент успешно удален!", "Успех!", MessageBoxButton.OK, MessageBoxImage.Information);
Fill_DGV_All_Client();
}
}
}
}
}
private void DGV_All_Client_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (DGV_All_Client.SelectedIndex > -1)
{
btn_Edit_Client.IsEnabled = true;
btn_Delete_Client.IsEnabled = true;
}
else
{
btn_Edit_Client.IsEnabled = false;
btn_Delete_Client.IsEnabled = false;
}
}
private void btn_Add_Specialist_Click(object sender, RoutedEventArgs e)
{
Edit_Specialist edit_Specialist = new Edit_Specialist();
edit_Specialist.Show();
}
private void DGV_All_Specialist_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (DGV_All_Specialist.SelectedIndex > -1)
{
btn_Edit_Specialist.IsEnabled = true;
btn_Delete_Specialist.IsEnabled = true;
}
else
{
btn_Edit_Specialist.IsEnabled = false;
btn_Delete_Specialist.IsEnabled = false;
}
}
private void btn_Edit_Specialist_Click(object sender, RoutedEventArgs e)
{
DataRowView rowView = DGV_All_Specialist.SelectedValue as DataRowView;
if (DGV_All_Specialist.SelectedItem != null)
{
Edit_Specialist edit_Specialist = new Edit_Specialist();
edit_Specialist.ID_Specialist = Convert.ToInt64(rowView[0].ToString());
edit_Specialist.Show();
}
}
private void btn_Delete_Specialist_Click(object sender, RoutedEventArgs e)
{
DataRowView rowView = DGV_All_Specialist.SelectedValue as DataRowView;
long ID_Specialist_Del = Convert.ToInt64(rowView[0].ToString());
if (DGV_All_Specialist.SelectedItem != null)
{
const string message =
"Вы действительно хотите удалить выбранного специалиста? После удаления его невозможно будет восстановить. Прежде чем удалить специалиста - удалите все его талоны,в которых он числиться. Подтвердить удаление?";
const string caption = "Удаление";
var result = MessageBox.Show(message, caption,
MessageBoxButton.YesNo,
MessageBoxImage.Question);
if (result == MessageBoxResult.Yes)
{
string sql_command = "SELECT [ID] FROM [dbo].[Ticket_of_order] where (Ticket_of_order.ID_Specialist=" + ID_Specialist_Del + ")";
int row_count = 0;
req.con.Open();
SqlCommand exeSql = new SqlCommand(sql_command, req.con);
SqlDataReader dr = exeSql.ExecuteReader();
while (dr.Read())
{
row_count++;
}
dr.Close();
req.con.Close();
if (row_count > 0)
{
MessageBox.Show("Невозможно удалить специалиста. Специалист имеет талоны в работе. Для того, чтобы удалить специалиста, удалите талоны специалиста и повторите попытку!", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Exclamation);
}
else
{
string sql_delete = "DELETE FROM [dbo].[Specialist] WHERE Specialist.ID=" + ID_Specialist_Del + "";
int res = req.insert_del_update(sql_delete);
if (res > 0)
{
MessageBox.Show("Специалист успешно удален!", "Успех!", MessageBoxButton.OK, MessageBoxImage.Information);
Fill_DGV_All_Specialist();
}
}
}
}
}
}
}<file_sep>using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace AP_test
{
[TestClass]
public class AP_test
{
[TestMethod]
public void TestMethod1()
{
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Text.RegularExpressions;
using System.Data.SqlClient;
using System.Data;
namespace Application_Processing
{
/// <summary>
/// Логика взаимодействия для Edit_Specialist.xaml
/// </summary>
public partial class Edit_Specialist : Window
{
Request req = new Request();
public long ID_Specialist = 0;
public Edit_Specialist()
{
InitializeComponent();
}
private void btn_Cancel_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
private void btn_Add_Click(object sender, RoutedEventArgs e)
{
if (String.IsNullOrEmpty(txt_FIO.Text.ToString()))
{
MessageBox.Show("Введите ФИО специалиста", "Информация", MessageBoxButton.OK, MessageBoxImage.Information);
return;
}
if (String.IsNullOrEmpty(txt_Audience.Text.ToString()))
{
MessageBox.Show("Введите АУДИТОРЮ специалиста!", "Информация", MessageBoxButton.OK, MessageBoxImage.Information);
return;
}
if (txt_Email.Text.Length == 0)
{
txt_Email.Focus();
return;
}
else if (!Regex.IsMatch(txt_Email.Text, @"^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$"))
{
MessageBox.Show("Email адрес специалиста неверный. Введите валидный Email!", "Информация", MessageBoxButton.OK, MessageBoxImage.Information);
txt_Email.Select(0, txt_Email.Text.Length);
txt_Email.Focus();
return;
}
if (String.IsNullOrEmpty(txt_Phone.Text.ToString()))
{
MessageBox.Show("Введите ТЕЛЕФОН специалиста!", "Информация", MessageBoxButton.OK, MessageBoxImage.Information);
return;
}
string str_FIO = txt_FIO.Text.ToString();
string str_AUDIENCE = txt_Audience.Text.ToString();
string str_EMAIL = txt_Email.Text.ToString();
string str_PHONE = txt_Phone.Text.ToString();
if (ID_Specialist > 0)
{
string Sql_Command_Update_Specialist = "UPDATE [dbo].[Specialist] SET " +
"[FIO] = '" + str_FIO + "', " +
"[Audience] = '" + str_AUDIENCE + "', " +
"[Email] = '" + str_EMAIL + "', " +
"[Phone] = '" + str_PHONE + "' " +
"WHERE ID=" + ID_Specialist + "";
long rez_Update_Specialist = req.insert_del_update(Sql_Command_Update_Specialist);
if (rez_Update_Specialist > 0)
{
MessageBox.Show("Данные о специалисте успешно обновлены!", "Успех", MessageBoxButton.OK, MessageBoxImage.Information);
MainWindow.SelfRefMain_frm.Fill_DGV_All_Specialist();
this.Close();
}
}
else
{
string Sql_Command_Insert_Specialist = "INSERT INTO [dbo].[Specialist] (" +
"[FIO], " +
"[Audience], " +
"[Email], [" +
"Phone]) " +
"VALUES (" +
"'" + str_FIO + "', " +
"'" + str_AUDIENCE + "', " +
"'" + str_EMAIL + "', " +
"'" + str_PHONE + "')";
long rez_insert_Specialist = req.insert_del_update(Sql_Command_Insert_Specialist);
if (rez_insert_Specialist > 0)
{
MessageBox.Show("Специалист успешно создан!", "Успех", MessageBoxButton.OK, MessageBoxImage.Information);
MainWindow.SelfRefMain_frm.Fill_DGV_All_Specialist();
this.Close();
}
}
}
private void txt_Phone_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
Regex regex = new Regex("[^0-9]+");
e.Handled = regex.IsMatch(e.Text);
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
if (ID_Specialist > 0)
{
string sql_command = "SELECT " +
"[FIO], " +
"[Audience], " +
"[Email], " +
"[Phone] " +
"FROM " +
"[dbo].[Specialist] " +
"where ID="+ID_Specialist+"";
int row_count = 0;
req.con.Open();
SqlCommand exeSql = new SqlCommand(sql_command, req.con);
SqlDataReader dr = exeSql.ExecuteReader();
while (dr.Read())
{
row_count++;
}
dr.Close();
if (row_count > 0)
{
dr = exeSql.ExecuteReader(CommandBehavior.CloseConnection);
int i = 0;
while (dr.Read())
{
txt_FIO.Text = (dr[0].ToString());
txt_Audience.Text = (dr[1].ToString());
txt_Email.Text = (dr[2].ToString());
txt_Phone.Text = (dr[3].ToString());
}
dr.Close();
req.con.Close();
}
dr.Close();
req.con.Close();
}
}
}
}
|
233472270a7f4ded4eb2c1bb19762eed5554aaeb
|
[
"C#"
] | 7 |
C#
|
ttystota/Application-Processing
|
4df793a23377a35b768e73e34a7d51ed2fd4910e
|
540dc4fc8b8bd53f324fce65091f437883d41eea
|
refs/heads/main
|
<repo_name>faiber1986/covid19_web<file_sep>/src/components/Covid.jsx
import axios from 'axios'
import moment from 'moment';
import React, { useEffect, useState } from 'react'
export const Covid = () => {
const [title, setTitle] = useState('Global');
const [dataDate, setDataDate] = useState('');
const [stats, setStats] = useState({});
const [countries, setCountries] = useState([]);
const [select, setSelect] = useState(0);
const [loading, setLoading] = useState('');
useEffect(() => {
getDataCovid();
}, []);
const getDataCovid = async() => {
try {
setLoading(true);
const {data} = await axios.get('https://api.covid19api.com/summary');
setLoading(false);
setTitle('Global')
setSelect(0);
setDataDate(moment(data.Date).format('MMMM Do YYYY, h:mm:ss a'))
setStats(data.Global)
setCountries(data.Countries)
} catch (error) {
console.log('error en getDataCovid', error.message)
}
};
const onChange = (e) => {
setSelect(e.target.value)
const country = countries.find(item => item.ID === e.target.value)
setStats(country)
setTitle(country.Country)
};
const numberWithCommas = (x) => {
if (typeof x !== 'undefined'){return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
};
};
return (
<div>
<header className='text-center text-white bg-dark p-4 mb-5 col-xxl-12'>
<div className='fw-bold fs-1'>
<i className='fa fa-biohazard m-2'></i>
COVID-19 TRACKER
</div>
<p>
API by
{' '}
<a href="https://api.covid19api.com" target = '_blank' rel = 'noreferrer' className='text-white'>
Covid19api.com
</a>
</p>
</header>
{loading?
<div class="d-grid gap-2">
<button className="btn btn-dark mx-auto" type="button" disabled>
<span className="spinner-grow spinner-grow-sm" role="status" aria-hidden="true"></span>
Loading...
</button>
</div>:
<div className="container">
<div className="text-center">
<h2 className='fw-bold'>{title}</h2>
<div className="my-4">{dataDate}</div>
</div>
<div className="row g-4 mb-5">
{/* box-1 */}
<div className="col-md-4">
<div className="card text-center p-5 bg-secondary">
<h3 className='fw-bold mb-4 text-white'>* CASOS *</h3>
<div className="mb-4 fs-4">
<span className='fw-bold'>Nuevos : </span>
{numberWithCommas(stats.NewConfirmed)}
</div>
<div className="mb-4 fs-4">
<span className='fw-bold'>Totales : </span>
{numberWithCommas(stats.TotalConfirmed)}
</div>
</div>
</div>
{/* box-2 */}
<div className="col-md-4">
<div className="card text-center p-5 bg-danger">
<h3 className='fw-bold mb-4 text-white'>* MUERTOS *</h3>
<div className="mb-4 fs-4">
<span className='fw-bold'>Nuevos : </span>
{numberWithCommas(stats.NewDeaths)}
</div>
<div className="mb-4 fs-4">
<span className='fw-bold'>Totales : </span>
{numberWithCommas(stats.TotalDeaths)}
</div>
</div>
</div>
{/* box-3 */}
<div className="col-md-4">
<div className="card text-center p-5 bg-primary">
<h3 className='fw-bold mb-4 text-white'>* RECUPERADOS *</h3>
<div className="mb-4 fs-4">
<span className='fw-bold'>Nuevos : </span>
{numberWithCommas(stats.NewRecovered)}
</div>
<div className="mb-4 fs-4">
<span className='fw-bold'>Totales : </span>
{numberWithCommas(stats.TotalRecovered)}
</div>
</div>
</div>
</div>
<div className="row g-4 mb-4">
{/* box-1 */}
<div className="col-md-12">
<div className="card text-center p-5 bg-warning">
<h3 className='fw-bold mb-4'>* TASAS *</h3>
<div className="mb-4 fs-4">
<span className='fw-bold'>Mortalidad : </span>
{Math.round(stats.TotalDeaths/stats.TotalConfirmed*10000)/100} {'%'}
</div>
<div className="mb-4 fs-4">
<span className='fw-bold'>Recuperación : </span>
{Math.round(stats.TotalRecovered/stats.TotalConfirmed*10000)/100} {'%'}
</div>
</div>
</div>
</div>
<select className="my-3 col-12 py-3 border bg-dark text-white" value={select} placeholder='Seleccione el país' onChange = {e => onChange(e)}>
<option hidden selected>
Seleccione el país
</option>
{
countries.map(item => (
<option key={item.ID} value={item.ID}>
{item.Country}
</option>
))
}
</select>
{stats.Country && (
<div class="d-grid gap-2 col-6 mx-auto mb-4">
<button className='btn btn-dark mx-auto' onClick = {() => getDataCovid()}>
Global
</button>
</div>
)}
</div>
}
</div>
)
}
|
390a0d551b9bc2575402fe6459e4e91bf24b0790
|
[
"JavaScript"
] | 1 |
JavaScript
|
faiber1986/covid19_web
|
40c6ea53799eb520d6f0c5ec10b159f4b705d934
|
4e17949250b450d039e1f6e627eed0ab08a47823
|
refs/heads/master
|
<repo_name>BrisingrGaunt/Projecte_final<file_sep>/M7/projecte_kevin/application/controllers/Client.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Client extends CI_Controller {
public function index()
{
$info=$this->session->flashdata('informacio');
$data['info_client']=$info;
$this->load->view('client',$data);
}
}
<file_sep>/M6/script.js
window.addEventListener('load', function () {
inputs = document.getElementsByClassName('inputMajus');
for (let i = 0; i < inputs.length; i++) {
inputs[i].addEventListener('keyup', comprovarMajuscula);
inputs[i].addEventListener('keyup', comprovarSeguretat);
}
//pestanyes del formulari
let opcions_acces = document.getElementsByClassName("opcions");
for (let i = 0; i < opcions_acces.length; i++) {
opcions_acces[i].addEventListener('click', canviarAmbit);
}
//es mostra per defecte sempre el formulari de login de l'usuari
document.getElementById('home-tab').addEventListener('click', function () {
login_usuari.style.display = 'block';
});
let botons = document.getElementsByClassName('btnRegister');
for (let i = 0; i < botons.length; i++) {
botons[i].addEventListener('click', validarCamps);
}
document.getElementById('profile-tab').addEventListener('click', function () {
login_empresa.style.display = 'block';
});
checks = document.getElementsByName("mostrarPass");
for (let i = 0; i < checks.length; i++) {
checks[i].addEventListener('click', mostrarContrasenya);
}
//Petició AJAX amb la que obtenim un llistat de municipis de Catalunya
let ruta = 'https://api.idescat.cat/emex/v1/nodes.json?tipus=mun';
let peticio = $.post(ruta);
peticio.done(exit);
peticio.fail(fracas);
tabs = document.getElementsByClassName("opcio_inici");
for (let i = 0; i < tabs.length; i++) {
tabs[i].addEventListener('click', obrirPestanya);
}
barres = document.getElementsByTagName('progress');
for (let i = 0; i < barres.length; i++) {
barres[i].value = 0;
}
});
function canviarAmbit() {
let opcions = document.getElementsByClassName("opcio_inici");
let tipusAcces = this.innerHTML.toLowerCase();
opcions[0].href = "#login_" + tipusAcces;
opcions[1].href = "#registre_" + tipusAcces;
}
function validarCamps() {
//Ens quedem amb el formulari al qual pertany el botó que ha sigut clicat
let form;
if (this.name == "registre_emp") {
form = this.parentElement.parentElement.parentElement.parentElement.parentElement;
} else {
form = this.parentElement.parentElement.parentElement;
}
//El nom del formulari ens indicarà el tipus de validació que aplicarem:
// Valors:
// 0 - Login (només es comprovarà que els inputs no siguin buits)
// 1 - Registre d'usuari (es comprova llargades, seguretat de password, i email correcte)
// 2 - Registre d'empresa (es comprova llargades, seguretat de password, email correcte i la resta de dades del formulari)
let validacions = [[/\w{6,}/], [/\w{6,}/, /^[\w\.]{6,}@\w{4,}\.[a-z]{2,5}$/], [/\w{6,}/, /^[\w\.]{6,}@\w{4,}\.[a-z]{2,5}$/, /\w{6,}/, /^((?!Tipus via).)*$/, /\w{6,}/, /^\d{1,}$/, /^((?!Població).)*$/]];
let errors_text = ['Camp usuari', "Camp email", "Camp nom", "Camp tipusVia", "Camp direccio", "Camp num", "Camp comarca", 'Contrasenya: mínim 8 caràcters, 1 núm, 1 majus, 1 minus i 1 símbol'];
let elements_form = form.elements;
let valid = true;
let index = 0;
let errors = [];
for (let i = 0; i < elements_form.length; i++) {
if (elements_form[i].type != 'button' && elements_form[i].type != 'checkbox' && elements_form[i].type != "hidden") {
if (elements_form[i].type == "password") {
//si existeix la barra de progrés
let pass_correcte = true;
if (typeof form.getElementsByTagName('progress')[0] != "undefined") {
form.getElementsByTagName('progress')[0].value == 5 ? pass_correcte = pass_correcte : pass_correcte = false;
} else {
//si no existeix barra de progrés només es comprova que el camp no vingui buit ja que la contrasenya que
//s'entra ha de ser vàlida (ja que ha passat previament pel formulari de registre)
elements_form[i].value.length > 6 ? pass_correcte = pass_correcte : pass_correcte = false;
}
if (pass_correcte == false) {
valid = false;
errors.push(7);
}
} else {
if (validacions[form.name][index].test(elements_form[i].value) == false) {
valid = false;
errors.push(index);
}
index++;
}
}
}
if (valid) {
form.submit();
} else {
let cadena = "Revisa els següents camps:<br>"
for (let i = 0; i < errors.length; i++) {
//es recorren tots els errors
cadena += "- " + errors_text[errors[i]] + "<br>";
}
info.innerHTML = cadena;
}
}
let tabs;
let barres;
let inputs;
let checks;
function obrirPestanya(evt) {
for (let i = 0; i < inputs.length; i++) {
inputs[i].value = "";
}
for (let i = 0; i < barres.length; i++) {
barres[i].value = 0;
}
let id = evt.currentTarget.href.split("#")[1];
let opcions = document.getElementsByClassName("content");
for (let i = 0; i < opcions.length; i++) {
opcions[i].style.display = 'none';
}
for (let i = 0; i < tabs.length; i++) {
tabs[i].className = tabs[i].className.replace("active", "");
}
document.getElementById(id).style.display = "block";
evt.currentTarget.className += " active";
}
function exit(dades) {
let cadena = "<option class='hidden' selected disabled>Població</option>";
for (let i = 0; i < dades.fitxes.v.length; i++) {
cadena += "<option value='" + dades.fitxes.v[i].content + "'>" + dades.fitxes.v[i].content + "</option>";
}
comarca.innerHTML = cadena;
}
function fracas() {
console.info("Error al carregar el desplegable de comarques");
}
let pass = "";
function comprovarMajuscula(ev) {
if (ev.getModifierState("CapsLock") == true) {
console.info("Majúscules activades");
info.innerHTML = "Majúscules activades";
} else {
console.info("Majúscules desactivades");
info.innerHTML = "";
}
}
function comprovarSeguretat() {
pass = this.value;
let expressions = [/\d/, /[A-Z]/, /[a-z]/, /(?=.*[@$!%*+_\-?&])/];
let robustesa = 0;
if (pass.length > 8) robustesa++;
for (let i = 0; i < expressions.length; i++) {
robustesa += comprovarPattern(expressions[i]);
}
for (let i = 0; i < barres.length; i++) {
barres[i].value = robustesa;
}
}
function desarCredencials() {
let qt_storage = localStorage.getItem('qt_usuaris');
qt_storage++;
localStorage.setItem('username_' + qt_storage, pass);
localStorage.setItem('pass_' + qt_storage, pass);
localStorage.setItem('qt_usuaris', qt_storage);
}
function comprovarPattern(pattern) {
if (pass.match(pattern)) {
return 1;
}
return 0;
}
function mostrarContrasenya() {
let contrasenya = document.getElementsByClassName('inputMajus');
for (let i = 0; i < contrasenya.length; i++) {
if (this.checked) {
contrasenya[i].setAttribute("type", "text");
} else {
contrasenya[i].setAttribute("type", "password");
}
}
}
<file_sep>/M7/projecte_kevin/application/views/inscripcions.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
include 'items.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Inscripcions</title>
<meta name="viewport" content="width=device-width">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link rel="stylesheet" href="<?php echo base_url();?>/css/estilo.css">
<link rel="stylesheet" href="<?php echo base_url();?>/css/base.css">
</head>
<body>
<header>
<?php echo $barra_client;?>
</header>
<main class="container-fluid">
<div class="row">
<div class="col-md-3 col-12 order-2 order-md-1">
<?php echo $esquerra;?>
</div>
<div class="col-md-9 col-12 order-1 order-md-2">
<h1>Totes les cates</h1>
<?php
$i=0;
$qt=0;
echo "<div class='row'>";
for($j=0;$j<sizeof($cates);$j++){
$trobat=false;
if($i==2){
echo "</div><br><div class='row'>";
$i=0;
}
if(isset($filtre)){
while($j!=sizeof($cates) && gettype(array_search($cates[$j]['id'], explode(":",$participacions['cates'])))!="integer"){
$j++;
}
if($j!=sizeof($cates)){
//hi ha alguna coincidència
$trobat=true;
}
}
if(isset($filtre) && $trobat==true || !isset($filtre)){
$qt++;
//només es mostran les cates en cas que sigui el general o que sigui per usuari i hi hagen coincidències
?>
<div class="col-md-1 col-1"></div>
<div class="cata col-md-4 col-10 nota">
<i class="pin"></i>
<h2><?php echo $cates[$j]['nom'];?></h2>
<p class="descripcio">"<?php echo $cates[$j]['descripcio'];?>"</p>
<p><b>On?</b> <?php echo $cates[$j]['tipusVia']." ".$cates[$j]['direccio'].", ".$cates[$j]['numDireccio']." (".$cates[$j]['comarca'].")";?></p>
<p><b>Quan?</b> <?php $newDate = date("d/m/Y H:i", strtotime($cates[$j]['data'])); echo $newDate;?></p>
<p><?php
if($cates[$j]['estat']==0){
$estat="Oberta";
}
else{
$estat="Tancada";
}
echo "<b>Estat: </b>".$estat;?></p>
<p class="peu">
<?php
echo "<a href='";
if($cates[$j]['estat']==1 && gettype(array_search($cates[$j]['id'],explode(":",$participacions['cates'])))=="integer"){
//si la cata està finalitzada i l'usuari ha participat
echo site_url('Cliente/valora/?id='.$cates[$j]['id'])."'>Valorar cata</a>";
}
else if($cates[$j]['estat']==1 && array_search($cates[$j]['id'],explode(":",$participacions['cates']))==false){
//si la cata està tancada i l'usuari NO ha participat
echo site_url('Cliente')."'></a>";
}
else if($cates[$j]['estat']==0 && gettype(array_search($cates[$j]['id'],explode(":",$participacions['cates'])))=="integer"){
//últim cas contemplat en el que l'usuari està registrat a una cata oberta i es pot desapuntar
echo site_url('Cliente/gestio_inscripcio/?id='.$cates[$j]['id'].'&accio=desapuntar')."'>Desapuntar-se</a>";
}
else{
//cata oberta usari NO apuntat
echo site_url('Cliente/gestio_inscripcio/?id='.$cates[$j]['id'].'&accio=apuntar')."'>Apuntar-se</a>";
}
?>
</p>
</div>
<div class="col-md-1 col-1"></div>
<?php
$i++;
}
}
if($qt==0){
echo "<h2>Encara no estàs apuntat a cap cata.</h2>";
}
echo " </div>";
?>
</div>
</div>
</main>
<!-- Footer -->
<footer class="page-footer font-small">
<!-- Copyright -->
<div class="footer-copyright text-center">© 2019 Copyright --
BrisingrGaunt Productions
</div>
<!-- Copyright -->
</footer>
<!-- Footer -->
</body>
</html>
<file_sep>/M7/projecte_kevin/application/views/producte.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
include 'items.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Empresa</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="<?php echo base_url();?>/js/script_prod.js"></script>
<link href='https://fonts.googleapis.com/css?family=Cabin+Condensed:700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="<?php echo base_url();?>/css/estil.css">
<link rel="stylesheet" href="<?php echo base_url();?>/css/estilo.css">
<link rel="stylesheet" href="<?php echo base_url();?>/css/base.css">
</head>
<body>
<header>
<?php echo $barra_empresa;?>
</header>
<main class="container-fluid">
<div class="row">
<div class="col-md-3 col-12 order-2 order-md-1">
<?php echo $esquerra;?>
</div>
<div class="col-md-9 order-md-2 order-1">
<div class="row">
<div class="col-md-2 d-none d-sm-block"></div>
<div class="col-md-8 col-12">
<h1>Amplia la teva selecció de productes...</h1>
</div>
<div class="col-md-2 d-none d-sm-block"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8">
<form method="post" action="<?php echo site_url('Empresa/pujar_producte');?>">
<input type="hidden" name="empresa" value="<?php echo $info_empresa['id']?>" />
<div class="form-group">
<label for="nom_producte">Producte *</label>
<input type="text" class="form-control" name="nom" id="nom_producte" placeholder="Nom" value="" />
</div>
<div class="form-group">
<label for="descripcio_producte">Descripció *</label>
<textarea class="form-control" name="descripcio" id="descripcio_producte" rows="3" placeholder="Descripció del producte"></textarea>
</div>
<div class="row">
<div class="col-md-1 d-sm-block d-none"></div>
<div class="col-md-5 col-12"><input type="button" id="afegirProd" class="btnRegister" value="Afegir producte" /></div>
<div class="col-md-5 col-12">
<input type="submit" id="carregaMassiva" name="xml" class="btnRegister" value="Realitzar carrega XML" /></div>
<div class="col-md-1 d-sm-block d-none"></div>
</div>
</form>
</div>
<div class="col-md-2"></div>
</div>
</div>
</div>
</main> <!-- Footer -->
<footer class="page-footer font-small">
<!-- Copyright -->
<div class="footer-copyright text-center">© 2019 Copyright --
BrisingrGaunt Productions
</div>
<!-- Copyright -->
</footer>
<!-- Footer -->
</body>
</html>
<file_sep>/M8/doxygen_java_m3/html/search/functions_4.js
var searchData=
[
['login',['Login',['../class_login_1_1_login.html#a685e9c305b50efcb21f02403e88a9878',1,'Login::Login']]]
];
<file_sep>/M8/doxygen_java_m3/html/search/all_4.js
var searchData=
[
['login',['Login',['../class_login_1_1_login.html',1,'Login.Login'],['../class_login_1_1_login.html#a685e9c305b50efcb21f02403e88a9878',1,'Login.Login.Login()']]]
];
<file_sep>/M7/projecte_kevin/application/views/carrega_massiva.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
include 'items.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Afegir productes per XML</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link href='https://fonts.googleapis.com/css?family=Cabin+Condensed:700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="<?php echo base_url();?>/css/estil.css">
<link rel="stylesheet" href="<?php echo base_url();?>/css/estilo.css">
<link rel="stylesheet" href="<?php echo base_url();?>/css/base.css">
</head>
<body>
<header>
<?php echo $barra_empresa;?>
</header>
<main class="container-fluid">
<div class="row">
<div class="col-md-3 col-12 order-2 order-md-1">
<?php echo $esquerra;?>
</div>
<div class="col-md-9 principal order-md-2 order-1">
<div class="row">
<div class="col-md-2 col-1"></div>
<div class="col-md-8 col-10">
<h1>Càrrega de productes per XML</h1>
</div>
<div class="col-md-2 col-1"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8">
<p>L'XML que has de pujar ha de seguir el següent esquema: </p>
<div class="row">
<div class="col-md-3 col-1"></div>
<div class="col-md-6 col-10">
<img src="<?php echo base_url();?>/pics/exemple_xml.png">
</div>
<div class="col-md-3 col-1"></div>
</div>
<p>Consulta amb l'administrador quin es l'identificador de la teva empresa</p>
<form method="post" action="<?php echo site_url('Empresa/carregaXML');?>" enctype="multipart/form-data">
<input type="hidden" name="empresa" value="<?php echo $info_empresa['id']?>" />
<div class="form-group">
<label for="file_xml">Fitxer XML</label>
<input type="file" class="form-control" name="xml" id="file_xml" />
</div>
<div class="row">
<div class="col-md-3 col-1"></div>
<div class="col-md-6 col-10">
<input type="submit" id="carregaMassiva" name="xml" class="btnRegister" value="Pujar arxiu" />
</div>
<div class="col-md-3 col-1"></div>
</div>
</form>
</div>
<div class="col-md-2"></div>
</div>
</div>
</div>
</main>
<footer class="page-footer font-small">
<!-- Copyright -->
<div class="footer-copyright text-center">© 2019 Copyright --
BrisingrGaunt Productions
</div>
<!-- Copyright -->
</footer>
</body>
</html>
<file_sep>/M7/projecte_kevin/js/script_valoracio.js
window.addEventListener('load', function () {
spans = document.getElementsByClassName('estrella');
primer_cop = true;
if (primer_cop == true) {
//&& document.getElementById('hidden_valoracio').value!=0
console.info(document.getElementById('hidden_valoracio').value);
canvi_color();
}
for (let i = 0; i < spans.length; i++) {
spans[i].addEventListener('mouseenter', canvi_color);
spans[i].addEventListener('mouseout', desmarcar);
spans[i].addEventListener('click', seleccionar_valor);
}
});
let primer_cop;
let spans;
function desmarcar() {
for (let i = 0; i < spans.length; i++) {
spans[i].style.color = 'black';
}
}
function canvi_color() {
let maxim;
if (primer_cop) {
maxim = document.getElementById('hidden_valoracio').value;
primer_cop = false;
} else {
maxim = this.getAttribute('name');
}
console.info("estas entrant " + maxim);
for (let i = 0; i < maxim; i++) {
spans[i].style.color = 'orange';
}
}
function seleccionar_valor() {
let maxim = this.getAttribute('name');
console.info(maxim);
for (let i = 0; i < spans.length; i++) {
spans[i].style.color = 'black';
if (i < maxim) {
spans[i].style.color = 'orange';
}
spans[i].removeEventListener('mouseenter', canvi_color);
spans[i].removeEventListener('mouseout', desmarcar);
}
document.getElementById('hidden_valoracio').value = maxim;
}
<file_sep>/M8/doxygen_java_m3/html/search/functions_0.js
var searchData=
[
['afegir_5fmodificar',['Afegir_Modificar',['../class_gestio_empreses_1_1_afegir___modificar.html#a5a9fe23eba7323eb0068cf645ab9db2e',1,'GestioEmpreses::Afegir_Modificar']]]
];
<file_sep>/Gestio_empreses/src/GestioEmpreses/Afegir_Modificar.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package GestioEmpreses;
import Connexio.Connexio;
import static Login.Login.neteja;
import GestioEmpreses.Gestio;
import static GestioEmpreses.Gestio.crear_missatge;
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
/**
*
* @author Kevin
* @brief Clase Afegir_Modificar on s'implementen les funcions d'afegir o editar depenent de com ha siguit cridat en la clase Gestio
*/
public class Afegir_Modificar {
static JFrame fAccio = null;
static JPanel pTop = new JPanel();
static JPanel pCenter = new JPanel();
static JPanel pBottom = new JPanel();
static int id_empresa;
static LayoutManager l=new GridLayout(8,2);
static JButton btnAccio=new JButton();
static JComboBox selVia=new JComboBox<>(new String[]{"Via","Carrer","Avinguda"});
static String [] valorsLabel={"Nom","Tipus via","Adreça","Número","Població","Correu electrònic","Usuari","Contrasenya"};
static JTextField filtres[]=new JTextField[valorsLabel.length-1];
/**
* Constructor de la clase Afegir_Modificar
* @param empresa si el valor és diferent a 0 entra en mode 'Editar' en cas contrari, el mètode es 'Afegir'
*/
public Afegir_Modificar(int empresa) {
crear_interficie(empresa);
set_escoltador();
}
/**
* Mètode que crea l'interficie gràfica de la clase Afegir_Modificar
* @param empresa si té valor 0 els camps seràn buits sinó, seran plens amb l'informació obtinguda a la BDD a través de l'id empresa pasat per paràmetre
*/
public void crear_interficie(int empresa) {
if(fAccio==null){
fAccio=new JFrame();
}
pCenter.setLayout(l);
id_empresa=empresa;
int i=0;
for(String valor:valorsLabel){
JTextField text=new JTextField();
pCenter.add(new JLabel(valor));
if(valor.equals("Tipus via")==true){
pCenter.add(selVia);
}
else{
if(valor.equals("Contrasenya")==true){
filtres[i]=new JPasswordField();
}
else{
filtres[i]=new JTextField();
}
pCenter.add(filtres[i]);
i++;
}
}
String tipusAccio="";
if(empresa==0){
//afegir empresa
tipusAccio="Afegir empresa";
}
else{
tipusAccio="Modificar empresa";
carregarDades(empresa);
}
fAccio.setTitle(tipusAccio);
btnAccio.setText(tipusAccio);
JLabel titol=new JLabel("BrisingrGaunt Productions, SL");
titol.setFont(new Font(titol.getFont().getFontName(),Font.PLAIN,16));
pTop.add(titol);
fAccio.add(pTop,BorderLayout.NORTH);
pTop.setBorder(new EmptyBorder(20,100,20,100));
pCenter.setBorder(new EmptyBorder(20,100,20,100));
fAccio.add(pCenter,BorderLayout.CENTER);
pBottom.add(btnAccio);
pBottom.setBorder(new EmptyBorder(20,100,20,100));
fAccio.add(pBottom,BorderLayout.SOUTH);
fAccio.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
fAccio.pack();
fAccio.setSize(550, 500);
fAccio.setLocationRelativeTo(null);
fAccio.setVisible(true);
fAccio.setResizable(false);
}
/**
* Col·loca un escoltador a l'únic botó de l'aplicació
*/
private void set_escoltador() {
btnAccio.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
boolean correcte=comprovar_camps();
if(correcte){
try {
String sql="";
Connection con=new Connexio().getConnexio();
if(id_empresa==0){
sql="insert into empresa (nom, tipusVia, direccio, numDireccio, comarca, email, username, password) values (?,?,?,?,?,?,?,?)";
}
else{
sql="update empresa set nom=?, tipusVia=?, direccio=?, numDireccio=?, comarca=?, email=?, username=?, password=? where id=?";
}
PreparedStatement st = con.prepareStatement(sql);
//Lliguem els valors del formulari
String valors_formulari[]=new String[filtres.length];
int i=1;
for(JTextField filtre:filtres){
if(i==2){
//Agafem el valor del dropdown
st.setString(i,String.valueOf(selVia.getSelectedItem()));
i++;
}
st.setString(i, filtre.getText());
i++;
}
if(id_empresa!=0){
//Si estem modificant passem l'últim paràmetre (el del where)
st.setString(9,String.valueOf(id_empresa));
}
int n=st.executeUpdate();
String accio=id_empresa==0?"Inserció":"Modificació";
con.close();
st.close();
if(n==1){
Gestio.crear_missatge(accio+" realitzada correctament.", 1);
}
else{
Gestio.crear_missatge("Error al realitzar "+accio+".", 0);
}
fAccio.setVisible(false);
Gestio.estatInicialTaulaEmpreses();
Gestio.fGestio.setVisible(true);
} catch (SQLException ex) {
Logger.getLogger(Afegir_Modificar.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
});
}
/**
* Mètode que comprova que el contingut dels JTextFields siguin els adequats
* @return true si el contingut dels JTextField ha pasat per les expressions regulars amb èxit o fals si no s'ha trobat cap coincidència
*/
private boolean comprovar_camps(){
String expressions[]={"^\\w{5,}","^\\d","^[\\w\\.]{6,}@\\w{4,}\\.[a-z]{2,5}$","^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=])(?=\\S+$).{8,}$"};
String errors[]={"Nom","Adreça","Número","Població","Correu electrònic","Usuari","La contrasenya ha d'incloure 1 majúscula, 1 minúscula, 1 número, 1 símbol, no pot tenir espais i llargària mínima de 8 caràcters"};
int posicio=0;
int i=0;
boolean correcte=true;
String validacio="Hi ha errors en els següents camps: ";
for(JTextField filtre:filtres){
if(posicio%2==0 && posicio!=0){
i=posicio/2;
}
else{
i=0;
}
Pattern p=Pattern.compile(expressions[i]);
Matcher m=p.matcher(filtre.getText());
if(!m.find()){
correcte=false;
validacio+="\n\t - "+errors[posicio];
}
posicio++;
}
if(!correcte){
crear_missatge(validacio,1);
}
return correcte;
}
/**
* Mètode que carrega l'informació d'una empresa en els JTextField en cas que s'entri per mètode 'Editar'
* @param empresa id de l'empresa a recuperar les dades
*/
public static void carregarDades(int empresa){
try {
//editar empresa
//es fa el populate dels camps del formulari
String s2="select nom, tipusVia, direccio, numDireccio, comarca, email, username, password from empresa where id like ?";
Connection con=new Connexio().getConnexio();
PreparedStatement st=con.prepareStatement(s2);
st.setString(1, String.valueOf(id_empresa));
ResultSet rs=st.executeQuery();
//Només tornarà un registre per tant ens estalviem el bucle rs.next()
rs.first();
//Es selecciona l'element del dropdown
for(int i=0;i<selVia.getItemCount();i++){
if(rs.getString(2).equals(selVia.getItemAt(i))==true){
selVia.setSelectedIndex(i);
}
}
//S'omplen els JTextField
int j=3;
for(int i=0;i<filtres.length;i++){
if(i!=0){
filtres[i].setText(rs.getString(j));
j++;
}
else{
filtres[i].setText(rs.getString((i+1)));
}
}
con.close();
rs.close();
} catch (SQLException ex) {
Logger.getLogger(Afegir_Modificar.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Canvia l'estat de l'instància de la clase Afegir_Modificar, és un mètode emprat en la clase Gestió
* @param empresa
*/
public static void setEstat(int empresa){
id_empresa=empresa;
if(empresa==0){
for(JTextField camp: filtres){
camp.setText("");
}
btnAccio.setText("Afegir empresa");
}
else{
carregarDades(empresa);
btnAccio.setText("Modificar empresa");
}
}
}
<file_sep>/M7/projecte_kevin/application/models/participacio.php
<?php
class Participacio extends CI_Model {
public function getValoracionsUna($filtre){
$this->db->select('p.nom, pa.valoracio, cl.username, c.estat,c.data, pa.cata, pa.client, e.nom as empresa');
$this->db->from('participacio pa');
$this->db->join('cata c', 'c.id = pa.cata');
$this->db->join('client cl','cl.email=pa.client');
$this->db->join('producte p','p.codi=c.producte');
$this->db->join('empresa e','e.id=c.empresa');
$this->db->where($filtre);
$query=$this->db->get();
if($query->num_rows()==0){
return 0;
}
return $query->result_array();
}
public function getAllEmpresa($empresa){
$query = $this->db->query("select p.nom, pa.valoracio, cl.username, c.estat, c.data, pa.cata from participacio pa, cata c, client cl, producte p where c.id=pa.cata and cl.email=pa.client and p.codi=c.producte and pa.cata in (select id from cata where empresa='".$empresa."');");
return $query->result_array();
}
public function apuntar($dades){
//primer es comprova que no existeixi l'usuari en aquesta cata
$resultat=$this->db->get_where('participacio',$dades);
if($resultat->num_rows()!=0){
return "Ja estàs apuntat a aquesta cata";
}
$this->db->insert('participacio',$dades);
return "T'has apuntat a la cata correctament";
}
public function desapuntar($dades){
//comprovem que l'usuari no existeixi en aquesta cata
$resultat=$this->db->get_where('participacio',$dades);
if($resultat->num_rows()==0){
return "No et pots desapuntar d'una cata en la que no participes";
}
$this->db->delete('participacio',$dades);
return "T'has desapuntat de forma correcta";
}
public function valorar($dades){
//primer es comprova que l'usuari estigui apuntat a la cata que vol valorar en cas que es vulgui fer el lio per URL
$resultat=$this->db->get_where('participacio',array('cata'=>$dades['cata'],'client'=>$dades['client']));
if($resultat->num_rows()==0){
return "No pots valorar una cata en la que no estàs apuntat!!";
}
//si tot correcte, llavors es puntua
$this->db->where(array('cata'=>$dades['cata'],'client'=>$dades['client']));
$this->db->update('participacio', array('valoracio'=>$dades['valoracio']));
return "Valoració realitzada, gràcies.";
}
public function getAllUsuari($user){
$this->db->select('pa.cata, pa.valoracio');
$this->db->from('participacio pa');
$this->db->where($user);
$this->db->order_by("pa.cata","asc");
$query=$this->db->get();
$cates="";
$valoracions="";
foreach($query->result_array() as $aux){
$cates.=$aux['cata'].":";
$valoracions.=$aux['valoracio'].":";
}
$resultat['cates']=$cates;
$resultat['valoracions']=$valoracions;
return $resultat;
}
}
?>
<file_sep>/M8/doxygen_java_m3/html/search/classes_0.js
var searchData=
[
['afegir_5fmodificar',['Afegir_Modificar',['../class_gestio_empreses_1_1_afegir___modificar.html',1,'GestioEmpreses']]]
];
<file_sep>/M7/projecte_kevin/application/models/producte.php
<?php
class Producte extends CI_Model {
public function afegir($data){
//primer es busca que no existeixi ja
$resultat=$this->db->get_where('producte',array('empresa'=>$data['empresa'],'nom'=>$data['nom']));
if($resultat->num_rows()!=0){
return "Error: Aquest producte ja existeix dintre del teu catàleg";
}
else{
$this->db->insert('producte',$data);
return "Producte donat d'alta correctament";
}
}
public function getAllByEmpresa($empresa){
$sql=$this->db->get_where('producte',array('empresa'=>$empresa));
return $sql->result_array();
}
public function getNom($id){
$sql=$this->db->get_where('producte',array('codi'=>$id));
return $sql->result_array()[0]['nom'];
}
public function obtenirRanking(){
//per obtenir el ranking de productes
$resultat=$this->db->query("SELECT DISTINCT `p`.`nom`, `p`.`descripcio`, avg(`pa`.`valoracio`) as valoracio, `e`.`nom` as `empresa`, `e`.`id`, `c`.`data` FROM `producte` `p` JOIN `cata` `c` ON `c`.`producte`=`p`.`codi` JOIN `participacio` `pa` ON `pa`.`cata`=`c`.`id` JOIN `empresa` `e` ON `e`.`id`=`c`.`empresa` group by p.nom, p.descripcio, e.nom, e.id, c.data ORDER BY `pa`.`valoracio` DESC, `p`.`nom` ASC");
return $resultat;
}
}
?>
<file_sep>/M7/projecte_kevin/application/language/spanish/projecte_lang.php
<?php
$lang['identificador_login'] = 'Usuario / Correo electrónico'; // %s is the REST API key
$lang['password'] = '<PASSWORD>';
$lang['identificador']='Nombre de usuario';
$lang['mail'] = 'Correo electrónico';
$lang['mostrarPass'] = 'Mostrar <PASSWORD>';
$lang['botoLogin'] = 'Iniciar sesión';
$lang['botoRegister'] = 'Registrarse';
$lang['perfilUsuari']='Perfil Usuario';
$lang['perfilEmpresa']='Perfil Empresa';
$lang['nomComercial']='Nombre comercial';
$lang['tipusVia']='Tipo de via';
$lang['direccio']='Dirección';
$lang['nomVia']='Nombre de la via';
$lang['poblacio']='Población';
$lang['avinguda']='Avenida';
$lang['carrer']='Calle';
?>
<file_sep>/M7/projecte_kevin/application/language/catalan/projecte_lang.php
<?php
$lang['identificador_login'] = 'Usuari / Corre<NAME>rònic'; // %s is the REST API key
$lang['password'] = '<PASSWORD>';
$lang['identificador']="<NAME>'usuari";
$lang['mail'] = 'Correo electrònic';
$lang['mostrarPass'] = '<PASSWORD>';
$lang['botoLogin'] = 'Iniciar sessió';
$lang['botoRegister'] = 'Registrar-se';
$lang['perfilUsuari']='Perfil Usuari';
$lang['nomComercial']='Nom comercial';
$lang['tipusVia']='Tipus de via';
$lang['direccio']='Direcció';
$lang['nomVia']='Nom del carrer';
$lang['poblacio']='Població';
$lang['avinguda']='Avinguda';
$lang['carrer']='Carrer';
?>
<file_sep>/M7/projecte_kevin/application/views/empresa.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
include 'items.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Empresa</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="<?php echo base_url();?>/js/script.js"></script>
<link href='https://fonts.googleapis.com/css?family=Cabin+Condensed:700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="<?php echo base_url();?>/css/estilo.css">
<link rel="stylesheet" href="<?php echo base_url();?>/css/base.css">
</head>
<body>
<header>
<?php echo $barra_empresa;?>
</header>
<main class="container-fluid">
<div class="row">
<div class="col-md-3 col-12 order-2 order-md-1">
<?php echo $esquerra;?>
</div>
<div class="col-md-9 register-right principal order-md-2 order-1">
<div id="contingut">
<div class="row">
<div class="col-md-3 d-sm-block d-none"></div>
<div class="col-md-6 col-12">
<h1>Els teus events...</h1>
</div>
<div class="col-md-3 d-sm-block d-none"></div>
</div>
<?php
if(isset($cates)){
$i=0;
echo "<div class='row'>";
foreach($cates as $c){
if($i==2){
echo "</div><div class='row'>";
}
?>
<div class="col-md-1 col-1"></div>
<div class="cata col-md-4 col-10 nota">
<i class="pin"></i>
<h2><?php echo $c['nom'];?></h2>
<p class="descripcio">"<?php echo $c['descripcio'];?>"</p>
<p><b>On?</b> <?php echo $info_empresa['tipusVia']." ".$info_empresa['direccio'].", ".$info_empresa['numDireccio']." (".$info_empresa['comarca'].")";?></p>
<p><b>Quan?</b> <?php $newDate = date("d/m/Y H:i", strtotime($c['data'])); echo $newDate;?></p>
<p><?php
if($c['estat']==0){
$estat="Oberta";
}
else{
$estat="Tancada";
}
echo "<b>Estat: </b>".$estat;?></p>
<p class="peu">
<?php
echo "<a href='";
if($c['estat']==0){
echo site_url('Empresa/modificar_cata/?id='.$c['id'])."'>Modificar cata</a>";
}
else{
echo site_url('Empresa/veure_valoracions/?id='.$c['id'])."'>Veure valoracions</a>";
}
?>
</p>
</div>
<div class="col-md-1 col-1"></div>
<?php
$i++;
}
echo "</div>";
}
else{
echo "<h2>Benvolgut ".$info_empresa['nom'].", encara no tens cap event programat, planifica algun";
}
?>
</div>
</div>
</div>
</main>
<footer class="page-footer font-small">
<div class="footer-copyright text-center">© 2019 Copyright --
BrisingrGaunt Productions
</div>
</footer>
</body>
</html>
<file_sep>/M2/eliminacio_taules.sql
delete from participacio;
delete from cata;
delete from client;
delete from producte;
delete from empresa;
drop table participacio;
drop table cata;
drop table client;
drop table producte;
drop table empresa;
<file_sep>/M6/script_mapa.js
$('document').ready(function(){
let info=document.querySelector('#coordenades').value;
coordenades=info.split(",");
mapa.style.width='500px';
mapa.style.height='400px';
console.info(coordenades);
initMap();
});
let coordenades;
function initMap(){
let latitud = coordenades[0];
let longitud = coordenades[1];
let latlon = new google.maps.LatLng(latitud, longitud);
let myOptions = {
center: latlon, // centre de myOptions, la posició actual
zoom: 19, // Nivell de zoom
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false,
navigationControl: true,
// Mostrar o no els botons de navegació.
navigationControlOptions:{style:google.maps.NavigationControlStyle.SMALL}
// Estil dels botons de navegació.
}
let map = new google.maps.Map(document.getElementById('mapa'), myOptions);//es crea el objecte map
console.info(map);
let marker = new google.maps.Marker(//primer marcador amb els valors del formulari
{
position:latlon,
map:map,
label: "Aquí ens trobem!"
});
}<file_sep>/M8/doxygen_java_m3/html/search/all_8.js
var searchData=
[
['validar_5fcamps',['validar_camps',['../class_login_1_1_login.html#a206a680beeee1f655925c36eeceb231e',1,'Login::Login']]]
];
<file_sep>/M7/projecte_kevin/application/views/mapa.php
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Ubícate</title>
<link rel="shortcut icon" href="<?php base_url();?>/pics/B.svg" />
<script async defer src="http://maps.googleapis.com/maps/api/js?key=AIzaSyBhIshCfsCDpx<KEY>RUw3sczEiTJE"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link href='https://fonts.googleapis.com/css?family=Cabin+Condensed:700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="<?php echo base_url();?>/css/base.css">
<script src="<?php echo base_url();?>/js/script_mapa.js"></script>
</head>
<body>
<header>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="#"><img src="<?php echo base_url();?>/pics/B.svg"></a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="<?php echo site_url('Inici');?>">BrisingrGaunt Productions SL <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item d-none">
<a class="nav-link" href="#"> </a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Accés empresa
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="<?php echo site_url('Inici/login');?>">Registre</a>
<a class="dropdown-item" href="<?php echo site_url('Inici/login');?>">Iniciar Sessió</a>
</div>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Accés usuari
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="<?php echo site_url('Inici/login');?>">Registre</a>
<a class="dropdown-item" href="<?php echo site_url('Inici/login');?>">Iniciar Sessió</a>
</div>
</li>
</ul>
</div>
</nav>
</header>
<main class="container-fluid">
<input type="hidden" id='coordenades' value="<?php echo $coordenades;?>">
<br>
<h1>Ubicació de <?php echo $nom;?></h1>
<br>
<div class="row">
<div class="col-md-2 col-1"></div>
<div class="col-md-8 col-10" id="mapa"></div>
<div class="col-md-2 col-1"></div>
</div>
<br>
<h2><?php echo $direccio;?></h2>
</main>
<!-- Footer -->
<footer class="page-footer">
<!-- Copyright -->
<div class="footer-copyright text-center">© 2019 Copyright --
BrisingrGaunt Productions
</div>
<!-- Copyright -->
</footer>
<!-- Footer -->
</body>
</html>
<file_sep>/M6/script_prod.js
window.addEventListener('load', function () {
let boto=document.querySelector("input[type='button']");
console.info(boto);
boto.addEventListener('click', function () {
let formulari=this.parentElement.parentElement.parentElement;
let elements_form=formulari.elements;
let errors=false;
for(let i=0;i<elements_form.length;i++){
if(elements_form[i].type!="button" || elements_form[i].type!="hidden"){
if(elements_form[i].value.length==0){
errors=true;
}
}
}
if(errors){
info.innerHTML="<br><b>Els camps no poden estar buits</b>";
}
else{
info.innerHTML="";
formulari.submit();
}
});
});
<file_sep>/M8/doxygen_java_m3/html/search/functions_3.js
var searchData=
[
['gestio',['Gestio',['../class_gestio_empreses_1_1_gestio.html#a91ba56ea47931cbd57490803f1d4fe9a',1,'GestioEmpreses::Gestio']]],
['getconnexio',['getConnexio',['../class_connexio_1_1_connexio.html#a32d5077179258391ba99699a87a4cff2',1,'Connexio::Connexio']]]
];
<file_sep>/M7/projecte_kevin/application/controllers/Empresa.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Empresa extends CI_Controller {
public function index()
{
$info=$this->session->flashdata('informacio');
if($info!=""){
$_SESSION['info_empresa']=$info;
}
else{
$this->comprovacionsEmpresa();
$info=$_SESSION['info_empresa'];
}
$this->load->model('cata');
$data['info_empresa']=$info;
$filtre=array('c.empresa'=>$info['id']);
$cates=$this->cata->getAllFiltre($filtre);
if($cates!=0){
$data['cates']=$cates;
}
$this->load->view('empresa',$data);
}
public function comprovacionsEmpresa(){
if(!isset($_SESSION['info_empresa'])){
redirect('Inici/logout');
}
}
public function carregaXML(){
$this->comprovacionsEmpresa();
$data['info_empresa']=$_SESSION['info_empresa'];
$data['info']="";
if($this->input->post()){
$config['upload_path']= './uploads/';
$config['allowed_types']= 'xml';
$this->load->library('upload',$config);
if ($this->upload->do_upload('xml')) {
$nom_arxiu = $this->upload->data()['file_name'];
$xml = simplexml_load_file(base_url(). "/uploads/".$nom_arxiu);
$this->load->model('producte');
$errors=false;
foreach($xml->producte as $producte){
$valors=[];
$valors['empresa']=$producte->attributes()->empresa;
$valors['nom']=$producte->nom;
$valors['descripcio']=$producte->descripcio;
$resultat=$this->producte->afegir($valors);
if (strpos($resultat, 'Error') !== false) {
$errors=true;
}
}
if($errors){
$missatge="Hi ha hagut errors al realitzar la càrrega massiva. Contacta l'administrador.";
}
else{
$missatge="Els productes han sigut donats d'alta correctament";
}
}
else{
$missatge="Error al llegir l'arxiu XML.";
}
$data['info']=$missatge;
}
$this->load->view('carrega_massiva',$data);
}
public function pujar_producte(){
$this->comprovacionsEmpresa();
$data['info']="";
if($this->input->post()){
//var_dump($_POST);
//si entrem per la carrega xml
if(isset($_POST['xml'])){
redirect('Empresa/carregaXML');
}
$this->load->model('producte');
$resultat=$this->producte->afegir($_POST);
$data['info']=$resultat;
}
$data['info_empresa']=$_SESSION['info_empresa'];
$this->load->view('producte',$data);
}
public function veure_valoracions(){
$this->comprovacionsEmpresa();
$this->load->model('participacio');
if(isset($_GET['id'])){
$filtre=array('pa.cata'=>$_GET['id']);
$dades=$this->participacio->getValoracionsUna($filtre);
}
else{
$dades=$this->participacio->getAllEmpresa($_SESSION['info_empresa']['id']);
$data['esGeneral']=true;
}
//var_dump($dades);
//exit;
$data['info_cata_individual']=$dades;
$data['info_empresa']=$_SESSION['info_empresa'];
$this->load->view('visualitzar_valoracions',$data);
}
public function modificar_cata(){
$this->comprovacionsEmpresa();
//$this->load->model('cata');
$this->load->model('producte');
if(isset($_GET['id'])){
$filtre=array('id'=>$_GET['id']);
$curl=curl_init("http://127.0.0.1/projecte_kevin_webservice/index.php/api/Server/mostrarCatesFiltre");
curl_setopt($curl,CURLOPT_TIMEOUT,20);
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query(array('filtre'=>$filtre)));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER,1);
$resultat=json_decode(curl_exec($curl),true);
curl_close($curl);
$data['editar_cata']=$resultat[0];
}
else{
//entrem per post (modificar o eliminar)
$this->load->model('cata');
$missatge="";
if(isset($_POST['eliminar'])){
//Mètode eliminar
$filtre=array('id',$_POST['id']);
//resultat retornarà 0 si no hi ha cap usuari apuntat a la cata o el llistat d'usuaris
$resultat=$this->cata->eliminar($filtre);
if($resultat==0){
$missatge="Cata anul·lada, no hi havia ningú apuntat, so that's all folks!";
}
else{
foreach($resultat as $r){
$this->email->clear();
$this->email->from('<EMAIL>', 'BrisingrGaunt Productions, SL');
$this->email->to($r['client']);
$this->email->subject('Cata anul·lada :(');
$this->email->message('Benvolgut/da, '.$r['username'].'<br>Ens fa mal al coraçao informar-te de que la cata que tenies prevista pel dia '.$r['data'].' del producte '.$r['nom'].' ha sigut: <b>CANCELADA!!!!!!!</b> consulta el web per més informació.');
$this->email->send();
}
$missatge="Cata anul·lada. Les persones apuntades ja han sigut avisades.";
}
}
else{
//MODIFIQUEM CATA
$resultat=$this->cata->modificar($_POST);
if($resultat==1){
$missatge="No es pot canviar la data a un temps passat";
}
else if($resultat==0){
$missatge="Cata modificada correctament, no hi ha cap participant al que avisar";
}
else{
//Obtenim el nom del producte antic
$producte_vell=$this->producte->getNom($_POST['producte_vell']);
$data_vella=$_POST['data_vella'];
foreach($resultat as $r){
$this->email->clear();
$this->email->from('<EMAIL>','BrisingrGaunt Productions, SL');
$this->email->to($r['client']);
$this->email->subject('Cata modificada');
$this->email->message('Benvolgut/da, '.$r['username']."<br>T'informem que la cata a la que estaves apuntat: <ul><li>Data: ".$data_vella."</li><li>Producte: ".$producte_vell."</li></ul><br>Ha sigut modificada amb els següents valors:<ul><li>Data: ".$r['data']."</li><li>Producte: ".$r['nom']."</li></ul><br>Disculpa les molèsties.");
$this->email->send();
}
$missatge="Cata modificada correctament. Les persones apuntades han sigut notificades del canvi";
}
}
$data['info']=$missatge;
}
$data['productes']=$this->producte->getAllByEmpresa($_SESSION['info_empresa']['id']);
$data['info_empresa']=$_SESSION['info_empresa'];
$this->load->view('programar_cata',$data);
}
public function programar_cata(){
$this->comprovacionsEmpresa();
$data['info']="";
if($this->input->post()){
$this->load->model('cata');
$resultat=$this->cata->programar_cata($_POST);
$data['info']=$resultat;
}
$this->load->model('producte');
$data['productes']=$this->producte->getAllByEmpresa($_SESSION['info_empresa']['id']);
$data['info_empresa']=$_SESSION['info_empresa'];
$this->load->view('programar_cata',$data);
}
}
<file_sep>/M7/projecte_kevin/application/models/empresa.php
<?php
class Empresa extends CI_Model {
public function preparar($post){
$taula=[];
foreach($post as $clau => $valor){
if($clau!="accio"){
if($clau=="password"){
$taula[$clau]=md5($valor);
}
else{
$taula[$clau]=$valor;
}
}
}
return $taula;
}
public function registre($post){
//Primer comprovarem que no existeixi el client que es vol inserir
$data=$this->preparar($post);
$query = $this->db->get_where('empresa', array('email' => $data['email'],'username'=>$data['username']));
if($query->num_rows()!=0){
return "No s'ha pogut realitzar l'alta d'empresa degut a que ja existeix a l'aplicació";
}
$this->db->insert('empresa',$data);
return "Registre realitzat correctament";
}
public function getDireccio($id){
$this->db->select('tipusVia, direccio, numDireccio, comarca');
$this->db->from('empresa');
$this->db->where(array('id'=>$id));
$resultat=$this->db->get();
$info=$resultat->result_array()[0];
$direccio=$info['tipusVia']." ".$info['direccio']." ".$info['numDireccio']." ".$info['comarca'];
return $direccio;
}
public function getNom($id){
$this->db->select('nom');
$this->db->from('empresa');
$this->db->where(array('id'=>$id));
$resultat=$this->db->get();
return $resultat->result_array()[0]['nom'];
}
public function login($post){
$taula=$this->preparar($post);
$query=$this->db->query("select * from empresa where password like '".$taula['password']."' and (email like '".$taula['username']."' or username like '".$taula['username']."')");
if($query->num_rows()==0){
return 0;
}
return $query->result_array()[0];
}
}
?>
<file_sep>/M7/projecte_kevin/application/controllers/Inici.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Inici extends CI_Controller {
public function index()
{
$this->load->model('producte');
$data['productes']=$this->producte->obtenirRanking();
$curl=curl_init("http://127.0.0.1/projecte_kevin_webservice/index.php/api/Server/mostrarCatesAll");
curl_setopt($curl,CURLOPT_TIMEOUT,20);
curl_setopt($curl, CURLOPT_RETURNTRANSFER,1);
$resultat=json_decode(curl_exec($curl),true);
curl_close($curl);
$data['cates']=$resultat;
$this->load->view('index',$data);
}
public function login(){
if(isset($_GET['idioma'])){
$idioma=$_GET['idioma'];
}
else{
$idioma='english';
}
$this->lang->load('projecte',$idioma);
$data['lang']=$this->lang;
$this->load->view('inici',$data);
}
public function ubicar(){
if(isset($_GET)){
$id=$_GET['id'];
$this->load->model('empresa');
$direccio=$this->empresa->getDireccio($id);
$data['direccio']=$direccio;
$data['nom']=$this->empresa->getNom($id);
$data['coordenades']=$this->getCoordinates($direccio);
$this->load->view('mapa',$data);
}
}
public function idioma($idioma="catalan"){
$idioma=$this->input->get('id');
$this->lang->load('projecte',$idioma);
}
function getCoordinates($address){
$address = str_replace(" ", "+", $address);
$url = "https://maps.google.com/maps/api/geocode/json?sensor=false&key=<KEY>&address=$address";
$response = file_get_contents($url);
$json = json_decode($response,TRUE);
return ($json['results'][0]['geometry']['location']['lat'].",".$json['results'][0]['geometry']['location']['lng']);
}
public function accio(){
$valors=explode('_',$_POST['accio']);
$accio=$valors[0];
$model=$valors[1];
$this->load->model($model);
$data=array();
if(sizeof($_POST)==3){
$info=$this->$model->login($_POST);
if($info==0){
//Si no hi ha cap usuari amb aquests credencials
$data['info']="Credencials errònies, comprova les dades";
}
else{
$this->session->set_flashdata('informacio', $info);
if(sizeof($info)==3){
// Part client
$_SESSION['client']=$info['email'];
redirect('Cliente');
}
else{
// Part empresa
$_SESSION['empresa']=$info['id'];
redirect('Empresa');
}
}
}
else{
$missatge=$this->$model->registre($_POST);
$data['info']=$missatge;
}
$this->lang->load('projecte',"english");
$data['lang']=$this->lang;
$this->load->view('inici',$data);
}
public function logout(){
$this->session->sess_destroy();
redirect('Inici');
}
}
<file_sep>/M8/doxygen_java_m3/html/search/all_0.js
var searchData=
[
['afegir_5fmodificar',['Afegir_Modificar',['../class_gestio_empreses_1_1_afegir___modificar.html',1,'GestioEmpreses.Afegir_Modificar'],['../class_gestio_empreses_1_1_afegir___modificar.html#a5a9fe23eba7323eb0068cf645ab9db2e',1,'GestioEmpreses.Afegir_Modificar.Afegir_Modificar()']]]
];
<file_sep>/M7/projecte_kevin/application/models/client.php
<?php class Client extends CI_Model {
public function preparar($post){
$taula=[];
foreach($post as $clau => $valor){
if($clau!="accio"){
if($clau=="password"){
$taula[$clau]=md5($valor);
}
else{
$taula[$clau]=$valor;
}
}
}
return $taula;
}
public function login($post) {
$taula=$this->preparar($post);
$query=$this->db->query("select * from client where password like '".$taula['password']."' and (email like '".$taula['username']."' or username like '".$taula['username']."')");
if($query->num_rows()==0){
return 0;
}
return $query->result_array()[0];
}
public function registre($post){
//Primer comprovarem que no existeixi el client que es vol inserir
$data=$this->preparar($post);
$query = $this->db->get_where('client', array('email' => $data['email'],'username'=>$data['username']));
if($query->num_rows()!=0){
return "No s'ha pogut realitzar l'alta d'usuari degut a que ja existeix a l'aplicació";
}
$this->db->insert('client',$data);
return "Registre realitzat correctament";
}
public function getProperEvent($filtre){
$this->db->select('e.nom as empresa, p.nom as producte, c.id, c.data, e.tipusVia, e.direccio, e.numDireccio, e.comarca');
$this->db->from('empresa e');
$this->db->join('cata c','c.empresa = e.id');
$this->db->join('producte p','p.empresa = e.id');
$this->db->where($filtre);
$this->db->order_by("c.data", "asc");
$this->db->limit(1);
$query=$this->db->get();
return $query->result_array()[0];
}
public function getQtParticipacions($filtre){
$this->db->select('pa.cata');
$this->db->from('participacio pa');
$this->db->join('cata c', 'pa.cata = c.id');
$this->db->where($filtre);
$query=$this->db->get();
return $query->num_rows();
}
}
?>
<file_sep>/M7/projecte_kevin_webservice/application/models/cata.php
<?php
class Cata extends CI_Model {
function __construct(){
}
public function getAllDetallat(){
$this->db->select('p.nom,p.descripcio, c.data, c.estat, c.id, p.codi, e.nom as empresa, e.direccio, e.numDireccio, e.comarca, e.tipusVia');
$this->db->from('cata c');
$this->db->join('producte p', 'p.codi = c.producte');
$this->db->join('empresa e','e.id=c.empresa');
$this->db->order_by('c.data','desc');
$query=$this->db->get();
return $query->result_array();
}
public function getAllFiltre($filtre){
$this->db->select('p.nom,p.descripcio, c.data, c.estat, c.id, p.codi');
$this->db->from('cata c');
$this->db->join('producte p', 'p.codi = c.producte');
$this->db->where($filtre);
$query=$this->db->get();
if($query->num_rows()==0){
return 0;
}
return $query->result_array();
}
}
?><file_sep>/M8/doxygen_java_m3/html/search/classes_1.js
var searchData=
[
['clickafegir',['clickAfegir',['../class_gestio_empreses_1_1_gestio_1_1click_afegir.html',1,'GestioEmpreses::Gestio']]],
['clickcercar',['clickCercar',['../class_gestio_empreses_1_1_gestio_1_1click_cercar.html',1,'GestioEmpreses::Gestio']]],
['clickeditar',['clickEditar',['../class_gestio_empreses_1_1_gestio_1_1click_editar.html',1,'GestioEmpreses::Gestio']]],
['clickesborrar',['clickEsborrar',['../class_gestio_empreses_1_1_gestio_1_1click_esborrar.html',1,'GestioEmpreses::Gestio']]],
['connexio',['Connexio',['../class_connexio_1_1_connexio.html',1,'Connexio']]]
];
<file_sep>/M7/projecte_kevin/application/views/programar_cata.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
include 'items.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Programar cata</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="<?php echo base_url();?>/js/script_prod.js"></script>
<link href='https://fonts.googleapis.com/css?family=Cabin+Condensed:700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="<?php echo base_url();?>/css/estil.css">
<link rel="stylesheet" href="<?php echo base_url();?>/css/estilo.css">
<link rel="stylesheet" href="<?php echo base_url();?>/css/base.css">
</head>
<body>
<header>
<?php echo $barra_empresa;?>
</header>
<main class="container-fluid">
<div class="row">
<div class="col-md-3 col-12 order-2 order-md-1">
<?php echo $esquerra;?>
</div>
<div class="col-md-9 principal order-md-2 order-1">
<div class="row">
<div class="col-md-3 col-1"></div>
<div class="col-md-7 col-10">
<h1>Programació de cata</h1>
</div>
<div class="col-md-2 col-1"></div>
</div>
<div class="row">
<div class="col-md-3"></div>
<div class="col-md-6">
<form method="post" action="<?php if(isset($editar_cata)){echo site_url('Empresa/modificar_cata');}else{echo site_url('Empresa/programar_cata');}?>">
<input type="hidden" name="empresa" value="<?php echo $info_empresa['id']?>" />
<?php if(isset($editar_cata)){?>
<input type="hidden" name='id' value="<?php echo $editar_cata['id'];?>" />
<input type="hidden" name='producte_vell' value="<?php echo $editar_cata['codi'];?>"/>
<input type="hidden" name="data_vella" value="<?php echo $editar_cata['data'];?>"/>
<?php } ?>
<div class="form-group row">
<div class="col-md-3 col-1"></div>
<div class="col-md-5 col-10"><label for="nom_producte">Producte *</label><br>
<select name="producte" id="nom_producte">
<option value="-1">Selecciona un producte</option>
<?php
foreach($productes as $p){
echo "<option value='".$p['codi']."'";
if(isset($editar_cata)){
if($editar_cata['codi']==$p['codi']){
echo " selected ";
}
}
echo ">".$p['nom']."</option>";
}
?>
</select>
</div>
<div class="col-md-4 col-1"></div>
</div>
<div class="form-group row">
<div class="col-md-3 col-1"></div>
<div class="col-md-5 col-10"><label for="data_event">Data i hora *</label><br>
<input type="datetime-local" name="data" id="data_event" <?php if(isset($editar_cata)){
echo "value='".str_replace(" ","T",$editar_cata['data'])."'";}?> /></div>
<div class="col-md-4 col-1"></div>
</div>
<div class="row">
<div class="col-md-4 col-1"></div>
<div class="col-md-4 col-10">
<?php if(isset($editar_cata)){ ?>
<input type='submit' id="eliminarCata" class="btnRegister" value="Eliminar cata" name='eliminar'>
<input type='button' id='modificarCata' class="btnRegister" value="Modificar cata" name="modificar">
<?php }else{?>
<input type="button" id="afegirCata" class="btnRegister" value="Afegir">
<?php }?>
</div>
<div class="col-md-4 col-1"></div>
</div>
</form>
</div>
<div class="col-md-3"></div>
</div>
</div>
</div>
</main>
<!-- Footer -->
<footer class="page-footer font-small">
<!-- Copyright -->
<div class="footer-copyright text-center">© 2019 Copyright --
BrisingrGaunt Productions
</div>
<!-- Copyright -->
</footer>
</body>
</html>
<file_sep>/M7/projecte_kevin/application/views/index.php
<html>
<head>
<meta charset="utf-8">
<meta http-equiv=”Content-Language” content=”es”/>
<meta name="viewport" content="width=device-width">
<title>BrisingrGaunt Productions</title>
<link rel="shortcut icon" href="<?php base_url();?>/pics/B.svg" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link href='https://fonts.googleapis.com/css?family=Cabin+Condensed:700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="<?php echo base_url();?>/css/base.css">
<script src="<?php echo base_url();?>/js/script_base.js"></script>
</head>
<body>
<header>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="<?php echo site_url('Inici');?>"><img src="<?php echo base_url();?>/pics/B.svg" class="logo" alt="logo empresa"></a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="#">BrisingrGaunt Productions SL <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Accés empresa
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="<?php echo site_url('Inici/login');?>">Registre</a>
<a class="dropdown-item" href="<?php echo site_url('Inici/login');?>">Iniciar Sessió</a>
</div>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Accés usuari
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="<?php echo site_url('Inici/login');?>">Registre</a>
<a class="dropdown-item" href="<?php echo site_url('Inici/login');?>">Iniciar Sessió</a>
</div>
</li>
</ul>
</div>
<div class="animacio d-none d-sm-block">
<img src="<?php echo base_url()."/pics/botella.png";?>" class="botella" alt="botella">
<img src="<?php echo base_url()."/pics/botella.png";?>" class="botella" alt="botella">
<img src="<?php echo base_url()."/pics/botella.png";?>" class="botella" alt="botella">
<img src="<?php echo base_url()."/pics/botella.png";?>" class="botella" alt="botella">
</div>
</nav>
</header>
<main class="container-fluid">
<div class="row">
<div class="col-md-4 col-12">
<h1>Els més valorats</h1>
<table>
<?php
foreach($productes->result_array() as $p){
echo "<tr><tr><td>Organitza: ".$p['empresa']."</td><td><a href='".site_url('Inici/ubicar/?id='.$p['id'])."'>Ubicar</a></td><td></td></tr><td>Producte</td><td>".$p['nom'].":</td><td>";
//echo $nom.": ";
for($i=0;$i<intval($p['valoracio']);$i++){
echo "★";
}
for($i=intval($p['valoracio']);$i<5;$i++){
echo "☆";
}
echo "</td></tr>";
}
?>
</table>
</div>
<div class="col-md-1"></div>
<div class="col-12 col-md-7">
<h1>Les cates</h1>
<?php
$i=0;
echo " <div class='row'>";
foreach($cates as $c){
?>
<div class="d-md-none col-1 d-block"></div>
<div class="nota col-md-5 col-10">
<i class="pin"></i>
<h2><?php echo $c['nom'];?></h2>
<p><span>Quan? </span> <?php $newDate = date("d/m/Y H:i", strtotime($c['data'])); echo $newDate;?></p>
<p><span>On? </span><?php echo $c['tipusVia']." ".$c['direccio'].", ".$c['numDireccio']." (".$c['comarca'].")";?></p>
<p><span>Estat: </span><?php if($c['estat']==0){
$estat="Oberta";
}
else{
$estat="Tancada";
}
echo $estat;?></p>
<p class="amagat"><span>Organitza: </span><?php echo $c['empresa'];?></p>
<p class="amagat"><span>Descripció del producte: </span><?php echo $c['descripcio'];?></p>
</div>
<div class="d-md-none col-1 d-block"></div>
<div class="col-md-1"></div>
<?php
$i++;
if($i==2){
$i=0;
echo "</div><div class='row'>";
}
}
echo "</div>";
?> </div>
</div>
</main>
<!-- Footer -->
<footer class="page-footer">
<!-- Copyright -->
<div class="footer-copyright text-center">© 2019 Copyright --
BrisingrGaunt Productions
</div>
<!-- Copyright -->
</footer>
<!-- Footer -->
</body>
</html>
<file_sep>/M7/projecte_kevin/application/views/client.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
include 'items.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Client</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="<?php echo base_url();?>/js/script.js"></script>
<link href='https://fonts.googleapis.com/css?family=Cabin+Condensed:700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="<?php echo base_url();?>/css/estil.css">
<link rel="stylesheet" href="<?php echo base_url();?>/css/estilo.css">
<link rel="stylesheet" href="<?php echo base_url();?>/css/base.css">
</head>
<body>
<header>
<?php echo $barra_client;?>
</header>
<main class="container-fluid">
<div class="row">
<div class="col-md-3 col-12 order-2 order-md-1">
<?php echo $esquerra;?>
</div>
<?php //var_dump($propera_cata);exit?>
<div class="col-md-9 order-md-2 order-1">
<div class="row">
<div class="col-md-2 col-1"></div>
<div class="col-md-8 col-10 nota">
<i class="pin"></i>
<h1>Benvolgut <?php echo $info_client['username']; ?></h1>
<h2>Estàs inscrit a <?php echo $qt_participacions; ?> events.</h2>
<h2>Pròxim event: </h2>
<h2>Quin producte? <?php echo $propera_cata['producte'];?></h2>
<h2>Quan? <?php echo date("d-m-Y H:i", strtotime($propera_cata['data']));?></h2>
<h2>On? <?php
echo $propera_cata['tipusVia']." ".$propera_cata['direccio'].", ".$propera_cata['numDireccio']." (".$propera_cata['comarca'].")";
?></h2>
<h2>Qui ho organitza? <?php echo $propera_cata['empresa'];?></h2>
</div>
<div class="col-md-2 col-1"></div>
</div>
</div>
</div>
</main>
<!-- Footer -->
<footer class="page-footer font-small">
<!-- Copyright -->
<div class="footer-copyright text-center">© 2019 Copyright --
BrisingrGaunt Productions
</div>
<!-- Copyright -->
</footer>
<!-- Footer -->
</body>
</html>
<file_sep>/M7/projecte_kevin/application/controllers/Cliente.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Cliente extends CI_Controller {
public function index()
{
$info=$this->session->flashdata('informacio');
if($info!=""){
$_SESSION['info_client']=$info;
}
else{
$this->comprovacions_client();
$info=$_SESSION['info_client'];
}
$this->load->model("client");
$data['qt_participacions']=$this->client->getQtParticipacions(array('pa.client'=>$info['email']));
//Obtenim la propera cata per mostrar en la pàgina principal
$data['propera_cata']=$this->client->getProperEvent(array('c.data >'=>date('Y-m-d H:i')));
$data['info_client']=$info;
$this->load->view('client',$data);
}
public function comprovacions_client(){
if(!isset($_SESSION['info_client'])){
redirect('Inici/logout');
}
}
public function apuntar(){
if(isset($_GET['filtre'])){
$data['filtre']=true;
}
$this->comprovacions_client();
$data['info_client']=$_SESSION['info_client'];
$data['info']="";
if($this->session->flashdata('info')){
$data['info']=$this->session->flashdata('info');
}
$this->load->model("cata");
$this->load->model("participacio");
$data['cates']=$this->cata->getAllDetallat();
$data['participacions']=$this->participacio->getAllUsuari(array('pa.client'=>$_SESSION['info_client']['email']));
//var_dump($data['participacions']);
//exit;
$this->load->view('inscripcions',$data);
}
public function gestio_inscripcio(){
$this->comprovacions_client();
if(isset($_GET)){
$this->load->model('participacio');
$dades=array('cata'=>$_GET['id'],'client'=>$_SESSION['info_client']['email']);
if($_GET['accio']=='apuntar'){
$resultat=$this->participacio->apuntar($dades);
}
else{
$resultat=$this->participacio->desapuntar($dades);
}
$this->session->set_flashdata('info',$resultat);
redirect('Cliente/apuntar');
}
redirect('Cliente');
}
public function valora(){
$this->comprovacions_client();
$data['info_client']=$_SESSION['info_client'];
$this->load->model('participacio');
if($this->input->post()){
$resultat=$this->participacio->valorar($_POST);
$data['info']=$resultat;
$filtre=array('pa.cata'=>$_POST['cata'],'pa.client'=>$_SESSION['info_client']['email']);
}
else{
if(isset($_GET)){
$filtre=array('pa.cata'=>$_GET['id'],'pa.client'=>$_SESSION['info_client']['email']);
}
}
$data['valoracio']=$this->participacio->getValoracionsUna($filtre)[0];
$this->load->view('valoracio',$data);
}
}
?>
<file_sep>/M2/script_definitiu.sql
-- phpMyAdmin SQL Dump
-- version 4.7.0
-- https://www.phpmyadmin.net/
--
-- Servidor: 1172.16.31.10
-- Tiempo de generación: 31-05-2019 a las 00:05:51
-- Versión del servidor: 5.7.17
-- Versión de PHP: 7.1.3
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Base de datos: `projecte_kevin`
--
DROP DATABASE IF EXISTS `projecte_kevin`;
CREATE DATABASE IF NOT EXISTS `projecte_kevin` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;
USE `projecte_kevin`;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `cata`
--
DROP TABLE IF EXISTS `cata`;
CREATE TABLE `cata` (
`id` int(11) NOT NULL,
`empresa` int(11) NOT NULL,
`producte` int(11) NOT NULL,
`estat` int(10) UNSIGNED NOT NULL DEFAULT '0',
`data` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Volcado de datos para la tabla `cata`
--
INSERT INTO `cata` (`id`, `empresa`, `producte`, `estat`, `data`) VALUES
(3, 15, 11, 1, '2019-05-18 18:00:00'),
(4, 15, 13, 1, '2019-05-28 00:15:00'),
(5, 14, 8, 1, '2019-05-30 10:00:00'),
(6, 12, 10, 1, '2019-05-30 16:24:00'),
(7, 14, 6, 1, '2019-05-21 09:00:00'),
(8, 15, 18, 0, '2019-07-26 07:07:00');
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `client`
--
DROP TABLE IF EXISTS `client`;
CREATE TABLE `client` (
`email` varchar(50) NOT NULL,
`username` varchar(40) NOT NULL,
`password` varchar(35) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Volcado de datos para la tabla `client`
--
INSERT INTO `client` (`email`, `username`, `password`) VALUES
('<EMAIL>', '<PASSWORD>', '<PASSWORD>'),
('<EMAIL>', 'BritneySpears1', '<PASSWORD>'),
('<EMAIL>', 'DaenerysTargaryen', '<PASSWORD>'),
('<EMAIL>', 'EmmaWatson', '<PASSWORD>'),
('<EMAIL>', 'Formation', '<PASSWORD>'),
('<EMAIL>', 'KevinMede', '<PASSWORD>'),
('<EMAIL>', 'Kev', '<PASSWORD>'),
('<EMAIL>', 'Miwui11', '<PASSWORD>'),
('<EMAIL>', 'Pedronsio', '<PASSWORD>');
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `empresa`
--
DROP TABLE IF EXISTS `empresa`;
CREATE TABLE `empresa` (
`id` int(11) NOT NULL,
`username` varchar(30) NOT NULL,
`nom` varchar(80) NOT NULL,
`tipusVia` varchar(15) NOT NULL,
`direccio` varchar(210) NOT NULL,
`comarca` varchar(45) NOT NULL,
`numDireccio` int(11) NOT NULL,
`password` varchar(130) NOT NULL,
`email` varchar(50) NOT NULL,
`visibilitat` int(11) NOT NULL DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='password';
--
-- Volcado de datos para la tabla `empresa`
--
INSERT INTO `empresa` (`id`, `username`, `nom`, `tipusVia`, `direccio`, `comarca`, `numDireccio`, `password`, `email`, `visibilitat`) VALUES
(11, 'Clein', '<NAME>', 'Carrer', '<NAME>', 'Igualada', 26, 'ece65e19890b8bfbf064a31a90b712da', '<EMAIL>', 0),
(12, 'Krusty', '<NAME>', 'Avinguda', 'Evergreen Terrace ', 'Neverland', 11, 'fe8285631ba08a82af86a370a37353e4', '<EMAIL>', 0),
(13, 'BobEsponja', 'Crustáceo crujiente', 'Carrer', 'Piña debajo del mar', 'Igualada', 12, '94336a363c529a5350ce2e50ccb49e5b', '<EMAIL>', 0),
(14, 'centralPerk', 'Central Perk Cafe', 'Avinguda', 'la quinta avenida', 'Igualada', 5, 'ac8<EMAIL>3f634f291849b03f999c1e', '<EMAIL>', 0),
(15, 'Baviera', '<NAME>', 'Carrer', 'Lleida', 'Igualada', 57, '63e3bfc5901e7554ecb6310d16d67bdf', '<EMAIL>', 0),
(17, 'Fitzgerald', '<NAME>', 'Avinguda', 'whaaat', 'Garraf', 23, 'ec0e60929ec1dddae97fd87b301304ce', '<EMAIL>', 0),
(26, 'kevinmedina', '<NAME>', 'Carrer', 'Veciana', 'Igualada', 6, 'acf4f333fb00bbe6b5e02d81cfbd395a', '<EMAIL>', 0),
(27, 'lordgaunt', 'LordGaunt', 'Avinguda', 'falsaaaaa', 'Igualada', 1, 'acf4f333fb00bbe6b5e02d81cfbd395a', '<EMAIL>', 0);
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `participacio`
--
DROP TABLE IF EXISTS `participacio`;
CREATE TABLE `participacio` (
`cata` int(11) NOT NULL,
`client` varchar(50) NOT NULL,
`valoracio` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Volcado de datos para la tabla `participacio`
--
INSERT INTO `participacio` (`cata`, `client`, `valoracio`) VALUES
(3, '<EMAIL>', 5),
(4, '<EMAIL>', NULL),
(4, '<EMAIL>', NULL),
(4, '<EMAIL>', NULL),
(5, '<EMAIL>', 2),
(6, '<EMAIL>', NULL),
(8, '<EMAIL>', NULL);
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `producte`
--
DROP TABLE IF EXISTS `producte`;
CREATE TABLE `producte` (
`codi` int(11) NOT NULL,
`empresa` int(11) NOT NULL,
`nom` varchar(50) NOT NULL,
`descripcio` varchar(210) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Volcado de datos para la tabla `producte`
--
INSERT INTO `producte` (`codi`, `empresa`, `nom`, `descripcio`) VALUES
(1, 11, '<NAME>', '<NAME> de moro amb salsa brava'),
(2, 11, 'Pizza de tonyina', 'Pizza de tonyina amb ceba caramelitzada'),
(3, 11, 'Aigua de pluja', 'Aigua de les pluges de l\'Amazones'),
(4, 13, 'CangreBurger', 'Hamburguesa realizada for the one and only Señor Patricio'),
(5, 12, 'KrustyBurger', 'Hamburguesa de animal extinguido hecha por el chico de los granos'),
(6, 14, 'Café con amigos', 'Nosotros ponemos el café, tú los amigos'),
(7, 15, 'Aigua de pluja de l\'Amazones', 'Aigua purificada amb propietats curatives'),
(8, 14, 'Magdalena de xocolata gegant', 'Muffin para los amigos'),
(9, 13, '<NAME>', '<NAME> sota el mar'),
(10, 12, 'Bolsa sorpresa', 'Diferents ítems que es troben quan es neteja la fregidora (disponible 2 cops a l\'any)'),
(11, 15, 'Frankfurt de la casa', 'Frankfurt com el que et fas a casa, però més car'),
(12, 13, '<NAME>', '(No és la mateixa pinya que la del Bob)'),
(13, 15, 'Nuggets de pollastre', 'de que sinó?'),
(17, 13, 'La concha de arenita', 'La parte salada de una ardilla submarina'),
(18, 15, 'Ganas de vivir', 'No sé que son, no tengo'),
(19, 27, 'Blow me', 'Descripció 1'),
(20, 27, 'The truth about love', 'yeah yeah '),
(21, 27, 'Hola buenas que tal', 'Beam me up');
--
-- Índices para tablas volcadas
--
--
-- Indices de la tabla `cata`
--
ALTER TABLE `cata`
ADD PRIMARY KEY (`id`),
ADD KEY `producte` (`producte`),
ADD KEY `empresa` (`empresa`);
--
-- Indices de la tabla `client`
--
ALTER TABLE `client`
ADD PRIMARY KEY (`email`),
ADD UNIQUE KEY `username` (`username`);
--
-- Indices de la tabla `empresa`
--
ALTER TABLE `empresa`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `email` (`email`),
ADD UNIQUE KEY `nom` (`nom`),
ADD UNIQUE KEY `username` (`username`);
--
-- Indices de la tabla `participacio`
--
ALTER TABLE `participacio`
ADD PRIMARY KEY (`cata`,`client`),
ADD KEY `client` (`client`),
ADD KEY `cata` (`cata`);
--
-- Indices de la tabla `producte`
--
ALTER TABLE `producte`
ADD PRIMARY KEY (`codi`,`empresa`),
ADD UNIQUE KEY `nom` (`nom`),
ADD KEY `empresa` (`empresa`);
--
-- AUTO_INCREMENT de las tablas volcadas
--
--
-- AUTO_INCREMENT de la tabla `cata`
--
ALTER TABLE `cata`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9;
--
-- AUTO_INCREMENT de la tabla `empresa`
--
ALTER TABLE `empresa`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=28;
--
-- AUTO_INCREMENT de la tabla `producte`
--
ALTER TABLE `producte`
MODIFY `codi` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=22;
--
-- Restricciones para tablas volcadas
--
--
-- Filtros para la tabla `cata`
--
ALTER TABLE `cata`
ADD CONSTRAINT `cata_ibfk_1` FOREIGN KEY (`producte`) REFERENCES `producte` (`codi`),
ADD CONSTRAINT `cata_ibfk_2` FOREIGN KEY (`empresa`) REFERENCES `empresa` (`id`);
--
-- Filtros para la tabla `participacio`
--
ALTER TABLE `participacio`
ADD CONSTRAINT `participacio_ibfk_1` FOREIGN KEY (`client`) REFERENCES `client` (`email`),
ADD CONSTRAINT `participacio_ibfk_2` FOREIGN KEY (`cata`) REFERENCES `cata` (`id`);
--
-- Filtros para la tabla `producte`
--
ALTER TABLE `producte`
ADD CONSTRAINT `producte_ibfk_1` FOREIGN KEY (`empresa`) REFERENCES `empresa` (`id`);
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep>/M7/projecte_kevin/application/views/inici.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
include 'items.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Inici</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="<?php echo base_url();?>/js/script.js"></script>
<link href='https://fonts.googleapis.com/css?family=Cabin+Condensed:700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="<?php echo base_url();?>/css/estil.css">
<link rel="stylesheet" href="<?php echo base_url();?>/css/estilo.css">
<link rel="stylesheet" href="<?php echo base_url();?>/css/base.css">
</head>
<body>
<header>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<a class="navbar-brand" href="<?php echo site_url('Inici');?>"><img src="<?php echo base_url();?>/pics/Bwhite.svg" class="logo" alt="logo"></a>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="<?php echo site_url('Inici/login');?>">BrisingrGaunt Productions SL <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Accés empresa
</a>
<div class="dropdown-menu" >
<a class="dropdown-item" href="<?php echo site_url('Inici/login');?>">Registre</a>
<a class="dropdown-item" href="<?php echo site_url('Inici/login');?>">Iniciar Sessió</a>
</div>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Accés usuari
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="<?php echo site_url('Inici/login');?>">Registre</a>
<a class="dropdown-item" href="<?php echo site_url('Inici/login');?>">Iniciar Sessió</a>
</div>
</li>
<li>
<div class="banderes">
<li class="nav-item flag">
<a href="<?php echo site_url('Inici/login');?>?idioma=spanish">
<img src="../../pics/espanya.jpg" class="flag" alt="españita">
</a>
</li>
<li class="nav-item">
<a href="<?php echo site_url('Inici/login');?>?idioma=english">
<img src="../../pics/catalunya.png" class="flag" alt="cat">
</a>
</li>
</div>
</li>
</ul>
</div>
</nav>
</header>
<main class="container-fluid">
<div>
<div class="register">
<div class="row">
<div class="col-md-3 col-12 order-2 order-md-1 especialito">
<?php echo $esquerra;?>
</div>
<div class="col-md-9 col-12 order-1 order-md-2">
<div class="row">
<div class="col-md-1 d-none d-sm-block"></div>
<div class="col-md-10 col-12">
<ul class="nav nav-tabs nav-justified" id="myTab" role="tablist">
<li class="nav-item">
<a class="nav-link active opcions" id="home-tab" data-toggle="tab" href="#home" role="tab" aria-controls="home" aria-selected="true">Usuari</a>
</li>
<li class="nav-item">
<a class="nav-link opcions" id="profile-tab" data-toggle="tab" href="#profile" role="tab" aria-controls="profile" aria-selected="false">Empresa</a>
</li>
</ul>
</div>
</div>
<div class="row">
<div class="tab-content col-md-12" id="myTabContent">
<div class="tab-pane fade show active" id="home" role="tabpanel" aria-labelledby="home-tab">
<h3 class="register-heading"><?php echo $lang->language['perfilUsuari'] ?></h3>
<div class="content" id="registre_usuari" role="tabpanel">
<div class="row register-form">
<div class="col-md-2 d-none d-sm-block"></div>
<div class="col-md-8 col-12">
<form method="post" action="<?php echo site_url('Inici/accio');?>" name="1">
<input type="hidden" name="accio" value="registre_client">
<div class="form-group">
<label for="user_registre_usuari"><?php echo $lang->language['identificador_login'];?> *</label>
<input type="text" class="form-control" name="username" id="user_registre_usuari" placeholder="<?php echo $lang->language['identificador_login'];?>" value="" />
</div>
<div class="form-group">
<label for="email_registre_usuari">
<?php echo $lang->language['mail'];?> *</label>
<input type="text" class="form-control" id="email_registre_usuari" name="email" placeholder="<?php echo $lang->language['mail'];?>" value="" />
</div>
<div class="form-group">
<label for="contrasenya_registre_usuari"><?php echo $lang->language['password'];?> *</label>
<input type="password" class="form-control inputMajus" name="password" id="contrasenya_registre_usuari" placeholder="<?php echo $lang->language['password'];?>" value="" /><br>
<input type="checkbox" name="mostrarPass" id="mostrarPass3"> <label for="mostrarPass3"><?php echo $lang->language['mostrarPass'];?></label><br>
<progress id='barra' min="0" max="5"></progress>
</div>
<div class="row">
<div class="col-md-4 col-1"></div>
<div class="col-md-4 col-10">
<input type="button" class="btnRegister" value="<?php echo $lang->language['botoRegister'];?>" />
</div>
<div class="col-md-4 col-1"></div>
</div>
</form>
</div>
<div class="col-md-2 d-none d-sm-block"></div>
</div>
</div>
<div class="content" id="login_usuari" role="tabpanel">
<div class="row register-form">
<div class="col-md-2 d-none d-sm-block"></div>
<div class="col-md-8 col-12">
<form method="post" action="<?php echo site_url('Inici/accio');?>" name="0">
<input type="hidden" name="accio" value="login_client">
<div class="form-group">
<label for="user_login_empresa"><?php echo $lang->language['identificador_login'];?> *</label>
<input type="text" class="form-control" name="username" id="user_login_empresa" placeholder="<?php echo $lang->language['identificador_login'];?>" value="" />
</div>
<div class="form-group">
<label for="pass_login_empresa"><?php echo $lang->language['password'];?> *</label>
<input type="password" class="form-control inputMajus" id="pass_login_empresa" name="password" placeholder="<?php echo $lang->language['password'];?>" value="" />
<br>
<input type="checkbox" name="mostrarPass" id="mostrarPass2"> <label for="mostrarPass2"> <?php echo $lang->language['mostrarPass'];?></label><br>
</div>
<div class="row">
<div class="col-md-4 d-sm-block d-none"></div>
<div class="col-md-4 col-12">
<input type="button" class="btnRegister" value="<?php echo $lang->language['botoLogin'];?>" />
</div>
<div class="col-md-4 d-sm-block d-none"></div>
</div>
</form>
</div>
<div class="col-md-2 d-none d-sm-block"></div>
</div>
</div>
</div>
<div class="tab-pane fade show" id="profile" role="tabpanel" >
<h3 class="register-heading">Perfil Empresa</h3>
<div class="content" id="registre_empresa" role="tabpanel" >
<form method="post" action="<?php echo site_url('Inici/accio');?>" name="2">
<input type="hidden" name="accio" value="registre_empresa">
<div class="row register-form">
<div class="col-md-6">
<div class="form-group">
<label for="user_registre_empresa"><?php echo $lang->language['identificador'];?> *</label>
<input type="text" class="form-control" id="user_registre_empresa" name="username" placeholder="<?php echo $lang->language['identificador'];?>" />
</div>
<div class="form-group">
<label for="pass_registre_empresa"><?php echo $lang->language['password'];?> *</label>
<input type="password" class="form-control inputMajus" id="pass_registre_empresa" name="password" placeholder="<?php echo $lang->language['password'];?>" value="" /><br>
<input type="checkbox" name="mostrarPass" id="mostrarPass"> <label for="mostrarPass"> <?php echo $lang->language['mostrarPass'];?></label><br>
<progress id='barra' min="0" max="5"></progress>
</div>
<div class="form-group">
<label for="mail_registre_empresa"><?php echo $lang->language['mail'];?> *</label>
<input type="email" class="form-control" name="email" id="mail_registre_empresa" placeholder="<?php echo $lang->language['mail'];?>" value="" />
</div>
<div class="form-group">
<label for="nom_comercial"><?php echo $lang->language['nomComercial'];?> *</label>
<input type="text" class="form-control" name="nom" id="nom_comercial" placeholder="<?php echo $lang->language['nomComercial'];?>" />
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="tipusVia"><?php echo $lang->language['tipusVia'];?> *</label>
<select class="form-control" name="tipusVia" id="tipusVia">
<option class="hidden" selected disabled><?php echo $lang->language['tipusVia'];?></option>
<option value="Avinguda"><?php echo $lang->language['avinguda'];?></option>
<option value="Carrer"><?php echo $lang->language['carrer'];?></option>
<option value="Via">Via</option>
</select>
</div>
<div class="form-group">
<label for="direccio"><?php echo $lang->language['nomVia'];?> *</label>
<input type="text" class="form-control" name="direccio" id="direccio" placeholder="<?php echo $lang->language['nomVia'];?>" />
</div>
<div class="form-group">
<label for="num"> Número *</label>
<input type="number" class="form-control" name="numDireccio" id="num" placeholder="Número" value="" />
</div>
<div class="form-group">
<label for="comarca"><?php echo $lang->language['poblacio'];?> *</label>
<select class="form-control" id="comarca" name="comarca">
</select>
</div>
<div class="form-group">
<div class="col-md-8">
<input type="button" class="btnRegister" value="<?php echo $lang->language['botoRegister'];?>" name="registre_emp" />
</div>
</div>
</div>
</div>
</form>
</div>
<div class="content" id="login_empresa" role="tabpanel">
<div class="row register-form center">
<div class="col-md-2"></div>
<div class="col-md-8">
<form method="post" action="<?php echo site_url('Inici/accio');?>" name="0">
<input type="hidden" name="accio" value="login_empresa">
<div class="form-group">
<label for="id_emp"><?php echo $lang->language['identificador_login'];?> *</label>
<input type="text" class="form-control" id="id_emp" name="username" placeholder="<?php echo $lang->language['identificador_login'];?>" />
</div>
<div class="form-group">
<label for="contrasenya_emp"><?php echo $lang->language['password'];?> *</label>
<input type="password" class="form-control inputMajus" id="contrasenya_emp" name="password" placeholder="<?php echo $lang->language['password'];?>" value="" /><br>
<input type="checkbox" name="mostrarPass" id="mostrarPass1"> <label for="mostrarPass1"><?php echo $lang->language['mostrarPass'];?></label><br>
</div>
<div class="row">
<div class="col-md-4 col-1"></div>
<div class="col-md-4 col-10">
<input type="button" class="btnRegister" value="<?php echo $lang->language['botoLogin'];?>" /><br />
</div>
<div class="col-md-4 col-1"></div>
</div>
</form>
</div>
<div class="col-md-2"></div>
</div>
</div>
</div>
</div>
</div>
<div class="row pestanya">
<div class="col-md-12 col-12">
<ul class="nav nav-tabs nav-justified" id="tabEmpresa" role="tablist">
<li class="nav-item">
<a class="nav-link active opcio_inici" id="login_empresa-tab" data-toggle="tab" href="#login_usuari" role="tab" aria-controls="home" aria-selected="true">Iniciar sessió</a>
</li>
<li class="nav-item">
<a class="nav-link opcio_inici" id="registre_empresa-tab" data-toggle="tab" href="#registre_usuari" role="tab" aria-controls="profile" aria-selected="false">Registrar-se</a>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
</main>
</body>
</html>
<file_sep>/M7/projecte_kevin/application/views/valoracio.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
include 'items.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Valoració</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="<?php echo base_url();?>/js/script_valoracio.js"></script>
<link href='https://fonts.googleapis.com/css?family=Cabin+Condensed:700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="<?php echo base_url();?>/css/base.css">
</head>
<body>
<header>
<?php echo $barra_client;?>
</header>
<main>
<div class="container-fluid">
<br><br>
<div class="row">
<div class="col-md-2 col-1"></div>
<div class="col-md-8 col-10 nota desactivat">
<form method='post' action="<?php site_url('Cliente/valorar')?>">
<input type="hidden" name="cata" value="<?php echo $valoracio['cata'];?>">
<input type="hidden" name="valoracio" id="hidden_valoracio" value="<?php echo $valoracio['valoracio']==0?"0":$valoracio['valoracio'];?>"/>
<input type="hidden" name="client" value="<?php echo $valoracio['client'];?>">
<div class="row">
<div class="col-md-2 d-sm-block d-none"></div>
<div class="col-md-8 col-12"><h1><?php echo $valoracio['nom'];?></h1><h2>Valora la teva experiència del dia <?php $newDate = date("d/m/Y H:i", strtotime($valoracio['data'])); echo $newDate; ?></h2></div>
<div class="col-md-2 d-sm-block d-none"></div>
</div>
<br>
<div class="row">
<div class="col-md-1 d-none"></div>
<div class="formulari_element col-md-10 col-12 text-center">
<label for="comentari">A <b><?php echo $valoracio['empresa'];?></b> els agradaria conèixer la teva opinió:</label><br><br>
<div class="row">
<div class="col-md-3 col-1"></div>
<div class="col-md-6 col-12">
<textarea id="comentari" rows="4" cols="50"></textarea><br>
</div>
<div class="col-md-3 d-none col-1"></div>
</div>
<label for="hidden_valoracio">Puntua la cata</label>
<p class="estrelles">
<?php
for($i=1;$i<6;$i++){
echo "<span name='".$i."' class='estrella'>★</span>";
}
?>
</p>
<input type="submit" value="Puntuar">
</div>
<div class="col-md-1 d-none"></div>
</div>
</form>
<div class="row">
<div class="col-md-3 col-1 d-md-block"></div>
<div class="col-md-6 col-10">
<?php if(isset($info)){echo "<p>Resultat de l'operació: ".$info."</p>";}?>
</div>
<div class="col-md-3 col-1 d-md-block"></div>
</div>
</div>
<div class="col-md-2 col-1"></div>
</div>
</div>
</main>
<!-- Footer -->
<footer class="page-footer">
<!-- Copyright -->
<div class="footer-copyright text-center">© 2019 Copyright --
BrisingrGaunt Productions
</div>
<!-- Copyright -->
</footer>
<!-- Footer -->
</body>
</html>
<file_sep>/M8/doxygen_java_m3/html/search/classes_2.js
var searchData=
[
['gestio',['Gestio',['../class_gestio_empreses_1_1_gestio.html',1,'GestioEmpreses']]],
['gestio_5fempreses',['Gestio_empreses',['../class_main_1_1_gestio__empreses.html',1,'Main']]]
];
<file_sep>/M7/projecte_kevin/application/views/visualitzar_valoracions.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
include 'items.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Visualitzar cata</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link href='https://fonts.googleapis.com/css?family=Cabin+Condensed:700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="<?php echo base_url();?>/css/estilo.css">
<link rel="stylesheet" href="<?php echo base_url();?>/css/base.css">
<link rel="stylesheet" href="<?php echo base_url();?>/css/generic.css">
</head>
<body>
<header>
<?php echo $barra_empresa;?>
</header>
<main class="container-fluid">
<div class="row">
<div class="col-md-3 col-12 order-2 order-md-1">
<?php echo $esquerra;?>
</div>
<div class="col-md-9 principal order-md-2 order-1">
<div class="row">
<?php
if(isset($info_cata_individual) && sizeof($info_cata_individual)>0){
?>
<div class="col-md-2 d-none d-sm-block"></div>
<div class="col-md-8 col-12">
<?php
$cata=$info_cata_individual[0]['cata'];
echo "<div class='valoracio'><h1>Valoració de la cata # ".$cata."</h1>";
$aux=1;
foreach($info_cata_individual as $i){
if($cata!=$i['cata']){
echo "</table></div><div class='valoracio'><h1>Valoració de la cata # ".$i['cata']."</h1>";
$aux=1;
}
if($aux==1){
?>
<h2 class="visualitzacio">Producte: <span><?php echo $i['nom'];?></span></h2>
<h2 class="visualitzacio">Data: <span><?php $newDate = date("d/m/Y H:i", strtotime($i['data'])); echo $newDate;?></span></h2>
<h2 class="visualitzacio">Adreça: <span><?php echo $info_empresa['tipusVia']." ".$info_empresa['direccio'].", ".$info_empresa['numDireccio']." (".$info_empresa['comarca'].")";?></span></h2>
<h2 class="visualitzacio">Estat: <span><?php $cadena=""; $i['estat']==0?$cadena="Oberta":$cadena="Finalitzada"; echo $cadena;?></span></h2>
<h2>Participants</h2>
<table class="valoracions" colspan="3">
<th> </th>
<th>Usuari</th>
<th>Valoració</th>
<?php
}
echo "<tr><td>".$aux."</td><td>".$i['username']."</td><td>";
if($i['estat']=="1"){
echo "<p class='estrelles'>";
for($j=0;$j<$i['valoracio'];$j++){
echo "★";
}
echo "<span class='estrelles'>";
for($j=$i['valoracio'];$j<5;$j++){
echo "✩";
}
echo "</span></p>";
}
else{
echo "<p>Pròximament</p>";
}
echo "</td></tr>";
$aux++;
$cata=$i['cata'];
}
?>
</table></div>
<?php }else{
echo "<h1>No tens events disponibles o no hi ha cap usuari interesat</h1>";
} ?>
<div class="col-md-2 d-none d-sm-block"></div>
</div>
</div>
</div>
</main>
<!-- Footer -->
<footer class="page-footer font-small">
<!-- Copyright -->
<div class="footer-copyright text-center">© 2019 Copyright --
BrisingrGaunt Productions
</div>
<!-- Copyright -->
</footer>
</body>
</html>
<file_sep>/M7/projecte_kevin/application/models/cata.php
<?php
class Cata extends CI_Model {
public function getAllFiltre($filtre){
$this->db->select('p.nom,p.descripcio, c.data, c.estat, c.id, p.codi');
$this->db->from('cata c');
$this->db->join('producte p', 'p.codi = c.producte');
$this->db->where($filtre);
$query=$this->db->get();
if($query->num_rows()==0){
return 0;
}
return $query->result_array();
}
public function getAllDetallat(){
$this->db->select('p.nom,p.descripcio, c.data, c.estat, c.id, p.codi, e.nom as empresa, e.direccio, e.numDireccio, e.comarca, e.tipusVia');
$this->db->from('cata c');
$this->db->join('producte p', 'p.codi = c.producte');
$this->db->join('empresa e','e.id=c.empresa');
$this->db->order_by('c.id','asc');
$query=$this->db->get();
return $query->result_array();
}
public function programar_cata($dades){
// comprovem que la cata sigui programada en el futur
if($dades['data']<date('Y-m-d H:i')){
return "No es pot programar una cata en un dia anterior a l'actual";
}
// comprovem que no existeixi una cata igual
$query=$this->db->get_where('cata',$dades);
if($query->num_rows()!=0){
return "Aquesta cata ja està programada.";
}
$this->db->insert('cata',$dades);
return "Nova cata afegida";
}
public function eliminar($filtre){
$this->load->model('participacio');
// Ens quedem amb l'id de la cata
$id=$filtre[1];
$filtre_participacio=array('pa.cata'=>$id);
//busquem les participacions que té aquesta cata
$registres=$this->participacio->getValoracionsUna($filtre_participacio);
if($registres==0){
return 0;
}
// eliminem les participacions
$this->db->delete('participacio', array('cata' => $id));
// eliminem les cates
$this->db->delete('cata', array('id' => $id));
return $registres;
}
public function modificar($dades){
//Primer es comprova que la data sigui major al temps actual:
if($dades['data']<date('Y-m-d H:i')){
return 1;
}
//Si tot correcte, s'actualitza la cata amb les noves dades recollides del post
$data = array(
'producte' => $dades['producte'],
'data' => $dades['data']
);
$this->db->where('id', $dades['id']);
$this->db->update('cata', $data);
//S'obtenen les dades dels usuaris apuntats a la cata
$this->db->select('p.nom, cl.username, c.data, pa.client');
$this->db->from('cata c');
$this->db->join('producte p','p.codi=c.producte');
$this->db->join('participacio pa','pa.cata=c.id');
$this->db->join('client cl','pa.client=cl.email');
$this->db->where('pa.cata',$dades['id']);
$resultat=$this->db->get();
if($resultat->num_rows()==0){
return 0;
}
return $resultat->result_array();
}
}
?>
|
6fd8af54a5ba4d535e2c31aeb7662c77431eaa19
|
[
"JavaScript",
"Java",
"PHP",
"SQL"
] | 39 |
PHP
|
BrisingrGaunt/Projecte_final
|
e66cb553034507e289ad42a60e05a13e2f9820b2
|
6f0d04aa687bd9a838bd0121ccb2acc9b63bd1b5
|
refs/heads/master
|
<repo_name>CA-DevTest/SV-as-Code-UnitTest<file_sep>/devtest-unit-test-java/src/main/java/com/ca/devtest/sv/devtools/utils/FreePortFinder.java
package com.ca.devtest.sv.devtools.utils;
import java.io.IOException;
import java.net.ServerSocket;
import java.util.concurrent.ThreadLocalRandom;
/**
* @author gaspa03
*
*/
public final class FreePortFinder {
/**
* @param from
* @param to
* @return available port in range
*/
public static int nextFreePort(int from, int to) {
int port = randomPort(from, to);
while (true) {
if (isLocalPortFree(port)) {
return port;
} else {
port = randomPort(from, to);
}
}
}
private static int randomPort(int from, int to) {
return ThreadLocalRandom.current().nextInt(from, to);
}
/**
* @param port
* @return true is port is available
*/
private static boolean isLocalPortFree(int port) {
try {
new ServerSocket(port).close();
return true;
} catch (IOException e) {
return false;
}
}
}
<file_sep>/devtest-unit-test-java/src/test/java/com/ca/devtest/sv/devtools/TransportProtocolBuilderTest.java
/**
*
*/
package com.ca.devtest.sv.devtools;
import org.junit.Test;
import com.ca.devtest.sv.devtools.protocol.TransportProtocolDefinition;
import com.ca.devtest.sv.devtools.protocol.builder.DataProtocolBuilder;
import com.ca.devtest.sv.devtools.protocol.builder.TransportProtocolBuilderImpl;
import com.ca.devtest.sv.devtools.type.DataProtocolType;
import com.ca.devtest.sv.devtools.type.TransportProtocolType;
/**
* @author gaspa03
*
*/
public class TransportProtocolBuilderTest {
/*private String SWEETDEV="com.ca.devtest.extension.protocol.sweetdev.SweetDevRRTransportProtocol";
@Test
public void buildHttpDoit() {
TransportProtocolDefinition tphDefinition= new TransportProtocolBuilderImpl(TransportProtocolType.HTTP.getType()).addParameter("listenPort", "8080").addParameter("basePath", "/cgi-bin/GatewayJavaDoIt.cgi").addParameter("targetHost", "localhost").addRequestDataProtocol(new DataProtocolBuilder(DataProtocolType.DOIT.getType())).addResponseDataProtocol(new DataProtocolBuilder(DataProtocolType.DOIT.getType())).build();
System.out.println(tphDefinition.toVrsContent());
}
@Test
public void buildJavaSweetDev() {
TransportProtocolDefinition tphDefinition= new TransportProtocolBuilderImpl(SWEETDEV).addParameter("TargetAgents", "localhost_demo_lisa").addParameter("TargetClasses", "com.ca.devtest.lisabank.demo.business.LisaBankService").build();
System.out.println(tphDefinition.toVrsContent());
}*/
}
<file_sep>/devtest-unit-test-java/src/test/java/com/ca/devtest/sv/devtools/VirtualServiceV3ClassScopeTest.java
package com.ca.devtest.sv.devtools;
import com.ca.devtest.sv.devtools.annotation.DevTestVirtualServer;
import com.ca.devtest.sv.devtools.annotation.v3.DevTestVirtualServiceV3;
import com.ca.devtest.sv.devtools.junit.VirtualServiceClassScopeRule;
import com.ca.devtest.sv.devtools.v3.HttpUtils;
import com.ca.devtest.sv.devtools.v3.ResponseParser;
import org.junit.Rule;
import org.junit.Test;
@DevTestVirtualServer(deployServiceToVse = "VSE",groupName="V3UpdateTest", protocol = "http")
@DevTestVirtualServiceV3(
serviceName = "vsV3_Verify",
port = "24778",
workingFolder = "v3/rrpair",
inputFile2 = "operation-8-req.txt",
inputFile1 = "operation-8-rsp.txt"
)
public class VirtualServiceV3ClassScopeTest {
@Rule
public VirtualServiceClassScopeRule rules = new VirtualServiceClassScopeRule();
@Test
public void vsV3_Verify1(){
ResponseParser op8Response = HttpUtils.GET(HttpUtils.URL_FORMAT, "http", "localhost",
"24778","import/test/operation-8");
assert (op8Response!=null);
assert (op8Response.getValue("$.TCEntry[0].termsType").equals("Operation 8 terms"));
}
@Test
public void vsV3_Verify2(){
ResponseParser op8Response = HttpUtils.GET(HttpUtils.URL_FORMAT, "http", "localhost",
"24778","import/test/operation-8");
assert (op8Response!=null);
assert (op8Response.getValue("$.TCEntry[0].termsType").equals("Operation 8 terms"));
}
}
<file_sep>/lisabank-demo/src/main/java/com/ca/devtest/utils/GenerateRRPairs.java
/**
*
*/
package com.ca.devtest.utils;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPathExpressionException;
import org.xml.sax.SAXException;
import com.ca.devtest.tools.rawtraffic.FromRawTrafficTestReferentialGenerator;
/**
* @author gaspa03
*
*/
public class GenerateRRPairs {
/**
* @param args
*/
public static void main(String[] args) {
try {
FromRawTrafficTestReferentialGenerator.generateRRPairFromRawFiles((GenerateRRPairs.class.getProtectionDomain().getCodeSource().getLocation().getPath()).replaceAll("%20", " ") + ".."
+ File.separatorChar + ".." + File.separatorChar + ".." + File.separatorChar
+ "lisabank-demo/src/test/resources/rawtraffic");
} catch (XPathExpressionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
<file_sep>/devtest-unit-test-java/src/main/java/com/ca/devtest/sv/devtools/annotation/v3/TransportProtocolConfig.java
package com.ca.devtest.sv.devtools.annotation.v3;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author sm632260
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE,ElementType.METHOD})
public @interface TransportProtocolConfig {
String typeId() default "HTTP";
boolean useGateway() default true;
boolean hostHeaderPassThrough() default false;
TargetEndpointConfig targetEndpoint() default @TargetEndpointConfig();
RecordingEndpointConfig recordingEndpoint() default @RecordingEndpointConfig();
}
<file_sep>/lisabank-demo/src/main/java/com/ca/devtest/lisabank/wsdl/EJB3UserControlBean.java
package com.ca.devtest.lisabank.wsdl;
import java.util.List;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.ws.RequestWrapper;
import javax.xml.ws.ResponseWrapper;
/**
* This class was generated by the JAX-WS RI.
* JAX-WS RI 2.2.9-b14002
* Generated source version: 2.2
*
*/
@WebService(name = "EJB3UserControlBean", targetNamespace = "http://ejb3.examples.itko.com/")
@XmlSeeAlso({
ObjectFactory.class
})
public interface EJB3UserControlBean {
/**
*
* @param addressObject
* @param username
* @return
* returns java.lang.String
*/
@WebMethod
@WebResult(targetNamespace = "")
@RequestWrapper(localName = "addAddress", targetNamespace = "http://ejb3.examples.itko.com/", className = "com.ca.devtest.lisabank.wsdl.AddAddress")
@ResponseWrapper(localName = "addAddressResponse", targetNamespace = "http://ejb3.examples.itko.com/", className = "com.ca.devtest.lisabank.wsdl.AddAddressResponse")
public String addAddress(
@WebParam(name = "username", targetNamespace = "")
String username,
@WebParam(name = "addressObject", targetNamespace = "")
Address addressObject);
/**
*
* @param <PASSWORD>
* @param username
* @return
* returns com.ca.devtest.lisabank.wsdl.User
*/
@WebMethod
@WebResult(targetNamespace = "")
@RequestWrapper(localName = "addUser", targetNamespace = "http://ejb3.examples.itko.com/", className = "com.ca.devtest.lisabank.wsdl.AddUser")
@ResponseWrapper(localName = "addUserResponse", targetNamespace = "http://ejb3.examples.itko.com/", className = "com.ca.devtest.lisabank.wsdl.AddUserResponse")
public User addUser(
@WebParam(name = "username", targetNamespace = "")
String username,
@WebParam(name = "password", targetNamespace = "")
String password);
/**
*
* @param userObject
* @return
* returns com.ca.devtest.lisabank.wsdl.User
*/
@WebMethod
@WebResult(targetNamespace = "")
@RequestWrapper(localName = "addUserObject", targetNamespace = "http://ejb3.examples.itko.com/", className = "com.ca.devtest.lisabank.wsdl.AddUserObject")
@ResponseWrapper(localName = "addUserObjectResponse", targetNamespace = "http://ejb3.examples.itko.com/", className = "com.ca.devtest.lisabank.wsdl.AddUserObjectResponse")
public User addUserObject(
@WebParam(name = "userObject", targetNamespace = "")
User userObject);
/**
*
* @param username
* @param addressId
* @return
* returns boolean
*/
@WebMethod
@WebResult(targetNamespace = "")
@RequestWrapper(localName = "deleteAddress", targetNamespace = "http://ejb3.examples.itko.com/", className = "com.ca.devtest.lisabank.wsdl.DeleteAddress")
@ResponseWrapper(localName = "deleteAddressResponse", targetNamespace = "http://ejb3.examples.itko.com/", className = "com.ca.devtest.lisabank.wsdl.DeleteAddressResponse")
public boolean deleteAddress(
@WebParam(name = "username", targetNamespace = "")
String username,
@WebParam(name = "addressId", targetNamespace = "")
String addressId);
/**
*
* @return
* returns boolean
*/
@WebMethod
@WebResult(targetNamespace = "")
@RequestWrapper(localName = "deleteTestAccounts", targetNamespace = "http://ejb3.examples.itko.com/", className = "com.ca.devtest.lisabank.wsdl.DeleteTestAccounts")
@ResponseWrapper(localName = "deleteTestAccountsResponse", targetNamespace = "http://ejb3.examples.itko.com/", className = "com.ca.devtest.lisabank.wsdl.DeleteTestAccountsResponse")
public boolean deleteTestAccounts();
/**
*
* @param username
* @return
* returns boolean
*/
@WebMethod
@WebResult(targetNamespace = "")
@RequestWrapper(localName = "deleteUser", targetNamespace = "http://ejb3.examples.itko.com/", className = "com.ca.devtest.lisabank.wsdl.DeleteUser")
@ResponseWrapper(localName = "deleteUserResponse", targetNamespace = "http://ejb3.examples.itko.com/", className = "com.ca.devtest.lisabank.wsdl.DeleteUserResponse")
public boolean deleteUser(
@WebParam(name = "username", targetNamespace = "")
String username);
/**
*
* @param addressId
* @return
* returns com.ca.devtest.lisabank.wsdl.Address
*/
@WebMethod
@WebResult(targetNamespace = "")
@RequestWrapper(localName = "getAddress", targetNamespace = "http://ejb3.examples.itko.com/", className = "com.ca.devtest.lisabank.wsdl.GetAddress")
@ResponseWrapper(localName = "getAddressResponse", targetNamespace = "http://ejb3.examples.itko.com/", className = "com.ca.devtest.lisabank.wsdl.GetAddressResponse")
public Address getAddress(
@WebParam(name = "addressId", targetNamespace = "")
String addressId);
/**
*
* @param username
* @return
* returns com.ca.devtest.lisabank.wsdl.User
*/
@WebMethod
@WebResult(targetNamespace = "")
@RequestWrapper(localName = "getUser", targetNamespace = "http://ejb3.examples.itko.com/", className = "com.ca.devtest.lisabank.wsdl.GetUser")
@ResponseWrapper(localName = "getUserResponse", targetNamespace = "http://ejb3.examples.itko.com/", className = "com.ca.devtest.lisabank.wsdl.GetUserResponse")
public User getUser(
@WebParam(name = "username", targetNamespace = "")
String username);
/**
*
* @param username
* @return
* returns java.util.List<com.ca.devtest.lisabank.wsdl.Address>
*/
@WebMethod
@WebResult(targetNamespace = "")
@RequestWrapper(localName = "listAddresses", targetNamespace = "http://ejb3.examples.itko.com/", className = "com.ca.devtest.lisabank.wsdl.ListAddresses")
@ResponseWrapper(localName = "listAddressesResponse", targetNamespace = "http://ejb3.examples.itko.com/", className = "com.ca.devtest.lisabank.wsdl.ListAddressesResponse")
public List<Address> listAddresses(
@WebParam(name = "username", targetNamespace = "")
String username);
/**
*
* @return
* returns java.util.List<com.ca.devtest.lisabank.wsdl.User>
*/
@WebMethod
@WebResult(targetNamespace = "")
@RequestWrapper(localName = "listUsers", targetNamespace = "http://ejb3.examples.itko.com/", className = "com.ca.devtest.lisabank.wsdl.ListUsers")
@ResponseWrapper(localName = "listUsersResponse", targetNamespace = "http://ejb3.examples.itko.com/", className = "com.ca.devtest.lisabank.wsdl.ListUsersResponse")
public List<User> listUsers();
/**
*
* @param arg0
* @return
* returns java.lang.String
*/
@WebMethod
@WebResult(targetNamespace = "")
@RequestWrapper(localName = "ping", targetNamespace = "http://ejb3.examples.itko.com/", className = "com.ca.devtest.lisabank.wsdl.Ping")
@ResponseWrapper(localName = "pingResponse", targetNamespace = "http://ejb3.examples.itko.com/", className = "com.ca.devtest.lisabank.wsdl.PingResponse")
public String ping(
@WebParam(name = "arg0", targetNamespace = "")
String arg0);
/**
*
* @param username
* @return
* returns com.ca.devtest.lisabank.wsdl.User
*/
@WebMethod
@WebResult(targetNamespace = "")
@RequestWrapper(localName = "resetPassword", targetNamespace = "http://ejb3.examples.itko.com/", className = "com.ca.devtest.lisabank.wsdl.ResetPassword")
@ResponseWrapper(localName = "resetPasswordResponse", targetNamespace = "http://ejb3.examples.itko.com/", className = "com.ca.devtest.lisabank.wsdl.ResetPasswordResponse")
public User resetPassword(
@WebParam(name = "username", targetNamespace = "")
String username);
/**
*
* @param userObject
* @return
* returns com.ca.devtest.lisabank.wsdl.User
*/
@WebMethod
@WebResult(targetNamespace = "")
@RequestWrapper(localName = "updateUser", targetNamespace = "http://ejb3.examples.itko.com/", className = "com.ca.devtest.lisabank.wsdl.UpdateUser")
@ResponseWrapper(localName = "updateUserResponse", targetNamespace = "http://ejb3.examples.itko.com/", className = "com.ca.devtest.lisabank.wsdl.UpdateUserResponse")
public User updateUser(
@WebParam(name = "userObject", targetNamespace = "")
User userObject);
/**
*
* @param <PASSWORD>
* @param username
* @return
* returns boolean
*/
@WebMethod
@WebResult(targetNamespace = "")
@RequestWrapper(localName = "validate", targetNamespace = "http://ejb3.examples.itko.com/", className = "com.ca.devtest.lisabank.wsdl.Validate")
@ResponseWrapper(localName = "validateResponse", targetNamespace = "http://ejb3.examples.itko.com/", className = "com.ca.devtest.lisabank.wsdl.ValidateResponse")
public boolean validate(
@WebParam(name = "username", targetNamespace = "")
String username,
@WebParam(name = "password", targetNamespace = "")
String password);
}
<file_sep>/devtest-unit-test-java/src/main/java/com/ca/devtest/sv/devtools/annotation/VirtualServiceType.java
package com.ca.devtest.sv.devtools.annotation;
public enum VirtualServiceType {
// Objets directement construits
RRPAIRS(Constants.DCM_API_RRPAIRS, Constants.DCM_API_RRPAIRS_URL),
VSM(Constants.DCM_API_VSM, Constants.DCM_API_VSM_URL);
private String type = "";
private String urlPattern = "";
// Constructeur
VirtualServiceType(String type, String url) {
this.type = type;
this.urlPattern = url;
}
/**
* @return url pattern
*/
public String geturlPattern(){
return urlPattern;
}
public String getType() { return type;}
public String toString() {
return type;
}
}
<file_sep>/devtest-unit-test-java/src/main/java/com/ca/devtest/sv/devtools/services/v3/VirtualServiceV3.java
package com.ca.devtest.sv.devtools.services.v3;
import com.ca.devtest.sv.devtools.VirtualServiceEnvironment;
import com.ca.devtest.sv.devtools.services.AbstractVirtualService;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* @author sm632260
*
*/
public class VirtualServiceV3 extends AbstractVirtualService {
List<File> updatedTempFiles;
String config;
String inputFile1;
String inputFile2;
String dataFile;
String activeConfig;
String swaggerurl;
String ramlurl;
String wadlurl;
public VirtualServiceV3(String name, String type, String url, VirtualServiceEnvironment vse) {
super(name,type, url, vse);
updatedTempFiles = new ArrayList<>();
}
public String getConfig() {
return config;
}
public void setConfig(String config) {
this.config = config;
}
public String getInputFile1() {
return inputFile1;
}
public void setInputFile1(String inputFile1) {
this.inputFile1 = inputFile1;
}
public String getInputFile2() {
return inputFile2;
}
public void setInputFile2(String inputFile2) {
this.inputFile2 = inputFile2;
}
public String getDataFile() {
return dataFile;
}
public void setDataFile(String dataFile) {
this.dataFile = dataFile;
}
public String getActiveConfig() {
return activeConfig;
}
public void setActiveConfig(String activeConfig) {
this.activeConfig = activeConfig;
}
public String getSwaggerurl() {
return swaggerurl;
}
public void setSwaggerurl(String swaggerurl) {
this.swaggerurl = swaggerurl;
}
public String getRamlurl() {
return ramlurl;
}
public void setRamlurl(String ramlurl) {
this.ramlurl = ramlurl;
}
public String getWadlurl() {
return wadlurl;
}
public void setWadlurl(String wadlurl) {
this.wadlurl = wadlurl;
}
public void addUpdatedFile(File updatedFile) {
this.updatedTempFiles.add(updatedFile);
}
public void clean(){
this.updatedTempFiles.forEach(file->{
file.deleteOnExit();
});
}
}
<file_sep>/devtest-unit-test-java/src/test/java/com/ca/devtest/sv/devtools/v3/HttpUtils.java
package com.ca.devtest.sv.devtools.v3;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.SSLContexts;
import javax.net.ssl.SSLContext;
import java.io.File;
import java.io.IOException;
import java.util.Properties;
public class HttpUtils {
public static final String URL_FORMAT = "%s://%s:%s/%s";
public static final String VS_DETAILS_URL = "%s://%s:%s/lisa-virtualize-invoke/api/v3/vses/%s/services/%s";
public static final String VS_SPECIFICS_URL = "%s://%s:%s/lisa-virtualize-invoke/api/v3/vses/%s/services/%s/specifics";
public static ResponseParser GET(String protocol, String url, String server, String port, String operation){
//HttpClient client = HttpClients.createDefault();
CloseableHttpClient client = HttpClients.
custom()
.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
.build();
HttpGet get = new HttpGet(String.format(protocol, url, server, port, operation));
get.addHeader("Accept", "application/json");
Properties props = System.getProperties();
props.setProperty("jdk.internal.httpclient.disableHostnameVerification", Boolean.TRUE.toString());
HttpResponse response = null;
try {
response = client.execute(get);
return getParser(response);
}catch(Exception e){
e.printStackTrace();
return null;
}
}
public static ResponseParser POST(String protocol, String url, String server, String port, String operation){
HttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost(String.format(protocol, url, server, port, operation));
post.addHeader("User-Agent", "SV-as-Code-Parser");
post.addHeader("Accept","application/json");
post.addHeader("Content-Type","application/json");
HttpResponse response = null;
try {
response = client.execute(post);
return getParser(response);
}catch(Exception e){
e.printStackTrace();
return null;
}
}
public static ResponseParser GET_VS_SPECIFICS(String protocol, String server, String port, String vse, String service){
return GET_VS_INFO(VS_SPECIFICS_URL,protocol, server, port, vse, service);
}
public static ResponseParser GET_VS_DETAILS(String protocol, String server, String port, String vse, String service) {
return GET_VS_INFO(VS_DETAILS_URL,protocol, server, port, vse, service);
}
private static ResponseParser GET_VS_INFO(String url, String protocol, String server, String port, String vse, String service){
int timeout = 300;
RequestConfig config = RequestConfig.custom().
setConnectTimeout(timeout * 1000).
setConnectionRequestTimeout(timeout * 1000).
setSocketTimeout(timeout * 1000).build();
CloseableHttpClient httpClient = HttpClientBuilder.create()
.setDefaultRequestConfig(config).build();
try {
if(protocol.equals("https")) {
SSLContextBuilder SSLBuilder = SSLContexts.custom();
File file = new File("/Applications/CA/DevTest/webserver.ks");
SSLBuilder = SSLBuilder.loadTrustMaterial(file, "changeit".toCharArray());
SSLContext sslContext = SSLBuilder.build();
SSLConnectionSocketFactory sslConSocFactory = new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier());
HttpClientBuilder clientbuilder = HttpClients.custom();
clientbuilder = clientbuilder.setSSLSocketFactory(sslConSocFactory);
httpClient = clientbuilder.setDefaultRequestConfig(config).build();
}
HttpGet get = new HttpGet(String.format(url, protocol, server, port, vse, service));
get.setConfig(config);
get.setHeader("Authorization", String.format("Basic %s",
new String(Base64.encodeBase64(("admin" + ":" + "admin").getBytes()))));
get.addHeader("Accept", "application/json");
HttpResponse response = httpClient.execute(get);
return getParser(response);
}catch(Exception e){
e.printStackTrace();
return null;
}finally {
try {
httpClient.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
public static ResponseParser getParser(HttpResponse response){
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
return null;
}
String contentType = response.getEntity().getContentType().getValue();
HttpEntity entity = response.getEntity();
if(contentType.contains(ContentType.APPLICATION_JSON.getMimeType())){
return new JsonResponseParser(entity);
}else if(contentType.contains(ContentType.APPLICATION_XML.getMimeType())){
return new XMLResponseParser(entity);
}else{
throw new RuntimeException("Content-Type is not supported "+response.getEntity().getContentType());
}
}
}
<file_sep>/devtest-unit-test-java/src/test/java/com/ca/devtest/sv/devtools/ExistingVS.java
package com.ca.devtest.sv.devtools;
import org.junit.Rule;
import org.junit.Test;
import com.ca.devtest.sv.devtools.annotation.DevTestVirtualServer;
import com.ca.devtest.sv.devtools.annotation.DevTestVirtualService;
import com.ca.devtest.sv.devtools.annotation.VirtualServiceType;
import com.ca.devtest.sv.devtools.junit.VirtualServicesRule;
@DevTestVirtualServer(groupName="Test")
public class ExistingVS {
@Rule
public VirtualServicesRule rules = new VirtualServicesRule();
@DevTestVirtualService(serviceName = "Proxy", type = VirtualServiceType.VSM, workingFolder = "mar/vsm/proto" )
@Test
public void deployExistingService() {
System.out.println("demo");
}
}
<file_sep>/devtest-unit-test-java/src/main/java/com/ca/devtest/sv/devtools/annotation/ProtocolType.java
package com.ca.devtest.sv.devtools.annotation;
/**
* @author gaspa03
*
*/
public interface ProtocolType {
//public String DPH_DOIT= "com.ca.devtest.dph.DoItDataHandler";
String DPH_SOAP = "com.itko.lisa.vse.stateful.protocol.ws.WSSOAPProtocolHandler";
String TPH_HTTP = "com.itko.lisa.vse.stateful.protocol.http.HttpProtocolHandler";
//public String TPH_SWEETDEV="com.ca.devtest.extension.protocol.sweetdev.SweetDevRRTransportProtocol";
String DPH_REST = "com.itko.lisa.vse.stateful.protocol.rest.RestDataProtocol";
String DPH_XML = "com.itko.lisa.vse.stateful.protocol.xml.XMLDataProtocol";
String DPH_JSON = "com.itko.lisa.vse.stateful.protocol.json.JSONDataProtocolHandler";
}<file_sep>/lisabank-demo/src/main/java/com/ca/devtest/lisabank/wsdl/DepositMoney.java
package com.ca.devtest.lisabank.wsdl;
import java.math.BigDecimal;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for depositMoney complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="depositMoney">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="accountId" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="amount" type="{http://www.w3.org/2001/XMLSchema}decimal" minOccurs="0"/>
* <element name="desc" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "depositMoney", propOrder = {
"accountId",
"amount",
"desc"
})
public class DepositMoney {
protected String accountId;
protected BigDecimal amount;
protected String desc;
/**
* Gets the value of the accountId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAccountId() {
return accountId;
}
/**
* Sets the value of the accountId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAccountId(String value) {
this.accountId = value;
}
/**
* Gets the value of the amount property.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getAmount() {
return amount;
}
/**
* Sets the value of the amount property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setAmount(BigDecimal value) {
this.amount = value;
}
/**
* Gets the value of the desc property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDesc() {
return desc;
}
/**
* Sets the value of the desc property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDesc(String value) {
this.desc = value;
}
}
<file_sep>/lisabank-demo/src/test/resources/application.properties
logging.level.org.apache.cxf=INFO
webservice.url.user=http://localhost:9081/itkoExamples/EJB3UserControlBean
webservice.url.account=http://localhost:9081/itkoExamples/EJB3AccountControlBean
webservice.url.token=http://localhost:9081/itkoExamples/TokenBean
webservice.url.lisaUser=http://localhost:9904/users
webservice.url.product=http://localhost:9956/product
webservice.url.storeInventory=http://localhost:19804/v2/store/inventory<file_sep>/devtest-unit-test-java/src/main/java/com/ca/devtest/sv/devtools/services/ExecutionModeType.java
/**
*
*/
package com.ca.devtest.sv.devtools.services;
/**
* @author gaspa03
*
*/
public enum ExecutionModeType {
EFFICIENT, LIVE, TRACK, STAND_IN, FAILOVER, DYNAMIC, LEARNING;
public static ExecutionModeType valueIgnoreCaseOf(String executionMode){
ExecutionModeType result=EFFICIENT;
if ((executionMode == null) || (executionMode.length() == 0)) {
return result;
}
for (ExecutionModeType mode : values()) {
if (mode.name().equalsIgnoreCase(executionMode)) {
result= mode;
break;
}
}
return result;
}
}
<file_sep>/devtest-unit-test-java/src/main/java/com/ca/devtest/sv/devtools/annotation/DevTestVirtualServicesFromVrs.java
/**
*
*/
package com.ca.devtest.sv.devtools.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author gaspa03
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE,ElementType.METHOD})
public @interface DevTestVirtualServicesFromVrs {
DevTestVirtualServiceFromVrs[] value() default{ } ;
}<file_sep>/devtest-unit-test-java/pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.ca.devtest.sv.devtools</groupId>
<artifactId>devtest-unit-test-java</artifactId>
<version>1.4.0</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<name>devtest-unit-test-java</name>
<packaging>jar</packaging>
<description>API to use SV as API with Junit
This API will cover same scope as WirMock or MokServer</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
<javadoc.opts>-Xdoclint:none</javadoc.opts>
<jarsigner.plugin.version>1.3.1</jarsigner.plugin.version>
</properties>
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.3</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-simple -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.36</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.5</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.3</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.10</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.7</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.7</version>
</dependency>
<dependency>
<groupId>org.aeonbits.owner</groupId>
<artifactId>owner</artifactId>
<version>1.0.12</version>
</dependency>
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>2.4.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
</dependency>
</dependencies>
<profiles>
<profile>
<id>build</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>3.0.1</version>
<executions>
<execution>
<id>attach-sources</id>
<phase>verify</phase>
<goals>
<goal>jar-no-fork</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.10.2</version>
<executions>
<execution>
<id>attach-javadocs</id>
<goals>
<goal>jar</goal>
</goals>
<configuration>
<nohelp>true</nohelp>
<notree>true</notree>
<quiet>true</quiet>
<additionalparam>${javadoc.opts}</additionalparam>
<excludePackageNames>com.ca.devtest.sv.devtools.annotation.processors</excludePackageNames>
<subpackages>com.ca.devtest.sv.devtools.annotation</subpackages>
<sourcepath>${project.basedir}/src/main/java</sourcepath>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>sign</id>
<build>
<plugins>
<!--
The property values for this plugin should be either passed in on the
command line (not really secure as the passwords will be easily
readable and recorded in the shell/CI invocation) or set in the maven
settings.xml file for the 'sign' profile.
-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jarsigner-plugin</artifactId>
<version>${jarsigner.plugin.version}</version>
<executions>
<execution>
<id>sign</id>
<goals>
<goal>sign</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project><file_sep>/lisabank-demo/src/test/java/com/ca/devtest/lisabank/demo/sv/vsm/ExistingVirtualServiceTestV3.java
package com.ca.devtest.lisabank.demo.sv.vsm;
import com.ca.devtest.lisabank.demo.LisaBankClientApplication;
import com.ca.devtest.lisabank.demo.business.BankService;
import com.ca.devtest.lisabank.wsdl.User;
import com.ca.devtest.sv.devtools.annotation.DevTestVirtualServer;
import com.ca.devtest.sv.devtools.annotation.DevTestVirtualService;
import com.ca.devtest.sv.devtools.annotation.Parameter;
import com.ca.devtest.sv.devtools.annotation.VirtualServiceType;
import com.ca.devtest.sv.devtools.annotation.v3.DevTestVirtualServiceV3;
import com.ca.devtest.sv.devtools.junit.VirtualServiceClassScopeRule;
import com.ca.devtest.sv.devtools.junit.VirtualServicesRule;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = LisaBankClientApplication.class)
@DevTestVirtualServer()
@DevTestVirtualServiceV3(serviceName = "Proxy",
port = "9081",
workingFolder = "vsm.lisabank.v3",
inputFile1 = "LisaBank.vsm",
inputFile2 = "LisaBank.vsi",
activeConfig = "project.config"
)
public class ExistingVirtualServiceTestV3 {
// handle VS with Class scope
@ClassRule
public static VirtualServiceClassScopeRule clazzRule = new VirtualServiceClassScopeRule();
@Rule
public VirtualServicesRule rules = new VirtualServicesRule();
static final Log logger = LogFactory.getLog(ExistingVirtualServiceTestV3.class);
@Autowired
private BankService bankServices;
@Test
public void getListUser() {
try {
User[] users = bankServices.getListUser();
assertNotNull(users);
printUsers(users);
assertEquals(9, users.length);
} finally {
}
}
private void printUsers(User[] users) {
for (User user : users) {
logger.info(user.getFname() + " " + user.getLname() + " " + user.getLogin());
}
}
}
<file_sep>/devtest-unit-test-java/src/test/java/com/ca/devtest/sv/devtools/VirtualServiceV3CreateTest.java
package com.ca.devtest.sv.devtools;
import com.ca.devtest.sv.devtools.annotation.DevTestVirtualServer;
import com.ca.devtest.sv.devtools.annotation.v3.*;
import com.ca.devtest.sv.devtools.application.SoapClient;
import com.ca.devtest.sv.devtools.junit.VirtualServicesRule;
import com.ca.devtest.sv.devtools.v3.HttpUtils;
import com.ca.devtest.sv.devtools.v3.ResponseParser;
import org.apache.commons.io.FileUtils;
import org.junit.Rule;
import org.junit.Test;
import java.io.File;
import java.net.URL;
/**
* @author sm632260
*
*/
@DevTestVirtualServer(deployServiceToVse = "VSE",groupName="V3Test")
public class VirtualServiceV3CreateTest {
@Rule
public VirtualServicesRule rules = new VirtualServicesRule();
String API_PROTOCOL = "http";
/**
* Create and deploy VS with RRPair and with default configuration
*/
@DevTestVirtualServiceV3(
serviceName = "vsV3_Deploy",
port = "24778",
workingFolder = "v3/rrpair",
inputFile2 = "operation-8-req.txt",
inputFile1 = "operation-8-rsp.txt"
)
@Test
public void vsV3_Deploy() throws InterruptedException {
ResponseParser responseParser = HttpUtils.GET(HttpUtils.URL_FORMAT, "http","localhost",
"24778", "import/test/operation-8");
ResponseParser vsResponseParser = HttpUtils.GET_VS_DETAILS(API_PROTOCOL,"localhost", "1505", "VSE", "V3Test.vsV3_Deploy");
//ResponseParser vsSpecificParser = HttpUtils.GET_VS_SPECIFICS(API_PROTOCOL, "localhost", "1505", "VSE", "V3Test.vsV3_Deploy");
assert (responseParser != null);
assert (responseParser.getValue("$.TCEntry[0].termsType").equals("Operation 8 terms"));
assert (vsResponseParser != null);
assert (vsResponseParser.getValue("$.modelName").equals("V3Test.vsV3_Deploy"));
assert (vsResponseParser.getValue("$.capacity").equals("1"));
assert (vsResponseParser.getValue("$.thinkScale").equals("100"));
assert (vsResponseParser.getValue("$.autoRestartEnabled").equals("true"));
assert (vsResponseParser.getValue("$.executionMode").equals("Most Efficient"));
assert (vsResponseParser.getValue("$.executionModeValue").equals("EFFICIENT"));
assert (vsResponseParser.getValue("$.resourceName").equals("24778 : http : : /"));
assert (vsResponseParser.getValue("$.groupTag").isEmpty());
assert (vsResponseParser.getValue("$.statusDescription").equals("running"));
//assert (vsSpecificParser != null);
//assert (vsSpecificParser.getValue("$.description").equals("Deployed using SV-as-Code"));
//assert (vsSpecificParser.getValue("$.deployedBy").equals("svpower"));
}
/***
* Create and deploy VS with RR pair and with custom configuration
*/
@DevTestVirtualServiceV3(
serviceName = "vsV3_RRPairCustomConfig",
port = "24779",
workingFolder = "v3/rrpair",
inputFile2 = "operation-8-req.txt",
inputFile1 = "operation-8-rsp.txt",
groupTag = "CustomConfig",
thinkScale = 200,
autoRestartEnabled = false
)
@Test
public void vsV3_RRPairCustomConfig() {
ResponseParser responseParser = HttpUtils.GET(HttpUtils.URL_FORMAT, "http", "localhost",
"24779", "import/test/operation-8");
ResponseParser vsResponseParser = HttpUtils.GET_VS_DETAILS(API_PROTOCOL,"localhost", "1505", "VSE", "V3Test.vsV3_RRPairCustomConfig");
assert (responseParser != null);
assert (responseParser.getValue("$.TCEntry[0].termsType").equals("Operation 8 terms"));
assert (vsResponseParser != null);
assert (vsResponseParser.getValue("$.modelName").equals("V3Test.vsV3_RRPairCustomConfig"));
assert (vsResponseParser.getValue("$.capacity").equals("1"));
assert (vsResponseParser.getValue("$.thinkScale").equals("200"));
assert (vsResponseParser.getValue("$.autoRestartEnabled").equals("false"));
assert (vsResponseParser.getValue("$.executionMode").equals("Most Efficient"));
assert (vsResponseParser.getValue("$.executionModeValue").equals("EFFICIENT"));
assert (vsResponseParser.getValue("$.configurationName").equals("project.config"));
assert (vsResponseParser.getValue("$.resourceName").equals("24779 : http : : /"));
assert (vsResponseParser.getValue("$.groupTag").equals("CustomConfig"));
assert (vsResponseParser.getValue("$.status").equals("2"));
assert (vsResponseParser.getValue("$.statusDescription").equals("running"));
assert (vsResponseParser.getValue("$.errorCount").equals("0"));
}
/**
* Create and Deploy VS with RRpair zip file
*/
@DevTestVirtualServiceV3(
serviceName = "vsV3_RRPairZip",
port = "24778",
workingFolder = "v3/rrpair",
inputFile2 = "Op8andOp9-RRPairs.zip"
)
@Test
public void vsV3_RRPairZip() {
ResponseParser op8Response = HttpUtils.GET(HttpUtils.URL_FORMAT, "http", "localhost",
"24778", "import/test/operation-8");
ResponseParser op9Response = HttpUtils.GET(HttpUtils.URL_FORMAT, "http", "localhost",
"24778", "import/test/operation-9");
assert (op8Response != null);
assert (op8Response.getValue("$.TCEntry[0].termsType").equals("Operation 8 terms"));
assert (op9Response != null);
assert (op9Response.getValue("$.TCEntry[0].termsType").equals("Operation 9 terms"));
}
/***
* Create and deploy VS with VSM and VSI files
*/
@DevTestVirtualServiceV3(
serviceName = "vsV3_VSMVSI",
port = "13712",
workingFolder = "v3/vsmvsi",
inputFile1 = "Op8AndOp9.vsi",
inputFile2 = "Op8AndOp9.vsm"
)
@Test
public void vsV3_VSMVSI() {
ResponseParser op8Response = HttpUtils.GET(HttpUtils.URL_FORMAT, "http", "localhost",
"13712", "import/test/operation-8");
ResponseParser op9Response = HttpUtils.GET(HttpUtils.URL_FORMAT, "http", "localhost",
"13712", "import/test/operation-9");
assert (op8Response != null);
assert (op8Response.getValue("$.TCEntry[0].termsType").equals("Operation 8 terms"));
assert (op9Response != null);
assert (op9Response.getValue("$.TCEntry[0].termsType").equals("Operation 9 terms"));
}
/***
* Create and deploy VS with VSM and VSI files and custom port
*/
@DevTestVirtualServiceV3(
serviceName = "vsV3_VSMVSI_CustomPort",
description = "Test Case vsV3_VSMVSI_CustomPort",
port = "24000",
workingFolder = "v3/vsmvsi_port_parameter",
inputFile1 = "Op8AndOp9.vsi",
inputFile2 = "Op8AndOp9.vsm"
)
@Test
public void vsV3_VSMVSI_CustomPort() {
ResponseParser op8Response = HttpUtils.GET(HttpUtils.URL_FORMAT, "http", "localhost",
"24000", "import/test/operation-8");
ResponseParser op9Response = HttpUtils.GET(HttpUtils.URL_FORMAT, "http", "localhost",
"24000", "import/test/operation-9");
assert (op8Response != null);
assert (op8Response.getValue("$.TCEntry[0].termsType").equals("Operation 8 terms"));
assert (op9Response != null);
assert (op9Response.getValue("$.TCEntry[0].termsType").equals("Operation 9 terms"));
}
/***
* Create and Deploy VS with swagger file
*/
@DevTestVirtualServiceV3(
serviceName = "vsV3_SwaggerFile",
port = "24778",
workingFolder = "v3/swagger",
inputFile1 = "swagger.json"
)
@Test
public void vsV3_SwaggerFile() {
ResponseParser responseParser = HttpUtils.GET(HttpUtils.URL_FORMAT, "http", "localhost",
"24778", "v2/store/inventory");
String value = responseParser.getValue("//root/integer_0");
assert (responseParser != null);
assert (value.equals("1"));
}
/***
* Create and deploy VS with Swagger url
*/
@DevTestVirtualServiceV3(
serviceName = "vsV3_SwaggerUrl",
port = "24778",
workingFolder = "v3/swagger",
swaggerurl = "https://petstore.swagger.io/v2/swagger.json"
)
@Test
public void vsV3_SwaggerUrl() {
ResponseParser responseParser = HttpUtils.GET(HttpUtils.URL_FORMAT, "http", "localhost",
"24778", "v2/store/inventory");
String value = responseParser.getValue("//root/integer_0");
String str = (new File("v3/swager", "swagger.json")).toURI().toString();
assert (responseParser != null);
assert (value.equals("1"));
}
/***
* Create and deploy VS with raml file
*/
@DevTestVirtualServiceV3(
serviceName = "vsV3_RAML",
port = "24778",
workingFolder = "v3/raml",
inputFile1 = "storage.raml"
)
@Test
public void vsV3_RAML() {
ResponseParser responseParser = HttpUtils.GET(HttpUtils.URL_FORMAT, "http", "localhost",
"24778", "organizations/S5RnX22D");
String value = responseParser.getValue("$.name");
assert (responseParser != null);
assert (value.equals("name: Acme"));
}
/***
* Create and deploy VS with raml file
*/
@DevTestVirtualServiceV3(
serviceName = "vsV3_RAMLUrl",
port = "24778",
workingFolder = "v3/raml",
ramlurl = "file:///Users/sachinmaske/Code/SV-as-Code/devtest-unit-test-java/src/test/resources/v3/raml/storage.raml"
)
@Test
public void vsV3_RAMLUrl() {
ResponseParser responseParser = HttpUtils.GET(HttpUtils.URL_FORMAT, "http", "localhost",
"24778", "organizations/S5RnX22D");
String value = responseParser.getValue("$.name");
assert (responseParser != null);
assert (value.equals("name: Acme"));
}
/**
* Create and deploy VS with wadl file
*/
@DevTestVirtualServiceV3(
serviceName = "vsV3_WADLFile",
port = "24778",
workingFolder = "v3/wadl",
inputFile1 = "os-services.wadl"
)
@Test
public void vsV3_WADLFile() {
ResponseParser responseParser = HttpUtils.GET(HttpUtils.URL_FORMAT, "http", "localhost",
"24778", "/v2/tenant_id/os-services");
String value = responseParser.getValue("$.Lang");
assert (responseParser != null);
assert (value != null && !value.isEmpty());
}
/**
* Create and deploy VS with wadl url
*/
@DevTestVirtualServiceV3(
serviceName = "vsV3_WADLUrl",
port = "24778",
workingFolder = "v3/wadl",
wadlurl = "http://rackerlabs.github.io/wadl2swagger/openstack/wadls/os-services.wadl"
)
@Test
public void vsV3_WADLUrl() {
ResponseParser responseParser = HttpUtils.GET(HttpUtils.URL_FORMAT, "http", "localhost",
"24778", "/v2/tenant_id/os-services");
String value = responseParser.getValue("$.Lang");
assert (responseParser != null);
assert (value != null && !value.isEmpty());
}
/***
* Create and Deploy VS with sidecars files
*/
@DevTestVirtualServiceV3(
serviceName = "vsV3_SideCars",
port = "13712",
workingFolder = "v3/sidecars",
inputFile1 = "rrpair-sidecars.zip"
)
@Test
public void vsV3_SideCars() throws InterruptedException {
ResponseParser responseParser = HttpUtils.GET(HttpUtils.URL_FORMAT, "http", "localhost",
"13712", "import/test/operation-8");
//ResponseParser vsResponseParser = HttpUtils.GET_VS_SPECIFICS(API_PROTOCOL, "localhost", "1505", "VSE", "V3Test.vsV3_SideCars");
assert (responseParser != null);
//assert (vsResponseParser.getValue("$.statelessTransactions[0].defaultResponses[0].thinkTime").equals("101"));
}
/***
* Create and Deploy VS with SOAP dph
*/
@DevTestVirtualServiceV3(
serviceName = "vsV3_RRPairSoap",
port = "24778",
workingFolder = "rrpairs/soap",
inputFile2 = "getUser-req.xml",
inputFile1 = "getUser-rsp.xml",
dataProtocolsConfig = {
@DataProtocolConfig(
typeId = "SOAPDPH",
forRequest = true
)
}
)
@Test
public void vsV3_RRPairSoap() throws Exception {
int port = 24778;
String path = "/";
SoapClient soapclient = new SoapClient("localhost", String.valueOf(port));
URL url = getClass().getClassLoader().getResource("rrpairs/soap/getUser-req.xml");
File requestFile = new File(getClass().getClassLoader().getResource("rrpairs/soap/getUser-req.xml").toURI());
String request = FileUtils.readFileToString(requestFile, "UTF-8");
String response = soapclient.callService(path, request);
assert (response.contains("<EMAIL>"));
}
/***
* Create and Deploy VS with SOAP Body and Header dph
*/
@DevTestVirtualServiceV3(
serviceName = "vsV3_RRPairMultipleDPH",
port = "24778",
workingFolder = "v3/soap_header_body",
inputFile2 = "getMovieInformation-req.xml",
inputFile1 = "getMovieInformation-rsp.xml",
dataProtocolsConfig = {
@DataProtocolConfig(
typeId = "SOAPDPH",
forRequest = true
),
@DataProtocolConfig(
typeId = "SOAPHEADERDPH",
forRequest = true
)
}
)
@Test
public void vsV3_RRPairMultipleDPH() throws Exception {
int port = 24778;
String path = "/";
SoapClient soapclient = new SoapClient("localhost", String.valueOf(port));
URL url = getClass().getClassLoader().getResource("v3/soap_header_body/getMovieInformation-req.xml");
File requestFile = new File(getClass().getClassLoader().getResource("v3/soap_header_body/getMovieInformation-req.xml").toURI());
String request = FileUtils.readFileToString(requestFile, "UTF-8");
String response = soapclient.callService(path, request);
assert(response.contains("Movie Id"));
assert(response.contains("Movie Name Goes Here"));
}
/**
* Create and deploy VS with custom target and recording endpoint.
*/
@DevTestVirtualServiceV3(
serviceName = "vsV3_RRPairConfigObject",
description = "Created with annotation provided for function vsV3_RRPairConfigObject",
port = "24778",
workingFolder = "v3/rrpair",
inputFile2 = "operation-8-req.txt",
inputFile1 = "operation-8-rsp.txt",
transportProtocolConfig = @TransportProtocolConfig(
typeId = "HTTP",
useGateway = false,
hostHeaderPassThrough = true,
targetEndpoint = @TargetEndpointConfig(
host = "livehost",
port = "8080",
useSSL = true
),
recordingEndpoint = @RecordingEndpointConfig(
host = "recordinghost",
useSSL = true
)
)
)
@Test
public void vsV3_RRPairConfigObject() {
ResponseParser responseParser = HttpUtils.GET(HttpUtils.URL_FORMAT, "http", "localhost",
"24778", "import/test/operation-8");
ResponseParser vsResponseParser = HttpUtils.GET_VS_DETAILS(API_PROTOCOL, "localhost", "1505", "VSE", "V3Test.vsV3_Deploy");
assert (responseParser != null);
assert (responseParser.getValue("$.TCEntry[0].termsType").equals("Operation 8 terms"));
}
/**
* Creat and Deploy multiple VS
*/
@DevTestVirtualServicesV3(
value = {@DevTestVirtualServiceV3(
serviceName = "vsV3_RRPair2VS1",
port = "24778",
workingFolder = "v3/rrpair",
inputFile2 = "operation-8-req.txt",
inputFile1 = "operation-8-rsp.txt"
),
@DevTestVirtualServiceV3(
port = "13712",
serviceName = "vsV3_RRPair2VS2",
workingFolder = "v3/rrpair",
inputFile2 = "operation-9-req.txt",
inputFile1 = "operation-9-rsp.txt"
)}
)
@Test
public void vsV3_RRPair2VS() {
ResponseParser op8Response = HttpUtils.GET(HttpUtils.URL_FORMAT, "http", "localhost",
"24778", "import/test/operation-8");
ResponseParser op9Response = HttpUtils.GET(HttpUtils.URL_FORMAT, "http", "localhost",
"13712", "import/test/operation-9");
assert (op8Response != null);
assert (op8Response.getValue("$.TCEntry[0].termsType").equals("Operation 8 terms"));
assert (op9Response != null);
assert (op9Response.getValue("$.TCEntry[0].termsType").equals("Operation 9 terms"));
}
/***
* Create VS with vsm, vsi, data and active config file
*/
@DevTestVirtualServiceV3(
serviceName = "vsV3_Data_Config_Create",
port = "8001",
workingFolder = "v3/activeconfig_data",
inputFile2 = "DataDriven.vsi",
inputFile1 = "DataDriven.vsm",
dataFile = "Data.xlsx",
activeConfig = "project.config"
)
@Test
public void vsV3_Data_Config_Create() {
ResponseParser op8Response = HttpUtils.GET(HttpUtils.URL_FORMAT, "http", "localhost",
"8001", "import/test/operation-8");
assert (op8Response != null);
assert (op8Response.getValue("$.Id").equals("1"));
assert (op8Response.getValue("$.Movie").equals("Avatar"));
assert (op8Response.getValue("$.LIVE_INVOCATION_SERVER").equals("localhost"));
assert (op8Response.getValue("$.LIVE_INVOCATION_PORT").equals("8080"));
}
@DevTestVirtualServiceV3(
serviceName = "vsV3_SSLConfig",
description = "Created with annotation provided for function vsV3_RRPairConfigObject",
port = "24778",
workingFolder = "v3/rrpair",
inputFile2 = "operation-8-req.txt",
inputFile1 = "operation-8-rsp.txt",
transportProtocolConfig = @TransportProtocolConfig(
typeId = "HTTP",
useGateway = false,
hostHeaderPassThrough = true,
recordingEndpoint = @RecordingEndpointConfig(
host = "recordinghost",
useSSL = true,
sslConfig = @SSLConfig (
keystorePassword = "<PASSWORD>",
keystoreFile = "/Applications/CA/DevTest/webreckeys.ks",
aliasPassword = "<PASSWORD>",
alias = "lisa"
)
)
)
)
@Test
public void vsV3_SSLConfig(){
//Before executing this test case extract certificate from webreckeys.ks and then add it to jre with following commands
//command to extract certificates
//keytool -export -alias lisa -keystore /Applications/CA/DevTest/webreckeys.ks -rfc -file webreckeys.cert
//command to import into jdk certificates
//sudo keytool -import -alias svdevtest -trustcacerts -keystore ./jre/lib/security/cacerts -file ~/webreckeys.cert
ResponseParser responseParser = HttpUtils.GET(HttpUtils.URL_FORMAT, "https", "localhost",
"24778","import/test/operation-8");
ResponseParser vsResponseParser = HttpUtils.GET_VS_DETAILS(API_PROTOCOL, "localhost", "1505", "VSE", "V3Test.vsV3_Deploy");
assert (responseParser!=null);
assert (responseParser.getValue("$.TCEntry[0].termsType").equals("Operation 8 terms"));
}
}
<file_sep>/devtest-unit-test-java/src/main/java/com/ca/devtest/sv/devtools/services/AbstractVirtualService.java
package com.ca.devtest.sv.devtools.services;
import com.ca.devtest.sv.devtools.VirtualServiceEnvironment;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
/**
* @author sm632260
*
*/
public abstract class AbstractVirtualService implements VirtualServiceInterface{
VirtualServiceEnvironment vse;
String url;
String type;
String name;
String deployedName;
public AbstractVirtualService(String name, String type, String url, VirtualServiceEnvironment vse){
if (name == null)
throw new IllegalArgumentException("Service Name cannot be null");
this.name = name;
this.vse = vse;
this.type = type;
this.url = url;
}
@Override
public String getType(){
return type;
}
@Override
public void setType(String type){
this.type=type;
}
@Override
public String getUrl(){
return url;
}
@Override
public void setUrl(String url){
this.url = url;
}
@Override
public VirtualServiceEnvironment getVse() {
return this.vse;
}
@Override
public String getName() {
return this.name;
}
@Override
public String getGroup() {
return vse.getGroup();
}
@Override
public void deploy() throws IOException, NoSuchAlgorithmException, KeyManagementException, CertificateException, KeyStoreException {
getVse().deployService(this);
}
@Override
public void unDeploy() throws IOException, CertificateException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
getVse().unDeployService(this);
}
@Override
public void exists() throws IOException, CertificateException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
getVse().exist(this);
}
@Override
public String getDeployedName() {
return deployedName;
}
@Override
public void setDeployedName(String deployedName) {
this.deployedName = deployedName;
}
}
<file_sep>/devtest-unit-test-java/src/main/java/com/ca/devtest/sv/devtools/annotation/DevTestVirtualServer.java
/**
*
*/
package com.ca.devtest.sv.devtools.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Specify DevTest registry to be used for deployement, with differents
* parameters. <br/>
*
* Attributes are :
* <ul>
* <li>registryHost : registry host (default is "localhost")</li>
* <li>deployServiceToVse : VSE name (default is "VSE")</li>
* <li>login : login used to connect to registry (default is "svpower")</li>
* <li>password : password used to connect to registry (default is
* "svpower")</li>
* <li>groupName : group name used to prefix virtual services</li>
* <li>protocol : protocol used to access API</li>
* </ul>
*
* @author gaspa03, bboulch
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface DevTestVirtualServer {
/**
* Registry server name. By default 'localhost'.
*
* @return registry server name.
*/
String registryHost() default "";
/**
* VSE name. By default 'VSE'.
*
* @return VSE name
*/
String deployServiceToVse() default "";
/**
* Devtest user. By default 'svpower'
*
* @return devtest user
*/
String login() default "";
/**
* Devtest password. By default '<PASSWORD>'
*
* @return devtest password
*/
String password() default "";
/**
* Group name used to prefix virtual services. Empty by default.
*
* @return group name used to prefix virtual services
*/
String groupName() default "";
/**
* Protocol to access API. By default 'http'
*
* @return protocol to access api
*/
String protocol() default "";
String keystore() default "";
String keystorePassword() default "";
}
<file_sep>/devtest-unit-test-java/src/test/java/Demo.java
import org.aeonbits.owner.ConfigFactory;
import org.junit.Test;
import com.ca.devtest.sv.devtools.SVasCodeConfig;
public class Demo {
@Test
public void test() {
SVasCodeConfig cfg = ConfigFactory
.create(SVasCodeConfig.class,System.getenv());
System.out.println(cfg.login());
}
}
<file_sep>/lisabank-demo/src/main/java/com/ca/devtest/lisabank/demo/business/BankService.java
package com.ca.devtest.lisabank.demo.business;
import java.util.List;
import com.ca.devtest.lisabank.wsdl.Account;
import com.ca.devtest.lisabank.wsdl.User;
public interface BankService {
Account createUserWithCheckingAccount(String username, String password, int amount);
/**
* @return List of Users without Admin User
*/
List<User> getListUserWithoutAdmin();
/**
* @return List of Users
*/
public User[] getListUser();
/**
* @param username
* @return
*/
public boolean deleteUser(String username);
}<file_sep>/lisabank-demo/src/test/java/com/ca/devtest/lisabank/demo/sv/rest/LisaUserServiceTest.java
package com.ca.devtest.lisabank.demo.sv.rest;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.util.List;
import com.ca.devtest.sv.devtools.annotation.v3.DevTestVirtualServiceV3;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.ca.devtest.lisabank.demo.LisaBankClientApplication;
import com.ca.devtest.lisabank.demo.business.LisaUserService;
import com.ca.devtest.lisabank.demo.model.LisaUser;
import com.ca.devtest.sv.devtools.annotation.DevTestVirtualServer;
import com.ca.devtest.sv.devtools.annotation.DevTestVirtualService;
import com.ca.devtest.sv.devtools.annotation.Protocol;
import com.ca.devtest.sv.devtools.annotation.ProtocolType;
import com.ca.devtest.sv.devtools.junit.VirtualServicesRule;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = LisaBankClientApplication.class)
@DevTestVirtualServer()
public class LisaUserServiceTest {
static final Log logger = LogFactory.getLog(LisaUserServiceTest.class);
@Autowired
private LisaUserService lisaUserService;
@Rule
public VirtualServicesRule rules = new VirtualServicesRule();
@DevTestVirtualService(serviceName = "getLisaUser",
basePath = "/",
port = 9904,
workingFolder = "rrpairs/rest",
requestDataProtocol = {
@Protocol(ProtocolType.DPH_REST) })
@Test
public void getLisaUser() {
List<LisaUser> users = lisaUserService.getListUsers();
assertNotNull(users);
printUsers(users);
assertEquals(1, users.size());
}
@DevTestVirtualServiceV3(serviceName = "getLisaUserV3",
basePath = "/",
port = "9904",
workingFolder = "rrpairs/rest",
inputFile1 = "1-req.txt",
inputFile2 = "1-rsp.txt"
)
@Test
public void getLisaUserV3() {
List<LisaUser> users = lisaUserService.getListUsers();
assertNotNull(users);
printUsers(users);
assertEquals(1, users.size());
}
private void printUsers(List<LisaUser> users) {
for (LisaUser user : users) {
logger.info(user.getFname() + " " + user.getLname() + " " + user.getLogin());
}
}
@DevTestVirtualService(serviceName = "getUserByJSON",
basePath = "/",
port = 9904,
workingFolder = "rrpairs/rest",
requestDataProtocol = {
@Protocol(ProtocolType.DPH_JSON) })
@Test
public void getUserByJSON() {
List<LisaUser> users = lisaUserService.getListUsers();
assertNotNull(users);
printUsers(users);
assertEquals(1, users.size());
}
@DevTestVirtualServiceV3(serviceName = "getUserByJSON",
basePath = "/",
port = "9904",
workingFolder = "rrpairs/rest",
inputFile1 = "1-req.txt",
inputFile2 = "1-rsp.txt"
)
@Test
public void getUserByJSONV3() {
List<LisaUser> users = lisaUserService.getListUsers();
assertNotNull(users);
printUsers(users);
assertEquals(1, users.size());
}
}
<file_sep>/devtest-unit-test-java/src/test/java/com/ca/devtest/sv/devtools/DevTesClientRRPairs.java
package com.ca.devtest.sv.devtools;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import com.ca.devtest.sv.devtools.annotation.v3.DevTestVirtualServiceV3;
import org.apache.commons.io.FileUtils;
import org.junit.Rule;
import org.junit.Test;
import com.ca.devtest.sv.devtools.annotation.Config;
import com.ca.devtest.sv.devtools.annotation.DevTestVirtualServer;
import com.ca.devtest.sv.devtools.annotation.DevTestVirtualService;
import com.ca.devtest.sv.devtools.annotation.DevTestVirtualServiceFromVrs;
import com.ca.devtest.sv.devtools.annotation.Parameter;
import com.ca.devtest.sv.devtools.annotation.Protocol;
import com.ca.devtest.sv.devtools.annotation.ProtocolType;
import com.ca.devtest.sv.devtools.application.SoapClient;
import com.ca.devtest.sv.devtools.junit.VirtualServicesRule;
/**
* @author gaspa03
*
*/
@DevTestVirtualServer(deployServiceToVse = "VSE")
public class DevTesClientRRPairs {
@Rule
public VirtualServicesRule rules = new VirtualServicesRule();
/**
* @throws IOException
* @throws URISyntaxException
*/
@DevTestVirtualService(serviceName = "lisa", port = 9001, basePath = "/lisa", workingFolder = "rrpairs/soap",
parameters = {
@Parameter(name = "port", value = "8999"),
@Parameter(name = "basePath", value = "/errorManagement") },
requestDataProtocol = {
@Protocol(ProtocolType.DPH_SOAP) })
@Test
public void createSoapService() throws IOException, URISyntaxException {
int port = 9001;
String path = "/lisa";
/* Test */
SoapClient soapclient = new SoapClient("localhost", String.valueOf(port));
URL url = getClass().getClassLoader().getResource("rrpairs/soap/getUser-req.xml");
File requestFile = new File(getClass().getClassLoader().getResource("rrpairs/soap/getUser-req.xml").toURI());
String request = FileUtils.readFileToString(requestFile, "UTF-8");
String response = soapclient.callService(path, request);
}
@DevTestVirtualServiceV3(serviceName = "lisa",
port = "9001",
basePath = "/lisa",
workingFolder = "rrpairs/soap",
inputFile2 = "getUser-req.xml",
inputFile1 = "getUser-rsp.xml"
)
@Test
public void createSoapServiceV3() throws IOException, URISyntaxException {
int port = 9001;
String path = "/lisa";
/* Test */
SoapClient soapclient = new SoapClient("localhost", String.valueOf(port));
URL url = getClass().getClassLoader().getResource("rrpairs/soap/getUser-req.xml");
File requestFile = new File(getClass().getClassLoader().getResource("rrpairs/soap/getUser-req.xml").toURI());
String request = FileUtils.readFileToString(requestFile, "UTF-8");
String response = soapclient.callService(path, request);
}
@DevTestVirtualServiceFromVrs(serviceName = "demo", workingFolder = "rrpairs/soapWithVrs", vrsConfig = @Config(value = "transport.vrs", parameters = {
@Parameter(name = "port", value = "9002"), @Parameter(name = "basePath", value = "/lisa") }))
@Test
public void createSoapServicFromVrs() throws IOException, URISyntaxException {
int port = 9002;
String path = "/lisa";
/* Test */
SoapClient soapclient = new SoapClient("localhost", String.valueOf(port));
URL url = getClass().getClassLoader().getResource("rrpairs/soap/getUser-req.xml");
File requestFile = new File(getClass().getClassLoader().getResource("rrpairs/soap/getUser-req.xml").toURI());
String request = FileUtils.readFileToString(requestFile, "UTF-8");
String response = soapclient.callService(path, request);
}
@DevTestVirtualServiceFromVrs(serviceName = "errorManagement", workingFolder = "rrpairs/errorManagement",
vrsConfig = @Config(value = "errorManagement.vrs", parameters = { @Parameter(name = "port", value = "8999"),
@Parameter(name = "basePath", value = "/errorManagement") }))
@Test
public void createErrorManagementSVFromVrs() throws IOException, URISyntaxException {
int port = 8999;
String path = "/errorManagement";
/* Test */
SoapClient soapclient = new SoapClient("localhost", String.valueOf(port));
URL url = getClass().getClassLoader().getResource("rrpairs/soap/getUser-req.xml");
File requestFile = new File(getClass().getClassLoader().getResource("rrpairs/soap/getUser-req.xml").toURI());
String request = FileUtils.readFileToString(requestFile, "UTF-8");
String response = soapclient.callService(path, request);
}
@DevTestVirtualServiceFromVrs(serviceName = "oms", workingFolder = "rrpairs/searchOrder", vrsConfig = @Config(value = "searchOrder-FinalV2.vrs", parameters = {
@Parameter(name = "port", value = "7002"), @Parameter(name = "basePath", value = "/") }))
@Test
public void createJsonServiceFromVrs() throws IOException, URISyntaxException {
int port = 7002;
String path = "/";
/* Test */
SoapClient soapclient = new SoapClient("localhost", String.valueOf(port));
File requestFile = new File(
getClass().getClassLoader().getResource("rrpairs/searchOrder/searchOrder-Final-1-req.xml").toURI());
String request = FileUtils.readFileToString(requestFile, "UTF-8");
String response = soapclient.callJSONService(path, request);
}
@DevTestVirtualServiceFromVrs(serviceName = "swagger", workingFolder = "rrpairs/swagger", vrsConfig = @Config(value = "swagger.vrs", parameters = {
@Parameter(name = "port", value = "8010"), @Parameter(name = "basePath", value = "/") }))
@Test
public void createSwaggerServiceFromVrs() throws IOException, URISyntaxException {
int port = 8010;
String path = "/";
/* Test */
SoapClient soapclient = new SoapClient("localhost", String.valueOf(port));
File requestFile = new File(
getClass().getClassLoader().getResource("rrpairs/searchOrder/searchOrder-Final-1-req.xml").toURI());
String request = FileUtils.readFileToString(requestFile, "UTF-8");
String response = soapclient.callJSONService(path, request);
}
}
<file_sep>/devtest-unit-test-java/src/main/java/com/ca/devtest/tools/rawtraffic/FromRawTrafficTestReferentialGenerator.java
package com.ca.devtest.tools.rawtraffic;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class FromRawTrafficTestReferentialGenerator {
private static final String RAWFILETEMPLATE_TEXT = "%s-%d-%s.txt";
private static final String RAWFILETEMPLATE_XML = "%s-%d-%s.xml";
private static final String TEMPLATE_META_LINE = "%s: %s\r\n";
private static final String METAFILETEMPLATE_XML = "%s-%d-%s.properties";
private static final String TEMPLATE_REPORT = "%s;%s";
private static final String TEMPLATE_SERVICE_CATALOGUE_COL_NAME = "SERVICENAME;ENDPOINT;RRPairs;port";
private static final String TEMPLATE_SERVICE_CATALOGUE = "%s;%s;%s;50000";
private static final String TEMPLATE_TEST_CATALOG_COL_NAME = "ServiceName;EndPoint;TargetServer;TargetPort;LisaPort;RRPairsFolder;RequestFile;ResponseFile";
private static final String TEMPLATE_TEST_CATALOG = "%s;%s;%s;%s;50000;%s;%s;%s";
private static final boolean GENERATE_META = false;
private static final String ROOTFOLDER = "rrpairs";
private static final XPath XPATH = XPathFactory.newInstance().newXPath();
private static final List<String> listofMetaToRejet = new ArrayList<String>();
static {
listofMetaToRejet.add("HTTP-Response-Code");
listofMetaToRejet.add("HTTP-Response-Code-Text");
listofMetaToRejet.add("Server");
listofMetaToRejet.add("Date");
listofMetaToRejet.add("X-Powered-By");
listofMetaToRejet.add("X-Requested-With");
listofMetaToRejet.add("Accept");
listofMetaToRejet.add("Host");
}
public static void main(String[] args)
throws XPathExpressionException, ParserConfigurationException, SAXException, IOException {
if (args.length == 0) {
System.err.println("please specify the raw traffic file location");
System.exit(1);
}
String rawFolder = args[0];
generateRRPairFromRawFiles(rawFolder);
}
/**
* @param args
* @throws ParserConfigurationException
* @throws SAXException
* @throws IOException
* @throws XPathExpressionException
*/
public static void generateRRPairFromRawFiles(String rawFileFolder)
throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {
File rawFolderFile = new File(rawFileFolder);
File[] files = rawFolderFile.listFiles();
List<String> auditList = new ArrayList<String>();
List<String> testCatalogList = new ArrayList<String>();
// list of service to build the CSV file for service generation
// the line will be serviceName;endpoints;directory of RRpairs;port
Set<String> listOfServices = new HashSet<String>();
for (File rawFile : files) {
if (rawFile.getName().contains(".xml"))
try {
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse(rawFile);
// XPath Query for showing all nodes value
XPathExpression expr = XPATH.compile("//transaction");
XPathExpression exprRequest = XPATH.compile("request/body/text()");
XPathExpression exprRequestmeta = XPATH.compile("request/metaData");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
XPathExpression itemResponseExpr = XPATH.compile("responses/response/body/text()");
XPathExpression exprResponsetmeta = XPATH.compile("responses/response/metaData");
NodeList nodes = (NodeList) result;
String reqorres = null;
int indice = 1;
String folderName = null;
File folderStore = null;
String audit = null;
String serviceCalatogeLine = null;
File requestFile = null;
File responseFile = null;
String testCalatogeLine = null;
String targetServer = null;
String scenarioName = rawFile.getName().replace(".xml", "");
String parameters = null;
String endpoint = null;
for (int i = 0; i < nodes.getLength(); i++) {
Node item = nodes.item(i);
Object request = exprRequest.evaluate(item, XPathConstants.NODESET);
Object response = itemResponseExpr.evaluate(item, XPathConstants.NODESET);
Node requestItem = ((NodeList) request).item(0);
folderName = getOperationName(item);
parameters = getParameters(item);
endpoint = parameters.length() > 0 ? folderName + "?" + parameters : folderName;
targetServer = getHost(item);
folderStore = new File(rawFile.getParentFile(), ROOTFOLDER + folderName);
folderStore.mkdirs();
Node requestMeta = (Node) exprRequestmeta.evaluate(item, XPathConstants.NODE);
reqorres = "req";
if (isBinary(requestItem)) {
writeBeforeDecodeBase64(requestItem, scenarioName, indice, reqorres, folderStore);
} else {
requestFile = writeBeforeDecodeXML(requestItem, requestMeta, scenarioName, indice, reqorres,
folderStore);
}
// treat meta-data of request
/*
* Object requestMeta = exprRequestmeta.evaluate(item,
* XPathConstants.NODESET); Node requestMetaItem =
* (Node) ((NodeList) requestMeta) .item(0);
* writeMetaData(requestMetaItem, scenarioName, indice,
* "meta-req", folderStore);
*/
// treat the response Node
Node itemResponse = ((NodeList) response).item(0);
// treat meta-data of response
Object responseMeta = exprResponsetmeta.evaluate(item, XPathConstants.NODESET);
Node responseMetaItem = ((NodeList) responseMeta).item(0);
reqorres = "rsp";
if (isBinary(itemResponse)) {
writeBeforeDecodeBase64(itemResponse, scenarioName, indice, reqorres, folderStore);
} else {
responseFile = writeBeforeDecodeXML(itemResponse, null, scenarioName, indice,
reqorres, folderStore);
}
// comming from meta-rsp
if (GENERATE_META)
writeMetaData(responseMetaItem, scenarioName, indice, "rsp-meta", folderStore);
// Add line in test catalogue
String requestFileName = folderName + "/" + requestFile.getName();
String responseFileName = folderName + "/" + responseFile.getName();
String[] infos = targetServer.split(":");
String server = infos[0];
String port = "80";
if (infos.length > 1) {
port = infos[1];
}
testCalatogeLine = String.format(TEMPLATE_TEST_CATALOG, folderStore.getName(), endpoint, server,
port, ROOTFOLDER, requestFileName, responseFileName);
testCatalogList.add(testCalatogeLine);
indice++;
}
// generate Test Catalog
generateTestCatalog(testCatalogList, rawFile.getParentFile());
} catch (Exception e) {
e.printStackTrace();
System.err.println("Error during handle raw file");
System.exit(1);
}
}
System.out.println("DONE...");
}
private static void generateTestCatalog(Collection<String> listOfServices, File inFolder) throws IOException {
Collection<String> lines = new ArrayList<String>();
lines.add(TEMPLATE_TEST_CATALOG_COL_NAME);
lines.addAll(listOfServices);
writeReport(lines, inFolder, ROOTFOLDER + "/testCatalog.csv");
}
private static void generateServiceCatalog(Set<String> listOfServices, File inFolder) throws IOException {
Collection<String> lines = new ArrayList<String>();
lines.add(TEMPLATE_SERVICE_CATALOGUE_COL_NAME);
lines.addAll(listOfServices);
writeReport(lines, inFolder, "sevicesCatalogue.csv");
}
private static File writeMetaData(Node metaItem, String scenarioName, int indice, String reqorres, File folderStore)
throws XPathExpressionException {
NodeList parameters = metaItem.getChildNodes();
StringBuilder metaProperties = new StringBuilder();
for (int i = 0; i < parameters.getLength(); i++) {
Node item = parameters.item(i);
String name = XPATH.evaluate("@name", item);
String value = XPATH.evaluate("text()", item);
if (!StringUtils.isBlank(name) && !listofMetaToRejet.contains(name.trim()))
metaProperties.append((String.format(TEMPLATE_META_LINE, name, value)));
}
return writeInFile(metaProperties.toString().getBytes(), indice, scenarioName, METAFILETEMPLATE_XML, reqorres,
folderStore);
}
/**
* @param item
* @param indice
* @param reqorres
* @param directory
*/
private static File writeBeforeDecodeBase64(Node item, String nameofScenario, int indice, String reqorres,
File directory) {
return writeInFile(Base64.decodeBase64(item.getNodeValue().getBytes()), indice, nameofScenario,
RAWFILETEMPLATE_TEXT, reqorres, directory);
}
/**
* @param item
* @param indice
* @param reqorres
* @param directory
* @throws XPathExpressionException
*/
private static File writeBeforeDecodeXML(Node item, Node metaData, String nameofScenario, int indice,
String reqorres, File directory) throws XPathExpressionException {
String content = "";
if( null!=item){
content=item.getNodeValue().replace(System.getProperty("line.separator"), "");
}
String message =null;
if(null!=metaData){
String header = handleMetaData(metaData);
message = String.format(header, content);
}else{
message =content;
}
return writeInFile(message.getBytes(), indice, nameofScenario,
RAWFILETEMPLATE_XML, reqorres, directory);
}
private static String handleMetaData(Node metaItem) throws XPathExpressionException {
NodeList parameters = metaItem.getChildNodes();
StringBuilder metaProperties = new StringBuilder(" ");
String method = "";
String uri = "";
String version = "";
String contentType = "";
for (int i = 0; i < parameters.getLength(); i++) {
Node item = parameters.item(i);
String name = XPATH.evaluate("@name", item);
String value = XPATH.evaluate("text()", item);
if (!StringUtils.isBlank(name)) {
if ("HTTP-Method".equals(name)) {
method = value;
continue;
}
if ("HTTP-URI".equals(name)) {
uri = value;
continue;
}
if ("HTTP-Version".equals(name)) {
version = value;
continue;
}
if ("Content-Type".equals(name)) {
contentType = value;
}
}
if (!StringUtils.isBlank(name) && !listofMetaToRejet.contains(name.trim()))
metaProperties.append((String.format(TEMPLATE_META_LINE, name, value)));
}
// analyse contentType to define right template
StringBuilder meta = new StringBuilder();
if(contentType.contains("x-www-form-urlencoded")){
meta.append(method).append(" ").append(uri).append("?%s ").append(version).append("\n")
.append(metaProperties);
}else{
meta.append(method).append(" ").append(uri).append(" ").append(version).append("\n")
.append(metaProperties).append("\n%s");
}
return meta.toString();
}
private static void writeReport(Collection<String> auditList, File parent, String fileName) throws IOException {
FileUtils.writeLines(new File(parent, fileName), auditList);
}
/**
* @param data
* @param indice
* @param reqorres
* @param directory
*/
private static File writeInFile(byte[] data, int indice, String scenarioName, String templateName, String reqorres,
File directory) {
String fileName = String.format(templateName, scenarioName, indice, reqorres);
System.out.println("Creating file :" + fileName);
OutputStream os = null;
File result = new File(directory, fileName);
try {
os = new FileOutputStream(result);
os.write(data);
os.flush();
} catch (Exception e) {
} finally {
try {
os.close();
} catch (Exception e2) {
}
}
return result;
}
/**
* @param item
* @return
* @throws XPathExpressionException
*/
private static boolean isBinary(Node item) throws XPathExpressionException {
// String value = XPATH.evaluate("//@binary", item);
// return null != value && Boolean.valueOf(value);
return false;
}
/**
* @param endpoint
* @return
*/
private static String getTransactionName(String endpoint) {
if (endpoint.startsWith("/")) {
endpoint = endpoint.substring(1);
}
if (endpoint.endsWith("/")) {
endpoint = endpoint.substring(0, endpoint.length() - 1);
}
endpoint = endpoint.replaceAll("/", "-");
return endpoint;
}
/**
* @param item
* @return
* @throws XPathExpressionException
*/
private static String getOperationName(Node requestNode) throws XPathExpressionException {
XPathExpression exprRequestmeta = XPATH.compile("request/metaData/parameter");
NodeList parameters = (NodeList) exprRequestmeta.evaluate(requestNode, XPathConstants.NODESET);
for (int i = 0; i < parameters.getLength(); i++) {
Node item = parameters.item(i);
String name = XPATH.evaluate("@name", item);
String value = XPATH.evaluate("text()", item);
if ("HTTP-URI".equalsIgnoreCase(name)) {
return value;
}
}
return null;
}
private static String getParameters(Node requestNode) throws XPathExpressionException {
XPathExpression exprRequestParameter = XPATH.compile("request/arguments/parameter");
NodeList parameters = (NodeList) exprRequestParameter.evaluate(requestNode, XPathConstants.NODESET);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < parameters.getLength(); i++) {
Node item = parameters.item(i);
String name = XPATH.evaluate("@name", item);
String value = XPATH.evaluate("text()", item);
if (sb.length() > 0) {
sb.append("&");
}
sb.append(name).append("=").append(value);
}
return sb.toString();
}
/**
* @param item
* @return
* @throws XPathExpressionException
*/
private static String getHost(final Node requestNode) throws XPathExpressionException {
XPathExpression exprRequestmeta = XPATH.compile("request/metaData/parameter");
NodeList parameters = (NodeList) exprRequestmeta.evaluate(requestNode, XPathConstants.NODESET);
for (int i = 0; i < parameters.getLength(); i++) {
Node item = parameters.item(i);
String name = XPATH.evaluate("@name", item);
String value = XPATH.evaluate("text()", item);
if ("Host".equalsIgnoreCase(name)) {
return value;
}
}
return null;
}
}
<file_sep>/devtest-unit-test-java/src/main/java/com/ca/devtest/sv/devtools/junit/VirtualServicesRule.java
/**
*
*/
package com.ca.devtest.sv.devtools.junit;
import java.io.IOException;
import java.lang.reflect.Method;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import com.ca.devtest.sv.devtools.services.VirtualServiceInterface;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ca.devtest.sv.devtools.annotation.DevTestVirtualServer;
import com.ca.devtest.sv.devtools.annotation.processor.DevTestVirtualServerAnnotationProcessor;
/**
* Extend JUnit behaviour for using virtual services. <br/>
*
* Allow virtual services to be deployed before test methods and undeployed after.
*
* @author gaspa03, bboulch
*
*/
public class VirtualServicesRule implements TestRule {
private static final Logger LOGGER = LoggerFactory.getLogger(VirtualServicesRule.class);
public VirtualServicesRule() {
}
/*
* (non-Javadoc)
*
* @see org.junit.rules.TestRule#apply(org.junit.runners.model.Statement,
* org.junit.runner.Description)
*/
public Statement apply(final Statement base, final Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
List<VirtualServiceInterface> deployedServices = new ArrayList<>();
boolean evaluate = true;
if (!clazzNeedVirtualServices(description.getTestClass())) {
LOGGER.info(description.getTestClass() + "is not annoted by DevTestVirtualServer");
base.evaluate();
} else {
List<VirtualServiceInterface> virtualServices = null;
try {
LOGGER.info("deploying VS for method " + description.getMethodName() + "......");
virtualServices = processMethodAnnotations(description);
deployedServices = deployVirtualServices(virtualServices);
} catch (RuntimeException e){
evaluate = false;
throw e;
}
try{
if(evaluate) {
base.evaluate();
}
}finally{
Thread.sleep(500);
LOGGER.info(".... undeploying VS for method " + description.getMethodName());
unDeployVirtualServices(deployedServices);
}
}
}
};
}
/**
* @param virtualServices list of virtual services to deploy
*/
private List<VirtualServiceInterface> deployVirtualServices(List<VirtualServiceInterface> virtualServices) throws
Exception {
List<VirtualServiceInterface> deployedVirtualServices = new ArrayList<>();
if (null != virtualServices) {
for (VirtualServiceInterface virtualService : virtualServices) {
LOGGER.debug("Deploy virtual service " + virtualService.getName() + ".....");
virtualService.deploy();
deployedVirtualServices.add(virtualService);
LOGGER.debug("Virtual service " + virtualService.getName() + " deployed!");
}
}
return deployedVirtualServices;
}
/**
*
* @param virtualServices list of virtual services to undeployy
*/
private void unDeployVirtualServices(Collection<VirtualServiceInterface> virtualServices) throws
Exception {
if (null != virtualServices) {
List<String> undeployedServices = new ArrayList<>();
for (VirtualServiceInterface virtualService : virtualServices) {
if(undeployedServices.contains(virtualService.getDeployedName())){
LOGGER.info("Virtual service is already undeployed "+virtualService.getName());
continue;
}
LOGGER.debug("unDeploy virtual service " + virtualService.getName() + ".....");
virtualService.unDeploy();
LOGGER.debug("Virtual service " + virtualService.getName() + " unDeployed!");
undeployedServices.add(virtualService.getDeployedName());
}
}
}
/**
* Find out SV annotation on method level
* @param description
* @throws SecurityException
* @throws NoSuchMethodException
*/
private List<VirtualServiceInterface> processMethodAnnotations(Description description) throws Exception {
List<VirtualServiceInterface> virtualServices = new ArrayList<VirtualServiceInterface>();
LOGGER.debug("Process annotation for method "+description.getMethodName());
Class<?> testClazz = description.getTestClass();
DevTestVirtualServerAnnotationProcessor devtestProcessor=new DevTestVirtualServerAnnotationProcessor(testClazz);
Method method = testClazz.getMethod(description.getMethodName());
virtualServices.addAll(devtestProcessor.process(method));
return virtualServices;
}
/**
* @param clazz
* @return
*/
private boolean clazzNeedVirtualServices(Class<?> clazz) {
return null != clazz.getAnnotation(DevTestVirtualServer.class);
}
@Override
/*
* Undeploy Virtual service with scope classes
* */
protected void finalize() throws Throwable {
super.finalize();
}
}
<file_sep>/devtest-unit-test-java/src/main/java/com/ca/devtest/sv/devtools/protocol/builder/DataProtocolBuilder.java
/**
*
*/
package com.ca.devtest.sv.devtools.protocol.builder;
import java.util.HashMap;
import java.util.Map;
import com.ca.devtest.sv.devtools.protocol.DataProtocolDefinition;
/**
* @author gaspa03
*
*/
public class DataProtocolBuilder implements ParamatrizedBuilder{
protected final String typebuilder ;
protected Map<String, String> parameters= new HashMap<String, String>();
public DataProtocolBuilder( String type) {
super();
this.typebuilder=type;
}
public void addKeyValue(String key, String value) {
parameters.put(key, value);
}
public DataProtocolBuilder addParameter(String key, String value) {
addKeyValue(key, value);
return this;
}
/**
* @return
*/
public DataProtocolDefinition build(){
DataProtocolDefinition baseProtocol = new DataProtocolDefinition(typebuilder);
baseProtocol.getParameters().putAll(parameters);
return baseProtocol;
}
}
<file_sep>/lisabank-demo/src/main/java/com/ca/devtest/lisabank/demo/business/HttpHeaderInterceptor.java
package com.ca.devtest.lisabank.demo.business;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.cxf.message.Message;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import com.ca.devtest.lisabank.wsdl.TokenBean;
public class HttpHeaderInterceptor extends AbstractPhaseInterceptor<Message> {
String token = null;
private TokenBean tokenService;
public HttpHeaderInterceptor(TokenBean tokenService) {
super(Phase.POST_LOGICAL);
this.tokenService=tokenService;
}
public void handleMessage(Message message) {
Map<String, List<String>> headers = new HashMap<String, List<String>>();
authenticate();
headers.put("Token", Arrays.asList(token));
message.put(Message.PROTOCOL_HEADERS, headers);
}
private void authenticate(){
//if(null==token)
//token=tokenService.getNewToken("gpaco", "gpaco");
}
}<file_sep>/devtest-unit-test-java/src/main/java/com/ca/devtest/sv/devtools/services/v3/ConfigObjectBuilder.java
package com.ca.devtest.sv.devtools.services.v3;
import com.ca.devtest.sv.devtools.annotation.v3.*;
import com.ca.devtest.sv.devtools.utils.ObjectMapperUtil;
/**
* @author sm632260
*
*/
public class ConfigObjectBuilder {
public static String buildConfigJSON(DevTestVirtualServiceV3 virtualService, String deployedName) throws Exception{
if(deployedName != null) {
return ObjectMapperUtil.objectToJSON(buildCreateConfig(virtualService, deployedName));
}else{
//currently update config of V3 update API have does not have many parameters hence
//return string instead of using java objects and converting it.
if(virtualService.overwriteTxns()) {
return "{\"virtualService\":{},\"transportProtocol\":{\"overwriteTxns\":true}}";
}else{
return "{\"virtualService\":{},\"transportProtocol\":{\"overwriteTxns\":false}}";
}
}
}
public static String convertToJson(Config config) throws Exception {
return ObjectMapperUtil.objectToJSON(config);
}
private static Config buildCreateConfig(DevTestVirtualServiceV3 virtualService, String deployedName){
VirtualService virtualServiceConfig = VirtualService.VirtualServiceBuilder.builder()
.withName(deployedName)
.withDescription(virtualService.description())
.withVerison(virtualService.version())
.withCapacity(virtualService.capacity())
.withAutoRestart(virtualService.autoRestartEnabled())
.withGroupTag(virtualService.groupTag())
.withStartOnDeploy(virtualService.startOnDeployEnabled())
.withStatus(virtualService.status())
.withThinkScale(virtualService.thinkScale())
.build();
TransportProtocol transportProtocolConfig = TransportProtocol.TransportProtocolBuilder.builder()
.withBasePath(virtualService.basePath())
.withHostHeaderPassThrough(virtualService.transportProtocolConfig().hostHeaderPassThrough())
.withUseGateway(virtualService.transportProtocolConfig().useGateway())
.withTypeId(virtualService.transportProtocolConfig().typeId())
.withRecordingEndpoint(buildRecordingEndpoint(virtualService))
.withTargetEndpoint(buildTargetEndpoint(virtualService.transportProtocolConfig().targetEndpoint()))
.build();
return Config.ConfigBuilder.builder()
.withVirtualService(virtualServiceConfig)
.withDataProtocols(buildDataProtocols(virtualService.dataProtocolsConfig()))
.withTransportProtocol(transportProtocolConfig)
.build();
}
private static DataProtocol[] buildDataProtocols(DataProtocolConfig[] dataProtocolsConfig){
DataProtocol[] dataProtocols = new DataProtocol[dataProtocolsConfig.length];
for(int index=0;index<dataProtocolsConfig.length;index++){
dataProtocols[index] = buildDataProtocol(dataProtocolsConfig[index]);
}
return dataProtocols;
}
private static DataProtocol buildDataProtocol(DataProtocolConfig dataProtocolConfig){
return DataProtocol.DataProtocolBuilder.builder()
.withTypeId(dataProtocolConfig.typeId())
.withForRequest(dataProtocolConfig.forRequest())
.build();
}
private static Endpoint buildTargetEndpoint(TargetEndpointConfig endpointConfig){
return Endpoint.EndpointBuilder.builder()
.withHost(endpointConfig.host())
.withPort(endpointConfig.port())
.withUseSSL(endpointConfig.useSSL())
.withSSLConfig(
SSLConfig.SSLConfigBuilder.builder()
.withAlias(endpointConfig.sslConfig().alias())
.withAliasPassword(endpointConfig.sslConfig().aliasPassword())
.withKeystoreFile(endpointConfig.sslConfig().keystoreFile())
.withKeystorePassword(endpointConfig.sslConfig().keystorePassword())
.build()
)
.build();
}
private static Endpoint buildRecordingEndpoint(DevTestVirtualServiceV3 virtualService){
RecordingEndpointConfig endpointConfig = virtualService.transportProtocolConfig().recordingEndpoint();
return Endpoint.EndpointBuilder.builder()
.withHost(endpointConfig.host())
.withPort(virtualService.port())
.withUseSSL(endpointConfig.useSSL())
.withSSLConfig(
SSLConfig.SSLConfigBuilder.builder()
.withAlias(endpointConfig.sslConfig().alias())
.withAliasPassword(endpointConfig.sslConfig().aliasPassword())
.withKeystoreFile(endpointConfig.sslConfig().keystoreFile())
.withKeystorePassword(endpointConfig.sslConfig().keystorePassword())
.build()
)
.build();
}
}
<file_sep>/devtest-unit-test-java/src/main/java/com/ca/devtest/sv/devtools/services/VirtualService.java
/**
*
*/
package com.ca.devtest.sv.devtools.services;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.io.IOUtils;
import com.ca.devtest.sv.devtools.VirtualServiceEnvironment;
import com.ca.devtest.sv.devtools.annotation.VirtualServiceType;
import com.ca.devtest.sv.devtools.utils.VelocityRender;
/**
* @author gaspa03
*
*/
public final class VirtualService extends AbstractVirtualService{
private File packedVirtualService=null;
private ExecutionMode executionMode=new ExecutionMode();
public VirtualService( String name, VirtualServiceEnvironment vse) {
super(name,VirtualServiceType.RRPAIRS.getType(),VirtualServiceType.RRPAIRS.geturlPattern(), vse);
this.type=VirtualServiceType.RRPAIRS.getType();
}
public VirtualService( String name, String type, String url,VirtualServiceEnvironment vse) {
super(name, type, url, vse);
this.name = name;
this.vse = vse;
}
/**
* @param packedVirtualService the packedVirtualService to set
*/
public void setPackedVirtualService(File packedVirtualService) {
this.packedVirtualService = packedVirtualService;
}
/**
* @return
*/
public File getPackedVirtualService() {
return packedVirtualService;
}
/**
* @return the mode
*/
public ExecutionMode getExecutionMode() {
return executionMode;
}
/**
* @param mode the mode to set
*/
public void setExecutionMode(ExecutionMode mode) {
this.executionMode = mode;
}
/**
* @return Payload to change Service Execution mode
* @throws IOException
*/
public String buildExcusionModePayload() throws IOException{
InputStream inputStreamContent =getClass().getClassLoader().getResourceAsStream("virtualize-put-message.xml");
Map<String, VirtualService> config = new HashMap<String,VirtualService>();
config.put("virtualService", this);
return VelocityRender.render(IOUtils.toString(inputStreamContent, Charset.defaultCharset()), config);
}
/**
* @throws IOException
*/
public void deploy() throws IOException, NoSuchAlgorithmException, KeyManagementException, CertificateException, KeyStoreException {
getVse().deployService(this);
getVse().changeExecutionMode(this);
}
/**
* @throws IOException
*/
public void unDeploy() throws IOException, CertificateException, NoSuchAlgorithmException, KeyStoreException,
KeyManagementException {
getVse().unDeployService(this);
}
public void clean(){
if(packedVirtualService!=null && packedVirtualService.exists()){
packedVirtualService.deleteOnExit();
}
}
}
<file_sep>/devtest-unit-test-java/src/main/java/com/ca/devtest/sv/devtools/type/DataProtocolType.java
/**
*
*/
package com.ca.devtest.sv.devtools.type;
/**
* @author gaspa03
*
*/
public enum DataProtocolType {
//DOIT("com.personalfinance.devtest.dph.DoItDataHandler"),
SOAP("com.itko.lisa.vse.stateful.protocol.ws.WSSOAPProtocolHandler"),
COPY_BOOK("com.itko.lisa.vse.stateful.protocol.copybook.CopybookDataProtocol"),
COPY_BOOK_RRPAIRS("com.ca.devtest.copybook.dph.CopybookRRPairsDatahandler"),
REST("com.itko.lisa.vse.stateful.protocol.rest.RestDataProtocol"),
XML("com.itko.lisa.vse.stateful.protocol.xml.XMLDataProtocol"),
JSON("com.itko.lisa.vse.stateful.protocol.json.JSONDataProtocol");
private String type="";
DataProtocolType(String type){
this.type=type;
}
public String getType(){
return type;
}
}
<file_sep>/lisabank-demo/src/test/java/com/ca/devtest/lisabank/demo/sv/http/BasicTest.java
package com.ca.devtest.lisabank.demo.sv.http;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import com.ca.devtest.sv.devtools.annotation.*;
import com.ca.devtest.sv.devtools.annotation.v3.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.ca.devtest.lisabank.demo.LisaBankClientApplication;
import com.ca.devtest.lisabank.demo.business.BankService;
import com.ca.devtest.lisabank.wsdl.User;
import com.ca.devtest.sv.devtools.junit.VirtualServicesRule;
/**
* @author gaspa03
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = LisaBankClientApplication.class)
@DevTestVirtualServer()
public class BasicTest {
static final Log logger = LogFactory.getLog(BasicTest.class);
@Autowired
private BankService bankServices;
@Rule
public VirtualServicesRule rules = new VirtualServicesRule();
@DevTestVirtualService(serviceName = "getListUser0",
basePath = "/itkoExamples/EJB3UserControlBean",
port = 9081,
workingFolder = "UserServiceTest/getListUser/EJB3UserControlBean",
requestDataProtocol = {
@Protocol(ProtocolType.DPH_SOAP) })
@Test
public void getListUser() {
User[] users = bankServices.getListUser();
assertNotNull(users);
printUsers(users);
assertEquals(9, users.length);
}
@DevTestVirtualServiceV3(serviceName = "getListUserV3",
basePath = "/itkoExamples/EJB3UserControlBean",
port = "9081",
workingFolder = "UserServiceTest/getListUser/EJB3UserControlBeanV3",
inputFile1 = "listUsers-req.xml",
inputFile2 = "listUsers-rsp.xml",
dataProtocolsConfig = {
@DataProtocolConfig(
typeId = "SOAPDPH"
)
}
)
@Test
public void getListUserV3() {
User[] users = bankServices.getListUser();
assertNotNull(users);
printUsers(users);
assertEquals(9, users.length);
}
@DevTestVirtualService(serviceName = "getListUser1",
basePath = "/itkoExamples/EJB3UserControlBean",
port = 9081,
workingFolder = "UserServiceTest/getListUser/EJB3UserControlBean1",
requestDataProtocol = {
@Protocol(ProtocolType.DPH_SOAP) })
@Test
public void getListUser1() {
User[] users = bankServices.getListUser();
assertNotNull(users);
printUsers(users);
assertEquals(0, users.length);
}
@DevTestVirtualServiceV3(serviceName = "getListUser1V3",
basePath = "/itkoExamples/EJB3UserControlBean",
port = "9081",
workingFolder = "UserServiceTest/getListUser/EJB3UserControlBean1V3",
inputFile1 = "listUsers-req.xml",
inputFile2 = "listUsers-rsp.xml",
dataProtocolsConfig = {
@DataProtocolConfig(
typeId = "SOAPDPH"
)
}
)
@Test
public void getListUser1V3() {
User[] users = bankServices.getListUser();
assertNotNull(users);
printUsers(users);
assertEquals(0, users.length);
}
@DevTestVirtualService(serviceName = "getListUserTemplate",
basePath = "/itkoExamples/EJB3UserControlBean",
port = 9081, workingFolder = "UserServiceTest/getListUser/template",
parameters={@Parameter(name="email", value="<EMAIL>"),
@Parameter(name="nom", value="Gasp"),
@Parameter(name="login", value="pgasp"),
@Parameter(name="pwd", value="<PASSWORD>")},
requestDataProtocol = {
@Protocol(ProtocolType.DPH_SOAP) })
@Test
public void getListUserTemplate() {
User[] users = bankServices.getListUser();
assertNotNull(users);
assertEquals(1, users.length);
printUsers(users);
}
@DevTestVirtualServiceV3(serviceName = "getListUserTemplateV3",
basePath = "/itkoExamples/EJB3UserControlBean",
port = "9081",
workingFolder = "UserServiceTest/getListUser/template",
inputFile2 = "listUser-1-req.xml",
inputFile1 = "listUser-1-rsp.xml",
parameters={@Parameter(name="email", value="<EMAIL>"),
@Parameter(name="nom", value="Gasp"),
@Parameter(name="login", value="pgasp"),
@Parameter(name="pwd", value="<PASSWORD>")},
dataProtocolsConfig = {
@DataProtocolConfig(
typeId = "SOAPDPH"
)
}
)
@Test
public void getListUserTemplateV3() {
User[] users = bankServices.getListUser();
assertNotNull(users);
assertEquals(1, users.length);
printUsers(users);
}
private void printUsers(User[] users) {
for (User user : users) {
logger.info(user.getFname() + " " + user.getLname() + " " + user.getLogin());
}
}
}
<file_sep>/devtest-unit-test-java/src/main/java/com/ca/devtest/sv/devtools/services/v3/VirtualService.java
package com.ca.devtest.sv.devtools.services.v3;
/**
* @author sm632260
*
*/
public class VirtualService {
String version;
String name;
String description;
String status;
int capacity;
int thinkScale;
boolean autoRestart;
boolean startOnDeploy;
String groupTag;
public VirtualService() {
this.version = "1.0";
this.description = "Deployed using SV-as-Code";
this.name="";
this.status="";
this.groupTag="";
this.autoRestart=true;
this.startOnDeploy=true;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public int getCapacity() {
return capacity;
}
public void setCapacity(int capacity) {
this.capacity = capacity;
}
public int getThinkScale() {
return thinkScale;
}
public void setThinkScale(int thinkScale) {
this.thinkScale = thinkScale;
}
public boolean getAutoRestart() {
return autoRestart;
}
public void setAutoRestart(boolean autoRestart) {
this.autoRestart = autoRestart;
}
public boolean getStartOnDeploy() {
return startOnDeploy;
}
public void setStartOnDeploy(boolean startOnDeploy) {
this.startOnDeploy = startOnDeploy;
}
public String getGroupTag() {
return groupTag;
}
public void setGroupTag(String groupTag) {
this.groupTag = groupTag;
}
public static class VirtualServiceBuilder{
private final VirtualService virtualServiceInstance = new VirtualService();
private VirtualServiceBuilder VirtualServiceBuilder(){
return new VirtualServiceBuilder();
}
public static VirtualServiceBuilder builder(){
return new VirtualServiceBuilder();
}
public VirtualServiceBuilder withVerison(String version){
virtualServiceInstance.setVersion(version);
return this;
}
public VirtualServiceBuilder withName(String name){
virtualServiceInstance.setName(name);
return this;
}
public VirtualServiceBuilder withDescription(String description){
virtualServiceInstance.setDescription(description);
return this;
}
public VirtualServiceBuilder withStatus(String status){
virtualServiceInstance.setStatus(status);
return this;
}
public VirtualServiceBuilder withCapacity(int capacity){
virtualServiceInstance.setCapacity(capacity);
return this;
}
public VirtualServiceBuilder withThinkScale(int thinkScale){
virtualServiceInstance.setThinkScale(thinkScale);
return this;
}
public VirtualServiceBuilder withAutoRestart(boolean autoRestart){
virtualServiceInstance.setAutoRestart(autoRestart);
return this;
}
public VirtualServiceBuilder withStartOnDeploy(boolean startOnDeploy){
virtualServiceInstance.setStartOnDeploy(startOnDeploy);
return this;
}
public VirtualServiceBuilder withGroupTag(String groupTag){
virtualServiceInstance.setGroupTag(groupTag);
return this;
}
public VirtualService build(){
return this.virtualServiceInstance;
}
}
}
<file_sep>/devtest-unit-test-java/src/main/java/com/ca/devtest/tools/rawtraffic/RawTrafficTransactionGouper.java
package com.ca.devtest.tools.rawtraffic;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.apache.commons.io.FileUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* @author gaspa03
*
*/
public class RawTrafficTransactionGouper {
private static final XPath XPATH = XPathFactory.newInstance().newXPath();
private static final String SHORT_MESSAGE_LOG_ENDPOINT = "%s=%d";
private static final String GENERATED_FOLDERNAME = "generated";
private static final String SUM_MESSAGE_LOG_ENDPOINT = "# Endpoint =%d #transaction=%d";
private static final String GROUP_ENDPOINT = "DomaineDR7CandidatServiceSync,,";
private static final String TRANSCATION_FILENAME_PAT = "%s.xml";
private static final String SERVICE_LINE_HEADER = "serviceName;targetServer;targetPort;endpointPath;vsport;vsmName,vsmType";
private static final String SERVICE_LINE_FORMAT = "%s;%s;%s;%s;50000;%s;%s";
private static final String SERVICE_REPORT_FILENAME = "00-servicesCatalog.csv";
private static final String LISA_VSM_NAME = "lisa.vsm.%s.name=%s";
private static final String LISA_VSM_TYPE = "lisa.vsm.%s.type=%s";
public static void main(String[] args) {
if (args.length == 0) {
System.err.println("please specify the raw traffic file location");
System.exit(1);
}
String rawFolder = args[0];
generateGroupRawTrafficByTransaction(rawFolder, GROUP_ENDPOINT);
}
/**
* @param rawFolderPath
*/
public static void generateGroupRawTrafficByTransaction(
String rawFolderPath, String groupedEndPoint) {
try {
File rawFolder = new File(rawFolderPath);
Collection<File> rawTrafficFiles = FileUtils.listFiles(rawFolder,
new String[] { "xml" }, false);
DocumentBuilderFactory domFactory = DocumentBuilderFactory
.newInstance();
domFactory.setNamespaceAware(true);
DocumentBuilder builder;
builder = domFactory.newDocumentBuilder();
Map<String, List<Node>> sortedTransactions = new HashMap<String, List<Node>>();
for (File rawFile : rawTrafficFiles) {
Document doc = builder.parse(rawFile);
// XPath Query for showing all nodes value
XPathExpression transactionExpr = XPATH
.compile("//transaction");
NodeList transactions = (NodeList) transactionExpr.evaluate(
doc, XPathConstants.NODESET);
for (int i = 0; i < transactions.getLength(); i++) {
Node transaction = transactions.item(i);
addTransaction(sortedTransactions,
getEndPoint(transaction), transaction,
groupedEndPoint);
}
}
print(sortedTransactions, false);
generateRawTrafficGrouped(builder, rawFolder, sortedTransactions);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* @param rawFolder
* @param sortedTransactions
* @throws XPathExpressionException
* @throws IOException
*/
private static void generateRawTrafficGrouped(DocumentBuilder builder,
File rawFolder, Map<String, List<Node>> sortedTransactions)
throws XPathExpressionException, IOException {
Set<String> keys = sortedTransactions.keySet();
List<Node> transactions = null;
Collection<String> servicesList = new HashSet<String>();
for (String endpoint : keys) {
transactions = sortedTransactions.get(endpoint);
generateRawTraffic(builder, servicesList, rawFolder, endpoint,
transactions);
}
generateServicesRepport(servicesList, rawFolder);
}
/**
* @param servicesList
* @param rawFolder
* @throws IOException
*/
private static void generateServicesRepport(
Collection<String> servicesList, File rawFolder) throws IOException {
Collection<String> lines = new ArrayList<String>();
lines.add(SERVICE_LINE_HEADER);
lines.addAll(servicesList);
FileUtils.writeLines(new File(getGeneratedFolder(rawFolder),
SERVICE_REPORT_FILENAME), lines);
}
/**
* @param servicesList
* @param rawFolder
* @param endpoint
* @param transactions
* @throws XPathExpressionException
*/
private static void generateRawTraffic(DocumentBuilder builder,
Collection<String> servicesList, File rawFolder, String endpoint,
List<Node> transactions) throws XPathExpressionException {
try {
// root elements
Document doc = builder.newDocument();
Element rootElement = doc.createElement("rawTraffic");
doc.appendChild(rootElement);
String transactionName = getTransactionName(endpoint);
File folderGenerated = getGeneratedFolder(rawFolder);
File transactionFile = new File(folderGenerated, String.format(
TRANSCATION_FILENAME_PAT, transactionName));
for (Node transaction : transactions) {
rootElement.appendChild(doc.adoptNode(transaction));
// transaction info in list of transcation
servicesList.add(getServiceLine(transaction, transactionName,
endpoint));
}
// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory
.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(transactionFile);
// Output to console for testing
// StreamResult result = new StreamResult(System.out);
transformer.transform(source, result);
} catch (TransformerException tfe) {
tfe.printStackTrace();
}
}
/**
* @param rawFolder
* @return
*/
private static File getGeneratedFolder(File rawFolder) {
File folderGenerated = new File(rawFolder, GENERATED_FOLDERNAME);
folderGenerated.mkdirs();
return folderGenerated;
}
/**
* @param endpoint
* @return
*/
private static String getTransactionName(String endpoint) {
if (endpoint.startsWith("/")) {
endpoint = endpoint.substring(1);
}
if (endpoint.endsWith("/")) {
endpoint = endpoint.substring(0, endpoint.length() - 1);
}
endpoint = endpoint.replaceAll("/", "-");
return endpoint;
}
private static String getServiceLine(Node transaction,
String transactionName, String endpoint)
throws XPathExpressionException {
String host = getHost(transaction);
String[] infos = host.split(":");
String server = infos[0];
String port = "80";
if (infos.length > 0) {
port = infos[1];
}
String lisaVsmName = String.format(LISA_VSM_NAME, transactionName,transactionName);
String lisaVsmType = String.format(LISA_VSM_TYPE,transactionName ,"SOAP");
return String.format(SERVICE_LINE_FORMAT, transactionName, server,
port, endpoint, lisaVsmName,lisaVsmType);
}
/**
* @param sortedTransactions
* @param deep
*/
private static void print(Map<String, List<Node>> sortedTransactions,
boolean deep) {
Set<String> keys = sortedTransactions.keySet();
List<Node> transactions = null;
int transactionCounter = 0;
int nbEndpoints = 0;
int nbTransaction = 0;
for (String endpoint : keys) {
transactions = sortedTransactions.get(endpoint);
nbTransaction = transactions.size();
transactionCounter = transactionCounter + nbTransaction;
nbEndpoints++;
if (!deep) {
System.out.printf((SHORT_MESSAGE_LOG_ENDPOINT) + "%n",
endpoint, nbTransaction);
}
}
System.out.printf((SUM_MESSAGE_LOG_ENDPOINT) + "%n", nbEndpoints,
transactionCounter);
}
/**
* @param sortedTransactions
* @param endPoint
* @param transaction
*/
private static void addTransaction(
Map<String, List<Node>> sortedTransactions, String endPoint,
Node transaction, String groupedEnpoint) {
List<Node> rawTrafficList = null;
endPoint = getEndpointGroupeName(endPoint, groupedEnpoint);
if (sortedTransactions.containsKey(endPoint)) {
rawTrafficList = sortedTransactions.get(endPoint);
} else {
rawTrafficList = new ArrayList<Node>();
sortedTransactions.put(endPoint, rawTrafficList);
}
rawTrafficList.add(transaction);
}
/**
* @param endPoint
* @return
*/
private static String getEndpointGroupeName(String endPoint,
String groupedEnpoint) {
String endpointName = endPoint;
String[] group = groupedEnpoint.split(",");
for (String groupeName : group) {
if (groupeName.length()>0&&endPoint.startsWith(groupeName)) {
endpointName = groupeName;
break;
}
}
return endpointName;
}
/**
* @param item
* @return
* @throws XPathExpressionException
*/
private static String getEndPoint(Node requestNode)
throws XPathExpressionException {
XPathExpression exprRequestmeta = XPATH
.compile("request/metaData/parameter");
NodeList parameters = (NodeList) exprRequestmeta.evaluate(requestNode,
XPathConstants.NODESET);
for (int i = 0; i < parameters.getLength(); i++) {
Node item = parameters.item(i);
String name = XPATH.evaluate("@name", item);
String value = XPATH.evaluate("text()", item);
if ("HTTP-URI".equalsIgnoreCase(name)) {
return value;
}
}
return null;
}
/**
* @param item
* @return
* @throws XPathExpressionException
*/
private static String getHost(final Node requestNode)
throws XPathExpressionException {
XPathExpression exprRequestmeta = XPATH
.compile("request/metaData/parameter");
NodeList parameters = (NodeList) exprRequestmeta.evaluate(requestNode,
XPathConstants.NODESET);
for (int i = 0; i < parameters.getLength(); i++) {
Node item = parameters.item(i);
String name = XPATH.evaluate("@name", item);
String value = XPATH.evaluate("text()", item);
if ("Host".equalsIgnoreCase(name)) {
return value;
}
}
return null;
}
}
<file_sep>/devtest-unit-test-java/src/main/java/com/ca/devtest/sv/devtools/annotation/processor/VirtualServiceFromVrsAnnotationProcessor.java
/**
*
*/
package com.ca.devtest.sv.devtools.annotation.processor;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import com.ca.devtest.sv.devtools.services.VirtualServiceInterface;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import com.ca.devtest.sv.devtools.DevTestClient;
import com.ca.devtest.sv.devtools.annotation.DevTestVirtualServiceFromVrs;
import com.ca.devtest.sv.devtools.annotation.Parameter;
import com.ca.devtest.sv.devtools.exception.VirtualServiceProcessorException;
import com.ca.devtest.sv.devtools.protocol.builder.TransportProtocolFromVrsBuilder;
import com.ca.devtest.sv.devtools.services.builder.VirtualServiceBuilder;
import com.ca.devtest.sv.devtools.utils.Utility;
/**
* @author gaspa03
*
*/
public class VirtualServiceFromVrsAnnotationProcessor implements AnnotationProcessor {
/* (non-Javadoc)
* @see com.ca.devtest.sv.devtools.annotation.processor.MethodProcessorAnnotation#process(com.ca.devtest.sv.devtools.DevTestClient, java.lang.annotation.Annotation)
*/
@Override
public List<VirtualServiceInterface> process(DevTestClient devTestClient, Annotation annotation)
throws VirtualServiceProcessorException {
List<VirtualServiceInterface> result=new ArrayList<VirtualServiceInterface>(1);
result.add( buildVirtualService(devTestClient,(DevTestVirtualServiceFromVrs)annotation));
return result;
}
/**
* @param devTestClient
* @param virtualService
* @return
* @throws VirtualServiceProcessorException
*/
private VirtualServiceInterface buildVirtualService(DevTestClient devTestClient, DevTestVirtualServiceFromVrs virtualService)
throws VirtualServiceProcessorException {
try {
URL url = getClass().getClassLoader().getResource(virtualService.workingFolder());
File workingFolder = new File(url.toURI());
VirtualServiceBuilder virtualServiceBuilder = devTestClient.fromRRPairs(virtualService.serviceName(),workingFolder);
File vrsFile = null;
if (!StringUtils.isEmpty(virtualService.vrsConfig().value())) {
// if vrsConfig.value is specified, vrs file is loaded from this value
vrsFile = new File(workingFolder, virtualService.vrsConfig().value());
} else {
// else we try to load a template in class path
File tmpVrs = File.createTempFile(virtualService.serviceName(), "vrs");
tmpVrs.deleteOnExit();
InputStream inputStream = getClass().getClassLoader().getResourceAsStream("template.vrs");
FileOutputStream fileOutputStream = new FileOutputStream(tmpVrs);
try {
IOUtils.copy(inputStream, fileOutputStream);
} catch (Exception error) {
throw new VirtualServiceProcessorException(
"Error while reading template.vrs file from classpath (maybe not found ?) : ", error);
}
inputStream.close();
fileOutputStream.close();
vrsFile = tmpVrs;
}
// Fin de rajout
// handle Parameters and propagate parameters to Virtualservicebuilder
Utility.addParamsToBuilder(virtualServiceBuilder, virtualService.parameters());
// build Transport Protocol
TransportProtocolFromVrsBuilder transportBuilder = new TransportProtocolFromVrsBuilder(vrsFile);
Parameter[] transportParam = virtualService.vrsConfig().parameters();
Utility.addParamsToBuilder(transportBuilder, transportParam);
// add Transport Protocol
virtualServiceBuilder.over(transportBuilder.build());
virtualServiceBuilder.setCapacity(virtualService.capacity());
virtualServiceBuilder.setAutoRestartEnabled(virtualService.autoRestartEnabled());
virtualServiceBuilder.setExecutionMode(virtualService.executionMode());
virtualServiceBuilder.setThinkScale(virtualService.thinkScale());
virtualServiceBuilder.setGroupTag(virtualService.groupTag());
return virtualServiceBuilder.build();
} catch (Exception error) {
throw new VirtualServiceProcessorException("Error during building virtual service : ", error);
}
}
}
<file_sep>/README.adoc
== Service Virtualization As Code
This project provides simple **Java annotations** that can be used in your Junit Test to deploy Virtual Services before starting your test. The scope of annotations are test methods. +
This java annotation helps to embed your Virtual Services in your source code. This approach makes your application ready for Continous Integration testing by removing system and data constraints with **Service Virtualization**. **Your tests become more reliable, repeatable and automated**. +
With this approach, using **Virtual Services** from your Continuous Integration plateform becomes native.
== Projects description
- **devtest-unit-test-java** : Source code of java annotations and java API wrapped on **Devtest Rest API** to build and deploy virtual services
- **lisabank-demo** : Demo project using SV as Code annotation to deploy virtual services in junit test
== Pre-requises
You should have **DevTest Server ** up and running. This server could be installed on your machine or on remote server. You will setup registry url and VSE name through Java Annotation *@DevTestVirtualServer* .
This both parameters will be used to build and deploy your virtual services.
This annotations will use ***DevTest Rest API (DevTest Invoke 2)*** and it's compatible **from DevTest 8.0 and above**.
== Getting started
In the **pom file** of your maven project add a new repository to get the libraries dependencies.
[source,xml]
----
<repositories>
<repository>
<id>bintray-ca-sv</id>
<name>bintray-ca</name>
<url>http://ca.bintray.com/sv</url>
</repository>
</repositories>
----
Add below dependency with scope test in your **pom file** :
[source,xml]
----
<dependency>
<groupId>com.ca.devtest.sv.devtools</groupId>
<artifactId>devtest-unit-test-java</artifactId>
<version>1.4.0</version>
</dependency>
----
Below is a quick sample of how to use " SV as code " in your Junit classes:
[source,java,indent=0]
----
/**
* @author <EMAIL>.com
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = LisaBankClientApplication.class)
@DevTestVirtualServer(registryHost = "localhost", deployServiceToVse = "VSE")
public class SimpleDemo {
static final Log logger = LogFactory.getLog(SimpleDemo.class);
@Autowired
private BankService bankServices;
@Rule
public VirtualServicesRule rules = new VirtualServicesRule();
@DevTestVirtualService(serviceName = "UserServiceTest-EJB3UserControlBean",
port = 9080, basePath = "/itkoExamples/EJB3UserControlBean",
rrpairsFolder = "UserServiceTest/getListUser/EJB3UserControlBean",
requestDataProtocol = {@Protocol(ProtocolType.DPH_SOAP) })
@Test
public void getListUser() {
User[] users = bankServices.getListUser();
assertNotNull(users);
assertEquals(9, users.length);
}
}
----
First, flag your Junit class as a Test using Virtual Services. This annotation will be used to refer to the DevTest Server :
* *registryHost* :* Registry hostname _(default value localhost)_
* *deployServiceToVse :* Name of VSE
* *login :* Devtest username _(default value svpower)_
* *password :* Devtest password _(default value svpower)_
* *protocol :* Protcol to connect with Registry _(default value http)_
* *keystore :* Keystore location required when Protocol is https
* *keystorePasswored :* Keystore Passwored
all of this parameters are optional. You could set values in **local-svascode.porperties** file with following properties:
* *devtest.vsename :* Name of VSE
* *devtest.registry :* Registry hostname
* *devtest.registryUrl :* Registry url
* *devtest.login :* Devtest username
* *devtest.password :* <PASSWORD>
* *devtest.protocol :* Protocol to connect with Registry
* *devtest.keystore :* Keystore location
* *devtest.keystorePassword :* Keystore password
* *devtest.undeploy.ifexists :* Flag to undeploy existing Virtual Service before deploying
[source,java,indent=0]
----
@DevTestVirtualServer()
----
Add *VirtualServices* rule as a field member of Junit class. This rule will handle *SV as Code annotations* during Junit life cycle. Rules allow very flexible addition or redefinition of the behavior of each test method in a test class
[source,java,indent=0]
----
@Rule
public VirtualServicesRule rules = new VirtualServicesRule();
----
Above of each test method, add virtual service annotations. This annotation should refer to the Requests/Responses folder and define virtual service configuration such as service name, listnen port, path, type of protocole
[source,java,indent=0]
----
DevTestVirtualService annotation which uses DCM capabilities
@DevTestVirtualService(serviceName = "UserServiceTest-EJB3UserControlBean",
port = 9080, basePath = "/itkoExamples/EJB3UserControlBean",
rrpairsFolder = "UserServiceTest/getListUser/EJB3UserControlBean",
requestDataProtocol = {@Protocol(ProtocolType.DPH_SOAP) })
DevTestVirtualServiceV3 annotation which uses V3 capabilities
@DevTestVirtualServiceV3(
serviceName = "vsV3_SSLConfig",
description = "Created with annotation provided for function vsV3_RRPairConfigObject",
port = "24778",
workingFolder = "v3/rrpair",
inputFile2 = "operation-8-req.txt",
inputFile1 = "operation-8-rsp.txt",
transportProtocolConfig = @TransportProtocolConfig(
typeId = "HTTP",
useGateway = false,
hostHeaderPassThrough = true,
recordingEndpoint = @RecordingEndpointConfig(
host = "recordinghost",
useSSL = true,
sslConfig = @SSLConfig (
keystorePassword = "<PASSWORD>",
keystoreFile = "/Applications/CA/DevTest/webreckeys.ks",
aliasPassword = "<PASSWORD>",
alias = "lisa"
)
)
)
)
----
It's possible to define a set of Virtual Services with Class scope. In this case all virtual services will be deployed once at class level.
First you should add Junit Class Rule as described below
[source,java,indent=0]
----
@ClassRule
public static VirtualServiceClassScopeRule ruleClass= new VirtualServiceClassScopeRule();
----
Then you could use DevTestVirtualService annotations on top of your class.
[source,java,indent=0]
----
/**
*
*/
package com.ca.devtest.lisabank.demo.sv.http;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.ca.devtest.lisabank.demo.LisaBankClientApplication;
import com.ca.devtest.lisabank.demo.business.BankService;
import com.ca.devtest.lisabank.wsdl.User;
import com.ca.devtest.sv.devtools.annotation.DevTestVirtualServer;
import com.ca.devtest.sv.devtools.annotation.DevTestVirtualService;
import com.ca.devtest.sv.devtools.annotation.Protocol;
import com.ca.devtest.sv.devtools.annotation.ProtocolType;
import com.ca.devtest.sv.devtools.junit.VirtualServiceClassScopeRule;
/**
* @author <EMAIL>
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = LisaBankClientApplication.class)
// Mark as Test using Service Virtualization
@DevTestVirtualServer()
// Define Virtual Service with Clazz scope => Deploy once for all methods
@DevTestVirtualService(serviceName = "VSClazzScopeSimpleDemo",
basePath = "/itkoExamples/EJB3UserControlBean",
port = 9081,
workingFolder = "UserServiceTest/getListUser/EJB3UserControlBean",
requestDataProtocol = {
@Protocol(ProtocolType.DPH_SOAP) })
public class VSClazzScopeSimpleDemo {
static final Log logger = LogFactory.getLog(VSClazzScopeSimpleDemo.class);
@Autowired
private BankService bankServices;
// handle VS with Class scope
@ClassRule
public static VirtualServiceClassScopeRule clazzRule = new VirtualServiceClassScopeRule();
@Test
public void getListUser() {
User[] users = bankServices.getListUser();
assertNotNull(users);
printUsers(users);
assertEquals(9, users.length);
}
private void printUsers(User[] users) {
for (User user : users) {
logger.info(user.getFname() + " " + user.getLname() + " " + user.getLogin());
}
}
@DevTestVirtualServiceV3(
serviceName = "vsV3_SSLConfig",
description = "Created with annotation provided for function vsV3_RRPairConfigObject",
port = "24778",
workingFolder = "v3/rrpair",
inputFile2 = "operation-8-req.txt",
inputFile1 = "operation-8-rsp.txt",
transportProtocolConfig = @TransportProtocolConfig(
typeId = "HTTP",
useGateway = false,
hostHeaderPassThrough = true,
recordingEndpoint = @RecordingEndpointConfig(
host = "recordinghost",
useSSL = true,
sslConfig = @SSLConfig (
keystorePassword = "<PASSWORD>",
keystoreFile = "/Applications/CA/DevTest/webreckeys.ks",
aliasPassword = "<PASSWORD>",
alias = "lisa"
)
)
)
)
@Test
public void vsV3_SSLConfig(){
ResponseParser responseParser = HttpUtils.GET(HttpUtils.URL_FORMAT, "https", "localhost",
"24778","import/test/operation-8");
ResponseParser vsResponseParser = HttpUtils.GET_VS_DETAILS(API_PROTOCOL, "localhost", "1505", "VSE", "V3Test.vsV3_Deploy");
assert (responseParser!=null);
assert (responseParser.getValue("$.TCEntry[0].termsType").equals("Operation 8 terms"));
}
}
----
<file_sep>/lisabank-demo/src/test/java/com/ca/devtest/lisabank/demo/sv/vsm/InventoryVirtualServiceTest.java
package com.ca.devtest.lisabank.demo.sv.vsm;
import com.ca.devtest.lisabank.demo.LisaBankClientApplication;
import com.ca.devtest.lisabank.demo.business.StoreServiceImp;
import com.ca.devtest.lisabank.demo.model.StoreInventory;
import com.ca.devtest.sv.devtools.annotation.*;
import com.ca.devtest.sv.devtools.annotation.v3.DevTestVirtualServiceV3;
import com.ca.devtest.sv.devtools.junit.VirtualServicesRule;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = LisaBankClientApplication.class)
@DevTestVirtualServer(registryHost = "localhost",deployServiceToVse = "VSE", login = "admin", password="<PASSWORD>")
public class InventoryVirtualServiceTest {
// handle VS with Class scope
static final Log logger = LogFactory.getLog(com.ca.devtest.lisabank.demo.sv.vsm.InventoryVirtualServiceTest.class);
@Autowired
private StoreServiceImp storeService;
@Rule
public VirtualServicesRule rules = new VirtualServicesRule();
@DevTestVirtualService(serviceName = "getStoresInventory", type = VirtualServiceType.VSM,
workingFolder = "storeInventoryVSM", basePath = "/", parameters = {
@Parameter(name = "port", value = "19804")},requestDataProtocol = {
@Protocol(ProtocolType.DPH_JSON) },
responseDataProtocol = {@Protocol(ProtocolType.DPH_JSON)})
@Test
public void getStoresInventory() {
try {
StoreInventory store = storeService.getStoreInventory();
assertNotNull(store);
printUsers(store);
assertEquals(new Integer(1), store.getInteger_0());
} finally {
}
}
@DevTestVirtualServiceV3(serviceName = "getStoresInventoryV3",
workingFolder = "storeInventoryVSM",
basePath = "/",
port = "19804",
inputFile2 = "getStoresInventory.vsm",
inputFile1 = "getStoresInventory.vsi"
)
@Test
public void getStoresInventoryV3() {
try {
StoreInventory store = storeService.getStoreInventory();
assertNotNull(store);
printUsers(store);
assertEquals(new Integer(1), store.getInteger_0());
} finally {
}
}
private void printUsers(StoreInventory store) {
// for (StoreInventory inv : stores) {
logger.info(store.getInteger_0());
// }
}
}
<file_sep>/devtest-unit-test-java/src/main/java/com/ca/devtest/sv/devtools/services/VirtualServiceInterface.java
package com.ca.devtest.sv.devtools.services;
import com.ca.devtest.sv.devtools.VirtualServiceEnvironment;
/**
* @author sm632260
*
*/
public interface VirtualServiceInterface {
VirtualServiceEnvironment getVse();
String getType();
void setType(String type);
String getUrl();
void setUrl(String url);
String getName();
String getGroup();
void deploy() throws Exception;
void unDeploy() throws Exception;
void exists() throws Exception;
String getDeployedName();
void setDeployedName(String deployedName);
void clean();
}
<file_sep>/lisabank-demo/src/main/java/com/ca/devtest/lisabank/demo/business/LisaUserService.java
package com.ca.devtest.lisabank.demo.business;
import java.util.List;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import com.ca.devtest.lisabank.demo.model.LisaUser;
@Component
public class LisaUserService {
LisaUser user;
@Value("${webservice.url.lisaUser}")
private String lisaServiceUrl;
public List<LisaUser> getListUsers(){
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<LisaUser[]> entity = new HttpEntity<LisaUser[]>(headers);
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<List<LisaUser>> response = restTemplate.exchange(lisaServiceUrl,
HttpMethod.GET, entity, new ParameterizedTypeReference<List<LisaUser>>(){});
return response.getBody();
}
}
<file_sep>/devtest-unit-test-java/src/test/java/com/ca/devtest/sv/devtools/VirtualServiceV3RemoteServerTest.java
package com.ca.devtest.sv.devtools;
import com.ca.devtest.sv.devtools.annotation.DevTestVirtualServer;
import com.ca.devtest.sv.devtools.annotation.v3.DevTestVirtualServiceV3;
import com.ca.devtest.sv.devtools.junit.VirtualServicesRule;
import com.ca.devtest.sv.devtools.v3.HttpUtils;
import com.ca.devtest.sv.devtools.v3.ResponseParser;
import org.junit.Rule;
import org.junit.Test;
@DevTestVirtualServer( registryHost = "remoteserver", groupName = "remote")
public class VirtualServiceV3RemoteServerTest {
@Rule
public VirtualServicesRule rules = new VirtualServicesRule();
@DevTestVirtualServiceV3(
serviceName = "vsV3_Deploy",
port = "24778",
workingFolder = "v3/rrpair",
inputFile2 = "operation-8-req.txt",
inputFile1 = "operation-8-rsp.txt"
)
@Test
public void vsV3_Deploy(){
ResponseParser responseParser = HttpUtils.GET(HttpUtils.URL_FORMAT, "http","ussv-w2k19-itc2.dhcp.broadcom.net",
"24778","import/test/operation-8");
assert (responseParser!=null);
assert (responseParser.getValue("$.TCEntry[0].termsType").equals("Operation 8 terms"));
}
}
<file_sep>/devtest-unit-test-java/src/main/java/com/ca/devtest/sv/devtools/utils/FileUtils.java
package com.ca.devtest.sv.devtools.utils;
import java.io.*;
public class FileUtils {
/***
* Creates temp file with given file name and writes contents to it
*
* @param fileName - Name of the file
* @param content - Contents to be written to the file
* @return
* @throws IOException
*/
public static File crateTempFile (String fileName, String content) throws IOException {
String tempDir = System.getProperty("java.io.tmpdir");
File tempFile = new File(tempDir,fileName);
BufferedWriter out = new BufferedWriter(new FileWriter(tempFile));
try {
out.write(content);
}
finally{
out.close();
}
return tempFile;
}
}
<file_sep>/devtest-unit-test-java/src/main/java/com/ca/devtest/sv/devtools/annotation/v3/DataProtocolConfig.java
package com.ca.devtest.sv.devtools.annotation.v3;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author sm632260
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE,ElementType.METHOD})
public @interface DataProtocolConfig {
boolean forRequest() default true;
String typeId() default "RESTDPH";
}
<file_sep>/devtest-unit-test-java/src/main/java/com/ca/devtest/sv/devtools/protocol/TransportProtocolDefinitionImpl.java
/**
*
*/
package com.ca.devtest.sv.devtools.protocol;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* @author gaspa03
*
*/
public class TransportProtocolDefinitionImpl implements TransportProtocolDefinition{
private boolean allAreStateless = true;
private boolean asObject = true;
private boolean desensitize = false;
private boolean duptxns = true;
private List<DataProtocolDefinition> requestSide = new ArrayList<DataProtocolDefinition>();
private List<DataProtocolDefinition> responseSide = new ArrayList<DataProtocolDefinition>();
private final String TRANSPORT_TPL = "<Transport allAreStateless=\"%b\" asObject=\"%b\" desensitize=\"%b\" duptxns=\"%b\"><RequestSide>%s</RequestSide><ResponseSide>%s</ResponseSide></Transport>";
private final String type;
private final HashMap<String, String> parameters = new HashMap<String, String>();
public TransportProtocolDefinitionImpl(String type) {
super();
this.type = type;
}
/**
* @return the allAreStateless
*/
public final boolean isAllAreStateless() {
return allAreStateless;
}
/**
* @param allAreStateless
* the allAreStateless to set
*/
public final void setAllAreStateless(boolean allAreStateless) {
this.allAreStateless = allAreStateless;
}
/**
* @return the asObject
*/
public final boolean isAsObject() {
return asObject;
}
/**
* @param asObject
* the asObject to set
*/
public final void setAsObject(boolean asObject) {
this.asObject = asObject;
}
/**
* @return the desensitize
*/
public final boolean isDesensitize() {
return desensitize;
}
/**
* @param desensitize
* the desensitize to set
*/
public final void setDesensitize(boolean desensitize) {
this.desensitize = desensitize;
}
/**
* @return the duptxns
*/
public final boolean isDuptxns() {
return duptxns;
}
/**
* @param duptxns
* the duptxns to set
*/
public final void setDuptxns(boolean duptxns) {
this.duptxns = duptxns;
}
/**
* @param requestSide
* the requestSide to set
*/
public final void setRequestSide(List<DataProtocolDefinition> requestSide) {
this.requestSide = requestSide;
}
/**
* @param responseSide
* the responseSide to set
*/
public final void setResponseSide(List<DataProtocolDefinition> responseSide) {
this.responseSide = responseSide;
}
/**
* @return the requestSide
*/
public final List<DataProtocolDefinition> getRequestSide() {
return requestSide;
}
/**
* @return the responseSide
*/
public final List<DataProtocolDefinition> getResponseSide() {
return responseSide;
}
/*
* (non-Javadoc)
*
* @see com.ca.devtest.sv.devtools.tph.BaseProtocol#doPrintSpecific()
*/
protected String doPrintSpecific() {
String requestSide = printRequestSide();
String responsetSide = printResponseSide();
return String.format(TRANSPORT_TPL, allAreStateless, asObject, desensitize, duptxns, requestSide,
responsetSide);
}
/**
* @return
*/
private String printRequestSide() {
StringBuilder definition = new StringBuilder();
if (!requestSide.isEmpty()) {
for (DataProtocolDefinition dataProtocolDefinition : requestSide) {
dataProtocolDefinition.printXml(definition);
}
}
return definition.toString();
}
/**
* @return
*/
private String printResponseSide() {
StringBuilder definition = new StringBuilder();
if (!responseSide.isEmpty()) {
for (DataProtocolDefinition dataProtocolDefinition : responseSide) {
dataProtocolDefinition.printXml(definition);
}
}
return definition.toString();
}
/**
* @return
*/
public String toVrsContent() {
StringBuilder sb = new StringBuilder();
sb.append("<RecordingSession nonLeaf=\"WIDE\" leaf=\"LOOSE\" asObject=\"true\">");
printXml(sb);
sb.append("</RecordingSession>");
return sb.toString();
}
/**
* @return
*/
protected final String printParameters() {
StringBuilder result = new StringBuilder();
if (!parameters.isEmpty()) {
Set<String> keys = parameters.keySet();
for (String key : keys) {
result.append("<").append(key).append(">").append(parameters.get(key)).append("</").append(key)
.append(">");
}
}
return result.toString();
}
/**
* @param definition
*/
protected void printXml(StringBuilder definition) {
definition.append("<Protocol type=\"").append(type).append("\">").append(printParameters())
.append(doPrintSpecific()).append("</Protocol>");
}
@Override
public Map<String, String> getParameters() {
return parameters;
}
}<file_sep>/devtest-unit-test-java/src/main/java/com/ca/devtest/sv/devtools/protocol/TransportProtocolResource.java
/**
*
*/
package com.ca.devtest.sv.devtools.protocol;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ca.devtest.sv.devtools.utils.VelocityRender;
/**
* @author gaspa03
*
*/
public class TransportProtocolResource implements TransportProtocolDefinition {
private final File resource;
private final Map<String, String> parameters = new HashMap<String,String>();
private static final Logger LOGGING= LoggerFactory.getLogger(TransportProtocolResource.class);
/**
* @param resource
* @param parameters
*/
public TransportProtocolResource( File resource) {
super();
this.resource=resource;
}
/**
* @return
*/
public String toVrsContent() {
String content=null;
try {
content = FileUtils.readFileToString(resource,"UTF-8");
content=VelocityRender.render(content, parameters) ;
} catch (IOException e) {
LOGGING.error("Not able to open resources "+ resource.getPath(), e);
}
return content;
}
@Override
public Map<String, String> getParameters() {
return parameters;
}
@Override
public List<DataProtocolDefinition> getRequestSide() {
throw new UnsupportedOperationException("method not suported for this implementation");
}
@Override
public List<DataProtocolDefinition> getResponseSide() {
throw new UnsupportedOperationException("method not suported for this implementation");
}
}
<file_sep>/devtest-unit-test-java/src/main/java/com/ca/devtest/sv/devtools/protocol/builder/TransportProtocolBuilderImpl.java
/**
*
*/
package com.ca.devtest.sv.devtools.protocol.builder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.ca.devtest.sv.devtools.protocol.DataProtocolDefinition;
import com.ca.devtest.sv.devtools.protocol.TransportProtocolDefinition;
import com.ca.devtest.sv.devtools.protocol.TransportProtocolDefinitionImpl;
/**
* @author gaspa03
*
*/
public class TransportProtocolBuilderImpl implements TransportProtocolBuilder, ParamatrizedBuilder {
protected final String typebuilder;
protected Map<String, String> parameters = new HashMap<String, String>();
private final List<DataProtocolDefinition> requestDataProtocol = new ArrayList<DataProtocolDefinition>();
private final List<DataProtocolDefinition> responseDataProtocol = new ArrayList<DataProtocolDefinition>();
public TransportProtocolBuilderImpl(String type) {
this.typebuilder = type;
}
public TransportProtocolBuilder addParameter(String key, String value) {
addKeyValue(key, value);
return this;
}
public void addKeyValue(String key, String value) {
parameters.put(key, value);
}
/**
* @param type
* @return
*/
public TransportProtocolBuilderImpl addRequestDataProtocol(DataProtocolBuilder dataProtocolBuilder) {
requestDataProtocol.add(dataProtocolBuilder.build());
return this;
}
/**
* @param type
* @return
*/
public TransportProtocolBuilder addResponseDataProtocol(DataProtocolBuilder dphBuilder) {
responseDataProtocol.add(dphBuilder.build());
return this;
}
/* (non-Javadoc)
* @see com.ca.devtest.sv.devtools.protocol.builder.TransportProtocolBuilder#build()
*/
@Override
public TransportProtocolDefinition build() {
TransportProtocolDefinitionImpl tph = new TransportProtocolDefinitionImpl(typebuilder);
tph.setRequestSide(requestDataProtocol);
tph.setResponseSide(responseDataProtocol);
tph.getParameters().putAll(parameters);
return tph;
}
}
<file_sep>/lisabank-demo/src/main/java/com/ca/devtest/lisabank/wsdl/EJB3AccountControlBean.java
package com.ca.devtest.lisabank.wsdl;
import java.math.BigDecimal;
import java.util.List;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.ws.RequestWrapper;
import javax.xml.ws.ResponseWrapper;
/**
* This class was generated by the JAX-WS RI.
* JAX-WS RI 2.2.9-b14002
* Generated source version: 2.2
*
*/
@WebService(name = "EJB3AccountControlBean", targetNamespace = "http://ejb3.examples.itko.com/")
@XmlSeeAlso({
ObjectFactory.class
})
public interface EJB3AccountControlBean {
/**
*
* @param accountObj
* @param username
* @return
* returns java.lang.String
*/
@WebMethod
@WebResult(targetNamespace = "")
@RequestWrapper(localName = "addAccount", targetNamespace = "http://ejb3.examples.itko.com/", className = "com.ca.devtest.lisabank.wsdl.AddAccount")
@ResponseWrapper(localName = "addAccountResponse", targetNamespace = "http://ejb3.examples.itko.com/", className = "com.ca.devtest.lisabank.wsdl.AddAccountResponse")
public String addAccount(
@WebParam(name = "username", targetNamespace = "")
String username,
@WebParam(name = "accountObj", targetNamespace = "")
Account accountObj);
/**
*
* @param accountId
* @param username
* @return
* returns boolean
*/
@WebMethod
@WebResult(targetNamespace = "")
@RequestWrapper(localName = "deleteAccount", targetNamespace = "http://ejb3.examples.itko.com/", className = "com.ca.devtest.lisabank.wsdl.DeleteAccount")
@ResponseWrapper(localName = "deleteAccountResponse", targetNamespace = "http://ejb3.examples.itko.com/", className = "com.ca.devtest.lisabank.wsdl.DeleteAccountResponse")
public boolean deleteAccount(
@WebParam(name = "username", targetNamespace = "")
String username,
@WebParam(name = "accountId", targetNamespace = "")
String accountId);
/**
*
* @param accountId
* @param amount
* @param desc
* @return
* returns java.lang.String
*/
@WebMethod
@WebResult(targetNamespace = "")
@RequestWrapper(localName = "depositMoney", targetNamespace = "http://ejb3.examples.itko.com/", className = "com.ca.devtest.lisabank.wsdl.DepositMoney")
@ResponseWrapper(localName = "depositMoneyResponse", targetNamespace = "http://ejb3.examples.itko.com/", className = "com.ca.devtest.lisabank.wsdl.DepositMoneyResponse")
public String depositMoney(
@WebParam(name = "accountId", targetNamespace = "")
String accountId,
@WebParam(name = "amount", targetNamespace = "")
BigDecimal amount,
@WebParam(name = "desc", targetNamespace = "")
String desc);
/**
*
* @param accountId
* @return
* returns com.ca.devtest.lisabank.wsdl.Account
*/
@WebMethod
@WebResult(targetNamespace = "")
@RequestWrapper(localName = "getAccount", targetNamespace = "http://ejb3.examples.itko.com/", className = "com.ca.devtest.lisabank.wsdl.GetAccount")
@ResponseWrapper(localName = "getAccountResponse", targetNamespace = "http://ejb3.examples.itko.com/", className = "com.ca.devtest.lisabank.wsdl.GetAccountResponse")
public Account getAccount(
@WebParam(name = "accountId", targetNamespace = "")
String accountId);
/**
*
* @param accountId
* @param transId
* @return
* returns com.ca.devtest.lisabank.wsdl.Transaction
*/
@WebMethod
@WebResult(targetNamespace = "")
@RequestWrapper(localName = "getTransaction", targetNamespace = "http://ejb3.examples.itko.com/", className = "com.ca.devtest.lisabank.wsdl.GetTransaction")
@ResponseWrapper(localName = "getTransactionResponse", targetNamespace = "http://ejb3.examples.itko.com/", className = "com.ca.devtest.lisabank.wsdl.GetTransactionResponse")
public Transaction getTransaction(
@WebParam(name = "accountId", targetNamespace = "")
String accountId,
@WebParam(name = "transId", targetNamespace = "")
String transId);
/**
*
* @param accountId
* @param from
* @param to
* @return
* returns java.util.List<com.ca.devtest.lisabank.wsdl.Transaction>
*/
@WebMethod
@WebResult(targetNamespace = "")
@RequestWrapper(localName = "getTransactions", targetNamespace = "http://ejb3.examples.itko.com/", className = "com.ca.devtest.lisabank.wsdl.GetTransactions")
@ResponseWrapper(localName = "getTransactionsResponse", targetNamespace = "http://ejb3.examples.itko.com/", className = "com.ca.devtest.lisabank.wsdl.GetTransactionsResponse")
public List<Transaction> getTransactions(
@WebParam(name = "accountId", targetNamespace = "")
String accountId,
@WebParam(name = "from", targetNamespace = "")
XMLGregorianCalendar from,
@WebParam(name = "to", targetNamespace = "")
XMLGregorianCalendar to);
/**
*
* @param username
* @return
* returns java.util.List<com.ca.devtest.lisabank.wsdl.Account>
*/
@WebMethod
@WebResult(targetNamespace = "")
@RequestWrapper(localName = "listAccounts", targetNamespace = "http://ejb3.examples.itko.com/", className = "com.ca.devtest.lisabank.wsdl.ListAccounts")
@ResponseWrapper(localName = "listAccountsResponse", targetNamespace = "http://ejb3.examples.itko.com/", className = "com.ca.devtest.lisabank.wsdl.ListAccountsResponse")
public List<Account> listAccounts(
@WebParam(name = "username", targetNamespace = "")
String username);
/**
*
* @param amount
* @param fromAccountId
* @param toAccountId
* @param desc
* @return
* returns java.lang.String
*/
@WebMethod
@WebResult(targetNamespace = "")
@RequestWrapper(localName = "transferMoney", targetNamespace = "http://ejb3.examples.itko.com/", className = "com.ca.devtest.lisabank.wsdl.TransferMoney")
@ResponseWrapper(localName = "transferMoneyResponse", targetNamespace = "http://ejb3.examples.itko.com/", className = "com.ca.devtest.lisabank.wsdl.TransferMoneyResponse")
public String transferMoney(
@WebParam(name = "fromAccountId", targetNamespace = "")
String fromAccountId,
@WebParam(name = "toAccountId", targetNamespace = "")
String toAccountId,
@WebParam(name = "amount", targetNamespace = "")
BigDecimal amount,
@WebParam(name = "desc", targetNamespace = "")
String desc);
/**
*
* @param accountId
* @param amount
* @param desc
* @return
* returns java.lang.String
*/
@WebMethod
@WebResult(targetNamespace = "")
@RequestWrapper(localName = "withdrawMoney", targetNamespace = "http://ejb3.examples.itko.com/", className = "com.ca.devtest.lisabank.wsdl.WithdrawMoney")
@ResponseWrapper(localName = "withdrawMoneyResponse", targetNamespace = "http://ejb3.examples.itko.com/", className = "com.ca.devtest.lisabank.wsdl.WithdrawMoneyResponse")
public String withdrawMoney(
@WebParam(name = "accountId", targetNamespace = "")
String accountId,
@WebParam(name = "amount", targetNamespace = "")
BigDecimal amount,
@WebParam(name = "desc", targetNamespace = "")
String desc);
}
<file_sep>/devtest-unit-test-java/src/main/java/com/ca/devtest/sv/devtools/protocol/TransportProtocolDefinition.java
/**
*
*/
package com.ca.devtest.sv.devtools.protocol;
import java.util.List;
import java.util.Map;
/**
* @author gaspa03
*
*/
public interface TransportProtocolDefinition {
/**
* @return
*/
Map<String, String> getParameters();
/**
* @return
*/
String toVrsContent();
/**
* @return
*/
List<DataProtocolDefinition> getRequestSide();
/**
* @return
*/
List<DataProtocolDefinition> getResponseSide();
}
<file_sep>/lisabank-demo/src/main/java/com/ca/devtest/lisabank/demo/business/Product.java
package com.ca.devtest.lisabank.demo.business;
import org.springframework.stereotype.Component;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.math.BigDecimal;
@XmlRootElement (name = "product")
public class Product {
@XmlElement(name = "description")
private String description;
@XmlElement(name = "price")
private BigDecimal price;
@XmlElement(name = "createdBy")
private String createdBy;
public Product(){}
public Product(String productId, String description,
BigDecimal price, String createdBy) {
this.description = description;
this.price = price;
this.createdBy = createdBy;
}
@Override
public String toString() {
return "Product{" +
",\n description='" + description + '\'' +
",\n price=" + price +
",\n createdBy=" + createdBy +"\n"+
'}';
}
}
<file_sep>/devtest-unit-test-java/src/test/java/com/ca/devtest/sv/devtools/utils/test/PackMarFileTest.java
package com.ca.devtest.sv.devtools.utils.test;
import java.io.File;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import com.ca.devtest.sv.devtools.utils.PackMarFile;
public class PackMarFileTest {
@Test
public void test() throws Exception {
File workingFolder = new File(getClass().getClassLoader().getResource("mar/vsm/proto").toURI());
Map<String, String> config= new HashMap<String, String>();
SimpleDateFormat df= new SimpleDateFormat("YYYY-MM-dd.HH:mm:ss.SSS.Z");
config.put("dateOfMar", df.format(new Date()));
config.put("hostname", getHostName());
File zip = PackMarFile.packVirtualService(workingFolder,"demo", config);
zip.delete();
}
private String getHostName() {
String result="UNKNOWN";
try {
InetAddress address = InetAddress.getLocalHost();
result= address.getHostName();
} catch (UnknownHostException e) {
}
return result;
}
}
<file_sep>/devtest-unit-test-java/src/main/java/com/ca/devtest/sv/devtools/services/v3/DataProtocol.java
package com.ca.devtest.sv.devtools.services.v3;
/**
* @author sm632260
*
*/
public class DataProtocol {
String typeId;
boolean forRequest;
public DataProtocol() {
}
public String getTypeId() {
return typeId;
}
public void setTypeId(String typeId) {
this.typeId = typeId;
}
public boolean getForRequest() {
return forRequest;
}
public void setForRequest(boolean forRequest) {
this.forRequest = forRequest;
}
public static class DataProtocolBuilder{
private final DataProtocol dataProtocolInstance = new DataProtocol();
private DataProtocolBuilder(){}
public static DataProtocolBuilder builder (){
return new DataProtocolBuilder();
}
public DataProtocolBuilder withTypeId(String typeId){
dataProtocolInstance.setTypeId(typeId);
return this;
}
public DataProtocolBuilder withForRequest(boolean forRequest){
dataProtocolInstance.setForRequest(forRequest);
return this;
}
public DataProtocol build(){
return dataProtocolInstance;
}
}
}
<file_sep>/devtest-unit-test-java/src/main/java/com/ca/devtest/sv/devtools/utils/ObjectMapperUtil.java
package com.ca.devtest.sv.devtools.utils;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
public class ObjectMapperUtil {
/***
* Convert given string into object of give class type
*
* @param json - json string to convert
* @param tClass - target object class type
* @return - returns object of given class type
* @param <T>
* @throws Exception
*/
public static <T>T json2Object(String json, Class<T> tClass) throws Exception{
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readValue(json, tClass);
}
/***
* Converts given object into json string
*
* @param object - object which should be converted to json string
* @return - returns json representation of given object
* @param <T>
* @throws Exception
*/
public static <T> String objectToJSON(T object) throws Exception{
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.writeValueAsString(object);
}
/***
* Writes java object to given file
*
* @param file - Name of the file where content should be written
* @param object - object which should be written to the file
* @param <T>
* @throws Exception
*/
public static<T> void objectToFile( File file, T object) throws Exception{
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.writeValue(file, object);
}
/***
* Reads a file into object
*
* @param file - Name of the file from which content should be read
* @param tClass - target object class type
* @return
* @param <T>
* @throws Exception
*/
public static<T> T fileToObject(File file, Class<T> tClass) throws Exception{
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readValue(file, tClass);
}
}
<file_sep>/devtest-unit-test-java/src/test/java/com/ca/devtest/expe/svasacode/SvAsCodeAPI.java
package com.ca.devtest.expe.svasacode;
import java.io.File;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import com.ca.devtest.sv.devtools.services.VirtualServiceInterface;
import org.junit.Test;
import com.ca.devtest.sv.devtools.DevTestClient;
import com.ca.devtest.sv.devtools.protocol.builder.TransportProtocolFromVrsBuilder;
import com.ca.devtest.sv.devtools.services.builder.VirtualServiceBuilder;
/**
*
*/
/**
* @author gaspa03
*
*/
public class SvAsCodeAPI {
@Test
public void testAPI() throws Exception {
File rrpairsFolder = new File(
(SvAsCodeAPI.class.getProtectionDomain().getCodeSource().getLocation().getPath()+"rrpairs"+File.separatorChar+"search_client").replaceAll("%20", " "));
File vrsFile = new File(rrpairsFolder, "vrs_template.xml");
// Create
DevTestClient devtest =
new DevTestClient( "http", "localhost", "VSE", "svpower", "svpower", "demo", "", "");
// build Transport Protocol
TransportProtocolFromVrsBuilder transportBuilder = new TransportProtocolFromVrsBuilder(vrsFile);
// Optional:fill out parameter in your VRS file
transportBuilder.addParameter("port", "8081");
// Virtual Service builder
VirtualServiceBuilder vsbuilder = devtest.fromRRPairs("myservice", rrpairsFolder);
vsbuilder.over(transportBuilder.build());
// Optional : fill out parameters in you rrpairs file
vsbuilder.addKeyValue("clientID", "12345");
// Virtual Service
VirtualServiceInterface sv = vsbuilder.build();
// Deploy VS
sv.deploy();
// unDeploy VS
sv.unDeploy();
}
}
<file_sep>/devtest-unit-test-java/src/main/java/com/ca/devtest/sv/devtools/annotation/processor/AnnotationProcessor.java
package com.ca.devtest.sv.devtools.annotation.processor;
import java.lang.annotation.Annotation;
import java.util.List;
import com.ca.devtest.sv.devtools.DevTestClient;
import com.ca.devtest.sv.devtools.services.VirtualServiceInterface;
/**
* @author gaspa03
*
*/
public interface AnnotationProcessor {
/**
* @return
*/
List<VirtualServiceInterface> process(DevTestClient devTestClient, Annotation annotation) throws Exception;
}
<file_sep>/lisabank-demo/src/main/resources/application.properties
logging.level.org.apache.cxf=INFO
logging.level.com.ca.devtest.sv.devtools.utils=INFO
webservice.url.user=http://www.monsite.com/itkoExamples/EJB3UserControlBean
webservice.url.account=http://www.monsite.com/itkoExamples/EJB3AccountControlBean
webservice.url.token=http://www.monsite.com/itkoExamples/TokenBean
<file_sep>/devtest-unit-test-java/src/test/java/com/ca/devtest/expe/svasacode/SVAsCodeV3API.java
package com.ca.devtest.expe.svasacode;
import com.ca.devtest.sv.devtools.DevTestClient;
import com.ca.devtest.sv.devtools.protocol.builder.TransportProtocolFromVrsBuilder;
import com.ca.devtest.sv.devtools.services.VirtualServiceInterface;
import com.ca.devtest.sv.devtools.services.builder.VirtualServiceBuilder;
import com.ca.devtest.sv.devtools.services.builder.v3.VirtualServiceV3Builder;
import com.ca.devtest.sv.devtools.services.v3.*;
import com.ca.devtest.sv.devtools.v3.HttpUtils;
import com.ca.devtest.sv.devtools.v3.ResponseParser;
import org.junit.Test;
import java.io.File;
public class SVAsCodeV3API {
@Test
public void testAPI() throws Exception {
File rrpairsFolder = new File(
(SvAsCodeAPI.class.getProtectionDomain().getCodeSource().getLocation().getPath() + "v3"
+ File.separatorChar + "rrpair").replaceAll("%20", " "));
// Create
DevTestClient devtest =
new DevTestClient("http", "localhost", "VSE", "svpower", "svpower", "demo", "", "");
// Virtual Service builder
VirtualServiceV3Builder v3VSBuilder = devtest.withV3API("myservice", rrpairsFolder);
v3VSBuilder.setInputFile1("operation-8-req.txt");
v3VSBuilder.setInputFile2("operation-8-rsp.txt");
// build Transport Protocol
Config configObject = Config.ConfigBuilder.builder()
.withVirtualService( VirtualService.VirtualServiceBuilder.builder()
.withName(v3VSBuilder.getDeployedName())
.build())
.withTransportProtocol(
TransportProtocol.TransportProtocolBuilder.builder()
.withBasePath("/")
.withRecordingEndpoint(
Endpoint.EndpointBuilder.builder()
.withPort("8081")
.withSSLConfig(
SSLConfig.SSLConfigBuilder.builder().build()
)
.build()
).build()
).build();
v3VSBuilder.setConfig(ConfigObjectBuilder.convertToJson(configObject));
VirtualServiceInterface sv = v3VSBuilder.build();
// Deploy VS
sv.deploy();
ResponseParser responseParser = HttpUtils.GET(HttpUtils.URL_FORMAT, "http","localhost",
"8081", "import/test/operation-8");
ResponseParser vsResponseParser = HttpUtils.GET_VS_DETAILS("http","localhost", "1505", "VSE", v3VSBuilder.getDeployedName());
//ResponseParser vsSpecificParser = HttpUtils.GET_VS_SPECIFICS(API_PROTOCOL, "localhost", "1505", "VSE", "V3Test.vsV3_Deploy");
assert (responseParser != null);
assert (responseParser.getValue("$.TCEntry[0].termsType").equals("Operation 8 terms"));
assert (vsResponseParser != null);
assert (vsResponseParser.getValue("$.modelName").equals(v3VSBuilder.getDeployedName()));
assert (vsResponseParser.getValue("$.capacity").equals("1"));
assert (vsResponseParser.getValue("$.thinkScale").equals("0"));
assert (vsResponseParser.getValue("$.autoRestartEnabled").equals("true"));
assert (vsResponseParser.getValue("$.executionMode").equals("Most Efficient"));
assert (vsResponseParser.getValue("$.executionModeValue").equals("EFFICIENT"));
assert (vsResponseParser.getValue("$.resourceName").equals("8081 : http : : /"));
assert (vsResponseParser.getValue("$.groupTag").isEmpty());
assert (vsResponseParser.getValue("$.statusDescription").equals("running"));
// unDeploy VS
sv.unDeploy();
}
@Test
public void testAPI2() throws Exception {
File rrpairsFolder = new File(
(SvAsCodeAPI.class.getProtectionDomain().getCodeSource().getLocation().getPath() + "v3"
+ File.separatorChar + "rrpair").replaceAll("%20", " "));
// Create
DevTestClient devtest =
new DevTestClient("http", "localhost", "VSE", "svpower", "svpower", "demo2", "", "");
// Virtual Service builder
VirtualServiceV3Builder v3VSBuilder = devtest.withV3API("myservice", rrpairsFolder);
v3VSBuilder.setInputFile1("operation-8-req.txt");
v3VSBuilder.setInputFile2("operation-8-rsp.txt");
v3VSBuilder.setConfig("{\"virtualService\":{\"version\":\"1.0\",\"name\":\""+v3VSBuilder.getDeployedName()+"\",\"description\":\"Deployed using SV-as-Code\",\"status\":\"\",\"capacity\":0,\"thinkScale\":0,\"autoRestart\":true,\"startOnDeploy\":true,\"groupTag\":\"\"},\"transportProtocol\":{\"typeId\":\"HTTP\",\"basePath\":\"/\",\"useGateway\":false,\"hostHeaderPassThrough\":false,\"recordingEndpoint\":{\"useSSL\":false,\"host\":\"\",\"port\":\"8081\"}}}");
VirtualServiceInterface sv = v3VSBuilder.build();
// Deploy VS
sv.deploy();
ResponseParser responseParser = HttpUtils.GET(HttpUtils.URL_FORMAT, "http","localhost",
"8081", "import/test/operation-8");
ResponseParser vsResponseParser = HttpUtils.GET_VS_DETAILS("http","localhost", "1505", "VSE", v3VSBuilder.getDeployedName());
//ResponseParser vsSpecificParser = HttpUtils.GET_VS_SPECIFICS(API_PROTOCOL, "localhost", "1505", "VSE", "V3Test.vsV3_Deploy");
assert (responseParser != null);
assert (responseParser.getValue("$.TCEntry[0].termsType").equals("Operation 8 terms"));
assert (vsResponseParser != null);
assert (vsResponseParser.getValue("$.modelName").equals(v3VSBuilder.getDeployedName()));
assert (vsResponseParser.getValue("$.capacity").equals("1"));
assert (vsResponseParser.getValue("$.thinkScale").equals("0"));
assert (vsResponseParser.getValue("$.autoRestartEnabled").equals("true"));
assert (vsResponseParser.getValue("$.executionMode").equals("Most Efficient"));
assert (vsResponseParser.getValue("$.executionModeValue").equals("EFFICIENT"));
assert (vsResponseParser.getValue("$.resourceName").equals("8081 : http : : /"));
assert (vsResponseParser.getValue("$.groupTag").isEmpty());
assert (vsResponseParser.getValue("$.statusDescription").equals("running"));
// unDeploy VS
sv.unDeploy();
}
}
<file_sep>/lisabank-demo/src/main/java/com/ca/devtest/lisabank/demo/model/StoreInventory.java
package com.ca.devtest.lisabank.demo.model;
public class StoreInventory {
public Integer integer_0;
public StoreInventory() {
}
public StoreInventory(Integer integer_0) {
this.integer_0 = integer_0;
}
public Integer getInteger_0() {
return integer_0;
}
public void setInteger_0(Integer integer_0) {
this.integer_0 = integer_0;
}
}
<file_sep>/lisabank-demo/src/main/java/com/ca/devtest/lisabank/wsdl/AccountType.java
package com.ca.devtest.lisabank.wsdl;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for accountType.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="accountType">
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="CHECKING"/>
* <enumeration value="SAVINGS"/>
* <enumeration value="CREDIT"/>
* <enumeration value="AUTO_LOAN"/>
* <enumeration value="STUDENT_LOAN"/>
* <enumeration value="MORTGAGE"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "accountType")
@XmlEnum
public enum AccountType {
CHECKING,
SAVINGS,
CREDIT,
AUTO_LOAN,
STUDENT_LOAN,
MORTGAGE;
public String value() {
return name();
}
public static AccountType fromValue(String v) {
return valueOf(v);
}
}
<file_sep>/devtest-unit-test-java/src/main/java/com/ca/devtest/sv/devtools/utils/PackMarFile.java
/**
*
*/
package com.ca.devtest.sv.devtools.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
/**
* @author gaspa03
*
*/
public class PackMarFile {
/**
* @param workingFolder
* @param config
* @return
* @throws IOException
*/
public static File packVirtualService(File workingFolder, String serviceName,
@SuppressWarnings("rawtypes") Map config) throws IOException {
File virtualServiceArchive = File.createTempFile(serviceName, ".mar");
ZipOutputStream zip = null;
try {
FileOutputStream fileWriter = null;
/*
* create the output stream to zip file result
*/
fileWriter = new FileOutputStream(virtualServiceArchive);
zip = new ZipOutputStream(fileWriter);
/*
* add the folder to the zip
*/
addFolderToZip("", serviceName, workingFolder, zip, config);
ZipEntry entry = new ZipEntry(".marinfo");
zip.putNextEntry(entry);
byte[] data = IOUtils.toByteArray(getMarinfoTpl());
data = VelocityRender.render(IOUtils.toString(data, Charset.defaultCharset().name()), config)
.getBytes();
zip.write(data, 0, data.length);
zip.closeEntry();
entry = new ZipEntry(".maraudit");
zip.putNextEntry(entry);
data = IOUtils.toByteArray(getMarAuditTpl());
data = VelocityRender.render(IOUtils.toString(data, Charset.defaultCharset().name()), config)
.getBytes();
zip.write(data, 0, data.length);
zip.closeEntry();
entry = new ZipEntry(serviceName+"/lisa.project");
zip.putNextEntry(entry);
data = IOUtils.toByteArray(getLisaProjectTpl());
data = VelocityRender.render(IOUtils.toString(data, Charset.defaultCharset().name()), config)
.getBytes();
zip.write(data, 0, data.length);
zip.closeEntry();
} finally {
if (null != zip) {
zip.flush();
zip.close();
}
}
return virtualServiceArchive;
}
/**
* @return
*/
private static InputStream getLisaProjectTpl() {
return Thread.currentThread().getContextClassLoader().getResourceAsStream("mar/lisa.project.tpl");
}
/**
* @return
*/
private static InputStream getMarAuditTpl() {
return Thread.currentThread().getContextClassLoader().getResourceAsStream("mar/maraudit.tpl");
}
/**
* @return
*/
private static InputStream getMarinfoTpl() {
return Thread.currentThread().getContextClassLoader().getResourceAsStream("mar/marinfo.tpl");
}
/*
* recursively add files to the zip files
*/
private static void addFileToZip(String path, String serviceName, File folder, ZipOutputStream zip, boolean flag,
@SuppressWarnings("rawtypes") Map config) throws IOException {
/*
* if the folder is empty add empty folder to the Zip file
*/
if (flag) {
zip.putNextEntry(new ZipEntry(path + "/" + folder.getName() + "/"));
} else { /*
* if the current name is directory, recursively traverse it
* to get the files
*/
if (folder.isDirectory()) {
/*
* if folder is not empty
*/
addFolderToZip(path, serviceName, folder, zip, config);
} else {
/*
* write the file to the output
*/
if (shouldPack(folder)) {
String ressource = path + "/" + folder.getName();
zip.putNextEntry(new ZipEntry(path + "/" + folder.getName()));
byte[] data = IOUtils.toByteArray(new FileInputStream(folder));
data = VelocityRender.render(IOUtils.toString(data, Charset.defaultCharset().name()), config)
.getBytes();
zip.write(data, 0, data.length);
updateConfig(config, ressource,serviceName);
// fixing bug
zip.closeEntry();
}
}
}
}
/**
* add in the context file reference
*
* @param config
* @param ressource
* @param serviceName
*/
private static void updateConfig(Map config, String ressource, String serviceName) {
ressource=StringUtils.replace(ressource, serviceName+"/", "");
if (FilenameUtils.wildcardMatch(ressource, "*.vsm")) {
config.put("vsmLocation", ressource);
}
if (FilenameUtils.wildcardMatch(ressource, "*.config")) {
config.put("configLocation", ressource);
}
}
private static boolean shouldPack(File file) {
return FilenameUtils.wildcardMatch(file.getName(), "*.vsi")
|| FilenameUtils.wildcardMatch(file.getName(), "*.vsm")
|| FilenameUtils.wildcardMatch(file.getName(), "*.config");
}
/*
* add folder to the zip file
*/
private static void addFolderToZip(String path, String serviceName, File srcFolder, ZipOutputStream zip,
@SuppressWarnings("rawtypes") Map config) throws IOException {
/*
* check the empty folder
*/
if (srcFolder.list().length == 0) {
addFileToZip(path, serviceName, srcFolder, zip, true, config);
} else {
/*
* list the files in the folder
*/
// FilenameFilter filter = new WildcardFileFilter(new String[] {
// "*.vsm", "*.vsi", "*.config" });
String[] files = srcFolder.list();
for (String fileName : files) {
if (path.equals("")) {
addFileToZip(serviceName, serviceName, new File(srcFolder + "/" + fileName), zip, false, config);
} else {
addFileToZip(path + "/" + srcFolder.getName(), serviceName, new File(srcFolder + "/" + fileName),
zip, false, config);
}
}
}
}
}
<file_sep>/devtest-unit-test-java/src/main/java/com/ca/devtest/sv/devtools/protocol/BaseProtocol.java
/**
*
*/
package com.ca.devtest.sv.devtools.protocol;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* @author gaspa03
*
*/
public abstract class BaseProtocol {
private final String type;
private final HashMap<String, Object> parameters = new HashMap<String, Object>() ;
public BaseProtocol(String type) {
super();
this.type=type;
}
/**
* @return the parameters
*/
public final Map<String, Object> getParameters() {
return parameters;
}
/**
* @return
*/
protected final String printParameters() {
StringBuilder result= new StringBuilder();
if( !parameters.isEmpty()){
Set<String> keys=parameters.keySet();
for (String key : keys) {
result.append("<").append(key).append(">").append(parameters.get(key)).append("</").append(key).append(">");
}
}
return result.toString();
}
/**
* @param definition
*/
protected void printXml(StringBuilder definition){
definition.append("<Protocol type=\"").append(type).append("\">").append(printParameters()).append(doPrintSpecific()).append("</Protocol>");
}
protected abstract String doPrintSpecific();
}
<file_sep>/devtest-unit-test-java/src/main/java/com/ca/devtest/sv/devtools/vse/VirtualServerEnvironmentRemote.java
/**
*
*/
package com.ca.devtest.sv.devtools.vse;
import java.io.IOException;
/**
* @author gaspa03
*
*/
public class VirtualServerEnvironmentRemote implements VirtualServerEnvironment {
public VirtualServerEnvironmentRemote(String aRegistry, String aVseName) {
}
/* (non-Javadoc)
* @see com.ca.devtest.sv.devtools.vse.VirtualServerEnvironment#start()
*/
@Override
public boolean start() throws IOException {
// TODO Auto-generated method stub
return false;
}
/* (non-Javadoc)
* @see com.ca.devtest.sv.devtools.vse.VirtualServerEnvironment#stop()
*/
@Override
public boolean stop() throws RuntimeException {
// TODO Auto-generated method stub
return false;
}
/* (non-Javadoc)
* @see com.ca.devtest.sv.devtools.vse.VirtualServerEnvironment#isRunning()
*/
@Override
public boolean isRunning() throws RuntimeException {
// TODO Auto-generated method stub
return false;
}
}
|
6624ffee8811142c25cc8d74e82cf1a625f845a4
|
[
"Java",
"Maven POM",
"AsciiDoc",
"INI"
] | 60 |
Java
|
CA-DevTest/SV-as-Code-UnitTest
|
df96e46ccfd4c5a6ee25db632923d1e429a52843
|
516b08d979b86300a4e7982ea9eee2d3b456e5b2
|
refs/heads/master
|
<repo_name>HuangYongXuan/el-common-components<file_sep>/README.md
# el-common-components<file_sep>/src/mixins/MdMVVMObject.js
export default {
props: {
value: {
type: Object | String | Number | Array | Boolean
},
formRef: {
type: String,
default: 'form'
},
showValidatorFailMsg: {
type: Boolean,
default: true
},
failMsg: {
type: String,
default: '表单数据不完整'
}
},
data() {
return {
data: this.value
};
},
methods: {
onSubmit(e) {
this.$refs[this.formRef].validate(valid => {
if (valid) {
this.$emit('submit', e);
} else {
this.$emit('fail', this);
if (this.showValidatorFailMsg) {
this.$message.warning(this.failMsg)
}
}
})
}
},
watch: {
async value(n) {
await this.$nextTick();
this.data = n;
},
async data() {
await this.$nextTick();
this.$emit('input', this.data);
}
}
};<file_sep>/src/index.js
import Vue from 'vue';
import MdDateTimeRangePicker from './components/date/MdDateTimeRangePicker';
import MdDateTimeRangePickerAlone from './components/date/MdDateTimeRangePickerAlone';
import MdPagination from './components/page/MdPagination';
import MdTableColumnDatetime from './components/table/MdTableColumnDatetime';
Vue.component('MdDateTimeRangePicker', MdDateTimeRangePicker);
Vue.component('MdDateTimeRangePickerAlone', MdDateTimeRangePickerAlone);
Vue.component('MdPagination', MdPagination);
Vue.component('MdTableColumnDatetime', MdTableColumnDatetime);
|
fce976d046dc454df1608692d9728ed829cdadbb
|
[
"Markdown",
"JavaScript"
] | 3 |
Markdown
|
HuangYongXuan/el-common-components
|
a5a6b462dba05c10a270980c3f9b430d5aec0bd3
|
fc5ee93eeb5aa1e4becd8efda724848f2503b80d
|
refs/heads/master
|
<repo_name>anushajoshi06/example_application<file_sep>/app/src/main/java/com/example/example_app/Dashboard.java
package com.example.example_app;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
public class Dashboard extends AppCompatActivity {
EditText etName, etAge, etPhone, etEmail, etCountry;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_dashboard);
etName = findViewById(R.id.editText2);
etAge = findViewById(R.id.editText3);
etPhone = findViewById(R.id.editText);
etEmail = findViewById(R.id.editText5);
etCountry = findViewById(R.id.editText4);
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String name = etName.getText().toString().trim();
String age = etAge.getText().toString().trim();
String phone = etPhone.getText().toString().trim();
String email = etEmail.getText().toString().trim();
String country = etCountry.getText().toString().trim();
Bundle bundle = new Bundle();
bundle.putString("name", name);
bundle.putString("age", age);
bundle.putString("phone", phone);
bundle.putString("email", email);
bundle.putString("country", country);
Intent intent = new Intent(Dashboard.this, Dashboard2.class);
intent.putExtras(bundle);
startActivity(intent);
overridePendingTransition(android.R.anim.slide_in_left,android.R.anim.slide_out_right);
}
});
}
}
|
1ddf30533bfc86f4a156bce6a7a70c8ce937fbe4
|
[
"Java"
] | 1 |
Java
|
anushajoshi06/example_application
|
47532852b2950e2eac2687a6b62e87db54720dc8
|
5b45300e4ece020ec82dade000ad8391b17e71d4
|
refs/heads/master
|
<repo_name>simon-rock/emacs_config<file_sep>/doc/regexp_test.py
#coding: utf8
import re
import string
text = "JGood is a handsome boy, he is cool, clever, and so on..."
content1 = "hello.cpp"
def match_case(content, regexpstr):
prog = re.compile(regexpstr)
res = re.match(prog, content)
if res:
print "true"
print res.group(), "--", res.groups()
else:
print "false"
#you can test regexp in emacs
def test_regexp_for_emacs():
#match_case(content1, r"(\w+).(cpp)") # group "()" is only valid in python
match_case(content1, r"\w+[.]cpp")
# match_case(text, r"(\w+)\s")
# match_case("translate(57.077812,12.405725) scale(1.530265,1.530265)", "(\S+)\((\S+),(\S+)\)\s+(\S+)\((\S+),(\S+)\)")
if __name__ == "__main__":
test_regexp_for_emacs()
<file_sep>/other/install26.sh
#! /bin/bash
HOME=~
EMACS_CONF_HOME=~/.emacs.d
PYTHON_PACKET_PATH=`python -c "from distutils.sysconfig import get_python_lib; print get_python_lib()"`
CMD_PATH=`pwd`/../
cd ~
HOME=`pwd`
EMACS_CONF_HOME=$HOME/.emacs.d
echo $PYTHON_PACKET_PATH
#echo "check python version, need 2.7"
#ret=`echo "$PYTHON_PACKET_PATH" | grep "2.7" | wc -l`
#if [ $ret -ne 1 ];then #cmp char* ge ne
# echo "check python version failed"
# exit 1
#fi
sudo yum install ncurses-devel.x86_64 -y
if [ $? -ne 0 ]; then
echo "Error: failed!"
exit 1
fi
sudo yum install unzip -y
if [ $? -ne 0 ]; then
echo "Error: failed!"
exit 1
fi
echo "download emacs..."
cd $CMD_PATH/../
sudo dnf install emacs -y
echo "install plug-in"
cd $CMD_PATH
cp -fr config/.emacs.d $HOME/
cp -fr config/.emacs $HOME/
cp -fr config/emacs26/.emacs.d $HOME/
cp -fr config/emacs26/.emacs $HOME/
echo "skip install python plug-in"
exit
cd plug-in
tar xzvf pymacs.tgz
sudo cp -rf pymacs/Pymacs pycomplete.py $PYTHON_PACKET_PATH
cd ropemacs
tar xzvf rope-0.9.4.tar.gz
cd rope-0.9.4
sudo python setup.py install
cd ..
tar xzvf ropemode-0.2.tar.gz
cd ropemode-0.2
sudo python setup.py install
cd ..
tar xzvf ropemacs-0.7.tar.gz
cd ropemacs-0.7
sudo python setup.py install
cd ..
cd $EMACS_CONF_HOME/install
echo "cscope ..."
sudo cp cscope_linux_15.8a/cscope cscope_linux_15.8a/cscope-indexer /usr/local/bin -f
sudo chmod +x /usr/local/bin/cscope
sudo chmod +x /usr/local/bin/cscope-indexer
echo "cedet &ecb ..."
tar xzvf cedet-1.0.tar.gz
cd cedet-1.0
make
if [ $? -ne 0 ]; then
echo "Error: failed!"
exit 1
fi
cd ..
rm -rf ecb-2.40
unzip ecb-2.40.zip
#update highlight
cp ecb-face.el ecb-2.40
echo "clang ..."
sudo yum install clang -y
if [ $? -ne 0 ]; then
echo "Error: failed!"
exit 1
fi
echo "*************************************"
echo "please remove erlang config from .emacs if don't need"
echo "please remove sigo config from .emacs if don't need"
echo "please copy these path to all-auto-complete-settgings.el for clang"
echo "*************************************"
echo "" | g++ -v -x c++ -E -
<file_sep>/other/install.sh
#! /bin/bash
HOME=~
EMACS_CONF_HOME=~/.emacs.d
PYTHON_PACKET_PATH=`python -c "from distutils.sysconfig import get_python_lib; print get_python_lib()"`
CMD_PATH=`pwd`/../
cd ~
HOME=`pwd`
EMACS_CONF_HOME=$HOME/.emacs.d
echo $PYTHON_PACKET_PATH
echo "check python version, need 2.7"
ret=`echo "$PYTHON_PACKET_PATH" | grep "2.7" | wc -l`
if [ $ret -ne 1 ];then #cmp char* ge ne
echo "check python version failed"
exit 1
fi
sudo yum install ncurses-devel.x86_64 -y
if [ $? -ne 0 ]; then
echo "Error: failed!"
exit 1
fi
sudo yum install unzip -y
if [ $? -ne 0 ]; then
echo "Error: failed!"
exit 1
fi
echo "download emacs..."
cd $CMD_PATH/../
#wget http://ftp.gnu.org/pub/gnu/emacs/emacs-23.3b.tar.gz
git clone [email protected]:simon-rock/emacs-23.3b.git
if [ $? -ne 0 ]; then
echo "Error: failed!"
exit 1
fi
#rm -rf emacs-23.2
#tar xzvf emacs-23.2b.tar.gz
#cd emacs-23.2
cd emacs-23.3b
./configure --with-x=no
make
sudo make install
if [ $? -ne 0 ]; then
echo "Error: failed!"
exit 1
fi
echo "install plug-in"
cd $CMD_PATH
cp -fr config/.emacs.d $HOME/
cp -fr config/.emacs $HOME/
echo "install python plug-in"
cd plug-in
tar xzvf pymacs.tgz
sudo cp -rf pymacs/Pymacs pycomplete.py $PYTHON_PACKET_PATH
cd ropemacs
tar xzvf rope-0.9.4.tar.gz
cd rope-0.9.4
sudo python setup.py install
cd ..
tar xzvf ropemode-0.2.tar.gz
cd ropemode-0.2
sudo python setup.py install
cd ..
tar xzvf ropemacs-0.7.tar.gz
cd ropemacs-0.7
sudo python setup.py install
cd ..
cd $EMACS_CONF_HOME/install
echo "cscope ..."
sudo cp cscope_linux_15.8a/cscope cscope_linux_15.8a/cscope-indexer /usr/local/bin -f
sudo chmod +x /usr/local/bin/cscope
sudo chmod +x /usr/local/bin/cscope-indexer
echo "cedet &ecb ..."
tar xzvf cedet-1.0.tar.gz
cd cedet-1.0
make
if [ $? -ne 0 ]; then
echo "Error: failed!"
exit 1
fi
cd ..
rm -rf ecb-2.40
unzip ecb-2.40.zip
#update highlight
cp ecb-face.el ecb-2.40
echo "clang ..."
sudo yum install clang -y
if [ $? -ne 0 ]; then
echo "Error: failed!"
exit 1
fi
echo "*************************************"
echo "please remove erlang config from .emacs if don't need"
echo "please remove sigo config from .emacs if don't need"
echo "please copy these path to all-auto-complete-settgings.el for clang"
echo "*************************************"
echo "" | g++ -v -x c++ -E -
|
f5f06f19d6bbb3c1e7001a105a79efd4e1d558a0
|
[
"Python",
"Shell"
] | 3 |
Python
|
simon-rock/emacs_config
|
a3969bdfb6491c1f6fceda482d27062ca23e41fd
|
883aed39b2cdd3276790c8c86373ae8bc626180c
|
refs/heads/master
|
<file_sep>angular.module('myApp',[]).
controller('ControllerA',function($scope){
$scope.title = 'Angular Power';
$scope.bannerh = 'Angular Templates';
$scope.message = 'Hello from this App';
$scope.bannerp = 'Dynamic Home page';
$scope.fheading = 'Core Angular';
$scope.theading = 'HTML template ';
$scope.sheading = 'Dependency injection';
$scope.lheading ='Angular 2 was a compiler';
});
<file_sep>function tellTime(){
var time = new Date();
var hour = time.getHours(),
ampm;
var minutes = time.getMinutes();
var seconds = time.getSeconds();
var week = time.getDay();
var day = time.getDate();
var month = time.getMonth();
var year = time.getFullYear();
var phour = document.getElementById('hour');
var pampm = document.getElementById('ampm');
var pminutes = document.getElementById('minutes');
var pseconds = document.getElementById('seconds');
var pweek = document.getElementById('week');
var pday = document.getElementById('day');
var pmonth = document.getElementById('month');
var pyear = document.getElementById('year');
var weeks = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
pweek.textContent = weeks[week];
var months = ['January','Febreary','March','April','May','June','July','August','September','October','November','December'];
pmonth.textContent = months[month];
pyear.textContent = year;
if(hour >= 12){
hour = hour - 12;
ampm ='PM';
}else{
ampm ='AM';
}
if(hour == 0){
hour == 12;
}
phour.textContent = hour;
pampm.textContent = ampm;
pminutes.textContent = minutes;
pseconds.textContent = seconds;
}
setInterval(tellTime,1000);<file_sep>
<?php
include"inc/header.php";
?>
<div class="banner parallax--bg">
<img src="images/banner-bg.jpeg" alt="">
<div class="container">
<h2 class="banner-title">{{bannerh}}</h2>
<p class="banner-txt">{{bannerp}}</p>
<a href="/" class="btn btn-primary">More Info</a>
</div>
</div>
<!-- Info Area -->
<section id="info">
<div class="container">
<div class="row">
<div class="col-lg-12">
<h2 class="main-heading">{{title}}</h2>
<p>This theme features a flexible, UX friendly </p>
<a class="btn btn-lg btn-danger">What We Offer</a>
</div>
</div>
<p>Input Something in the input Box</p>
<p>Name: <input type="text" ng-model="name" id="name"/></p>
<p>{{name}}</p>
{{1+1}}
</section>
<section id="blog">
<h2 class="main-heading">{{title}}</h2>
<div class="container">
<div class="row">
<div class="col-md-6 col-sm-6">
<h3>Bounce Effect</h3>
<img id="img1" src="images/1.jpg" alt="">
<h4>{{fheading}}</h4>
</div>
<div class="col-md-6 col-sm-6">
<h3>Slide Effect</h3>
<img id="img2" src="images/2.jpg" alt="">
<h4>{{sheading}}</h4>
</div>
<div class="col-md-6 col-sm-6">
<h3>Bounce Effec</h3>
<img id="img3" src="images/3.jpg" alt="">
<h4>{{theading}}</h4>
</div>
<div class="col-md-6 col-sm-6">
<h3>Explode Effect</h3>
<img id="img4"src="images/4.jpg" alt="">
<h4>{{lheading}}</h4>
</div>
</div>
</div>
</section>
<section id="info1">
<div class="container">
<div class="row">
<div class="col-lg-12">
<h3>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Debitis,
nesciunt? Voluptas dolorem blanditiis ex nam maxime.</h3>
{{message}}
</div>
</div>
<div class="row">
<div class="col-md-3 col-sm-6 info-pet">
<img src="images/img1.jpg" alt="">
<h4>Lorem, ipsum dolor.</h4>
</div>
<div class="col-md-3 col-sm-6 info-pet">
<img src="images/img1.jpg" alt="">
<h4>Lorem, ipsum dolor.</h4>
</div>
<div class="col-md-3 col-sm-6 info-pet">
<img src="images/img1.jpg" alt="">
<h4>Lorem, ipsum dolor.</h4>
</div>
<div class="col-md-3 col-sm-6 info-pet">
<img src="images/img1.jpg" alt="">
<h4>Lorem, ipsum dolor.</h4>
</div>
</div>
</div>
</section>
<section id="tellTime">
<div class="container">
<div class="row">
<div class="col-lg-12">
<h2>Tell The Time</h2>
<hr>
</div>
</div>
<div class="row">
<div class="col-md-6 col-sm-6">
<div class="widget">
<div class="time">
<p id="week" class="week"></p>
<p id="month" class="month"></p>
<p>-</p>
<p id="day" class="day"></p>
<p id="year" class="year"></p>
</div>
<div class="clock">
<p id="hour" class="hour"></p>
<p>:</p>
<p id="minutes" class="minutes"></p>
<div class="seconds-box">
<p id="ampm" class="ampm"></p>
<p id="seconds" class="seconds"></p>
</div>
</div>
</div>
</div>
<div class="col-md-6 col-sm-6 box text-center">
<h2>Amazing Templates</h2>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit.
Earum nihil praesentium provident repudiandae qui quas excepturi
enim modi minus, esse iste quaerat molestias voluptatem quibusdam
dignissimos ipsum adipisci.</p>
<a href="/" class="btn btn-danger">More Info</a>
</div>
</div>
</div>
</section>
<section id="contact-area">
<div class="container">
<div class="row">
<div class="col-lg-12">
<h2>Contact-me</h2>
{{message}}
<hr>
</div>
</div>
<div class="row text-center">
<div class="col-md-4">
<i class="fa fa-home"></i>
<h2>Location</h2>
</div>
<div class="col-md-4">
<i class="fa fa-file"></i>
<h2>Email-Me</h2>
</div>
<div class="col-md-4">
<i class="fa fa-envelope"></i>
<h2>Contact-Me</h2>
</div>
</div>
</div>
</section>
<section id="cta">
<div class="container">
<h2>Subscribe For News Letters</h2>
<a href="#" class="btn btn-primary">Get News Letters</a>
</div>
</section>
<section id="links">
<div class="container">
<div class="row">
<div class="col-lg-12">
<h2>Follow Us</h2>
<hr>
</div>
</div>
<div class="row">
<div class="col-md-4">
<img class="img-responsive" src="images/partner1.gif" alt="">
<h2>Googlee...!</h2>
</div>
<div class="col-md-4">
<img class="img-responsive" src="images/partner2.jpg" alt="">
<h2>yahhoo..!</h2>
</div>
<div class="col-md-4">
<img class="img-responsive" src="images/partner3.jpg" alt="">
<h2>Bingg....!</h2>
</div>
</div>
</div>
</section>
<?php
include"inc/footer.php";
?><file_sep>$("document").ready(function(){
$("#img1").click(function(e){
$(this).effect("shake",{
direction:"down", distance:20, times:5}, 3000);
});
$("#img2").click(function(e){
$(this).effect("slide",{
direction:"down", distance:200}, 3000, function(){
$(this).effect("slide",{
direction:"right", distance:200}, 3000);
});
});
$("#img3").click(function(){
$(this).effect("shake",{
direction:"up", distance:20, times:5}, 3000);
});
$("#img4").click(function(e){
$(this).effect("slide", {
direction:"up", distance:200}, 3000, function(){
$(this).effect("slide",{
direction:"left", distance:200}, 3000);
});
});
}); <file_sep><?php
include("inc/header.php");
?>
<h2>Welcome to my Blog</h2>
<hr>
<div class="container">
<div class="row">
<div class="col-lg-8">
<img src="images/1.jpg" alt="">
<h3>The Best Programming Language of 2016<h3>
<hr>
<p>Lorem ipsum dolor sit amet consectetur, adipisicing
elit. Ea officia eos nostrum dolor aliquid repellendus
tenetur facilis perferendis eligendi, voluptatibus
eaque quos ex assumenda, reprehenderit dolores
facere laboriosam porro recusandae.</p>
<a class="btn btn-primary"href="">Learn More</a>
</div>
</div>
</div>
<?php
include("inc/footer.php");
?>
|
d53e89f8da0475074543f9fc7e86d5c605d5b558
|
[
"JavaScript",
"PHP"
] | 5 |
JavaScript
|
UxDeveloper82/tres-demo
|
3535cf58d9bab0f3ff6c8e892e202ba888414e71
|
28e6be8f77070338f0052050a8e2f172c74d273e
|
refs/heads/master
|
<file_sep>import logging
import cv2
import numpy as np
import socket
import sys
import time
from senseact.communicator import Communicator
class RealSenseCommunicator(Communicator):
"""
Intel Real Sense Communicator for interfacing.
"""
def __init__(self, host='localhost', port=5000, height=480, width=640, num_channels=3):
# Create a TCP/IP socket
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect the socket to the port where the server is listening
self.server_address = (host, port)
self._height = height
self._width = width
self._num_channels = num_channels
self._packet_size = self._height * self._width * self._num_channels
self._old_image = np.zeros((self._num_channels, self._height, self._width), dtype=np.uint8)
sensor_args = {
'array_len': self._packet_size,
'array_type': 'd',
'np_array_type': 'd',
}
super(RealSenseCommunicator, self).__init__(use_sensor=True,
use_actuator=False,
sensor_args=sensor_args,
actuator_args={})
def run(self):
print('connecting to {} port {}'.format(*self.server_address))
self.sock.connect(self.server_address)
super(RealSenseCommunicator, self).run()
self.sock.sendall(b'done')
self.sock.close()
def terminate(self):
self.sock.sendall(b'done')
self.sock.close()
super(RealSenseCommunicator, self).terminate()
def _sensor_handler(self):
self.sock.sendall(b'get')
received_data = b''
while len(received_data) < self._packet_size:
received_data += self.sock.recv(self._packet_size)
image = np.frombuffer(received_data, dtype=np.uint8)
# Check for image change
if np.array_equal(image, self._old_image):
return
self._old_image = image
self.sensor_buffer.write(image.flatten().astype(float) / 255)
time.sleep(0.01)
def _actuator_handler(self):
"""
There is no actuator for cameras.
"""
raise RuntimeError("Real Sense Communicator does not have an actuator handler.")
if __name__ == "__main__":
communicator = RealSenseCommunicator()
communicator.run()
<file_sep>device="cuda:0"
dataset="path/to/cache/<name>.pkl"
n_batches=(64)
decay_learning_rates=(3e-4)
schedulers=('none')
batch_norms=('False')
bi_directionals=('False')
weight_inits=('custom')
ks=(15)
alpha_nets=('lstm')
n_epochs=(16384)
opt=('adam')
comment=('traj32_learnseparate_NoRegularize_expstacked_Q0.08')
storage_base_path="path/to/result/store/${comment}/"
resume_training_path=("none")
measurement_net=('cnn')
debug=('True')
nl=('relu')
free_nats=(0)
traj_len=(32)
init_cov=(20.0)
measurement_uncertainties=('learn_separate')
weight_decay=(1e-5)
use_stochastic_dynamics=('False')
for n in {1..1}; do
lam_rec=0.95
lam_kl=0.80
n_annealing_epoch_beta=0
opt_vae_epoch=0
opt_vae_kf_epoch=2048
for scheduler in ${schedulers[@]}; do
for batch_norm in ${batch_norms[@]}; do
for k in ${ks[@]}; do
for weight_init in ${weight_inits[@]}; do
for n_batch in ${n_batches[@]}; do
for alpha_net in ${alpha_nets[@]}; do
for lr in ${decay_learning_rates[@]}; do
for bi_directional in ${bi_directionals[@]}; do
for n_epoch in ${n_epochs[@]}; do
for measurement_uncertainty in ${measurement_uncertainties[@]}; do
python3 ../srl/train.py \
--k $k \
--dim_a 2 \
--dim_z 3 \
--dim_alpha 3 \
--n_worker 4 \
--use_binary_ce "False" \
--beta1 0.9 \
--beta2 0.999 \
--n_epoch $n_epoch \
--debug $debug \
--comment $comment \
--n_batch $n_batch \
--device $device \
--lr $lr \
--weight_init $weight_init \
--dataset $dataset \
--lam_rec $lam_rec \
--lam_kl $lam_kl \
--storage_base_path $storage_base_path \
--resume_training_path $resume_training_path \
--scheduler $scheduler \
--fc_hidden_size 128 \
--alpha_hidden_size 128 \
--use_bidirectional $bi_directional \
--use_batch_norm $batch_norm \
--measurement_net $measurement_net \
--transition_noise 0.08 \
--emission_noise 1.0 \
--opt_vae_epochs $opt_vae_epoch \
--opt_vae_kf_epochs $opt_vae_kf_epoch \
--n_annealing_epoch_beta $n_annealing_epoch_beta \
--opt $opt \
--alpha_net $alpha_net \
--task "pendulum64" \
--val_split 0 \
--dim_x "1,64,64" \
--non_linearity $nl \
--traj_len $traj_len \
--init_cov $init_cov \
--free_nats $free_nats \
--measurement_uncertainty $measurement_uncertainty \
--weight_decay $weight_decay \
--use_stochastic_dynamics $use_stochastic_dynamics \
done
done
wait
done
done
done
done
done
done
done
done
done<file_sep>import numpy as np
import torch
import torch.nn as nn
import torch.distributions as tdist
import time
class Flatten(nn.Module):
def forward(self, x):
return x.view(x.size(0), -1)
class FullyConvEncoderVAE(nn.Module):
def __init__(self, input=1, latent_size=12, bn=True, extra_scalars=0,
extra_scalars_conc=0, drop=False, nl=nn.ReLU(), stochastic=True, img_dim="64"):
super(FullyConvEncoderVAE, self).__init__()
self.stochastic = stochastic
self.layers = nn.ModuleList()
self.extra_scalars = extra_scalars
self.extra_scalars_conc = extra_scalars_conc
self.latent_size = latent_size
self.layers.append(nn.Conv2d(input, 32, 4, stride=2, bias=False))
if bn: self.layers.append(nn.BatchNorm2d(32, track_running_stats=True))
if drop: self.layers.append(nn.Dropout(p=0.5))
self.layers.append(nl)
self.layers.append(nn.Conv2d(32, 64, 4, stride=2, bias=False))
if bn: self.layers.append(nn.BatchNorm2d(64, track_running_stats=True))
if drop: self.layers.append(nn.Dropout(p=0.5))
self.layers.append(nl)
self.layers.append(nn.Conv2d(64, 128, 4, stride=2, bias=False))
if bn: self.layers.append(nn.BatchNorm2d(128, track_running_stats=True))
if drop: self.layers.append(nn.Dropout(p=0.5))
self.layers.append(nl)
self.layers.append(nn.Conv2d(128, 256, 4, stride=2, bias=False))
if bn: self.layers.append(nn.BatchNorm2d(256, track_running_stats=True))
if drop: self.layers.append(nn.Dropout(p=0.5))
self.layers.append(nl)
if img_dim == "64":
n_size = 256 * 2 * 2
elif img_dim == "128":
n_size = 256 * 6 * 6
else:
raise NotImplementedError()
if self.stochastic:
self.fc_mu = nn.Linear(n_size, latent_size + extra_scalars_conc)
self.fc_logvar = nn.Linear(n_size, latent_size)
else:
self.fc = nn.Linear(n_size, latent_size)
if self.extra_scalars > 0:
self.fc_extra = nn.Sequential(
nn.Linear(n_size, 1024),
nn.ELU(),
nn.Linear(1024, 1024),
nn.ReLU(),
nn.Linear(1024, self.extra_scalars),
nn.ELU(alpha=4)
)
self.flatten = Flatten()
def forward(self, x):
for i in range(len(self.layers)):
x = self.layers[i](x)
x = self.flatten(x)
if self.stochastic:
x_mu = self.fc_mu(x)
mu = x_mu[:, :self.latent_size]
logvar = self.fc_logvar(x)
# Reparameterize
std = torch.exp(logvar / 2.0)
eps = torch.randn_like(std)
z = mu + eps * std
# Extra variables with shared network
if self.extra_scalars > 0:
extra_scalars = self.fc_extra(x)
# return z, mu, logvar, torch.exp(extra_scalars)
return z, mu, logvar, extra_scalars
if self.extra_scalars_conc > 0:
extra_scalars = x_mu[:, self.latent_size:]
return z, mu, logvar, extra_scalars
return z, mu, logvar
else:
z = self.fc(x)
if self.extra_scalar_size > 0:
extra_scalars = self.fc_extra(x)
return z, extra_scalars
if self.extra_scalars_conc > 0:
extra_scalars = x_mu[self.latent_size:]
return z, extra_scalars
return z
class FullyConvDecoderVAE(nn.Module):
def __init__(self, input=1, latent_size=12, output_nl=nn.Tanh(), bn=True,
drop=False, nl=nn.ReLU(), img_dim="64"):
super(FullyConvDecoderVAE, self).__init__()
self.bn = bn
self.drop = drop
self.layers = nn.ModuleList()
if img_dim == "64":
n_size = 256 * 2 * 2
elif img_dim == "128":
n_size = 256 * 6 * 6
else:
raise NotImplementedError()
self.layers.append(nn.ConvTranspose2d(n_size, 128, 5, stride=2, bias=False))
if bn: self.layers.append(nn.BatchNorm2d(128))
if drop: self.layers.append(nn.Dropout(p=0.5))
self.layers.append(nl)
self.layers.append(nn.ConvTranspose2d(128, 64, 5, stride=2, bias=False))
if bn: self.layers.append(nn.BatchNorm2d(64, track_running_stats=True))
if drop: self.layers.append(nn.Dropout(p=0.5))
self.layers.append(nl)
if img_dim == "64":
self.layers.append(nn.ConvTranspose2d(64, 32, 6, stride=2, bias=False))
if bn: self.layers.append(nn.BatchNorm2d(32, track_running_stats=True))
if drop: self.layers.append(nn.Dropout(p=0.5))
self.layers.append(nl)
self.layers.append(nn.ConvTranspose2d(32, input, 6, stride=2, bias=False))
if bn: self.layers.append(nn.BatchNorm2d(input, track_running_stats=True))
if drop: self.layers.append(nn.Dropout(p=0.5))
elif img_dim == "128":
self.layers.append(nn.ConvTranspose2d(64, 32, 5, stride=2, bias=False))
if bn: self.layers.append(nn.BatchNorm2d(32, track_running_stats=True))
if drop: self.layers.append(nn.Dropout(p=0.5))
self.layers.append(nl)
self.layers.append(nn.ConvTranspose2d(32, 16, 6, stride=2, bias=False))
if bn: self.layers.append(nn.BatchNorm2d(16, track_running_stats=True))
if drop: self.layers.append(nn.Dropout(p=0.5))
self.layers.append(nn.ConvTranspose2d(16, input, 6, stride=2, bias=False))
if bn: self.layers.append(nn.BatchNorm2d(input, track_running_stats=True))
if drop: self.layers.append(nn.Dropout(p=0.5))
else:
raise NotImplementedError()
if output_nl != None:
self.layers.append(output_nl)
self.linear = nn.Linear(latent_size, n_size, bias=False)
self.batchn = nn.BatchNorm1d(n_size)
self.dropout = nn.Dropout(p=0.5)
self.nl = nl
def forward(self, x):
if self.bn:
x = self.nl(self.batchn(self.linear(x)))
elif self.drop:
x = self.nl(self.dropout(self.linear(x)))
else:
x = self.nl(self.linear(x))
x = x.unsqueeze(-1)
x = x.unsqueeze(-1)
for i in range(len(self.layers)):
x = self.layers[i](x)
return x
class FCNEncoderVAE(nn.Module):
def __init__(self, dim_in, dim_out, bn=False, drop=False, nl=nn.ReLU(), hidden_size=800, stochastic=True):
super(FCNEncoderVAE, self).__init__()
self.flatten = Flatten()
self.stochastic = stochastic
self.bn = bn
self.layers = nn.ModuleList()
self.layers.append(torch.nn.Linear(dim_in, hidden_size))
if bn: self.layers.append(nn.BatchNorm1d(hidden_size, track_running_stats=True))
if drop: self.layers.append(nn.Dropout(p=0.5))
self.layers.append(nl)
self.layers.append(torch.nn.Linear(hidden_size, hidden_size))
if bn: self.layers.append(nn.BatchNorm1d(hidden_size, track_running_stats=True))
if drop: self.layers.append(nn.Dropout(p=0.5))
self.layers.append(nl)
if stochastic:
self.layers.append(torch.nn.Linear(hidden_size, 2 * dim_out))
else:
self.layers.append(torch.nn.Linear(hidden_size, dim_out))
def forward(self, x):
x = self.flatten(x)
for l in self.layers:
x = l(x)
if self.stochastic:
print(x.shape)
mu, logvar = x.chunk(2, dim=1)
# Reparameterize
std = torch.exp(logvar / 2.0)
eps = torch.randn_like(std)
z = mu + eps * std
return z, mu, logvar
else:
return x
class FCNDecoderVAE(nn.Module):
def __init__(self, dim_in, dim_out, bn=False, drop=False, nl=nn.ReLU(), output_nl=None, hidden_size=800):
super(FCNDecoderVAE, self).__init__()
self.dim_out = dim_out
self.layers = nn.ModuleList()
self.layers.append(torch.nn.Linear(dim_in, hidden_size))
if bn: self.layers.append(nn.BatchNorm1d(hidden_size, track_running_stats=True))
if drop: self.layers.append(nn.Dropout(p=0.5))
self.layers.append(nl)
self.layers.append(torch.nn.Linear(hidden_size, hidden_size))
if bn: self.layers.append(nn.BatchNorm1d(hidden_size, track_running_stats=True))
if drop: self.layers.append(nn.Dropout(p=0.5))
self.layers.append(nl)
self.layers.append(torch.nn.Linear(hidden_size, int(np.product(dim_out))))
if output_nl != None:
self.layers.append(output_nl)
def forward(self, z):
for l in self.layers:
z = l(z)
x = z.view(-1, *self.dim_out)
return x
class RNNAlpha(nn.Module):
"""
This class defines the GRU-based or LSTM-based dynamics parameter network alpha from
https://github.com/simonkamronn/kvae/blob/master/kvae/filter.py.
Args:
input_size: Input dimension
hidden_size: Hidden state dimension
K: Mixture amount
layers: Number of layers
bidirectional: Use bidirectional version
net_type: Use the LSTM or GRU variation
"""
def __init__(self, input_size, hidden_size=128, K=1, layers=1, bidirectional=False, net_type="lstm"):
super(RNNAlpha, self).__init__()
self.K = K
self.hidden_size = hidden_size
self.bidirectional = bidirectional
self.layers = layers
if net_type == "gru":
self.rnn = nn.GRU(input_size=input_size, hidden_size=hidden_size,
num_layers=layers, bidirectional=bidirectional)
elif net_type =="lstm":
self.rnn = nn.LSTM(input_size=input_size, hidden_size=hidden_size,
num_layers=layers, bidirectional=bidirectional)
if bidirectional:
self.linear = nn.Linear(in_features=2*hidden_size, out_features=K)
else:
self.linear = nn.Linear(in_features=hidden_size, out_features=K)
self.softmax = nn.Softmax(dim=-1)
def forward(self, a, h=None):
"""
Forward call to produce the alpha mixing weights.
Args:
a: pseudo measurements from the VAEs (seq_len, batch_size, dim_a)
h: hidden state of the LSTM (num_layers * num_directions, batch_size, hidden_size) or None. If None, h is defaulted as 0-tensor
Returns:
alpha: mixing vector of dimension K (batch_size, seq_len, K)
"""
L, N, _ = a.shape
if h is None:
x, h = self.rnn(a)
else:
x, h = self.rnn(a, h)
if self.bidirectional:
x = x.reshape(L * N, 2*self.hidden_size) # (seq_len * batch_size, 2 * hidden_size)
else:
x = x.reshape(L * N, self.hidden_size) # (seq_len * batch_size, hidden_size)
x = self.linear(x)
alpha = self.softmax(x)
alpha = alpha.reshape(L, N, self.K).transpose(1,0) # (batch_size, seq_len, hidden_size)
return alpha, h
class LGSSM(nn.Module):
"""
This class defines a Kalman Filter (Linear Gaussian State Space model), possibly with a dynamics parameter
network alpha which uses a weighed combination of base linear matrices.
Based on https://github.com/simonkamronn/kvae/blob/master/kvae/filter.py.
"""
def __init__(self, dim_z, dim_a, dim_u, alpha_net, device,
K=4, init_cov=20.0, transition_noise=1., emission_noise=1., init_kf_matrices=1.):
super(LGSSM, self).__init__()
self.dim_z = dim_z
self.dim_a = dim_a
self.dim_u = dim_u
self.device = device
# initial distribution p(z0)
self.mu_0 = torch.zeros((dim_z, 1), requires_grad=False, device=device)
self.Sigma_0 = init_cov * torch.eye(dim_z, requires_grad=False, device=device)
self.A = nn.Parameter(torch.eye(dim_z, device=device).repeat(K, 1, 1))
self.B = nn.Parameter(init_kf_matrices * torch.rand((K, dim_z, dim_u), device=device))
self.C = nn.Parameter(init_kf_matrices * torch.rand((K, dim_a, dim_z), device=device))
# initial latent state
self.z_n1 = nn.Parameter(torch.zeros((dim_z, 1), device=device))
# untrainable uncertainties for now
self.Q = torch.eye(dim_z, requires_grad=False, device=device) * transition_noise
self.R = torch.eye(dim_a, requires_grad=False, device=device) * emission_noise
self.I = torch.eye(dim_z, requires_grad=False, device=device)
self.eps = 0
# amount of mixture components
self.K = K
# dynamic parameter network
self.alpha_net = alpha_net.to(device=device)
def initialize(self, a, u, s=1.0, R=None):
"""
Initialize state with a window of "T".
Args:
a: Initial encoded measurements (batch_size, T, dim_a) e.g. [a_0, a_1, ..., a_(T-1)]
u: Initial control inputs (batch_size, T, dim_u) e.g. [u_1, u_2, ..., u_T]
s: (batch_size, T, dim_a, dim_a)
R: (batch_size, T, dim_a, dim_a)
Returns:
mu_i: latest mu filtered @ index T - 1, (batch_size, dim_z, 1)
Sigma_i: latest Sigma filtered @ index T - 1, (batch_size, dim_z, dim_z)
alpha_i: latest alpha calculated from index T -1, (batch_size, K)
h_i: latest hidden state @ index T
"""
with torch.no_grad():
backward_states = self.smooth(a, u, s=s, R=R)
mu_smooth, Sigma_smooth, _, _, _, _, _, alpha_smooth, h_last = backward_states
# initial state is last filtered state @ index T-1
mu_i = mu_smooth[:, -1, :, :] # mu_smooth @ index T - 1, (batch_size, dim_z, 1)
Sigma_i = Sigma_smooth[:, -1, :, :] # Sigma_smooth @ index T - 1, (batch_size, dim_z, dim_z)
alpha_i = alpha_smooth[:, -1, :] # alpha @ index T calculated from index T -1, (batch_size, K)
h_i = h_last
return mu_i, Sigma_i, alpha_i, h_i
def predict(self, mu_tn1, Sigma_tn1, alpha_t, h_t, u_f):
"""
Predict or generate "pred_len" future states based on control input "u_f"
Args:
mu_tn1: initial mu filtered @ index T - 1 (batch_size, dim_z, 1)
Sigma_tn1: initial Sigma filtered @ index T - 1, (batch_size, dim_z, dim_z)
alpha_t: initial alpha T calculated from index T-1, (batch_size, K)
h_t: initial hidden state @ index T
u_f: Future control inputs (batch_size, pred_len, dim_u) [u_{T}, u_{T+1}, ..., u_{T+pred_len-1}]
Returns:
z: (batch_size, pred_len, dim_z, 1)
mu: (batch_size, pred_len, dim_z, 1)
Sigma: (batch_size, pred_len, dim_z, dim_z)
a: (batch_size, pred_len, dim_a, 1)
A: (batch_size, pred_len, dim_z, dim_z)
B: (batch_size, pred_len, dim_z, dim_u)
C: (batch_size, pred_len, dim_a, dim_z)
"""
with torch.no_grad():
batch_size, pred_len = u_f.shape[0], u_f.shape[1]
# pre-allocate forward states needed
a = torch.empty((batch_size, pred_len, self.dim_a, 1), device=self.device)
z = torch.empty((batch_size, pred_len, self.dim_z, 1), device=self.device)
mu = torch.empty((batch_size, pred_len, self.dim_z, 1), device=self.device)
Sigma = torch.empty((batch_size, pred_len, self.dim_z, self.dim_z), device=self.device)
A = torch.empty((batch_size, pred_len, self.dim_z, self.dim_z), device=self.device)
B = torch.empty((batch_size, pred_len, self.dim_z, self.dim_u), device=self.device)
C = torch.empty((batch_size, pred_len, self.dim_a, self.dim_z), device=self.device)
for ii in range(pred_len):
u_t = u_f[:, ii, :]
# mixture of A
A_t = torch.mm(alpha_t, self.A.reshape(-1, self.dim_z * self.dim_z)) # (bs, k) x (k, dim_z*dim_z)
A_t = A_t.reshape(-1, self.dim_z, self.dim_z) # (bs, dim_z, dim_z)
# mixture of B
B_t = torch.mm(alpha_t, self.B.reshape(-1, self.dim_z * self.dim_u)) # (bs, k) x (k, dim_z*dim_u)
B_t = B_t.reshape(-1, self.dim_z, self.dim_u) # (bs, dim_z, dim_u)
# mixture of C
C_t = torch.mm(alpha_t, self.C.reshape(-1, self.dim_a * self.dim_z)) # (bs, k) x (k, dim_a*dim_z)
C_t = C_t.reshape(-1, self.dim_a, self.dim_z) # (bs, dim_a, dim_z)
# prediction
mu_t = torch.bmm(A_t, mu_tn1) + torch.bmm(B_t, u_t.unsqueeze(-1))
Sigma_t = torch.bmm(torch.bmm(A_t, Sigma_tn1), A_t.transpose(-1,-2)) + self.Q
mvn = tdist.MultivariateNormal(torch.squeeze(mu_t), covariance_matrix=Sigma_t)
z_t_sampled = mvn.sample().unsqueeze(-1) # (bs, dim_z, 1)
a_pred = torch.bmm(C_t, z_t_sampled)
# store
z[:, ii, :, :] = z_t_sampled
a[:, ii, :, :] = a_pred
mu[:, ii, :, :] = mu_t
Sigma[:, ii, :, :] = Sigma_t
A[:, ii, :, :] = A_t # (0, ..., T)
B[:, ii, :, :] = B_t # (0, ..., T)
C[:, ii, :, :] = C_t # (0, ..., T)
alpha_out, h_out = self.alpha_net(a=z_t_sampled.squeeze(-1).unsqueeze(0), h=h_t)
# restart
alpha_t = alpha_out[:, 0, :]
h_t = h_out
mu_tn1 = mu_t
Sigma_tn1 = Sigma_t
return z, mu, Sigma, a, A, B, C
def forward(self, a, u, u_f, s=1.0, R=None):
"""
Predict or generate "pred_len" future states based on control input
and an initial history of "T".
Args:
a: Initial encoded measurements (batch_size, T, dim_a) e.g. [a_0, a_1, ..., a_(T-1)]
u: Initial control inputs (batch_size, T, dim_u) e.g. [u_1, u_2, ..., u_T]
u_f: Future control inputs (batch_size, pred_len, dim_u) [u_{T}, u_{T+1}, ..., u_{T+pred_len-1}]
s: (batch_size, T, dim_a, dim_a)
R: (batch_size, T, dim_a, dim_a)
Returns:
z: (batch_size, pred_len, dim_z, 1)
mu: (batch_size, pred_len, dim_z, 1)
Sigma: (batch_size, pred_len, dim_z, dim_z)
a: (batch_size, pred_len, dim_a, 1)
A: (batch_size, pred_len, dim_z, dim_z)
B: (batch_size, pred_len, dim_z, dim_u)
C: (batch_size, pred_len, dim_a, dim_z)
"""
with torch.no_grad():
mu_tn1, Sigma_tn1, alpha_t, h_t = self.initialize(a, u, s, R)
z, mu, Sigma, a, A, B, C = self.predict(mu_tn1, Sigma_tn1, alpha_t, h_t, u_f)
return z, mu, Sigma, a, A, B, C
def filter_update(self, mu_pred, Sigma_pred, alpha, a, R):
"""
Filter a single predicted state.
"""
# mixture of C
C = torch.mm(alpha, self.C.reshape(-1, self.dim_a * self.dim_z)) # (bs, k) x (k, dim_a*dim_z)
C = C.reshape(-1, self.dim_a, self.dim_z) # (bs, dim_a, dim_z)
# residual
a_pred = torch.bmm(C, mu_pred) # (bs, dim_a, 1)
r_t = a.unsqueeze(-1) - a_pred
# project uncertainty into measurement space
S_t = torch.bmm(torch.bmm(C, Sigma_pred), C.transpose(-1, -2)) + R # (bs, dim_a, dim_a)
S_t_inv = torch.inverse(S_t)
# Kalman gain
K_t = torch.bmm(torch.bmm(Sigma_pred, C.transpose(-1, -2)), S_t_inv) # (bs, dim_z, dim_a)
# measurement update using Joseph's form
mu_filt = mu_pred + torch.bmm(K_t, r_t)
ImKC = self.I - torch.bmm(K_t, C) # (bs, dim_z, dim_z)
Sigma_filt = torch.bmm(torch.bmm(ImKC, Sigma_pred), ImKC.transpose(-1,-2)) + \
torch.bmm(torch.bmm(K_t, R), K_t.transpose(-1,-2))
return mu_filt, Sigma_filt, C
def predict_update(self, mu_filt, Sigma_filt, alpha, u):
"""
Predict a single filtered state.
"""
# mixture of A
A = torch.mm(alpha, self.A.reshape(-1, self.dim_z * self.dim_z)) # (bs, k) x (k, dim_z*dim_z)
A = A.reshape(-1, self.dim_z, self.dim_z) # (bs, dim_z, dim_z)
# mixture of B
B = torch.mm(alpha, self.B.reshape(-1, self.dim_z * self.dim_u)) # (bs, k) x (k, dim_z*dim_u)
B = B.reshape(-1, self.dim_z, self.dim_u) # (bs, dim_z, dim_u)
# prediction
mu_pred = torch.bmm(A, mu_filt) + torch.bmm(B, u.unsqueeze(-1))
Sigma_pred = torch.bmm(torch.bmm(A, Sigma_filt), A.transpose(-1,-2)) + self.Q
return mu_pred, Sigma_pred, A, B
def compute_forward_step(self, mu_pred_t, Sigma_pred_t, alpha_t, h_last, a_t, R_t, u_tp1):
"""
Compute the forward step in the Kalman filter (measurement update then prediction).
Args:
mu_pred_t: Previous time step's mean prediction (batch_size, dim_z, 1)
Sigma_pred_t: Previous time step's covariance prediction (batch_size, dim_z, dim_z)
alpha_t: Previous time step's alpha (batch_size, K)
h_last: Previous time step's hidden state
a_t: Previous time step's measurement (batch_size, dim_a)
R_t: Previous time step's measurement covariance (batch_size, dim_a, dim_a)
u_tp1: Current control inputs (batch_size, dim_u)
Returns:
mu_filt_t: Previous time step's prediction mean updated with the measurement (batch_size, dim_z, 1)
Sigma_filt_t: Previous time step's prediction covariance updated with the measurement (batch_size, dim_z, dim_z)
mu_pred_tp1: Current time step's mean prediction (batch_size, dim_z, 1)
Sigma_pred_tp1: Current time step's covariance prediction (batch_size, dim_z, dim_z)
A_tp1: Current time step's transition matrix (batch_size, dim_z, dim_z)
B_tp1:
C_t:
alpha_tp1:
h_last_tp1:
"""
mu_filt_t, Sigma_filt_t, C_t = \
self.filter_update(mu_pred_t, Sigma_pred_t, alpha_t, a_t, R_t)
mvn = tdist.MultivariateNormal(mu_filt_t.squeeze(-1), covariance_matrix=Sigma_filt_t) # ((batch_size, dim_z), (batch_size, dim_z, dim_z))
z_t = mvn.rsample() # (batch_size, dim_z)
z_t = z_t.unsqueeze(0) # (1, batch_size, dim_z)
alpha_tp1, h_last_tp1 = self.alpha_net(z_t, h_last) # (batch_size, 1, K)
alpha_tp1 = alpha_tp1[:,0,:]
mu_pred_tp1, Sigma_pred_tp1, A_tp1, B_tp1 = \
self.predict_update(mu_filt_t, Sigma_filt_t, alpha_tp1, u_tp1)
return mu_filt_t, Sigma_filt_t, mu_pred_tp1, Sigma_pred_tp1, A_tp1, B_tp1, C_t, alpha_tp1, h_last_tp1
def compute_forward(self, a, u, s=1.0, R=None):
"""
Get forward states based on forward pass.
Args:
a: (batch_size, T, dim_a) e.g. [a_0, a_1, ..., a_(T-1)]
u: (batch_size, T, dim_u) e.g. [u_1, u_2, ..., u_T]
a_cov: (batch_size, T, dim_a, dim_a) e.g. [a_cov_0, a_cov_1, ..., a_cov_(T-1)]
Returns:
forward_states: (batch_size, T, <feature_dim1>, <feature_dim2>)
"""
batch_size = a.shape[0]
T = a.shape[1]
I = torch.eye(self.dim_a, requires_grad=False, device=self.device)
if R is None:
R = self.R.repeat(batch_size, T, 1, 1)
else:
R = R
R = s * R + self.eps * I
# sample initial state
mu_pred_t = self.mu_0.repeat(batch_size, 1, 1) # (batch_size, dim_z, 1)
Sigma_pred_t = self.Sigma_0.repeat(batch_size, 1, 1) # (batch_size, dim_z, dim_z)
# pre-allocate forward states needed
mu_filt = torch.empty((batch_size, T, self.dim_z, 1)).to(device=self.device)
Sigma_filt = torch.empty((batch_size, T, self.dim_z, self.dim_z)).to(device=self.device)
mu_pred = torch.empty((batch_size, T, self.dim_z, 1)).to(device=self.device)
Sigma_pred = torch.empty((batch_size, T, self.dim_z, self.dim_z)).to(device=self.device)
alpha = torch.empty((batch_size, T, self.K)).to(device=self.device)
A = torch.empty((batch_size, T, self.dim_z, self.dim_z)).to(device=self.device)
B = torch.empty((batch_size, T, self.dim_z, self.dim_u)).to(device=self.device)
C = torch.empty((batch_size, T, self.dim_a, self.dim_z)).to(device=self.device)
z_n1 = self.z_n1.repeat(batch_size, 1, 1).squeeze(-1).unsqueeze(0)
alpha_t, h_last_t = self.alpha_net(z_n1) # (batch_size, 1, K)
alpha_t = alpha_t[:,0,:]
# single steps (roll-out from index 0 ... T - 1) + prediction at T
for tt in range(T):
mu_filt_t, Sigma_filt_t, mu_pred_tp1, Sigma_pred_tp1, A_tp1, B_tp1, C_t, alpha_tp1, h_last_tp1 = \
self.compute_forward_step(mu_pred_t=mu_pred_t, Sigma_pred_t=Sigma_pred_t,
alpha_t=alpha_t, h_last=h_last_t,
a_t=a[:, tt, :], R_t=R[:, tt, :, :], u_tp1=u[:, tt, :])
# store results
mu_pred[:, tt, :, :] = mu_pred_tp1
Sigma_pred[:, tt, :, :] = Sigma_pred_tp1
mu_filt[:, tt, :, :] = mu_filt_t
Sigma_filt[:, tt, :, :] = Sigma_filt_t
alpha[:, tt, :] = alpha_tp1
A[:, tt, :, :] = A_tp1
B[:, tt, :, :] = B_tp1
C[:, tt, :, :] = C_t
# restart
mu_pred_t = mu_pred_tp1
Sigma_pred_t = Sigma_pred_tp1
alpha_t = alpha_tp1
h_last_t = h_last_tp1
forward_states = (mu_pred, Sigma_pred, mu_filt, Sigma_filt, A, B, C, a, u, alpha, h_last_t)
return forward_states
def compute_backward_step(self, mu_smooth_tp1, Sigma_smooth_tp1, mu_pred_tp1, Sigma_pred_tp1,
mu_filt_t, Sigma_filt_t, A_tp1):
"""
Compute the backward step in the Kalman smoother.
Args:
mu_smooth_tp1: Future time step's smoothed distribution mean (batch_size, dim_z, 1)
Sigma_smooth_tp1: Future time step's smoothed distribution covariance (batch_size, dim_z, dim_z)
mu_pred_tp1: (batch_size, dim_z, 1)
Sigma_pred_tp1: (batch_size, dim_z, dim_z)
mu_filt_t: (batch_size, dim_z, 1)
Sigma_filt_t: (batch_size, dim_z, dim_z)
A_tp1: (batch_size, dim_z, dim_z)
Returns:
mu_smooth_t: Previous time step's smoothed distribution mean (batch_size, dim_z, 1)
Sigma_smooth_t: Previous time step's smoothed distribution covariance (batch_size, dim_z, dim_z)
"""
Sigma_pred_tp1_inv = torch.inverse(Sigma_pred_tp1)
J = torch.bmm(torch.bmm(Sigma_filt_t, A_tp1.transpose(-1,-2)), Sigma_pred_tp1_inv)
mu_smooth_t = mu_filt_t + torch.bmm(J, (mu_smooth_tp1 - mu_pred_tp1))
JSJt = torch.bmm(torch.bmm(J, (Sigma_smooth_tp1 - Sigma_pred_tp1)), J.transpose(-1, -2))
Sigma_smooth_t = Sigma_filt_t + JSJt
return mu_smooth_t, Sigma_smooth_t
def compute_backward(self, forward_states):
"""
Get backward states based on smoothing.
Args:
forward_states: tuple of (mu_pred, Sigma_pred, mu_filt, Sigma_filt, A, B, C, a, u)
(batch_size, T, <feature_dim1>, <feature_dim2>)
Returns:
backward_states: tuple of (mu_smooth, Sigma_smooth, A, B, C, a, u)
"""
mu_pred, Sigma_pred, mu_filt, Sigma_filt, A, B, C, a, u, alpha, h_last = forward_states
# Number of states
batch_size = mu_filt.shape[0]
T = mu_filt.shape[1]
# pre-allocated smoothing backward states needed
mu_smooth = torch.empty((batch_size, T, self.dim_z, 1)).to(device=self.device)
Sigma_smooth = torch.empty((batch_size, T, self.dim_z, self.dim_z)).to(device=self.device)
# last smoothing. state (T-1) is just the last filtering state used to initialize
mu_smooth[:, 0, :, :] = mu_filt[:, -1, :, :]
Sigma_smooth[:, 0, :, :] = Sigma_filt[:, -1, :, :]
# initial variables for backwards pass
mu_smooth_tp1 = mu_filt[:, -1, :, :]
Sigma_smooth_tp1 = Sigma_filt[:, -1, :, :]
# discard last time dimension to account for indices,
# predictive t=1, ..., T-1
# filter t=0, ..., T-2
mu_pred = mu_pred[:, :-1, :, :]
Sigma_pred = Sigma_pred[:, :-1, :, :]
mu_filt = mu_filt[:, :-1, :, :]
Sigma_filt = Sigma_filt[:, :-1, :, :]
A_backward = A[:, :-1, :, :]
# Number of states to loop backwards
Tm1 = T - 1
# reverse direction along "time" direction
# predictive t=T-1, ..., 1
# filter t=T-2, ..., 0
mu_pred = torch.flip(mu_pred, (1,))
Sigma_pred = torch.flip(Sigma_pred, (1,))
mu_filt = torch.flip(mu_filt, (1,))
Sigma_filt = torch.flip(Sigma_filt, (1,))
A_backward = torch.flip(A_backward, (1,))
for tt in range(Tm1):
mu_smooth_t, Sigma_smooth_t = self.compute_backward_step(
mu_smooth_tp1=mu_smooth_tp1,
Sigma_smooth_tp1=Sigma_smooth_tp1,
mu_pred_tp1=mu_pred[:, tt, :, :],
Sigma_pred_tp1=Sigma_pred[:, tt, :, :],
mu_filt_t=mu_filt[:, tt, :, :],
Sigma_filt_t=Sigma_filt[:, tt, :, :],
A_tp1=A_backward[:, tt, :, :]
)
mu_smooth_tp1 = mu_smooth_t
Sigma_smooth_tp1 = Sigma_smooth_t
mu_smooth[:, tt + 1, :, :] = mu_smooth_t # skip initial which is set as filtering state
Sigma_smooth[:, tt + 1, :, :] = Sigma_smooth_t
# reverse direction to orthodox "time" direction
# smooth t=0, ..., T-1
mu_smooth = torch.flip(mu_smooth, (1,))
Sigma_smooth = torch.flip(Sigma_smooth, (1,))
backward_states = (mu_smooth, Sigma_smooth, A, B, C, a, u, alpha, h_last)
return backward_states
def filter(self, a, u, R=None, s=1.0):
return self.compute_forward(a, u, s=s, R=R)
def smooth(self, a, u, s=1.0, R=None):
return self.compute_backward(self.compute_forward(a, u, s=s, R=R))
def get_prior(self, backward_states, s=1.0, R=None):
"""
Calculate the prior of a sample for the LGSSM.
Args:
backward_states: Smoothed states ((batch_size, T, dim_z, 1), (batch_size, T, dim_z, dim_z))
A: A matrices from dynamic network (batch_size, T, dim_z, dim_z) (A_1, A_2, ..., A_T)
B: B matrices from dynamic network (batch_size, T, dim_z, dim_u) (B_1, B_2, ..., B_T)
C: C matrices from dynamic network (batch_size, T, dim_y, dim_z) (C_0, C_1, ..., C_(T-1)) OR (C_1, C_2, ..., C_T)
a: Compressed observations (batch_size, T, dim_a) e.g. [a_0, a_1, ..., a_(T-1)]
u: Control inputs (batch_size, T, dim_u) e.g. [u_1, u_2, ..., u_T]
Returns:
log_prob_trans, log_prob_emiss, entropy: log probabilities (batch_size, T)
"""
mu_smooth, Sigma_smooth, A, B, C, a, u, _, _ = backward_states
batch_size = A.shape[0]
T = A.shape[1]
I = torch.eye(self.dim_a, requires_grad=False, device=self.device)
if R is None:
R = self.R.repeat(batch_size, T, 1, 1)
else:
R = R
R = s * R + self.eps * I
Q_batch = self.Q.repeat(batch_size, T, 1, 1)
mu_smooth = torch.squeeze(mu_smooth)
mvn_smooth = tdist.MultivariateNormal(mu_smooth, covariance_matrix=Sigma_smooth)
# from t=0 to T-1
z_smooth = mvn_smooth.rsample() # (batch_size, T, dim_z)
# entropy \prod_{t=0}^{T-1} p(z_t|y_{0:T-1}, u_{1:T-1})
entropy = mvn_smooth.log_prob(z_smooth) # (batch_size, T)
# distribution of the initial state p(z_0)
mu_0 = self.mu_0.repeat(batch_size, 1, 1).squeeze(-1)
Sigma_0 = self.Sigma_0.repeat(batch_size, 1, 1)
mvn_0 = tdist.MultivariateNormal(mu_0, covariance_matrix=Sigma_0) # ((batch_size, dim_z), (batch_size, dim_z, dim_z))
log_prob_0 = mvn_0.log_prob(z_smooth[:, 0, :]).unsqueeze(-1) # (batch_size, 1)
# re-use original transitions and emission
A = A[:, :-1, :, :] # (batch_size, T-1, dim_z, dim_z)
B = B[:, :-1, :, :]
u = u[:, :-1, :].unsqueeze(-1) # (batch_size, T-1, dim_u, 1)
z_smooth_trans = z_smooth[:, :-1, :].unsqueeze(-1) # (batch_size, T-1, dim_z, 1)
z_smooth_emiss = z_smooth.unsqueeze(-1) # (batch_size, T, dim_z, 1)
# transition distribution \prod_{t=1}^{T-1} p(z_t|z_{t-1}, u_{t})
A = A.reshape(A.shape[0] * A.shape[1], *A.shape[2:]) # (batch_size, T-1, dim_z, dim_z) --> # (batch_size * T-1, dim_z, dim_z)
z_smooth_trans = z_smooth_trans.reshape(z_smooth_trans.shape[0] * z_smooth_trans.shape[1],
*z_smooth_trans.shape[2:]) # (batch_size, T-1, dim_z, 1) --> (batch_size * T-1, dim_z, 1)
Az_tm1 = torch.bmm(A, z_smooth_trans)
Az_tm1 = Az_tm1.reshape(batch_size, T-1, self.dim_z, 1)
u = u.reshape(u.shape[0] * u.shape[1], *u.shape[2:]) # (batch_size, T-1, dim_z, 1) --> (batch_size * T-1, dim_z, 1)
B = B.reshape(B.shape[0] * B.shape[1], *B.shape[2:])
Bu_t = torch.bmm(B, u)
Bu_t = Bu_t.reshape(batch_size, T-1, self.dim_z, 1)
u = u.reshape(batch_size, T-1, self.dim_u, 1)
mu_trans = Az_tm1 + Bu_t
mu_trans = torch.squeeze(mu_trans) # (batch_size, T-1, dim_z)
mvn_trans = tdist.MultivariateNormal(mu_trans, covariance_matrix=Q_batch[:, :-1, :, :]) # ((batch_size, T-1, dim_z), (batch_size, T-1, dim_z, dim_z))
log_prob_trans = mvn_trans.log_prob(z_smooth[:, 1:, :]) # (batch_size, T-1)
log_prob_trans = torch.cat((log_prob_0, log_prob_trans), dim=1)
# emission distribution \prod_{t=0}^{T-1} p(a_t|z_t)
C = C.reshape(C.shape[0] * C.shape[1], *C.shape[2:])
z_smooth_emiss = z_smooth_emiss.reshape(z_smooth_emiss.shape[0] * z_smooth_emiss.shape[1],
*z_smooth_emiss.shape[2:])
Cz_t = torch.bmm(C, z_smooth_emiss)
Cz_t = Cz_t.reshape(batch_size, T, self.dim_a, 1) # (batch_size, T, dim_a, 1)
mu_emiss = torch.squeeze(Cz_t) # (batch_size, T, dim_a)
mvn_emiss = tdist.MultivariateNormal(mu_emiss, covariance_matrix=R) # ((batch, T, dim_a), (batch_size, T, dim_a, dim_a))
log_prob_emiss = mvn_emiss.log_prob(a) # (batch_size, T)
return (log_prob_trans + log_prob_emiss - entropy)<file_sep># Heteroscedastic Uncertainty for Robust Generative Latent Dynamics
<img src="https://raw.githubusercontent.com/utiasSTARS/robust-latent-srl/master/system.svg" width="500px"/>
Accompanying code and supplementary material for 2020 IROS/RA-L paper "Heteroscedastic Uncertainty for Robust Generative Latent Dynamics".
<file_sep>from setuptools import setup, find_packages
from setuptools.command.develop import develop
from setuptools.command.install import install
import sys, subprocess
if sys.version_info.major != 3:
print('This Python is only compatible with Python 3, but you are running '
'Python {}. The installation will likely fail.'.format(sys.version_info.major))
setup(name='senseact',
packages=[package for package in find_packages()
if package.startswith('senseact') or package.startswith('test')],
install_requires=[
'gym', # 0.10.5
'matplotlib',
'numpy',
'opencv-python>=3.3.1',
'psutil',
'pyserial',
],
description='Kindred SenseAct framework',
author='<NAME>',
url='https://github.com/kindredresearch/SenseAct',
author_email='',
version='0.0.1')
<file_sep>from setuptools import setup, find_packages
setup(name='robust-latent-srl',
packages=[package for package in find_packages()
if package in ('args',
'data_collection',
'experiments',
'learning_utils'
'real_sense_server',
'rl',
'senseact.senseact',
'srl')],
install_requires=[],
version='0.0.1',
)
<file_sep>from cv2 import cv2
import numpy as np
import _pickle as pkl
import torch
from torch.distributions import normal
class Normalize:
def __init__(self, mean, var):
self.mean = mean
self.var = var
def __call__(self, x):
return (x - self.mean) / self.var
def __repr__(self):
return self.__class__.__name__ + '(mean={self.mean}, var={self.var})'
class Dropped(object):
"""Drop an image measurement (set image as 1).
Args:
p: Probability of applying this transform
"""
def __init__(self, p=1):
self.p = p
def __call__(self, img):
if np.random.binomial(1, self.p):
black_out_img = torch.zeros_like(img)
black_out_img = torch.clamp(black_out_img, 0, 1)
return black_out_img
else:
return img
def __repr__(self):
return self.__class__.__name__ + '(p={})'.format(self.p)
class GaussianNoise(object):
"""Add Gaussian noise to the image.
Args:
p: Probability of applying this transform
std: Standard deviation of Gaussian noise
mean: Mean of Gaussian noise
"""
def __init__(self, p=1, std=0.1, mean=0.0):
self.p = p
self.n = normal.Normal(mean, std)
def __call__(self, img):
if np.random.binomial(1,self.p):
noise = torch.abs(self.n.sample((img.shape[0], img.shape[1]))).to(device=img.device)
noisy_img = img + noise
noisy_img_clipped = torch.clamp(noisy_img, 0, 1)
return noisy_img_clipped
else:
return img
def __repr__(self):
return self.__class__.__name__ + '(p={})'.format(self.p)
class Obstruct(object):
"""Obstruct an image.
Args:
p: Probability of applying this transform
"""
def __init__(self, p=0.5, value=0):
self.p = p
self.value = value
def __call__(self, img):
if np.random.binomial(1,self.p):
obstructed_img = img.clone()
size = np.random.randint(12,48, size=2)
location = np.random.randint(0,24, size=2)
x = location[0]
y = location[1]
obstructed_img[x:x+size[0], y:y+size[1]] = self.value
return obstructed_img
else:
return img
def __repr__(self):
return self.__class__.__name__ + '(p={})'.format(self.p)
class DownSample():
def __init__(self, height, width):
self._height = height
self._width = width
def __call__(self, image):
image = cv2.resize(image, (self._height, self._width))
return image
class NormalizeImage():
def __init__(self, const=255):
self.const = const
def __call__(self, image):
return image / self.const
class AsType():
def __init__(self, dtype=np.uint8):
self.dtype = dtype
def __call__(self, input_data):
return input_data.astype(self.dtype)
class Reshape():
def __init__(self, shape):
self.shape = shape
def __call__(self, input_data):
return input_data.reshape(self.shape)
class Transpose():
def __init__(self, transpose_shape):
self.transpose_shape = transpose_shape
def __call__(self, input_data):
return input_data.transpose(self.transpose_shape)
class DropScalarFeature():
def __init__(self, scalar_feature_dim):
self.scalar_feature_dim = scalar_feature_dim
def __call__(self, input_data):
return input_data[:, :-self.scalar_feature_dim]
<file_sep>"""Collect dataset specifically for the pendulum env."""
import sys
from classic_control_pixel.pendulum import Pendulum
import numpy as np
import matplotlib.pyplot as plt
import _pickle as pkl
from torchvision import transforms
TRAJECTORIES = 2048
T = 16
REPEAT = 1
SAVE_PATH = "/path/to/save/"
RES = 16
INCLUDE_ANGLE = True
def angle_normalize(x):
return (((x+np.pi) % (2*np.pi)) - np.pi)
def main():
env = Pendulum(render_h=RES, render_w=RES)
obs = env.reset()
cached_data_imgs = np.empty((TRAJECTORIES,
T*REPEAT,
3 * RES * RES
), dtype=np.uint8)
cached_data_actions = np.empty((TRAJECTORIES,
T*REPEAT,
1), dtype=np.float32)
cached_data_angles = np.empty((TRAJECTORIES,
T*REPEAT,
2), dtype=np.float32)
n_bytes = cached_data_imgs.size * cached_data_imgs.itemsize + \
cached_data_actions.size * cached_data_actions.itemsize + \
cached_data_angles.size * cached_data_angles.itemsize
print("Saving {} GBs of data in {}".format(n_bytes/1e9, SAVE_PATH))
for traj in np.arange(TRAJECTORIES):
th = np.random.uniform(0, np.pi * 2)
thdot = np.random.uniform(-1,1)
state = np.array([th, thdot])
obs = env.reset(state=state)
count = 0
for _ in np.arange(T):
u = np.random.normal(0, 1)
# u = np.random.uniform(-2, 2, size=(1,))
u = np.clip(u, -2, 2)
for _ in np.arange(REPEAT):
obs, _, _, _ = env.step(u=np.array([u]))
cached_data_imgs[traj, count, :] = obs.flatten()
cached_data_actions[traj, count, :] = u
if INCLUDE_ANGLE:
cached_data_angles[traj, count, :] = np.array([angle_normalize(env.state[0]),
env.state[1]])
count+=1
if INCLUDE_ANGLE:
cached_data = (cached_data_imgs, cached_data_actions, cached_data_angles)
else:
cached_data = (cached_data_imgs, cached_data_actions)
pickle_out = open(SAVE_PATH + "pendulum{}_total_{}_traj_{}_repeat_{}_with_angle_train.pkl".format(RES,TRAJECTORIES, T, REPEAT), "wb")
pkl.dump(cached_data, pickle_out, protocol=4)
pickle_out.close()
env.close()
if __name__ == "__main__":
main()
<file_sep>import _pickle as pickle
import argparse
import time
import copy
import numpy as np
from multiprocessing import Process, Value, Manager
from args.parser import parse_data_collection_args
from data_collection.storage import Storage
from senseact.envs.real_sense.reacher_env_with_real_sense import ReacherEnvWithRealSense
def collect_data(args):
assert len(args.camera_res) == 3
assert len(args.hosts) == len(args.ports) > 0
assert args.dt > 0
assert args.repeat_actions >= 0
assert args.timeout > 0
assert args.speed_max > 0
with open("{}".format(args.args_output_file), "wb") as f:
pickle.dump(args, f)
storage = Storage(args.dbname)
print("Creating Environment")
# use fixed random state
rand_state = np.random.RandomState(args.seed).get_state()
np.random.set_state(rand_state)
# Create UR10 Reacher2D environment
env = ReacherEnvWithRealSense(
setup="UR10_default",
camera_hosts=args.hosts,
camera_ports=args.ports,
camera_res=args.camera_res,
host=None,
dof=2,
control_type="velocity",
target_type="position",
reset_type="random",
reward_type="precision",
derivative_type="none",
deriv_action_max=5,
first_deriv_max=2,
accel_max=1.4,
speed_max=args.speed_max,
speedj_a=1.4,
episode_length_time=None,
episode_length_step=args.timeout,
actuation_sync_period=1,
dt=args.dt,
run_mode="multiprocess",
rllab_box=False,
movej_t=2.0,
delay=0.0,
random_state=rand_state
)
# Create and start plotting process
plot_running = Value('i', 1)
shared_returns = Manager().dict({"write_lock": False,
"episodic_returns": [],
"episodic_lengths": [], })
# Spawn plotting process
pp = Process(target=plot_ur10_reacher, args=(env, 2048, shared_returns, plot_running))
pp.start()
render = lambda: None
if args.render and env.render:
render = env.render
try:
storage.start()
env.start()
for episode in range(args.num_episodes):
print("Episode: {}".format(episode + 1))
done = False
timestep = 0
curr_obs = env.reset()
while not done:
if timestep % args.repeat_actions == 0:
action = np.random.normal(scale=0.1, size=(2,))
render()
next_obs, reward, done, _ = env.step(action)
storage.save_transition(
episode,
timestep,
curr_obs,
action,
reward,
done,
next_obs
)
timestep += 1
curr_obs = next_obs
if timestep == args.timeout:
print("Reached Timeout Limit {}".format(args.timeout))
assert done
finally:
storage.close()
env.close()
# Safely terminate plotter process
plot_running.value = 0 # shutdown ploting process
time.sleep(2)
pp.join()
def plot_ur10_reacher(env, batch_size, shared_returns, plot_running):
"""Helper process for visualize the tasks and episodic returns.
Args:
env: An instance of ReacherEnv
batch_size: An int representing timesteps_per_batch provided to the PPO learn function
shared_returns: A manager dictionary object containing `episodic returns` and `episodic lengths`
plot_running: A multiprocessing Value object containing 0/1.
1: Continue plotting, 0: Terminate plotting loop
"""
print ("Started plotting routine")
import matplotlib.pyplot as plt
plt.ion()
time.sleep(5.0)
fig = plt.figure(figsize=(20, 6))
ax1 = fig.add_subplot(131)
hl1, = ax1.plot([], [], markersize=10, marker="o", color='r')
hl2, = ax1.plot([], [], markersize=10, marker="o", color='b')
ax1.set_xlabel("X", fontsize=14)
h = ax1.set_ylabel("Y", fontsize=14)
h.set_rotation(0)
ax3 = fig.add_subplot(132)
hl3, = ax3.plot([], [], markersize=10, marker="o", color='r')
hl4, = ax3.plot([], [], markersize=10, marker="o", color='b')
ax3.set_xlabel("X", fontsize=14)
h = ax3.set_ylabel("Z", fontsize=14)
h.set_rotation(0)
ax2 = fig.add_subplot(133)
hl11, = ax2.plot([], [])
count = 0
old_size = len(shared_returns['episodic_returns'])
while plot_running.value:
plt.suptitle("Reward: {:.2f}".format(env._reward_.value), x=0.375, fontsize=14)
hl1.set_ydata([env._x_target_[1]])
hl1.set_xdata([env._x_target_[2]])
hl2.set_ydata([env._x_[1]])
hl2.set_xdata([env._x_[2]])
ax1.set_ylim([env._end_effector_low[1], env._end_effector_high[1]])
ax1.set_xlim([env._end_effector_low[2], env._end_effector_high[2]])
ax1.set_title("Y-Z plane", fontsize=14)
ax1.set_xlim(ax1.get_xlim()[::-1])
ax1.set_ylim(ax1.get_ylim()[::-1])
hl3.set_ydata([env._x_target_[2]])
hl3.set_xdata([env._x_target_[0]])
hl4.set_ydata([env._x_[2]])
hl4.set_xdata([env._x_[0]])
ax3.set_ylim([env._end_effector_high[2], env._end_effector_low[2]])
ax3.set_xlim([env._end_effector_low[0], env._end_effector_high[0]])
ax3.set_title("X-Z plane", fontsize=14)
ax3.set_xlim(ax3.get_xlim()[::-1])
ax3.set_ylim(ax3.get_ylim()[::-1])
# make a copy of the whole dict to avoid episode_returns and episodic_lengths getting desync
# while plotting
copied_returns = copy.deepcopy(shared_returns)
if not copied_returns['write_lock'] and len(copied_returns['episodic_returns']) > old_size:
# plot learning curve
returns = np.array(copied_returns['episodic_returns'])
old_size = len(copied_returns['episodic_returns'])
window_size_steps = 5000
x_tick = 1000
if copied_returns['episodic_lengths']:
ep_lens = np.array(copied_returns['episodic_lengths'])
else:
ep_lens = batch_size * np.arange(len(returns))
cum_episode_lengths = np.cumsum(ep_lens)
if cum_episode_lengths[-1] >= x_tick:
steps_show = np.arange(x_tick, cum_episode_lengths[-1] + 1, x_tick)
rets = []
for i in range(len(steps_show)):
rets_in_window = returns[(cum_episode_lengths > max(0, x_tick * (i + 1) - window_size_steps)) *
(cum_episode_lengths < x_tick * (i + 1))]
if rets_in_window.any():
rets.append(np.mean(rets_in_window))
hl11.set_xdata(np.arange(1, len(rets) + 1) * x_tick)
ax2.set_xlim([x_tick, len(rets) * x_tick])
hl11.set_ydata(rets)
ax2.set_ylim([np.min(rets), np.max(rets) + 50])
time.sleep(0.01)
fig.canvas.draw()
fig.canvas.flush_events()
count += 1
if __name__ == "__main__":
args = parse_data_collection_args()
collect_data(args)
<file_sep>import argparse
from args.utils import str2bool, str2inttuple, str2tuple, str2floattuple
def parse_common_training_args(parser=None):
if parser is None:
parser = argparse.ArgumentParser()
# Debug Settings
parser.add_argument('--debug', type=str2bool, default=False,
help='Debug and do not save models or log anything')
# Experiment Settings
parser.add_argument('--storage_base_path', type=str, required=True,
help='Base path to store all training data')
parser.add_argument('--resume_training_path', type=str, required=False, default='none',
help='Path to store previous weights, and optimizers to resume training')
parser.add_argument('--device', type=str, default='cpu',
help='Device to use for PyTorch')
parser.add_argument('--cudnn_deterministic', type=str2bool, default=True,
help='Use cudnn deterministic')
parser.add_argument('--cudnn_benchmark', type=str2bool, default=False,
help='Use cudnn benchmark')
parser.add_argument('--task', type=str, default="pendulum48",
help='The task that is being trained on')
parser.add_argument('--comment', type=str, default="None",
help='Comment to describe model')
# Dataset Settings
parser.add_argument('--dataset', type=str, required=True,
help='Name of dataset to train on')
parser.add_argument('--val_split', type=float, default=0.1,
help='Amount of dataset to use for validation')
# Training Settings
parser.add_argument('--n_epoch', type=int, default=600,
help='Number of epochs',)
parser.add_argument('--n_batch', type=int, default=128,
help='Batch size')
parser.add_argument('--n_example', type=int, default=10000000,
help='Maximum samples to train from the dataset')
parser.add_argument('--n_worker', type=int, default=4,
help='Amount of workers for dataloading.')
# Network Settings
parser.add_argument('--use_batch_norm', type=str2bool, default=False,
help='Use batch normalization')
parser.add_argument('--use_dropout', type=str2bool, default=False,
help='Use dropout')
parser.add_argument('--weight_init', choices=['custom', 'none'], default='none',
help='Weight initialization')
# Optimizer Settings
parser.add_argument('--beta1', type=float, default=0.9,
help='Adam optimizer beta 1')
parser.add_argument('--beta2', type=float, default=0.999,
help='Adam optimizer beta 2')
parser.add_argument('--opt', choices=['adam', 'sgd', 'adadelta', 'rmsprop'], default='adam',
help='Optimizer used')
parser.add_argument('--scheduler', choices=['none', 'exponential'], default='none',
help='Scheduler used')
parser.add_argument('--weight_decay', type=float, default=0,
help='Weight decay rate')
args = parser.parse_args()
return args
def parse_training_args():
parser = argparse.ArgumentParser()
# Network args
parser.add_argument('--dim_u', type=int, default=1,
help='Action dimension')
parser.add_argument('--dim_a', type=int, default=3,
help='Emission state dimension')
parser.add_argument('--dim_alpha', type=int, default=3,
help='Transition state dimension')
parser.add_argument('--dim_z', type=int, default=3,
help='True state dimension')
parser.add_argument('--dim_x', type=str2inttuple, default=(1, 48, 48),
help='3-tuple image dimension (C, H, W)')
parser.add_argument('--k', type=int, default=2,
help='Number of dynamic models')
parser.add_argument('--n_annealing_epoch_beta', type=int, default=0,
help='The number of annealing steps')
parser.add_argument('--fc_hidden_size', type=int, default=50,
help='The number of hidden units for each linear layer')
parser.add_argument('--alpha_hidden_size', type=int, default=55,
help='The number of hidden units for each GRU layer')
parser.add_argument('--use_bidirectional', type=str2bool, default=False,
help='Use bidirectional RNN')
parser.add_argument('--transition_noise', type=float, default=0.08,
help='Transition noise')
parser.add_argument('--emission_noise', type=float, default=0.03,
help='Emission noise')
parser.add_argument('--alpha_net', choices=['gru', 'lstm'], default='gru',
help='Alpha network type')
parser.add_argument('--measurement_net', choices=['fcn', 'cnn'], default='fcn',
help='Network architecture for measurement representation')
parser.add_argument('--non_linearity', choices=['relu', 'elu'], default='relu',
help='Activation used for neural network')
parser.add_argument('--measurement_uncertainty', choices=['constant', 'scale', 'feature', 'learn_VAE', 'learn_separate', 'learn_separate_conc'], default='constant',
help='The type of measurement uncertainty used.')
parser.add_argument('--use_stochastic_dynamics', type=str2bool, default=False,
help='Add some stochasticity to the dynamics.')
# Training Settings
parser.add_argument('--lr', type=float, default= 3e-4,
help='Learning rate')
parser.add_argument('--opt_vae_epochs', type=int, default=0,
help='Number of epochs to train VAE only')
parser.add_argument('--opt_vae_kf_epochs', type=int, default=10,
help='Number of epochs to train VAE and LGSSM (must be >= opt_vae_epochs)')
parser.add_argument('--free_nats', type=float, default= 3.,
help='Amount of free nats allowed')
parser.add_argument('--traj_len', type=int, default= 32,
help='Size of trajectory to train on')
parser.add_argument('--init_cov', type=float, default= 40.,
help='Initial state covariance')
# Loss Settings
parser.add_argument('--lam_rec', type=float, default=1.0/256.0,
help='Weight of reconstruction loss')
parser.add_argument('--lam_kl', type=float, default=1.0/256.0,
help='Weight of kl loss')
parser.add_argument('--use_binary_ce', type=str2bool, default=False,
help='Use Binary Cross Entropy loss insted of default Mean Squared Error loss')
args = parse_common_training_args(parser=parser)
return args
def parse_tcp_server_args():
parser = argparse.ArgumentParser()
parser.add_argument('--host', type=str, default='localhost',
help='Host Address')
parser.add_argument('--port', type=int, default=5000,
help='Host Port')
parser.add_argument('--device_id', type=int, default=0,
help='Camera Device ID')
parser.add_argument('--height', type=int, default=480,
help='Camera Resolution Height')
parser.add_argument('--width', type=int, default=640,
help='Camera Resolution Width')
parser.add_argument('--frame_rate', type=int, default=30,
help='Camera Frame Rate')
parser.add_argument('--colour_format', type=str, default='rgb8',
choices=['rgb8'], help='Camera Colour Format')
args = parser.parse_args()
return args
def parse_data_collection_args():
parser = argparse.ArgumentParser()
parser.add_argument('--dbname', type=str, required=True,
help='Database file name to store')
parser.add_argument('--args_output_file', type=str, required=True,
help='File name for storing arguments')
parser.add_argument('--camera_res', type=str2inttuple, default=(3, 480, 640),
help='Camera Resolution')
parser.add_argument('--hosts', type=str2tuple, default=('localhost', 'localhost'),
help='Hosts for connecting to RealSense cameras')
parser.add_argument('--ports', type=str2inttuple, default=(5000, 5001),
help='Correspond ports for connecting to RealSense cameras')
parser.add_argument('--seed', type=int, default=123,
help='Random seed')
parser.add_argument('--dt', type=float, default=0.5,
help='Action frequency (in seconds)')
parser.add_argument('--speed_max', type=float, default=0.5,
help='Maximum speed')
parser.add_argument('--repeat_actions', type=int, default=3,
help='Number of times the same action is repeated until next action is sampled')
parser.add_argument('--timeout', type=int, default=15,
help='The time limit of each episode')
parser.add_argument('--num_episodes', type=int, default=10,
help='Number of episodes to collect')
parser.add_argument('--render', type=str2bool, default=False,
help='Visualize the cameras')
args = parser.parse_args()
return args
def parse_control_experiment_args():
parser = argparse.ArgumentParser()
parser.add_argument('--dbname', type=str, required=True,
help='Database file name to store')
parser.add_argument('--args_output_file', type=str, required=True,
help='File name for storing arguments')
parser.add_argument('--model_path', type=str, required=True,
help='The path to the model')
parser.add_argument('--device', type=str, required=False, default="cuda:0",
help='Device for the model')
parser.add_argument('--goal_path', type=str, required=True,
help='The path specifying the goal')
parser.add_argument('--T', type=int, default=4,
help='Number of history to initialize LGSSM')
parser.add_argument('--mpc_horizon', type=int, default=5,
help='The number of actions MPC predicts')
parser.add_argument('--enable_ood', type=str2bool, default=False,
help='Whether or not to enable OOD detection')
parser.add_argument('--camera_res', type=str2inttuple, default=(3, 480, 640),
help='Camera Resolution')
parser.add_argument('--hosts', type=str2tuple, default=('localhost', 'localhost'),
help='Hosts for connecting to RealSense cameras')
parser.add_argument('--ports', type=str2inttuple, default=(5000, 5001),
help='Correspond ports for connecting to RealSense cameras')
parser.add_argument('--seed', type=int, default=123,
help='Random seed')
parser.add_argument('--dt', type=float, default=0.5,
help='Action frequency (in seconds)')
parser.add_argument('--speed_max', type=float, default=0.5,
help='Maximum speed')
parser.add_argument('--repeat_actions', type=int, default=3,
help='Number of times the same action is applied until next action is sampled')
parser.add_argument('--timeout', type=int, default=15,
help='The time limit of each episode')
parser.add_argument('--num_episodes', type=int, default=10,
help='Number of episodes to collect')
parser.add_argument('--render', type=str2bool, default=False,
help='Visualize the cameras')
args = parser.parse_args()
return args
<file_sep>device="cuda:0"
dataset="path/to/cache/<name>.pkl"
n_batches=(64)
learning_rates=(3e-4)
schedulers=('none')
batch_norms=('False')
bi_directionals=('False')
weight_inits=('custom')
ks=(15)
alpha_nets=('gru')
n_epochs=(4096)
opt=('adam')
folder=('traj_16_no_BN_post_noise_p_1e-2')
storage_base_path="path/to/result/store/${folder}/"
task="real_life_reacher"
measurement_net=('cnn')
debug=('False')
nl=('relu')
free_nats=(0)
traj_lens=(7)
init_cov=(20.0)
measurement_uncertainties=('learn_separate' 'scale')
weight_decays=(0 1e-5)
val_split=0.07
dim_zs=(10)
dim_as=(4)
emission_noises=(0.03)
for n in {1..1}; do
lam_rec=0.95
lam_kl=0.80
n_annealing_epoch_beta=0
opt_vae_kf_epoch=1024
for scheduler in ${schedulers[@]}; do
for batch_norm in ${batch_norms[@]}; do
for k in ${ks[@]}; do
for weight_init in ${weight_inits[@]}; do
for weight_decay in ${weight_decays[@]}; do
for n_batch in ${n_batches[@]}; do
for alpha_net in ${alpha_nets[@]}; do
for lr in ${learning_rates[@]}; do
for bi_directional in ${bi_directionals[@]}; do
for n_epoch in ${n_epochs[@]}; do
for emission_noise in ${emission_noises[@]}; do
for measurement_uncertainty in ${measurement_uncertainties[@]}; do
for traj_len in ${traj_lens[@]}; do
for dim_a in ${dim_as[@]}; do
for dim_z in ${dim_zs[@]}; do
python3 ../srl/train.py \
--k $k \
--dim_a $dim_a \
--dim_z $dim_z \
--dim_u 2 \
--dim_alpha $dim_z \
--n_worker 0 \
--use_binary_ce "False" \
--beta1 0.9 \
--beta2 0.999 \
--n_epoch $n_epoch \
--debug $debug \
--n_batch $n_batch \
--device $device \
--lr $lr \
--weight_init $weight_init \
--weight_decay $weight_decay \
--dataset $dataset \
--lam_rec $lam_rec \
--lam_kl $lam_kl \
--comment "res64_net${alpha_net}_${measurement_uncertainty}_a${dim_a}_z${dim_z}_trajlen${traj_len}_wd${weight_decay}_bs${n_batch}_bn${batch_norm}_lr${lr}_R${emission_noise}" \
--storage_base_path "${storage_base_path}" \
--scheduler $scheduler \
--fc_hidden_size 128 \
--alpha_hidden_size 128 \
--use_bidirectional $bi_directional \
--use_batch_norm $batch_norm \
--measurement_net $measurement_net \
--transition_noise 0.08 \
--emission_noise $emission_noise \
--opt_vae_epochs 0 \
--opt_vae_kf_epochs $opt_vae_kf_epoch \
--n_annealing_epoch_beta $n_annealing_epoch_beta \
--opt $opt \
--alpha_net $alpha_net \
--task $task \
--val_split $val_split \
--dim_x "1,64,64" \
--non_linearity $nl \
--traj_len $traj_len \
--init_cov $init_cov \
--free_nats $free_nats \
--measurement_uncertainty $measurement_uncertainty
done
done
# wait
done
done
done
done
done
done
done
done
done
done
done
done
done
done
<file_sep>import numpy as np
from os import path
import gym
import gym.spaces
from gym import spaces
from gym.utils import seeding
from skimage.transform import resize
from skimage.util import img_as_ubyte
from skimage.color import rgb2gray
def angle_normalize(x):
return (((x+np.pi) % (2*np.pi)) - np.pi)
class Pendulum(gym.Env):
metadata = {
'render.modes' : ['human', 'rgb_array'],
'video.frames_per_second' : 30
}
def __init__(self, render_w=64, render_h=64):
self.max_speed=8
self.max_torque=2.
self.dt=.05
self.viewer = None
self.render_w = render_w
self.render_h = render_h
self.action_space = spaces.Box(low=-self.max_torque, high=self.max_torque, shape=(1,), dtype=np.float32)
self.observation_space = spaces.Box(low=0, high=1, shape=(64,64,1), dtype=np.float32)
self.seed()
def seed(self, seed=None):
self.np_random, seed = seeding.np_random(seed)
return [seed]
def step(self,u):
th, thdot = self.state # th := theta
g = 10.
m = 1.
l = 1.
dt = self.dt
u = np.clip(u, -self.max_torque, self.max_torque)[0]
self.last_u = u # for rendering
costs = angle_normalize(th)**2 + .1*thdot**2 + .001*(u**2)
newthdot = thdot + (-3*g/(2*l) * np.sin(th + np.pi) + 3./(m*l**2)*u) * dt
newth = th + newthdot*dt
newthdot = np.clip(newthdot, -self.max_speed, self.max_speed) #pylint: disable=E1111
self.state = np.array([newth, newthdot])
return self._get_obs(), -costs, False, {}
def step_from_state(self, state, u):
th, thdot = state
g = 10.
m = 1.
l = 1.
dt = self.dt
u = np.clip(u, -self.max_torque, self.max_torque)[0]
costs = angle_normalize(th)**2 + .1*thdot**2 + .001*(u**2)
newthdot = thdot + (-3*g/(2*l) * np.sin(th + np.pi) + 3./(m*l**2)*u) * dt
newth = th + newthdot*dt
newthdot = np.clip(newthdot, -self.max_speed, self.max_speed) #pylint: disable=E1111
return np.array([newth, newthdot])
def reset(self, state=np.array([])):
if state.size > 0:
self.state = state
else:
high = np.array([np.pi, 1])
self.state = self.np_random.uniform(low=-high, high=high)
self.last_u = None
return self._get_obs()
def image_transforms(self,img):
resized_img = resize(img, (self.render_w, self.render_h), anti_aliasing=True)
rescaled_img = 255 * resized_img
img = rescaled_img.astype(np.uint8)
return img
def _get_obs(self):
img = self.render(mode='rgb_array')
img = self.image_transforms(img)
return img
def render(self, mode='human', close=False):
if close:
if self.viewer is not None:
self.viewer.close()
self.viewer = None
return
if self.viewer is None:
from env.pendulum import rendering
self.viewer = rendering.Viewer(500, 500, visible=True)
self.viewer.set_bounds(-2.2,2.2,-2.2,2.2)
rod = rendering.make_capsule(1, .2)
rod.set_color(.8, .3, .3)
self.pole_transform = rendering.Transform()
rod.add_attr(self.pole_transform)
self.viewer.add_geom(rod)
axle = rendering.make_circle(.05)
axle.set_color(0,0,0)
self.viewer.add_geom(axle)
self.imgtrans = rendering.Transform()
self.pole_transform.set_rotation(self.state[0] + np.pi/2)
if self.last_u:
self.imgtrans.scale = (-self.last_u/2, np.abs(self.last_u)/2)
return self.viewer.render(return_rgb_array = mode=='rgb_array')
def close(self):
if self.viewer:
self.viewer.close()
self.viewer = None
<file_sep>import sqlite3
import numpy as np
import io
# SQLITE Converter
def adapt_ndarray(arr):
"""
http://stackoverflow.com/a/31312102/190597 (SoulNibbler)
"""
out = io.BytesIO()
np.save(out, arr)
out.seek(0)
return sqlite3.Binary(out.read())
def convert_ndarray(text):
out = io.BytesIO(text)
out.seek(0)
return np.load(out)
<file_sep>"""
References:
https://github.com/pytorch/vision/blob/master/torchvision/datasets/folder.py
"""
import torch.utils.data as data
import torch
import os
import sys
import pickle
import numpy as np
from srl.srl.transforms import GaussianNoise, Obstruct, Dropped
def has_file_allowed_extension(filename, extensions):
"""Checks if a file is an allowed extension.
Args:
filename (string): path to a file
extensions (iterable of strings): extensions to consider (lowercase)
Returns:
bool: True if the filename ends with one of given extensions
"""
filename_lower = filename.lower()
return any(filename_lower.endswith(ext) for ext in extensions)
def find_subdir(dir):
"""
Finds the subdirectories in a directory.
Args:
dir (string): Root directory path.
Returns:
subdirs (list): where subdirs are relative to (dir).
"""
if sys.version_info >= (3, 5):
# Faster and available in Python 3.5 and above
subdirs = [d.name for d in os.scandir(dir) if d.is_dir()]
else:
subdirs = [d for d in os.listdir(dir) if os.path.isdir(os.path.join(dir, d))]
subdirs.sort()
return subdirs
def make_dataset_traj(dir, extensions):
"""Generate a list of data file paths."""
data_path_list = []
dir = os.path.expanduser(dir)
for batch in find_subdir(dir):
batch_path = os.path.join(dir, batch)
for root, _, fnames in sorted(os.walk(batch_path)):
for fname in sorted(fnames):
if has_file_allowed_extension(fname, extensions):
path = os.path.join(root, fname)
data_path_list.append(path)
return data_path_list
def pickle_loader(path):
"""A data loader for pickle files."""
with open(path, 'rb') as f:
data = pickle.load(f)
return data
class DatasetUnsupervisedCached(data.Dataset):
"""Unsupervised dataset with no labels from a single cache file.
"""
def __init__(self, dir, loader=pickle_loader, transform=None,
render_h=64, render_w=64, p_noise=0, p_obstruction=0, p_dropped=0):
"""
Args:
dir (string): Directory of the cache.
loader (callable): Function to load a sample given its path.
"""
self.dir = dir
self.p_obstruction = p_obstruction
self.obstruct = Obstruct(p=p_obstruction)
self.p_dropped = p_dropped
self.drop = Dropped(p=p_dropped)
self.p_noise = p_noise
self.add_noise = GaussianNoise(p=p_noise, std=0.75, mean=0)
self.transform = transform
print("Loading cache for dataset")
data = loader(dir)
if len(data) == 2:
cached_data_raw, self.cached_data_actions = data
elif len(data) == 3:
cached_data_raw, self.cached_data_actions, self.cached_data_state = data
else:
raise NotImplementedError()
print("Formating dataset")
og_shape = cached_data_raw.shape
cached_data_raw = cached_data_raw.reshape(og_shape[0], og_shape[1], render_h, render_w, 3)
self.cached_data = torch.zeros(og_shape[0], og_shape[1], 1, render_h, render_w)
for ii in range(og_shape[0]):
for tt in range(og_shape[1]):
self.cached_data[ii, tt, 0, :, :] = transform(cached_data_raw[ii, tt, :, :, :])
def __len__(self):
return self.cached_data.shape[0]
def __getitem__(self, idx):
"""
Args:
index (int): Index
Returns:
sample (dict):
"""
assert(idx < self.__len__()), "Index must be lower than dataset size " + str(self.__len__())
img = self.cached_data[idx] # (T, 1, res, res) or (T, 2, res, res)
a = self.cached_data_actions[idx] # (T, 1)
# Randomly add noise in training dataset
if self.p_noise > 0:
for tt in range(img.shape[0]):
img[tt, 0, :, :] = self.add_noise(img[tt, 0, :, :])
# Randomly drop or obstruct whole measurements in training dataset
if self.p_dropped > 0:
for tt in range(img.shape[0]):
img[tt, 0, :, :] = self.drop(img[tt, 0, :, :])
# Randomly obstruct images in training dataset
if self.p_obstruction > 0:
for tt in range(img.shape[0]):
img[tt, 0, :, :] = self.obstruct(img[tt, 0, :, :])
sample = {'images':img, # (T, 1, res, res) or (T, 2, res, res)
'actions': a}
return sample
def __repr__(self):
fmt_str = 'Dataset ' + self.__class__.__name__ + '\n'
fmt_str += ' Number of datapoints: {}\n'.format(self.__len__())
fmt_str += ' Dir Location: {}\n'.format(self.dir)
tmp = ' Image Transforms (if any): '
fmt_str += '{0}{1}\n'.format(tmp, self.transform.__repr__().replace('\n', '\n' + ' ' * len(tmp)))
return fmt_str
class DatasetRealLifeCache(data.Dataset):
""" A dataset that treats each trajectory as a data point.
"""
def __init__(self, cached_data_path, transform=lambda x: x, loader=pickle_loader):
assert os.path.exists(cached_data_path)
self.cached_data_path = cached_data_path
self.transform = transform
print("Loading cache for dataset")
self.data = loader(cached_data_path)
drop_p = 1e-2
obstruct_p = 1e-2
noise_p = 1e-2
self.random_t = [Dropped(p=drop_p),
Obstruct(p=obstruct_p, value=0),
GaussianNoise(p=noise_p, std=0.25, mean=0.25)]
def __len__(self):
return len(self.data["trajectories"])
def __getitem__(self, idx):
assert(idx < self.__len__()), "Index must be lower than dataset size " + str(self.__len__())
(observations, actions, rewards, dones) = self.data["trajectories"][idx]
traj_obs = torch.tensor(self.transform(observations[1:]))
for timestep, traj_ob in enumerate(traj_obs):
t = np.random.choice(self.random_t)
traj_obs[timestep, 0] = t(traj_ob[0])
return {"images": traj_obs,
"actions": actions,
"rewards": rewards,
"dones": dones}
<file_sep>import cvxpy as cp
import numpy as np
import scipy.sparse as sparse
class MPC:
def __init__(self, nz, nu, K, Q, R, zmin, zmax, umin, umax):
self._nz = nz
self._nu = nu
self._K = K
self._Q = Q
self._R = R
self._zmin = zmin
self._zmax = zmax
self._umin = umin
self._umax = umax
# Define parameters
self.z_init = cp.Parameter(self._nz)
self.z_goal = cp.Parameter(self._nz)
self.A = [None] * self._K
self.B = [None] * self._K
self.o = [None] * self._K
for k in range(self._K):
self.A[k] = cp.Parameter((self._nz, self._nz))
self.B[k] = cp.Parameter((self._nz, self._nu))
# Define action and observation vectors (variables)
self.u = cp.Variable((self._nu, self._K))
self.z = cp.Variable((self._nz, self._K + 1))
objective = 0
constraints = [self.z[:, 0] == self.z_init]
for k in range(self._K):
objective += cp.quad_form(self.z[:, k+1] - self.z_goal, self._Q) + cp.quad_form(self.u[:, k], self._R)
constraints += [self.z[:, k + 1] == self.A[k] * self.z[:, k] + self.B[k] * self.u[:, k]]
constraints += [self._zmin <= self.z[:, k], self.z[:, k] <= self._zmax]
constraints += [self._umin <= self.u[:, k], self.u[:, k] <= self._umax]
self.prob = cp.Problem(cp.Minimize(objective), constraints)
def run_mpc(self, A, B, z0, zn):
self.z_init.value = z0
self.z_goal.value = zn
for k in range(self._K):
self.A[k].value = A[k, :, :]
self.B[k].value = B[k, :, :]
return self.prob.solve(warm_start=True)<file_sep># python3 /home/olimoyo/multimodal-latent-srl/real_sense_server/tcp_server.py --host=localhost --port=5000 --device_id=0 --height=480 --width=640 --frame_rate=30 --colour_format=rgb8 &
python3 collect_ur10.py \
--camera_res=3,480,640 \
--dbname="/home/olimoyo/robust-latent-srl/experiments/results/1024T_white_3.db" \
--dt=0.5 \
--speed_max=0.5 \
--timeout=15 \
--hosts=192.168.42.115 \
--ports=5000 \
--num_episodes=1024 \
--args_output_file="/home/olimoyo/robust-latent-srl/experiments/results/1024T_white_3_params.pkl" \
--repeat_actions=3 \
--seed=0 \
--render=False
<file_sep>import argparse
def str2inttuple(v):
return tuple([int(item) for item in v.split(',')] if v else [])
def str2floattuple(v):
return tuple([float(item) for item in v.split(',')] if v else [])
def str2tuple(v):
return tuple([item for item in v.split(',')] if v else [])
def str2bool(v):
if isinstance(v, bool):
return v
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif v.lower() in ('no', 'false', 'f', 'n', '0'):
return False
else:
raise argparse.ArgumentTypeError('Boolean value expected.')
<file_sep>import torch
import torch.nn as nn
from srl.srl.networks import (FCNEncoderVAE, FCNDecoderVAE,
FullyConvEncoderVAE, FullyConvDecoderVAE,
LGSSM, RNNAlpha)
import numpy as np
def to_img(x, shape):
assert len(shape) == 2
sig = nn.Sigmoid()
x = sig(x)
x = x.clamp(0, 1)
x = x.view(x.size(0), 1, *shape)
return x
def load_models(path, args, mode='eval', device='cuda:0'):
print("Loading models in path: ", path)
obs_flatten_dim = int(np.product(args.dim_x))
if args.non_linearity=="relu":
nl = nn.ReLU()
elif args.non_linearity=="elu":
nl = nn.ELU()
else:
raise NotImplementedError()
if args.measurement_net == "fcn":
enc = FCNEncoderVAE(dim_in=obs_flatten_dim,
dim_out=args.dim_a,
bn=args.use_batch_norm,
drop=args.use_dropout,
nl=nl,
hidden_size=args.fc_hidden_size,
stochastic=True).to(device=device)
elif args.measurement_net == "cnn":
if args.measurement_uncertainty == 'learn_VAE':
extra_scalars = 0
elif args.measurement_uncertainty == 'learn_separate':
extra_scalars = args.dim_a
elif args.measurement_uncertainty == 'constant':
extra_scalars = 0
elif args.measurement_uncertainty == 'scale':
extra_scalars = 1
else:
raise NotImplementedError()
enc = FullyConvEncoderVAE(input=1,
latent_size=args.dim_a,
bn=args.use_batch_norm,
drop=args.use_dropout,
extra_scalars=extra_scalars,
img_dim=str(args.dim_x[1]),
nl=nl,
stochastic=True).to(device=device)
else:
raise NotImplementedError()
try:
enc.load_state_dict(torch.load(path + "/enc.pth", map_location=device))
if mode == 'eval':
enc.eval()
elif mode == 'train':
enc.train()
else:
raise NotImplementedError()
except Exception as e:
print(e)
output_nl = None if args.use_binary_ce else nn.Sigmoid()
if args.measurement_net == "fcn":
dec = FCNDecoderVAE(dim_in=args.dim_a,
dim_out=args.dim_x,
bn=args.use_batch_norm,
drop=args.use_dropout,
nl=nl,
output_nl=output_nl,
hidden_size=args.fc_hidden_size).to(device=device)
elif args.measurement_net == "cnn":
dec = FullyConvDecoderVAE(input=1,
latent_size=args.dim_a,
bn=args.use_batch_norm,
drop=args.use_dropout,
img_dim=str(args.dim_x[1]),
nl=nl,
output_nl=output_nl).to(device=device)
else:
raise NotImplementedError()
try:
dec.load_state_dict(torch.load(path + "/dec.pth", map_location=device))
if mode == 'eval':
dec.eval()
elif mode == 'train':
dec.train()
else:
raise NotImplementedError()
except Exception as e:
print(e)
# LGSSM and dynamic parameter network
alpha_net = RNNAlpha(input_size=args.dim_alpha,
hidden_size=args.alpha_hidden_size,
bidirectional=args.use_bidirectional,
net_type=args.alpha_net,
K=args.k)
lgssm = LGSSM(dim_z=args.dim_z,
dim_a=args.dim_a,
dim_u=args.dim_u,
alpha_net=alpha_net,
K=args.k,
transition_noise=args.transition_noise,
emission_noise=args.emission_noise,
device=device).to(device=device)
try:
lgssm.load_state_dict(torch.load(path + "/lgssm.pth", map_location=device))
if mode == 'eval':
lgssm.eval()
elif mode == 'train':
lgssm.train()
else:
raise NotImplementedError()
except Exception as e:
print(e)
return enc, dec, lgssm
<file_sep>import cv2
import logging
import numpy as np
import gym
import time
from gym import spaces
from multiprocessing import Array, Value
from senseact.devices.real_sense.real_sense_communicator import RealSenseCommunicator
from senseact.devices.ur import ur_utils
from senseact.devices.ur.ur_setups import setups
from senseact.rtrl_base_env import RTRLBaseEnv
from senseact.sharedbuffer import SharedBuffer
from senseact import utils
class RealSenseEnv(RTRLBaseEnv, gym.core.Env):
def __init__(self,
camera_res=(3, 480, 640),
time_limit=10,
hosts=('localhost',),
ports=(5000,),
rng=np.random,
**kwargs):
assert time_limit > 0
assert len(hosts) == len(ports)
self.num_cameras = len(hosts)
self.buffer_len = 2
self.action_dim = 2
self.camera_dim = int(np.product(camera_res))
self.input_dim = self.num_cameras * self.camera_dim
self.camera_res = camera_res
self._time_limit = time_limit
self.rng = rng
self._action_space = spaces.Discrete(2)
self._observation_space = spaces.Box(
low=0, high=1, shape=(self.input_dim,), dtype=np.float32)
# Setup communicator and buffer
communicator_setups = {}
self._camera_images_ = {}
for idx, (host, port) in enumerate(zip(hosts, ports)):
communicator_setups[f'Camera_{idx}'] = {
'Communicator': RealSenseCommunicator,
# have to read in this number of packets everytime to support
# all operations
'num_sensor_packets': self.buffer_len,
'kwargs': {
'host': host,
'port': port,
'num_channels': camera_res[0],
'height': camera_res[1],
'width': camera_res[2]
}
}
self._camera_images_[f'Camera_{idx}'] = np.frombuffer(
Array('f', self.camera_dim).get_obj(), dtype='float32')
super(RealSenseEnv, self).__init__(
communicator_setups=communicator_setups,
action_dim=self.action_dim,
observation_dim=self.input_dim,
**kwargs
)
self._obs_ = np.zeros(shape=self.input_dim)
self.episode_steps = Value('i', 0)
def _reset_(self):
self.done = False
self.episode_steps.value = 0
self._sensor_to_sensation_()
def _compute_sensation_(self, name, sensor_window, timestamp_window, index_window):
if name.startswith('Camera'):
image = np.array(sensor_window[-1])
camera_idx = int(name.split("_")[1])
np.copyto(self._camera_images_[name], image.flatten())
np.copyto(self._obs_[camera_idx * self.camera_dim:(camera_idx + 1) * self.camera_dim], image.flatten())
reward = self._compute_reward()
return np.concatenate((self._obs_, [reward], [self.done]))
def _compute_actuation_(self, action, timestamp, index):
if action[1]:
self.done = True
def _check_done(self, env_done):
self.episode_steps.value += 1
return env_done or (self._time_limit < self.episode_steps.value)
def _compute_reward(self):
return self.rng.normal(loc=0, scale=self.episode_steps.value)
@property
def observation_space(self):
return self._observation_space
@property
def action_space(self):
return self._action_space
def render(self):
cv2.namedWindow('RealSense', cv2.WINDOW_AUTOSIZE)
images = []
for idx in range(self.num_cameras):
images.append(self._camera_images_[f'Camera_{idx}'].reshape(self.camera_res).transpose(1, 2, 0))
images = np.hstack(images)
cv2.imshow('RealSense', images)
cv2.waitKey(1)
def terminate(self):
"""Gracefully terminates environment processes."""
super(RealSenseEnv, self).close()
if __name__ == "__main__":
hosts = ('localhost',)
ports = (5000,)
env = RealSenseEnv(
time_limit=10,
hosts=hosts,
ports=ports)
env.start()
for episode in range(10):
print(f"Episode: {episode}")
done = False
obs = env.reset()
while not done:
env.render()
obs, reward, done, _ = env.step([1, 0])
env.close()
<file_sep>import threading
from queue import Queue
import numpy as np
import os
import sqlite3
from data_collection.utils import adapt_ndarray, convert_ndarray
class Storage(threading.Thread):
""" This is a storage that uses SQLite3.
Writing is on a separate thread to reduce blocking time while interacting with the environment.
You should wait until all writes are flushed before closing the connection.
NOTE: This only support one instance for a database.
NOTE: Episode == Trajectory
The database consists of 3 tables:
- sample: (Sample ID, State, Action, Reward, Done)
- sample_relation: (Sample ID, Episode, Timestep)
- last_obs: (Episode, State)
"""
def __init__(self, dbname):
super(Storage, self).__init__()
self._stop_event = threading.Event()
sqlite3.register_adapter(np.ndarray, adapt_ndarray)
sqlite3.register_converter("NDARRAY", convert_ndarray)
self._dbname = dbname
self._is_new = not os.path.exists(dbname)
self._main_conn = sqlite3.connect(
dbname, detect_types=sqlite3.PARSE_DECLTYPES)
self._main_cursor = self._main_conn.cursor()
self._counter = 0
self._episode_counter = 0
if self._is_new:
print("{} not found... Creating new database".format(dbname))
self._main_cursor.executescript("""
CREATE TABLE sample(
sample_id INTEGER PRIMARY KEY,
curr_obs NDARRAY,
action NDARRAY,
reward REAL,
done bit
);
CREATE TABLE sample_relation(
episode INTEGER,
timestep INTEGER,
sample_id INTEGER,
PRIMARY KEY (episode, timestep),
FOREIGN KEY(sample_id) REFERENCES sample(sample_id)
);
CREATE TABLE last_obs(
episode INTEGER PRIMARY KEY,
last_obs NDARRAY
);
""")
self._main_conn.commit()
else:
self._counter = self.get_num_transitions()
self._episode_counter = self.get_num_episodes()
self.reqs = Queue()
def run(self):
write_conn = sqlite3.connect(
self._dbname, detect_types=sqlite3.PARSE_DECLTYPES)
write_cursor = write_conn.cursor()
while True:
if self._stop_event.isSet() and self.reqs.empty():
break
request, args = self.reqs.get()
try:
write_cursor.execute(request, args)
write_conn.commit()
except sqlite3.IntegrityError:
print("Conflicting entry")
print("Closing connection")
write_conn.close()
def save_transition(self, episode, timestep, curr_obs, action, reward, done, next_obs):
self.reqs.put(("insert into sample(curr_obs, action, reward, done, sample_id) values (?, ?, ?, ?, ?)", (curr_obs, action, reward, done, self._counter)))
if done:
self.reqs.put(("insert into last_obs(episode, last_obs) values (?, ?)", (self._episode_counter + episode, next_obs)))
self.reqs.put(("insert into sample_relation(episode, timestep, sample_id) values (?, ?, ?)", (self._episode_counter + episode, timestep, self._counter)))
self._counter += 1
def get_transition(self, episode, timestep):
self._main_cursor.execute("""
SELECT curr_obs, action, reward, done
FROM (
SELECT sample_id
FROM sample_relation
WHERE
episode = {}
AND timestep = {}
) AS filtered_sample
JOIN sample
""".format(episode, timestep))
return self._main_cursor.fetchone()
def sample_transitions(self, batch_size):
self._main_cursor.execute("""
SELECT curr_obs, action, reward, done FROM sample ORDER BY RANDOM() LIMIT {};
""".format(batch_size))
return self._main_cursor.fetchall()
def get_episode(self, episode):
self._main_cursor.execute("""
SELECT curr_obs, action, reward, done
FROM (
SELECT sample_id
FROM sample_relation
WHERE
episode = {}
) AS filtered_sample
JOIN sample
ON filtered_sample.sample_id = sample.sample_id
""".format(episode))
transitions = self._main_cursor.fetchall()
self._main_cursor.execute("""
SELECT last_obs
FROM last_obs
WHERE
episode = {}
""".format(episode))
last_obs = self._main_cursor.fetchone()[0]
# Episode is a list of lists of (observations, actions, rewards, dones)
episode = tuple(map(list, zip(*transitions)))
episode[0].append(last_obs)
return episode
def get_num_transitions(self):
self._main_cursor.execute("""
SELECT count(*)
FROM sample
""")
return self._main_cursor.fetchone()[0]
def get_num_episodes(self):
self._main_cursor.execute("""
SELECT max(episode), count(episode)
FROM last_obs
""")
res = self._main_cursor.fetchone()
assert (res[0] + 1) == res[1], res
return res[1]
def close(self):
self._main_conn.close()
self._stop_event.set()
if __name__ == "__main__":
from pprint import pprint
storage = Storage("test.db")
storage.start()
for i in range(10):
storage.save_transition(1, i, np.random.normal(size=(10, 10)), np.random.normal(size=(5,)), np.random.normal(), i == 9, np.random.normal(size=(10, 10)))
storage.close()
# You can read at the same time, but this ensures the writes are flushed already
storage = Storage("test.db")
row = storage.get_transition(1, 1)
pprint(row)
rows = storage.sample_transitions(2)
for row in rows:
pprint(row)
trajectory = storage.get_episode(1)
print(storage.get_num_transitions())
for i in trajectory:
print(len(i))
print(storage.get_num_episodes())
<file_sep>import _pickle as pickle
import argparse
import copy
import json
import numpy as np
import operator
import os
import time
import torch
import torchvision.transforms as torch_transforms
from argparse import Namespace
from functools import partial
from multiprocessing import Process, Value, Manager
from args.parser import parse_control_experiment_args
from data_collection.storage import Storage
from experiments.mpc import *
from senseact.envs.real_sense.reacher_env_with_real_sense import ReacherEnvWithRealSense
from srl.srl.networks import (FullyConvEncoderVAE,
FullyConvDecoderVAE,
LGSSM,
RNNAlpha)
from srl.srl.transforms import (AsType,
DownSample,
Dropped,
GaussianNoise,
NormalizeImage,
Obstruct,
Reshape,
Transpose)
from srl.srl.utils import load_models
def get_alpha_scaling_torch(l_train_avg, x, x_rec, dim):
diff = (x - x_rec)**2
L_rec = torch.sum(diff, dim=(1,2,3)) / (diff.shape[-1] * diff.shape[-2])
alpha = torch.log(1 + (L_rec/l_train_avg)).unsqueeze(-1)
alpha = torch.diag_embed(alpha.repeat(1, dim))
alpha = 10 * alpha.reshape(1, x.shape[0], *alpha.shape[1:])
return alpha
def ur10_control(args):
assert len(args.camera_res) == 3
assert len(args.hosts) == len(args.ports) > 0
assert args.dt > 0
assert args.repeat_actions >= 0
assert args.timeout > 0
assert args.speed_max > 0
assert os.path.isdir(args.model_path)
num_feature_dim = 8
L_TRAIN_AVG = 0.000939284324645996 # reacher
ood_detection = partial(get_alpha_scaling_torch, l_train_avg=L_TRAIN_AVG)
with open("{}".format(args.args_output_file), "wb") as f:
pickle.dump(args, f)
# use fixed random state
rand_state = np.random.RandomState(args.seed).get_state()
np.random.set_state(rand_state)
storage = Storage(args.dbname)
# Load model
print("Loading Model")
with open(os.path.join(args.model_path, "hyperparameters.txt"), "r") as f:
model_args = Namespace(**json.load(f))
enc, dec, lgssm = load_models(args.model_path, model_args, device=args.device)
goal_data = np.load(args.goal_path)
goal_gt = goal_data[-num_feature_dim:]
goal_image = goal_data[:-num_feature_dim].reshape(model_args.dim_x[1:])
# TARGET [-1.49640781 -1.75541813]
# q_start_queue = [#[-1.6, -1.3],
# # [-2.0, -1.4],
# # [-2.2, -1.6],
# # [-2.35, -1.2],
# # [-0.8, -1.85],
# [-1.1, -1.7],##
# [-2.5, -0.66],##E STOP
# [-2.2, -0.6],##
# [-2.68, -0.07],##
# [-2.69, 0.28]]
q_start_queue = [[-1.50518352, -1.80493862],
[-1.16035873, -1.89097912],
[-1.1, -1.7],##
[-2.5, -0.66],##E STOP
[-2.2, -0.6],##
[-2.68, -0.07],##
[-2.21267349, -0.69658262],
[-0.5753792, -1.88098842],
[-1.41478187, -1.4714458]]
# q_start_queue = [[-1.41478187, -1.4714458], [-0.5753792, -1.88098842]]
q_target = goal_gt[:2]
print("TARGET {}".format(q_target))
# Create UR10 Reacher2D environment
print("Creating Environment")
env = ReacherEnvWithRealSense(
setup="UR10_default",
camera_hosts=args.hosts,
camera_ports=args.ports,
camera_res=args.camera_res,
host=None,
q_start_queue=q_start_queue,
q_target=q_target,
dof=2,
control_type="velocity",
target_type="position",
reset_type="random",
reward_type="precision",
derivative_type="none",
deriv_action_max=5,
first_deriv_max=2,
accel_max=1.4,
speed_max=args.speed_max,
speedj_a=1.4,
episode_length_time=None,
episode_length_step=args.timeout,
actuation_sync_period=1,
dt=args.dt,
run_mode="multiprocess",
rllab_box=False,
movej_t=2.0,
delay=0.0,
random_state=rand_state
)
# Create and start plotting process
plot_running = Value('i', 1)
shared_returns = Manager().dict({"write_lock": False,
"episodic_returns": [],
"episodic_lengths": [], })
# Spawn plotting process
print("Spawning plotting process")
pp = Process(target=plot_ur10_reacher, args=(env, 2048, shared_returns, plot_running))
pp.start()
render = lambda: None
if args.render and env.render:
render = env.render
print ("Setup Goal and transforms")
# Setup transform
obs_transform = torch_transforms.Compose(transforms=[Reshape(args.camera_res),
NormalizeImage(const=1/255),
AsType(dtype=np.uint8),
Transpose(transpose_shape=(1, 2, 0)),
DownSample(*model_args.dim_x[1:]),
torch_transforms.ToPILImage(),
torch_transforms.Grayscale(num_output_channels=1),
torch_transforms.ToTensor()])
# Randomly generate goal image
goal_img = torch.tensor(goal_image.reshape(model_args.dim_x), dtype=torch.float, device=args.device)
x_goal = goal_img.unsqueeze(0).expand(args.T, *model_args.dim_x).reshape(args.T, *model_args.dim_x)
u_goal = torch.zeros(1, args.T, model_args.dim_u, device=args.device)
a_goal, a_goal_mu, a_goal_logvar = enc(x_goal)
a_goal_cov = torch.exp(a_goal_logvar)
R_goal_cov = None
s_goal = torch.tensor(1.0, requires_grad=False, device=args.device)
a_goal = a_goal.reshape(1, args.T, model_args.dim_a)
with torch.no_grad():
mu_goal, Sigma_goal, alpha_goal, h_goal = lgssm.initialize(a_goal, u_goal, R=R_goal_cov)
z_goal = mu_goal[0, :, 0].cpu().detach().numpy()
# Setup MPC
umin = -0.5 * np.ones((model_args.dim_u))
umax = 0.5 * np.ones((model_args.dim_u))
zmin = -np.inf * np.ones((model_args.dim_z))
zmax = np.inf * np.ones((model_args.dim_z))
mpc_Q = 1.0 * sparse.eye(model_args.dim_z)
mpc_R = 1.0 * sparse.eye(model_args.dim_u)
mpc = MPC(model_args.dim_z, model_args.dim_u, args.mpc_horizon, mpc_Q, mpc_R, zmin, zmax, umin, umax)
R_update = torch.eye(model_args.dim_a, requires_grad=False, device=args.device).unsqueeze(0) * model_args.emission_noise
t_dropped = Dropped(p=1.0)
t_obstruct = Obstruct(p=1.0, value=1)
t_noise = GaussianNoise(p=1.0, std=0.25, mean=0.25)
t_image_transform = torch_transforms.ColorJitter()
# =========== SETUP OOD
ood_transform = t_dropped
clean_frequency = 2
dirty_frequency = 2
# GT is clean first. LE is dirty first
apply_ood = operator.le
# apply_ood = operator.gt
def transform_initialization(curr_x):
curr_x[0] = ood_transform(curr_x[0])
curr_x[1] = ood_transform(curr_x[1])
curr_x[3] = ood_transform(curr_x[3])
return curr_x
def transform_image(curr_x, timestep):
if apply_ood(timestep % (clean_frequency + dirty_frequency), dirty_frequency - 1):
curr_x = ood_transform(curr_x)
return curr_x
try:
print("START CONTROL EXPERIMENT")
storage.start()
env.start()
with torch.no_grad():
for episode in range(args.num_episodes):
# for episode in range(len(q_start_queue)):
print("Episode: {}".format(episode + 1))
done = False
timestep = 0
curr_obs = env.reset()
# Initialize LGSSM using first observation
# NOTE: Assume constant setting from LGSSM
tic = time.time()
curr_x = torch.tensor(obs_transform(curr_obs[:-num_feature_dim]),
device=args.device)
print("STARTING STATE: {}".format(curr_obs[-num_feature_dim:][:2]))
curr_x = curr_x.expand(args.T, *model_args.dim_x).reshape(args.T, *model_args.dim_x)
curr_x = transform_initialization(curr_x)
curr_a, _, _ = enc(curr_x)
curr_x_hat = dec(curr_a)
# OOD
ood_factor = 1.
curr_R_cov = None
if args.enable_ood:
ood_factor = ood_detection(x=curr_x, x_rec=curr_x_hat, dim=model_args.dim_a)
curr_R_cov = ood_factor * model_args.emission_noise
curr_s = torch.tensor(1., requires_grad=False, device=args.device)
curr_a = curr_a.reshape(1, args.T, model_args.dim_a)
curr_u = torch.zeros(1, args.T, model_args.dim_u, device=args.device)
mu, Sigma, alpha, h = lgssm.initialize(curr_a, curr_u, s=curr_s, R=curr_R_cov)
curr_z = mu[0, :, 0].cpu().detach().numpy()
mpc_curr_u = torch.zeros((1, args.mpc_horizon * args.repeat_actions, model_args.dim_u)).float().to(args.device)
toc = time.time()
# print("TIME TAKEN FOR INITIALIZATION: {}".format(toc - tic))
while not done:
# print("TIMESTEP: {} ========================".format(timestep))
if timestep % args.repeat_actions == 0:
tic = time.time()
_, _, _, _, A, B, _ = lgssm.predict(mu_tn1=mu,
Sigma_tn1=Sigma,
alpha_t=alpha,
h_t=h,
u_f=mpc_curr_u)
toc = time.time()
# print("TIME TAKEN FOR LGSSM PREDICT: {}".format(toc - tic))
A = A[0].reshape(args.mpc_horizon, args.repeat_actions, model_args.dim_z, model_args.dim_z)
B = B[0].reshape(args.mpc_horizon, args.repeat_actions, model_args.dim_z, model_args.dim_u)
# Approiximate transformations for A and B
mpc_A = A[:, -1]
mpc_B = B[:, -1]
for action_i in range(args.repeat_actions - 2, -1, -1):
mpc_B = mpc_B + torch.bmm(mpc_A, B[:, action_i])
mpc_A = torch.bmm(mpc_A, A[:, action_i])
mpc_A = mpc_A.cpu().detach().numpy()
mpc_B = mpc_B.cpu().detach().numpy()
# Compute actions using MPC
tic = time.time()
_ = mpc.run_mpc(mpc_A, mpc_B, curr_z, z_goal)
toc = time.time()
# print("TIME TAKEN FOR MPC CALL: {}".format(toc - tic))
mpc_curr_u = mpc.u.value
action = np.copy(mpc_curr_u[:, 0])
# print("ACTION FROM MPC: {}".format(action))
# Repeat actions
mpc_curr_u[:, :-1] = mpc_curr_u[:, 1:]
mpc_curr_u[:, -1] = 0
mpc_curr_u = torch.tensor(mpc_curr_u, device=args.device).float().repeat_interleave(args.repeat_actions, 1).transpose(1, 0).unsqueeze(0)
render()
# dummy_action = np.zeros(model_args.dim_u)
# print(action)
# tic = time.time()
next_obs, reward, done, _ = env.step(action)
# toc = time.time()
# print("TIME FOR STEP: {}".format(toc - tic))
storage.save_transition(
episode,
timestep,
curr_obs,
action,
reward,
done,
next_obs
)
timestep += 1
curr_obs = next_obs
tic = time.time()
curr_x = torch.tensor(obs_transform(curr_obs[:-num_feature_dim]),
device=args.device).reshape(1, *model_args.dim_x)
# if timestep % 4 <= 1:
# curr_x[0] = t_dropped(curr_x[0])
curr_x[0] = transform_image(curr_x[0], timestep)
curr_u = torch.from_numpy(action).unsqueeze(0).float().to(args.device) # (1, dim_u)
curr_a, _, _ = enc(curr_x)
curr_x_hat = dec(curr_a)
if args.enable_ood:
ood_factor = ood_detection(x=curr_x, x_rec=curr_x_hat, dim=model_args.dim_a).squeeze(0)
mu, Sigma, _, _ = \
lgssm.predict_update(mu, Sigma, alpha, curr_u)
mu, Sigma, _ = \
lgssm.filter_update(mu, Sigma,
alpha, curr_a, R=R_update * ood_factor)
curr_z = mu[0, :, 0]
alpha, h = lgssm.alpha_net(curr_z.reshape(1, 1, -1), h) # (1, 1, args.mpc_horizon)
alpha = alpha[:, 0, :]
curr_z = curr_z.cpu().detach().numpy() # (dim_z,)
toc = time.time()
# print("TIME TAKEN FOR UPDATING LGSSM: {}".format(toc - tic))
if timestep == args.timeout:
# print("Reached Timeout Limit {}".format(args.timeout))
assert done
finally:
storage.close()
print(env._pstop_times_)
env.close()
# Safely terminate plotter process
plot_running.value = 0 # shutdown ploting process
time.sleep(2)
pp.join()
def plot_ur10_reacher(env, batch_size, shared_returns, plot_running):
"""Helper process for visualize the tasks and episodic returns.
Args:
env: An instance of ReacherEnv
batch_size: An int representing timesteps_per_batch provided to the PPO learn function
shared_returns: A manager dictionary object containing `episodic returns` and `episodic lengths`
plot_running: A multiprocessing Value object containing 0/1.
1: Continue plotting, 0: Terminate plotting loop
"""
print ("Started plotting routine")
import matplotlib.pyplot as plt
plt.ion()
time.sleep(5.0)
fig = plt.figure(figsize=(20, 6))
ax1 = fig.add_subplot(131)
hl1, = ax1.plot([], [], markersize=10, marker="o", color='r')
hl2, = ax1.plot([], [], markersize=10, marker="o", color='b')
ax1.set_xlabel("X", fontsize=14)
h = ax1.set_ylabel("Y", fontsize=14)
h.set_rotation(0)
ax3 = fig.add_subplot(132)
hl3, = ax3.plot([], [], markersize=10, marker="o", color='r')
hl4, = ax3.plot([], [], markersize=10, marker="o", color='b')
ax3.set_xlabel("X", fontsize=14)
h = ax3.set_ylabel("Z", fontsize=14)
h.set_rotation(0)
ax2 = fig.add_subplot(133)
hl11, = ax2.plot([], [])
count = 0
old_size = len(shared_returns['episodic_returns'])
while plot_running.value:
plt.suptitle("Reward: {:.2f}".format(env._reward_.value), x=0.375, fontsize=14)
hl1.set_ydata([env._x_target_[1]])
hl1.set_xdata([env._x_target_[2]])
hl2.set_ydata([env._x_[1]])
hl2.set_xdata([env._x_[2]])
ax1.set_ylim([env._end_effector_low[1], env._end_effector_high[1]])
ax1.set_xlim([env._end_effector_low[2], env._end_effector_high[2]])
ax1.set_title("Y-Z plane", fontsize=14)
ax1.set_xlim(ax1.get_xlim()[::-1])
ax1.set_ylim(ax1.get_ylim()[::-1])
hl3.set_ydata([env._x_target_[2]])
hl3.set_xdata([env._x_target_[0]])
hl4.set_ydata([env._x_[2]])
hl4.set_xdata([env._x_[0]])
ax3.set_ylim([env._end_effector_high[2], env._end_effector_low[2]])
ax3.set_xlim([env._end_effector_low[0], env._end_effector_high[0]])
ax3.set_title("X-Z plane", fontsize=14)
ax3.set_xlim(ax3.get_xlim()[::-1])
ax3.set_ylim(ax3.get_ylim()[::-1])
# make a copy of the whole dict to avoid episode_returns and episodic_lengths getting desync
# while plotting
copied_returns = copy.deepcopy(shared_returns)
if not copied_returns['write_lock'] and len(copied_returns['episodic_returns']) > old_size:
# plot learning curve
returns = np.array(copied_returns['episodic_returns'])
old_size = len(copied_returns['episodic_returns'])
window_size_steps = 5000
x_tick = 1000
if copied_returns['episodic_lengths']:
ep_lens = np.array(copied_returns['episodic_lengths'])
else:
ep_lens = batch_size * np.arange(len(returns))
cum_episode_lengths = np.cumsum(ep_lens)
if cum_episode_lengths[-1] >= x_tick:
steps_show = np.arange(x_tick, cum_episode_lengths[-1] + 1, x_tick)
rets = []
for i in range(len(steps_show)):
rets_in_window = returns[(cum_episode_lengths > max(0, x_tick * (i + 1) - window_size_steps)) *
(cum_episode_lengths < x_tick * (i + 1))]
if rets_in_window.any():
rets.append(np.mean(rets_in_window))
hl11.set_xdata(np.arange(1, len(rets) + 1) * x_tick)
ax2.set_xlim([x_tick, len(rets) * x_tick])
hl11.set_ydata(rets)
ax2.set_ylim([np.min(rets), np.max(rets) + 50])
time.sleep(0.01)
fig.canvas.draw()
fig.canvas.flush_events()
count += 1
if __name__ == "__main__":
args = parse_control_experiment_args()
ur10_control(args)
<file_sep>import torch
import torch.nn as nn
import torch.nn.init as init
def common_init_weights(m):
if type(m) == nn.Linear:
nn.init.xavier_uniform_(m.weight)
if m.bias is not None:
nn.init.zeros_(m.bias)
# consider also xavier_uniform_, kaiming_uniform_ , orthogonal_
elif type(m) == nn.Conv2d or type(m) == nn.Conv3d:
nn.init.kaiming_uniform_(m.weight)
if m.bias is not None:
m.bias.data.fill_(0)
elif type(m) in [nn.LSTM, nn.RNN, nn.GRU]:
nn.init.orthogonal_(m.weight_hh_l0)
nn.init.xavier_uniform_(m.weight_ih_l0)
nn.init.zeros_(m.bias_hh_l0)
nn.init.zeros_(m.bias_ih_l0)<file_sep>from gym.envs.mujoco.mujoco_env import MujocoEnv
# message if mujoco is not installed correctly
from senseact.envs.sim_double_pendulum.assets.inverted_double_pendulum_dt_0_001 import InvertedDoublePendulumEnvSenseAct
<file_sep>import os
from gym import utils
from gym.envs.mujoco import inverted_double_pendulum, mujoco_env
class InvertedDoublePendulumEnvSenseAct(inverted_double_pendulum.InvertedDoublePendulumEnv):
def __init__(self):
mujoco_env.MujocoEnv.__init__(self, os.path.dirname(__file__) + '/inverted_double_pendulum_dt_0_001.xml', 5)
utils.EzPickle.__init__(self)
<file_sep>from math import pi
setups = \
{
'dxl_gripper_default':
{
'angles_low' : [-150.0 * pi/180.0],
'angles_high' : [0.0 * pi/180.0],
'high_load' : [85],
},
'dxl_tracker_default':
{
'angles_low' : [-pi/3.],
'angles_high' : [pi/3.],
'high_load' : [85],
}
}
<file_sep>python3 ../control_experiment_ur10.py \
--camera_res=3,480,640 \
--dbname="/path/to/outputdb/<storagedbname>.db" \
--goal_path="/path/to/goalimage/<filename>.npy" \
--dt=0.5 \
--speed_max=0.5 \
--timeout=30 \
--mpc_horizon=3 \
--enable_ood=False \
--hosts=192.168.42.115 \
--ports=5000 \
--num_episodes=9 \
--args_output_file="/path/to/outputargs/<filename>.pkl" \
--repeat_actions=3 \
--seed=0 \
--render=False \
--model_path="path/to/load/model" \
--device=cuda:0 \
--T=4<file_sep>class ExponentialScheduler():
def __init__(self, opt, lr_decay=1, lr_decay_frequency=1, min_lr=3e-6):
self._opt = opt
self._lr_decay = lr_decay
self._lr_decay_frequency = lr_decay_frequency
self._min_lr = min_lr
self._epoch = 0
def __call__(self):
if (self._epoch + 1) % self._lr_decay_frequency == 0:
for param_group in self._opt.param_groups:
param_group['lr'] = max(param_group['lr'] * self._lr_decay, self._min_lr)
self._epoch += 1
def step(self):
self()
<file_sep>import _pickle as pickle
import json
import math
import matplotlib.pyplot as plt
import numpy as np
import os
import random
import sys
import time
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.distributions as tdist
def set_seed_torch(seed):
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
random.seed(seed)
seed = 0
set_seed_torch(seed)
def _init_fn(worker_id):
np.random.seed(int(seed))
from pprint import pprint
from collections import OrderedDict
from datetime import datetime
from tensorboardX import SummaryWriter
from torchvision import transforms
from torchvision.utils import make_grid, save_image
from torch.distributions import normal
from torch.utils.data import DataLoader
from torch.utils.data.sampler import SubsetRandomSampler
from args.parser import parse_training_args
from srl.srl.learning_utils.weight_initializations import common_init_weights
from srl.srl.learning_utils.learning_rate_schedulers import ExponentialScheduler
from srl.srl.datasets import DatasetUnsupervisedCached, DatasetRealLifeCache
from srl.srl.networks import (FCNEncoderVAE,
FCNDecoderVAE,
LGSSM,
FullyConvEncoderVAE,
FullyConvDecoderVAE,
RNNAlpha)
from srl.srl.transforms import (Dropped,
DropScalarFeature,
GaussianNoise,
Normalize,
Obstruct,
Reshape)
def loop(args):
assert 0 <= args.opt_vae_epochs <= args.opt_vae_kf_epochs <= args.n_epoch
device = torch.device(args.device)
torch.backends.cudnn.deterministic = args.cudnn_deterministic
torch.backends.cudnn.benchmark = args.cudnn_benchmark
checkpoint_epoch = 2048
# Save directory
if not args.debug:
time_tag = datetime.strftime(datetime.now(), '%m-%d-%y_%H:%M:%S')
data_dir = args.storage_base_path + time_tag + '_' + args.comment
os.makedirs(data_dir, exist_ok=True)
if args.n_epoch > checkpoint_epoch:
checkpoint_dir = os.path.join(data_dir, "checkpoints")
os.makedirs(checkpoint_dir, exist_ok=True)
args.__dict__ = OrderedDict(sorted(args.__dict__.items(), key=lambda t: t[0]))
with open(data_dir + '/hyperparameters.txt', 'w') as f:
json.dump(args.__dict__, f, indent=2)
writer = SummaryWriter(logdir=data_dir)
obs_flatten_dim = int(np.product(args.dim_x))
if args.non_linearity=="relu":
nl = nn.ReLU()
elif args.non_linearity=="elu":
nl = nn.ELU()
else:
raise NotImplementedError()
output_nl = None if args.use_binary_ce else nn.Sigmoid()
if args.measurement_net == 'fcn':
enc = FCNEncoderVAE(dim_in=obs_flatten_dim,
dim_out=args.dim_a,
bn=args.use_batch_norm,
drop=args.use_dropout,
nl=nl,
hidden_size=args.fc_hidden_size,
stochastic=True).to(device=device)
dec = FCNDecoderVAE(dim_in=args.dim_a,
dim_out=args.dim_x,
bn=args.use_batch_norm,
drop=args.use_dropout,
nl=nl,
output_nl=output_nl,
hidden_size=args.fc_hidden_size).to(device=device)
elif args.measurement_net == 'cnn':
if args.measurement_uncertainty == 'learn_VAE':
extra_scalars = 0
extra_scalars_conc = 0
elif args.measurement_uncertainty == 'learn_separate':
extra_scalars = args.dim_a
extra_scalars_conc = 0
elif args.measurement_uncertainty == 'learn_separate_conc':
extra_scalars = 0
extra_scalars_conc = args.dim_a
elif args.measurement_uncertainty == 'constant':
extra_scalars = 0
extra_scalars_conc = 0
elif args.measurement_uncertainty == 'scale':
extra_scalars = 1
extra_scalars_conc = 0
elif args.measurement_uncertainty == 'feature':
extra_scalars = 0
extra_scalars_conc = 0
R_net = FCNEncoderVAE(dim_in=args.dim_a,
dim_out=args.dim_a,
bn=args.use_batch_norm,
drop=args.use_dropout,
nl=nl,
hidden_size=args.fc_hidden_size,
stochastic=False).to(device=device)
else:
raise NotImplementedError()
enc = FullyConvEncoderVAE(input=1,
latent_size=args.dim_a,
bn=args.use_batch_norm,
drop=args.use_dropout,
nl=nl,
img_dim=str(args.dim_x[1]),
extra_scalars=extra_scalars,
extra_scalars_conc=extra_scalars_conc,
stochastic=True).to(device=device)
dec = FullyConvDecoderVAE(input=1,
latent_size=args.dim_a,
bn=args.use_batch_norm,
img_dim=str(args.dim_x[1]),
drop=args.use_dropout,
nl=nl,
output_nl=output_nl).to(device=device)
if args.measurement_uncertainty == 'feature':
uncertainty_params = list(R_net.parameters())
else:
uncertainty_params = []
# LGSSM and dynamic parameter network
alpha_network = RNNAlpha(input_size=args.dim_alpha,
hidden_size=args.alpha_hidden_size,
bidirectional=args.use_bidirectional,
net_type=args.alpha_net,
K=args.k)
lgssm = LGSSM(dim_z=args.dim_z,
dim_a=args.dim_a,
dim_u=args.dim_u,
alpha_net=alpha_network,
K=args.k,
init_cov=args.init_cov,
transition_noise=args.transition_noise,
emission_noise=args.emission_noise,
device=device).to(device=device)
dynamic_params = [lgssm.A, lgssm.B, lgssm.C]
initial_params = [lgssm.z_n1]
if args.opt == "adam":
opt_vae = torch.optim.Adam(list(enc.parameters()) + list(dec.parameters()),
lr=args.lr, betas=(args.beta1, args.beta2),
weight_decay=args.weight_decay)
opt_vae_kf = torch.optim.Adam(list(enc.parameters()) + list(dec.parameters()) +
uncertainty_params +
dynamic_params + initial_params,
lr=args.lr, betas=(args.beta1, args.beta2),
weight_decay=args.weight_decay)
opt_all = torch.optim.Adam(list(enc.parameters()) + list(dec.parameters()) +
uncertainty_params + list(lgssm.parameters()),
lr=args.lr, betas=(args.beta1, args.beta2),
weight_decay=args.weight_decay)
elif args.opt == "sgd":
opt_vae = torch.optim.SGD(list(enc.parameters()) + list(dec.parameters()),
lr=args.lr, momentum=0.9, nesterov=True)
opt_vae_kf = torch.optim.SGD(list(enc.parameters()) + list(dec.parameters()) +
uncertainty_params +
dynamic_params + initial_params,
lr=args.lr, momentum=0.9, nesterov=True)
opt_all = torch.optim.SGD(list(enc.parameters()) + list(dec.parameters()) +
uncertainty_params + list(lgssm.parameters()),
lr=args.lr, momentum=0.9, nesterov=True)
elif args.opt == "adadelta":
opt_vae = torch.optim.Adadelta(list(enc.parameters()) + list(dec.parameters()))
opt_vae_kf = torch.optim.Adadelta(list(enc.parameters()) + list(dec.parameters()) + uncertainty_params +
dynamic_params + initial_params)
opt_all = torch.optim.Adadelta(list(enc.parameters()) + list(dec.parameters()) + uncertainty_params +
list(lgssm.parameters()))
elif args.opt == "rmsprop":
opt_vae = torch.optim.RMSprop(list(enc.parameters()) + list(dec.parameters()),
lr=args.lr, momentum=0.9)
opt_vae_kf = torch.optim.RMSprop(list(enc.parameters()) + list(dec.parameters()) + uncertainty_params +
dynamic_params + initial_params,
lr=args.lr, momentum=0.9)
opt_all = torch.optim.RMSprop(list(enc.parameters()) + list(dec.parameters()) + uncertainty_params +
list(lgssm.parameters()),
lr=args.lr, momentum=0.9)
else:
raise NotImplementedError()
if args.weight_init == 'custom':
enc.apply(common_init_weights)
dec.apply(common_init_weights)
lgssm.apply(common_init_weights)
if args.measurement_uncertainty == 'feature':
R_net.apply(common_init_weights)
if args.scheduler == "exponential":
lr_scheduler_vae = ExponentialScheduler(opt_vae, lr_decay=0.85, lr_decay_frequency=750, min_lr=3e-6)
lr_scheduler_vae_kf = ExponentialScheduler(opt_vae_kf, lr_decay=0.85, lr_decay_frequency=750, min_lr=3e-6)
lr_scheduler_all = ExponentialScheduler(opt_all, lr_decay=0.85, lr_decay_frequency=750, min_lr=3e-6)
# Loss functions
if args.use_binary_ce:
loss_REC = nn.BCEWithLogitsLoss(reduction='none').to(device=device)
else:
loss_REC = nn.MSELoss(reduction='none').to(device=device)
if args.task == "pendulum64":
transform = transforms.Compose([
transforms.ToPILImage(),
transforms.Grayscale(num_output_channels=1),
transforms.ToTensor(),
Normalize(mean=0.27, var=1.0 - 0.27) # 64x64
])
elif args.task == "real_life_reacher":
transform = transforms.Compose([
DropScalarFeature(scalar_feature_dim=8),
Reshape((15, 1, args.dim_x[1], args.dim_x[2]))
])
else:
raise NotImplementedError()
if args.resume_training_path != "none":
load_path = [x[0] for x in os.walk(args.resume_training_path)][1]
# load weights
lgssm.load_state_dict(torch.load(os.path.join(load_path, "lgssm.pth"), map_location=device))
enc.load_state_dict(torch.load(os.path.join(load_path, "enc.pth"), map_location=device))
dec.load_state_dict(torch.load(os.path.join(load_path, "dec.pth"), map_location=device))
if args.measurement_uncertainty == 'feature':
R_net.load_state_dict(torch.load(os.path.join(load_path, "R_net.pth"), map_location=device))
# load optimizers
opt_vae.load_state_dict(torch.load(os.path.join(load_path, "opt_vae.pth"), map_location=device))
opt_vae_kf.load_state_dict(torch.load(os.path.join(load_path, "opt_vae_kf.pth"), map_location=device))
opt_all.load_state_dict(torch.load(os.path.join(load_path, "opt_all.pth"), map_location=device))
with open(os.path.join(load_path, "training_info.pkl"), "rb") as f:
info = pickle.load(f)
ini_epoch = info["epoch"]
train_annealing_counter = info["train_annealing_counter"]
val_annealing_counter = info["val_annealing_counter"]
train_indices = info["train_indices"]
val_indices = info["val_indices"]
transform = info["transform"]
if args.scheduler != 'none':
lr_scheduler_vae = info["lr_scheduler_vae"]
lr_scheduler_vae_kf = info["lr_scheduler_vae_kf"]
lr_scheduler_all = info["lr_scheduler_all"]
# Dataset
if args.task == "real_life_reacher":
dataset = DatasetRealLifeCache(args.dataset,
transform=transform)
else:
dataset = DatasetUnsupervisedCached(args.dataset,
transform=transform,
render_h=args.dim_x[1],
render_w=args.dim_x[2])
if args.resume_training_path == "none":
dataset_size = len(dataset)
indices = list(range(dataset_size))
split = int(np.floor(args.val_split * dataset_size))
train_indices, val_indices = indices[split:], indices[:split]
train_sampler = SubsetRandomSampler(train_indices)
valid_sampler = SubsetRandomSampler(val_indices)
train_loader = DataLoader(dataset,
batch_size=args.n_batch,
num_workers=args.n_worker,
sampler=train_sampler,
worker_init_fn=_init_fn)
val_loader = DataLoader(dataset,
batch_size=args.n_batch,
num_workers=args.n_worker,
sampler=valid_sampler,
worker_init_fn=_init_fn)
train_mini_batches = len(train_loader)
val_mini_batches = len(val_loader)
annealing_den_train = float(args.n_annealing_epoch_beta * train_mini_batches)
annealing_den_val = float(args.n_annealing_epoch_beta * val_mini_batches)
def kvae(epoch, annealing_counter, opt=None, lr_scheduler=None):
"""Training code for unimodal model."""
if opt:
enc.train()
dec.train()
lgssm.train()
loader = train_loader
if epoch < args.n_annealing_epoch_beta:
annealing_factor_beta = min(1., annealing_counter / annealing_den_train)
one_to_zero = 1. - (annealing_counter / annealing_den_train)
annealing_factor_beta = max(1., 99.0 * one_to_zero + 1)
else:
annealing_factor_beta = 1.
else:
enc.eval()
dec.eval()
lgssm.eval()
loader = val_loader
if epoch < args.n_annealing_epoch_beta:
annealing_factor_beta = min(1., annealing_counter / annealing_den_val)
one_to_zero = 1. - (annealing_counter / annealing_den_val)
annealing_factor_beta = max(1., 99.0 * one_to_zero + 1)
else:
annealing_factor_beta = 1.
avg_l = []
for idx, data in enumerate(loader):
if idx == args.n_example:
break
# XXX: all trajectories have same length
x_full = data['images'].float().to(device=device)
# Sample random range of traj_len
s_idx = np.random.randint(x_full.shape[1] - args.traj_len + 1)
e_idx = s_idx + args.traj_len
x = x_full[:, s_idx:(e_idx - 1)]
x_dim = x.shape
N = x_dim[0]
T = x_dim[1]
# reshape to (N * T, 1, height, width) & encode and decode
x = x.reshape(N * T, *x_dim[2:])
if args.measurement_uncertainty == 'learn_VAE':
# Use VAE's covariance as R in LGSSM
a, a_mu, a_logvar = enc(x)
a_cov = torch.diag_embed(torch.exp(a_logvar)).reshape(N, T, args.dim_a, args.dim_a)
a_mu = a_mu.reshape(N, T, args.dim_a)
R = a_cov
s = torch.tensor(1.0, requires_grad=False, device=device)
elif args.measurement_uncertainty == "learn_separate" or \
args.measurement_uncertainty == "learn_separate_conc":
# Learn noise separately in VAE as R in LGSSM
a, a_mu, a_logvar, R_logvar = enc(x)
a_cov = torch.diag_embed(torch.exp(a_logvar)).reshape(N, T, args.dim_a, args.dim_a)
a_mu = a_mu.reshape(N, T, args.dim_a)
R = torch.diag_embed(torch.exp(R_logvar)).reshape(N, T, args.dim_a, args.dim_a)
s = torch.tensor(1.0, requires_grad=False, device=device)
elif args.measurement_uncertainty == 'constant':
# Use R as R in LGSSM
a, a_mu, a_logvar = enc(x)
a_cov = torch.diag_embed(torch.exp(a_logvar)).reshape(N, T, args.dim_a, args.dim_a)
a_mu = a_mu.reshape(N, T, args.dim_a)
R = None
s = torch.tensor(1.0, requires_grad=False, device=device)
elif args.measurement_uncertainty == 'scale':
# Scale R by s in LGSSM
a, a_mu, a_logvar, s = enc(x)
a_cov = torch.diag_embed(torch.exp(a_logvar)).reshape(N, T, args.dim_a, args.dim_a)
a_mu = a_mu.reshape(N, T, args.dim_a)
R = None
s = torch.diag_embed(s.repeat(1, args.dim_a)).reshape(N, T, *s.shape[1:])
elif args.measurement_uncertainty == 'feature':
# Learn noise separately in VAE as R in LGSSM
a, a_mu, a_logvar = enc(x)
a_cov = torch.diag_embed(torch.exp(a_logvar)).reshape(N, T, args.dim_a, args.dim_a)
a_mu = a_mu.reshape(N, T, args.dim_a)
R_logvar = R_net(a)
R = torch.diag_embed(torch.exp(R_logvar)).reshape(N, T, args.dim_a, args.dim_a)
s = torch.tensor(1.0, requires_grad=False, device=device)
else:
raise NotImplementedError()
x_hat = dec(a)
# Reshape to (N, T, dim_a)
a = a.reshape(N, T, args.dim_a)
u = data['actions'].float().to(device=device)[:, (s_idx + 1):e_idx]
if args.use_stochastic_dynamics:
# Simulate imperfect dynamics "counterfactually" with noisy control inputs
noise = torch.empty(u.shape, requires_grad=False, device=device).normal_(0, 0.2)
u = u + noise
u = torch.clamp(u, min=-2.0, max=2.0)
backward_states = lgssm.smooth(a, u, s=s, R=R)
# NLL reconstruction
loss_rec = loss_REC(x_hat, x)
loss_rec = loss_rec.view(N, T, -1).sum(-1)
# Loss KL sampling based
loss_2 = lgssm.get_prior(backward_states, s=s, R=R)
# q(a|x)
mvn_a = tdist.MultivariateNormal(a_mu, covariance_matrix=a_cov) # ((N, T, dim_a), (N, T, dim_a, dim_a))
loss_3 = mvn_a.log_prob(a)
loss_KL = loss_3 - loss_2
# free nats margin
# loss_KL = torch.max(torch.zeros_like(loss_KL), (loss_KL - args.free_nats))
loss_rec = torch.sum(loss_rec)
loss_KL = torch.sum(loss_KL)
if epoch % 1 == 0 and idx == 0:
if R is None:
I = torch.eye(args.dim_a, requires_grad=False, device=device)
R = lgssm.R.repeat(N, T, 1, 1)
R = s.detach() * R + lgssm.eps * I
pprint({
"Reconstruction (per N)": loss_rec.item() / N,
"Reconstruction (per N * T)": loss_rec.item() / (N * T),
"KL divergence (per N)": loss_KL.item() / N,
"KL divergence (per N * T)": loss_KL.item() / (N * T),
"R": R[0,0,:,:]
})
total_loss = (args.lam_rec * loss_rec +
annealing_factor_beta * args.lam_kl * loss_KL) / N
avg_l.append((loss_rec.item() + loss_KL.item()) / N)
annealing_counter += 1
# jointly optimize everything
if opt:
opt.zero_grad()
total_loss.backward()
# clip for stable RNN training
if args.measurement_uncertainty == 'feature':
torch.nn.utils.clip_grad_norm_(R_net.parameters(), 0.5)
torch.nn.utils.clip_grad_norm_(lgssm.parameters(), 0.5)
torch.nn.utils.clip_grad_norm_(enc.parameters(), 0.5)
torch.nn.utils.clip_grad_norm_(dec.parameters(), 0.5)
opt.step()
if lr_scheduler:
lr_scheduler.step()
avg_loss = sum(avg_l) / len(avg_l)
return avg_loss, annealing_counter
# initialize training variables
if args.resume_training_path == "none":
ini_epoch = 0
train_annealing_counter = 0
val_annealing_counter = 0
lr_scheduler = None
opt = opt_vae
if args.scheduler != 'none':
lr_scheduler = lr_scheduler_vae
#XXX: Overwrites learning rate even if loading previous optimizer
for param_group in opt_all.param_groups:
param_group['lr'] = args.lr
# training loop
try:
for epoch in range(ini_epoch, ini_epoch + args.n_epoch):
tic = time.time()
if epoch >= args.opt_vae_kf_epochs:
opt = opt_all
if args.scheduler != 'none':
lr_scheduler = lr_scheduler_all
elif epoch >= args.opt_vae_epochs:
opt = opt_vae_kf
if args.scheduler != 'none':
lr_scheduler = lr_scheduler_vae_kf
avg_train_loss, train_annealing_counter = kvae(epoch, train_annealing_counter, opt, lr_scheduler)
if args.val_split > 0:
with torch.no_grad():
avg_val_loss, val_annealing_counter = kvae(epoch, val_annealing_counter)
else:
avg_val_loss = 0
epoch_time = time.time() - tic
print("Epoch {}/{}: Avg train loss: {}, Avg val loss: {}, Time per epoch: {}"
.format(epoch + 1, ini_epoch + args.n_epoch, avg_train_loss, avg_val_loss, epoch_time))
if not args.debug:
writer.add_scalars("Loss",
{'train': avg_train_loss, 'val': avg_val_loss}, epoch)
if (epoch + 1) % checkpoint_epoch == 0:
checkpoint_i_path = os.path.join(checkpoint_dir, str((epoch + 1) // checkpoint_epoch))
os.makedirs(checkpoint_i_path, exist_ok=True)
# Save models
torch.save(lgssm.state_dict(), checkpoint_i_path + '/lgssm.pth')
torch.save(enc.state_dict(), checkpoint_i_path + '/enc.pth')
torch.save(dec.state_dict(), checkpoint_i_path + '/dec.pth')
if args.measurement_uncertainty == 'feature':
torch.save(R_net.state_dict(), checkpoint_i_path + '/R_net.pth')
# Save optimizers
torch.save(opt_all.state_dict(), checkpoint_i_path + "/opt_all.pth")
torch.save(opt_vae.state_dict(), checkpoint_i_path + "/opt_vae.pth")
torch.save(opt_vae_kf.state_dict(), checkpoint_i_path + "/opt_vae_kf.pth")
finally:
if not args.debug:
if not np.isnan(avg_train_loss):
# Save models
torch.save(lgssm.state_dict(), data_dir + '/lgssm.pth')
torch.save(enc.state_dict(), data_dir + '/enc.pth')
torch.save(dec.state_dict(), data_dir + '/dec.pth')
if args.measurement_uncertainty == 'feature':
torch.save(R_net.state_dict(), data_dir + '/R_net.pth')
# Save optimizers
torch.save(opt_all.state_dict(), data_dir + "/opt_all.pth")
torch.save(opt_vae.state_dict(), data_dir + "/opt_vae.pth")
torch.save(opt_vae_kf.state_dict(), data_dir + "/opt_vae_kf.pth")
writer.close()
# Save training information
with open(os.path.join(data_dir, "training_info.pkl"), "wb") as f:
info = {"epoch": epoch,
"train_annealing_counter": train_annealing_counter,
"val_annealing_counter": val_annealing_counter,
"train_indices": train_indices,
"val_indices": val_indices,
"transform": transform}
if args.scheduler != 'none':
info["lr_scheduler_vae"] = lr_scheduler_vae
info["lr_scheduler_vae_kf"] = lr_scheduler_vae_kf
info["lr_scheduler_all"] = lr_scheduler_all
pickle.dump(info, f)
def main():
args = parse_training_args()
loop(args)
if __name__ == "__main__":
main()
<file_sep>import argparse
import numpy as np
import pyrealsense2 as rs
import socket
import sys
from args.parser import parse_tcp_server_args
def run(args):
assert args.height > 0
assert args.width > 0
assert args.frame_rate > 0
assert args.colour_format in ("rgb8",)
# Get colour format
if args.colour_format == "rgb8":
colour_format = rs.format.rgb8
else:
raise NotImplementedError()
# Get device serial number
realsense_ctx = rs.context()
device_sn = realsense_ctx.devices[args.device_id].get_info(rs.camera_info.serial_number)
print("ID: {} - S/N: {}".format(args.device_id, device_sn))
# Intel RealSense pipeline
config = rs.config()
config.enable_device(device_sn)
config.enable_stream(rs.stream.color, args.width, args.height, colour_format, args.frame_rate)
pipeline = rs.pipeline()
pipeline.start(config)
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to the port
server_address = (args.host, args.port)
print('Starting up on {} port {}'.format(*server_address))
sock.bind(server_address)
# Listen for incoming connections
sock.listen(1)
try:
while True:
# Wait for a connection
print('waiting for a connection')
connection, client_address = sock.accept()
try:
print('connection from', client_address)
# Receive the data in small chunks and retransmit it
while True:
data = connection.recv(16).decode("utf-8")
if data == 'done':
break
if data != 'get':
continue
frames = pipeline.wait_for_frames()
color_frame = frames.get_color_frame()
if not color_frame:
continue
# Convert images to numpy arrays
# Data Shape: (Width, Height, Channels)
image = np.asanyarray(color_frame.get_data()).transpose(2, 0, 1)
connection.send(image.tobytes())
finally:
print('Closing connection from {}:{}', *client_address)
# Clean up the connection
connection.close()
finally:
pipeline.stop()
sock.close()
if __name__ == "__main__":
args = parse_tcp_server_args()
run(args)
<file_sep>"""Exceptions raised by DXL device interface code."""
class NoSuchServo(Exception):
"""No such servo with given ID on this USB."""
class CommError(Exception):
"""An unexpected communication error occurred."""
class UnitConversionNotImplemented(Exception):
"""Unit Conversion not set for given registers."""
class MalformedStatus(Exception):
"""Internal Exception for bus retry."""
<file_sep>import cv2
import numpy as np
import time
import gym
import sys
from multiprocessing import Array, Value
from senseact.rtrl_base_env import RTRLBaseEnv
from senseact.envs.ur.reacher_env import ReacherEnv
from senseact.devices.real_sense.real_sense_communicator import RealSenseCommunicator
from senseact.devices.ur import ur_utils
from senseact.devices.ur.ur_setups import setups
from senseact.sharedbuffer import SharedBuffer
from senseact import utils
class ReacherEnvWithRealSense(ReacherEnv, gym.core.Env):
def __init__(self,
setup,
camera_hosts=('localhost',),
camera_ports=(5000,),
camera_res=(3, 480, 640),
host=None,
q_start_queue=None,
q_target=None,
dof=6,
control_type='position',
derivative_type='none',
target_type='position',
reset_type='random',
reward_type='linear',
deriv_action_max=10,
first_deriv_max=10, # used only with second derivative control
vel_penalty=0,
obs_history=1,
actuation_sync_period=1,
episode_length_time=None,
episode_length_step=None,
rllab_box = False,
servoj_t=ur_utils.COMMANDS['SERVOJ']['default']['t'],
servoj_gain=ur_utils.COMMANDS['SERVOJ']['default']['gain'],
speedj_a=ur_utils.COMMANDS['SPEEDJ']['default']['a'],
speedj_t_min=ur_utils.COMMANDS['SPEEDJ']['default']['t_min'],
movej_t=2, # used for resetting
accel_max=None,
speed_max=None,
dt=0.008,
delay=0.0, # to simulate extra delay in the system
**kwargs):
assert len(camera_hosts) == len(camera_ports)
self.num_cameras = len(camera_hosts)
self.camera_res = camera_res
self.camera_dim = int(np.product(camera_res))
self.buffer_len = obs_history
self.q_start_queue = q_start_queue
self.q_target = q_target
# Setup camera communicators and buffer
communicator_setups = {}
self._camera_images_ = {}
for idx, (camera_host, camera_port) in enumerate(zip(camera_hosts, camera_ports)):
communicator_setups['Camera_{}'.format(idx)] = {
'Communicator': RealSenseCommunicator,
# have to read in this number of packets everytime to support
# all operations
'num_sensor_packets': self.buffer_len,
'kwargs': {
'host': camera_host,
'port': camera_port,
'num_channels': camera_res[0],
'height': camera_res[1],
'width': camera_res[2]
}
}
self._camera_images_['Camera_{}'.format(idx)] = np.frombuffer(
Array('f', self.camera_dim).get_obj(), dtype='float32')
print("Setup Reacher Environment")
# Setup UR environment
super(ReacherEnvWithRealSense, self).__init__(
setup,
host=host,
dof=dof,
control_type=control_type,
derivative_type=derivative_type,
target_type=target_type,
reset_type=reset_type,
reward_type=reward_type,
deriv_action_max=deriv_action_max,
first_deriv_max=first_deriv_max, # used only with second derivative control
vel_penalty=vel_penalty,
obs_history=obs_history,
actuation_sync_period=actuation_sync_period,
episode_length_time=episode_length_time,
episode_length_step=episode_length_step,
rllab_box = rllab_box,
servoj_t=servoj_t,
servoj_gain=servoj_gain,
speedj_a=speedj_a,
speedj_t_min=speedj_t_min,
movej_t=movej_t, # used for resetting
accel_max=accel_max,
speed_max=speed_max,
dt=dt,
delay=delay, # to simulate extra delay in the system
communicator_setups=communicator_setups,
**kwargs)
# Update the observation space from ReacherEnv to include camera
self.joint_dim = int(np.product(self._observation_space.shape))
self.input_dim = self.joint_dim + self.num_cameras * self.camera_dim
if rllab_box:
from rllab.spaces import Box as RlBox # use this for rllab TRPO
Box = RlBox
else:
from gym.spaces import Box as GymBox # use this for baselines algos
Box = GymBox
self._observation_space = Box(
low=-np.concatenate(
(np.zeros(self.num_cameras * self.camera_dim), self._observation_space.low)),
high=np.concatenate(
(np.ones(self.num_cameras * self.camera_dim), self._observation_space.high))
)
print("Communicators Setup")
RTRLBaseEnv.__init__(self, communicator_setups=communicator_setups,
action_dim=len(self.action_space.low),
observation_dim=len(self.observation_space.low),
dt=dt,
**kwargs)
self._obs_ = np.zeros(self.input_dim)
def _reset_(self):
print ("Reset Arm")
q_start = None
if self.q_start_queue:
q_start = np.array(self.q_start_queue.pop(0))
resetted = False
while not resetted:
super(ReacherEnvWithRealSense, self)._reset_(q_start=q_start,
q_target=self.q_target)
self._sensor_to_sensation_()
sensation, _, _ = self._sensation_buffer.read()
ur5_obs = sensation[0][:-2]
print(ur5_obs[-8:][:2], q_start)
if q_start is None or np.allclose(ur5_obs[-8:][:2], q_start, atol=1e-2, rtol=1e-2):
resetted = True
print("Reset Completed")
def _compute_sensation_(self, name, sensor_window, timestamp_window, index_window):
if name == 'UR5':
ur5_obs = super(ReacherEnvWithRealSense, self)._compute_sensation_(name, sensor_window, timestamp_window, index_window)
np.copyto(self._obs_[-self.joint_dim:], ur5_obs[:-2])
elif name.startswith('Camera'):
image = np.array(sensor_window[-1])
camera_idx = int(name.split("_")[1])
np.copyto(self._camera_images_[name], image.flatten())
np.copyto(self._obs_[camera_idx * self.camera_dim:(camera_idx + 1) * self.camera_dim], image.flatten())
return np.concatenate((self._obs_, [self._reward_.value], [0]))
def render(self):
cv2.namedWindow('RealSense', cv2.WINDOW_AUTOSIZE)
images = []
for idx in range(self.num_cameras):
images.append(self._camera_images_['Camera_{}'.format(idx)].reshape(self.camera_res).transpose(1, 2, 0))
images = np.hstack(images)
cv2.imshow('RealSense', images)
cv2.waitKey(1)
<file_sep>"""
AX-12 definitions
"""
#pylint: disable=invalid-name
from .dxl_unit_conv import (
Affine,
AngleVelRange,
SignedPercentRange,
BaudConversion,
ReturnTimeDelayConversion,
BooleanFlag,
ComplianceSlope)
from .dxl_reg import Reg, ContiguousRegisters
from math import pi
EightBits = (0, 255)
TenBits = (0, 1023)
# N.B.: Angle range of (-150, 150) is inconsistent with Robotis docs which
# are (0, 300) but consistent with our historic use.
AngleRange = Affine(-150 * pi / 180., 150 * pi / 180.) # Angles in radians
PercentRange = Affine(0, 100)
VoltRange = Affine(0, 25.5)
TempRange = Affine(0, 255)
SpeedRange = Affine(0, 114 * 360 * pi / 180. / 60.) # 114 rot/min -> rad/sec
AX12 = ContiguousRegisters(
Reg('version_0', 12),
Reg('version_1', 0),
Reg('firmware', 0),
Reg('bus_id', 1),
Reg('baud', 1, x_lim=EightBits, unit=BaudConversion()),
Reg('rtd', 250, x_lim=EightBits, unit=ReturnTimeDelayConversion()),
Reg('angle_limit_cw', (0, 0), x_lim=TenBits, unit=AngleRange),
Reg('angle_limit_ccw', (255, 3), x_lim=TenBits, unit=AngleRange),
Reg('reserved_0', 0),
Reg('temp_limit_high', 70, x_lim=EightBits, unit=TempRange),
Reg('voltage_limit_low', 60, x_lim=EightBits, unit=VoltRange),
Reg('voltage_limit_high', 140, x_lim=EightBits, unit=VoltRange),
Reg('max_torque', (255, 3), x_lim=TenBits, unit=PercentRange),
Reg('status_return', 2),
Reg('alarm_led', 36),
Reg('alarm_shutdown', 36),
Reg('reserved_1', (0, 0)),
Reg('reserved_2', (0, 0)),
Reg('reserved_3', 0),
Reg('torque_enable', 0, x_lim=(0, 1), unit=BooleanFlag()),
Reg('led', 0, x_lim=(0, 1), unit=BooleanFlag()),
Reg('cw_compliance_margin', 1, x_lim=EightBits, unit=AngleRange),
Reg('ccw_compliance_margin', 1, x_lim=EightBits, unit=AngleRange),
Reg('cw_compliance_slope', 32, x_lim=EightBits, unit=ComplianceSlope()),
Reg('ccw_compliance_slope', 32, x_lim=EightBits, unit=ComplianceSlope()),
Reg('goal_pos', (0, 0), x_lim=TenBits, unit=AngleRange),
Reg('moving_speed', (0, 0), x_lim=TenBits, unit=SpeedRange),
Reg('torque_limit', (255, 3), x_lim=TenBits, unit=PercentRange),
Reg('present_pos', (0, 0), x_lim=TenBits, unit=AngleRange),
Reg('present_speed', (0, 0),
x_lim=(0, 2047),
unit=AngleVelRange(114 * 360 * pi / 180. / 60.)),
Reg('present_load', (0, 0), x_lim=(0, 2047), unit=SignedPercentRange()),
Reg('voltage', 0, x_lim=EightBits, unit=VoltRange),
Reg('temperature', 0, x_lim=EightBits, unit=TempRange),
Reg('registered', 0),
Reg('reserved_4', 0),
Reg('moving', 0),
Reg('lock', 0),
Reg('punch', (32, 0), x_lim=(0x20, 0x3FF)))
<file_sep>import _pickle as pickle
import argparse
import numpy as np
import os
from torchvision import transforms
from args.parser import parse_data_cache_args
from data_collection.storage import Storage
from srl.srl.transforms import AsType, DownSample, NormalizeImage, Reshape, Transpose
def construct_data_cache_from_sql(args):
""" Construct data cache from sqlite3 storage.
We assume the data is a combination of images and a feature vector with the order:
(img_1, img_2, ..., img_N, feature_vector)
We also assume all images have the same resolution and channels
"""
print(args.dbname)
assert os.path.isfile(args.dbname)
assert args.num_scalar_features >= 0
assert args.num_images >= 0
assert args.num_channels >= 0
assert len(args.camera_res) == len(args.down_sample_res) == 2
original_image_flattened_dim = args.num_channels * int(np.product(args.camera_res))
down_sampled_image_flattened_dim = int(np.product(args.down_sample_res))
observation_transform = transforms.Compose(transforms=[
Reshape((args.num_channels, *args.camera_res)),
NormalizeImage(const=1/255),
AsType(dtype=np.uint8),
Transpose(transpose_shape=(1, 2, 0)),
DownSample(*args.down_sample_res),
transforms.ToPILImage(),
transforms.Grayscale(num_output_channels=1),
transforms.ToTensor(),
Reshape((down_sampled_image_flattened_dim))
])
storage = Storage(args.dbname)
num_episodes = storage.get_num_episodes()
print("{} episodes to process".format(num_episodes))
cached_data_trajectories = []
for episode_id in range(num_episodes):
if (episode_id + 1) % 100 == 0:
print("Processed {} episodes".format(episode_id + 1))
(observations, actions, rewards, dones) = storage.get_episode(episode_id)
num_timesteps = len(actions)
np_observations = np.empty(
shape=(num_timesteps + 1, args.num_images * down_sampled_image_flattened_dim + args.num_scalar_features),
dtype=np.float
)
np_actions = np.empty(shape=(num_timesteps, *actions[0].shape), dtype=np.float)
np_rewards = np.empty(shape=(num_timesteps, 1), dtype=np.float)
np_dones = np.empty(shape=(num_timesteps, 1), dtype=np.bool)
# Process observation
for timestep in range(num_timesteps):
for image_i in range(args.num_images):
np_observations[timestep, image_i * down_sampled_image_flattened_dim:(image_i + 1) * down_sampled_image_flattened_dim] = \
observation_transform(observations[timestep][image_i * original_image_flattened_dim:(image_i + 1) * original_image_flattened_dim])
np_observations[timestep, -args.num_scalar_features:] = observations[timestep][-args.num_scalar_features:]
np_actions[timestep] = actions[timestep]
np_rewards[timestep] = rewards[timestep]
np_dones[timestep] = dones[timestep]
# This is for last observation
for image_i in range(args.num_images):
np_observations[num_timesteps, image_i * down_sampled_image_flattened_dim:(image_i + 1) * down_sampled_image_flattened_dim] = \
observation_transform(observations[num_timesteps][image_i * original_image_flattened_dim:(image_i + 1) * original_image_flattened_dim])
np_observations[num_timesteps, -args.num_scalar_features:] = observations[num_timesteps][-args.num_scalar_features:]
cached_data_trajectories.append((np_observations, np_actions, np_rewards, np_dones))
print("Saving cache to {}".format(args.cached_data_path))
with open(args.cached_data_path, 'wb') as f:
pickle.dump({"trajectories": cached_data_trajectories, "args": args}, f, protocol=4)
if __name__ == "__main__":
args = parse_data_cache_args()
construct_data_cache_from_sql(args)
|
cc3860dca80d9f766354eba5abefb51aec61e2a2
|
[
"Markdown",
"Python",
"Shell"
] | 33 |
Python
|
utiasSTARS/robust-latent-srl
|
6979acba62ade7056d1b2e6c55439e39ffd51d33
|
b8c3131c525a13838c01363c6dccf137f0096584
|
refs/heads/hubs/master
|
<file_sep>#!/usr/bin/env node
var generator = require('./lib/generator');
var async = require('async');
var fs = require('fs');
var path = require('path');
var glob = require('glob');
var optimist = require('optimist');
module.exports = generate;
var FORMATS = {
'json': {template: 'json.template', extension: 'json', trim: false},
'yaml': {template: 'yaml.template', extension: 'yaml', trim: false},
'jsonarray': {template: 'jsonarray.template', extension: 'json', trim: false},
'pixi.js': {template: 'json.template', extension: 'json', trim: true},
'starling': {template: 'starling.template', extension: 'xml', trim: true},
'sparrow': {template: 'starling.template', extension: 'xml', trim: true},
'easel.js': {template: 'easeljs.template', extension: 'json', trim: false},
'egret': {template: 'egret.template', extension: 'json', trim: false},
'zebkit': {template: 'zebkit.template', extension: 'js', trim: false},
'cocos2d': {template: 'cocos2d.template', extension: 'plist', trim: false},
'cocos2d-v3': {template: 'cocos2d-v3.template', extension: 'plist', trim: false},
'css': {template: 'css.template', extension: 'css', trim: false},
'css-modules': {template: 'css-modules.template', extension: 'css', trim: false},
'custom-scale-css-modules': {template: 'custom-scale-css-modules.template', extension: 'css', trim: false}
};
if (!module.parent) {
var argv = optimist.usage('Usage: $0 [options] <files>')
.options('f', {
alias: 'format',
describe: 'format of spritesheet (starling, sparrow, json, yaml, pixi.js, easel.js, egret, zebkit, cocos2d)',
default: ''
})
.options('cf', {
alias: 'customFormat',
describe: 'path to external format template',
default: ''
})
.options('n', {
alias: 'name',
describe: 'name of generated spritesheet',
default: 'spritesheet'
})
.options('p', {
alias: 'path',
describe: 'path to export directory',
default: '.'
})
.options('fullpath', {
describe: 'include path in file name',
default: false,
boolean: true
})
.options('prefix', {
describe: 'prefix for image paths',
default: ""
})
.options('trim', {
describe: 'removes transparent whitespaces around images',
default: false,
boolean: true
})
.options('square', {
describe: 'texture should be s square',
default: false,
boolean: true
})
.options('powerOfTwo', {
describe: 'texture width and height should be power of two',
default: false,
boolean: true
})
.options('validate', {
describe: 'check algorithm returned data',
default: false,
boolean: true
})
.options('scale', {
describe: 'percentage scale',
default: '100%'
})
.options('fuzz', {
describe: 'percentage fuzz factor (usually value of 1% is a good choice)',
default: ''
})
.options('algorithm', {
describe: 'packing algorithm: growing-binpacking (default), binpacking (requires passing --width and --height options), vertical or horizontal',
default: 'growing-binpacking'
})
.options('width', {
describe: 'width for binpacking',
default: undefined
})
.options('height', {
describe: 'height for binpacking',
default: undefined
})
.options('padding', {
describe: 'padding between images in spritesheet',
default: 0
})
.options('sort', {
describe: 'Sort method: maxside (default), area, width or height',
default: 'maxside'
})
.options('divisibleByTwo', {
describe: 'every generated frame coordinates should be divisible by two',
default: false,
boolean: true
})
.options('cssOrder', {
describe: 'specify the exact order of generated css class names',
default: ''
})
.options('hubsFlag', {
describe: 'custom flag for generating spritesheet in hubs'
})
.options('customCanvasHeight', {
describe: 'custom canvas height',
default: 0
})
.options('customCanvasWidth', {
describe: 'custom canvas width',
default: 0
})
.options('customHeight', {
describe: 'custom height for css module spritesheet',
default: 0
})
.options('customWidth', {
describe: 'custom width for css module spritesheet',
default: 0
})
.check(function(argv){
if(argv.algorithm !== 'binpacking' || !isNaN(Number(argv.width)) && !isNaN(Number(argv.height))){
return true;
}
throw new Error('Width and/or height are not defined for binpacking');
})
.demand(1)
.argv;
if (argv._.length == 0) {
optimist.showHelp();
return;
}
const files = argv._[0].includes('*') ? argv._[0] : argv._;
generate(files, argv, function (err) {
if (err) throw err;
console.log('Spritesheet successfully generated');
});
}
/**
* generates spritesheet
* @param {string} files pattern of files images files
* @param {string[]} files paths to image files
* @param {object} options
* @param {string} options.format format of spritesheet (starling, sparrow, json, yaml, pixi.js, zebkit, easel.js, cocos2d)
* @param {string} options.customFormat external format template
* @param {string} options.name name of the generated spritesheet
* @param {string} options.path path to the generated spritesheet
* @param {string} options.prefix prefix for image paths
* @param {boolean} options.fullpath include path in file name
* @param {boolean} options.trim removes transparent whitespaces around images
* @param {boolean} options.square texture should be square
* @param {boolean} options.powerOfTwo texture's size (both width and height) should be a power of two
* @param {string} options.algorithm packing algorithm: growing-binpacking (default), binpacking (requires passing width and height options), vertical or horizontal
* @param {boolean} options.padding padding between images in spritesheet
* @param {string} options.sort Sort method: maxside (default), area, width, height or none
* @param {boolean} options.divisibleByTwo every generated frame coordinates should be divisible by two
* @param {string} options.cssOrder specify the exact order of generated css class names
* @param {function} callback
*/
function generate(files, options, callback) {
files = Array.isArray(files) ? files : glob.sync(files);
if (files.length == 0) return callback(new Error('no files specified'));
options = options || {};
if (Array.isArray(options.format)) {
options.format = options.format.map(function(x){return FORMATS[x]});
}
else if (options.format || !options.customFormat) {
options.format = [FORMATS[options.format] || FORMATS['json']];
}
options.name = options.name || 'spritesheet';
options.spritesheetName = options.name;
options.path = path.resolve(options.path || '.');
options.fullpath = options.hasOwnProperty('fullpath') ? options.fullpath : false;
options.square = options.hasOwnProperty('square') ? options.square : false;
options.powerOfTwo = options.hasOwnProperty('powerOfTwo') ? options.powerOfTwo : false;
options.extension = options.hasOwnProperty('extension') ? options.extension : options.format[0].extension;
options.trim = options.hasOwnProperty('trim') ? options.trim : options.format[0].trim;
options.algorithm = options.hasOwnProperty('algorithm') ? options.algorithm : 'growing-binpacking';
options.sort = options.hasOwnProperty('sort') ? options.sort : 'maxside';
options.padding = options.hasOwnProperty('padding') ? parseInt(options.padding, 10) : 0;
options.customHeight = options.hasOwnProperty('customHeight') ? parseInt(options.customHeight, 10) : 0;
options.customWidth = options.hasOwnProperty('customWidth') ? parseInt(options.customWidth, 10) : 0;
options.customCanvasHeight = options.hasOwnProperty('customCanvasHeight') ? parseInt(options.customCanvasHeight, 10) : 0;
options.customCanvasWidth = options.hasOwnProperty('customCanvasWidth') ? parseInt(options.customCanvasWidth, 10) : 0;
options.prefix = options.hasOwnProperty('prefix') ? options.prefix : '';
options.divisibleByTwo = options.hasOwnProperty('divisibleByTwo') ? options.divisibleByTwo : false;
options.cssOrder = options.hasOwnProperty('cssOrder') ? options.cssOrder : null;
options.hubsFlag = options.hasOwnProperty('hubsFlag');
files = files.map(function (item, index) {
var resolvedItem = path.resolve(item);
var name = "";
if (options.fullpath) {
name = item.substring(0, item.lastIndexOf("."));
}
else {
name = options.prefix + resolvedItem.substring(resolvedItem.lastIndexOf(path.sep) + 1, resolvedItem.lastIndexOf('.'));
}
return {
index: index,
path: resolvedItem,
name: name,
extension: path.extname(resolvedItem)
};
});
if (!fs.existsSync(options.path) && options.path !== '') fs.mkdirSync(options.path);
async.waterfall([
function (callback) {
generator.trimImages(files, options, callback);
},
function (callback) {
generator.getImagesSizes(files, options, callback);
},
function (files, callback) {
generator.determineCanvasSize(files, options, callback);
},
function (options, callback) {
generator.generateImage(files, options, callback);
},
function (callback) {
generator.generateData(files, options, callback);
}
],
callback);
}
<file_sep>var exec = require('child_process').exec;
var fs = require('fs');
var Mustache = require('mustache');
var async = require('async');
var os = require('os');
var path = require('path');
var crypto = require("crypto");
var packing = require('./packing/packing.js');
var sorter = require('./sorter/sorter.js');
/**
* Generate temporary trimmed image files
* @param {string[]} files
* @param {object} options
* @param {boolean} options.trim is trimming enabled
* @param callback
*/
exports.trimImages = function (files, options, callback) {
if (!options.trim) return callback(null);
var uuid = crypto.randomBytes(16).toString("hex");
var i = 0;
async.eachSeries(files, function (file, next) {
file.originalPath = file.path;
i++;
file.path = path.join(os.tmpdir(), 'spritesheet_js_' + uuid + "_" + (new Date()).getTime() + '_image_' + i + '.png');
var scale = options.scale && (options.scale !== '100%') ? ' -resize ' + options.scale : '';
var fuzz = options.fuzz ? ' -fuzz ' + options.fuzz : '';
//have to add 1px transparent border because imagemagick does trimming based on border pixel's color
exec('convert' + scale + ' ' + fuzz + ' -define png:exclude-chunks=date "' + file.originalPath + '" -bordercolor transparent -border 1 -trim "' + file.path + '"', next);
}, callback);
};
/**
* Iterates through given files and gets its size
* @param {string[]} files
* @param {object} options
* @param {boolean} options.trim is trimming enabled
* @param {function} callback
*/
exports.getImagesSizes = function (files, options, callback) {
var filePaths = files.map(function (file) {
return '"' + file.path + '"';
});
exec('identify ' + filePaths.join(' '), function (err, stdout) {
if (err) return callback(err);
var sizes = stdout.split('\n');
sizes = sizes.splice(0, sizes.length - 1);
sizes.forEach(function (item, i) {
var size = item.match(/ ([0-9]+)x([0-9]+) /);
files[i].width = parseInt(size[1], 10) + options.padding * 2;
files[i].height = parseInt(size[2], 10) + options.padding * 2;
var forceTrimmed = false;
if (options.divisibleByTwo) {
if (files[i].width & 1) {
files[i].width += 1;
forceTrimmed = true;
}
if (files[i].height & 1) {
files[i].height += 1;
forceTrimmed = true;
}
}
files[i].area = files[i].width * files[i].height;
files[i].trimmed = false;
if (options.trim) {
var rect = item.match(/ ([0-9]+)x([0-9]+)[\+\-]([0-9]+)[\+\-]([0-9]+) /);
files[i].trim = {};
files[i].trim.x = parseInt(rect[3], 10) - 1;
files[i].trim.y = parseInt(rect[4], 10) - 1;
files[i].trim.width = parseInt(rect[1], 10) - 2;
files[i].trim.height = parseInt(rect[2], 10) - 2;
files[i].trimmed = forceTrimmed || (files[i].trim.width !== files[i].width - options.padding * 2 || files[i].trim.height !== files[i].height - options.padding * 2);
}
});
callback(null, files);
});
};
/**
* Determines texture size using selected algorithm
* @param {object[]} files
* @param {object} options
* @param {object} options.algorithm (growing-binpacking, binpacking, vertical, horizontal)
* @param {object} options.square canvas width and height should be equal
* @param {object} options.powerOfTwo canvas width and height should be power of two
* @param {function} callback
*/
exports.determineCanvasSize = function (files, options, callback) {
files.forEach(function (item) {
item.w = item.width;
item.h = item.height;
});
// sort files based on the choosen options.sort method
sorter.run(options.sort, files);
packing.pack(options.algorithm, files, options);
if (options.square) {
options.width = options.height = Math.max(options.width, options.height);
}
if (options.powerOfTwo) {
options.width = roundToPowerOfTwo(options.width);
options.height = roundToPowerOfTwo(options.height);
}
options.width = options.customCanvasWidth || options.width;
options.height = options.customCanvasHeight || options.height;
callback(null, options);
};
/**
* generates texture data file
* @param {object[]} files
* @param {object} options
* @param {string} options.path path to image file
* @param {function} callback
*/
exports.generateImage = function (files, options, callback) {
var command = ['convert -define png:exclude-chunks=date -quality 0% -size ' + options.width + 'x' + options.height + ' xc:none'];
files.forEach(function (file) {
command.push('"' + file.path + '" -geometry +' + (file.x + options.padding) + '+' + (file.y + options.padding) + ' -composite');
});
command.push('"' + options.path + '/' + options.name + '.png"');
exec(command.join(' '), function (err) {
if (err) return callback(err);
unlinkTempFiles(files);
callback(null);
});
};
function unlinkTempFiles(files) {
files.forEach(function (file) {
if (file.originalPath && file.originalPath !== file.path) {
fs.unlinkSync(file.path.replace(/\\ /g, ' '));
}
});
}
/**
* generates texture data file
* @param {object[]} files
* @param {object} options
* @param {string} options.path path to data file
* @param {string} options.dataFile data file name
* @param {function} callback
*/
exports.generateData = function (files, options, callback) {
var formats = (Array.isArray(options.customFormat) ? options.customFormat : [options.customFormat]).concat(Array.isArray(options.format) ? options.format : [options.format]);
formats.forEach(function(format, i){
if (!format) return;
var path = typeof format === 'string' ? format : __dirname + '/../templates/' + format.template;
var templateContent = fs.readFileSync(path, 'utf-8');
var cssPriority = 0;
var cssPriorityNormal = cssPriority++;
var cssPriorityHover = cssPriority++;
var cssPriorityActive = cssPriority++;
// sort files based on the choosen options.sort method
sorter.run(options.sort, files);
options.customCssFiles = [];
options.files = files;
options.files.forEach(function (item, i) {
item.spritesheetWidth = options.width;
item.spritesheetHeight = options.height;
item.width -= options.padding * 2;
item.height -= options.padding * 2;
item.x += options.padding;
item.y += options.padding;
item.index = i;
if (item.trim) {
item.trim.frameX = -item.trim.x;
item.trim.frameY = -item.trim.y;
item.trim.offsetX = Math.floor(Math.abs(item.trim.x + item.width / 2 - item.trim.width / 2));
item.trim.offsetY = Math.floor(Math.abs(item.trim.y + item.height / 2 - item.trim.height / 2));
}
item.cssName = item.name || "";
if (item.cssName.indexOf("_hover") >= 0) {
item.cssName = item.cssName.replace("_hover", ":hover");
item.cssPriority = cssPriorityHover;
}
else if (item.cssName.indexOf("_active") >= 0) {
item.cssName = item.cssName.replace("_active", ":active");
item.cssPriority = cssPriorityActive;
}
else {
item.cssPriority = cssPriorityNormal;
}
if (options.hubsFlag && options.customWidth && options.customHeight) {
item.cssWidth = options.customWidth;
item.cssHeight = options.customHeight;
item.cssBackgroundPositionX = item.x * item.cssWidth / item.width;
item.cssBackgroundPositionY = item.y * item.cssHeight / item.height;
item.cssBackgroundWidth = item.spritesheetWidth * item.cssWidth / item.width;
item.cssBackgroundHeight = item.spritesheetHeight * item.cssHeight / item.height;
}
});
const hubsHoverMap = new Map();
if (options.hubsFlag) {
options.files.forEach( ( item ) =>{
const key = item.name.replace("_hover", "");
const pair = hubsHoverMap.get(key) || {};
const key2 = item.name.indexOf("_hover") !== -1 ? "hover" : "notHover";
pair[key2] = item;
hubsHoverMap.set(key, pair);
});
options.files.forEach((item)=>{
const hover = item.name.indexOf("_hover") !== -1;
if (hover) return;
const hoverItem = hubsHoverMap.get(item.name).hover;
item.hoverCssName = hoverItem.cssName;
item.hoverCssWidth = hoverItem.cssWidth;
item.hoverCssHeight = hoverItem.cssHeight;
item.hoverCssBackgroundPositionX = hoverItem.cssBackgroundPositionX;
item.hoverCssBackgroundPositionY = hoverItem.cssBackgroundPositionY;
item.hoverCssBackgroundWidth = hoverItem.cssBackgroundWidth;
item.hoverCssBackgroundHeight = hoverItem.cssBackgroundHeight;
options.customCssFiles.push(item);
});
}
function getIndexOfCssName(files, cssName) {
for (var i = 0; i < files.length; ++i) {
if (files[i].cssName === cssName) {
return i;
}
}
return -1;
};
if (options.cssOrder) {
var order = options.cssOrder.replace(/\./g,"").split(",");
order.forEach(function(cssName) {
var index = getIndexOfCssName(files, cssName);
if (index >= 0) {
files[index].cssPriority = cssPriority++;
}
else {
console.warn("could not find :" + cssName + "css name");
}
});
}
options.files.sort(function(a, b) {
return a.cssPriority - b.cssPriority;
});
options.files[options.files.length - 1].isLast = true;
var result = Mustache.render(templateContent, options);
function findPriority(property) {
var value = options[property];
var isArray = Array.isArray(value);
if (isArray) {
return i < value.length ? value[i] : format[property] || value[0];
}
return format[property] || value;
}
fs.writeFile(findPriority('path') + '/' + findPriority('name') + '.' + findPriority('extension'), result, callback);
});
};
/**
* Rounds a given number to to next number which is power of two
* @param {number} value number to be rounded
* @return {number} rounded number
*/
function roundToPowerOfTwo(value) {
var powers = 2;
while (value > powers) {
powers *= 2;
}
return powers;
}
<file_sep>// create 'images' package
var masv = masv || zebra.namespace("masv");
masv("images");
(function() {
var pkg = masv.images;
var sheet={
"image": "spritesheet.png",
"frames": [
[124, 713, 124, 50], //button
[0, 713, 124, 50], //button_active
[572, 649, 124, 50], //button_hover
[0, 0, 286, 355], //character_evil
[286, 0, 203, 346], //character_hero
[614, 355, 23, 115], //fx_particle_bomb
[0, 529, 190, 120], //fx_particle_boom_01
[190, 529, 161, 102], //fx_particle_boom_02
[480, 649, 92, 59], //fx_particle_boom_03
[286, 346, 59, 4], //fx_particle_bullett
[489, 218, 187, 134], //fx_particle_crash_01
[574, 529, 99, 82], //fx_particle_crash_02
[0, 355, 287, 174], //fx_particle_crash_03
[688, 454, 73, 36], //fx_particle_crash_04
[688, 220, 49, 55], //fx_particle_engine_01
[736, 148, 25, 23], //fx_particle_engine_02
[688, 524, 41, 34], //fx_particle_engine_03
[688, 275, 46, 49], //fx_particle_engine_04
[287, 355, 111, 170], //fx_particle_pow_01
[637, 355, 49, 84], //fx_particle_pow_02
[688, 324, 59, 45], //fx_particle_pow_03
[391, 649, 89, 59], //fx_particle_ratata_01
[248, 713, 85, 49], //fx_particle_ratata_02
[688, 412, 62, 42], //fx_particle_ratata_03
[688, 613, 52, 23], //fx_particle_ratata_04
[729, 524, 31, 23], //fx_particle_ratata_05
[736, 189, 17, 14], //fx_particle_ratata_06
[736, 171, 17, 18], //fx_particle_ratata_07
[734, 141, 7, 7], //fx_particle_shell
[688, 75, 46, 73], //fx_particle_smoke_01
[688, 0, 76, 75], //fx_particle_smoke_02
[688, 558, 37, 29], //fx_particle_smoke_03
[450, 713, 124, 46], //ship_enemy_body
[253, 649, 138, 61], //ship_enemy_full
[688, 636, 49, 13], //ship_enemy_gun
[688, 490, 68, 34], //ship_enemy_wing
[351, 529, 108, 95], //ship_giant_body
[734, 75, 25, 42], //ship_giant_engine
[333, 713, 117, 48], //ship_giant_floor
[489, 0, 199, 218], //ship_giant_full
[532, 355, 82, 129], //ship_giant_head
[398, 355, 134, 142], //ship_giant_roof
[574, 713, 82, 43], //ship_jet_body
[734, 117, 30, 24], //ship_jet_engine
[688, 587, 60, 26], //ship_jet_exhaust
[0, 649, 138, 64], //ship_jet_full
[398, 497, 54, 18], //ship_jet_gun
[688, 369, 46, 43], //ship_jet_head
[138, 649, 115, 62], //turret_enemy_base
[459, 529, 115, 94], //turret_enemy_full
[688, 148, 48, 72] //turret_enemy_gun
],
"sprites": {
"button":[0],
"button_active":[1],
"button_hover":[2],
"character_evil":[3],
"character_hero":[4],
"fx_particle_bomb":[5],
"fx_particle_boom_01":[6],
"fx_particle_boom_02":[7],
"fx_particle_boom_03":[8],
"fx_particle_bullett":[9],
"fx_particle_crash_01":[10],
"fx_particle_crash_02":[11],
"fx_particle_crash_03":[12],
"fx_particle_crash_04":[13],
"fx_particle_engine_01":[14],
"fx_particle_engine_02":[15],
"fx_particle_engine_03":[16],
"fx_particle_engine_04":[17],
"fx_particle_pow_01":[18],
"fx_particle_pow_02":[19],
"fx_particle_pow_03":[20],
"fx_particle_ratata_01":[21],
"fx_particle_ratata_02":[22],
"fx_particle_ratata_03":[23],
"fx_particle_ratata_04":[24],
"fx_particle_ratata_05":[25],
"fx_particle_ratata_06":[26],
"fx_particle_ratata_07":[27],
"fx_particle_shell":[28],
"fx_particle_smoke_01":[29],
"fx_particle_smoke_02":[30],
"fx_particle_smoke_03":[31],
"ship_enemy_body":[32],
"ship_enemy_full":[33],
"ship_enemy_gun":[34],
"ship_enemy_wing":[35],
"ship_giant_body":[36],
"ship_giant_engine":[37],
"ship_giant_floor":[38],
"ship_giant_full":[39],
"ship_giant_head":[40],
"ship_giant_roof":[41],
"ship_jet_body":[42],
"ship_jet_engine":[43],
"ship_jet_exhaust":[44],
"ship_jet_full":[45],
"ship_jet_gun":[46],
"ship_jet_head":[47],
"turret_enemy_base":[48],
"turret_enemy_full":[49],
"turret_enemy_gun":[50]
}
};
var atlas = new Image();
atlas.src=sheet.image;
var process = function(coords) { return new zebra.ui.Picture(atlas, coords[0], coords[1], coords[2], coords[3])};
var evalStr='';
for (var i=0;i<sheet.frames.length;i++) evalStr+='pkg.'+Object.keys(sheet.sprites)[i]+'=process(['+sheet.frames[i]+']);';
eval(evalStr);
}());
<file_sep>
==============
Spritesheet.js is command-line spritesheet (a.k.a. Texture Atlas) generator written in node.js.
### Supported spritesheet formats ###
* Starling / Sparrow
* JSON (i.e. PIXI.js)
* Easel.js
* cocos2d (i.e. version 2.x)
* cocos2d-v3 (i.e. version 3.x)
* CSS (new!)
### Usage ###
**Command Line**
```bash
$ spritesheet-js assets/*.png
```
Options:
```bash
$ spritesheet-js
Usage: spritesheet-js [options] <files>
Options:
-f, --format format of spritesheet (starling, sparrow, json, pixi.js, easel.js, cocos2d) [default: "json"]
-n, --name name of generated spritesheet [default: "spritesheet"]
-p, --path path to export directory [default: "."]
--fullpath include path in file name [default: false]
--prefix prefix for image paths (css format only) [default: ""]
--trim removes transparent whitespaces around images [default: false]
--square texture should be s square [default: false]
--powerOfTwo texture width and height should be power of two [default: false]
--validate check algorithm returned data [default: false]
--algorithm packing algorithm: growing-binpacking (default), binpacking (requires passing --width and --height options), vertical or horizontal [default: "growing-binpacking"]
--width width for binpacking [default: undefined]
--height height for binpacking [default: undefined]
--padding padding between images in spritesheet [default: 0]
--scale percentage scale [default: "100%"]
--fuzz percentage fuzz factor (usually value of 1% is a good choice) [default: ""]
```
**Node.js**
```javascript
var spritesheet = require('spritesheet-js');
spritesheet('assets/*.png', {format: 'json'}, function (err) {
if (err) throw err;
console.log('spritesheet successfully generated');
});
```
### Trimming / Cropping ###
Spritesheet.js can remove transparent whitespace around images. Thanks to that you can pack more assets into one spritesheet and it makes rendering a little bit faster.
*NOTE: Some libraries such as Easel.js dont't support this feature.*

### Installation ###
1. Install [ImageMagick](http://www.imagemagick.org/)
2. ```npm install spritesheet-js -g```
### Test ###
```
mocha test
```
--------------
Thanks [<NAME>](http://www.behance.net/piekarski) for logo design and assets in examples.
<file_sep>var spritesheet = require('..');
var assert = require('assert');
var expect = require('expect.js');
var fs = require('fs');
var FORMAT = {extension: 'json', template: 'json.template'};
describe('spritesheet.js', function () {
describe('with given pattern of files', function () {
it('should generate xml file', function (done) {
spritesheet(__dirname + '/fixtures/*', {name: 'test', path: __dirname, format: FORMAT}, function (err) {
expect(err).to.be(null);
expect(fs.existsSync(__dirname + '/test.json')).to.be.ok();
done();
});
});
it('should generate png file', function (done) {
spritesheet(__dirname + '/fixtures/*', {name: 'test', path: __dirname, format: FORMAT}, function (err) {
expect(err).to.be(null);
expect(fs.existsSync(__dirname + '/test.png')).to.be.ok();
done();
});
});
after(function () {
fs.unlinkSync(__dirname + '/test.json');
fs.unlinkSync(__dirname + '/test.png');
});
});
describe('with given array of files', function () {
it('should generate xml file', function (done) {
spritesheet([__dirname + '/fixtures/100x100.jpg'], {name: 'test', path: __dirname, format: FORMAT}, function (err) {
expect(err).to.be(null);
expect(fs.existsSync(__dirname + '/test.json')).to.be.ok();
done();
});
});
it('should generate png file', function (done) {
spritesheet([__dirname + '/fixtures/100x100.jpg'], {name: 'test', path: __dirname, format: FORMAT}, function (err) {
expect(err).to.be(null);
expect(fs.existsSync(__dirname + '/test.png')).to.be.ok();
done();
});
});
after(function () {
fs.unlinkSync(__dirname + '/test.json');
fs.unlinkSync(__dirname + '/test.png');
});
});
});
<file_sep>#!/bin/bash
node ../index.js -p json -f json --trim --padding 10 assets/*.png
node ../index.js -p yaml -f yaml --trim --padding 10 assets/*.png
node ../index.js -p json_50% -f json --trim --padding 10 --scale 50% assets/*.png
node ../index.js -p starling_sparrow -f starling --trim assets/*.png
node ../index.js -p easel_js -f easel.js --trim assets/*.png
node ../index.js -p zebkit -f zebkit --trim assets/*.png
node ../index.js -p cocos2d -f cocos2d --trim assets/*.png
node ../index.js -p css -f css --trim assets/*.png
#node ../index.js --name vertical --algorithm vertical --trim assets/*.png
#node ../index.js --name horizontal --algorithm horizontal --trim assets/*.png
#node ../index.js --name growing-binpacking --algorithm growing-binpacking --trim assets/*.png
#node ../index.js --name binpacking --algorithm binpacking --width 1000 --height 1000 --trim assets/*.png
|
58752e6b0773159bed688363b94e9fe4c6ba92b3
|
[
"JavaScript",
"Markdown",
"Shell"
] | 6 |
JavaScript
|
MozillaReality/spritesheet.js
|
edce7f45d9f1f5997850fba0d0034a44fceda8c5
|
de1810dd66d1ccaee44bf490b531bc2c55b2f861
|
refs/heads/master
|
<repo_name>davidfang/dolphin<file_sep>/utils/requestshelper.py
# -*- coding: utf-8 -*-
import requests
from settings import PROXIES
class RequestsHelper(object):
def __init__(self):
pass
@classmethod
def get(cls, url, params=None, **kwargs):
return requests.get(url, params, proxies=PROXIES, **kwargs)
@classmethod
def options(cls, url, **kwargs):
return requests.options(url, proxies=PROXIES, **kwargs)
@classmethod
def head(cls, url, **kwargs):
return requests.head(url, **kwargs)
@classmethod
def post(cls, url, data=None, json=None, **kwargs):
return requests.post(url, data=data, json=json, proxies=PROXIES, **kwargs)
@classmethod
def put(cls, url, data=None, **kwargs):
return requests.put(url, data=data, proxies=PROXIES, **kwargs)
@classmethod
def patch(cls, url, data=None, **kwargs):
return requests.patch(url, data=data, proxies=PROXIES, **kwargs)
@classmethod
def delete(cls, url, **kwargs):
return requests.delete(url, proxies=PROXIES, **kwargs)
<file_sep>/utils/exceptions.py
# -*- coding: utf-8 -*-
class TestException(Exception):
pass
<file_sep>/test/pathtest.py
# -*- coding: utf-8 -*-
print("__file__: %s" % __file__)
print("__name__: %s" % __name__)
# test windows<file_sep>/test/main.py
#coding=utf-8
from appium import webdriver
import os
# Returns abs path relative to this file and not cwd
PATH = lambda p: os.path.abspath(
os.path.join(os.path.dirname(__file__), p)
)
def get_desired_capabilities(app):
desired_caps = {
'platformName': 'Android',
'platformVersion': '5.1',
'deviceName': 'Android Emulator',
'app': PATH('../opt/' + app),
'newCommandTimeout': 240
}
return desired_caps
desired_caps = get_desired_capabilities(u'aweme_aweGW_v1.8.3_61b8304.apk')
driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)
driver.quit()
<file_sep>/utils/log.py
# -*- coding: utf-8 -*-
import logging
from settings import logging_config
logging.config.dictConfig(logging_config)
<file_sep>/utils/webfont.py
# -*- coding: utf-8 -*-
import os
from utils.log import logging
from utils.requestshelper import RequestsHelper
from fontTools.ttLib import TTFont
from PIL import Image, ImageEnhance
from pytesseract import *
logger = logging.getLogger(__name__)
class WebFont(object):
def __init__(self, plat_name):
self.url = 'https://vfile.meituan.net/colorstone/2c8d9a8f5031f26f4e9fe924263e31ce2076.woff'
self.plat_name = plat_name
self.font_dict = dict()
self.manual_dict = {
'uniF3C5': 8,
'uniEDEE': 6,
'uniF38E': 2,
'uniE824': 3,
'uniE829': 5,
'uniE851': 0,
'uniEBCF': 1,
'uniEE5A': 9,
'uniEFFE': 4,
'uniF35D': 7,
}
self.__init_font_map()
def __init_font_map(self):
"""
初始化猫眼的字符集模版,只在倒入模块时有构造方法调用一次
"""
font_file = self.__save_font_file(self.url)
font = TTFont(font_file)
glyph_set = font.getGlyphSet()
glyph_dict = glyph_set._glyphs.glyphs
for k, v in self.manual_dict.items():
self.font_dict[glyph_dict[k].data] = v
def __save_font_file(self, url):
filename = url.split('/')[-1]
font_dir = "%s/%s" % (os.path.dirname(__file__), '../opt/fonts')
# 判断文件是否存在
if not os.path.exists("%s/%s" % (font_dir, filename)):
if not os.path.exists(font_dir):
os.mkdir(font_dir)
try:
response = RequestsHelper.get(url)
except Exception:
raise Exception()
with open("%s/%s" % (font_dir, filename), 'wb') as fw:
fw.write(response.content)
return "%s/%s" % (font_dir, filename)
def convert_to_num(self, series, url):
"""
获取unicode的对应的数字
:param series: int
:param url: 字符集文件的地址
:return: int,series对应数字
"""
font_file = self.__save_font_file(url)
font = TTFont(font_file)
cmap = font.getBestCmap()
num = cmap.get(series)
glyph_set = font.getGlyphSet()
return self.font_dict[glyph_set._glyphs.glyphs[num].data]
class FontManager(object):
def __init__(self):
self.fonts = dict()
def add_font(self, plat_name):
"""
倒入该模块时调用此方法初始化字符集模版
:param plat_name: str 'maoyan'/
"""
if plat_name == 'maoyan':
self.fonts['maoyan'] = WebFont(plat_name)
elif plat_name == 'douyin':
pass
else:
raise Exception('平台:%s 暂不支持' % plat_name)
def get_font(self, plat_name):
try:
return self.fonts[plat_name]
except KeyError:
raise Exception('请先调用get_font()来添加平台%s的字符集' % plat_name)
def convert_to_num_ocr(self, fp):
"""
获取unicode的对应的数字
:param fp: 图片文件的路径或文件对象(必须byte方式打开)
:return: 图片对应的数字, 如果不符合数字格式,则返回图片上的文本
"""
im = Image.open(fp)
enhancer = ImageEnhance.Contrast(im)
image_enhancer = enhancer.enhance(4)
im_orig = image_enhancer.resize((image_enhancer.size[0]*2, image_enhancer.size[1]*2), Image.BILINEAR)
text = image_to_string(im_orig)
try:
return int(text)
except ValueError:
return text
fm = FontManager()
fm.add_font('maoyan')
maoyan_font = fm.get_font('maoyan')
logger.info(maoyan_font.convert_to_num(0xf8c3, 'https://vfile.meituan.net/colorstone/7986a5279399aeee3ef19fe37989a00d2088.woff'))
fp = open('/Users/apple/test/dolphin/opt/[email protected]', 'rb')
print(fm.convert_to_num_ocr(fp))<file_sep>/README.md
# dolphin
scrapy for maoyan
|
6e9cc00ee5df466b55a8b56670ef1988e190a1ab
|
[
"Markdown",
"Python"
] | 7 |
Python
|
davidfang/dolphin
|
c492b369b963ded2865b96d29e8c0a895082f0ac
|
ef4dc29a1f096dd4b945636930ca5a0d50fdb1ae
|
refs/heads/master
|
<file_sep>//
// ServerManager.hpp
// SocketServer
//
// Created by tng on 16/4/5.
// Copyright © 2016年 tng. All rights reserved.
//
#ifndef ServerManager_hpp
#define ServerManager_hpp
#include <stdio.h>
class ServerManager
{
public:
ServerManager();
~ServerManager();
void showLaunchLog();
void startServer();
};
#endif /* ServerManager_hpp */
<file_sep>//
// main.cpp
// SocketServer
//
// Created by tng on 16/4/4.
// Copyright © 2016年 tng. All rights reserved.
//
#include <iostream>
#include "ServerManager.hpp"
#include <sys/un.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string>
#include <assert.h>
#include "MainDefine_SocketManager.h"
using namespace std;
void startServer();
int main(int argc, const char * argv[])
{
startServer();// update.
printf("New commit.");
return 0;
}
void startServer()
{
struct sockaddr_in serv_addr, client_addr;
char recvmsgs[MAX_LEN_RW];
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
assert(sockfd >= 0);
// Config.
//
int reuse_addr_flag = 1;
int res_reuse = setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &reuse_addr_flag, sizeof(reuse_addr_flag));
assert(res_reuse >= 0);
// Addr.
//
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(SERVER_ADDR_PORT);
inet_pton(AF_INET, SERVER_ADDR_NAME, &client_addr.sin_addr);
bzero(&(serv_addr.sin_zero), 8);
// Bind and listen.
//
int res_bind = bind(sockfd, (struct sockaddr *)&serv_addr, sizeof(struct sockaddr));
assert(res_bind >= 0);
int res_listen = listen(sockfd, 5);
assert(res_listen != -1);
// Accept client service.
//
print_line;
cout<<"<< Server start :: Begin to accept client ... Host : "<<SERVER_ADDR_NAME<<" Port : "<<SERVER_ADDR_PORT<<endl;
print_line;
socklen_t len = sizeof(client_addr);
int res_accept = accept(sockfd, (struct sockaddr *)&client_addr, &len);
assert(res_accept >= 0);
char client_d[INET_ADDRSTRLEN];
print_line_short_sp;
cout<<"<< Server running :: New client : "<<inet_ntop(AF_INET, &client_addr.sin_addr, client_d, INET_ADDRSTRLEN);
cout<<" Port : "<<ntohs(client_addr.sin_port)<<endl;
print_line_short_sp;
// Receiving data.
//
while (true)
{
cout<<"<< Begin to recv ... accpstatus : "<<res_accept<<endl;
memset(recvmsgs, 0, MAX_LEN_RW);
size_t res_recv = recv(res_accept, recvmsgs, sizeof(recvmsgs), 0);
assert(res_recv >= 0);
cout<<"<< Recv time : "<<time(NULL)<<", got data : "<<recvmsgs<<endl;
string gotStr = recvmsgs;
if (gotStr.substr(0,4).compare("exit") == 0)
{
cout<<"<< Exit ... "<<endl;
close(res_accept);
}
}
}
<file_sep>//
// ServerManager.cpp
// SocketServer
//
// Created by tng on 16/4/5.
// Copyright © 2016年 tng. All rights reserved.
//
#include "ServerManager.hpp"
#include <iostream>
#include <sys/un.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string>
#include <assert.h>
#include "MainDefine_SocketManager.h"
using namespace std;
ServerManager::ServerManager()
{
this->startServer();
}
ServerManager::~ServerManager()
{
}
void ServerManager::showLaunchLog()
{
// Do nothing.
}
void ServerManager::startServer()
{
}
<file_sep>//
// MainDefine_SocketManager.h
// SocketServer
//
// Created by tng on 16/4/5.
// Copyright © 2016年 tng. All rights reserved.
//
#ifndef MainDefine_SocketManager_h
#define MainDefine_SocketManager_h
#define print_line cout<<"--------------------------------------------------------------------------"<<endl
#define print_line_short cout<<"------------------------------------------------------"<<endl
#define print_line_short_sp cout<<"-*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*--*-"<<endl
#define SERVER_ADDR_NAME "127.0.0.1"
#define SERVER_ADDR_PORT 9999
#define MAX_LEN_RW (8 * 4096)
#endif /* MainDefine_SocketManager_h */
<file_sep># SocketSer
SocketSer
|
fffde85de98554bfa17b0bd799b95ead128ef890
|
[
"Markdown",
"C",
"C++"
] | 5 |
C++
|
tang4595/SocketSer
|
0033084172e3c010ee15f6e5ccd4fbcda5671b80
|
060eb29322335123dd460b11c674c484d314fa75
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace stoppeklokke
{
public partial class frmStoppeklokke : Form
{
int i = 0;
public frmStoppeklokke()
{
InitializeComponent();
}
private void timer1_Tick(object sender, EventArgs e)
{
i++;
lblTid.Text = ftime(i);
}
private void btnStart_Click(object sender, EventArgs e)
{
timer1.Enabled = true;
btnStart.Enabled = false;
btnStopp.Enabled = true;
btnNullstill.Enabled = false;
}
private void btnStopp_Click(object sender, EventArgs e)
{
timer1.Enabled = false;
btnStopp.Enabled = false;
btnStart.Enabled = true;
btnNullstill.Enabled = true;
}
private void btnNullstill_Click(object sender, EventArgs e)
{
lblTid.Text = "00:00:00";
i = 0;
btnStopp.Enabled = false;
btnNullstill.Enabled = false;
btnStart.Enabled = true;
}
private string ftime(int i)
{
int h, m, s;
string hs, ms, ss;
h = (i / 3600) % 24;
m = (i / 60) % 60;
s = i % 60;
if (h < 10){ hs = "0" + h;} else {hs = h.ToString();}
if (m < 10){ ms = "0" + m;} else {ms = m.ToString();}
if (s < 10){ ss = "0" + s;} else {ss = s.ToString();}
return (hs + ":" + ms + ":" + ss);
}
}
}
<file_sep># stoppeklokke
En simpel stoppeklokke laget som øvingsoppgave i kurset PRG2000 - Programmering med .NET
|
90dc5a35eec242a614e0cb6a093c6c27c6376ba2
|
[
"Markdown",
"C#"
] | 2 |
C#
|
ERR0000RR/stoppeklokke
|
af751d474fe77218b0b7b7ef335c9ee6a8450c08
|
aae76899b4f4cce24384710b9635876e5a3d1e36
|
refs/heads/main
|
<repo_name>GRGR22/GEEKBRAINS<file_sep>/C/vim.c
#include <stdio.h>
int main() {
int input;
printf("Enter number");
scanf("%d, &input");
printf("Ypu entered number %d, we are doubled them for you%d", input, input*2)
return 0;
}
<file_sep>/README.md
# GEEKBRAINS
Study materials are located here
<file_sep>/C/Proj C/main.c
#include <stdio.h>
int main() {
int input;
printf("Input your penis inlargement");
scanf ("%d", &input);
if (input >= 18)
printf("Your penis is very goooood");
else
printf("Your penis is too small");
return 0;
}
|
3615745533e0fc9ff11c4322a8e2af074f0ee52f
|
[
"Markdown",
"C"
] | 3 |
C
|
GRGR22/GEEKBRAINS
|
5d83fc058829fae83fcb5e2bb1f1e300d4c93e32
|
2531d15f442667a8c44b8396fb2d2847204c0198
|
refs/heads/master
|
<repo_name>hszy00232/developExperience<file_sep>/JavaScript常用代码片断.md
## 克隆数组
javascript设计时,漏掉了数组的复制功能。在ES5中,开发者经常使用concat()方法来克隆。
```javascript
var colors = ["red","green","blue"];
var cloneColors = colors.concat();
console.log(cloneColors); //["red","green","blue"];
```
在ES6中,可以使用对象数组结构来实现
```javascript
let colors = ["red","green","blue"];
let [...cloneColors] = colors;
console.log(cloneColors); //["red","green","blue"];
```
<file_sep>/snapSlider.js
;(function($,win,doc){
var pluginName = 'snapSlider';
var pluginId = pluginName + 'Id';
var instances = {};
var makeUid = function(){
return 'u' + Math.random().toString().slice(-6) + (+new Date).toString().slice(-4);
};
var isEmptyObject = function(obj){
for(var i in obj){
if(obj.hasOwnProperty(i)){
return false;
}
}
return true;
};
var isBScrollLoaded = false;
var hasRunLoad = false;
var callbackQueue = [];
var loadScript = function(){
hasRunLoad = true;
if(isBScrollLoaded)return;
_loader.use('BScroll',function(){
isBScrollLoaded = true;
if(callbackQueue.length){
var callback;
while(typeof (callback = callbackQueue.shift()) === 'function'){
callback();
}
}
});
setTimeout(function(){
if(!isBScrollLoaded){
loadScript();
}
},6000);
};
$.fn[pluginName] = function(options){
var defaults = {
classNames: {
wrap: 'g-slider-snap',
list: 'g-slider-list',
item: 'g-slider-list > li',
dot: 'g-slider-dot',
active: 'active'
}
};
var config = $.extend(true,defaults,options || {});
var classSelector = function(name,scope){
return $('.' + config.classNames[name],scope);
};
var captialize = function(str){
return str.charAt(0).toUpperCase() + str.slice(1);
};
var isFn = function(fn){
return typeof fn === 'function';
};
this.each(function(){
var scope = $(this);
var slideWrap;
if(scope.hasClass(config.classNames.wrap)){
slideWrap = scope;
}else{
slideWrap = classSelector('wrap',scope);
}
slideWrap.each(function(){
var wrap = $(this);
var list = classSelector('list',wrap);
var items = classSelector('item',wrap);
var dotBar = classSelector('dot',wrap);
if(wrap.data(pluginId) || items.length === 0)return;
var w = items.width();
var init = function(w){
if(!w){
w = items.width();
}
items.show().css('width',w + 'px');
list.css('width',100 * items.length + '%');
var scroller = new BScroll(wrap[0],{
scrollX: true,
scrollY: false,
snap: true,
snapSpeed: 400,
momentum: false,
bounce: true,
click: false,
eventPassthrough: 'vertical'
});
var origDestroy = scroller.destroy;
var uid = makeUid();
var params = {
scroller: scroller,
list: list,
items: items,
wrap: wrap,
dot: dotBar,
uid: uid
};
var callbacks = [];
var customEvents = ['beforeScrollStart','scrollCancel','scrollStart','scroll','flick','zoomStart','zoomEnd'];
wrap.data(pluginId,uid);
scroller.__uid__ = uid;
scroller.destroy = function(){
var uid = this.__uid__;
var target = instances[uid];
if(target){
target.wrap.data(pluginId,null);
target.list.css('width','');
delete instances[uid];
}
origDestroy.call(this);
};
instances[uid] = params;
if(dotBar.length){
callbacks.push(function(page){
var cls = config.classNames.active;
dotBar.children().eq(page).addClass(cls).siblings('.' + cls).removeClass(cls);
});
}
if(isFn(config.onScrollEnd)){
callbacks.push(config.onScrollEnd);
}
if(isFn(config.initCallBack)){
config.initCallBack.call(this, scroller);
}
scroller.on('scrollEnd',function(){
var page = this.getCurrentPage().pageX;
if(callbacks.length){
var i = 0,total = callbacks.length;
for(; i < total; i++){
var fn = callbacks[i];
fn.call(this,page,params);
}
}
});
$.each(customEvents,function(i,name){
var fn = 'on' + captialize(name);
if(isFn(config[fn])){
scroller.on(name,config[fn]);
}
});
};
var callback = function(w){
if(!hasRunLoad){
loadScript();
}
if(!isBScrollLoaded){
callbackQueue.push(function(){
init(w);
});
}else{
init(w);
}
};
if(w === 0){
setTimeout(function(){
callback();
},0);
}else{
callback(w);
}
});
});
return this;
};
$(window).on('orientationchange',function(){
if(!isEmptyObject(instances)){
setTimeout(function(){
$.each(instances,function(i,cur){
var w = cur.wrap.width();
cur.items.css('width',w + 'px');
cur.scroller.refresh();
});
},200);
}
});
$.fn[pluginName].getInstance = function($ele,all){
var uid = $ele.data(pluginId);
return instances[uid] ? (all ? instances[uid] : instances[uid].scroller) : null;
};
})($,window,document);
<file_sep>/移动端开发.md
# img标签使用background属性无效
这个可能是安卓的微信webview支持的不好,因为在iphone和别的手机浏览器当中都可以支持,但是在安卓的微信webview不能显示,这个是兼容性的问题,所以最后选择在div中加background。
<file_sep>/README.md
# practicecode
用于存放一些demo,可以通过issue提交
<file_sep>/微信小程序开发.md
# 目录
* wepy重复点击问题处理
* 微信小程序中markdown转成html
1. [微信小程序设计稿规范](https://github.com/hszy00232/developExperience/blob/master/%E5%BE%AE%E4%BF%A1%E5%B0%8F%E7%A8%8B%E5%BA%8F%E5%BC%80%E5%8F%91.md#%E5%BE%AE%E4%BF%A1%E5%B0%8F%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1%E7%A8%BF%E8%A7%84%E8%8C%83)
2. [微信小程序开发相关资源](https://github.com/hszy00232/developExperience/blob/master/%E5%BE%AE%E4%BF%A1%E5%B0%8F%E7%A8%8B%E5%BA%8F%E5%BC%80%E5%8F%91.md#%E5%BE%AE%E4%BF%A1%E5%B0%8F%E7%A8%8B%E5%BA%8F%E5%BC%80%E5%8F%91%E7%9B%B8%E5%85%B3%E8%B5%84%E6%BA%90)
3. [wepy使用中的小坑](https://github.com/hszy00232/developExperience/blob/master/%E5%BE%AE%E4%BF%A1%E5%B0%8F%E7%A8%8B%E5%BA%8F%E5%BC%80%E5%8F%91.md#wepy%E4%BD%BF%E7%94%A8%E4%B8%AD%E7%9A%84%E5%B0%8F%E5%9D%91)
4. [发送模板消息(订阅通知)](https://github.com/hszy00232/developExperience/blob/master/%E5%BE%AE%E4%BF%A1%E5%B0%8F%E7%A8%8B%E5%BA%8F%E5%BC%80%E5%8F%91.md#%E5%8F%91%E9%80%81%E6%A8%A1%E6%9D%BF%E6%B6%88%E6%81%AF%E8%AE%A2%E9%98%85%E9%80%9A%E7%9F%A5)
5. [图片上传](https://github.com/hszy00232/developExperience/blob/master/%E5%BE%AE%E4%BF%A1%E5%B0%8F%E7%A8%8B%E5%BA%8F%E5%BC%80%E5%8F%91.md#%E5%9B%BE%E7%89%87%E4%B8%8A%E4%BC%A0)
6. [url参数限制](https://github.com/hszy00232/developExperience/blob/master/%E5%BE%AE%E4%BF%A1%E5%B0%8F%E7%A8%8B%E5%BA%8F%E5%BC%80%E5%8F%91.md#url%E5%8F%82%E6%95%B0%E9%99%90%E5%88%B6)
## 重复点击问题处理
```html
<view class="card" @tap="{{!buttonClicked?'goArticle':''}}"></view>
```
```javascript
data = {
buttonClicked: false
}
goArticle(){
var that = this
this.buttonClicked = true
setTimeout(function() {
that.buttonClicked = false
that.$apply()
}, 1500)
console.log(this.buttonClicked) // true
}
```
采用这种方式,连续点击时还是偶尔会触发两次
推荐方式:
```html
<view class="card" @tap="goArticle"></view>
```
```javascript
data = {
buttonClicked: false
}
goArticle(e) {
var that = this
if (!this.buttonClicked) {
that.buttonClicked = true
let id = e.currentTarget.id
wepy.navigateTo({
url: `/pages/original-article?id=${id}`
})
setTimeout(function() {
that.buttonClicked = false
that.$apply()
}, 1500)
}
}
```
## 微信小程序中markdown转成html
**showdown**:如果markdown文件中存在语法错乱问题时不能很好的解析
```javascript
var converter = new showdown.Converter({
extensions: function() {
function htmlunencode(text) {
return (
text
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/ /g, ' ')
.replace(/'/g, ''')
.replace(/"/g, '"')
);
}
return [{
type: 'output',
filter: function(text, converter, options) {
// use new shodown's regexp engine to conditionally parse codeblocks
var left = '<pre><code\\b[^>]*>',
right = '</code></pre>',
flags = 'g',
replacement = function(wholeMatch, match, left, right) {
// unescape match to prevent double escaping
match = htmlunencode(match);
return left + hljs.highlightAuto(match).value + right;
};
return showdown.helper.replaceRecursiveRegExp(text, replacement, left, right, flags);
}
}];
}()
});
var html = converter.makeHtml(data);
transData = HtmlToJson.html2json(html, bindName);
```
**markdown-it**:如果markdown文件中存在语法错乱问题时不能很好的解析
```javascript
let option = {
html: true,
xhtmlOut: true,
typographer: true,
highlight: function(code, lang, callback) {
return hljs.highlightAuto(code).value;
}
};
var html = markdown(option);
transData = HtmlToJson.html2json(html.render(data), bindName)
```
**marked**:对于markdown中有错误,也可很好的解析
```javascript
marked.setOptions({
highlight: function(code) {
return hljs.highlightAuto(code).value;
}
})
var html = marked(data);
transData = HtmlToJson.html2json(html, bindName);
```
## 微信小程序服务直达开发文档
https://mp.weixin.qq.com/servicezone/apidocs/html/%E6%9C%8D%E5%8A%A1%E7%B1%BB%E7%9B%AE/%E5%A4%A9%E6%B0%94/%E5%89%8D%E7%AB%AF%E6%A8%A1%E6%9D%BF.html
## 微信小程序无法弹出授权询问框
https://mp.weixin.qq.com/cgi-bin/announce?action=getannouncement&announce_id=11524128456FDRhq&version=&lang=zh_CN
## 微信小程序设计稿规范
设计师提供的设计稿建议采用iphone6,尺寸为`750px X 1334px`。开发使用时直接使用设计稿中给定的尺寸,单位由px替换成rpx。
## 微信小程序开发相关资源
[wepy文档](https://tencent.github.io/wepy/document.html)
[wepy使用介绍](http://dev.qq.com/topic/5844d6947badb2796037f9e3)
[微信小程序API](https://mp.weixin.qq.com/debug/wxadoc/dev/api/)
## wepy使用中的小坑
### 使用wepy new project命令生成的项目运行出错
VM8634:1 thirdScriptError sdk uncaught third Error Cannot set property 'Promise' of undefined TypeError: Cannot set property 'Promise' of undefined
VM8634:1 thirdScriptError sdk uncaught third Error Cannot read property '$pages' of undefined TypeError: Cannot read property '$pages' of undefined
解决方法:开发者工具 -> 设置 -> 项目设置 关闭ES6转ES5
### 使用wepy.request时报错
Cannot read property 'then' of undefined;
解决方法:
app.wpy文件中
```javascript
constructor () {
super()
this.use('promisify')
this.use('requestfix')
}
```
### dist目录中不需要的文件不会自动删除,可以使用npm run clean
package.json配置如下:
```
"clean": "find ./dist -maxdepth 1 -not -name 'project.config.json' -not -name 'dist' | xargs rm -rf",
```
## 发送模板消息(订阅通知)
[API地址](https://mp.weixin.qq.com/debug/wxadoc/dev/api/notice.html)



第一步:获取模板ID
第二步:使用`<form/>`组件,属性`report-submit`为`true`时,可以声明为需发模板消息,此时点击按钮提交表单可以通过`event.detail.formId`获取`formId`,用于发送模板消息。或者当用户完成支付行为,可以获取`prepay_id`用于发送模板消息。**注意:** `formId`只能在手机上才能取到,使用开发工具取不到
第三步:调用接口下发模板消息
## 图片上传
选取图片:
[选取图片API地址](https://mp.weixin.qq.com/debug/wxadoc/dev/api/media-picture.html#wxchooseimageobject)
```javascript
async chooseImage (method) {
const image = await wepy.chooseImage({
count: 1
})
let size = image.tempFiles[0].size / Math.pow(1024, 2)
// 图片超过2MB时不可以提交
if (size.toFixed(2) > 2) {
wx.showToast({
title: '图片不能超过2MB',
duration: 1000
})
return
}
this.imgPath = image.tempFilePaths[0]
this.$apply()
}
```
图片上传
[选取图片API地址](https://mp.weixin.qq.com/debug/wxadoc/dev/api/network-file.html)
```javascript
uploadImage (filePath) {
const userInfo = wepy.getStorageSync('user_info')
return wepy.uploadFile({
url: `${Conf.apiUrl}/image/upload`,
name: 'image',
filePath,
header: {
'content-type': 'multipart/form-data',
'Cookie': `token=${userInfo.token}`
}
})
}
```
踩到的坑:
iphone在某些情况下通过相机选取图片后,会把页面撑大,横向出现滚动条,从视觉上看像是宽高尺寸进行了对调。
临时的解决方案是,page尺寸定死,不用默认或100%,这种解决方案只是解决了page,但view仍然尺寸还是有问题的,所以横向还是有滚动条。
## url参数限制
url参数总长度不能超过30个字节,否则会被截断
## 获取二维码
[获取二维码API](https://mp.weixin.qq.com/debug/wxadoc/dev/api/qrcode.html)
## 转发功能
通过给 button 组件设置属性 open-type="share",可以在用户点击按钮后触发 Page.onShareAppMessage() 事件,如果当前页面没有定义此事件,则点击后无效果。
```
<button class="share-btn" open-type="share">邀请好友答题</button>
// 分享给朋友
onShareAppMessage() {
...
// 请求异步接口
let shareInfoConf = this.settingsConf.shareInfo
let titleLen = shareInfoConf.title.length
let index = Math.floor(Math.random() * titleLen) || 0
let title = shareInfoConf.title[index]
this.$apply()
return {
...shareInfoConf,
title: title,
path: `pages/hongbao/answer/index?q=${this.questId}`
}
};
```
|
e61923e7e3a8936c70e066655f035fc253e1513d
|
[
"Markdown",
"JavaScript"
] | 5 |
Markdown
|
hszy00232/developExperience
|
f34b04d7a01f755e6a0221bf668e6b84d2bb4387
|
48a14f2e57e7381388d46063dcf1a37926ef8c2c
|
refs/heads/master
|
<repo_name>Danilgor/untitled<file_sep>/src/table/table_by_days.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>WB</title>
</head>
<body>
<h1>Данные за всё время</h1>
<script>
let products = [
{date: '22.06.2021', price: 1735, qty: 3},
{date: '21.06.2021', price: 1735, qty: 1},
{date: '20.06.2021', price: 1735, qty: 1},
{date: '19.06.2021', price: 1735, qty: 0},
{date: '18.06.2021', price: 1845, qty: 3},
{date: '17.06.2021', price: 1845, qty: 1},
{date: '16.06.2021', price: 1845, qty: 0},
{date: '15.06.2021', price: 1845, qty: 1},
{date: '14.06.2021', price: 1845, qty: 3},
{date: '13.06.2021', price: 1845, qty: 1},
{date: '12.06.2021', price: 1845, qty: 0},
{date: '11.06.2021', price: 1845, qty: 2},
{date: '10.06.2021', price: 1600, qty: 2},
{date: '09.06.2021', price: 1500, qty: 1}
];
</script>
</body>
</html>
<!---
const Table = ({sortData, contactData}) => {
return (
<table className="table table-bordered">
<thead>
<button type="button" className="btn btn-success">Success</button>
<tr>
<th onClick={()=>{sortData('date')}}>
date
</th>
<th onClick={()=>{sortData('price')}}>price</th>
<th onClick={()=>{sortData('qty')}}>qty</th>
</tr>
</thead>
<tbody>
{contactData.map(
item=>(
<tr key={item.date}>
<td> {item.date}</td>
<td> {item.price}</td>
<td> {item.qty}</td>
</tr>
))}
</tbody>
</table>
)
}<file_sep>/src/App.js
import React, {useEffect, useState, Fragment} from 'react';
import TableDay from "./table/TableDay";
import TableTime from "./table/TableTime";
const App = ({children}) => (
<Fragment>
{children}
</Fragment>
)
export default App;
<file_sep>/src/table/TableDay.js
import React from 'react';
import {AgGridColumn, AgGridReact} from 'ag-grid-react';
import 'ag-grid-enterprise';
import '../App.scss'
import './TableDay.css'
const TableDay = (props) => {
const row_style = { background: 'black' };
//const [rowData, setRowData] = useState([]);
let rowData = [
{date: '22.06.2021', price: 1735, qty: 3},
{date: '22.05.2021', price: 1735, qty: 1},
{date: '22.05.2020', price: 1735, qty: 1},
{date: '19.06.2021', price: 1735, qty: 0},
{date: '18.06.2021', price: 1845, qty: 3},
{date: '17.06.2021', price: 1845, qty: 1},
{date: '16.06.2021', price: 1845, qty: 0},
{date: '15.06.2021', price: 1845, qty: 1},
{date: '14.06.2021', price: 1845, qty: 3},
{date: '13.06.2021', price: 1845, qty: 1},
{date: '12.06.2021', price: 1845, qty: 0},
{date: '11.06.2021', price: 1845, qty: 2},
{date: '10.06.2021', price: 1600, qty: 2},
{date: '09.06.2021', price: 1500, qty: 1}
];
// useEffect(() => {
// fetch('http://localhost:3000/products')
// .then(result => result.json())
// .then(rowData => setRowData(rowData))
// }, []);
// (function (item, index, rowData) {
// return rowData[0].date;
// })
//
// let result = rowData.date
// .sort((a, b) => new Date(a).getTime() > new Date(b).getTime() ? 1 : -1)
// console.log(result)
function formatNumber(number) {
return Math.floor(number)
.toString()
}
function currencyFormatter(params) {
return formatNumber(params.value) + ' ₽';
}
function textFormatter(params) {
return formatNumber(params.value) + ' шт';
}
const getContextMenuItems = (params) => {
if (0 === 0) {
return [
{
name: 'Open this day',
action: function () {
let day = params.value
localStorage.setItem('day', day);
// eslint-disable-next-line no-restricted-globals
open('http://localhost:3000/tabletime');
},
}
];
}
else return alert('is not date')
};
return (
<div className="ag-theme-balham table-day" row_style={row_style} style={{ height: 687, width: 647}}>
<AgGridReact defaultColDef={{
width: 215,
editable: false,
filter: 'agNumberColumnFilter',
floatingFilter: true,
resizable: false,
sortable: true,
}}
getContextMenuItems={getContextMenuItems}
popupParent={document.querySelector('body')}
debounceVerticalScrollbar={true}
enableRangeSelection={true}
clipboardDeliminator={' '}
columnTypes={{
numberColumn: {
width: 215,
filter: 'agNumberColumnFilter',
},
medalColumn: {
width: 215,
filter: false,
},
nonEditableColumn: { editable: false },
dateColumn: {
filter: 'agDateColumnFilter',
filterParams: {
comparator: function (filterLocalDateAtMidnight, cellValue) {
const dateParts = cellValue.split('.');
const day = Number(dateParts[0]);
const month = Number(dateParts[1]) - 1;
const year = Number(dateParts[2]);
const cellDate = new Date(year, month, day);
if (cellDate < filterLocalDateAtMidnight) {
return -1;
} else if (cellDate > filterLocalDateAtMidnight) {
return 1;
} else {
return 0;
}
},
},
},
}}
rowData={rowData}
>
<AgGridColumn
field="date"
minWidth={215}
filter="agDateColumnFilter"
type={['dateColumn', 'nonEditableColumn']}
comparator={dateComparator}
/>
<AgGridColumn
headerName="price"
minWidth={215}
field="price"
valueFormatter={currencyFormatter}
/>
<AgGridColumn
headerName="qty"
minWidth={215}
field="qty"
valueFormatter={textFormatter}
/>
</AgGridReact>
</div>
)
}
function dateComparator(date1, date2) {
let date1Number = monthToComparableNumber(date1);
let date2Number = monthToComparableNumber(date2);
function isDate(){
alert('is date')
};
if (date1Number === null && date2Number === null) {
return 0;
}
if (date1Number === null) {
return -1;
}
if (date2Number === null) {
return 1;
}
return date1Number - date2Number;
}
function monthToComparableNumber(date) {
if (date === undefined || date === null || date.length !== 10) {
return null;
}
let yearNumber = date.substring(6, 10);
let monthNumber = date.substring(3, 5);
let dayNumber = date.substring(0, 2);
return yearNumber * 10000 + monthNumber * 100 + dayNumber;
}
export default TableDay<file_sep>/src/SwitchTable.js
import React, {Fragment, useEffect, useState} from 'react';
import TableDay from "./table/TableDay";
import TableTime from "./table/TableTime";
import './table/rectangle.css'
const SwitchTable = ({children}) => (
<div>
<a href='http://localhost:3000/tableday'>tableday</a>
<br></br>
<a href='http://localhost:3000/tabletime'>tabletime</a>
<Fragment>
{children}
</Fragment>
</div>
)
export default SwitchTable;
|
0456d9c87300375e2fac5257124c174e2014d7d9
|
[
"JavaScript",
"HTML"
] | 4 |
HTML
|
Danilgor/untitled
|
e853fbc0b6c049ec9b5c62b992de5378f062d6e7
|
2a18a66b3a9bf8e7ff50363148284ba5b2f1b1b0
|
refs/heads/master
|
<repo_name>hhjyhxw/house-pre<file_sep>/pages/home/home.js
var {APIS} = require('../../const');
var { request } = require('../../libs/request');
var homeData = require('../../data/data-home.js');
var homeListData = require('../../data/data-homeList.js');
var { checkAppLogin } = require('../../libs/user');
Page({
/**
* 页面的初始数据
*/
data: {
specialsList:[],//特价房源
newHousingList:[],//最新房源
fuzzyQuery:[],//模糊查询
dowQuery:[],//上拉
inputShowed: true, // 搜索框状态
viewShowed: false,//显示结果view的状态
inputVal: "",// 搜索框值
show: false,//控制下拉列表的显示隐藏,false隐藏、true显示
// selectData: ['深圳', '龙华新区大浪', '大浪', '福田'],//下拉列表的数据
qyName: '南山区',//选择的下拉列表下标
imgList: APIS.IMG_LIST,//列表图片地址
},
// 点击下拉显示框
selectTap() {
this.setData({
show: !this.data.show
});
},
//点击下拉列表
optionTap(e) {
let qyName = e.currentTarget.dataset.name;//获取点击的下拉列表的下标
this.setData({
qyName: qyName,
show: !this.data.show
});
},
// 获取特价房源列表数据
getSpecialsList(e) {
let that = this;
request({
url: APIS.HOUSE_QUERY,
data: {
specifyes:'1'
},
method:'POST',
// 获取特价房源列表数据
realSuccess: function (resultData) {
let specialsList = resultData.dataList;
console.log(resultData)
that.setData({
specialsList:resultData.dataList,
});
},
//返回失败信息提示
realFail: function (resultMsg) {
wx.showToast({
title: resultMsg
});
},
realComplete: function (resultMsg) {
// console.log(resultMsg)
wx.showToast({
title: resultMsg
});
}
}, false, that)
},
// 获取最新房源列表数据
getNewhousingList() {
let that = this;
request({
url: APIS.HOUSE_QUERY,
data: {
latest: '1',
},
method:'POST',
// 获取最新房源列表数据
realSuccess: function (resultData) {
let newHousingList = resultData.dataList;
console.log(resultData)
that.setData({
newHousingList: resultData.dataList,
});
},
//返回失败信息提示
realFail: function (resultMsg) {
wx.showToast({
title: resultMsg
});
},
realComplete: function (resultMsg) {
// console.log(resultMsg)
wx.showToast({
title: resultMsg
});
}
}, false, that)
},
// 清除搜索框值
clearInput: function () {
this.setData({
inputVal: ""
});
},
// 模糊查询
fuzzyQuery:function(e) {
let that = this;
console.log(e.detail.value)
console.log(that.data.qyName)
if (e.detail.value == '') {
return;
}
that.setData({
viewShowed: false,
inputVal: e.detail.value
});
request({
url: APIS.HOUSE_QUERY,
data: {
title: e.detail.value,
village: that.data.qyName
},
method:'POST',
// 获取列表数据
realSuccess: function (resultData) {
that.setData({
specialsList: resultData.dataList,
newHousingList: resultData.dataList,
});
},
//返回失败信息提示
realFail: function (resultMsg) {
wx.showToast({
title: resultMsg
});
},
realComplete: function (resultMsg) {
// console.log(resultMsg)
wx.showToast({
title: resultMsg
});
}
}, false, that)
},
// 获取下拉框数据
dowQuery:function(e) {
let that = this;
request({
url: APIS.HOUSE_QUERY,
data: {
},
method:'POST',
// 获取列表数据
realSuccess: function (resultData) {
let dowQuery = resultData.dataList;
console.log(dowQuery)
that.setData({
dowQuery: resultData.dataList
});
},
//返回失败信息提示
realFail: function (resultMsg) {
wx.showToast({
title: resultMsg
});
},
realComplete: function (resultMsg) {
// console.log(resultMsg)
wx.showToast({
title: resultMsg
});
}
}, false, that)
},
// 跳转详情列表
detailsList: function (event){
// id;
// housetype;
// rentable;
// describes; //项目详情
// intdetail; // 主力户型
// baseservicer; // 楼盘动态
let { id, housetype, rentable, describes, intdetail, baseservicer } = event.currentTarget.dataset
if (housetype === 1 && rentable==='1'){//跳转写字楼租详情页
wx.navigateTo({
url: '../detailsPage/details/details?id=' + id + '&describes=' + describes + '&intdetail =' + intdetail,
})
} else if (housetype === 1 && rentable === '0') {//跳转写字楼售详情页
wx.navigateTo({
url: '../detailsPage/salesDetails/salesDetails?id=' + id + '&describes=' + describes + '&intdetail =' + intdetail + '&baseservicer' + baseservicer,
})
} else if (housetype === 2) {//跳转新房详情页
wx.navigateTo({
url: '../detailsPage/newHousDetails/newHousDetails?id=' + id + '&describes=' + describes + '&intdetail =' + intdetail + '&baseservicer' + baseservicer,
})
} else if (housetype === 3) {//跳转共享办公详情页
wx.navigateTo({
url: '../detailsPage/sharedDetails/sharedDetails?id=' + id,
})
}
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
let sid = wx.getStorageSync('sid');
checkAppLogin(sid, function () {
this.getSpecialsList()
this.getNewhousingList()
this.dowQuery()
}, this)
// this.setData({
// homeData: homeData.local_database,
// homeListData: homeListData.local_homeListdata
// })
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
})<file_sep>/data/data-home.js
var local_database = [
{
navigationImg: '/images/icon/home/navigation-1.png',
navigationText: '写字楼租'
},
{
navigationImg: '/images/icon/home/navigation-2.png',
navigationText: '写字楼售'
},
{
navigationImg: '/images/icon/home/navigation-3.png',
navigationText: '新房'
},
{
navigationImg: '/images/icon/home/navigation-4.png',
navigationText: '共享办公室'
},
]
module.exports = {
local_database: local_database
}
|
7722ba139bbea78a5ecc368a5b8f07cd834845e7
|
[
"JavaScript"
] | 2 |
JavaScript
|
hhjyhxw/house-pre
|
36ad24ba6fb94b32f1055de1d1314e9ef18e6b7d
|
649002362e7a1c33d20f20c0a5596e6f052639b0
|
refs/heads/master
|
<repo_name>ziyouchutuwenwu/hex_str<file_sep>/src/hex_str/hex_to_str.h
#ifndef HEX_TO_STR_H
#define HEX_TO_STR_H
/*
#include "hex_str/hex_to_str.h"
int main(void) {
char rx_buffer[] = {0xC8, 0x32, 0x9B, 0xFD, 0x0E, 0x01};
char hex_str_array[32] = {0};
int len = hex_to_str(rx_buffer, sizeof(rx_buffer), hex_str_array);
printf("hex_str_array: %s\n", hex_str_array);
char new_hex_bytes[100] = {0};
int len_to_save = str_to_hex(hex_str_array, new_hex_bytes);
return 0;
}
*/
int hex_to_str(unsigned char* input_buffer, unsigned int input_buffer_len, char* hex_str_to_save);
int str_to_hex(char* hex_str, unsigned char* bytes_to_save);
static int raw_str_to_hex(char* hex_str, unsigned char* bytes_to_save);
static char* del_substr(char* origin_str, const char* str_to_delete);
#endif<file_sep>/src/hex_str/hex_to_str.c
#include <stdio.h>
#include <string.h>
#include "hex_to_str.h"
int hex_to_str(unsigned char* input_buffer, unsigned int input_buffer_len, char* hex_str_to_save)
{
char str_buf[65] = {0};
char pbuf[64];
// 格式化字符串的长度
int times = 5;
for(unsigned int i = 0; i < input_buffer_len; i++) {
sprintf(pbuf, "0x%02X ", input_buffer[i]);
strncat(str_buf, pbuf, times);
}
strncpy(hex_str_to_save, str_buf, input_buffer_len * times);
return input_buffer_len * times;
}
int str_to_hex(char* hex_str, unsigned char* bytes_to_save)
{
char hex_str_without_prefix_space[100] = {0};
strncpy(
hex_str_without_prefix_space,
del_substr(del_substr(hex_str, "0x"), " "),
strlen(hex_str)/5 * 2 );
printf("hex_str_array: %s\n", hex_str_without_prefix_space);
int len_to_save = raw_str_to_hex(hex_str_without_prefix_space, bytes_to_save);
return len_to_save;
}
static int raw_str_to_hex(char* hex_str, unsigned char* bytes_to_save)
{
char* p = hex_str;
char high = 0, low = 0;
int tmplen = strlen(p), cnt = 0;
tmplen = strlen(p);
while(cnt < (tmplen / 2))
{
high = ((*p > '9') && ((*p <= 'F') || (*p <= 'f'))) ? *p - 48 - 7 : *p - 48;
low = (*(++ p) > '9' && ((*p <= 'F') || (*p <= 'f'))) ? *(p) - 48 - 7 : *(p) - 48;
bytes_to_save[cnt] = ((high & 0x0f) << 4 | (low & 0x0f));
p ++;
cnt ++;
}
if(tmplen % 2 != 0) bytes_to_save[cnt] = ((*p > '9') && ((*p <= 'F') || (*p <= 'f'))) ? *p - 48 - 7 : *p - 48;
return tmplen / 2 + tmplen % 2;
}
static char* del_substr(char* origin_str, const char* str_to_delete) {
int len = strlen(origin_str);
int len_sub = strlen(str_to_delete);
int i, j, k, m;
if ( len >= len_sub ) {
for(i=0,j=0; i<len; ) {
if(origin_str[i]==str_to_delete[0])
{
for(k=i,m=0; origin_str[k]==str_to_delete[m];k++,m++);
if(!str_to_delete[m]) i+=len_sub;
}
origin_str[j++]=origin_str[i++];
}
}
if (i==len ) origin_str[j]='\0';
return origin_str;
}<file_sep>/README.md
# c语言的 hex_to_str 和 str_to_hex, 将就用
<file_sep>/src/main.c
#include "hex_str/hex_to_str.h"
int main(void) {
char rx_buffer[] = {0xC8, 0x32, 0x9B, 0xFD, 0x0E, 0x01};
char hex_str_array[32] = {0};
int len = hex_to_str(rx_buffer, sizeof(rx_buffer), hex_str_array);
printf("hex_str_array: %s\n", hex_str_array);
char new_hex_bytes[100] = {0};
int len_to_save = str_to_hex(hex_str_array, new_hex_bytes);
return 0;
}
|
36566f23eed56b87a7efbb4d0590e3f3feb9a18d
|
[
"Markdown",
"C"
] | 4 |
C
|
ziyouchutuwenwu/hex_str
|
4eddaa7bd9df32797291ca5654c90e0fb61feb34
|
ba931e59cbf13238de97e7a4bf178e64ea932ff7
|
refs/heads/main
|
<repo_name>zhaoweixs/spring-cloud-study<file_sep>/oauth2/oauth2-study-02/oauth2-code-client/src/main/java/com/example/oauth2codeclient/controller/CodeController.java
package com.example.oauth2codeclient.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.*;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import io.jsonwebtoken.*;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;
/**
* ToDO
*
* @author zhaowei
* @date 2020/12/1 16:50
*/
@Controller
public class CodeController {
@GetMapping("/index")
public Object index(){
return "index";
}
/**
* 回调接口 接受授权码 并同步用授权码请求access_token
* @param code
* @return
*/
@GetMapping("/login")
public Object login(String code, Model model){
String tokenUrl = "http://localhost:8081/oauth/token";
OkHttpClient okHttpClient = new OkHttpClient();
RequestBody requestBody = new FormBody.Builder()
.add("grant_type","authorization_code")
.add("code",code)
.add("redirect_uri","http://localhost:8083/login")
.build();
Request request = new Request.Builder()
.url(tokenUrl)
.post(requestBody)
.addHeader("Authorization","Basic Y29kZS1jbGllbnQ6Y29kZS1zZWNyZXQtODg4OA==")
.build();
try {
Response response = okHttpClient.newCall(request).execute();
String result = response.body().string();
ObjectMapper objectMapper = new ObjectMapper();
Map<String,Object> map = objectMapper.readValue(result,Map.class);
String accessToken = map.get("access_token").toString();
Claims claims = Jwts.parser().setSigningKey("testSignKey".getBytes(StandardCharsets.UTF_8))
.parseClaimsJws(accessToken)
.getBody();
String username = claims.get("user_name").toString();
model.addAttribute("username",username);
model.addAttribute("accessToken",accessToken);
} catch (IOException e) {
e.printStackTrace();
}
return "index";
}
@org.springframework.web.bind.annotation.ResponseBody
@GetMapping(value = "get")
@PreAuthorize("hasAnyRole('ROLE_ADMIN')")
public Object get(Authentication authentication) {
//Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
authentication.getCredentials();
OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) authentication.getDetails();
String token = details.getTokenValue();
return token;
}
}
<file_sep>/oauth2/oauth2-study-01/oauth2-jwt-server/src/main/java/com/example/oauth2server/config/AuthorizationServerConfig.java
package com.example.oauth2server.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import java.util.ArrayList;
import java.util.List;
/**
* ToDO
*
* @author zhaowei
* @date 2020/11/30 15:12
*/
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private UserDetailsService userDetailsServiceImpl;
@Autowired
private TokenStore jwtTokenStore;
@Autowired
private JwtAccessTokenConverter jwtAccessTokenConverter;
@Autowired
private TokenEnhancer jwtTokenEnhancer;
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
security.tokenKeyAccess("isAuthenticated()");
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("testClientId")
.secret(passwordEncoder.encode("<PASSWORD>"))
.accessTokenValiditySeconds(3600)
.refreshTokenValiditySeconds(6000)
//.redirectUris("http://www.baidu.com")
.redirectUris("http://localhost:8082/login")
.autoApprove(true) // 这里加上自动授权 就会自动跳过需要用户点击手动授权那个步骤
.scopes("all")
.authorizedGrantTypes("authorization_code","password","refresh_token");
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
List<TokenEnhancer> delegates = new ArrayList<>();
delegates.add(jwtTokenEnhancer);
delegates.add(jwtAccessTokenConverter);
tokenEnhancerChain.setTokenEnhancers(delegates);
endpoints.authenticationManager(authenticationManager)
.userDetailsService(userDetailsServiceImpl)
.tokenStore(jwtTokenStore)
.accessTokenConverter(jwtAccessTokenConverter)
.tokenEnhancer(tokenEnhancerChain);
}
}
<file_sep>/oauth2/oauth2-study-01/oauth2-jwt-server/src/main/java/com/example/oauth2server/config/JwtTokenStoreConfiguration.java
package com.example.oauth2server.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
/**
* ToDO
*
* @author zhaowei
* @date 2020/11/30 19:04
*/
@Configuration
public class JwtTokenStoreConfiguration {
@Bean
public TokenStore jwtTokenStore(JwtAccessTokenConverter jwtAccessTokenConverter){
return new JwtTokenStore(jwtAccessTokenConverter);
}
@Bean
public JwtAccessTokenConverter jwtAccessTokenConverter(){
JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
jwtAccessTokenConverter.setSigningKey("testSignKey");
return jwtAccessTokenConverter;
}
@Bean
public TokenEnhancer jwtTokenEnhancer(){
return new JwtTokenEnhancer();
}
}
<file_sep>/oauth2/oauth2-study-01/oauth2-jwt-server/src/main/java/com/example/oauth2server/controller/UserController.java
package com.example.oauth2server.controller;
import io.jsonwebtoken.Jwts;
import org.springframework.security.core.Authentication;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
/**
* ToDO
*
* @author zhaowei
* @date 2020/11/30 15:30
*/
@RestController
@RequestMapping("/user")
public class UserController {
@GetMapping("/getCurrentLoginUser")
public Object getCurrentLoginUser(Authentication authentication, HttpServletRequest request){
String header = request.getHeader("Authorization");
String token = header.substring("bearer ".length());
return Jwts.parser().setSigningKey("testSignKey".getBytes(StandardCharsets.UTF_8)).parseClaimsJws(token)
.getBody();
}
}
<file_sep>/oauth2/oauth2-study-01/oauth2-server/src/main/java/com/example/oauth2server/controller/UserController.java
package com.example.oauth2server.controller;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* ToDO
*
* @author zhaowei
* @date 2020/11/30 15:30
*/
@RestController
@RequestMapping("/user")
public class UserController {
@GetMapping("/getCurrentLoginUser")
public Object getCurrentLoginUser(Authentication authentication){
return authentication.getPrincipal();
}
}
<file_sep>/README.md
# spring-cloud-study
spring cloud 学习整理
<file_sep>/oauth2/oauth2-study-01/oauth2-server/src/main/java/com/example/oauth2server/service/UserDetailsServiceImpl.java
package com.example.oauth2server.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
/**
*
* @author zhaowei
*/
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
private List<User> userList = new ArrayList<>();
@Autowired
private PasswordEncoder passwordEncoder;
@PostConstruct
public void init(){
String password = passwordEncoder.encode("<PASSWORD>");
userList.add(new User("admin",password, AuthorityUtils.commaSeparatedStringToAuthorityList("admin")));
userList.add(new User("zhaowei",password,AuthorityUtils.commaSeparatedStringToAuthorityList("client")));
userList.add(new User("dahuang",password,AuthorityUtils.commaSeparatedStringToAuthorityList("client")));
}
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
Optional<User> optionalUser = userList.stream().filter(u -> u.getUsername().equals(s)).findFirst();
if (optionalUser.isPresent()){
return optionalUser.get();
}else {
throw new UsernameNotFoundException("用户名错了");
}
}
}
<file_sep>/oauth2/oauth2-study-02/oauth2-server/src/main/java/com/example/oauth2server/config/OAuth2Config.java
package com.example.oauth2server.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.builders.JdbcClientDetailsServiceBuilder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.List;
/**
* ToDO
*
* @author zhaowei
* @date 2020/12/1 10:45
*/
@Configuration
@EnableAuthorizationServer
public class OAuth2Config extends AuthorizationServerConfigurerAdapter {
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private UserDetailsService userDetailsServiceImpl;
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private TokenStore jwtTokenStore;
@Autowired
private JwtAccessTokenConverter jwtAccessTokenConverter;
@Autowired
private TokenEnhancer jwtTokenEnhancer;
@Autowired
private DataSource dataSource;
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
security.allowFormAuthenticationForClients().checkTokenAccess("isAuthenticated()")
.tokenKeyAccess("isAuthenticated()");
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.jdbc(dataSource);
// clients.inMemory()
// .withClient("code-client")
// .secret(passwordEncoder.encode("<PASSWORD>"))
// .authorizedGrantTypes("refresh_token", "authorization_code", "password")
// .accessTokenValiditySeconds(3600)
// .refreshTokenValiditySeconds(6000)
// .autoApprove()
// .scopes("all")
// .redirectUris("http://localhost:8083/login")
// .and()
// .withClient("user-client")
// .secret(passwordEncoder.encode("<PASSWORD>"))
// .authorizedGrantTypes("refresh_token", "authorization_code", "password")
// .accessTokenValiditySeconds(3600)
// .refreshTokenValiditySeconds(6000)
// .scopes("all");
}
// @Bean
// public ClientDetailsService clientDetailsService(){
// return new JdbcClientDetailsService(dataSource);
// }
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
List<TokenEnhancer> list = new ArrayList<>();
// 注意这里的顺序 增强器要先放到集合里 否则返回的jwt没有增强属性
list.add(jwtTokenEnhancer);
list.add(jwtAccessTokenConverter);
tokenEnhancerChain.setTokenEnhancers(list);
endpoints.authenticationManager(authenticationManager)
.userDetailsService(userDetailsServiceImpl)
.tokenStore(jwtTokenStore)
.accessTokenConverter(jwtAccessTokenConverter)
.tokenEnhancer(tokenEnhancerChain);
}
}
|
3f1d879ff4eef2a5c3f349294bf1ebf4bb115c15
|
[
"Markdown",
"Java"
] | 8 |
Java
|
zhaoweixs/spring-cloud-study
|
5c3d56e74c36bb174b2b9ff3aecc0e18bac10646
|
e57284823f8dfaf529df16ccede0242c0f86c8d0
|
refs/heads/master
|
<repo_name>danielmessi13/OpenCV-Python<file_sep>/README.md
# OpenCV-Python
Teste com OpenCV usando Python (LAPESI)
<file_sep>/Reconhecimento_OpenCV/reconhecimento.py
# coding=utf-8
import cv2
import numpy as np
# carregar as imagens
img1 = cv2.imread("ESTEIRA0.jpg")
img2 = cv2.imread("ESTEIRA1.jpg")
img3 = cv2.imread("mask.jpg")
# convert the images for gray scale
imgray1 = cv2.cvtColor(img1, cv2.COLOR_RGB2GRAY)
imgray2 = cv2.cvtColor(img2, cv2.COLOR_RGB2GRAY)
maskgray = cv2.cvtColor(img3, cv2.COLOR_RGB2GRAY)
# cv2.imshow("Segunda",imgray2)
# cv2.imshow("Terceira",maskgray3)
# cv2.imshow("Terceira",imgray3)
# cv2.waitKey(0)
# procura diferença entre as duas img
diference = cv2.subtract(imgray1, imgray2)
# Se não fizer isso alguns pixels não vão ser binarios e vão mostrar cores diferentes
diference[diference > 0] = 255
# Kernel pra usar na função de tirar os contornos errados
kernel = np.ones((2, 2), np.uint8)
# Tirar erros
erode = cv2.erode(diference, kernel, iterations=2)
maskerode = cv2.erode(maskgray, kernel, iterations=2)
# Procurar contornos
im1, cont1, hier1 = cv2.findContours(maskerode, cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_NONE)
#find contours
im2, cont, hier = cv2.findContours(erode, cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_NONE)
fruits = [0,0,0]
for i in range(0, len(cont)):
result = [0,0]
for j in range(0, len(cont1)):
result[j] = cv2.matchShapes(cont1[j], cont[i], 1, 0)
index = result.index(min(result))
if index is 0:
fruits[i] = "banana"
print min(result)
else:
fruits[i] = "laranja"
print min(result)
fruits = np.array(fruits)
# draw the rectangle of the contour
if len(cont) > 0:
num = 0
for c in cont:
x, y, w, h = cv2.boundingRect(c)
cv2.rectangle(img2, (x,y), (x+w,y+h), (0, 255, 0), 2)
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(img2,fruits[num],(x,y-10), font, 0.8,(0,255,0),2,cv2.LINE_AA)
num += 1
# show the result
if result is not True:
cv2.imshow('DETECCAO', img2)
cv2.waitKey(0)
else:
print("Não há itens!!")
# A função toma três argumentos: a imagem a ser erodida,
# o kernel que é basicamente um quadrado que será aplicado como erosão, logo acima eu criei um array 2×2
# zeros tipo uint8. E por último o iterations, que é a quantidade de vezes que será aplicado o processo de erosão.
# Tanto o tamanho do kernel e o iterations vão variar de acordo com a aplicação, então se você precisar utilizar,
# terá que testar na prática qual configuração lhe dá o melhor resultado. Neste caso poderia usar outra função chamada
# cv2.morphologyEx().
<file_sep>/Reconhecimento_OpenCV/formas_geometricas.py
import cv2
import numpy as np
canvas = np.ones((300, 400, 3)) * 255
#imagem 400x300, com fundo branco e 3 canais para as cores
#cv2.imshow("Canvas", canvas)
# desenha a linha diagonal
azul = (255, 0, 0)
cv2.line(canvas, (0, 0), (400, 300), azul)
#img, ponto 1, ponto 2, cor, tickness (timidez)
#cv2.imshow("Canvas", canvas)
# desenha a linha vertical
verde = (0, 255, 0)
cv2.line(canvas, (200, 0), (200, 300), verde, 3)
#img, ponto 1, ponto 2, cor, tickness (timidez)
#cv2.imshow("Canvas", canvas)
# desenha o retângulo com borda verde
cv2.rectangle(canvas, (10, 70), (90, 190), verde)
#img, ponto 1, ponto 2, cor, tickness (timidez)
#cv2.imshow("Canvas", canvas)
# desenha o retângulo todo vermelho
vermelho = (0, 0, 255)
cv2.rectangle(canvas, (250, 50), (300, 125), vermelho, -1)
cv2.imshow("Canvas", canvas)
cv2.waitKey(0)
|
d521dd56fbed45c5a2ccd51af07c7dc56181e58d
|
[
"Markdown",
"Python"
] | 3 |
Markdown
|
danielmessi13/OpenCV-Python
|
7335ac2809750ab2ab6722eaa726e134bc53f363
|
f0bb20674bd80710a72f6e2cd1b0356ef2dd7653
|
refs/heads/master
|
<repo_name>m-den-i/embedded<file_sep>/Lab5/hello_timer.c
#include <linux/module.h>
#include <linux/init.h>
#include <linux/kobject.h>
#include <linux/sysfs.h>
#include <linux/string.h>
#include <linux/kernel.h>
#include <linux/timer.h>
static int delay = -1;
struct timer_list timer;
static void hello(unsigned long arg)
{
printk(KERN_INFO "hello world!\n");
timer.expires = jiffies + HZ*delay;
add_timer (&timer);
}
static ssize_t show(struct kobject *kobj,
struct kobj_attribute *attr, char *buf)
{
return sprintf(buf, "%d\n", delay);
}
static ssize_t store(struct kobject *kobj,
struct kobj_attribute *attr, const char *buf, size_t count)
{
int tmp = 0;
sscanf(buf, "%du", &tmp);
if(tmp > 0) {
if(delay < 0) {
init_timer (&timer);
timer.function = hello;
timer.data = 0;
hello(0);
}
delay = tmp;
}
return count;
}
static struct kobj_attribute sc_attrb =
__ATTR(timer, 0666, show, store);
static struct kobject *kobj;
static int __init example_init(void)
{
kobj = kobject_create_and_add("hello", NULL);
if (!kobj)
return - ENOMEM;
if(sysfs_create_file(kobj, &sc_attrb.attr))
kobject_put(kobj);
return 0;
}
static void __exit example_exit(void)
{
del_timer (&timer);
sysfs_remove_file(kobj, &sc_attrb.attr);
kobject_put(kobj);
}
module_init(example_init);
module_exit(example_exit);
MODULE_LICENSE("GPL");
<file_sep>/Lab1/Makefile
#############################################################################
# Makefile for building: admin-console
#############################################################################
####### Compiler, tools and options
CC = gcc
CFLAGS = -Wall
LIBS = -ldl
####### Files
SOURCES = main.c
OBJECTS = main.o
TARGET = main
####### Build rules
all: $(TARGET)
clean:
$(RM) -f $(TARGET) *.o *~
$(TARGET): $(OBJECTS)
$(CC) $(CFLAGS) $(OBJECTS) $(LIBS) -o $(TARGET)
%.o: %.c
$(CC) $(CFLAGS) -c $<
<file_sep>/Lab4/test.sh
#!/bin/bash
op[0]='-'
op[1]='+'
op[2]='*'
op[3]='/'
for i in {0..3}
do
as=$RANDOM
bs=$RANDOM
let "cs = $as ${op[i]} $bs"
echo EXPECTED: $as${op[i]}$bs = $cs
echo $as > /proc/a
echo $bs > /proc/b
echo ${op[i]} > /proc/op
res=$(cat /proc/res)
echo GOT: $res
if [[ "$res" -eq "$cs" ]]
then
echo TRUE
else
echo FALSE
fi
done
<file_sep>/README.md
#<NAME>, "Embedded systems"
<file_sep>/Lab3/server.c
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <errno.h>
#include <pthread.h>
#include <unistd.h>
#define PORT 5000
#define BUFFER_SIZE 256
#define MAX_FILENAME_SIZE 256
#define MAX_THREAD_COUNT 5
//#define THREAD
void* send_file(void* param)
{
char filename[MAX_FILENAME_SIZE];
unsigned char buffer[BUFFER_SIZE] = { 0 };
FILE *file;
int bytes_read = 0, bytes_send = 0;
int client_id = (int)param;
bytes_read = read(client_id, filename, sizeof(filename)-1);
if (bytes_read < 0) {
printf("Error reading filename.\n");
close(client_id);
return 0;
}
/* Open the file to transfer */
filename[bytes_read] = 0;
if (access(filename, F_OK) == -1) {
printf("File not found.\n");
close(client_id);
return 0;
}
file = fopen(filename, "rb");
if (file == NULL) {
printf("File open error.\n");
close(client_id);
return 0;
}
/* Read file and send it */
for (;;) {
bytes_read = fread(buffer, 1, BUFFER_SIZE, file);
/* If read was success, send data. */
if (bytes_read > 0) {
bytes_send = write(client_id, buffer, bytes_read);
if (bytes_send < bytes_read) {
printf("Error sending file.\n");
fclose(file);
close(client_id);
return 0;
}
printf("Bytes send: %d\n", bytes_send);
}
if (bytes_read < BUFFER_SIZE) {
if (feof(file))
printf("File send.\n");
if (ferror(file))
printf("Error reading from file.\n");
break;
}
}
fclose(file);
close(client_id);
return 0;
}
int main(int argc, char* argv[])
{
int socket_id = 0, client_id = 0, yes = 1;
struct sockaddr_in server_socket;
#ifdef THREAD
pthread_t threads[MAX_THREAD_COUNT] = { NULL };
int error = 0;
int i = 0;
#else
pid_t proc_id = 0;
#endif
if ((socket_id = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
printf("Error : Could not create socket.\n");
return 1;
}
printf("Socket retrieve success\n");
memset(&server_socket, '0', sizeof(server_socket));
server_socket.sin_family = AF_INET;
server_socket.sin_addr.s_addr = INADDR_ANY;
server_socket.sin_port = htons(PORT);
if (setsockopt(socket_id, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) {
printf("Error : Setting socket options failed.\n");
return 1;
}
if ((bind(socket_id, (struct sockaddr*)&server_socket, sizeof(server_socket))) < 0) {
printf("Error : Binding socket failed.\n");
return 1;
}
if (listen(socket_id, 10) == -1) {
printf("Error : Listening socket failed.\n");
return -1;
}
for (;;) {
client_id = accept(socket_id, (struct sockaddr*)NULL, NULL);
if (client_id < 0) {
printf("Error : Accept client failed.\n");
continue;
}
#ifdef THREAD
for (i = 0; i < MAX_THREAD_COUNT; i++)
if ((threads[i] == NULL) || (pthread_kill(threads[i], 0) != ESRCH))
break;
if (i >= MAX_THREAD_COUNT) {
printf("Error : There's no free threads.\n");
continue;
}
error = pthread_create(&threads[i], NULL, send_file, (void*)client_id);
if (error) {
printf("Error : Thread create failed.\n");
continue;
}
#else
switch (proc_id = fork()) {
case -1:
printf("Error : Process create failed.\n");
break;
case 0:
send_file((void*)client_id);
return 0;
default:
close(client_id);
break;
}
#endif
}
return 0;
}
<file_sep>/Lab2/weather.sh
#!/bin/bash
source config
while true
do
rm minsk > /dev/null 2>&1
wget http://pogoda.tut.by/city/minsk > /dev/null 2>&1
grep '<span\ class=\"temp-i\">.*<\/span>' minsk | sed -n '1p' | grep -o '[+-]*[0-9]'
sleep $timeout
done
<file_sep>/Lab3/Makefile
all:
gcc client.c -o client
gcc -lpthread server.c -o server
threads:
gcc client.c -o client
gcc -lpthread server.c -DTHREAD -o server
clean:
rm -f client
rm -f server<file_sep>/Lab3/client.c
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#define PORT 5000
#define BUF_SIZE 256
#define MAX_FILENAME_SIZE 256
int main(int argc, char* argv[])
{
char filename[MAX_FILENAME_SIZE];
int bytes_received = 0, socket_id = 0;
char buffer[BUF_SIZE];
struct sockaddr_in server_socket;
FILE *file;
memset(buffer, '0', sizeof(buffer));
printf("Input file name: ");
scanf("%s", filename);
/* Create socket*/
if ((socket_id = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
printf("Error : Could not create socket.\n");
return 1;
}
/* Initialize sockaddr_in data structure */
server_socket.sin_family = AF_INET;
server_socket.sin_port = htons(PORT);
server_socket.sin_addr.s_addr = inet_addr("127.0.0.1"); //localhost
/* Attempt a connection */
if (connect(socket_id, (struct sockaddr*)&server_socket, sizeof(server_socket)) < 0) {
printf("Error : Connection failed.\n");
close(socket_id);
return 1;
}
/* Send file name */
if (send(socket_id, filename, strlen(filename), 0) < 0) {
printf("Error : Sending file name failed.\n");
close(socket_id);
return 1;
}
printf("Filename send.\n");
/* Receive data */
if ((bytes_received = read(socket_id, buffer, BUF_SIZE)) > 0) {
file = fopen(filename, "wb");
if (file == NULL) {
printf("Error opening file.\n");
close(socket_id);
return 1;
}
fwrite(buffer, 1, bytes_received, file);
} else {
printf("Error : File not found.\n");
close(socket_id);
return 1;
}
while ((bytes_received = read(socket_id, buffer, BUF_SIZE)) > 0)
fwrite(buffer, 1, bytes_received, file);
if (bytes_received < 0)
printf("Error : Reading file failed.\n");
printf("File reading finished.\n");
fclose(file);
close(socket_id);
return 0;
}
<file_sep>/Lab4/procfs.c
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/proc_fs.h>
#include <asm-generic/uaccess.h>
static char msg[128];
static int len = 0;
static int len_check = 1;
int a = 0, b = 0;
static int res = 0;
//Simple read/write/open/release functions
int simple_proc_open(struct inode * sp_inode, struct file *sp_file){
printk(KERN_INFO "proc called open\n");
return 0;
}
int simple_proc_release(struct inode *sp_indoe, struct file *sp_file){
printk(KERN_INFO "proc called release\n");
return 0;
}
int simple_proc_write(struct file *sp_file,const char __user *buf, size_t size, loff_t *offset)
{
printk(KERN_INFO "proc called write %d\n",(int)size);
len = size;
copy_from_user(msg,buf,len);
return len;
}
int simple_proc_read(struct file *sp_file,char __user *buf, size_t size, loff_t *offset){
if (len_check)
len_check = 0;
else {
len_check = 1;
return 0;
}
printk(KERN_INFO "proc called read %d\n",(int)size);
copy_to_user(buf,msg,len);
return len;
}
//Calculating functions
void add(int a, int b){
res = a + b;
}
void neg(int a, int b){
res = a - b;
}
void mul(int a, int b){
res = a * b;
}
void div(int a, int b){
if (b != 0)
res = a / b;
else res = -1;
}
//Input/output for operators
int res_open(struct file *sp_file,char __user *buf, size_t size, loff_t *offset){
int i = 0;
if (len_check)
len_check = 0;
else {
len_check = 1;
return 0;
}
printk(KERN_INFO "proc called read %d\n",size);
sprintf(msg, "%d", res);
while (msg[i]!='\0') i++;
printk(KERN_INFO "res = %d, msg=%s\n", res, msg);
copy_to_user(buf,msg, i+1);
return len;
}
int a_write(struct file *sp_file,const char __user *buf, size_t size, loff_t *offset){
printk(KERN_INFO "proc called write %d\n",size);
len = size;
copy_from_user(msg,buf,len);
sscanf(msg, "%d", &a);
return len;
}
int b_write(struct file *sp_file,const char __user *buf, size_t size, loff_t *offset){
printk(KERN_INFO "proc called write %d\n",size);
len = size;
copy_from_user(msg,buf,len);
sscanf(msg, "%d", &b);
return len;
}
int op_write(struct file *sp_file,const char __user *buf, size_t size, loff_t *offset){
printk(KERN_INFO "proc called write %d\n",size);
len = size;
copy_from_user(msg,buf,len);
switch (msg[0]){
case '+': add(a,b); break;
case '-': neg(a,b); break;
case '*': mul(a,b); break;
case '/': div(a,b); break;
}
return len;
}
//Operations for procs
struct file_operations resops = {
.owner = THIS_MODULE,
//.open = res_open,
.read = res_open
};
struct file_operations aops = {
.owner = THIS_MODULE,
.write = a_write
};
struct file_operations bops = {
.owner = THIS_MODULE,
.write = b_write
};
struct file_operations opops = {
.owner = THIS_MODULE,
.write = op_write
};
//Creating proc
int create_proc(char * name, struct file_operations * ops){
if (! proc_create(name,0666,NULL,ops)) {
remove_proc_entry(name,NULL);
return 0;
}
return 1;
}
static int __init init_simpleproc (void){
printk(KERN_INFO "init simple proc\n");
if (create_proc("a", &aops) && create_proc("b", &bops) && create_proc("res", &resops) && create_proc("op", &opops)){
return 0;
}
else {
printk(KERN_INFO "ERROR! proc_create\n");
return -1;
}
}
static void __exit exit_simpleproc(void){
remove_proc_entry("a",NULL);
remove_proc_entry("b",NULL);
remove_proc_entry("res",NULL);
remove_proc_entry("op",NULL);
printk(KERN_INFO "exit simple proc\n");
}
module_init(init_simpleproc);
module_exit(exit_simpleproc);
MODULE_AUTHOR("Denis");
MODULE_LICENSE("GPL v3");
MODULE_DESCRIPTION("A simple module to calculate");
|
e45f9a7ef3efec847f5cc24ee94894d43a509b2d
|
[
"Markdown",
"C",
"Makefile",
"Shell"
] | 9 |
C
|
m-den-i/embedded
|
28b116b7581e93a41e6dfd4c520f8a29c3322af2
|
a1741bbfe929b3cbb80d2b3f1e8eed84659982e0
|
refs/heads/master
|
<repo_name>magnusahlstroem/cpR<file_sep>/R/cpr_functions.R
#' This function checks if the cpr-number is a real cpr-number.
#'
#' @param cpr a character vector representating the cpr-numbers. must be 10 digits long and containg no '-'.
#' @return logical indicating whether the cpr-number is real or not
#' @author <NAME>
#' @details
#' A real cpr number contains numbers from 0-9 is 10 digits long and when the digits are multiplied by
#' a specific vector, the rowsum should be dividable by 11.
#' @seealso \code{cpr2BD} \code{cpr2Sex}
cpr_correct <- function(cpr) {
if(!is.character(cpr)) stop("cpr must be a character string")
if(sum(grepl("[[:digit:]]{6}-[[:digit:]]{4}", cpr), na.rm = T) > 0) stop("cpr should be without a dash ('-')")
if(sum(nchar(cpr) != 10) > 0) stop("cpr should be 10 digit long")
cdd <- suppressWarnings(as.numeric(substr(cpr,1,2)))
splitted <- t(matrix(as.numeric(do.call(rbind, strsplit(cpr, ""))), ncol = 10))
out <- colSums(splitted * c(4,3,2,7,6,5,4,3,2,1)) %% 11 == 0
as.logical((is.na(out) * F) + (!is.na(cdd) & cdd <= 31 & cdd >= 1))
}
#' This function returns a birthday based on a real cpr-number
#'
#' @param cpr a character vector representating the cpr-numbers. must be 10 digits long and containg no '-'.
#' @return a date vector of birthdates of the individuals.
#' @author <NAME>
#' @details
#' Based on the digits 1-2 day of birth is calculated, the month is calculated based on digits 3-4 and year is
#' calculated based on digits 5-7.
#' @export
#' @seealso \code{cpr_correct} \code{cpr2Sex}
cpr2BD <- function(cpr) {
kor <- cpr_correct(cpr)
if (sum(!kor) > 0) warning("Some or more cprs where invalid Danish cprs")
cdd <- suppressWarnings(as.numeric(substr(cpr, 1, 2)))
cmm <- suppressWarnings(as.numeric(substr(cpr, 3, 4)))
cyy <- suppressWarnings(as.numeric(substr(cpr, 5, 6)))
c7 <- as.numeric(substr(cpr, 7, 7))
year <-
(c7 %in% c("0", "1", "2", "3")) * 1900 +
(c7 %in% c("4") & cyy <= 36) * 2000 +
(c7 %in% c("4") & cyy > 36) * 1900 +
(c7 %in% c("5", "6", "7", "8") & cyy <= 57) * 2000 +
(c7 %in% c("5", "6", "7", "8") & cyy > 57) * 1800 +
(c7 %in% c("9") & cyy <= 36) * 2000 +
(c7 %in% c("9") & cyy > 36) * 1900 +
cyy
ds <- paste(year, cmm, cdd, sep = "-")
ds <- replace(ds, !kor, NA)
date.temp <- as.Date(ds)
date.temp <- as.numeric(date.temp) * kor + as.numeric(!kor) * c(-25567)
#date.temp <- replace(date.temp, !kor, NA)
as.Date(date.temp, origin = "1970-01-01")
}
#' This function returns sex based on a real cpr-number
#'
#' @param cpr a character vector representating the cpr-numbers. must be 10 digits long and containg no '-'.
#' @param output class of the output either 'numeric' 1 is male and 2 is female. Or factor with labels
#' 'M', 'F' or 'Invalid'
#' @return a date vector of birthdates of the individuals.
#' @author <NAME>
#' @details
#' Based on digit 10 sex is calculated, if the number is dividable by 2 output is female if not then
#' output is male.
#' @export
#' @seealso \code{cpr_correct} \code{cpr2BD}
cpr2Sex <- function(cpr, output = c("as.numeric", "factor")) {
kor <- cpr_correct(cpr)
if (sum(!kor) > 0) warning("Some or more cprs where invalid Danish cprs")
output <- match.arg(output)
L10 <- substr(cpr, 10, 10)
N10 <- ((as.numeric(L10) %% 2 == 1) * 1 + (as.numeric(L10) %% 2 == 0) * 2) * kor
out <- eval(call(output, x = N10, levels = c(0,1,2), labels = c("Invalid", "M", "F")))
out[!kor] <- NA
out
}
|
25ab5b5d2edcf967a6dba5fbe73dd3e386d031e6
|
[
"R"
] | 1 |
R
|
magnusahlstroem/cpR
|
b9a713478664dfa5a0012b7f189ef3b470ad2bb1
|
fd139f21f3c56bb1c92f3a6b81b41394b3930f3b
|
refs/heads/main
|
<file_sep>#include <FastLED.h>
#include <OneButton.h>
// This example also shows one easy way to define multiple
// animations patterns and have them automatically rotate.
//
// -<NAME>, December 2014
#if defined(FASTLED_VERSION) && (FASTLED_VERSION < 3001000)
#warning "Requires FastLED 3.1 or later; check github for latest code."
#endif
#define DATA_PIN 33
#define LED_TYPE WS2812B
#define COLOR_ORDER GRB
#define NUM_LEDS 460
#define FRAMES_PER_SECOND 120
#define MASTER_BRIGHTNESS 235 // Set the master brigtness value [should be greater then min_brightness value].
uint8_t min_brightness = 40;
CRGB leds[NUM_LEDS];
int potBriVal;
int potHueVal;
int8_t brightness;
int potBri = 34;
int potHue = 35;
int buttonPin = 32;
int8_t patternRotate = 0;
OneButton btn = OneButton(buttonPin, true, true);
void setup() {
delay(3000); // 3 second delay for recovery
pinMode(potBri, INPUT);
pinMode(potHue, INPUT);
pinMode(buttonPin, INPUT_PULLUP);
btn.attachClick(nextPattern);
btn.attachDoubleClick(doubleClick);
// tell FastLED about the LED strip configuration
FastLED.addLeds<LED_TYPE, DATA_PIN, COLOR_ORDER>(leds, NUM_LEDS).setCorrection(TypicalLEDStrip);
// set master brightness control
FastLED.setBrightness(50);
Serial.begin(9600);
}
// List of patterns to cycle through. Each is defined as a separate function below.
typedef void (*SimplePatternList[])();
SimplePatternList gPatterns = {colorPulse, pulseWithGlitter, confetti, chasingLines, juggle, weave, vegasSign, vegasSign2, lightning};
uint8_t gCurrentPatternNumber = 0; // Index number of which pattern is current
uint8_t gHue = 0; // rotating "base color" used by many of the patterns
void loop() {
/*EVERY_N_MILLISECONDS(500) {
Serial.print("Pot Brightness = ");
Serial.println(potBriVal);
Serial.print("Pot Hue = ");
Serial.println(potHueVal);
Serial.print("gCurrentPatternNumber = ");
Serial.println(gCurrentPatternNumber);
}*/
checkKnobs(); // Call function to check knob positions.
// Call the current pattern function once, updating the 'leds' array
gPatterns[gCurrentPatternNumber]();
// checks the button every loop
btn.tick();
// send the 'leds' array out to the actual LED strip
FastLED.show();
// insert a delay to keep the framerate modest
FastLED.delay(1000 / FRAMES_PER_SECOND);
// do some periodic updates
// EVERY_N_MILLISECONDS( 20 ) { gHue++; } // slowly cycle the "base color" through the rainbow
if (patternRotate == 1) {
EVERY_N_SECONDS( 10 ) {
nextPattern(); // change patterns periodically
}
}
}
void checkKnobs() {
potBriVal = analogRead(potBri); // Read potentiometer A (for brightness).
//potValA = map(potValA, 1023, 0, 0, 1023); // Reverse reading if potentiometer is wired backwards.
brightness = map(potBriVal, 0, 4096, min_brightness, MASTER_BRIGHTNESS); // map(value, fromLow, fromHigh, toLow, toHigh)
potHueVal = analogRead(potHue); // Read potentiometer B (for hue).
if (potHueVal > 4050) {
EVERY_N_MILLISECONDS( 20 ) {
gHue++;
}
} else {
gHue = map(potHueVal, 0, 4050, 0, 255);
}
FastLED.setBrightness(brightness); // Set master brightness based on potentiometer position.
}
// #define ARRAY_SIZE(A) (sizeof(A) / sizeof((A)[0]))
void doubleClick() { // this function will be called when the button was pressed 2 times in a short timeframe
patternRotate = (patternRotate + 1) % 2;
}
#define ARRAY_SIZE(A) (sizeof(A) / sizeof((A)[0]))
void nextPattern() {
gCurrentPatternNumber = (gCurrentPatternNumber + 1) % ARRAY_SIZE(gPatterns); // add one to the current pattern number, and wrap around at the end
}
void colorPulse() {
// randomly* pulsing strip with color determined by gHue/hue knob
uint8_t dim = beatsin8(30, 64, 255, 0, 0);
uint8_t dim2 = beatsin8(45, 64, 255, 0, 0);
fill_solid(leds, NUM_LEDS, CHSV(gHue, 255, ((dim + dim2) / 2)));
}
void pulseWithGlitter() {
// built-in FastLED rainbow, plus some random sparkly glitter
colorPulse();
addGlitter(127);
}
void addGlitter( fract8 chanceOfGlitter) {
if ( random8() < chanceOfGlitter) {
leds[ random16(NUM_LEDS) ] += CRGB::White;
}
}
void confetti() { // random colored speckles that blink in and fade smoothly
fadeToBlackBy(leds, NUM_LEDS, 5);
int pos = random16(NUM_LEDS);
int pos2 = random16(NUM_LEDS);
leds[pos] += CHSV( gHue + random8(51), 200, 255);
leds[pos2] += CHSV( gHue + random8(51), 200, 255);
}
void chasingLines() {
fadeToBlackBy(leds, NUM_LEDS, 30); // fades the light tails to black, higher number = faster fade and shorter "tails"
uint8_t bpm = 8; // how many times a dot goes from one end to the other
uint8_t numDots = 10; // number of dots across the strip
int j = 0; // a counter that keeps track of beat16's timebase offset
for (uint8_t i = 0; i < numDots; i++) { // a for loop to assign the number of dots (numDots) a color and starting position
uint16_t pos = map(beat16(bpm, j), 0, 65535, 0, NUM_LEDS - 1); // maps beat16's 0 through 65535 to a number between 0 and NUM_LEDS - 1
if (i % 2 == 0) { // translation --> if(i == even number) {
leds[NUM_LEDS - pos] = CHSV(gHue + 127, 220, 255); // sets a dot to a color "opposite" of gHue
}
else { // if "i" is an odd number,
(leds[pos] = CHSV(gHue, 255, 255)); // it becomes the standard gHue color
}
j += (60 / bpm * 1000 / numDots); // j is the timebase offset of beat16, timebase is linked to beats like so (60 seconds/bpm *1000) = milliseconds for one beat
} // we then divide the milliseconds of one beat by the number of dots to place dots evenly down the led strip
}
void juggle() {
// colored stripes pulsing at a defined Beats-Per-Minute (BPM)
uint8_t BeatsPerMinute = 62;
CRGBPalette16 palette = PartyColors_p;
uint8_t beat = beatsin8(BeatsPerMinute, 64, 255);
for ( int i = 0; i < NUM_LEDS; i++) { //9948
// leds[i] = CHSV(gHue, 255, beat - gHue + (i * 10));
leds[i] = ColorFromPalette(palette, gHue+(i*2), beat-gHue+(i*10));
}
}
void weave() {
// eight colored dots, weaving in and out of sync with each other
fadeToBlackBy(leds, NUM_LEDS, 20);
for ( int i = 0; i < 7 ; i++) {
leds[beatsin16( i + 5, 0, NUM_LEDS - 1 )] |= CHSV(gHue, 200, 255);
gHue += 127;
}
}
void vegasSign () {
fadeToBlackBy(leds, NUM_LEDS, 255);
uint8_t moveSpeed = 4; // how many times a pixel travels across the LED strip in a minute (higher # means faster)
uint16_t beat = map(beat16(moveSpeed, 0), 0, 65535, 0, NUM_LEDS - 1); // maps beat16's 0 through 65535 to a number between 0 and NUM_LEDS
uint16_t posStart = 0;
for (uint8_t segments = 0; segments < 10; segments++) { // this for loop assigns 30 pixels a color 10 times, to total 300
for (uint8_t pos = 0; pos < 46; pos++) { // this for loop assigns pixels 0-29 a color
//if (pos >= 0 && pos <= 1 || pos >= 6 && pos <= 9 || pos >= 20 && pos <= 23 || pos >= 28 && pos <= 29) { // and is designed with exactly 30 pixels assigned exactly
// leds[(posStart + pos + beat) % NUM_LEDS] = CRGB::Black; // 10 times across the strip of 300 pixels to fill the strip
//}
if (pos >= 6 && pos <= 11) {
leds[(posStart + pos + beat) % NUM_LEDS] = CRGB::White; // these numbers will have to be manually adjusted
} // to a factor of NUM_LEDS that equals a whole number
if (pos >= 22 && pos <= 39) {
leds[(posStart + pos + beat) % NUM_LEDS] = CHSV(gHue, 230, 255); // example: NUM_LEDS = 300, 30 is a factor of 300 b/c 300/30=10
} // that's why the for loop above this one goes 10 times
}
posStart += 46; // this moves the pixel assignments up 30 pixels so it doesn't just overwrite the first 30 pixels again
}
}
void vegasSign2() {
fadeToBlackBy(leds, NUM_LEDS, 127);
uint16_t beat = beatsin16(2, 0, NUM_LEDS - 1, 0, 0);
uint16_t posStart = 0;
if (beat <= NUM_LEDS * 0.01) {
beat = NUM_LEDS * 0.01;
}
if (beat >= NUM_LEDS * 0.99) {
beat = NUM_LEDS * 0.99;
}
for (uint8_t segments = 0; segments < 10; segments++) {
for (uint8_t pos = 0; pos < 43; pos++) {
//if (pos >= 5 && pos <= 8) { // white bars
// leds[(posStart + pos + beat) % NUM_LEDS] = CRGB::White;
//}
if (pos >= 5 && pos <= 17) { // bar 1 color
leds[(posStart + pos + beat) % NUM_LEDS] = CHSV(gHue, 255, 255);
}
if (pos >= 28 && pos <= 40) { // bar 2 color
leds[(posStart + pos + beat) % NUM_LEDS] = CHSV(gHue+127, 230, 255);
}
}
posStart += 46;
}
}
void lightning() {
// The first "flash" in a bolt of lightning is the "leader." The leader
// is usually duller and has a longer delay until the next flash. Subsequent
// flashes, the "strokes," are brighter and happen at shorter intervals.
FastLED.clear();
int ledStart = random16(NUM_LEDS); // Determine starting location of flash
int ledLength = random16(NUM_LEDS-ledStart); // Determine length of flash (not to go beyond NUM_LEDS-1)
const uint8_t frequency = 40; // controls the interval between strikes
const uint8_t flashes = 12; // the upper limit of flashes per strike
static uint8_t dimmer = 1;
static uint8_t flashCount = flashes;
static uint8_t flashCounter = 0;
static uint32_t delayMillis = 0;
static uint32_t delayStart = 0;
static bool flashing = true;
// bail, if we haven't waited long enough
if (millis() < delayMillis + delayStart) {
return;
}
flashing = !flashing;
if (flashCounter >= flashCount) { // if we've finished the current set of flashes, clear the display and wait a bit
flashCounter = 0;
//fill_solid(leds + ledStart, ledLength, CRGB::Black); // clear the display
fill_solid(leds, NUM_LEDS, CRGB::Black);
delayMillis = random8(frequency) * 130;
delayStart = millis();
return;
}
if (flashCounter == 0) {
dimmer = 5; // the brightness of the leader is scaled down by a factor of 5
}
else dimmer = random8(1, 3); // return strokes are brighter than the leader
if (flashing) {
fill_solid(leds + ledStart, ledLength, CHSV(255, 0, 255 / dimmer));
delayMillis = random8(4, 10);
delayStart = millis();
}
else {
//fill_solid(leds+ledStart, ledLength, CRGB::Black); // clear the display
fill_solid(leds, NUM_LEDS, CRGB::Black);
delayMillis = 50 + random8(100);
if (flashCount == 0) delayMillis += 150; // longer delay until next flash after the leader
}
flashCounter++;
}
|
daefc7c33acd3245e3647370a4e615c470d5f3d8
|
[
"C++"
] | 1 |
C++
|
ProperPort/ArcticKiwii-Pegboard-Lights
|
b12b921e90714c317fd56fc9c2a551e83b49e97a
|
2f11eae751023d99a4fcadee00ebc4559c2774ad
|
refs/heads/main
|
<file_sep># License: All rights reserved
(c) 2021 UvA
<file_sep>module.exports = {
stories: ['../src/**/*stories.@(js|mdx)'],
features: {
postcss: false,
},
addons: [
{
name: '@storybook/addon-docs',
options: { configureJSX: true },
},
'@storybook/addon-a11y',
'@storybook/addon-viewport',
'@storybook/addon-notes/register',
'@storybook/preset-scss',
'@etchteam/storybook-addon-status/register',
'storybook-addon-mdx-embed',
],
};
<file_sep># Design Tokens for UvA
This project uses [Style Dictionary v3+](https://amzn.github.io/style-dictionary) to define our common design language with Design Tokens.
It also uses [Storybook](https://storybook.js.org) to visualize these Design Tokens
## Getting started
To install all packages and start the developer environment:
```shell
yarn
yarn bootstrap
yarn storybook
```
This will start storybook and a watcher for the design-token package. If you change a value in the design-token package your storybook should update automatically.
<file_sep>import { Description, Meta, ColorPalette, ColorItem } from "@storybook/addon-docs/blocks";
import { MDXEmbedProvider } from "mdx-embed";
import brandColorTokens from "../../design-tokens/dist/index.json";
import { path2css } from "./util.js";
# Colors
<Meta title="UvA/Color" />
Introduction into our brand colors...
## Color Palette
<ColorPalette>
<ColorItem title="Red" colors={Object.values(brandColorTokens["uva"]["color"]["red"]).map(({ value }) => value)} />
</ColorPalette>
## Design Tokens
<ColorPalette>
{[brandColorTokens["uva"]["color"]["red"][1]].map(({ original: { name }, value, path }) => (
<ColorItem key={path.join("-")} title={name} subtitle={path2css(path)} colors={[value]} />
))}
</ColorPalette>
<file_sep>import { Description, Meta, Typeset } from "@storybook/addon-docs/blocks";
import { MDXEmbedProvider } from "mdx-embed";
import brandTypography from "../../design-tokens/src/brand/typography.json";
# Lettertypes
<Meta title="UvA/Typography" />
### Serif
Serif font family:
<code>{`${brandTypography["uva"]["typography"]["serif"]["font-family"]["value"]}`}</code>
Fallback:
<code>{`${brandTypography["uva"]["typography"]["serif-fallback"]["font-family"]["value"]}`}</code>
<Typeset
fontFamily={brandTypography["uva"]["typography"]["serif"]["font-family"]["value"]}
fontSizes={["24px"]}
sampleText="The Quick Brown Fox Jumps Over The Lazy Dog"
/>
### Sans
Sans-serif font family:
<code>{`${brandTypography["uva"]["typography"]["sans-serif"]["font-family"]["value"]}`}</code>
Fallback:
<code>{`${brandTypography["uva"]["typography"]["sans-serif-fallback"]["font-family"]["value"]}`}</code>
<Typeset
fontFamily={brandTypography["uva"]["typography"]["sans-serif"]["font-family"]["value"]}
fontSizes={["24px"]}
sampleText="The Quick Brown Fox Jumps Over The Lazy Dog"
/>
|
b86ded7e14812b97fac6ee49727f284a3116a430
|
[
"Markdown",
"JavaScript"
] | 5 |
Markdown
|
Lefthandmedia/design-tokens
|
6f631b269ba8de263213f5e80e801ee7ba0a086d
|
a006e6a7e7aa9afca562dc7e7df7d2f84966d228
|
refs/heads/master
|
<repo_name>rchliu/smag-rpg<file_sep>/src/game1/Flasher.java
package game1;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.Timer;
public class Flasher {
boolean flash = true, flashing = true;
Color buttonBlue = new Color(36, 108, 242, 128);
JButton button;
Timer buttonFlash;
public Flasher(JButton button) {
this.button = button;
}
public void start() {
if (flashing) {
buttonFlash = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent e){
if (flash) {
button.setBackground(buttonBlue);
} else {
button.setBackground(null);
}
flash = !flash;
}
});
buttonFlash.start();
}
}
public void stop() {
flashing = false;
button.setBackground(null);
//buttonFlash.stop();
}
}
<file_sep>/README.md
# Hero's Name and the Magical Plot Device
RPG where the player must oust the evil Smiff from his throne by collecting all nine Earth Gems, scattered in various dungeons around the world. Written in Java.
<p>
<img src="http://i.imgur.com/cW9C30q.png" width="250"/>
<img src="http://i.imgur.com/Qn544jz.png" width="250"/>
<img src="http://i.imgur.com/BR6uUOO.png" width="250"/>
<img src="http://i.imgur.com/Aj9TOZ1.png" width="250"/>
<img src="http://i.imgur.com/5GHSy5r.png" width="250"/>
<img src="http://i.imgur.com/3mWBVcH.png" width="250"/>
<img src="http://i.imgur.com/q2kEW0A.png" width="250"/>
</p>
<file_sep>/src/game1/Wall.java
package game1;
public class Wall extends Block {
public Wall(int x, int y, int width, int height) {
super(x, y, width, height);
img = Main.rock;
}
public void collsionCheck(RealTimeHero player) {
/* If Character's hitbox contains x-side of wall move character
* just to the x of that wall */
if (Main.right == true) {
if (player.hitbox.contains(left, top) || player.hitbox.contains(left, bot)) {
if (hitbox.getCenterX() > player.hitbox.getMaxX())
player.hitbox.x = (int) (left - player.hitbox.width - 1);
}
}
if (Main.up == true) {
if (player.hitbox.contains(left, bot) || player.hitbox.contains(right, bot)) {
if (hitbox.getCenterY() < player.hitbox.getMinY())
if (Main.left == true) {
if (!(hitbox.getCenterX() < player.hitbox.getMinX()))
player.hitbox.y = (int) (bot + 1);
} else
player.hitbox.y = (int) (bot + 1);
}
}
if (Main.down == true) {
if (player.hitbox.contains(left, top) || player.hitbox.contains(right, top)) {
if (hitbox.getCenterY() > player.hitbox.getMaxY())
player.hitbox.y = (int) (top - player.hitbox.height - 1);
}
}
if (Main.left == true) {
if (player.hitbox.contains(right, top) || player.hitbox.contains(right, bot)) {
if (hitbox.getCenterX() < player.hitbox.getMinX()) {
if (Main.up == true) {
if (!(hitbox.getCenterY() < player.hitbox.getMinY()))
player.hitbox.x = (int) (right + 1);
} else
player.hitbox.x = (int) (right + 1);
}
}
}
}
}
<file_sep>/src/game1/Enemies/Frog.java
package game1.Enemies;
import game1.Enemy;
public class Frog extends Enemy {
public Frog() {
setType("Deathfrog");
setHealth(10);
setDamage(5);
setGoldValue(30);
setMaxActionTimer(120);
setExpValue(50);
setDamageResistance(0.9);
setImage("Graphics/Characters/frog1.png");
}
}
<file_sep>/src/game1/Enemies/Ghost.java
package game1.Enemies;
import game1.Enemy;
public class Ghost extends Enemy {
public Ghost() {
setType("Ghost");
setHealth(15);
setDamage(5);
setGoldValue(30);
setMaxActionTimer(180);
setExpValue(50);
setDamageResistance(0.8);
setImage("Graphics/Characters/ghost1.png");
}
public void specialMove() {
System.out.println("I am a spoopy, spoopy, hypercharged ghost!");
}
}
<file_sep>/src/game1/Items.java
package game1;
public class Items {
String name;
int value, effectiveness, manaCost;
boolean isMagic, isWeapon, isPotion, isHelmet, isBodyArmour, isBoots = false;
boolean isWindMagic, isWaterMagic, isFireMagic, isEarthMagic = false;
public Items(int itemID){
if (itemID == 1){
name = "Health Potion";
value = 25;
effectiveness = 50;
isPotion = true;
}
else if (itemID == 2){
name = "Mana Potion";
value = 25;
effectiveness = 50;
isPotion = true;
}
else if (itemID == 3){
name = "Wooden Sword";
value = 50;
effectiveness = 5;
isWeapon = true;
}
else if (itemID == 4){
name = "Copper Sword";
value = 250;
effectiveness = 15;
isWeapon = true;
}
else if (itemID == 5){
name = "Steel Sword";
value = 1000;
effectiveness = 35;
isWeapon = true;
}
else if (itemID == 6){
name = "Leather Helmet";
value = 50;
effectiveness = 3;
isHelmet = true;
}
else if (itemID == 7){
name = "Leather Body Armour";
value = 100;
effectiveness = 5;
isBodyArmour = true;
}
else if (itemID == 8){
name = "Leather Boots";
value = 50;
effectiveness = 2;
isBoots = true;
}
else if (itemID == 9){
name = "Chain Helmet";
value = 100;
effectiveness = 5;
isHelmet = true;
}
else if (itemID == 10){
name = "Chain Body Armour";
value = 250;
effectiveness = 10;
isBodyArmour = true;
}
else if (itemID == 11){
name = "Chain Boots";
value = 100;
effectiveness = 5;
isBoots = true;
}
else if (itemID == 12){
name = "Dragon Scale Helmet";
value = 250;
effectiveness = 10;
isHelmet = true;
}
else if (itemID == 13){
name = "Dragon Scale Armour";
value = 1000;
effectiveness = 20;
isBodyArmour = true;
}
else if (itemID == 14){
name = "Dragon Scale Boots";
value = 250;
effectiveness = 10;
isBoots = true;
}
else if (itemID == 15){
name = "Pebble Pound";
value = 50;
manaCost = 1;
effectiveness = 3;
isMagic = true;
isEarthMagic = true;
}
else if (itemID == 16){
name = "Rock Roundhouse";
value = 250;
manaCost = 2;
effectiveness = 7;
isMagic = true;
isEarthMagic = true;
}
else if (itemID == 17){
name = "Boulder Bash";
value = 1000;
manaCost = 4;
effectiveness = 14;
isMagic = true;
isEarthMagic = true;
}
else if (itemID == 18){
name = "Bruising Breeze";
value = 50;
manaCost = 3;
effectiveness = 3;
isMagic = true;
isWindMagic = true;
}
else if (itemID == 19){
name = "Wind Whack";
value = 250;
manaCost = 9;
effectiveness = 9;
isMagic = true;
isWindMagic = true;
}
else if (itemID == 20){
name = "Tormenting Tempest";
value = 1000;
manaCost = 21;
effectiveness = 21;
isMagic = true;
isWindMagic = true;
}
else if (itemID == 21){
name = "<NAME>";
value = 50;
manaCost = 7;
effectiveness = 5;
isMagic = true;
isWaterMagic = true;
}
else if (itemID == 22){
name = "<NAME>";
value = 250;
manaCost = 23;
effectiveness = 15;
isMagic = true;
isWaterMagic = true;
}
else if (itemID == 23){
name = "<NAME>";
value = 1000;
manaCost = 45;
effectiveness = 30;
isMagic = true;
isWaterMagic = true;
}
else if (itemID == 24){
name = "<NAME>";
value = 50;
manaCost = 4;
effectiveness = 8;
isMagic = true;
isFireMagic = true;
}
else if (itemID == 25){
name = "<NAME>";
value = 250;
manaCost = 10;
effectiveness = 20;
isMagic = true;
isFireMagic = true;
}
else if (itemID == 26){
name = "<NAME>";
value = 1000;
manaCost = 25;
effectiveness = 50;
isMagic = true;
isFireMagic = true;
}
}
}
<file_sep>/src/game1/Door.java
package game1;
public class Door extends Block {
int access;
public Door(int x, int y, int width, int height, int direction) {
super(x, y, width, height);
access = direction;
}
public void collsionCheck(RealTimeHero player) {
if (Main.right == true) {
if (access == 1) {
if (player.hitbox.contains(left, top) || player.hitbox.contains(left, bot)) {
player.hitbox.x = Main.screenWidth - hitbox.x + 30;
Main.roomX++;
Main.pickRoom(1);
}
}
}
if (Main.up == true) {
if (access == 3) {
if (player.hitbox.contains(left, bot) || player.hitbox.contains(right, bot)) {
player.hitbox.y = (int) (Main.screenHeight - hitbox.getMinY() - player.hitbox.height - 30);
Main.roomY--;
Main.pickRoom(3);
}
}
}
if (Main.down == true) {
if (access == 4) {
if (player.hitbox.contains(left, top) || player.hitbox.contains(right, top)) {
player.hitbox.y = Main.screenHeight - hitbox.y + 30;
Main.roomY++;
Main.pickRoom(4);
}
}
}
if (Main.left == true) {
if (access == 2) {
if (player.hitbox.contains(right, top) || player.hitbox.contains(right, bot)) {
player.hitbox.x = (int) (Main.screenWidth - hitbox.getMaxX() - player.hitbox.width - 30);
Main.roomX--;
Main.pickRoom(2);
}
}
}
}
}<file_sep>/src/game1/RealTimeHero.java
package game1;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class RealTimeHero{
int speed;
Rectangle hitbox;
//Image img;
BufferedImage image;
public RealTimeHero(int x, int y) {
speed = 8;
hitbox = new Rectangle();
hitbox.x = x;
hitbox.y = y;
hitbox.width = 73;
hitbox.height = 73;
try {
this.image = ImageIO.read(new File("Graphics/Characters/hero1.png"));
} catch (IOException e) {
}
//img = Main.heroImg;
}
public void moveR() {
hitbox.x += speed;
if (hitbox.x > Main.screenWidth - hitbox.width)
hitbox.x = Main.screenWidth - hitbox.width;
}
public void moveL() {
hitbox.x -= speed;
if (hitbox.x < 0)
hitbox.x = 0;
}
public void moveU() {
hitbox.y -= speed;
if (hitbox.y < 0)
hitbox.y = 0;
}
public void moveD() {
hitbox.y += speed;
if (hitbox.y > Main.screenHeight - hitbox.height)
hitbox.y = Main.screenHeight - hitbox.height;
}
public void paint(Graphics g) {
g.drawImage(image, hitbox.x, hitbox.y, hitbox.width, hitbox.height, null);
}
}<file_sep>/src/game1/TurnBasedHero.java
package game1;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class TurnBasedHero {
int health, mana, strength, endurance, intelligence, agility, damage;
int maxHealth, maxMana;
final int maxActionTimer;
double actionTimer = 0.0;
double damageResistance;
Color actionBarColor;
Color actionBarLoadingColor = new Color(174, 250, 132);
Image image = null;
public TurnBasedHero(int health, int mana, int strength, int endurance,
int intelligence, int agility) {
this.health = 10 * endurance;
this.maxHealth = 10 * endurance;
this.mana = 10 * intelligence;
this.maxMana = 10 * intelligence;
this.strength = strength;
this.intelligence = intelligence;
this.agility = agility;
this.maxActionTimer = 150;
try {
image = ImageIO.read(new File("Graphics/Characters/hero1.png"));
} catch (IOException e) {
}
}
public void setDamage(Items weapon) {
if (weapon != null) {
this.damage = strength + weapon.effectiveness / 2;
} else {
this.damage = strength;
}
}
public void setDamageResistance(Items[] armour) {
int totalArmourEffectiveness = 0;
for (Items armourPiece : armour) {
if (armourPiece != null) {
totalArmourEffectiveness += armourPiece.effectiveness;
}
}
this.damageResistance = 1 - (5*endurance + totalArmourEffectiveness) / 100.0;
}
public void showBars(Graphics g) {
ResourceBar heroHealthBar = new ResourceBar(health, maxHealth,
Color.RED, 100, 280);
ResourceBar heroManaBar = new ResourceBar(mana, maxMana, Color.BLUE,
100, 300);
ResourceBar heroActionBar = new ResourceBar((int) actionTimer,
maxActionTimer, actionBarColor, 100, 320);
heroHealthBar.draw(g);
heroManaBar.draw(g);
heroActionBar.draw(g);
}
public void basicAttack(Enemy enemy) {
enemy.health -= damage * enemy.damageResistance;
enemy.actionTimer -= 3*strength;
actionTimer -= 60;
}
public void sweepingAttack(Enemy[] enemies) {
for (Enemy enemy : enemies) {
if (enemy != null) {
enemy.health -= 0.8 * damage * enemy.damageResistance;
}
}
actionTimer -= 120;
}
public void staggeringAttack(Enemy enemy) {
enemy.health -= 1.2*damage*enemy.damageResistance;
if (enemy.actionTimer > 8 * strength) {
enemy.actionTimer -= 8*strength;
} else if (enemy.actionTimer - 8*strength <= 0) {
enemy.actionTimer = 0;
}
actionTimer -= 100;
}
public void castSpell(Enemy enemy, Items spell) {
enemy.health -= 0.2 * intelligence * spell.effectiveness;
mana -= spell.manaCost;
}
public void castMultiTargetSpell(Enemy[] enemies, Items spell) {
for (Enemy enemy : enemies) {
if (enemy != null) {
enemy.health -= 0.2 * intelligence * spell.effectiveness;
}
}
mana -= spell.manaCost;
}
public void setHealthAndMana(int endurance, int intelligence) {
this.maxMana = 10 * intelligence;
this.mana = maxMana;
this.maxHealth = 10 * endurance;
this.health = maxHealth;
}
}
<file_sep>/src/game1/Enemies/Alien.java
package game1.Enemies;
import game1.Enemy;
public class Alien extends Enemy {
public Alien() {
setType("Alien");
setHealth(10);
setDamage(5);
setGoldValue(30);
setMaxActionTimer(100);
setExpValue(50);
setDamageResistance(0.8);
setImage("Graphics/Characters/alien1.png");
}
}
|
03bd67ed60269868fbf50151e6419699b30489b7
|
[
"Markdown",
"Java"
] | 10 |
Java
|
rchliu/smag-rpg
|
381f75390d17d1774944bd75329d7f1234ac291c
|
0bc233ff77cf3b0e5732537aefbe0fcefa104846
|
refs/heads/master
|
<file_sep># WebScraping_Games Request
Este projeto foi construído baseado em uma das funções de trabalho de um amigo,
vale ressaltar que o projeto está adaptado a ambiente totalmente fictício, e não será utilizado comercialmente.
## Tarefa:
O funcionário de uma loja de venda de games deve contar a quantidade de produtos no estoque e criar uma planilha com os seguintes dados:
- Distribuidora
- Jogo
- Plataforma
- Quantidade no estoque
- Imagem do Produto (pesquisa no google)
## Aplicativo:
Esse Aplicativo tem o objetivo de pesquisar as imagens dos games no google e criar nossa planilha formatada.
<br />
site para pesquisar os games: https://www.grouvee.com/
Primeiro o usuário deve cadastrar todos os games

Depois basta clicar em 'Pesquisar' para iniciar o processo de pesquisa e gerar a planilha.

## Atualização
Essa é a segunda versão do aplicativo. <br />
modificações:
- troca do selenium para o request (ganho de performance)
- troca da interface (interface mais agradável para o usuário)
- o uso de Threads para evitar o travamento da interface.
<file_sep>from tkinter import *
from tkinter import ttk
from tkinter import filedialog
from tkinter import messagebox
import tkinter
import pandas as pd
import Web_Scraping
class Tela:
def __init__(self, janela):
#Configurando Janela
janela.geometry("650x400+100+100")
janela['bg'] = '#25222f'
janela.title("tela principal")
# Texto de erro
self.text = StringVar()
self.text.set('* Inválido')
# Label erro marca
self.lbErroM = Label(janela, textvariable=self.text, background='#25222f',foreground='#ff0000')
self.lbErroM.place(x=50, y=30)
self.lbErroM.place_forget()
# textbox marca
self.tbMarc = Entry(janela, width=15)
self.tbMarc.place(x=50, y=50)
self.tbMarc.insert(0, 'Distribuidora')
self.tbMarc.bind("<Button-1>", lambda event: self.clear_entry(self.tbMarc))
self.lbErroI = Label(janela, textvariable=self.text, background='#25222f',foreground='#ff0000')
self.lbErroI.place(x=180, y=30)
self.lbErroI.place_forget()
# textbox Item
self.tbItem = Entry(janela, width=15)
self.tbItem.place(x=180, y=50)
self.tbItem.insert(0, 'Jogo')
self.tbItem.bind("<Button-1>", lambda event: self.clear_entry(self.tbItem))
# label error Plataforma
self.lbErroP = Label(janela, textvariable=self.text, background='#25222f',foreground='#ff0000')
self.lbErroP.place(x=310, y=30)
self.lbErroP.place_forget()
# textbox Plataforma
self.tbPlat = Entry(janela, width=13)
self.tbPlat.place(x=310, y=50)
self.tbPlat.insert(0, 'Plataforma')
self.tbPlat.bind("<Button-1>", lambda event: self.clear_entry(self.tbPlat))
#label erro quantidade
self.lbErroQ = Label(janela, textvariable=self.text, background='#25222f',foreground='#ff0000')
self.lbErroQ.place(x=430, y=30)
self.lbErroQ.place_forget()
# Spinbox qtd
self.tbQtd = Spinbox(janela, width=5, from_=0, to=100)
self.tbQtd.place(x=430, y=50)
# Botão para Inserir dado no treeview
self.btnInsert = Button(janela, width=2, height=1, text="+", command= lambda:[self.btnInsert_click(self.tbMarc.get(), self.tbItem.get(), self.tbPlat.get(), self.tbQtd.get())])
self.btnInsert.place (x=505, y=50)
self.btnInsert['bg'] = '#5f5dff'
# Botão para Excluir dado no treeview
self.btnDel = Button(janela, width=2, height=1, text="-", command= lambda:[self.btnDel_click()])
self.btnDel .place (x=555, y=50)
self.btnDel ['bg'] = '#ff5d5b'
# Criar treeview
self.columns = ('#1', '#2', '#3', '#4')
self.tree = ttk.Treeview(janela, columns=self.columns, show='headings')
self.tree.column('#1',width=150)
self.tree.column('#2',width=150)
self.tree.column('#3',width=150)
self.tree.column('#4',width=100)
# define headings(colunas)
self.tree.heading('#1', text='Marca')
self.tree.heading('#2', text='Item')
self.tree.heading('#3', text='Plataforma')
self.tree.heading('#4', text='QTD')
self.tree.place(x=50, y=100)
# Botão Confirmar para realizar o web scraping
self.btnConf = Button(janela, width=15, text="Confirmar",
command= lambda:[self.btnConf_click()])
self.btnConf.place (x=455, y=340)
self.btnConf['bg'] = '#00ff14'
# limpa os textbox
def clear_entry(self,tb):
tb.delete(0, END)
# Validar dados
def Validar(self, Marc, Item, Plat, QTD):
self.lbErroM.place_forget()
self.lbErroI.place_forget()
self.lbErroP.place_forget()
self.lbErroQ.place_forget()
erro = False
try:
Marc = str(Marc)
if(Marc=='Distribuidora' or Marc==''):
erro = True
self.lbErroM.place(x=50, y=30)
except:
erro = True
self.lbErroM.place(x=50, y=30)
try:
Item = str(Item)
if(Item=='Jogo' or Item==''):
erro = True
self.lbErroI.place(x=180, y=30)
except:
erro = True
self.lbErroI.place(x=180, y=30)
try:
Plat = str(Plat)
if(Plat=='Plataforma' or Plat==''):
erro = True
self.lbErroP.place(x=310, y=30)
except:
erro = True
self.lbErroP.place(x=310, y=30)
try:
QTD = int(QTD)
if(QTD==''):
self.lbErroQ.place(x=430, y=30)
erro = True
except:
self.lbErroQ.place(x=430, y=30)
erro = True
if erro==False:
dados = [Marc, Item, Plat, QTD]
else:
dados = 'erro'
return dados
# Inserir no treeView
def btnInsert_click(self, Marc, Item, Plat, QTD):
dados = self.Validar(Marc, Item, Plat, QTD)
if(dados!='erro'):
self.tree.insert('', tkinter.END, values=dados)
# Excluir dados do treeview
def btnDel_click(self):
try:
selected_item = self.tree.selection()[0]
self.tree.delete(selected_item)
except:
pass
# Chamar função de web scraping
def btnConf_click(self):
lista = []
for dado in self.tree.get_children():
lista.append(self.tree.item(dado)['values'])
colunas = ['Marca', 'Item', 'Plataforma', 'QTD']
df = pd.DataFrame(data= lista, columns=colunas)
Web_Scraping.Buscar_game(df)
# criar janela
janela = Tk()
#passar janela para a tela
Tela(janela)
#manter janela aberta
janela.mainloop()
<file_sep># -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'Main.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5.QtCore import QObject, QThread, pyqtSignal
from PyQt5 import QtCore, QtGui, QtWidgets, Qt
from typing import List, Dict, Optional
import pandas as pd
import time
import Web_Scraping
# Classe para executar a tarefa em uma thread
# impede o travamento da interface
# Executa a função de web scraping em paralelo a interface
class Tarefa(QObject):
# Sinal progress bar
bar = pyqtSignal(int)
# sinal da função de web scraping
status = pyqtSignal()
# Sinal de finalização
finished = pyqtSignal()
# Construtor com os dados
def __init__(self, df):
super().__init__()
self.data = df
# Barra de progresso
def progress_bar(self):
for i in range(101):
time.sleep(0.03)
self.bar.emit(i)
self.finished.emit()
# função Web Scraping
def run(self):
Web_Scraping.Buscar_game(self.data)
self.status.emit()
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(750, 600)
MainWindow.setMinimumSize(QtCore.QSize(750, 600))
MainWindow.setCursor(QtGui.QCursor(QtCore.Qt.ArrowCursor))
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap("icones/excel.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
MainWindow.setWindowIcon(icon)
MainWindow.setStyleSheet("color: rgb(255, 255, 255);")
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.verticalLayout = QtWidgets.QVBoxLayout(self.centralwidget)
self.verticalLayout.setContentsMargins(0, 0, 0, 0)
self.verticalLayout.setSpacing(0)
self.verticalLayout.setObjectName("verticalLayout")
self.frame_top = QtWidgets.QFrame(self.centralwidget)
self.frame_top.setMinimumSize(QtCore.QSize(0, 30))
self.frame_top.setMaximumSize(QtCore.QSize(16777215, 50))
self.frame_top.setStyleSheet("background-color: rgb(3, 0, 33);")
self.frame_top.setFrameShape(QtWidgets.QFrame.NoFrame)
self.frame_top.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame_top.setObjectName("frame_top")
self.hboxlayout = QtWidgets.QHBoxLayout(self.frame_top)
self.hboxlayout.setContentsMargins(0, 0, 0, 0)
self.hboxlayout.setSpacing(0)
self.hboxlayout.setObjectName("hboxlayout")
self.frame_error = QtWidgets.QFrame(self.frame_top)
self.frame_error.setMaximumSize(QtCore.QSize(450, 30))
self.frame_error.setStyleSheet("background-color: rgb(253, 118, 118);\n"
"border-radius:10px;")
self.frame_error.setFrameShape(QtWidgets.QFrame.NoFrame)
self.frame_error.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame_error.setObjectName("frame_error")
self.horizontalLayout = QtWidgets.QHBoxLayout(self.frame_error)
self.horizontalLayout.setContentsMargins(5, 5, 5, 5)
self.horizontalLayout.setObjectName("horizontalLayout")
self.label_error = QtWidgets.QLabel(self.frame_error)
font = QtGui.QFont()
font.setFamily("DejaVu")
font.setBold(True)
font.setWeight(75)
self.label_error.setFont(font)
self.label_error.setStyleSheet("color: rgb(0, 0, 0);")
self.label_error.setAlignment(QtCore.Qt.AlignCenter)
self.label_error.setObjectName("label_error")
self.horizontalLayout.addWidget(self.label_error)
self.pushButton_Error = QtWidgets.QPushButton(self.frame_error)
self.pushButton_Error.setMaximumSize(QtCore.QSize(30, 30))
self.pushButton_Error.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
self.pushButton_Error.setStyleSheet("QPushButton#pushButton_Error\n"
"{\n"
"color: rgb(0,0,0);\n"
" border-radius:5px;\n"
" background-color: rgb(253, 118, 118);\n"
"}\n"
"QPushButton:hover#pushButton_Error\n"
"{\n"
" color: rgb(255, 255, 255);\n"
" background-color: rgb(3, 0, 33);\n"
"}")
self.pushButton_Error.setObjectName("pushButton_Error")
self.horizontalLayout.addWidget(self.pushButton_Error)
self.hboxlayout.addWidget(self.frame_error)
self.verticalLayout.addWidget(self.frame_top)
self.frame_Info = QtWidgets.QFrame(self.centralwidget)
self.frame_Info.setMaximumSize(QtCore.QSize(16777215, 80))
self.frame_Info.setStyleSheet("background-color: rgb(3, 0, 33);")
self.frame_Info.setFrameShape(QtWidgets.QFrame.NoFrame)
self.frame_Info.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame_Info.setObjectName("frame_Info")
self.horizontalLayout_2 = QtWidgets.QHBoxLayout(self.frame_Info)
self.horizontalLayout_2.setObjectName("horizontalLayout_2")
self.frame_2 = QtWidgets.QFrame(self.frame_Info)
self.frame_2.setMaximumSize(QtCore.QSize(650, 16777215))
self.frame_2.setStyleSheet("background-color: rgb(3, 0, 33);")
self.frame_2.setFrameShape(QtWidgets.QFrame.NoFrame)
self.frame_2.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame_2.setObjectName("frame_2")
self.horizontalLayout_3 = QtWidgets.QHBoxLayout(self.frame_2)
self.horizontalLayout_3.setObjectName("horizontalLayout_3")
self.lineEdit_Marc = QtWidgets.QLineEdit(self.frame_2)
font = QtGui.QFont()
font.setFamily("DejaVu")
self.lineEdit_Marc.setFont(font)
self.lineEdit_Marc.setStyleSheet("background-color: rgb(255, 255, 255);\n"
"color: rgb(0, 0, 0);")
self.lineEdit_Marc.setObjectName("lineEdit_Marc")
self.horizontalLayout_3.addWidget(self.lineEdit_Marc)
self.lineEdit_Jogo = QtWidgets.QLineEdit(self.frame_2)
font = QtGui.QFont()
font.setFamily("DejaVu")
self.lineEdit_Jogo.setFont(font)
self.lineEdit_Jogo.setStyleSheet("background-color: rgb(255, 255, 255);\n"
"color: rgb(0, 0, 0);")
self.lineEdit_Jogo.setObjectName("lineEdit_Jogo")
self.horizontalLayout_3.addWidget(self.lineEdit_Jogo)
self.lineEdit_Plat = QtWidgets.QLineEdit(self.frame_2)
font = QtGui.QFont()
font.setFamily("DejaVu")
self.lineEdit_Plat.setFont(font)
self.lineEdit_Plat.setStyleSheet("background-color: rgb(255, 255, 255);\n"
"color: rgb(0, 0, 0);")
self.lineEdit_Plat.setObjectName("lineEdit_Plat")
self.horizontalLayout_3.addWidget(self.lineEdit_Plat)
self.spinBox_QTD = QtWidgets.QSpinBox(self.frame_2)
font = QtGui.QFont()
font.setFamily("DejaVu")
self.spinBox_QTD.setFont(font)
self.spinBox_QTD.setStyleSheet("background-color: rgb(255, 255, 255);\n"
"color: rgb(0, 0, 0);")
self.spinBox_QTD.setObjectName("spinBox_QTD")
self.horizontalLayout_3.addWidget(self.spinBox_QTD)
self.horizontalLayout_2.addWidget(self.frame_2)
self.verticalLayout.addWidget(self.frame_Info)
self.frame_botao = QtWidgets.QFrame(self.centralwidget)
self.frame_botao.setMaximumSize(QtCore.QSize(16777215, 60))
self.frame_botao.setStyleSheet("background-color: rgb(3, 0, 33);")
self.frame_botao.setFrameShape(QtWidgets.QFrame.NoFrame)
self.frame_botao.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame_botao.setObjectName("frame_botao")
self.horizontalLayout_4 = QtWidgets.QHBoxLayout(self.frame_botao)
self.horizontalLayout_4.setContentsMargins(0, 0, 0, 0)
self.horizontalLayout_4.setSpacing(0)
self.horizontalLayout_4.setObjectName("horizontalLayout_4")
self.frame_3 = QtWidgets.QFrame(self.frame_botao)
self.frame_3.setMinimumSize(QtCore.QSize(0, 50))
self.frame_3.setMaximumSize(QtCore.QSize(200, 50))
self.frame_3.setStyleSheet("background-color: rgb(3, 0, 33);")
self.frame_3.setFrameShape(QtWidgets.QFrame.NoFrame)
self.frame_3.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame_3.setObjectName("frame_3")
self.horizontalLayout_5 = QtWidgets.QHBoxLayout(self.frame_3)
self.horizontalLayout_5.setObjectName("horizontalLayout_5")
self.pushButton_Add = QtWidgets.QPushButton(self.frame_3)
self.pushButton_Add.setMinimumSize(QtCore.QSize(60, 30))
self.pushButton_Add.setMaximumSize(QtCore.QSize(60, 30))
font = QtGui.QFont()
font.setFamily("DejaVu")
font.setBold(True)
font.setWeight(75)
self.pushButton_Add.setFont(font)
self.pushButton_Add.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
self.pushButton_Add.setStyleSheet("QPushButton#pushButton_Add\n"
"{\n"
" \n"
" color: rgb(0, 0, 0);\n"
" background-color: rgb(150,255,150);\n"
" border-radius:10px;\n"
"}\n"
"QPushButton:hover#pushButton_Add\n"
"{\n"
" background-color: rgb(40, 140, 30);\n"
"}")
self.pushButton_Add.setObjectName("pushButton_Add")
self.horizontalLayout_5.addWidget(self.pushButton_Add)
self.pushButton_Del = QtWidgets.QPushButton(self.frame_3)
self.pushButton_Del.setMinimumSize(QtCore.QSize(60, 30))
self.pushButton_Del.setMaximumSize(QtCore.QSize(60, 30))
font = QtGui.QFont()
font.setFamily("DejaVu")
font.setBold(True)
font.setWeight(75)
self.pushButton_Del.setFont(font)
self.pushButton_Del.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
self.pushButton_Del.setStyleSheet("QPushButton#pushButton_Del\n"
"{\n"
" color: rgb(0, 0, 0);\n"
" background-color: rgb(255,150,150);\n"
" border-radius:10px;\n"
"}\n"
"QPushButton:hover#pushButton_Del\n"
"{\n"
" background-color: rgb(140, 40, 30);\n"
"}")
self.pushButton_Del.setObjectName("pushButton_Del")
self.horizontalLayout_5.addWidget(self.pushButton_Del)
self.horizontalLayout_4.addWidget(self.frame_3)
self.verticalLayout.addWidget(self.frame_botao)
self.frame_view = QtWidgets.QFrame(self.centralwidget)
self.frame_view.setStyleSheet("background-color: rgb(3, 0, 33);")
self.frame_view.setFrameShape(QtWidgets.QFrame.NoFrame)
self.frame_view.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame_view.setObjectName("frame_view")
self.horizontalLayout_6 = QtWidgets.QHBoxLayout(self.frame_view)
self.horizontalLayout_6.setContentsMargins(50, 9, 50, -1)
self.horizontalLayout_6.setObjectName("horizontalLayout_6")
# Table View
self.tableView = QtWidgets.QTableWidget(self.frame_view)
self.tableView.setMinimumSize(QtCore.QSize(200, 200))
self.tableView.setStyleSheet("background-color: rgb(255, 255, 255);\n"
"color: rgb(0, 0, 0);")
self.tableView.setObjectName("tableView")
self.tableView.setColumnCount(4)
self.tableView.setRowCount(0)
self.tableView.setColumnWidth(0,200)
self.tableView.setColumnWidth(1,280)
self.tableView.setColumnWidth(2,100)
self.tableView.setColumnWidth(3,50)
self.tableView.setHorizontalHeaderLabels(('Distribuidora', 'Jogo', 'Plataforma', 'QTD'))
header = self.tableView.horizontalHeader()
header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
header.setSectionResizeMode(0, QtWidgets.QHeaderView.Stretch)
header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
self.horizontalLayout_6.addWidget(self.tableView)
self.verticalLayout.addWidget(self.frame_view)
self.frame_Pesq = QtWidgets.QFrame(self.centralwidget)
self.frame_Pesq.setMinimumSize(QtCore.QSize(0, 50))
self.frame_Pesq.setMaximumSize(QtCore.QSize(16777215, 50))
self.frame_Pesq.setStyleSheet("background-color: rgb(3, 0, 33);")
self.frame_Pesq.setFrameShape(QtWidgets.QFrame.NoFrame)
self.frame_Pesq.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame_Pesq.setObjectName("frame_Pesq")
self.horizontalLayout_7 = QtWidgets.QHBoxLayout(self.frame_Pesq)
self.horizontalLayout_7.setContentsMargins(-1, 5, -1, 5)
self.horizontalLayout_7.setObjectName("horizontalLayout_7")
self.progressBar = QtWidgets.QProgressBar(self.frame_Pesq)
self.progressBar.setMaximumSize(QtCore.QSize(450, 25))
self.progressBar.setStyleSheet("QProgressBar {\n"
" background-color: rgb(255, 255, 255);\n"
" color: rgb(0, 0, 0);\n"
"}\n"
"QProgressBar::chunk {\n"
" \n"
" background-color: rgb(0, 255, 0);\n"
" \n"
" }")
self.progressBar.setProperty("value", 0)
self.progressBar.setAlignment(QtCore.Qt.AlignCenter)
self.progressBar.setObjectName("progressBar")
self.horizontalLayout_7.addWidget(self.progressBar)
self.pushButton_Pes = QtWidgets.QPushButton(self.frame_Pesq)
self.pushButton_Pes.setMinimumSize(QtCore.QSize(150, 40))
self.pushButton_Pes.setMaximumSize(QtCore.QSize(100, 16777215))
font = QtGui.QFont()
font.setFamily("DejaVu")
font.setBold(True)
font.setWeight(75)
self.pushButton_Pes.setFont(font)
self.pushButton_Pes.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
self.pushButton_Pes.setStyleSheet("QPushButton#pushButton_Pes\n"
"{\n"
" \n"
" color: rgb(0, 0, 0);\n"
" background-color: rgb(150,150,255);\n"
" border-radius:10px;\n"
"}\n"
"QPushButton:hover#pushButton_Pes\n"
"{\n"
" background-color: rgb(30,40, 140);\n"
"}")
self.pushButton_Pes.setObjectName("pushButton_Pes")
self.horizontalLayout_7.addWidget(self.pushButton_Pes)
self.verticalLayout.addWidget(self.frame_Pesq)
self.frame_Bottom = QtWidgets.QFrame(self.centralwidget)
self.frame_Bottom.setMinimumSize(QtCore.QSize(0, 30))
self.frame_Bottom.setStyleSheet("background-color: rgb(3, 0, 33);")
self.frame_Bottom.setFrameShape(QtWidgets.QFrame.NoFrame)
self.frame_Bottom.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame_Bottom.setObjectName("frame_Bottom")
self.horizontalLayout_8 = QtWidgets.QHBoxLayout(self.frame_Bottom)
self.horizontalLayout_8.setObjectName("horizontalLayout_8")
self.label = QtWidgets.QLabel(self.frame_Bottom)
self.label.setMinimumSize(QtCore.QSize(200, 0))
font = QtGui.QFont()
font.setFamily("DejaVu")
self.label.setFont(font)
self.label.setLayoutDirection(QtCore.Qt.RightToLeft)
self.label.setStyleSheet("color: rgb(67, 67, 67);")
self.label.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.label.setObjectName("label")
self.horizontalLayout_8.addWidget(self.label)
self.verticalLayout.addWidget(self.frame_Bottom)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 750, 20))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
# Click Botões
# Ocultar POPUP
self.frame_error.hide()
# Ocultar Barra de Progesso
self.progressBar.hide()
# Fechar POPUP
self.pushButton_Error.clicked.connect(lambda: self.frame_error.hide())
# Click do botão adicionar
self.pushButton_Add.clicked.connect(self.validar)
#Click do botão excluir
self.pushButton_Del.clicked.connect(self.del_table)
#Click do botão Pesquisar
self.pushButton_Pes.clicked.connect(self.get_value)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
#Funções
# Validar Campos
def validar(self):
marca = None
jogo = None
Plat = None
qtd = None
qtd = int(self.spinBox_QTD.value())
if (self.lineEdit_Marc.text() != '' and self.lineEdit_Marc.text() != None):
marca = str(self.lineEdit_Marc.text())
if (self.lineEdit_Jogo.text() != '' and self.lineEdit_Jogo.text() != None):
jogo = str(self.lineEdit_Jogo.text())
if (self.lineEdit_Plat.text() != '' and self.lineEdit_Plat.text() != None):
Plat = str(self.lineEdit_Plat.text())
if(marca==None or jogo ==None or Plat==None or qtd==None):
self.label_error.setText('Erro valor inválido')
self.frame_error.show()
else:
self.add_table(marca, jogo, Plat, qtd)
# Adicionar dados a tabela
def add_table(self, Marca: str, Jogo: str, Plat:str, QTD:int):
rowCount = self.tableView.rowCount()
self.tableView.insertRow(rowCount)
self.tableView.setItem(rowCount, 0, QtWidgets.QTableWidgetItem(str(Marca)))
self.tableView.setItem(rowCount, 1, QtWidgets.QTableWidgetItem(str(Jogo)))
self.tableView.setItem(rowCount, 2, QtWidgets.QTableWidgetItem(str(Plat)))
self.tableView.setItem(rowCount, 3, QtWidgets.QTableWidgetItem(str(QTD)))
# Deletar dados da tabela
def del_table(self):
try:
indices = self.tableView.selectionModel().selectedRows()
for index in indices:
self.tableView.removeRow(index.row())
except:
pass
# obter valores da tabela
def get_value(self):
lista = [[]]
lista.clear()
headers = [self.tableView.horizontalHeaderItem(c).text()
for c in range(self.tableView.columnCount())]
lista = [[self.tableView.item(row, col).text()
for col in range(self.tableView.columnCount())]
for row in range(self.tableView.rowCount())]
if(lista):
self.pushButton_Pes.hide()
self.progressBar.show()
data = pd.DataFrame(data= lista, columns=headers)
time.sleep(0.05)
self.load_bar(data)
# função que executa as tarefas em uma thread e carrega a progressbar
def load_bar(self, data):
self.thread = QThread()
self.task = Tarefa(df=data)
# Sinais da Thread
self.task.moveToThread(self.thread)
self.thread.started.connect(self.task.run)
self.task.status.connect(self.task.progress_bar)
self.task.bar.connect(self.set_bar)
self.task.finished.connect(self.thread.quit)
self.task.finished.connect(self.task.deleteLater)
self.thread.finished.connect(self.thread.deleteLater)
self.thread.start()
self.pushButton_Pes.setEnabled(False)
self.thread.finished.connect(lambda: [
self.pushButton_Pes.setEnabled(True), self.pushButton_Pes.show(),
self.progressBar.hide(), self.progressBar.setValue(0)])
def set_bar(self, progresso : int):
self.progressBar.setValue(progresso)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "Planilha_Estoque"))
self.label_error.setText(_translate("MainWindow", "Erro Dados Inválidos"))
self.pushButton_Error.setText(_translate("MainWindow", "X"))
self.lineEdit_Marc.setPlaceholderText(_translate("MainWindow", "Distribuidora"))
self.lineEdit_Jogo.setPlaceholderText(_translate("MainWindow", "Jogo"))
self.lineEdit_Plat.setPlaceholderText(_translate("MainWindow", "Plataforma"))
self.pushButton_Add.setText(_translate("MainWindow", "+"))
self.pushButton_Del.setText(_translate("MainWindow", "-"))
self.pushButton_Pes.setText(_translate("MainWindow", "Pesquisar"))
self.label.setText(_translate("MainWindow", "Desenvolvido por Alisson_Tech"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
<file_sep>from genericpath import isdir
from pandas.core.indexes.base import Index
import time
import pandas as pd
import urllib
import os
import shutil
import requests
from bs4 import BeautifulSoup
# Buscar games
def Buscar_game(df):
#Criar pasta temporaria para armazenar imagens
criar_pasta()
# obter lista de game
game = df['Jogo'].to_list()
for g in game:
try:
# Parametros de Pesuisa
pesquisa = {'q': g}
# Requisição da pagina
page = requests.get("https://www.grouvee.com/search/", params=pesquisa)
time.sleep(2)
# Transformar em objeto BeautifulSoup
soup_page = BeautifulSoup(page.text, 'html.parser')
# Procurar Div da Img
div = soup_page.find(class_='box-art')
# Procurar tag da Img
img = div.find('a').find('img')
# Obter Link da Img
link_img = img.get('src')
# Salvar imagem
urllib.request.urlretrieve(link_img, 'img/{}.jpg'.format(g))
except:
pass
Planilha(df)
# Criar Planilha
def Planilha(df):
df['Capa'] = None
# Converter dataframe em excel
writer = pd.ExcelWriter('Estoque_Games.xlsx', engine='xlsxwriter')
# definir sheet
df.to_excel(writer, sheet_name='Sheet1')
workbook = writer.book
worksheet = writer.sheets['Sheet1']
# Formato das células
data_format = workbook.add_format({'align':'center', 'valign':'vcenter'})
# Tamanho das células
worksheet.set_default_row(150)
worksheet.set_row(0, 20)
worksheet.set_column('A:D', 20, data_format)
worksheet.set_column('E:E', 10, data_format)
worksheet.set_column('F:F', 25, data_format)
game = df['Jogo'].to_list()
count = 1
# Colocar imagem na planilha se ela existir
# Se não existir colocar '?'
for g in game:
count+=1
imgPath = f'img/{g}.jpg'
if(os.path.isfile(imgPath)):
# Inserir imagens e centralizar
worksheet.insert_image('F{}'.format(count), imgPath,
{'x_offset': 20, 'y_offset': 20})
else:
worksheet.write(f'F{count}', '?')
# Fechar pandas e gerar planilha
writer.save()
# Apagar pasta temporaria
apagar_pasta()
#apagar pasta com imagens
def apagar_pasta():
dir = 'img'
if(os.path.isdir(dir)):
shutil.rmtree(dir)
# Criar pasta para salvar as imagens
def criar_pasta():
dir = 'img'
if(not os.path.isdir(dir)):
os.makedirs(dir)
|
41469b1a40cb73c89a40e4bae0ed3f04b7b80ee6
|
[
"Markdown",
"Python"
] | 4 |
Markdown
|
Alisson-tech/WebScraping_Games
|
ad2d88575282830c830c17429da3e84592409138
|
8d0fbe09423abf36ba106cbe5117ed3d0c548838
|
refs/heads/master
|
<file_sep># spring-boot-with-rabbitMQ
Project to communicate two spring-boot services using RabbitMQ
Run rabbitMQ using docker ("https://hub.docker.com/_/rabbitmq")
<file_sep>package br.com.andremoresco.produto.service;
import br.com.andremoresco.produto.repository.ProdutoRepository;
import br.com.andremoresco.produto.sender.FreteQueueSender;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Map;
@Service
public class ProdutoService {
@Autowired
private FreteQueueSender freteQueueSender;
@Autowired
private ProdutoRepository produtoRepository;
public Object create(Map<String, Object> produto) {
Map<String, Object> response = produtoRepository.create(produto);
this.sendNewProductToFreteService(produto);
return response;
}
private void sendNewProductToFreteService(Map<String, Object> produto) {
freteQueueSender.send(produto);
}
}<file_sep>package br.com.andremoresco.frete.consumer;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;
import java.util.Map;
@Component
public class FreteConsumer {
@RabbitListener(queues = "${queue.frete.name}")
public void receive(@Payload Map<String, Object> produto) throws Exception {
System.out.println(produto.toString());
}
}
|
edbdd543ff0d209631b17b32591337e477604903
|
[
"Markdown",
"Java"
] | 3 |
Markdown
|
andremoresco/spring-boot-with-rabbitMQ
|
46c19ce751808129a1bd7e5dfb8305c7239017d8
|
72dd7b4d55b52cc2e3d3abff92ca0337751e0d5e
|
refs/heads/master
|
<repo_name>letanthang/demo_go<file_sep>/mongo_crud/main.go
package main
import (
"context"
"log"
"time"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
const (
database = "test_db"
collection = "post"
replicaSetName = "mongo-rs"
)
var Client *mongo.Client
type Post struct {
Tile string `json:"tile" bson:"tile"`
Content string `json:"content" bson:"content"`
}
func connect() {
// uri := "mongodb://mongoadmin:secret@localhost:27017"
// change stream work only with replica set
uri := "mongodb+srv://mongoadmin:<EMAIL>@<EMAIL>-xxyrd.gcp.<EMAIL>"
client, err := mongo.NewClient(options.Client().ApplyURI(uri))
if err != nil {
log.Fatal(err)
}
err = client.Connect(context.TODO())
if err != nil {
log.Fatal(err)
}
Client = client
}
func AddAndSleep() {
for i := 0; i < 10; i++ {
AddOne()
log.Println("sleep 300ms")
time.Sleep(time.Millisecond * 300)
}
}
func AddOne() {
res, err := Client.Database(database).Collection(collection).InsertOne(context.TODO(), Post{"Vietnam thang Indo", "Viet Nam thang dam Indo 3-1"})
if err != nil {
log.Fatal(err)
}
id := res.InsertedID
log.Println(id)
}
func main() {
connect()
// AddOne()
AddAndSleep()
}
<file_sep>/0510/main.go
package main
import (
"encoding/json"
"fmt"
)
type Student struct {
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
Email string `json:"email"`
Age int `json:"age"`
ClassName string `json:"course_name"`
AcademyName string `json:"acedemy_name"`
}
func main() {
//parse string to struct
jsonString := "{\"first_name\":\"Tin\",\"last_name\":\"Tran\",\"email_address\":\"<EMAIL>\",\"age\":80,\"course_name\":\"golang0110\",\"acedemy_name\":\"Nordic Coder\"}"
fmt.Println(jsonString)
bs := []byte(jsonString)
var aStudent Student
json.Unmarshal(bs, &aStudent)
//type casting
//1. int - float
aInt := 5
var aFloat float64
aFloat = float64(aInt)
fmt.Println("aFloat=", aFloat)
//2. struct -struct
aBoy := Boy{Name: "Thai", Age: 90}
PrintPersonName(Person(aBoy))
//type assertion
var i interface{}
i = "62.0"
var bFloat float64
bFloat, _ = i.(float64)
fmt.Println("bFloat=", bFloat)
}
type Person struct {
Name string
Age int
}
type Boy struct {
Name string
Age int
}
func PrintPersonName(p Person) {
fmt.Println(p.Name)
}
<file_sep>/go_testify_assert/main_test.go
package main
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestSum(t *testing.T) {
result := Sum(1, 1)
assert.Equal(t, 3, result, "they should be equal")
}
func TestMutiple(t *testing.T) {
result := Mutiple(2, 2)
assert.Equal(t, 4, result, "they should be equal")
}
<file_sep>/os_signal/main.go
package main
import (
"fmt"
"os"
"os/signal"
"time"
)
func main() {
forever := make(chan os.Signal)
signal.Notify(forever, os.Interrupt)
go func() {
i := 0
for {
i++
fmt.Println("Hello world", i)
time.Sleep(800 * time.Millisecond)
}
}()
<-forever
fmt.Println("Thanks for learning Golang")
}
<file_sep>/test_n_bench/main_test.go
package main
import "testing"
func TestAsChan(t *testing.T) {
intSlice := []int{1, 2, 3, 4, 5, 6}
ch := AsChan(intSlice...)
seen := map[int]struct{}{}
// test duplicate
for v := range ch {
if _, ok := seen[v]; ok {
t.Errorf("duplicate value %d", v)
}
seen[v] = struct{}{}
}
// test seen all
for _, v := range intSlice {
if _, ok := seen[v]; !ok {
t.Errorf("miss value %d", v)
}
}
}
func TestMergeChannel(t *testing.T) {
ch1 := AsChan(1, 2, 3)
ch2 := AsChan(4, 5, 6)
ch3 := AsChan(7, 8, 9)
mCh := MergeChannel(ch1, ch2, ch3)
seen := map[int]struct{}{}
// test duplicate
for v := range mCh {
if _, ok := seen[v]; ok {
t.Errorf("duplicate value %d", v)
}
seen[v] = struct{}{}
}
// test seen all
for v := 1; v < 10; v++ {
if _, ok := seen[v]; !ok {
t.Errorf("miss value %d", v)
}
}
}
func BenchmarkMergeChannel(b *testing.B) {
for i := 0; i < b.N; i++ {
c := MergeChannel(AsChan(0, 1, 2, 3, 4, 5, 6, 7, 8, 9))
for range c {
}
}
}
<file_sep>/panic_recover2/main.go
package main
import (
"fmt"
"time"
)
func main() {
ch := make(chan int)
go func() {
defer close(ch)
ch <- 1
time.Sleep(1 * time.Second)
ch <- 2
time.Sleep(1 * time.Second)
ch <- 0
time.Sleep(1 * time.Second)
ch <- 10
time.Sleep(1 * time.Second)
}()
for i := range ch {
safelyDo(i)
}
}
func safelyDo(work int) {
// call recover() in defer
defer func() {
if err := recover(); err != nil {
fmt.Println(err)
}
}()
dangerous(work)
}
func dangerous(work int) {
res := 100 / work
fmt.Print(res, " ")
}
<file_sep>/go.mod
module github.com/letanthang/demo_go
go 1.13
require (
github.com/dgrijalva/jwt-go v3.2.0+incompatible
github.com/golang/snappy v0.0.1 // indirect
github.com/google/go-cmp v0.3.1 // indirect
github.com/jinzhu/gorm v1.9.11
github.com/labstack/gommon v0.3.0
github.com/stretchr/testify v1.4.0
github.com/xdg/scram v0.0.0-20180814205039-7eeb5667e42c // indirect
github.com/xdg/stringprep v1.0.0 // indirect
go.mongodb.org/mongo-driver v1.1.3
golang.org/x/crypto v0.0.0-20191106202628-ed6320f186d4 // indirect
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e // indirect
golang.org/x/text v0.3.2 // indirect
gopkg.in/mgo.v2 v2.0.0-20190816093944-a6b53ec6cb22
)
<file_sep>/go_unit_test/main_test.go
package main
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestSum(t *testing.T) {
result := Sum(1, 1)
if result != 2 {
t.Errorf("Sum is fail, 1 + 1 must be 2 but receive %d", result)
}
}
func TestMutiple(t *testing.T) {
result := Mutiple(2, 2)
if result != 4 {
t.Errorf("Mutiple is fail, 2 * 2 must be 4 but receive %d", result)
}
}
func TestMutipleTestify(t *testing.T) {
tests := []struct {
Name string
Input1 int
Input2 int
Expected int
}{
{"case1", 1, 2, 2},
{"case2", 2, 2, 4},
{"case2", 4, 2, 8},
}
for _, tc := range tests {
t.Run(tc.Name, func(t *testing.T) {
result := Mutiple(tc.Input1, tc.Input2)
assert.Equal(t, tc.Expected, result, "Phai bang nhau")
})
}
}
<file_sep>/channel_buffer/buffer/main.go
package main
import "fmt"
func main() {
ch := make(chan string, 2)
ch <- "some data"
ch <- "other data"
fmt.Println(<-ch)
fmt.Println(<-ch)
}
<file_sep>/md5/main.go
package main
import (
"crypto/md5"
"encoding/hex"
"fmt"
"io"
)
func main() {
text := "abcd1234"
t1 := GetMD5(text)
fmt.Println(t1)
t2 := GenMD5(text)
fmt.Println(t2)
t3 := HashMD5(text)
fmt.Println(t3)
}
func GetMD5(text string) string {
h := md5.New()
io.WriteString(h, text)
return fmt.Sprintf("%x", h.Sum(nil))
}
func GenMD5(text string) string {
h := md5.New()
h.Write([]byte(text))
return fmt.Sprintf("%x", h.Sum(nil))
}
func HashMD5(text string) string {
h := md5.New()
h.Write([]byte(text))
return hex.EncodeToString(h.Sum(nil))
}
<file_sep>/mongo_change_stream/main.go
package main
import (
"context"
"log"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
const (
database = "test_db"
collection = "post"
replicaSetName = "mongo-rs"
)
var Client *mongo.Client
type Post struct {
Tile string `json:"tile" bson:"tile"`
Content string `json:"content" bson:"content"`
}
type IDELem struct {
Data string `json:"data" bson:"_data"`
}
type NSELem struct {
DB string `json:"db" bson:"db"`
Coll string `json:"coll" bson:"coll"`
}
type DocumentKeyElem struct {
ID string `json:"id" bson:"_id"`
}
type CSElem struct {
ID IDELem `json:"id" bson:"_id"`
OperationType string `json:"operationType" bson:"operationType"`
FullDocument Post `json:"fullDocument" bson:"fullDocument"`
NS NSELem `json:"ns" bson:"ns"`
DocumentKey interface{} `json:"documentKey" bson:"documentKey"`
}
func connect() {
// uri := "mongodb://mongoadmin:secret@localhost:27017"
// change stream work only with replica set
uri := "mongodb+srv://mongoadmin:<EMAIL>@cluster0-xxyrd.gcp.mongodb.net"
client, err := mongo.NewClient(options.Client().ApplyURI(uri))
if err != nil {
log.Fatal(err)
}
err = client.Connect(context.TODO())
if err != nil {
log.Fatal(err)
}
Client = client
}
func main() {
connect()
col := Client.Database(database).Collection(collection)
ctx := context.Background()
stream, err := col.Watch(ctx, mongo.Pipeline{}) // bson.A{}
if err != nil {
log.Println(err)
return
}
defer stream.Close(ctx)
for stream.Next(ctx) {
elem := CSElem{}
if err := stream.Decode(&elem); err != nil {
log.Fatal(err)
}
log.Printf("event %+v \n", elem)
}
if err := stream.Err(); err != nil {
log.Fatal(err)
}
}
<file_sep>/practise_interface/main.go
package main
import (
"fmt"
"math"
)
func main() {
rect := Rect{Width: 10, Height: 20}
PrintArea(rect)
c := Circle{Diameter: 30}
PrintArea(c)
}
type Shape interface {
Area() float64
Perimeter() float64
}
type Rect struct {
Width float64
Height float64
}
func (r Rect) Area() float64 {
return r.Width * r.Height
}
func (r Rect) Perimeter() float64 {
return 0
}
type Circle struct {
Diameter float64
}
func (r Circle) Area() float64 {
return r.Diameter * r.Diameter / 4 * math.Pi
}
func PrintArea(s interface{}) {
if shape, ok := s.(Shape); ok {
fmt.Println(shape.Area())
} else {
fmt.Println("Unmatch interface")
}
}
<file_sep>/go_change_stream/main.go
package main
import (
"context"
"fmt"
"log"
"time"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
"gopkg.in/mgo.v2/bson"
)
var Client *mongo.Client
func main() {
connect()
collection := Client.Database("test_db").Collection("post")
ctx := context.Background()
stream, err := collection.Watch(ctx, mongo.Pipeline{})
if err != nil {
log.Println(err)
return
}
defer stream.Close(ctx)
for stream.Next(ctx) {
var elem bson.M
if err := stream.Decode(&elem); err != nil {
log.Fatal(err)
}
log.Println(elem)
}
}
func connect() {
// uri := "mongodb://mongoadmin:mongosecret@localhost:27017"
uri := "mongodb+srv://mongoadmin:<EMAIL>"
fmt.Println("Connect MongoDb with uri", uri)
client, err := mongo.NewClient(options.Client().ApplyURI(uri))
if err != nil {
panic(err)
}
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
err = client.Connect(ctx)
if err != nil {
panic(err)
}
ctx, _ = context.WithTimeout(context.Background(), 2*time.Second)
err = client.Ping(ctx, readpref.Primary())
if err != nil {
panic(err)
}
Client = client
}
<file_sep>/go_package/main.go
package main
import (
"fmt"
db2 "github.com/letanthang/demo_go/model"
)
func main() {
aStudent := db2.Student{FirstName: "Sang", LastName: "Nguyen", Age: 100}
fmt.Println(aStudent.GetName())
// SetAge - 1000
aStudent.SetAge(1000)
var p *db2.Student
p = &aStudent
p.Age = 20000
fmt.Println(aStudent.Age)
}
<file_sep>/db/init.go
package db
import (
"time"
"github.com/labstack/gommon/log"
"gopkg.in/mgo.v2"
)
var SessionOrginal *mgo.Session
var databaseName string
var (
MongoDBHosts string
AuthDatabase string
AuthUserName string
AuthPassword string
)
func nativeConnection() {
mongoDBDialInfo := &mgo.DialInfo{
Addrs: []string{MongoDBHosts},
Timeout: 60 * time.Second,
Database: AuthDatabase,
Username: AuthUserName,
Password: <PASSWORD>,
}
// Create a session which maintains a pool of socket connections
// to our MongoDB.
mgoSession, err := mgo.DialWithInfo(mongoDBDialInfo)
if err != nil {
log.Fatalf("CreateSession: %s\n", err)
}
log.Info("Mongodb connected")
mgoSession.SetMode(mgo.Monotonic, true)
SessionOrginal = mgoSession
}
func init() {
MongoDBHosts = "127.0.0.1"
AuthDatabase = "admin"
AuthUserName = "mongoadmin"
AuthPassword = "<PASSWORD>"
databaseName = "go3008"
nativeConnection()
}
<file_sep>/gorm_postgres/main.go
package main
import (
"fmt"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres"
)
var DB *gorm.DB
type Student struct {
gorm.Model
FirstName string `json:"first_name" gorm:"column:first_name"`
LastName string `json:"last_name" gorm:"column:last_name"`
Age int
ClassName string `json:"class_name" gorm:"column:class_name"`
Email string `json:"email" gorm:"column:email"`
}
func (Student) TableName() string {
return "student"
}
func main() {
DB = newDB()
//insert one
// aStudent := Student{gorm.Model{ID: 102}, "Nghia", "Nguyen", 100, "golang", "<EMAIL>"}
// DB.Create(&aStudent)
// soft delete
filter := map[string]interface{}{}
filter["id"] = 102
DB.Delete(&Student{}, filter)
// query all
var students []Student
DB.Find(&students)
fmt.Printf("students :%+v", students)
}
func newDB() *gorm.DB {
// db, err := gorm.Open("sqlite3", "test.db")
connectionString := fmt.Sprintf("host=%s user=%s dbname=%s sslmode=disable password=%s", "localhost", "postgres", "nc", "docker")
fmt.Println(connectionString)
db, err := gorm.Open("postgres", connectionString)
if err != nil {
panic(err)
}
// defer db.Close()
db.DB().SetMaxIdleConns(10)
db.DB().SetMaxOpenConns(100)
db.DB().Ping()
db.LogMode(true)
return db
}
<file_sep>/reflection/main.go
package main
import (
"fmt"
"reflect"
"strings"
)
type Foo struct {
A int `json:"a" gorm:"colum:a" tag1:"hehe" tag2:"hihi"`
B string `json:"b" gorm:"colum:b"`
}
func main() {
// struct
// type struct
// slice
// pointer
// map
// get kind and type
// case reflect.Array, reflect.Chan, reflect.Map, reflect.Ptr, reflect.Slice : get element: Elem()
// case reflect.Struct : get field : NumField(), Field(int)
aStruct := struct {
A int
B string
}{1, "hehe"}
bStruct := Foo{A: 2, B: "hihi"}
cSlice := []int{1, 2, 4}
dPointer := &cSlice
eMap := map[string]interface{}{"name": "Thang", "age": 1}
aType := reflect.TypeOf(aStruct)
bType := reflect.TypeOf(bStruct)
cType := reflect.TypeOf(cSlice)
dType := reflect.TypeOf(dPointer)
eType := reflect.TypeOf(eMap)
fmt.Println("bType name=", aType.Name(), "bType Kind=", aType.Kind())
fmt.Println("bType name=", bType.Name(), "bType Kind=", bType.Kind(), "fields=", bType.Field(0))
pointer := &bType
fmt.Println("type of", bType, pointer, reflect.ValueOf(bType), reflect.ValueOf(pointer))
b1 := reflect.New(bType)
b1.Elem().Field(0).SetInt(3)
b1.Elem().Field(1).SetString("kaka")
b1Struct := b1.Elem().Interface().(Foo)
fmt.Println(b1Struct.A, b1Struct.B)
fmt.Println("------------------------------")
inspect(aType, 0)
inspect(bType, 0)
inspect(cType, 0)
inspect(dType, 0)
inspect(eType, 0)
fmt.Println("ba" + strings.Repeat("na", 5))
}
func inspect(t reflect.Type, depth int) {
fmt.Println(strings.Repeat("\t", depth), "Type is", t.Name(), "- kind is", t.Kind())
switch t.Kind() {
case reflect.Array, reflect.Chan, reflect.Map, reflect.Ptr, reflect.Slice:
fmt.Println(strings.Repeat("\t", depth+1), "Contained type:")
inspect(t.Elem(), depth+1)
case reflect.Struct:
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
fmt.Println(strings.Repeat("\t", depth+1), "Field", i+1, "name is", f.Name)
if f.Tag != "" {
fmt.Println(strings.Repeat("\t", depth+2), "Tag is", f.Tag)
fmt.Println(strings.Repeat("\t", depth+2), "Tag1 is", f.Tag.Get("tag1"), "Tag2 is", f.Tag.Get("tag2"))
}
}
}
}
<file_sep>/go_interface/main.go
package main
import (
"fmt"
"math"
)
// interface{}
type Shape interface {
Area() float64
Perimeter() float64
}
type Rect struct {
Width float64
Height float64
}
func (r Rect) Area() float64 {
return r.Width * r.Height
}
func (r Rect) Perimeter() float64 {
return 2 * (r.Width + r.Height)
}
type Triangle struct {
Width float64
Height float64
}
func (t Triangle) Area() float64 {
return t.Width * t.Height / 2
}
type Circle struct {
Diameter float64
}
func (r Circle) Area() float64 {
return math.Pi * math.Pi * r.Diameter
}
func (r Circle) Perimeter() float64 {
return math.Pi * r.Diameter
}
func PrintArea(s interface{}) {
//type assertion
shape, ok := s.(Shape)
if !ok {
fmt.Println("Cannot use type assertion to this type")
return
}
fmt.Println("Shape has area=", shape.Area())
}
func PrintPerimeter(s Shape) {
fmt.Println("Shape has area=", s.Perimeter())
}
func main() {
rect := Rect{Width: 20, Height: 30}
PrintArea(rect)
cirle := Circle{Diameter: 50}
PrintArea(cirle)
triangle := Triangle{Width: 30, Height: 60}
PrintArea(triangle)
}
<file_sep>/error_handling1/main.go
package main
import "errors"
func main() {
}
type Bar struct {
ID int
Name string
Err error
}
func (b Bar) Error() string {
return b.Err.Error()
}
func Foo() error {
res := Bar{1, "Thang", errors.New("Some Error")}
return res
}
<file_sep>/call_rest_api/main.go
package main
import (
"encoding/json"
"fmt"
"net/http"
)
type Student struct {
ID int
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
Age int `json:"age"`
Email string `json:"email"`
}
func main() {
url := "http://localhost:9090/api/v1/public/student"
resp, err := http.Get(url)
if err != nil {
panic(err)
}
defer resp.Body.Close()
var result []Student // var result []map[string]interface{}
err = json.NewDecoder(resp.Body).Decode(&result)
if err != nil {
panic(err)
}
fmt.Printf("Students : %+v", result)
}
<file_sep>/error_handling/main.go
package main
import (
"fmt"
"os"
"syscall"
)
func main() {
filename := "hello/test.txt"
for try := 0; try < 2; try++ {
_, err := os.Create(filename)
if err == nil {
fmt.Println("Success! file created", err)
return
}
if e, ok := err.(*os.PathError); ok && e.Err == syscall.ENOSPC {
// deleteTempFiles() // Recover some space.
fmt.Println("Cannot create the file: diskspace, err", e)
continue
}
if e, ok := err.(*os.PathError); ok && e.Err == syscall.ENOENT {
// deleteTempFiles() // Recover some space.
fmt.Println("Cannot create the file: no such path/directory, err", e)
continue
}
return
}
}
<file_sep>/0110/main.go
package main
import (
"encoding/json"
"errors"
"fmt"
"strconv"
)
type MyInt int
type Student struct {
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
Email string `json:"email"`
Age int `json:"age"`
ClassName string `json:"class_name"`
AcademyName string `json:"acedemy_name"`
}
func main() {
fmt.Println("Hello World Golang 01/10/2019")
// int
var aInt int
aInt = 10
fmt.Println("aInt=", aInt)
bInt := 11
fmt.Println("bInt=", bInt)
bInt = 12
fmt.Println("bInt=", bInt)
// string
var aString string
aString = "hello"
bString := "1000"
fmt.Println(aString)
// string concat : way 1
aString = aString + bString
fmt.Println(aString)
fmt.Printf("%s\n", aString)
fmt.Printf("%d\n", aInt)
// string concat : way 2
aString = fmt.Sprintf("hehe %s %d\n", aString, aInt)
fmt.Println(aString)
res, err := getAnInterger(bString)
fmt.Println(res, err)
aSlice := []int{1, 5, 6, 8}
fmt.Println(aSlice)
fmt.Printf("%v", aSlice)
// slice iterate
for _, v := range aSlice {
fmt.Println(v)
}
aMap := map[string]interface{}{"name": "Phat", "email": "<EMAIL>"}
aMap["age"] = 100
fmt.Printf("%v", aMap)
// map iterate
for k, v := range aMap {
fmt.Println("key", k, "has value", v)
}
aStudent := Student{
FirstName: "Tin",
LastName: "Tran",
Email: "<EMAIL>",
Age: 80,
ClassName: "golang0110",
AcademyName: "Nordic Coder",
}
bs, _ := json.Marshal(aStudent)
dString := string(bs)
fmt.Printf("%v+ \n %s", aStudent, dString)
}
func getAnInterger(a string) (int, error) {
res, _ := strconv.Atoi(a)
return res, errors.New("bad request")
}
<file_sep>/practise_error_handling/main.go
package main
import (
"errors"
"fmt"
"os"
"syscall"
)
func main() {
filename := "hehe/test_error.txt"
for try := 0; try < 2; try++ {
_, err := os.Create(filename)
if err == nil {
return
}
if e, ok := err.(*os.PathError); ok && e.Err == syscall.ENOSPC {
// deleteTempFiles() // Recover some space.
continue
}
if errors.Is(err, syscall.ENOENT) {
// deleteTempFiles() // Recover some space.
fmt.Println("Khong ton tai duong dan/ thu muc")
continue
}
return
}
}
<file_sep>/go_routine/main.go
package main
import (
"fmt"
"sync"
"time"
)
func main() {
var waitgroup sync.WaitGroup
waitgroup.Add(1)
go DoSomething2(&waitgroup)
waitgroup.Add(1)
go DoSomething3(&waitgroup)
waitgroup.Add(1)
DoSomething1(&waitgroup)
waitgroup.Wait()
}
func DoSomething1(wg *sync.WaitGroup) {
time.Sleep(2 * time.Second)
fmt.Println("Done1")
wg.Done()
}
func DoSomething2(wg *sync.WaitGroup) {
time.Sleep(2 * time.Second)
fmt.Println("Done2")
wg.Done()
}
func DoSomething3(wg *sync.WaitGroup) {
time.Sleep(2 * time.Second)
fmt.Println("Done3")
wg.Done()
}
<file_sep>/go_reflection/main.go
package main
import (
"fmt"
"reflect"
)
type Person struct {
Name string
Age int
}
func main() {
aInt := 5
aType := reflect.TypeOf(aInt)
fmt.Printf("type %s | kind %s \n", aType.Name(), aType.Kind())
// type int , kind int
aStruct := struct {
Name string
Age int
}{Name: "Thang", Age: 35}
aType = reflect.TypeOf(aStruct)
fmt.Printf("type %s | kind %s \n", aType.Name(), aType.Kind())
// type nil , kind struct
// aPerson := Person{Name: "T", Age: 35}
}
<file_sep>/go_subtest1/main_test.go
package main
import (
"testing"
"github.com/stretchr/testify/assert"
)
type TestCase struct {
Name string
Input1 int
Input2 int
Expect int
}
func TestSum(t *testing.T) {
testCases := []TestCase{
{"case 1: 1 + 1", 1, 1, 2},
{"case 2: 1 + 2", 1, 2, 3},
{"case 3: 2 + 2", 2, 2, 4},
}
// subtest
for _, tc := range testCases {
result := Sum(tc.Input1, tc.Input2)
t.Run(tc.Name, func(t *testing.T) {
assert.Equal(t, tc.Expect, result)
})
}
}
func TestMultiply(t *testing.T) {
testCases := []TestCase{
{"case 1: 1 x 1", 1, 1, 1},
{"case 2: 1 x 2", 1, 2, 2},
{"case 3: 2 x 2", 2, 2, 4},
}
// subtest
for _, tc := range testCases {
result := Multiply(tc.Input1, tc.Input2)
t.Run(tc.Name, func(t *testing.T) {
assert.Equal(t, tc.Expect, result)
})
}
}
<file_sep>/panic_recover/main.go
package main
import (
"fmt"
"log"
"time"
)
func main() {
ch := asChan(1, 2, 4, 0, 5, 6)
for v := range ch {
// fmt.Print(v, " ")
safelyDo(v)
}
}
func asChan(vs ...int) chan int {
out := make(chan int, 2)
go func() {
defer close(out)
for _, v := range vs {
time.Sleep(20 * time.Millisecond)
out <- v
}
}()
return out
}
func safelyDo(work int) {
defer func() {
if err := recover(); err != nil {
log.Println("work failed:", err)
}
}()
do(work)
}
func do(work int) {
res := 100 / work
fmt.Print(res, " ")
}
<file_sep>/demo_channel/ch_for_wait/main.go
package main
import (
"fmt"
"time"
)
func main() {
ch := make(chan int, 5)
go DoTask2(ch)
go DoTask3(ch)
go DoTask1(ch)
<-ch
<-ch
<-ch
<-ch
}
func DoTask1(ch chan int) {
time.Sleep(2 * time.Second)
fmt.Println("Task1 done")
ch <- 1
}
func DoTask2(ch chan int) {
time.Sleep(2 * time.Second)
fmt.Println("Task2 done")
ch <- 1
}
func DoTask3(ch chan int) {
time.Sleep(2 * time.Second)
fmt.Println("Task3 done")
ch <- 1
}
<file_sep>/type_conversion/main.go
package main
import "fmt"
func main() {
// aPerson := Person{Name: "Thai", Age: 90}
aBoy := Boy{Name: "Tam", Age: 100}
PrintPersonName(Person(aBoy))
}
func PrintPersonName(p Person) {
fmt.Println(p.Name)
}
type Person struct {
Name string
Age int `json:"age"`
}
type Boy struct {
Name string
Age int `json:"abc"`
}
<file_sep>/jwt/main.go
package main
import (
"fmt"
"time"
"github.com/dgrijalva/jwt-go"
)
type MyClaims struct {
ClientID int `json:"cid"`
GroupID int `json:"gid"`
jwt.StandardClaims
}
func main() {
claims := MyClaims{
ClientID: 123,
GroupID: 456,
StandardClaims: jwt.StandardClaims{
ExpiresAt: time.Now().Add(time.Hour * 48).Unix(),
},
}
token, _ := GetJWTToken(claims)
fmt.Println(token)
fmt.Println(ParseJWTToken(token))
}
func GetJWTToken(c MyClaims) (string, error) {
mySigningKey := []byte("MySecret1234")
token := jwt.NewWithClaims(jwt.SigningMethodHS256, c)
ss, err := token.SignedString(mySigningKey)
return ss, err
}
func ParseJWTToken(tokenString string) *MyClaims {
mySigningKey := []byte("MySecret1234")
token, err := jwt.ParseWithClaims(tokenString, &MyClaims{}, func(*jwt.Token) (interface{}, error) {
return mySigningKey, nil
})
if err != nil {
return nil
}
if claims, ok := token.Claims.(*MyClaims); ok {
return claims
}
return nil
}
<file_sep>/main.go
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"gopkg.in/mgo.v2/bson"
model "github.com/letanthang/demo_go/model"
"github.com/letanthang/demo_go/db"
)
func main() {
people, err := GetPeopleNew()
if err != nil {
log.Panic(err)
return
}
err = StorePeople(*people)
if err != nil {
log.Panic(err)
return
}
err = UpdatePeople()
if err != nil {
log.Panic(err)
return
}
fmt.Println("************** success ****************")
fmt.Printf("people: %+v", people)
}
func UpdatePeople() error {
sessionClone := db.SessionOrginal.Clone()
defer sessionClone.Close()
selector := bson.M{"id": 7}
update := bson.M{"$set": bson.M{"married": false, "first_name": "Thang123"}}
err := sessionClone.DB("go3008").C("people").Update(selector, update)
return err
}
func StorePeople(people []model.Person) error {
sessionClone := db.SessionOrginal.Clone()
defer sessionClone.Close()
// err := sessionClone.DB("go3008").C("people").Insert(people[0])
bulk := sessionClone.DB("go3008").C("people").Bulk()
data := []interface{}{}
for _, i := range people {
data = append(data, i)
}
bulk.Insert(data...)
_, err := bulk.Run()
return err
}
func GetPeople() (*[]model.Person, error) {
url := "http://localhost:9090/v1/people"
data := map[string]interface{}{"course": "golang"}
bs, _ := json.Marshal(data)
req, _ := http.NewRequest("GET", url, bytes.NewBuffer(bs))
req.Header.Add("Authorization", "key=<KEY>")
req.Header.Add("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
bs, err = ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var people []model.Person
err = json.Unmarshal(bs, &people)
if err != nil {
return nil, err
}
return &people, nil
}
func GetPeopleNew() (*[]model.Person, error) {
url := "http://localhost:9090/v1/people"
data := map[string]interface{}{"course": "golang"}
bs, _ := json.Marshal(data)
req, _ := http.NewRequest("GET", url, bytes.NewBuffer(bs))
req.Header.Add("Authorization", "key=<KEY> <KEY>")
req.Header.Add("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
decoder := json.NewDecoder(resp.Body)
var people []model.Person
err = decoder.Decode(&people)
return &people, nil
}
func practise() {
bs := []int{10, 100, 2000, 2000, 100, 2000, 10}
var aMap map[int]int
aMap = map[int]int{}
for _, v := range bs {
aMap[v] = v
}
var uniqueSlice []int
for v := range aMap {
uniqueSlice = append(uniqueSlice, v)
}
fmt.Println(bs, aMap, uniqueSlice)
aPerson := model.Person{FirstName: "Thang", LastName: "Le"}
aPerson.ChangeFirstName("Tam")
firstName := aPerson.GetFirstName()
fmt.Println(firstName)
}
<file_sep>/wait_group/main.go
package main
import (
"fmt"
"sync"
"time"
)
func main() {
var wg sync.WaitGroup
wg.Add(1)
go DoTask2(&wg)
wg.Add(1)
go DoTask3(&wg)
DoTask1()
wg.Wait()
}
func DoTask1() {
time.Sleep(2 * time.Second)
fmt.Println("Task1 done")
}
func DoTask2(wg *sync.WaitGroup) {
time.Sleep(2 * time.Second)
fmt.Println("Task2 done")
wg.Done()
}
func DoTask3(wg *sync.WaitGroup) {
defer wg.Done()
time.Sleep(2 * time.Second)
fmt.Println("Task3 done")
}
<file_sep>/go_subtest/main_test.go
package main
import (
"fmt"
"testing"
"github.com/stretchr/testify/assert"
)
func TestSum(t *testing.T) {
tests := []struct {
a int
b int
want int
}{
{1, 1, 3},
{1, 9, 10},
{2, 3, 5},
}
for _, tc := range tests {
name := fmt.Sprintf("Test %d + %d", tc.a, tc.b)
t.Run(name, func(t *testing.T) {
got := Sum(tc.a, tc.b)
assert.Equal(t, tc.want, got, "they should be equal")
})
}
}
func TestMutiple(t *testing.T) {
result := Mutiple(2, 2)
if result != 4 {
t.Errorf("Mutiple is fail, 2 * 2 must be 4 but receive %d", result)
}
}
<file_sep>/go_crawler/main.go
package main
import "fmt"
func main() {
ch := make(chan string)
go func() {
ch <- "https://vnexpress.net/the-gioi/dong-co-may-bay-boc-chay-khi-sap-cat-canh-3999385.html?vn_source=Home&vn_campaign=TopNews&vn_medium=Item-1&vn_term=Desktop&vn_thumb=0"
}()
resultChannel := startWorker(ch)
for result := range resultChannel {
fmt.Println("Find on result!", result)
// write workload/urls to ch
go func() {
for _, url := range result.Urls {
ch <- url
}
}()
}
}
type Result struct {
Title string
Description string
Content string
Urls []string
}
func startWorker(ch chan string) chan Result {
out := make(chan Result)
go func() {
for url := range ch {
go func(url string) {
result := parseUrl(url)
out <- result
}(url)
}
}()
return out
}
func parseUrl(url string) Result {
return Result{
Title: "Viet Nam thang Indo 3-1",
Description: "lasjd;fals;dfj",
Content: "HÀN QUỐCĐộng cơ máy bay hãng Asiana Airlines bốc cháy trên đường băng sân bay Incheon ở Seoul khi đang tiếp nhiên liệu để chuẩn bị cất cánh. Hành khách đang chờ lên máy bay tại sân bay quốc tế Incheon hôm 18/10 hoảng sợ khi chứng kiến ngọn lửa bùng lên từ một động cơ của chiếc Airbus A380. Động cơ bốc cháy trong lúc máy bay đang tiếp nhiên liệu để khởi hành từ Seoul tới Los Angeles, Mỹ với 495 hành khách.Không có ai bị thương trong sự cố và toàn bộ hành khách đã được sơ tán khỏi khu vực cổng ra máy bay.",
Urls: []string{"https://vnexpress.net/the-gioi/1.html", "https://vnexpress.net/the-gioi/2.html", "https://vnexpress.net/the-gioi/3.html"},
}
}
<file_sep>/simple_go_crawler/main.go
package main
import "fmt"
func main() {
ch := make(chan string)
go func() {
ch <- "vnexpress.net/home"
}()
resultChannel := startWorker(ch)
for result := range resultChannel {
fmt.Println("Fin 1 result", result)
for _, url := range result.Urls {
go func(url string) {
ch <- url
}(url)
}
}
}
type CrawlResult struct {
Content string
Title string
Author string
Urls []string
}
func startWorker(ch chan string) chan CrawlResult {
out := make(chan CrawlResult)
go func() {
for url := range ch {
go func(url string) {
result := parseUrl(url)
out <- result
}(url)
}
}()
return out
}
func parseUrl(url string) CrawlResult {
return CrawlResult{
Content: "Indo thua Viet Nam 3-1",
Title: " Indo thua",
Author: "<NAME>",
Urls: []string{"vnexpress.net/1", "vnexpress.net/2", "vnexpress.net/3", "vnexpress.net/4"},
}
}
<file_sep>/test_n_bench/main.go
package main
import (
"fmt"
"math/rand"
"sync"
"time"
)
func main() {
ch := AsChan(1, 2, 3, 4, 5)
for v := range ch {
fmt.Println(v)
}
ch1 := AsChan(1, 2, 3)
ch2 := AsChan(4, 5, 6)
ch3 := AsChan(7, 8, 9)
mCh := MergeChannel(ch1, ch2, ch3)
fmt.Println("merged channel:")
for v := range mCh {
fmt.Print(v, " ")
}
}
func MergeChannel(chans ...<-chan int) <-chan int {
out := make(chan int)
go func() {
defer close(out)
var wg sync.WaitGroup
for _, ch := range chans {
wg.Add(1)
go func(c <-chan int) {
defer wg.Done()
for v := range c {
out <- v
}
}(ch)
}
wg.Wait()
}()
return out
}
func AsChan(nums ...int) <-chan int {
c := make(chan int)
go func() {
defer close(c)
for _, v := range nums {
c <- v
time.Sleep(time.Millisecond * time.Duration(rand.Intn(10)))
}
}()
return c
}
<file_sep>/type_assertion/main.go
package main
import (
"encoding/json"
"fmt"
)
func main() {
jsonString := `{
"first_name": "Van",
"last_name": "Tran",
"email_address": "<EMAIL>",
"age": 80,
"course_name": "golang0110",
"acedemy_name": "Nordic Coder"
}`
var aMap map[string]interface{}
bs := []byte(jsonString)
json.Unmarshal(bs, &aMap)
// fmt.Println(aMap)
var age interface{}
age = aMap["age"]
fmt.Println(age)
var numAge float64
// if numAge, ok := age.(float64); ok == false {
// fmt.Println("cannot type assertion", numAge)
// }
numAge = age.(float64)
fmt.Println(numAge)
}
<file_sep>/demo_channel/pipeline/main.go
package main
import (
"fmt"
"sync"
"time"
)
func main() {
// ch := make(chan int)
// go func() {
// ch <- 100
// }()
// var aInt int
// aInt = <-ch
// fmt.Println("read value:", aInt)
ch := asChan(1, 2, 3, 4, 5, 6)
c1 := AddOne(ch)
c2 := DoubleValue(c1)
// 4 6 8 10 12 14
fmt.Println("channel value :")
for v := range c2 {
fmt.Print(v, " ")
}
}
func AddOne(c chan int) chan int {
out := make(chan int)
go func() {
defer close(out) // đóng channel
for v := range c {
out <- v + 1
}
}()
return out
}
func DoubleValue(c chan int) chan int {
out := make(chan int)
go func() {
defer close(out) // đóng channel
for v := range c {
out <- v * 2
}
}()
return out
}
func asChan(vs ...int) chan int {
out := make(chan int)
go func() {
defer close(out)
for _, v := range vs {
out <- v
time.Sleep(100 * time.Millisecond)
}
}()
return out
}
// var wg sync.WaitGroup
// wg.Add(3)
// go DoTask2(&wg)
// go DoTask3(&wg)
// go DoTask1(&wg)
// wg.Wait()
func DoTask1(wg *sync.WaitGroup) {
defer wg.Done()
time.Sleep(2 * time.Second)
fmt.Println("Task1 done")
}
func DoTask2(wg *sync.WaitGroup) {
time.Sleep(2 * time.Second)
fmt.Println("Task2 done")
wg.Done()
}
func DoTask3(wg *sync.WaitGroup) {
defer wg.Done()
time.Sleep(2 * time.Second)
fmt.Println("Task3 done")
}
<file_sep>/simple_crawler/main.go
package main
import "fmt"
func main() {
ch := make(chan string)
go func() {
ch <- "https://vnexpress.net/"
}()
resultChannel := startWorker(ch)
urlMap := map[string]bool{}
for v := range resultChannel {
fmt.Println("Receive 1 result", v)
for _, url := range v.Urls {
if urlMap[url] != true {
ch <- url
urlMap[url] = true
}
}
}
}
func startWorker(ch chan string) chan ParseResult {
out := make(chan ParseResult)
go func() {
guard := make(chan int, 4)
for url := range ch {
guard <- 1
go func(url string) {
pr := parse(url)
out <- pr
<-guard
}(url)
}
}()
return out
}
type ParseResult struct {
Title string
Author string
Urls []string
}
func parse(url string) ParseResult {
return ParseResult{}
}
<file_sep>/embedding_type/main.go
package main
import "fmt"
type Ball struct {
Radius int
}
func (b Ball) Bounce() {
fmt.Println(b, "has radius", b.Radius)
}
type BasketBall struct {
Ball
Radius int
Weight int
}
type FootBall struct {
Ball
Weight int
Radius int
}
type BaseBall struct {
*Ball
Weight int
}
type VolleyBall struct {
Action
Weight int
}
type Action interface {
Bounce()
}
func BounceIt(b Action) {
b.Bounce()
}
func BounceBall(b Ball) {
b.Bounce()
}
func main() {
bb := BasketBall{Ball{5}, 6, 50}
// fmt.Println(bb.Radius)
// bb.Bounce()
// BounceBall(bb.Ball)
BounceIt(bb)
//cannot casting embedding to embedded
// var i interface{}
// i = bb
// BounceBall(i.(Ball))
// fb := FootBall{Ball{Radius: 5}, 50, 10}
// fb.Bounce()
// baseball := BaseBall{&Ball{5}, 60}
// baseball.Bounce()
// fmt.Println("access radius",baseball.Radius)
// vb := VolleyBall{&Ball{5}, 60}
// vb.Bounce()
// BounceIt(vb)
// cannot access interface embedded properties
// fmt.Println("access radius",vb.Radius)
}
<file_sep>/model/person.go
package db1
type Person struct {
ID int `json:"id" bson:"id"`
FirstName string `json:"first_name" bson:"first_name" gorm:"column:firstname" validate:"email,required"`
LastName string `json:"last_name" bson:"last_name"`
Age int `json:"age"`
Married bool `json:"married"`
}
func (p Person) GetFirstName() string {
return p.FirstName
}
func (p *Person) ChangeFirstName(firstname string) {
p.FirstName = firstname
}
<file_sep>/sync_by_channel/main.go
package main
import (
"fmt"
"time"
)
func main() {
ch := make(chan int, 2)
go DoTask1(ch)
go DoTask2(ch)
go DoTask3(ch)
<-ch
<-ch
}
func DoTask1(ch chan int) {
time.Sleep(2 * time.Second)
fmt.Println("Done1")
ch <- 1
}
func DoTask2(ch chan int) {
time.Sleep(2 * time.Second)
fmt.Println("Done2")
ch <- 1
}
func DoTask3(ch chan int) {
time.Sleep(2 * time.Second)
fmt.Println("Done3")
ch <- 1
}
<file_sep>/call_rest/main.go
package main
import (
"encoding/json"
"fmt"
"net/http"
)
func main() {
url := "http://service-name/api/v1/public/student"
resp, err := http.Get(url)
if err != nil {
panic(err)
}
defer resp.Body.Close()
var result []map[string]interface{}
err = json.NewDecoder(resp.Body).Decode(&result)
if err != nil {
panic(err)
}
fmt.Printf("students: %+v", result)
}
<file_sep>/model/student.go
package db1
type Student struct {
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
Email string `json:"email"`
Age int `json:"age"`
ClassName string `json:"course_name"`
AcademyName string `json:"acedemy_name"`
}
func (s Student) GetName() string {
return s.FirstName + " " + s.LastName
}
func (s *Student) SetAge(age int) {
s.Age = age
}
|
3b6753bacb258bcc9928f6373cec8d596d1adfdf
|
[
"Go Module",
"Go"
] | 44 |
Go
|
letanthang/demo_go
|
7c5f3cdcdfc8064c48b4aa8ec5c83d888e1c0e71
|
3426a4e6b682a3f35b677b6b854066a66c3c120d
|
refs/heads/master
|
<file_sep># prereqs: iterators, hashes, conditional logic
# Given a hash with numeric values, return the key for the smallest value
def key_for_min_value(name_hash)
values = name_hash.collect {|key, value| value}
sorted = values.sort
name_hash.each do |key, value|
if value == sorted[0]
return key
end
end
nil
end
|
2aceaf107af726e87c296ea272f906898476f715
|
[
"Ruby"
] | 1 |
Ruby
|
Gingertonic/key-for-min-value-v-000
|
07fb1856acfa490cdae2f1fa578622abbd15d6a9
|
cdd7bcfa31c50f89cb4e39458b3cf1b8f6ba13fa
|
refs/heads/master
|
<file_sep>#!/usr/bin/ruby
require 'cgi'
require 'rubygems'
require 'fitgem'
require 'pp'
require 'yaml'
require 'erb'
# Prepare CGI
cgi = CGI.new
puts cgi.header
page_headline = "Sign Up Here!"
page_contents = ""
# Load the existing yml config and periods
database = YAML.load(File.open("fitgem.yml"))
periods = YAML.load(File.open("periods.yml"))
# Create Fitgem config client
config = begin
Fitgem::Client.symbolize_keys(database)
rescue ArgumentError => e
puts "Could not parse YAML: #{e.message}"
exit
end
options = { :operation => nil }
# Parse GET options for information
if cgi['action'] === 'report'
options[:operation] = 'report'
page_headline = "Standings"
period = cgi['period'].to_i
options[:period] = period
options[:start_date] = periods[period - 1][:weeks][0][:start_date]
options[:end_date] = periods[period - 1][:weeks][1][:end_date]
elsif cgi['action'] === 'sync'
options[:operation] = 'sync'
elsif cgi['action'] === 'create'
options[:operation] = 'create'
options[:verifier] = cgi['verifier']
options[:token] = cgi['token']
options[:secret] = cgi['secret']
else
options[:operation] = 'new'
end
if options[:operation] === 'report'
period = options[:period]
output = "Average steps/day for #{Date.parse(options[:start_date]).strftime('%-m-%d')} through #{Date.parse(options[:end_date]).strftime('%-m-%d')}"
output += "\n"
# Process data for each user
users = database[:users]
users.each do |user|
# Create Fitgem client
client = Fitgem::Client.new(config[:oauth])
# Make sure user info is included correctly
if user[:token] && user[:secret]
access_token = client.reconnect(user[:token], user[:secret])
else
next
end
# API call to get raw data
steps_data = client.data_by_time_range "/activities/log/steps", { :base_date => options[:start_date], :end_date => options[:end_date] }
# Extract steps data and save to user hash
total = steps_data["activities-log-steps"].map{ |d| d["value"].to_i }.inject(:+)
user[:periods][period - 1][:total] = total
user[:periods][period - 1][:weeks].detect{ |wk| wk[:week] === 1 }[:steps] = steps_data["activities-log-steps"][0..6].map{ |d| d["value"].to_i }.inject(:+)
user[:periods][period - 1][:weeks].detect{ |wk| wk[:week] === 2 }[:steps] = steps_data["activities-log-steps"][7..13].map{ |d| d["value"].to_i }.inject(:+)
user_output = "#{user[:name]}: #{(total / 14).round} steps/day"
output += user_output + "\n"
end
page_contents += "<pre>#{output}</pre>"
File.write('fitgem.yml', YAML.dump(database))
elsif options[:operation] === 'new'
client = Fitgem::Client.new(config[:oauth])
request_token = client.request_token
token = request_token.token
secret = request_token.secret
page_contents += "<p>1. Click this button: <a class=\"btn btn-primary\" target=\"_blank\" href=\"http://www.fitbit.com/oauth/authorize?oauth_token=#{token}\">Authorize with Fitbit</a></p>"
page_contents += "<p>2. Authorize the Magellan Jets app</p><p>3. Copy the verifier code (it will look like \"3c0d14888d8671263bbc7a15d4c4fff0\")</p>"
page_contents += "<p>4. Paste the verifier code into the box below</p>"
page_contents += "<p>5. Click submit!</p>"
page_contents += '<form method="post" enctype="application/x-www-form-urlencoded"><div class="form-group"><label>Verifier Code</label><input type="text" class="form-control" name="verifier" placeholder="Verifier Code" /></div>'
page_contents += "<input type=\"hidden\" name=\"token\" value=\"#{token}\" /><input type=\"hidden\" name=\"secret\" value=\"#{secret}\" /><input type=\"hidden\" name=\"action\" value=\"create\" />"
page_contents += '<button type="Submit" class="btn btn-success">Submit</button></form>'
elsif options[:operation] === 'create'
user = { :periods => [] }
(1..6).each{ |wk| user[:periods] << { period: wk, total: 0, weeks: [{ week: 1, steps: 0 }, { week: 2, steps: 0 }] } }
client = Fitgem::Client.new(config[:oauth])
access_token = client.authorize(options[:token], options[:secret], { :oauth_verifier => options[:verifier] })
user_info = client.user_info['user']
unless database[:users].detect{ |user| user[:id] == user_info['encodedId'] }
user[:token] = access_token.token
user[:secret] = access_token.secret
user[:id] = user_info['encodedId']
user[:name] = user_info['fullName']
database[:users] << user
File.write('fitgem.yml', YAML.dump(database))
end
page_headline = "Success!"
end
stylesheet = File.open("cover.css").read
template = File.open("template.html.erb").read
renderer = ERB.new(template)
puts output = renderer.result()
|
d7e1eb3a80433ab4b68a6d71a3ecb23883bf3813
|
[
"Ruby"
] | 1 |
Ruby
|
ChrisMagellan/fit-challenge
|
01be6faea293ce5f1d31b443b037e6ef88d6c691
|
e99b356b38961fb1cb1a47f15ff0816cc440c48d
|
refs/heads/master
|
<file_sep>import Counter from './Counter.svelte';
const counter = new Counter({
target: document.getElementById('svelte-counter'),
});
export default counter;<file_sep>import svelte from 'rollup-plugin-svelte';
import commonjs from '@rollup/plugin-commonjs';
import resolve from '@rollup/plugin-node-resolve';
import { terser } from 'rollup-plugin-terser';
import css from 'rollup-plugin-css-only';
import autoPreprocess from 'svelte-preprocess';
const production = true;
export default {
input: 'src/lib/main.ts',
output: {
sourcemap: true,
format: 'iife',
name: 'app',
file: 'package-js/counter.js'
},
plugins: [
svelte({
compilerOptions: {
dev: !production,
customElement: false,
},
preprocess: autoPreprocess()
}),
css({ output: 'counter.css' }),
resolve({
browser: true,
dedupe: ['svelte']
}),
commonjs(),
production && terser()
],
};
|
8095641fae3acdb3922e7bd5e5af9b97043760e8
|
[
"JavaScript",
"TypeScript"
] | 2 |
TypeScript
|
anthonylegoas/sveltekit-compile-components-sample
|
b7f72195db0e4793e85d6684bb1db1a195f58fc6
|
6b58d59d444c2362d4c6ddafb8e1c05c99608733
|
refs/heads/master
|
<repo_name>Elguava/P_Prog_Week-3-Assign-2<file_sep>/R_prog_ Week 3_assingment 2 _ caching function.r
## Put comments here that give an overall description of what your
## functions do
## Write a short comment describing this function
makeCacheMatrix <- function(x = matrix()) {
inv_mx <- NULL
set <- function(y) {
x<<- y
inv_mx <<- NULL
}
get <- function()x
setinverse <- function(inverse) inv_mx <<- inverse
getinverse <- function() inv_mx
list(set = set, get = get, setinverse= setinverse, getinverse = getinverse)
}
## Write a short comment describing this function
## Caching The Inverse of a Matrix:
## matrix inverse is a timely computation and caching the computation may be of some benefit if you calculate it a lot of times.
## This script creates a special object that the matrix and caches its inverse.
cacheSolve <- function(x, ...) {
## Return a matrix that is the inverse of 'x'
inv_mx <- x$getinverse()
if(!is.null(inv_mx)) {
message("getting cached data")
return(inv_mx)
}
data <- x$get()
inv_mx <- solve(data, ...)
x$setinverse(inv_mx)
inv_mx
}
<file_sep>/README.md
# P_Prog_Week-3-Assign-2
|
32930ebee639fa10dff7f2149a3fb19318473f54
|
[
"Markdown",
"R"
] | 2 |
R
|
Elguava/P_Prog_Week-3-Assign-2
|
dc81ddd2bfd0ae7765c18c854e86d589b16032de
|
b454ba2f58c9d0376f36cad304515411273ad062
|
refs/heads/master
|
<file_sep>package com.totnghiepluon.duancrm.Customers;
import android.os.Bundle;
import android.view.View;
import com.totnghiepluon.duancrm.Base.BaseFragment;
import com.totnghiepluon.duancrm.R;
public class CustomersFragment extends BaseFragment {
public static CustomersFragment createInstance() {
Bundle args = new Bundle();
CustomersFragment fragment = new CustomersFragment();
fragment.setArguments(args);
return fragment;
}
@Override
protected int getLayoutResource() {
return R.layout.fragment_customers;
}
@Override
protected void initVariables(Bundle savedInstanceState, View rootView) {
}
@Override
protected void initData(Bundle savedInstanceState) {
}
}
<file_sep>package com.totnghiepluon.duancrm.Labels;
import android.os.Bundle;
import android.view.View;
import com.totnghiepluon.duancrm.Base.BaseFragment;
import com.totnghiepluon.duancrm.R;
public class LabelsFragment extends BaseFragment {
public static LabelsFragment createInstance() {
Bundle args = new Bundle();
LabelsFragment fragment = new LabelsFragment();
fragment.setArguments(args);
return fragment;
}
@Override
protected int getLayoutResource() {
return R.layout.fragment_labels;
}
@Override
protected void initVariables(Bundle savedInstanceState, View rootView) {
}
@Override
protected void initData(Bundle savedInstanceState) {
}
}
<file_sep>package com.totnghiepluon.duancrm.Leads;
import android.os.Bundle;
import android.view.View;
import com.totnghiepluon.duancrm.Base.BaseFragment;
import com.totnghiepluon.duancrm.R;
public class LeadsFragment extends BaseFragment {
public static LeadsFragment createInstance() {
Bundle args = new Bundle();
LeadsFragment fragment = new LeadsFragment();
fragment.setArguments(args);
return fragment;
}
@Override
protected int getLayoutResource() {
return R.layout.fragment_leads;
}
@Override
protected void initVariables(Bundle savedInstanceState, View rootView) {
}
@Override
protected void initData(Bundle savedInstanceState) {
}
}
|
2f6bffb1476a4ed440608b7ff39775b77a2b47e9
|
[
"Java"
] | 3 |
Java
|
linhlq58/DuAnCRM
|
344e1f901c417a377590c569782ea6279be2c71c
|
b61f37b362409276831648456a34661dedbd28ca
|
refs/heads/master
|
<file_sep>#!/usr/bin/env python
try:
import mock
except Exception:
from unittest import mock
import straceexec
import glob
import os
import json
import pytest
class TestStrace:
def remove_test_files(self):
files = glob.glob('test_output*')
for output_file in files:
os.unlink(output_file)
try:
os.unlink("command.sh")
except OSError:
pass
@pytest.fixture(autouse=True)
def file_fixture(self):
self.remove_test_files()
self.datadir = os.path.dirname(os.path.abspath(__file__)) + '/data/'
yield
self.remove_test_files()
def test_execute_command(self):
command = {'command': '/bin/sh',
'args': ['sh', '-c', 'touch test_output'],
'env': os.environ,
'mode': 'execute'}
pid = os.fork()
if pid == 0:
straceexec.execute_command(command)
os.waitpid(pid, 0)
assert os.path.exists('test_output')
def test_execute_command_env(self):
env = os.environ
env['TEST_SUFFIX'] = 'foo'
command = {'command': '/bin/sh',
'args': ['sh', '-c', 'touch test_output$TEST_SUFFIX'],
'env': env,
'mode': 'execute'}
pid = os.fork()
if pid == 0:
straceexec.execute_command(command)
os.waitpid(pid, 0)
assert os.path.exists('test_outputfoo')
def test_execute_command_print_only(self):
command = {'command': '/bin/sh',
'args': ['sh', '-c', 'touch test_output'],
'env': os.environ, 'mode': 'print_only'}
# for now we ignore the actual output and just ensure that it doesn't
# run the command
with open("/dev/null", "w") as null_file:
with mock.patch('sys.stdout', null_file):
try:
straceexec.execute_command(command)
except SystemExit:
pass
assert not os.path.exists('test_output')
def test_execute_command_write_script(self):
command = {'command': '/bin/sh',
'args': ['sh', '-c', 'touch test_output'],
'env': os.environ, 'mode': 'write_script'}
try:
straceexec.execute_command(command)
except SystemExit:
pass
assert not os.path.exists('test_output')
assert os.path.exists('command.sh')
os.system("chmod a+x ./command.sh && ./command.sh")
assert os.path.exists('test_output')
def test_strace_parse(self):
with open(self.datadir + 'strace-1.log', 'r') as input_file:
commands = straceexec.collect_commands(input_file)
with open(self.datadir + 'strace-1.json', 'r') as json_file:
commands_expected = json.loads(json_file.read())
assert commands == commands_expected
def test_get_selection_simple(self):
with open(self.datadir + 'strace-1.json', 'r') as json_file:
commands = json.loads(json_file.read())
input_str = 'six.moves.input'
with mock.patch(input_str, return_value='4'):
command = straceexec.get_selection(commands)
with open(self.datadir + 'strace-1-cmd4.json', 'r') as json_result:
expected = json.loads(json_result.read())
assert command == expected
def test_get_selection_noenv(self):
with open(self.datadir + 'strace-1.json', 'r') as json_file:
commands = json.loads(json_file.read())
input_str = 'six.moves.input'
if "STRACE_TEST_ENV" in os.environ:
del os.environ["STRACE_TEST_ENV"]
with mock.patch(input_str, return_value="2n"):
command = straceexec.get_selection(commands)
with open(self.datadir + 'strace-1-cmd2n.json', 'r') as json_result:
expected = json.loads(json_result.read())
# os.environ is not good for comparison or conversion to json so we
# have to convert it into a dict here.
expected["env"] = {}
for key in os.environ:
expected["env"][key] = os.environ[key]
command_env = command["env"]
command["env"] = {}
for key in command_env:
command["env"][key] = command_env[key]
assert command == expected
assert "STRACE_TEST_ENV" not in command["env"]
def test_get_selection_print(self):
with open(self.datadir + 'strace-1.json', 'r') as json_file:
commands = json.loads(json_file.read())
input_str = 'six.moves.input'
with mock.patch(input_str, return_value="1p"):
command = straceexec.get_selection(commands)
with open(self.datadir + 'strace-1-cmd1p.json') as json_result:
expected = json.loads(json_result.read())
assert command == expected
def test_get_selection_script(self):
with open(self.datadir + 'strace-1.json', 'r') as json_file:
commands = json.loads(json_file.read())
input_str = 'six.moves.input'
with mock.patch(input_str, return_value="0s"):
command = straceexec.get_selection(commands)
with open(self.datadir + 'strace-1-cmd0s.json') as json_result:
expected = json.loads(json_result.read())
with open("1", "w") as f:
f.write(json.dumps(command))
assert command == expected
<file_sep>import setuptools
import os
with open(os.path.join(os.path.dirname(__file__), 'README.md')) as f:
long_description = f.read()
setuptools.setup(
name='straceexec',
version='1.1.1',
py_modules=['straceexec'],
entry_points={
'console_scripts': [
'straceexec = straceexec:main_func',
]
},
author='<NAME>',
author_email='<EMAIL>',
description='A tool for executing commands based on strace output',
long_description=long_description,
long_description_content_type='text/markdown',
url="https://github.com/dandedrick/straceexec",
classifiers=[
"License :: OSI Approved :: MIT License",
"Operating System :: POSIX :: Linux",
"Topic :: Utilities",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 3"
]
)
<file_sep>#!/usr/bin/env python
import os
import re
import sys
import six
def collect_commands(input_file):
commands = []
exec_line_re = re.compile(r'([0-9]+ |\[pid [0-9]+\] |)'
r' *execve\("([^"]*)", \[(.*)\], \[(.*)\]'
r'(\)| <unfinished \.\.\.>)*')
for line in input_file:
exec_match = exec_line_re.match(line)
if exec_match:
command = exec_match.group(2)
# We have to do some manipulation to remove the '"'s and ','s
# properly. We don't want to split arguments that contain , and "
# but we need to remove them to properly split and save away the
# arguments.
args = []
first = True
last_arg = None
for arg in exec_match.group(3).split('", "'):
arg = arg.encode().decode('unicode_escape')
if first:
arg = arg[1:]
first = False
if last_arg:
args.append(last_arg)
last_arg = arg
args.append(last_arg[:-1])
env = {}
first = True
last_var = None
for var in exec_match.group(4).split('", "'):
var = var.encode().decode('unicode_escape')
if first:
var = var[1:]
first = False
if last_var:
(key, value) = last_var.split("=", 1)
env[key] = value
last_var = var
(key, value) = last_var[:-1].split("=", 1)
env[key] = value
commands.append({"command": command, "args": args, "env": env})
return commands
def print_commands(commands):
index = 0
rows, columns = os.popen('stty size', 'r').read().split()
columns = int(columns)
for command in commands:
env_string = ""
for key, value in command['env'].items():
env_string = env_string + " " + key + "=" + value
line = "{}: {} -:ENV:-{}".format(index, " ".join(command["args"]),
env_string)
if columns < len(line):
line = line[:columns]
print(line)
index = index + 1
def get_selection(commands):
invalid_input = True
index = len(commands)
while invalid_input:
input_prompt = """Enter the number of the command you would like to execute
\tAppend an n to not copy the environment
\tAppend a p to print the full command and exit
\tAppend a g to run under gdb
\tAppend an s to write a script to execute the command
Select: """
selected = six.moves.input(input_prompt)
match = re.match(r'([0-9]+)([npgs]?)', selected)
if match:
command_index = int(match.group(1))
commands[command_index]["mode"] = "execute"
if match.group(2) == "n":
commands[command_index]["env"] = os.environ
elif match.group(2) == "p":
commands[command_index]["mode"] = "print_only"
elif match.group(2) == "g":
new_args = []
new_args.append("gdb")
new_args.append("-ex")
set_gdb_args = 'set args'
for arg in commands[command_index]["args"][1:]:
set_gdb_args = '{} "{}"'.format(set_gdb_args,
arg.replace('"', '\"'))
new_args.append(set_gdb_args)
for key, value in commands[command_index]['env'].items():
new_args.append("-ex")
new_args.append("set environment " + key + "=" + value)
new_args.append(commands[command_index]["command"])
commands[command_index]["command"] = "/usr/bin/gdb"
commands[command_index]["args"] = new_args
commands[command_index]["env"] = os.environ
elif match.group(2) == "s":
commands[command_index]["mode"] = "write_script"
if command_index < index:
invalid_input = False
else:
print("Invalid selection. The value must be less than " +
str(index) + ".")
else:
print("Invalid entry")
return commands[command_index]
def print_command(command):
print_args = ""
first = True
for arg in command["args"]:
if first:
print_args = arg
first = False
else:
print_args = print_args + " '" + arg.replace("'", "\\'") + "'"
env_string = ""
for key, value in command['env'].items():
env_string = env_string + key + "=" + value + "\n"
print("\nPATH:\n{}\n\nARGS:\n{}\n\nENV:\n{}".format(command["command"],
print_args,
env_string))
def write_script(command):
with open("command.sh", "w") as f:
f.write("#!/bin/sh\n")
f.write("env -i \\\n")
for key, value in command['env'].items():
f.write("'")
f.write(key)
f.write('=')
f.write(value.replace("'", "'\"'\"'"))
f.write("' \\\n")
for arg in command["args"]:
f.write("'")
f.write(arg.replace("'", "'\"'\"'"))
f.write("' ")
f.write("\n")
def execute_command(command):
if command["mode"] == 'print_only':
print_command(command)
sys.exit(0)
elif command["mode"] == 'write_script':
write_script(command)
sys.exit(0)
os.execve(command["command"], command["args"], command["env"])
def main_func():
if len(sys.argv) > 1:
input_file = open(sys.argv[1], "r")
else:
input_file = sys.stdin
commands = collect_commands(input_file)
print_commands(commands)
run_command = get_selection(commands)
execute_command(run_command)
if __name__ == "__main__":
main_func()
<file_sep># straceexec
[](https://github.com/dandedrick/straceexec/actions)
[](https://badge.fury.io/py/straceexec)
straceexec is a python script that allows for playback and analysis of
execve commands from strace logs. This is useful for debugging commands
embedded several layers deep with significant automated setup. One specific
use case would be debugging specific commands from a build system that setup
many environment variables or have complex command line invocations.
## Usage
```
# strace -f -v -s 10000 -o strace.log ninja
# straceexec strace.log
0: ninja -:ENV:- LANG=en_US.UTF-8 USERNAME=ddedrick SHELL=/bin/bash output=default GDM_LANG=en_US.UTF EDITOR=vimx PATH=/u
1: /bin/sh -c /usr/lib64/ccache/cc -Dfoo_EXPORTS -fPIC -MD -MT CMakeFiles/foo.dir/foo.c.o -MF CMakeFiles/foo.dir/foo.c.o
2: /usr/lib64/ccache/cc -Dfoo_EXPORTS -fPIC -MD -MT CMakeFiles/foo.dir/foo.c.o -MF CMakeFiles/foo.dir/foo.c.o.d -o CMakeF
3: /bin/sh -c : && /usr/lib64/ccache/cc -fPIC -shared -Wl,-soname,libfoo.so.0 -o libfoo.so.0.3.0 CMakeFiles/foo.dir/fo
4: /usr/lib64/ccache/cc -fPIC -shared -Wl,-soname,libfoo.so.0 -o libfoo.so.0.3.0 CMakeFiles/foo.dir/foo.c.o -:ENV:- LANG=
5: /usr/bin/cc -fPIC -shared -Wl,-soname,libfoo.so.0 -o libfoo.so.0.3.0 CMakeFiles/foo.dir/foo.c.o -:ENV:- LANG=en_US.UTF
6: /usr/libexec/gcc/x86_64-redhat-linux/8/collect2 -plugin /usr/libexec/gcc/x86_64-redhat-linux/8/liblto_plugin.so -plugi
7: /usr/bin/ld -plugin /usr/libexec/gcc/x86_64-redhat-linux/8/liblto_plugin.so -plugin-opt=/usr/libexec/gcc/x86_64-redhat
8: /bin/sh -c /usr/bin/cmake -E cmake_symlink_library libfoo.so.0.3.0 libfoo.so.0 libfoo.so && : -:ENV:- LANG=en_US.UTF-
9: /usr/bin/cmake -E cmake_symlink_library libfoo.so.0.3.0 libfoo.so.0 libfoo.so -:ENV:- LANG=en_US.UTF-8 USERNAME=ddedri
Enter the number of the command you would like to execute
Append an n to not copy the environment
Append a p to print the full command and exit
Append a g to run under gdb
Select: 1
```
strace output should be collected with -v to ensure that arguments are not
left off and -s with a sufficiently large size so that they are not
truncated.
By default the command will be run and will have the same environment setup
as is found in the strace output. Several options are available for
modifying this behavior. Appending an ```n``` will use the current
environment instead of the one present in the strace log. Appending a
```p``` will not exec the command but instead print it in full along with
its environment. Appending a ```g``` will start start up gdb with the
executable, arguments, and environment already setup. Appending an ```s``` will
generate a script named command.sh that will set the environment and run the
the command.
## Contributing
Contributions, issues, and feature requests are welcome. Feel free to open
pull requests or issues as needed.
## Author
Written by <NAME> to simplify isolating, reproducing and tweaking build
system issues.
## License
straceexec is distributed under the MIT license. See the included LICENSE
file for details.
|
663d066231cadf1069442cd28701df9c9c1e86c8
|
[
"Markdown",
"Python"
] | 4 |
Python
|
dandedrick/straceexec
|
31eb5753d94ea15562c5048580df9d1ebe262c81
|
e5b85ed140680856814d9c45ced52eb6275e9d2c
|
refs/heads/master
|
<file_sep>#!/usr/bin/env python
#
import errno
import feedparser
import hashlib
import itertools
import logging
import optparse
import os
import re
import string
import sys
import threading
import time
import urllib
import xml.dom.minidom
logging.basicConfig(level=logging.WARNING,
format='[%(levelname)s:%(threadName)s] %(message)s')
tfmt = '%Y-%m-%dT%H:%M:%S'
cfg_base = os.path.join(os.path.expanduser('~'), '.plogaster')
cfg_file = cfg_base + '.xml' # default, could be changed by --config option
cfg_temp = cfg_base + '.tmp'
cfg_lock = threading.RLock()
class ExceptionKillThread(StandardError):
pass
def mkdir_p(path):
try:
os.makedirs(path)
except OSError as e:
if e.errno == errno.EEXIST:
pass
else:
raise
def hashfile(filename):
with open(filename, 'rb') as f:
return hashlib.sha1(f.read()).hexdigest()
def get_mp3_link(links):
for l in links:
url = l.get('href')
type = l.get('type')
if type == 'audio/mpeg':
return url
return None
def cfg_get_node(node, tag):
return node.getElementsByTagName(tag)[0].firstChild
def cfg_get_data(node, tag):
return cfg_get_node(node, tag).data
def safe_name(name):
ok_char = string.letters + string.digits
return ''.join(c if c in ok_char else '_' for c in name)
def isactive(t):
t.join(0.5)
return t.isAlive()
def wait_for_threads(threads, event_quit):
try:
while len(threads) > 0:
threads[:] = itertools.ifilter(isactive, threads)
except KeyboardInterrupt:
logging.info('aborting')
event_quit.set()
def get_feed_links_to_download(feed, update_after, dirs, default_dir, reverse):
link_info = [] # all links from the feed
link_group = [] # links with the same timestamp
prev_updated = None
for entry in feed.entries:
# get and parse timestamp for this feed entry
updated_parsed = time.strptime(time.strftime(tfmt,
entry.updated_parsed), tfmt)
# bail out as soon as we hit an entry that isn't newer than our most
# recent update
if updated_parsed > update_after:
# make sure the link is an MP3
mp3_link = get_mp3_link(entry.links)
if not mp3_link:
continue
# check for custom output directory
outdir = None
for d in dirs:
if re.search(d.getAttribute('match'), entry.title):
outdir = d.firstChild.data
break
if not outdir:
outdir = default_dir
# if the update timestamp is not in the current group, flush the
# link group
if updated_parsed != prev_updated:
if reverse:
link_group.reverse()
link_info.extend(link_group)
link_group = []
prev_updated = updated_parsed
# add this link to the temporary link group
link_group.append((updated_parsed,
entry.title,
mp3_link,
outdir))
else:
break
# flush any remaining link group
if link_group:
if reverse:
link_group.reverse()
link_info.extend(link_group)
# reverse list of links so they are numbered from oldest to newest
link_info.reverse()
return link_info
def get_all_links_to_download(cfg, event_quit):
link_info = []
default_dir = cfg_get_data(cfg, 'default_dir')
event_done = threading.Event()
bytes_received = {}
def progress_thread():
while True:
msg = '\rDownloading feed XML: %d KB' % (
sum(bytes_received.values()) / 1024)
sys.stdout.write(msg)
sys.stdout.flush()
if event_done.wait(0.25):
sys.stdout.write(msg + '\n')
sys.stdout.flush()
break
def worker(cast, nick):
def url_progress(block_count, block_size, total_size):
if event_quit.isSet():
# kill the thread
raise ExceptionKillThread()
bytes_received[nick] = block_count * block_size
with cfg_lock:
url = cfg_get_data(cast, 'url')
name = cfg_get_data(cast, 'name')
reverse = len(cast.getElementsByTagName('reverse_order')) > 0
try:
logging.debug('%-8s getting links' % nick)
# get feed XML and parse it
feed_xml = nick + '.xml'
urllib.urlretrieve(url, feed_xml, url_progress)
feed = feedparser.parse(feed_xml)
with cfg_lock:
# determine time of last successful download from feed
update_after_node = cfg_get_node(cast, 'update_after')
update_after = time.strptime(update_after_node.data, tfmt)
# get new links in feed
links = get_feed_links_to_download(feed, update_after,
cast.getElementsByTagName('dir'), default_dir, reverse)
if len(links) > 0:
link_info.append((links, name, nick,
update_after_node, cast))
logging.info('%-8s got %d links' % (nick, len(links)))
except ExceptionKillThread:
logging.info('aborted %s' % feed_xml)
os.unlink(feed_xml)
threads = []
for cast in cfg.getElementsByTagName('cast'):
with cfg_lock:
nick = (cfg_get_data(cast, 'nick') + 8 * '_')[:8]
t = threading.Thread(name=nick, target=worker, args=(cast, nick))
threads.append(t)
t.start()
p = threading.Thread(name='progress', target=progress_thread)
p.start()
wait_for_threads(threads, event_quit)
event_done.set()
return link_info
def next_counter(cfg):
with cfg_lock:
node = cfg_get_node(cfg, 'counter')
value = int(node.data)
node.data = str(value+1)
with open(cfg_temp, 'w') as f:
f.write(cfg.toxml())
os.rename(cfg_temp, cfg_file)
return value
def download_links(cfg, link_info, event_quit):
base_dir = cfg_get_data(cfg, 'base_dir')
# default maximum number of checksums to keep
max_history = 25
max_history_nodes = cfg.getElementsByTagName('max_history')
if max_history_nodes:
max_history_text = max_history_nodes[0].firstChild
if max_history_text:
max_history = int(max_history_text.data)
event_done = threading.Event()
console_lock = threading.RLock()
progress_data = {}
def progress_thread():
while True:
# single-line output
msg = ' '.join('%d/%d:%s' % (d['link'], d['links'],
'?' if d['total'] in (0,-1) else
'%02d' % min(99, (100 * d['data'] / d['total'])))
for n, d in progress_data.iteritems() if not d['done'])
with console_lock:
sys.stdout.write((msg + 78 * ' ')[:78] + '\r')
sys.stdout.flush()
if event_done.wait(0.25):
with console_lock:
print
break
def worker(cast):
links, name, nick, update_after_node, cast_node = cast
dups = 0
try:
for i, link in enumerate(links):
def url_progress(block_count, block_size, total_size):
if event_quit.isSet():
# kill the thread
raise ExceptionKillThread()
progress_data[nick] = {
'data' : block_count * block_size,
'total' : total_size,
'link' : i + 1,
'links' : len(links),
'done' : False,
}
# get feed timestamp for this link
update_after = time.strftime(tfmt, link[0])
# create a unique filename for the file to download
safe_title = '%05d_%s_%s.mp3' % (next_counter(cfg), nick,
safe_name(link[1]))
outdir = os.path.join(base_dir, link[3])
outfile = os.path.join(outdir, safe_title)
mkdir_p(outdir)
# download the file
url = link[2]
logging.debug('GET %s' % url)
urllib.urlretrieve(url, outfile, url_progress)
# handle zero-length files
if os.path.getsize(outfile) == 0:
# try again on zero-size file
logging.warning('0 KB file, retrying download')
urllib.urlretrieve(url, outfile, url_progress)
if os.path.getsize(outfile) == 0:
# after second try, bail out
logging.error('download failed')
i -= 1
break
# set filesystem timestamp on downloaded file
timestamp = time.mktime(link[0])
os.utime(outfile, (timestamp, timestamp))
# determine checksum of downloaded file
file_checksum = hashfile(outfile)
# update config data for this feed
with cfg_lock:
# set time of last successful download
update_after_node.data = update_after
# get checksums of previous downloads
history_nodes = cast_node.getElementsByTagName('history')
if history_nodes:
history_node = history_nodes[0]
else:
history_node = cast_node.appendChild(
cfg.createElement('history'))
checksums = history_node.getElementsByTagName('checksum')
# remove the downloaded file if it's a duplicate, otherwise
# record the checksum of the new file
for checksum in checksums:
if checksum.firstChild.data == file_checksum:
# duplicate
logging.info('DUP %s %s' % (file_checksum, link[1]))
os.unlink(outfile)
dups += 1
break
else:
# new file
logging.info('GOT %s %s' % (file_checksum, link[1]))
# add its checksum to the history
checksum_node = history_node.appendChild(
cfg.createElement('checksum'))
checksum_node.appendChild(
cfg.createTextNode(file_checksum))
# purge older checksums if history list is too long
while len(history_node.childNodes) > max_history:
logging.info('PURGE %s' % cfg_get_data(
history_node, 'checksum'))
history_node.removeChild(
history_node.firstChild).unlink()
# Write config to temp file, then commit change to original
with open(cfg_temp, 'w') as f:
f.write(cfg.toxml())
os.rename(cfg_temp, cfg_file)
# update progress meter
progress_data[nick]['done'] = True
msg = '%s got %d' % (nick, i + 1 - dups)
if dups:
msg += ', %d dups' % dups
with console_lock:
print (msg + 78 * ' ')[:78]
except ExceptionKillThread:
os.unlink(outfile)
logging.info('aborted %s' % outfile)
# launch a worker thread for each feed that has updates and another thread
# to monitor progress
threads = []
for cast in link_info:
t = threading.Thread(name=cast[2], target=worker, args=(cast,))
threads.append(t)
t.start()
p = threading.Thread(name='progress', target=progress_thread)
p.start()
wait_for_threads(threads, event_quit)
event_done.set()
def main():
# process command line
parser = optparse.OptionParser()
parser.add_option("-c", "--config")
options, args = parser.parse_args()
# parse config XML
global cfg_file
if options.config:
cfg_file = options.config
try:
cfg = xml.dom.minidom.parse(cfg_file)
except IOError, e:
parser.error('Could not open configuration file: %s' % cfg_file)
event_quit = threading.Event()
link_info = get_all_links_to_download(cfg, event_quit)
if not event_quit.isSet():
download_links(cfg, link_info, event_quit)
if __name__ == '__main__':
main()
<file_sep>plogaster
=========
Simple podcast downloader
|
20fd3ae50ac2c3587d4e1519584fcb13162b8be3
|
[
"Markdown",
"Python"
] | 2 |
Python
|
damonws/plogaster
|
908c4cfbbc1188b6d102c7e3524a988258812b51
|
e55410ac7d2e52066cdbab4ea4569cb314599044
|
refs/heads/master
|
<file_sep>class Appointment < ApplicationRecord
belongs_to :user
belongs_to :lesson
validates :start_time, presence: true
end
<file_sep># This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
Appointment.delete_all
Lesson.delete_all
User.delete_all
puts "Deleted all the past data"
test_url = "https://kitt.lewagon.com/placeholder/users/takumamatata"
test_user= User.new(email: "<EMAIL>", password: "<PASSWORD>", first_name: "Takuma", last_name: "Naruke")
test_user.remote_photo_url = test_url
test_user.save
20.times do
url = "https://kitt.lewagon.com/placeholder/users/random"
user_new = User.new(email: Faker::Internet.email, password: "<PASSWORD>", first_name: Faker::HarryPotter.character.split[0], last_name: Faker::HarryPotter.character.split[1])
user_new.remote_photo_url = url
user_new.save
end
puts "Created #{User.count} users"
languages = ["English", "Japanese", "French"]
level = ["Novice", "Conversational", "Business", "Fluent"]
location = ["Meguro, Tokyo", "Shibuya, Tokyo", "Yokohama, Kanagawa"]
duration = [40, 60, 90]
price = [2000, 3000, 5000]
50.times do
Lesson.create(language: languages.sample, user_id: User.all.sample.id, duration: duration.sample, price: price.sample, level: level.sample, location: location.sample)
end
puts "Created #{Lesson.count} lessons"
50.times do
lesson = Lesson.all.sample
appointment = Appointment.new(user_id: User.all.sample.id, lesson_id: lesson.id, start_time: Faker::Time.forward(30, :day))
if appointment.user != lesson.user
appointment.save
end
end
puts "Created #{Appointment.count} appointments"
<file_sep>class RemoveLocationFromAppointments < ActiveRecord::Migration[5.2]
def change
remove_column :appointments, :location
add_column :lessons, :location, :string
end
end
<file_sep>Rails.application.routes.draw do
root to: 'lessons#index'
devise_for :users
resources :users, only: [:show]
resources :lessons do
resources :appointments, shallow: true
end
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
<file_sep>// import swal from 'sweetalert';
// function bindSweetAlertButtonDemo() {
// const swalButton = document.getElementById('sweet-alert-demo');
// if (swalButton) { // protect other pages
// swalButton.addEventListener('click', () => {
// swal({
// title: "A nice alert",
// text: "This is a great alert, isn't it?",
// icon: "success"
// });
// });
// }
// }
// export { bindSweetAlertButtonDemo };
import Typed from 'typed.js';
function loadDynamicBannerText() {
new Typed('#banner-typed-text', {
strings: ["Find your perfect lesson"],
typeSpeed: 40,
loop: true
});
}
export { loadDynamicBannerText };
<file_sep>class Lesson < ApplicationRecord
include PgSearch
pg_search_scope :search_by_location_and_language,
against: [ :location, :language ],
using: {
tsearch: { prefix: true } # <-- now `superman batm` will return something!
}
belongs_to :user
has_many :appointments
validates :language, inclusion: { in: ["English", "Japanese", "French"]}
validates :level, inclusion: { in: ["Novice", "Conversational", "Business", "Fluent"]}
validates :price, presence: true, numericality: { only_integer: true }
validates :duration, inclusion: {in: [40, 60, 90]}
geocoded_by :location
after_validation :geocode, if: :will_save_change_to_location?
end
<file_sep>//= require rails-ujs
//= require_tree .
//= require jquery
//= require jquery_ujs
//= require sweetalert2
//= require sweet-alert2-rails
window.sweetAlertConfirmConfig = {
type: 'warning',
text: 'hello there!!',
showCancelButton: true,
confirmButtonColor: '#50C978',
confirmButtonText: 'Open class!'
};
<file_sep>class LessonsController < ApplicationController
skip_before_action :authenticate_user!, only: [:index, :show]
def index
unless params[:query]
@lessons = Lesson.all
else
@lessons = Lesson.search_by_location_and_language(params[:query])
end
authorize @lessons
end
def show
find_lesson
@markers = [{
lat: @lesson.latitude,
lng: @lesson.longitude#,
# infoWindow: { content: render_to_string(partial: "/lessons/map_box", locals: { lesson: lesson }) }
}]
end
def new
@lesson = Lesson.new
authorize @lesson
end
def create
@lesson = Lesson.new(lesson_params)
@lesson.user = current_user
authorize @lesson
if @lesson.save
redirect_to lesson_path(@lesson)
else
render :new
end
end
def edit
find_lesson
end
def update
find_lesson
@lesson = Lesson.update(lesson_params)
if @lesson.save
redirect_to user_lesson_path(@user)
else
render :new
end
end
private
def find_lesson
@lesson = Lesson.find(params[:id])
authorize @lesson
end
def lesson_params
params.require(:lesson).permit(:language, :level, :description, :duration, :price, :location)
end
end
<file_sep>class UsersController < ApplicationController
# def index
# @users = User.all
# end
def show
@user = current_user
@appointments = current_user.appointments
# @teaching_appointments = current_user.lessons.appointments
@teaching_appointments = current_user.lessons.map{ |lesson| lesson.appointments }.flatten
end
# def edit
# find_user
# end
# def update
# find_user
# @user = User.update(user_params)
# redirect_to user_path(@user)
# end
# private
# def user_params
# params.require(:user).permit(:first_name, :last_name, :email, :password, :photo)
# end
# def find_user
# @user = current_user
# @usser = User.find(params[])
# end
end
|
60d3b8bb19c56a5d30566cbb57dea6f65ae2d38a
|
[
"JavaScript",
"Ruby"
] | 9 |
Ruby
|
KazeIU/teachme
|
b9a49dea620658ad44c212b7874f1e343a204af3
|
cee23e16f4cefe8f9a34d18659258a2dea2955ea
|
refs/heads/master
|
<repo_name>Ramsabarish123/Wishes<file_sep>/README.md
# Wishes
docker-compose.yaml is the base file to start the project.
Excecute this file using follwing commands:
docker-compose up --build mysql
docker-compose up --build app
If we execute above commands two services mysql,app will get started in differnet containers.
see the Docker-compose.yaml
In one container mysql database will be running and in another python3 will be running with all dependencies.
see the Dockerfile1 and Dockerfile2
These two containers will communicate and send mails to the respective person who has birthday today.
<file_sep>/docker-compose.yaml
version: '2'
services:
mysql:
build:
dockerfile: Dockerfile2
context: .
app:
build:
dockerfile: Dockerfile1
context: .
depends_on:
- mysql
links:
- mysql<file_sep>/Pythonfile1.py
import os,mysql.connector,smtplib,datetime,random
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEBase import MIMEBase
from email import encoders
mydb = mysql.connector.connect(host="mysql",user="root",passwd="",port="3306")
mycursor = mydb.cursor()
mycursor.execute("CREATE DATABASE Birthday")
mycursor.execute("CREATE TABLE Birthday.Employees (id INTEGER, name VARCHAR(255), gmail VARCHAR(255), birthdate VARCHAR(10))")
sql = "INSERT INTO Birthday.Employees (id, name, gmail, birthdate) VALUES (%s, %s, %s, %s)"
val = ("1", "sabarish", "<EMAIL>", "6/12")
mycursor.execute(sql, val)
#sql2 = "INSERT INTO Birthday.Employees (id, name, gmail, birthdate) VALUES (%s, %s, %s, %s)"
#val2 = ("3", "Madhu", "<EMAIL>", "2018-11-2")
#mycursor.execute(sql2, val2)
#sql3 = "INSERT INTO Birthday.Employees (id, name, gmail, birthdate) VALUES (%s, %s, %s, %s)"
#val3 = ("4", "Rohini", "<EMAIL>", "10/1") #--10/01/1996
#mycursor.execute(sql3, val3)
#sql4 = "INSERT INTO Birthday.Employees (id, name, gmail, birthdate) VALUES (%s, %s, %s, %s)"
#val4 = ("5", "Rohini", "<EMAIL>", "17/6") #---17/06/1997
#mycursor.execute(sql4, val4)
#sql4 = "INSERT INTO Birthday.Employees (id, name, gmail, birthdate) VALUES (%s, %s, %s, %s)"
#val4 = ("5", "Rohini", "<EMAIL>", "6/11") #---17/06/1997
#mycursor.execute(sql4, val4)
mydb.commit()
mycursor.execute("SELECT * FROM Birthday.Employees")
myresult = mycursor.fetchall()
print("hello dude")
print(myresult)
today = datetime.datetime.now()
print(today)
fromaddr = "<EMAIL>"
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['Subject'] = "Happy Birthday"
wishes_list=['Wishing you the most joyous Bday!. May this and every day of the year be special, magical and unforgettable!',
'Let yourself do everything that you like most in life, may your Big Day be cheerful and happy!',
'May the angels watch over you and bring you peace on your special day and every day',
'Congratulations on your bday! Wishing you joy, success and happiness in life! Hoping you make the most of your big day today!']
body = random.choice(wishes_list)
print(body)
msg.attach(MIMEText(body, 'plain'))
image_list = ['HappyBirthday.jpg', 'HappieBirthday.jpg', 'HapyBirthday.jpg', 'BirthdayWishes.jpg', 'BirthdayWish.jpg','Wishes.jpg','wish.jpg','happyWishes.jpg',"wish1.jpg","wish2.jpg","wish3.jpg","wish4.jpg","wish5.jpg","wish6.jpg","wish7.jpg","wish8.jpg","wish10.jpg","wish11.jpg","wish12.jpg","wish13.jpg","wish14.jpg"]
filename = random.choice(image_list)
print(filename)
attachment = open("./"+filename, "rb")
part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % filename)
msg.attach(part)
server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server.login(fromaddr, "<PASSWORD>")
formatdate=str(today.day)+"/"+str(today.month)
print(formatdate)
for x in myresult:
print(x[3])
if(x[3]==formatdate):
msg['To'] = x[2]
server.sendmail(fromaddr,x[2], msg.as_string())
print(x[3])
server.quit()
|
0e7a810cd2afb1f0f619b8158ffbb38accc7afb3
|
[
"Markdown",
"Python",
"YAML"
] | 3 |
Markdown
|
Ramsabarish123/Wishes
|
0a2c6790594c470312aa20cf92665ca4f8e34be7
|
d6546b57e56fdf589b6b829b426d4d0f7995f733
|
refs/heads/master
|
<file_sep># get_data.py
import requests
import json
print("REQUESTING SOME DATA FROM THE INTERNET...")
#----- part 1 --------
request_url = "https://raw.githubusercontent.com/prof-rossetti/intro-to-python/master/data/products/2.json"
response = requests.get(request_url)
response_data = json.loads(response.text)
print(response_data['department'],":",response_data['name'],",$",response_data['price'])
#------- part 2 -------
request2_url = "https://raw.githubusercontent.com/prof-rossetti/intro-to-python/master/data/products.json"
response = requests.get(request_url)
response_data = json.loads(response.text)
for x in response_data2:
print(x["id"], x["name"]
# ---------
|
40a1602f912c01930e62b1da53fbf486917fd1f9
|
[
"Python"
] | 1 |
Python
|
alexkuvshinoff/web-requests-exercise
|
bf35ef9a3ceb6785e26d8c1bf029ec1ad66b1ee7
|
1a24c3edbddff90ae8a27136b11863b8f6cc2c33
|
refs/heads/master
|
<file_sep># -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
#'docker run --rm -p 8888:8888 \
# rpy2/rpy2:2.8.x
import csv
import pandas as pd
import numpy as np
import matplotlib.pylab as plt
from statsmodels.tsa.arima_model import ARIMA
from statsmodels.tsa.arima_model import ARIMAResults
from statsmodels.tsa.stattools import adfuller
#If R starts working here, then do apply these
#import rpy2 as rp
#import rpy2.objects as robj
#from robj.packages import importr as impr
#base = impr('base')
#utils = impr('utils')
#Set up of dictionaries and equities
inteq = 'GLD'
hedge = 'INTC'
mktBIC = {}
hedgeBIC = {}
equitypath = 'C:/Users/Nikita/Documents/Trading-Strategy/'
toteq = equitypath + inteq +'.csv'
def csvset(file):
global p_log
datemake = lambda dates: pd.datetime.strptime(dates, '%m/%d/%Y')
daten = pd.read_csv(file, parse_dates=True, index_col='Date',date_parser=datemake)
# ADD BRACKETS AFTER ADJ CLOSE FOR CHOOSING YOUR SAMPLE
p = daten['Adj Close'][1:60]
p_log = np.log(p)
#Dickey-Fuller to test for stationarity
def acfpacfdf(data):
global dftest
global d
dftest = float(adfuller(data)[1])
if dftest > float(0.05):
d = 1
else:
d = 0
#Multi-Use automatically choosing the best BIC
def bestBIC(bic):
global min_BIC
min_BIC = min(bic, key=bic.get)
#Allocating the Best ARIMA
def bestarima(model):
global bestmodel
if str(model[0:1]) == "AR":
a = int(model[4])
m = 0
else:
a = 0
m = int(model[4])
model = ARIMA(p_log, order=(a,d,m))
bestmodel = model.fit(disp=-1)
#ARIMA Function
def arimaTest(l_eq):
for i in range(1,6):
ar = ARIMA(l_eq, order=(i,d,0))
arfit = ar.fit(disp=-1)
arresults = ARIMAResults.bic(arfit)
mktBIC["AR (" + str(i) + ")"] = arresults
for i in range(1,6):
ma = ARIMA(l_eq, order=(0,d,i))
mafit = ma.fit(disp=-1)
maresults = ARIMAResults.bic(mafit)
mktBIC["MA (" + str(i) + ")"] = maresults
def predict(model):
global fore
fore = model.predict(1,100)
def archTest(l_eq):
pass
#for i in range(1,len(['Date'])):
csvset(toteq)
acfpacfdf(p_log)
arimaTest(p_log)
bestBIC(mktBIC)
bestarima(min_BIC)
print (min_BIC)
plt.plot(p_log - p_log.shift())
plt.plot(bestmodel.fittedvalues, color='red')
predict(bestmodel)
print (fore[100])
#eqpredict = pd.Series(bestmodel.fittedvalues, copy=True)
#print (eqpredict.head())<file_sep># -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
import pandas as pd
import numpy as np
import matplotlib.pylab as plt
from statsmodels.tsa.arima_model import ARIMA
from statsmodels.tsa.arima_model import ARIMAResults
#Set up of dictionaries and equity iteration
mktBIC = {}
hedgeBIC = {}
mktequity = 'C:/Users/Nikita/Documents/FDP/ADSK.csv'
hedgeequity = 'C:/Users/Nikita/Documents/FDP/INTC.csv'
datemake = lambda dates: pd.datetime.strptime(dates, '%m/%d/%Y')
daten = pd.read_csv(mktequity, parse_dates=True, index_col='Date',date_parser=datemake)
p = daten['Adj Close']
p_log = np.log(p)
plt.plot(p_log)
def arimaTest(l_eq):
for i in range(1,6):
ar = ARIMA(l_eq, order=(i,1,0))
arfit = ar.fit(disp=-1)
arresults = ARIMAResults.bic(arfit)
mktBIC["AR(" + str(i) + ")"] = arresults
for i in range(1,6):
ma = ARIMA(l_eq, order=(0,1,i))
mafit = ma.fit(disp=-1)
maresults = ARIMAResults.bic(mafit)
mktBIC["MA(" + str(i) + ")"] = maresults
#bestARIMA = min(mktBIC, key=mktBIC.get)
arimaTest(p_log)
#print bestARIMA
print mktBIC<file_sep># Trading-
A start into Algo Trading.
|
217532c06e87579fd7273c82889e58a120bd6cb5
|
[
"Markdown",
"Python"
] | 3 |
Python
|
davinci07/Trading-
|
7fe4024a35200d7685ed7c20f48779e0e5a6a298
|
2a13a3fcf6dcb74500aba52ebbf8da93542b29ae
|
refs/heads/master
|
<file_sep>#!/bin/python
from . import API
from . import dataset
from . import backtest
<file_sep>#!/bin/python
#from subprocess import run
from subprocess import Popen, PIPE
import random
from copy import deepcopy
import operator
from functools import reduce
from urllib import request, parse
import json
import requests
import datetime
import os
gekkoDIR = 'TBD'
def firePaperTrader(GekkoInstanceUrl, TradeSetting, Exchange, Currency, Asset):
TradeMethod = list(TradeSetting.keys())[0]
true = True
false= False
CONFIG = {
"market":{
"type":"leech",
"from":"2017-09-13T15:42:00Z" # TIME ATM;
},
"mode":"realtime",
"watch":{
"exchange": Exchange,
"currency": Currency,
"asset": Asset
},
"tradingAdvisor":{
"enabled":true,
"method":TradeMethod,
"candleSize":60,
"historySize":10},
TradeMethod: TradeSetting[TradeMethod],
"paperTrader":{
"fee":0.25,
"slippage":0.05,
"simulationBalance":{
"asset":1,
"currency":100
},
"reportRoundtrips":true,
"enabled":true
},
"candleWriter":{
"enabled":true,
"adapter":"sqlite"
},
"type":
"paper trader",
"performanceAnalyzer":{
"riskFreeReturn":2,
"enabled":true},
"valid":true
}
RESULT = httpPost(URL,CONFIG)
print(RESULT)
<file_sep>#!/bin/python
import promoterz
import evaluation
def showDatasetSpecifications(specs):
message = "%s/%s @%s" % (specs["asset"],
specs["currency"],
specs["exchange"])
return message
def dateRangeToText(dateRange):
Range = [ evaluation.gekko.dataset.epochToString(dateRange[x])\
for x in ['from', 'to'] ]
Text = "%s to %s" % (Range[0], Range[1])
return Text
def parseDatasetInfo(purpose, candlestickDataset):
textdaterange = dateRangeToText(candlestickDataset.daterange)
print()
Text = "\n%s candlestick dataset %s\n" % (purpose,
textdaterange)
Text+= showDatasetSpecifications(candlestickDataset.specifications) + '\n'
return Text
|
008cef1271d91b7861029e4405c167125c463f40
|
[
"Python"
] | 3 |
Python
|
donkykong017/japonicus
|
27765d659095bba3024d82cee8a820a103cb3b66
|
aac550139a67b0c70a6671ca02669d02a0204982
|
refs/heads/master
|
<repo_name>Keerthi-143/Telecom<file_sep>/plans.php
<html>
<head>
<title><center>Post Paid Plans</center></title>
</head>
<?php
<body>
<form><input type="text" value="plans.php">
Plan Name:<input type="text" name="plan name">
Monthly Rental:<input type="text" name="monthly rental">
Free Internet:<input type="text" name="free internet">
Free Calls:<input type="text" name="free internet">
Free SMSs:<input type="text" name="free smss">
Call Charges:<input type="text" name="call charges">
SMS Charges:<input type="text" name="sms charges">
Data Charges:<input type="text" name="data charges">
Roaming Charges:<input type="text" name="roaming charges">
<input type="submit" value="add">
</form>
?>
</body>
</html>
<file_sep>/telecom.php
<html>
<head>
<title>Telecom Operator Apllication</title>
</head>
<?php
<body>
<input type="button" value="prepaid" ClickOn="plan.php">
<input type="button" value="postpaid" ClickOn="plans.php">
<input type="submit" value="add">
?>
</body>
</html>
|
d9ee18cacf3a8887d8e47b9736e8ac529c11474a
|
[
"PHP"
] | 2 |
PHP
|
Keerthi-143/Telecom
|
9f3d9d98e9366846edcf369a147d9e7348f7e8ec
|
ab7d02af4fd7b10c72c79cbf8447a160fdfe5111
|
refs/heads/master
|
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package davidchavesmultiagent.psoalgorithm;
import java.util.ArrayList;
import java.util.Comparator;
/**
*
* @author DavidChaves
*/
public class Particle implements Comparator<Particle>{
private ArrayList<Integer> data;
private double distance;
private double best;
private double velocity;
public Particle(){
data = new ArrayList<>();
this.distance = 0;
this.velocity = 0;
this.best=0;
}
public ArrayList<Integer> getData(){
return this.data;
}
public void setData(ArrayList<Integer> data){
this.data = (ArrayList<Integer>)data.clone();
}
public double getDistance(){
return this.distance;
}
public void setDistance(double distance){
this.distance = distance;
this.setBest(distance);
}
public double getVelocity(){
return this.velocity;
}
public void setVelocity(double velocity){
this.velocity = velocity;
}
public double getBest() {
return best;
}
public void setBest(double best) {
if(best<this.best || this.best==0)
this.best = best;
}
@Override
public int compare(Particle p1, Particle p2){
if(p1.getBest()<p2.getBest())
return -1;
else if(p1.getBest()>p2.getBest())
return 1;
else
return 0;
}
}
<file_sep>package davidchavesmultiagent.psoalgorithm;
import static sim.engine.SimState.doLoop;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author DavidChaves
*/
public class main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
PSO pso = new PSO(System.currentTimeMillis());
pso.start();
do{
if (!pso.schedule.step(pso))
break;
}while(pso.schedule.getSteps()<30000);
pso.finish();
System.exit(0);
}
}
|
bffadffc005b0f6ea9652bd53be903cd78da50bd
|
[
"Java"
] | 2 |
Java
|
dachafra/TSPpso
|
275ce4197c70cc97586be1b278db629d97c480d2
|
24b2e435ebbd6ca59db3226ecb02314d8b991cf6
|
refs/heads/master
|
<file_sep># Overlay It Plugin
~Current Version:1.0~
Author: <a href="http://github.com/joshhannan"><NAME></a>
This is a WordPress plugin that shows an Overlay Popup as desired.<file_sep><?php
/*
<a href="http://test.com"><img src="http://placehold.it/500x500" /></a>
Plugin Name: IP Overlay Plugin
Plugin URI: https://github.com/joshhannan/ip-overlay-it-plugin
Description: Plugin that shows an Overlay Popup
Version: 1.0.0
Author: <a href="http://github.com/joshhannan"><NAME></a>
Author URI: http://www.inverseparadox.com
*/
/*======================================================================
AUTHORIZE PLUGIN UPDATES
======================================================================*/
add_action( 'init', 'github_plugin_updater_ip_overlay_init' );
function github_plugin_updater_ip_overlay_init() {
include_once('updater.php');
define( 'WP_GITHUB_FORCE_UPDATE', true );
if ( is_admin() ) {
// note the use of is_admin() to double check that this is happening in the admin
$config = array(
'slug' => 'ip-overlay-plugin/index.php',
'proper_folder_name' => 'ip-overlay-plugin',
'api_url' => 'https://api.github.com/repos/joshhannan/ip-overlay-plugin',
'raw_url' => 'https://raw.github.com/joshhannan/ip-overlay-plugin/master',
'github_url' => 'https://github.com/joshhannan/ip-overlay-plugin',
'zip_url' => 'https://github.com/joshhannan/ip-overlay-plugin/archive/master.zip',
'sslverify' => true,
'requires' => '3.0',
'tested' => '4.7',
'readme' => 'README.md',
'access_token' => '',
);
new WP_GitHub_Updater_IP_Overlay( $config );
}
}
/*======================================================================
INIT
======================================================================*/
$ip_overlay = new ip_overlay();
add_action( 'wp_footer', [ $ip_overlay, 'ip_overlay_check' ], 1 );
add_action('wp_enqueue_scripts', [ $ip_overlay, 'ip_overlay_scripts_styles'] );
class ip_overlay {
function __construct() {
add_action( 'admin_menu', array( $this, 'admin_menu' ) );
}
function admin_menu () {
add_options_page( 'IP Overlay Settings', 'IP Overlay Settings', 'manage_options', 'ip-overlay-plugin', array( $this, 'ip_overlay_plugin_page' ) );
}
function ip_register_overlay_settings() {
register_setting( 'ip_overlay_settings', 'ip_overlay_display' );
register_setting( 'ip_overlay_settings', 'ip_overlay_content_editor' );
}
function ip_overlay_plugin_page() {
// Set Defaults
$ip_overlay_settings_defaults = array(
'ip_overlay_display' => 'false',
'ip_overlay_content_editor' => '',
'ip_overlay_locations' => ''
);
$options = wp_parse_args( get_option( 'ip_overlay_settings' ), $ip_overlay_settings_defaults );
update_option( 'ip_overlay_settings', $options );
$ip_overlay_settings = get_option('ip_overlay_settings');
if( $_POST['update_settings'] === 'Y' ) {
$ip_overlay_settings['ip_overlay_display'] = $_POST['ip_overlay_display'];
$ip_overlay_settings['ip_overlay_locations'] = $_POST['ip_overlay_locations'];
$ip_overlay_settings['ip_overlay_content_editor'] = wp_kses_post( $_POST['ip_overlay_content_editor'] );
update_option( "ip_overlay_settings", $ip_overlay_settings );
}
?>
<div class="wrap">
<h2>Overlay It Settings</h2>
<form id="ip_overlay_settings_form" method="POST" enctype="multipart/form-data">
<input type="hidden" name="update_settings" value="Y" />
<table class="form-table">
<tr>
<th scope="row">Display Overlay?</th>
<td>
<select id="ip_overlay_display" name="ip_overlay_display">
<?php
$display = array(
'false' => 'No',
'true' => 'Yes'
);
foreach( $display as $toggle => $value ) :
$selected = '';
$type_set = $ip_overlay_settings['ip_overlay_display'];
if( $toggle == $type_set ) :
$selected = 'selected="selected"';
endif;
echo '<option value="' . esc_attr( $toggle ) . '" ' . $selected . '>' . $value . '</option>';
endforeach;
?>
</select>
</td>
</tr>
<tr>
<th scope="row">Where should the overlay Display?</th>
<td>
<?php
$where_to_display = array(
'posts' => 'Posts',
'pages' => 'Pages',
'home' => 'On Home Page'
);
foreach( $where_to_display as $checkbox => $value ) :
$checked = '';
$type_set = $ip_overlay_settings['ip_overlay_locations'];
if( $ip_overlay_settings['ip_overlay_locations'][$checkbox] == 'on' ) :
$checked = 'checked="checked"';
endif;
echo '<div id="ip_overlay_location_' . $checkbox . '" style="display: inline-block; margin: 0 10px 0 0;"><input name="ip_overlay_locations[' . $checkbox . ']" type="checkbox" ' . $checked . ' /><label>' . $value . '</label></div>';
endforeach;
?>
</td>
</tr>
<tr>
<td colspan="2">
<?php
$content = $ip_overlay_settings['ip_overlay_content_editor'];
$editor_id = 'ip_overlay_content_editor';
wp_editor( $content, $editor_id );
?>
</td>
</tr>
</table>
<?php submit_button(); ?>
</form>
</div><!--/wrap-->
<?php
}
public function ip_overlay_check() {
if( get_option('ip_overlay_settings') ) :
$ip_overlay_settings = get_option( 'ip_overlay_settings' );
if( $ip_overlay_settings['ip_overlay_display'] === 'true' ) :
if( $ip_overlay_settings['ip_overlay_locations']['home'] === 'on' ) :
if( is_front_page() ) :
echo '<div class="ip-overlay-container" style="display: none;"><div class="ip-overlay-box content">' . $ip_overlay_settings['ip_overlay_content_editor'] . '<div class="close"><span>Close</span></div></div></div>';
endif;
endif;
if( $ip_overlay_settings['ip_overlay_locations']['pages'] === 'on' ) :
if( is_page() && !is_front_page() ) :
echo '<div class="ip-overlay-container" style="display: none;"><div class="ip-overlay-box content">' . $ip_overlay_settings['ip_overlay_content_editor'] . '<div class="close"><span>Close</span></div></div></div>';
endif;
endif;
if( $ip_overlay_settings['ip_overlay_locations']['posts'] === 'on' ) :
if( is_single() ) :
echo '<div class="overlay_it_container" style="display: none;"><div class="ip-overlay-box content">' . $ip_overlay_settings['ip_overlay_content_editor'] . '<div class="close"><span>Close</span></div></div></div>';
endif;
endif;
endif;
endif;
}
public function ip_overlay_scripts_styles() {
// register scripts
wp_register_script( 'ip_overlay_plugin_script', get_bloginfo('url') . '/wp-content/plugins/ip-overlay-plugin/js/ip-overlay.min.js', array( 'jquery' ), null, true );
wp_register_style( 'ip_overlay_plugin_style', get_bloginfo('url') . '/wp-content/plugins/ip-overlay-plugin/css/ip-overlay.css', false, null );
// enqueue
wp_enqueue_script( 'ip_overlay_plugin_script' );
wp_enqueue_style( 'ip_overlay_plugin_style');
}
}<file_sep>// Include gulp
var gulp = require('gulp');
// Include Our Plugins
var sass = require( 'gulp-sass' );
var imagemin = require( 'gulp-imagemin' );
var pngquant = require( 'imagemin-pngquant' );
var concat = require( 'gulp-concat' );
var uglify = require( 'gulp-uglify' );
var rename = require( 'gulp-rename' );
var sourcemaps = require( 'gulp-sourcemaps' );
var filter = require( 'gulp-filter' );
gulp.task(images);
gulp.task(styles);
gulp.task(scripts);
// images Task
function images() {
return gulp.src( ['images/**/*.jpg', 'images/**/*.png', 'images/**/*.gif', '!images/min/**/*'] )
.pipe(imagemin({
progressive: true,
svgoPlugins: [{removeViewBox: false}],
use: [pngquant()]
}))
.pipe( gulp.dest( './images/min' ) );
}
// Compile styles
function styles() {
return gulp.src('scss/**/*.scss')
.pipe( sourcemaps.init( { loadMaps: true } ) )
.pipe( sass.sync({ outputStyle : 'compressed' }).on('error', sass.logError) )
.pipe( sourcemaps.write( '../css' ) )
.pipe(gulp.dest('css'));
}
// Concatenate & Minify JS
function scripts() {
return gulp.src( ['js/lib/*.js', 'js/vendor/*.js' ])
.pipe( concat('ip-overlay.js') )
.pipe( sourcemaps.init( { loadMaps: true } ) )
.pipe( rename('ip-overlay.min.js') )
.pipe( uglify() )
.pipe( sourcemaps.write( '../js' ) )
.pipe( gulp.dest('js') );
}
gulp.task( 'watch:scripts', function() {
gulp.watch( 'js/vendor/**/*.js', scripts);
});
gulp.task( 'watch:sass', function() {
gulp.watch( ['scss/**/*.scss'], styles);
});
gulp.task( 'watch:images', function() {
gulp.watch( ['images/**/*', '!images/min/**/*'], images);
});
gulp.task('watch', gulp.parallel('watch:scripts', 'watch:sass', 'watch:images'));
// Default Task
gulp.task( 'default', gulp.series('images', 'styles', 'scripts', 'watch'));
|
bcd6de4f079c542aa6d31a58ba0317a8b71b0a71
|
[
"Markdown",
"JavaScript",
"PHP"
] | 3 |
Markdown
|
joshhannan/ip-overlay-it-plugin
|
fb51c20a813af781461bcd421eaefb7387c80344
|
d0994002e23aa141988820a7626593393bb327e8
|
refs/heads/master
|
<file_sep>apply plugin: 'com.android.application'
dependencies {
compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.3'
compile project(':library')
}
android {
compileSdkVersion 23
buildToolsVersion '23.0.1'
defaultConfig {
applicationId "uk.co.senab.photoview.sample"
minSdkVersion 9
targetSdkVersion 23
versionCode 124
versionName "1.2.4"
}
}
<file_sep>apply plugin: 'com.android.library'
apply plugin: 'com.novoda.bintray-release'
android {
compileSdkVersion 23
buildToolsVersion '23.0.1'
defaultConfig {
minSdkVersion 9
targetSdkVersion 23
versionCode 124
versionName "1.2.4"
}
}
dependencies {
compile "com.android.support:support-v4:23.0.1"
compile 'com.facebook.fresco:fresco:0.7.0'
}
//./gradlew clean build bintrayUpload -PbintrayUser=BINTRAY_USERNAME -PbintrayKey=BINTRAY_KEY -PdryRun=false
publish {
userOrg = 'commit451'
groupId = 'com.commit451'
artifactId = 'PhotoView'
version = '1.2.4'
description = 'Implementation of ImageView for Android that supports zooming, by various touch gestures.'
website = 'https://github.com/chrisbanes/PhotoView'
issueTracker = "https://github.com/chrisbanes/PhotoView/issues"
repository = "https://github.com/chrisbanes/PhotoView.git"
}
<file_sep>package uk.co.senab.photoview.utils;
/**
* Created by <NAME> on 09/10/15.
*/
public interface ImageDownloadListener {
void onUpdate(int progress);
}
|
be4f9618d3f1a9a961bc3471d7a9f94607f93b9a
|
[
"Java",
"Gradle"
] | 3 |
Gradle
|
bastiotutuama/FrescoPhotoView
|
d105b1c27715642451eac18d9d0ee82a320fe60a
|
b650862f08fa81e3c57beae520d9fc3b4bdbf3c9
|
refs/heads/master
|
<repo_name>asidwell/fs_scripts<file_sep>/recon1.sh
#!/usr/bin/env bash
#send first recon-all to cluster
pbsubmit -c "recon-all -subjid $1 -i $FS_PROJECTS_DIR/$1_MR.nii -all" -m <EMAIL> -f
<file_sep>/README.md
# fs_scripts
scripts for Freesurfer viewing/recons
<file_sep>/recon2.sh
#!/usr/bin/env bash
#send edited recon-all to cluster
pbsubmit -c "recon-all -autorecon2 -autorecon3 -no-isrunning -subjid $1" -m <EMAIL> -f
|
d4e137f40cd17fba6352159aa3da7904156a0872
|
[
"Markdown",
"Shell"
] | 3 |
Shell
|
asidwell/fs_scripts
|
a5476ca87cdf8a1a968e6f5fdfcf648671e89b27
|
c1d6a869c27bd71eb72c19c75738ffc981b59beb
|
refs/heads/master
|
<repo_name>KOOTSTHEHOOTS/Smorse<file_sep>/9.Smorse.py/asmorse.py
''' Challenge [2019-08-05] Challenge #380 [Easy] Smooshed Morse Code 1
https://www.reddit.com/r/dailyprogrammer/comments/cmd1hb/20190805_challenge_380_easy_smooshed_morse_code_1/
'''
import string
morse = ".- -... -.-. -.. . ..-. --. .... .. .--- -.- .-.. -- -. --- .--. --.- .-. ... - ..- ...- .-- -..- -.-- --.."
morse = morse.split(" ")
alphabet = string.ascii_lowercase
morse_alphabet_list = zip(alphabet, morse)
''' can be done using zip function'''
#for morse_symbol in morse:
# morse_index = morse.index(morse_symbol)
# morse_alphabet_list.append([alphabet[morse_index] , morse_symbol])
def smorse(decoded_word):
'''
decoded_word: string, lowercased alphabets that is to be encoded into morse
return: string, word encoded in morse
'''
'''
encode word given - encode each letter one by one
1. find letter in list of lists
2. add morse code to a list
3. print the result
'''
counter = 0
#Encoded word to be returned
encoded_word = []
counter = 0
for letter in decoded_word:
while letter != morse_alphabet_list[counter][0]:
counter += 1
#Morse symbol of letter
morse_symbol = morse_alphabet_list[counter][1]
encoded_word.append(morse_symbol)
counter = 0
encoded_word = ("").join(encoded_word)#convert encoded word to string
return encoded_word
def test_smorse():
assert smorse("sos") == "...---...", "Should be ...---..."
assert smorse("daily") == "-...-...-..-.--", "Should be -...-...-..-.--"
assert smorse("programmer") == ".--..-.-----..-..-----..-.", "Should be .--..-.-----..-..-----..-."
assert smorse("bits") == "-.....-...", "Should be -.....-..."
assert smorse("three") == "-.....-...", "Should be -.....-..."
def test_zip():
assert list(zip(alphabet, morse))[0][0] == "a", "This should be a"
assert list(zip(alphabet, morse))[0][1] == ".-", "This should be .-"
assert list(zip(alphabet, morse))[1][0] == "b", "This should be b"
assert list(zip(alphabet, morse))[1][1] == "-...", "This should be -..."
if __name__ == "__main__":
# test_smorse()
test_zip()
print("Everything passed")<file_sep>/9.Smorse.py/bBonus1.py
''' The sequence -...-....-.--. is the code for four different words
(needing, nervate, niding, tiling). Find the only sequence
that's the code for 13 different words.
'''
import asmorse
smorse = asmorse.smorse
def unique(integer, word_file):
'''
integer: int, the number of words that is meant to match the morse
sequence
word_file: The word file containing words separated by a new line or space
to search for morse sequence.
returns list of morse codes, string, that has the number words that
match arguement, integer from arguement, word_file.
'''
# open word list provided in read mode
f = open(word_file, "r")
if f.mode == "r":
words = f.read()
word_list = words.split()
print("loading", word_file)
print("loaded", len(word_list), "words!")
# smorsed_word_list = [smorse(word) for word in word_list]
# print(smorsed_word_list)
#
def test_unique():
assert unique(13, "enable1.txt") == "-...-....-.--.", "Morse Sequence: -...-....-.--., is the code for 13 words"
if __name__ == "__main__":
# test_unique()
asmorse.smorse("sos")
unique(13, "enable1.txt")
|
c57e9f8752bba0ea6aeaecdd7384fa639a0d509f
|
[
"Python"
] | 2 |
Python
|
KOOTSTHEHOOTS/Smorse
|
af99cfaf3ff14262ac23282bc60c0c92a23cdfc0
|
4fac16565fa35d6f1ed73eb061a727ad3262e4cf
|
refs/heads/master
|
<repo_name>zhanglun/Node-Authentication-demo<file_sep>/raw-node-authentication/app/routes.js
var User = require('./models/user');
module.exports = function(app, passport) {
// =====================================
// HOME PAGE (with login links) ========
// =====================================
app.get('/', function(req, res) {
res.render('index'); // load the index.ejs file
});
// =====================================
// LOGIN ===============================
// =====================================
// show the login form
app.get('/login', function(req, res) {
// render the page and pass in any flash data if it exists
res.render('login.ejs', {
message: req.flash('message')
});
});
// process the login form
// app.post('/login', do all our passport stuff here);
// =====================================
// SIGNUP ==============================
// =====================================
// show the signup form
app.get('/signup', function(req, res) {
console.log('signup');
// render the page and pass in any flash data if it exists
res.render('signup.ejs', {
message: req.flash('signupMessage')
});
});
// process the signup form
// app.post('/signup', do all our passport stuff here);
// =====================================
// PROFILE SECTION =====================
// =====================================
// we will want this protected so you have to be logged in to visit
// we will use route middleware to verify this (the isLoggedIn function)
app.get('/profile', isLoggedIn, function(req, res) {
res.render('profile.ejs', {
user: req.session.user // get the user out of session and pass to template
});
});
// =====================================
// LOGOUT ==============================
// =====================================
app.get('/logout', function(req, res) {
req.session.user = null;
res.redirect('/');
});
app.post('/signup', function(req, res, next) {
var _user = {
email: req.body.email,
password: req.body.<PASSWORD>
};
User.findOne({email: _user.email}, function(err, user){
if(err){
throw err;
}
if(user){
req.flash('message', 'User exists!!');
res.redirect('/signup');
}else{
var newUser = new User();
newUser.email = _user.email;
newUser.password = <PASSWORD>(_user.<PASSWORD>);
newUser.save(function(err){
if(err){
throw err;
}else{
req.session.user = user;
res.redirect('/profile');
}
});
}
});
});
app.post('/login', verifyUser, function(req, res, next) {
});
// route for logging out
app.get('/logout', function(req, res) {
req.session.user = null;
res.redirect('/');
});
};
// route middleware to make sure a user is logged in
function isLoggedIn(req, res, next) {
// if user is authenticated in the session, carry on
if (req.session.user) {
return next();
} else {
// if they aren't redirect them to the home page
res.redirect('/');
}
}
function verifyUser(req, res, next) {
var _user = {
email: req.body.email,
password: <PASSWORD>
};
console.log(_user);
if (!_user.email) {
req.flash('message', 'Flashed message');
return res.redirect('/login');
}
User.findOne({
email: _user.email
}, function(err, user){
if (user && user.validPassword(_user.password)) {
// check user password
req.session.user = user;
return res.redirect('/profile');
} else {
req.flash('message', 'No User!!!');
return res.redirect('/login');
}
});
}
<file_sep>/README.md
Node Authentication Demo List:
1. [Authenticate a Node.js API with JSON Web Tokens](https://scotch.io/tutorials/authenticate-a-node-js-api-with-json-web-tokens)
2. [Easy Node Authentication: Setup and Local](https://scotch.io/tutorials/easy-node-authentication-setup-and-local)
3. [Easy Node Authentication: Facebook](https://scotch.io/tutorials/easy-node-authentication-facebook)
<file_sep>/raw-node-authentication/config/database.js
module.exports = {
url: 'mongodb://localhost/nodesite'
};
|
93bef29954417591ae83620f2778b7dba7d6cf8a
|
[
"JavaScript",
"Markdown"
] | 3 |
JavaScript
|
zhanglun/Node-Authentication-demo
|
dde038fce6b5be73e618df750ccbf1b9c12b7158
|
a6f6cb6ab99b7acfac34d80949949ed0bf89d971
|
refs/heads/master
|
<file_sep><?php
$servername = "localhost";
$username = "u939969079_test";
$password = "<PASSWORD>";
$dbname = "u939969079_test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$NumSub = 5;
$start = (int)$_GET['limit'];
$sql = "SELECT * FROM storys LIMIT $start , $NumSub";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$All_storys = array();
while($row = $result->fetch_assoc()) {
$All_storys[] = $row;
}
} else {
echo "0 results";
}
$json_re=array();
array_push($json_re,array("All_storys"=>$All_storys));
echo json_encode($json_re);
$conn->close();
?>
|
f77b108df7450e1650e4f7e5a369e2dabc4ac126
|
[
"PHP"
] | 1 |
PHP
|
salim3dd/RecyclerView_moredata1
|
ad085f2e78055acd1c88677d92c82fe6832b91f3
|
d553ff989eb1f2b7f28657c4a2863d8f7cae86b9
|
refs/heads/master
|
<file_sep>from flask_wtf import FlaskForm
from wtforms.fields.simple import FileField, TextAreaField
from wtforms.validators import InputRequired
from flask_wtf.file import FileRequired, FileAllowed
class UploadForm(FlaskForm):
description = TextAreaField('Description',validators=[InputRequired()])
photo = FileField('Photo',validators=[FileRequired(),FileAllowed(['jpg', 'jpeg', 'png'], 'Images only!')])
|
897e6dbbc00d29759e6a693ed83a910ab5cc3130
|
[
"Python"
] | 1 |
Python
|
Keneil-Thompson/info3180-lab7
|
185b1fc406a74d558cf7f7c0a7042cdd925650b8
|
053319a18aefda1fbbec0a74034d881904a139e0
|
refs/heads/master
|
<repo_name>ss2102/djangogirls<file_sep>/minhnd/bin/django-admin.py
#!/Users/minhnd/Project/Django/djangogirls/minhnd/bin/python3
from django.core import management
if __name__ == "__main__":
management.execute_from_command_line()
|
f5b6027248af9f6b3a8cf816f6f6d24ef6f7743a
|
[
"Python"
] | 1 |
Python
|
ss2102/djangogirls
|
25f039a9894383f1fa64b2ad1725456095f2430c
|
2f1a55f1a471b71aa575711b7731eb4bb97ba4f9
|
refs/heads/master
|
<file_sep># DM-6162
Untitled-copy6.ipynb investigates the quirky noisy image in https://jira.lsstcorp.org/browse/DM-7376
It also attempts to compare the result to standard ZOGY, and those results seem poor.
Future work will be to look at spatial variation of correction kernel.
<file_sep>import numpy as np
import scipy
import scipy.stats
from scipy.fftpack import fft2, ifft2, fftfreq, fftshift
import lsst.afw.image as afwImage
import lsst.afw.math as afwMath
def zscale_image(input_img, contrast=0.25):
"""This emulates ds9's zscale feature. Returns the suggested minimum and
maximum values to display."""
samples = input_img.flatten()
samples = samples[~np.isnan(samples)]
samples.sort()
chop_size = int(0.10*len(samples))
subset = samples[chop_size:-chop_size]
i_midpoint = int(len(subset)/2)
I_mid = subset[i_midpoint]
fit = np.polyfit(np.arange(len(subset)) - i_midpoint, subset, 1)
# fit = [ slope, intercept]
z1 = I_mid + fit[0]/contrast * (1-i_midpoint)/1.0
z2 = I_mid + fit[0]/contrast * (len(subset)-i_midpoint)/1.0
return z1, z2
def plotImageGrid(images, nrows_ncols=None, extent=None, clim=None, interpolation='none',
cmap='gray', imScale=2., cbar=True, titles=None, titlecol=['r','y']):
import matplotlib.pyplot as plt
import matplotlib
matplotlib.style.use('ggplot')
from mpl_toolkits.axes_grid1 import ImageGrid
def add_inner_title(ax, title, loc, size=None, **kwargs):
from matplotlib.offsetbox import AnchoredText
from matplotlib.patheffects import withStroke
if size is None:
size = dict(size=plt.rcParams['legend.fontsize'], color=titlecol[0])
at = AnchoredText(title, loc=loc, prop=size,
pad=0., borderpad=0.5,
frameon=False, **kwargs)
ax.add_artist(at)
at.txt._text.set_path_effects([withStroke(foreground=titlecol[1], linewidth=3)])
return at
if nrows_ncols is None:
tmp = np.int(np.floor(np.sqrt(len(images))))
nrows_ncols = (tmp, np.int(np.ceil(np.float(len(images))/tmp)))
if nrows_ncols[0] <= 0:
nrows_ncols[0] = 1
if nrows_ncols[1] <= 0:
nrows_ncols[1] = 1
size = (nrows_ncols[1]*imScale, nrows_ncols[0]*imScale)
fig = plt.figure(1, size)
igrid = ImageGrid(fig, 111, # similar to subplot(111)
nrows_ncols=nrows_ncols, direction='row', # creates 2x2 grid of axes
axes_pad=0.1, # pad between axes in inch.
label_mode="L", # share_all=True,
cbar_location="right", cbar_mode="single", cbar_size='7%')
extentWasNone = False
clim_orig = clim
for i in range(len(images)):
ii = images[i]
if hasattr(ii, 'computeImage'):
img = afwImage.ImageD(ii.getDimensions())
ii.computeImage(img, doNormalize=False)
ii = img
if hasattr(ii, 'getImage'):
ii = ii.getImage()
if hasattr(ii, 'getMaskedImage'):
ii = ii.getMaskedImage().getImage()
if hasattr(ii, 'getArray'):
bbox = ii.getBBox()
if extent is None:
extentWasNone = True
extent = (bbox.getBeginX(), bbox.getEndX(), bbox.getBeginY(), bbox.getEndY())
ii = ii.getArray()
if extent is not None and not extentWasNone:
ii = ii[extent[0]:extent[1], extent[2]:extent[3]]
if clim_orig is None:
clim = zscale_image(ii)
if cbar and clim_orig is not None:
ii = np.clip(ii, clim[0], clim[1])
im = igrid[i].imshow(ii, origin='lower', interpolation=interpolation, cmap=cmap,
extent=extent, clim=clim)
if cbar:
igrid[i].cax.colorbar(im)
if titles is not None: # assume titles is an array or tuple of same length as images.
t = add_inner_title(igrid[i], titles[i], loc=2)
t.patch.set_ec("none")
t.patch.set_alpha(0.5)
if extentWasNone:
extent = None
extentWasNone = False
return igrid
def gaussian2d(grid, m=None, s=None):
# see https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.multivariate_normal.html
if m is None:
m = [0., 0.]
if s is None:
s = [1., 1.]
cov = [[s[0], 0], [0, s[1]]]
var = scipy.stats.multivariate_normal(mean=m, cov=cov)
return var.pdf(grid)
def singleGaussian2d(x, y, xc, yc, sigma_x=1., sigma_y=1., theta=0., offset=0.):
theta = (theta/180.) * np.pi
cos_theta2, sin_theta2 = np.cos(theta)**2., np.sin(theta)**2.
sigma_x2, sigma_y2 = sigma_x**2., sigma_y**2.
a = cos_theta2/(2.*sigma_x2) + sin_theta2/(2.*sigma_y2)
b = -(np.sin(2.*theta))/(4.*sigma_x2) + (np.sin(2.*theta))/(4.*sigma_y2)
c = sin_theta2/(2.*sigma_x2) + cos_theta2/(2.*sigma_y2)
xxc, yyc = x-xc, y-yc
out = np.exp( - (a*(xxc**2.) + 2.*b*xxc*yyc + c*(yyc**2.)))
if offset != 0.:
out += offset
out /= out.sum()
return out
# Make the two "images". im1 is the template, im2 is the science
# image.
# NOTE: having sources near the edges really messes up the
# fitting (probably because of the convolution). So make sure no
# sources are near the edge.
# NOTE: also it seems that having the variable source with a large
# flux increase also messes up the fitting (seems to lead to
# overfitting -- perhaps to the source itself). This might be fixed by
# adding more constant sources.
def makeFakeImages(xim=None, yim=None, sig1=0.2, sig2=0.2, psf1=None, psf2=None, offset=None,
psf_yvary_factor=0.2, varSourceChange=1/50., theta1=0., theta2=-45., im2background=10.,
n_sources=500, seed=66):
np.random.seed(seed)
# psf1 = 1.6 # sigma in pixels im1 will be template
# psf2 = 2.2 # sigma in pixels im2 will be science image. make the psf in this image slighly offset and elongated
psf1 = [1.6, 1.6] if psf1 is None else psf1
print 'Template PSF:', psf1, theta1
psf2 = [1.8, 2.2] if psf2 is None else psf2
print 'Science PSF:', psf2, theta2
print np.sqrt(psf2[0]**2 - psf1[1]**2)
# offset = 0.2 # astrometric offset (pixels) between the two images
offset = [0.2, 0.2] if offset is None else offset
print 'Offset:', offset
xim = np.arange(-256, 256, 1) if xim is None else xim
yim = xim.copy() if yim is None else yim
x0im, y0im = np.meshgrid(xim, yim)
fluxes = np.random.uniform(50, 30000, n_sources)
xposns = np.random.uniform(xim.min()+16, xim.max()-5, n_sources)
yposns = np.random.uniform(yim.min()+16, yim.max()-5, n_sources)
# Make the source closest to the center of the image the one that increases in flux
ind = np.argmin(xposns**2. + yposns**2.)
#print ind, xposns[ind], yposns[ind]
im1 = np.random.normal(scale=sig1, size=x0im.shape) # sigma of template
im2 = np.random.normal(scale=sig2, size=x0im.shape) # sigma of science image
psf2_yvary = psf_yvary_factor * (yim.mean() - yposns) / yim.max() # variation in y-width of psf in science image across (x-dim of) image
print 'PSF y spatial-variation:', psf2_yvary.min(), psf2_yvary.max()
# psf2_yvary[:] = 1.1 # turn it off for now, just add a constant 1.1 pixel horizontal width
for i in range(n_sources):
flux = fluxes[i]
tmp1 = flux * singleGaussian2d(x0im, y0im, xposns[i], yposns[i], psf1[0], psf1[1], theta=theta1)
im1 += tmp1
if i == ind:
flux += flux * varSourceChange # / 50.
tmp2 = flux * singleGaussian2d(x0im, y0im, xposns[i]+offset[0], yposns[i]+offset[1],
psf2[0], psf2[1]+psf2_yvary[i], theta=theta2)
im2 += tmp2
# Add a (constant, for now) background offset to im2
if im2background != 0.: # im2background = 10.
print 'Background:', im2background
im2 += im2background
im1_psf = singleGaussian2d(x0im, y0im, 0, 0, psf1[0], psf1[1], theta=theta1)
im2_psf = singleGaussian2d(x0im, y0im, offset[0], offset[1], psf2[0], psf2[1], theta=theta2)
return im1, im2, im1_psf, im2_psf
# Okay, here we start the A&L basis functions...
# Update: it looks like the actual code in the stack uses chebyshev1 polynomials!
# Note these are essentially the same but with different scale factors.
# Here beta is a rescale factor but this is NOT what it is really used for.
# Can be used to rescale so that sigGauss[1] = sqrt(sigmaPsf_I^2 - sigmaPsf_T^2)
def chebGauss2d(x, y, m=None, s=None, ord=[0,0], beta=1., verbose=False):
from numpy.polynomial.chebyshev import chebval2d
if m is None:
m = [0., 0.]
if s is None:
s = [1., 1.]
# cov = [[s[0], 0], [0, s[1]]]
coefLen = np.max(ord)+1
coef0 = np.zeros(coefLen)
coef0[ord[0]] = 1
coef1 = np.zeros(coefLen)
coef1[ord[1]] = 1
if verbose:
print s, beta, ord, coef0, coef1
ga = singleGaussian2d(x, y, 0, 0, s[0]/beta, s[1]/beta)
ch = chebval2d(x, y, c=np.outer(coef0, coef1))
return ch * ga
# use same parameters as from the stack.
# TBD: is a degGauss of 2 mean it goes up to order 2 (i.e. $x^2$)? Or
# is it 2 orders so it only goes up to linear ($x$)? Probably the
# former, so that's what we'll use.
# Parameters from stack
# betaGauss is actually the scale factor for sigGauss -> sigGauss[0] = sigGauss[1]/betaGauss and
# sigGauss[2] = sigGauss[1] * betaGauss. Looks like here, betaGauss is 2 (see sigGauss below) but
# we'll just set it to 1.
# Note should rescale sigGauss so sigGauss[1] = sqrt(sigma_I^2 - sigma_T^2)
# betaGauss = 1 # in the Becker et al. paper betaGauss is 1 but PSF is more like 2 pixels?
# sigGauss = [0.75, 1.5, 3.0]
# degGauss = [4, 2, 2]
# # Parameters from and Becker et al. (2012)
# degGauss = [6, 4, 2]
def getALChebGaussBases(x0, y0, sigGauss=None, degGauss=None, betaGauss=1, verbose=True):
sigGauss = [0.75, 1.5, 3.0] if sigGauss is None else sigGauss
#degGauss = [4, 2, 2] if degGauss is None else degGauss
degGauss = [6, 4, 2] if degGauss is None else degGauss
# Old, too many bases:
#basis = [chebGauss2d(x0, y0, grid, m=[0,0], s=[sig0,sig1], ord=[deg0,deg1], beta=betaGauss, verbose=False) for i0,sig0 in enumerate(sigGauss) for i1,sig1 in enumerate(sigGauss) for deg0 in range(degGauss[i0]) for deg1 in range(degGauss[i1])]
def get_valid_inds(Nmax):
tmp = np.add.outer(range(Nmax+1), range(Nmax+1))
return np.where(tmp <= Nmax)
inds = [get_valid_inds(i) for i in degGauss]
if verbose:
for i in inds:
print i
basis = [chebGauss2d(x0, y0, m=[0,0], s=[sig,sig], ord=[inds[i][0][ind], inds[i][1][ind]], beta=betaGauss, verbose=verbose) for i,sig in enumerate(sigGauss) for ind in range(len(inds[i][0]))]
return basis
# Convolve im1 (template) with the basis functions, and make these the *new* bases.
# Input 'basis' is the output of getALChebGaussBases().
def makeImageBases(im1, basis):
import scipy.signal
#basis2 = [scipy.signal.fftconvolve(im1, b, mode='same') for b in basis]
basis2 = [scipy.ndimage.filters.convolve(im1, b, mode='constant') for b in basis]
return basis2
def makeSpatialBases(im1, basis, basis2, spatialKernelOrder=2, spatialBackgroundOrder=2, verbose=False):
# Then make the spatially modified basis by simply multiplying the constant
# basis (basis2 from makeImageBases()) by a polynomial along the image coordinate.
# Note that since we *are* including i=0, this new basis *does include* basis2 and
# thus can replace it.
# Here beta is a rescale factor but this is NOT what it is really used for.
# Can be used to rescale so that sigGauss[1] = sqrt(sigmaPsf_I^2 - sigmaPsf_T^2)
# Apparently the stack uses a spatial kernel order of 2? (2nd-order?)
#spatialKernelOrder = 2 # 0
# Same for background order.
#spatialBackgroundOrder = 2
def cheb2d(x, y, ord=[0,0], verbose=False):
from numpy.polynomial.chebyshev import chebval2d
coefLen = np.max(ord)+1
coef0 = np.zeros(coefLen)
coef0[ord[0]] = 1
coef1 = np.zeros(coefLen)
coef1[ord[1]] = 1
if verbose:
print ord, coef0, coef1
ch = chebval2d(x, y, c=np.outer(coef0, coef1))
return ch
def get_valid_inds(Nmax):
tmp = np.add.outer(range(Nmax+1), range(Nmax+1))
return np.where(tmp <= Nmax)
spatialBasis = bgBasis = None
spatialInds = get_valid_inds(spatialKernelOrder)
if verbose:
print spatialInds
#xim = np.arange(np.int(-np.floor(im1.shape[0]/2.)), np.int(np.floor(im1.shape[0]/2)))
#yim = np.arange(np.int(-np.floor(im1.shape[1]/2.)), np.int(np.floor(im1.shape[1]/2)))
x0im, y0im = getImageGrid(im1) #np.meshgrid(xim, yim)
# Note the ordering of the loop is important! Make the basis2 the last one so the first set of values
# that are returned are all of the original (basis2) unmodified bases.
# Store "spatialBasis" which is the kernel basis and the spatial basis separated so we can recompute the
# final kernel at the end. Include in index 2 the "original" kernel basis as well.
if spatialKernelOrder > 0:
spatialBasis = [[basis2[bi], cheb2d(x0im, y0im, ord=[spatialInds[0][i], spatialInds[1][i]], verbose=False), basis[bi]] for i in range(1,len(spatialInds[0])) for bi in range(len(basis2))]
#basis2m = [b * cheb2d(x0im, y0im, ord=[spatialInds[0][i], spatialInds[1][i]], verbose=False) for i in range(1,len(spatialInds[0])) for b in basis2]
spatialBgInds = get_valid_inds(spatialBackgroundOrder)
if verbose:
print spatialBgInds
# Then make the spatial background part
if spatialBackgroundOrder > 0:
bgBasis = [cheb2d(x0im, y0im, ord=[spatialBgInds[0][i], spatialBgInds[1][i]], verbose=False) for i in range(len(spatialBgInds[0]))]
return spatialBasis, bgBasis
# Collect the bases into a single matrix
# ITMT, let's make sure all the bases are on a reasonable scale.
def collectAllBases(basis2, spatialBasis, bgBasis, verbose=False):
basis2a = np.vstack([b.flatten() for b in basis2]).T
constKernelIndices = np.arange(0, basis2a.shape[1])
if verbose:
print constKernelIndices
nonConstKernelIndices = None
if spatialBasis is not None:
b1 = np.vstack([(b[0]*b[1]).flatten() for b in spatialBasis]).T
nonConstKernelIndices = np.arange(basis2a.shape[1], basis2a.shape[1]+b1.shape[1])
basis2a = np.hstack([basis2a, b1])
if verbose:
print nonConstKernelIndices
bgIndices = None
if bgBasis is not None:
b1 = np.vstack([b.flatten() for b in bgBasis]).T
bgIndices = np.arange(basis2a.shape[1], basis2a.shape[1]+b1.shape[1])
basis2a = np.hstack([basis2a, b1])
if verbose:
print bgIndices
# Rescale the bases so that the "standard" A&L linear fit will work (i.e. when squared, not too large!)
basisOffset = 0. # basis2a.mean(0) + 0.1
basisScale = basis2a.std(0) + 0.1 # avoid division by zero
basis2a = (basis2a-basisOffset)/(basisScale)
return basis2a, (constKernelIndices, nonConstKernelIndices, bgIndices), (basisOffset, basisScale)
# Do the linear fit to compute the matching kernel. This is NOT the
# same fit as is done by standard A&L but gives the same results. This
# will not work for very large images. See below. The resulting fit is
# the matched template.
def doTheLinearFitOLD(basis2a, im2, verbose=False):
pars, resid, _, _ = np.linalg.lstsq(basis2a, im2.flatten())
fit = (pars * basis2a).sum(1).reshape(im2.shape)
if verbose:
print resid, np.sum((im2 - fit.reshape(im2.shape))**2)
return pars, fit, resid
# Create the $b_i$ and $M_{ij}$ from the A&L (1998) and Becker (2012)
# papers. This was done wrong in the previous version of notebook 3
# (and above), although it gives identical results.
def doTheLinearFitAL(basis2a, im2, verbose=False):
b = (basis2a.T * im2.flatten()).sum(1)
M = np.dot(basis2a.T, basis2a)
pars, resid, _, _ = np.linalg.lstsq(M, b)
fit = (pars * basis2a).sum(1).reshape(im2.shape)
if verbose:
print resid, np.sum((im2 - fit.reshape(im2.shape))**2)
return pars, fit, resid
# Also generate the matching kernel from the resulting pars.
# Look at the resulting matching kernel by multiplying the fitted
# parameters times the original basis funcs. and test that actually
# convolving it with the template gives us a good subtraction.
# Here, we'll just compute the spatial part at x,y=0,0
# (i.e. x,y=256,256 in img coords)
def getMatchingKernelAL(pars, basis, constKernelIndices, nonConstKernelIndices, spatialBasis,
basisScale, basisOffset=0, xcen=256, ycen=256, verbose=False):
kbasis1 = np.vstack([b.flatten() for b in basis]).T
kbasis1 = (kbasis1 - basisOffset) / basisScale[constKernelIndices]
kfit1 = (pars[constKernelIndices] * kbasis1).sum(1).reshape(basis[0].shape)
kbasis2 = np.vstack([(b[2]*b[1][xcen, ycen]).flatten() for b in spatialBasis]).T
kbasis2 = (kbasis2 - basisOffset) / basisScale[nonConstKernelIndices]
kfit2 = (pars[nonConstKernelIndices] * kbasis2).sum(1).reshape(basis[0].shape)
kfit = kfit1 + kfit2
if verbose:
print kfit1.sum(), kfit2.sum(), kfit.sum()
kfit /= kfit.sum() # this is necessary if the variable source changes a lot - prevent the kernel from incorporating that change in flux
return kfit
# Compute the "L(ZOGY)" post-conv. kernel from kfit
# Note unlike previous notebooks, here because the PSF is varying,
# we'll just use `fit2` rather than `im2-conv_im1` as the diffim,
# since `fit2` already incorporates the spatially varying PSF.
# sig1 and sig2 are the same as those input to makeFakeImages().
def computeCorrectionKernelALZC(kappa, sig1=0.2, sig2=0.2):
def kernel_ft2(kernel):
FFT = fft2(kernel)
return FFT
def post_conv_kernel_ft2(kernel, sig1=1., sig2=1.):
kft = kernel_ft2(kernel)
return np.sqrt((sig1**2 + sig2**2) / (sig1**2 + sig2**2 * kft**2))
def post_conv_kernel2(kernel, sig1=1., sig2=1.):
kft = post_conv_kernel_ft2(kernel, sig1, sig2)
out = ifft2(kft)
return out
pck = post_conv_kernel2(kappa, sig1=sig2, sig2=sig1)
pck = np.fft.ifftshift(pck.real)
#print np.unravel_index(np.argmax(pck), pck.shape)
# I think we actually need to "reverse" the PSF, as in the ZOGY (and Kaiser) papers... let's try it.
# This is the same as taking the complex conjugate in Fourier space before FFT-ing back to real space.
if False:
# I still think we need to flip it in one axis (TBD: figure this out!)
pck = pck[::-1, :]
return pck
# Compute the (corrected) diffim's new PSF
# post_conv_psf = phi_1(k) * sym.sqrt((sig1**2 + sig2**2) / (sig1**2 + sig2**2 * kappa_ft(k)**2))
# we'll parameterize phi_1(k) as a gaussian with sigma "psfsig1".
# im2_psf is the the psf of im2
def computeCorrectedDiffimPsfALZC(kappa, im2_psf, sig1=0.2, sig2=0.2):
def post_conv_psf_ft2(psf, kernel, sig1=1., sig2=1.):
# Pad psf or kernel symmetrically to make them the same size!
if psf.shape[0] < kernel.shape[0]:
while psf.shape[0] < kernel.shape[0]:
psf = np.pad(psf, (1, 1), mode='constant')
elif psf.shape[0] > kernel.shape[0]:
while psf.shape[0] > kernel.shape[0]:
kernel = np.pad(kernel, (1, 1), mode='constant')
psf_ft = fft2(psf)
kft = fft2(kernel)
out = psf_ft * np.sqrt((sig1**2 + sig2**2) / (sig1**2 + sig2**2 * kft**2))
return out
def post_conv_psf(psf, kernel, sig1=1., sig2=1.):
kft = post_conv_psf_ft2(psf, kernel, sig1, sig2)
out = ifft2(kft)
return out
im2_psf_small = im2_psf
# First compute the science image's (im2's) psf, subset on -16:15 coords
if im2_psf.shape[0] > 50:
x0im, y0im = getImageGrid(im2_psf)
x = np.arange(-16, 16, 1)
y = x.copy()
x0, y0 = np.meshgrid(x, y)
im2_psf_small = im2_psf[(x0im.max()+x.min()+1):(x0im.max()-x.min()+1),
(y0im.max()+y.min()+1):(y0im.max()-y.min()+1)]
pcf = post_conv_psf(psf=im2_psf_small, kernel=kappa, sig1=sig2, sig2=sig1)
pcf = pcf.real / pcf.real.sum()
return pcf
def computeClippedImageStats(im, low=3, high=3):
_, low, upp = scipy.stats.sigmaclip(im, low=low, high=high)
tmp = im[(im > low) & (im < upp)]
mean1 = np.nanmean(tmp)
sig1 = np.nanstd(tmp)
return mean1, sig1
def getImageGrid(im):
xim = np.arange(np.int(-np.floor(im.shape[0]/2.)), np.int(np.floor(im.shape[0]/2)))
yim = np.arange(np.int(-np.floor(im.shape[1]/2.)), np.int(np.floor(im.shape[1]/2)))
x0im, y0im = np.meshgrid(xim, yim)
return x0im, y0im
def performAlardLupton(im1, im2, sigGauss=None, degGauss=None, betaGauss=1,
spatialKernelOrder=2, spatialBackgroundOrder=2, doALZCcorrection=True,
sig1=None, sig2=None, verbose=False):
x = np.arange(-16, 16, 1)
y = x.copy()
x0, y0 = np.meshgrid(x, y)
basis = getALChebGaussBases(x0, y0, sigGauss=sigGauss, degGauss=degGauss,
betaGauss=betaGauss, verbose=verbose)
basis2 = makeImageBases(im1, basis)
spatialBasis, bgBasis = makeSpatialBases(im1, basis, basis2, verbose=verbose)
basis2a, (constKernelIndices, nonConstKernelIndices, bgIndices), (basisOffset, basisScale) \
= collectAllBases(basis2, spatialBasis, bgBasis)
pars, fit, resid = doTheLinearFitAL(basis2a, im2)
xcen = np.int(np.floor(im1.shape[0]/2.))
ycen = np.int(np.floor(im1.shape[1]/2.))
kfit = getMatchingKernelAL(pars, basis, constKernelIndices, nonConstKernelIndices,
spatialBasis, basisScale, basisOffset, xcen=xcen, ycen=ycen,
verbose=verbose)
diffim = im2 - fit
if doALZCcorrection:
if sig1 is None:
_, sig1 = computeClippedImageStats(im1)
if sig2 is None:
_, sig2 = computeClippedImageStats(im2)
print sig1, sig2
pck = computeCorrectionKernelALZC(kfit, sig1, sig2)
pci = scipy.ndimage.filters.convolve(diffim, pck, mode='constant')
diffim = pci
return diffim, kfit
# Compute the ZOGY eqn. (13):
# $$
# \widehat{D} = \frac{F_r\widehat{P_r}\widehat{N} -
# F_n\widehat{P_n}\widehat{R}}{\sqrt{\sigma_n^2 F_r^2
# |\widehat{P_r}|^2 + \sigma_r^2 F_n^2 |\widehat{P_n}|^2}}
# $$
# where $D$ is the optimal difference image, $R$ and $N$ are the
# reference and "new" image, respectively, $P_r$ and $P_n$ are their
# PSFs, $F_r$ and $F_n$ are their flux-based zero-points (which we
# will set to one here), $\sigma_r^2$ and $\sigma_n^2$ are their
# variance, and $\widehat{D}$ denotes the FT of $D$.
def performZOGY(im1, im2, im1_psf, im2_psf, sig1=None, sig2=None):
from scipy.fftpack import fft2, ifft2, ifftshift
if sig1 is None:
_, sig1 = computeClippedImageStats(im1)
if sig2 is None:
_, sig2 = computeClippedImageStats(im2)
F_r = F_n = 1.
R_hat = fft2(im1)
N_hat = fft2(im2)
P_r = im1_psf
P_n = im2_psf
P_r_hat = fft2(P_r)
P_n_hat = fft2(P_n)
d_hat_numerator = (F_r * P_r_hat * N_hat - F_n * P_n_hat * R_hat)
d_hat_denom = np.sqrt((sig1**2 * F_r**2 * np.abs(P_r_hat)**2) + (sig2**2 * F_n**2 * np.abs(P_n_hat)**2))
d_hat = d_hat_numerator / d_hat_denom
d = ifft2(d_hat)
D = ifftshift(d.real)
return D
def computePixelCovariance(diffim, diffim2=None):
diffim = diffim/diffim.std()
shifted_imgs2 = None
shifted_imgs = [
diffim,
np.roll(diffim, 1, 0), np.roll(diffim, -1, 0), np.roll(diffim, 1, 1), np.roll(diffim, -1, 1),
np.roll(np.roll(diffim, 1, 0), 1, 1), np.roll(np.roll(diffim, 1, 0), -1, 1),
np.roll(np.roll(diffim, -1, 0), 1, 1), np.roll(np.roll(diffim, -1, 0), -1, 1),
np.roll(diffim, 2, 0), np.roll(diffim, -2, 0), np.roll(diffim, 2, 1), np.roll(diffim, -2, 1),
np.roll(diffim, 3, 0), np.roll(diffim, -3, 0), np.roll(diffim, 3, 1), np.roll(diffim, -3, 1),
np.roll(diffim, 4, 0), np.roll(diffim, -4, 0), np.roll(diffim, 4, 1), np.roll(diffim, -4, 1),
np.roll(diffim, 5, 0), np.roll(diffim, -5, 0), np.roll(diffim, 5, 1), np.roll(diffim, -5, 1),
]
shifted_imgs = np.vstack([i.flatten() for i in shifted_imgs])
#out = np.corrcoef(shifted_imgs)
if diffim2 is not None:
shifted_imgs2 = [
diffim2,
np.roll(diffim2, 1, 0), np.roll(diffim2, -1, 0), np.roll(diffim2, 1, 1), np.roll(diffim2, -1, 1),
np.roll(np.roll(diffim2, 1, 0), 1, 1), np.roll(np.roll(diffim2, 1, 0), -1, 1),
np.roll(np.roll(diffim2, -1, 0), 1, 1), np.roll(np.roll(diffim2, -1, 0), -1, 1),
np.roll(diffim2, 2, 0), np.roll(diffim2, -2, 0), np.roll(diffim2, 2, 1), np.roll(diffim2, -2, 1),
np.roll(diffim2, 3, 0), np.roll(diffim2, -3, 0), np.roll(diffim2, 3, 1), np.roll(diffim2, -3, 1),
np.roll(diffim2, 4, 0), np.roll(diffim2, -4, 0), np.roll(diffim2, 4, 1), np.roll(diffim2, -4, 1),
np.roll(diffim2, 5, 0), np.roll(diffim2, -5, 0), np.roll(diffim2, 5, 1), np.roll(diffim2, -5, 1),
]
shifted_imgs2 = np.vstack([i.flatten() for i in shifted_imgs2])
out = np.cov(shifted_imgs, shifted_imgs2, bias=1)
tmp2 = out.copy()
np.fill_diagonal(tmp2, np.NaN)
stat = np.nansum(tmp2)/np.sum(np.diag(out)) # print sum of off-diag / sum of diag
return out, stat
# Compute ALZC correction kernel from matching kernel
# Here we use a constant kernel, just compute it for the center of the image.
def performALZCExposureCorrection(templateExposure, exposure, subtractedExposure, psfMatchingKernel, log):
import lsst.afw.image as afwImage
import lsst.meas.algorithms as measAlg
import lsst.afw.math as afwMath
spatialKernel = psfMatchingKernel
kimg = afwImage.ImageD(spatialKernel.getDimensions())
bbox = subtractedExposure.getBBox()
xcen = (bbox.getBeginX() + bbox.getEndX()) / 2.
ycen = (bbox.getBeginY() + bbox.getEndY()) / 2.
spatialKernel.computeImage(kimg, True, xcen, ycen)
# Compute the images' sigmas (sqrt of variance)
sig1 = templateExposure.getMaskedImage().getVariance().getArray()
sig2 = exposure.getMaskedImage().getVariance().getArray()
sig1squared, _ = computeClippedImageStats(sig1)
sig2squared, _ = computeClippedImageStats(sig2)
sig1 = np.sqrt(sig1squared)
sig2 = np.sqrt(sig2squared)
corrKernel = computeCorrectionKernelALZC(kimg.getArray(), sig1=sig1, sig2=sig2)
# Eventually, use afwMath.convolve(), but for now just use scipy.
log.info("ALZC: Convolving.")
pci, _ = doConvolve(subtractedExposure.getMaskedImage().getImage().getArray(),
corrKernel)
subtractedExposure.getMaskedImage().getImage().getArray()[:, :] = pci
log.info("ALZC: Finished with convolution.")
# Compute the subtracted exposure's updated psf
psf = subtractedExposure.getPsf().computeImage().getArray()
psfc = computeCorrectedDiffimPsfALZC(corrKernel, psf, sig1=sig1, sig2=sig2)
psfcI = afwImage.ImageD(subtractedExposure.getPsf().computeImage().getBBox())
psfcI.getArray()[:, :] = psfc
psfcK = afwMath.FixedKernel(psfcI)
psfNew = measAlg.KernelPsf(psfcK)
subtractedExposure.setPsf(psfNew)
return subtractedExposure, corrKernel
def computeClippedAfwStats(im, numSigmaClip=3., numIter=3, maskIm=None):
"""! Utility function for sigma-clipped array statistics on an image or exposure.
@param im An afw.Exposure, masked image, or image.
@return sigma-clipped mean, std, and variance of input array
"""
statsControl = afwMath.StatisticsControl()
statsControl.setNumSigmaClip(numSigmaClip)
statsControl.setNumIter(numIter)
ignoreMaskPlanes = ["INTRP", "EDGE", "DETECTED", "SAT", "CR", "BAD", "NO_DATA", "DETECTED_NEGATIVE"]
statsControl.setAndMask(afwImage.MaskU.getPlaneBitMask(ignoreMaskPlanes))
if maskIm is None:
statObj = afwMath.makeStatistics(im,
afwMath.MEANCLIP | afwMath.STDEVCLIP | afwMath.VARIANCECLIP,
statsControl)
else:
statObj = afwMath.makeStatistics(im, maskIm,
afwMath.MEANCLIP | afwMath.STDEVCLIP | afwMath.VARIANCECLIP,
statsControl)
mean = statObj.getValue(afwMath.MEANCLIP)
std = statObj.getValue(afwMath.STDEVCLIP)
var = statObj.getValue(afwMath.VARIANCECLIP)
return mean, std, var
def doConvolve(exposure, kernel, use_scipy=False):
"""! Convolve an Exposure with a decorrelation convolution kernel.
@param exposure Input afw.image.Exposure to be convolved.
@param kernel Input 2-d numpy.array to convolve the image with
@param use_scipy Use scipy to do convolution instead of afwMath
@return a new Exposure with the convolved pixels and the (possibly
re-centered) kernel.
@note We use afwMath.convolve() but keep scipy.convolve for debugging.
@note We re-center the kernel if necessary and return the possibly re-centered kernel
"""
def _fixEvenKernel(kernel):
"""! Take a kernel with even dimensions and make them odd, centered correctly.
@param kernel a numpy.array
@return a fixed kernel numpy.array
"""
# Make sure the peak (close to a delta-function) is in the center!
maxloc = np.unravel_index(np.argmax(kernel), kernel.shape)
out = np.roll(kernel, kernel.shape[0]//2 - maxloc[0], axis=0)
out = np.roll(out, out.shape[1]//2 - maxloc[1], axis=1)
# Make sure it is odd-dimensioned by trimming it.
if (out.shape[0] % 2) == 0:
maxloc = np.unravel_index(np.argmax(out), out.shape)
if out.shape[0] - maxloc[0] > maxloc[0]:
out = out[:-1, :]
else:
out = out[1:, :]
if out.shape[1] - maxloc[1] > maxloc[1]:
out = out[:, :-1]
else:
out = out[:, 1:]
return out
outExp = kern = None
fkernel = _fixEvenKernel(kernel)
if use_scipy:
from scipy.ndimage.filters import convolve
pci = convolve(exposure.getMaskedImage().getImage().getArray(),
fkernel, mode='constant', cval=np.nan)
outExp = exposure.clone()
outExp.getMaskedImage().getImage().getArray()[:, :] = pci
kern = fkernel
else:
kernelImg = afwImage.ImageD(fkernel.shape[0], fkernel.shape[1])
kernelImg.getArray()[:, :] = fkernel
kern = afwMath.FixedKernel(kernelImg)
maxloc = np.unravel_index(np.argmax(fkernel), fkernel.shape)
kern.setCtrX(maxloc[0])
kern.setCtrY(maxloc[1])
outExp = exposure.clone() # Do this to keep WCS, PSF, masks, etc.
convCntrl = afwMath.ConvolutionControl(False, True, 0)
afwMath.convolve(outExp.getMaskedImage(), exposure.getMaskedImage(), kern, convCntrl)
return outExp, kern
# Code taken from https://github.com/lsst-dm/dmtn-006/blob/master/python/diasource_mosaic.py
def mosaicDIASources(repo_dir, visitid, ccdnum=10, cutout_size=30,
template_catalog=None, xnear=None, ynear=None, sourceIds=None, gridSpec=[7, 4],
dipoleFlag='ip_diffim_ClassificationDipole_value'):
import matplotlib.pyplot as plt
import matplotlib
matplotlib.style.use('ggplot')
import matplotlib.gridspec as gridspec
import lsst.daf.persistence as dafPersist
#
# This matches up which exposures were differenced against which templates,
# and is purely specific to this particular set of data.
if template_catalog is None:
template_catalog = {197790: [197802, 198372, 198376, 198380, 198384],
197662: [198668, 199009, 199021, 199033],
197408: [197400, 197404, 197412],
197384: [197388, 197392],
197371: [197367, 197375, 197379]}
# Need to invert this to template_visit_catalog[exposure] = template
template_visit_catalog = {}
for templateid, visits in template_catalog.iteritems():
for visit in visits:
template_visit_catalog[visit] = templateid
def make_cutout(img, x, y, cutout_size=20):
return img[(x-cutout_size//2):(x+cutout_size//2), (y-cutout_size//2):(y+cutout_size//2)]
def group_items(items, group_length):
for n in xrange(0, len(items), group_length):
yield items[n:(n+group_length)]
b = dafPersist.Butler(repo_dir)
template_visit = template_visit_catalog[visitid]
templateExposure = b.get("calexp", visit=template_visit, ccdnum=ccdnum, immediate=True)
template_img, _, _ = templateExposure.getMaskedImage().getArrays()
template_wcs = templateExposure.getWcs()
sourceExposure = b.get("calexp", visit=visitid, ccdnum=ccdnum, immediate=True)
source_img, _, _ = sourceExposure.getMaskedImage().getArrays()
subtractedExposure = b.get("deepDiff_differenceExp", visit=visitid, ccdnum=ccdnum, immediate=True)
subtracted_img, _, _ = subtractedExposure.getMaskedImage().getArrays()
subtracted_wcs = subtractedExposure.getWcs()
diaSources = b.get("deepDiff_diaSrc", visit=visitid, ccdnum=ccdnum, immediate=True)
masked_img = subtractedExposure.getMaskedImage()
img_arr, mask_arr, var_arr = masked_img.getArrays()
z1, z2 = zscale_image(img_arr)
top_level_grid = gridspec.GridSpec(gridSpec[0], gridSpec[1])
source_ind = 0
for source_n, source in enumerate(diaSources):
source_id = source.getId()
if sourceIds is not None and not np.in1d(source_id, sourceIds)[0]:
continue
source_x = source.get("ip_diffim_NaiveDipoleCentroid_x")
source_y = source.get("ip_diffim_NaiveDipoleCentroid_y")
if xnear is not None and not np.any(np.abs(source_x - xnear) <= cutout_size):
continue
if ynear is not None and not np.any(np.abs(source_y - ynear) <= cutout_size):
continue
#is_dipole = source.get("ip_diffim_ClassificationDipole_value") == 1
dipoleLabel = ''
if source.get(dipoleFlag) == 1:
dipoleLabel = 'Dipole'
if source.get("ip_diffim_DipoleFit_flag_classificationAttempted") == 1:
dipoleLabel += ' *'
template_xycoord = template_wcs.skyToPixel(subtracted_wcs.pixelToSky(source_x, source_y))
cutouts = [make_cutout(template_img, template_xycoord.getY(), template_xycoord.getX(),
cutout_size=cutout_size),
make_cutout(source_img, source_y, source_x, cutout_size=cutout_size),
make_cutout(subtracted_img, source_y, source_x, cutout_size=cutout_size)]
try:
subgrid = gridspec.GridSpecFromSubplotSpec(1, 3, subplot_spec=top_level_grid[source_ind],
wspace=0)
except:
continue
for cutout_n, cutout in enumerate(cutouts):
plt.subplot(subgrid[0, cutout_n])
plt.imshow(cutout, vmin=z1, vmax=z2, cmap=plt.cm.gray)
plt.gca().xaxis.set_ticklabels([])
plt.gca().yaxis.set_ticklabels([])
plt.subplot(subgrid[0, 0])
source_ind += 1
#if is_dipole:
#print(source_n, source_id)
plt.ylabel(str(source_n) + dipoleLabel)
|
b75a53931c2fd2422326e088a77f933d9c3e8f04
|
[
"Markdown",
"Python"
] | 2 |
Markdown
|
djreiss/DM-6162
|
2fae9c2baa43d0b1365934c152bf14685334476f
|
55fe22267bb4e31b83ef19fa1632922284815e86
|
refs/heads/main
|
<repo_name>immahesh1/OS-Automation<file_sep>/README.md
# OS-Automation
## A mini project
## used <a href="https://www.npmjs.com/package/robotjs">RobotJs</a> and NodeJs to automate the operating system to open few required app.
To install Robotjs --> npm install robotjs
### just give <b>node index</b> and it will open
1. GIT Bash
2. few tabs on Google Chrome [Opens couple of windows]
(You can customise tabs in chrome.json)
3. Visual studio code
4. Notepad with a message
<file_sep>/index.js
var robot = require('robotjs')
var fs = require('fs')
setTimeout(openGITBash,2000);
function openGITBash(){
robot.moveMouseSmooth(53,750)
robot.mouseClick()
robot.typeString("GIT Bash")
robot.keyTap("enter")
setTimeout(openChrome,2000);
}
function openChrome(){
robot.moveMouseSmooth(53,750)
robot.mouseClick()
robot.typeString("google chrome")
robot.keyTap("enter")
// Opening tabs
setTimeout(openTabs,2000);
}
function openTabs(){
var rawdata = fs.readFileSync("./chrome.json")
var tabs = JSON.parse(rawdata)
for(var i=0; i<tabs.length; i++){
for(var j=0; j<tabs[i].length; j++){
robot.typeString(tabs[i][j])
robot.keyTap("enter")
if(j < tabs[i].length-1){
robot.keyToggle("control","down")
robot.keyTap("T")
robot.keyToggle("control","up")
}else if(i < tabs.length - 1){
robot.keyToggle("control","down")
robot.keyTap("n")
robot.keyToggle("control","up")
}
}
}
setTimeout(openVsCode,7000);
}
function openVsCode(){
robot.moveMouseSmooth(53,750)
robot.mouseClick()
robot.typeString("Visual Studio Code")
robot.keyTap("enter")
setTimeout(openNotePad,12000);
}
function openNotePad(){
robot.moveMouseSmooth(53,750)
robot.mouseClick()
robot.typeString("Notepad")
robot.keyTap("enter")
setTimeout(function(){
robot.typeStringDelayed("Setup is Ready! ")
robot.typeStringDelayed("Please start working...")
},2000)
}
|
cbee2b480dde670483c1d4088a6f0584ebefc6c2
|
[
"Markdown",
"JavaScript"
] | 2 |
Markdown
|
immahesh1/OS-Automation
|
f0954c87d2ca57de0b814f3749c811a19f51ca5c
|
6f6f51cc71ebc5ddbe9f97808fa7cd3ec1a98e04
|
refs/heads/new_webprofiler
|
<file_sep><?php
namespace Drupal\webprofiler\Panel;
/**
* Interface for dashboard panels.
*/
interface PanelInterface {
/**
* Render a panel.
*
* @param string $token
* A profile token.
* @param string $name
* The panel name.
*
* @return array
* A render array for this panel.
*/
public function render($token, $name): array;
}
<file_sep><?php
namespace Drupal\webprofiler\DataCollector;
use Drupal\Core\Controller\ControllerResolverInterface;
use Drupal\webprofiler\Panel\PanelInterface;
use Drupal\webprofiler\Panel\RequestPanel;
use Symfony\Component\HttpFoundation\ParameterBag;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\DataCollector\RequestDataCollector as BaseRequestDataCollector;
/**
* DataCollector for HTTP Request.
*/
class RequestDataCollector extends BaseRequestDataCollector implements DrupalDataCollectorInterface {
use DataCollectorTrait;
public const SERVICE_ID = 'service_id';
public const CALLABLE = 'callable';
/**
* The Controller resolver service.
*
* @var \Drupal\Core\Controller\ControllerResolverInterface
*/
private ControllerResolverInterface $controllerResolver;
/**
* The list of access checks applied to this request.
*
* @var array
*/
private array $accessChecks;
/**
* RequestDataCollector constructor.
*
* @param \Drupal\Core\Controller\ControllerResolverInterface $controllerResolver
* The Controller resolver service.
*/
public function __construct(ControllerResolverInterface $controllerResolver) {
parent::__construct();
$this->controllerResolver = $controllerResolver;
}
/**
* {@inheritdoc}
*/
public function collect(
Request $request,
Response $response
/*, \Throwable $exception = null*/
) {
parent::collect($request, $response);
if ($controller = $this->controllerResolver->getController($request)) {
$this->data['controller'] = $this->getMethodData(
$controller[0], $controller[1]
);
$this->data['access_checks'] = $this->accessChecks;
}
}
/**
* {@inheritdoc}
*/
public function getPanel(): PanelInterface {
return new RequestPanel();
}
/**
* Save an access check.
*
* @param string $service_id
* The service id of the service implementing the access check.
* @param array $callable
* The callable that implement the access check.
*/
public function addAccessCheck(
string $service_id,
array $callable
) {
$this->accessChecks[] = [
self::SERVICE_ID => $service_id,
self::CALLABLE => $this->getMethodData($callable[0], $callable[1]),
];
}
/**
* Return the list of access checks as ParameterBag.
*
* @return \Symfony\Component\HttpFoundation\ParameterBag
* The list of access checks.
*/
public function getAccessChecks(): ParameterBag {
return new ParameterBag($this->data['access_checks']->getValue());
}
}
<file_sep><?php
namespace Drupal\webprofiler\Entity;
use Drupal\webprofiler\Decorator;
/**
* Decorator for services that manage entities.
*/
class EntityDecorator extends Decorator {
/**
* Entities managed by services decorated with this decorator.
*
* @var array
*/
protected $entities;
/**
* Return the entities managed by services decorated with this decorator.
*
* @return mixed
* The entities managed by services decorated with this decorator.
*/
public function getEntities() {
return $this->entities;
}
}
<file_sep><?php
namespace Drupal\webprofiler;
use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\DependencyInjection\ServiceProviderBase;
use Drupal\webprofiler\Compiler\ProfilerPass;
use Symfony\Component\DependencyInjection\Reference;
/**
* Defines a service profiler for the webprofiler module.
*/
class WebprofilerServiceProvider extends ServiceProviderBase {
/**
* {@inheritdoc}
*/
public function register(ContainerBuilder $container) {
// Add a compiler pass to discover all data collector services.
$container->addCompilerPass(new ProfilerPass());
$modules = $container->getParameter('container.modules');
// Add BlockDataCollector only if Block module is enabled.
if (isset($modules['block'])) {
$container->register('webprofiler.blocks',
'Drupal\webprofiler\DataCollector\BlocksDataCollector')
->addArgument(new Reference(('entity_type.manager')))
->addTag('data_collector', [
'template' => '@webprofiler/Collector/blocks.html.twig',
'id' => 'blocks',
'title' => 'Blocks',
'priority' => 78,
]);
}
}
/**
* {@inheritdoc}
*/
public function alter(ContainerBuilder $container) {
// Replace the regular access_manager service with a traceable one.
$container->getDefinition('access_manager')
->setClass('Drupal\webprofiler\Access\AccessManagerWrapper')
->addMethodCall('setDataCollector',
[new Reference('webprofiler.request')]);
}
}
<file_sep><?php
namespace Drupal\webprofiler\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Render\RendererInterface;
use Drupal\Core\Routing\UrlGeneratorInterface;
use Drupal\webprofiler\Csp\ContentSecurityPolicyHandler;
use Drupal\webprofiler\Profiler\TemplateManager;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Profiler\Profiler;
/**
* Controller for the Webprofiler toolbar.
*/
class ProfilerController extends ControllerBase {
/**
* The Url generator service.
*
* @var \Drupal\Core\Routing\UrlGeneratorInterface
*/
private $generator;
/**
* The Profiler service.
*
* @var \Symfony\Component\HttpKernel\Profiler\Profiler
*/
private $profiler;
/**
* The Renderer service.
*
* @var \Drupal\Core\Render\RendererInterface
*/
private $renderer;
/**
* The Template manager service.
*
* @var \Drupal\webprofiler\Profiler\TemplateManager
*/
private $templateManager;
/**
* The Content-Security-Policy service.
*
* @var \Drupal\webprofiler\Csp\ContentSecurityPolicyHandler
*/
private $cspHandler;
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('url_generator'),
$container->get('webprofiler.profiler'),
$container->get('renderer'),
$container->get('webprofiler.template_manager'),
$container->get('webprofiler.csp')
);
}
/**
* ProfilerController constructor.
*
* @param \Drupal\Core\Routing\UrlGeneratorInterface $generator
* The Url generator service.
* @param \Symfony\Component\HttpKernel\Profiler\Profiler $profiler
* The Profiler service.
* @param \Drupal\Core\Render\RendererInterface $renderer
* The Renderer service.
* @param \Drupal\webprofiler\Profiler\TemplateManager $templateManager
* The Template manager service.
* @param \Drupal\webprofiler\Csp\ContentSecurityPolicyHandler $cspHandler
* The Content-Security-Policy service.
*/
final public function __construct(UrlGeneratorInterface $generator, Profiler $profiler, RendererInterface $renderer, TemplateManager $templateManager, ContentSecurityPolicyHandler $cspHandler) {
$this->generator = $generator;
$this->profiler = $profiler;
$this->renderer = $renderer;
$this->templateManager = $templateManager;
$this->cspHandler = $cspHandler;
}
/**
* Renders the Web Debug Toolbar.
*
* @param \Symfony\Component\HttpFoundation\Request $request
* The current HTTP Request.
* @param string $token
* The profiler token.
*
* @return \Symfony\Component\HttpFoundation\Response
* A Response instance.
*
* @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
*/
public function toolbarAction(Request $request, $token) {
if ('empty' === $token || NULL === $token) {
return new Response('', 200, ['Content-Type' => 'text/html']);
}
$this->profiler->disable();
if (!$profile = $this->profiler->loadProfile($token)) {
return new Response('', 404, ['Content-Type' => 'text/html']);
}
$url = NULL;
try {
$url = $this->generator->generate('webprofiler.toolbar', ['token' => $token], UrlGeneratorInterface::ABSOLUTE_URL);
}
catch (\Exception $e) {
// The profiler is not enabled.
}
$response = new Response('', 200, ['Content-Type' => 'text/html']);
$nonces = $this->cspHandler ? $this->cspHandler->getNonces($request, $response) : [];
$toolbar = [
'#theme' => 'webprofiler_toolbar',
'#request' => $request,
'#profile' => $profile,
'#templates' => $this->templateManager->getNames($profile),
'#profiler_url' => $url,
'#token' => $token,
'#csp_script_nonce' => isset($nonces['csp_script_nonce']) ? $nonces['csp_script_nonce'] : NULL,
'#csp_style_nonce' => isset($nonces['csp_style_nonce']) ? $nonces['csp_style_nonce'] : NULL,
];
$response->setContent($this->renderer->renderRoot($toolbar));
return $response;
}
}
<file_sep><?php
namespace Drupal\webprofiler\Entity;
use PhpParser\Node\Stmt\ClassMethod;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\PhpStorage\PhpStorageFactory;
use Drupal\webprofiler\DecoratorGeneratorInterface;
use PhpParser\Error;
use PhpParser\Node;
use PhpParser\Node\Stmt\Class_;
use PhpParser\NodeFinder;
use PhpParser\NodeTraverser;
use PhpParser\NodeVisitor\FindingVisitor;
use PhpParser\NodeVisitor\NameResolver;
use PhpParser\ParserFactory;
use Psr\Log\LoggerInterface;
use Twig\Error\Error as TwigError;
/**
* Generate decorators for config entity storage classes.
*/
class ConfigEntityStorageDecoratorGenerator implements DecoratorGeneratorInterface {
/**
* The Entity type manager service.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
private $entityTypeManager;
/**
* The logger service.
*
* @var \Psr\Log\LoggerInterface
*/
private $log;
/**
* DecoratorGenerator constructor.
*
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The Entity type manager service.
* @param \Psr\Log\LoggerInterface $log
* The logger service.
*/
public function __construct(EntityTypeManagerInterface $entity_type_manager, LoggerInterface $log) {
$this->entityTypeManager = $entity_type_manager;
$this->log = $log;
}
/**
* {@inheritdoc}
*/
public function generate() {
$classes = $this->getClasses();
foreach ($classes as $class) {
try {
$body = $this->createDecorator($class);
$this->writeDecorator($class['id'], $body);
}
catch (\Exception $e) {
throw new \Exception('Unable to generate decorator for class ' . $class['class'] . '. ' . $e->getMessage());
}
}
}
/**
* {@inheritdoc}
*/
public function getDecorators(): array {
return [
'taxonomy_vocabulary' => '\Drupal\webprofiler\Entity\VocabularyStorageDecorator',
'user_role' => '\Drupal\webprofiler\Entity\RoleStorageDecorator',
'shortcut_set' => '\Drupal\webprofiler\Entity\ShortcutSetStorageDecorator',
'image_style' => '\Drupal\webprofiler\Entity\ImageStyleStorageDecorator',
];
}
/**
* Return information about every config entity storage classes.
*
* @return array
* Information about every config entity storage classes.
*/
public function getClasses(): array {
$definitions = $this->entityTypeManager->getDefinitions();
$classes = [];
foreach ($definitions as $definition) {
try {
$classPath = $this->getClassPath($definition->getStorageClass());
$ast = $this->getAst($classPath);
$visitor = new FindingVisitor(function (Node $node) {
return $this->isConfigEntityStorage($node);
});
$traverser = new NodeTraverser();
$traverser->addVisitor($visitor);
$traverser->addVisitor(new NameResolver());
$traverser->traverse($ast);
$nodes = $visitor->getFoundNodes();
/** @var \PhpParser\Node\Stmt\Class_ $node */
foreach ($nodes as $node) {
$classes[$definition->id()] = [
'id' => $definition->id(),
'class' => $node->name->name,
'interface' => '\\' . implode('\\', $node->implements[0]->parts),
'decoratorClass' => '\\Drupal\\webprofiler\\Entity\\' . $node->name->name . 'Decorator',
];
}
}
catch (Error $error) {
echo "Parse error: {$error->getMessage()}\n";
return [];
}
catch (\ReflectionException $error) {
echo "Reflection error: {$error->getMessage()}\n";
return [];
}
}
return $classes;
}
/**
* Get the filename of the file in which the class has been defined.
*
* @param string $class
* A class name.
*
* @return string
* The filename of the file in which the class has been defined.
*
* @throws \ReflectionException
*/
private function getClassPath(string $class): string {
$reflector = new \ReflectionClass($class);
return $reflector->getFileName();
}
/**
* Parses PHP code into a node tree.
*
* @param string $classPath
* The filename of the file in which a class has been defined.
*
* @return \PhpParser\Node\Stmt[]|null
* Array of statements.
*/
private function getAst(string $classPath): array {
$code = file_get_contents($classPath);
$parser = (new ParserFactory())->create(ParserFactory::ONLY_PHP7);
return $parser->parse($code);
}
/**
* Return TRUE if this Node represent a config entity storage class.
*
* @param \PhpParser\Node $node
* The Node to check.
*
* @return bool
* TRUE if this Node represent a config entity storage class.
*/
private function isConfigEntityStorage(Node $node): bool {
if ($node instanceof Class_
&& $node->extends !== NULL &&
$node->implements !== NULL &&
$node->extends->parts[0] == 'ConfigEntityStorage' &&
$node->implements[0]->parts[0] != ''
) {
return TRUE;
}
return FALSE;
}
/**
* Create the decorator from class information.
*
* @param array $class
* The class information.
*
* @return string
* The decorator class body.
*
* @throws \Exception
*/
private function createDecorator(array $class): string {
$decorator = $class['class'] . 'Decorator';
$classPath = $this->getClassPath($class['interface']);
$ast = $this->getAst($classPath);
$nodeFinder = new NodeFinder();
$nodes = $nodeFinder->find($ast, function (Node $node) {
return $node instanceof ClassMethod;
});
$methods = [];
/** @var \PhpParser\Node\Stmt\ClassMethod $node */
foreach ($nodes as $node) {
$params = [];
/** @var \PhpParser\Node\Param $param */
foreach ($node->getParams() as $param) {
$params[] = [
'name' => $param->var->name,
];
}
$methods[] = [
'name' => $node->name->name,
'params' => $params,
];
}
try {
/** @var \Twig\Environment $twig */
$twig = \Drupal::service('twig');
return $twig->render('@webprofiler/Decorator/storageDecorator.php.twig', [
'decorator' => $decorator,
'interface' => $class['interface'],
'methods' => $methods,
]);
}
catch (TwigError $e) {
throw new \Exception('Unable to create a decorator. ' . $e->getMessage());
}
}
/**
* Write a decorator class body to file.
*
* @param string $name
* The class name.
* @param string $body
* The class body.
*/
private function writeDecorator(string $name, string $body) {
$storage = PhpStorageFactory::get('webprofiler');
if (!$storage->exists($name)) {
$storage->save($name, $body);
}
}
}
<file_sep><?php
namespace Drupal\webprofiler\EventListener;
use Drupal\Core\Config\ConfigFactoryInterface;
use Symfony\Component\HttpFoundation\RequestMatcherInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpKernel\EventListener\ProfilerListener as SymfonyProfilerListener;
use Symfony\Component\HttpKernel\Profiler\Profiler;
/**
* ProfilerListener collects data for the current request.
*/
class ProfilerListener extends SymfonyProfilerListener {
/**
* An immutable config object.
*
* @var \Drupal\Core\Config\ImmutableConfig
*/
private $config;
/**
* ProfilerListener constructor.
*
* @param \Symfony\Component\HttpKernel\Profiler\Profiler $profiler
* The profiler service.
* @param \Symfony\Component\HttpFoundation\RequestStack $requestStack
* The request stack service.
* @param \Symfony\Component\HttpFoundation\RequestMatcherInterface $matcher
* The request matcher service.
* @param \Drupal\Core\Config\ConfigFactoryInterface $config
* The config factory service.
*/
public function __construct(Profiler $profiler, RequestStack $requestStack, RequestMatcherInterface $matcher, ConfigFactoryInterface $config) {
$this->config = $config->get('webprofiler.settings');
parent::__construct($profiler, $requestStack, $matcher, FALSE, FALSE);
}
}
<file_sep><?php
namespace Drupal\webprofiler\DataCollector;
use Drupal\webprofiler\MethodData;
use Symfony\Component\VarDumper\Caster\Caster;
use Symfony\Component\VarDumper\Caster\LinkStub;
use Symfony\Component\VarDumper\Cloner\Stub;
/**
* Trait with common code for data collectors.
*/
trait DataCollectorTrait {
/**
* Return information about a method of a class.
*
* @param mixed $class
* A class name.
* @param string $method
* A method name.
*
* @return \Drupal\webprofiler\MethodData
* Array of information about a method of a class.
*/
public function getMethodData($class, string $method): ?MethodData {
$class = is_object($class) ? get_class($class) : $class;
$data = NULL;
try {
$reflectedMethod = new \ReflectionMethod($class, $method);
$data = new MethodData(
$class,
$method,
$reflectedMethod->getFilename(),
$reflectedMethod->getStartLine()
);
}
catch (\ReflectionException $re) {
return NULL;
}
finally {
return $data;
}
}
/**
* Convert a numeric value to a human readable string.
*
* @param string $value
* The value to convert.
*
* @return int
* A human readable string.
*/
private function convertToBytes(string $value) {
if ('-1' === $value) {
return -1;
}
$value = strtolower($value);
$max = strtolower(ltrim($value, '+'));
if (0 === strpos($max, '0x')) {
$max = intval($max, 16);
}
elseif (0 === strpos($max, '0')) {
$max = intval($max, 8);
}
else {
$max = intval($max);
}
switch (substr($value, -1)) {
case 't':
$max *= 1024 * 1024 * 1024 * 1024;
break;
case 'g':
$max *= 1024 * 1024 * 1024;
break;
case 'm':
$max *= 1024 * 1024;
break;
case 'k':
$max *= 1024;
break;
}
return $max;
}
/**
* {@inheritDoc}
*/
protected function getCasters(): array {
return parent::getCasters() + [
MethodData::class => function (MethodData $md, array $a, Stub $stub) {
$a[Caster::PREFIX_DYNAMIC . 'link'] = new LinkStub($md->getClass() . '::' . $md->getMethod(),
$md->getLine(), 'file://' . $md->getFile());
return $a;
},
];
}
}
<file_sep><?php
namespace Drupal\webprofiler\Controller;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\HtmlCommand;
use Drupal\Core\Controller\ControllerBase;
use Drupal\webprofiler\DataCollector\DrupalDataCollectorInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Profiler\Profiler;
/**
* Controller for the Webprofiler dashboard.
*/
class DashboardController extends ControllerBase {
/**
* The Profiler service.
*
* @var \Symfony\Component\HttpKernel\Profiler\Profiler
*/
private $profiler;
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('webprofiler.profiler')
);
}
/**
* DashboardController constructor.
*
* @param \Symfony\Component\HttpKernel\Profiler\Profiler $profiler
* The Profiler service.
*/
final public function __construct(Profiler $profiler) {
$this->profiler = $profiler;
}
/**
* Controller for the whole dashboard page.
*
* @param \Symfony\Component\HttpFoundation\Request $request
* A Request.
*
* @return array
* A render array for webprofiler_dashboard theme.
*/
public function dashboard(Request $request) {
$this->profiler->disable();
$token = $request->get('token');
$profile = $this->profiler->loadProfile($token);
if ($profile == NULL) {
return [];
}
/** @var \Symfony\Component\HttpKernel\DataCollector\DataCollectorInterface $el */
$collectors = array_filter($profile->getCollectors(), function ($el) {
return [
'name' => $el->getName(),
];
});
return [
'#theme' => 'webprofiler_dashboard',
'#collectors' => $collectors,
'#token' => $token,
'#profile' => $profile,
'#attached' => [
'library' => [
'webprofiler/dashboard',
],
],
];
}
/**
* Renders a profiler panel for the given token and type.
*
* @param string $token
* The profiler token.
* @param string $name
* The panel name to render.
*
* @return \Symfony\Component\HttpFoundation\JsonResponse
* A Response instance.
*/
public function panel($token, $name) {
$this->profiler->disable();
if ('empty' === $token || NULL === $token || NULL === $name) {
return new JsonResponse('');
}
if (!$profile = $this->profiler->loadProfile($token)) {
return new JsonResponse('');
}
$collector = $profile->getCollector($name);
if (!($collector instanceof DrupalDataCollectorInterface)) {
return new JsonResponse('');
}
$panel = $collector->getPanel();
$response = new AjaxResponse();
$response->addCommand(
new HtmlCommand(
'#js-webprofiler-panel',
$panel->render($token, $name)
)
);
return $response;
}
}
<file_sep><?php
namespace Drupal\webprofiler\Panel;
/**
* Panel to render collected data about blocks.
*/
class BlocksPanel extends PanelBase implements PanelInterface {
/**
* {@inheritDoc}
*/
public function render($token, $name): array {
/** @var \Symfony\Component\HttpKernel\Profiler\Profiler $profiler */
$profiler = \Drupal::service('webprofiler.profiler');
/** @var \Drupal\webprofiler\DataCollector\BlocksDataCollector $collector */
$collector = $profiler->loadProfile($token)->getCollector($name);
$data = array_merge(
$this->renderBlocks($collector->getLoadedBlocks(), 'Loaded'),
$this->renderBlocks($collector->getRenderedBlocks(), 'Rendered'),
);
return [
'#theme' => 'webprofiler_dashboard_panel',
'#title' => $this->t('Blocks'),
'#data' => $data,
];
}
/**
* Render a list of blocks.
*
* @param array $blocks
* The list of blocks to render.
* @param string $label
* The list label.
*
* @return array
* The render array of the list of blocks.
*/
protected function renderBlocks(array $blocks, string $label): array {
if (count($blocks) == 0) {
return [
$label => [
'#markup' => '<p>' . $this->t('No @label blocks collected',
['@label' => $label]) . '</p>',
],
];
}
$rows = [];
foreach ($blocks as $block) {
$rows[] = [
$block['id'],
$block['settings']['label'],
$block['region'] ?? 'No region',
$block['settings']['provider'],
$block['theme'],
$block['status'] ? $this->t('Enabled') : $this->t('Disabled'),
$block['plugin'],
];
}
return [
$label => [
'#theme' => 'webprofiler_dashboard_table',
'#title' => $label,
'#data' => [
'#type' => 'table',
'#header' => [
$this->t('ID'),
$this->t('Label'),
$this->t('Region'),
$this->t('Source'),
[
'data' => $this->t('Theme'),
'class' => [RESPONSIVE_PRIORITY_LOW],
],
$this->t('Status'),
[
'data' => $this->t('Plugin'),
'class' => [RESPONSIVE_PRIORITY_LOW],
],
],
'#rows' => $rows,
'#attributes' => [
'class' => [
'webprofiler__table',
],
],
'#sticky' => TRUE,
],
],
];
}
}
<file_sep><?php
namespace Drupal\webprofiler\Entity;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Config\Entity\ConfigEntityStorageInterface;
use Drupal\Core\DependencyInjection\ClassResolverInterface;
use Drupal\Core\Entity\EntityLastInstalledSchemaRepositoryInterface;
use Drupal\Core\Entity\EntityTypeManager;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Entity\EntityViewBuilderInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\PhpStorage\PhpStorageFactory;
use Drupal\Core\StringTranslation\TranslationInterface;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
/**
* Wrap the entity type manager service to collect loaded and rendered entities.
*/
class EntityTypeManagerWrapper extends EntityTypeManager implements EntityTypeManagerInterface, ContainerAwareInterface {
/**
* Loaded entities.
*
* @var array
*/
private $loaded;
/**
* Rendered entities.
*
* @var array
*/
private $rendered;
/**
* The original entity type manager service.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
private $entityManager;
/**
* EntityTypeManagerWrapper constructor.
*
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_manager
* The original entity manager service.
* @param \Traversable $namespaces
* An object that implements \Traversable which contains the root paths
* keyed by the corresponding namespace to look for plugin implementations.
* @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
* The module handler.
* @param \Drupal\Core\Cache\CacheBackendInterface $cache
* The cache backend to use.
* @param \Drupal\Core\StringTranslation\TranslationInterface $string_translation
* The string translation.
* @param \Drupal\Core\DependencyInjection\ClassResolverInterface $class_resolver
* The class resolver.
* @param \Drupal\Core\Entity\EntityLastInstalledSchemaRepositoryInterface $entity_last_installed_schema_repository
* The entity last installed schema repository.
*/
public function __construct(EntityTypeManagerInterface $entity_manager, \Traversable $namespaces, ModuleHandlerInterface $module_handler, CacheBackendInterface $cache, TranslationInterface $string_translation, ClassResolverInterface $class_resolver, EntityLastInstalledSchemaRepositoryInterface $entity_last_installed_schema_repository) {
$this->entityManager = $entity_manager;
parent::__construct($namespaces, $module_handler, $cache, $string_translation, $class_resolver, $entity_last_installed_schema_repository);
}
/**
* {@inheritdoc}
*/
public function getStorage($entity_type) {
/** @var \Drupal\Core\Config\Entity\ConfigEntityStorageInterface $handler */
$handler = $this->getHandler($entity_type, 'storage');
$entity_kind = ($handler instanceof ConfigEntityStorageInterface) ? 'config' : 'content';
if (!isset($this->loaded[$entity_kind][$entity_type])) {
$handler = $this->getStorageDecorator($entity_type, $handler);
$this->loaded[$entity_kind][$entity_type] = $handler;
}
else {
$handler = $this->loaded[$entity_kind][$entity_type];
}
return $handler;
}
/**
* {@inheritdoc}
*/
public function getViewBuilder($entity_type) {
/** @var \Drupal\Core\Entity\EntityViewBuilderInterface $handler */
$handler = $this->getHandler($entity_type, 'view_builder');
if ($handler instanceof EntityViewBuilderInterface) {
if (!isset($this->rendered[$entity_type])) {
$handler = new EntityViewBuilderDecorator($handler);
$this->rendered[$entity_type] = $handler;
}
else {
$handler = $this->rendered[$entity_type];
}
}
return $handler;
}
/**
* Return loaded entities.
*
* @param string $entity_kind
* The kind of the entity: config or content.
* @param string $entity_type
* The entity type.
*
* @return array
* Loaded entities.
*/
public function getLoaded($entity_kind, $entity_type) {
return isset($this->loaded[$entity_kind][$entity_type]) ? $this->loaded[$entity_kind][$entity_type] : NULL;
}
/**
* Return rendered entities.
*
* @param string $entity_type
* The entity type.
*
* @return array
* Rendered entities.
*/
public function getRendered($entity_type) {
return isset($this->rendered[$entity_type]) ? $this->rendered[$entity_type] : NULL;
}
/**
* Return a decorator for the storage handler.
*
* @param string $entity_type
* The entity type.
* @param object $handler
* The original storage handler.
*
* @return \Drupal\Core\Config\Entity\ConfigEntityStorageInterface
* A decorator for the storage handler.
*/
private function getStorageDecorator($entity_type, $handler) {
// Loaded this way to avoid circular references.
/** @var \Drupal\webprofiler\DecoratorGeneratorInterface $decoratorGenerator */
$decoratorGenerator = \Drupal::service('webprofiler.config_entity_storage_decorator_generator');
$decorators = $decoratorGenerator->getDecorators();
$storage = PhpStorageFactory::get('webprofiler');
if ($handler instanceof ConfigEntityStorageInterface) {
if (array_key_exists($entity_type, $decorators)) {
$storage->load($entity_type);
if (!class_exists($decorators[$entity_type])) {
try {
$decoratorGenerator->generate();
$storage->load($entity_type);
}
catch (\Exception $e) {
return $handler;
}
}
return new $decorators[$entity_type]($handler);
}
return new ConfigEntityStorageDecorator($handler);
}
return $handler;
}
}
<file_sep><?php
namespace Drupal\webprofiler\DataCollector;
use Drupal\webprofiler\Panel\PanelInterface;
/**
* Interface for DataCollector classes.
*/
interface DrupalDataCollectorInterface {
/**
* Return the class used to render data for this data collector.
*
* @return \Drupal\webprofiler\Panel\PanelInterface
* A class that can render this data collector.
*/
public function getPanel(): PanelInterface;
}
<file_sep><?php
namespace Drupal\webprofiler\RequestMatcher;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Path\PathMatcherInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestMatcherInterface;
/**
* Exclude some path to be profiled.
*/
class WebprofilerRequestMatcher implements RequestMatcherInterface {
/**
* An immutable config object.
*
* @var \Drupal\Core\Config\ImmutableConfig
*/
private $config;
/**
* The path matcher service.
*
* @var \Drupal\Core\Path\PathMatcherInterface
*/
private $pathMatcher;
/**
* WebprofilerRequestMatcher constructor.
*
* @param \Drupal\Core\Config\ConfigFactoryInterface $config
* The config factory service.
* @param \Drupal\Core\Path\PathMatcherInterface $pathMatcher
* The path matcher service.
*/
public function __construct(ConfigFactoryInterface $config, PathMatcherInterface $pathMatcher) {
$this->config = $config->get('webprofiler.settings');
$this->pathMatcher = $pathMatcher;
}
/**
* {@inheritdoc}
*/
public function matches(Request $request) {
$path = $request->getPathInfo();
$patterns = $this->config->get('exclude_paths');
// Never add Webprofiler to phpinfo page.
$patterns .= "\r\n/admin/reports/status/php";
// Never add Webprofiler to uninstall confirm page.
$patterns .= "\r\n/admin/modules/uninstall/*";
return !$this->pathMatcher->matchPath($path, $patterns);
}
}
<file_sep><?php
namespace Drupal\webprofiler\Commands;
use Drupal\webprofiler\DecoratorGeneratorInterface;
use Drush\Commands\DrushCommands;
/**
* Drush commands for Webprofiler.
*/
class WebprofilerCommands extends DrushCommands {
/**
* The decorator generator service.
*
* @var \Drupal\webprofiler\DecoratorGeneratorInterface
*/
private $generator;
/**
* WebprofilerCommands constructor.
*
* @param \Drupal\webprofiler\DecoratorGeneratorInterface $generator
* The decorator generator service.
*/
public function __construct(DecoratorGeneratorInterface $generator) {
parent::__construct();
$this->generator = $generator;
}
/**
* Generate decorators for ConfigEntityStorageInterface.
*
* @command webprofiler:generateDecorators
* @aliases wp-decorators
*/
public function generateDecorators() {
try {
$this->generator->generate();
}
catch (\Exception $e) {
$this->writeln($e->getMessage());
}
}
}
<file_sep><?php
namespace Drupal\webprofiler;
/**
* Value object to store some method data from reflection.
*/
class MethodData {
/**
* The method class.
*
* @var string
*/
private string $class;
/**
* The method name.
*
* @var string
*/
private string $method;
/**
* The method file.
*
* @var string
*/
private string $file;
/**
* The method line in file.
*
* @var string
*/
private string $line;
/**
* MethodData constructor.
*
* @param string $class
* The method class.
* @param string $method
* The method name.
* @param string $file
* The method file.
* @param string $line
* The method line in file.
*/
public function __construct(string $class, string $method, string $file, string $line) {
$this->class = $class;
$this->method = $method;
$this->file = $file;
$this->line = $line;
}
/**
* Return the method class.
*
* @return string
* The method class.
*/
public function getClass(): string {
return $this->class;
}
/**
* Return the method name.
*
* @return string
* The method name.
*/
public function getMethod(): string {
return $this->method;
}
/**
* Return the method file.
*
* @return string
* The method file.
*/
public function getFile(): string {
return $this->file;
}
/**
* Return the method line in file.
*
* @return string
* The method line in file.
*/
public function getLine(): string {
return $this->line;
}
}
<file_sep><?php
namespace Drupal\webprofiler\Csp;
/**
* Generates Content-Security-Policy nonce.
*
* @internal
*/
class NonceGenerator {
/**
* Generates Content-Security-Policy nonce.
*
* @return string
* A nonce.
*
* @throws \Exception
*/
public function generate() {
return bin2hex(random_bytes(16));
}
}
<file_sep><?php
namespace Drupal\webprofiler\Panel;
use Drupal\webprofiler\DataCollector\RequestDataCollector;
/**
* Panel to render collected data about the request.
*/
class RequestPanel extends PanelBase implements PanelInterface {
/**
* {@inheritDoc}
*/
public function render($token, $name): array {
/** @var \Symfony\Component\HttpKernel\Profiler\Profiler $profiler */
$profiler = \Drupal::service('webprofiler.profiler');
/** @var \Drupal\webprofiler\DataCollector\RequestDataCollector $collector */
$collector = $profiler->loadProfile($token)->getCollector($name);
$data = array_merge(
$this->renderTable(
$collector->getRequestQuery()->all(), 'GET parameters'),
$this->renderTable(
$collector->getRequestRequest()->all(), 'POST parameters'),
$this->renderTable(
$collector->getRequestAttributes()->all(), 'Request attributes'),
$this->renderAccessChecks(
$collector->getAccessChecks()->all(), 'Access check'),
$this->renderTable(
$collector->getRequestCookies()->all(), 'Cookies'),
$this->renderTable(
$collector->getSessionMetadata(), 'Session Metadata'),
$this->renderTable(
$collector->getSessionAttributes(), 'Session Attributes'),
$this->renderTable(
$collector->getRequestHeaders()->all(), 'Request headers'),
$this->renderContent(
$collector->getContent(), 'Raw content'),
$this->renderTable(
$collector->getRequestServer()->all(), 'Server Parameters'),
$this->renderTable(
$collector->getResponseHeaders()->all(), 'Response headers')
);
return [
'#theme' => 'webprofiler_dashboard_panel',
'#title' => $this->t('Request'),
'#data' => $data,
];
}
/**
* Render the content of a POST request.
*
* @param string $content
* The content of a POST request.
* @param string $label
* The section label.
*
* @return array
* The render array of the content.
*/
private function renderContent($content, $label): array {
return [
$label => [
'#type' => 'inline_template',
'#template' => '<h3>{{ title }}</h3> {{ data|raw }}',
'#context' => [
'title' => $this->t($label),
'data' => $content,
],
],
];
}
/**
* Render the list of access checks.
*
* @param array $accessChecks
* The list of access checks.
* @param string $label
* The section label.
*
* @return array
* The render array of the list of access checks.
*/
private function renderAccessChecks(array $accessChecks, $label): array {
if (count($accessChecks) == 0) {
return [];
}
$rows = [];
/** @var \Symfony\Component\VarDumper\Cloner\Data $el */
foreach ($accessChecks as $el) {
$service_id = $el->getValue()[RequestDataCollector::SERVICE_ID];
$callable = $el->getValue()[RequestDataCollector::CALLABLE];
$rows[] = [
[
'data' => $service_id->getValue(),
'class' => 'webprofiler__key',
],
[
'data' => [
'#type' => 'inline_template',
'#template' => '{{ data|raw }}',
'#context' => [
'data' => $this->dumpData($callable),
],
],
'class' => 'webprofiler__value',
],
];
}
return [
$label => [
'#theme' => 'webprofiler_dashboard_table',
'#title' => $this->t($label),
'#data' => [
'#type' => 'table',
'#header' => [$this->t('Name'), $this->t('Value')],
'#rows' => $rows,
'#attributes' => [
'class' => [
'webprofiler__table',
],
],
],
],
];
}
}
<file_sep><?php
namespace Drupal\webprofiler\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Link;
use Drupal\Core\Url;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Controller for the report page.
*/
class ReportController extends ControllerBase {
/**
* The Profiler service.
*
* @var \Symfony\Component\HttpKernel\Profiler\Profiler
*/
private $profiler;
/**
* The Date formatter service.
*
* @var \Drupal\Core\Datetime\DateFormatter
*/
private $dateFormatter;
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
$instance = parent::create($container);
$instance->profiler = $container->get('webprofiler.profiler');
$instance->dateFormatter = $container->get('date.formatter');
return $instance;
}
/**
* Generates the list page.
*
* @param \Symfony\Component\HttpFoundation\Request $request
* A request object.
*
* @return array
* A render array for the profile list table.
*/
public function list(Request $request) {
$limit = $request->get('limit', 10);
$this->profiler->disable();
$ip = $request->query->get('ip');
$method = $request->query->get('method');
$url = $request->query->get('url');
$profiles = $this->profiler->find($ip, $url, $limit, $method, '', '');
$rows = [];
if (count($profiles)) {
foreach ($profiles as $profile) {
$row = [];
$row[] = Link::fromTextAndUrl($profile['token'], new Url('webprofiler.dashboard', ['token' => $profile['token']]))->toString();
$row[] = $profile['ip'];
$row[] = $profile['method'];
$row[] = $profile['url'];
$row[] = $this->dateFormatter->format($profile['time']);
$rows[] = $row;
}
}
else {
$rows[] = [
[
'data' => $this->t('No profiles found'),
'colspan' => 6,
],
];
}
$build = [];
$build['table'] = [
'#type' => 'table',
'#rows' => $rows,
'#header' => [
$this->t('Token'),
[
'data' => $this->t('Ip'),
'class' => [RESPONSIVE_PRIORITY_LOW],
],
[
'data' => $this->t('Method'),
'class' => [RESPONSIVE_PRIORITY_LOW],
],
$this->t('Url'),
[
'data' => $this->t('Time'),
'class' => [RESPONSIVE_PRIORITY_MEDIUM],
],
],
'#sticky' => TRUE,
];
return $build;
}
}
<file_sep><?php
namespace Drupal\webprofiler;
/**
* Interface for decorator generators.
*/
interface DecoratorGeneratorInterface {
/**
* Generates Entity Storage decorators.
*
* @throws \Exception
*/
public function generate();
/**
* Return the list of all available decorators.
*
* @return array
* The list of all available decorators.
*/
public function getDecorators(): array;
}
<file_sep><?php
namespace Drupal\webprofiler\EventListener;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Render\RendererInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\webprofiler\Csp\ContentSecurityPolicyHandler;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
/**
* Listen to kernel response event to inject the toolbar.
*/
class WebDebugToolbarListener implements EventSubscriberInterface {
/**
* The renderer service.
*
* @var \Drupal\Core\Render\RendererInterface
*/
protected $renderer;
/**
* The current user.
*
* @var \Drupal\Core\Session\AccountInterface
*/
private $currentUser;
/**
* The url generator service.
*
* @var \Symfony\Component\Routing\Generator\UrlGeneratorInterface
*/
protected $urlGenerator;
/**
* The Content-Security-Policy handler service.
*
* @var \Drupal\webprofiler\Csp\ContentSecurityPolicyHandler
*/
private $cspHandler;
/**
* An immutable config object.
*
* @var \Drupal\Core\Config\ImmutableConfig
*/
private $config;
/**
* WebDebugToolbarListener constructor.
*
* @param \Drupal\Core\Render\RendererInterface $renderer
* The renderer service.
* @param \Drupal\Core\Session\AccountInterface $currentUser
* The current user.
* @param \Symfony\Component\Routing\Generator\UrlGeneratorInterface $urlGenerator
* The url generator service.
* @param \Drupal\webprofiler\Csp\ContentSecurityPolicyHandler $cspHandler
* The Content-Security-Policy handler service.
* @param \Drupal\Core\Config\ConfigFactoryInterface $config
* The config factory service.
*/
public function __construct(RendererInterface $renderer, AccountInterface $currentUser, UrlGeneratorInterface $urlGenerator, ContentSecurityPolicyHandler $cspHandler, ConfigFactoryInterface $config) {
$this->renderer = $renderer;
$this->currentUser = $currentUser;
$this->urlGenerator = $urlGenerator;
$this->cspHandler = $cspHandler;
$this->config = $config->get('webprofiler.settings');
}
/**
* {@inheritDoc}
*/
public static function getSubscribedEvents() {
return [
KernelEvents::RESPONSE => ['onKernelResponse', -128],
];
}
/**
* Listen for the kernel.response event.
*
* @param \Symfony\Component\HttpKernel\Event\ResponseEvent $event
* A response event.
*/
public function onKernelResponse(ResponseEvent $event) {
$response = $event->getResponse();
$request = $event->getRequest();
if ($response->headers->has('X-Debug-Token') && NULL !== $this->urlGenerator) {
try {
$response->headers->set(
'X-Debug-Token-Link',
$this->urlGenerator->generate('webprofiler.toolbar', ['token' => $response->headers->get('X-Debug-Token')], UrlGeneratorInterface::ABSOLUTE_URL)
);
}
catch (\Exception $e) {
$response->headers->set('X-Debug-Error', \get_class($e) . ': ' . preg_replace('/\s+/', ' ', $e->getMessage()));
}
}
if (!$event->isMasterRequest()) {
return;
}
$nonces = $this->cspHandler ? $this->cspHandler->updateResponseHeaders($request, $response) : [];
// Do not capture redirects or modify XML HTTP Requests.
if ($request->isXmlHttpRequest()) {
return;
}
if ($response->headers->has('X-Debug-Token') && $response->isRedirect() && $this->config->get('intercept_redirects') && 'html' === $request->getRequestFormat()) {
$toolbarRedirect = [
'#theme' => 'webprofiler_toolbar_redirect',
'#location' => $response->headers->get('Location'),
];
$response->setContent($this->renderer->renderRoot($toolbarRedirect));
$response->setStatusCode(200);
$response->headers->remove('Location');
}
if (!$response->headers->has('X-Debug-Token')
|| $response->isRedirection()
|| ($response->headers->has('Content-Type') && FALSE === strpos($response->headers->get('Content-Type'), 'html'))
|| 'html' !== $request->getRequestFormat()
|| FALSE !== stripos($response->headers->get('Content-Disposition'), 'attachment;')
) {
return;
}
if ($this->currentUser->hasPermission('view webprofiler toolbar')) {
$this->injectToolbar($response, $request, $nonces);
}
}
/**
* Injects the web debug toolbar into the given Response.
*
* @param \Symfony\Component\HttpFoundation\Response $response
* A response.
* @param \Symfony\Component\HttpFoundation\Request $request
* A request.
* @param array $nonces
* Nonces used in Content-Security-Policy header.
*/
protected function injectToolbar(Response $response, Request $request, array $nonces) {
$content = $response->getContent();
$pos = strripos($content, '</body>');
if (FALSE !== $pos) {
$toolbarJs = [
'#theme' => 'webprofiler_toolbar_js',
'#token' => $response->headers->get('X-Debug-Token'),
'#request' => $request,
'#csp_script_nonce' => isset($nonces['csp_script_nonce']) ? $nonces['csp_script_nonce'] : NULL,
'#csp_style_nonce' => isset($nonces['csp_style_nonce']) ? $nonces['csp_style_nonce'] : NULL,
];
$toolbar = "\n" . str_replace("\n", '', $this->renderer->renderRoot($toolbarJs)) . "\n";
$content = substr($content, 0, $pos) . $toolbar . substr($content, $pos);
$response->setContent($content);
}
}
}
<file_sep><?php
namespace Drupal\webprofiler\Twig\Extension;
use Symfony\Component\HttpKernel\Debug\FileLinkFormatter;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
/**
* Twig extension relate to PHP code and used by Webprofiler.
*/
class CodeExtension extends AbstractExtension {
/**
* The File link formatter service.
*
* @var \Symfony\Component\HttpKernel\Debug\FileLinkFormatter
*/
private FileLinkFormatter $fileLinkFormat;
/**
* CodeExtension constructor.
*
* @param \Symfony\Component\HttpKernel\Debug\FileLinkFormatter $file_link_format
* The File link formatter service.
*/
public function __construct(FileLinkFormatter $file_link_format) {
$this->fileLinkFormat = $file_link_format;
}
/**
* {@inheritdoc}
*/
public function getFilters(): array {
return [
new TwigFilter('abbr_class', [$this, 'abbrClass'],
['is_safe' => ['html']]),
new TwigFilter('file_link', [$this, 'getFileLink']),
];
}
/**
* Return the abbreviated form of a class name.
*
* @param string $class
* The class name to abbreviate.
*
* @return string
* The abbreviated form of a class name.
*/
public function abbrClass($class) {
$parts = explode('\\', $class);
$short = array_pop($parts);
return sprintf('<abbr title="%s">%s</abbr>', $class, $short);
}
/**
* Returns the link for a given file/line pair.
*
* @param string $file
* An absolute file path.
* @param int $line
* The line number.
*
* @return string|false
* A link or false.
*/
public function getFileLink(string $file, int $line) {
if ($fmt = $this->fileLinkFormat) {
return \is_string($fmt) ? strtr($fmt,
['%f' => $file, '%l' => $line]) : $fmt->format($file, $line);
}
return FALSE;
}
}
<file_sep><?php
namespace Drupal\webprofiler\Profiler;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Profiler\Profile;
use Symfony\Component\HttpKernel\Profiler\Profiler;
use Twig\Environment;
/**
* Profiler Templates Manager.
*/
class TemplateManager {
/**
* The profiler service.
*
* @var \Symfony\Component\HttpKernel\Profiler\Profiler
*/
protected $profiler;
/**
* The Twig environment service.
*
* @var \Twig\Environment
*/
protected $twig;
/**
* Data collector templates retrieved by ProfilerPass class.
*
* @var array
*/
protected $templates;
/**
* TemplateManager constructor.
*
* @param \Symfony\Component\HttpKernel\Profiler\Profiler $profiler
* The profiler service.
* @param \Twig\Environment $twig
* The Twig environment service.
* @param array $templates
* Data collector templates retrieved by ProfilerPass class.
*/
public function __construct(Profiler $profiler, Environment $twig, array $templates) {
$this->profiler = $profiler;
$this->twig = $twig;
$this->templates = $templates;
}
/**
* Get the template name for a given panel.
*
* @param \Symfony\Component\HttpKernel\Profiler\Profile $profile
* A profile.
* @param string $panel
* A data collector name.
*
* @return string
* The template name for a given panel.
*
* @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
*/
public function getName(Profile $profile, $panel) {
$templates = $this->getNames($profile);
if (!isset($templates[$panel])) {
throw new NotFoundHttpException(sprintf('Panel "%s" is not registered in profiler or is not present in viewed profile.', $panel));
}
return $templates[$panel];
}
/**
* Get template names of templates that are present in the viewed profile.
*
* @param \Symfony\Component\HttpKernel\Profiler\Profile $profile
* A profile.
*
* @return array
* Template names of templates that are present in the viewed profile.
*/
public function getNames(Profile $profile) {
$templates = [];
foreach ($this->templates as $arguments) {
if (NULL === $arguments) {
continue;
}
[$name, $template] = $arguments;
if (!$this->profiler->has($name) || !$profile->hasCollector($name)) {
continue;
}
if ('.html.twig' === substr($template, -10)) {
$template = substr($template, 0, -10);
}
if (!$this->twig->getLoader()->exists($template . '.html.twig')) {
throw new \UnexpectedValueException(sprintf('The profiler template "%s.html.twig" for data collector "%s" does not exist.', $template, $name));
}
$templates[$name] = $template . '.html.twig';
}
return $templates;
}
}
<file_sep><?php
namespace Drupal\webprofiler;
use Drupal\Core\Config\ConfigFactoryInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpKernel\Debug\FileLinkFormatter;
/**
* Factory class to create FileLinkFormatter service instances.
*/
class FileLinkFormatterFactory {
/**
* Return a FileLinkFormatter configured with webprofiler settings.
*
* @param \Symfony\Component\HttpFoundation\RequestStack $requestStack
* The request stack service.
* @param \Drupal\Core\Config\ConfigFactoryInterface $configFactory
* The config factory service.
*
* @return \Symfony\Component\HttpKernel\Debug\FileLinkFormatter
* A FileLinkFormatter configured with webprofiler settings.
*/
final public static function getFileLinkFormatter(
RequestStack $requestStack,
ConfigFactoryInterface $configFactory
): FileLinkFormatter {
$settings = $configFactory->get('webprofiler.settings');
$ide = $settings->get('ide');
$ide_remote_path = $settings->get('ide_remote_path');
$ide_local_path = $settings->get('ide_local_path');
$link_format = sprintf('%s&%s>%s', $ide, $ide_remote_path, $ide_local_path);
return new FileLinkFormatter($link_format, $requestStack);
}
}
<file_sep><?php
namespace Drupal\webprofiler\Form;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* From controller to set Webprofiler settings.
*/
class SettingsForm extends ConfigFormBase {
/**
* The Profiler service.
*
* @var \Symfony\Component\HttpKernel\Profiler\Profiler
*/
private $profiler;
/**
* A list of registered data collector templates.
*
* @var array
*/
private $templates;
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
$instance = parent::create($container);
$instance->profiler = $container->get('webprofiler.profiler');
$instance->templates = $container->getParameter('webprofiler.templates');
return $instance;
}
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'webprofiler_settings';
}
/**
* {@inheritdoc}
*/
protected function getEditableConfigNames() {
return [
'webprofiler.settings',
];
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$config = $this->config('webprofiler.settings');
$form['purge_on_cache_clear'] = [
'#type' => 'checkbox',
'#title' => $this->t('Purge on cache clear'),
'#description' => $this->t('Deletes all profiler files during cache clear.'),
'#default_value' => $config->get('purge_on_cache_clear'),
];
$form['exclude_paths'] = [
'#type' => 'textarea',
'#title' => $this->t('Exclude paths'),
'#default_value' => $config->get('exclude_paths'),
'#description' => $this->t('Paths to exclude for profiling. One path per line.'),
];
$form['active_toolbar_items'] = [
'#type' => 'checkboxes',
'#title' => $this->t('Active toolbar items'),
'#options' => $this->getCollectors(),
'#description' => $this->t('Choose which items to show into the toolbar.'),
'#default_value' => $config->get('active_toolbar_items'),
];
$form['ide_settings'] = [
'#type' => 'details',
'#title' => $this->t('IDE settings'),
'#open' => FALSE,
];
$form['ide_settings']['ide'] = [
'#type' => 'select',
'#title' => $this->t('IDE'),
'#options' => $this->getIdes(),
'#description' => $this->t('IDE URL template for open files.'),
'#default_value' => $config->get('ide'),
];
$form['ide_settings']['ide_remote_path'] = [
'#type' => 'textfield',
'#title' => $this->t('IDE link remote path'),
'#description' => $this->t('The path of the remote docroot. Leave blank if the docroot is on the same machine of the IDE.'),
'#default_value' => $config->get('ide_remote_path'),
];
$form['ide_settings']['ide_local_path'] = [
'#type' => 'textfield',
'#title' => $this->t('IDE link local path'),
'#description' => $this->t('The path of the local docroot. Leave blank if the docroot is on the same machine of IDE.'),
'#default_value' => $config->get('ide_local_path'),
];
$form['database'] = [
'#type' => 'details',
'#title' => $this->t('Database settings'),
'#open' => FALSE,
'#states' => [
'visible' => [
[
'input[name="active_toolbar_items[database]"]' => ['checked' => TRUE],
],
],
],
];
$form['database']['query_sort'] = [
'#type' => 'radios',
'#title' => $this->t('Sort query log'),
'#options' => ['source' => $this->t('by source'), 'duration' => $this->t('by duration')],
'#description' => $this->t('The query table can be sorted in the order that the queries were executed or by descending duration.'),
'#default_value' => $config->get('query_sort'),
];
$form['database']['query_highlight'] = [
'#type' => 'number',
'#title' => $this->t('Slow query highlighting'),
'#description' => $this->t('Enter an integer in milliseconds. Any query which takes longer than this many milliseconds will be highlighted in the query log. This indicates a possibly inefficient query, or a candidate for caching.'),
'#default_value' => $config->get('query_highlight'),
'#min' => 0,
];
$form['purge'] = [
'#type' => 'details',
'#title' => $this->t('Purge profiles'),
'#open' => FALSE,
];
$form['purge']['actions'] = ['#type' => 'actions'];
$form['purge']['actions']['purge'] = [
'#type' => 'submit',
'#value' => $this->t('Purge'),
'#submit' => [[$this, 'purge']],
];
return parent::buildForm($form, $form_state);
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$this->config('webprofiler.settings')
->set('purge_on_cache_clear', $form_state->getValue('purge_on_cache_clear'))
->set('exclude_paths', $form_state->getValue('exclude_paths'))
->set('active_toolbar_items', $form_state->getValue('active_toolbar_items'))
->set('ide', $form_state->getValue('ide'))
->set('ide_remote_path', $form_state->getValue('ide_remote_path'))
->set('ide_local_path', $form_state->getValue('ide_local_path'))
->set('query_sort', $form_state->getValue('query_sort'))
->set('query_highlight', $form_state->getValue('query_highlight'))
->save();
parent::submitForm($form, $form_state);
}
/**
* Purges profiles.
*
* @param array $form
* The form structure.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The form state object.
*/
public function purge(array &$form, FormStateInterface $form_state) {
$this->profiler->purge();
$this->messenger()->addMessage($this->t('Profiles purged'));
}
/**
* Return a list of defined collectors.
*
* @return array
* A list of defined collectors.
*/
private function getCollectors() {
$options = [];
foreach ($this->templates as $template) {
// Drupal collector should not be disabled.
if ($template[0] != 'drupal') {
$options[$template[0]] = $template[2];
}
}
asort($options);
return $options;
}
/**
* Return a list of IDE URL template for open files.
*
* @return array
* A list of IDE URL template for open files.
*/
private function getIdes() {
return [
'txmt://open?url=file://%f&line=%l' => 'textmate',
'mvim://open?url=file://%f&line=%l' => 'macvim',
'emacs://open?url=file://%f&line=%l' => 'emacs',
'subl://open?url=file://%f&line=%l' => 'sublime',
'phpstorm://open?file=%f&line=%l' => 'phpstorm',
'atom://core/open/file?filename=%f&line=%l' => 'atom',
'vscode://file/%f:%l' => 'vscode',
];
}
}
<file_sep><?php
namespace Drupal\webprofiler\Panel;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Symfony\Component\VarDumper\Cloner\Data;
use Symfony\Component\VarDumper\Dumper\HtmlDumper;
/**
* Base class for dashboard panels.
*/
class PanelBase {
use StringTranslationTrait;
/**
* A data dumper for HTML output.
*
* @var \Twig\Profiler\Dumper\HtmlDumper
*/
private $dumper;
/**
* Internal resource to store dumped data.
*
* @var resource
*/
private $output;
/**
* PanelBase constructor.
*
* @param \Symfony\Component\VarDumper\Dumper\HtmlDumper|null $dumper
* A data dumper for HTML output.
*/
public function __construct(HtmlDumper $dumper = NULL) {
$this->dumper = $dumper ?: new HtmlDumper();
$this->dumper->setOutput($this->output = fopen('php://memory', 'r+b'));
$this->dumper->setTheme('light');
$file_link_formatter = \Drupal::service('webprofiler.file_link_formatter');
$this->dumper->setDisplayOptions(['fileLinkFormat' => $file_link_formatter]);
}
/**
* Dump data using a dumper.
*
* @param \Symfony\Component\VarDumper\Cloner\Data $data
* The data to dump.
* @param int $maxDepth
* The max depth to dump for complex data.
*
* @return string|string[]
* The string representation of dumped data.
*/
public function dumpData(Data $data, $maxDepth = 0) {
$this->dumper->dump($data, NULL, [
'maxDepth' => $maxDepth,
]);
$dump = stream_get_contents($this->output, -1, 0);
rewind($this->output);
ftruncate($this->output, 0);
return str_replace("\n</pre", '</pre', rtrim($dump));
}
/**
* Render data in an array as HTML table.
*
* @param array $data
* The data to render.
* @param string $label
* The table label.
* @param callable|null $element_converter
* An optional function to convert all elements of data before rendering.
* If NULL fallback to PanelBase::dumpData.
*
* @return array
* A render array.
*/
protected function renderTable(
array $data,
$label,
callable $element_converter = NULL
): array {
if (count($data) == 0) {
return [];
}
if ($element_converter == NULL) {
$element_converter = [$this, 'dumpData'];
}
$rows = [];
foreach ($data as $key => $el) {
$rows[] = [
[
'data' => $key,
'class' => 'webprofiler__key',
],
[
'data' => [
'#type' => 'inline_template',
'#template' => '{{ data|raw }}',
'#context' => [
'data' => $element_converter($el),
],
],
'class' => 'webprofiler__value',
],
];
}
return [
$label => [
'#theme' => 'webprofiler_dashboard_table',
'#title' => $this->t($label),
'#data' => [
'#type' => 'table',
'#header' => [$this->t('Name'), $this->t('Value')],
'#rows' => $rows,
'#attributes' => [
'class' => [
'webprofiler__table',
],
],
],
],
];
}
}
|
13ca41cbaab841a6d1db836c25b80c22628bd6ca
|
[
"PHP"
] | 25 |
PHP
|
wellnet/devel
|
d751c1e63f4f5a81211fbeee3cf6305e96d7e3f2
|
10036c5d8a7f865abb0a21b65be8f72d1b2aeb89
|
refs/heads/master
|
<file_sep>package com.example.anvanthinh.music;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.media.AudioManager;
import android.os.IBinder;
import android.telecom.ConnectionService;
import android.util.Log;
import android.view.KeyEvent;
import static android.view.KeyEvent.KEYCODE_HEADSETHOOK;
/**
* Created by <NAME> on 4/24/2017.
*/
public class MusicMediaButton extends BroadcastReceiver {
private static final int MSG_LONGPRESS_TIMEOUT = 1;
private static final int LONG_PRESS_DELAY = 500;
private boolean isNext = false;
private boolean isPlaying = false;
private MusicService mService;
private static boolean mDown = false;
private static long mLastClickTime = 0;
@Override
public void onReceive(Context context, Intent intent) {
String intentAction = intent.getAction();
int mCount = 0;
if (AudioManager.ACTION_AUDIO_BECOMING_NOISY.equals(intentAction)) {
Log.d("thinhavb:", "rut tai nghe");
Intent i = new Intent(context, MusicService.class);
i.setAction(MusicService.PAUSE);
context.startService(i);
} else if (Intent.ACTION_MEDIA_BUTTON.equals(intentAction)) {
Log.d("thinhavb:", mCount + "");
Intent i2 = new Intent(context, MusicService.class);
i2.setAction(MusicService.BUTTON_HEADPHONE);
context.startService(i2);
}
// else if (Intent.ACTION_MEDIA_BUTTON.equals(intentAction)) {
// Log.d("thinhavb:", "bam nut tai nghe");
// KeyEvent event = (KeyEvent) intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
//
// if (event == null) {
// return;
// }
//
// int keycode = event.getKeyCode();
// int action = event.getAction();
// long eventtime = event.getEventTime();
////
//// // single quick press: pause/resume.
//// // double press: next track
//// // long press: previous
////
// String command = null;
// switch (keycode) {
// case KeyEvent.KEYCODE_MEDIA_STOP:
// command = MusicService.PAUSE;
// Log.d("thinhavb:", "STOP");
// break;
// case KEYCODE_HEADSETHOOK:
// case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
// Log.d("thinhavb:", "PLAY_PAUSE");
//// command = MusicService.PAUSE;
// break;
// case KeyEvent.KEYCODE_MEDIA_NEXT:
// command = MusicService.NEXT;
// Log.d("thinhavb:", "NEXT");
//// Intent i = new Intent(context, MusicService.class);
//// i.setAction(MusicService.NEXT);
//// context.startService(i);
// break;
// case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
// command = MusicService.PREVIOUS;
// Log.d("thinhavb:", "PREVIOUS");
// break;
// case KeyEvent.KEYCODE_MEDIA_PAUSE:
// command = MusicService.PAUSE;
// Log.d("thinhavb:", "PAUSE");
// break;
// case KeyEvent.KEYCODE_MEDIA_PLAY:
// command = MusicService.PLAY_CONTINUES;
// Log.d("thinhavb:", "PLAY_CONTINUES");
//// Intent i3 = new Intent(context, MusicService.class);
//// i3.setAction(MusicService.PLAY_CONTINUES);
//// context.startService(i3);
// break;
// }
////
//// if (command != null) {
//// if (action == KeyEvent.ACTION_DOWN) {
//// if (mDown) {
//// if ((MusicService.PAUSE.equals(command) ||
//// MusicService.PLAY_CONTINUES.equals(command))
//// && mLastClickTime != 0
//// && eventtime - mLastClickTime > LONG_PRESS_DELAY) {
//// }
//// } else if (event.getRepeatCount() == 0) {
//// // only consider the first event in a sequence, not the repeat events,
//// // so that we don't trigger in cases where the first event went to
//// // a different app (e.g. when the user ends a phone call by
//// // long pressing the headset button)
////
//// // The service may or may not be running, but we need to send it
//// // a command.
//// Intent i = new Intent(context, MusicService.class);
//// if (keycode == KeyEvent.KEYCODE_HEADSETHOOK &&
//// eventtime - mLastClickTime < 300) {
//// i.setAction(MusicService.NEXT);
//// context.startService(i);
//// mLastClickTime = 0;
//// } else {
//// context.startService(i);
//// mLastClickTime = eventtime;
//// }
//// mDown = true;
//// }
//// } else {
//// mDown = false;
//// }
//// if (isOrderedBroadcast()) {
//// abortBroadcast();
//// }
//// }
// }
}
}
<file_sep>package com.example.anvanthinh.music.ui;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.anvanthinh.music.R;
import com.example.anvanthinh.music.adapter.SongPagerAdapter;
import com.example.anvanthinh.music.Animation.ZoomOutPageTransformer;
import com.ogaclejapan.smarttablayout.SmartTabLayout;
public class MusicFragment extends Fragment {
private SongPagerAdapter mAdapter;
private ViewPager mViewPager;
private InforMusicMini mMiniInfor;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.song_fragment, container, false);
mMiniInfor = (InforMusicMini)v.findViewById(R.id.mini_infor_fragmnet);
mMiniInfor.setFragment(this);
mAdapter = new SongPagerAdapter(getActivity().getSupportFragmentManager(), getContext());
mViewPager = (ViewPager) v.findViewById(R.id.viewpager);
mViewPager.setAdapter(mAdapter);
SmartTabLayout viewPagerTab = (SmartTabLayout) v.findViewById(R.id.viewpager_catalogies);
viewPagerTab.setViewPager(mViewPager);
mViewPager.setPageTransformer(true, new ZoomOutPageTransformer());
return v;
}
public void showMiniInfor(){
mMiniInfor.setVisibility(View.VISIBLE);
}
public void moveScreenPlaySong(Bundle bun){
final ScreenPlaySongFragment f = new ScreenPlaySongFragment();
f.setArguments(bun);
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.pane_list_music, f).commit();
}
public void replaceFragmentPager(Fragment item, int tab) {
mAdapter.replaceFragment(item, tab);
}
public interface OnNewSongPlayListener {
void onUpdateMiniInfor(Cursor c, int position);
}
public void restoreTabPager(){
mAdapter.restoreTab();
}
public boolean isChangeTab(){
return mAdapter.getIsChangetab();
}
}
<file_sep>package com.example.anvanthinh.music.ui;
import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import com.example.anvanthinh.music.Music;
import com.example.anvanthinh.music.MusicService;
import com.example.anvanthinh.music.R;
import com.example.anvanthinh.music.adapter.ImageSongAdapter;
import com.example.anvanthinh.music.adapter.ListAdapter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
/**
* Created by <NAME> on 2/19/2017.
*/
public class ScreenPlaySongFragment extends Fragment implements View.OnClickListener, View.OnTouchListener,
LoaderManager.LoaderCallbacks<Cursor> {
private static final int URL_IMAGE = 0;
private static final int SWIPE_VELOCITY = 100;
private static final int SWIPE_LONG = 100;
private static final long DURATION_ALPHA = 5000;
private TextView mSongTextView;
private TextView mAristsTextView;
private ImageButton mList;
private ImageButton mLoop, mPlay, mNext, mPrevious, mRandom;
private boolean mIsPlaying;
private BroadcastReceiver mReceiver;
private GestureDetector mGesture;
private SeekBar mSeekbar;
private TextView mTimeEnd, mTimeStart;
private ImageView mImageAlbum;
// private ViewPager mViewPager; // viewpager dung de hien thi noi dung anh cho moi bai hat
private ImageSongAdapter mImageAdapter; // adapter cho viewpager
private int mPosition; // vi tri bai hat dang choi
private ArrayList<Long> mArrAlbumId;
private long mAlbumId;
private ObjectAnimator mAnimRotate; // animator xoauy tron cho anh album
private MusicService mService;
private boolean isBinded = false; // ket noi toi service chua
private ServiceConnection mServiceConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName name, IBinder service) {
MusicService.MyBinded binder = (MusicService.MyBinded) service;
mService = binder.getService();
Music m = binder.getSongIsPlaying();
updateImageAlbum(m.getAlbumId());
isBinded = true;
}
@Override
public void onServiceDisconnected(ComponentName name) {
isBinded = false;
}
};
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = new Intent(getActivity(), MusicService.class);
getActivity().bindService(intent, mServiceConnection, Service.BIND_AUTO_CREATE);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.screen_play_song_fragment, null);
mSongTextView = (TextView) v.findViewById(R.id.song);
mAristsTextView = (TextView) v.findViewById(R.id.singer);
mList = (ImageButton) v.findViewById(R.id.list);
mPlay = (ImageButton) v.findViewById(R.id.play_pause);
mLoop = (ImageButton) v.findViewById(R.id.loop);
mNext = (ImageButton) v.findViewById(R.id.next);
mPrevious = (ImageButton) v.findViewById(R.id.previous);
mRandom = (ImageButton) v.findViewById(R.id.random);
mTimeStart = (TextView) v.findViewById(R.id.time_start);
mTimeEnd = (TextView) v.findViewById(R.id.time_end);
mSeekbar = (SeekBar) v.findViewById(R.id.seekbar);
mImageAlbum = (ImageView) v.findViewById(R.id.image_album);
// mViewPager = (ViewPager) v.findViewById(R.id.viewpager_song);
//mViewPager.setPageTransformer(true, new ZoomOutPageTransformer());
mGesture = new GestureDetector(getContext(), new ChangeImageGesture());
mImageAlbum.setOnTouchListener(this);
mList.setOnClickListener(this);
mPlay.setOnClickListener(this);
mLoop.setOnClickListener(this);
mNext.setOnClickListener(this);
mPrevious.setOnClickListener(this);
mRandom.setOnClickListener(this);
mSeekbar.setOnClickListener(this);
mAnimRotate = ObjectAnimator.ofFloat(mImageAlbum, "rotation", 0, 360);
mAnimRotate.setDuration(20000);
mAnimRotate.setRepeatCount(ObjectAnimator.INFINITE);
mAnimRotate.setInterpolator(new LinearInterpolator());
mAnimRotate.setRepeatMode(ObjectAnimator.INFINITE);
mAnimRotate.start();
return v;
}
@Override
public void onActivityCreated(@Nullable Bundle bundle) {
super.onActivityCreated(bundle);
mArrAlbumId = new ArrayList<Long>(); // danh sach id album
Bundle bun = getArguments();
if (bun != null) {
mIsPlaying = bun.getBoolean(MusicService.IS_PLAYING);
long durattion = bun.getLong(ListSongFragment.DURATION);
final SimpleDateFormat sdf = new SimpleDateFormat("mm:ss");
mTimeEnd.setText(sdf.format(durattion));
mSeekbar.setMax((int) durattion);
updateText(bun.getString(InforMusicMini.SONG_NAME), bun.getString(InforMusicMini.ARISRT));
updateButton(bun.getBoolean(MusicService.IS_PLAYING));
}
getActivity().getSupportLoaderManager().initLoader(URL_IMAGE, null, this);
mSeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
mTimeStart.setText(changeTime(progress));
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
Intent i = new Intent(getActivity(), MusicService.class);
i.setAction(MusicService.TUA_NHANH);
int a = seekBar.getProgress();
i.putExtra(MusicService.VI_TRI, seekBar.getProgress());
getActivity().startService(i);
mTimeStart.setText(changeTime(seekBar.getProgress()));
}
});
}
@Override
public void onStart() {
super.onStart();
}
@Override
public void onResume() {
super.onResume();
mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction() == MusicService.THONG_TIN_BAI_HAT) {
Bundle bun = intent.getBundleExtra(MusicService.THONG_TIN_BAI_HAT);
Music m = (Music) bun.getSerializable(MusicService.THONG_TIN_BAI_HAT);
updateUI(m.getName_song(), m.getName_singer(), m.getDuration());
mAlbumId = m.getAlbumId();
updateImageAlbum(mAlbumId);
mSeekbar.setMax((int) m.getDuration());
startAnimationAlbumView();
} else if (intent.getAction() == MusicService.PROGRESS_SEEKBAR) {
final int time_length_song = intent.getIntExtra(ListSongFragment.DURATION, 0);
final int time_current_song = intent.getIntExtra(MusicService.TIME_CURRENT, 0);
updateSeebar(time_length_song, time_current_song);
} else if (intent.getAction() == MusicService.UPDATE_BUTTON) {
mIsPlaying = intent.getBooleanExtra(MusicService.IS_PLAYING, false);
updateButton(mIsPlaying);
}
}
};
IntentFilter filter = new IntentFilter(MusicService.BROADCAST);
filter.addAction(MusicService.THONG_TIN_BAI_HAT);
filter.addAction(MusicService.UPDATE_BUTTON);
filter.addAction(MusicService.PROGRESS_SEEKBAR);
getActivity().registerReceiver(mReceiver, filter);
}
@Override
public void onStop() {
super.onStop();
getActivity().unregisterReceiver(mReceiver);
if (isBinded == true) {
getActivity().unbindService(mServiceConnection);
isBinded = false;
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.list:
MusicFragment f = new MusicFragment();
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.pane_list_music, f).commit();
break;
case R.id.play_pause:
if (mIsPlaying == true) {
startService(getActivity(), MusicService.PAUSE);
mIsPlaying = false;
} else {
startService(getActivity(), MusicService.PLAY_CONTINUES);
mIsPlaying = true;
}
updateButton(mIsPlaying);
break;
case R.id.next:
mSeekbar.setProgress(0);
startService(getActivity(), MusicService.NEXT);
mPosition = mPosition + 1;
break;
case R.id.previous:
mSeekbar.setProgress(0);
startService(getActivity(), MusicService.PREVIOUS);
mPosition = mPosition - 1;
break;
case R.id.loop:
repeatSong();
break;
case R.id.random:
SharedPreferences sharedPreferences = getActivity().getSharedPreferences(MusicService.SHUFFLE_MODE, Context.MODE_PRIVATE);
boolean shuffMode = sharedPreferences.getBoolean(MusicService.SHUFFLE_MODE, false);
updateShuff(shuffMode);
break;
}
}
private void updateShuff(boolean shuffMode) {
if (shuffMode){
mRandom.setImageResource(R.drawable.ic_shuffle_orrange_24dp);
} else{
mRandom.setImageResource(R.drawable.ic_shuffle_white_48dp);
}
}
private void repeatSong() {
SharedPreferences sharedPreferences = getActivity().getSharedPreferences(MusicService.REPEAT_MODE, Context.MODE_PRIVATE);
int repeatMode = sharedPreferences.getInt(MusicService.REPEAT_MODE, MusicService.REPEAT_NONE);
updateRepeatButton(repeatMode);
}
private void updateRepeatButton(int repeatMode) {
if (repeatMode == MusicService.REPEAT_NONE) {
mLoop.setImageResource(R.drawable.ic_repeat_white_24dp);
} else if (repeatMode == MusicService.REPEAT_ALL) {
mLoop.setImageResource(R.drawable.ic_repeat__all_orange_24dp);
} else if (repeatMode == MusicService.REPEAT_ONE) {
mLoop.setImageResource(R.drawable.ic_repeat_one_orange_24dp);
}
}
// ham update lai giao dien man hinh choi nhac
private void updateUI(String name, String arists, long duration) {
updateText(name, arists);
final SimpleDateFormat sdf = new SimpleDateFormat("mm:ss");
mTimeEnd.setText(sdf.format(duration));
mTimeStart.setText("00:00");
}
// ham update anh album
private void updateImageAlbum(long mAlbumId) {
ListAdapter.setImageAvatar(getContext(), mImageAlbum, mAlbumId);
}
private void updateText(String name, String arists) {
mSongTextView.setText(name);
mAristsTextView.setText(arists);
}
public static void startService(Activity activity, String action) {
Intent i = new Intent(activity, MusicService.class);
i.setAction(action);
activity.startService(i);
}
private void randomSong() {
Intent i = new Intent(getActivity(), MusicService.class);
i.setAction(MusicService.PLAY_CONTINUES);
getActivity().startService(i);
}
// ham cap nhat seekbar
private void updateSeebar(int longTime, int currentTime) {
mSeekbar.setProgress(currentTime);
mTimeStart.setText(changeTime(currentTime));
}
private String changeTime(long duration) {
final SimpleDateFormat sdf = new SimpleDateFormat("mm:ss");
String time = sdf.format(duration);
return time;
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
final String sortOder = MediaStore.Audio.Media.TITLE + " ASC";
final String[] projection = new String[]{MediaStore.Audio.Media.ALBUM_ID};
if (id == URL_IMAGE) {
CursorLoader cursorLoader = new CursorLoader(getActivity(), MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, projection, null, null, sortOder);
return cursorLoader;
} else {
return null;
}
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
for (data.moveToFirst(); !data.isAfterLast(); data.moveToNext()) {
mArrAlbumId.add(data.getLong(data.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID)));
}
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
}
public void updateButton(boolean isPlaying) {
if (isPlaying == true) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mPlay.setImageDrawable(getContext().getDrawable(R.drawable.ic_pause_circle_outline_white_24dp));
} else {
mPlay.setBackgroundResource(R.drawable.ic_pause_circle_outline_white_24dp);
}
mAnimRotate.resume();
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mPlay.setImageDrawable(getContext().getDrawable(R.drawable.ic_play_circle_outline_white_24dp));
} else {
mPlay.setBackgroundResource(R.drawable.ic_play_circle_outline_white_24dp);
}
mAnimRotate.pause();
}
}
@Override
public boolean onTouch(View v, MotionEvent event) {
if (v.getId() == R.id.image_album) {
mGesture.onTouchEvent(event);
}
return true;
}
// su dung animation khi chuyen anh bai hat
private void startAnimationAlbumView() {
mAnimRotate.end();
// ObjectAnimator fadeIn = ObjectAnimator.ofFloat(mImageAlbum, View.ALPHA, 1f, 0f);
// fadeIn.setDuration(DURATION_ALPHA);
// fadeIn.start();
ObjectAnimator fadeOut = ObjectAnimator.ofFloat(mImageAlbum, View.ALPHA, 0f, 1f);
fadeOut.setDuration(DURATION_ALPHA);
fadeOut.start();
mAnimRotate.start();
}
class ChangeImageGesture extends GestureDetector.SimpleOnGestureListener {
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
// vuot tu phai sang trai
if (e1.getX() - e2.getX() > SWIPE_LONG && Math.abs(velocityX) > SWIPE_VELOCITY) {
startService(getActivity(), MusicService.NEXT);
} else if (e2.getX() - e1.getX() > SWIPE_LONG && Math.abs(velocityX) > SWIPE_VELOCITY) { //vuot tu trai sang phai
startService(getActivity(), MusicService.PREVIOUS);
}
return super.onFling(e1, e2, velocityX, velocityY);
}
}
}
<file_sep>package com.example.anvanthinh.music.adapter;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.support.v4.graphics.drawable.RoundedBitmapDrawable;
import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory;
import android.support.v4.widget.CursorAdapter;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RemoteViews;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.BitmapImageViewTarget;
import com.example.anvanthinh.music.Controller.MainActivity;
import com.example.anvanthinh.music.Music;
import com.example.anvanthinh.music.MusicService;
import com.example.anvanthinh.music.R;
import com.example.anvanthinh.music.ui.MusicFragment;
import com.example.anvanthinh.music.ui.NotificationMusic;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import es.claucookie.miniequalizerlibrary.EqualizerView;
/**
* Created by <NAME> on 3/29/2017.
*/
public class ListAdapter extends RecyclerView.Adapter<ListAdapter.ViewHolder> {
private CursorAdapter mCursorAdapter;
private Context mContext;
private Activity mActivity;
private MusicFragment.OnNewSongPlayListener mOnNewSongPlayListener;
private EqualizerView mEqualizer;
private ArrayList<Music> mArrSong;
public ListAdapter(Activity a, Context c, Cursor cursor) {
mContext = c;
mActivity = a;
mArrSong = new ArrayList<Music>();
mCursorAdapter = new CursorAdapter(mContext, cursor, 0) {
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.item_music, parent, false);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
}
};
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
Music m = new Music();
m.setPath(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA)));
m.setName_singer(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST)));
m.setName_song(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE)));
m.setDuration(cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION)));
m.setAlbumId(cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID)));
mArrSong.add(m);
}
}
@Override
public long getItemId(int position) {
return super.getItemId(position);
}
@Override
public ListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = mCursorAdapter.newView(mContext, mCursorAdapter.getCursor(), parent);
return new ViewHolder(v);
}
@Override
public void onBindViewHolder(final ListAdapter.ViewHolder holder, int position) {
mCursorAdapter.getCursor().moveToPosition(position);
mCursorAdapter.bindView(holder.itemView, mContext, mCursorAdapter.getCursor());
final Cursor cursor = mCursorAdapter.getCursor();
holder.mName.setText(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE)));
holder.mSinger.setText(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST)));
final long time = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION));
SimpleDateFormat sdf = null;
sdf = new SimpleDateFormat("mm:ss");
holder.mTime.setText(sdf.format(time));
final Long albumId = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID));
setImageAvatar(mContext, holder.mAvatar, albumId);
// mAvatar.setVisibility(View.GONE);
// mEqualizer.setVisibility(View.VISIBLE);
// mEqualizer.animateBars();
}
@Override
public int getItemCount() {
return mCursorAdapter.getCount();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView mName;
private LinearLayout mInforSong;
private TextView mTime;
private TextView mSinger;
private ImageButton mMore;
private LinearLayout mItemView;
private ImageView mAvatar;
public ViewHolder(View itemView) {
super(itemView);
mName = (TextView) itemView.findViewById(R.id.name);
mTime = (TextView) itemView.findViewById(R.id.time);
mSinger = (TextView) itemView.findViewById(R.id.singer);
mMore = (ImageButton) itemView.findViewById(R.id.more);
mInforSong = (LinearLayout) itemView.findViewById(R.id.infor_song);
mItemView = (LinearLayout) itemView.findViewById(R.id.itemview);
mAvatar = (ImageView) itemView.findViewById(R.id.image);
mEqualizer = (EqualizerView) itemView.findViewById(R.id.equalizer_view);
mName.setOnClickListener(this);
mTime.setOnClickListener(this);
mSinger.setOnClickListener(this);
mMore.setOnClickListener(this);
mInforSong.setOnClickListener(this);
mAvatar.setOnClickListener(this);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public void onClick(View v) {
int id = v.getId();
switch (id) {
case R.id.more:
showPopupMenu();
break;
case R.id.infor_song:
case R.id.name:
case R.id.singer:
playSong(this.getAdapterPosition());
mItemView.setBackground(mContext.getResources().getDrawable(R.drawable.custom_item_music));
if (mOnNewSongPlayListener != null) {
Cursor c = (Cursor) mCursorAdapter.getItem(this.getAdapterPosition());
mOnNewSongPlayListener.onUpdateMiniInfor(c, this.getAdapterPosition());
}
//onBindViewHolder(this, getAdapterPosition());
break;
}
}
private void showPopupMenu() {
final PopupMenu popup = new PopupMenu(mActivity, mMore);
popup.getMenuInflater().inflate(R.menu.menu_more_listview, popup.getMenu());
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
return true;
}
});
popup.show();
}
}
private void playSong(int postion) {
Intent i = new Intent(mContext, MusicService.class);
i.setAction(MusicService.PLAY_SONG_FROM_LIST);
i.putExtra(MusicService.PLAY_SONG_FROM_LIST, postion);
i.putExtra(MusicService.DANH_SACH_NHAC, mArrSong);
mContext.startService(i);
}
public void setOnNewSongPlayListener(MusicFragment.OnNewSongPlayListener onNewSongPlayListener) {
mOnNewSongPlayListener = onNewSongPlayListener;
}
//animation xoa 1 bai hat
public void remove(int position) {
//mCursorAdapter.(position);
notifyItemRemoved(position);
}
public static void setImageAvatar(final Context context, final ImageView imageView, long albumId) {
final Uri sArtworkUri = Uri.parse("content://media/external/audio/albumart");
final Uri albumArtUri = ContentUris.withAppendedId(sArtworkUri, albumId);
Glide.with(context).load(albumArtUri).asBitmap().centerCrop().placeholder(R.drawable.album_art)
.into(new BitmapImageViewTarget(imageView) {
@Override
protected void setResource(Bitmap resource) {
RoundedBitmapDrawable circularBitmapDrawable =
RoundedBitmapDrawableFactory.create(context.getResources(), resource);
circularBitmapDrawable.setCircular(true);
imageView.setImageDrawable(circularBitmapDrawable);
}
});
}
public void stopEliquazor() {
// mEqualizer.stopBars();
}
public void startEliquazor() {
// mEqualizer.animateBars();
}
}
<file_sep>package com.example.anvanthinh.music.Controller;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import com.example.anvanthinh.music.ItemClickRecycleView;
import com.example.anvanthinh.music.MusicMediaButton;
import com.example.anvanthinh.music.MusicService;
import com.example.anvanthinh.music.R;
import com.example.anvanthinh.music.ui.ListSongFragment;
import com.example.anvanthinh.music.ui.MusicFragment;
public class MainActivity extends AppCompatActivity {
private ActivityController mController;
private boolean isTablet = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
isTablet = this.getResources().getBoolean(R.bool.isTablet);
if(isTablet == true){
mController = new TwoPaneController(this);
}else{
mController = new OnePaneController(MainActivity.this);
}
mController.onCreate(savedInstanceState);
// dang ki nhan su kien tu tai nghe
IntentFilter filter = new IntentFilter(Intent.ACTION_MEDIA_BUTTON);
MusicMediaButton r = new MusicMediaButton();
registerReceiver(r, filter);
}
@Override
protected void onStart() {
super.onStart();
}
@Override
protected void onStop() {
super.onStop();
mController.onStop();
Log.d("thinhavb", "MainActivity - stop");
}
public MusicFragment.OnNewSongPlayListener getOnNewSongPlayListener() {
return mController;
}
public void replaceFragment(Fragment listSongFragment, int tabAlbum) {
mController.replaceFragment(listSongFragment, tabAlbum);
}
@Override
public void onBackPressed() {
mController.onBackPressed();
}
}
<file_sep>package com.example.anvanthinh.music;
import android.app.NotificationManager;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.MediaStore;
import android.support.v4.content.Loader;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import com.example.anvanthinh.music.ui.NotificationMusic;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;
import static com.example.anvanthinh.music.ui.ListSongFragment.DURATION;
public class MusicService extends Service implements Loader.OnLoadCompleteListener<Cursor> {
public static final String BROADCAST = "gui broadcast";
public static final String THONG_TIN_BAI_HAT = "thong_tin_bai_hat";
public static final String UPDATE_BUTTON = "update button";
public static final String DANH_SACH_NHAC = "danh sach bai hat";
public static final String PLAY_SONG_FROM_LIST = "choi bai hat o vi tri";
public static final String PAUSE = "pause";
public static final String PLAY_CONTINUES = "Play tiep tai vi tri dang dung";
public static final String BUTTON_HEADPHONE = "su kien tu tai nghe";
public static final String NEXT = "chuyen bai hat tiep theo";
public static final String PREVIOUS = "quay lai bai truoc";
public static final int REPEAT_ONE = 1;
public static final int REPEAT_ALL = 2;
public static final int REPEAT_NONE = 3;
public static final String REPEAT_MODE = "che do lap lai bai hat";
public static final String SHUFFLE_MODE = "che do random bai hat";
public static final int RANDOM = 4;
public static final String PROGRESS_SEEKBAR = "procress seekbar";
public static final String TIME_CURRENT = "time current";
public static final String TUA_NHANH = "tua_nhanh_bai_hat";
public static final String IS_PLAYING = "trang thai bai hat";
public static final String VI_TRI = "position_song_now";
public static final String TURN_OFF_NOTIFICATION = "cancel notification";
private MediaPlayer mPlayer = new MediaPlayer();
private ArrayList<Music> mArr;
private int mPosition;
private Thread mThreadSeekbar;
private NotificationMusic mNotification;
private final IBinder mBinder = new MyBinded();
private int mRepeatMode;
private int mShuffle;
int mCount = 0;
public MusicService() {
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
public class MyBinded extends Binder {
public MusicService getService() {
return MusicService.this;
}
public Music getSongIsPlaying() {
Music m = mArr.get(mPosition);
return m;
}
}
public void connect(){
Log.d("thinhav", "adadaw");
}
@Override
public void onCreate() {
mNotification = new NotificationMusic(getApplicationContext());
mArr = new ArrayList<Music>();
final String sortOder = MediaStore.Audio.Media.TITLE + " ASC";
AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
ComponentName rec = new ComponentName(getPackageName(),
MusicMediaButton.class.getName());
audioManager.registerMediaButtonEventReceiver(rec);
// final Cursor c = getApplication().getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, sortOder);
// for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
// Music m = new Music();
// m.setPath(c.getString(c.getColumnIndex(MediaStore.Audio.Media.DATA)));
// m.setName_singer(c.getString(c.getColumnIndex(MediaStore.Audio.Media.ARTIST)));
// m.setName_song(c.getString(c.getColumnIndex(MediaStore.Audio.Media.TITLE)));
// m.setDuration(c.getLong(c.getColumnIndex(MediaStore.Audio.Media.DURATION)));
// m.setAlbumId(c.getLong(c.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID)));
// mArr.add(m);
// }
// c.close();
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null) {
final String actionIntent = intent.getAction();
switch (actionIntent) {
case PLAY_SONG_FROM_LIST:
mArr.clear();
ArrayList<Music> arr = (ArrayList<Music>) intent.getSerializableExtra(DANH_SACH_NHAC);
mArr.addAll(arr);
if (mPlayer.isPlaying()) {
mPlayer.release();
}
mPosition = intent.getIntExtra(PLAY_SONG_FROM_LIST, 0);
playSong(mPosition);
break;
case PAUSE:
finishUpdateSeekbar();
pauseSong();
sendBroastReceiver(UPDATE_BUTTON);
break;
case PLAY_CONTINUES:
playContinues();
sendBroastReceiver(UPDATE_BUTTON);
break;
case NEXT:
moveSong(true);
break;
case PREVIOUS:
moveSong(false);
break;
case TUA_NHANH:
finishUpdateSeekbar();
int time = intent.getIntExtra(VI_TRI, -1);
mPlayer.seekTo(time);
mPlayer.start();
updateSeekbar();
break;
case TURN_OFF_NOTIFICATION:
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(NotificationMusic.ID_NOTIFICATION);
break;
case BUTTON_HEADPHONE:
mCount ++;
if(mCount >0 && mCount %2 == 0){
if(mPlayer.isPlaying() == true){
finishUpdateSeekbar();
pauseSong();
sendBroastReceiver(UPDATE_BUTTON);
} else{
playContinues();
sendBroastReceiver(UPDATE_BUTTON);
}
}
break;
}
}
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onLoadComplete(Loader<Cursor> loader, Cursor c) {
}
@Override
public void onDestroy() {
super.onDestroy();
}
// ham phat nhac tiep o vi tri dang dung
private void playContinues() {
if (mPlayer.isPlaying() == false) {
mPlayer.start();
}
}
// ham tam dung nhac
private void pauseSong() {
if (mPlayer.isPlaying()) {
mPlayer.pause();
}
}
// ham choi nhac tai vi tri position
private void playSong(int position) {
final String pathMusic = mArr.get(position).getPath();
mPlayer = new MediaPlayer();
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mPlayer.setVolume(1, 1);
try {
if (null != pathMusic) {
mPlayer.setDataSource(pathMusic);
mPlayer.prepare();
mPlayer.start();
}
} catch (IOException e) {
e.printStackTrace();
}
updateSeekbar();
sendBroastReceiver(THONG_TIN_BAI_HAT);
sendBroastReceiver(UPDATE_BUTTON);
ContinuesSong(mPlayer);
}
private void ContinuesSong(MediaPlayer media) {
media.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
SharedPreferences sharedPreferences = getSharedPreferences(REPEAT_MODE, MODE_PRIVATE);
mRepeatMode = sharedPreferences.getInt(REPEAT_MODE, REPEAT_NONE);
if (mRepeatMode == RANDOM) {
Random r = new Random();
int randomSong = r.nextInt(mArr.size() - 1);
playSong(randomSong);
} else{
repeatSong(mRepeatMode);
}
}
});
}
private void repeatSong(int modeRepeat) {
int positionSongNext = mPosition;
if (modeRepeat == REPEAT_ONE) {
positionSongNext = mPosition;
} else if (modeRepeat == REPEAT_ALL) {
positionSongNext = mPosition + 1;
if (positionSongNext == mArr.size() - 1) {
positionSongNext = 0;
}
} else if (modeRepeat == REPEAT_NONE) {
positionSongNext = mPosition + 1;
if (positionSongNext == mArr.size()) {
mPlayer.stop();
return;
}
}
playSong(positionSongNext);
}
private void moveSong(boolean isNext) {
mPlayer.release();
finishUpdateSeekbar();
if (isNext == true) {
mPosition = mPosition + 1;
if (mPosition == mArr.size()){
mPosition = 0;
}
} else {
mPosition = mPosition - 1;
if (mPosition == -1){
mPosition = mArr.size() -1;
}
}
playSong(mPosition);
sendBroastReceiver(UPDATE_BUTTON);
}
// gui broadcast di de cap nhat thong tin cac giao dien
private void sendBroastReceiver(String action) {
Intent i = new Intent(action);
Music m = mArr.get(mPosition);
mNotification.onCreate(m, mPlayer.isPlaying());
if (THONG_TIN_BAI_HAT.equals(action)) {
Bundle bun = new Bundle();
bun.putSerializable(THONG_TIN_BAI_HAT, m);
i.putExtra(THONG_TIN_BAI_HAT, bun);
} else if (UPDATE_BUTTON.equals(action)) {
if (mPlayer.isPlaying() == true) {
i.putExtra(IS_PLAYING, true);
} else {
i.putExtra(IS_PLAYING, false);
}
}
sendBroadcast(i);
}
// hàm cập nhật seekbar
public void updateSeekbar() {
if (mPlayer.isPlaying() == false) {
mPlayer.start();
}
mThreadSeekbar = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i != -1 ; i++) {
try {
Thread.sleep(1000);
Intent intent_seekbar = new Intent(PROGRESS_SEEKBAR);
intent_seekbar.putExtra(TIME_CURRENT, mPlayer.getCurrentPosition());
sendBroadcast(intent_seekbar);
} catch (InterruptedException e) {
if (mThreadSeekbar.isInterrupted() == false) {
return;
}
e.printStackTrace();
}
}
}
});
mThreadSeekbar.start();
sendBroastReceiver(UPDATE_BUTTON);
}
// hàm kết thúc cập nhật seekbar
public void finishUpdateSeekbar() {
if (mThreadSeekbar != null && mThreadSeekbar.isAlive()) {
mThreadSeekbar.interrupt();
}
}
public int getAudioSessionId() {
return mPlayer.getAudioSessionId();
}
public boolean checkPlaying(){
return mPlayer.isPlaying();
}
}
<file_sep>include ':app', ':library_viewpagers', ':player_view', ':library_equalizer'
project(':library_viewpagers').projectDir = new File('library_viewpager')<file_sep>package com.example.anvanthinh.music.ui;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.DialogFragment;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.crystal.crystalrangeseekbar.interfaces.OnSeekbarChangeListener;
import com.crystal.crystalrangeseekbar.widgets.CrystalSeekbar;
import com.example.anvanthinh.music.Controller.AlarmReceiver;
import com.example.anvanthinh.music.R;
/**
* Created by <NAME> on 5/25/2017.
*/
public class SetTime extends Activity{
private static final int ID_SET_TIME = 0;
private CrystalSeekbar mSeekbar;
private Button mButton;
private TextView mStart, mEnd;
private int mTime;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.set_time);
mSeekbar = (CrystalSeekbar) findViewById(R.id.seekbar_set_time);
mButton = (Button) findViewById(R.id.ok);
mStart = (TextView) findViewById(R.id.start);
mEnd = (TextView) findViewById(R.id.end);
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setTime();
}
});
mSeekbar.setOnSeekbarChangeListener(new OnSeekbarChangeListener() {
@Override
public void valueChanged(Number value) {
mStart.setText(value+"");
}
});
}
private void setTime(){
int time = Integer.parseInt(mStart.getText() + "");
Intent intent = new Intent(this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), ID_SET_TIME, intent, 0);
AlarmManager alarmManager = (AlarmManager) this.getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (time * 60 * 1000), pendingIntent);
Toast.makeText(this, getResources().getString(R.string.turn_off_music)
+ " " + time + " " + getResources().getString(R.string.minutes), Toast.LENGTH_SHORT).show();
finish();
}
}
<file_sep>package com.example.anvanthinh.music.ui;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.OvershootInterpolator;
import android.widget.LinearLayout;
import android.widget.ListView;
import com.example.anvanthinh.music.Animation.BlurBuilder;
import com.example.anvanthinh.music.Controller.MainActivity;
import com.example.anvanthinh.music.Controller.OnePaneController;
import com.example.anvanthinh.music.Music;
import com.example.anvanthinh.music.MusicService;
import com.example.anvanthinh.music.R;
import com.example.anvanthinh.music.adapter.ListAdapter;
import com.example.anvanthinh.music.adapter.ListAlbumAdapter;
import jp.wasabeef.recyclerview.animators.SlideInLeftAnimator;
import jp.wasabeef.recyclerview.animators.SlideInUpAnimator;
/**
* Created by <NAME> on 2/19/2017.
*/
public class ListSongFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor>, OnePaneController.QuerySearch {
public static final int ID_SONG_LOADER = 0;
public static final int ID_SONGAlBUM_LOADER = 10;
private static final int UPDATE_LISTVIEW = 1;
private static final String QUERY_SEARCH = "query_search";
public static final String NAME_SONG = "name song";
public static final String ARISTS = "arists";
public static final String DURATION = "duration";
public static final String POSITION = "position";
private ListAdapter mAdapter;
private RecyclerView mList;
private RecyclerView.LayoutManager mLayout;
private BroadcastReceiver mReceiver;
private boolean mIsPlaying;
private String mNameQuery; // ten bai hat hoac ca si
private Cursor mCursor;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.list_song_fragment, null);
mList = (RecyclerView) v.findViewById(R.id.list_song);
SlideInUpAnimator animator = new SlideInUpAnimator(new OvershootInterpolator(1f));
mList.setItemAnimator(animator);
mList.getItemAnimator().setMoveDuration(1000);
return v;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mLayout = new LinearLayoutManager(getActivity());
mList.setLayoutManager(mLayout);
mList.setAdapter(mAdapter);
Bundle bun = getArguments();
if (bun != null) {
int state = bun.getInt(ArsistListFragment.STATE);
String selection = null;
if (state == ListAlbumAdapter.STATE_ALBUM) {
mNameQuery = bun.getString(AlbumListFragment.ID_ALBUM);
selection = MediaStore.Audio.Media.ALBUM_ID + "=?";
} else if (state == ListAlbumAdapter.STATE_ARSIST) {
mNameQuery = bun.getString(ArsistListFragment.ID_ARTIST);
selection = MediaStore.Audio.Media.ARTIST_ID + "=?";
}
final String finalSelection = selection;
mList.post(new Runnable() {
@Override
public void run() {
final String sortOder = MediaStore.Audio.Media.TITLE + " ASC";
String[] selectionArgs = new String[]{mNameQuery + ""};
mCursor = getContext().getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, finalSelection,
selectionArgs, sortOder);
mAdapter = new ListAdapter(getActivity(), getContext(), mCursor);
mList.setAdapter(mAdapter);
Activity activity = getActivity();
if (activity instanceof MainActivity) {
MusicFragment.OnNewSongPlayListener listener = ((MainActivity) activity).getOnNewSongPlayListener();
mAdapter.setOnNewSongPlayListener(listener);
}
}
});
} else {
getActivity().getSupportLoaderManager().initLoader(ID_SONG_LOADER, null, this);
}
}
@Override
public void onResume() {
super.onResume();
mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction() == MusicService.UPDATE_BUTTON) {
mIsPlaying = intent.getBooleanExtra(MusicService.IS_PLAYING, false);
if (mIsPlaying) {
mAdapter.startEliquazor();
} else {
mAdapter.stopEliquazor();
}
}
}
};
IntentFilter filter = new IntentFilter(MusicService.BROADCAST);
filter.addAction(MusicService.THONG_TIN_BAI_HAT);
filter.addAction(MusicService.UPDATE_BUTTON);
getActivity().registerReceiver(mReceiver, filter);
}
@Override
public void onStop() {
super.onStop();
getActivity().unregisterReceiver(mReceiver);
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
final String sortOder = MediaStore.Audio.Media.TITLE + " ASC";
if (id == ID_SONG_LOADER) {
CursorLoader cursor = new CursorLoader(getActivity(), MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, sortOder);
return cursor;
} else if (id == UPDATE_LISTVIEW) {
String text = null;
String[] projection = new String[]{MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.ARTIST};
if (args != null) {
text = args.getString(QUERY_SEARCH);
}
CursorLoader cursor = new CursorLoader(getActivity(), MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, text, projection, sortOder);
return cursor;
} else {
return null;
}
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
mAdapter = new ListAdapter(getActivity(), getContext(), data);
mList.setAdapter(mAdapter);
Activity activity = getActivity();
if (activity instanceof MainActivity) {
MusicFragment.OnNewSongPlayListener listener = ((MainActivity) activity).getOnNewSongPlayListener();
mAdapter.setOnNewSongPlayListener(listener);
}
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
}
@Override
public void updateListView(String text) {
Bundle bun = new Bundle();
bun.putString(QUERY_SEARCH, text);
getActivity().getSupportLoaderManager().initLoader(UPDATE_LISTVIEW, bun, this);
}
}
<file_sep>package com.example.anvanthinh.music.Controller;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
import com.example.anvanthinh.music.MusicService;
import static java.security.AccessController.getContext;
/**
* Created by <NAME> on 5/25/2017.
*/
public class AlarmReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context, MusicService.class);
i.setAction(MusicService.PAUSE);
context.startService(i);
}
}
<file_sep>package com.example.anvanthinh.music.ui;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.view.View;
import android.widget.RemoteViews;
import com.example.anvanthinh.music.Controller.MainActivity;
import com.example.anvanthinh.music.Music;
import com.example.anvanthinh.music.MusicService;
import com.example.anvanthinh.music.R;
/**
* Created by <NAME> on 4/12/2017.
*/
public class NotificationMusic {
public static final int ID_NOTIFICATION = 100;
private Context mContext;
private RemoteViews mRemoteViews;
public NotificationMusic(Context context) {
mContext = context;
}
public PendingIntent getPendingIntent(String action) {
Intent i = new Intent(mContext, MusicService.class);
i.setAction(action);
PendingIntent pendingIntent = PendingIntent.getService(mContext, 0, i, 0);
return pendingIntent;
}
public void onCreate(Music m, boolean isPlaying){
mRemoteViews = new RemoteViews(mContext.getPackageName(), R.layout.notification_music);
mRemoteViews.setTextViewText(R.id.name, m.getName_song());
mRemoteViews.setOnClickPendingIntent(R.id.next, getPendingIntent(MusicService.NEXT));
mRemoteViews.setOnClickPendingIntent(R.id.previous, getPendingIntent(MusicService.PREVIOUS));
mRemoteViews.setOnClickPendingIntent(R.id.cancel, getPendingIntent(MusicService.TURN_OFF_NOTIFICATION));
if (isPlaying) {
mRemoteViews.setOnClickPendingIntent(R.id.play_pause, getPendingIntent(MusicService.PAUSE));
mRemoteViews.setImageViewResource(R.id.play_pause, R.drawable.ic_pause_white_48dp);
} else {
mRemoteViews.setOnClickPendingIntent(R.id.play_pause, getPendingIntent(MusicService.PLAY_CONTINUES));
mRemoteViews.setImageViewResource(R.id.play_pause, R.drawable.ic_play_arrow_white_48dp);
}
showNotification();
}
public void showNotification() {
Intent resultIntent = new Intent(mContext, MainActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(mContext, 0, resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
mContext).setSmallIcon(R.drawable.ic_library_music_white24dp).setContent(mRemoteViews);
mBuilder.setCustomBigContentView(mRemoteViews).setAutoCancel(false);
mBuilder.setContentIntent(pIntent);
mBuilder.setOngoing(true);
NotificationManager mNotificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(ID_NOTIFICATION, mBuilder.build());
}
}
|
4576782a84de5180b62b0a6fccab5eca0b86cf06
|
[
"Java",
"Gradle"
] | 11 |
Java
|
anthinh123/Music
|
29b0253adc1a22932b6cd7151356ff106cb16b6b
|
756d48b1d02490f20c0b831d8f5c348a57bd865b
|
refs/heads/master
|
<file_sep># Board-Game-Review-Predictor
Can we predict the average score humans will give a new, yet-to-be released board game?
We can use the given dataset to train a model and make this prediction.
<file_sep>import pandas as pd
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
#first step of data exploration- read in the data and output basic summary stats
#read in the CSV
games_data = pd.read_csv("games.csv")
#print the columns which describe the various attributes we have for each game (row) of the dataset
print(games_data.columns)
#print the number of columns & rows of the dataset i.e. the shape
print(games_data.shape)
#81,312 games (rows) and 20 attributes (columns)
#problem- can we predict the average score humans will give a new, yet-to-be released board game?
#we can use the given dataset to train a model and make this prediction
#let's plot all of the average ratings in the given dataset. Hence let's plot the "average_ratings" column
plt.hist(games_data["average_rating"])
plt.show()
#after showing the plot, we find an anomaly that there are an unusually large number of games with 0 rating
#let's find out why
#print out the games (rows) that has a "0" rating
print(games_data[games_data["average_rating"]==0])
#so we see there are 24,380 such games with 0 ratings
#now let's see the other attributes of these games other than just its "average_rating".
#let's print out all the attributes of the games that have 0 average ratings, hence [:]
#by seeing the other attributes, we can possibly detect why there are so many 0 average_ratings.
#to do this, make a new dataframe
print(games_data[games_data["average_rating"]==0].iloc[:])
#this shows us that for this game, and presumably other games with 0 ratings, there are no customer reviews
#to confirm this theory, let's print all the attributes of all games which has a non-zero rating
print(games_data[games_data["average_rating"]>0].iloc[0])
#as theorized, all of these games that have a non-zero rating have thousands of customer reviews
#to get rid of the extraneous data, let's remove all the games with 0 reviews. games_data now only contains games with > 0 user reviews
games_data = games_data[games_data["users_rated"]>0]
#side note, many ML algorithms don't work with data that has missing values. so let's remove any rows (Games) that have missing attributes
games_data = games_data.dropna(axis=0)
#so now we see that there may be different "sets" of games i.e. those without reviews, those with high reviews, etc
#so, use k-means clustering to group together similar rows (i.e. games)
kmeans_training_model = KMeans(n_clusters = 5, random_state = 1)
#we only want the attributes (columns) that have numeric data, not text data
cols = games_data._get_numeric_data()
#fit the training model
kmeans_training_model.fit(cols)
#get the cluster assignment labels
labels = kmeans_training_model.labels_
#before we plot the clustering results, we need to perform dimensionality reduction using PCA. this is because
#currently we have too many attributes (dimensions/columns). its hard to make a comprehensible graph that plots all of these
from sklearn.decomposition import PCA
pca_2 = PCA(2)
#fit the model
cols_to_be_plotted = pca_2.fit_transform(cols)
#scatter plot of each game
plt.scatter(x=cols_to_be_plotted[:,0], y=cols_to_be_plotted[:,1], c=labels)
plt.show()
#find the attribute which has the strongest corrleation with "average_rating" so that it can be used to
#help predict average_rating
games_data.corr()["average_rating"]
|
8ffcaff691d8c94e90b33fc9d4799e735194fa6e
|
[
"Markdown",
"Python"
] | 2 |
Markdown
|
tdshah/Board-Game-Review-Predictor
|
4ebf0e5204bfbc183d595f8ff00b66acbf5195ff
|
4a959202da980c4aca92307828e5cfebbc213013
|
refs/heads/main
|
<repo_name>AkshithaRajavel/django-web-app<file_sep>/sudokumain/views.py
from django.shortcuts import render, redirect
def find(l):
try:
return l.index(0)
except:
return -1
def valid(j, L, x, n):
n1 = int(n ** 0.5)
if j in L[n * int(x / n):n * (int(x / n) + 1)]:
return 0
if j in L[x % n::n]:
return 0
i = (n1 ** 3) * (int(x / (n1 ** 3))) + n1 * int((x % n) / n1)
for y in range(n1):
if j in L[i:i + (n1 ** 3):n]:
return 0
i += 1
return 1
def sudoku(L, l1, n):
x = find(L)
if x == -1:
l1.extend(L)
return 1
else:
for j in range(1, n + 1):
if valid(j, L, x, n):
if sudoku(L[:x] + [j] + L[x + 1:], l1, n):
return 1
def home(request):
return render(request, 'home.html')
def solve(request, n=0):
d = {}
if request.method == "GET":
d['N'] = int(request.GET["num"])
n = d["N"]
if d['N'] == 9:
d["name"] = "cell"
else:
d["name"] = "b"
d["keys"] = []
for i in range(int(n)):
d['keys'].append([])
for j in range(int(n)):
d["keys"][i].append(int(n) * i + j)
else:
d["N"] = int(n)
if d['N'] == 9:
d["name"] = "cell"
else:
d["name"] = "b"
l1, L = [], []
for i in list(request.POST.values())[1:]:
if i:
L.append(int(i))
else:
L.append(0)
sudoku(L, l1, int(n))
d["vals"] = []
for i in range(int(n)):
d['vals'].append([])
for j in range(int(n)):
if l1[int(n) * i + j] == L[int(n) * i + j]:
a = "red"
else:
a = "black"
d["vals"][i].append((int(n) * i + j, l1[int(n) * i + j], a))
return render(request, "result.html", d)
return render(request, "board.html", d)
|
fa3358a9607e031632005dcd5a4820ad50a30690
|
[
"Python"
] | 1 |
Python
|
AkshithaRajavel/django-web-app
|
39e0eaf2111550d0a40f1f604c5e956c8e8c7166
|
1baa0564b06d930cd62037badf9dd70ce3252fc7
|
refs/heads/master
|
<file_sep>'use strict'
var FMM = (function() {
var FMM = {};
var add_field_grids = function(field1, field2, add_fn) {
for(var cell_key in field2){
if (field1[cell_key] === void 0) {
field1[cell_key] = field2[cell_key];
continue;
};
field1[cell_key] = add_fn(field1[cell_key], field2[cell_key]);
}
}
// Field2
// A class representing 2D mathmatical fields using the fast multipole method.
// Any data type can be used to describe point values in the field,
// provided appropriate values are given for add_fn and remove_fn
// If add_fn and remove_fn are not defined, the field must operate on scalar numbers
//
// resolution - Distance at which two particles are treated as one
// range - Distance at which two particles can no longer interact with one another
// value_fn - A function that describes the field.
// This is expressed as a function of distance to a particle.
// It is highly recommended this be proportionate to an inverse exponent of distance,
// e.g. function(distance) { return 1/Math.pow(distance,2) }
// background - background value that is applied evenly to every point on the field
FMM.Field2 = function(resolution, range, value_fn, add_fn, remove_fn, background) {
function Cell (level, x,y) {
return { level: level, x: x, y: y };
}
function Point (x,y,z) {
return { x:x, y:y };
}
var min_level = resolution ? Math.floor(Math.log(resolution) / Math.log(2)) : 0;
var max_level = range ? Math.floor(Math.log(range) / Math.log(2)) : 0;
function cell_hash (cell_) {
return cell_.level + ',' + cell_.x + ',' + cell_.y ;
};
function format_pos (pos) {
if (pos.x !== void 0 && pos.y !== void 0) {
return pos;
};
return Point(
pos[0],
pos[1]
);
};
function distance (u, v) {
return Math.sqrt(Math.pow(u.x - v.x , 2) + Math.pow(u.y - v.y, 2));
}
function offset (location, particle) {
return Point(
particle.x - location.x,
particle.y - location.y
);
}
function parent (cell) {
return Cell(
cell.level + 1,
Math.floor(cell.x/2),
Math.floor(cell.y/2)
);
}
function parents (cells) {
var unique = {}
for (var i = 0, li = cells.length; i < li; i++) {
var parent_ = parent(cells[i]);
unique[cell_hash(parent_)] = parent_;
};
var parents_ = [];
for (var parent_ in unique) {
parents_.push(unique[parent_]);
}
return parents_;
}
function children (cell) {
var children_ = [];
for (var i = 0; i <= 1; i++) {
for (var j = 0; j <= 1; j++) {
children_.push( Cell(
cell.level - 1,
cell.x * 2 + i,
cell.y * 2 + j
));
}
};
return children_;
}
function midpoint (cell) {
return Point(
(cell.x + 0.5) * Math.pow(2, cell.level),
(cell.y + 0.5) * Math.pow(2, cell.level)
)
}
function cell (pos, level) {
return Cell(
level,
Math.floor(pos.x / Math.pow(2, level)),
Math.floor(pos.y / Math.pow(2, level))
);
}
function cells (pos) {
var cells_ = [];
for (var level = min_level; level < max_level; level++) {
cells_.push(cell(pos, level))
};
return cells_;
}
function vicinity (pos, level) {
var center = cell(pos, level);
var vicinity_ = [];
for (var i = -1; i <= 1; i++) {
for (var j = -1; j <= 1; j++) {
vicinity_.push( Cell(
level,
center.x + i,
center.y + j
));
}
};
return vicinity_;
}
function vicinities (pos) {
var vicinities_ = [];
for (var level = min_level; level < max_level; level++) {
vicinities_.push(vicinity(pos, level))
};
return vicinities_;
}
// adds to grid the effect of a single particle
function add_monopole_field_grid (grid, pos, options, value_fn, add_fn) {
var cell_ = cell(pos, min_level);
var vicinities_ = vicinities(pos);
var excluded = {};
excluded[cell_hash(cell_)] = cell_;
for (var i = 0, li = vicinities_.length; i < li; i++) {
var vicinity_ = vicinities_[i];
var parents_ = parents(vicinity_);
for (var j = 0, lj = parents_.length; j < lj; j++) {
var parent_ = parents_[j];
excluded[cell_hash(parent_)] = parent_;
var children_ = children(parent_);
for (var k = 0, lk = children_.length; k < lk; k++) {
var child_ = children_[k];
var child_key = cell_hash(child_);
if (excluded[child_key] !== void 0) {
continue;
};
var new_value = format_pos(value_fn(offset(midpoint(child_), pos), options));
var old_value = grid[child_key];
if (old_value === void 0) {
grid[child_key] = new_value;
continue;
};
grid[child_key] = add_fn(old_value, new_value);
};
};
};
}
function add_field_grids (grid, field2, add_fn) {
for(var cell_key in field2){
if (grid[cell_key] === void 0) {
grid[cell_key] = field2[cell_key];
continue;
};
grid[cell_key] = add_fn(grid[cell_key], field2[cell_key]);
}
}
function get_value (field, pos, background){
var value = background;
var cells_ = cells(pos);
for (var i = 0, li = cells_.length; i < li; i++) {
var cell_ = cells_[i];
if (field[cell_hash(cell_)] === void 0) {
continue;
};
if (value === void 0) {
value = field[cell_hash(cell_)];
continue;
};
value = add_fn(field[cell_hash(cell_)], value);
};
return value;
}
var this_ = {};
this_._grid = {};
this_.value = function (pos) {
var value = get_value(this_._grid, format_pos(pos), background);
return value;
}
this_.clear = function () {
this_._grid = {};
}
this_.add_field = function(field) {
add_field_grids(this_._grid, field._grid, add_fn);
}
this_.remove_field = function(field) {
add_field_grids(this_._grid, field._grid, remove_fn);
}
this_.add_particle = function(pos, options) {
options = options || {};
add_monopole_field_grid(this_._grid, format_pos(pos), options, value_fn, add_fn);
}
this_.remove_particle = function(pos, options) {
options = options || {};
add_monopole_field_grid(this_._grid, format_pos(pos), options, value_fn, remove_fn);
}
return this_;
}
FMM.ScalarField2 = function(resolution, range, value_fn, background) {
return FMM.Field2(resolution, range, value_fn,
function(u, v) { return u + v; },
function(u, v) { return u - v; },
background || 0);
}
FMM.VectorField2 = function(resolution, range, value_fn, background) {
return FMM.Field2(resolution, range, value_fn,
function(u, v) {
return {
x: u.x+v.x,
y: u.y+v.y,
};
},
function(u, v) {
return {
x: u.x-v.x,
y: u.y-v.y,
};
},
background || {x:0,y:0}
);
}
// Field3
// A class representing 2D mathmatical fields using the fast multipole method.
// Any data type can be used to describe point values in the field,
// provided appropriate values are given for add_fn and remove_fn
// If add_fn and remove_fn are not defined, the field must operate on scalar numbers
//
// resolution - Distance at which two particles are treated as one
// range - Distance at which two particles can no longer interact with one another
// value_fn - A function that describes the field.
// This is expressed as a function of distance to a particle.
// It is highly recommended this be proportionate to an inverse exponent of distance,
// e.g. function(distance) { return 1/Math.pow(distance,2) }
// background - background value that is applied evenly to every point on the field
FMM.Field3 = function(resolution, range, value_fn, add_fn, remove_fn, background) {
function Cell (level, x,y,z) {
return { level: level, x: x, y: y, z: z };
}
function Point (x,y,z) {
return { x:x, y:y, z:z };
}
var min_level = resolution ? Math.floor(Math.log(resolution) / Math.log(2)) : 0;
var max_level = range ? Math.floor(Math.log(range) / Math.log(2)) : 0;
function cell_hash (cell_) {
return cell_.level + ',' + cell_.x + ',' + cell_.y + ',' + cell_.z;
};
function format_pos (pos) {
if (pos.x !== void 0 && pos.y !== void 0 && pos.z !== void 0) {
return pos;
};
return Point(
pos[0],
pos[1],
pos[2]
);
};
function distance (u, v) {
return Math.sqrt(Math.pow(u.x - v.x , 2) + Math.pow(u.y - v.y, 2) + Math.pow(u.z - v.z, 2));
}
function offset (location, particle) {
return Point(
particle.x - location.x,
particle.y - location.y,
particle.z - location.z
);
}
function parent (cell) {
return Cell(
cell.level + 1,
Math.floor(cell.x/2),
Math.floor(cell.y/2),
Math.floor(cell.z/2)
);
}
function parents (cells) {
var unique = {}
for (var i = 0, li = cells.length; i < li; i++) {
var parent_ = parent(cells[i]);
unique[cell_hash(parent_)] = parent_;
};
var parents_ = [];
for (var parent_ in unique) {
parents_.push(unique[parent_]);
}
return parents_;
}
function children (cell) {
var children_ = [];
for (var i = 0; i <= 1; i++) {
for (var j = 0; j <= 1; j++) {
for (var k = 0; k <= 1; k++) {
children_.push( Cell(
cell.level - 1,
cell.x * 2 + i,
cell.y * 2 + j,
cell.z * 2 + k
));
}
}
};
return children_;
}
function midpoint (cell) {
return Point(
(cell.x + 0.5) * Math.pow(2, cell.level),
(cell.y + 0.5) * Math.pow(2, cell.level),
(cell.z + 0.5) * Math.pow(2, cell.level)
)
}
function cell (pos, level) {
return Cell(
level,
Math.floor(pos.x / Math.pow(2, level)),
Math.floor(pos.y / Math.pow(2, level)),
Math.floor(pos.z / Math.pow(2, level))
);
}
function cells (pos) {
var cells_ = [];
for (var level = min_level; level < max_level; level++) {
cells_.push(cell(pos, level))
};
return cells_;
}
function vicinity (pos, level) {
var center = cell(pos, level);
var vicinity_ = [];
for (var i = -1; i <= 1; i++) {
for (var j = -1; j <= 1; j++) {
for (var k = -1; k <= 1; k++) {
vicinity_.push( Cell(
level,
center.x + i,
center.y + j,
center.z + k
));
}
}
};
return vicinity_;
}
function vicinities (pos) {
var vicinities_ = [];
for (var level = min_level; level < max_level; level++) {
vicinities_.push(vicinity(pos, level))
};
return vicinities_;
}
// adds to grid the effect of a single particle
function add_monopole_field_grid (grid, pos, options, value_fn, add_fn) {
var cell_ = cell(pos, min_level);
var vicinities_ = vicinities(pos);
var excluded = {};
excluded[cell_hash(cell_)] = cell_;
for (var i = 0, li = vicinities_.length; i < li; i++) {
var vicinity_ = vicinities_[i];
var parents_ = parents(vicinity_);
for (var j = 0, lj = parents_.length; j < lj; j++) {
var parent_ = parents_[j];
excluded[cell_hash(parent_)] = parent_;
var children_ = children(parent_);
for (var k = 0, lk = children_.length; k < lk; k++) {
var child_ = children_[k];
var child_key = cell_hash(child_);
if (excluded[child_key] !== void 0) {
continue;
};
var new_value = format_pos(value_fn(offset(midpoint(child_), pos), options));
var old_value = grid[child_key];
if (old_value === void 0) {
grid[child_key] = new_value;
continue;
};
grid[child_key] = add_fn(old_value, new_value);
};
};
};
}
function add_field_grids (grid, field2, add_fn) {
for(var cell_key in field2){
if (grid[cell_key] === void 0) {
grid[cell_key] = field2[cell_key];
continue;
};
grid[cell_key] = add_fn(grid[cell_key], field2[cell_key]);
}
}
function get_value (field, pos, background){
var value = background;
var cells_ = cells(pos);
for (var i = 0, li = cells_.length; i < li; i++) {
var cell_ = cells_[i];
if (field[cell_hash(cell_)] === void 0) {
continue;
};
if (value === void 0) {
value = field[cell_hash(cell_)];
continue;
};
value = add_fn(field[cell_hash(cell_)], value);
};
return value;
}
var this_ = {};
this_._grid = {};
this_.value = function (pos) {
var value = get_value(this_._grid, format_pos(pos), background);
return value;
}
this_.clear = function () {
this_._grid = {};
}
this_.add_field = function(field) {
add_field_grids(this_._grid, field._grid, add_fn);
}
this_.remove_field = function(field) {
add_field_grids(this_._grid, field._grid, remove_fn);
}
this_.add_particle = function(pos, options) {
options = options || {};
add_monopole_field_grid(this_._grid, format_pos(pos), options, value_fn, add_fn);
}
this_.remove_particle = function(pos, options) {
options = options || {};
add_monopole_field_grid(this_._grid, format_pos(pos), options, value_fn, remove_fn);
}
return this_;
}
FMM.ScalarField3 = function(resolution, range, value_fn, background) {
return FMM.Field3(resolution, range, value_fn,
function(u, v) { return u + v; },
function(u, v) { return u - v; },
background || 0);
}
FMM.VectorField3 = function(resolution, range, value_fn, background) {
return FMM.Field3(resolution, range, value_fn,
function(u, v) {
return Point(
u.x+v.x,
u.y+v.y,
u.z+v.z
);
},
function(u, v) {
return Point(
u.x-v.x,
u.y-v.y,
u.z-v.z
);
},
background || {x:0,y:0,z:0}
);
}
return FMM;
})();
var THREE = THREE || {};
THREE.VectorField2 = function (resolution, range, value_fn) {
return FMM.Field2(resolution, range,
function(offset, particle) {
return value_fn(new THREE.Vector2(offset.x, offset.y), particle);
},
function(u, v) {
return THREE.Vector2.addVectors( u, v );
},
function(u, v) {
return THREE.Vector2.subVectors( u, v );
}
);
}
THREE.VectorField3 = function (resolution, range, value_fn) {
return FMM.Field3(resolution, range,
function(offset, particle) {
return value_fn(new THREE.Vector3(offset.x, offset.y, offset.z), particle);
},
function(u, v) {
return new THREE.Vector3().addVectors( u, v );
},
function(u, v) {
return new THREE.Vector3().subVectors( u, v );
}
);
}
<file_sep># simple makefile to avoid repeatitive tasks
buildDoc:
docco *.js
monitorDoc: build
(while inotifywait -r -e modify,attrib,create . ; do make build; done)
server:
python -m SimpleHTTPServer
deploy:
# assume there is something to commit
# use "git diff --exit-code HEAD" to know if there is something to commit
# so two lines: one if no commit, one if something to commit
git commit -a -m "New deploy" && git push -f origin HEAD:gh-pages && git reset HEAD~
<file_sep># fast-multipole-method.js
This is a javascript implementation for the [fast multipole method](https://en.wikipedia.org/wiki/Fast_multipole_method). Classes exist for both 2D and 3D simulations. A subset of classes allow you to work easily with Vector2 and Vector3 objects in Three.js. Otherwise, you can work with any object that has x and y attributes, or alternatively, you can work with lists of size 2 or 3.
## The problem
Let's say you want to simulate a solar system. You'll recall all objects in the universe effect one another through gravity, right? A naïve simulator might simulate this as follows:
for every object in the universe:
for every other object in the universe:
calculate the force exerted between the objects
The simulation above doesn't scale well as we increase the number of objects. If I want to simulate 3 objects I have to make 6 calculations per timestep. If I want to simulate 4 objects I have to make 12 calculations per timestep - I doubled the number of calculations just by adding one object! Things get out of hand quickly. What I really want is for the number of calculations to increase *in direct proportion* to the number of objects.
Well, fine then, why don't I do it this way:
for every object in the universe:
for every location in the universe:
calculate the force exerted by the object from that location and store it in a grid somewhere
The "grid" we mention is an approximation for what physicists call a [field](https://en.wikipedia.org/wiki/Field_(physics)). For every point on a field, there is a corresponding value. Sometimes, that value is a scalar, like density or pressure. Sometimes, that value is a vector, like force, velocity, or acceleration. Gravity can be represented by a field of vectors, each vector expressing the acceleration one would experience at a specific location.
Now I'm a bit of a smart-aleck, here. It's true the solution above scales well with the number of objects, but it doesn't scale well with the size of the grid. If I want to simulate a square universe that's 3 grid cells wide, I have to make 9 calculations for each object. If I want to simulate a universe that's 4 grid cells wide I have to make 16 calculations for each object. Again, things get out of hand quickly. What we really need is a simulation that scales well for both the number of objects *and* the size of the grid.
Well, fine then, how about this. Gravity gets weaker with distance, so let's say we keep the grid, but we ignore any interaction between objects that are further than a grid cell's width apart. This approach scales well, but it has some undesireable consequences. Gravity might get weaker with distance in the real world, but it never completely vanishes. If we have a really massive object, that object will no longer be able to effect distant objects like it should.
## The fast multipole method
The solution here relies upon an observation. As you move further away from an object, you still have to simulate gravity, but it becomes less important to do so accurately. This is because gravity follows an [inverse square law](https://en.wikipedia.org/wiki/Inverse-square_law). The further you go, the less gravity you feel, and the less important it becomes to get the details right. The only thing that continues to matter is the order of magnitude.
An object that's very far away is best modeled using very large grid cells. Only a single value is stored per grid cell, so it's not likely this value will correctly represent the force of gravity all throughout its cell, but that's okay, because the object is far away and accuracy doesn't matter much.
Likewise, an object that's very close can be modeled using very small grid cells. Using small grid cells is normally costly to performance, but that's okay if we only consider adjacent grid cells.
So why not use both sizes? As a matter of fact, we can have a number of different cell sizes, each nested within one another. It becomes very easy this way to scale up our simulation. Let's say we have a series of nested grid cells. Each cell has a number of subdivisions, and each subdivision is half the width of its parent. It only takes about [200](http://www.wolframalpha.com/input/?i=log2+%28+%28diameter+of+the+universe%29+%2F+%28planck+length%29+%29) such subdivisions before we can simulate the entire observable universe down to the resolution of a planck unit. Assuming we represent our grid with a sparsely populated hash table, we can easily implement this on modern hardware.
Naturally, our universe has to be very sparsely populated, but the simulation scales well with object count, too, so we can still simulate an impressive number of objects. It's totally possible to have a few million particles in our simulation, assuming we don't mind the lag.
The algorithm itself remains fairly simple. For each object we iterate through our nested grids and examine the grid cells that are adjacent to the one housing the object. Each grid cell gets a value assigned to it, and this value represents the force exerted on every object within the grid cell. The simulator now looks something like this:
for every object in the universe:
for every level in the nested grid:
for every neighboring grid cell within the level:
calculate the force between the object and the midpoint of the grid cell
And if we want to retrieve the value at a specific location, we do the following:
for every level in the nested grid:
find the grid cell that intersects with our location and add its value to a running total
The solution here is known as the [fast multipole method](https://en.wikipedia.org/wiki/Fast_multipole_method). Our runtime scales linearly with the number of objects. It also scales logarithmically with the size of the simulation. Complexity is O(N log(M)), where N is the object count and and M is the simulation size. This is exactly what we want.
## How do I use it?
Let's say you want to simulate the solar system in 2D. For starters, you'll want something to represent your gravity field:
field = FMM.VectorField2(resolution, range, value_function);
`resolution` expresses the smallest distance considered by the model. It is the distance at which two particles become treated as one. `range` expresses the maximum distance considered by the model. It is the distance at which two particles can no longer interact with one another.
What's `value_function`, you ask? `value_function` specifies the value at each point in the field. It accepts a 2D vector indicating the distance to a particle, and returns a 2D vector indicating the value at that distance. It can also accept an optional parameter expressing the properties of a particle, such as mass or charge. Here's what `value_function` looks like in our gravity simulator:
function value_function(offset, particle) {
var distance = Math.sqrt( Math.pow(offset.x, 2) + Math.pow(offset.y, 2) );
var acceleration = gravitational_constant * particle.mass / Math.pow(distance, 2)
var normalized = {
x: offset.x / distance,
y: offset.y / distance,
};
return {
x: normalized.x * acceleration
y: normalized.y * acceleration,
}
}
Now we add objects to our simulation.
field.add_particle([0,0], { mass: 1 * solar_mass });
`add_particle()` accepts two parameters. The first expresses the location of the particle. You can use either an array of size two (e.g. `[0,0]`) or an object with `x` and `y` attributes (e.g. `{x: 0, y: 0}`). The second parameter is optional, and specifies any additional properties of the particle.
We are now ready to retrieve values from our gravity field.
acceleration = field.value([1,1]);
As with `add_particle()`, the `value()` method accepts a single parameter representing location. This can either be an array of size two (`[1,1]`) or an object with `x` and `y` attributes (e.g. `{x: 1, y: 1}`).
## Other fields
You can create 2D scalar fields with a second class called `ScalarField2`.
scalarfield = FMM.ScalarField2(resolution, range, scalar_value_function);
There are also equivalent classes for representing 3D scalar fields, `ScalarField3` and `VectorField3`
scalarfield = FMM.ScalarField3(resolution, range, scalar_value_function);
vectorfield = FMM.VectorField3(resolution, range, vector_value_function);
If you do any work with [Three.js](http://threejs.org/), you can also try the equivalent classes available under the `THREE` namespace. These classes operate in the exact same manner, but utilize the `THREE.Vector2` and `THREE.Vector3` classes that are provided by Three.js.
vectorfield = THREE.VectorField2(resolution, range, vector2_value_function);
vectorfield = THREE.VectorField3(resolution, range, vector3_value_function);
Lastly, if you want to work with another type of class for vectors/scalars, you can try the generic `Field2` and `Field3` classes. These generics expose two additional function parameters, `add_function` and `remove_function`, which tell the library how to add or subtract the values within the field. Here's how `THREE.VectorField3` is implemented using `Field3`:
THREE.VectorField3 = function (resolution, range, value_fn) {
return FMM.Field3(resolution, range, value_fn,
function(u, v) {
return THREE.Vector3.addVectors( u, v );
},
function(u, v) {
return THREE.Vector3.subVectors( u, v );
}
);
}
<file_sep>'use strict'
var FMM = (function() {
var FMM = {};
// Field3
// A class representing 3D mathmatical fields using the fast multipole method.
// This class makes certain assumptions about data types in order to optimize for performance.
//
// resolution - Distance at which two particles are treated as one
// range - Distance at which two particles can no longer interact with one another
// value_fn - A function that describes the field.
// This is expressed as a function of distance to a particle.
// It is highly recommended this be proportionate to an inverse exponent of distance,
// e.g. function(distance) { return 1/Math.pow(distance,2) }
FMM.Field3 = function(resolution, range, value_fn) {
var N = 3; // number of dimensions, always constant
function Cell (level, x,y,z) {
return { level: level, x: x, y: y, z: z };
}
function Point (x,y,z) {
return { x:x, y:y, z:z };
}
function midpoint (cell) {
var cell_size = range / ( 1 << cell.level );
return Point(
(cell.x + 0.5) * cell_size - 0.5 * range,
(cell.y + 0.5) * cell_size - 0.5 * range,
(cell.z + 0.5) * cell_size - 0.5 * range,
);
}
function cell_hash (cell_) {
return (1 << (N*cell_.level))
+ cell_.x * (1 << (2*cell_.level))
+ cell_.y * (1 << (1*cell_.level))
+ cell_.z;
};
var min_level = 1;
var max_level = Math.ceil(Math.log(range/resolution) / Math.log(2)) + 1;
if (max_level > 9) {
throw 'grid consumes too much memory! try adjusting resolution or range parameters'
}
var max_hash_size = 1 << (N*max_level);
var _grid = {
x: new Float32Array(max_hash_size),
y: new Float32Array(max_hash_size),
z: new Float32Array(max_hash_size),
};
function distance (u, v) {
return Math.sqrt((u.x - v.x )*(u.x - v.x ) + (u.y - v.y)*(u.y - v.y) + (u.z - v.z)*(u.z - v.z));
}
function offset (location, particle) {
return Point(
particle.x - location.x,
particle.y - location.y,
particle.z - location.z
);
}
function equals(a, b) {
return a.x == b.x &&
a.y == b.y &&
a.z == b.z &&
a.level == b.level;
}
function is_out_of_bounds(cell) {
var cell_num = 1 << cell.level;
return !( 0 <= cell.x && cell.x < cell_num
&& 0 <= cell.y && cell.y < cell_num
&& 0 <= cell.z && cell.z < cell_num );
}
function children(cell_) {
var level = cell_.level + 1;
var x = 2*cell_.x;
var y = 2*cell_.y;
var z = 2*cell_.z;
return [
Cell(level, x, y, z ),
Cell(level, x+1, y, z ),
Cell(level, x, y+1, z ),
Cell(level, x, y, z+1 ),
Cell(level, x+1, y+1, z ),
Cell(level, x, y+1, z+1 ),
Cell(level, x+1, y, z+1 ),
Cell(level, x+1, y+1, z+1 ),
];
}
function cell (pos, level) {
var cell_size = range / ( 1 << level );
var cell_x = (pos.x + 0.5 * range) / (cell_size);
var cell_y = (pos.y + 0.5 * range) / (cell_size);
var cell_z = (pos.z + 0.5 * range) / (cell_size);
var floor_x = Math.floor(cell_x);
var floor_y = Math.floor(cell_y);
var floor_z = Math.floor(cell_z);
return Cell(level, floor_x, floor_y, floor_z);
}
function cells (pos) {
var cells_ = [];
var cell_;
for (var level = min_level; level < max_level; level++) {
cell_ = cell(pos, level);
if (!is_out_of_bounds(cell_)) {
cells_.push(cell_);
}
};
return cells_;
}
function vicinities (pos) {
var cells_ = cells(pos);
var vicinities_ = [];
var cell_ = Cell(0, 0,0,0);
// for each cell in cells_, find the children of that cell that aren't occupied by pos
for (var cell_i = 1; cell_i < cells_.length; cell_i++) {
var occupied_ = cells_[cell_i];
var children_ = children(cell_);
for (var child_i = 0; child_i < children_.length; child_i++) {
var child_ = children_[child_i];
if (!equals(child_, occupied_) && !is_out_of_bounds(child_)) {
vicinities_.push(child_);
}
}
cell_ = occupied_;
}
return vicinities_;
}
// adds to grid the effect of a single particle
function add_monopole_field_grid (grid, pos, charge, value_fn) {
var x = grid.x;
var y = grid.y;
var z = grid.z;
var vicinities_ = vicinities(pos);
for (var i = 0, li = vicinities_.length; i < li; i++) {
var cell_ = vicinities_[i];
var cell_hash_ = cell_hash(cell_);
var new_value = value_fn(offset(midpoint(cell_), pos), charge);
x[cell_hash_] += new_value.x;
y[cell_hash_] += new_value.y;
z[cell_hash_] += new_value.z;
}
}
function add_field_grids (field1, field2) {
var x1 = field1.x;
var y1 = field1.y;
var z1 = field1.z;
var x2 = field2.x;
var y2 = field2.y;
var z2 = field2.z;
for (var i = 0, li = x.length; i < li; i++) {
x1[i] += x2[i];
y1[i] += y2[i];
z1[i] += z2[i];
}
}
function get_value (field, pos, out){
var x = field.x;
var y = field.y;
var z = field.z;
var ox = 0;
var oy = 0;
var oz = 0;
var cells_ = cells(pos);
var cell_ = cells_[0];
var cell_hash_ = 0;
for (var i = 0, li = cells_.length; i < li; i++) {
cell_ = cells_[i];
cell_hash_ = cell_hash(cell_);
ox += x[cell_hash_];
oy += y[cell_hash_];
oz += z[cell_hash_];
};
out.x = ox;
out.y = oy;
out.z = oz;
return out;
}
function print(field, level) {
var x = field.x;
var y = field.y;
var z = field.z;
var cell_num = 1 << level;
console.log('level ' + level + ':')
for (var k = 0; k < cell_num; k++) {
console.log(k + ':')
var line = '';
for (var i = 0; i < cell_num; i++) {
for (var j = 0; j < cell_num; j++) {
var cell_ = Cell(level, i, j, k);
var cell_hash_ = cell_hash(cell_);
var magnitude = x[cell_hash_]*x[cell_hash_]
+ y[cell_hash_]*y[cell_hash_]
+ z[cell_hash_]*z[cell_hash_];
var ref = 0.01;
line += magnitude > ref? '▓' : magnitude > ref/10? '▒': magnitude > ref/100? '░':' ';
}
line += '\n'
}
console.log(line);
}
}
var this_ = {};
this_._grid = _grid; // NOTE: this is exposed for debugging purposes, only
this_.value = function (pos, out) {
out = out || Point(0,0,0);
return get_value(_grid, pos, out);
}
this_.clear = function () {
_grid.x.fill(0);
_grid.y.fill(0);
_grid.z.fill(0);
}
// this_.add_field = function(field) {
// add_field_grids(_grid, field._grid, add_fn);
// }
// this_.remove_field = function(field) {
// add_field_grids(_grid, field._grid, remove_fn);
// }
this_.add_particle = function(pos, charge) {
add_monopole_field_grid(_grid, pos, charge, value_fn );
}
this_.remove_particle = function(pos, charge) {
add_monopole_field_grid(_grid, pos, -charge, value_fn );
}
this_.print = function(level) {
print(_grid, level);
}
return this_;
}
return FMM; })();
//var gravitational_constant = 1;
//var field = FMM.Field3(1, 10, function(offset, charge) {
// var distance = Math.sqrt( offset.x*offset.x + offset.y*offset.y + offset.z*offset.z );// console.log(offset, particle);
// var acceleration = gravitational_constant * charge / Math.pow(distance, 2)
// var normalized = {
// x: offset.x / distance,
// y: offset.y / distance,
// z: offset.z / distance,
// };
// return {
// x: normalized.x * acceleration,
// y: normalized.y * acceleration,
// z: normalized.z * acceleration
// };
//})
//
//field.add_particle({x:1,y:0,z:0}, 1);
//console.log(field.value({x:3,y:0,z:0}));
//
|
b9a9d850cdb2d9d9bf50fff21c21b3819a01be0a
|
[
"JavaScript",
"Makefile",
"Markdown"
] | 4 |
JavaScript
|
davidson16807/fast-multipole-method
|
95cd9bb499a893b0e176745400c21aefe6cf7382
|
0d50ec299681a73d9f062bf4950ca73b3d0e646d
|
refs/heads/master
|
<repo_name>mthang1801/track_corona_status<file_sep>/src/actions/page.js
import * as types from "./types";
export const changePage = url => dispatch => {
let type = "";
url = url.replace("/", "");
switch(url){
case "global" : type = types.GLOBAL_PAGE ; break;
case "countries" : type = types.COUNTRIES_PAGE ; break;
default : type = types.HOME_PAGE;
}
console.log(type);
dispatch({
type : type
})
}
<file_sep>/src/reducer/index.js
import {combineReducers} from "redux";
import corona from "./corona";
import page from "./page";
export default combineReducers({
corona,
page
})
<file_sep>/src/components/Global/Header/Header.jsx
import React from 'react'
import Moment from "react-moment";
import styles from "./Header.module.css";
import {connect} from "react-redux";
import PropTypes from "prop-types";
const Header = ({corona : {data_item}}) => {
return (
<div className={styles.header}>
<h1 className={styles.title}>DIỄN BIẾN DỊCH VIRUS CORONA TRÊN TOÀN CẦU</h1>
<h4>Dữ liệu ngày : <Moment format="DD-MM-YYYY">{data_item.date}</Moment></h4>
</div>
)
}
Header.propTypes = {
corona : PropTypes.object.isRequired
}
const mapStateToProps = state => ({
corona : state.corona
})
export default connect(mapStateToProps)(Header)
<file_sep>/src/components/Home/index.js
export {default as Header} from "./Header/Header";
export {default as Navbar} from "../Layout/Navbar/Navbar";
export {default as CardsHome} from "./CardsHome/CardsHome";
export {default as Charts} from "./Charts/Charts";
export {default as StatisticCards} from "./StatisticCards/StatisticCards"<file_sep>/src/components/Global/CardDetails/CardDetails.jsx
import React from 'react'
import PropTypes from 'prop-types';
import {connect} from "react-redux";
import { makeStyles } from '@material-ui/core/styles';
import styles from "./CardDetails.module.css";
import {Bar} from "react-chartjs-2";
import Moment from "react-moment";
const CardDetails = ({data_item}) => {
const barChartTotalCases =(
<Bar
data={{
labels : ["Bị nhiễm", "Hồi phục", "Tử vong"],
datasets : [
{
label : "People",
backgroundColor : [
"rgba(0, 0, 255, 0.8)",
"rgba(0, 255, 0, 0.8)",
"rgba(255, 0, 0, 0.8)"
],
data : [data_item.confirmed, data_item.recovered, data_item.deaths]
}
]
}}
options={{
maintainAspectRatio: false,
responsive : true
}}
/>
)
const barChartNewCases=(
<Bar
data={{
labels : ["Bị nhiễm", "Hồi phục", "Tử vong"],
datasets : [
{
label : "People",
backgroundColor : [
"rgba(0, 0, 255, 0.8)",
"rgba(0, 255, 0, 0.8)",
"rgba(255, 0, 0, 0.8)"
],
data : [data_item.new_confirmed, data_item.new_recovered, data_item.new_deaths]
}
]
}}
options={{
maintainAspectRatio: false,
responsive : true
}}
/>
)
return (
<div className={styles.container}>
<div className={styles.card}>
<div className={styles.card_header}>
<h3 className={styles.title}>TỔNG SỐ TRƯỜNG HỢP</h3>
<h5 className={styles.subtitle}><Moment format="DD-MM-YYYY HH:MM Z">{data_item.date}</Moment></h5>
</div>
<div className={styles.content}>
<div>Nhiễm bệnh: <span className={styles.new_confirmed}>{data_item.confirmed}</span></div>
<div>Hồi phục: <span className={styles.new_recovered}>{data_item.recovered}</span></div>
<div>Tử vong: <span className={styles.new_deaths}>{data_item.deaths}</span></div>
</div>
<div className={styles.chart}>
{barChartTotalCases}
</div>
</div>
<div className={styles.card}>
<div className={styles.card_header}>
<h3 className={styles.title}>GHI NHẬN MỚI</h3>
<h5 className={styles.subtitle}> <Moment format="DD-MM-YYYY HH:MM Z">{data_item.date}</Moment></h5>
</div>
<div className={styles.content}>
<div><span>Nhiễm bệnh:</span> <span className={styles.new_confirmed}>{data_item.new_confirmed}</span></div>
<div><span>Hồi phục:</span> <span className={styles.new_recovered}>{data_item.new_recovered}</span></div>
<div><span>Tử vong: </span><span className={styles.new_deaths}>{data_item.new_deaths}</span></div>
</div>
<div className={styles.chart}>
{barChartNewCases}
</div>
</div>
</div>
)
}
CardDetails.propTypes = {
data_item : PropTypes.object.isRequired
}
const mapStateToProps = state => ({
data_item : state.corona.data_item
})
export default connect(mapStateToProps)(CardDetails)
<file_sep>/src/components/Global/index.js
export {default as Header} from "./Header/Header";
export {default as CardDetails} from "./CardDetails/CardDetails";
export {default as Tables} from "./Tables/Tables";
export {default as TableItem } from "./TableItem/TableItem";
<file_sep>/src/actions/corona.js
import * as types from "./types";
import axios from "axios";
import _ from "lodash";
const url_history = "https://corona-api.com";
const url_countries = "https://corona-api.com/countries/"
const url_population = "https://world-population.p.rapidapi.com/worldpopulation";
export const loadData = () => async dispatch => {
try {
//get history
let res = await axios.get(`${url_history}/timeline`);
let histories = res.data.data.map( data => ({
confirmed : data.confirmed,
recovered : data.recovered,
deaths : data.deaths,
active : data.active,
new_confirmed : data.new_confirmed,
new_deaths : data.new_deaths,
new_recovered : data.new_recovered,
date : data.date
}))
//get countries
res = await axios.get(`${url_history}/countries`);
let countries = res.data.data;
let totalCritical = _.sumBy(countries, (country => country.latest_data.critical));
let totalActive = _.sumBy(countries, (({latest_data}) => latest_data.confirmed - latest_data.recovered -latest_data.deaths));
let confirmed = _.sumBy(countries, (({latest_data}) => latest_data.confirmed));
let recovered = _.sumBy(countries, (({latest_data}) => latest_data.recovered));
let deaths = _.sumBy(countries, (({latest_data}) => latest_data.deaths));
//get new update
let new_update ={} ;
new_update.totalActive = totalActive;
new_update.totalCritical = totalCritical;
new_update.confirmed = confirmed;
new_update.recovered = recovered;
new_update.deaths = deaths;
new_update.date = histories[0].date;
//Sort number of confirmed by country
countries = _.sortBy(countries, (country => -country.latest_data.confirmed));
countries = countries.map( country => {
country.latest_data.calculated.deaths_per_mllion_population = Math.round(country.latest_data.deaths / country.population * 1000000);
return country;
})
//get population
let config = {
headers : {
"x-rapidapi-host": "world-population.p.rapidapi.com",
"x-rapidapi-key": "<KEY>"
}
}
res = await axios.get(url_population, config);
let world_population = res.data.body.world_population;
let world = {
name : "World",
population : world_population,
updated_at : countries[0].updated_at,
today : {
deaths : _.sumBy(countries , country => country.today.deaths),
confirmed : _.sumBy(countries, country => country.today.confirmed)
},
latest_data : {
deaths : _.sumBy(countries , country => country.latest_data.deaths),
confirmed : _.sumBy(countries , country => country.latest_data.confirmed),
recovered : _.sumBy(countries , country => country.latest_data.recovered),
critical : _.sumBy(countries , country => country.latest_data.critical),
}
};
world.latest_data.calculated = {
death_rate : world.latest_data.deaths / world.latest_data.confirmed,
recovery_rate : world.latest_data.recovered / world.latest_data.recovered,
cases_per_million_population :Math.round( world.latest_data.confirmed / world.population * 1000000),
deaths_per_mllion_population : Math.round(world.latest_data.deaths / world.population * 1000000)
}
countries.unshift(world);
dispatch({
type : types.LOADED_DATA,
payload : {new_update, histories : histories , countries , home_country : {timeline : histories}}
})
} catch (error) {
dispatch({
type : types.DATA_ERROR,
payload : {msg : error.response.statusText, status : error.response.status}
})
}
}
export const getDataItem = data => dispatch => {
dispatch({
type : types.DATA_ITEM,
payload : data
})
}
export const getHomeCountryData = countryCode => async dispatch => {
let url = "";
switch(countryCode){
case "GB" : url = `${url_history}/timeline`; break;
case "VN" : url = `${url_countries}/VN` ; break;
default : url = `${url_countries}/${countryCode}`;
}
try {
let res = await axios.get(url);
if(countryCode === "GB"){
dispatch({
type : types.DATA_HOME_COUNTRY,
payload : {timeline : res.data.data}
})
}else{
dispatch({
type : types.DATA_HOME_COUNTRY,
payload : res.data.data
})
}
} catch (error) {
dispatch({
type : types.DATA_ERROR,
payload : {msg : error.response.statusText, status : error.response.status}
})
}
}
export const clearCountry = () => dispatch => {
dispatch({
type : types.CLEAR_COUNTRY
})
}
export const loadHomePage = () => dispatch => {
dispatch({
type : types.LOAD_HOME
})
}
export const getCountryData = code => async dispatch => {
try {
let res = await axios.get(`${url_history}/countries/${code}`);
if(code){
dispatch({
type : types.DATA_COUNTRY,
payload : res.data.data
})
return;
}
dispatch({
type : types.DATA_COUNTRY
})
} catch (error) {
dispatch({
type : types.DATA_ERROR,
payload : {msg : error.response.statusText, status : error.response.status}
})
}
}
export const getDefaultCountryData = () => dispatch => {
dispatch({
type : types.DEFAULT_DATA_COUNTRY
})
}
<file_sep>/src/App.js
import React, {useEffect} from 'react'
import store from "./store";
import {createMuiTheme } from '@material-ui/core/styles';
import { ThemeProvider } from '@material-ui/styles';
import {Provider} from "react-redux";
import {BrowserRouter as Router, Route, Switch, Link} from "react-router-dom";
import "./App.css";
import {Home, Global, Countries} from "./containers"
import {loadData} from "./actions/corona";
const THEME = createMuiTheme({
typography: {
"fontFamily":" -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif",
"fontSize": 16,
"fontWeightLight": 300,
"fontWeightRegular": 400,
"fontWeightMedium": 500
}
});
const App = () => {
useEffect(() => {
store.dispatch(loadData());
},[])
console.log();
return (
<ThemeProvider theme={THEME}>
<Provider store={store}>
<Router>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/global" component={Global}/>
<Route path="/countries" component={Countries}/>
</Switch>
</Router>
</Provider>
</ThemeProvider>
)
}
export default App
<file_sep>/src/components/Home/CardsHome/CardsHome.jsx
import React from 'react';
import clsx from "clsx";
import {connect} from "react-redux";
import PropTypes from "prop-types";
import Grid from "@material-ui/core/Grid";
import Card from "@material-ui/core/Card";
import Box from "@material-ui/core/Box";
import CardContent from "@material-ui/core/CardContent";
import Typography from "@material-ui/core/Typography";
import CountUp from "react-countup";
import styles from "./CardsHome.module.css";
import {makeStyles} from "@material-ui/core/styles";
const useStyles = makeStyles((theme) => ({
root: {
flexGrow : 1,
margin : "2rem 0",
[theme.breakpoints.down("sm")] : {
padding : 0
},
},
card : {
[theme.breakpoints.down("lg")] : {
width : 500
},
[theme.breakpoints.up("xs")] : {
width : "90%",
padding :"0"
},
[theme.breakpoints.up("sm")] : {
width : 350
},
[theme.breakpoints.up("md")] : {
width : 400,
padding : "2rem"
},
[theme.breakpoints.up("lg")] : {
width : 320,
padding : "2rem 4rem"
},
[theme.breakpoints.up("xl")] : {
marginRight : "2rem",
width : 400
},
padding : "4rem 5rem"
}
}))
const Cards = ({new_update : {confirmed, recovered, deaths, date}}) => {
const classes = useStyles();
return(
<Grid container spacing={2} justify="space-between" align="center" className={clsx(styles.container,classes.root)} >
<Grid item xs={12} lg={3} className={styles.grid}>
<Box component={Card} className={clsx(classes.card, styles.confirmed)} boxShadow={4}>
<CardContent className={styles.card_item}>
<Typography className={styles.title}>Nhiễm bệnh</Typography>
<Typography className={clsx(styles.subtitle)}><CountUp start={0} end={confirmed} duration={2.5} separator="."></CountUp></Typography>
</CardContent>
</Box>
</Grid>
<Grid item xs={12} lg={3} className={styles.grid}>
<Box component={Card} className={clsx(classes.card, styles.recovered)} boxShadow={4} >
<CardContent className={styles.card_item}>
<Typography className={clsx(styles.title)}>Hồi phục</Typography>
<Typography className={clsx(styles.subtitle,styles.text_recovered)}><CountUp start={0} end={recovered} duration={2.5} separator="."></CountUp></Typography>
</CardContent>
</Box>
</Grid>
<Grid item xs={12} lg={3} className={styles.grid}>
<Box component={Card} className={clsx(classes.card, styles.deaths)} boxShadow={4}>
<CardContent className={styles.card_item}>
<Typography className={styles.title}>Tử vong</Typography>
<Typography className={clsx(styles.subtitle, styles.sub_deaths)}><CountUp start={0} end={deaths} duration={2.5} separator="."></CountUp></Typography>
</CardContent>
</Box>
</Grid>
</Grid>
)
}
Cards.propTypes = {
new_update : PropTypes.object.isRequired
}
const mapStateToProps = state => ({
new_update : state.corona.new_update
})
export default connect(mapStateToProps)(Cards)
<file_sep>/src/components/Home/StatisticCards/StatisticCards.jsx
import React from "react";
import styles from "./StatisticCards.module.css";
import { Pie } from "react-chartjs-2";
import clsx from "clsx";
import { connect } from "react-redux";
import PropTypes from "prop-types";
import CountUp from "react-countup";
const StatisticCards = ({
corona: { histories, new_update },
page: { home },
}) => {
const [tgGraph1, setToggleGraph1] = React.useState(false);
const [tgGraph2, setToggleGraph2] = React.useState(false);
const refFrontActive = React.useRef(null);
const refBackActive = React.useRef(null);
const refFrontClosed = React.useRef(null);
const refBackClosed = React.useRef(null);
const historiesGlobal = [...histories];
const closedCase = new_update.confirmed - new_update.totalActive;
const recovered = new_update.recovered;
const deaths = closedCase - recovered;
historiesGlobal.reverse();
const option = {
responsive: true,
maintainAspectRatio: false,
tooltips: {
callbacks: {
label: function (tooltipItem, data) {
var dataset = data.datasets[tooltipItem.datasetIndex];
var meta = dataset._meta[Object.keys(dataset._meta)[0]];
var total = meta.total;
var currentValue = dataset.data[tooltipItem.index];
var percentage = parseFloat(
((currentValue / total) * 100).toFixed(1)
);
return currentValue + " (" + percentage + "%)";
},
title: function (tooltipItem, data) {
return data.labels[tooltipItem[0].index];
},
},
},
};
const pieChartActiveCase = (
<React.Fragment>
<Pie
options={option}
data={{
labels: ["Bình thường", "Nguy kịch"],
datasets: [
{
data: [
new_update.totalActive - new_update.totalCritical,
new_update.totalCritical,
],
backgroundColor: ["rgba(0,150,255, .9)", "rgba(255,0,0,.8)"],
hoverBackgroundColor: ["rgba(0,200,255)", "rgba(255,0,0)"],
},
],
}}
/>
</React.Fragment>
);
const pieChartClosedCase = (
<React.Fragment>
<Pie
options={option}
data={{
labels: ["Hồi phục", "Tử vong"],
datasets: [
{
data: [new_update.recovered, new_update.deaths],
backgroundColor: ["rgba(0,255,0, .8)", "rgba(100,100,100,.8)"],
hoverBackgroundColor: ["rgba(0,255,0)", "rgba(95,95,95)"],
},
],
}}
/>
</React.Fragment>
);
const toggleGraph1 = () => {
setToggleGraph1(!tgGraph1);
if (refFrontActive.current.style.transform === "rotateY(-180deg)") {
refFrontActive.current.style.transform = "rotateY(0)";
refBackActive.current.style.transform = "rotateY(180deg)";
refBackActive.current.style.opacity = "0";
refBackActive.current.style.transition = "all .7s";
return;
}
refFrontActive.current.style.transform = "rotateY(-180deg)";
refBackActive.current.style.opacity = "1";
refBackActive.current.style.transition = "all .7s";
refBackActive.current.style.transform = "rotateY(0deg)";
};
const toggleGraph2 = () => {
setToggleGraph2(!tgGraph2);
if (refFrontClosed.current.style.transform === "rotateY(-180deg)") {
refFrontClosed.current.style.transform = "rotateY(0)";
refBackClosed.current.style.transform = "rotateY(180deg)";
refBackClosed.current.style.opacity = "0";
refBackClosed.current.style.transition = "all .7s";
return;
}
refFrontClosed.current.style.transform = "rotateY(-180deg)";
refBackClosed.current.style.opacity = "1";
refBackClosed.current.style.transition = "all .7s";
refBackClosed.current.style.transform = "rotateY(0deg)";
};
return (
<div className={styles.container}>
<div className={styles.wrapper}>
<h2 className={styles.title}>Biểu đồ diễn biến dịch coronavirus</h2>
<div className={styles.cards}>
<div className={styles.card}>
<div className={styles.card_header}>Số ca dương tính</div>
<div className={styles.card_content}>
<div
className={clsx(styles.side, styles.front)}
ref={refFrontActive}>
<div className={styles.general}>
<div className={styles.general_num}>
<CountUp
start={0}
end={new_update.totalActive}
duration={2.5}
separator=",">
{new_update.totalActive}
</CountUp>
</div>
<div className={styles.general_sub}>
Số bệnh nhân hiện tại
</div>
</div>
<div className={styles.details}>
<div className={styles.mild_condition}>
<div className={styles.detail_mild_num}>
<CountUp
start={0}
end={new_update.totalActive - new_update.totalCritical}
duration={2.5}
separator=",">
{new_update.totalActive}
</CountUp>{" "}
(
{(
((new_update.totalActive - new_update.totalCritical) /
new_update.totalActive) *
100
).toFixed(0)}
%)
</div>
<div className={styles.detail_mild_sub}>
Tình trạng bình thường
</div>
</div>
<div className={styles.critical_condition}>
<div className={styles.detail_crit_num}>
<CountUp
start={0}
end={new_update.totalCritical}
duration={2.5}
separator=",">
{new_update.totalActive}
</CountUp>{" "}
(
{(
(new_update.totalCritical / new_update.totalActive) *
100
).toFixed(0)}
%)
</div>
<div className={styles.detail_crit_sub}>Nguy kịch</div>
</div>
</div>
</div>
<div
className={clsx(
styles.side,
styles.back,
styles.pieChartActiveCase
)}
ref={refBackActive}>
{pieChartActiveCase}
</div>
</div>
<div className={styles.card_action}>
<a href="#!" className={styles.link} onClick={toggleGraph1}>
{tgGraph1 ? "Xem số liệu" : "Xem biểu đồ"}
</a>
</div>
</div>
<div className={styles.card}>
<div className={styles.card_header}>hồi phục/ tử vong</div>
<div className={styles.card_content}>
<div
className={clsx(styles.side, styles.front)}
ref={refFrontClosed}>
<div className={styles.general}>
<div className={styles.general_num}>
<CountUp
start={0}
end={closedCase}
duration={2.5}
separator=",">
{closedCase}
</CountUp>
</div>
<div className={styles.general_sub}>
Tổng số ca hồi phục/ tử vong
</div>
</div>
<div className={styles.details}>
<div className={styles.mild_condition}>
<div className={styles.detail_recovered_num}>
<CountUp
start={0}
end={recovered}
duration={2.5}
separator=",">
{recovered}
</CountUp>{" "}
({((recovered / closedCase) * 100).toFixed(0)}%)
</div>
<div className={styles.detail_recovered_sub}>
Số ca hồi phục
</div>
</div>
<div className={styles.critical_condition}>
<div className={styles.detail_deaths_num}>
<CountUp
start={0}
end={closedCase - recovered}
duration={2.5}
separator=",">
{closedCase - recovered}
</CountUp>{" "}
(
{(((closedCase - recovered) / closedCase) * 100).toFixed(
0
)}
%)
</div>
<div className={styles.detail_deaths_sub}>
Số ca tử vong
</div>
</div>
</div>
</div>
<div
className={clsx(
styles.side,
styles.back,
styles.pieChartActiveCase
)}
ref={refBackClosed}>
{pieChartClosedCase}
</div>
</div>
<div className={styles.card_action}>
<a href="#!" className={styles.link} onClick={toggleGraph2}>
{tgGraph2 ? "Xem số liệu" : "Xem biểu đồ"}
</a>
</div>
</div>
</div>
</div>
</div>
);
};
StatisticCards.propTypes = {
corona: PropTypes.object.isRequired,
page: PropTypes.object.isRequired,
};
const mapStateToProps = (state) => ({
corona: state.corona,
page: state.page,
});
export default connect(mapStateToProps)(StatisticCards);
<file_sep>/src/components/index.js
export {default as Spinner} from "./Layout/Spinner/Spinner";
export {default as Tables} from "./Global/Tables/Tables";
export {default as CardDetails} from "./Global/CardDetails/CardDetails";
<file_sep>/src/reducer/corona.js
import * as types from "../actions/types";
const initialState = {
new_update : null ,
histories : [],
data_item : null,
countries : [] ,
country : null ,
home_country : null, //active at home page
cities : [] ,
city : null,
loading : true,
error : null
}
export default function(state=initialState, action){
const {type, payload} = action;
switch(type){
case types.LOADED_DATA :
return {
...state ,
...payload ,
loading: false
};
case types.DATA_ITEM :
return {
...state,
data_item : payload ,
loading :false
};
case types.DATA_HOME_COUNTRY :
return {
...state ,
loading : false,
home_country : payload
};
case types.DATA_COUNTRY :
console.log(payload);
return {
...state,
loading : false ,
country : payload
};
case types.CLEAR_COUNTRY :
return {
...state,
country : null ,
loading: false
};
case types.DEFAULT_DATA_COUNTRY :
let data = {...state.countries[0]};
data.timeline = [...state.histories];
return{
...state ,
country : data,
loading :false
}
case types.DATA_ERROR :
return{
new_update : null ,
history : [],
countries : [] ,
country : null ,
home_country : null,
cities : [] ,
city : null,
loading : false,
error : {...payload }
}
default : return state ;
}
}
<file_sep>/src/components/Countries/Charts/Charts.jsx
import React from 'react'
import {connect} from "react-redux";
import PropTypes from "prop-types";
import {Line} from "react-chartjs-2";
import styles from "./Charts.module.css";
const Charts = ({corona : {country}}) => {
console.log(country);
const ascendingData = [...country.timeline];
ascendingData.reverse();
const lineHistoryCountryData = (
<Line
options={{
responsive : true ,
maintainAspectRatio: false,
scales :{
xAxis : [{
ticks : {
fontSize : 10
},
gridLineWidth: 0,
}],
yAxis : [{
ticks : {
fontSize : 10,
},
gridLineWidth: 0,
}]
},
elements : {
point : {
radius : 2
}
}
}}
data={{
labels : ascendingData.map(({date}) => date),
datasets: [
{
label: "Xác nhận" ,
data : ascendingData.map(({confirmed}) => confirmed),
strokeColor : "rgba(80,80,80)",
showLine: true,
fill : "none",
pointBorderWidth: 1,
},
{
label: "Hồi phục" ,
data : ascendingData.map(({recovered}) => recovered),
backgroundColor : "rgba(0,255,0,.8)",
},
{
label : "Tử vong",
data : ascendingData.map(({deaths}) => deaths),
backgroundColor : "rgba(255, 0, 0)",
},
]
}}
/>
)
return (
<div className={styles.container}>
<h2 className={styles.title}>{country.name ==="World" ? "biểu đồ diễn biến dịch trên thế giới" : `biểu đồ diễn biến dịch coronavirus tại ${country.name}`}</h2>
<div className={styles.line_chart}>
{lineHistoryCountryData}
</div>
</div>
)
}
Charts.propTypes = {
corona : PropTypes.object.isRequired
}
const mapStateToProps = state => ({
corona : state.corona
})
export default connect(mapStateToProps)(Charts)
<file_sep>/src/components/Layout/Footer/Footer.jsx
import React from 'react'
import styles from "./Footer.module.css";
import qrcodeImage from "../../../My_Social_Media_Page.png";
const Footer = () => {
const handleClick = e => {
window.open('mailto:<EMAIL>?subject=CoronaVirus&subject=Feedback&body=',"_blank", "width=600,height=500")
}
return (
<div className={styles.footer}>
<div className={styles.left_side}>
<p className={styles.main_content}><i className="fas fa-globe"></i> Website tra cứu diễn biến dịch CoronaVirus</p>
<p className={styles.sub_content}><i className="fas fa-database"></i> Dữ liệu tra cứu <a href="https://about-corona.net/documentation" target="_blank">tại đây</a></p>
<p className={styles.author}><i className="fas fa-id-card"></i> Bản quyền thuộc về @MVT</p>
<p><i className="fas fa-graduation-cap"></i> About author : <a href="https://github.com/mthang1801" target="_blank" className={styles.link}>
<img src={qrcodeImage} ></img>
</a></p>
</div>
<div className={styles.right_side}>
<p className={styles.social_fb}>Follow me at: <a href="https://www.facebook.com/maivanthang95" target="_blank"><i className="fab fa-facebook-square fa-lg" aria-hidden="true"></i></a></p>
<p className={styles.social_github}>Visit my projects at: <a href="https://github.com/mthang1801"><i className="fab fa-github-square fa-lg"></i></a> </p>
<p className={styles.send_mail}>Mọi ý kiến đóng góp vui lòng gửi <a href="mailto:mthang180<EMAIL>?subject=Feedback&body=" target="_blank" onClick={handleClick}>tại đây</a></p>
</div>
</div>
)
}
export default Footer
<file_sep>/src/containers/Global/Global.jsx
import React, {useEffect} from 'react'
import clsx from "clsx";
import {connect} from "react-redux";
import PropTypes from "prop-types";
import styles from "./Global.module.css";
import {changePage} from "../../actions/page";
import Spinner from "../../components/Layout/Spinner/Spinner";
import {Header, CardDetails, Tables} from "../../components/Global";
import {getDataItem} from "../../actions/corona";
import {Link, withRouter} from "react-router-dom";
const Global = ({corona : {new_update, histories, data_item}, changePage, getDataItem, location}) => {
useEffect(() => {
console.log(location);
getDataItem(histories[0])
}, [histories]);
useEffect(()=>{
document.title = "Toàn cầu";
},[location.pathname]);
if(!data_item){
return <Spinner/>
}
return (
<React.Fragment>
<div style={{margin:"2rem"}}>
<Header />
<CardDetails/>
<Tables />
<Link to="/"><i className="fas fa-arrow-left"></i> Trở về trang chủ</Link>
<div style={{float : "right"}}>
<Link to="/countries">Xem chi tiết từng quốc gia <i className="fas fa-arrow-right"></i></Link>
</div>
</div>
</React.Fragment>
)
}
Global.propTypes = {
corona : PropTypes.object.isRequired,
changePage : PropTypes.func.isRequired,
}
const mapStateToProps = state => ({
corona : state.corona,
page : state.page
})
export default connect(mapStateToProps, {changePage, getDataItem})(withRouter(Global));
<file_sep>/src/components/Countries/Header/Header.jsx
import React from "react";
import styles from "./Header.module.css";
import { connect } from "react-redux";
import PropTypes from "prop-types";
import Moment from "react-moment";
const Header = ({ country , new_update}) => {
return (
<div className={styles.container}>
{ country && country.name ? (
<React.Fragment>
<h1 className={styles.title}>
Dữ liệu coronavirus{" "}
<span className={styles.country}>{country.name === "World" ? "trên thế giới" : `tại ${country.name}`}</span>{" "}
</h1>
<h4>Cập nhật lúc : <Moment format="HH:MM DD-MM-YYYY">{country.updated_at}</Moment></h4>
</React.Fragment>
) : (
<React.Fragment>
<h1 className={styles.title}>DỮ LIỆU DỊCH BỆNH TẠI CÁC QUỐC GIA</h1>
<h4>Cập nhật lúc : <Moment format="HH:MM DD-MM-YYYY">{new_update.updated_at}</Moment></h4>
</React.Fragment>
)}
</div>
);
};
Header.propTypes = {
country: PropTypes.object,
new_update : PropTypes.object.isRequired
};
const mapStateToProps = (state) => ({
country: state.corona.country,
new_update : state.corona.new_update
});
export default connect(mapStateToProps)(Header);
<file_sep>/src/containers/Home/Home.jsx
import React , {useEffect} from 'react'
import {Header, Navbar, CardsHome, Charts, StatisticCards} from "../../components/Home";
import {Spinner} from "../../components";
import {connect} from "react-redux";
import PropTypes from "prop-types";
import {changePage} from "../../actions/page";
import {withRouter} from "react-router-dom";
import {Link} from "react-router-dom";
import styles from "./Home.module.css";
import Footer from "../../components/Layout/Footer/Footer";
const Home = ({corona : {loading, home_country}, location,changePage}) => {
useEffect(() => {
changePage("/");
},[location]);
useEffect(()=>{
document.title = "Trang chủ"
},[location.pathname]);
if(loading || !home_country){
return <Spinner/>
}
return (
<React.Fragment>
<Header/>
<div className="container">
<Navbar/>
<CardsHome/>
<StatisticCards/>
<Charts/>
<Link to="/countries" className={styles.link}>Xem thêm các quốc gia</Link>
</div>
<Footer />
</React.Fragment>
)
}
Home.propTypes = {
corona : PropTypes.object.isRequired,
changePage : PropTypes.func.isRequired
}
const mapStateToProps = state => ({
corona : state.corona
})
export default connect(mapStateToProps, {changePage})(withRouter(Home));
<file_sep>/src/components/Global/TableItem/TableItem.jsx
import React from 'react'
import withWidth from "@material-ui/core/withWidth";
import Moment from "react-moment";
import PropTypes from "prop-types";
import TableRow from '@material-ui/core/TableRow';
import TableCell from '@material-ui/core/TableCell';
import {v4 as uuid} from "uuid";
import {getDataItem} from "../../../actions/corona";
import {connect} from "react-redux";
import styles from "./TableItem.module.css";
import CountUp from 'react-countup';
const TableItem = ({labels, row, width, getDataItem}) => {
const handleClick = e => {
getDataItem(row);
window.scroll({
top : 0,
behavior : "smooth"
})
}
return (
<TableRow hover tabIndex={-1} onClick={handleClick} className={styles.row} style={{cursor: "pointer"}}>
{labels.map( label => {
const value = row[label];
if(label==="active" && width === "md"){
return null
}
if(["active", "new_confirmed", "new_recovered", "new_deaths"].indexOf(label) !== -1 ){
if(["sm", "xs"].indexOf(width) !== -1){
return null;
}
}
return(
<TableCell key={uuid()} align="center" >
{typeof value === "number" ? value.toLocaleString("en-US") : <Moment format="DD-MM-YYYY">{value}</Moment> }
</TableCell>
)
})}
</TableRow>
)
}
TableItem.propTypes = {
width : PropTypes.oneOf(['lg', 'md', 'sm', 'xl', 'xs']).isRequired,
getDataItem : PropTypes.func.isRequired
}
export default withWidth()(connect(null,{getDataItem})(TableItem));
<file_sep>/src/reducer/page.js
import * as types from "../actions/types";
const initialState = {
home : true,
global : false ,
countries : false ,
cities : false
}
export default function(state=initialState, action){
const {type, payload} = action;
switch(type){
case types.HOME_PAGE :
return{
home: true ,
global : false ,
countries : false ,
cities : false
};
case types.GLOBAL_PAGE :
return {
home: false ,
global : true ,
countries : false ,
cities : false
};
case types.COUNTRIES_PAGE :
return {
home: false ,
global : false ,
countries : true ,
cities : false
};
case types.CITIES_PAGE :
return {
home: false ,
global : false ,
countries : false ,
cities : true
};
default : return state;
}
}
<file_sep>/src/actions/types.js
export const LOADED_DATA = 'LOADED_DATA';
export const DATA_ERROR = "DATA_ERROR";
export const CLEAR_DATA = "CLEAR_DATA";
export const DATA_HOME_COUNTRY = "DATA_HOME_COUNTRY";
export const DATA_COUNTRY = "DATA_COUNTRY";
export const DEFAULT_DATA_COUNTRY = "DEFAULT_DATA_COUNTRY";
export const CLEAR_COUNTRY = "CLEAR_COUNTRY";
export const LOAD_HOME = "LOAD_HOME";
export const DATA_ITEM = "DATA_ITEM";
export const HOME_PAGE = "HOME_PAGE";
export const GLOBAL_PAGE = "GLOBAL_PAGE";
export const COUNTRIES_PAGE = "COUNTRIES_PAGE";
export const CITIES_PAGE = "CITIES_PAGE";
<file_sep>/src/components/Home/Charts/Charts.jsx
import React from 'react'
import {connect} from "react-redux";
import PropTypes from "prop-types";
import {Line, Bar, Pie} from "react-chartjs-2";
import styles from "./Charts.module.css";
import clsx from "clsx";
import CountUp from "react-countup";
import { makeStyles } from '@material-ui/core/styles';
import AppBar from '@material-ui/core/AppBar';
import Tabs from '@material-ui/core/Tabs';
import Tab from '@material-ui/core/Tab';
import Typography from '@material-ui/core/Typography';
import Box from '@material-ui/core/Box';
import Public from "@material-ui/icons/Public"
import Flag from "react-world-flags";
import {getHomeCountryData} from "../../../actions/corona";
import Spinner from "../../Layout/Spinner/Spinner";
import withWidth from "@material-ui/core/withWidth";
function TabPanel(props) {
const { classes , children, value, index, ...other } = props;
return (
<Typography
component="div"
role="tabpanel"
hidden={value !== index}
id={`scrollable-auto-tabpanel-${index}`}
aria-labelledby={`scrollable-auto-tab-${index}`}
{...other}
>
{value === index && <Box p={3}>{children}</Box>}
</Typography>
)
};
TabPanel.propTypes = {
children: PropTypes.node,
index: PropTypes.any.isRequired,
value: PropTypes.any.isRequired,
};
function a11yProps(index) {
return {
id: `scrollable-prevent-tab-${index}`,
'aria-controls': `scrollable-prevent-tabpanel-${index}`,
};
};
const useStyles = makeStyles((theme) => ({
root: {
flexGrow: 1,
width: '100%',
backgroundColor: theme.palette.background.paper,
},
tab: {
width : 75,
minWidth :75
},
}));
const Chart = ({corona : {histories, new_update, countries, home_country},getHomeCountryData, width}) => {
const classes = useStyles();
const [value, setValue] = React.useState(0);
React.useEffect(() => {
async function fetchData(){
if(value === 0 ){
await getHomeCountryData("GB");
}else if(value === 6) {
await getHomeCountryData("VN");
}else{
await getHomeCountryData(countries[value].code);
}
}
fetchData();
}, [value]);
const handleChange = (event, newValue) => {
setValue(newValue);
};
const topCountries = [];
for(let i = 1 ; i < 6 ; i++){
topCountries.push(countries[i]);
}
const vn_region = countries.find(country => country.code === "VN");
if(vn_region){
topCountries.push(vn_region);
}
let ascendingTimeLine = [...home_country.timeline];
ascendingTimeLine.reverse();
const lineChartCountry = (
<div className={styles.line_chart}>
<Line
options={{
responsive : true ,
maintainAspectRatio: false,
scales :{
xAxis : [{
ticks : {
fontSize : 10
},
gridLineWidth: 0,
labelMaxWidth : 5
}],
yAxis : [{
ticks : {
fontSize : 10,
},
font: function(context) {
var width = context.chart.width;
var size = Math.round(width / 32);
return {
weight: 'bold',
size: size
};
},
labelMaxWidth : 5,
gridLineWidth: 0,
}]
},
elements : {
point : {
radius : 2
}
}
}}
data={{
labels : ascendingTimeLine.map(({date}) => date),
datasets: [
{
label: "Xác nhận" ,
data : ascendingTimeLine.map(({confirmed}) => confirmed),
strokeColor : "rgba(80,80,80)",
showLine: true,
fill : "none",
pointBorderWidth: 1,
},
{
label: "Hồi phục" ,
data : ascendingTimeLine.map(({recovered}) => recovered),
backgroundColor : "rgba(0,255,0,.8)",
},
{
label : "Tử vong",
data : ascendingTimeLine.map(({deaths}) => deaths),
backgroundColor : "rgba(255, 0, 0)",
},
]
}}
/>
</div>
)
if(!home_country){
return <Spinner/>
}
return (
<React.Fragment>
<h2 className={styles.title}>BIỂU ĐỒ DỊCH TRÊN TOÀN CẦU VÀ MỘT SỐ QUỐC GIA</h2>
<div className={classes.root}>
<AppBar position="static" color="inherit">
<Tabs
value={value}
onChange={handleChange}
variant="scrollable"
scrollButtons="on"
indicatorColor="primary"
aria-label="scrollable prevent tabs example"
>
<Tab icon={<Public style={{color: "rgba(0,0,255,.8)"}}/>} aria-label="phone" {...a11yProps(0)} classes={{root :classes.tab}} />
{topCountries.map( (country, index) => (
<Tab key={country.code} icon={<Flag code={country.code} height={16}/>} aria-label={country.name} {...a11yProps(index+1)} classes={{root :classes.tab}} />
))}
</Tabs>
</AppBar>
<TabPanel value={value} index={0} classes={classes} >
{lineChartCountry}
</TabPanel>
{topCountries.map( (country, index) => (
<TabPanel key={index+1} value={value} index={index+1} classes={classes}>
{lineChartCountry}
</TabPanel>
))}
</div>
</React.Fragment>
)
}
Chart.propTypes = {
corona : PropTypes.object.isRequired,
page : PropTypes.object.isRequired,
getHomeCountryData : PropTypes.func.isRequired,
width : PropTypes.oneOf(['lg', 'md', 'sm', 'xl', 'xs']).isRequired,
}
const mapStateToProps = state =>({
corona : state.corona,
page : state.page
})
export default withWidth()(connect(mapStateToProps,{getHomeCountryData})(Chart));
<file_sep>/src/containers/index.js
export {default as Home} from "./Home/Home";
export {default as Global} from "./Global/Global";
export {default as Countries} from "./Countries/Countries";<file_sep>/src/components/Countries/index.js
export {default as Header} from "./Header/Header";
export {default as Tables} from "./Tables/Tables";
export {default as StatisticCards} from "./StatisticCards/StatisticCards";
export {default as Charts} from "./Charts/Charts";
<file_sep>/src/components/Countries/StatisticCards/StatisticCards.jsx
import React from "react";
import styles from "./StatisticCards.module.css";
import { Pie } from "react-chartjs-2";
import clsx from "clsx";
import { connect } from "react-redux";
import PropTypes from "prop-types";
import CountUp from "react-countup";
const StatisticCards = ({
corona: { country : {name, code, population, updated_at, today, latest_data : {confirmed, deaths, recovered, critical, calculated : {death_rate, recovery_rate, cases_per_million_population, deaths_per_mllion_population}}}},
}) => {
const [tgGraph1, setToggleGraph1] = React.useState(false);
const [tgGraph2, setToggleGraph2] = React.useState(false);
const [tgGraph3, setToggleGraph3] = React.useState(false);
const [tgGraph4, setToggleGraph4] = React.useState(false);
const refFrontActive = React.useRef(null);
const refBackActive = React.useRef(null);
const refFrontClosed = React.useRef(null);
const refBackClosed = React.useRef(null);
const refFrontCasesRate = React.useRef(null);
const refBackCasesRate = React.useRef(null);
const refFrontDeathsRate = React.useRef(null);
const refBackDeathsRate = React.useRef(null);
const totalActive = confirmed - deaths - recovered;
const option = {
tooltips: {
callbacks: {
label: function (tooltipItem, data) {
var dataset = data.datasets[tooltipItem.datasetIndex];
var meta = dataset._meta[Object.keys(dataset._meta)[0]];
var total = meta.total;
var currentValue = dataset.data[tooltipItem.index];
var percentage = parseFloat(
((currentValue / total) * 100).toFixed(1)
);
return currentValue + " (" + percentage + "%)";
},
title: function (tooltipItem, data) {
return data.labels[tooltipItem[0].index];
},
},
},
};
const pieChartActiveCase = (
<React.Fragment>
<Pie
option={{
responsive: true,
maintainAspectRatio: false,
}}
options={option}
data={{
labels: ["Bình thường", "Nguy kịch"],
datasets: [
{
data: [
totalActive- critical,
critical,
],
backgroundColor: ["rgba(0,150,255, .9)", "rgba(255,0,0,.8)"],
hoverBackgroundColor: ["rgba(0,200,255)", "rgba(255,0,0)"],
},
],
}}
/>
</React.Fragment>
);
const pieChartClosedCase = (
<React.Fragment>
<Pie
option={{
responsive: true,
maintainAspectRatio: false,
}}
options={option}
data={{
labels: ["Hồi phục", "Tử vong", "Đang điều trị"],
datasets: [
{
data: [recovered, deaths, confirmed -recovered - deaths],
backgroundColor: ["rgba(0,255,0, .8)", "rgba(100,100,100,.8)"],
hoverBackgroundColor: ["rgba(0,255,0)", "rgba(95,95,95)"],
},
],
}}
/>
</React.Fragment>
);
const pieChartCasesRate = (
<React.Fragment>
<Pie
option={{
responsive: true,
maintainAspectRatio: false,
}}
options={option}
data={{
labels: ["Bị nhiễm", "Bình thường"],
datasets: [
{
data: [confirmed, population-confirmed],
backgroundColor: ["rgba(255, 89, 0,.8)", "rgba(125, 242, 0,.8)"],
hoverBackgroundColor: ["rgba(255, 89, 0,1)", "rgba(125, 242, 0,1)"],
},
],
}}
/>
</React.Fragment>
);
const pieChartDeathsRate = (
<React.Fragment>
<Pie
option={{
responsive: true,
maintainAspectRatio: false,
}}
options={option}
data={{
labels: ["Tử vong", "Bình thường"],
datasets: [
{
data: [deaths, population-deaths],
backgroundColor: ["rgba(100,100,100,.8)", "rgba(125, 242, 0,.8)"],
hoverBackgroundColor: ["rgba(100,100,100)", "rgba(125, 242, 0,1)"],
},
],
}}
/>
</React.Fragment>
);
const toggleGraph1 = () => {
setToggleGraph1(!tgGraph1);
if (refFrontActive.current.style.transform === "rotateY(-180deg)") {
refFrontActive.current.style.transform = "rotateY(0)";
refBackActive.current.style.transform = "rotateY(180deg)";
refBackActive.current.style.opacity = "0";
refBackActive.current.style.transition = "all .7s";
return;
}
refFrontActive.current.style.transform = "rotateY(-180deg)";
refBackActive.current.style.opacity = "1";
refBackActive.current.style.transition = "all .7s";
refBackActive.current.style.transform = "rotateY(0deg)";
};
const toggleGraph2 = () => {
setToggleGraph2(!tgGraph2);
if (refFrontClosed.current.style.transform === "rotateY(-180deg)") {
refFrontClosed.current.style.transform = "rotateY(0)";
refBackClosed.current.style.transform = "rotateY(180deg)";
refBackClosed.current.style.opacity = "0";
refBackClosed.current.style.transition = "all .7s";
return;
}
refFrontClosed.current.style.transform = "rotateY(-180deg)";
refBackClosed.current.style.opacity = "1";
refBackClosed.current.style.transition = "all .7s";
refBackClosed.current.style.transform = "rotateY(0deg)";
};
const toggleGraph3 = () => {
setToggleGraph3(!tgGraph3);
if (refFrontCasesRate.current.style.transform === "rotateY(-180deg)") {
refFrontCasesRate.current.style.transform = "rotateY(0)";
refBackCasesRate.current.style.transform = "rotateY(180deg)";
refBackCasesRate.current.style.opacity = "0";
refBackCasesRate.current.style.transition = "all .7s";
return;
}
refFrontCasesRate.current.style.transform = "rotateY(-180deg)";
refBackCasesRate.current.style.opacity = "1";
refBackCasesRate.current.style.transition = "all .7s";
refBackCasesRate.current.style.transform = "rotateY(0deg)";
};
const toggleGraph4 = () => {
setToggleGraph4(!tgGraph4);
if (refFrontDeathsRate.current.style.transform === "rotateY(-180deg)") {
refFrontDeathsRate.current.style.transform = "rotateY(0)";
refBackDeathsRate.current.style.transform = "rotateY(180deg)";
refBackDeathsRate.current.style.opacity = "0";
refBackDeathsRate.current.style.transition = "all .7s";
return;
}
refFrontDeathsRate.current.style.transform = "rotateY(-180deg)";
refBackDeathsRate.current.style.opacity = "1";
refBackDeathsRate.current.style.transition = "all .7s";
refBackDeathsRate.current.style.transform = "rotateY(0deg)";
};
return (
<div className={styles.container}>
<div className={styles.wrapper}>
<h2 className={styles.title}>Bảng thống kê diễn biến dịch coronavirus</h2>
<div className={styles.cards}>
{/* Card 1 */}
<div className={styles.card}>
<div className={styles.card_header}>Số ca dương tính</div>
<div className={styles.card_content}>
<div
className={clsx(styles.side, styles.front)}
ref={refFrontActive}>
<div className={styles.general}>
<div className={styles.general_num}>
<CountUp
start={0}
end={totalActive}
duration={2.5}
separator=",">
{totalActive}
</CountUp>
</div>
<div className={styles.general_sub}>
Số bệnh nhân hiện tại
</div>
</div>
<div className={styles.details}>
<div className={styles.first_detail}>
<div className={clsx(styles.first_detail_digit,styles.mild_status)}>
<CountUp
start={0}
end={totalActive - critical}
duration={2.5}
separator=",">
{totalActive}
</CountUp>{" "}
(
{(
((totalActive - critical) /
totalActive) *
100
).toFixed(0)}
%)
</div>
<div className={styles.first_detail_status}>
Tình trạng bình thường
</div>
</div>
<div className={styles.second_detail}>
<div className={clsx(styles.second_detail_digit,styles.critical_status)}>
<CountUp
start={0}
end={critical}
duration={2.5}
separator=",">
{totalActive}
</CountUp>{" "}
(
{(
(critical / totalActive) *
100
).toFixed(0)}
%)
</div>
<div className={styles.second_detail_status}>Nguy kịch</div>
</div>
</div>
</div>
<div
className={clsx(
styles.side,
styles.back,
styles.pieChartActiveCase
)}
ref={refBackActive}>
{pieChartActiveCase}
</div>
</div>
<div className={styles.card_action}>
<a href="#!" className={styles.link} onClick={toggleGraph1}>
{tgGraph1 ? "Xem số liệu" : "Xem biểu đồ"}
</a>
</div>
</div>
{/* Card 2 */}
<div className={styles.card}>
<div className={styles.card_header}>hồi phục/ tử vong</div>
<div className={styles.card_content}>
<div
className={clsx(styles.side, styles.front)}
ref={refFrontClosed}>
<div className={styles.general}>
<div className={styles.general_num}>
<CountUp
start={0}
end={confirmed}
duration={2.5}
separator=",">
{confirmed}
</CountUp>
</div>
<div className={styles.general_sub}>
Tổng số ca nhiễm
</div>
</div>
<div className={styles.details}>
<div className={styles.first_detail}>
<div className={clsx(styles.first_detail_digit,styles.recovered_status)}>
<CountUp
start={0}
end={recovered}
duration={2.5}
separator=",">
{recovered}
</CountUp>{" "}
({((recovered / (confirmed)) * 100 ).toFixed(0)}%)
</div>
<div className={styles.first_detail_status}>
Hồi phục
</div>
</div>
<div className={styles.second_detail}>
<div className={clsx(styles.second_detail_digit,styles.deaths_status)}>
<CountUp
start={0}
end={deaths}
duration={2.5}
separator=",">
{deaths}
</CountUp>{" "}
({((deaths / (confirmed)) * 100 ).toFixed(0)}%)
</div>
<div className={styles.second_detail_status}>Tử vong</div>
</div>
</div>
</div>
<div
className={clsx(
styles.side,
styles.back,
styles.pieChartClosedCase
)}
ref={refBackClosed}>
{pieChartClosedCase}
</div>
</div>
<div className={styles.card_action}>
<a href="#!" className={styles.link} onClick={toggleGraph2}>
{tgGraph2 ? "Xem số liệu" : "Xem biểu đồ"}
</a>
</div>
</div>
</div>
<div className={clsx(styles.cards,styles.hide_sm)}>
{/* Card 3 */}
<div className={styles.card}>
<div className={styles.card_header}>{name === "World" ? "tỉ lệ lây nhiễm toàn cầu" : "tỉ lệ lây nhiễm toàn quốc"}</div>
<div className={styles.card_content}>
<div
className={clsx(styles.side, styles.front)}
ref={refFrontCasesRate}>
<div className={styles.general}>
<div className={styles.general_num}>
<CountUp
start={0}
end={population}
duration={2.5}
separator=",">
{population}
</CountUp>
</div>
<div className={styles.general_sub}>
Tổng số dân
</div>
</div>
<div className={styles.details}>
<div className={styles.first_detail}>
<div className={clsx(styles.first_detail_digit,styles.cases_status)}>
<CountUp
start={0}
end={confirmed}
duration={2.5}
separator=",">
{confirmed}}
</CountUp>{" "}
({Math.ceil(((confirmed) / population) * 100)}%)
</div>
<div className={styles.first_detail_status}>
Số người nhiễm
</div>
</div>
<div className={styles.second_detail}>
<div className={clsx(styles.second_detail_digit,styles.normal_status)}>
<CountUp
start={0}
end={population-confirmed}
duration={2.5}
separator=",">
{population-confirmed}
</CountUp>{" "}
({Math.floor(((population-confirmed) / population) * 100).toFixed(0)}%)
</div>
<div className={styles.second_detail_status}>Số người khỏe mạnh</div>
</div>
</div>
</div>
<div
className={clsx(
styles.side,
styles.back,
styles.pieChartCasesRate
)}
ref={refBackCasesRate}>
{pieChartCasesRate}
</div>
</div>
<div className={styles.card_action}>
<a href="#!" className={styles.link} onClick={toggleGraph3}>
{tgGraph3 ? "Xem số liệu" : "Xem biểu đồ"}
</a>
</div>
</div>
{/* Card 4 */}
<div className={styles.card}>
<div className={styles.card_header}>{name === "World" ? "tỉ lệ tử vong toàn cầu" : "tỉ lệ tử vong toàn quốc"}</div>
<div className={styles.card_content}>
<div
className={clsx(styles.side, styles.front)}
ref={refFrontDeathsRate}>
<div className={styles.general}>
<div className={styles.general_num}>
<CountUp
start={0}
end={population}
duration={2.5}
separator=",">
{population}
</CountUp>
</div>
<div className={styles.general_sub}>
Tổng số dân
</div>
</div>
<div className={styles.details}>
<div className={styles.first_detail}>
<div className={clsx(styles.first_detail_digit,styles.deaths_status)}>
<CountUp
start={0}
end={deaths}
duration={2.5}
separator=",">
{deaths}
</CountUp>{" "}
({Math.ceil((deaths / population) * 100 )}%)
</div>
<div className={styles.first_detail_status}>
Tử vong
</div>
</div>
<div className={styles.second_detail}>
<div className={clsx(styles.second_detail_digit,styles.normal_status)}>
<CountUp
start={0}
end={population-deaths}
duration={2.5}
separator=",">
{population-deaths}
</CountUp>{" "}
({Math.floor(((population-deaths) / population) * 100 )}%)
</div>
<div className={styles.second_detail_status}>Số người khỏe mạnh</div>
</div>
</div>
</div>
<div
className={clsx(
styles.side,
styles.back,
styles.pieChartClosedCase
)}
ref={refBackDeathsRate}>
{pieChartDeathsRate}
</div>
</div>
<div className={styles.card_action}>
<a href="#!" className={styles.link} onClick={toggleGraph4}>
{tgGraph4 ? "Xem số liệu" : "Xem biểu đồ"}
</a>
</div>
</div>
</div>
</div>
</div>
);
};
StatisticCards.propTypes = {
corona: PropTypes.object.isRequired,
page: PropTypes.object.isRequired,
};
const mapStateToProps = (state) => ({
corona: state.corona,
page: state.page,
});
export default connect(mapStateToProps)(StatisticCards);
|
874f27ff61b256c8ffb959f2528029d0096babd8
|
[
"JavaScript"
] | 24 |
JavaScript
|
mthang1801/track_corona_status
|
a073ef93f61ee6a38dc8bfa73f76c5c4d7fcf1a0
|
623865ce9ec20143873ca9e8a9397d402e9dc064
|
refs/heads/master
|
<file_sep># Define here the models for your scraped items
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/items.html
import scrapy
class RateItem(scrapy.Item):
# define the fields for your item here like:
RoomTypeID = scrapy.Field()
RoomTypeName = scrapy.Field()
RoomTypeCode = scrapy.Field()
NewCube = scrapy.Field()
SilverCube = scrapy.Field()
GoldCube = scrapy.Field()
PlatinumCube = scrapy.Field()
BlackCube = scrapy.Field()
AllNight = scrapy.Field()
Remarks = scrapy.Field()
accbegin = scrapy.Field()
accend = scrapy.Field()
class TokenItem(scrapy.Item):
token = scrapy.Field()
login_token = scrapy.Field()
class MemberItem(scrapy.Item):
name = scrapy.Field()
memid = scrapy.Field()
cardno = scrapy.Field()
class CouponItem(scrapy.Item):
memid = scrapy.Field()
DisDescription = scrapy.Field()
<file_sep>import hashlib
import json
import datetime
import time
from urllib import parse
import jsonpath
import scrapy
from wfpms.items import RateItem
from wfpms.items import TokenItem
class WfpmsPriceSpider(scrapy.Spider):
name = 'wfpms_price'
allowed_domains = ['http://test.wfpms.com:9000']
def start_requests(self):
url = 'http://test.wfpms.com:9000/api/login?login_chainid=0&login_shift=A&_=1607415178032&token=<PASSWORD>&sign=c8fc9618a32e301199c3a0f7ce966cc8671d62f4'
data = {
'usercode': 'm3_admin',
'password': '<PASSWORD>',
'username': '',
'fingerprint': '9844f81e1408f6ecb932137d33bed7cfdcf518a3',
}
headers = {
'Accept': 'application/json, text/javascript, */*; q=0.01',
'Accept-Language': 'zh-CN, zh;',
'q': '0.9',
'Connection': 'keep-alive',
'Content-Type': 'application/x-www-form-urlencoded',
'Host': 'test.wfpms.com:9000',
'Origin': 'http://test.wfpms.com:9000',
'Referer': 'http://test.wfpms.com:9000/login.html'
}
yield scrapy.FormRequest(url=url, formdata=data, headers=headers,
callback=self.parse_login)
def parse_login(self, response):
url = 'http://test.wfpms.com:9000/index.html?chainid=440135'
yield scrapy.Request(url=url, callback=self.parse_login_token, dont_filter=True)
def parse_login_token(self, response):
url = 'http://test.wfpms.com:9000/api/login?login_chainid=0&login_shift=&_=1607682456849&token=145_4239_d197b0ac6cbafe4b680aa3227ddab04&sign=b269ceda8d1564e1a7d170661ae08e00996f25eb'
data = {
'usercode': 'm3_admin',
'password': '<PASSWORD>',
'username': '',
'fingerprint': '<KEY>',
}
headers = {
'Accept': 'application/json, text/javascript, */*; q=0.01',
'Accept-Language': 'zh-CN, zh;',
'q': '0.9',
'Connection': 'keep-alive',
'Content-Type': 'application/x-www-form-urlencoded',
'Host': 'test.wfpms.com:9000',
'Origin': 'http://test.wfpms.com:9000',
'Referer': 'http://test.wfpms.com:9000/login.html'
}
yield scrapy.FormRequest(url=url, formdata=data, headers=headers, callback=self.parse_price,
dont_filter=True)
def parse_price(self, response):
content = json.loads(response.text)
item = TokenItem()
item['token'] = jsonpath.jsonpath(content, '$..Token')
item['login_token'] = jsonpath.jsonpath(content, '$..LoginToken')
today = datetime.date.today()
tomorrow = (datetime.date.today() + datetime.timedelta(days=+1)).strftime('%Y-%m-%d')
url = f'http://test.wfpms.com:9000/api/GetRoomRate?accbegin={today}&accend={tomorrow}&roomtypeid=0&roomratetype=0&login_chainid=440135&login_shift=A'
# 解析url
params = parse.parse_qs(parse.urlparse(url.lower()).query)
data = Sign.create_link(params)
dtime = int(time.time())
# 拼接请求
params_str = data + f'&_={dtime}&token={item["token"][0]}'
# 生成签名
sign = Sign.encryption(params_str)
url = "http://test.wfpms.com:9000/api/GetRoomRate?" + f'accbegin={today}&accend={tomorrow}&roomtypeid=0&roomratetype=0&login_chainid=440135&login_shift=a&_={dtime}&token={item["login_token"][0]}' + f'&sign={sign}'
yield scrapy.Request(url=url, callback=self.parse_get_price, dont_filter=True)
def parse_get_price(self, response):
content = json.loads(response.text)
price_dict = {}
# 获取所有房型编号
RoomTypeID_list = jsonpath.jsonpath(content, '$.Data..RoomTypeID')
# 获取所有房型的名称
RoomTypeName_list = jsonpath.jsonpath(content, '$.Data..RoomTypeName')
# 获取所有房型的编码
RoomTypeCode_list = jsonpath.jsonpath(content, '$.Data..RoomTypeCode')
for i in range(len(RoomTypeID_list)):
price_dict['RoomTypeID'] = RoomTypeID_list[i]
price_dict['RoomTypeName'] = RoomTypeName_list[i]
price_dict['RoomTypeCode'] = RoomTypeCode_list[i]
today = datetime.date.today()
tomorrow = (datetime.date.today() + datetime.timedelta(days=+1)).strftime('%Y-%m-%d')
price_dict['Remarks'] = str(today) + 'to' + tomorrow
# 获取对应房型的数据
data = jsonpath.jsonpath(content, f'$.Data[?(@.RoomTypeID == {RoomTypeID_list[i]})]')
# 获取房价
price_dict['NewCube'] = jsonpath.jsonpath(data,
'$..RoomRateTypeItem[?(@.RoomRateTypeName == "新立方会员价")]..RoomRate')
price_dict['SilverCube'] = jsonpath.jsonpath(data,
'$..RoomRateTypeItem[?(@.RoomRateTypeName == "银立方会员价")]..RoomRate')
price_dict['GoldCube'] = jsonpath.jsonpath(data,
'$..RoomRateTypeItem[?(@.RoomRateTypeName == "金立方会员价")]..RoomRate')
price_dict['PlatinumCube'] = jsonpath.jsonpath(data,
'$..RoomRateTypeItem[?(@.RoomRateTypeName == "铂金立方会员价")]..RoomRate')
price_dict['BlackCube'] = jsonpath.jsonpath(data,
'$..RoomRateTypeItem[?(@.RoomRateTypeName == "黑立方会员价")]..RoomRate')
price_dict['AllNight'] = jsonpath.jsonpath(data,
'$..RoomRateTypeItem[?(@.RoomRateTypeName == "整夜房")]..RoomRate')
rate = RateItem(RoomTypeID=price_dict['RoomTypeID'], RoomTypeName=price_dict['RoomTypeName'],
RoomTypeCode=price_dict['RoomTypeCode'], NewCube=price_dict['NewCube'],
SilverCube=price_dict['SilverCube'], GoldCube=price_dict['GoldCube'],
PlatinumCube=price_dict['PlatinumCube'],
BlackCube=price_dict['BlackCube'], AllNight=price_dict['AllNight'],
Remarks=price_dict['Remarks'], accbegin=today, accend=tomorrow)
yield rate
class Sign:
@staticmethod
def para_filter(kwargs):
sign_dict = {}
for key, value in kwargs.items():
if str(kwargs[key]) != '' and str(key) != 'sign' and str(key) != 'sign_type' and str(
key) != 'token' and str(key) != '_':
sign_dict[key] = kwargs[key]
return sorted(sign_dict.items(), key=lambda x: x[0])
@staticmethod
def create_link_string(sign_dict):
pre_str = ''
for key in sign_dict:
pre_str = pre_str + str(key[0]) + '=' + str(key[1][0] + '&')
else:
pre_str = pre_str.rstrip('&')
return pre_str
@staticmethod
def encryption(s):
m = hashlib.sha1()
b = s.encode(encoding='utf-8')
m.update(b)
str_sha1 = m.hexdigest()
return str_sha1.lower()
@staticmethod
def create_link(sign_dict):
pre_str = ''
for key in sign_dict:
pre_str = pre_str + str(key) + '=' + str(sign_dict[key][0] + "&")
else:
pre_str = pre_str.rstrip('&')
return pre_str
<file_sep>import scrapy
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from scrapy.linkextractors import LinkExtractor
class WfpmsCouponSpider(scrapy.Spider):
name = 'wfpms_coupon'
allowed_domains = ['http://test.wfpms.com:9000']
start_urls = ['http://http://test.wfpms.com:9000/']
def __init__(self):
super().__init__()
options = Options()
options.add_argument('--headless')
self.driver = webdriver.Chrome('chromedriver', options=options)
def parse(self, response):
le = LinkExtractor()
links = le.extract_links(response)
for link in links:
yield {
'file_urls': [link.url]
}
def close(spider, reason):
spider.driver.quit() # 关闭浏览器
<file_sep>import hashlib
import json
import time
from urllib import parse
import jsonpath
import scrapy
from wfpms.items import TokenItem
class WfpmsGetmainstatuswithrevenueSpider(scrapy.Spider):
name = 'wfpms_getmainstatuswithrevenue'
allowed_domains = ['http://test.wfpms.com:9000']
def start_requests(self):
url = 'http://test.wfpms.com:9000/api/login?login_chainid=0&login_shift=&_=1607914726653&token=<PASSWORD>&sign=7<PASSWORD>'
data = {
'usercode': 'm3_admin',
'password': '<PASSWORD>',
'username': '',
'fingerprint': '9844f81e1408f6ecb932137d33bed7cfdcf518a3',
}
headers = {
'Accept': 'application/json, text/javascript, */*; q=0.01',
'Accept-Language': 'zh-CN, zh;',
'q': '0.9',
'Connection': 'keep-alive',
'Content-Type': 'application/x-www-form-urlencoded',
'Host': 'test.wfpms.com:9000',
'Origin': 'http://test.wfpms.com:9000',
'Referer': 'http://test.wfpms.com:9000/login.html'
}
yield scrapy.FormRequest(url=url, formdata=data, headers=headers,
callback=self.parse_get_one_members)
def parse_get_fangtai(self, response):
"""获取房态"""
content = json.loads(response.text)
item = TokenItem()
item['token'] = jsonpath.jsonpath(content, '$..Token')
item['login_token'] = jsonpath.jsonpath(content, '$..LoginToken')
url = "http://test.wfpms.com:9000/api/GetMainStatusWithRevenue?login_chainid=440135&login_shift=A"
# 解析url
params = parse.parse_qs(parse.urlparse(url.lower()).query)
# 排序
str_list = Sign.para_filter(params)
dtime = int(time.time())
# 拼接请求
params_str = Sign.create_link_string(str_list) + f'&_={dtime}&token={item["token"][0]}'
# 生成签名
sign = Sign.encryption(params_str)
url = "http://test.wfpms.com:9000/api/GetMainStatusWithRevenue?" + f'login_chainid=440135&login_shift=A&_={dtime}&token={item["login_token"][0]}' + f'&sign={sign}'
yield scrapy.Request(url=url, meta={'item': item}, callback=self.parse_get_coupon, dont_filter=True)
class Sign:
@staticmethod
def para_filter(kwargs):
sign_dict = {}
for key, value in kwargs.items():
if str(kwargs[key]) != '' and str(key) != 'sign' and str(key) != 'sign_type' and str(
key) != 'token' and str(key) != '_':
sign_dict[key] = kwargs[key]
return sorted(sign_dict.items(), key=lambda x: x[0])
@staticmethod
def create_link_string(sign_dict):
pre_str = ''
for key in sign_dict:
pre_str = pre_str + str(key[0]) + '=' + str(key[1][0] + '&')
else:
pre_str = pre_str.rstrip('&')
return pre_str
@staticmethod
def encryption(s):
m = hashlib.sha1()
b = s.encode(encoding='utf-8')
m.update(b)
str_sha1 = m.hexdigest()
return str_sha1.lower()
@staticmethod
def create_link(sign_dict):
pre_str = ''
for key in sign_dict:
pre_str = pre_str + str(key) + '=' + str(sign_dict[key][0] + "&")
else:
pre_str = pre_str.rstrip('&')
return pre_str
<file_sep># Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
# useful for handling different item types with a single interface
from itemadapter import ItemAdapter
import pymysql
from scrapy.utils.project import get_project_settings
class WfpmsPipeline:
def process_item(self, item, spider):
return item
class MysqlPipeline:
def __init__(self):
settings = get_project_settings()
self.host = settings['DB_HOST']
self.port = settings['DB_PORT']
self.user = settings['DB_USER']
self.pwd = settings['<PASSWORD>']
self.name = settings['DB_NAME']
self.charset = settings['DB_CHARSET']
self.connect()
def connect(self):
self.conn = pymysql.connect(host=self.host, port=self.port, user=self.user, password=<PASSWORD>, db=self.name,
charset=self.charset)
self.cursor = self.conn.cursor()
def process_item(self, item, spider):
sql = f"insert into RoomRate values(0,{item['RoomTypeID']},\'{item['RoomTypeName']}\',\'{item['RoomTypeCode']}\',{item['NewCube'][0]},{item['SilverCube'][0]},{item['GoldCube'][0]},{item['PlatinumCube'][0]},{item['BlackCube'][0]},{item['AllNight'][0]},\'{item['Remarks']}\',\'{item['accbegin']}\',\'{item['accend']}\')"
self.cursor.execute(sql)
self.conn.commit()
def close(self):
self.cursor.close()
self.conn.close()
|
5107ef1b20b2fbc9305bf5b885fc830679f4cfcc
|
[
"Python"
] | 5 |
Python
|
seselinfeng/pms_scrapy
|
cf9b83bff2037d8bb4e3c98dcf94a43534e61bc1
|
a6540ae1550a520baf2da43cc97e02a37041d3ce
|
refs/heads/master
|
<repo_name>VoidTsundere/DereRPG<file_sep>/DereRPG/Data/Engine.py
import json, os, random, time
#Tables-----------------------
xpTable = [100,150,200,250,300,350,400,450,500,550,600]
hpTable = [100,110,120,130,140,150,160,170,180,190,200]
mpTable = [10,20,30,40,50,60,70,80,90,100]
maxLvl = 10
class System:
class BattleSystem:
def createEnemy(ID):
with open('Data/EnemyTable.JDere') as EnemyTable:
Data = json.load(EnemyTable)
return print(Data['ID1'])
def loadEnemy():
return
def attack():
return
def FindSaves():
global savesInDir
global inVar1
savesInDir = 0
inVar1 = 0
saves = []
for files in os.listdir("saves"):
if files.endswith(".JDere"):
data = files.replace('.JDere','')
saves.append(data)
savesInDir+=1
print('')
while inVar1 <= savesInDir:
if inVar1+1 > savesInDir:
break
print(' ',inVar1,saves[inVar1])
inVar1 +=1
print('\nDigite o número do save para carrega-lo')
sellect = input('Save:')
if int(sellect) > savesInDir:
print('Save não existe\n')
input('Precione Enter para continuar')
else:
System.LoadData(saves[int(sellect)])
return True
def NewSave(name):
rawPlayerData = {
"name":name,
"race":"Humano",
"hp":100,
"mp":10,
"maxHp":100,
"maxMp":10,
"power":0,
"agility":0,
"senses":0,
"magic":0,
"lvl":0,
"upPoints":0,
"local":0,
"localList":0,
"history":0,
"inv1":0,
"inv2":0,
"inv3:":0,
"inv4":0,
"inv5":0,
"deff":0,
"weapon1":0,
"subWeapon1":0,
"subWeapon2":0,
"xp":1000,
"debug":0
}
saveName = 'Saves/'+name+'.JDere'
jsonPlayerData = json.dumps(rawPlayerData, indent=1)
openFile = open(saveName,'w')
openFile.write(jsonPlayerData)
openFile.close()
def LoadData(name):
saveName = 'Saves/'+name+'.JDere'
global rawData
with open(saveName, 'r+') as rawData:
global pld
pld = json.load(rawData)
global nameVar
nameVar = name
rawData.close()
def CheckSave(name):
saveName = 'Saves'+name+'.JDere'
if os.path.exists(saveName) == True:
return 0
if os.path.exists(saveName) == False:
return 1
def levelUp():
global upPossibility
upPossibility = True
if Player.Get.lvl() >= maxLvl:
upPossibility = False
if upPossibility == True:
if pld['xp'] >= xpTable[pld['lvl']]:
lvl = pld["lvl"] +1
oldHP = Player.Get.maxHp()
newHP = hpTable[lvl]
oldMP = Player.Get.maxMp()
newMP = mpTable[lvl]
#Update values----
if upPossibility == True:
VarPoints = Player.Get.upPoints() +1
Player.Update.upPoints(VarPoints)
VarXp = Player.Get.xp() -xpTable[Player.Get.lvl()]
Player.Update.xp(VarXp)
VarLvl = Player.Get.lvl() +1
Player.Update.lvl(VarLvl)
Player.Update.maxHp(newHP)
Player.Update.maxMp(newMP)
#Update values----
upMessage = '\nAumentando o seu nível você obteve uma melhora de Hp de {oldHp} para {newHp}\ne tambem uma melhora de Mp de {oldMp} para {newMp}\n tambem recebeu 1 ponto de modificador que pode ser usado com /mod'.format(oldHp=oldHP,newHp=newHP,oldMp=oldMP,newMp=newMP)
print(upMessage)
else:
print('\nParece que você ainda não atende aos requeimentos necessários para subir de\nnível, volte denovo quando tiver XP suficiente pra isso')
else:
print('\nParece que você ja está no nível máximo do jogo')
class Check:
def stats():
global message
if pld['xp'] >= xpTable[pld['lvl']]:
message = '\nParece que você está pronto para subir de nível\nUse /lvlUp para passar para o próximo nível'
print(message)
if Player.Get.upPoints() > 0:
print('\nVocê tambem possui {points} pontos de Upgrade para serem usados com o /mod'.format(points = Player.Get.upPoints()))
def history():
if Player.Get.history() == 0:
Player.History.tutorial_part_1()
class Player:
class Get:
def name():
return pld["name"]
def hp():
return pld["hp"]
def mp():
return pld["mp"]
def maxHp():
return pld["maxHp"]
def maxMp():
return pld["maxMp"]
def power():
return pld["power"]
def agility():
return pld["agility"]
def senses():
return pld["senses"]
def magic():
return pld["magic"]
def lvl():
return pld["lvl"]
def upPoints():
return pld["upPoints"]
def local():
return pld["local"]
def localList():
return pld["localList"]
def history():
return pld["history"]
def inv1():
return pld["inv1"]
def inv2():
return pld["inv2"]
def inv3():
return pld["inv3"]
def inv4():
return pld["inv4"]
def inv5():
return pld["inv5"]
def deff():
return pld["deff"]
def weapon1():
return pld["weapon1"]
def subWeapon1():
return["subWeapon1"]
def subWeapon2():
return pld["subWeapon2"]
def xp():
return pld["xp"]
class Restore:
def hp(ammount):
addHealth=0
hpMax = Player.Get.maxHp()
if ammount == 'full':
addHealth = Player.Get.maxHp()
else:
addHealth = Player.Get.hp() + ammount
if addHealth < hpMax:
addHealth = Player.Get.maxHp()
Player.Update.hp(addHealth)
def mp(ammount):
addMana=0
mpMax = Player.Get.maxMp()
if ammount == 'full':
addMana = Player.Get.maxMp()
else:
addMana = Player.Get.mp() + ammount
if addMana < mpMax:
addMana = Player.Get.maxMp()
Player.Update.mp(addMana)
class Update:
global _UPDATE_
def _UPDATE_(up,value):
saveName = 'Saves/'+nameVar+'.JDere'
with open(saveName, 'r+') as rawData:
data = json.load(rawData)
rawData.seek(0)
data[up] = value
json.dump(data, rawData, indent=1)
rawData.truncate()
rawData.close()
def local(upLocal):
_UPDATE_('local',upLocal)
def hp(hpUp):
_UPDATE_('hp',hpUp)
def mp(mpUp):
_UPDATE_('mp',mpUp)
def maxHp(maxHpUp):
_UPDATE_('maxHp',maxHpUp)
def maxMp(maxMpUp):
_UPDATE_('maxMp',maxMpUp)
def power(powerUp):
_UPDATE_('power',powerUp)
def senses(sensesUp):
_UPDATE_('senses',sensesUp)
def agility(agilityUp):
_UPDATE_('agility',agilityUp)
def magic(magicUp):
_UPDATE_('magic',magicUp)
def lvl(lvlUp):
_UPDATE_('lvl',lvlUp)
def upPoints(upPointsUp):
_UPDATE_('upPoints',upPointsUp)
def localList(localListUp):
_UPDATE_('localList',localListUp)
def history(historyUp):
_UPDATE_('history',historyUp)
def inv1(inv1Up):
_UPDATE_('inv1',inv1Up)
def inv2(inv2Up):
_UPDATE_('inv2',inv2Up)
def inv3(inv3Up):
_UPDATE_('inv3',inv3Up)
def inv4(inv4Up):
_UPDATE_('inv4',inv4Up)
def inv5(inv5Up):
_UPDATE_('inv5',inv5Up)
def deff(deffUp):
_UPDATE_('deff',deffUp)
def weapon1(weapon1Up):
_UPDATE_('weapon1',weapon1Up)
def subWeapon1(subWeapon1Up):
_UPDATE_('subWeapon1',subWeapon1Up)
def subWeapon2(subWeapon2Up):
_UPDATE_('subWeapon2',subWeapon2Up)
def xp(xpUp):
_UPDATE_('xp',int(xpUp))
class History:
def tutorial_part_1():
if Player.Get.history() == 0:
print('Você se encontra perdido em uma sala de pedra, olhando em volta você consegue ver uma luz que parece vir de um portal estranho')<file_sep>/DereRPG/Main.py
import sys, os
sys.path.insert(0, 'data')
from Engine import *
loaded = False
def loadedd():
global loaded
loaded = True
def new():
header(loaded)
name = input('Nome: ')
if System.CheckSave(name) == 1:
System.NewSave(name)
if System.CheckSave(name) == 0:
print('Já existe um save com esse nome\ndeseja subescrever? [y/n]')
check = input('Opção:')
if check in ['y','Y']:
System.NewSave(name)
else:
console(0)
def header(loaded):
os.system('cls')
if loaded == False:
print('Tsundere RPG version 0.0.0A')
if loaded == True:
print('Tsundere RPG version 0.0.0A')
print(Player.Get.name(),'|HP:',Player.Get.hp(),'|MP:',Player.Get.mp(),'|A:',Player.Get.agility(),'|P:',Player.Get.power(),'|S:',Player.Get.senses(),'|M:',Player.Get.magic(),'|D:',Player.Get.deff())
def console(mode):
cl = input('Ação: ')
if '/new' in cl:
new()
if '/load' in cl:
header(loaded)
if System.FindSaves() == True:
loadedd()
header(loaded)
console(loaded)
if loaded == True:
if '/lvlUp' in cl:
header(loaded)
System.levelUp()
input('\nPrecione Enter para continuar')
header(loaded)
console(loaded)
if '/stats' in cl:
header(loaded)
System.Check.stats()
input('\nPrecione Enter para continuar')
header(loaded)
console(loaded)
if '/xp' in cl:
amount = input()
Player.Update.xp(amount)
if '/rec' in cl:
Player.Restore.hp('full')
if '/mod' in cl:
header(loaded)
print('Sistema ainda não implementado\n')
input('Precione Enter para continuar')
header(loaded)
console(loaded)
if 'get' in cl:
System.BattleSystem.createEnemy(1)
input('')
header(loaded)
console(loaded)
<file_sep>/Build-2/main.py
from PyQt5 import uic
from PyQt5.QtWidgets import QApplication, QWidget, QMainWindow
from PyQt5.QtGui import QFont, QFontDatabase, QKeyEvent
from PyQt5.QtCore import Qt
from PyQt5 import QtCore
from sys import argv, exit
import sqlite3
conn = sqlite3.connect('data/data.dere')
app = QApplication(argv)
class game:
class mainWindow(QWidget):
def __init__(self):
super().__init__()
def runConsole():
command = self.dlg.console.text()
if 'exit' in command:
self.dlg.close()
if 'clear' in command:
self.dlg.textBox.clear()
if 'run' in command:
commandZone = command.split(' ')
if commandZone[1] == 'new':
if commandZone[2] == 'save':
try:
playerName = commandZone[3]
except:
self.dlg.textBox.append("Use 'run new save (player name)'")
self.dlg.console.clear()
screen = app.primaryScreen()
self.dlg = uic.loadUi('data/ui/main.ui')
self.consoleFont = QFontDatabase.addApplicationFont('./data/ui/Modeseven.ttf')
self.fontConsole = QFont('Modeseven',12)
self.dlg.textBox.setFont(self.fontConsole)
self.dlg.console.move(0,screen.size().height()-70)
self.dlg.console.setFixedSize(screen.size().width(),31)
self.dlg.console.setFont(self.fontConsole)
self.dlg.console.installEventFilter(self)
self.dlg.setWindowFlags(QtCore.Qt.FramelessWindowHint)
self.dlg.console.returnPressed.connect(runConsole)
self.dlg.showMaximized()
self.dlg.exit_button.clicked.connect(self.dlg.close)
self.dlg.exit_button.setFont(self.fontConsole)
self.dlg.exit_button.move(screen.size().width()-50,0)
self.dlg.show()
def keyPressEvent(self, event):
if event.key() == QtCore.Qt.Key_Space:
printt()
window = game.mainWindow()
exit(app.exec_())<file_sep>/Build-3/Project Immortal.py
import pymongo
from PyQt5 import uic
from PyQt5.QtWidgets import QWidget, QApplication
from PyQt5.QtGui import QFont, QFontDatabase
from PyQt5.QtCore import Qt
app = QApplication([])
consoleFont = QFontDatabase.addApplicationFont('./data/resources/fonts/Modeseven.ttf')
fontConsole = QFont('Modeseven',12)
class Game:
class login_window(QWidget):
def __init__(self):
super().__init__()
self.dlg = uic.loadUi('data/ui/login_scr.ui', self)
self.dlg.setWindowFlags(Qt.FramelessWindowHint)
self.dlg.exit_button.clicked.connect(self.close)
self.dlg.minus_button.clicked.connect(self.dlg.showMinimized)
self.show()
win = Game.login_window()
app.exec_()<file_sep>/Build-3/server.py
import pymongo
import flask
from flask import request, jsonify
from passlib.hash import pbkdf2_sha256
import re
import jwt
import datetime
from os import urandom
from random import choice, randrange
from string import ascii_uppercase
def TODO():
return 'not implemented'
global client
client = pymongo.MongoClient("mongodb+srv://Dere:[email protected]/USER?retryWrites=true&w=majority")
app = flask.Flask(__name__)
app.config["DEBUG"] = True
#Contem os codigos de erro e sucesso
class ids:
eID = {
'eID-1':'No name provided',
'eID-2':'No password provided',
'eID-3':'User not Exists',
'eID-4':'Incorrect password',
'eID-5':'Name in Use',
'eID-6':'Email in Use',
'eID-7':'Invalid email',
'eID-8':'No Email provided',
'eID-9':'Invalid Token',
'eID-10':'Token not provided',
'eID-11':'User allready in game room',
'eID-12':'ADM cannot connect to his own room'
}
sID = {
'sID-1':'Account created',
'sID-2':'Match created',
'sID-3':'Join success'
}
#contem as funções de autenticação da API
class auth:
def encode_token(user_id):
payload = {
'exp':datetime.datetime.utcnow() + datetime.timedelta(days=1, hours=0, minutes=0, seconds=0),
'iat':datetime.datetime.utcnow(),
'sub':user_id
}
return jwt.encode(payload, 'dere_key', algorithm='HS256')
def decode_token(token):
payload = jwt.decode(token, 'dere_key', algorithms='HS256', verify=False)
return payload['sub']
#contem as funções de uitilidade da API como as funções de geração de codigos
class utility:
def gen_match_id():
result = ''.join(choice(ascii_uppercase) for i in range(4))
result += '-'+str(randrange(10,100))
return result
#a rota nula da API apenas retorna uma pagina vazia
@app.route('/', methods=['GET'])
def home():
return "<h1> Ops... </h1><p>Looks like you didn't use any end-point</p>"
#a rota de login da API, requer os itens: "name", "password" e retorna o resultado contendo: "connection", "con", "auth" em caso de sucesso
@app.route('/api/v1/dlark/login/', methods=["GET"])
def dlark_login():
db_user_data = client.USER.data
if 'name' in request.args:
in_name = request.args['name']
else:
return {"error":"No NAME provided","eID":1}
if 'password' in request.args:
in_password = request.args['password']
else:
return {"error":"No PASSWORD provided","eID":2}
sr_result = db_user_data.find_one({'name':re.compile(in_name, re.IGNORECASE)})
if type(sr_result) == dict:
if 'name' in sr_result:
if pbkdf2_sha256.verify(in_password,sr_result['password']) == True:
return {"connection":"success","con":True,'auth':auth.encode_token(str(sr_result['_id']))}
else:
return {"error":"Incorrect PASSWORD","eID":4}
else:
return {"error":"User not exists","eID":3}
else:
return {"error":"User not exists","eID":3}
#a rota de registro na API, ela cria uma conta no MongoDB, requer os itens: "name", "password", "email" e retorna o resultado contendo: "success", "sID" em caso de sucesso
@app.route('/api/v1/dlark/register/', methods=["GET"])
def dlark_register():
db = client.USER.data
if 'name' in request.args:
if 'password' in request.args:
if 'email' in request.args:
if type(db.find_one({'name':request.args['name']})) == dict:
return {'error':'Name in Use', 'eID':5}
if type(db.find_one({'email':request.args['email']})) == dict:
return {'error':'Email in Use', 'eID':6}
else:
if '@' in request.args['email'] and '.' in request.args['email']:
player_acc = {
'name':request.args['name'],
'password':<PASSWORD>(request.args['<PASSWORD>']),
'email':request.args['email'],
'custom_itens':[],
'matches':[]
}
db.insert_one(player_acc)
return {'success':'Account created','sID':1}
else:
return {'error':'Invalid Email','eID':7}
else:
return {'error':'No email provided', 'eID':8}
else:
return {'error':'no password provided', 'eID':2}
else:
return {'error':'No name provided', 'eID':1}
#uma rota de debug ou uso emergencial feita pra criar uma hash, requer: "value" e retorna: hash
@app.route('/api/help/sha256/make/', methods=["GET"])
def sha256_help():
if 'value' in request.args:
return pbkdf2_sha256.hash(request.args['value'])
#uma rota debug ou uso emergencial feita pra criptografar um token, requer: "id" e retorna: token
@app.route('/api/debug/encode/', methods=["GET"])
def encode_debug():
if 'id' in request.args:
return auth.encode_token(user_id=request.args['id'])
#uma rota debug para uso emergencial feita para descriptografar um token, requer "token" e retorna: decoded token
@app.route('/api/debug/decode/', methods=["GET"])
def decode_debug():
if 'token' in request.args:
return auth.decode_token(token=request.args['token'])
#a rota feita para criar partidas no MongoDB, requer: "token", "name" e retorna: "success", "sID", "match_id" em caso de sucesso
@app.route('/api/v1/dlark/new_match', methods=["GET"])
def new_match():
player_db = client.USER.data
game_db = client.MATCH.data
if 'token' in request.args:
if 'name' in request.args:
player_data = player_db.find_one({'name':request.args['name']})
if str(player_data['_id']) == auth.decode_token(request.args['token']):
match_id_var = utility.gen_match_id()
while game_db.find_one({'match_id':match_id_var}) == dict:
match_id_var = utility.gen_match_id()
match_data = {
'match_id':utility.gen_match_id(),
'adm':{'name':request.args['name'],'id':str(player_data['_id'])},
'players':[],
'characters':[],
'enemies':[],
'game_type':"D'Lark",
'player_requests':[],
'match_pos':0,
'turn':0
}
game_db.insert_one(match_data)
return {'success':'Match created','sID':2, 'match_id':match_data['match_id']}
else:
return {'error':'invalid token','eID':9}
else:
return {'error':'No name provided', 'eID':1}
else:
return {'error':'No token provided', 'eID':10}
#a rota para se juntar a uma partida, requer: "token", "name", "match_id" e retorna: "success", "sID" em em caso de sucesso
@app.route('/api/v1/dlark/join_match', methods=["GET"])
def join_match():
game_db = client.MATCH.data
if 'token' in request.args:
if 'name' in request.args:
if 'match_id' in request.args:
player_data = client.USER.data.find_one({'name':request.args['name']})
if str(player_data['_id']) == auth.decode_token(request.args['token']):
match_data = game_db.find_one({'match_id':re.compile(request.args['match_id'], re.IGNORECASE)})
if 'match_id' in match_data:
if match_data['adm']['id'] == str(player_data['_id']):
return {'error':'Adm cannot enter his own room', 'eID':12}
for player_pos, data in enumerate(match_data['player_requests']):
if match_data['player_requests'][player_pos]['id'] == str(player_data['_id']):
return {'error':'User allready in match', 'eID':11}
for player_pos, data in enumerate(match_data['players']):
if match_data['player_requests'][player_pos]['id'] == str(player_data['_id']):
return {'error':'User allready in match', 'eID':11}
match_players_request = match_data['player_requests']
match_players_request.append({'name':request.args['name'], 'id':str(player_data['_id'])})
game_db.update_one({'match_id':request.args['match_id']}, {'$set':{'player_requests':match_players_request}})
return {'success':'Player joined the room','sID':3}
#a rota que permite jogadores criarem os personagens dos jogadores
@app.route('/api/v1/dlark/new_character', methods=['GET'])
def new_character():
return TODO()
#a a rota que permite ADMs criar inimigos
@app.route('/api/v1/dlark/new_enemy', methods=['GET'])
def new_enemy():
return TODO()
#a a rota que permite ADMs aceitar jogadores na fila de espera
@app.route('/api/v1/dlark/accept_player', methods=['GET'])
def accept_player():
return TODO()
#a a rota que permite ADMs passarem para o próximo turno
@app.route('/api/v1/dlark/roll_turn', methods=['GET'])
def roll_turn():
return TODO()
#a a rota que permite ADMs adicionarem itens aos jogadores
@app.route('/api/v1/dlark/add_item_to_player', methods=['GET'])
def add_item_to_player():
return TODO()
#a a rota que permite ADMs removerem itens de jogadores
@app.route('/api/v1/dlark/remove_item_from_player', methods=['GET'])
def remove_item_from_player():
return TODO()
#a a rota que permite ADMs modificarem algum status de um personagem
@app.route('/api/v1/dlark/modify_stats_from_character', methods=['GET'])
def modify_stats_from_character():
return TODO()
#a a rota que permite ADMs adicionarem um efeito a um jogador
@app.route('/api/v1/dlark/add_effect_to_character', methods=['GET'])
def add_effect_to_character():
return TODO()
#a a rota que permite usuarios equiparem seus itens
@app.route('/api/v1/dlark/equip_item', methods=['GET'])
def equip_item():
return TODO()
app.run()
|
54c0ef524ffa3e094038696259788e176c9e568f
|
[
"Python"
] | 5 |
Python
|
VoidTsundere/DereRPG
|
a7daaa0b8e9e8b46c4182af101d96f0e814b5b96
|
1d2fe239ffa3d94ef3aceb3b90be4542f5e43796
|
refs/heads/master
|
<repo_name>dimitri-yatsenko/nvidia-docker-compose<file_sep>/bin/nvidia-docker-compose
#!/usr/bin/env python
import subprocess
import argparse
from jinja2 import Template
from os.path import isfile
import yaml
import json
import sys
import re
GPU_DEVICE_PATTERN = re.compile(r'/dev/nvidia\d+')
# support Python 2 or 3
if sys.version_info[0] == 3:
import urllib.request as request
else:
import urllib2 as request
parser = argparse.ArgumentParser()
parser.add_argument('-f')
(v, extras) = parser.parse_known_args()
resp = request.urlopen('http://localhost:3476/docker/cli/json').read().decode()
cuda_config = json.loads(resp)
gpu_devices = []
support_devices = []
for dev in cuda_config['Devices']:
if GPU_DEVICE_PATTERN.match(dev):
gpu_devices.append(dev)
else:
support_devices.append(dev)
gpu_devices.sort()
n_gpu = len(gpu_devices)
volume = cuda_config['Volumes'][0].split(':')[0]
dc_file = v.f or 'docker-compose.yml'
jinja_file = dc_file + '.jinja'
if isfile(jinja_file):
with open(jinja_file, 'r') as f:
content = Template(f.read()).render(N_GPU=n_gpu, GPU_DEVICES=gpu_devices)
config = yaml.load(content)
else:
with open(dc_file, 'r') as f:
config = yaml.load(f)
volumes = config.setdefault('volumes', {})
volumes[volume] = {'external': True}
for service, sconf in config['services'].items():
sconf.setdefault('volumes', []).extend(cuda_config['Volumes'])
devices = sconf.setdefault('devices', [])
if not any(gdev in devices for gdev in gpu_devices):
devices.extend(gpu_devices)
devices.extend(support_devices)
with open('nvidia-docker-compose.yml', 'w') as f:
yaml.safe_dump(config, f, default_flow_style=False)
command = ['docker-compose','-f', 'nvidia-docker-compose.yml'] + extras
try:
subprocess.call(command)
except:
print('Terminating')
|
55b94075f33ed3a79306169102b42862de7af4f6
|
[
"Python"
] | 1 |
Python
|
dimitri-yatsenko/nvidia-docker-compose
|
5840c5be237c91a7bede636bfa14066b5265e859
|
d78b55e84a8f5359a3c3a3f1be8d62073f28f970
|
refs/heads/main
|
<repo_name>edgarlunaa/formulario-incorporacion-benficiario-cti-ctd<file_sep>/src/app/components/autorizacion-tutelar/autorizacion-tutelar.component.ts
import { Component, OnInit } from '@angular/core'
import { FormGroup, PatternValidator } from '@angular/forms'
import { FormlyFieldConfig, FormlyFormOptions } from '@ngx-formly/core'
import jsPDF from 'jspdf'
@Component({
selector: 'app-autorizacion-tutelar',
templateUrl: './autorizacion-tutelar.component.html',
styleUrls: ['./autorizacion-tutelar.component.scss']
})
export class AutorizacionTutelarComponent implements OnInit {
constructor() { }
ngOnInit(): void {
}
title = 'AUTORIZACIÓN DEL PADRE, MADRE O TUTOR DE MENORES DE 18 AÑOS PARA DESARROLLAR TAREAS DE CAPACITACIÓN O PRÁCTICA LABORAL'
form = new FormGroup({})
options: FormlyFormOptions = {};
model: any = {
}
fields: FormlyFieldConfig[] = [
{
key: 'Aclaración',
type: 'no repeat',
templateOptions: {
required: true,
addText: 'Ingresar aclaración',
},
fieldArray: {
fieldGroup: [
{
key: 'Lugar',
type: 'input',
templateOptions: {
label: 'Lugar',
required: true,
placeholder: 'Ingrese un lugar'
}
},
{
key: 'Fecha',
type: 'input',
templateOptions: {
label: 'Fecha',
required: true,
type: 'date',
}
},
{
key: 'En el día de la fecha comparece propia voluntad',
type: 'input',
templateOptions: {
label: 'En el día de la fecha comparece propia voluntad',
placeholder: 'Ingrese el nombre del Padre, Madre o Tutor',
required: true
}
},
{
key: 'DNI Padre, Madre o Tutor',
type: 'input',
templateOptions: {
label: 'DNI Padre, Madre o Tutor',
required: true,
placeholder: 'Ingrese el DNI del Padre, Madre o Tutor',
pattern: '\\d{7,8}'
}
},
{
key: 'quien en este acto AUTORIZA a su hijo/tutorado',
type: 'input',
templateOptions:{
label: 'quien en este acto AUTORIZA a su hijo/tutorado',
placeholder: 'Ingrese el nombre de su hijo/tutorado',
required: true,
}
},
{
key: 'DNI hijo/tutorado',
type: 'input',
templateOptions: {
label: 'DNI hijo/tutorado',
required: true,
placeholder: 'Ingrese el DNI del hijo/tutorado',
pattern: '\\d{7,8}'
}
},
{
className: 'info-aclaracion',
template: 'a participar de Programa PIL del Gobierno de la Provincia de Córdoba.<p>Leído, firma por ante mi previa lectura y ratificación. CONSTE.</p>'
}
]
},
},
//--------------------------------------------------------------------------------------------------------
{
className: 'datos-del-beneficiario',
template: '<div><h1>FORMULARIO PARA DESIGNAR APODERADO A PADRE, MADRE O TUTOR DE MENORES DE 18 AÑOS PARA EL COBRO DEL BENEFICIO DE PROGRAMAS DE EMPLEO</h1></div>',
},
{
key: 'Datos del beneficiarios',
type: 'no repeat',
templateOptions: {
required: true,
addText: 'Ingresar beneficiario',
},
fieldArray: {
fieldGroup: [
{
key: 'Apellido y Nombre',
type: 'input',
templateOptions: {
label: 'Apellido y Nombre',
placeholder: 'Ingrese un apellido y un nombre'
}
},
{
key: 'DNI',
type: 'input',
templateOptions: {
label: 'DNI',
pattern: '\\d{7,8}',
placeholder: 'Ingrese un DNI'
}
},
]
}
},
//--------------------------------------------------------------------------------------------------------
{
className: 'datos-solicitados-por-el-banco',
template: '<div><h2>DATOS SOLICITADOS POR EL BANCO PARA APODERAR. (Solo datos del apoderado mayor de edad)</div></h2>'
},
{
key: 'Datos del apoderado',
type: 'no repeat',
templateOptions: {
required: true,
addText: 'Ingresar datos del apoderado'
},
fieldArray:{
fieldGroup:[
{
key: 'CUIL',
type: 'input',
templateOptions: {
label: 'CUIL',
pattern: '\\d{11}',
required: true,
placeholder: 'Ingrese un CUIT'
}
},
{
key: 'Sexo',
type: 'select',
templateOptions: {
label: 'Sexo',
options:[
{value: 'Masculino', label: 'Masculino'},
{value: 'Femenino', label: 'Femenino'},
]
}
},
{
key: 'Fecha de nacimiento',
type: 'input',
templateOptions: {
type: 'date',
label: 'Fecha de nacimiento'
}
},
{
key: 'Apellido y Nombre',
type: 'input',
templateOptions: {
label: 'Apellido y Nombre (tal como figura en el DNI)',
required: true,
placeholder: 'Ingrese su Nombre y Apellido'
}
},
{
key: 'Tipo de documento',
type: 'select',
templateOptions: {
label: 'Tipo de documento',
required: true,
options: [
{value: 'DNI', label: 'DNI'},
{value: 'LE', label: 'LE'},
{value: 'LC', label: 'LC'},
{value: 'Pasaporte', label: 'Pasaporte'},
]
}
},
{
key: 'Número de documento',
type: 'input',
templateOptions: {
label: 'Número de documento',
placeholder: 'Ingrese un numero de documento',
required: true,
pattern: '\\d{5,10}'
}
},
{
template: '<h3>Domicilio</h3'
},
{
key: 'Calle',
type: 'input',
templateOptions: {
label: 'Calle',
placeholder: 'Ingrese una calle'
}
},
{
key: 'Número',
type: 'input',
templateOptions: {
label: 'Número',
placeholder: 'Ingrese un número',
pattern: '\\d{1,10}',
}
},
{
key: 'Piso',
type: 'input',
templateOptions: {
label: 'Piso',
placeholder: 'Ingrese un piso',
pattern: '\\d{1,10}',
}
},
{
key: 'Depto',
type: 'input',
templateOptions: {
label: 'Depto',
placeholder: 'Ingrese un departamento',
}
},
{
key: 'Barrio',
type: 'input',
templateOptions: {
label: 'Barrio',
placeholder: 'Ingrese un barrio',
}
},
{
key: 'Localidad',
type: 'input',
templateOptions: {
label: 'Localidad',
placeholder: 'Ingrese una localidad',
}
},
{
key: 'Código Postal',
type: 'input',
templateOptions: {
label: 'Código Postal',
placeholder: 'Igrese un CP',
pattern: '\\d{1,10}',
}
},
{
key: 'Teléfono',
type: 'input',
templateOptions: {
label: 'Teléfono',
placeholder: 'Igrese un teléfono',
pattern: '\\d{1,25}',
}
}
]
}
},
{
key: "text",
type: "textarea",
defaultValue:
"fhskdjfhs dfk sdfhk sdfhk sdfkj skdfj skjd fksj dfksd fksjdfhks dfkjs dfksjd fksjdf hksdf hksdf ksdf hksdfh ksjdfh skjdfh skjdfh skjdfh skjdf hksjfdhksfd",
templateOptions: {
label: "Textarea with specified rows",
placeholder: "This has 10 rows",
rows: 10,
disabled: true,
}
}
]
createPdf() {
if (this.form.valid) {
let modelo = Object.entries(this.model);
//
var doc = new jsPDF('p', 'mm', 'a4');
doc.setFont('helvetica')
//doc.text('Quien suscribe la nota declara conocer las reglamentaciones vigentes del Programa y se comprometena cumplimentar los requisitos estipulados en el mismo. Los datos contenidos en este formulario tienen carácter de declaración jurada y están protegidos por el secreto estadístico.',15,20)
let m = 5;
let y = 0;
let x = 15;
let i = 0; //
//var arr:JSON[];
for (let seccion of modelo) {
let arr: any = seccion[1];
y = y + 6;
doc.setFontSize(16);
doc.setTextColor(45);
doc.text(seccion[0], x, m + y); //nombre seccion
doc.line(x, m + y + 1, x + 180, m + y + 1);
for (var j = 0; j < arr.length; j++) {
//console.log(reg);
var res = [];
var z = 0;
for (var clave in arr[j]) {
if (y > 240 && x === 110) {
doc.addPage();
m = 5;
y = 0;
x = 15;
}
i++;
if (i % 2 != 0) { x = 15; y = y + 12; }
else { x = 110; }
doc.setFontSize(10);
doc.setDrawColor(100);
res.push([clave, arr[j][clave]]);
var registro: String[] = [clave, 'algo quee no se paso a string'];
try {
registro = res[z]; //paso los valores a string
} catch (e) {
console.log(e)
}
z++;
doc.text(registro[1], x, m + y); //valor
doc.line(x, m + y + 1, x + 90, m + y + 1); // linea horizontal
doc.setFontSize(8);
doc.setDrawColor(60);
doc.text(clave, x, m + y + 5); //key
}
}
i = 0;
x = 15;
y = y + 12;
}
let nombreArchivo = '00000000000';
nombreArchivo = this.model['Aclaración'][0]['DNI Padre, Madre o Tutor'];
doc.output('dataurlnewwindow');
doc.save('AutorizacionTutelar' + nombreArchivo + '.pdf');
} else (error) => {
console.error('error:', error);
}
if (this.form.invalid) {
alert("falta completar datos")
}
}
}
<file_sep>/src/app/components/baja-benficiarios/baja-benficiarios.component.html
<div flex = 33 id="container">
<h1>{{ title }}</h1>
<form [formGroup]="form" >
<formly-form [form]="form" [fields]="fields" [model]="model" [options]="options"></formly-form>
<mat-card>
<b>IMPORTANTE:</b> Una vez completo el formulario deberá adjuntarse a <a href="https://fid.cba.gov.ar/ee-fid-multinota/multinota/#/form/FID/MNOTA_OTRO?reparticion=SEPE01">Mesa de entrada e-tramites </a>
<p></p>
<b>IMPORTANTE:</b> El beneficio de los programas es para las personas que realizan su Entrenamiento en el
marco de los mismos, con el fin de facilitarles la inserción en el mercado laboral. Por tanto, para continuar en el programa, los
beneficiarios pueden presentar un Formulario de Cambio de Empresa. Mientras tanto, estarán suspendidos en el programa lo cual implica
que no se les abonará el pago del beneficio hasta tanto se les autorice el cambio de empresa y cumplan con el entrenamiento en la nueva empresa.
Así mismo, no se les abonarán los meses que no hacen prestación por más que continúen dentro del presupuesto provincial.
<p></p>
En caso de beneficiarios asignados por la Dirección de Conciliación y Arbitraje del Ministerio de Trabajo, o la delegación del Ministerio
de Trabajo correspondiente a cada localidad
<p></p>
<p><button type="button" mat-raised-button color="primary" (click)="createPdf()" [disabled]="!form.valid">Generar Formulario en PDF</button></p>
</mat-card>
</form>
<pre>
{{model | json}}
</pre>
</div> <file_sep>/src/app/components/cambio-empresa/cambio-empresa.component.ts
import { Component, OnInit } from '@angular/core'
import { FormGroup, PatternValidator } from '@angular/forms'
import { FormlyFieldConfig, FormlyFormOptions } from '@ngx-formly/core'
import jsPDF from 'jspdf'
@Component({
selector: 'app-cambio-empresa',
templateUrl: './cambio-empresa.component.html',
styleUrls: ['./cambio-empresa.component.scss']
})
export class CambioEmpresaComponent implements OnInit {
constructor() { }
ngOnInit(): void {
}
title = 'FORMULARIO de Cambio de Empresa'
form = new FormGroup({})
options: FormlyFormOptions = {};
model: any = {
}
fields: FormlyFieldConfig[] = [
{
className: 'datos-personales',
template: '<div class="coltit"><h2 style="color:#53aae0;">Datos personales:</h2></div>',
},
// datos personales
{
key: 'Datos personales',
type: 'no repeat',
templateOptions: {
addText: 'Ingresar datos personales',
},
fieldArray: {
fieldGroup: [
{
key: 'Apellido y Nombre',
type: 'input',
templateOptions: {
label: 'Apellido y Nombre:',
required: true,
placeholder: 'Ingrese su/s nombre/s y apellido/s'
}
},
{
key: 'DNI',
type: 'input',
templateOptions: {
label: 'DNI',
pattern: '\\d{7,8}',
placeholder: 'Ingrese un DNI',
}
},
{
key: 'CUIL',
type: 'input',
templateOptions: {
label: 'CUIL',
pattern: '\\d{11}',
required: true,
placeholder: 'Ingrese un CUIL',
}
},
{
key: 'Motivo del cambio de empresa',
type: 'select',
templateOptions:{
label: 'Motivo del cambio de empresa',
options:[
{value: 'La empresa me despidió o me dió de baja', label: 'La empresa me despidió o me dió de baja'},
{value: 'La empresa cerró o quebró', label: 'La empresa cerró o quebró'},
{value: 'Presenté una denuncia por problemas laborales', label: 'Presenté una denuncia por problemas laborales'},
{value: 'Otro motivo', label: 'Otro motivo'},
]
}
},
{
key: 'Otro motivo',
type: 'input',
templateOptions:{
label: 'En caso de haber seleccionado otro motivo llenar este campo',
placeholder: 'Ingrese un motivo'
}
}
],
},
},
//--------------------------------------------------------------------------------------------------------
{
className: 'datos-a-completar-por-la-empresa',
template: '<div><h2>Datos que debe completar la Nueva Empresa</h2></div>',
},
{
key: 'Datos de la Nueva Empresa',
type: 'no repeat',
templateOptions: {
addText: 'Ingresar datos de la Nueva Empresa',
},
fieldArray: {
fieldGroup: [
{
key: 'CUIT',
type: 'input',
templateOptions: {
label: 'CUIT',
pattern: '\\d{11}',
placeholder: 'Ingrese un CUIT'
}
},
{
key: 'Razón social',
type: 'input',
templateOptions: {
label: 'Razón social',
placeholder: 'Ingrese una razón social'
}
},
{
key: 'Domicilio Legal',
type: 'input',
templateOptions: {
label: 'Domicilio Legal',
placeholder: 'Ingrese un Domicilio Legal'
}
},
{
key: 'Número del domicilio legal',
type: 'input',
templateOptions: {
label: 'Número',
pattern: '\\d{1,25}',
placeholder: 'Ingrese una número'
}
},
{
key: 'Localidad del domicilio legal',
type: 'input',
templateOptions:{
label: 'Localidad',
placeholder: 'Ingrese una localidad'
}
},
{
key: 'CP del domicilio legal',
type: 'input',
templateOptions: {
label: 'C.P.',
placeholder: 'Ingrese un Código Postal',
pattern: '\\d{1,25}'
}
},
{
key: 'Email del domicilio legal',
type: 'input',
templateOptions: {
label: 'E-mail',
placeholder: 'Ingrese un e-mail',
}
},
{
key: 'Teléfono del domicilio legal',
type: 'input',
templateOptions: {
label: 'Teléfono',
placeholder: 'Ingrese un Teléfono',
pattern: '\\d{1,25}'
}
},
{
key: 'Celular del domicilio legal',
type: 'input',
templateOptions: {
label: 'Celular',
placeholder: 'Ingrese un Celular',
pattern: '\\d{1,25}'
}
},
{
className: 'domicilio-practica',
template: '<div><h3>Domicilio de práctica</h3></div>'
},
{
key: 'Responsable de contacto',
type: 'input',
templateOptions: {
label: 'Responsable de contacto',
placeholder: 'Ingresar un responsable de contacto'
}
},
{
key: 'Localidad del domicilio de práctica',
type: 'input',
templateOptions:{
label: 'Localidad',
placeholder: 'Ingrese una localidad'
}
},
{
key: 'CP del domicilio de práctica',
type: 'input',
templateOptions: {
label: 'C.P.',
placeholder: 'Ingrese un Código Postal',
pattern: '\\d{1,25}'
}
},
{
key: 'Email del domicilio de práctica',
type: 'input',
templateOptions: {
label: 'E-mail',
placeholder: 'Ingrese un e-mail',
}
},
{
key: 'Teléfono del domicilio de práctica',
type: 'input',
templateOptions: {
label: 'Teléfono',
placeholder: 'Ingrese un Teléfono',
pattern: '\\d{1,25}'
}
},
{
key: 'Celular del domicilio de práctica',
type: 'input',
templateOptions: {
label: 'Celular',
placeholder: 'Ingrese un Celular',
pattern: '\\d{1,25}'
}
},
{
key: 'Cantidad de empleados permanentes a la fecha del tramite',
type: 'input',
templateOptions: {
label: 'Cantidad de empleados permanentes a la fecha del tramite',
placeholder: 'Ingrese una cantidad',
pattern: '\\d{1,25}'
}
}
]
}
},
//--------------------------------------------------------------------------------------------------------
{
className: 'datos-dias-y-horarios',
template: '<div><h2>Días y horarios de práctica</h2></div>',
},
{
className: 'info-completar',
template: '<div><h3>(Completar 20 horas semanales)</h3></div>'
},
{
key: '<NAME>',
type: 'repeat',
templateOptions: {
addText: 'Ingresar Un día y un horario',
},
fieldArray: {
fieldGroup: [
{
key: 'Día',
type: 'select',
templateOptions:{
label: 'Día',
options:[
{value: 'Lunes', label: 'Lunes'},
{value: 'Martes', label: 'Martes'},
{value: 'Miércoles', label: 'Miércoles'},
{value: 'Jueves', label: 'Jueves'},
{value: 'Viernes', label: 'Viernes'},
{value: 'Sábado', label: 'Sábado'},
{value: 'Domingo', label: 'Domingo'},
],
required: true
}
},
{
key: 'Turno',
type: 'select',
templateOptions:{
label: 'Turno',
options:[
{value: 'Mañana', label: 'Mañana'},
{value: 'Tarde', label: 'Tarde'},
],
required: true
},
},
{
key: 'Horario desde',
type: 'input',
templateOptions:{
label: 'Horario desde (hs)',
placeholder: 'Ingrese una hora',
pattern: '\\d{1,2}',
required: true
}
},
{
key: 'Horario hasta',
type: 'input',
templateOptions:{
label: 'Horario hasta (hs)',
placeholder: 'Ingrese una hora',
pattern: '\\d{1,2}',
required: true
}
}
]
},
},
//-------------------------------------------------------------------------------------------------------
{
className: 'modalidad-de-incorporación',
template: '<div><h2>Modalidad en la que va a incorporar al beneficiario</h2></div>',
},
{
key: 'Modalidad',
type: 'select',
templateOptions: {
label: 'Modalidad',
options:[
{label: 'Entrenamiento', value: 'Entrenamiento'},
{label: 'CTI (Se formaliza un Contrato laboral por Tiempo Indeterminado con el beneficiario reglamentado por la legislación vigente)', value: 'CTI (Se formaliza un Contrato laboral por Tiempo Indeterminado con el beneficiario reglamentado por la legislación vigente)'}
]
}
},
//--------------------------------------------------------------------------------------------------------
]
createPdf() {
if (this.form.valid) {
let modelo = Object.entries(this.model);
//
var doc = new jsPDF('p', 'mm', 'a4');
doc.setFont('helvetica')
let m = 5;
let y = 0;
let x = 15;
let i = 0; //
//var arr:JSON[];
for (let seccion of modelo) {
let arr: any = seccion[1];
y = y + 6;
doc.setFontSize(16);
doc.setTextColor(45);
doc.text(seccion[0], x, m + y); //nombre seccion
doc.line(x, m + y + 1, x + 180, m + y + 1);
for (var j = 0; j < arr.length; j++) {
//console.log(reg);
var res = [];
var z = 0;
for (var clave in arr[j]) {
if (y > 240 && x === 110) {
doc.addPage();
m = 5;
y = 0;
x = 15;
}
i++;
if (i % 2 != 0) { x = 15; y = y + 12; }
else { x = 110; }
doc.setFontSize(10);
doc.setDrawColor(100);
res.push([clave, arr[j][clave]]);
var registro: String[] = [clave, 'algo quee no se paso a string'];
try {
registro = res[z]; //paso los valores a string
} catch (e) {
console.log(e)
}
z++;
doc.text(registro[1], x, m + y); //valor
doc.line(x, m + y + 1, x + 90, m + y + 1); // linea horizontal
doc.setFontSize(8);
doc.setDrawColor(60);
doc.text(clave, x, m + y + 5); //key
}
}
i = 0;
x = 15;
y = y + 12;
}
let nombreArchivo = '00000000000';
nombreArchivo = this.model['Datos personales'][0]['CUIL'];
doc.output('dataurlnewwindow');
doc.save('InscripcionCapacitador' + nombreArchivo + '.pdf');
} else (error) => {
console.error('error:', error);
}
if (this.form.invalid) {
alert("falta completar datos")
}
}
}
<file_sep>/src/app/components/emprendedores/emprendedores.component.ts
import { Component } from '@angular/core'
import { FormGroup } from '@angular/forms'
import { FormlyFieldConfig, FormlyFormOptions } from '@ngx-formly/core'
import jsPDF from 'jspdf'
@Component({
selector: 'app-emprendedores',
templateUrl: './emprendedores.component.html',
styleUrls: ['./emprendedores.component.scss']
})
export class EmprendedoresComponent {
title = 'PROGRAMA COMERCIO ELECTRÓNICO CAPACITACIÓN PARA EMPRENDEDORES'
form = new FormGroup({})
options: FormlyFormOptions = {};
model: any = {
}
fields: FormlyFieldConfig[] = [
{
className: 'datos-solicitante',
template: '<div class="coltit"><h2 style="color:#53aae0;">Datos del emprendedor:</h2></div>',
},
// Emprendedor
{
key: 'Emprendedor',
type: 'no repeat',
templateOptions: {
addText: 'Ingresar sus datos',
},
fieldArray: {
fieldGroup: [
{
key: 'Direcciñon de correo electrónico',
type: 'input',
templateOptions: {
label: 'Direcciñon de correo electrónico',
placeholder: 'Ingrese Email',
required: true,
},
},
{
key: 'Nombre completo',
type: 'input',
templateOptions: {
label: 'Nombre completo',
placeholder: 'Ingrese su nombre completo',
required: true,
},
},
{
key: 'Apellido',
type: 'input',
templateOptions: {
label: 'Apellido',
placeholder: 'Ingrese su apellido',
required: true,
},
},
{
key: 'CUIT',
type: 'input',
templateOptions: {
label: 'CUIT',
placeholder: 'Su CUIT',
required: true,
pattern: '\\d{11}',
maxLength: 11,
minLength: 11
},
},
{
key: 'Condición impositiva',
type: 'input',
templateOptions: {
label: 'Condición impositiva',
placeholder: 'Su condición impositiva',
},
},
{
key: 'Edad',
type: 'input',
templateOptions: {
label: 'Edad',
maxLength: 3,
minLength: 1,
pattern: '\\d{1,3}',
placeholder: 'Ingrese una edad'
}
},
{
key: 'Teléfono celular',
type: 'input',
templateOptions: {
label: 'Teléfono celular (sin 0 ni 15)',
placeholder: 'Ingrese su teléfono celular',
pattern: '\\d{1,25}',
},
},
{
key: 'Dirección',
type: 'input',
templateOptions: {
label: 'Dirección',
placeholder: 'Direccion',
},
},
{
key: 'Departamento',
type: 'select',
templateOptions: {
label: 'Departamento',
placeholder: 'Placeholder',
description: 'Departamento',
required: true,
options: [
{ value: 'CAPITAL', label:'CAPITAL' },
{ value: 'CALAMUCHITA', label:'CALAMUCHITA' },
{ value: 'COLON', label:'COLON' },
{ value: 'CRUZ DEL EJE', label:'CRUZ DEL EJE' },
{ value: 'GENERAL ROCA', label:'GENERAL ROCA' },
{ value: '<NAME>', label:'<NAME>' },
{ value: 'ISCHILIN', label:'ISCHILIN' },
{ value: '<NAME>', label:'<NAME>' },
{ value: '<NAME>', label:'<NAME>' },
{ value: 'MINAS', label:'MINAS' },
{ value: 'POCHO', label:'POCHO' },
{ value: 'PUNILLA', label:'PUNILLA' },
{ value: 'RIO CUARTO', label:'RIO CUARTO' },
{ value: 'RIO PRIMERO', label:'<NAME>' },
{ value: '<NAME>', label:'<NAME>' },
{ value: '<NAME>', label:'<NAME>' },
{ value: '<NAME>', label:'<NAME>' },
{ value: '<NAME>', label:'<NAME>' },
{ value: '<NAME>', label:'<NAME>' },
{ value: '<NAME>', label:'<NAME>' },
{ value: '<NAME>', label:'<NAME>' },
{ value: 'SOBREMONTE', label:'SOBREMONTE' },
{ value: '<NAME>', label:'<NAME>' },
{ value: 'TOTORAL', label:'TOTORAL' },
{ value: 'TULUMBA', label:'TULUMBA' },
{ value: 'UNION', label:'UNION' },
],
},
},
{
key: '¿Con qué género te identificas?',
type: 'select',
templateOptions: {
label: '¿Con qué género te identificas?',
placeholder: 'Ingrese un género',
options: [
{ value: 'MASCULINO', label: 'MASCULINO' },
{ value: 'FEMENINO', label: 'FEMENINO' },
{ value: 'OTRO', label: 'OTRO' },]
}
},
{
key: 'Nivel educativo alcanzado',
type: 'select',
templateOptions: {
label: 'Nivel alcanzado',
placeholder: 'Nivel educacion',
options: [
{ value: "primario inc", label: 'Primario Incompleto' },
{ value: "primario comp", label: 'Primario Completo' },
{ value: "secundario inc", label: 'Secundario Incompleto' },
{ value: "secundario comp", label: 'Secundario Completo' },
{ value: "terciario inc", label: 'Terciario Incompleto' },
{ value: "terciario comp", label: 'Terciario Completo' },
{ value: "universitario inc", label: 'Universitario Incompleto' },
{ value: "Universitario comp", label: 'Universitario Completo' },
],
},
},
]
}
},
//--------------------------------------------------------------------------------------------------------
{
className: 'datos-emprendimiento',
template: '<div><h2>Datos del Emprendimiento:</h2></div>',
},
{
key: 'Emprendimiento',
type: 'no repeat',
templateOptions: {
addText: 'Ingresar datos del Emprendimiento',
},
fieldArray: {
fieldGroup: [
{
key: 'Nombre del Emprendimiento',
type: 'input',
templateOptions: {
label: 'Nombre del Emprendimiento',
placeholder: 'Ingrese el nombre de su emprendimiento'
}
},
{
key: 'Ubicación del Emprendimiento',
type: 'input',
templateOptions: {
label: 'Ubicación del Emprendimiento',
placeholder: 'Ingrese una unbicación',
},
},
{
key: 'Cantidad de personas que forman parte del Emprendimiento',
type: 'input',
templateOptions: {
label: 'Cantidad de personas que forman parte del Emprendimiento',
placeholder: 'Ingrese una cantidad',
required: true,
pattern: "\\d{1,5}",
maxLength: 5,
},
},
{
key: 'Sitio web y/o redes sociales del Emprendimiento',
type: 'input',
templateOptions: {
label: 'Sitio web y/o redes sociales del Emprendimiento',
placeholder: 'Ingrese algun sitio web o red social',
},
},
{
key: 'Rubro al que pertenece el Emprendimiento',
type: 'select',
templateOptions: {
label: 'Rubro al que pertenece el Emprendimiento',
options:[
{value: 'Industria', label: 'Industria'},
{value: 'Servicios', label: 'Servicios'},
{value: 'Tecnología', label: 'Tecnología'},
{value: 'Otros', label: 'Otros'},
]
},
},
{
key: 'Describi brevemente qué productos o servicios ofrece el Emprendimiento',
type: 'input',
templateOptions: {
label: 'Describi brevemente qué productos o servicios ofrece el Emprendimiento',
placeholder: 'Ingrese una descripción',
},
},
{
key: '¿Cuáles son tus espectativas con respecto a la Capacitación en Comercio Electrónico?',
type: 'input',
templateOptions: {
label: '¿Cuáles son tus espectativas con respecto a la Capacitación en Comercio Electrónico?',
placeholder: 'Ingrese alguna espectativa',
},
},
]
}
},
]
createPdf(){
if (this.form.valid) {
let modelo = Object.entries(this.model);
//
var doc = new jsPDF('p', 'mm', 'a4');
var img = new Image();
img.src = 'assets/cabecera.jpg';
doc.addImage(img, 'jpg', 0, 0);
doc.setFont('helvetica')
let m = 30;
let y = 5;
let x = 15;
let i = 0; //
let ll = 90;
//var arr:JSON[];
//console.log(this.form)
for (let seccion of modelo) {
if(Array.isArray(seccion[1]) != true){
seccion[1] = [[seccion[1]]]
}
//console.log(seccion)
let arr: any = seccion[1];
if (y > 240 ) {
doc.addPage();
doc.addImage(img, 'jpg', 0, 0);
m = 30;
y = 5;
x = 15;
}
y = y + 6;
doc.setFontSize(16);
doc.setTextColor(45);
doc.text(seccion[0], x, m + y); //nombre seccion
doc.line(x, m + y + 1, x + 180, m + y + 1);
//console.log(arr)
for (var j = 0; j < arr.length; j++) {
var res = [];
var z = 0;
for (var clave in arr[j]) {
i++;
res.push([clave, arr[j][clave]]);
var registro: String[] = [clave, 'algo quee no se paso a string'];
try {
registro = res[z]; //paso los valores a string
} catch (e) {
console.log(e)
}
z++;
var texto = ''
//RESUELVO SI EL TEXTO ES LARGO O CORTO O SI ES DE UNA COLUMNA U OTRA
//console.log(registro[1])
texto = registro[1].toString()
var text_arr_aux = new Array
text_arr_aux = []
text_arr_aux = texto.split("",texto.length)
var text_arr = new Array
text_arr = []
var texto_aux = ""
for(var jj = 0; jj < text_arr_aux.length; jj++){
texto_aux = texto_aux + text_arr_aux[jj]
if(jj%90==0 && jj != 0){
text_arr.push(texto_aux)
texto_aux = ""
}
}
text_arr.push(texto_aux)
if (texto.length > 40) {x = 15; y = y + 12; i++; ll=180}
else { if (i % 2 != 0 || ll==180 ) { x = 15; y = y + 12; ll=90 }
else { x = 110; ll=90 } }
//ACA PREGUNTO SI ESTOY SALIENDOME DE LA HOJA
if (y > 240) {
doc.addPage();
doc.addImage(img, 'jpg', 0, 0);
m = 30;
y = 5;
x = 15;
}
doc.setFontSize(10);
doc.setDrawColor(100);
for (var ia = 0; ia < text_arr.length; ia++) {
doc.text(text_arr[ia], x, m + y); //valor
if (y > 240) {
doc.addPage();
doc.addImage(img, 'jpg', 0, 0);
m = 30;
y = 5;
x = 15;
}
y = y + 5
}
y = y - 5
doc.line(x, m + y + 1, x + ll, m + y + 1); // linea horizontal
doc.setFontSize(8);
doc.setDrawColor(60);
doc.text(clave, x, m + y + 5); //key
}
}
i = 0;
x = 15;
y = y + 12;
}
let nombreArchivo = '00000000000';
nombreArchivo = this.model['Emprendedor'][0]['CUIT'];
doc.output('dataurlnewwindow');
doc.save('solicitudCapacitacion' + nombreArchivo + '.pdf');
} else (error) => {
console.error('error:', error);
}
if (this.form.invalid) {
alert("falta completar datos")
}
}
}
<file_sep>/src/app/components/renuncia-programa/renuncia-programa.component.ts
import { Component, OnInit } from '@angular/core'
import { FormGroup, PatternValidator } from '@angular/forms'
import { FormlyFieldConfig, FormlyFormOptions } from '@ngx-formly/core'
import jsPDF from 'jspdf'
@Component({
selector: 'app-renuncia-programa',
templateUrl: './renuncia-programa.component.html',
styleUrls: ['./renuncia-programa.component.scss']
})
export class RenunciaProgramaComponent implements OnInit {
constructor() { }
ngOnInit(): void {
}
title = 'RENUNCIA AL PROGRAMA'
form = new FormGroup({})
options: FormlyFormOptions = {};
model: any = {
}
fields: FormlyFieldConfig[] = [
{
className: 'datos-beneficiario',
template: '<div class="coltit"><h2 style="color:#53aae0;">Datos del beneficiario que renuncia al programa:</h2></div>',
},
// datos personales
{
key: 'Datos del beneficiario',
type: 'no repeat',
templateOptions: {
required: true,
addText: 'Ingresar datos del beneficiario',
},
fieldArray: {
fieldGroup: [
{
key: 'Apellido y Nombre',
type: 'input',
templateOptions: {
label: 'Apellido y Nombre',
placeholder: 'Ingrese su Apellido y Nombre'
}
},
{
key: 'CUIL',
type: 'input',
templateOptions: {
label: 'CUIL',
pattern: '\\d{11}',
required: true,
placeholder: 'Ingrese un CUIT'
}
},
{
key: 'DNI',
type: 'input',
templateOptions: {
label: 'DNI',
placeholder: 'Ingrese un DNI',
pattern: '\\d{7,8}'
}
},
{
key: 'Teléfono',
type: 'input',
templateOptions: {
label: 'Teléfono',
pattern: '\\d{1,25}',
placeholder: 'Ingrese un teléfono',
}
},
{
key: 'E-mail',
type: 'input',
templateOptions: {
label: 'E-mail',
placeholder: 'Ingrese un e-mail',
}
}
]
},
},
//--------------------------------------------------------------------------------------------------------
{
className: 'datos-empresa',
template: '<div class="coltit"><h2 style="color:#53aae0;">Datos de la empresa en la que realiza el entrenamiento:</h2></div>',
},
// datos empresa
{
key: 'Datos de la empresa',
type: 'no repeat',
templateOptions: {
required: true,
addText: 'Ingresar datos de la empresa',
},
fieldArray: {
fieldGroup: [
{
key: 'CUIT',
type: 'input',
templateOptions: {
label: 'CUIT',
pattern: '\\d{11}',
required: true,
placeholder: 'Ingrese un CUIT'
}
},
{
key: 'Razón social',
type: 'input',
templateOptions: {
label: 'Razón social',
required: true,
placeholder: 'Ingrese una razón social',
}
},
]
},
},
//--------------------------------------------------------------------------------------------------------
{
className: 'datos-motivo',
template: '<div class="coltit"><h2 style="color:#53aae0;">Motivo de la renuncia</h2></div>'
},
{
key: 'Motivo',
type: 'select',
templateOptions: {
label: 'Motivo',
required: true,
options: [
{value: 'La empresa cerró o quebró', label: 'La empresa cerró o quebró'},
{value: 'Presenta Denuncia o Descargo', label: 'Presenta Denuncia o Descargo'},
{value: 'Estudios', label: 'Estudios'},
{value: 'Otro motivo', label: 'Otro motivo (detallar abajo)'},
]
}
},
{
key: 'Otro motivo',
type: 'input',
templateOptions: {
label: 'Otro motivo',
placeholder: 'Ingrese un motivo'
}
},
{
key: 'Fecha en que dejó de asistir a la empresa',
type: 'input',
templateOptions:{
type: 'date',
label: 'Fecha en que dejó de asistir a la empresa',
}
}
]
createPdf() {
if (this.form.valid) {
let modelo = Object.entries(this.model);
//
var doc = new jsPDF('p', 'mm', 'a4');
doc.setFont('helvetica')
let m = 5;
let y = 0;
let x = 15;
let i = 0; //
//var arr:JSON[];
for (let seccion of modelo) {
let arr: any = seccion[1];
y = y + 6;
doc.setFontSize(16);
doc.setTextColor(45);
doc.text(seccion[0], x, m + y); //nombre seccion
doc.line(x, m + y + 1, x + 180, m + y + 1);
for (var j = 0; j < arr.length; j++) {
//console.log(reg);
var res = [];
var z = 0;
for (var clave in arr[j]) {
if (y > 240 && x === 110) {
doc.addPage();
m = 5;
y = 0;
x = 15;
}
i++;
if (i % 2 != 0) { x = 15; y = y + 12; }
else { x = 110; }
doc.setFontSize(10);
doc.setDrawColor(100);
res.push([clave, arr[j][clave]]);
var registro: String[] = [clave, 'algo quee no se paso a string'];
try {
registro = res[z]; //paso los valores a string
} catch (e) {
console.log(e)
}
z++;
doc.text(registro[1], x, m + y); //valor
doc.line(x, m + y + 1, x + 90, m + y + 1); // linea horizontal
doc.setFontSize(8);
doc.setDrawColor(60);
doc.text(clave, x, m + y + 5); //key
}
}
i = 0;
x = 15;
y = y + 12;
}
let nombreArchivo = '00000000000';
nombreArchivo = this.model['Datos del beneficiario'][0]['CUIL'];
doc.output('dataurlnewwindow');
doc.save('RenunciaPrograma' + nombreArchivo + '.pdf');
} else (error) => {
console.error('error:', error);
}
if (this.form.invalid) {
alert("falta completar datos")
}
}
}
<file_sep>/src/app/components/renuncia-programa/renuncia-programa.component.html
<div flex = 33 id="container">
<h1>{{ title }}</h1>
<form [formGroup]="form" >
<formly-form [form]="form" [fields]="fields" [model]="model" [options]="options"></formly-form>
<mat-card>
<b>IMPORTANTE:</b> Una vez completo el formulario podrá presentarse en cualquiera de las mesas de entrada (SUAC) del
Gobierno Provincial, también se podrá remitir a través de Correo del interior, sin abonar franqueo, al Ministerio de
Promoción del Empleo y de la Economía Familiar, Av. <NAME> 3600, B° Gral. Bustos. CP 5000, Córdoba Capital.
<p></p>
El beneficiario declara conocer las reglamentaciones vigentes del Programa. Los datos contenidos en la solicitud
tienen carárcter de declaración jurada y están protegidos por el secreto estadístico.
<p></p>
<b>IMPORTANTE:</b> El beneficiario que renuncia al programa es dado de baja en el mismo y no puede reclamar con posterioridad el alta
del programa.
<p>En caso de beneficiarios asignados en la modalidad Contrato por Tiempo Indeterminado (CTI), se debe tener en cuenta que
el vínculo laboral está regulado por la Dirección de Concilliación y Arbitraje del Ministerio de Trabajo, o la delegación del
Ministerio de Trabajo correspondiente a cada localidad.
</p>
<p></p>
<p><button type="button" mat-raised-button color="primary" (click)="createPdf()" [disabled]="!form.valid">Generar Formulario en PDF</button></p>
</mat-card>
</form>
<pre>
{{model | json}}
</pre>
</div> <file_sep>/README.md
# formulario-incorporacion-benficiario-cti-ctd<file_sep>/src/app/components/capacitacion-pil/capacitacion-pil.component.ts
import { Component, OnInit } from '@angular/core'
import { FormGroup, PatternValidator } from '@angular/forms'
import { FormlyFieldConfig, FormlyFormOptions } from '@ngx-formly/core'
import jsPDF from 'jspdf'
@Component({
selector: 'app-capacitacion-pil',
templateUrl: './capacitacion-pil.component.html',
styleUrls: ['./capacitacion-pil.component.scss'],
})
export class CapacitacionPilComponent implements OnInit {
ngOnInit(): void {
}
title = 'FORMULARIO INSCRIPCION DE EMPLEADOS A CURSOS PIL'
form = new FormGroup({})
options: FormlyFormOptions = {
formState: {
selectOptionsData: {
Capacitacion: [
{id: 'Metalmecánica para Fábricas de Maquinaria Agrícola', name: 'Metalmecánica para Fábricas de Maquinaria Agrícola', idSector: 'Industria de maquinarias agrícolas'},
{id: 'Orientación Soldadura', name: 'Orientación Soldadura', idSector: 'Industria de maquinarias agrícolas'},
{id: 'Orientación Tornería', name: 'Orientación Tornería', idSector: 'Industria de maquinarias agrícolas'},
{id: 'Comercio electrónico', name: 'Comercio electrónico', idSector: 'Comercio electrónico'},
{id: 'Nuevas tecnologías', name: 'Nuevas tecnologías', idSector: 'Nuevas tecnologías'},
{id: 'Comercio exterior', name: 'Comercio exterior', idSector: 'Comercio exterior'},
],
}
}
};
model: any = {
}
fields: FormlyFieldConfig[] = [
{
className: 'datos-empresa',
template: '<div class="coltit"><h2 style="color:#53aae0;">Datos de la empresa:</h2></div>',
},
// datos personales
{
key: 'Datos de la empresa',
type: 'no repeat',
templateOptions: {
addText: 'Ingresar datos de la empresa',
},
fieldArray: {
fieldGroup: [
{
key: 'CUIT',
type: 'input',
templateOptions: {
label: 'CUIT',
pattern: '\\d{11}',
required: true,
placeholder: 'Ingrese un CUIT'
}
},
{
key: 'Razón social',
type: 'input',
templateOptions: {
label: 'Razón social',
required: true,
placeholder: 'Ingrese una razón social',
}
},
]
},
},
//--------------------------------------------------------------------------------------------------------
{
className: 'datos-del-los-empleados',
template: '<div><h2>Datos del/los empleados</h2></div>',
},
{
key: 'Datos del/los empleados',
type: 'repeat',
templateOptions: {
addText: 'Agregar empleado',
},
fieldArray: {
fieldGroup: [
{
key: 'Apellido y Nombre',
type: 'input',
templateOptions: {
label: 'Apellido y Nombre',
placeholder: 'Ingrese un apellido y un nombre'
}
},
{
key: 'CUIL',
type: 'input',
templateOptions: {
label: 'CUIL',
pattern: '\\d{11}',
placeholder: 'Ingrese un CUIL del empleado'
}
},
{
key: 'PIL',
type: 'select',
templateOptions: {
label: 'PIL',
options:[
{id: 'Comercio exterior', name: 'Comercio exterior'},
{id: 'Nuevas tecnologías', name: 'Nuevas tecnologías'},
{id: 'Comercio electrónico', name: 'Comercio electrónico'},
{id: 'Industria de maquinarias agrícolas', name: 'Industria de maquinarias agrícolas'},
],
valueProp: 'id',
labelProp: 'name'
}
},
{
key: 'Capacitacion',
type: 'select',
templateOptions: {
label: 'Capacitación',
options:[],
valueProp: 'id',
labelProp: 'name'
},
expressionProperties: {
'templateOptions.options': 'formState.selectOptionsData.Capacitacion.filter(Capacitacion => Capacitacion.idSector === model.PIL)',
// reset model when updating select options
'model.Capacitacion': `field.templateOptions.options.find(o => o.id === model.Capacitacion) ? model.Capacitacion:null`,
},
},
]
}
},
//--------------------------------------------------------------------------------------------------------
]
createPdf() {
if (this.form.valid) {
let modelo = Object.entries(this.model);
//
var doc = new jsPDF('p', 'mm', 'a4');
doc.setFont('helvetica')
let m = 5;
let y = 0;
let x = 15;
let i = 0; //
//var arr:JSON[];
for (let seccion of modelo) {
let arr: any = seccion[1];
y = y + 6;
doc.setFontSize(16);
doc.setTextColor(45);
doc.text(seccion[0], x, m + y); //nombre seccion
doc.line(x, m + y + 1, x + 180, m + y + 1);
for (var j = 0; j < arr.length; j++) {
//console.log(reg);
var res = [];
var z = 0;
for (var clave in arr[j]) {
if (y > 240 && x === 110) {
doc.addPage();
m = 5;
y = 0;
x = 15;
}
i++;
if (i % 2 != 0) { x = 15; y = y + 12; }
else { x = 110; }
doc.setFontSize(10);
doc.setDrawColor(100);
res.push([clave, arr[j][clave]]);
var registro: String[] = [clave, 'algo quee no se paso a string'];
try {
registro = res[z]; //paso los valores a string
} catch (e) {
console.log(e)
}
z++;
doc.text(registro[1], x, m + y); //valor
doc.line(x, m + y + 1, x + 90, m + y + 1); // linea horizontal
doc.setFontSize(8);
doc.setDrawColor(60);
doc.text(clave, x, m + y + 5); //key
}
}
i = 0;
x = 15;
y = y + 12;
}
let nombreArchivo = '00000000000';
nombreArchivo = this.model['Datos de la empresa'][0]['CUIT'];
doc.output('dataurlnewwindow');
doc.save('IncorporacionBeneficiario' + nombreArchivo + '.pdf');
} else (error) => {
console.error('error:', error);
}
if (this.form.invalid) {
alert("falta completar datos")
}
}
}
<file_sep>/src/app/app-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { EmprendedoresComponent } from './components/emprendedores/emprendedores.component'
import { CapacitacionPilComponent } from './components/capacitacion-pil/capacitacion-pil.component'
import { InscripcionCtiComponent } from './components/inscripcion-cti/inscripcion-cti.component'
import { BajaBenficiariosComponent } from './components/baja-benficiarios/baja-benficiarios.component'
import { DescargaODenunciaComponent } from './components/descarga-o-denuncia/descarga-o-denuncia.component'
import { RenunciaProgramaComponent } from './components/renuncia-programa/renuncia-programa.component'
import { ReconsideracionBeneficiarioComponent } from './components/reconsideracion-beneficiario/reconsideracion-beneficiario.component'
import { AutorizacionTutelarComponent } from './components/autorizacion-tutelar/autorizacion-tutelar.component'
import { IndiceComponent } from './components/indice/indice.component'
import { CambioEmpresaComponent } from './components/cambio-empresa/cambio-empresa.component'
const routes: Routes = [
{
path: 'emprendedores',
component: EmprendedoresComponent
},
{
path: 'capacitacion-pil',
component: CapacitacionPilComponent
},
{
path: 'inscripcion-cti',
component: InscripcionCtiComponent
},
{
path: 'baja-beneficiarios',
component: BajaBenficiariosComponent
},
{
path: 'descarga-o-denuncia',
component: DescargaODenunciaComponent
},
{
path: 'renuncia-programa',
component: RenunciaProgramaComponent
},
{
path: 'reconsideracion-beneficiario',
component: ReconsideracionBeneficiarioComponent
},
{
path: 'autorizacion-tutelar',
component: AutorizacionTutelarComponent
},
{
path: '',
component: IndiceComponent
},
{
path: 'cambio-empresa',
component: CambioEmpresaComponent
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
|
29170f62fa2f4df3b695b4452cfffc52068b2f63
|
[
"Markdown",
"TypeScript",
"HTML"
] | 9 |
TypeScript
|
edgarlunaa/formulario-incorporacion-benficiario-cti-ctd
|
b620b37da89ab089318d33c0519efa4133d953d2
|
25fca14a93f1e91ae80504d78e688c3b02670e7d
|
refs/heads/master
|
<repo_name>Luisky/incremental_comp<file_sep>/data_comp_linux.py
#!/bin/python
import subprocess, os, tarfile, shutil
import MySQLdb
from bz2 import decompress
LINUX_DIR = "linux-4.13.3"
LINUX_TAR = LINUX_DIR + ".tar.xz"
MAKE_J4 = "make -j4"
def init():
if not os.path.isdir(LINUX_DIR):
tar = tarfile.open(LINUX_TAR, "r:xz")
tar.extractall()
tar.close()
os.chdir("/home/luisky/dev/M1_SSR/incremental_compilation/linux-4.13.3")
if not os.path.isfile(".config"):
str_make_tinyconfig = "KCONFIG_ALLCONFIG=../tuxml.config make tinyconfig".format()
subprocess.call(args=str_make_tinyconfig, shell=True)
subprocess.call(args=MAKE_J4, shell=True)
os.chdir("..")
return
def get_cid_data(cids=10):
socket = MySQLdb.connect(host="192.168.3.11", user="script2", passwd="<PASSWORD>", database="IrmaDB_prod")
cursor = socket.cursor()
query = "SELECT cid, core_size, config_file FROM Compilations WHERE core_size > 0 ORDER BY cid DESC LIMIT {}".format(cids)
cursor.execute(query)
compilations = cursor.fetchall()
return compilations
if __name__ == "__main__":
init()
comp_data = get_cid_data()
res_file = open("res_file", "w+")
res_file.write("cid, core_size, core_size_inc\n")
core_sizes = []
for row in comp_data:
hit = True
for core in core_sizes:
if row[1] == core:
hit = False
if hit is True:
shutil.copytree(LINUX_DIR, str(row[0]))
os.chdir(str(row[0]))
f = open(str(row[0]),"wb+")
f.write(row[2])
f.close()
data = decompress(row[2]).decode('ascii')
f = open(".config", "w+")
f.write(data)
f.close()
subprocess.call(args=MAKE_J4, shell=True)
size = os.path.getsize("vmlinux")
res_string = "{}, {}, {}\n".format(str(row[0]), str(row[1]), str(size))
res_file.write(res_string)
core_sizes.append(row[1])
os.chdir("..")
shutil.rmtree(str(row[0]))
<file_sep>/compilation_incrementale.md
# Compilation incrémentale dans le cadre du projet TuxML
## Introduction
TODO: Write it
## Methodologie
make -j4
copy folder N times
get .config
make -j4 from it
get size
output csv with .config and size compared to the size from DB
|
47664fef5cebca1e5aff6a844e276cce75348188
|
[
"Markdown",
"Python"
] | 2 |
Python
|
Luisky/incremental_comp
|
6df49546aa5b91ab6b814259b33585572c7597bf
|
54dc6da0dc83f402b3a2d5e3b2d5bc703ad01d51
|
refs/heads/main
|
<file_sep>// TODO: Include packages needed for this application
const fs = require ('fs');
const inquirer = require('inquirer');
const generateMarkdown = require('./utils/generateMarkdown');
// TODO: Create an array of questions for user input
const questions = [
{
type:"input",
name:"name",
message:"name of the project?",
},
{
type:"input",
name:"statement",
message:"Give a explanition of the project:",
},
{
type:"input",
name:"develop",
message:"Describe the development?"
},
{
type:"input",
name:"usage",
message:"What is this project usage for?"
},
{
type: "input",
name: "contributing",
message: "who are the contributors?"
},
{
type:"input",
name: "test",
message: "How would you test this"
},
{
type:"list",
name:"license",
message:"what licencse would you use",
choices: [
"Apache 2.0", "MIT" ]
},
{
type:"input",
name: "id",
message: "Enter github id:"
},
{
type: "input",
name: "email",
message: "Enter email address"
},
]
// TODO: Create a function to write README file
function writeToFile(fileName, data) {
fs.writeFile(fileName, data, function(err){
if(err) return console.log(error);
console.log("README.md sucessful!")
})
}
// TODO: Create a function to initialize app
function init() {
inquirer.prompt(questions).then(answers => {
const readMEData =generateMarkdown(answers)
return readMEData
})
.then(readMEData =>writeToFile('README.md', readMEData))
}
// Function call to initialize app
init();
<file_sep>
## License
[](https://opensource.org/licenses/Apache-2.0) <br /> This application is covered by the Apache 2.0 license.
# Name
m
## Table of Contents
* [Name](#name)
* [Statement](#statement)
* [Usage](#usage)
* [License](#license)
* [Contributing](#contributing)
* [Test](#test)
* [Questions](#questions)
## statement
c
## usage
c
## Contributing
c
## Test
c
## Questions
undefined
This README was generated by c using the [README.generator.]# READ-ME-GENEATOR
|
f17a0fea53cc04f234f3ae90106b897d562226aa
|
[
"JavaScript",
"Markdown"
] | 2 |
JavaScript
|
cMfarris/read-me-gen
|
a68ec4d0813c46d5efde429a4ca9591848c78a95
|
69a7ece2535584b084a3bd77aa072dd5c087c949
|
refs/heads/master
|
<file_sep> <KEY>
<file_sep> <KEY>
<file_sep> <KEY>
<file_sep> <KEY>
<file_sep> <KEY>
<file_sep> <KEY>
<file_sep> <KEY>
<file_sep> <KEY>
<file_sep> <KEY>
<file_sep> <KEY>
<file_sep> <KEY>
<KEY>
<file_sep> <KEY>
<file_sep> <KEY>
|
55c305c93a69e9f0b5280912683e5c1ed2269e60
|
[
"Shell"
] | 13 |
Shell
|
st01tkh/loom-chroot
|
66196d713f9580475ff5b332da16a35270a9dad7
|
a30bd5a2742ceb289a6986332da5a6cec419b735
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.